Neural Machine Translation: From Attention to Modern Systems
What You'll Learn
- 1Explain why attention beat fixed vector encoders
- 2Score beam candidates with length normalization
- 3Compute clipped n-gram precision and brevity penalty
- 4Choose between BLEU, chrF, and COMET
Machine translation converts a sentence from one language into another while preserving meaning, and it is where nearly every modern NLP architecture was proven first. A one point BLEU regression on a high volume direction degrades millions of daily queries, so automatic metrics are the only scalable guardrail. This lesson builds the pipeline from Bahdanau attention through the Transformer, then scores beam search and BLEU.
From Phrase-Based SMT to Attention
Statistical systems such as Moses (Koehn et al., 2007) scored candidates with a log-linear mixture of phrase table, language model, and reordering features. Each language pair needed a fresh word alignment run, and unseen words broke phrase tables.
Sequence to sequence learning (Sutskever et al., 2014) compressed the source into one vector with a stacked LSTM, and quality collapsed on long sentences. Bahdanau, Cho, and Bengio (2014) fixed that by letting the decoder revisit all source states at each target step:
The weights sum to one over the source positions, so the context is a convex combination of source states:
Training uses teacher forcing and token level cross entropy over the reference target of length :
The Transformer Translation Architecture
The Transformer (Vaswani et al., 2017) removes recurrence and computes every position from pairwise interactions with all positions in a single parallel pass:
Dividing by the square root of keeps query key logits near unit variance so the softmax does not saturate, and heads specialize on syntax, locality, and agreement. The base stacks 6 layers per side with 512 dimensions, 8 heads, and 2048 unit feed-forward blocks for about 65 million parameters; the big uses 1024 dimensions, 16 heads, and 4096 units for about 213 million.
Recurrence forces a sequential chain whose length grows with the sentence, while self-attention connects any two positions in one step:
| Layer type | Per layer cost | Sequential steps | Path length |
|---|---|---|---|
| Recurrent | |||
| Convolution, kernel | |||
| Self-attention |
Self-attention pays a quadratic cost in , so batches are bucketed by length and inputs capped at a few hundred subword tokens.
Beam Search Decoding
Greedy decoding takes the argmax at each step and commits early. Beam search keeps the highest scoring partial hypotheses, expands each over the vocabulary, and prunes back to :
Raw log probability favors short strings, since each extra token multiplies in a factor below one, so production systems normalize by length:
With beam width 5 and a 32,000 token vocabulary, each step scores continuations, and a 30 token output then costs about 4.8 million scores. Widths above 6 rarely help and often lower BLEU through search error.
Evaluating Translation Quality
BLEU (Papineni et al., 2002) clips each hypothesis n-gram count at its count in the reference, takes the geometric mean of four clipped precisions, and multiplies by a brevity penalty:
Corpus BLEU sums matches over the whole test set before taking roots, the SacreBLEU default (Post, 2018), and its printed signature makes numbers comparable. Sentence level BLEU tracks human judgment poorly (Callison-Burch et al., 2006), since short candidates often share no 4-grams.
| Metric | Measures | Scale | Best for |
|---|---|---|---|
| BLEU-4 | clipped word n-gram precision | 0 to 100 | WMT style evaluation |
| chrF2 | character 6-gram F-score | 0 to 100 | rich morphology targets |
| TER | word edits over length | lower is better | post-editing effort |
| COMET | neural regression on human scores | about -1 to 1 | human correlated decisions |
FLORES-200 is the modern balanced benchmark: 1012 development and 1012 development test sentences across 204 languages.
Worked Examples
Worked Code
"""BLEU: clipped n-gram precision times brevity penalty (Papineni 2002)."""
import math
from collections import Counter
def bleu(hyp, ref, max_n=4):
logs, c_len, r_len = [], len(hyp), len(ref)
for n in range(1, max_n + 1):
h = Counter(zip(*[hyp[i:] for i in range(n)]))
r = Counter(zip(*[ref[i:] for i in range(n)]))
hit = sum(min(c, r[g]) for g, c in h.items())
logs.append(math.log(hit / sum(h.values())) if hit else float("-inf"))
bp = min(1.0, math.exp(1 - r_len / max(c_len, 1)))
return bp * math.exp(sum(logs) / max_n)
print(round(bleu("the cat sat on the red mat".split(),
"the cat sat on a red mat".split()) * 100, 1))
"""MarianMT translation with length-normalized beam search."""
from transformers import MarianMTModel, MarianTokenizer
tok = MarianTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de")
model = MarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de")
batch = tok("Attention lets the decoder focus on relevant source words.",
return_tensors="pt", truncation=True)
out = model.generate(**batch, num_beams=5, length_penalty=0.6,
max_new_tokens=64)
print(tok.decode(out[0], skip_special_tokens=True))
Real-World Applications
- WMT 2014 record - Transformer big reached 28.4 BLEU on English to German and 41.8 on English to French after 3.5 days on 8 GPUs (Vaswani et al., 2017).- 200 languages - NLLB-200 pushes past the roughly 100 languages commercial systems covered, scored on FLORES-200.
- On device models - MarianMT trains a 6 layer encoder decoder in C++ and translates one sentence on CPU in milliseconds.
đĄScore Corpora, Not Sentences
Common Mistakes
Comparing BLEU from different tokenizers
Fix: Use SacreBLEU and report its signature, since tokenization and casing move BLEU by several points.
Leaving the brevity penalty out
Fix: BP equals exp(1 minus r over c), so tune length penalty with beam width.
Tuning beam settings on the test set
Fix: Tune on held out newstest data and report the test set once.
Best Practices
- Report BLEU through SacreBLEU so the signature pins down tokenization
- Pair an n-gram metric with a learned metric such as COMET
- Keep beam width between 4 and 6 and tune length penalty per direction
Key Takeaways
- Self-attention gives an O(1) path length versus the O(n) path of an RNN
- Length normalized score divides log probability by |y| to the alpha, usually 0.6
- BLEU is the geometric mean of four clipped precisions times a brevity penalty
- Transformer big hit 28.4 BLEU on WMT 2014 En-De with about 213 million parameters
Frequently Asked Questions
Why does raw log probability favor short translations?
Each added token multiplies the probability by a factor at most 1, so a 10 token string usually outscores a 40 token string saying the same thing. Dividing by cancels the bias.
What does the brevity penalty actually cost?
With reference 15 and candidate 12, , a 22 percent cut. Longer candidates pay nothing.
When should I prefer chrF over BLEU?
Use chrF2 for morphologically rich targets and text full of names, since character n-grams give partial credit where word n-grams give none. Add COMET for human quality decisions.
Interview Questions
Q1: Why did attention fix the fixed vector bottleneck?
It replaced one summary vector with a sum over all source states, so the decoder reads source position j at step t and quality stops falling with sentence length.
Q2: What does the square root of d_k scaling do?
It holds query key logit variance near one as d_k grows, so the softmax stays out of saturation.