Skip to content

Module 13

Anurag Prasad edited this page Nov 8, 2026 · 9 revisions

Module 13 — Sequence-to-Sequence Learning and Attention Mechanisms

⬅️ 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


Overview and learning goals

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.

Beginner: the big picture

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"]
Loading

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.

Core concepts and derivations

Encoder–decoder and the fixed-context bottleneck

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).

Variable-length sequences and the translation pipeline

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.

Teacher forcing and inference decoding

Training maximises $\sum_t\ln P(y_t^\ast\mid y^\ast_{&lt;t},\mathbf{x})$ feeding gold tokens (teacher forcing). Inference must feed back generated tokens.

Greedy decoding and beam search

Greedy picks $\arg\max$ each step — fast but can commit to early mistakes. Beam search keeps the $B$ highest-scoring partial hypotheses by cumulative log-probability, expanding each by all next tokens and pruning to $B$; length normalisation $\frac1{\lvert y\rvert^\alpha}\sum_t\ln P$ avoids a bias toward short outputs. Beam search maximises probability, which can differ from quality for open-ended generation (sampling methods, Module 23).

Attention: scores, alignment weights and context vectors

With decoder query $\mathbf{s}_{t-1}$ and encoder states $\mathbf{h}_1..\mathbf{h}_T$:

$$ e_{tj}=a(\mathbf{s}_{t-1},\mathbf{h}_j),\qquad \alpha_{tj}=\frac{\exp e_{tj}}{\sum_k\exp e_{tk}},\qquad \mathbf{c}_t=\sum_{j=1}^T\alpha_{tj}\mathbf{h}_j . $$

The weights $\alpha_{t\cdot}$ form a probability distribution (the alignment); $\mathbf{c}t$ is fed to the decoder together with $\mathbf{s}{t-1}$ and $y_{t-1}$. The whole thing is differentiable, so alignment is learned from translation loss alone.

Additive and dot-product attention

Additive (Bahdanau et al. 2015): $a=\mathbf{v}^\top\tanh(W_s\mathbf{s}+W_h\mathbf{h})$ — a small MLP. Multiplicative (Luong et al. 2015): dot $\mathbf{s}^\top\mathbf{h}$ or general $\mathbf{s}^\top W\mathbf{h}$ — cheaper, matrix-multiply friendly; scaled by $1/\sqrt d$ in Transformers (Module 14).

RNN attention and image captioning

Show, Attend and Tell (Xu et al. 2015): a CNN encodes an image into $L$ spatial feature vectors $\mathbf{a}_1..\mathbf{a}_L$; an LSTM decoder attends over them while emitting each word, so the model "looks at" the relevant region for each word. Soft attention (weighted average, trained with backprop) versus hard attention (sample one location, trained with REINFORCE-style estimators). Alternatives: single global feature fed once, region proposals (object detectors), or Transformer decoders over patch tokens.

Worked example

Attention numerically. Scores $\mathbf{e}=(2,1,0)$ over encoder states $\mathbf{h}_1=(1,0)$, $\mathbf{h}_2=(0,1)$, $\mathbf{h}_3=(1,1)$. $\boldsymbol\alpha=\operatorname{softmax}\mathbf{e}=(0.665,0.245,0.090)$, so $\mathbf{c}=0.665(1,0)+0.245(0,1)+0.090(1,1)=(0.755,0.335)$.

Beam search ($B=2$) beating greedy. Step 1: A 0.5, B 0.4, C 0.1. Greedy commits to A. Step 2: after A the best continuation has probability 0.4; after B it is 0.9. Sequence scores: greedy $A!\to!x$: $0.5\cdot0.4=0.20$; beam search keeps both A and B, finds $B!\to!x'$: $0.4\cdot0.9=0.36$, and returns it. Greedy's early commitment cost it a better overall sequence.

Implementation

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]

Advanced topics

  • 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).

Pitfalls and best practices

  • 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.

Conceptual questions and answers

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 $1/\sqrt d$ scaling, performs as well at scale.

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.

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally