Algorithm Search⌘K

Algorithmadvanced

Minimum Bayes risk decoding

Also called MBR decoding.

Choose the candidate output with the least expected loss under the model, for a loss such as 1 - BLEU or the word error rate, often with the expectation estimated from model samples.

Time
O(H N L) worst
Space
O(H + N) extra
Where
H = the number of candidates; L = the cost of one call of the loss; N = the number of evidence outputs (samples or list entries)
Properties
deterministicexactofflineiterative
Origin
Vaibhava Goel, William J. Byrne, 2000

Minimum Bayes risk (MBR) decoding picks the output that is best on average, not the output that is most probable. Given a model p(y∣x)p(y \mid x) and a loss ℓ(h,y)\ell(h, y) that says how bad it is to output hh when the right answer is yy, it returns the candidate hh of least expected loss ∑yp(y∣x) ℓ(h,y)\sum_y p(y \mid x) \, \ell(h, y). With the 0-1 loss this is the most probable output, so MBR generalizes MAP decoding. With a loss that gives partial credit, such as the word error rate or $1 - $ BLEU, it prefers an output that agrees with many probable outputs over a single probable outlier. The sum runs over all outputs, so in practice it is estimated: over an N-best list or a lattice in older systems, and over samples from the model in neural ones. The decision rule is exact for the candidates and the evidence it is given; whether it improves quality is a measurement.

In plain words

The model gives many possible answers, each with a chance of being right. The most likely single answer can still be a bad bet, for example if the other answers all agree with each other and not with it. MBR decoding asks, for each candidate: if I output this, how wrong will I be on average, counting each possible right answer by its chance? It then outputs the candidate with the smallest average error. If you only count exact matches, this is the most likely answer. If near misses count as partly right, it is often a different, safer answer.

The problem

The input is a set H\mathcal{H} of HH candidates, a list E\mathcal{E} of evidence pairs (yj,wj)(y_j, w_j) with weights wj≥0w_j \ge 0, and a loss ℓ(h,y)≥0\ell(h, y) \ge 0. The risk of a candidate is

R(h)=∑j=1Nwj ℓ(h,yj),R(h) = \sum_{j=1}^{N} w_j \, \ell(h, y_j),

and the task is h∗=arg⁡min⁡h∈HR(h)h^* = \arg\min_{h \in \mathcal{H}} R(h). Three common choices of the evidence:

  • The full distribution. The evidence is every output with w=p(y∣x)w = p(y \mid x). Then R(h)R(h) is the exact Bayes risk, which no system can compute for a neural model, because the outputs are too many.
  • A list. The evidence is an N-best list or the paths of a word lattice, with the model probabilities renormalized over the list.
  • Samples. Draw y1,…,yNy_1, \ldots, y_N independently from p(⋅∣x)p(\cdot \mid x) and set wj=1/Nw_j = 1/N. Then R(h)R(h) is an unbiased Monte Carlo estimate of the true risk, and the distinct samples are usually also the candidates (Eikema and Aziz 2020).

The loss is often 1−u(h,y)1 - u(h, y) for a utility uu in [0,1][0, 1] such as BLEU, chrF or COMET, or the edit distance for speech recognition.

The algorithm

  1. MBR-DECODE(H, E, ℓ) ▷ H = candidates, E = list of (y, w), ℓ = loss
  2. best ← none
  3. 1r* ← +∞
  4. 2for each h in H do
  5. 3r ← Σ over (y, w) in E of w · ℓ(h, y)
  6. 4if r < r* then (best, r*) ← (h, r) ▷ ties: the first candidate wins
  7. 5return (best, r*)

The code has two front ends. One takes the evidence as log probabilities and normalizes them in log space with log-sum-exp, so that weights near e−1000e^{-1000} do not underflow before the normalization. The other takes NN samples, uses the distinct samples as candidates and every sample as evidence with weight 1/N1/N, and so makes NN loss calls per distinct sample.

Example

A model has four outputs with these probabilities, and the loss is the word edit distance.

output words pp
A a b c 7/25
B a b d 6/25
C a e d 6/25
D f b d 6/25

