Techniquecore
Length normalization
Also called length penalty.
Divide the log probability of each finished beam hypothesis by a function of its length, such as |Y|^alpha, so that beam search does not prefer short outputs.
Length normalization changes the score that beam search uses to compare finished hypotheses. The raw score of an output is , a sum of terms that are all at most 0. So every extra token lowers the score, and among finished outputs the raw score prefers short ones. Length normalization divides the score by a penalty that grows with the length: , with or the GNMT penalty of Wu et al. 2016. With this is the raw score, and with and the power form it is the mean log probability per token. The technique is a heuristic: it changes which output the decoder returns, and whether that output is better is a measurement on a task. The value of is tuned on held-out data.
In plain words
A model gives each next word a chance. The chance of a whole sentence is the product of these chances, so each extra word makes the total smaller. If the decoder simply picks the sentence with the largest total, it favors short sentences, sometimes far too short. Length normalization corrects this. It compares sentences by their score divided by a number that grows with the length, like an average per word. A single setting controls how strong the correction is; it is chosen by trying values on test data.
When it applies
Use length normalization when a decoder compares complete outputs of different lengths by their total log probability, and those outputs come from a search, not from sampling. The typical case is beam search in machine translation, speech recognition and summarization with an encoder-decoder model. It does not apply to greedy decoding, which compares tokens at one position only, or to sampling, which does not compare outputs at all.
The template
The finished hypotheses of a beam search, as pairs (tokens, log probability), are reranked by the normalized score:
RERANK(hyps, lp) ▷ hyps = list of (Y, log p(Y)), lp = the penalty- 1
best ← none - 2
for each (Y, s) in hyps do - 3
v ← s / lp(|Y|) - 4
if best = none or v > best.score then best ← (Y, v) ▷ ties: the first one wins - 5
return best
The length counts every predicted token, the end token </s> included. Toolkits differ on this point; whatever rule you use, use the same one everywhere.
Inside the beam search, open hypotheses are still ranked by their raw log probability, because all open hypotheses at one step have the same length. Only finished hypotheses are compared by . The search can stop early with a bound: if lp is positive and does not decrease with the length, an open hypothesis with raw score can reach at most for a length limit , because its log probability can only go down and its penalty can grow at most to . When no open hypothesis can beat the best finished one by this bound, the search stops. The proof is in proofs/correctness.md, with the facts that RERANK returns a hypothesis of best normalized score and that a beam of unbounded width returns the best normalized output.
Classic examples
Two hypotheses. A beam ends with SHORT, 3 tokens with log probability , and LONG, 8 tokens with log probability .
| penalty | SHORT | LONG | choice |
|---|---|---|---|
| none () | SHORT | ||
| LONG | |||
| LONG | |||
| GNMT, | SHORT | ||
| GNMT, | LONG |
The GNMT penalty grows more slowly with the length than for the same , because of the constant 5: , and at , where . So the same does not mean the same strength in the two forms.
GNMT. Wu et al. 2016 score a finished translation by , with the coverage penalty , where is the attention weight of target word on source word . The coverage term penalizes source words that received little attention. For two target words with attention rows and over three source words, the source words receive , and , and with the coverage penalty is . The final GNMT system used ; a value of between 0.6 and 0.7 was reported for an earlier form of the penalty, so do not copy one of these values to the other form.
A word reward. Murray and Chiang 2018 add a reward per word, , and tune on held-out data. In the example, LONG wins when , that is when .
Variations
- Power penalty , with from 0 (no correction) to 1 (the mean log probability per token).
- GNMT penalty , with the coverage term for attention models.
- Word reward , an additive form. It can also be applied to open hypotheses during the search, since all of them get the same reward at one step.
- Length ratio. Penalize the gap between and an expected length, for example a fixed ratio times the source length.
- A length model. Add from a separate predictor of the length.
- Minimum length. Forbid
</s>before a minimum number of tokens, a hard constraint in place of a score change.
Pitfalls
- The bias comes back with wide beams. Normalization fixes the comparison of the finished outputs that the beam finds, but a wider beam finds more short outputs to compare. Koehn and Knowles 2017 measured lower quality with very wide beams, most strongly without normalization, and also with it for several language pairs. The deeper cause is described in inadequacy of the mode.
- Normalized scores are not monotone. The raw log probability never increases when a token is added, but the normalized score can: with , a hypothesis at after one token goes to after two. So do not prune open hypotheses by their normalized score as if it were a bound.
- Count the length the same way. Counting
</s>or not, and counting subword tokens or words, changes the effective . - Do not use underflowing probabilities. Divide the log probability, not the probability. For 1000 tokens of probability 0.4 each, the probability is 0 in double precision, while the log probability is and its mean is .
- Tune per task and per model. The best depends on the model, the data and the beam width. Report it.
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/length-normalization/. The authors are listed in prov/AP6ENR.jsonl.
"""Length normalization of the scores of finished hypotheses.
The length |Y| of a hypothesis counts every predicted token, "</s>"
included. Toolkits differ on this point; the code follows one rule
everywhere. A model is a function from a prefix (a tuple of strings) to a
dict of log probabilities, in natural log. The code takes these log
probabilities as given; it does not run a network.
"""
import math
from typing import Callable, Dict, List, Optional, Sequence, Tuple
from nlslog import NEG_INF
EOS = "</s>"
Model = Callable[[Tuple[str, ...]], Dict[str, float]]
Penalty = Callable[[int], float]
def power_penalty(alpha: float) -> Penalty:
"""lp(Y) = |Y|^alpha. alpha = 0 is the raw score, alpha = 1 the mean log probability."""
return lambda length: float(length) ** alpha
def gnmt_penalty(alpha: float) -> Penalty:
"""lp(Y) = ((5 + |Y|) / 6)^alpha of Wu et al. 2016. lp = 1 for |Y| = 1."""
return lambda length: ((5.0 + length) / 6.0) ** alpha
def gnmt_coverage(attention: Sequence[Sequence[float]], beta: float) -> float:
"""cp = beta * sum over source words i of log(min(sum over target words j of p_ij, 1)).
attention[j][i] is the attention weight of target position j on source
word i. A source word with no attention gives NEG_INF.
"""
if not attention:
return 0.0
total = 0.0
for i in range(len(attention[0])):
mass = math.fsum(row[i] for row in attention)
if mass <= 0:
return NEG_INF
total += math.log(min(mass, 1.0))
return beta * total
def normalized(log_p: float, length: int, lp: Penalty) -> float:
"""Return log p / lp(|Y|)."""
return log_p / lp(length)
def word_reward(log_p: float, length: int, reward: float) -> float:
"""Return log p + reward * |Y|, the additive fix of Murray and Chiang 2018 and others."""
return log_p + reward * length
def rerank(hyps: Sequence[Tuple[Sequence[str], float]], lp: Penalty) -> Optional[Tuple[List[str], float]]:
"""Return the finished hypothesis with the best normalized score, and that score.
hyps holds (tokens, log p). On ties the first one wins.
"""
best: Optional[Tuple[List[str], float]] = None # @line L1
for y, log_p in hyps: # @line L2
s = normalized(log_p, len(y), lp) # @line L3
if best is None or s > best[1]: # @line L4
best = (list(y), s)
return best # @line L5
def beam_search_normalized(model: Model, max_len: int, width: int, lp: Penalty) -> Optional[Tuple[List[str], float]]:
"""Beam search that ranks open hypotheses by log p and finished ones by log p / lp.
It stops when no open hypothesis can beat the best finished one. Since
log p <= 0 can only go down and lp does not go down with the length, an
open hypothesis of score s can reach at most s / lp(max_len) when lp is
non-decreasing and positive. The function needs that property of lp.
"""
beam: List[Tuple[Tuple[str, ...], float]] = [((), 0.0)]
best: Optional[Tuple[List[str], float]] = None
for _ in range(max_len):
cand = []
for y, s in beam:
for w, lpw in model(y).items():
if lpw > NEG_INF:
cand.append((y + (w,), s + lpw))
beam = []
for y, s in sorted(cand, key=lambda t: -t[1]):
if y[-1] == EOS:
score = normalized(s, len(y), lp)
if best is None or score > best[1]:
best = (list(y), score)
elif len(beam) < width:
beam.append((y, s))
if not beam:
break
if best is not None and all(s / lp(max_len) <= best[1] for _, s in beam):
break
return best
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_length_normalization.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/length-normalization/. The authors are listed in prov/AP6ENR.jsonl.
import math
import random
from length_normalization import (
EOS,
beam_search_normalized,
gnmt_coverage,
gnmt_penalty,
normalized,
power_penalty,
rerank,
word_reward,
)
from nlslog import NEG_INF, log_normalize
SHORT = (["x", "y", EOS], -2.0)
LONG = (["x", "y", "z", "x", "y", "z", "w", EOS], -3.2)
def random_model(seed, vocab, n):
def model(prefix):
if len(prefix) >= n - 1:
return {w: (0.0 if w == EOS else NEG_INF) for w in vocab}
rng = random.Random(f"{seed}|{' '.join(prefix)}")
raw = [math.log(rng.random() ** 2 + 1e-3) for _ in vocab]
return dict(zip(vocab, log_normalize(raw)))
return model
def exhaustive(model, n):
out = []
def rec(prefix, s):
for w, lp in model(tuple(prefix)).items():
if lp == NEG_INF:
continue
if w == EOS:
out.append((prefix + [w], s + lp))
elif len(prefix) + 1 < n:
rec(prefix + [w], s + lp)
rec([], 0.0)
return out
def test_gnmt_check_value() -> None:
assert round(gnmt_penalty(0.6)(10), 6) == 1.732862
assert gnmt_penalty(0.6)(1) == 1.0
assert gnmt_penalty(0.0)(10) == 1.0
def test_example() -> None:
hyps = [SHORT, LONG]
assert rerank(hyps, power_penalty(0.0))[0] == SHORT[0]
y, s = rerank(hyps, power_penalty(1.0))
assert y == LONG[0] and math.isclose(s, -0.4)
assert math.isclose(normalized(-2.0, 3, power_penalty(1.0)), -2.0 / 3)
assert rerank(hyps, gnmt_penalty(0.6))[0] == SHORT[0]
assert rerank(hyps, gnmt_penalty(1.0))[0] == LONG[0]
assert math.isclose(normalized(-2.0, 3, gnmt_penalty(1.0)), -1.5)
assert math.isclose(normalized(-3.2, 8, gnmt_penalty(1.0)), -3.2 * 6 / 13)
assert rerank(hyps, power_penalty(0.6))[0] == LONG[0]
def test_rerank_against_brute_force() -> None:
rng = random.Random(1)
for _ in range(300):
hyps = [(["t"] * rng.randrange(1, 12), -rng.uniform(0, 15)) for _ in range(rng.randrange(1, 8))]
for lp in (power_penalty(0.0), power_penalty(0.7), gnmt_penalty(0.6), gnmt_penalty(1.0)):
y, s = rerank(hyps, lp)
best = max(h[1] / lp(len(h[0])) for h in hyps)
assert s == best
assert any(h[0] == y and h[1] / lp(len(h[0])) == best for h in hyps)
def test_normalized_score_is_not_monotone() -> None:
lp = power_penalty(1.0)
before = normalized(-1.0, 1, lp)
after = normalized(-1.0 + math.log(0.9), 2, lp)
assert after > before
# The raw log probability can only go down.
assert -1.0 + math.log(0.9) < -1.0
def test_wide_beam_finds_the_best_normalized_output() -> None:
vocab = ["a", "b", "c", EOS]
for seed in range(40):
model = random_model(seed, vocab, 5)
outs = exhaustive(model, 5)
for lp in (power_penalty(0.0), power_penalty(1.0), gnmt_penalty(0.6), gnmt_penalty(2.0)):
got = beam_search_normalized(model, 5, 10**6, lp)
want = max(s / lp(len(y)) for y, s in outs)
assert math.isclose(got[1], want)
def test_normalization_changes_the_length_of_the_choice() -> None:
vocab = ["a", "b", "c", EOS]
shorter = longer = 0
for seed in range(40):
model = random_model(seed, vocab, 6)
raw = beam_search_normalized(model, 6, 10**6, power_penalty(0.0))
norm = beam_search_normalized(model, 6, 10**6, power_penalty(1.0))
assert len(norm[0]) >= len(raw[0]) or norm[1] >= raw[1] / len(raw[0])
shorter += len(raw[0]) < len(norm[0])
longer += len(raw[0]) > len(norm[0])
assert shorter > 0 and longer == 0
def test_coverage_penalty() -> None:
# Two target positions attend to three source words.
attention = [[0.7, 0.3, 0.0], [0.6, 0.3, 0.1]]
cp = gnmt_coverage(attention, 0.2)
assert math.isclose(cp, 0.2 * (math.log(1.0) + math.log(0.6) + math.log(0.1)))
assert gnmt_coverage(attention, 0.0) == 0.0
assert gnmt_coverage([[1.0, 0.0]], 0.2) == NEG_INF
def test_word_reward() -> None:
# The long hypothesis wins when 5 r > 1.2, that is r > 0.24.
assert word_reward(-3.2, 8, 0.3) > word_reward(-2.0, 3, 0.3)
assert word_reward(-3.2, 8, 0.2) < word_reward(-2.0, 3, 0.2)
assert word_reward(-3.2, 8, 0.0) < word_reward(-2.0, 3, 0.0)
def test_long_hypothesis_in_log_space() -> None:
log_p = 1000 * math.log(0.4)
assert math.exp(log_p) == 0.0
assert math.isclose(normalized(log_p, 1000, power_penalty(1.0)), math.log(0.4))
Exercises
- Show that the log probability of a prefix never increases when a token is added, and use it to explain why the raw score prefers short outputs.
- For SHORT and LONG above, find the value of at which the power penalty changes its choice. (Solve .)
- Prove the stopping bound of the template: if lp is positive and non-decreasing, an open hypothesis with raw score cannot reach a normalized score above .
- Show that the word reward and the power penalty with can choose different outputs from the same two hypotheses.
Proof: Reranking and the stopping bound of length normalized beam searchfull
We use the notation of the page. A model gives for every prefix and token , the score of a sequence is the sum of these terms, and a penalty lp maps a length to a number . We assume exact arithmetic.
Lemma 1 (raw scores only go down). If extends , then .
Proof. is plus one term per added token.
So among outputs whose tokens all have the same probability , the raw score is largest for the shortest output. This is the bias that the technique corrects.
Theorem 2 (RERANK). RERANK returns a pair with maximal over the input list, and is the first hypothesis in the list that attains it.
Proof. After the pass of line L2 for the -th hypothesis, best holds the first of the hypotheses with the largest normalized score, and that score. This holds after the first pass, where line L4 sets best because it is none. Line L3 computes the normalized score, and line L4 replaces best only on a strict increase, so an equal later score keeps the earlier hypothesis. After the last pass, line L5 returns it.
Lemma 3 (the bound). Let lp be non-decreasing. Let be an open hypothesis of length with raw score , and let be a finished extension of with . Then .
Proof. By Lemma 1, . Since and both are positive, , and multiplying by the non-positive number reverses the order: .
Both the power penalty with and the GNMT penalty with are positive and non-decreasing, so the lemma applies to them.
Theorem 4 (an unbounded beam is exact). Let the beam width be at least the number of open hypotheses at every step, and let lp be positive and non-decreasing. Then the beam search of the code returns a finished output with that maximizes over all such outputs of positive probability.
Proof. With an unbounded width, no open hypothesis is ever dropped by the width, so every prefix of positive probability is expanded until it either ends with </s>, where it is scored by its normalized score and compared with the best so far, or reaches the length limit. The only other way to drop hypotheses is the early stop. The search stops early only when every open hypothesis satisfies the best normalized score found so far. By Lemma 3, no finished extension of any open hypothesis can then beat the best found, so stopping loses no better output. Hence the best normalized score over all finished outputs is found.
With a bounded width the beam drops hypotheses, and the result is only a heuristic, as for plain beam search.
Lemma 5 (normalized scores are not monotone). With the power penalty and , the normalized score of a prefix can increase when a token is added.
Proof. A prefix of one token with has normalized score . Add a token of probability : the new score is .
So the normalized score of an open hypothesis is not an upper bound on the normalized scores of its extensions, and Lemma 3 uses the raw score instead.
Word reward. For two outputs of lengths and log probabilities , the score prefers the longer one exactly when . For the example of the page, .
References
- Yonghui Wu, Mike Schuster, Zhifeng Chen, Quoc V. Le, Mohammad Norouzi and others, Google's neural machine translation system, bridging the gap between human and machine translation, arXiv 1609.08144, 2016, Section 7, the length penalty lp(Y) = ((5 + |Y|) / 6)^alpha and the coverage penalty in Equation 14
- Kenton Murray and David Chiang, Correcting length bias in neural machine translation, Third Conference on Machine Translation (WMT), 2018, pages 212 to 223, the length bias of beam search, and a per-word reward tuned on held-out data
- Philipp Koehn and Rebecca Knowles, Six challenges for neural machine translation, First Workshop on Neural Machine Translation, 2017, pages 28 to 39, the challenge of beam search, where wider beams lower the translation quality, also with normalized scores
- Clara Meister, Ryan Cotterell and Tim Vieira, If beam search is the answer, what was the question?, EMNLP 2020, beam search as the solution of a regularized decoding objective, and the role of the length of the output
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag AP6ENR Edit this page History Report an error Markdown