Neural Machine Translation

Michael BrenndoerferNovember 26, 202649 min read

Train a toy encoder-decoder Transformer for machine translation. Compare decoding policies, inspect cross-attention weights, and diagnose NMT failure modes.

Language AI HandbookAll chapters
Part 27 of 67Machine Translation and Speech Translation
Chapter 191Neural Machine Translation
Reading the full chapter · 12 sections · 49 min12 sections · 49 min

All 12 sections · 49 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

Neural Machine Translation

A phrase-based statistical machine translation system of the kind described by Koehn et al. (2003) estimates word alignments, extracts phrase pairs, adds target-language scores, and searches over phrase options. See Statistical Machine Translation Foundations for the full pipeline.

Changing an upstream aligner can change the phrase table available to the decoder. To evaluate the change, rebuild the dependent artifacts, retune the feature weights if needed, and compare the completed translations on the same held-out inputs.

A supervised end-to-end NMT baseline trains one conditional neural model on pairs of source and reference sentences. The translation loss updates the components jointly. Explicit phrase tables and alignment labels are unnecessary for the encoder-decoder we build here.

We start with conditional generation and trace the encoder, attention, objective, data, and decoder choices. The worked example trains a small Transformer on a synthetic reordering language. It compares decoding policies and plots cross-attention for one held-out example.

As a quick orientation, you have already built the pieces:

A translation model scores a target sequence conditional on a specific source. Reference-token likelihood rewards assigning probability to the translated text in the data. To check meaning preservation, inspect translations against their sources or use an appropriate evaluation metric.

Neural Machine Translation (NMT)

Neural machine translation uses a neural model to translate a source in one language into another. Our supervised setup learns a conditional distribution P(y∣x)P(y \mid x) from parallel sentence pairs, with source xx and target yy. At inference we search for a target sequence under that model.

The Translation Problem as Conditional Generation

Let the source sentence be a sequence of tokens x=(x1,…,xm)x = (x_1, \dots, x_m) and the target be y=(y1,…,yn)y = (y_1, \dots, y_n). Their lengths and vocabulary sizes can differ. In the likelihood and decoding formulas, a completed target sequence includes its final EOS token. The length nn counts that EOS but excludes the BOS prompt marker and padding. The worked example reports lexical lengths without EOS.

A vocabulary of VV symbols gives VnV^n unrestricted strings of length nn. A completed target uses only a subset of this space because its first EOS is its last token. The chain rule lets us score one candidate by evaluating the model at its successive prefixes. Searching for the best completed sequence still requires a decoding strategy.

We factorize with the chain rule, exactly as any language model does:

P(y∣x)=∏t=1nP(yt∣y<t,x)P(y \mid x) = \prod_{t=1}^{n} P\big(y_t \mid y_{<t}, x\big)

Each factor is a conditional distribution over the target vocabulary given the source and the target prefix. A neural network parameterizes this with weights θ\theta:

Pθ(yt∣y<t,x)=softmax⁡(Wo gθ(y<t,x))ytP_\theta(y_t \mid y_{<t}, x) = \operatorname{softmax}\big(W_o\, g_\theta(y_{<t}, x)\big)_{y_t}

Here gθg_\theta produces a hidden vector of size dd, and Wo∈RV×dW_o \in \mathbb{R}^{V \times d} projects it onto target-vocabulary logits. The subscript yty_t selects the gold token during training. The maximum-likelihood loss takes the negative logarithm of that probability. At inference, the decoder scores candidate continuations, including the end-of-sequence token when ranking completed sequences.

This factorization hides three distinct subproblems that statistical MT attacked separately:

  • Lexical transfer. Which target words correspond to which source words? "Katze" for "cat", but also "chat" and "gato" depending on the language pair. Beyond single words, lexical transfer must handle multi-word expressions ("kick the bucket"), idioms, and collocations that do not decompose word-for-word.
  • Reordering. Consider “because she reads the book” and “weil sie das Buch liest.” The English verb “reads” precedes its object, while “liest” follows its object in the German example. The same source and target positions need not correspond. The model also needs to handle cases where one position corresponds to several, such as an idiom rendered with a longer phrase.
  • Fluency. The target-side language model supplies a separate score in a phrase-based SMT system. To test fluency in an output, inspect whether the words fit the target construction, including agreement and idiomatic phrasing where relevant.

SMT combined these as separate features in a log-linear model:

P(y∣x)∝exp⁡(∑iλifi(x,y))P(y \mid x) \propto \exp\left(\sum_{i} \lambda_i f_i(x, y)\right)

The features can include phrase-translation, lexical, reordering, length, and target-language scores. Och (2003) describes minimum error rate training for tuning feature weights. Koehn et al. (2003) show how to extract phrase pairs from word alignments.

The log-score is a weighted sum of the supplied features. With fixed weights and no interaction feature, its sensitivity to the language-model score is the same whether the phrase-table score is high or low. A feature that combines both scores would let the model express a different relationship.

In the end-to-end model, lexical choices, order, and well-formedness all contribute to the conditional output. We train the components through the same translation loss.

Why joint learning helps

Compare where each design allows the training signal and the source context to enter.

Translation loss can reach the encoder. If phrase extraction excludes a useful phrase pair, that pair is unavailable to that phrase-based decoder. In the differentiable model below, gradients from the translation loss can flow through cross-attention into the encoder. The gradient gives a direction for a parameter update.

The attention weights are continuous. A softmax assigns weights across source positions. The weighted sum and the softmax can be differentiated when training the model. A discrete choice of one alignment would require a different treatment.

The encoder sees surrounding words. Compare “on the bank of the river” with “at the bank to withdraw cash.” In a contextual encoder, the representation at “bank” can depend on those surrounding tokens. Test the two sentences if you want to know whether the model uses the distinction in practice.

What NMT did not fix

When evaluating an NMT system, check the types of failure the intended application cannot tolerate. Four useful diagnostic cases are:

  • Hallucination. The model can produce fluent output with content that appears nowhere in the source.
  • Off-target translation. A multilingual model can silently translate into the wrong language.
  • Length and coverage failures. Compare the source and translation for omitted or repeated content.
  • Sparse training coverage. Inspect how many examples in your bitext cover the intended language pair and domain.

Use these cases when you compare model, preprocessing, and decoding changes.

Encoder-Decoder Translation

An early recurrent design used an LSTM to encode the source and another LSTM to generate the target, as in Sutskever et al. (2014). The Encoder-Decoder Framework gives the general setup.

The encoder reads the source and produces hidden states. A bidirectional RNN runs forward and backward and concatenates:

h→j=RNN⁡fwd(h→j−1,Exxj),h←j=RNN⁡bwd(h←j+1,Exxj)\overrightarrow{h}_j = \operatorname{RNN}_{\text{fwd}}\big(\overrightarrow{h}_{j-1}, E_x x_j\big), \qquad \overleftarrow{h}_j = \operatorname{RNN}_{\text{bwd}}\big(\overleftarrow{h}_{j+1}, E_x x_j\big) hj=[h→j;h←j]h_j = \big[\overrightarrow{h}_j ; \overleftarrow{h}_j\big]

For this bidirectional variant, the forward state depends on the prefix and the backward state depends on the suffix. Concatenating them lets the decoder's source representation incorporate context on both sides of a position.

The decoder is a conditional language model. At step tt it consumes the previous target token and its own previous state:

st=RNN⁡dec(st−1,Eyyt−1)s_t = \operatorname{RNN}_{\text{dec}}\big(s_{t-1}, E_y y_{t-1}\big) P(yt∣y<t,x)=[softmax⁡(Wost+bo)]ytP(y_t \mid y_{<t}, x) = \big[\operatorname{softmax}(W_o s_t + b_o)\big]_{y_t}

During autoregressive inference, the next-token distribution depends on the generated prefix. Decoding proceeds until an end token or a length limit. Each new token supplies part of the context for the next step.

Teacher forcing feeds the reference prefix y<ty_{<t} and scores yty_t. During generation the model uses its own prefix, which can contain earlier errors. Teacher Forcing describes the mismatch.

The fixed-vector bottleneck

In the fixed-vector design, the decoder receives one fixed-size source representation as its initial state. In this simplified notation, s0=hms_0=h_m denotes the final encoder state of a unidirectional encoder. A bidirectional variant can combine the terminal states of both directions.

Increasing the source length leaves the size of this representation fixed. The decoder can use encoded information about a source position only through that initial representation.

