FlowSeq: Non-Autoregressive Conditional Sequence Generation with Generative Flow

Xuezhe Ma, Chunting Zhou, Xian Li, Graham Neubig, Eduard Hovy

Introduction

Neural sequence-to-sequence (seq2seq) models (Bahdanau et al., 2015; Rush et al., 2015; Vinyals et al., 2015; Vaswani et al., 2017) generate an output sequence y={y1,…,yT}\mathbf{y}=\{y_{1},\ldots,y_{T}\} given an input sequence x={x1,…,xT′}\mathbf{x}=\{x_{1},\ldots,x_{T^{\prime}}\} using conditional probabilities Pθ(y∣x)P_{\theta}(\mathbf{y}|\mathbf{x}) predicted by neural networks (parameterized by θ\theta).

Most seq2seq models are autoregressive, meaning that they factorize the joint probability of the output sequence given the input sequence Pθ(y∣x)P_{\theta}(\mathbf{y}|\mathbf{x}) into the product of probabilities over the next token in the sequence given the input sequence and previously generated tokens:

Each factor, Pθ(yt∣y<t,x)P_{\theta}(y_{t}|y_{<t},\mathbf{x}), can be implemented by function approximators such as RNNs (Bahdanau et al., 2015) and Transformers (Vaswani et al., 2017). This factorization takes the complicated problem of joint estimation over an exponentially large output space of outputs y\mathbf{y}, and turns it into a sequence of tractable multi-class classification problems predicting yty_{t} given the previous words, allowing for simple maximum log-likelihood training. However, this assumption of left-to-right factorization may be sub-optimal from a modeling perspective Gu et al. (2019); Stern et al. (2019), and generation of outputs must be done through a linear left-to-right pass through the output tokens using beam search, which is not easily parallelizable on hardware such as GPUs.

Recently, there has been work on non-autoregressive sequence generation for neural machine translation (NMT; Gu et al. (2018); Lee et al. (2018); Ghazvininejad et al. (2019)) and language modeling (Ziegler and Rush, 2019). Non-autoregressive models attempt to model the joint distribution Pθ(y∣x)P_{\theta}(\mathbf{y}|\mathbf{x}) directly, decoupling the dependencies of decoding history during generation. A naïve solution is to assume that each token of the target sequence is independent given the input:

Unfortunately, the performance of this simple model falls far behind autoregressive models, as seq2seq tasks usually do have strong conditional dependencies between output variables (Gu et al., 2018). This problem can be mitigated by introducing a latent variable z\mathbf{z} to model these conditional dependencies:

where pθ(z∣x)p_{\theta}(\mathbf{z}|\mathbf{x}) is the prior distribution over latent z\mathbf{z} and Pθ(y∣z,x)P_{\theta}(\mathbf{y}|\mathbf{z},\mathbf{x}) is the “generative” distribution (a.k.a decoder). Non-autoregressive generation can be achieved by the following independence assumption in the decoding process:

Gu et al. (2018) proposed a z\mathbf{z} representing fertility scores specifying the number of output words each input word generates, significantly improving the performance over Eq. (2). But the performance still falls behind state-of-the-art autoregressive models due to the limited expressiveness of fertility to model the interdependence between words in y.

In this paper, we propose a simple, effective, and efficient model, FlowSeq, which models expressive prior distribution pθ(z∣x)p_{\theta}(\mathbf{z}|\mathbf{x}) using a powerful mathematical framework called generative flow Rezende and Mohamed (2015). This framework can elegantly model complex distributions, and has obtained remarkable success in modeling continuous data such as images and speech through efficient density estimation and sampling Kingma and Dhariwal (2018); Prenger et al. (2019); Ma and Hovy (2019). Based on this, we posit that generative flow also has potential to introduce more meaningful latent variables z\mathbf{z} in the non-autoregressive generation in Eq. (3).

FlowSeq is a flow-based sequence-to-sequence model, which is (to our knowledge) the first non-autoregressive seq2seq model utilizing generative flows. It allows for efficient parallel decoding while modeling the joint distribution of the output sequence. Experimentally, on three benchmark datasets for machine translation – WMT2014, WMT2016 and IWSLT-2014, FlowSeq achieves comparable performance with state-of-the-art non-autoregressive models, and almost constant decoding time w.r.t. the sequence length compared to a typical left-to-right Transformer model, which is super-linear.

Background

As noted above, incorporating expressive latent variables z\mathbf{z} is essential to decouple the dependencies between tokens in the target sequence in non-autoregressive models. However, in order to model all of the complexities of sequence generation to the point that we can read off all of the words in the output in an independent fashion (as in Eq. (4)), the prior distribution pθ(z∣x)p_{\theta}(\mathbf{z}|\mathbf{x}) will necessarily be quite complex. In this section, we describe generative flows Rezende and Mohamed (2015), an effective method for arbitrary modeling of complicated distributions, before describing how we apply them to sequence-to-sequence generation in §3.

Put simply, flow-based generative models work by transforming a simple distribution (e.g. a simple Gaussian) into a complex one (e.g. the complex prior distribution over z\mathbf{z} that we want to model) through a chain of invertible transformations.

Formally, a set of latent variables υ∈Υ\bm{\upsilon}\in\Upsilon are introduced with a simple prior distribution pΥ(υ)p_{\Upsilon}(\upsilon). We then define a bijection function f:Z→Υf:\mathcal{Z}\rightarrow\Upsilon (with g=f−1g=f^{-1}), whereby we can define a generative process over variables z\mathbf{z}:

An important insight behind flow-based models is that given this bijection function, the change of variable formula defines the model distribution on z∈Z\mathbf{z}\in\mathcal{Z} by:

Here ∂fθ(z)∂z\frac{\partial f_{\theta}(\mathbf{z})}{\partial\mathbf{z}} is the Jacobian matrix of fθf_{\theta} at z\mathbf{z}.

Eq. (6) provides a way to calculate the (complex) density of z\mathbf{z} by calculating the (simple) density of υ\upsilon and the Jacobian of the transformation from z\mathbf{z} to υ\upsilon. For efficiency purposes, flow-based models generally use certain types of transformations fθf_{\theta} where both the inverse functions gθg_{\theta} and the Jacobian determinants are tractable to compute. A stacked sequence of such invertible transformations is also called a (normalizing) flow (Rezende and Mohamed, 2015):

where f=f1∘f2∘⋯∘fKf=f_{1}\circ f_{2}\circ\cdots\circ f_{K} is a flow of KK transformations (omitting θ\thetas for brevity).

2 Variational Inference and Training

In the context of maximal likelihood estimation (MLE), we wish to minimize the negative log-likelihood of the parameters:

where D={(xi,yi)}i=1ND=\{(\mathbf{x}^{i},\mathbf{y}^{i})\}_{i=1}^{N} is the set of training data. However, the likelihood Pθ(y∣x)P_{\theta}(\mathbf{y}|\mathbf{x}) after marginalizing out latent variables z\mathbf{z} (LHS in Eq. (3)) is intractable to compute or differentiate directly. Variational inference (Wainwright et al., 2008) provides a solution by introducing a parametric inference model qϕ(z∣y,x)q_{\phi}(\mathbf{z}|\mathbf{y},\mathbf{x}) (a.k.a posterior) which is then used to approximate this integral by sampling individual examples of z\mathbf{z}. These models then optimize the evidence lower bound (ELBO), which considers both the “reconstruction error” log⁡Pθ(y∣z,x)\log P_{\theta}(\mathbf{y}|\mathbf{z},\mathbf{x}) and KL-divergence between the posterior and the prior:

Both inference model ϕ\phi and decoder θ\theta parameters are optimized according to this objective.

FlowSeq

We first overview FlowSeq’s architecture (shown in Figure 2) and training process here before detailing each component in following sections. Similarly to classic seq2seq models, at both training and test time FlowSeq first reads the whole input sequence x\mathbf{x} and calculates a vector for each word in the sequence, the source encoding.

At training time, FlowSeq’s parameters are learned using a variational training paradigm overviewed in §2.2. First, we draw samples of latent codes z\mathbf{z} from the current posterior qϕ(z∣y,x)q_{\phi}(\mathbf{z}|\mathbf{y},\mathbf{x}). Next, we feed z\mathbf{z} together with source encodings into the decoder network and the prior flow to compute the probabilities of Pθ(y∣z,x)P_{\theta}(\mathbf{y}|\mathbf{z},\mathbf{x}) and pθ(z∣x)p_{\theta}(\mathbf{z}|\mathbf{x}) for optimizing the ELBO (Eq. (2.2)).

