Algorithmadvanced
Translation edit rate
Also called TER.
Word insertions, deletions, substitutions and block shifts from a translation to its closest reference, over the reference length. Greedy shifts make it an upper bound on the fewest edits.
- Time
- O(n^6) worst
- Space
- O(n²) extra
- Where
- n = the larger of the hypothesis length and the reference length, in words
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Matthew Snover, Bonnie Dorr, Richard Schwartz, Linnea Micciulla, John Makhoul, 2006
Translation edit rate (TER) counts the word edits needed to turn a machine translation output into a reference translation, and divides by the reference length. The edits are the insertion, deletion and substitution of one word, as in edit distance, plus the shift of a block of words to another place, each at cost 1. Lower is better, 0 means an exact match, and the value can exceed 1. Finding the fewest edits with shifts is NP-hard, so TER chooses the shifts greedily, and the computed value is an upper bound on the true minimum.
In plain words
Take the machine output and a human translation of the same sentence. Count how many small changes a person would make to turn the output into the human translation: put a word in, take a word out, change one word into another, or move a group of words to another place. Each change counts 1. Divide the count by the number of words in the human translation.
Moving a group of words counts as one change, so an output with the right phrases in the wrong order is not punished as hard as by plain edit distance.
The search for moves is greedy. It keeps making the move that helps most, while some move helps. It can miss a cheaper set of moves, so the count can be a little too high, but never below the true fewest changes.
The problem
A hypothesis and a reference are lists of words. The allowed edits on are: insert a word, delete a word, substitute a word, and shift a block of consecutive words to another position. Each costs 1. TER of a hypothesis with references is
the fewest edits to the closest reference over the mean reference length (Snover et al. 2006, Section 3). At the corpus level, sacreBLEU divides the sum of the edits by the sum of the mean reference lengths. Lower is better. The range is from 0 up; a long wrong hypothesis needs more edits than the reference has words, so TER can exceed 1.
The exact minimum of is hard: edit distance with block moves is NP-complete (Shapira and Storer 2002), and Snover et al. cite this. TER as defined in practice is the value of the greedy search below. It is an upper bound on the minimum.
Tokenization. The words are the white-space tokens of the text. In the paper, punctuation marks count as words and a difference of case counts as an error, so the text must be tokenized first. sacreBLEU by default ignores case and splits on white space only, and it has options for punctuation and tokenization.
The algorithm
EDIT-DISTANCE is the Wagner-Fischer algorithm on words with a traceback. It returns the distance and flags, for one optimal alignment, which words of and of are errors (not matched with an equal word). SHIFT removes the block and puts it back so that it starts at index .
TER(h, R) ▷ R: the references- 1
best ← +∞ - 2
for each reference r in R do - 3
h' ← h; s ← 0 - 4
(d, errors) ← EDIT-DISTANCE(h', r) - 5
loop - 6
G ← the blocks (i, k) of h' that equal some r[j .. j+k-1], with an error word in both - 7
for each block in G and each destination p ≠ i do d' ← EDIT-DISTANCE(SHIFT(h', i, k, p), r) - 8
pick the try with the largest d - d', then the largest k, the smallest i, the smallest p - 9
if no try has d - d' ≥ 1 then leave the loop - 10
h' ← SHIFT(h', i, k, p); s ← s + 1 - 11
(d, errors) ← EDIT-DISTANCE(h', r) - 12
best ← min(best, s + d) - 13
ℓ ← the mean length of the references in R - 14
if ℓ = 0 then return 0 if best = 0, else 1 - 15
return best / ℓ
Line L6 is how the paper limits the shifts. Snover et al. ask that (1) the shifted words match the reference words at the destination exactly, (2) the words at the old place do not already match the reference, and (3) the reference words at the destination are not already matched. Line L6 keeps (1) as "the block occurs in " and checks (2) and (3) with the error flags of one optimal alignment, as the tercom port of sacreBLEU does. Line L9 is the greedy rule of Algorithm 1 of the paper: a shift is applied while it lowers the edit distance, even by only 1, which leaves the total count unchanged.
Limits in tercom. tercom and sacreBLEU try blocks of at most 10 words, moved at most 50 positions, and compute the edit distance in a beam of width 25. This implementation tries every block and every destination, so on long sentences it can find shifts that tercom does not, and its value can differ from tercom.
Example
The example of Snover et al. (Section 3), lowercased:
- reference: "saudi arabia denied this week information published in the american new york times" (13 words)
- hypothesis: "this week the saudis denied information published in the new york times" (12 words)
The plain edit distance is 6. The greedy search shifts "this week" to after "denied", which gives "the saudis denied this week information published in the new york times". Now three edits remain: substitute "the" by "saudi", "saudis" by "arabia", and insert "american". So TER = (1 + 3)/13 = 4/13 = 0.31.
A second example from the paper: for the reference "a b c d e f c" and the hypothesis "a d e b c f", the shift of "b c" to after "a" gives "a b c d e f", and one insertion finishes the job. TER counts 2 edits, against an edit distance of 4.
Greedy is not optimal. For = "a a b b" and = "b c c a", the edit distance is 4. Moving "b b" to the front gives "b b a a" at distance 2, so 3 edits suffice. But "b b" does not occur in , so line L6 does not allow it. The search moves "a" to the end (distance 3) and then "b" to the front (distance 2), and reports edits.
Correctness
The claim is that for each reference the search ends and returns the cost of a real sequence of edits from to , with . The search ends because each applied shift lowers the edit distance by at least 1, so there are at most shifts. The shifts followed by an optimal alignment of with are a valid sequence of edits, which gives the lower bound. Each shift adds 1 to and takes at least 1 from , which gives the upper bound. These are theorems; the full proof is in the proofs file.
The value is not exact: the example above has and . How close the greedy count is to the minimum on real text is not known in general.
Proof: Greedy TER terminates and returns the cost of a valid edit sequence, between the fewest edits and the plain edit distancefull
Fix a hypothesis and a reference , lists of words. The edits are the insertion, the deletion and the substitution of one word, and the shift of a block: a run of consecutive words of moved to another place. Each costs 1. Let be the word edit distance (insertions, deletions and substitutions only), and let be the least cost of a sequence of edits of the four kinds that turns into . Let .
Lemma 1 (the edit distance). EDIT-DISTANCE of lines L4, L7 and L11 returns , and the words it flags as correct form a common subsequence of and that is matched in order.
Proof. The table is the one of the Wagner-Fischer algorithm, whose correctness gives . The traceback moves from to , and every step goes to a cell whose value plus the cost of the step equals the current value, so the steps form an optimal alignment. A word pair is flagged correct only on a diagonal step with equal words. The diagonal steps of a path from to have strictly decreasing and , so the flagged words are matched in order.
Lemma 2 (termination). Let be the edit distance after shifts. Every round that applies a shift has . Hence the loop of lines L5 to L11 ends after at most shifts.
Proof. Line L9 leaves the loop unless the chosen shift has a gain , and line L10 applies only that shift. The values are non-negative integers that drop by at least 1 per applied shift, so at most shifts are applied. Each round itself is finite: there are finitely many blocks and destinations .
Theorem. For one reference, let be the number of shifts applied, the final hypothesis and the value used at line L12. Then
With several references, line L12 keeps the least , and lines L13 to L15 divide it by the mean reference length (with the stated rule for a length of 0).
Proof. The lower bound: applying the shifts in order turns into , and an optimal alignment of and gives word edits that turn into . Together these are a sequence of edits of the allowed kinds from to , so .
The upper bound: by Lemma 2, by induction on the number of shifts. So .
The rest of lines L1 to L15 takes a minimum over the references and divides by a positive number, or returns the fixed value of line L14.
Remark (the bound is not tight). For = "a a b b" and = "b c c a", . One shift of the block "b b" to the front gives "b b a a", at edit distance 2 from , so . The greedy search may shift only blocks that occur in , and "b b" and "a a" do not. It shifts "a" to the end and then "b" to the front, and returns . The tests find by trying all sequences of shifts. In general no polynomial algorithm for is known: Shapira and Storer (2002) showed that edit distance with block moves is NP-complete.
Remark (complexity). Let be the larger of and . A round tries blocks, and for each block destinations, and each try computes an edit distance in time. So a round takes time, and by Lemma 2 there are at most rounds with a shift plus one final round. The total is time per reference and space. Bounds on the block size and on the distance of a move, as in tercom, cut the number of tries per round.
Complexity
In the word RAM model with words compared in , let be the larger of the two lengths. One round tries blocks with destinations each, and each try costs an edit distance, so a round costs . There are at most rounds with a shift, so the worst case is per reference, and references multiply it by . The space is the table. tercom's limits of 10 words per block and 50 positions per move, and its beam, bring a round down to tries of each in practice. Snover et al. state the beam cuts the edit distance from to .
Properties
- Direction and range. Lower is better. The value is 0 for an exact match and has no fixed upper limit.
- Sentence and corpus. It is defined per sentence. The corpus value divides the summed edits by the summed lengths, so it is not the mean of the sentence values.
- An upper bound. The greedy count is at least the fewest edits and at most the plain edit distance (a theorem).
- Not symmetric. The length in the denominator is the reference length, so exchanging the hypothesis and the reference changes the value.
- Word level. A wrong word ending is a full substitution, unlike in chrF.
- Several references. The edits are counted to the closest reference only, but the length is the mean of all of them.
Variants and improvements
- HTER. Human-targeted TER (Section 4 of the paper): a fluent speaker edits the output into a correct translation with as few changes as possible, and TER is computed against that targeted reference. It measures the post-editing work and is expensive.
- No shifts. Without lines L5 to L11, TER becomes the word error rate of speech recognition: the edit distance over the reference length.
- Normalization and case. tercom and sacreBLEU have options for case, punctuation removal and a tokenizer for Asian scripts. Each option gives another number.
- Exact or approximate moves. Shapira and Storer (2002) give a greedy algorithm with an approximation factor for a restricted form of moves. TER does not use it.
- Other scores. BLEU and chrF count n-grams, and COMET is a trained model.
When to use it
Use TER when the question is how much work it takes to fix the output, for example in post-editing studies, where HTER is the standard. It is also reported next to BLEU and chrF in evaluation campaigns. Report the tool and its options, since the shift search and the normalization change the value. Do not treat it as an exact minimum, and do not compare TER from tools with different shift limits.
Pitfalls
- Exact minimum. The value is a greedy upper bound. Claims that TER is the fewest edits are wrong in general.
- Different tools. tercom, sacreBLEU and other ports differ in shift limits, tie rules and normalization, so their values can differ on the same text.
- Case. The paper counts a case difference as an edit, while tercom and sacreBLEU ignore case unless asked. State which.
- Empty reference. The ratio has a zero denominator. sacreBLEU returns 1 if there are edits and 0 if not; this implementation does the same.
- Higher is worse. Unlike BLEU and chrF, a lower TER is better. Tables that mix them need a clear direction for each column.
- Long sentences. Without limits, the search is . Use the tercom limits for long text.
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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/translation-edit-rate/. The authors are listed in prov/EWE8J4.jsonl.
"""Translation edit rate (TER) of Snover et al. (2006), with greedy shifts.
The input is pre-tokenized: a hypothesis is a list of tokens, and it has one or
more references, each a list of tokens. Every edit costs 1: the insertion, the
deletion or the substitution of one word, and the shift of a block of words.
Finding the fewest edits with shifts is NP-hard, so the shifts are chosen
greedily as in tercom: in each round, among the blocks of the hypothesis that
occur in the reference and contain an error on both sides, the shift that most
lowers the edit distance is applied, while some shift lowers it by at least 1.
The result is the cost of a valid sequence of edits, so it is an upper bound
on the fewest edits, and it is never above the plain edit distance.
This version tries every block and every destination, with no limit on the
block size or the distance moved (tercom limits both). Ties go to the larger
gain, then the longer block, then the earlier block, then the earlier
destination.
"""
from typing import List, Optional, Sequence, Tuple
Tokens = Sequence[str]
def edit_distance_errors(h: Tokens, r: Tokens) -> Tuple[int, List[bool], List[bool]]:
"""Return the word edit distance and, for one optimal alignment, the error flag of each word.
A word of h or r has the flag False when the alignment matches it with an
equal word. The traceback prefers a match, then a substitution, then a
deletion of a word of h, then an insertion of a word of r.
"""
n, m = len(h), len(r)
d = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n + 1):
d[i][0] = i
for j in range(m + 1):
d[0][j] = j
for i in range(1, n + 1):
for j in range(1, m + 1):
d[i][j] = min(d[i - 1][j - 1] + (h[i - 1] != r[j - 1]), d[i - 1][j] + 1, d[i][j - 1] + 1)
herr, rerr = [True] * n, [True] * m
i, j = n, m
while i > 0 or j > 0:
if i > 0 and j > 0 and h[i - 1] == r[j - 1] and d[i][j] == d[i - 1][j - 1]:
herr[i - 1] = rerr[j - 1] = False
i, j = i - 1, j - 1
elif i > 0 and j > 0 and d[i][j] == d[i - 1][j - 1] + 1:
i, j = i - 1, j - 1
elif i > 0 and d[i][j] == d[i - 1][j] + 1:
i -= 1
else:
j -= 1
return d[n][m], herr, rerr
def shift(h: Tokens, i: int, k: int, p: int) -> List[str]:
"""Move the block h[i:i+k] so that it starts at index p of the result."""
block = list(h[i:i + k])
rest = list(h[:i]) + list(h[i + k:])
return rest[:p] + block + rest[p:]
def best_shift(h: Tokens, r: Tokens, d: int, herr: List[bool],
rerr: List[bool]) -> Optional[Tuple[int, int, int, int]]:
"""Return (gain, k, i, p) of the best shift with gain >= 1, or None."""
n, m = len(h), len(r)
best = None
for i in range(n):
for k in range(1, n - i + 1):
if not any(herr[i:i + k]): # @line L6
continue
block = list(h[i:i + k])
if not any(block == list(r[j:j + k]) and any(rerr[j:j + k]) for j in range(m - k + 1)):
continue
for p in range(n - k + 1):
if p == i:
continue
d2, _, _ = edit_distance_errors(shift(h, i, k, p), r) # @line L7
key = (d - d2, k, -i, -p)
if best is None or key > best: # @line L8
best = key
if best is None or best[0] < 1: # @line L9
return None
return best[0], best[1], -best[2], -best[3]
def ter_edits(h: Tokens, r: Tokens) -> Tuple[int, int, List[str]]:
"""Return (edits, shifts, shifted hypothesis) against one reference."""
cur = list(h)
s = 0 # @line L3
d, herr, rerr = edit_distance_errors(cur, r) # @line L4
while True: # @line L5
found = best_shift(cur, r, d, herr, rerr)
if found is None:
break
_, k, i, p = found
cur = shift(cur, i, k, p) # @line L10
s += 1
d, herr, rerr = edit_distance_errors(cur, r) # @line L11
return s + d, s, cur
def ter_stats(h: Tokens, refs: Sequence[Tokens]) -> Tuple[int, float]:
"""Return (the fewest greedy edits over the references, the mean reference length)."""
if not refs:
raise ValueError("each hypothesis needs at least one reference")
best = None # @line L1
for r in refs: # @line L2
e, _, _ = ter_edits(h, r)
best = e if best is None else min(best, e) # @line L12
mean_len = sum(len(r) for r in refs) / len(refs) # @line L13
return best, mean_len
def ratio(edits: float, length: float) -> float:
"""Return edits / length, with 0/0 = 0 and e/0 = 1 for e > 0, as in sacreBLEU."""
if length == 0: # @line L14
return 0.0 if edits == 0 else 1.0
return edits / length # @line L15
def sentence_ter(h: Tokens, refs: Sequence[Tokens]) -> float:
"""Return the TER of one hypothesis. Lower is better; it can exceed 1."""
e, ell = ter_stats(h, refs)
return ratio(e, ell)
def corpus_ter(hyps: Sequence[Tokens], refs: Sequence[Sequence[Tokens]]) -> float:
"""Return the corpus TER: the summed edits over the summed mean reference lengths."""
if len(hyps) != len(refs):
raise ValueError("one list of references per hypothesis")
total_e, total_len = 0, 0.0
for h, rs in zip(hyps, refs):
e, ell = ter_stats(h, rs)
total_e += e
total_len += ell
return ratio(total_e, total_len)
test_translation_edit_rate.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/translation-edit-rate/. The authors are listed in prov/EWE8J4.jsonl.
import random
from collections import deque
from functools import lru_cache
from translation_edit_rate import (
corpus_ter,
edit_distance_errors,
sentence_ter,
shift,
ter_edits,
)
def levenshtein(a, b):
"""Word edit distance by plain recursion with a cache."""
a, b = tuple(a), tuple(b)
@lru_cache(maxsize=None)
def go(i, j):
if i == 0 or j == 0:
return i + j
return min(go(i - 1, j - 1) + (a[i - 1] != b[j - 1]), go(i - 1, j) + 1, go(i, j - 1) + 1)
return go(len(a), len(b))
def exact_with_shifts(h, r):
"""The fewest edits: any number of shifts of any block, then the edit distance."""
start = tuple(h)
dist = {start: 0}
queue = deque([start])
while queue:
x = queue.popleft()
for i in range(len(x)):
for k in range(1, len(x) - i + 1):
for p in range(len(x) - k + 1):
if p != i:
y = tuple(shift(x, i, k, p))
if y not in dist:
dist[y] = dist[x] + 1
queue.append(y)
return min(s + levenshtein(y, r) for y, s in dist.items())
def test_paper_example():
ref = "saudi arabia denied this week information published in the american new york times".split()
hyp = "this week the saudis denied information published in the new york times".split()
edits, shifts, final = ter_edits(hyp, ref)
assert (edits, shifts) == (4, 1)
assert final[:5] == ["the", "saudis", "denied", "this", "week"]
assert sentence_ter(hyp, [ref]) == 4 / 13
assert levenshtein(hyp, ref) == 6
def test_shift_example():
edits, shifts, final = ter_edits("a d e b c f".split(), "a b c d e f c".split())
assert final == "a b c d e f".split()
assert (edits, shifts) == (2, 1)
def test_greedy_is_not_optimal():
h, r = "a a b b".split(), "b c c a".split()
edits, shifts, _ = ter_edits(h, r)
assert (edits, shifts) == (4, 2)
assert exact_with_shifts(h, r) == 3
def test_edit_distance_and_flags():
rng = random.Random(99)
for _ in range(300):
h = [rng.choice("abcd") for _ in range(rng.randint(0, 7))]
r = [rng.choice("abcd") for _ in range(rng.randint(0, 7))]
d, herr, rerr = edit_distance_errors(h, r)
assert d == levenshtein(h, r)
# the matched words, in order, are equal on both sides
hm = [w for w, e in zip(h, herr) if not e]
rm = [w for w, e in zip(r, rerr) if not e]
assert hm == rm
# an optimal alignment with c matches costs max(n, m) - c at least
assert d >= max(len(h), len(r)) - len(hm)
def test_bounds_against_brute_force():
rng = random.Random(2006)
for _ in range(120):
h = [rng.choice("abc") for _ in range(rng.randint(1, 4))]
r = [rng.choice("abc") for _ in range(rng.randint(1, 5))]
edits, shifts, final = ter_edits(h, r)
assert exact_with_shifts(h, r) <= edits <= levenshtein(h, r)
assert sorted(final) == sorted(h)
assert edits == shifts + levenshtein(final, r)
def test_no_shift_cases():
assert ter_edits("a b c".split(), "a b c".split())[:2] == (0, 0)
assert ter_edits("x y".split(), "a b c".split())[:2] == (3, 0)
assert sentence_ter([], [[]]) == 0.0
assert sentence_ter(["a"], [[]]) == 1.0
assert sentence_ter([], [["a", "b"]]) == 1.0
assert sentence_ter("a b c d".split(), [["a"]]) == 3.0
def test_several_references_and_corpus():
h = "the cat sat".split()
refs = ["a cat sat down".split(), "the cat sat".split()]
# the edits are the fewest over the references, the length is the mean length
assert sentence_ter(h, refs) == 0 / 3.5
refs2 = ["a cat sat down".split(), "the dog sat".split()]
assert sentence_ter(h, refs2) == 1 / 3.5
hyps = ["a b".split(), "c d e f".split()]
rs = [["a c".split()], ["c d e f".split()]]
assert corpus_ter(hyps, rs) == 1 / 6
History
TER grew out of word error rate and of edit distances with moves. Snover, Dorr, Schwartz, Micciulla and Makhoul defined TER and HTER at AMTA 2006 for the DARPA GALE program, where HTER became an official measure. They chose a greedy search for shifts because the exact problem is NP-complete (Shapira and Storer 2002), and released tercom. Their paper reports that HTER agrees better with human judgments than BLEU and other automatic scores (a measurement). Matt Post added a port of tercom to sacreBLEU, so that TER can be computed with the same settings as BLEU and chrF.
References
- Snover et al. 2006, Section 3, pages 225 and 226 (the definition, the example with 4 edits over 13 words, the three constraints on shifts and Algorithm 1, the greedy search), Section 4 (HTER)
- Dana Shapira and James A. Storer, Edit Distance with Move Operations, CPM 2002, LNCS 2373, pages 85 to 98, the NP-completeness of edit distance with block moves, and a greedy approximation
- Daniel Lopresti and Andrew Tomkins, Block edit models for approximate string matching, Theoretical Computer Science 181(1), 1997, pages 159 to 179, the NP-completeness of several block edit models
- Matt Post, A Call for Clarity in Reporting BLEU Scores, Third Conference on Machine Translation (WMT), 2018, pages 186 to 191, sacreBLEU, which includes a port of tercom
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EWE8J4 Edit this page History Report an error Markdown