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 xx, learn P(y∣x)P(y \mid x) over target sentences yy. 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.

Key takeaways
  • NMT models translation as conditional sequence generation: P(y∣x)P(y \mid x) 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 O(T⋅k⋅∣V∣)O(T \cdot k \cdot |V|) time where kk is beam width, TT output length, ∣V∣|V| 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.
The core insight

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 P(y∣x;θ)P(y \mid x; \theta) over target-language sentences y=(y1,…,yT)y = (y_1, \dots, y_T) given a source sentence x=(x1,…,xS)x = (x_1, \dots, x_S). The distribution factors autoregressively by the chain rule of probability:

P(y∣x)=∏t=1TP(yt∣y1,…,yt−1,x)P(y \mid x) = \prod_{t=1}^{T} P(y_t \mid y_1, \dots, y_{t-1}, x)

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 (x(i),y(i))(x^{(i)}, y^{(i)}), adjust θ\theta to maximize ∑ilog⁡P(y(i)∣x(i);θ)\sum_i \log P(y^{(i)} \mid x^{(i)}; \theta), 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 h1,…,hSh_1, \dots, h_S. The decoder is unrolled step by step. At step tt, it computes an attention distribution over the encoder states, forms a context vector ctc_t, and combines ctc_t with its own hidden state to produce a distribution over the target vocabulary for yty_t. Teacher forcing means the decoder's input at step tt is the gold token yt−1truey_{t-1}^{\text{true}}, 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 arg⁡max⁡ytP(yt∣y<t,x)\arg\max_{y_t} P(y_t \mid y_{<t}, x) 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 ∣V∣T|V|^T possible sequences is intractable. Beam search is the practical middle ground: maintain the kk most promising partial hypotheses at each step (a "beam" of width kk), extend each by one token, score all k×∣V∣k \times |V| extensions, and keep only the top kk 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 kk 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 ∣V∣|V| every step. Second, raw log-probability sums are monotonically decreasing (more negative) as sequences get longer, since every factor P(yt∣… )≤1P(y_t \mid \dots) \le 1; without a length correction, beam search is biased toward short, truncated outputs, which is why a length penalty (dividing by ∣y∣α|y|^\alpha for some α∈[0,1]\alpha \in [0,1], or an additive variant) is applied before ranking.

Figure
Encoder–decoder with attention feeding a beam-search decoder
Source → Encoder → Attention → Beam Search Decoder Le chat dort h1 h2 h3 attention weights α c_t decoder P(y_t | y<t, x) Beam (k = 2) over decoding steps "The" "A" "cat" "cat" (pruned) <s>

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 P(y∣x)P(y\mid x)), decoding (search for good yy under that model), and evaluation (score the resulting yy against references) constitute the complete NMT pipeline.

Complexity & correctness

Training complexity. For a single sentence pair of source length SS and target length TT with hidden dimension dd and vocabulary size ∣V∣|V|, one training step costs O(S⋅d2+T⋅d2+T⋅S⋅d)O(S \cdot d^2 + T \cdot d^2 + T \cdot S \cdot d) for the recurrent/attention computations (encoder self-processing, decoder self-processing, and the T×ST \times S attention score matrix) plus O(T⋅d⋅∣V∣)O(T \cdot d \cdot |V|) 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 tt 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

y^=arg⁡max⁡yP(y∣x)\hat{y} = \arg\max_{y} P(y \mid x)

over all finite sequences yy, an exponentially large search space (∣V∣T|V|^T candidates for length-TT outputs). Exhaustive maximization is intractable for any realistic vocabulary. Greedy decoding (beam width k=1k=1) costs O(T⋅∣V∣⋅d)O(T \cdot |V| \cdot d) — linear in output length — but is a purely local heuristic with no lookahead: choosing the highest-probability token at step tt can lock in a prefix from which no high-probability continuation exists, even though a slightly lower-probability token at step tt would have opened onto a much better full sentence. Beam search with width kk costs O(T⋅k⋅∣V∣⋅d)O(T \cdot k \cdot |V| \cdot d): at each of TT steps, each of the kk hypotheses is extended over ∣V∣|V| possible next tokens (an O(k⋅∣V∣)O(k \cdot |V|) scoring pass, dominated by dd-dimensional decode-step computation), then re-pruned to kk. This is exponentially cheaper than exhaustive search while retaining a bounded amount of lookahead capacity — the kk 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 P(y∣x)P(y\mid x); 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 kk at step tt is discarded even if some suffix from it would eventually dominate. Formally, larger kk can only improve or maintain the achieved score relative to smaller kk under the same scoring function, because the set of hypotheses retained by beam width kk is a superset of those retained by any k′<kk' < k at every step (monotonicity in beam width). This gives a partial correctness guarantee: beam search score is monotonically non-decreasing in kk, converging to the true arg⁡max⁡\arg\max as k→∣V∣Tk \to |V|^T (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 kk 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 CC against reference(s) RR using modified n-gram precision: for each n-gram (typically n=1,…,4n=1,\dots,4), 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:

pn=∑ngram∈Cmin⁡(countC(ngram),max⁡refcountref(ngram))∑ngram∈CcountC(ngram)p_n = \frac{\sum_{\text{ngram} \in C} \min\big(\text{count}_C(\text{ngram}), \max_{\text{ref}} \text{count}_{\text{ref}}(\text{ngram})\big)}{\sum_{\text{ngram} \in C} \text{count}_C(\text{ngram})}

