Algorithm Search⌘K

Algorithmcore

Minimum error rate training

Also called MERT.

Tune the weights of a log-linear model to maximize BLEU on n-best lists by exact line search along one direction at a time.

Time
O(n (p + log n)) worst
Space
O(n) extra
Where
n = the total number of candidates in all n-best lists; p = the number of features
Properties
deterministicnot exactofflineiterative
Origin
Franz Josef Och, 2003

Minimum error rate training (MERT) sets the weights of a log-linear translation model so that the translations the model prefers score well under an evaluation metric such as BLEU. It works on fixed n-best lists of candidate translations and changes one direction of the weight vector at a time. Along one direction, the metric is a step function of the step size, and MERT finds its exact maximum by computing where the model's choice changes. The line search is exact, but the whole method is a heuristic: the objective is not smooth and not concave, so the search can stop at a local optimum.

In plain words

A translation system has a few knobs: how much to trust the language model, how much to punish reordering, and so on. For each tuning sentence, the decoder gives a list of candidate translations, and the knobs decide which candidate wins. We want the knob setting whose winners get the best score against the reference translations.

Turn one knob slowly. The winner of a sentence changes only at a few points, where another candidate overtakes it. Between those points nothing changes, so the score of the whole set is flat in pieces. MERT finds all the points where some winner changes, checks the score once in each piece, and moves the knob to the middle of the best piece. Then it does the same for the next knob, and repeats until no knob helps. New candidate lists are then made with the new knobs.

The problem

Translation runs from source sentences f(1),…,f(S)f^{(1)}, \ldots, f^{(S)} to target sentences, each with reference translations. The model scores a candidate ee by w⋅h(e,f)w \cdot h(e, f) with weights w∈Rpw \in \mathbb{R}^p and feature vector hh. For sentence ii the decoder has produced an n-best list CiC_i; each candidate cc has features hi,ch_{i,c} and sufficient statistics ϕi,c\phi_{i,c} for the metric. For BLEU these are the clipped n-gram matches and the n-gram counts for n=1,…,4n = 1, \ldots, 4, the candidate length and the reference length. The model picks c^i(w)=arg⁡max⁡cw⋅hi,c\hat c_i(w) = \arg\max_c w \cdot h_{i,c}, and the goal is

max⁡w  M(w)=μ(∑iϕi,c^i(w)),\max_w \; M(w) = \mu\Bigl(\sum_i \phi_{i, \hat c_i(w)}\Bigr),

where μ\mu turns summed statistics into the corpus score. For an error count, μ\mu is minus the sum. The function MM is piecewise constant in ww, so its gradient is zero almost everywhere and gradient methods do not apply.

The line search. Given ww and a direction dd, find γ\gamma that maximizes F(γ)=M(w+γd)F(\gamma) = M(w + \gamma d). Each candidate's model score along the line is ai,c+γ bi,ca_{i,c} + \gamma \, b_{i,c}, a line with ai,c=w⋅hi,ca_{i,c} = w \cdot h_{i,c} and bi,c=d⋅hi,cb_{i,c} = d \cdot h_{i,c}. The winner of sentence ii at γ\gamma is the highest of its lines, so the winners change only where the upper envelope of the lines changes.

The algorithm

UPPER-ENVELOPE sorts the lines by slope and keeps a stack of the lines on the envelope, each with the point where it starts to be highest, as in the convex hull trick.

  1. UPPER-ENVELOPE(lines) ▷ each line: slope b, intercept a, candidate c
  2. U1 sort lines by slope; for equal slopes keep only the highest
  3. U2 H ← empty stack of (line, start)
  4. U3 for each line ℓ = (b, a, c) in order do
  5. U4 while H is not empty do
  6. U5 x ← the γ where ℓ passes the top line of H
  7. U6 if x ≤ start of the top line then pop H else break
  8. U7 push (ℓ, x) on H, with start −∞ if H was empty
  9. U8 return the starts and the candidates of H
  10. LINE-SEARCH(w, d, n-best lists, μ)
  11. 1events ← empty list
  12. 2for each sentence i do
  13. 3lines ← (d · h_{i,c}, w · h_{i,c}, c) for each candidate c
  14. 4E ← UPPER-ENVELOPE(lines)
  15. 5add φ of the first candidate of E to the running total Φ
  16. 6for each later envelope point g with candidates c_prev, c: add event (g, φ_c − φ_{c_prev})
  17. 7sort events by g
  18. 8best ← μ(Φ); γ* ← (first event) − 1, or 0 if there are no events
  19. 9for each group of events at the same g, in order: add them to Φ; if μ(Φ) > best then best ← μ(Φ); γ* ← middle of g and the next event, or g + 1 after the last
  20. 10return γ*, best

