Foundations to Frontier
Tests
E. Deep Learning › E11 Recurrent and Sequence Models

Bahdanau attention

Bahdanau attention (Bahdanau, Cho and Bengio, 2015) removes the fixed-vector bottleneck of sequence-to-sequence models. At each output step, the decoder scores every encoder state with a small network, e_j = v · tanh(W s + U h_j), turns the scores into weights with a softmax, and reads their weighted average as a context vector. The model learns where to look (a soft alignment), translation quality stopped collapsing on long sentences, and the idea led directly to the Transformer. This page covers additive attention, the context vector, alignments and cost. In the exercises you implement additive attention, then add it to E11-8's encoder–decoder: copying 12 tokens goes from 0.229 accuracy without attention to 1.000 with it, and the learned alignment is exactly diagonal.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Looking back while writing

A plain encoder–decoder must cram a whole sentence into one summary before writing a word. With attention, the decoder can look back at every input word whenever it writes. Before each output word it decides how much to look at each input word, takes a weighted mix of them and uses that mix to write. When translating, it learns to look at the matching source words. The demo shows such attention weights: each row is one output step.

Sequence-model lab
encoder positions →, decoder steps ↓
Each row is one decoder step's attention weights (summing to 1). At sharpness 0 attention is uniform; high sharpness approaches a hard, monotonic alignment.
Why engineers care

Attention made long-sequence translation and speech recognition work. Its weights also show which inputs a decision used, a useful diagnostic in safety-critical systems.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Attention lets the decoder…
  2. 2. Attention weights at one step…
  3. 3. Attention removed…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Scores: for decoder state sᵢ₋₁ and encoder states h₁ … h_S, eᵢⱼ = vᵀ tanh(W sᵢ₋₁ + U hⱼ). This is “additive” attention: a one-hidden-layer network.
  • Weights: αᵢⱼ = softmax over j of eᵢⱼ. Scores (0, 0) give weights (0.5, 0.5), and scores (1000, 0) give (1, 0).
  • Context: cᵢ = Σⱼ αᵢⱼ hⱼ, a weighted average of encoder states.
  • Decoder: sᵢ = f(sᵢ₋₁, yᵢ₋₁, cᵢ). The output distribution uses sᵢ (and, in the paper, cᵢ and yᵢ₋₁).
  • Encoder: Bahdanau et al. used a bidirectional RNN, so each hⱼ summarises the whole sentence with focus around word j.
  • Parameters:
    • W (decoder size × a), U (encoder size × a) and v (a);
    • with a 1000-unit decoder, a 2000-dimensional bidirectional encoder and a = 1000, that is 3,001,000.
  • Cost: U hⱼ can be computed once per sentence (S·h·a). Scoring then costs T·S·a multiply–adds for T outputs, which is quadratic in length.
  • Sharpness: the entropy of α is 0 for a hard, one-position focus and log S for uniform attention (log 4 = 1.386 for 4 positions).
📝 Quick check (Level 1)
0/3 answered
  1. 1. Weights for scores (0, 0):
  2. 2. The context vector is…
  3. 3. Entropy of uniform attention over 4 positions:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Attention in code

Exercise 1.

  • The weights were positive and summed to 1, and the context equalled their weighted average.
  • Reversing the encoder states reversed the weights and left the context unchanged: attention by itself ignores order. The encoder RNN supplies position information.

Practice.

  • Precompute U·hⱼ for all source positions once per batch.
  • Mask padded source positions with −∞ before the softmax.
  • Plot α as a source × target heat map to debug alignment. Monotone diagonals appear for similar word orders, and crossings for reordering.
  • PyTorch has no built-in additive attention layer. nn.MultiheadAttention implements scaled dot-product attention (E12-2), which is cheaper and now standard.
UH = enc_out @ U                                    # (B, S, a), once
for t in range(T):
    e = torch.tanh(s.unsqueeze(1) @ W + UH) @ v     # (B, S)
    e = e.masked_fill(src_pad, float("-inf")); a = e.softmax(-1)
    ctx = (a.unsqueeze(-1) * enc_out).sum(1)
    s = cell(torch.cat([emb(y_prev), ctx], -1), s)
