Encoder–Decoder Models & Attention
Mapping sequences to sequences, and the attention mechanism that removed the bottleneck.
Translate "the black cat" into French and you get "le chat noir": the same number of words, but the adjective has moved. An encoder–decoder reads the whole input, then writes the output one token at a time until it predicts an end token. Its first version squeezed every sentence into one vector. Attention let the decoder look back at every input word instead, and that change led directly to the transformer.
What you’ll learn
- Write an encoder–decoder as a conditional language model and train it by maximum likelihood with teacher forcing.
- Explain the fixed-vector bottleneck with a gradient-path argument, and derive additive (Bahdanau) and multiplicative (Luong) attention with their costs.
- Implement an attention decoder in PyTorch, and decode it greedily or with beam search, counting the work per step.
- Compute BLEU from clipped n-gram precisions and the brevity penalty, and trace how cross-attention carried this design into the transformer.
Sequences in, sequences out
Translation, summarization, speech recognition and question answering all map one sequence to another. The output's length is not fixed by the input's ("je ne sais pas" has four words, "I don't know" three), and the order can change. An RNN that emits one output per input step cannot express either. The encoder–decoder, or sequence-to-sequence model, splits the job in two: an encoder reads the whole input, and a decoder writes the output one token at a time, conditioning each token on the input and on the tokens it has already written.
Generation stops when the decoder emits , so the model chooses the length of its output. Sutskever, Vinyals and Le (2014) built this with two four-layer LSTMs of 1,000 cells per layer, one reading English and one writing French. Cho et al. (2014) proposed the same scheme with a new gated cell, the GRU, and used it to score phrase pairs inside a conventional statistical translation system.
Sutskever et al. also found a curious trick: feed the source sentence backwards. Reversal leaves the average distance between corresponding words unchanged but puts the first source words right next to the first target words, giving the optimizer some short dependencies to start from. It cut test perplexity from 5.8 to 4.7. An ensemble of five reversed networks, decoded with beam search, scored 34.8 BLEU on the WMT'14 English→French test set against 33.3 for a phrase-based system: by the authors' account, the first time a purely neural translator beat a phrase-based baseline on a large-scale task by a sizeable margin.
Why must every training target end with the token ?
- It tells the encoder where the source sentence ends
- It resets the decoder's hidden state between sentences
- It lets the model put probability on outputs of every length, since stopping becomes one more prediction
- It makes beam search faster by pruning long hypotheses
Show the answer
C. It lets the model put probability on outputs of every length, since stopping becomes one more prediction
Without a stop token, would only define distributions over sequences of one fixed length. With it, "stop now" competes with every other token at every step, and the probabilities of all finite sequences can sum to one. The model learns when translations end from the data.
Training: teacher forcing and its gradient
Training maximizes the log-likelihood of a parallel corpus (maximum likelihood). The logarithm turns the product of the factorization into a sum, so the loss is one cross-entropy term per target token. Each term is computed on the gold prefix: at step the decoder is fed the true previous token , not its own guess. This is teacher forcing (Williams & Zipser, 1989). It needs no sampling during training, and every step's target is known in advance.
Take logs of the factorization and average over the corpus:
With logits and , the gradient of one term is the familiar "prediction minus one-hot target":
This error flows back through the decoder and then into the encoder by backpropagation through time. In the fixed-vector model it reaches the encoder only through , so the gradient for an early state is multiplied by every encoder Jacobian between and :
If every Jacobian has norm at most , the signal that ties output to source word shrinks geometrically with the number of steps in between. That is the vanishing gradient of Recurrent Neural Networks, now standing between a translation and the words it translates:
The bottleneck
In the basic model, all the information about the source that the decoder can use has to pass through one vector of fixed size, however long the sentence. Two problems follow. Information about early words must survive every later encoder update, and, as the derivation showed, the gradient that would teach the encoder to keep it must survive the same journey backwards.
Sutskever et al.'s encoder is a 4-layer LSTM with 1,000 cells per layer, and the decoder starts from its final state. How many real numbers carry the whole source sentence to the decoder?
Show the answer
8000
Each LSTM layer has a hidden state and a cell state , each with 1,000 entries, so numbers, the figure the paper itself gives. A 50-word sentence with 1,000-dimensional embeddings enters as numbers; a 100-word one as , and still leaves through the same .
Bahdanau, Cho and Bengio (2015) measured the cost. Their fixed-vector baseline lost translation quality steeply as sentences grew longer, while their attention model, trained on the same data, showed no deterioration even for sentences of 50 words or more. On the full WMT'14 English→French test set it scored 26.75 BLEU against the baseline's 17.82. (Sutskever et al.'s deep LSTMs, trained on reversed sources, held up well on long sentences, where related encoder–decoders from other groups had degraded, which shows that the bottleneck is a matter of degree; attention removed it.)
Attention: a new context for every output
Bahdanau et al. kept every encoder state. A bidirectional encoder reads the source in both directions, so each annotation summarizes the whole sentence with a focus on the words around . Before emitting , the decoder scores every annotation against its previous state, turns the scores into weights with a softmax, and reads the weighted average:
Bahdanau et al. read as the probability that target word is aligned to, or translated from, source word . Then is an expected annotation. Classical statistical translation treated word alignment as a discrete hidden variable to be inferred; here a soft alignment is computed directly and learned with no alignment labels. Plotted as a matrix it hugs the diagonal and bends where the two languages order words differently. In today's vocabulary of the attention mechanism, the decoder state is the query and the annotations are the keys and values.
Differentiate the context with respect to one annotation. Besides the terms that pass through the weights, there is a direct one:
So the loss at output reaches in one hop, scaled by , instead of through encoder Jacobians. Every source position is a constant number of steps from every output, whatever the sentence length:
The price is one score per (output, source) pair. does not depend on , so it is computed once per sentence; each output step then needs and scores of size . With annotation size and decoder size , the multiply–adds per sentence pair are about
Bahdanau et al. used , a decoder of size and annotations of size (two directions of 1,000 units), so the scoring network alone has about three million weights, evaluated times per sentence pair:
Score functions, in code
Luong, Pham and Manning (2015) simplified the recipe. Their decoder first updates its state to , scores the encoder states against rather than , and combines context and state into , which feeds the output softmax and, with "input feeding", the next step's input. They compared score functions, and multiplicative ones are cheaper than the additive network:
| Score | Form | Weights | Used in |
|---|---|---|---|
| Additive (concat) | Bahdanau et al. (2015) | ||
| Dot | none; needs | Luong et al. (2015) | |
| General (bilinear) | Luong et al. (2015) | ||
| Scaled dot product | with , , and separate values | three projections | transformers (Vaswani et al., 2017) |
import torch
import torch.nn as nn
class AttnSeq2Seq(nn.Module):
def __init__(self, V_src, V_tgt, d=256, d_a=256):
super().__init__()
self.src_emb, self.tgt_emb = nn.Embedding(V_src, d), nn.Embedding(V_tgt, d)
self.enc = nn.GRU(d, d, batch_first=True, bidirectional=True) # annotations: 2d
self.dec = nn.GRUCell(3 * d, d) # input: [e(y_prev); c_t]
self.W, self.U = nn.Linear(d, d_a, bias=False), nn.Linear(2 * d, d_a)
self.v = nn.Linear(d_a, 1, bias=False)
self.out = nn.Linear(3 * d, V_tgt) # reads [s_t; c_t]
def forward(self, x, y_in): # x: (B, T_x); y_in: (B, T_y) = <bos> + gold prefix
H, _ = self.enc(self.src_emb(x)) # (B, T_x, 2d)
UH = self.U(H) # once per sentence
s = H.new_zeros(x.size(0), self.dec.hidden_size)
logits = []
for t in range(y_in.size(1)): # teacher forcing
e = self.v(torch.tanh(self.W(s)[:, None] + UH)).squeeze(-1) # (B, T_x)
a = torch.softmax(e, dim=-1) # alignment weights
c = torch.bmm(a[:, None], H).squeeze(1) # context: (B, 2d)
s = self.dec(torch.cat([self.tgt_emb(y_in[:, t]), c], -1), s)
logits.append(self.out(torch.cat([s, c], -1)))
return torch.stack(logits, 1) # (B, T_y, V_tgt)Additive attention exactly as in the equation, scored with the previous state. Train with F.cross_entropy(logits.transpose(1, 2), y_out), where y_out is the gold target shifted one step left and ending in . Real code also gives padded source positions a score of and ignores padded target positions in the loss.
From here to the transformer. By 2016, attention-based LSTM encoder–decoders were the standard in translation; Google's production system stacked eight LSTM layers in both encoder and decoder with attention between them (Wu et al., 2016). What remained slow was the recurrence: the encoder still needed sequential steps, even though attention had already made every source word one hop from every output. Vaswani et al. (2017) removed recurrence altogether. In the transformer, encoder and decoder both use self-attention, each position attending to the positions of its own sequence, and the decoder reads the encoder through cross-attention: Bahdanau's attention in matrix form, with queries from the decoder, keys and values from the encoder and scaled dot-product scores. Encoder–decoder transformers such as T5 and Whisper keep this layout; decoder-only language models drop the encoder and put the source text in the prompt. Self-Attention & Multi-Head Attention derives the layer.
Decoding and evaluation
A trained model defines , but translation needs one output, ideally the mode . The decoder state depends on the entire prefix, so there is no dynamic program over candidate sequences. Greedy decoding takes the most probable token at every step. Beam search keeps the best prefixes instead:
BEAM-SEARCH(x, beam width k, maximum length T_max)
live ← { (⟨bos⟩, 0) } // prefixes with their log-probabilities
done ← ∅
for t = 1 … T_max:
cand ← { (y·w, s + log p(w | y, x)) : (y, s) ∈ live, w ∈ V } // k·|V| candidates
keep the k highest-scoring candidates
move those ending in ⟨eos⟩ to done; live ← the rest
if live = ∅ or the best score in done ≥ the best score in live: stop
return the y in done with the largest score(y) / lp(y)Each step runs the decoder once per live prefix (batched) and selects the top of candidates. Greedy decoding is . The stopping rule is exact for plain log-probabilities (), because adding a token can only lower a score. Every token adds a negative log-probability, so raw scores favor short outputs, and length normalization divides by (Wu et al., 2016).
You decode one source sentence greedily and with beam search (). Which statement is guaranteed?
- Beam search returns the most probable translation
- Beam search's output is at least as probable as greedy's
- Neither output is guaranteed to be the most probable translation
- Both return the same output, because they start with the same first token
Show the answer
C. Neither output is guaranteed to be the most probable translation
Both are heuristics for a search over exponentially many sequences. A larger beam usually finds more probable outputs, but nothing guarantees it, and the most probable output can be one neither of them reaches.
Scoring translations. Outputs are compared with human references, most often with BLEU (Papineni, Roukos, Ward & Zhu, 2002). Over a whole test corpus it computes, for , the modified -gram precision : the fraction of the output's -grams that occur in a reference, with each -gram's count clipped to its largest count in any single reference, so repeating a correct word earns nothing. Precision alone would reward short, timid outputs, so the geometric mean is multiplied by a brevity penalty in the total output length and reference length :
BLEU is a corpus-level statistic. On single sentences it is noisy (a sentence without a single matching 4-gram scores zero), and it gives no credit to a correct paraphrase that uses different words.
Key takeaways
- An encoder–decoder is a conditional language model, ; an end-of-sequence token lets it choose the output length, and teacher forcing trains every step with one cross-entropy term on the gold prefix.
- A single context vector is a bottleneck: the source must fit in a fixed number of values (8,000 for Sutskever et al.), and the gradient to early source words must cross encoder Jacobians.
- Attention recomputes at every step from softmax-normalized scores (additive or multiplicative ): a soft alignment learned without labels, costing scores.
- Decoding approximates the mode with greedy search or beam search ( candidates per step), usually with length normalization; BLEU scores outputs by clipped -gram precision times a brevity penalty.
- The transformer keeps the encoder–decoder and its cross-attention but replaces recurrence with self-attention.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
In Bahdanau et al.'s attention model, which quantity is recomputed at every output step ?
- The encoder annotations
- The weights and the context
- The projected annotations
- The source embeddings
Show the answer
B. The weights and the context
The scores depend on the decoder state , so the weights and the context change with every output token. Everything on the source side is computed once per sentence.
During teacher-forced training, what is the decoder's input at step ?
- Its own prediction from step
- The gold token that it must predict
- The encoder annotation at the same position
- The gold previous token
Show the answer
D. The gold previous token
Teacher forcing conditions every prediction on the true prefix , so each step's loss is a plain cross-entropy against . At test time the model must condition on its own outputs instead, which is the source of exposure bias.
Beam search with width runs over a vocabulary of tokens. How many candidate extensions does it score at each step, once the beam is full?
Show the answer
C.
Each of the live prefixes is extended by every token: candidates, of which the best 4 survive. The cost grows linearly in ; exact search would grow exponentially in the length.
A fixed-vector encoder–decoder translates short sentences well and long ones badly. Which change attacks the cause most directly?
- Let the decoder attend over all encoder states at every step
- Use a larger beam at test time
- Enlarge the output vocabulary
- Reverse the target sentence
Show the answer
A. Let the decoder attend over all encoder states at every step
The cause is that the whole source must pass through one fixed-size vector, and the gradient to early words through a long chain of Jacobians. Attention gives every output step direct access to every annotation.
Which score function requires the decoder state and the encoder annotations to have the same dimension?
- Additive:
- General:
- Dot:
- Scaled dot product on learned projections:
Show the answer
C. Dot:
An inner product needs two vectors of the same size. The other forms map both sides into a shared space first, through and , through , or through and , so the sizes can differ.
Go deeper
- Decoding: Beam Search & Its Pathologies · Search versus sampling, length bias and the beam search curse.
- Alignment-Free Training: CTC & Transducers · Summing over every alignment with dynamic programming.
- Pointer, Copy & Monotonic Attention · Attending to positions in order to copy, point and align online.
Further reading
- I. Sutskever, O. Vinyals & Q. V. Le, "Sequence to sequence learning with neural networks," NeurIPS (2014).
- D. Bahdanau, K. Cho & Y. Bengio, "Neural machine translation by jointly learning to align and translate," ICLR (2015).
- M.-T. Luong, H. Pham & C. D. Manning, "Effective approaches to attention-based neural machine translation," EMNLP (2015).
- D. Jurafsky & J. H. Martin, Speech and Language Processing (3rd ed. draft), chapter on machine translation and encoder–decoder models, free at web.stanford.edu/~jurafsky/slp3.