In their English-to-French experiment, Sutskever et al. (2014), §§3.3 and 3.5 found that reversing the source improved BLEU. They argued that the reversal shortened some early source-to-target dependencies, while the average distance between corresponding words was unchanged. The reversed-input model translated long sentences well in their length analysis.

Another way to give the decoder access to earlier source information is to retain a representation for each position and let the decoder select among them.

Attention removes the bottleneck

With attention the decoder can form a different weighted sum over the encoder states h1,…,hmh_1, \dots, h_m at each step. We covered the mechanism in Attention Intuition and Bahdanau Attention.

For decoder state st−1s_{t-1} and encoder state hjh_j, compute an energy:

et,j=v⊤tanh⁡(Wsst−1+Whhj)e_{t,j} = v^\top \tanh\big(W_s s_{t-1} + W_h h_j\big)

The energy is a learned score: how relevant is source position jj to the token the decoder is about to produce. The tanh⁡\tanh lets the score depend nonlinearly on both the decoder state and the encoder state, and the vector vv collapses the result to a scalar.

Normalize over source positions:

αt,j=exp⁡(et,j)∑j′=1mexp⁡(et,j′)\alpha_{t,j} = \frac{\exp(e_{t,j})}{\sum_{j'=1}^{m} \exp(e_{t,j'})}

The softmax turns the scores into a distribution over allowed source positions. This row of weights is recomputed at each decoder step.

Form the context vector and feed it into the decoder:

ct=∑j=1mαt,jhj,st=RNN⁡dec(st−1,[Eyyt−1;ct])c_t = \sum_{j=1}^{m} \alpha_{t,j} h_j, \qquad s_t = \operatorname{RNN}_{\text{dec}}\big(s_{t-1}, [E_y y_{t-1} ; c_t]\big)

The decoder can read h3h_3 through the attention sum, without requiring the encoder to carry the same information from position 3 all the way to its final state. Each decoder step still compresses the attended states into one context vector.

Bahdanau et al. (2015) reported that their attentive RNNsearch models held up better on longer English-to-French sentences than their fixed-vector RNNencdec baselines. Their qualitative examples included attention patterns resembling word correspondences, although the training objective used sentence pairs and supplied no word-alignment labels.

Attention as Learned Soft Alignment

The attention matrix α∈Rn×m\alpha \in \mathbb{R}^{n \times m} assigns source-position weights at each target step. A row can serve as a soft alignment diagnostic when compared with known token correspondences.

In the IBM models, each target position has a latent link to one source position or NULL. The model sums over possible alignments, and expectation-maximization can estimate the parameters. A phrase extraction pipeline can consume a set of word links, which you can evaluate using Alignment Error Rate. Multiple targets can link to the same source.

Neural attention is a differentiable weighted sum inside a model trained on translation. Without explicit alignment supervision, the weights are determined by what helps the translation objective.

The differences matter:

  • Soft weights. A row can spread mass across several source positions. Compare the weights with a reference alignment before interpreting that spread as uncertainty about word correspondences.
  • Repeated use of a source position. Several target rows can assign high weights to one source position. IBM Model 3 explicitly models how many target words a source word produces. The attention sum here has no separate fertility variable.
  • Translation objective. The weights can route contextual information that differs from a reference word link. For a known correspondence, compare both the recorded weights and the prediction.
  • Interpretation. Jain and Wallace (2019) found that in some of their NLP models, very different attention distributions could give similar predictions. Wiegreffe and Pinter (2019) emphasized the comparison and controls needed for an explanation. Use a translation heatmap to identify cases for follow-up. To make a causal claim, use a test that intervenes on the quantity of interest.

What attention learns about reordering

Sketch the token correspondences for a specific sentence before inspecting attention. The following examples are candidate comparisons for such a diagnostic.

  • English → French. In “the red book” and “le livre rouge,” mark where “red” links to “rouge” and “book” to “livre.” Those links are off the diagonal.
  • English → German. In the example with “because she reads the book,” trace “reads” to the final “liest.” A content-word link can cover several positions even in a short clause.
  • Japanese → English. Compare “猫が魚を食べる” with “The cat eats fish.” Trace the cat, fish, and eating correspondences before interpreting rows associated with articles or particles.
  • English → Chinese. Compare “three books” with “三本书.” The classifier 本 has no separate English word in that pair. Mark it explicitly before interpreting its target row.

These are reference links for selected phrases. If a trained model's weights differ, inspect the translation and the tokenization before deciding what the difference means.

Attention failure modes

Compare the output with the source before using attention to investigate a failure.

  • Under-translation. If a clause is missing, inspect the source span corresponding to that clause and see how it was attended to during decoding.
  • Over-translation. If a phrase repeats, compare the attention weights at each repetition and check whether they cover the same source region.
  • Source mismatch. If an out-of-domain output changes the meaning, compare it with outputs for an in-domain example and check which source positions the weights emphasize.

The coverage penalty below discourages low cumulative attention on a source position. Once the coverage reaches one, additional weight leaves that source position's contribution unchanged.

The Transformer for Translation

The encoder-decoder Transformer uses attention for communication within the encoder and the decoder, and to pass source information to target predictions.

In a unidirectional RNN, information from source position 1 reaches position 30 through 29 recurrent transitions. In global self-attention, position 30 can read position 1 within one layer. Compare those paths separately from arithmetic cost. The standard dense attention score matrix has m2m^2 entries for a source of length mm.

Self-attention can process the known positions of a training sequence in parallel. Autoregressive inference still generates positions successively. Vaswani et al. (2017), §5.2 report training on eight P100 GPUs for 12 hours for the base models and 3.5 days for the big models. Their Table 2 reports 28.4 BLEU on WMT 2014 English–German and 41.8 on English–French for the big models.

Residual connections provide an additive route around each attention or feed-forward sublayer. A short token-to-token path and a residual path describe the graph. To compare gradient behavior across architectures, measure it under controlled training configurations.

The three attention blocks

An encoder-decoder transformer for translation has three distinct attention operations, and it is worth keeping them straight:

  • Encoder self-attention. Unmasked source positions can attend in both directions, with padded positions excluded as keys.
  • Decoder masked self-attention. Causal, so position tt sees only positions ≤t\le t in the target prefix. This preserves the autoregressive factorization.
  • Decoder cross-attention. Queries come from the decoder, keys and values from the encoder output. In this translation model, cross-attention lets target generation read the source representation.

Cross-attention is the source-conditioning route in this encoder-decoder. Its weights are what we compare with reference correspondences in the worked example below.

Cross-Attention as the Translation Interface

In cross-attention, the decoder's hidden state at step tt forms a query qt=WQht(dec)q_t = W_Q h_t^{(dec)}, and the encoder output forms keys and values kj=WKhj(enc)k_j = W_K h_j^{(enc)}, vj=WVhj(enc)v_j = W_V h_j^{(enc)}. The output is ∑jsoftmax⁡j(qt⊤kj/dk) vj\sum_j \operatorname{softmax}_j(q_t^\top k_j / \sqrt{d_k})\, v_j. The softmax supplies the source weights for the sum.

Configuration choices that matter for MT

Vaswani et al.'s base Transformer used six encoder and six decoder layers, model width 512, eight heads, and feed-forward width 2048. Record the actual memory, latency, and data constraints before choosing a starting configuration.

  • Pre-norm vs. post-norm. The original Transformer placed normalization after each residual addition (§3.1) and used learning-rate warmup (§5.3). Xiong et al. (2020) studied moving normalization inside the residual block and tested removing warmup in their pre-norm configurations. See Pre-Norm vs Post-Norm.
  • Depth vs. width. Vary encoder and decoder depth separately when you want to know which side improves quality for your language pair under a fixed compute budget.
  • Weight tying. If the target embedding and output projection use compatible shapes, sharing a weight matrix removes one separate set of weights. See Weight Tying.
  • Position encoding. Compare absolute and relative position schemes at the input lengths you expect to use. Include document-length examples when the intended application needs document context.

Where decoder-only LLMs fit

A decoder-only Transformer can receive source text and a target-language instruction as a prefix, then generate the translation using causal self-attention. GPT-3 covers a prompted example of this approach. The rest of this chapter uses an encoder-decoder with separate source states.

Training Objective

Training is maximum likelihood estimation on parallel data. Given a corpus D={(x(i),y(i))}i=1N\mathcal{D} = \{(x^{(i)}, y^{(i)})\}_{i=1}^{N}, minimize:

L(θ)=−∑i=1N∑t=1nilog⁡Pθ(yt(i)∣y<t(i),x(i))\mathcal{L}(\theta) = -\sum_{i=1}^{N} \sum_{t=1}^{n_i} \log P_\theta\big(y^{(i)}_t \mid y^{(i)}_{<t}, x^{(i)}\big)

Everything below is a refinement of this objective or a consequence of it.

The inner sum is over target tokens, and the outer sum is over training examples. Summing gives each token a term, so longer examples contribute more terms. Dividing the batch loss by the number of nonpadding target tokens keeps its scale comparable across batches with different token counts. Averaging each sentence first would instead weight sentences equally.

Label smoothing

With a one-hot target the gradient on the gold logit is py−1p_y-1 and that on each other logit is pkp_k. For a fixed example, increasing the gold logit's margin pushes its probability toward one, where those gradients approach zero.

Label smoothing (Szegedy et al., 2016; standard in the transformer paper) replaces the one-hot target with a mixture of the true distribution and the uniform distribution. For vocabulary size KK, smoothing parameter ϵ\epsilon, and gold token yy:

q(k)={1−ϵ+ϵKk=yϵKk≠yq(k) = \begin{cases} 1 - \epsilon + \dfrac{\epsilon}{K} & k = y \\[6pt] \dfrac{\epsilon}{K} & k \neq y \end{cases}

The loss becomes:

L=−∑k=1Kq(k)log⁡pθ(k)=(1−ϵ)(−log⁡pθ(y))+ϵ(−∑k=1K1Klog⁡pθ(k))\mathcal{L} = -\sum_{k=1}^{K} q(k) \log p_\theta(k) = (1-\epsilon)\big(-\log p_\theta(y)\big) + \epsilon \left(-\sum_{k=1}^{K} \frac{1}{K} \log p_\theta(k)\right)

Label smoothing mixes the gold-token and uniform cross-entropy terms. With 0<ϵ≤10<\epsilon\leq 1, the minimum over predictive distributions is H(q)H(q), achieved at pθ=qp_\theta=q. The gradient on logit kk is pθ(k)−q(k)p_\theta(k)-q(k), so a prediction can be too confident even when it chooses the correct token.

Let's see the numbers.

PythonIn [3]
CollapseExpand
import torch
import torch.nn.functional as F

# A 5-token target vocabulary. The model is extremely confident on token 0.
logits = torch.tensor([[6.0, 1.0, 0.5, 0.2, 0.1]])
target = torch.tensor([0])

rows = []
for eps in [0.0, 0.05, 0.1, 0.2]:
    z = logits.clone().requires_grad_(True)
    loss = F.cross_entropy(z, target, label_smoothing=eps)
    loss.backward()
    rows.append((eps, loss.item(), z.grad[0, 0].item(), z.grad[0, 1].item()))
ConsoleOut [4]
CollapseExpand
   eps     loss   grad[correct]   grad[runner-up]
  0.00   0.0165        -0.01632           0.00663
  0.05   0.2385         0.02368          -0.00337
  0.10   0.4605         0.06368          -0.01337
  0.20   0.9045         0.14368          -0.03337

For these logits the gold-token gradient is about −0.016-0.016 without smoothing, so gradient descent raises the gold logit. At ϵ=0.1\epsilon=0.1 the gold target probability is 0.920.92, below the model's prediction of about 0.9840.984. The gold gradient changes sign to about +0.064+0.064, and the runner-up gradient becomes about −0.013-0.013. A descent step lowers the gold logit and raises the runner-up logit.

The figure varies smoothing while holding the logits fixed. The gold-token gradient rises because increasing smoothing lowers the gold target probability. At the model distribution that matches the smoothed target, all logit gradients are zero.

PythonIn [5]
CollapseExpand
eps_values = [row[0] for row in rows]
grad_correct = [row[2] for row in rows]
VisualizationOut [6]
CollapseExpand
Line chart of gradient on the correct token rising as label smoothing epsilon increases.
Gradient on the correct token as a function of label-smoothing epsilon for a highly confident five-token example. At these fixed logits, the signed gold-token gradient crosses zero as smoothing increases.
Label smoothing affects metrics differently

Vaswani et al. reported higher BLEU and worse perplexity with label smoothing in their Transformer setup. Müller, Kornblith, and Hinton reported better calibration in the configurations they studied and less effective distillation from their smoothed teachers. Evaluate perplexity using the unsmoothed reference-token likelihood and report the tokenization and normalization protocol. Vaswani et al. (2017), section 5.4, Müller et al. (2019)

Length bias in the objective

The log-probability of a token prefix cannot increase when another token is appended, since the next log-probability is at most zero. Completed translations include an EOS probability, so two different translations can rank in either order. A decoder can use a length penalty when raw likelihood favors outputs that are too short on the development set.

The next figure isolates the multiplication effect by assigning probability 0.9 to every token. It illustrates one reason to test length normalization. It does not predict the length distribution of a trained translation model.

PythonIn [7]
CollapseExpand
import numpy as np

lengths = np.arange(1, 21)
per_token_prob = 0.9
log_prob = lengths * np.log(per_token_prob)
VisualizationOut [8]
CollapseExpand
Line chart of cumulative log-probability falling linearly with sequence length.
Illustrative cumulative log-probability of a sequence as a function of length when every token has probability 0.9. The score falls linearly with length, illustrating how additional factors affect raw scores when their probabilities are held fixed.

Exposure bias

In teacher forcing the prefix comes from the reference. At inference the prefix can contain generated errors, and changing a token can change later predictions. The Teacher Forcing chapter discusses this exposure mismatch.

Bengio et al. (2015) proposed scheduled sampling, which sometimes feeds a generated token in place of the reference during training. If you compare it with teacher forcing, keep the decoding procedure fixed so the training change can be evaluated separately.

Alternative objectives

The likelihood of the reference and the quality score of a generated translation are different objectives. The following examples change what the learning procedure scores.

  • Minimum risk training (MRT). Minimize expected sentence-level risk, L=Ey∼Pθ(⋅∣x)[R(y,y∗)]\mathcal{L} = \mathbb{E}_{y \sim P_\theta(\cdot \mid x)}[R(y, y^*)]. For quality metrics where higher is better, a possible risk is the negative metric. Shen et al. (2016) approximate the expectation with a sampled set of candidate translations.
  • Sequence-level policy gradient. A reward such as negative risk weights the sampled sequence's log-probability gradient. A baseline that does not depend on the sampled sequence can be subtracted without changing the expected gradient.
  • Quality-based filtering and weighting. Estimate pair quality, then set a filtering threshold or give the pairs different training weights. Keep the held-out set fixed when comparing those choices.
  • Contrastive and ranking objectives. A ranking loss can reward higher scores for references than for sampled negatives. Choose negatives that test the errors you want the model to distinguish.

Keep a teacher-forced likelihood baseline and test each change on the same held-out translation set. Report both the translation metric and what changed in training or decoding.

Log-likelihood evaluates the probability assigned to reference text. BLEU and COMET evaluate generated outputs under different scoring rules. Report the metric you use to choose a model, alongside the objective used to train it.

Data, Preprocessing, and Subword Vocabulary

Before changing model size, audit the bitext for language, domain, and alignment quality. Compare corpus and architecture changes separately if you want to attribute the result to one of them.

Hold the architecture fixed while testing corpus size or filtering. Hold the corpus fixed while testing architecture. Report the training and evaluation domains in both comparisons.

Parallel corpora

Examples of parallel data sources include:

  • Curated documents: Europarl contains European Parliament proceedings. The UN Parallel Corpus collects official United Nations documents.
  • Mined bitext: ParaCrawl, CCMatrix, and WikiMatrix extract candidate sentence pairs from existing text. Screening can remove mismatched pairs and other noise.
  • Human-translated seed data: NLLB-Seed pairs Wikipedia-domain sentences with professional translations.
  • Domain corpora: The OPUS catalogue lists parallel corpora in multiple domains. Select material that matches the task and measure performance on a held-out sample from that setting.
  • Synthetic bitext: Back-translate target-side text when suitable parallel examples are limited. The next section shows how.

Cleaning

Audit the candidate pairs and choose filters based on the errors you observe.

  • Language identification on both sides. If the English side is French, the pair is mislabeled. See Language Identification.
  • Length ratio filtering. An example flag is ∣y∣/∣x∣|y|/|x| outside [0.5,2.5][0.5, 2.5] after tokenization, with a positive source length. Pilot the threshold in a specific direction and inspect flagged examples for valid but asymmetric translations.
  • Exact and near deduplication. Repeated pairs appear repeatedly in a per-example sum. If they are unintended, inspect and deduplicate them. See Deduplication and MinHash.
  • Source–target similarity heuristics. Compare character overlap on sample pairs you have verified before making it a rejection criterion. A translation written in a different script can have little overlap.
  • Model-based filtering. Score both sides with a bilingual model or quality estimator. Inspect how the score separates plausible pairs from known mismatches before setting a threshold.

We go deeper on mining and quality control in the next chapter, Parallel Data Mining and Quality Control.

Back-translation

Sennrich, Haddow, and Birch (2016) generated synthetic source text from target-language monolingual data. In this setup:

  1. Train a reverse model Pθ(x∣y)P_\theta(x \mid y) on the available parallel data.
  2. Select monolingual target-side sentences in a domain you want the forward model to handle.
  3. Translate it into the source language with the reverse model, producing synthetic pairs (x^,y)(\hat{x}, y).
  4. Add the synthetic pairs to the training data for the forward model and retrain.

The target side is the original monolingual text. The source is the reverse model's output. Edunov et al. (2018) compared ways of generating that synthetic source, including sampling and beam search. Caswell et al. (2019) tested adding a tag to distinguish synthetic pairs during forward training.

Inspect the synthetic source for missing content and mistranslated names. Keep trustworthy parallel data in the mixture and compare results on real source inputs when testing whether the added data helps.

Subword tokenization

A closed word vocabulary needs an unknown-token rule for words it does not contain. A subword tokenizer can represent many unseen words as sequences of pieces. SentencePiece can train and tokenize from raw text without a separate word pretokenizer. Kudo and Richardson (2018).

Three decisions dominate subword setup for MT:

  • Shared vs. separate vocabularies. A shared vocabulary allows matching subwords to share representations if the weights are tied. Compare it with separate vocabularies by measuring held-out translation quality, fragmentation, and coverage for each language.
  • Vocabulary size. Compare candidate sizes at a fixed training and evaluation budget. If common spans split into many pieces, record the extra tokens. If you add rare pieces, inspect how often the training data contains them.
  • Fertility. Here this means the number of subword tokens per word under a specified tokenizer and word segmentation. If two versions of comparable text use different token counts, the longer version consumes more of a fixed token budget. Report the tokenizer and the per-language distributions. See Multilingual Tokenization and Vocabulary Allocation.

Batching and masking

Two details that cause real bugs if you get them wrong:

  • Batch by token count when sequence length varies. For example, a batch of 32 eight-token sentences has 256 tokens before adding padding or special tokens. Sort or bucket similar lengths and use a fixed token budget when you need to control batch size.
  • Padding. If PAD is a batching symbol, exclude its source positions from attention keys and its target labels from the loss. In the implementation below, a key padding mask and ignore_index=PAD_ID apply those two rules.

The example's closed vocabulary contains 13 ordinary word types on each side. Four reserved symbols bring each vocabulary to 17 entries. Word-level tokenization is sufficient for that fixture.

Decoding: Turning Probabilities Into Translations

Training gives you Pθ(y∣x)P_\theta(y \mid x). Decoding is the search problem:

y^=arg⁡max⁡y∈Y∗Pθ(y∣x)\hat{y} = \arg\max_{y \in \mathcal{Y}^*} P_\theta(y \mid x)

With a maximum length and a finite vocabulary, you can enumerate all candidate strings exactly, but their number grows exponentially with the length limit. Beam search reduces how many prefixes are expanded and can miss the optimal completed sequence.

Hold model weights fixed when comparing decoders. Measure both the outputs and their costs on the same inputs.

Greedy decoding

Greedy decoding picks the highest-probability next token at each step. One locally best choice can lead to a lower-scoring complete sequence than another first choice. Use greedy when you want a one-hypothesis baseline and measure its quality and latency.

If a wider beam changes the output, compare the two sequences under the same scoring rule. Inspect whether the score increase also improves the evaluation metric.

Maintain kk partial hypotheses. At each step, expand every hypothesis by every vocabulary item, score by cumulative log-probability, and keep the top kk overall. We covered the algorithm in Beam Search; the translation-specific details are:

  • Beam size. Expanding every vocabulary item for each of kk active prefixes considers up to kVkV next-token candidates at a step. The latency also depends on how you batch and cache model states. Tune width using held-out translation quality and latency.
  • Length normalization. Completed outputs of different lengths can rank in either order under raw likelihood. On a development set, check whether short outputs are favored. Wu et al. (2016) used this length penalty:
lp(y)=(5+∣y∣6)α,score(y)=log⁡Pθ(y∣x)lp(y)\text{lp}(y) = \left(\frac{5 + |y|}{6}\right)^{\alpha}, \qquad \text{score}(y) = \frac{\log P_\theta(y \mid x)}{\text{lp}(y)}

The normalization equals one at length one. For positive α\alpha it increases with length, with linear growth only when α=1\alpha=1. Tune α\alpha using the decoder and development set you will evaluate.

  • Coverage penalty. Wu et al. also add a term for low cumulative coverage, with nonnegative β\beta:
cp(x,y)=β∑i=1mlog⁡ ⁣(min⁡ ⁣(∑t=1nαt,i, 1.0))\text{cp}(x, y) = \beta \sum_{i=1}^{m} \log\!\left(\min\!\left(\sum_{t=1}^{n} \alpha_{t,i},\ 1.0\right)\right)

The inner sum is the total attention assigned to source position ii. The cap at one prevents any additional reward for that position once it is covered. For β>0\beta>0, a position with zero cumulative attention contributes negative infinity before any numerical flooring. When β=0\beta=0, omit the coverage term.

  • Stopping. Keep completed hypotheses separate and use a stopping rule suited to the objective. Reaching the first EOS can leave better candidates unexplored, especially if final scores include length or coverage terms. Use a maximum length as an explicit fallback.

The beam search curse

Koehn and Knowles (2017) reported conditions where widening the beam decreased BLEU. A search algorithm can improve model score while worsening a separate evaluation metric. Use the same scoring rule for all returned outputs when tracking model scores across a sweep.

There are two distinct problems:

  • Model error. If the model assigns a higher score to an unsuitable output, finding that output more reliably does not improve translation. Stahlberg and Byrne (2019) found that for many sentences in their studied Transformer the highest-scoring output under raw likelihood was empty.
  • Search error. Under a fixed scoring rule, an approximate decoder makes a search error if it returns a sequence with a lower score than one it missed. Compare with exhaustive search on a tiny fixture if you want to isolate search error from score quality.

On a development set, compare widths and length settings and record latency. Reranking is another option: generate an nn-best list and score its members with a different criterion. A reference-based metric is useful offline when a reference exists. A deployment reranker needs a score it can compute from the available inputs.

Sampling

Temperature, top-kk, and top-pp change the distribution used to sample output. If the use calls for one translation, compare sampling with a deterministic baseline. Sampling is also a way to generate multiple candidates, including synthetic sources in the back-translation experiments cited above.

Constrained decoding

Write down any functional requirement that must hold even when the model gives a higher score to an output that violates it.

  • Terminology constraints. A glossary may require “cloud” to be translated as “nuage” in a specified context. Post and Vilar (2018) group candidates by the number of constraint tokens they satisfy and allocate a fixed beam budget across groups. Dinu et al. (2019) instead train the model to apply supplied terms.
  • Placeholders and markup. When the format requires {name} or <b> verbatim, check the generated string explicitly. You can restrict the decoder to eligible candidates, then check that the placeholder or markup survived. The Copy Mechanism chapter covers a related learned approach.
  • Length control. A subtitle may have a maximum number of characters or time on screen. Put that budget in the scoring or acceptance rule and test it on generated subtitles.
  • Formatting. When dates or units must follow a locale-specific convention, validate the output against the requested format and apply an appropriate formatter if needed.

Worked Example: A Toy Reordering Language

We train and evaluate a small transformer on Mirror, a synthetic target language. Two deterministic rules generate its base translations:

  1. Full reordering. The target is the source in reverse word order.
  2. Lexical substitution. The definite article "the" becomes "der".

With these rules, “the big cat sees a small dog” becomes “dog small a sees cat big der.” In the seeded corpus, each occurrence of “the” is independently dropped with probability 0.15 during target generation. The reverse order supplies a reference correspondence for the retained words.

The synthetic corpus lets us compare decoders by exact match against one sampled target per input. If the reference drops an article, a prediction that includes it loses exact-match credit even when its other words follow both deterministic rules.

Generating the corpus

The generator samples source sentences of five or seven words. Reversal and substitution preserve length, and randomly dropping definite articles can shorten targets. Excluding the special markers, sampled targets in this fixture range from three to seven words.

PythonIn [9]
CollapseExpand
import math
import random

import torch
import torch.nn as nn
import torch.nn.functional as F

SEED = 13
random.seed(SEED)
torch.manual_seed(SEED)
device = torch.device("cpu")
# The tiny batches use one CPU thread throughout this notebook.
torch.set_num_threads(1)

DETS = ["the", "a"]
ADJS = ["big", "small", "red", "blue"]
NOUNS = ["cat", "dog", "bird", "fox"]
VERBS = ["sees", "chases", "likes"]


def make_sentence(rng):
    """Sample a source sentence from one of two templates."""
    if rng.random() < 0.5:
        return [
            rng.choice(DETS),
            rng.choice(ADJS),
            rng.choice(NOUNS),
            rng.choice(VERBS),
            rng.choice(DETS),
            rng.choice(ADJS),
            rng.choice(NOUNS),
        ]
    return [
        rng.choice(DETS),
        rng.choice(NOUNS),
        rng.choice(VERBS),
        rng.choice(DETS),
        rng.choice(NOUNS),
    ]


def to_mirror(tokens):
    """Mirror language: reverse the order and map 'the' -> 'der'."""
    return ["der" if t == "the" else t for t in reversed(tokens)]


def to_mirror_noisy(tokens, rng, drop_prob=0.15):
    """Mirror language with a learned exception: some articles are dropped.

    Independent random deletions make the observed target ambiguous, even when
    the deterministic reversal and substitution are known.
    """
    out = []
    for t in reversed(tokens):
        if t == "the":
            if rng.random() < drop_prob:
                continue
            out.append("der")
        else:
            out.append(t)
    return out
PythonIn [10]
CollapseExpand
rng = random.Random(SEED)
seen, pairs = set(), []
while len(pairs) < 900:
    src_tokens = make_sentence(rng)
    key = tuple(src_tokens)
    if key in seen:
        continue
    seen.add(key)
    pairs.append((src_tokens, to_mirror_noisy(src_tokens, rng)))

rng.shuffle(pairs)
train_pairs, test_pairs = pairs[:800], pairs[800:]
ConsoleOut [11]
CollapseExpand
Training pairs: 800
Test pairs:     100
  the small fox likes a blue fox                -> fox blue a likes fox small der
  a red cat likes a big cat                     -> cat big a likes cat red a
  a blue bird likes a blue bird                 -> bird blue a likes bird blue a

The model is trained to learn reversal and substitution. The sampled references can omit definite articles. The source tells you the positions where omission is possible, while the random draws determine which articles the sampled target drops. Exact match compares one sampled reference per input.

Building vocabularies

We build separate source and target vocabularies with four reserved symbols. PAD is index 0 because we will use it as the ignore_index in the loss and as the padding_idx in the embeddings.

PythonIn [12]
CollapseExpand
PAD, BOS, EOS, UNK = "<pad>", "<bos>", "<eos>", "<unk>"
PAD_ID, BOS_ID, EOS_ID, UNK_ID = 0, 1, 2, 3

src_itos = [PAD, BOS, EOS, UNK] + sorted({t for s, _ in train_pairs for t in s})
tgt_itos = [PAD, BOS, EOS, UNK] + sorted({t for _, t in train_pairs for t in t})
src_stoi = {t: i for i, t in enumerate(src_itos)}
tgt_stoi = {t: i for i, t in enumerate(tgt_itos)}


def encode(tokens, stoi, bos=False, eos=True):
    """Map tokens to ids, optionally wrapping with BOS/EOS."""
    ids = [stoi.get(t, UNK_ID) for t in tokens]
    if bos:
        ids = [stoi[BOS]] + ids
    if eos:
        ids = ids + [stoi[EOS]]
    return ids
ConsoleOut [13]
CollapseExpand
Source vocabulary (17): ['<pad>', '<bos>', '<eos>', '<unk>', 'a', 'big', 'bird', 'blue', 'cat', 'chases', 'dog', 'fox', 'likes', 'red', 'sees', 'small', 'the']
Target vocabulary (17): ['<pad>', '<bos>', '<eos>', '<unk>', 'a', 'big', 'bird', 'blue', 'cat', 'chases', 'der', 'dog', 'fox', 'likes', 'red', 'sees', 'small']

The source vocabulary includes the and the target vocabulary includes der. The model below uses separate source and target embedding tables. That choice is independent of the target embedding–output tie.

Batching with padding and masks

The batch builder produces three tensors: the source (with EOS), the decoder input (BOS + target, no EOS), and the decoder target (target + EOS, no BOS). This shift-by-one is the standard teacher-forcing arrangement.

PythonIn [14]
CollapseExpand
def make_batch(batch):
    src = [torch.tensor(encode(s, src_stoi, eos=True)) for s, _ in batch]
    tgt_in = [
        torch.tensor(encode(t, tgt_stoi, bos=True, eos=False)) for _, t in batch
    ]
    tgt_out = [
        torch.tensor(encode(t, tgt_stoi, bos=False, eos=True)) for _, t in batch
    ]
    src = nn.utils.rnn.pad_sequence(src, batch_first=True, padding_value=PAD_ID)
    tgt_in = nn.utils.rnn.pad_sequence(
        tgt_in, batch_first=True, padding_value=PAD_ID
    )
    tgt_out = nn.utils.rnn.pad_sequence(
        tgt_out, batch_first=True, padding_value=PAD_ID
    )
    return src.to(device), tgt_in.to(device), tgt_out.to(device)
ConsoleOut [15]
CollapseExpand
source ids      : [[4, 8, 14, 16, 6, 2, 0, 0], [16, 15, 11, 12, 4, 7, 11, 2]]
decoder input   : [[1, 6, 15, 8, 4, 0, 0, 0], [1, 12, 7, 4, 13, 12, 16, 10]]
decoder target  : [[6, 15, 8, 4, 2, 0, 0, 0], [12, 7, 4, 13, 12, 16, 10, 2]]
source key mask : [[False, False, False, False, False, False, True, True], [False, False, False, False, False, False, False, False]]
target loss mask: [[True, True, True, True, True, False, False, False], [True, True, True, True, True, True, True, True]]

The short row shows padding after the source and target sequences. In key_padding_mask, True masks the corresponding key/value column before the attention softmax. A padded query can still produce an output. The target loss mask marks labels that count toward the loss. The loss uses ignore_index=PAD_ID to exclude the other labels.

The model

We build a pre-norm transformer encoder-decoder. Three pieces: sinusoidal position encoding, an encoder layer with self-attention, and a decoder layer with masked self-attention plus cross-attention.

PythonIn [16]
CollapseExpand
class PositionalEncoding(nn.Module):
    """Fixed sinusoidal position signal, added to token embeddings."""

    def __init__(self, d_model, max_len=64):
        super().__init__()
        pe = torch.zeros(max_len, d_model)
        pos = torch.arange(max_len).unsqueeze(1).float()
        div = torch.exp(
            torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)
        )
        pe[:, 0::2] = torch.sin(pos * div)
        pe[:, 1::2] = torch.cos(pos * div)
        self.register_buffer("pe", pe)

    def forward(self, x):
        return x + self.pe[: x.size(1)].unsqueeze(0)