🐍 Exercise 1: additive attention
Implement Bahdanau scores, a stable softmax and the context vector.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Padded source positions get score…
  2. 2. Bahdanau et al.'s encoder was…
  3. 3. Permuting encoder states…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why attention removes the bottleneck.

  • The decoder no longer depends on a single vector. At each step it gets cᵢ, a fresh summary focused on the relevant source states.
  • Gradient paths from an output to its source token become short: output → context → hⱼ, a couple of steps instead of a long recurrent path.
  • This is why length stopped hurting: Bahdanau et al.’s attention model kept its quality on sentences of 50+ words, where the plain encoder–decoder collapsed.

Soft alignment.

  • α is a differentiable, probabilistic alignment trained only from translation pairs, without alignment labels.
  • It recovers word alignments similar to statistical aligners, including non-monotone reordering (adjective–noun order in French).

Additive versus multiplicative.

  • Additive scoring uses a small MLP. Luong’s dot and general scores (E11-10) and the Transformer’s scaled dot product (E12-2) are cheaper and parallelise as matrix products.
  • Attention costs O(T·S) per sequence, which later motivated efficient attention (E12-15 onward).
📝 Quick check (Level 3)
0/3 answered
  1. 1. Attention shortens…
  2. 2. The alignment is learned…
  3. 3. Attention's cost per sequence:

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Does attention fix long sequences?

History.

  • A. Graves (2013) used a soft attention window to generate handwriting.
  • D. Bahdanau, K. Cho and Y. Bengio’s “Neural machine translation by jointly learning to align and translate” (ICLR 2015) introduced attention for translation. Its RNNsearch model was far more robust to sentence length than RNNencdec.
  • M.-T. Luong, H. Pham and C. Manning simplified the scores (2015, E11-10). Xu et al. applied attention to image captioning (2015). Vaswani et al. built the Transformer entirely from attention (2017).

Exercise 2.

  • Model: the encoder–decoder from E11-8 (tanh RNNs, 32 units, vocabulary 6), with and without additive attention (16 hidden units), feeding the context into the decoder.
  • Task: copy random sequences of length 8 and 12.
  • Training: 400 Adam steps, seed 0.
  • Measurement: greedy-decoding token accuracy, and how often attention peaks on the source token being copied.
length without attention with attention attention peaks on the copied token
8 0.750 0.930 0.538
12 0.229 1.000 1.000
  • Without attention, length 12 is almost hopeless (0.229, little above chance at 1/6): the single vector must carry 12 tokens through a long recurrent path.
  • With attention, length 12 is solved perfectly, and the attention has learned the exact diagonal alignment.
  • At length 8 attention helps but has not yet sharpened after 400 steps. It peaks on the right token only about half the time; the decoder also uses its own state.
  • Attention must still be discovered. In a separate run at length 16 with the same budget, neither model learned (about 0.20). The alignment had not formed (diagonal share 0.07), so longer training or a curriculum is needed.
🐍 Exercise 2 (research): does attention fix long sequences?
Add Bahdanau attention to an encoder–decoder and compare copy accuracy and learned alignment at lengths 8 and 12.

Attention in AI, robotics and aerospace

  • Speech: attention-based recognisers (Listen, Attend and Spell) align audio frames with characters.
  • Interpretability: attention maps over sensor channels or time steps help engineers see what a model attended to, though weights are not full explanations.
  • Trajectory forecasting: attention over past states and neighbouring agents is standard in prediction for drones and vehicles.

References

  1. D. Bahdanau, K. Cho, Y. Bengio (2015). “Neural machine translation by jointly learning to align and translate.” Proc. ICLR.
  2. A. Graves (2013). “Generating sequences with recurrent neural networks.” arXiv:1308.0850.
  3. K. Xu et al. (2015). “Show, attend and tell: neural image caption generation with visual attention.” Proc. ICML.