Algorithm Search⌘K

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 YY is log⁡p(Y∣X)=∑tlog⁡p(yt∣y<t,X)\log p(Y \mid X) = \sum_t \log p(y_t \mid y_{<t}, X), 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: s(Y)=log⁡p(Y∣X)/lp(∣Y∣)s(Y) = \log p(Y \mid X) / \text{lp}(|Y|), with lp(∣Y∣)=∣Y∣α\text{lp}(|Y|) = |Y|^\alpha or the GNMT penalty lp(∣Y∣)=((5+∣Y∣)/6)α\text{lp}(|Y|) = ((5 + |Y|) / 6)^\alpha of Wu et al. 2016. With α=0\alpha = 0 this is the raw score, and with α=1\alpha = 1 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 α\alpha 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:

  1. RERANK(hyps, lp) ▷ hyps = list of (Y, log p(Y)), lp = the penalty
  2. 1best ← none
  3. 2for each (Y, s) in hyps do
  4. 3v ← s / lp(|Y|)
  5. 4if best = none or v > best.score then best ← (Y, v) ▷ ties: the first one wins
  6. 5return best

The length ∣Y∣|Y| 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 s(Y)s(Y). 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 s≤0s \le 0 can reach at most s/lp(nmax⁡)s / \text{lp}(n_{\max}) for a length limit nmax⁡n_{\max}, because its log probability can only go down and its penalty can grow at most to lp(nmax⁡)\text{lp}(n_{\max}). 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 −2.0-2.0, and LONG, 8 tokens with log probability −3.2-3.2.

penalty SHORT LONG choice
none (α=0\alpha = 0) −2.0-2.0 −3.2-3.2 SHORT
∣Y∣1\vert Y\vert^{1} −0.6667-0.6667 −0.4-0.4 LONG
∣Y∣0.6\vert Y\vert^{0.6} −1.0346-1.0346 −0.9190-0.9190 LONG
GNMT, α=0.6\alpha = 0.6 −1.6829-1.6829 −2.0122-2.0122 SHORT
GNMT, α=1\alpha = 1 −1.5-1.5 −1.4769-1.4769 LONG

The GNMT penalty grows more slowly with the length than ∣Y∣α|Y|^\alpha for the same α\alpha, because of the constant 5: lp(1)=1\text{lp}(1) = 1, and lp(10)=(15/6)0.6=1.732862\text{lp}(10) = (15/6)^{0.6} = 1.732862 at α=0.6\alpha = 0.6, where 100.6=3.9810^{0.6} = 3.98. So the same α\alpha does not mean the same strength in the two forms.

GNMT. Wu et al. 2016 score a finished translation by log⁡p(Y∣X)/lp(Y)+cp(X;Y)\log p(Y \mid X) / \text{lp}(Y) + \text{cp}(X; Y), with the coverage penalty cp(X;Y)=β∑ilog⁡min⁡(∑jpi,j,1)\text{cp}(X; Y) = \beta \sum_i \log \min(\sum_j p_{i,j}, 1), where pi,jp_{i,j} is the attention weight of target word jj on source word ii. The coverage term penalizes source words that received little attention. For two target words with attention rows (0.7,0.3,0)(0.7, 0.3, 0) and (0.6,0.3,0.1)(0.6, 0.3, 0.1) over three source words, the source words receive 1.31.3, 0.60.6 and 0.10.1, and with β=0.2\beta = 0.2 the coverage penalty is 0.2(log⁡1+log⁡0.6+log⁡0.1)=−0.56270.2 (\log 1 + \log 0.6 + \log 0.1) = -0.5627. The final GNMT system used α=β=0.2\alpha = \beta = 0.2; a value of α\alpha 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 rr per word, log⁡p(Y∣X)+r∣Y∣\log p(Y \mid X) + r |Y|, and tune rr on held-out data. In the example, LONG wins when −3.2+8r>−2.0+3r-3.2 + 8 r > -2.0 + 3 r, that is when r>0.24r > 0.24.

Variations

  • Power penalty ∣Y∣α|Y|^\alpha, with α\alpha from 0 (no correction) to 1 (the mean log probability per token).
  • GNMT penalty ((5+∣Y∣)/6)α((5 + |Y|) / 6)^\alpha, with the coverage term cp\text{cp} for attention models.
  • Word reward +r∣Y∣+ r |Y|, 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 ∣Y∣|Y| and an expected length, for example a fixed ratio times the source length.
  • A length model. Add log⁡p(∣Y∣∣X)\log p(|Y| \mid X) 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 α=1\alpha = 1, a hypothesis at −1.0-1.0 after one token goes to (−1.0+log⁡0.9)/2≈−0.553(-1.0 + \log 0.9) / 2 \approx -0.553 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 α\alpha.
  • 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 −916.29-916.29 and its mean is log⁡0.4\log 0.4.
  • Tune per task and per model. The best α\alpha 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.