PythonIn [17]
CollapseExpand
class EncoderLayer(nn.Module):
    """Pre-norm self-attention block with a feed-forward sublayer."""

    def __init__(self, d_model, n_heads, d_ff, dropout=0.1):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(
            d_model, n_heads, dropout=dropout, batch_first=True
        )
        self.ff = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model)
        )
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.drop = nn.Dropout(dropout)

    def forward(self, x, src_key_padding_mask):
        h = self.norm1(x)
        a, _ = self.self_attn(
            h, h, h, key_padding_mask=src_key_padding_mask, need_weights=False
        )
        x = x + self.drop(a)
        h = self.norm2(x)
        return x + self.drop(self.ff(h))

The decoder layer has the extra cross-attention sublayer. We return its weights when asked, so we can visualize the alignment later.

PythonIn [18]
CollapseExpand
class DecoderLayer(nn.Module):
    """Pre-norm block with masked self-attention and cross-attention."""

    def __init__(self, d_model, n_heads, d_ff, dropout=0.1):
        super().__init__()
        self.self_attn = nn.MultiheadAttention(
            d_model, n_heads, dropout=dropout, batch_first=True
        )
        self.cross_attn = nn.MultiheadAttention(
            d_model, n_heads, dropout=dropout, batch_first=True
        )
        self.ff = nn.Sequential(
            nn.Linear(d_model, d_ff), nn.ReLU(), nn.Linear(d_ff, d_model)
        )
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.norm3 = nn.LayerNorm(d_model)
        self.drop = nn.Dropout(dropout)

    def forward(
        self,
        x,
        memory,
        tgt_mask,
        tgt_key_padding_mask,
        memory_key_padding_mask,
        return_attn=False,
    ):
        h = self.norm1(x)
        a, _ = self.self_attn(
            h,
            h,
            h,
            attn_mask=tgt_mask,
            key_padding_mask=tgt_key_padding_mask,
            need_weights=False,
        )
        x = x + self.drop(a)

        h = self.norm2(x)
        c, w = self.cross_attn(
            h,
            memory,
            memory,
            key_padding_mask=memory_key_padding_mask,
            need_weights=return_attn,
        )
        x = x + self.drop(c)

        h = self.norm3(x)
        return x + self.drop(self.ff(h)), w