At test time, generation is performed by first sampling a latent code z\mathbf{z} from the prior flow by executing the generative process defined in Eq. (5). In this step, the source encodings produced from the encoder are used as conditional inputs. Then the decoder receives both the sampled latent code z\mathbf{z} and the source encoder outputs to generate the target sequence y\mathbf{y} from Pθ(y∣z,x)P_{\theta}(\mathbf{y}|\mathbf{z},\mathbf{x}).

The source encoder encodes the source sequences into hidden representations, which are used in computing attention when generating latent variables in the posterior network and prior network as well as the cross-attention with decoder. Any standard neural sequence model can be used as its encoder, including RNNs (Bahdanau et al., 2015) or Transformers Vaswani et al. (2017).

2 Posterior

where μt(⋅)\mu_{t}(\cdot) and σt(⋅)\sigma_{t}(\cdot) are neural networks such as RNNs or Transformers.

Zero initialization.

While we perform standard random initialization for most layers of the network, we initialize the last linear transforms that generate the μ\mu and log⁡σ2\log\sigma^{2} values with zeros. This ensures that the posterior distribution as a simple normal distribution, which we found helps train very deep generative flows more stably.

Token Dropout.

The motivation of introducing the latent variable z\mathbf{z} into the model is to model the uncertainty in the generative process. Thus, it is preferable that z\mathbf{z} capture contextual interdependence between tokens in y\mathbf{y}. However, there is an obvious local optimum where the posterior network generates a latent vector zt\mathbf{z}_{t} that only encodes the information about the corresponding target token yty_{t}, and the decoder simply generates the “correct” token at each step tt with zt\mathbf{z}_{t} as input. In this case, FlowSeq reduces to the baseline model in Eq. (2). To escape this undesired local optimum, we apply token-level dropout to randomly drop an entire token when calculating the posterior, to ensure the model also has to learn how to use contextual information. This technique is similar to the “masked language model” in previous studies (Melamud et al., 2016; Devlin et al., 2018; Ma et al., 2018).

3 Decoder

As the decoder, we take the latent sequence z\mathbf{z} as input, run it through several layers of a neural sequence model such as a Transformer, then directly predict the output tokens in y\mathbf{y} individually and independently. Notably, unlike standard seq2seq decoders, we do not perform causal masking to prevent attending to future tokens, making the model fully non-autoregressive.

4 Flow Architecture for Prior

The flow architecture is based on Glow (Kingma and Dhariwal, 2018). It consists of a series of steps of flow, combined in a multi-scale architecture (see Figure 2.) Each step of flow consists three types of elementary flows – actnorm, invertible multi-head linear, and coupling. Note that all three functions are invertible and conducive to calculation of log determinants (details in Appendix A).

The activation normalization layer (actnorm; Kingma and Dhariwal (2018)) is an alternative for batch normalization (Ioffe and Szegedy, 2015), that has mainly been used in the context of image data to alleviate problems in model training. Actnorm performs an affine transformation of the activations using a scale and bias parameter per feature for sequences:

Invertible Multi-head Linear Layers.

To incorporate general permutations of variables along the feature dimension to ensure that each dimension can affect every other ones after a sufficient number of steps of flow, Kingma and Dhariwal (2018) proposed a trainable invertible 1×11\times 1 convolution layer for 2D images. It is straightforward to apply similar transformations to sequential data:

Affine Coupling Layers.

To model interdependence across time steps, we use affine coupling layers (Dinh et al., 2016):

Multi-scale Architecture.

We follow Dinh et al. (2016) in implementing a multi-scale architecture using the squeezing operation on the feature dimension, which has been demonstrated helpful for training deep flows. Formally, each scale is a combination of several steps of the flow (see Figure 3 (a)). After each scale, the model drops half of the dimensions with the third type of split in Figure 3 (b) to reduce computational and memory cost, outputting the tensor with shape [T×d2][T\times\frac{d}{2}]. Then the squeezing operation transforms the T×d2T\times\frac{d}{2} tensor into an T2×d\frac{T}{2}\times d one as the input of the next scale. We pad each sentence with EOS tokens to ensure TT is divisible by 22. The right component of Figure 2 illustrates the multi-scale architecture.