MERT itself is coordinate ascent: for each unit direction (and optionally some random directions), run LINE-SEARCH and move to w+γ∗dw + \gamma^* d if it improves MM. Repeat until no direction improves. The outer loop then decodes the tuning set again with the new weights, merges the new candidates into the n-best lists, and tunes again, until the lists stop growing.

Example

Two sentences, two features, and three candidates each. The metric counts errors (fewer is better). The candidates have features and errors:

sentence candidate hh errors score on the line w=(1,0)w = (1, 0), d=(0,1)d = (0, 1)
1 1 (−1,0)(-1, 0) 2 −1-1
1 2 (−2,1)(-2, 1) 0 −2+γ-2 + \gamma
1 3 (−4,2)(-4, 2) 1 −4+2γ-4 + 2\gamma
2 1 (−1,0)(-1, 0) 1 −1-1
2 2 (−2.5,2)(-2.5, 2) 0 −2.5+2γ-2.5 + 2\gamma
2 3 (−5,4)(-5, 4) 2 −5+4γ-5 + 4\gamma

For sentence 1, line 2 passes line 1 at γ=1\gamma = 1 and line 3 passes line 2 at γ=2\gamma = 2, so the envelope is candidate 1, then 2 from 1, then 3 from 2. For sentence 2, line 2 passes line 1 at 0.750.75, and line 3 passes line 2 at 1.251.25. The sweep over the merged points 0.75,1,1.25,20.75, 1, 1.25, 2 gives the total errors

interval of γ\gamma below 0.75 0.75 to 1 1 to 1.25 1.25 to 2 above 2
winners 1, 1 1, 2 2, 2 2, 3 3, 3
errors 3 2 0 2 3

The best interval is (1,1.25)(1, 1.25) with 0 errors, and the line search returns its middle, γ=1.125\gamma = 1.125, so w=(1,1.125)w = (1, 1.125). At the starting point γ=0\gamma = 0 there were 3 errors. Only 4 points were needed; a grid search would need a step finer than 0.250.25 to find this interval at all.

BLEU as μ\mu. For the candidate "the cat sat on the mat" and the reference "the cat sat on the red mat", the statistics are 6, 4, 3, 2 matches out of 6, 5, 4, 3 n-grams, a candidate length 6 and a reference length 7. BLEU is e1−7/6e^{1 - 7/6} times the geometric mean of 6/6,4/5,3/4,2/36/6, 4/5, 3/4, 2/3, which is 0.6730.673. Over a corpus, the statistics of the chosen candidates are added first, and BLEU is computed once from the sums. This is why the sweep keeps a running total of statistics and not a sum of sentence scores.

Correctness

The line search returns the exact maximum of FF over all γ\gamma that are not breakpoints (a theorem, proved in the proofs file). The two facts behind it are that the upper envelope gives, for each sentence, the winner on every interval between its breakpoints, and that adding the changes of statistics at each breakpoint in sorted order gives the summed statistics on every interval. The value at a breakpoint itself depends on how ties are broken; MERT returns a point in the middle of an interval so that a small change of the weights does not change the result.

Coordinate ascent never lowers MM and stops after finitely many improvements, because MM takes finitely many values. It is a heuristic: it stops at a point that no single line search improves, which need not be a global maximum. Implementations restart from random points to reduce this problem. The test file checks the line search against a grid of 2001 steps on random n-best lists, with BLEU and with smoothed BLEU.

Proof: The line search of minimum error rate training finds the exact maximum of the metric along the linefull

Fix a tuning set of SS sentences. Sentence ii has an n-best list of candidates c=1,…,nic = 1, \ldots, n_i, each with a feature vector hi,c∈RDh_{i,c} \in \mathbb{R}^D and a tuple of sufficient statistics ϕi,c\phi_{i,c} (for BLEU: the clipped n-gram matches, the n-gram counts, the candidate length and the reference length). For weights ww the decoder picks, in each list, the candidate c^i(w)\hat c_i(w) with the largest w⋅hi,cw \cdot h_{i,c}, the smallest index on ties. The corpus value is M(w)=μ(∑iϕi,c^i(w))M(w) = \mu\bigl(\sum_i \phi_{i, \hat c_i(w)}\bigr) for a function μ\mu of the summed statistics. LINE-SEARCH gets ww and a direction dd and looks at F(γ)=M(w+γd)F(\gamma) = M(w + \gamma d) for γ∈R\gamma \in \mathbb{R}.