Now the full model. Note the weight tying between the target embedding and the output projection: it saves parameters and helps the model keep input and output token representations consistent.

PythonIn [19]
CollapseExpand
class TransformerMT(nn.Module):
    """Minimal transformer encoder-decoder for sequence-to-sequence translation."""

    def __init__(
        self,
        src_vocab_size,
        tgt_vocab_size,
        d_model=64,
        n_heads=4,
        n_layers=2,
        d_ff=128,
        dropout=0.1,
    ):
        super().__init__()
        self.d_model = d_model
        self.src_embed = nn.Embedding(
            src_vocab_size, d_model, padding_idx=PAD_ID
        )
        self.tgt_embed = nn.Embedding(
            tgt_vocab_size, d_model, padding_idx=PAD_ID
        )
        self.src_pos = PositionalEncoding(d_model)
        self.tgt_pos = PositionalEncoding(d_model)
        self.encoder_layers = nn.ModuleList(
            [
                EncoderLayer(d_model, n_heads, d_ff, dropout)
                for _ in range(n_layers)
            ]
        )
        self.decoder_layers = nn.ModuleList(
            [
                DecoderLayer(d_model, n_heads, d_ff, dropout)
                for _ in range(n_layers)
            ]
        )
        self.norm_out = nn.LayerNorm(d_model)
        self.out = nn.Linear(d_model, tgt_vocab_size)
        self.out.weight = (
            self.tgt_embed.weight
        )  # Share the complete target embedding matrix.

    def encode(self, src, src_key_padding_mask):
        x = self.src_pos(self.src_embed(src) * math.sqrt(self.d_model))
        for layer in self.encoder_layers:
            x = layer(x, src_key_padding_mask)
        return x

    def decode(
        self, tgt_in, memory, memory_key_padding_mask, return_attn=False
    ):
        length = tgt_in.size(1)
        tgt_mask = torch.triu(
            torch.ones(length, length, dtype=torch.bool, device=tgt_in.device),
            diagonal=1,
        )
        tgt_kpm = tgt_in == PAD_ID
        x = self.tgt_pos(self.tgt_embed(tgt_in) * math.sqrt(self.d_model))
        attn = None
        for layer in self.decoder_layers:
            x, w = layer(
                x,
                memory,
                tgt_mask,
                tgt_kpm,
                memory_key_padding_mask,
                return_attn,
            )
            if return_attn:
                attn = w
        logits = self.out(self.norm_out(x))
        return (logits, attn) if return_attn else logits