The edit distances are d(A,B)=1d(A, B) = 1, d(A,C)=2d(A, C) = 2, d(A,D)=2d(A, D) = 2, d(B,C)=1d(B, C) = 1, d(B,D)=1d(B, D) = 1 and d(C,D)=2d(C, D) = 2. So

  • R(A)=(0⋅7+1⋅6+2⋅6+2⋅6)/25=30/25=6/5R(A) = (0 \cdot 7 + 1 \cdot 6 + 2 \cdot 6 + 2 \cdot 6) / 25 = 30/25 = 6/5,
  • R(B)=(1⋅7+0+1⋅6+1⋅6)/25=19/25R(B) = (1 \cdot 7 + 0 + 1 \cdot 6 + 1 \cdot 6) / 25 = 19/25,
  • R(C)=(2⋅7+1⋅6+0+2⋅6)/25=32/25R(C) = (2 \cdot 7 + 1 \cdot 6 + 0 + 2 \cdot 6) / 25 = 32/25,
  • R(D)=(2⋅7+1⋅6+2⋅6+0)/25=32/25R(D) = (2 \cdot 7 + 1 \cdot 6 + 2 \cdot 6 + 0) / 25 = 32/25.

MBR decoding returns B, with an expected edit distance of 19/25=0.7619/25 = 0.76 words. The most probable output A has an expected edit distance of 1.21.2. Under the 0-1 loss the risks are 1−p1 - p, so A wins with 18/2518/25, as MAP decoding would. B is the output that shares the most with all the others: it is one edit away from each of them.

With 2000 samples from this model (seed 5 in the test), sampling based MBR also returns B, with an estimated risk within 0.05 of 19/2519/25.

Correctness

The proof is in proofs/correctness.md. It proves that the algorithm returns a candidate of least risk, the first one on ties, and that scaling all weights by a positive constant does not change the choice, so the weights need not be normalized. It proves that with the 0-1 loss and the full distribution as evidence, MBR over all outputs is MAP decoding. And it proves that with NN independent samples as evidence the estimated risk of each fixed candidate is unbiased and converges to the true risk by the law of large numbers, so for a finite candidate set with a unique minimizer the sampled decision is the exact MBR decision with probability tending to 1.

What is not a theorem: that the MBR output is a better text. That is a measurement on a task with a metric, and it holds best when the loss used in decoding is the metric used in evaluation.

Proof: MBR decoding returns a candidate of least risk, reduces to MAP under the 0-1 loss, and is consistent with samplesfull

We use the notation of the page: candidates H=(h1,…,hH)\mathcal{H} = (h_1, \ldots, h_H) in a fixed order, evidence (yj,wj)(y_j, w_j) for j=1,…,Nj = 1, \ldots, N with wj≥0w_j \ge 0, a loss ℓ≥0\ell \ge 0, and the risk R(h)=∑jwjℓ(h,yj)R(h) = \sum_j w_j \ell(h, y_j). We assume exact arithmetic for the sums.

Theorem 1 (the decision). MBR-DECODE returns (hi,R(hi))(h_i, R(h_i)), where ii is the smallest index with R(hi)=min⁡h∈HR(h)R(h_i) = \min_{h \in \mathcal{H}} R(h).

Proof. The invariant after the pass for hih_i of the loop of line L2 is: r∗=min⁡i′≤iR(hi′)r^* = \min_{i' \le i} R(h_{i'}), and best is the first candidate among h1,…,hih_1, \ldots, h_i that attains it. It holds before the loop with r∗=+∞r^* = +\infty (line L1), since every risk is finite. Line L3 computes R(hi)R(h_i) exactly. Line L4 replaces the pair only on a strict decrease, so a later candidate with the same risk does not replace an earlier one. After the last pass the invariant gives the claim, and line L5 returns it. □\square

Lemma 2 (scaling). For any c>0c > 0, the evidence (yj,cwj)(y_j, c w_j) gives the same candidate.

Proof. Every risk is multiplied by cc, which keeps the order of the risks and their ties. □\square