For candidate cc of sentence ii, (w+γd)⋅hi,c=ai,c+γ bi,c(w + \gamma d) \cdot h_{i,c} = a_{i,c} + \gamma \, b_{i,c} with ai,c=w⋅hi,ca_{i,c} = w \cdot h_{i,c} and bi,c=d⋅hi,cb_{i,c} = d \cdot h_{i,c}: a line in γ\gamma.

Lemma 1 (the upper envelope). UPPER-ENVELOPE returns points −∞=g0<g1<⋯<gr-\infty = g_0 < g_1 < \cdots < g_r and candidates c0,…,crc_0, \ldots, c_r such that for every γ\gamma in the open interval (gq,gq+1)(g_q, g_{q+1}) (with gr+1=+∞g_{r+1} = +\infty), the line of cqc_q is strictly above every line with another slope, and is a highest line.

Proof. Lines U1 sort the lines by slope and keep, for each slope, only the highest one. Among lines with one slope, the highest is above the others for every γ\gamma, so dropping the others changes no maximum. Now the slopes are strictly increasing. For two lines with slopes b0<bb_0 < b, the second is above the first exactly for γ>x=(a0−a)/(b−b0)\gamma > x = (a_0 - a)/(b - b_0), the value of line U5.

Invariant: after each step of line U3, the stack holds the envelope of the lines read so far, as a list of lines with strictly increasing start points, each line highest from its start to the next start. This holds for one line, with start −∞-\infty. Add a line ℓ\ell with a larger slope than all lines on the stack. For large γ\gamma, ℓ\ell is the highest, because its slope is the largest. Let the top line ℓ0\ell_0 start at s0s_0. If ℓ\ell passes ℓ0\ell_0 at x≤s0x \le s_0, then ℓ\ell is above ℓ0\ell_0 on all of ℓ0\ell_0's interval, and ℓ0\ell_0 is no longer on the envelope: line U6 pops it. The interval of the line below now extends to the right, and the same test repeats. If x>s0x > s_0, then ℓ0\ell_0 is highest on (s0,x)(s_0, x), and ℓ\ell is highest from xx on, because ℓ\ell is above ℓ0\ell_0 there and ℓ0\ell_0 was above the lines below it from s0s_0 on. Line U7 pushes ℓ\ell with start xx. If the stack becomes empty, ℓ\ell is above every earlier line everywhere and starts at −∞-\infty. □\square

So for each sentence, c^i(w+γd)\hat c_i(w + \gamma d) is constant on each open interval between its breakpoints gqg_q (the tie rule matters only at the breakpoints and between parallel lines; parallel lines with equal intercepts are equal everywhere, and line U1 keeps the one that the tie rule picks).

Lemma 2 (the sweep). Let GG be the sorted set of all breakpoints of all sentences. On each open interval between two consecutive points of GG, and on the two unbounded intervals, FF is constant. When the loop of line L9 has handled all events at a point g∈Gg \in G, the running total equals ∑iϕi,c^i(γ)\sum_i \phi_{i, \hat c_i(\gamma)} for γ\gamma in the interval that starts at gg.

Proof. On an interval with no breakpoint, no sentence changes its choice, so the sum and FF are constant. At the start (line L5), the total is the sum of the statistics of the first envelope line of each sentence, which is the choice for γ\gamma below every breakpoint. At a breakpoint gqg_q of sentence ii, the choice of ii changes from cq−1c_{q-1} to cqc_q, and the event of line L6 holds ϕi,cq−ϕi,cq−1\phi_{i,c_q} - \phi_{i,c_{q-1}}. Line L9 adds all events at one point together, so after them the total matches the choices just right of gg. By induction over the sorted points, the claim holds. □\square

Theorem. LINE-SEARCH returns (γ∗,v)(\gamma^*, v) with v=max⁡γ∉GF(γ)v = \max_{\gamma \notin G} F(\gamma) and F(γ∗)=vF(\gamma^*) = v. That is, it finds the exact maximum of FF over all γ\gamma that are not breakpoints.