ConsoleOut [20]
CollapseExpand
Parameters: 169,745
Device:     cpu

This model has 169,745 parameters, about 1/383 of the 65 million reported for the original Transformer base configuration. The output layer and target embedding share the same 17×6417\times64 matrix. Vaswani et al. (2017), Table 3

Training

We use Adam with the Noam learning-rate schedule from the transformer paper: linear warmup followed by inverse-square-root decay.

lr(step)=dmodel−0.5⋅min⁡(step−0.5, step⋅warmup−1.5)\text{lr}(\text{step}) = d_{\text{model}}^{-0.5} \cdot \min\left(\text{step}^{-0.5},\ \text{step} \cdot \text{warmup}^{-1.5}\right)

The label_smoothing=0.1 in the loss is the term we analyzed earlier, applied for real.

PythonIn [21]
CollapseExpand
def train_model(
    model, data, epochs=70, batch_size=32, warmup=300, label_smoothing=0.1
):
    opt = torch.optim.Adam(
        model.parameters(), lr=1.0, betas=(0.9, 0.98), eps=1e-9
    )
    history = {"epoch": [], "loss": [], "tok_acc": []}
    step = 0

    for epoch in range(1, epochs + 1):
        model.train()
        rng.shuffle(data)
        ep_loss, ep_correct, ep_total = 0.0, 0, 0

        for i in range(0, len(data), batch_size):
            src, tgt_in, tgt_out = make_batch(data[i : i + batch_size])
            step += 1
            lr = model.d_model**-0.5 * min(step**-0.5, step * warmup**-1.5)
            for group in opt.param_groups:
                group["lr"] = lr

            src_kpm = src == PAD_ID
            memory = model.encode(src, src_kpm)
            logits = model.decode(tgt_in, memory, src_kpm)
            loss = F.cross_entropy(
                logits.reshape(-1, logits.size(-1)),
                tgt_out.reshape(-1),
                ignore_index=PAD_ID,
                label_smoothing=label_smoothing,
            )

            opt.zero_grad()
            loss.backward()
            nn.utils.clip_grad_norm_(model.parameters(), 1.0)
            opt.step()

            mask = tgt_out != PAD_ID
            ep_loss += loss.item() * mask.sum().item()
            ep_correct += ((logits.argmax(-1) == tgt_out) & mask).sum().item()
            ep_total += mask.sum().item()

        history["epoch"].append(epoch)
        history["loss"].append(ep_loss / ep_total)
        history["tok_acc"].append(ep_correct / ep_total)

    return history
PythonIn [22]
CollapseExpand
training_smoothing = 0.1
history = train_model(model, train_pairs, label_smoothing=training_smoothing)
vocab_size = len(tgt_itos)
uniform_mass = training_smoothing / vocab_size
gold_mass = 1 - training_smoothing + uniform_mass
loss_floor = -gold_mass * math.log(gold_mass) - (
    vocab_size - 1
) * uniform_mass * math.log(uniform_mass)
ConsoleOut [23]
CollapseExpand
epoch   1  loss 50.9890  token acc 0.0000
epoch   5  loss 1.7101  token acc 0.5444
epoch  10  loss 1.1861  token acc 0.7398
epoch  20  loss 0.8548  token acc 0.8894
epoch  40  loss 0.6803  token acc 0.9725
epoch  70  loss 0.6432  token acc 0.9770

Loss generally decreases and teacher-forced accuracy rises. The smoothed objective has a lower bound of H(q)=−∑kq(k)log⁡q(k)H(q)=-\sum_k q(k)\log q(k) per nonpadding target, about 0.57 nats for K=17K=17 and ϵ=0.1\epsilon=0.1. The observed loss can remain above this bound because the model need not predict each smoothed target distribution exactly.

VisualizationOut [24]
CollapseExpand
Two views of training cross-entropy. The late-epoch panel shows the observed curve above the dashed theoretical lower bound.
Smoothed token cross-entropy over 70 training epochs. The full run uses a logarithmic loss axis. The final 31 epochs use a linear loss axis to show the gap between the observed loss and the 0.57-nat theoretical lower bound.

The theoretical floor provides a reference for the loss curve. The accuracy curve measures how often the gold token has the highest predicted probability.

VisualizationOut [25]
CollapseExpand
Line chart of teacher-forced token accuracy rising from zero to near one over 70 epochs.
Teacher-forced token accuracy on the training set. It measures the model's next-token predictions when it receives the observed target prefix.

