Neural Machine Translation › Training Objective

Michael BrenndoerferNovember 26, 20266 min read
Language AI HandbookAll chapters
Part 27 of 67Machine Translation and Speech Translation
Chapter 191Neural Machine Translation › Training Objective
Reading section 6 of 12 · Training Objective · 6 minSection 6 of 12 · 6 min

Section 6 of 12 · 6 min read

Reading settings

Definitions

Choose how many terms have tooltips.

Article links

Make inline references clickable

Notes & comments

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.

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!

Newsletter

Stay up to date

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

Unsubscribe at any time. Privacy policy