Repository navigation
Module 13
⬅️ Module 12 · 🗺️ Curriculum · 🏠 Home · Module 14 ➡️
Level: Intermediate · Prerequisites: Module 12, Module 03 · Time: about 6–7 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
Many tasks map one sequence to another of different length: translation, summarisation, speech recognition, captioning. The encoder–decoder (seq2seq) architecture does this, and attention — letting the decoder look back at all encoder states — removed its main bottleneck and became the seed of the Transformer.
After this module you should be able to:
- describe the encoder–decoder pipeline and the fixed-context bottleneck;
- explain teacher forcing, greedy decoding and beam search;
- derive attention scores, alignment weights and context vectors (additive and dot-product);
- apply attention to image captioning.
An encoder reads the source sentence and compresses it into a vector; a decoder generates the target one token at a time. Squeezing a whole sentence into one vector is hard for long inputs. Attention lets the decoder, at each output step, re-read the source and focus on the most relevant words — like glancing back at the source while translating.
flowchart LR
subgraph Encoder
E1["h1"] --- E2["h2"] --- E3["h3"] --- E4["h4"]
end
subgraph Decoder
S1["s1"] --> S2["s2"] --> S3["s3"]
end
E1 -. "alpha" .-> C["Context c_t = sum alpha_j h_j"]
E2 -. "alpha" .-> C
E3 -. "alpha" .-> C
E4 -. "alpha" .-> C
S2 -- "query" --> C
C --> S3
S3 --> Y["Predict y_3"]
Figure 13.1 — At each decoder step the previous state (query) scores all encoder states; the softmax-weighted sum is the context vector. Original diagram.
Sutskever et al. (2014): an LSTM encoder produces $\mathbf{c}=\mathbf{h}T$; a decoder models $P(y_1,\dots,y{T'}\mid\mathbf{x})=\prod_tP(y_t\mid y_{<t},\mathbf{c})$. All source information must pass through a single fixed-size vector, so quality degrades with length (Cho et al. 2014).
Pipeline: tokenise → embed → encode → (attend) → decode → detokenise. Special tokens <bos>, <eos> mark start and end; padding + masks handle batches. Evaluation: BLEU (n-gram overlap) and, increasingly, learned metrics and human judgement.
Training maximises
Greedy picks
With decoder query
The weights
Additive (Bahdanau et al. 2015):
Show, Attend and Tell (Xu et al. 2015): a CNN encodes an image into
Attention numerically. Scores
Beam search (
import numpy as np
def softmax(z): z = z - z.max(); e = np.exp(z); return e / e.sum()
def context(scores, H): # H: (T, d) encoder states
alpha = softmax(scores); return alpha @ H, alpha
def dot_attention(query, H): # scores_j = query . h_j
return context(H @ query, H)
H = np.array([[1., 0.], [0., 1.], [1., 1.]])
c, a = context(np.array([2., 1., 0.]), H)
print(a.round(3), c.round(3)) # [0.665 0.245 0.09 ] [0.755 0.335]# Beam search skeleton
def beam_search(step_fn, bos, eos, B=4, maxlen=50):
beams = [([bos], 0.0)]
for _ in range(maxlen):
cand = []
for seq, lp in beams:
if seq[-1] == eos: cand.append((seq, lp)); continue
for tok, p in step_fn(seq): # list of (token, log-prob)
cand.append((seq + [tok], lp + p))
beams = sorted(cand, key=lambda x: x[1], reverse=True)[:B]
return beams[0][0]- Self-attention removes recurrence (Module 14); multi-head attention learns several alignments.
- Local/monotonic attention for speech; coverage to avoid repeating or skipping source words; pointer networks and copy mechanisms.
- Minimum-risk / sequence-level training, scheduled sampling, label smoothing for NMT.
- Neural machine translation at scale: subword vocabularies (BPE), back-translation, multilingual models (Google NMT; Wu et al. 2016).
- Interpretability caveat: attention weights are not guaranteed explanations of model decisions (Jain & Wallace 2019).
- Not masking padding positions in attention (the softmax assigns weight to pad).
- Comparing BLEU across different tokenisations.
- Using very large beams (can reduce quality or produce short/generic outputs).
- Exposure bias: evaluate with free-running decoding, not teacher-forced loss alone.
Q1. What is the bottleneck problem and how does attention solve it?
A single fixed-size vector must summarise the entire source. Attention gives the decoder direct, weighted access to all encoder states at every step.
Q2. Why is softmax used for alignment weights?
It produces non-negative weights summing to 1, a differentiable "soft selection" so a weighted average of states can be backpropagated through.
Q3. Additive vs dot-product attention?
Additive uses a learned MLP (more flexible for mismatched dimensions); dot-product is a single matmul (faster) and, with
Q4. How does beam search differ from greedy decoding?
It maintains several candidate prefixes and chooses the best overall sequence score, reducing early-commitment errors at higher cost.
Q5. What is exposure bias?
Training conditions on gold history, but inference conditions on the model's own outputs; errors compound because the model never saw such inputs.
Q6. Soft vs hard attention in image captioning?
Soft attention is a differentiable weighted average; hard attention samples a region and needs gradient estimators with higher variance.
Q7. Why length-normalise beam scores?
Cumulative log-probability decreases with length, so unnormalised beams favour overly short outputs.
Q8. Are attention weights explanations?
Not necessarily: they show where information is read, but other pathways and downstream layers also determine predictions.
- Sutskever, I., Vinyals, O., & Le, Q. V. (2014). Sequence to sequence learning with neural networks. NeurIPS. arXiv:1409.3215.
- Bahdanau, D., Cho, K., & Bengio, Y. (2015). Neural machine translation by jointly learning to align and translate. ICLR. arXiv:1409.0473.
- Luong, M.-T., Pham, H., & Manning, C. D. (2015). Effective approaches to attention-based neural machine translation. EMNLP. arXiv:1508.04025.
- Xu, K., et al. (2015). Show, attend and tell: neural image caption generation with visual attention. ICML. arXiv:1502.03044.
- Wu, Y., et al. (2016). Google's neural machine translation system. arXiv:1609.08144.
- Papineni, K., et al. (2002). BLEU: a method for automatic evaluation of machine translation. ACL.
- Jain, S., & Wallace, B. C. (2019). Attention is not explanation. NAACL.
⬅️ Module 12 · 🗺️ Curriculum · 🏠 Home · Module 14 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24