Proof. By Lemma 2, FF takes finitely many values on the intervals between the points of GG, and the loop evaluates μ\mu on each of them once: line L8 on the leftmost interval and line L9 after each point. It keeps the largest value and a γ\gamma inside its interval: one less than the first point for the leftmost interval, one more than the last point for the rightmost, and the midpoint otherwise. A midpoint is not a breakpoint, so F(γ∗)F(\gamma^*) is that interval's value. If GG is empty, FF is constant and γ∗=0\gamma^* = 0. □\square

At a breakpoint itself FF can take another value, which depends on the tie rule; such a value is not robust to any small change of the weights, so the search ignores it.

MERT as a whole. Each accepted line search raises MM strictly, and MM takes finitely many values (one per choice of a candidate in each list), so coordinate ascent stops after finitely many accepted steps. It stops at a point where no line search along the given directions improves MM. This is not a global maximum of MM over RD\mathbb{R}^D: MM is piecewise constant and not concave, and coordinate ascent can stop at a point that only the search along another direction could leave. This is a heuristic.

Cost. For sentence ii with nin_i candidates, line L3 costs O(niD)O(n_i D) and the envelope O(nilog⁡ni)O(n_i \log n_i) for the sort. There are at most N=∑iniN = \sum_i n_i events, sorted in O(Nlog⁡N)O(N \log N), and each costs one addition of statistics and one evaluation of μ\mu. With statistics of constant size, a line search costs O(N(D+log⁡N))O(N (D + \log N)).

Complexity

Count in the word RAM model, with metric statistics of constant size. For sentence ii with nin_i candidates, line L3 costs O(nip)O(n_i p) and the envelope O(nilog⁡ni)O(n_i \log n_i) for the sort; the stack loop is linear, because each line is pushed and popped at most once. There are at most n=∑inin = \sum_i n_i events, sorted in O(nlog⁡n)O(n \log n), and the sweep evaluates μ\mu once per group. So one line search costs O(n(p+log⁡n))O(n (p + \log n)), and one round of coordinate ascent costs pp line searches. The space is O(n)O(n) for the events. The expensive part in practice is not MERT but the decoding that produces the n-best lists, repeated in the outer loop.

Properties

  • Exact line search. Along a line the result is the true maximum on the n-best lists, not an approximation from a grid.
  • Any corpus metric. It needs only that the metric is a function of summed statistics. BLEU, TER and error counts all work.
  • Scale invariant. Multiplying ww by a positive number does not change the winners, so the weights are found only up to scale. Implementations normalize them.
  • Unstable with many features. With more than about 20 to 30 features the result varies much between runs and overfits the tuning set; this is a measurement reported in later work, not a theorem.
  • Only the n-best lists. It optimizes the metric on the lists, not on the full search space. The outer loop of decoding again narrows this gap.

Variants and improvements

  • Random directions and restarts. Search along random directions as well as the unit vectors, and start from several random points. This is the usual defence against local optima.
  • Lattice MERT. Macherey and others (2008) computed the envelope over all paths of a word lattice instead of an n-best list, which gives many more candidates at a modest cost.
  • Regularized MERT. Smoothing the objective, or choosing a point far from the interval ends, makes the result more stable.
  • Other tuning methods. Pairwise ranking optimization, MIRA and minimum risk training scale to many more features. The structured perceptron updates the weights from the best candidate and an oracle candidate.

When to use it

Use MERT to tune a log-linear model with a small number of dense features, up to about 20, for a corpus metric such as BLEU, on a tuning set of a few hundred to a few thousand sentences. Run it several times with different seeds and keep the weights that do best on a held-out set. For models with many sparse features, use a ranking or margin method instead.

Pitfalls

  • Sentence-level metric sums. BLEU of a corpus is not the sum or the mean of sentence BLEU. Add the statistics, then compute the metric.
  • Evaluating at a breakpoint. At the exact γ\gamma where two candidates tie, the winner depends on the tie rule. Return a point inside the interval.
  • Equal slopes. Two candidates with the same d⋅hd \cdot h give parallel lines, and the formula for the crossing divides by zero. Keep only the higher of them, as in line U1.
  • Too few candidates. With short n-best lists, the tuned weights can choose candidates the decoder would never find with new weights. Merge the lists over iterations and decode again until they stop changing.
  • Overfitting. On a small tuning set the metric gain is partly noise. Compare on held-out data.

Implementations

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_error_rate_training.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-error-rate-training/. The authors are listed in prov/P668TA.jsonl.