Teacher-forced accuracy scores individual predictions given a reference prefix. To assess free-running translation, decode complete outputs and compare them with references under a sequence-level metric.

Decoding implementations

Greedy decoding reruns the decoder on the full prefix at each step without caching its keys and values. This keeps the toy implementation short. A production benchmark should measure the cost of recomputing the prefix.

PythonIn [26]
CollapseExpand
@torch.no_grad()
def greedy_decode(model, src, max_len=16):
    model.eval()
    src_kpm = src == PAD_ID
    memory = model.encode(src, src_kpm)
    ys = torch.full(
        (src.size(0), 1), BOS_ID, dtype=torch.long, device=src.device
    )
    finished = torch.zeros(src.size(0), dtype=torch.bool, device=src.device)

    for _ in range(max_len):
        logits = model.decode(ys, memory, src_kpm)
        next_logits = logits[:, -1]
        next_logits[:, [PAD_ID, BOS_ID]] = float("-inf")
        nxt = next_logits.argmax(-1).masked_fill(finished, PAD_ID)
        ys = torch.cat([ys, nxt.unsqueeze(1)], dim=1)
        finished |= nxt == EOS_ID
        if finished.all():
            break

    return ys[:, 1:].cpu()

For each sentence, the beam keeps the highest raw scores among live prefixes. At each step it also scores EOS continuations and records the best completed output by length-normalized score. EOS counts toward length. At the cap, return the best recorded completion if one exists. If none exists, return the best live prefix from the last step with a finite score. If none was generated, return an empty unfinished output.

PythonIn [27]
CollapseExpand
@torch.no_grad()
def beam_search(model, src, beam_size=4, max_len=16, length_penalty=1.0):
    if beam_size < 1 or max_len < 0:
        raise ValueError(
            "beam_size must be positive and max_len must be nonnegative"
        )

    model.eval()
    B = src.size(0)
    K = beam_size
    V = len(tgt_itos)

    src_kpm = src == PAD_ID
    memory = model.encode(src, src_kpm).repeat_interleave(K, dim=0)
    mem_kpm = src_kpm.repeat_interleave(K, dim=0)

    ys = torch.full((B, K, 1), BOS_ID, dtype=torch.long, device=src.device)
    score_dtype = torch.promote_types(memory.dtype, torch.float32)
    scores = torch.full(
        (B, K), float("-inf"), dtype=score_dtype, device=src.device
    )
    scores[:, 0] = 0.0
    completed = torch.full(
        (B, max_len), PAD_ID, dtype=torch.long, device=src.device
    )
    completed_scores = scores.new_full((B,), float("-inf"))
    fallback = torch.full_like(completed, PAD_ID)
    fallback_scores = scores.new_zeros(B)
    rows = torch.arange(B, device=src.device)

    for step in range(max_len):
        logits = model.decode(ys.flatten(0, 1), memory, mem_kpm)[:, -1]
        score_dtype = torch.promote_types(scores.dtype, logits.dtype)
        scores = scores.to(score_dtype)
        completed_scores = completed_scores.to(score_dtype)
        fallback_scores = fallback_scores.to(score_dtype)
        log_probs = F.log_softmax(logits, dim=-1, dtype=score_dtype).view(
            B, K, V
        )
        log_probs[:, :, [PAD_ID, BOS_ID]] = float("-inf")
        log_probs = log_probs.masked_fill(
            ~torch.isfinite(log_probs), float("-inf")
        )
        candidates = scores.unsqueeze(-1) + log_probs

        eos_scores, eos_parents = candidates[:, :, EOS_ID].max(dim=1)
        eos_scores /= ((6.0 + step) / 6.0) ** length_penalty
        improved = eos_scores > completed_scores
        completed[improved, :] = PAD_ID
        completed[improved, :step] = ys[
            rows[improved], eos_parents[improved], 1:
        ]
        completed[improved, step] = EOS_ID
        completed_scores[improved] = eos_scores[improved]

        candidates[:, :, EOS_ID] = float("-inf")
        scores, top_idx = candidates.reshape(B, K * V).topk(K, dim=1)
        parents = top_idx // V
        next_ids = (top_idx % V).masked_fill(~torch.isfinite(scores), PAD_ID)
        ys = torch.cat(
            [ys[rows[:, None], parents], next_ids.unsqueeze(-1)], dim=-1
        )
        has_live = torch.isfinite(scores[:, 0])
        fallback[has_live, : step + 1] = ys[has_live, 0, 1:]
        fallback_scores[has_live] = (
            scores[has_live, 0] / ((6.0 + step) / 6.0) ** length_penalty
        )
        if not has_live.any():
            break

    missing = ~torch.isfinite(completed_scores)
    completed[missing] = fallback[missing]
    completed_scores[missing] = fallback_scores[missing]
    return completed.cpu(), completed_scores.cpu()

The ID parser keeps EOS completion separate from the visible token list. Exact match requires both the reference tokens and an EOS. An unfinished row stays in the denominator.

PythonIn [28]
CollapseExpand
def unpack_decoded(seq):
    """Return lexical IDs and whether EOS ended the sequence."""
    ids = []
    for tok in seq.tolist():
        if tok in (EOS_ID, PAD_ID):
            return ids, tok == EOS_ID
        ids.append(tok)
    return ids, False


def batch_src(data):
    src = [torch.tensor(encode(s, src_stoi)) for s, _ in data]
    return nn.utils.rnn.pad_sequence(
        src, batch_first=True, padding_value=PAD_ID
    ).to(device)


def exact_match(preds, data):
    if not data or len(preds) != len(data):
        raise ValueError(
            "exact match requires one prediction for each of a nonempty set of references"
        )
    golds = [encode(t, tgt_stoi, eos=False) for _, t in data]
    return sum(
        ended and ids == gold for (ids, ended), gold in zip(preds, golds)
    ) / len(golds)

Greedy results

PythonIn [29]
CollapseExpand
src_test = batch_src(test_pairs)
greedy_out = greedy_decode(model, src_test, max_len=16)
greedy_preds = [unpack_decoded(seq) for seq in greedy_out]
greedy_exact = exact_match(greedy_preds, test_pairs)
ConsoleOut [30]
CollapseExpand
Greedy exact match: 0.810

OK  src : a red fox chases the red cat
     gold: cat red der chases fox red a
     pred: cat red der chases fox red a
OK  src : a big fox chases a blue cat
     gold: cat blue a chases fox big a
     pred: cat blue a chases fox big a
OK  src : a big fox chases the red cat
     gold: cat red der chases fox big a
     pred: cat red der chases fox big a
ERR src : the blue fox sees the red cat
     gold: cat red sees fox blue der
     pred: cat red der sees fox blue der
OK  src : a big fox chases a red cat
     gold: cat red a chases fox big a
     pred: cat red a chases fox big a

Greedy exact match gives a baseline on the held-out sources. A prediction can disagree with the single sampled reference even when it obeys the deterministic reversal and substitution, because the reference may omit the article randomly.

Comparing decoding settings

PythonIn [31]
CollapseExpand
beam_sizes = [1, 2, 4, 8]
beam_exact = {}
beam_mean_len = {}
beam_completed = {}

for k in beam_sizes:
    if k == 1:
        preds = greedy_preds
    else:
        out, _ = beam_search(
            model, src_test, beam_size=k, max_len=16, length_penalty=1.0
        )
        preds = [unpack_decoded(seq) for seq in out]
    beam_exact[k] = exact_match(preds, test_pairs)
    beam_mean_len[k] = sum(len(ids) for ids, _ in preds) / len(preds)
    beam_completed[k] = sum(ended for _, ended in preds)
ConsoleOut [32]
CollapseExpand
Decoding setting    exact match   mean length  EOS rows
Greedy                    0.810          6.54       100
Beam 2                    0.810          6.54       100
Beam 4                    0.810          6.54       100
Beam 8                    0.810          6.54       100
VisualizationOut [33]
CollapseExpand
Four equal exact-match bars for greedy decoding and length-penalized beam search at widths two, four, and eight.
Held-out exact match for greedy decoding and length-penalized beam search at widths 2, 4, and 8. The comparison scores one sampled reference per source. A higher model score need not improve exact match.

Greedy and beam search at widths 2, 4, and 8 complete all 100 outputs with EOS, achieve 81% exact match, and produce 6.54 lexical tokens per output on average. The beam settings rank completed outputs with a length penalty. This sweep reports held-out accuracy, lexical length, and completion under each policy, with one sampled reference per source. When comparing model scores across decoding settings, evaluate the outputs with the same scoring rule.