5 Predicting Target Sequence Length

In autoregressive seq2seq models, it is natural to determine the length of the sequence dynamically by simply predicting a special EOS token. However, for FlowSeq to predict the entire sequence in parallel, it needs to know its length in advance to generate the latent sequence z\mathbf{z}. Instead of predicting the absolute length of the target sequence, we predict the length difference between source and target sequences using a classifier with a range of $$. Numbers in this range are predicted by max-pooling the source encodings into a single vector,We experimented with other methods such as mean-pooling or taking the last hidden state and found no major difference in our experiments running this through a linear layer, and taking a softmax. This classifier is learned jointly with the rest of the model.

6 Decoding Process

At inference time, the model needs to identify the sequence with the highest conditional probability by marginalizing over all possible latent variables (see Eq. (3)), which is intractable in practice. We propose three approximating decoding algorithms to reduce the search space.

Following Gu et al. (2018), one simple and effective method is to select the best sequence by choosing the highest-probability latent sequence z\mathbf{z}:

where identifying y∗\mathbf{y}^{*} only requires independently maximizing the local probability for each output position (see Eq. 4).

Noisy Parallel Decoding (NPD).

A more accurate approximation of decoding, proposed in Gu et al. (2018), is to draw samples from the latent space and compute the best output for each latent sequence. Then, a pre-trained autoregressive model is adopted to rank these sequences. In FlowSeq, different candidates can be generated by sampling different target lengths or different samples from the prior, and both of the strategies can be batched via masks during decoding. In our experiments, we first select the top ll length candidates from the length predictor in §3.5. Then, for each length candidate we use rr random samples from the prior network to generate output sequences, yielding a total of l×rl\times r candidates.

Importance Weighted Decoding (IWD)

The third approximating method is based on the lower bound of importance weighted estimation (Burda et al., 2015). Similarly to NPD, IWD first draws samples from the latent space and computes the best output for each latent sequence. Then, IWD ranks these candidate sequences with KK importance samples:

IWD does not rely on a separate pre-trained model, though it significantly slows down the decoding speed. The detailed comparison of these three decoding methods is provided in §4.2.

7 Discussion

Different from the architecture proposed in Ziegler and Rush (2019), the architecture of FlowSeq is not using any autoregressive flow (Kingma et al., 2016; Papamakarios et al., 2017), yielding a truly non-autoregressive model with both efficient density estimation and generation. Note that FlowSeq remains non-autoregressive even if we use an RNN in the architecture because RNN is only used to encode a complete sequence of codes and all the input tokens can be fed into the RNN in parallel. This makes it possible to use highly-optimized implementations of RNNs such as those provided by cuDNN.https://devblogs.nvidia.com/optimizing-recurrent-neural-networks-cudnn-5/ Thus while RNNs do experience some drop in speed, it is less extreme than that experienced when using autoregressive models.

Experiments

We evaluate FlowSeq on three machine translation benchmark datasets: WMT2014 DE-EN (around 4.5M sentence pairs), WMT2016 RO-EN (around 610K sentence pairs) and a smaller dataset IWSLT2014 DE-EN (around 150K sentence pairs) Cettolo et al. (2012). We use scripts from fairseq Ott et al. (2019) to preprocess WMT2014 and IWSLT2014, where the preprocessing steps follow Vaswani et al. (2017) for WMT2014. We use the data provided by Lee et al. (2018) for WMT2016. For both WMT datasets, the source and target languages share the same set of subword embeddings while for IWSLT2014 we use separate embeddings. During training, we filter out sentences longer than 8080 for WMT dataset and 6060 for IWSLT, respectively.

Modules and Hyperparameters

We implement the encoder, decoder and posterior networks with standard (unmasked) Transformer layers (Vaswani et al., 2017). For WMT datasets, we use 8 attention heads, the encoder consists of 6 layers, and the decoder and posterior are composed of 4 layers. For IWSLT, we use 4 attention heads, the encoder has 5 layers, and decoder and posterior have 3 layers. The prior flow consists of 3 scales with the number of steps $frombottomtotop.Todissecttheimpactofmodeldimensionontranslationqualityandspeed,weperformexperimentsontwoversionsofFlowSeqwithfrom bottom to top. To dissect the impact of model dimension on translation quality and speed, we perform experiments on two versions of FlowSeq withd_{model}/d_{hidden}=256/512(base)and(base) andd_{model}/d_{hidden}=512/1024$ (large). More model details are provided in Appendix B.

