Simple Algorithm
Deep Learning · Representation · 22 min

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 p(y∣x)=∏tp(yt∣y<t,x)p(\mathbf y\mid\mathbf x)=\prod_tp(y_t\mid y_{<t},\mathbf x) 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 ⟨eos⟩\langle\text{eos}\rangle, 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.

Check your understanding

Why must every training target end with the token ⟨eos⟩\langle\text{eos}\rangle?

  1. It tells the encoder where the source sentence ends
  2. It resets the decoder's hidden state between sentences
  3. It lets the model put probability on outputs of every length, since stopping becomes one more prediction
  4. 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, ∏tp(yt∣y<t,x)\prod_tp(y_t\mid y_{<t},\mathbf x) 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 D={(x(i),y(i))}i=1n\data=\{(\mathbf x^{(i)},\mathbf y^{(i)})\}_{i=1}^n (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 tt the decoder is fed the true previous token yt−1y_{t-1}, 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.

DerivationThe loss, and where its gradient has to travel
  1. L(θ)=−1n∑i=1n∑t=1Ty(i)log⁡pθ(yt(i)∣y<t(i),x(i))\loss(\boldsymbol\theta)=-\frac1n\sum_{i=1}^n\sum_{t=1}^{T_y^{(i)}}\log p_{\boldsymbol\theta}\big(y^{(i)}_t\mid y^{(i)}_{<t},\mathbf x^{(i)}\big)

    Take logs of the factorization and average over the corpus:

  2. ∂(−log⁡pt,yt)∂zt=pt−eyt\frac{\partial\big(-\log p_{t,y_t}\big)}{\partial\mathbf z_t}=\mathbf p_t-\mathbf e_{y_t}

    With logits zt=Wost+bo\mathbf z_t=W_o\mathbf s_t+\mathbf b_o and pt=softmax⁡(zt)\mathbf p_t=\softmax(\mathbf z_t), the gradient of one term is the familiar "prediction minus one-hot target":

  3. ∂ℓt∂hj=∂ℓt∂hTx JTxJTx−1⋯Jj+1\frac{\partial\ell_t}{\partial\mathbf h_j}=\frac{\partial\ell_t}{\partial\mathbf h_{T_x}}\,J_{T_x}J_{T_x-1}\cdots J_{j+1}

    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 c=hTx\mathbf c=\mathbf h_{T_x}, so the gradient for an early state hj\mathbf h_j is multiplied by every encoder Jacobian Jk=∂hk/∂hk−1J_k=\partial\mathbf h_k/\partial\mathbf h_{k-1} between jj and TxT_x:

  4. ∥∂ℓt∂hj∥≤γ Tx−j ∥∂ℓt∂hTx∥\Big\lVert\frac{\partial\ell_t}{\partial\mathbf h_j}\Big\rVert\le\gamma^{\,T_x-j}\,\Big\lVert\frac{\partial\ell_t}{\partial\mathbf h_{T_x}}\Big\rVert

    If every Jacobian has norm at most γ<1\gamma<1, the signal that ties output tt to source word jj 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.

Predict before you look

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 h\mathbf h and a cell state c\mathbf c, each with 1,000 entries, so 4×2×1,000=8,0004\times2\times1{,}000=8{,}000 numbers, the figure the paper itself gives. A 50-word sentence with 1,000-dimensional embeddings enters as 50,00050{,}000 numbers; a 100-word one as 100,000100{,}000, and still leaves through the same 8,0008{,}000.

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 hj=[h→j;h←j]\mathbf h_j=[\overrightarrow{\mathbf h}_j;\overleftarrow{\mathbf h}_j] summarizes the whole sentence with a focus on the words around xjx_j. Before emitting yty_t, the decoder scores every annotation against its previous state, turns the scores into weights with a softmax, and reads the weighted average:

etj=va⊤tanh⁡(Wast−1+Uahj),αtj=exp⁡(etj)∑k=1Txexp⁡(etk),ct=∑j=1Txαtj hje_{tj}=\mathbf v_a^\top\tanh\big(W_a\mathbf s_{t-1}+U_a\mathbf h_j\big),\qquad\alpha_{tj}=\frac{\exp(e_{tj})}{\sum_{k=1}^{T_x}\exp(e_{tk})},\qquad\mathbf c_t=\sum_{j=1}^{T_x}\alpha_{tj}\,\mathbf h_j
This is additive attention: the score is a small network with one hidden layer of size n′n'. The context then enters the decoder update, st=fdec(st−1,e(yt−1),ct)\mathbf s_t=f_{\text{dec}}(\mathbf s_{t-1},\mathbf e(y_{t-1}),\mathbf c_t), and the output layer. Every piece is differentiable, so the model is trained end to end by the same maximum-likelihood loss.

Bahdanau et al. read αtj\alpha_{tj} as the probability that target word yty_t is aligned to, or translated from, source word xjx_j. Then ct=Ej∼αt[hj]\mathbf c_t=\E_{j\sim\boldsymbol\alpha_t}[\mathbf h_j] 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.

DerivationWhat attention buys, and what it costs
  1. ∂ct∂hj=αtj I+∑k=1Txhk ∂αtk∂hj\frac{\partial\mathbf c_t}{\partial\mathbf h_j}=\alpha_{tj}\,I+\sum_{k=1}^{T_x}\mathbf h_k\,\frac{\partial\alpha_{tk}}{\partial\mathbf h_j}

    Differentiate the context with respect to one annotation. Besides the terms that pass through the weights, there is a direct one:

  2. ∂ℓt∂hj=αtj ∂ℓt∂ct+(terms through αt and through later encoder states)\frac{\partial\ell_t}{\partial\mathbf h_j}=\alpha_{tj}\,\frac{\partial\ell_t}{\partial\mathbf c_t}+\big(\text{terms through }\boldsymbol\alpha_t\text{ and through later encoder states}\big)

    So the loss at output tt reaches hj\mathbf h_j in one hop, scaled by αtj\alpha_{tj}, instead of through Tx−jT_x-j encoder Jacobians. Every source position is a constant number of steps from every output, whatever the sentence length:

  3. Tx n′dh⏟Uahj, once+Ty n′ds⏟Wast−1+O(TxTy n′)⏟the scores\underbrace{T_x\,n'd_h}_{U_a\mathbf h_j,\ \text{once}}+\underbrace{T_y\,n'd_s}_{W_a\mathbf s_{t-1}}+\underbrace{\order{T_xT_y\,n'}}_{\text{the scores}}

    The price is one score per (output, source) pair. UahjU_a\mathbf h_j does not depend on tt, so it is computed once per sentence; each output step then needs Wast−1W_a\mathbf s_{t-1} and TxT_x scores of size n′n'. With annotation size dhd_h and decoder size dsd_s, the multiply–adds per sentence pair are about

  4. n′ds⏟Wa+n′dh⏟Ua+n′⏟va=1,000×(1,000+2,000+1)=3,001,000\underbrace{n'd_s}_{W_a}+\underbrace{n'd_h}_{U_a}+\underbrace{n'}_{\mathbf v_a}=1{,}000\times(1{,}000+2{,}000+1)=3{,}001{,}000

    Bahdanau et al. used n′=1,000n'=1{,}000, a decoder of size ds=1,000d_s=1{,}000 and annotations of size dh=2,000d_h=2{,}000 (two directions of 1,000 units), so the scoring network alone has about three million weights, evaluated Tx×TyT_x\times T_y times per sentence pair:

Score functions, in code

Luong, Pham and Manning (2015) simplified the recipe. Their decoder first updates its state to st\mathbf s_t, scores the encoder states against st\mathbf s_t rather than st−1\mathbf s_{t-1}, and combines context and state into s~t=tanh⁡(Wc[ct;st])\tilde{\mathbf s}_t=\tanh(W_c[\mathbf c_t;\mathbf s_t]), 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 score⁡(s,h)\operatorname{score}(\mathbf s,\mathbf h)FormWeightsUsed in
Additive (concat)va⊤tanh⁡(Was+Uah)\mathbf v_a^\top\tanh(W_a\mathbf s+U_a\mathbf h)n′(ds+dh+1)n'(d_s+d_h+1)Bahdanau et al. (2015)
Dots⊤h\mathbf s^\top\mathbf hnone; needs ds=dhd_s=d_hLuong et al. (2015)
General (bilinear)s⊤Wah\mathbf s^\top W_a\mathbf hdsdhd_sd_hLuong et al. (2015)
Scaled dot productq⊤k/dk\mathbf q^\top\mathbf k/\sqrt{d_k} with q=WQ⊤s\mathbf q=W_Q^\top\mathbf s, k=WK⊤h\mathbf k=W_K^\top\mathbf h, and separate values WV⊤hW_V^\top\mathbf hthree projectionstransformers (Vaswani et al., 2017)
A bilinear score is a dot product after a linear map, and dot-product scores for all pairs are one matrix product, which suits GPUs. Luong et al. also tried local attention over a window around a predicted source position, a forerunner of Pointer, Copy & Monotonic Attention.
python
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 ⟨eos⟩\langle\text{eos}\rangle. Real code also gives padded source positions a score of −∞-\infty 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 TxT_x 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 p(y∣x)p(\mathbf y\mid\mathbf x), but translation needs one output, ideally the mode arg max⁡yp(y∣x)\argmax_{\mathbf y}p(\mathbf y\mid\mathbf x). The decoder state depends on the entire prefix, so there is no dynamic program over ∣V∣T|\mathcal V|^{T} candidate sequences. Greedy decoding takes the most probable token at every step. Beam search keeps the kk best prefixes instead:

text
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 kk of k∣V∣k|\mathcal V| candidates. Greedy decoding is k=1k=1. The stopping rule is exact for plain log-probabilities (lp=1\mathrm{lp}=1), 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 lp(y)=((5+∣y∣)/6)α\mathrm{lp}(\mathbf y)=\big((5+|\mathbf y|)/6\big)^\alpha (Wu et al., 2016).

Check your understanding

You decode one source sentence greedily and with beam search (k=5k=5). Which statement is guaranteed?

  1. Beam search returns the most probable translation
  2. Beam search's output is at least as probable as greedy's
  3. Neither output is guaranteed to be the most probable translation
  4. 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 n=1,…,4n=1,\dots,4, the modified nn-gram precision pnp_n: the fraction of the output's nn-grams that occur in a reference, with each nn-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 cc and reference length rr:

BLEU=min⁡(1, e 1−r/c)⋅exp⁡(14∑n=14log⁡pn).\mathrm{BLEU}=\min\big(1,\,e^{\,1-r/c}\big)\cdot\exp\Big(\tfrac14\sum_{n=1}^4\log p_n\Big).

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, p(y∣x)=∏tp(yt∣y<t,x)p(\mathbf y\mid\mathbf x)=\prod_tp(y_t\mid y_{<t},\mathbf x); 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 Tx−jT_x-j encoder Jacobians.
  • Attention recomputes ct=∑jαtjhj\mathbf c_t=\sum_j\alpha_{tj}\mathbf h_j at every step from softmax-normalized scores (additive v⊤tanh⁡(Ws+Uh)\mathbf v^\top\tanh(W\mathbf s+U\mathbf h) or multiplicative s⊤Wh\mathbf s^\top W\mathbf h): a soft alignment learned without labels, costing Tx×TyT_x\times T_y scores.
  • Decoding approximates the mode with greedy search or beam search (k∣V∣k|\mathcal V| candidates per step), usually with length normalization; BLEU scores outputs by clipped nn-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.

Question 1

In Bahdanau et al.'s attention model, which quantity is recomputed at every output step tt?

  1. The encoder annotations h1,…,hTx\mathbf h_1,\dots,\mathbf h_{T_x}
  2. The weights αt1,…,αtTx\alpha_{t1},\dots,\alpha_{tT_x} and the context ct\mathbf c_t
  3. The projected annotations UahjU_a\mathbf h_j
  4. The source embeddings e(xj)\mathbf e(x_j)
Show the answer

B. The weights αt1,…,αtTx\alpha_{t1},\dots,\alpha_{tT_x} and the context ct\mathbf c_t

The scores etje_{tj} depend on the decoder state st−1\mathbf s_{t-1}, so the weights and the context change with every output token. Everything on the source side is computed once per sentence.

Question 2

During teacher-forced training, what is the decoder's input at step tt?

  1. Its own prediction from step t−1t-1
  2. The gold token yty_t that it must predict
  3. The encoder annotation ht\mathbf h_t at the same position
  4. The gold previous token yt−1y_{t-1}
Show the answer

D. The gold previous token yt−1y_{t-1}

Teacher forcing conditions every prediction on the true prefix y<ty_{<t}, so each step's loss is a plain cross-entropy against yty_t. At test time the model must condition on its own outputs instead, which is the source of exposure bias.

Question 3

Beam search with width k=4k=4 runs over a vocabulary of 32,00032{,}000 tokens. How many candidate extensions does it score at each step, once the beam is full?

  1. 44
  2. 32,00032{,}000
  3. 128,000128{,}000
  4. 32,000432{,}000^4
Show the answer

C. 128,000128{,}000

Each of the k=4k=4 live prefixes is extended by every token: 4×32,000=128,0004\times32{,}000=128{,}000 candidates, of which the best 4 survive. The cost grows linearly in kk; exact search would grow exponentially in the length.

Question 4

A fixed-vector encoder–decoder translates short sentences well and long ones badly. Which change attacks the cause most directly?

  1. Let the decoder attend over all encoder states at every step
  2. Use a larger beam at test time
  3. Enlarge the output vocabulary
  4. 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.

Question 5

Which score function requires the decoder state and the encoder annotations to have the same dimension?

  1. Additive: va⊤tanh⁡(Was+Uah)\mathbf v_a^\top\tanh(W_a\mathbf s+U_a\mathbf h)
  2. General: s⊤Wah\mathbf s^\top W_a\mathbf h
  3. Dot: s⊤h\mathbf s^\top\mathbf h
  4. Scaled dot product on learned projections: (WQ⊤s)⊤(WK⊤h)/dk(W_Q^\top\mathbf s)^\top(W_K^\top\mathbf h)/\sqrt{d_k}
Show the answer

C. Dot: s⊤h\mathbf s^\top\mathbf h

An inner product needs two vectors of the same size. The other forms map both sides into a shared space first, through WaW_a and UaU_a, through WaW_a, or through WQW_Q and WKW_K, so the sizes can differ.

Go deeper

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.