Seq2Seq, Attention & Beam Search, Part 1: The Bottleneck and How Attention Fixed It
In September 2016, Google replaced ten years of statistical phrase-table machinery with a single neural network — eight stacked LSTMs wired into an encoder-decoder shape, equipped with attention, and decoded with beam search. Translation error rates dropped by roughly 60 percent on some language pairs overnight. The Google Neural Machine Translation paper became one of the most-cited engineering papers of the decade, and beam search width 12 became the de facto production setting for machine translation. But the real story is the mechanism that powered the leap: a graduate student named Dzmitry Bahdanau had two years earlier asked a very small question — what if the decoder could look back?, and that question quietly invented half of the transformer. This first part covers the problem and the attention fix. Part 2 covers how a finished sentence is actually chosen.
After this lesson, you will be able to:
Diagnose the fixed-context-vector bottleneck in vanilla encoder-decoder LSTMs — why compressing a 100-token sentence into one hidden state catastrophically hurts BLEU on long sequences — and articulate the precise fix attention provides
Derive Bahdanau (additive) and Luong (multiplicative) attention from first principles, prove they are computing a learned weighted dictionary lookup over encoder states, and trace the lineage to scaled dot-product self-attention in transformers
Implement scaled dot-product attention from scratch in numpy on a toy 3-token-source / 2-token-target example, and read the resulting alignment matrix
Say what coverage, copy and pointer mechanisms each repair in a plain attention model, and match each one to a task
In plain words: a translation model first reads the whole sentence, then writes the answer one word at a time. The old design handed the writer a single short summary of everything it read, which is like asking someone to translate a page from one sticky note. Attention fixes that. Each time the writer is about to produce a word, it glances back at every word of the original and gives the most weight to the ones that matter right now. This part builds that idea, then the three small repairs that came after it.
Words you need10 terms
The half of the model that reads the source sentence and turns each word into a vector of numbers.
The half that writes the output one word at a time, using what the encoder produced.
The summary the decoder is given of the source. Plain seq2seq gives one fixed summary. Attention builds a fresh one at every output step.
Training the decoder by feeding it the true previous word instead of its own guess.
The gap between training, where the decoder sees true words, and real use, where it sees its own possibly wrong words.
One number per source word, each between 0 and 1, adding up to 1. A big weight means look here now.
Bahdanau's scoring rule: a small neural network compares the decoder state with each source state.
Luong's scoring rule: multiply the decoder state with each source state and add up. One matrix multiplication scores every source word.
A running total of how much attention each source word has received, used to stop the model repeating or skipping words.
A learned gate that lets the decoder reuse a word straight from the source, such as a name or an error code.
Don't worry if the math notation looks dense — every formula in this lesson is doing one thing: computing a similarity score between something the decoder is asking for and every thing the encoder remembers, then averaging the encoder's memories weighted by that similarity. That single sentence is the entire attention mechanism. Once you see it once, you see it everywhere.
The vanilla encoder-decoder architecture, in one picture:
Source: "Le chat noir dort sur le canapé" (7 tokens)
ENCODER (LSTM)
Le → chat → noir → dort → sur → le → canapé
\
c (1000-dim "thought vector")
/
DECODER (LSTM)
<SOS> → "The" → "black" → "cat" → "sleeps" → "on" → "the" → "couch" → <EOS>
The encoder runs left-to-right (or bidirectionally), producing a hidden state at every step. The vanilla seq2seq throws away all of them except the final one. That final hidden state is the "thought vector" — the entire sentence's meaning, compressed.
The decoder is initialized with this thought vector and then generates the target sequence autoregressively: at each step it predicts a token distribution, samples or argmaxes a token, and feeds that token back as input to the next step.
#Where the Factorisation, the Loss and Exposure Bias Come From
Three results hide in the formulas above: the probability of a whole sentence as a product, the training loss as a sum, and the way mistakes pile up at test time. Open each derivation to see where it comes from.
#The Symptom: BLEU Drops Off A Cliff On Long Sentences
Bahdanau et al. ran the experiment that exposed the bottleneck. They trained two systems on the same English-French data: vanilla seq2seq (no attention) and seq2seq with attention. They then plotted BLEU as a function of source-sentence length.
Source length
Vanilla seq2seq BLEU
Seq2seq + Bahdanau attention
Gap
1-15 tokens
28.4
29.3
+0.9
15-30 tokens
24.8
28.1
+3.3
30-50 tokens
18.6
27.4
+8.8
50+ tokens
12.1
25.8
+13.7
(Approximate numbers from Bahdanau et al. 2015, Figure 2 — exact values varied by language pair and corpus, but the shape was identical everywhere they tried.)
The story is unambiguous: as source sentences get longer, vanilla seq2seq collapses. The thought vector cannot hold more information than its dimension, and information loss compounds catastrophically beyond ~30 tokens.
What Do You Think?
The encoder's final hidden state c is a 1000-dimensional vector. Roughly how much information (in bits, naively) can it hold?
Let the decoder look back at every encoder hidden state, not just the last one.
That is it. That is the entire conceptual leap. Once you grant the decoder access to the full sequence of encoder states [h_1, h_2, ..., h_{T_src}], instead of just h_{T_src}, the bottleneck vanishes. The question becomes: at each decoder step, how should the decoder combine those encoder states into a useful summary?
The answer is attention — a learned, content-aware weighted average.
Recap: The LSTM cell that builds the encoder's hidden statesInteractive
Loading visualization...
Before we add attention, ground yourself in what the encoder hidden states are. Each h_i is the LSTM cell's output at source position i — a vector that encodes everything the LSTM saw from position 1 up through position i. Step through the LSTM gates and notice how h_i accumulates context. Attention will treat this entire sequence [h_1, ..., h_{T_src}] as a memory bank the decoder can query.
At each decoder step j, for every encoder position i, compute an alignment score e_ij that measures how well the encoder state h_i matches the decoder's current information need s_:
eij=v⊤tanh(Whhi+Wssj−1)
The matrices W_h and W_s are learned during training. They project both states into a shared attention space of dimension A (typically 256 or 512). The vector v learns to score how aligned the projected states are.
Why does the lesson later call Luong's concat score a rewritten Bahdanau score? Open the derivation to see the two are one formula.
The context vector c_j for decoder step j is the weighted average of encoder states, weighted by the attention probabilities:
cj=i=1∑Tsrcαijhi
Two facts about the weights and the context vector are used everywhere later: the weights sum to 1, and the blend never leaves the encoder states. Open the derivation to see both.
That is the entire algorithm. Three small additions to vanilla seq2seq (score, softmax, weighted sum) gave Bahdanau, Cho, and Bengio +13 BLEU on long sentences.
To train attention, a gradient has to flow back through the softmax and the weighted sum into the scores. Open the derivation for the short formula it reduces to.
Watch the decoder's attention shift across the source sentence at each output stepInteractive
Loading visualization...
Step through the decoder one output token at a time. Watch the attention distribution α_ij change — the heatmap should highlight the source word(s) most relevant to the current target word. For translation, attention tends to learn soft alignment: each target word attends to the corresponding source word, with some smearing across nearby positions.
The dot-product variant is computationally trivial — one matrix-vector multiplication gives you all the scores. Compare with Bahdanau's additive form, which requires a tanh and two separate projections.
The general score hides a useful reading: it is a dot product after a learned change to the query. Open the derivation for the algebra.
By 2017, the field had largely converged on dot-product attention because:
Speed. One batched matmul instead of a tanh-MLP per (i, j) pair.
Parallelism. With pre-computed encoder states, you can compute all scores for all decoder steps in a single matmul of shape (T_tgt, H) @ (H, T_src) = (T_tgt, T_src). This is exactly what self-attention does at every layer.
Empirical equivalence. On standard MT benchmarks, dot-product and additive attention scored within noise of each other (Luong 2015, Vaswani 2017).
Hardware fit. GPUs are essentially matmul engines. Anything that reduces to a matmul wins.
What Do You Think?
Bahdanau (additive) vs Luong (dot-product), which is computationally cheaper, and why does it matter for transformer-scale models?
Here is the conceptual punchline: Luong's dot-product attention is mechanically identical to a single head of self-attention, applied between two sequences (decoder querying encoder). The transformer's contribution was three-fold:
Apply attention within a single sequence — every token attends to every other token (self-attention).
Rescale by 1/sqrt(d_k) to stabilize softmax gradients when hidden dimensions are large.
Use separate learned projections for queries, keys, and values (Q, K, V) instead of using the hidden state directly for all three roles.
Everything else (the softmax, the weighted sum, the parallel matmul) was already in Luong (2015). When we get to the transformers lesson, you will see this same math, the same dataflow, just applied recursively in a different topology. The DNA is identical.
Why exactly the square root of d_k, and not d_k or 2? Open the derivation to see the variance calculation behind the scaling.
Three small but important refinements appeared between 2015 and 2017, addressing pathologies that vanilla attention suffered from. They are worth knowing because they survive into the LLM era as inductive biases and as architectural ideas.
The pathology: vanilla attention can attend to the same source position repeatedly across many decoder steps. This causes two failure modes:
Over-translation. A single source word generates many target tokens (the model keeps "saying it again").
Under-translation. Some source words are never attended to and get dropped from the output.
The fix: maintain a coverage vector cov_j = Σ_{j' < j} α_{ij'} — a running sum, over all previous decoder steps, of the attention probability assigned to each source position. Feed this coverage vector into the score function as an additional input:
eij=v⊤tanh(Whhi+Wssj−1+Wccovij)
Tu et al. reported BLEU improvements of +1.0 to +1.5 on Chinese-English MT, and qualitatively cleaner output (fewer dropped words). Modern transformer decoders typically don't use explicit coverage — they pick up the same behavior implicitly from scale — but coverage remains a useful inductive bias for low-resource settings.
The running sum has a simple property that explains the coverage idea: all the attention an output can spend is fixed. Open the derivation to see it.
#Copy Mechanism (CopyNet, See et al. 2017; Pointer Networks, Vinyals et al. 2015)
The pathology: vocabularies are finite. If the source contains a rare named entity ("Tashkent") or a number ("17,432") that the decoder's output vocabulary doesn't contain, the model can't output it — even though the right thing to do is obviously to copy it verbatim.
The fix: at each decoder step, the model learns a soft switch between two modes:
Generate. Sample from the normal output distribution over the target vocabulary.
Copy. Pick a source token directly using the attention distribution as a copy probability.
Copy mechanisms transformed abstractive summarization in 2017 — the See et al. "Get to the Point" paper showed that CopyNet on news summarization beat all prior systems by a wide margin precisely because news articles are full of names, numbers, and quotes that should be copied verbatim. Modern LLMs implicitly learn the same behavior at scale: GPT-4 can copy a name from a 100K-token document because its attention naturally produces high copy-like weights on relevant spans. But the explicit copy switch survives in production code-generation systems and structured-output models where you need to guarantee exact copying.
Is a blend of a vocabulary distribution and an attention distribution still a distribution? Open the derivation to confirm it sums to 1.
A close cousin: pointer networks output only indices into the source — useful for problems like sorting, convex hulls, and combinatorial optimization where the output vocabulary IS the input. Mechanically: skip the vocabulary projection entirely, just output argmax_i α_{ij} at each step. Vinyals showed this worked for variable-output-size combinatorial problems where standard seq2seq has no good way to express "the answer is a permutation of the input."
Quick check
You're building a seq2seq model that translates user error reports into structured bug-report JSON. The reports contain product names ('iPhone 17 Pro Max'), error codes ('ERR_NET_503'), and version strings ('v2.7.14-beta') that should appear verbatim in the JSON output. Which mechanism most directly addresses this need?
Read through the output. Three things should jump out:
The attention distribution is peaked on the source position that matches the decoder's query (h_2 = "chat" matches the decoder's preparation to emit "cat"). This is what learned alignment looks like.
The context vector is not equal to any single h_i. It's a blend, weighted toward h_2 but with non-zero contributions from h_1 and h_3. This blend is what the decoder uses going forward.
The full attention computation reduces to two matmuls (scores = H @ s, context = α @ H) plus a softmax. That's it. The whole transformer revolution is built on this primitive applied at every layer with learned projections.
Visualize a learned MT alignment — how attention naturally recovers word-level alignmentInteractive
Loading visualization...
This is the kind of heatmap Bahdanau et al. published in 2014 that made the field gasp. The diagonal-ish pattern was learned end-to-end from translation pairs alone — no one annotated alignments; the model figured them out as a side effect of getting better at translation. Off-diagonal mass corresponds to genuine syntactic reordering (subject-verb-object swaps, adjective-noun position differences). The model not only translates — it understands word-level correspondences, for free.
The bottleneck. Vanilla seq2seq compresses the entire source into one fixed-size thought vector. Information loss is catastrophic for long sequences — BLEU collapses on sentences over 30 tokens.
Bahdanau additive attention (2014). Let the decoder look back at every encoder hidden state with learned weights computed by a small MLP. Score = v^T tanh(W_h h_i + W_s s_{j-1}). Solved the bottleneck and quietly seeded the transformer.
Luong dot-product attention (2015). Replaced the MLP with a dot product. Same alignment quality, dramatically cheaper, parallelizable as a single matmul. This is the math that survived into self-attention.
Coverage, copy, and pointer mechanisms address attention's pathologies: over/under-translation (coverage), rare-vocabulary copying (CopyNet), and combinatorial outputs (pointer networks). They survive into the LLM era as inductive biases and as explicit features in structured-output systems.
Attention is two matrix multiplications and a softmax. Score every source state against the decoder state, turn the scores into weights that add up to 1, and take the weighted sum. The result is a blend of encoder states, never a single one.