Precision alone rewards short outputs (a one-word candidate that happens to match can score p1=1p_1 = 1), so BLEU multiplies by a brevity penalty BP that penalizes candidates shorter than the reference:

BP={1if c>re(1−r/c)if c≤r\text{BP} = \begin{cases} 1 & \text{if } c > r \\ e^{(1 - r/c)} & \text{if } c \le r \end{cases}

where cc is candidate length and rr is (effective) reference length. The final score combines geometric-mean precision across n-gram orders with the brevity penalty:

BLEU=BP⋅exp⁡(∑n=1Nwnlog⁡pn),typically N=4, wn=1/N\text{BLEU} = \text{BP} \cdot \exp\left(\sum_{n=1}^{N} w_n \log p_n \right), \quad \text{typically } N=4,\ w_n = 1/N

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 p2,p3,p4p_2, p_3, p_4. 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 k=2k=2:

StepHypothesis (before)Top extensions consideredLog-probKept 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` The`"cat" (0.7), "dog" (0.2)total: −0.51+(−0.36)=−0.87; −0.51+(−1.61)=−2.12"The cat" ✓
2` A`"cat" (0.5), "dog" (0.4)total: −1.20+(−0.69)=−1.89; −1.20+(−0.92)=−2.12"A cat" ✓ (tied 2nd)
3` The cat`"sleeps" (0.8), "is" (0.15)−0.87+(−0.22)=−1.09; −0.87+(−1.90)=−2.77"The cat sleeps" ✓
3` A cat`"sleeps" (0.6), "is" (0.3)−1.89+(−0.51)=−2.40; −1.89+(−1.20)=−3.09"A cat sleeps" ✓
4both hyps emit ``—final scores: −1.09 vs −2.40winner: "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" ✗ → p1=2/4=0.5p_1 = 2/4 = 0.5
  • Bigram matches: "The cat" ✓ (appears in both), "cat sleeps" ✗, "sleeps now" ✗ → p2=1/3≈0.333p_2 = 1/3 \approx 0.333
  • Trigram matches: "The cat sleeps" ✗, "cat sleeps now" ✗ → p3=0/2=0p_3 = 0/2 = 0

Because p3=0p_3 = 0, 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 c=4c=4, reference length r=4r=4, so BP=1\text{BP} = 1 (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

PitfallWhy it happensConsequenceFix
Using beam search with large kk and expecting monotonic BLEU gainsHigher model log-probability ≠ higher output quality; the "beam search curse"BLEU can drop as kk grows past a moderate value (often k≈4k \approx 4–1010)Tune kk on a validation set; apply length normalization
No length penalty in beam scoringLog-probabilities are sums of negative terms; shorter sequences accumulate less penaltyDecoder favors truncated, unnaturally short outputsNormalize score by ∣y∣α|y|^\alpha or use coverage/length penalties
Exposure bias from teacher forcingTraining always conditions on gold prefixes; inference conditions on the model's own (possibly wrong) prefixesErrors compound at inference — one bad token derails the rest of the sentenceScheduled sampling, sequence-level training objectives, or simply robust beam search
Repetition loops in the decoderAttention can get "stuck" re-attending to the same source spanOutput like "the the the the" or repeated phrasesCoverage penalties, repetition penalties, n-gram blocking during beam search
Fixed word-level vocabulary and out-of-vocabulary wordsRare words, morphology-rich languages, and names cannot all fit in a finite word list`` tokens degrade fluency and lose informationUse subword units (see Subword Tokenization) instead of whole-word vocabularies
Treating BLEU as a semantic-adequacy scoreBLEU only measures surface n-gram overlap with referencesValid paraphrases scored low; systems can be over-tuned to BLEU rather than real qualityPair BLEU with human evaluation or learned metrics (e.g., embedding-based scores)

Pioneers & history

Origins · 1 minIlya Sutskever and how this was discovered
IS
Ilya Sutskever
1986– · Co-developed sequence-to-sequence learning with LSTMs, a direct precursor to modern NMT

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.

History
1954
— the Georgetown-IBM experiment demonstrates rule-based Russian-to-English translation, launching MT as a field.
2014
— sequence-to-sequence learning with neural networks (Sutskever, Vinyals, Le) shows LSTM encoder-decoders can translate end-to-end.
2015
— Bahdanau, Cho, and Bengio introduce attention for NMT, letting the decoder dynamically focus on relevant source words.
2016
— Google deploys Google Neural Machine Translation (GNMT) in production, replacing its phrase-based statistical system.
2017
— the Transformer architecture ("Attention Is All You Need") replaces recurrence with self-attention, becoming the dominant NMT backbone.

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 kk 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 kk partial hypotheses, and a hypothesis that looks weak at step tt might have led to the single best full sentence at step TT — that possibility is permanently lost once pruned. Increasing kk can only match or improve the score the algorithm finds relative to a smaller kk, converging toward the true maximizer as kk grows very large, but for any practical, bounded kk 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 kk 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 kk.

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 tt, 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, −log⁡P(yttrue∣y<ttrue,x)-\log P(y_t^{\text{true}} \mid y_{<t}^{\text{true}}, x). 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.

Before this