So weights that are proportional to the probabilities, for example exp⁡\exp of unnormalized log scores, give the same decision as the normalized probabilities. The code still normalizes in log space, because the unnormalized exponentials can all underflow to 0, which would make every risk 0.

Theorem 3 (MAP as a special case). Let the evidence be the full distribution, wy=p(y∣x)w_y = p(y \mid x) for every output yy, let H\mathcal{H} be the set of all outputs, and let ℓ(h,y)=0\ell(h, y) = 0 if h=yh = y and 1 otherwise. Then R(h)=1−p(h∣x)R(h) = 1 - p(h \mid x), and MBR returns a most probable output.

Proof. R(h)=∑y≠hp(y∣x)=1−p(h∣x)R(h) = \sum_{y \ne h} p(y \mid x) = 1 - p(h \mid x), because the probabilities sum to 1. Minimizing 1−p(h∣x)1 - p(h \mid x) maximizes p(h∣x)p(h \mid x). □\square

With NN samples as evidence and the distinct samples as candidates, the 0-1 risk of a candidate is 1−(its count)/N1 - (\text{its count}) / N, so sampling based MBR under the 0-1 loss returns the most frequent sample, the first one to appear on ties. The test checks this.

Theorem 4 (unbiased and consistent risk estimates). Let y1,y2,…y_1, y_2, \ldots be independent samples from p(⋅∣x)p(\cdot \mid x), and let R^N(h)=1N∑j=1Nℓ(h,yj)\hat R_N(h) = \frac{1}{N} \sum_{j=1}^{N} \ell(h, y_j). If ℓ\ell is bounded by BB, then for each fixed hh, E[R^N(h)]=R(h)E[\hat R_N(h)] = R(h), the true risk under pp, and P(∣R^N(h)−R(h)∣≥ε)≤2exp⁡(−2Nε2/B2)P(|\hat R_N(h) - R(h)| \ge \varepsilon) \le 2 \exp(-2 N \varepsilon^2 / B^2).

Proof. Each term ℓ(h,yj)\ell(h, y_j) has mean ∑yp(y∣x)ℓ(h,y)=R(h)\sum_y p(y \mid x) \ell(h, y) = R(h), so the average has the same mean. The terms are independent and lie in [0,B][0, B], so Hoeffding's inequality gives the bound. □\square

Corollary 5 (the sampled decision). Let H\mathcal{H} be a fixed finite candidate set with a unique minimizer h∗h^* of the true risk, and let Δ>0\Delta > 0 be the gap between R(h∗)R(h^*) and the second smallest risk. Then MBR-DECODE with the evidence (yj,1/N)(y_j, 1/N) returns h∗h^* with probability at least 1−2Hexp⁡(−NΔ2/(2B2))1 - 2 H \exp(-N \Delta^2 / (2 B^2)).

Proof. If every R^N(h)\hat R_N(h) is within Δ/2\Delta / 2 of R(h)R(h), then R^N(h∗)<R(h∗)+Δ/2≤R(h)−Δ/2<R^N(h)\hat R_N(h^*) < R(h^*) + \Delta/2 \le R(h) - \Delta/2 < \hat R_N(h) for every h≠h∗h \ne h^*, and Theorem 1 returns h∗h^*. Apply Theorem 4 with ε=Δ/2\varepsilon = \Delta / 2 to each of the HH candidates and take a union bound. □\square

When the candidates are the distinct samples themselves, the candidate set is random; the corollary then applies to the decision conditioned on the candidate set, as long as the evidence samples are drawn independently of it. With the same samples as candidates and evidence, each candidate also appears in its own evidence, which adds a bias of order 1/N1/N to its estimated risk for a loss with ℓ(h,h)=0\ell(h, h) = 0.

What is not claimed. The theorems say that the decoder computes the decision it defines. They do not say that the decision is a better output under any human judgment; that is a measurement.

Complexity

Each candidate needs NN loss calls, so the time is O(HNL)O(H N L) in the word RAM, for a loss call of cost LL. With the samples as candidates, H≤NH \le N, and the cost is O(N2L)O(N^2 L): 30 samples need up to 900 calls, and the test counts exactly 30×(distinct samples)30 \times (\text{distinct samples}) calls. For the word edit distance between outputs of nn words, L=O(n2)L = O(n^2) by the Wagner-Fischer algorithm; a neural metric such as COMET costs a network call per pair. The space is O(H+N)O(H + N) outputs, plus the work space of the loss.