What the cross-attention learned

For an undropped Mirror sentence, the known word correspondence runs in reverse order. The heatmap lets us compare that reference with the decoder's attention in one held-out example, including the EOS positions.

We switch the model to evaluation mode, feed the gold target prefix (teacher forcing), and read the cross-attention weights from the final decoder layer, averaged over heads.

PythonIn [34]
CollapseExpand
ex_src_tokens, ex_tgt_tokens = test_pairs[0]
ex_src_ids = torch.tensor([encode(ex_src_tokens, src_stoi)]).to(device)
ex_tgt_ids = torch.tensor(
    [[BOS_ID] + encode(ex_tgt_tokens, tgt_stoi, eos=False)]
).to(device)

model.eval()
with torch.no_grad():
    ex_memory = model.encode(ex_src_ids, ex_src_ids == PAD_ID)
    _, ex_attn = model.decode(
        ex_tgt_ids, ex_memory, ex_src_ids == PAD_ID, return_attn=True
    )

attn_matrix = ex_attn[0].cpu().numpy()
col_labels = ex_src_tokens + [EOS]
row_labels = ex_tgt_tokens + [EOS]
VisualizationOut [35]
CollapseExpand
Heatmap of final-layer cross-attention for one held-out example, with the encoder tokens across columns and the next target tokens down the rows.
Cross-attention weights from the final decoder layer for one test sentence, averaged over heads. Rows name the next tokens under teacher forcing and columns name encoder tokens, including the source end-of-sequence marker.

The model receives no explicit alignment labels, and attention need not place all its mass on the token a human would align to that prediction. A final-layer, head-averaged heatmap is a diagnostic of the recorded weights. It cannot show on its own which source tokens causally determine a given prediction.

The source EOS and the last prediction of target EOS are included in the heatmap. The plotted row labels describe predictions, so the first row is the first target token even though the decoder input at that position is BOS.

The bars show the maximum of each head-averaged row. A maximum below one leaves some mass on other source positions in that average. Individual heads can each assign all their weight to one position and still yield a spread-out average if they choose different positions.

PythonIn [36]
CollapseExpand
import numpy as np

row_max = attn_matrix.max(axis=1)
row_indices = np.arange(len(row_max))
VisualizationOut [37]
CollapseExpand
Bar chart of maxima from head-averaged cross-attention rows, mostly below one.
Maximum of each head-averaged cross-attention row in the example sentence. Values below one show mass at multiple source positions in the averaged row.

Limitations & Impact

Both NMT's impact and its limitations deserve attention.

The phrase-based and neural systems in this chapter offer two different ways to build translation. One exposes phrase and target-language scores to the decoder. The other learns a conditional score from paired sentences. The worked example shows which pieces can be trained together and which choices, such as beam width, you still make at inference.

A hallucination introduces content unsupported by the source. For example, in a synthetic test you could check whether a model adds an unmentioned location to an otherwise fluent translation. Raunak et al. (2021) studied hallucinations related to source perturbations and synthetic training data. Track source-copy and wrong-language outputs separately so a fluent-output metric does not hide those failure types. See Hallucination and Factuality.

Evaluation. BLEU summarizes overlap under a particular reference and scoring protocol. Rei et al. (2020) benchmarked COMET against human judgments. Hassan et al. (2018) claimed human parity on a Chinese-to-English news test. Läubli et al. (2018) found a preference for human translations in a document-level evaluation, and Toral et al. (2018) examined how the source-text provenance affected the comparison. Report test domain, scoring context, and rater protocol. See Translation Evaluation Beyond BLEU.

Language coverage. NLLB-200 covered about 200 languages. For each direction you plan to serve, report held-out performance alongside sample size and domain. In shared-capacity systems, evaluate both transfer and interference as you add languages. The chapter on Many-to-Many and Low-Resource Translation examines this trade-off.

Deployment. Measure latency at the proposed beam width and validate terminology and formatting constraints. Include document-level examples if pronouns or connectives require source context beyond one sentence. Ask translators to evaluate the cost of reviewing and correcting the output for their intended workflow.

Compare a dedicated encoder-decoder and a prompted decoder-only model on the same inputs if both are candidates for deployment. Evaluate quality, throughput, and whether the outputs obey the required constraints. Include the cost of post-editing in that comparison.

Summary

  • Conditional generation. Train a model for P(y∣x)=∏tP(yt∣y<t,x)P(y \mid x) = \prod_t P(y_t \mid y_{<t}, x) and use the translation loss to update its components jointly.
  • Source representations. A fixed-vector encoder compresses the source into one decoder input. Attention lets the decoder form a different weighted sum of source states at each step.
  • Attention diagnostics. Compare attention with known correspondences and use controlled tests for causal conclusions.
  • An encoder-decoder Transformer. Global source self-attention gives distant tokens a short path within a layer. Cross-attention lets target positions read the encoded source.
  • Likelihood and label smoothing. The baseline trains on reference tokens. Smoothing mixes gold and uniform cross-entropy and moves the logit-gradient zero to the smoothed distribution. State your tokenization and scoring convention when reporting perplexity.
  • Training data. Evaluate filtering, deduplication, domain fit, and back-translation against a fixed baseline.
  • Tokenization. Compare shared and separate vocabularies while tracking sequence lengths and coverage in each language.
  • Decoding. Compare beam width and scoring settings against a greedy baseline. Report model scores computed with a common scoring rule alongside the evaluation metric.
  • Failure analysis. Track hallucination, wrong target language, omitted or repeated content, and document-level coherence on cases designed to reveal them.

The next chapter, Parallel Data Mining and Quality Control, examines how to find and clean the parallel text used to train these systems.

Quiz

Ready to test your understanding? Take this quick quiz to reinforce what you've learned about neural machine translation.

Neural Machine Translation

Question 1 of 80 of 8 completed
In phrase-based SMT, what should you do to evaluate a change to an upstream word aligner?
Join the discussionAsk a question or share what you learned.

Comments

Add to the conversation

A question, a correction, or an example from your own work.

No comments yet. Be the first to share your thoughts!

A different angle
All writing
Language AI Handbook · Vol. 8

Parallel Data Mining and Quality Control

Mine parallel text from the web, align sentences, filter candidate pairs, and screen for training-evaluation contamination in translation corpora.

53 min read
Language AI Handbook · Vol. 8

Statistical Machine Translation Foundations

Learn how noisy-channel IBM word alignment, EM training, phrase extraction, log-linear scoring, and beam decoding build a statistical machine translation system.

59 min read
Language AI Handbook · Vol. 8

Translation Evaluation Beyond BLEU

Learn how translation evaluation goes beyond BLEU, covering MQM, human protocols, learned metrics, terminology checks, and paired bootstrap uncertainty.

52 min read

About the author

Reference

Citation details

Cite or share this article.

BIBTEXAcademic
@misc{brenndoerfer2026neuralmachine, author = {Michael Brenndoerfer}, title = {Neural Machine Translation}, year = {2026}, url = {https://mbrenndoerfer.com/writing/neural-machine-translation-encoder-decoder-transformers-attention}, organization = {mbrenndoerfer.com}, note = {Accessed: 2026-12-03} }
APAAcademic
Michael Brenndoerfer (2026). Neural Machine Translation. Retrieved from https://mbrenndoerfer.com/writing/neural-machine-translation-encoder-decoder-transformers-attention
MLAAcademic
Michael Brenndoerfer. "Neural Machine Translation." 2026. Web. December 3, 2026. <https://mbrenndoerfer.com/writing/neural-machine-translation-encoder-decoder-transformers-attention>.
CHICAGOAcademic
Michael Brenndoerfer. "Neural Machine Translation." Accessed December 3, 2026. https://mbrenndoerfer.com/writing/neural-machine-translation-encoder-decoder-transformers-attention.
HARVARDAcademic
Michael Brenndoerfer (2026) 'Neural Machine Translation'. Available at: https://mbrenndoerfer.com/writing/neural-machine-translation-encoder-decoder-transformers-attention (Accessed: December 3, 2026).
SimpleBasic
Michael Brenndoerfer (2026). Neural Machine Translation. https://mbrenndoerfer.com/writing/neural-machine-translation-encoder-decoder-transformers-attention
Newsletter

Stay up to date

Get new articles, book updates, and notes on AI and technology.

Unsubscribe at any time. Privacy policy