Techniqueadvanced
Minimum risk training
Also called expected risk minimization for sequences.
Train a sequence model to minimize the expected loss, such as 1 - BLEU, over a sample of its own outputs, renormalized.
Minimum risk training trains a sequence model, such as a neural translation model, to minimize the expected loss of its own outputs instead of the negative log likelihood of the reference. The loss is any sentence-level cost, for example 1 - sentence BLEU. The exact expectation is a sum over all output sequences, so the technique samples a small set of candidates from the model and renormalizes the model probabilities over that set, with a sharpness parameter α. Shen et al. (2016) applied it to neural machine translation. The written text sometimes calls it MRT.
In plain words
Normal training shows the model the reference translation and makes it more likely. The model never sees its own mistakes, and it never learns that some wrong translations are worse than others.
Minimum risk training asks the model to translate. It draws several candidate translations from the model, and a metric such as BLEU gives each candidate a loss. The model then moves probability from the candidates with a high loss to the candidates with a low loss.
The quantity that falls is the average loss of the candidates, weighted by how likely the model finds them. Because the candidates come from the model itself, the training sees the same kind of output that the model will produce at test time.
When it applies
- The model gives a probability to a whole output sequence, and you can compute and its gradient for any . An encoder-decoder model does this by the chain rule over the tokens.
- You can sample or list candidate outputs from the model.
- There is a loss $\Delta(y, y^*) $ for a candidate and the reference that you care about, such as 1 - sentence BLEU, 1 - chrF or TER. The loss need not be differentiable.
- The model already gives sensible outputs. Shen et al. start from a model trained by maximum likelihood; a random model gives candidates that are all bad, and the risk has almost no signal.
The template
For one sentence pair with a subset of candidates, the renormalized distribution and the risk are
The training objective is the sum of over the training pairs, minimized by stochastic gradient descent. Write . Then is the softmax of , and
SENTENCE-RISK(ℓ_y for y in S, Δ_y for y in S, α)- 1
for each y in S do s_y ← α · ℓ_y - 2
Q ← SOFTMAX(s) ▷ subtract max_y s_y before exp - 3
R ← Σ_y Q(y) Δ_y - 4
for each y in S do g_y ← α Q(y) (Δ_y - R) ▷ g_y = ∂R / ∂ℓ_y - 5
return R, Q, g CORPUS-RISK(batch, α)- 6
for each sentence pair in the batch do R_i, g_i ← SENTENCE-RISK(...) - 7
return Σ_i R_i and the g_i ▷ backpropagate Σ_y g_y ∂ℓ_y/∂θ
Line L2 works in log space with the log-sum-exp trick: a sentence probability is a product of many token probabilities and underflows in double precision, but does not. Line L4 is the derivative by the softmax Jacobian. A candidate with a loss above the current risk gets a positive , so a gradient step lowers its log probability; a candidate with a loss below the risk gets a negative and is pushed up. Line L7 hands the to the usual backpropagation through the network, as if were the weight of the log likelihood of .
The code on this page takes the log probabilities and the losses as given and implements lines L1 to L7; it does not train a network. The tests check the gradient through a toy model by central finite differences.
These facts about the template are theorems with short proofs:
- Bounds. , because is an average under .
- Zero-sum gradient. . So adding the same constant to every does not change , and adding a constant to every loss does not change the gradient. Training with and with is the same.
- Exact expectation. If is the set of all outputs and , then and is the exact expected loss .
- Limits of α. As , tends to the uniform distribution on . As , puts all its mass on the most probable candidates in , and tends to their loss.
With a sampled subset, is not an unbiased estimate of the expected loss under ; it is a different objective that Shen et al. found to work (a heuristic).
Classic examples
- Hand example. Take three candidates with and losses . With , and . The gradient in is , which sums to 0. With , gives and : a smaller flattens and moves the risk toward the plain mean 0.5.
- Neural translation. Shen et al. (2016) sampled candidates from an attention-based model trained by maximum likelihood, used a loss based on sentence-level BLEU, and set . They reported BLEU gains over maximum likelihood training on Chinese to English, English to French and English to German (measurements; see the paper for the test sets and the numbers).
- Statistical machine translation. Minimum error rate training tunes the few weights of a log-linear model to minimize the error of the 1-best output directly. Minimum risk training uses a smooth expectation in its place, so it can train millions of parameters by gradient descent.
Variations
- The loss. Any sentence-level cost works: 1 - smoothed sentence BLEU, 1 - chrF, TER, or a learned metric such as COMET. The model learns to please the metric, including its faults.
- Mixed objective. Many systems add a fraction of the cross-entropy loss on the reference to keep the model close to fluent text.
- Candidates from beam search. The subset can come from beam search instead of sampling. Beam candidates are more alike, so sees less of the space.
- Policy gradient. REINFORCE with the reward estimates the gradient of the true expected loss from samples, with a baseline in place of . Minimum risk training renormalizes over the subset instead, which gives a biased but lower variance estimate (a heuristic comparison, not a theorem).
- Decoding. Minimum Bayes risk decoding uses the same expected loss at test time to choose an output, with no training.
Pitfalls
- Starting from scratch. With random parameters every candidate is bad, the losses are all close to 1, and the gradient is near 0. Start from a model trained by maximum likelihood.
- The wrong α. A large α makes nearly one-hot, so only the top candidate gets a gradient. Shen et al. used the small value in their experiments; it is a hyperparameter, so tune it on held-out data (a heuristic).
- Counting duplicates. Sampling often draws the same candidate twice. is a set; if a duplicate stays in the list, its weight in doubles.
- Sentence BLEU without smoothing. Many short candidates have no matching 4-gram, so their BLEU is 0 and the losses tie. Use a smoothed sentence BLEU or chrF.
- Cost. Each update decodes and scores many candidates for each source sentence, which makes an epoch much slower than maximum likelihood training (a measurement of the setup, not a bound).
- Metric gaming. The model learns what the metric rewards. Check the gains with a second metric or with human judgments.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-risk-training/. The authors are listed in prov/1GGJMF.jsonl.
"""The risk of minimum risk training (Shen et al. 2016) and its gradient.
For one source sentence x with the reference y*, the model gives the log
probabilities log P(y | x; theta) of the candidates y in a subset S(x),
usually drawn by sampling from the model. The distribution over the subset is
Q(y) = P(y | x)^alpha / sum_{y' in S} P(y' | x)^alpha,
with the sharpness alpha, and the risk is R = sum_y Q(y) Delta(y, y*).
The derivative of R with respect to log P(y | x) is
alpha Q(y) (Delta(y, y*) - R),
and the chain rule through log P(y | x; theta) gives the gradient for the
parameters. The log probabilities and the losses are given (outputs of a
network and of a metric such as 1 - sentence BLEU); this module does not
train a network.
"""
import math
from typing import List, Sequence, Tuple
from nlslog import softmax
def risk_and_gradient(logp: Sequence[float], loss: Sequence[float],
alpha: float) -> Tuple[float, List[float], List[float]]:
"""Return (R, Q, g) for one sentence, where g[k] = dR / d logp[k]."""
if len(logp) == 0 or len(logp) != len(loss):
raise ValueError("logp and loss must be non-empty and of the same length")
if not alpha > 0:
raise ValueError("alpha must be positive")
s = [alpha * x for x in logp] # @line L1
q = softmax(s) # @line L2
r = math.fsum(qk * dk for qk, dk in zip(q, loss)) # @line L3
g = [alpha * qk * (dk - r) for qk, dk in zip(q, loss)] # @line L4
return r, q, g # @line L5
def corpus_risk(batch: Sequence[Tuple[Sequence[float], Sequence[float]]],
alpha: float) -> Tuple[float, List[List[float]]]:
"""Return the sum of the sentence risks and the gradients for each sentence."""
total, grads = 0.0, []
for logp, loss in batch: # @line L6
r, _, g = risk_and_gradient(logp, loss, alpha)
total += r
grads.append(g)
return total, grads # @line L7
def dedupe(samples: Sequence[Sequence[str]]) -> List[Tuple[str, ...]]:
"""Return the distinct candidates in the order of their first appearance.
S(x) is a set: a candidate drawn twice counts once in Q.
"""
seen, out = set(), []
for y in samples:
t = tuple(y)
if t not in seen:
seen.add(t)
out.append(t)
return out
nlslog.py 152 lines
# SPDX-License-Identifier: MIT
# Shared helper of the natural-language-and-speech pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Log-space arithmetic and semirings for the natural-language-and-speech pages.
Every log is the natural log. A probability of 0 is NEG_INF (float("-inf")),
never a large negative number. A cost is -log p, so a probability of 0 is a
cost of POS_INF.
The semirings are (K, plus, times, zero, one) as on the weighted-automaton page:
PROB probabilities plus = + times = * zero = 0 one = 1
LOG log probabilities plus = log_add times = + zero = -inf one = 0
VITERBI log probabilities plus = max times = + zero = -inf one = 0
TROPICAL costs -log p plus = min times = + zero = +inf one = 0
LOG_COST costs -log p plus = -log_add(-a, -b), times = +, zero = +inf, one = 0
BOOLEAN truth values plus = or times = and zero = False one = True
COUNTING path counts plus = + times = * zero = 0 one = 1
This module holds no algorithm of any page: no forward, Viterbi, CKY, Eisner,
CTC or DTW recursion. The pages build their dynamic programs on top of it.
"""
import math
from dataclasses import dataclass
from typing import Any, Callable, Iterable, List, Sequence
NEG_INF = float("-inf")
POS_INF = float("inf")
def safe_log(p) -> float:
"""Return log p, and NEG_INF for p = 0. Raise ValueError for p < 0."""
if p < 0:
raise ValueError("log of a negative number")
if p == 0:
return NEG_INF
return math.log(p)
def log_add(a: float, b: float) -> float:
"""Return log(exp(a) + exp(b)) = max(a, b) + log(1 + exp(-|a - b|)).
log_add(NEG_INF, NEG_INF) is NEG_INF. No exp of a large number is taken.
"""
if a < b:
a, b = b, a
if b == NEG_INF or a == POS_INF:
return a
return a + math.log1p(math.exp(b - a))
def log_sum(xs: Iterable[float]) -> float:
"""Return log(sum of exp(x)) over xs. An empty input gives NEG_INF."""
xs = list(xs)
if not xs:
return NEG_INF
m = max(xs)
if m == NEG_INF or m == POS_INF:
return m
return m + math.log(math.fsum(math.exp(x - m) for x in xs))
def log_normalize(xs: Sequence[float]) -> List[float]:
"""Return the list x - log_sum(xs): log values whose exps sum to 1.
Raise ValueError if every value is NEG_INF (nothing to normalize).
"""
z = log_sum(xs)
if z == NEG_INF:
raise ValueError("every weight is zero")
return [x - z for x in xs]
def log_softmax(xs: Sequence[float]) -> List[float]:
"""Return log softmax(xs): the logits xs turned into log probabilities."""
return log_normalize(xs)
def softmax(xs: Sequence[float], temperature: float = 1.0) -> List[float]:
"""Return the probabilities exp(x / temperature) / sum, computed stably.
The temperature must be positive. Logits of NEG_INF get probability 0.
"""
if not temperature > 0:
raise ValueError("the temperature must be positive")
m = max(xs)
if m == NEG_INF:
raise ValueError("every logit is -inf")
es = [math.exp((x - m) / temperature) for x in xs]
s = math.fsum(es)
return [e / s for e in es]
def argmax(xs: Sequence[Any]) -> int:
"""Return the first index of a largest value. Raise ValueError if xs is empty."""
if len(xs) == 0:
raise ValueError("argmax of an empty sequence")
best = 0
for i in range(1, len(xs)):
if xs[i] > xs[best]:
best = i
return best
@dataclass(frozen=True)
class Semiring:
"""A semiring (K, plus, times, zero, one). idempotent is True when a plus a = a."""
name: str
plus: Callable[[Any, Any], Any]
times: Callable[[Any, Any], Any]
zero: Any
one: Any
idempotent: bool
def _add(a, b):
return a + b
def _mul(a, b):
return a * b
def _log_add_cost(a: float, b: float) -> float:
return -log_add(-a, -b)
PROB = Semiring("probability", _add, _mul, 0, 1, False)
LOG = Semiring("log", log_add, _add, NEG_INF, 0.0, False)
VITERBI = Semiring("viterbi", max, _add, NEG_INF, 0.0, True)
TROPICAL = Semiring("tropical", min, _add, POS_INF, 0.0, True)
LOG_COST = Semiring("log-cost", _log_add_cost, _add, POS_INF, 0.0, False)
BOOLEAN = Semiring("boolean", lambda a, b: a or b, lambda a, b: a and b, False, True, True)
COUNTING = Semiring("counting", _add, _mul, 0, 1, False)
def sr_sum(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring sum of xs, and sr.zero for an empty input."""
acc = sr.zero
for x in xs:
acc = sr.plus(acc, x)
return acc
def sr_prod(sr: Semiring, xs: Iterable[Any]) -> Any:
"""Return the semiring product of xs, and sr.one for an empty input."""
acc = sr.one
for x in xs:
acc = sr.times(acc, x)
return acc
test_minimum_risk_training.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-risk-training/. The authors are listed in prov/1GGJMF.jsonl.
import itertools
import math
import random
import pytest
from minimum_risk_training import corpus_risk, dedupe, risk_and_gradient
VOCAB = ["a", "b", "c"]
def toy_logp(theta, y):
"""log P(y) for a toy model with an independent softmax over VOCAB at each position."""
total = 0.0
for t, w in enumerate(y):
row = theta[t]
m = max(row)
z = m + math.log(sum(math.exp(v - m) for v in row))
total += row[VOCAB.index(w)] - z
return total
def toy_dlogp(theta, y):
"""d log P(y) / d theta, row by row."""
out = []
for t, w in enumerate(y):
row = theta[t]
m = max(row)
e = [math.exp(v - m) for v in row]
z = sum(e)
out.append([(1.0 if VOCAB[j] == w else 0.0) - e[j] / z for j in range(len(row))])
return out
def hamming(y, ref):
return sum(1 for a, b in zip(y, ref) if a != b) / len(ref)
def test_page_example():
logp = [math.log(0.5), math.log(0.3), math.log(0.2)]
loss = [0.0, 0.5, 1.0]
r, q, g = risk_and_gradient(logp, loss, 1.0)
assert abs(r - 0.35) < 1e-12
assert all(abs(a - b) < 1e-12 for a, b in zip(q, [0.5, 0.3, 0.2]))
assert all(abs(a - b) < 1e-12 for a, b in zip(g, [-0.175, 0.045, 0.13]))
r, q, _ = risk_and_gradient(logp, loss, 0.5)
assert [round(x, 4) for x in q] == [0.4154, 0.3218, 0.2628]
assert round(r, 4) == 0.4237
def test_full_subset_with_alpha_one_is_expected_loss():
rng = random.Random(1683)
for _ in range(20):
theta = [[rng.uniform(-2, 2) for _ in VOCAB] for _ in range(2)]
ref = ("a", "b")
ys = list(itertools.product(VOCAB, repeat=2))
logp = [toy_logp(theta, y) for y in ys]
loss = [hamming(y, ref) for y in ys]
r, q, _ = risk_and_gradient(logp, loss, 1.0)
assert abs(sum(math.exp(x) for x in logp) - 1) < 1e-12
want = sum(math.exp(lp) * d for lp, d in zip(logp, loss))
assert abs(r - want) < 1e-12
assert all(abs(a - math.exp(b)) < 1e-12 for a, b in zip(q, logp))
def test_gradient_by_finite_differences():
rng = random.Random(5)
h = 1e-6
for _ in range(5):
theta = [[rng.uniform(-1, 1) for _ in VOCAB] for _ in range(3)]
ref = ("c", "a", "b")
samples = [tuple(rng.choice(VOCAB) for _ in range(3)) for _ in range(8)]
cands = dedupe(samples)
loss = [hamming(y, ref) for y in cands]
alpha = rng.choice([0.005, 0.5, 1.0, 3.0])
def risk():
return risk_and_gradient([toy_logp(theta, y) for y in cands], loss, alpha)[0]
_, _, g = risk_and_gradient([toy_logp(theta, y) for y in cands], loss, alpha)
grad = [[0.0] * len(VOCAB) for _ in range(3)]
for gk, y in zip(g, cands):
d = toy_dlogp(theta, y)
for t in range(3):
for j in range(len(VOCAB)):
grad[t][j] += gk * d[t][j]
for t in range(3):
for j in range(len(VOCAB)):
old = theta[t][j]
theta[t][j] = old + h
up = risk()
theta[t][j] = old - h
down = risk()
theta[t][j] = old
assert abs((up - down) / (2 * h) - grad[t][j]) < 1e-5
def test_shift_invariance_and_zero_sum():
rng = random.Random(9)
for _ in range(50):
n = rng.randint(1, 8)
logp = [rng.uniform(-30, 0) for _ in range(n)]
loss = [rng.random() for _ in range(n)]
alpha = rng.uniform(0.01, 2)
r1, _, g = risk_and_gradient(logp, loss, alpha)
r2, _, _ = risk_and_gradient([x - 7.5 for x in logp], loss, alpha)
assert abs(r1 - r2) < 1e-12
assert abs(sum(g)) < 1e-12
assert min(loss) - 1e-12 <= r1 <= max(loss) + 1e-12
def test_alpha_limits():
logp = [-1.0, -2.0, -4.0]
loss = [0.6, 0.2, 0.9]
# a large alpha puts all the mass on the most probable candidate
assert abs(risk_and_gradient(logp, loss, 200.0)[0] - 0.6) < 1e-12
# a small alpha makes Q nearly uniform
assert abs(risk_and_gradient(logp, loss, 1e-9)[0] - sum(loss) / 3) < 1e-8
def test_no_underflow():
# the probabilities exp(-2000) underflow to 0 in double precision
logp = [-2000.0, -2001.0]
assert math.exp(logp[0]) == 0.0
r, q, _ = risk_and_gradient(logp, [0.0, 1.0], 1.0)
want = 1 / (1 + math.e)
assert abs(r - want) < 1e-12 and abs(q[1] - want) < 1e-12
def test_corpus_and_helpers():
batch = [([-1.0, -2.0], [0.0, 1.0]), ([-0.5], [0.3])]
total, grads = corpus_risk(batch, 1.0)
r0 = risk_and_gradient(*batch[0], 1.0)[0]
assert abs(total - (r0 + 0.3)) < 1e-12 and grads[1] == [0.0]
assert dedupe([["a"], ["b"], ["a"]]) == [("a",), ("b",)]
with pytest.raises(ValueError):
risk_and_gradient([], [], 1.0)
with pytest.raises(ValueError):
risk_and_gradient([0.0], [1.0], 0.0)
Exercises
- Prove . Hint: .
- Show that if all candidates in have the same loss, the gradient is 0 whatever the probabilities. Answer: then for every .
- In the hand example with , one gradient step with a small rate on the directly changes them by . Which candidate gains probability? Answer: the first, the only one with a loss below .
- Show that for and equal to all outputs, the gradient is , the REINFORCE gradient with the baseline .
References
- Shiqi Shen, Yong Cheng, Zhongjun He, Wei He, Hua Wu, Maosong Sun and Yang Liu, Minimum Risk Training for Neural Machine Translation, ACL 2016, pages 1683 to 1692, the risk over a sampled subset of candidates, the sharpness alpha and the gradient alpha Q (Delta - R), with alpha = 5e-3 in the experiments
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 1GGJMF Edit this page History Report an error Markdown