Generating Sentences from a Continuous Space
- Publication
- CoNLL 2016Conference
- First submitted to arXiv
- arXiv:1511.06349
Cite this paper · BibTeX
The citation identifies the linked source version. It cites the original paper and its authors.
@misc{transformerssentencevae2015,
title = {{Generating Sentences from a Continuous Space}},
author = {Samuel R. Bowman and Luke Vilnis and Oriol Vinyals and Andrew M. Dai and Rafal Jozefowicz and Samy Bengio},
year = {2015},
eprint = {1511.06349},
archivePrefix = {arXiv},
url = {https://arxiv.org/abs/1511.06349}
}
Take an ordinary sequence autoencoder, encode two sentences into vectors, draw a straight line between the two vectors, pick a few points along it and decode them back into sentences, and you get something like this:
i went to the store to buy some groceries .
i store to buy some groceries .
i were to buy any groceries .
horses are to buy any groceries .
horses are to buy any animal .
horses the favorite any animal .
horses the favorite favorite animal .
horses are my favorite animal .
Compiled from Table 1 of the paper.
The first and last sentences are real; everything in between is broken English. The autoencoder memorizes each sentence as an isolated point in the space, and the regions between the points were never trained, so when the decoder gets a vector from there, all it can do is scribble.
The authors wanted a different kind of space, one where any point decodes to a fluent sentence, nearby points correspond to similar sentences, and you can draw a point straight from a known distribution and write a new sentence from it. VAEs had done this for images, so they moved the VAE over to sentences, replacing both the encoder and the decoder with LSTMs.
The first thing that happened after the move was that the decoder ignored the latent variable entirely and the KL term dropped to zero. This paper describes the phenomenon in concrete detail, proposes two ways around it, and honestly admits that it did not beat an ordinary RNN language model on perplexity. The phenomenon later came to be called posterior collapse, and for years afterward nearly every VAE paper that discussed it cited this one.
Defining the Problem
RNN language models have no "whole sentence"
In 2015, the strongest model for unsupervised sentence generation was the RNN language model (RNNLM). It factorizes the probability of a sentence into word-by-word conditional probabilities:
At each step it reads the previous word, updates its hidden state, and predicts the next word. This factorization makes no independence assumptions and can describe very long dependencies; machine translation and image captioning use the same kind of decoder, just with an extra condition attached.
The problem is that it has nowhere to keep "this whole sentence." Global features such as topic, tone, or whether the sentence is a question are scattered across the hidden states of every step; nothing outside the model can read them, and there is no way to specify them. What the authors wanted was a different factorization:
First draw a continuous vector that stands for the whole sentence, then write the sentence out from it.
None of the existing sentence vectors can generate
At the time there were three unsupervised ways to turn a sentence into a vector, and the authors rule them out one by one in Section 2.1.
- Sequence autoencoder: both encoder and decoder are RNNs, with a sentence vector in between. The interpolation table at the start is its report card. It has no prior over , so it can neither assign a probability to a sentence nor sample new ones.
- Skip-thought: the same structure as the sequence autoencoder, but the decoder writes the neighboring sentences rather than the sentence itself.
- Paragraph vector: each sentence needs its own vector inferred separately by gradient descent, and it is not a generative model either.
The VAE supplies exactly what these methods lack. Its encoder outputs a distribution (usually a diagonal Gaussian), which the paper describes as "soft ellipsoidal regions" in latent space; these ellipsoids are required to stay close to the prior , so they have no choice but to fill the space, and points drawn from the prior land in regions the decoder has seen.
Image VAEs, however, used decoders with independent pixels, each pixel looking only at . That doesn't work for sentences. Words depend on each other too strongly, so the decoder has to be an RNN. When the decoder is itself a complete language model, then, will it still use ?
Solving the Problem
The model

Follow the sentence RNNs work from the figure through the model.
The encoder is a single-layer LSTM that reads the word embeddings of RNNs and work in turn. Its final state splits into two paths, each through a linear layer, giving and , whose dimension is the dimension of the latent variable; in the PTB experiments, automatic hyperparameter tuning picked . Next comes sampling with the reparameterization trick:
is fed only into the first decoding cell, at the start of decoding. The decoder is also a single-layer LSTM; its input is the target sentence shifted right by one position, <EOS>, RNNs, work, and it has to write out RNNs, work, <EOS> in turn. During training every step is fed the true previous word (teacher forcing), and this will shortly turn out to be the source of the problem.
The authors tried several variants: concatenating to the decoder input at every step, parameterizing the variance with softplus, adding deep feedforward networks before and after . All performed about the same, and with feedforward networks, highway layers were needed for the model to train at all. More elaborate approximate posteriors, such as DRAW-style multi-step sampling or normalizing flows, brought no clear benefit either. So the whole paper uses the plainest version, the one in the figure.
The two terms of the objective
The training objective is the VAE's evidence lower bound (Eq. 1 of the paper). Substituting the word-by-word factorization of the sentence:
The first term is the reconstruction term, the negative of the decoder's cross-entropy on this sentence, estimated with a single sample of . The second is the KL divergence between the approximate posterior and the prior; both are diagonal Gaussians, so it has a closed form:
Take a 2-dimensional and work out two cases.
- The encoder outputs , for this sentence. Each dimension gives , so the KL is 0. This amounts to handing over the prior untouched: every sentence's comes from the same distribution, and the decoder can read nothing about this sentence from .
- The encoder outputs , . The first dimension gives , which times is 1.443; the second dimension gives 0. The KL is about 1.44 nats. The encoder has shifted and narrowed the first dimension's distribution, and starts carrying information about this sentence, at a cost of 1.44 nats.
Averaged over the whole dataset, the KL splits into the mutual information between and plus a nonnegative term, so it is an upper bound on how many nats of information carries on average. A KL of 0 means carries nothing.
Why the KL drops to zero
Section 3.1 records what actually happened in training. Trained with the setup above, except in vanishingly rare cases, most runs under most hyperparameters drive to equal the prior, the KL goes to zero, and the model degenerates into an RNNLM.
There are two reasons, one stacked on the other.
The first is that the decoder is good enough on its own. An RNNLM can express any distribution over sentences (just with a left-to-right factorization), and it can get the likelihood close to optimal without . Pushing the KL to 0 is then the easiest solution. Image VAEs have no such escape route. A decoder with independent pixels that ignores can only output an average image, and its likelihood will be poor, so it has no choice but to use .
The second is the dynamics early in training. At first the encoder hasn't learned anything, so to the decoder is just a lump of sampling noise, and LSTMs are sensitive to subtle variations in their hidden state. The lowest-hanging fruit is the previous word, so the decoder first learns to ignore and explain the data with the history that teacher forcing hands it. Once the decoder ignores , the gradient of the reconstruction term with respect to is close to 0, and the encoder is left with only the gradient of the KL term, which pushes toward 0 and toward 1. becomes the prior, the KL stays at 0, and the decoder has even less reason to look at . This is a stable equilibrium.
The authors propose two fixes, one that weakens the KL penalty and one that weakens the decoder.
KL annealing
The first fix puts a weight that changes over training in front of the KL term:
At first , and the model is an ordinary autoencoder with sampling noise; the encoder can pack as much information into as it likes at no cost. Then is raised slowly, forcing the model to organize its codes into the shape of the prior; once reaches 1, the objective is back to the true variational lower bound. The authors describe it as annealing from a vanilla autoencoder to a VAE. Early in training the optimization is not on the correct lower bound, yet at convergence the value of the bound comes out better.

These are the first 50,000 steps of language modeling on the Penn Treebank (PTB). The blue line is the KL weight, which stays almost at 0 for the first thousand-odd steps and then climbs along an S-shaped curve to 100% around step 6,000; the remaining 40,000-plus steps use the full VAE objective. The red line is the KL value without the weight, and it reads in three stages.
- For roughly the first 1,500 steps, the weight is still near 0, storing information in costs almost nothing, and the KL shoots up to about 7.5.
- Once the weight starts climbing, the KL plunges from 7.5 to around 1; the weight has barely left 0 and the KL has already lost a big chunk.
- After that, the KL slowly climbs back, to about 1.8 by step 50,000, as the model learns to condense more information into .
The authors say this is a pattern they observed often. The second stage is the dangerous one. If the KL kept falling all the way to 0 there, the model would be back at the collapsed equilibrium; annealing lets the encoder learn something useful before it gets penalized, so the decoder gets into the habit of looking at .
The paper calls this only a "typical sigmoid annealing schedule" without giving a formula, and the rate of increase is tuned as a hyperparameter. The popular PyTorch reproduction timbmg/Sentence-VAE uses with defaults and , so at step 0 , at step 2,500 it is 0.5, and at step 5,000 about 0.998, a shape very close to Figure 2. In Figure 2 the weight only starts climbing after the KL has peaked; if the weight climbs too early, the encoder gets pushed back to the prior before it has learned anything.
Word dropout
The second fix goes after the decoder. Teacher forcing lets the decoder see the correct previous word at every step, and that is what lets it afford to ignore . The authors randomly replace words in the decoder's input with the unknown-word token UNK; whatever words it can't see, it has to infer from .
Take i went to the kitchen . as an example. Normally the decoder input is just the target sequence shifted by one position; with the keep rate set to 75%, one training pass might look like this:
target i went to the kitchen . <EOS>
input <EOS> i UNK to the UNK .
At step 3 the decoder has to write to, but its input is UNK; all it knows is that there was an i followed by a word it can't see. Before writing . at step 6, it doesn't know that the previous word was kitchen. These gaps have to be filled in from .
The technique is parameterized by the keep rate , which is tuned for both the VAE and the RNNLM so the comparison is fair. is the original decoder; at the decoder sees UNK at every step and is left only with the information of how many words it has written so far, which the paper calls an inputless decoder. The authors also tried standard dropout on the decoder's word embeddings, and the model did not learn to use from it; what has to go is the whole word.
Together, the two fixes change only a few lines of the training loop. Below are word dropout and the weighted loss, written from the paper's description, with the KL computed by the closed form from earlier:
import torch
import torch.nn.functional as F
def word_dropout(dec_inputs, keep_rate, unk_id, pad_id, bos_id):
drop = torch.rand(dec_inputs.shape, device=dec_inputs.device) > keep_rate
drop &= (dec_inputs != pad_id) & (dec_inputs != bos_id)
return dec_inputs.masked_fill(drop, unk_id)
def sentence_vae_loss(logits, targets, mu, logvar, kl_weight, pad_id):
# logits: [B, T, V]; targets: [B, T]; mu, logvar: [B, d]
rec = F.cross_entropy(logits.transpose(1, 2), targets,
ignore_index=pad_id, reduction="sum")
kl = 0.5 * torch.sum(mu.pow(2) + logvar.exp() - 1 - logvar)
batch = targets.size(0)
return (rec + kl_weight * kl) / batch, rec / batch, kl / batch
word_dropout is applied only to the decoder input during training; the encoder always reads the full sentence, and at test time the decoder gets the full input too. The reconstruction term and the KL are returned separately so they can be monitored separately; the total loss alone won't tell you whether the KL has already hit zero.
Discussion
PTB language modeling: no win
Section 4 compares the VAE and the RNNLM on PTB. Hyperparameters for both are searched automatically with Bayesian optimization: each configuration runs for 10 hours, 12 in parallel, and the best is picked after 200 runs; the VAE search keeps only models whose KL is not 0. The reported results are test-set scores at the step that does best on the development set.
| Decoder | Model | NLL | PPL |
|---|---|---|---|
| Standard | RNNLM | 100 | 116 |
| Standard | VAE | 101 (KL 2) | 119 |
| Inputless | RNNLM | 135 | > 600 |
| Inputless | VAE | 125 (KL 15) | 380 |
Compiled from Table 2 of the paper, test set. NLL is the negative log-likelihood per sentence (nats) and PPL is per-word perplexity; lower is better for both.
The RNNLM's NLL is exact, while the VAE's is converted from the variational lower bound and is only an upper bound on the true value, so the comparison itself is tilted against the VAE.
In the two standard-decoder rows, the VAE's reconstruction term is 99, slightly better than the RNNLM's 100, but adding the KL of 2 brings the total to 101, with perplexity 119 against 116. In other words, carries at most 2 nats of information per sentence on average, about 2.9 bits, roughly what it takes to pick one of 7 () equally likely options, while the whole sentence takes 100 nats. The authors also state that unless word dropout and KL annealing are used together in training, the model reliably lands on the solution where the KL is 0 and it performs the same as the RNNLM. The VAE here uses word dropout with a keep rate of 0.62, and automatic tuning picked a latent dimension of 13.
The two inputless-decoder rows show more clearly what is doing. When the decoder sees nothing, the RNNLM can only memorize which words tend to appear at which position, and its perplexity exceeds 600; the VAE's KL rises to 15, its NLL drops by 10 nats, and its perplexity is 380. The latent dimension picked here is 111. The authors also note that the inputless decoder's generation process is fully differentiable, so it might someday be plugged into adversarial training that needs a differentiable generator.
Even with these tricks, though, the authors could not train a model whose KL was larger than its reconstruction term. Their reading is that factoring the data distribution with local statistics is still much easier, so the encoder only puts into the information that local statistics cannot describe.
Imputing words: letting z pass the message
Section 5 moves to the Books Corpus, compiled from 12,000 e-books (mostly novels), about 80 million sentences after pruning. All models here are trained with a 75% keep rate and 512 hidden units, and both the VAE and the RNNLM decode right to left.
The task is imputation. The last 20% of the words in each sentence are masked, and the model has to fill them back in. Because decoding runs right to left, the masked end of the sentence is exactly the part generated first. When the RNNLM writes the ending, it hasn't seen any of the earlier part of the sentence; the last word of the sentence is the first word it generates, and it can only pick from the 15 most probable words under the unconditional distribution (the beam size is 15). The authors also state that they chose this setting precisely to show the benefit of a global latent variable where the RNNLM's inductive bias puts it at the biggest disadvantage.
The VAE imputes with approximate iterated conditional modes. Unknown words are first filled with UNK, the whole sentence goes through the encoder, and the posterior mode is taken as ; then, with fixed, beam search fills only the unknown positions; once filled, the sentence is encoded again, for 3 rounds, each with beam size 5. This gives both sides the same compute, and the known first 80% of the sentence can reach the end through the encoder and .
A few examples (before the arrow is the known part of the sentence; after it come the ground truth, the RNNLM and the VAE, in that order):
you kill him and his→men ./. ”/brother .but now , as they parked out front and owen stepped out of the car , he could see→that the transition was complete ./it , ” i said ./through the driver ’s door .not surprising , the mothers dont exactly see eye to eye with me→on this matter ./, i said ./, right now .
Compiled from Table 3 of the paper.
Imputation quality is hard to score directly with likelihood, so the authors borrow ideas from adversarial training and two-sample tests and train classifiers to tell real sentences from imputed ones. The data is 320,000 sentences, half real and half imputed, split 80/10/10; there are two classifiers, a logistic regression on unigram bag-of-words features and an LSTM that reads the whole sentence before deciding. The adversarial error is defined as the gap between the classifier's accuracy and the ideal 50%; lower means harder to tell apart.
| Model | unigram | LSTM | NLL |
|---|---|---|---|
| RNNLM (beam 15) | 28.32 | 38.92 | 46.01 |
| VAE (3 × beam 5) | 22.39 | 35.59 | 46.14 |
Compiled from Table 4 of the paper. The first two columns are adversarial error (%), and NLL is the score a separately trained RNNLM gives the whole sentence; lower is better for all of them.
The VAE is harder to catch with both classifiers, 5.9 percentage points lower with unigrams and 3.3 lower with the LSTM. Converted back to accuracy, the LSTM classifier is 88.9% accurate on the RNNLM's imputations and still 85.6% on the VAE's, so both remain easy to spot. The RNNLM is slightly lower in the NLL column because it favors high-probability endings like he said. The paper itself notes that scoring sentences written by an RNNLM with an RNNLM can't measure the model's ability in the first place; all it shows is that the model picks what it considers typical phrasing.
How much word dropout

Section 6.1 sweeps the keep rate on the Books Corpus, with a separate held-out test set of 10,000 sentences. Each bar is the variational lower bound split into its two terms, blue for cross-entropy (reconstruction) and red for KL, and the total height is the negative lower bound.
At a keep rate of 100%, the KL is almost 0 and the cross-entropy about 45. As the keep rate drops to 90%, 75%, 50% and 0%, the KL is about 4.7, 8.8, 15.1 and 20.9, and the cross-entropy falls from 41 to around 33, then climbs back to about 35 at 0%. The total rises from 45 to about 56. The less history the decoder sees, the more information stores, and the overall likelihood gets worse along with it. Hyperparameters were not re-tuned for each keep rate in this experiment, which is also part of why the 100% bar has a KL of nearly 0.
The numbers alone don't say whether what stores is useful. The authors draw from the prior and write sentences with greedy decoding, taking the most probable word at every step; the decoding involves no randomness at all, so all of the variation in the sentences comes from . Samples at each keep rate:
- 100%:
“ no , ” he said .,“ thank you , ” he said . - 75%:
“ love you , too . ”,she put her hand on his shoulder and followed him to the door . - 50%:
“ maybe two or two . ”,she laughed again , once again , once again , and thought about it for a moment in long silence . - 0%:
i i hear some of of of,i was noticed that she was holding the in in of the the in
Compiled from Table 5 of the paper.
When stores almost nothing, you get much the same short sentence wherever you sample. At 75% the sentences are varied and fluent; at 50% they start repeating themselves, and at 0% they are no longer English, though they still have a bit more structure than unigram statistics. The authors use the 75% model for all their later analysis.
What the latent space looks like
Feed a sentence to the encoder and decode from its posterior, and you find out which sentences the model treats as neighbors. For example:
input we looked out at the setting sun .
mean they were laughing at the same time .
sample 1 ill see you in the early morning .
sample 2 i looked up at the blue sky .
sample 3 it was down on the dance floor .
Compiled from Table 7 of the paper.
The original sentence doesn't come back, but the word count, the part-of-speech order and the rough topic are all preserved. A VAE is required to output a distribution rather than a single point, so it was never going to recite its input back verbatim; the longer the sentence, the further the decoded sentences drift from the original. The other two examples are shorter. i went to the kitchen . decodes from the mean back to the original sentence, and how are you doing ? becomes what are you doing ?.
Next comes the VAE version of the experiment from the start. Take points on the straight line between two codes and
and greedily decode each one; the paper calls this a homotopy. Below are two paths whose endpoints were sampled at random from the latent space:
“ i want to talk to you . ”
“i want to be with you . ”
“i do n't want to be with you . ”
i do n't want to be with you .
she did n't want to be with him .
he was silent for a long moment .
he was silent for a moment .
it was quiet for a moment .
it was dark and cold .
there was a pause .
it was my turn .
Compiled from Table 8 of the paper.
Compared with the autoencoder's table, every sentence in the middle is grammatical, and neighboring sentences differ in only one or two places. The authors observe that mainly stores syntactic information, such as word count and the part of speech at each position, while the topic stays consistent only over short stretches of the path. Sentences with opposite sentiment but similar syntax and topic, such as the pain was unbearable and the thought made me smile, can also get very close codes, the same thing that often makes good and bad look alike in word vectors. The appendix also says that because the training data includes plenty of romance novels, the interpolated topics are often rather dramatic.
The authors also tried samples from the tails of the prior. They apply an approximately volume-preserving random linear transformation to Gaussian samples, stretching some directions by up to 4 times, to reach rarer regions. The decoded sentences are less typical, such as atop the circular dais perched atop the gleaming marble columns began to emerge from atop the stone dais, perched atop the dais ., but mostly still grammatical and on topic.
The appendix also uses the posterior mean as a sentence vector and attaches a linear classifier for downstream tasks. On MSR paraphrase detection, the VAE gets 72.9 accuracy and 81.4 F1, slightly below skip-thought's 73.0 and 82.0, and reaches up to 76.9 and 83.8 when concatenated with other features; on TREC question classification it scores 87.0, beating the sequence autoencoder's 84.2 but losing to averaged word vectors at 87.3 and skip-thought at 92.2. The authors' explanation is that a Gaussian latent space may be inherently unfavorable to linear separability.
How later work saw it
The paper attributes the KL dropping to zero to "optimization challenges," and both fixes change the training process. A year later, Chen et al. in "Variational Lossy Autoencoder" offered another angle. Working from bits-back coding, they showed that the VAE's average code length exceeds the data's entropy by at least , the extra cost of an inaccurate approximate posterior. As long as the decoder can describe the data without , setting to the prior makes this extra cost disappear. So even with flawless optimization, the optimal solution still ignores ; information that can be modeled locally stays in the decoder, and only the remainder goes into . On this view, KL annealing and word dropout work because they change this trade-off, and word dropout does it by changing the decoder itself.
In 2017, Yang et al. went further down the road of weakening the decoder. They replaced the LSTM decoder with a dilated CNN, using the receptive field to control how much history the decoder can see. On Yahoo Answers, an LSTM-VAE with Bowman's setup got an NLL of 342.1 and a KL of 0.0, losing to the LSTM language model's 334.9; a CNN decoder with a 125-word receptive field reached 333.9 with a KL of 6.7, which the authors called the first positive result for text VAEs in language modeling. Enlarging the receptive field to 187 dropped the KL to 0.7, and the NLL equaled that of a CNN language model of the same size, both 336.5. The further the decoder can see, the less use is, the same direction as the word dropout keep-rate sweep above.
KL annealing, meanwhile, became the default way to train text VAEs. In 2019, Fu et al.'s "Cyclical Annealing Schedule" said outright that this monotonic annealing was "the de facto standard in training text VAEs," yet had never been justified, and how to set the schedule had rarely been studied. Their explanation is that an autoregressive decoder has two paths available, one through and one that looks directly at the previous words; early in training is of too poor quality, so the model takes the latter. They repeat the process of raising from 0 to 1 several times, letting each cycle start from the learned in the one before. The same year, He et al. argued that the problem is the inference network failing to keep up with the true posterior, and updated the encoder several more times before each decoder update.
The timbmg/Sentence-VAE mentioned above first implemented word dropout as dropout on the word embeddings; in August 2018 someone pointed out in issue #5 that this differed from the paper, the maintainer replied "Right, this is different from the paper," and the same day added a --word_dropout that replaces words with <unk>. The same change, however, set the defaults to --word_dropout 0 and --embedding_dropout 0.5 (the very one the paper had just said doesn't help), so if you run it with the defaults, only one of the two fixes is left.
Conclusion
An LSTM encoder, an LSTM decoder and a single Gaussian latent variable, plus KL annealing and word dropout, and the authors got a VAE to learn a continuous space of sentences that can be sampled and interpolated. Points drawn from the prior produce varied sentences under greedy decoding, every step of an interpolation between sentences is grammatical, and in imputation can carry information from the start of a sentence to its end. The price is that on PTB carries only about 2 nats per sentence, with perplexity 119 against 116, so it did not beat the RNNLM.
If you're training a text VAE, log the reconstruction term and the KL separately. A KL that spikes in the first few thousand steps and then falls is normal; it's collapse when it hits 0 and never climbs back. Turn on word dropout first (try keep rates from 0.6 to 0.75), then tune the annealing speed so that the weight's climb comes after the KL spike; when using an existing reproduction, first check that it drops whole words, not word embeddings.
As for the RNNLM, across all of the paper's imputation examples, its favorite thing to write is still i said.