Drawing the NN samples costs NN decodes of the model, which is often more than the loss calls for string metrics. Over a lattice, the expected loss under the edit distance has no simple closed form, and systems approximate it, for example with a confusion network.

Properties

  • Exact for its inputs (a theorem). The output is a minimizer of the given risk over the given candidates.
  • MAP as a special case (a theorem). The 0-1 loss with the full distribution gives the most probable output.
  • Consistent with samples (a theorem). The sample estimate of each risk is unbiased and converges.
  • Not tied to the mode. A candidate can win without being probable, if it is close to many probable outputs. That avoids the failure of the mode described in inadequacy of the mode, where the most probable output can be empty.
  • Quadratic cost in the number of samples.

Variants and improvements

  • Lattice and N-best MBR. Goel and Byrne 2000 and Kumar and Byrne 2004 work on N-best lists and lattices from a beam decoder, with the probabilities renormalized over the list.
  • Consensus decoding. For the word error rate, align the lattice into a confusion network and take the best word in each slot. This minimizes an approximation to the expected word error at a much lower cost.
  • Separate candidates and evidence. Draw candidates from beam search, and evidence from unbiased samples; or draw candidates from nucleus sampling and evidence from the model. The candidate set should hold good outputs, while the evidence should represent the model.
  • Cheaper risk. Prune candidates with a cheap loss before scoring the survivors with an expensive one, or compare each candidate with the average of the evidence in an embedding space, which makes the cost linear in NN for metrics that allow it.
  • Self-consistency. For answers with a single final value, self-consistency decoding is MBR with the 0-1 loss on the final answer over sampled reasoning paths: the majority vote.

When to use it

Use MBR decoding when you know the metric that will judge the output, the model is not sharp, and you can afford NN samples and up to N2N^2 metric calls: translation with a strong metric, speech recognition with word error rate, or summarization. Do not use it for a single short label, where the most probable answer and the MBR answer agree, or under a tight latency budget.

Pitfalls

  • The loss defines the answer. MBR optimizes the loss you give it, including its blind spots. A neural metric used both to decode and to evaluate inflates the evaluation score; evaluate with a different metric too.
  • Biased evidence. Samples from a truncated or low temperature sampler, or a beam N-best list, are not unbiased samples of the model. The risk is then the risk under a different distribution. Say which one you use.
  • Too few samples. With small NN the risk estimates are noisy, and the choice can change from run to run. Report NN and the seed.
  • Unnormalized log weights. Exponentiating raw log probabilities of long outputs underflows to 0 for every candidate. Normalize in log space first.
  • Utilities versus losses. BLEU is a utility; MBR minimizes $1 - $ BLEU, or maximizes the expected BLEU. Mixing the two signs picks the worst candidate.

Implementations

The code takes the candidates, the evidence and their model scores as given, and implements the decision rule and the sample based front end; it does not run or train a network.

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.

minimum_bayes_risk_decoding.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-bayes-risk-decoding/. The authors are listed in prov/FTCX13.jsonl.

"""Minimum Bayes risk decoding.

The decoder picks, from a set of candidate outputs, the one with the least
expected loss under the model. The expectation runs over a list of evidence
outputs with weights: the exact distribution of a small model, or N samples
of the model with weight 1 / N each. The code takes the candidates, the
samples and their log probabilities as given; it does not run a network.
"""

import math
from typing import Callable, Hashable, List, Optional, Sequence, Tuple, TypeVar

from nlslog import log_normalize

Y = TypeVar("Y", bound=Hashable)
Loss = Callable[[Y, Y], float]


