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

Luong attention

Luong, Pham and Manning (EMNLP 2015) simplified and systematised attention for translation. They scored the current decoder state against encoder states with dot (s·h), general (s W h) or concat (additive) functions; compared global attention over all words with local attention over a predicted window; and fed the attentional vector back as input. Their multiplicative scores are cheap matrix products and lead directly to the Transformer's scaled dot product. This page covers the three scores, global and local attention, input feeding and costs. In the exercises you implement the scores and local windows, then compare score functions on a retrieval task. Dot fails when queries and keys live in different spaces (0.038), general learns the mapping (1.000), and bias-free additive attention is stuck at chance (0.104): you prove it has no component odd in both query and key, and adding a bias inside the tanh fixes it (1.000).

Level 0: Foundation

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

Simpler ways to decide where to look

Attention needs a score saying how relevant each input word is to the word being written. Bahdanau used a small neural network for that score. Luong and colleagues tried simpler scores:

  • a plain dot product (how aligned two vectors are);
  • a dot product after a learned transformation.

They also tried looking only at a small window of words. The simpler scores worked as well and ran faster, an idea the Transformer later built on. The demo shows attention weights becoming sharper or softer.

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

Multiplicative attention is a matrix product, which maps well onto GPUs and accelerators. That efficiency is why it, not additive attention, powers today’s models.

📝 Quick check (Level 0)
0/3 answered
  1. 1. Dot-product attention scores by…
  2. 2. Local attention looks at…
  3. 3. Multiplicative scores are fast because they are…

Level 1: Beginner

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

By hand

  • Scores for the current decoder state sₜ:
    • dot: sₜ · hⱼ;
    • general: sₜ W hⱼ;
    • concat: vᵀ tanh(W [sₜ; hⱼ]), which is additive attention.
    • Luong uses the current state sₜ; Bahdanau used the previous state sₜ₋₁.
  • Parameters for 512-dimensional states:
    • dot: 0 (it needs equal sizes);
    • general: 512² = 262,144;
    • concat with a = 512: 524,800.
  • Attentional vector:
    • h̃ₜ = tanh(W_c [cₜ; sₜ]) feeds the output softmax;
    • with input feeding, h̃ₜ is also fed into the next decoder step, so the model remembers past alignment decisions.
  • Global and local attention:
    • global attends to all S positions;
    • local-m assumes monotone alignment, pₜ = t, and attends to the window [pₜ − D, pₜ + D];
    • local-p predicts pₜ = S·σ(v_p · tanh(W_p sₜ)) (with S = 40 and z = 0, pₜ = 20) and multiplies the weights by a Gaussian exp(−(j − pₜ)²/(2σ²)) with σ = D/2;
    • for D = 10 the window has 21 positions.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Parameters of the general score for 512-dimensional states:
  2. 2. Window size for D = 10:
  3. 3. Luong scores the decoder's…

Level 2: Intermediate

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

Luong attention in code

Exercise 1.

  • Dot and general scores agreed when W = I.
  • Local windows were clipped at the sequence ends, and Gaussian reweighting with D = 2 (σ = 1) gave e⁻² at distance 2 from pₜ.

Practice.

  • Batch the scores as matrix products: for general, scores = (S @ W) @ H.transpose(1, 2) gives a T × S matrix in one call during training.
  • Scale dot products by 1/√d for large dimensions (Transformers, E12-2), or the softmax saturates.
  • Input feeding improves alignment, but it makes decoding strictly sequential even in training.
  • Luong et al.’s ensemble set a new state of the art on WMT’15 English→German (25.9 BLEU). Attention gave about 5 BLEU over a non-attention baseline.
scores = torch.bmm(dec_states @ W, enc_out.transpose(1, 2))   # (B, T, S), general score
scores = scores.masked_fill(src_pad[:, None, :], float("-inf"))
ctx = torch.bmm(scores.softmax(-1), enc_out)                   # (B, T, h)
h_tilde = torch.tanh(Wc(torch.cat([ctx, dec_states], -1)))
🐍 Exercise 1: Luong scores and local attention
Implement dot and general scores, local windows, Gaussian reweighting and the attentional vector.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Large-dimensional dot products should be…
  2. 2. Input feeding passes h̃ to…
  3. 3. Luong et al.'s ensemble on WMT'15 En→De:

Level 3: Advanced

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

Theory

Dot versus general.

  • Dot assumes queries and keys live in the same space and need no transformation.
  • General learns a bilinear form sᵀWh, so it can match vectors related by any linear map.
  • In an end-to-end model the encoder and decoder can learn compatible spaces, so dot often suffices. With fixed or mismatched representations, general is needed.

A parity limit of bias-free additive attention.

  • Write f(q, h) = vᵀ tanh(Wq + Uh). Since tanh is odd, the coefficient of each odd power of Uh in its Taylor expansion is an even function of Wq, and vice versa.
  • So f splits into a part odd in q and even in h plus a part even in q and odd in h. The part odd in both q and h is exactly zero, and a similarity such as q·Mh is entirely odd in both.
  • A bias inside the tanh breaks the symmetry. In full encoder–decoders, bias terms in the RNN states usually supply it implicitly, which is why E11-9’s bias-free attention still trained.

Local attention reduces cost from O(S) to O(D) per step and encodes a monotonicity prior. Predicting pₜ makes it differentiable, apart from the hard window edges.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Dot attention assumes queries and keys…
  2. 2. Bias-free additive scores have no component…
  3. 3. Local attention's cost per step:

Level 4: Expert

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

Which score can retrieve?

History.

  • M.-T. Luong, H. Pham and C. Manning, “Effective approaches to attention-based neural machine translation” (EMNLP 2015), introduced global and local attention, the dot, general and concat scores, and input feeding.
  • A. Vaswani et al. (2017) scaled the dot product by 1/√d and made it the core of the Transformer.

Exercise 2.

  • Task: encoder states are 10 random unit vectors in 16 dimensions. The query is one of them, rotated by a fixed orthogonal matrix M and slightly noised. The target is the position of the matching state, so the score must rank the true key first.
  • Training: each score is trained with cross-entropy for 400 Adam steps (analytic gradients, checked numerically).
score retrieval accuracy (chance 0.1)
dot (learned temperature) 0.038
general sᵀWh 1.000
concat, no bias 0.104
concat with a bias inside tanh 1.000

The odd-in-both part of the bias-free additive score, measured numerically: 0.0 (exactly zero).

  • Dot fails when spaces differ. The query is a rotated key, so s·h does not peak at the match. It scores below chance, because rotation can make the true key anti-aligned.
  • General solves it by learning W ≈ Mᵀ.
  • Bias-free additive attention cannot learn this at all, not with 256 hidden units, not after 3000 steps (64 units), not even with an unrotated query: all stayed at chance, with the loss fixed at ln 10. The parity argument explains why: retrieval needs exactly the odd-odd component it lacks.
  • Adding a bias inside the tanh makes additive attention solve the task.
🐍 Exercise 2 (research): which score can retrieve?
Train dot, general and additive scores (with and without an inner bias) to retrieve a transformed key, and verify the parity limit.

Luong attention in AI, robotics and aerospace

  • Efficient decoders: multiplicative attention keeps on-board sequence models fast on accelerators.
  • Retrieval: matching a query against stored memories (map features, past observations) is the same score-and-softmax pattern; general or scaled-dot scores are the default.
  • Implementation detail matters: omitting a bias in an additive scorer can silently prevent learning similarity, as exercise 2 showed.

References

  1. M.-T. Luong, H. Pham, C. D. Manning (2015). “Effective approaches to attention-based neural machine translation.” Proc. EMNLP.
  2. D. Bahdanau, K. Cho, Y. Bengio (2015). “Neural machine translation by jointly learning to align and translate.” Proc. ICLR.
  3. A. Vaswani et al. (2017). “Attention is all you need.” Proc. NeurIPS.