"""Minimum error rate training (Och 2003): exact line search on n-best lists.

An n-best list holds, for each tuning sentence, candidates (h, stats): h is the
feature vector of the log-linear model and stats is a tuple of sufficient
statistics of the metric (for BLEU: the clipped n-gram matches, the candidate
n-gram counts, the candidate length and the reference length). The metric of a
corpus is metric(sum of the stats of the chosen candidates), to be maximized.

Along the line w + gamma d, the model score of each candidate is the linear
function (w . h) + gamma (d . h). The decoder picks the highest line, so the
chosen candidate of a sentence changes only where the upper envelope of its
lines changes. line_search finds these points exactly, sweeps them in order,
and returns a gamma inside the best interval.
"""

import math
from collections import Counter
from typing import Callable, Optional, Sequence

Cand = tuple[Sequence[float], tuple]
Metric = Callable[[tuple], float]


def dot(a: Sequence[float], b: Sequence[float]) -> float:
    return sum(x * y for x, y in zip(a, b))


def add(a: tuple, b: tuple, sign: int = 1) -> tuple:
    return tuple(x + sign * y for x, y in zip(a, b))


def upper_envelope(lines: list[tuple[float, float, int]]) -> list[tuple[float, int]]:
    """lines: (slope, intercept, index). Returns [(gamma_start, index), ...] with
    gamma_start increasing; index is the highest line from gamma_start to the
    next start. The first start is -inf. Among identical lines the smallest
    index wins."""
    order = sorted(lines, key=lambda x: (x[0], x[1], -x[2]))  # @line U1
    hull: list[tuple[float, float, int, float]] = []  # @line U2
    for k, (b, a, c) in enumerate(order):  # @line U3
        if k + 1 < len(order) and order[k + 1][0] == b:
            continue  # a later line has the same slope and is at least as high
        start = -math.inf
        while hull:  # @line U4
            b0, a0, _, s0 = hull[-1]
            x = (a0 - a) / (b - b0)  # @line U5
            if x <= s0:  # @line U6
                hull.pop()
            else:
                start = x
                break
        hull.append((b, a, c, start))  # @line U7
    return [(s, c) for _, _, c, s in hull]  # @line U8


def line_search(
    w: Sequence[float], d: Sequence[float], nbest: list[list[Cand]], metric: Metric
) -> tuple[float, float]:
    """Return (gamma, value): a step gamma inside an interval where the metric of
    the choices on the line w + gamma d is largest, and that largest value."""
    events = []  # @line L1
    total: Optional[tuple] = None
    for i, cands in enumerate(nbest):  # @line L2
        lines = [(dot(d, h), dot(w, h), c) for c, (h, _) in enumerate(cands)]  # @line L3
        env = upper_envelope(lines)  # @line L4
        first = cands[env[0][1]][1]  # @line L5
        total = first if total is None else add(total, first)
        for (_, c_prev), (g, c) in zip(env, env[1:]):  # @line L6
            events.append((g, add(cands[c][1], cands[c_prev][1], -1)))
    assert total is not None
    events.sort(key=lambda e: e[0])  # @line L7
    best = metric(total)  # @line L8
    best_gamma = events[0][0] - 1.0 if events else 0.0
    k = 0
    while k < len(events):  # @line L9
        g = events[k][0]
        while k < len(events) and events[k][0] == g:
            total = add(total, events[k][1])
            k += 1
        nxt = events[k][0] if k < len(events) else None
        value = metric(total)
        if value > best:
            best = value
            best_gamma = g + 1.0 if nxt is None else (g + nxt) / 2
    return best_gamma, best  # @line L10


def choose(w: Sequence[float], cands: list[Cand]) -> int:
    """The decoder's choice: the highest model score, the smallest index on ties."""
    return max(range(len(cands)), key=lambda c: (dot(w, cands[c][0]), -c))


def corpus_value(w: Sequence[float], nbest: list[list[Cand]], metric: Metric) -> float:
    total = None
    for cands in nbest:
        s = cands[choose(w, cands)][1]
        total = s if total is None else add(total, s)
    return metric(total)


def mert(
    nbest: list[list[Cand]],
    w0: Sequence[float],
    metric: Metric,
    max_rounds: int = 20,
    extra_directions: Sequence[Sequence[float]] = (),
    eps: float = 1e-12,
) -> tuple[list[float], float]:
    """Coordinate ascent with exact line searches along each unit vector (and
    along extra_directions), until a round improves the metric by at most eps."""
    w = list(w0)
    dim = len(w)
    value = corpus_value(w, nbest, metric)
    directions = [[1.0 if k == j else 0.0 for k in range(dim)] for j in range(dim)]
    directions += [list(x) for x in extra_directions]
    for _ in range(max_rounds):
        improved = False
        for d in directions:
            gamma, v = line_search(w, d, nbest, metric)
            if v > value + eps:
                w = [x + gamma * y for x, y in zip(w, d)]
                value = v
                improved = True
        if not improved:
            break
    return w, value


# ---- BLEU as a metric on summed sufficient statistics (Papineni et al. 2002)


def ngrams(tokens: Sequence[str], n: int) -> Counter:
    return Counter(tuple(tokens[k : k + n]) for k in range(len(tokens) - n + 1))


def bleu_stats(cand: Sequence[str], refs: Sequence[Sequence[str]], max_n: int = 4) -> tuple:
    """(matches_1..max_n, counts_1..max_n, candidate length, effective reference
    length). Clipping uses the largest count in any one reference; the
    effective reference length is the closest one, the shorter on ties."""
    matches, counts = [], []
    for n in range(1, max_n + 1):
        c = ngrams(cand, n)
        clip: Counter = Counter()
        for r in refs:
            for g, k in ngrams(r, n).items():
                clip[g] = max(clip[g], k)
        matches.append(sum(min(k, clip[g]) for g, k in c.items()))
        counts.append(sum(c.values()))
    r = min((abs(len(x) - len(cand)), len(x)) for x in refs)[1]
    return tuple(matches) + tuple(counts) + (len(cand), r)


def bleu(stats: tuple, max_n: int = 4) -> float:
    """Corpus BLEU from summed statistics, without smoothing, on a 0 to 1 scale."""
    matches, counts = stats[:max_n], stats[max_n : 2 * max_n]
    c, r = stats[2 * max_n], stats[2 * max_n + 1]
    if c == 0 or any(x == 0 for x in matches):
        return 0.0
    log_p = sum(math.log(mt / ct) for mt, ct in zip(matches, counts)) / max_n
    bp = 1.0 if c > r else math.exp(1 - r / c)
    return bp * math.exp(log_p)
test_minimum_error_rate_training.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-error-rate-training/. The authors are listed in prov/P668TA.jsonl.

import math
import random

from minimum_error_rate_training import (
    bleu,
    bleu_stats,
    choose,
    corpus_value,
    dot,
    line_search,
    mert,
    upper_envelope,
)


def errors(stats: tuple) -> float:
    return -stats[0]


EXAMPLE = [
    [((-1.0, 0.0), (2,)), ((-2.0, 1.0), (0,)), ((-4.0, 2.0), (1,))],
    [((-1.0, 0.0), (1,)), ((-2.5, 2.0), (0,)), ((-5.0, 4.0), (2,))],
]


def test_example() -> None:
    w, d = (1.0, 0.0), (0.0, 1.0)
    envs = [upper_envelope([(dot(d, h), dot(w, h), c) for c, (h, _) in enumerate(cs)]) for cs in EXAMPLE]
    assert envs[0] == [(-math.inf, 0), (1.0, 1), (2.0, 2)]
    assert envs[1] == [(-math.inf, 0), (0.75, 1), (1.25, 2)]
    gamma, value = line_search(w, d, EXAMPLE, errors)
    assert gamma == 1.125 and value == 0
    assert [corpus_value((1.0, g), EXAMPLE, errors) for g in (0.5, 0.9, 1.1, 1.5, 2.5)] == [-3, -2, 0, -2, -3]
    w2, v2 = mert(EXAMPLE, w, errors)
    assert v2 == 0 and corpus_value(w2, EXAMPLE, errors) == 0


def test_bleu_check_values() -> None:
    st = bleu_stats("the cat sat on the mat".split(), ["the cat sat on the red mat".split()])
    assert st == (6, 4, 3, 2, 6, 5, 4, 3, 6, 7)
    assert math.isclose(bleu(st), 0.673182, abs_tol=1e-6)
    st = bleu_stats("the the the the the the the".split(), ["the cat is on the mat".split()], max_n=1)
    assert st[:2] == (2, 7)
    assert bleu((1, 0, 0, 0, 1, 0, 0, 0, 1, 1)) == 0.0