Optimization

Parameter optimization is performed with the Adam optimizer (Kingma and Ba, 2014) with β=(0.9,0.999)\beta=(0.9,0.999), ϵ=1e−8\epsilon=1e^{-8} and AMSGrad (Reddi et al., 2018). Each mini-batch consist of 20482048 sentences. The learning rate is initialized to 5e−45e-4, and exponentially decays with rate 0.9999950.999995. The gradient clipping cutoff is 1.01.0. For all the FlowSeq models, we apply 0.10.1 label smoothing (Vaswani et al., 2017) and averaged the 5 best checkpoints to create the final model.

Knowledge Distillation

Previous work on non-autoregressive generation (Gu et al., 2018; Ghazvininejad et al., 2019) has used translations produced by a pre-trained autoregressive NMT model as the training data, noting that this can significantly improve the performance. We analyze the impact of distillation in § 4.2.

2 Main Results

We first conduct experiments to compare the performance of FlowSeq with strong baseline models, including NAT w/ Fertility Gu et al. (2018), NAT-IR Lee et al. (2018), NAT-REG Wang et al. (2019), LV NAR Shu et al. (2019), CTC Loss Libovickỳ and Helcl (2018), and CMLM Ghazvininejad et al. (2019).

Table 1 provides the BLEU scores of FlowSeq with argmax decoding, together with baselines with purely non-autoregressive decoding methods that generate output sequence in one parallel pass. The first block lists results of models trained on raw data, while the second block shows results using knowledge distillation. Without using knowledge distillation, the FlowSeq base model achieves significant improvements (more than 99 BLEU points) over the baselines. This demonstrates the effectiveness of FlowSeq in modeling complex interdependences in the target languages.

Regarding the effect of knowledge distillation, we can mainly obtain two observations: i) Similar to the findings in previous work, knowledge distillation still benefits the translation quality of FlowSeq. ii) Compared to previous models, the benefit of knowledge distillation for FlowSeq is less significant, yielding less than 33 BLEU improvement on WMT2014 DE-EN corpus, and even no improvement on WMT2016 RO-EN corpus. We hypothesize that the reason for this is that FlowSeq’s stronger model is more robust against multi-modality, making it less necessary to rely on knowledge distillation.

Table 2 illustrates the BLEU scores of FlowSeq and baselines with advanced decoding methods such as iterative refinement, IWD and NPD rescoring. The first block in Table 2 includes the baseline results from autoregressive Transformer. For the sampling procedure in IWD and NPD, we sampled from a reduced-temperature model (Kingma and Dhariwal, 2018) to obtain high-quality samples. We vary the temperature within {0.1,0.2,0.3,0.4,0.5,1.0}\{0.1,0.2,0.3,0.4,0.5,1.0\} and select the best temperature based on the performance on development sets. The analysis of the impact of sampling temperature and other hyper-parameters on samples is shown in § 4.4. For FlowSeq, NPD obtains better results than IWD, showing that FlowSeq still falls behind the autoregressive Transformer on modeling the distributions of target languages. Compared with CMLM (Ghazvininejad et al., 2019) with 1010 iterations of refinement, which is a contemporaneous work that achieves state-of-the-art translation performance, FlowSeq obtains competitive performance on both WMT2014 and WMT2016 corpora, with only slight degradation in translation quality. Notably we did not attempt to perform iterative refinement, but there is nothing that makes FlowSeq inherently incompatible with refinement – we leave connecting the two techniques to future work.

3 Analysis on Decoding Speed

In this section, we compare the decoding speed (measured in average time in seconds required to decode one sentence) of FlowSeq at test time with that of the autoregressive Transformer model. We use the test set of WMT14 EN-DE for evaluation and all experiments are conducted on a single NVIDIA TITAN X GPU.

First, we investigate how different decoding batch size can affect the decoding speed. We vary the decoding batch size within {1,4,8,32,64,128}\{1,4,8,32,64,128\}. Figure. 4a shows that for both FlowSeq and the autoregressive Transformer decoding is faster when using a larger batch size. However, FlowSeq has much larger gains in the decoding speed w.r.t. the increase in batch size, gaining a speed up of 594% of the base model and 403% of the large model when using a batch size of 128. We hypothesize that this is because the operations in FlowSeq are more friendly to batching while the incremental nature of left-to-right search in the autoregressive model is less efficient in benefiting from batching.