length_normalization.pyI0RawGitHub
# 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

  1. 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.
  2. For SHORT and LONG above, find the value of α\alpha at which the power penalty changes its choice. (Solve −2.0/3α=−3.2/8α-2.0 / 3^\alpha = -3.2 / 8^\alpha.)
  3. Prove the stopping bound of the template: if lp is positive and non-decreasing, an open hypothesis with raw score s≤0s \le 0 cannot reach a normalized score above s/lp(nmax⁡)s / \text{lp}(n_{\max}).
  4. Show that the word reward and the power penalty with α=1\alpha = 1 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 log⁡p(w∣y)≤0\log p(w \mid y) \le 0 for every prefix yy and token ww, the score of a sequence is the sum of these terms, and a penalty lp maps a length m≥1m \ge 1 to a number lp(m)>0\text{lp}(m) > 0. We assume exact arithmetic.

Lemma 1 (raw scores only go down). If y′y' extends yy, then log⁡p(y′)≤log⁡p(y)\log p(y') \le \log p(y).

Proof. log⁡p(y′)\log p(y') is log⁡p(y)\log p(y) plus one term log⁡p(w∣⋅)≤0\log p(w \mid \cdot) \le 0 per added token. □\square

So among outputs whose tokens all have the same probability π<1\pi < 1, the raw score ∣Y∣log⁡π|Y| \log \pi is largest for the shortest output. This is the bias that the technique corrects.

Theorem 2 (RERANK). RERANK returns a pair (Y,v)(Y, v) with v=log⁡p(Y)/lp(∣Y∣)v = \log p(Y) / \text{lp}(|Y|) maximal over the input list, and YY is the first hypothesis in the list that attains it.

Proof. After the pass of line L2 for the ii-th hypothesis, best holds the first of the hypotheses 1…i1 \ldots i 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. □\square

Lemma 3 (the bound). Let lp be non-decreasing. Let yy be an open hypothesis of length mm with raw score s≤0s \le 0, and let YY be a finished extension of yy with ∣Y∣≤nmax⁡|Y| \le n_{\max}. Then log⁡p(Y)/lp(∣Y∣)≤s/lp(nmax⁡)\log p(Y) / \text{lp}(|Y|) \le s / \text{lp}(n_{\max}).

Proof. By Lemma 1, log⁡p(Y)≤s≤0\log p(Y) \le s \le 0. Since lp(∣Y∣)≤lp(nmax⁡)\text{lp}(|Y|) \le \text{lp}(n_{\max}) and both are positive, 1/lp(∣Y∣)≥1/lp(nmax⁡)1 / \text{lp}(|Y|) \ge 1 / \text{lp}(n_{\max}), and multiplying by the non-positive number log⁡p(Y)\log p(Y) reverses the order: log⁡p(Y)/lp(∣Y∣)≤log⁡p(Y)/lp(nmax⁡)≤s/lp(nmax⁡)\log p(Y) / \text{lp}(|Y|) \le \log p(Y) / \text{lp}(n_{\max}) \le s / \text{lp}(n_{\max}). □\square

Both the power penalty with α≥0\alpha \ge 0 and the GNMT penalty with α≥0\alpha \ge 0 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 YY with ∣Y∣≤nmax⁡|Y| \le n_{\max} that maximizes log⁡p(Y)/lp(∣Y∣)\log p(Y) / \text{lp}(|Y|) 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 yy satisfies s(y)/lp(nmax⁡)≤s(y) / \text{lp}(n_{\max}) \le 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. □\square

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 α=1\alpha = 1, the normalized score of a prefix can increase when a token is added.

Proof. A prefix of one token with log⁡p=−1\log p = -1 has normalized score −1-1. Add a token of probability 0.90.9: the new score is (−1+log⁡0.9)/2≈−0.553>−1(-1 + \log 0.9) / 2 \approx -0.553 > -1. □\square

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 m1<m2m_1 < m_2 and log probabilities s1>s2s_1 > s_2, the score s+rms + r m prefers the longer one exactly when r>(s1−s2)/(m2−m1)r > (s_1 - s_2) / (m_2 - m_1). For the example of the page, (−2.0+3.2)/(8−3)=0.24(-2.0 + 3.2) / (8 - 3) = 0.24.

References

  1. 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
  2. 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
  3. 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
  4. 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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/AP6ENR/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • three classic examples