Neural Machine Translation
Imagine building a system that reads a sentence in French. It produces a fluent, meaning-preserving sentence in English. Word choices and word order are fully rearranged as needed. This is machine translation. For decades it was dominated by statistical phrase-tables and hand-built alignment models. These stitched together fragments without any real understanding of sentence structure. Neural Machine Translation (NMT) replaced that pipeline with a single differentiable model. It is trained end-to-end to maximize the likelihood of correct translations. It uses the Encoder-Decoder Architecture and the Attention Mechanism in NLP as its computational backbone. NMT matters because it is the clearest large-scale success story of sequence-to-sequence learning. It powers Google Translate, Bing Translator, DeepL, and the translation layers inside countless multilingual products. Its architecture directly foreshadows the Transformer-based large language models used today for far more than translation. Understanding NMT means understanding three separable but interlocking pieces. First, how the encoder-decoder model computes a probability distribution over target sentences. Second, how beam search turns that distribution into an actual output sentence at inference time. Third, how BLEU (and its relatives) measure whether that output is any good. The big picture is that translation is reframed as conditional language modeling. Given a source sentence , learn over target sentences . Train by maximizing the log-likelihood of parallel human-translated data. Everything else — attention, beam search, subword vocabularies — exists to serve this goal. It makes this conditional language model more accurate to train. It also makes the model more useful to decode. This article delivers a complete, correct treatment of the full NMT pipeline. It covers the training objective and architecture in detail. It covers the greedy-vs-beam-search decoding algorithm, with pseudocode and complexity analysis. It covers the BLEU metric, with a worked numeric trace. It also covers the practical failure modes — length bias, exposure bias, repetition — that every real system must confront.
- NMT models translation as conditional sequence generation: learned by an encoder-decoder network with attention.
- Training uses teacher forcing and cross-entropy loss on parallel corpora, maximizing log-likelihood of gold translations.
- Exact decoding (finding the highest-probability sentence) is intractable, so beam search approximates it with a fixed-width frontier.
- Beam search runs in time where is beam width, output length, vocabulary size.
- BLEU scores translations via modified n-gram precision combined with a brevity penalty, correlating reasonably with human judgment.
- Subword tokenization (foreshadowed here, detailed elsewhere) solves the fixed-vocabulary bottleneck that plain word-level NMT suffers from.
NMT turns translation into learned conditional language modeling, and beam search plus BLEU are the practical machinery that make that model usable and measurable.
The idea
Neural Machine Translation frames translation as learning a conditional probability distribution over target-language sentences given a source sentence . The distribution factors autoregressively by the chain rule of probability:
An encoder network converts the source sequence into a set of contextualized vector representations; a decoder network, conditioned on those representations through an attention mechanism, generates the target sequence one token at a time. This is precisely the Encoder-Decoder Architecture combined with Attention Mechanism in NLP, applied to the specific task where inputs and outputs are sentences in different languages. Three distinct algorithmic problems sit inside "doing NMT," and it is important to keep them separate. Training is a supervised learning problem: given parallel sentence pairs , adjust to maximize , typically using teacher forcing (feeding the true previous target token as decoder input, rather than the model's own prediction, at each training step). Decoding (also called inference) is a search problem: at test time there is no gold target, so the system must search over the exponentially large space of possible output sentences to find one with high probability under the trained model; beam search is the standard approximate solution. Evaluation is a measurement problem: given a machine-produced translation and one or more human reference translations, produce a number that predicts human judgments of quality; BLEU is the classical automatic metric for this.
How it works
Training-time computation. During training, the encoder reads the entire source sentence (usually with a bidirectional recurrent network or a Transformer stack, so each token's representation depends on the whole sentence) and produces representations . The decoder is unrolled step by step. At step , it computes an attention distribution over the encoder states, forms a context vector , and combines with its own hidden state to produce a distribution over the target vocabulary for . Teacher forcing means the decoder's input at step is the gold token , not its own previous guess — this stabilizes training and lets the whole sequence be scored in one parallel pass (or one efficient recurrence), but it creates a train/test mismatch called exposure bias, discussed further below.
Decoding-time computation. At inference, there is no gold sequence. The obvious approach — greedily pick at every step — is fast but can commit to an early token that forecloses a much better full sentence, because local greedy choices are not guaranteed to compose into a globally optimal sequence. Exhaustive search over all possible sequences is intractable. Beam search is the practical middle ground: maintain the most promising partial hypotheses at each step (a "beam" of width ), extend each by one token, score all extensions, and keep only the top again. It is a form of pruned breadth-first search guided by the model's own probability estimates. ``` function BEAM_SEARCH(source x, model M, beam_width k, max_len T): encode source once: enc_states <- M.encode(x)
# each hypothesis: (token_sequence, log_probability, decoder_state, is_finished) beam <- [ ([""], 0.0, M.init_decoder_state(enc_states), false) ] completed <- [] for t in 1 .. T: candidates <- [] for (seq, logp, state, done) in beam: if done: candidates.append( (seq, logp, state, done) ) # keep finished hyps as-is continue
# one decoder step: distribution over next token dist, new_state <- M.decode_step(seq[-1], state, enc_states) top_k_tokens <- TOP_K(dist, k) # cheap local pruning before global pruning for token in top_k_tokens: new_logp <- logp + log(dist[token]) new_seq <- seq + [token] is_end <- (token == "") candidates.append( (new_seq, new_logp, new_state, is_end) )
# normalize by length to avoid favoring short hypotheses (see Complexity section) score(seq, logp) := logp / length_penalty(len(seq)) candidates.sort_by(score, descending) beam <- candidates[0 : k] for hyp in beam: if hyp.is_finished: completed.append(hyp) beam <- [h for h in beam if not h.is_finished] if beam is empty: break all_hyps <- completed + beam return argmax over all_hyps of score(seq, logp) ``` Two design choices deserve emphasis. First, pruning to before re-expanding at the next step is what keeps the algorithm polynomial rather than exponential — without it, the frontier would grow by a factor of every step. Second, raw log-probability sums are monotonically decreasing (more negative) as sequences get longer, since every factor ; without a length correction, beam search is biased toward short, truncated outputs, which is why a length penalty (dividing by for some , or an additive variant) is applied before ranking.
Where BLEU fits. After decoding produces a full hypothesis sentence, BLEU compares it against one or more human reference translations using overlapping n-grams, described precisely in the next section. Together, training (learn ), decoding (search for good under that model), and evaluation (score the resulting against references) constitute the complete NMT pipeline.
Complexity & correctness
Training complexity. For a single sentence pair of source length and target length with hidden dimension and vocabulary size , one training step costs for the recurrent/attention computations (encoder self-processing, decoder self-processing, and the attention score matrix) plus for the output softmax layers. Since teacher forcing supplies the gold prefix at every step, the entire target sequence's losses can be computed with one forward pass (parallelizable across for Transformer decoders, sequential but still single-pass for RNN decoders) — there is no search during training, only supervised loss computation, so this cost is polynomial and exact.
Decoding complexity — why beam search, and why it is not exact. The true decoding objective is
over all finite sequences , an exponentially large search space ( candidates for length- outputs). Exhaustive maximization is intractable for any realistic vocabulary. Greedy decoding (beam width ) costs — linear in output length — but is a purely local heuristic with no lookahead: choosing the highest-probability token at step can lock in a prefix from which no high-probability continuation exists, even though a slightly lower-probability token at step would have opened onto a much better full sentence. Beam search with width costs : at each of steps, each of the hypotheses is extended over possible next tokens (an scoring pass, dominated by -dimensional decode-step computation), then re-pruned to . This is exponentially cheaper than exhaustive search while retaining a bounded amount of lookahead capacity — the parallel hypotheses act as a beam of alternate futures rather than a single committed path. Correctness argument (approximation, not exactness). Beam search is not guaranteed to find the global maximizer of ; it is a heuristic pruned search, and the pruning at each step is the source of approximation error — a hypothesis that ranks outside the top at step is discarded even if some suffix from it would eventually dominate. Formally, larger can only improve or maintain the achieved score relative to smaller under the same scoring function, because the set of hypotheses retained by beam width is a superset of those retained by any at every step (monotonicity in beam width). This gives a partial correctness guarantee: beam search score is monotonically non-decreasing in , converging to the true as (impractical) or, more usefully, empirically converging quickly for well-trained models because probability mass concentrates sharply on a small set of plausible continuations. In practice, however, very large can even hurt end-task quality (measured by BLEU) despite improving the model's own log-probability score, an empirically documented mismatch between what the model considers likely and what humans consider good — a symptom of length bias and calibration issues in the trained distribution, not a bug in the search algorithm itself.
BLEU: definition and correctness as a proxy metric. BLEU (BiLingual Evaluation Understudy) scores a candidate translation against reference(s) using modified n-gram precision: for each n-gram (typically ), count matches between candidate and reference, but clip each n-gram's count in the candidate at the maximum number of times it appears in any single reference (this clipping is essential — without it, a degenerate candidate that repeats one high-frequency word could score perfect precision). Formally, for n-grams:
Precision alone rewards short outputs (a one-word candidate that happens to match can score ), so BLEU multiplies by a brevity penalty BP that penalizes candidates shorter than the reference:
where is candidate length and is (effective) reference length. The final score combines geometric-mean precision across n-gram orders with the brevity penalty:
Why this is a reasonable (if imperfect) proxy. The geometric mean over multiple n-gram orders rewards both lexical choice (unigrams) and local fluency/word order (higher-order n-grams), since a candidate must reproduce increasingly long contiguous spans of the reference to score well on . The brevity penalty is a correctness patch closing the "too-short" exploit that unclipped or unpenalized precision would allow. BLEU is not a measure of semantic adequacy — it has no model of synonymy, paraphrase, or meaning beyond surface n-gram overlap — so it systematically under-scores valid paraphrastic translations and is known to correlate imperfectly with human judgment at the sentence level, though correlation is stronger when aggregated over a full corpus.
Worked example
Beam search trace. Suppose the decoder vocabulary restricted to plausible next tokens gives (toy, illustrative probabilities), decoding "Le chat dort" with beam width :
| Step | Hypothesis (before) | Top extensions considered | Log-prob | Kept in beam (top 2)? |
|---|---|---|---|---|
| 1 | ` | "The" (0.6), "A" (0.3), "Cat" (0.1) | log 0.6 = −0.51, log 0.3 = −1.20, log 0.1 = −2.30 | "The" ✓, "A" ✓ |
| 2 | ` | "cat" (0.7), "dog" (0.2) | total: −0.51+(−0.36)=−0.87; −0.51+(−1.61)=−2.12 | "The cat" ✓ |
| 2 | ` | "cat" (0.5), "dog" (0.4) | total: −1.20+(−0.69)=−1.89; −1.20+(−0.92)=−2.12 | "A cat" ✓ (tied 2nd) |
| 3 | ` | "sleeps" (0.8), "is" (0.15) | −0.87+(−0.22)=−1.09; −0.87+(−1.90)=−2.77 | "The cat sleeps" ✓ |
| 3 | ` | "sleeps" (0.6), "is" (0.3) | −1.89+(−0.51)=−2.40; −1.89+(−1.20)=−3.09 | "A cat sleeps" ✓ |
| 4 | both hyps emit `` | — | final scores: −1.09 vs −2.40 | winner: "The cat sleeps" |
Notice that at step 1 the beam kept "The" and "A" even though "Cat" alone was locally lower-probability — this is the lookahead beam search provides over greedy decoding, which would have committed to "The" alone and never even considered "A" as a competing hypothesis (in this toy case both converge to a sensible answer, but in general only the beam explores enough alternatives to correct an early misstep). After length normalization (dividing by length, here both length 3 excluding ``/`` so ranking is unchanged), the decoder outputs "The cat sleeps."
BLEU trace. Suppose the reference translation is "The cat is sleeping" and the candidate (system output) is "The cat sleeps now":
- Unigram matches (clipped): "The" ✓, "cat" ✓, "sleeps" ✗ (not in reference as exact token — reference has "sleeping"), "now" ✗ →
- Bigram matches: "The cat" ✓ (appears in both), "cat sleeps" ✗, "sleeps now" ✗ →
- Trigram matches: "The cat sleeps" ✗, "cat sleeps now" ✗ →
Because , the raw geometric mean is zero — in practice implementations apply smoothing (e.g., adding a small count to avoid a zero score for otherwise-reasonable short sentences), but working through the unsmoothed math: candidate length , reference length , so (no penalty, lengths equal). The example shows concretely how BLEU harshly penalizes lexical variation ("sleeps" vs "sleeping") even when the translation is semantically correct — a central, well-documented limitation of surface-level n-gram metrics.
Common pitfalls & traps
| Pitfall | Why it happens | Consequence | Fix |
|---|---|---|---|
| Using beam search with large and expecting monotonic BLEU gains | Higher model log-probability ≠ higher output quality; the "beam search curse" | BLEU can drop as grows past a moderate value (often –) | Tune on a validation set; apply length normalization |
| No length penalty in beam scoring | Log-probabilities are sums of negative terms; shorter sequences accumulate less penalty | Decoder favors truncated, unnaturally short outputs | Normalize score by or use coverage/length penalties |
| Exposure bias from teacher forcing | Training always conditions on gold prefixes; inference conditions on the model's own (possibly wrong) prefixes | Errors compound at inference — one bad token derails the rest of the sentence | Scheduled sampling, sequence-level training objectives, or simply robust beam search |
| Repetition loops in the decoder | Attention can get "stuck" re-attending to the same source span | Output like "the the the the" or repeated phrases | Coverage penalties, repetition penalties, n-gram blocking during beam search |
| Fixed word-level vocabulary and out-of-vocabulary words | Rare words, morphology-rich languages, and names cannot all fit in a finite word list | `` tokens degrade fluency and lose information | Use subword units (see Subword Tokenization) instead of whole-word vocabularies |
| Treating BLEU as a semantic-adequacy score | BLEU only measures surface n-gram overlap with references | Valid paraphrases scored low; systems can be over-tuned to BLEU rather than real quality | Pair BLEU with human evaluation or learned metrics (e.g., embedding-based scores) |
Pioneers & history
Origins · 1 minIlya Sutskever and how this was discovered
Sutskever, along with Oriol Vinyals and Quoc Le, showed in 2014 that a single end-to-end LSTM encoder-decoder could translate competitively without any hand-built alignment or phrase tables, a result that reframed machine translation as a general sequence-learning problem and catalyzed the entire NMT research program.
Where this matters
Every major commercial translation product — Google Translate, Microsoft Translator, DeepL, Amazon Translate — runs an NMT pipeline of essentially this shape: an encoder-decoder with attention, a beam-search decoder at inference time, and BLEU (among other metrics) used during development and benchmarking. Multilingual customer support systems, subtitle generation and localization pipelines, and cross-lingual information retrieval all depend on NMT as a core component. The same encoder-decoder-plus-attention architecture, and the same beam-search decoding algorithm, generalize directly to other conditional generation tasks — abstractive summarization, image captioning, speech recognition, and code generation all reuse this machinery essentially unchanged. The Transformer architecture that now dominates large language models grew directly out of NMT research, meaning the training objective (conditional log-likelihood), decoding strategy (beam or sampling-based search), and evaluation-metric mindset (automatic n-gram or learned metrics standing in for human judgment) established in NMT research remain the conceptual template for modern text generation systems broadly.
Ask the tutor: How does the choice of beam width interact with the length penalty to affect final translation quality?
Why can't we just use greedy decoding and skip beam search entirely?
Greedy decoding picks the single highest-probability token at each step and never reconsiders that choice. Because sentence-level probability is a product over per-token conditional probabilities, an early greedy choice can commit the decoder to a prefix from which no good continuation exists, even though a slightly less likely early token would have opened onto a much better overall sentence. Beam search keeps several competing hypotheses alive simultaneously, giving the search a limited but genuine form of lookahead. It costs more computation — roughly times as much per step — but in practice yields measurably better translations for a modest beam width, which is why virtually all production NMT systems use beam search rather than pure greedy decoding at inference time.
Is beam search guaranteed to find the translation with highest probability under the model?
No. Beam search is a heuristic pruned search, not an exact optimization algorithm. At every decoding step it discards all but the top partial hypotheses, and a hypothesis that looks weak at step might have led to the single best full sentence at step — that possibility is permanently lost once pruned. Increasing can only match or improve the score the algorithm finds relative to a smaller , converging toward the true maximizer as grows very large, but for any practical, bounded there is no guarantee of global optimality. This is an accepted, well-understood tradeoff: exact search is exponential, so an approximate, polynomial-time heuristic is used instead.
Why does BLEU sometimes penalize a translation that a human would call correct?
BLEU measures surface n-gram overlap between the candidate and one or more fixed reference translations, with no model of synonymy or paraphrase. A translation that conveys the exact right meaning using different words or phrasing than the reference ("she is sleeping" versus reference "she sleeps") will score lower n-gram precision purely because the tokens don't match lexically. This is a known and much-discussed limitation: BLEU is a useful, cheap, reproducible proxy that correlates reasonably well with human judgment when aggregated over large corpora, but it is not a semantic adequacy metric, and sentence-level BLEU comparisons should be interpreted cautiously.
What is the relationship between attention and beam search — do they interact?
They operate at different stages and are logically independent, but they interact computationally. Attention is part of the model: at each decoder step, it produces a context vector by weighting encoder states, feeding into the probability distribution over the next token. Beam search is part of the decoding algorithm: it uses that per-step distribution, produced afresh for every live hypothesis in the beam, to decide which sequences to keep. Since each of the beam hypotheses requires its own attention computation over the (shared) encoder states at every step, beam width directly multiplies the number of attention computations performed, which is why decoding cost scales linearly in .
Why does NMT typically use subword units instead of whole words in the vocabulary?
Natural language vocabularies are effectively unbounded — new names, compounds, morphological variants, and rare words appear constantly — but a softmax output layer requires a fixed, finite vocabulary size. A whole-word vocabulary forces a hard cutoff, replacing anything outside it with an `` placeholder that destroys information and hurts fluency, especially for morphologically rich languages. Subword tokenization schemes split words into smaller frequent units, letting rare words be built compositionally from familiar pieces while keeping the vocabulary size manageable. This is exactly the problem that Subword Tokenization solves, and virtually every modern NMT system uses it rather than raw whole-word vocabularies.
How is the NMT training loss actually computed, given that outputs are discrete tokens?
Training uses cross-entropy loss at every decoder position: at step , the model outputs a probability distribution over the vocabulary, and the loss is the negative log-probability the model assigned to the true next token, . Summing (or averaging) this over all positions in a sentence, and over all sentences in a batch, gives a fully differentiable scalar loss that gradient descent can optimize via backpropagation through both the decoder and the attention-weighted encoder representations. Because teacher forcing supplies the true previous tokens rather than the model's own predictions during this computation, the entire loss can be computed in one pass without any search.
Does a lower training loss always mean a better translator?
Not directly. Training loss (cross-entropy against gold references) measures how well the model's probability distribution matches the training data, but the actual deployed system is judged by decoded output quality, measured imperfectly by BLEU or human evaluation. A model can achieve very low training loss yet still generate poor translations at inference due to exposure bias, miscalibrated probabilities interacting badly with beam search, or a training/test domain mismatch. This gap between the training objective and the deployment metric is a recurring theme across NMT and modern generative language modeling generally, and is one reason held-out BLEU (or human evaluation) is tracked separately from training loss throughout development.