def test_envelope_against_brute_force() -> None:
    rng = random.Random(160)
    for _ in range(300):
        n = rng.randint(1, 8)
        lines = [(rng.randint(-4, 4) * 0.5, rng.randint(-6, 6) * 0.5, c) for c in range(n)]
        env = upper_envelope(lines)
        starts = [s for s, _ in env]
        assert starts == sorted(starts) and starts[0] == -math.inf
        for _ in range(30):
            g = rng.uniform(-20, 20)
            if any(abs(g - s) < 1e-9 for s in starts):
                continue
            want = max(lines, key=lambda x: (x[1] + x[0] * g, -x[2]))
            k = max(i for i, s in enumerate(starts) if s < g)
            got = lines[env[k][1]]
            assert math.isclose(got[1] + got[0] * g, want[1] + want[0] * g, abs_tol=1e-12)


def random_nbest(rng: random.Random, sents: int, n: int, dim: int) -> list:
    refs = [[rng.choice("abcde") for _ in range(rng.randint(4, 7))] for _ in range(sents)]
    nbest = []
    for r in refs:
        cands = []
        for _ in range(n):
            hyp = [rng.choice("abcde") if rng.random() < 0.4 else x for x in r]
            if rng.random() < 0.5:
                hyp = hyp[: rng.randint(2, len(hyp))]
            h = [rng.uniform(-3, 3) for _ in range(dim)]
            cands.append((h, bleu_stats(hyp, [r])))
        nbest.append(cands)
    return nbest


def smoothed_bleu(stats: tuple) -> float:
    """Add-one smoothing on the precisions, so that the grid sees small changes."""
    s = list(stats)
    for k in range(4):
        s[k] += 1
        s[4 + k] += 1
    return bleu(tuple(s))


def test_line_search_against_fine_grid() -> None:
    rng = random.Random(2003)
    for _ in range(6):
        nbest = random_nbest(rng, 4, 5, 3)
        w = [rng.uniform(-1, 1) for _ in range(3)]
        d = [rng.uniform(-1, 1) for _ in range(3)]
        for metric in (bleu, smoothed_bleu):
            gamma, value = line_search(w, d, nbest, metric)
            at = corpus_value([x + gamma * y for x, y in zip(w, d)], nbest, metric)
            assert math.isclose(at, value, abs_tol=1e-12)
            grid = max(
                corpus_value([x + (k / 100) * y for x, y in zip(w, d)], nbest, metric)
                for k in range(-1000, 1001)
            )
            assert value >= grid - 1e-12


def test_mert_never_decreases() -> None:
    rng = random.Random(4)
    for _ in range(10):
        nbest = random_nbest(rng, 5, 6, 3)
        w0 = [rng.uniform(-1, 1) for _ in range(3)]
        start = corpus_value(w0, nbest, smoothed_bleu)
        w, v = mert(nbest, w0, smoothed_bleu, extra_directions=[[1.0, 1.0, 0.0]])
        assert v >= start
        assert math.isclose(corpus_value(w, nbest, smoothed_bleu), v, abs_tol=1e-12)
        # each line through the result gives no further gain on the unit directions
        for j in range(3):
            d = [1.0 if k == j else 0.0 for k in range(3)]
            assert line_search(w, d, nbest, smoothed_bleu)[1] <= v + 1e-12


def test_choose_ties() -> None:
    cands = [((1.0,), (0,)), ((1.0,), (1,))]
    assert choose((2.0,), cands) == 0

History

Before MERT, the weights of log-linear translation models were set by hand or trained for likelihood, as in the maximum entropy training of Och and Ney (2002). Och (2003) observed that the error count of an n-best list is piecewise constant along any line in weight space, gave the exact line search, and showed in his measurements that training for the evaluation metric gave better scores on that metric than likelihood training. MERT became the standard tuning method of the Moses and Joshua toolkits. From about 2008, methods such as MIRA and pairwise ranking took over for models with many features.

References

  1. Och 2003, the training criterion on n-best lists, the observation that the error is piecewise constant along a line, and the exact line search
  2. Papineni et al. 2002, the definition of BLEU from clipped n-gram precisions and the brevity penalty, summed over the corpus
  3. Koehn et al. 2005, Section 2.7 (minimum error rate training: a line search for one weight at a time on n-best lists)
  4. Philipp Koehn, Statistical Machine Translation, Cambridge University Press, 2010, Chapter 9 (discriminative training: parameter tuning and minimum error rate training)

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