def mbr_decode(
    candidates: Sequence[Y], evidence: Sequence[Tuple[Y, float]], loss: Loss
) -> Tuple[Y, float]:
    """Return (the candidate of least risk, its risk).

    The risk of h is the sum over (y, w) in evidence of w * loss(h, y). On
    ties the first candidate wins. The weights need not sum to 1; the choice
    does not change when every weight is scaled by the same positive number.
    """
    if not candidates:
        raise ValueError("no candidates")
    best: Optional[Y] = None
    best_risk = math.inf  # @line L1
    for h in candidates:  # @line L2
        risk = sum(w * loss(h, y) for y, w in evidence)  # @line L3
        if risk < best_risk:  # @line L4
            best, best_risk = h, risk
    return best, best_risk  # @line L5


def mbr_from_log_probs(
    candidates: Sequence[Y], evidence: Sequence[Tuple[Y, float]], loss: Loss
) -> Tuple[Y, float]:
    """MBR with evidence given as (y, log p(y)); the weights are normalized in log space."""
    ws = [math.exp(v) for v in log_normalize([lp for _, lp in evidence])]
    return mbr_decode(candidates, [(y, w) for (y, _), w in zip(evidence, ws)], loss)


def mbr_from_samples(samples: Sequence[Y], loss: Loss) -> Tuple[Y, float]:
    """Sample-based MBR: the distinct samples are the candidates, all samples the evidence.

    The cost is N * (the number of distinct samples) loss calls for N samples,
    so at most N^2.
    """
    if not samples:
        raise ValueError("no samples")
    seen = {}
    for y in samples:
        seen.setdefault(y, None)
    w = 1.0 / len(samples)
    return mbr_decode(list(seen), [(y, w) for y in samples], loss)


def word_edit_distance(a: Sequence[str], b: Sequence[str]) -> int:
    """Return the Levenshtein distance between two token sequences (unit costs)."""
    prev = list(range(len(b) + 1))
    for i in range(1, len(a) + 1):
        cur = [i] + [0] * len(b)
        for j in range(1, len(b) + 1):
            cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (a[i - 1] != b[j - 1]))
        prev = cur
    return prev[-1]


def zero_one_loss(a, b) -> int:
    """Return 0 if a equals b, else 1."""
    return 0 if a == b else 1


def expected_losses(candidates: Sequence[Y], evidence: Sequence[Tuple[Y, float]], loss: Loss) -> List[float]:
    """Return the risk of each candidate, in order."""
    return [sum(w * loss(h, y) for y, w in evidence) for h in candidates]
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_bayes_risk_decoding.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-bayes-risk-decoding/. The authors are listed in prov/FTCX13.jsonl.

import math
import random
from collections import Counter
from fractions import Fraction

from minimum_bayes_risk_decoding import (
    expected_losses,
    mbr_decode,
    mbr_from_log_probs,
    mbr_from_samples,
    word_edit_distance,
    zero_one_loss,
)

A, B, C, D = ("a", "b", "c"), ("a", "b", "d"), ("a", "e", "d"), ("f", "b", "d")
DIST = [(A, Fraction(7, 25)), (B, Fraction(6, 25)), (C, Fraction(6, 25)), (D, Fraction(6, 25))]


def brute_edit(a, b):
    if not a:
        return len(b)
    if not b:
        return len(a)
    return min(brute_edit(a[1:], b) + 1, brute_edit(a, b[1:]) + 1, brute_edit(a[1:], b[1:]) + (a[0] != b[0]))


def test_example() -> None:
    assert sum(w for _, w in DIST) == 1
    risks = expected_losses([A, B, C, D], DIST, word_edit_distance)
    assert risks == [Fraction(6, 5), Fraction(19, 25), Fraction(32, 25), Fraction(32, 25)]
    assert mbr_decode([A, B, C, D], DIST, word_edit_distance) == (B, Fraction(19, 25))
    # The mode is A, and 0-1 loss picks the mode.
    assert max(DIST, key=lambda t: t[1])[0] == A
    assert mbr_decode([A, B, C, D], DIST, zero_one_loss) == (A, Fraction(18, 25))


def test_edit_distance_against_brute_force() -> None:
    rng = random.Random(1)
    for _ in range(300):
        a = tuple(rng.choice("abc") for _ in range(rng.randrange(6)))
        b = tuple(rng.choice("abc") for _ in range(rng.randrange(6)))
        assert word_edit_distance(a, b) == brute_edit(a, b)
    assert word_edit_distance(["the", "cat", "sat"], ["the", "cat", "sat", "down"]) == 1