How does sentence length affect the decoding speed?

Next, we examine if sentence length is a major factor affecting the decoding speed. We bucket the test data by the target sentence length. From Fig. 4b, we can see that as the sentence length increases, FlowSeq achieves almost a constant decoding time while the autoregressive Transformer has a linearly increasing decoding time. The relative decoding speed of FlowSeq versus the Transformer linearly increases as the sequence length increases. The potential of decoding long sequences with constant time is an attractive property of FlowSeq.

4 Analysis of Rescoring Candidates

In Fig. 5, we analyze how different sampling hyperparameters affect the performance of rescoring. First, we observe that the number of samples rr for each length is the most important factor. The performance is always improved with a larger sample size. Second, a larger number of length candidates does not necessarily increase the rescoring performance. Third, we find that a larger sampling temperature (0.3 - 0.5) can increase the diversity of translations and leads to better rescoring BLEU. However, the latent samples become noisy when a large temperature (1.0) is used.

5 Analysis of Translation Diversity

Following He et al. (2018) and Shen et al. (2019), we analyze the output diversity of FlowSeq. They proposed pairwise-BLEU and BLEU computed in a leave-one-out manner to calibrate the diversity and quality of translation hypotheses. A lower pairwise-BLEU score implies a more diverse hypothesis set. And a higher BLEU score implies a better translation quality. We experiment on a subset of the test set of WMT14-ENDE with ten references for each sentence Ott et al. (2018). In Fig. 6, we compare FlowSeq with other multi-hypothesis generation methods (ten hypotheses each sentence) to analyze how well the generation outputs of FlowSeq are in terms of diversity and quality. The right corner area of the figure indicates the ideal generations: high diversity and high quality. While FlowSeq still lags behind the autoregressive generation, by increasing the sampling temperature it provides a way of generating more diverse outputs while keeping the translation quality almost unchanged. More analysis of translation outputs and detailed results are provided in the Appendix D and E.

Conclusion

We propose FlowSeq, an efficient and effective model for non-autoregressive sequence generation by using generative flows. One potential direction for future work is to leverage iterative refinement techniques such as masked language models to further improve translation quality. Another exciting direction is to, theoretically and empirically, investigate the latent space in FlowSeq, hence providing deeper insights into the model, and allowing for additional applications such as controllable text generation.

Acknowledgments

Xuezhe MA was supported in part by DARPA grant FA8750-18-2-0018 funded under the AIDA program and Chunting Zhou was supported by DARPA grant HR0011-15-C-0114 funded under the LORELEI program. Any opinions, findings, and conclusions expressed in this material are those of the authors and do not necessarily reflect the views of DARPA. The authors thank Amazon for their gift of AWS cloud credits and anonymous reviewers for their helpful suggestions.

References

Appendix A Flow Layers

Invertible Linear

Affine Coupling

Appendix B Model Details

Appendix C Analysis of training dynamics

In Fig. 7, we plot the train and dev loss together with dev BLEU scores for the first 50 epochs. We can see that the reconstruction loss is increasing at the initial stage of training, then starts to decrease when training with full KL loss. In addition, we observed that FlowSeq does not suffer the KL collapse problem (Bowman et al., 2015; Ma et al., 2019). This is because the decoder of FlowSeq is non-autogressive, with latent variable z\mathbf{z} as the only input.

Appendix D Analysis of Translation Results

In Tab. 4, we present randomly picked translation outputs from the test set of WMT14-DEEN. For each German input sentence, we pick three hypotheses from 30 samples. We have the following observations: First, in most cases, it can accurately express the meaning of the source sentence, sometimes in a different way from the reference sentence, which cannot be precisely reflected by the BLEU score. Second, by controlling the sampling hyper-parameters such as the length candidates ll, the sampling temperature τ\tau and the number of samples rr under each length, FlowSeq is able to generate diverse translations expressing the same meaning. Third, repetition and broken translations also exist in some cases due to the lack of direct modeling of dependencies between target words.

Appendix E Results of Translation Diversity

Table 5 shows the detailed results of translation diversity.