Contents

Foundation Model Engineering

Manuscript updated (UTC) · Chapter source on GitHub · Cite this chapter (RIS)

On this page

2.3 The Dawn of Attention

Translate red fox into French and the word order flips. In renard roux, the noun comes first. How could a decoder use the source position for fox at one step and the position for red at the next? In recurrent encoder–decoder attention, the source states stay available and the decoder changes how it mixes them at each step.

What has to fit in the final state?

In an early sequence-to-sequence LSTM, the encoder reads the source and passes its final recurrent state to the decoder [2]. The state has the same dimensions whether the source is two words or fifty. If the decoder needs the opening adjective again at the end of a sentence, the information must survive the intervening updates.

Sutskever, Vinyals and Le kept the target in its original order but reversed the source in one experiment. With source A B C and target a b c, reading C B A puts A right before the decoder starts predicting a. The authors proposed that shorter distances for some source–target pairs made optimization easier [2]. Reversal still gives the decoder one final encoder state.

How the decoder reads from several positions

Bahdanau, Cho and Bengio’s translation model kept an annotation hjh_j for each source position jj, combining the forward and backward encoder states [1]. When preparing target step tt, it compared the previous decoder state st−1s_{t-1} with each annotation. Its additive alignment model can be written as

etj=v⊤tanh⁡(Wst−1+Uhj).e_{tj}=v^\top\tanh(Ws_{t-1}+Uh_j).

WW and UU project the decoder and encoder states into the same space. The vector vv turns the resulting features into a scalar score. The model learns these parameters through the translation objective. For SS source positions, the normalized weights αtj\alpha_{tj} determine the context vector ctc_t.

αtj=exp⁡(etj)∑k=1Sexp⁡(etk),ct=∑j=1Sαtjhj.\alpha_{tj}=\frac{\exp(e_{tj})}{\sum_{k=1}^{S}\exp(e_{tk})}, \qquad c_t=\sum_{j=1}^{S}\alpha_{tj}h_j .
Bidirectional encoder states along the bottom feed a weighted sum. The decoder at the top receives that context at the current target step.
Read from the bottom up. Each source position contributes to the context vector in proportion to its alignment weight. Open the diagram to enlarge it. Figure by Lilian Weng.

Which word gets more weight?

Use two-dimensional source states hred=(1,0)h_{\mathrm{red}}=(1,0) and hfox=(0,1)h_{\mathrm{fox}}=(0,1). For the first target step, labelled renard, give the decoder a query (1,0)(1,0). Set W=U=IW=U=I and v=(1,1)v=(1,1). These are hand-chosen numbers so that you can check the readout. The target labels and queries are supplied as inputs to the exercise.

For red the additive score is tanh⁡(2)+tanh⁡(0)≈0.9640\tanh(2)+\tanh(0)\approx0.9640. For fox it is 2tanh⁡(1)≈1.52322\tanh(1)\approx1.5232. After softmax the weights are 0.3637 and 0.6363. Since the two source states are coordinate vectors, their weighted sum is (0.3637,0.6363)(0.3637,0.6363). Predict what happens when the query changes to (0,1)(0,1) for roux, then select the second step.

Translation step
Alignment score

Query at this step [1, 0]

SourceStateScoreWeight
red[1, 0]0.96400.3637
fox[0, 1]1.52320.6363

Context vector [0.3637, 0.6363]

Switch back to renard and select Dot product. The scores are now 1 and 0, and red receives 0.7311 of the weight. Both calculations use the same states. The scoring rule alone changes the ordering. Luong, Pham and Manning studied dot-product and learned alternatives in a decoder with its own update order [3]. The switch here isolates the score calculation.

Reproduce the two readouts in PyTorch

This CPU example starts after the encoder and decoder have produced their states. It computes one soft alignment and its context, with two real source tokens and no padding. Training a translator also requires embeddings, recurrent updates, an output distribution and target sequences.

import torch

# Rows are the source states for "red" and "fox".
h = torch.eye(2, dtype=torch.float64)
query = torch.tensor([1.0, 0.0], dtype=h.dtype)
additive = torch.tanh(h + query).sum(dim=-1)
dot = h @ query

for scores in (additive, dot):
    weights = scores.softmax(dim=0)
    context = weights @ h
    print(weights.tolist(), context.tolist())

expected = torch.tensor([0.36374167, 0.63625833], dtype=h.dtype)
torch.testing.assert_close(additive.softmax(0) @ h, expected)
torch.testing.assert_close(torch.tanh(h + query.flip(0)).sum(-1).softmax(0) @ h,
                           expected.flip(0))

With TT target steps, reading every source state requires STS T scores. A decoder can reuse the source annotations and their projections and compute one row at a time. The decoder still advances through its recurrent states sequentially. Self-attention in §3.1 uses the same weighted-sum idea with queries and keys from one sequence.

An alignment row tells you how states were mixed at this read. A bidirectional annotation at fox already carries some information from red. The decoder also has its own history, so a large weight alone cannot establish which word caused the final translation.

Quizzes

Quiz 1: What does source reversal change for A → a, and what stays the same? Putting A at the end of the source shortens its path to the first decoder step. The decoder still receives a fixed-size final encoder state.

Quiz 2: With the lesson’s additive score, what happens when the two query coordinates are swapped? The scores for red and fox swap. Their weights become approximately 0.6363 and 0.3637. The context coordinates swap as well because the source states are coordinate vectors.

Quiz 3: If both source states were identical, could changing the attention weights change the context? No. Any normalized weighted sum of two identical vectors gives that same vector. The decoder state could still change the output distribution.

Quiz 4: For 30 source positions and 20 generated positions, how many scores does global attention compute? It computes 600 scores. A decoder that consumes each row immediately needs only 30 current scores in addition to its reusable source states and other working memory.

References

  1. Bahdanau, D., Cho, K., & Bengio, Y. Neural Machine Translation by Jointly Learning to Align and Translate. 2014 preprint, ICLR 2015. Paper.
  2. Sutskever, I., Vinyals, O., & Le, Q. V. Sequence to Sequence Learning with Neural Networks. NeurIPS 2014. Paper.
  3. Luong, M.-T., Pham, H., & Manning, C. D. Effective Approaches to Attention-based Neural Machine Translation. EMNLP 2015. Paper.