def test_zero_one_loss_gives_the_map_output() -> None:
    rng = random.Random(2)
    for _ in range(200):
        ys = [tuple(rng.choice("ab") for _ in range(3)) for _ in range(6)]
        ys = list(dict.fromkeys(ys))
        ws = [Fraction(rng.randrange(1, 20)) for _ in ys]
        dist = [(y, w / sum(ws)) for y, w in zip(ys, ws)]
        got, _ = mbr_decode(ys, dist, zero_one_loss)
        assert dict(dist)[got] == max(w for _, w in dist)


def test_samples_with_zero_one_loss_give_the_most_frequent_sample() -> None:
    rng = random.Random(3)
    for _ in range(200):
        samples = [rng.choice(["x", "y", "z", "w"]) for _ in range(rng.randrange(1, 15))]
        got, risk = mbr_from_samples(samples, zero_one_loss)
        counts = Counter(samples)
        assert counts[got] == max(counts.values())
        assert math.isclose(risk, 1 - counts[got] / len(samples))


def test_number_of_loss_calls() -> None:
    calls = [0]

    def counted(a, b):
        calls[0] += 1
        return word_edit_distance(a, b)

    rng = random.Random(4)
    samples = [rng.choice([A, B, C, D]) for _ in range(30)]
    mbr_from_samples(samples, counted)
    assert calls[0] == 30 * len(set(samples))
    assert calls[0] <= 30 * 30


def test_sampled_mbr_finds_the_exact_choice() -> None:
    rng = random.Random(5)
    ys = [y for y, _ in DIST]
    ws = [float(w) for _, w in DIST]
    samples = rng.choices(ys, weights=ws, k=2000)
    got, risk = mbr_from_samples(samples, word_edit_distance)
    assert got == B
    assert abs(risk - 19 / 25) < 0.05


def test_scaling_and_log_space_weights() -> None:
    scaled = [(y, w * 1000) for y, w in DIST]
    assert mbr_decode([A, B, C, D], scaled, word_edit_distance)[0] == B
    # Log probabilities near -1000 underflow to 0 in exp, but the choice is the same.
    logs = [(y, -1000.0 + math.log(float(w))) for y, w in DIST]
    assert all(math.exp(v) == 0.0 for _, v in logs)
    got, risk = mbr_from_log_probs([A, B, C, D], logs, word_edit_distance)
    assert got == B and math.isclose(risk, 19 / 25)


def test_ties_keep_the_first_candidate() -> None:
    dist = [(C, Fraction(1, 2)), (D, Fraction(1, 2))]
    assert mbr_decode([C, D], dist, word_edit_distance)[0] == C
    assert mbr_decode([D, C], dist, word_edit_distance)[0] == D

History

Bayes decision theory gives the rule directly: the action of least expected loss under the posterior. Goel and Byrne 2000 made it a decoder for speech recognition over N-best lists and lattices, with the word error rate as the loss. Kumar and Byrne 2004 applied it to statistical translation with BLEU and other metrics. Neural translation used beam search for years; Eikema and Aziz 2020 argued that the mode of a neural translation model is often inadequate, and that MBR over unbiased samples is a better use of the model, which renewed interest in the method.

References

  1. Vaibhava Goel and William J. Byrne, Minimum Bayes-risk automatic speech recognition, Computer Speech and Language 14(2), 2000, pages 115 to 135, the minimum Bayes risk decision rule under a general loss, and its approximation over N-best lists and lattices
  2. Shankar Kumar and William Byrne, Minimum Bayes-risk decoding for statistical machine translation, HLT-NAACL 2004, pages 169 to 176, the MBR decoder over N-best lists with loss functions built from BLEU and other translation metrics
  3. Bryan Eikema and Wilker Aziz, Is MAP decoding all you need? The inadequacy of the mode in neural machine translation, COLING 2020, pages 4506 to 4520, sampling based MBR, with unbiased samples of the model as both candidates and pseudo references

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 proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
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
  • a scene preset for the example