Contents Working with Large Language Models Code Course home

Chapter 23Evaluating Generated Text

After this chapter you will be able to

  • compute clipped nn-gram precision, the brevity penalty and BLEU for a short candidate;

  • say why BLEU is a corpus metric and what a single zero does to it;

  • compute ROUGE and say why recall alone can be gamed;

  • name what embedding-based metrics and model judges fix and what they cost;

  • say how a metric is itself judged, and how to test a gain with resampling.

This chapter builds on Chapter 14 and Chapter 15, whose evaluation habits this chapter extends to generated text.

The measurement problem

Chapter 15 evaluated a classifier and the job was straightforward, because there is one right label, the model gives one label, and you compare. Generation breaks that, since there are many correct outputs, they do not resemble each other as strings, and nobody can enumerate them.

Translation shows it first. Take a translation of “Il pleut”, where It is raining, It’s raining and Rain is falling are all correct, so a metric that credits only the first is measuring the wrong thing. Everything in this chapter is an attempt to work around that, and none of the attempts fully succeeds. This is the one place the book evaluates generated text, so every metric a later chapter reports is defined here.

When the answer is a label

Where the output space is closed, use Chapter 15’s machinery unchanged, meaning per-class precision, recall and F1F_1, macro-averaged, with a confusion matrix to say what is failing. Two cautions carry over from there, since accuracy hides which class is wrong and micro-F1F_1 equals accuracy on single-label tasks, so reporting both tells you nothing twice. The rest of the chapter is about the open case.

BLEU

The oldest workable metric for open output compares nn-grams against one or more references and counts the matches. Papineni et al. (2002) proposed it, BLEU, to stand in for human judgement in everyday use, not to replace it on any single sentence. Human scoring is slow and expensive, and a group that retunes a system many times a day cannot wait weeks for it. Their guiding idea is short: the closer a machine translation is to a professional human translation, the better it is. So the metric measures closeness to one or more human references. It sets out to be cheap, fast and language independent. It is judged not by whether it is right on a sentence but by whether it ranks systems the way people do. The rest of this section builds it one piece at a time, and every piece answers a way the simplest version can be gamed.

Precision has to be clipped

Start with unigram precision, which asks what fraction of the candidate’s words appear in a reference. It is trivially gameable, so take the references “the cat is on the mat” and “there is a cat on the mat”, along with the candidate:

the the the the the the the

Every one of those seven words appears in a reference, so unclipped precision is 7/7=1.00007/7 = 1.0000, which is a perfect score for a sentence that says nothing. Modified precision caps each nn-gram at the most any single reference contains, and reference one has the twice, so the ceiling is two.

candidate clipped total p1p_1
the the the …(7 times) 2 7 0.2857
the cat is on the mat 6 6 1.0000

Clipping is not a refinement, because without it the metric can be won by repeating one word and would measure nothing at all. BLEU counts precision and not recall, and the references are the reason. When a sentence has several correct human translations, each phrased its own way, recall has no stable denominator, since a candidate can take different words from different references and look as though it recovered all of them. Precision has a denominator it can trust, the candidate’s own length, so BLEU measures precision and then leans on the brevity penalty of the next section to stop a short candidate from scoring well on precision alone.

The brevity penalty

Precision still rewards saying less, as it does against the reference “the cat is on the mat”:

candidate length p1p_1 BP p1×p_1 \times BP
the 1 1.0000 0.0067 0.0067
the cat 2 1.0000 0.1353 0.1353
the cat is on 4 1.0000 0.6065 0.6065
the cat is on the mat 6 1.0000 1.0000 1.0000
the cat is on the mat today for a while 10 0.6000 1.0000 0.6000

The first row is one word, perfectly precise and useless, and precision alone would rank it top. The brevity penalty fixes that:

BP={1,c>r,exp⁡(1−r/c),c≤r,(23.1)\begin{equation} \text{BP} \;=\; \begin{cases} 1, & c > r, \\ \exp\!\big(1 - r/c\big), & c \le r, \end{cases} \label{eq:bp} \quad\text{(23.1)} \end{equation}

where cc is the candidate length and rr the closest reference length. It is deliberately asymmetric, so that too short is punished while too long is not, because a long candidate is already punished by precision, as the last row shows.

Figure 23.1. The brevity penalty of Equation (23.1). It is 11 at or above the reference length and falls steeply below it. The three marked points are the rows of the table with lengths 22, 44 and 66 against a reference of 66.

BLEU, end to end

BLEU combines the clipped precisions p1p_1 to pNp_N, using their geometric mean, times the brevity penalty:

BLEU=BP⋅exp⁡(∑n=1Nwnlog⁡pn),N=4,wn=1N.(23.2)\begin{equation} \text{BLEU} \;=\; \text{BP} \cdot \exp\!\Big(\sum_{n=1}^{N} w_n \log p_n\Big), \qquad N = 4, \quad w_n = \tfrac{1}{N}. \label{eq:bleu} \quad\text{(23.2)} \end{equation}

The weights are uniform and N=4N = 4 is the standard choice, so the sum of logarithms is a plain average and its exponential is the geometric mean of the four precisions. Working in the log domain is deliberate. Modified precision falls off roughly geometrically as nn grows, so a plain arithmetic mean would be dominated by p1p_1 and would barely feel the high-order terms, whereas averaging logarithms gives each order of nn-gram an equal say.

candidate p1p_1 p2p_2 p3p_3 p4p_4 BLEU-4
the cat is on the mat 1.0000 1.0000 1.0000 1.0000 1.0000
a cat is on the mat 1.0000 1.0000 0.7500 0.6667 0.8409
the cat sat on the mat 0.8333 0.6000 0.2500 0.0000 0.0000
on mat the cat is the 1.0000 0.4000 0.2500 0.0000 0.0000

Three things are worth reading off that table. The geometric mean means one zero sends the whole score to zero, so the third candidate differs from a reference by a single word and scores 00. That severity is why BLEU is reported over a corpus rather than a sentence, since on a single sentence it is close to useless. The last candidate is the reference words in scrambled order, where the unigram precision is perfect and the higher nn-grams collapse, and that is how BLEU sees word order.

Figure 23.2. BLEU-4 of the four candidates of the table against the cat is on the mat. A single substituted word in the middle drops the sentence score to zero, because one zero precision sends the geometric mean to zero. This is why BLEU is reported over a corpus.

A corpus metric, not a sentence one

Every number above is for a single sentence, so the mechanism is visible, but BLEU was defined over a whole test set and is unreliable below one. The clipped matches and the totals are summed across all candidate sentences before the division,

pn=∑C∑n-gram∈Ccountclip∑C∑n-gram∈Ccount,(23.3)\begin{equation} p_n \;=\; \frac{\sum_{C} \sum_{\text{$n$-gram} \in C} \text{count}_\text{clip}} {\sum_{C} \sum_{\text{$n$-gram} \in C} \text{count}}, \label{eq:bleu-corpus} \quad\text{(23.3)} \end{equation}

and the brevity penalty of Equation (23.1) uses the candidate corpus length cc and the matching total reference length rr, not either sentence’s. Aggregating first is what rescues the geometric mean. One hard sentence can zero a pnp_n on its own, but over a few hundred sentences every order of nn-gram picks up some matches, so the corpus score is steady while the sentence scores are not.

Papineni et al. (2002) justified the metric by comparison and not by proof. Given a range of systems, from weak machine output up to professional human translators, BLEU ordered them as the human judges did and tracked the judges’ scores closely. This is the entire claim. BLEU does not measure translation quality, it is a cheap statistic that moves with it, and moving with it was enough to make it the field’s default ever since.

Run it. code/worked_examples/bleu.py produces every table in this chapter. --clip builds the degenerate candidate, --brevity sweeps the length term, and --bleu scores four candidates in full.

Run it

A candidate repeating the seven times, with clipped credit for two
Clipping stops a metric from being gamed. Without it a translation that repeats one common word scores perfectly, so each word is credited at most as often as a reference contains it.

ROUGE, and the other direction

BLEU asks how much of what you said was in the reference, which is precision, and it suits translation. Summarisation cares about the opposite. Did you leave out the important part? This is recall, and it is what ROUGE (Lin 2004) measures. ROUGE is a family, not one number. ROUGE-N is nn-gram recall, the mirror of BLEU’s modified precision,

ROUGE-N=∑n-gram∈Rmin⁡(countcand,countref)∑n-gram∈Rcountref,(23.4)\begin{equation} \text{ROUGE-N} \;=\; \frac{\sum_{\text{$n$-gram} \in R} \min\!\big(\text{count}_\text{cand}, \text{count}_\text{ref}\big)} {\sum_{\text{$n$-gram} \in R} \text{count}_\text{ref}}, \label{eq:rougen} \quad\text{(23.4)} \end{equation}

where the denominator is the reference’s nn-grams, so the question is how many of them the candidate recovered. ROUGE-L replaces fixed nn-grams with the longest common subsequence, rewarding words that appear in the reference’s order without demanding that they be adjacent, and ROUGE-S counts skip-bigrams for the same reason. Each has a recall form, a precision form, and an FF-measure that combines them,

Fβ=(1+β2)PRβ2P+R.F_\beta \;=\; \frac{(1 + \beta^2)\, P R}{\beta^2 P + R}.

Summarisation reports the FF-measure so that padding is punished, since recall alone rewards saying everything. The tables here use the recall form, to keep BLEU and ROUGE side by side.

One bookkeeping note before the table, because it changes the numbers. The BLEU tables above scored against two references, as BLEU classically does, whereas the table below scores against the single reference “the cat is on the mat”. So its BLEU-4 column is a different scoring from the one above, and only an exact match scores 11 in both.

candidate BLEU-4 ROUGE-1 ROUGE-2
the cat is on the mat 1.0000 1.0000 1.0000
the cat 0.0000 0.3333 0.2000
the cat is on the mat and also on a fine rug 0.4172 1.0000 1.0000
the feline rests upon the rug 0.0000 0.3333 0.0000

Row three is padded and ROUGE gives it a perfect score, because every reference nn-gram is present. Recall alone can be won by saying everything, so ROUGE is normally reported with its FF-measure variant.

The row that matters

Row four is a correct paraphrase of the reference and it shares no content word with it. BLEU gives it 0.00000.0000, ROUGE-2 gives it 0.00000.0000, and ROUGE-1 gives it 0.33330.3333, every point of which comes from the word the. Not one content word was credited, and the candidate is right.

ROUGE-L does no better here. The longest subsequence the paraphrase shares with the reference is the two the’s, length two against the reference’s six words, so ROUGE-L credits it 0.33330.3333 as well, every point from a function word.

Neither metric has any notion of meaning. They count string overlap and a paraphrase overlaps in the wrong places, so that single row is the argument for everything that came after.

Run it. code/worked_examples/bleu.py with --rouge runs the paraphrase and prints this table.

Run it

Metrics that tried to fix overlap

The paraphrase row is a lexical failure as much as a semantic one, and two metrics attack it at the level of words before any model of meaning is brought in. METEOR (Banerjee and Lavie 2005) aligns candidate and reference words, but matches them through a stem and a synonym table as well as by exact form, so rests can align with sits and feline with cat. It scores a unigram FF-measure over that alignment, weighted towards recall, and multiplies in a penalty for how fragmented the alignment is, which brings back a little of the word order that BLEU gets from higher nn-grams. On the paraphrase it credits the synonyms that ROUGE and BLEU threw away.

chrF (Popović 2015) drops words for characters and takes the FF-score of character nn-grams. Matching on characters makes it robust to morphology, since rested and resting already share most of their characters, and it needs no tokeniser, so it travels across languages where word-based metrics struggle. It is now a standard companion to BLEU in translation shared tasks.

Both are still counting surface overlap, cleverer overlap, and neither understands the sentence. For that the metric has to carry a model.

Beyond surface overlap

There are three families of response, and each trades a known weakness for a new one. Embedding-based metrics compare meaning, not strings, so BERTScore (Zhang et al. 2020) matches candidate and reference tokens by the cosine similarity of their contextual embeddings from Chapter 16. The paraphrase row above now scores well, which is the intent. The cost is that the metric is now a model with its own training data and its own blind spots, whose number cannot be recomputed by hand.

Trained metrics go further and fit the human scores directly. BLEURT (Sellam et al. 2020) fine-tunes a pretrained encoder to predict human quality ratings, and COMET (Rei et al. 2020) does the same while also reading the source sentence, not only the reference, so it can tell a fluent mistranslation from a faithful one. Both correlate with human judgement better than anything above, and both are only as good as the human scores they were trained on, which age as systems improve. COMET is the current default for translation, for the same reason BLEU was the default before it, that it tracks people more closely than the alternatives.

Model-as-judge asks a strong language model to rate an output against a rubric (Zheng et al. 2023). It handles open-ended tasks nothing else can score and correlates reasonably with human preference, while inheriting every bias of the judge model, including a documented preference for longer answers and for its own outputs. A judge is a measuring instrument that has opinions, so it is useful and it must be calibrated against human judgement, not trusted.

Human evaluation

Human judgement remains the standard everything else is validated against, and it has its own methodology. Pairwise comparison is more reliable than absolute rating, because people are better at ranking two things than at scoring one, and multiple annotators with a reported agreement statistic are necessary, because a single annotator’s number is unmeasurable. It is slow and expensive, so the field keeps trying to automate it and keeps having to come back.

What the scores do not see

Every metric so far asks whether the output resembles a reference, and none asks whether it is true. A summary can be fluent, score high on ROUGE and on BERTScore, and state a fact the source never contained. That failure has a name, hallucination, and it is the dominant error of fluent models, so for summarisation and for retrieval-augmented generation a separate axis is measured, faithfulness, whether every claim in the output is supported by the source.

The measurements reuse earlier machinery. One family runs a natural language inference model (the textual entailment task of Chapter 1) and checks that the source entails each output sentence. Another generates questions from the output and confirms the source answers them the same way. Both are noisy, and both measure something the overlap metrics cannot, since a faithful paraphrase and a fluent fabrication can carry the same ROUGE score.

Which metric, for which task

No metric is correct in general, only fit for a task, and the fit follows the shape of the output.

task what is usually reported
Translation BLEU or chrF to compare, COMET when human correlation matters, and a human check at the end
Summarisation ROUGE for overlap, and a faithfulness score for truth, since a summary can win one and fail the other
Extractive question answering exact match and token F1F_1 against the gold span, where the output space is almost closed
Open-ended generation and dialogue human preference, or a model judge calibrated against it, because there is no reference to match
Code generation execution, the fraction of samples that pass the tests, which ignores the text entirely

The pattern is that the more open the task, the less a reference can be trusted, until at the open end the only sound measure is whether a person, or a well checked stand-in for one, prefers the output.

How a metric is judged

A metric is a claim about human judgement, and it is tested the way any claim is, by correlation. The translation community runs a yearly exercise in which people score system outputs and every metric is ranked by how well it predicts those scores, which is how COMET displaced BLEU and how any new metric earns a place. A metric nobody has correlated with people is an untested instrument.

One more discipline rarely survives a leaderboard. A difference of half a BLEU point between two systems may be noise, so a reported gain should be checked by resampling the test set many times and asking how often the ordering holds. If it holds on nine tenths of the resamples the gain is probably real, and if it does not the two systems are tied whatever the headline number says.

The metric that becomes the target

One closing caution, and it applies to every number in this chapter.

When a measure becomes a target, it ceases to be a good measure.

This is Goodhart’s law in Strathern’s phrasing (Strathern 1997), and benchmark history is a long demonstration of it. Benchmarks saturate, test sets leak into pretraining corpora, and models are tuned against the leaderboard until the leaderboard stops measuring the thing it was built to measure.

No better metric defends against this. The discipline of Chapter 15 does: state your metric, hold out your test set, report the runs that failed, and look at the actual outputs. A number is a summary of an experiment, not a substitute for having looked.

Summary

Generated text has no single right answer, so metrics measure closeness to references. BLEU combines clipped nn-gram precisions by their geometric mean with a brevity penalty that punishes short candidates, not long ones, so one zero precision sends a sentence to zero and the score must be computed over a corpus. ROUGE counts recall of reference nn-grams and is gamed by padding, so its FF-measure is reported. Embedding metrics and model judges compare meaning, not strings, at the cost of being models with their own blind spots, length bias and self-preference. Human evaluation is slow and needs agreement statistics. A metric is judged by how well it predicts human scores, and a gain is tested by resampling. A metric that becomes the target stops measuring what it was chosen for.

Key terms

BLEU. a metric combining clipped nn-gram precisions with a brevity penalty.

clipped precision. nn-gram precision in which a candidate nn-gram counts at most as often as it occurs in a reference.

brevity penalty. a factor below one that punishes candidates shorter than the reference.

ROUGE. a recall-oriented overlap metric used for summaries.

BERTScore. a metric that matches tokens by the cosine of their contextual embeddings.

model judge. a language model asked to score or compare outputs.

Further reading.

For the original definitions, read Papineni et al. (2002) on BLEU and Lin (2004) on ROUGE. Banerjee and Lavie (2005) and Popović (2015) are the overlap metrics that followed, and Sellam et al. (2020) and Rei et al. (2020) are the trained ones. Zhang et al. (2020) introduce BERTScore, and Zheng et al. (2023) study language models as judges and document their biases carefully. Jurafsky and Martin (2025) cover evaluation across tasks with more examples. In practice BLEU comes from sacrebleu, which exists because BLEU scores were for years incomparable between papers, and ROUGE from rouge_score, while nltk.translate.bleu_score is the one closest to the arithmetic above.

Practice problems

23.1 Break unigram precision. Construct a candidate that scores 1.01.0 on unclipped unigram precision and is obviously useless. Then compute its clipped precision and its brevity penalty, and report the final score.

23.2 Why geometric. BLEU uses the geometric mean of four precisions. Compute both the arithmetic and geometric means of (0.83,0.60,0.25,0.00)(0.83, 0.60, 0.25, 0.00). Argue for the one BLEU uses, then argue against it, and say which argument you find stronger for a single sentence.

23.3 Asymmetric by design. Explain why the brevity penalty punishes short candidates and not long ones. Construct a candidate three times the reference length and show what stops it from scoring well.

23.4 The brevity penalty by hand. A reference has 1212 words. Compute the brevity penalty for candidates of 66, 99 and 1212 words, and for one of 1818 words. Say what the last number shows.

23.5 ROUGE by hand. Compute ROUGE-1 recall, precision and FF for the candidate the cat sat on the mat against the reference the cat is on the mat.

Build and measure

23.6 The paraphrase. Write a correct paraphrase of “the cat is on the mat” sharing no content word with it. Compute BLEU-4 and ROUGE-1. Then explain precisely what an embedding-based metric would do differently.

23.7 Overlap is not truth. Write a one-sentence summary of a short paragraph that would score high ROUGE-1 against a reference summary and yet state something the paragraph never says. Name a measurement that would catch the error and explain why ROUGE and BERTScore would not.

In practice

23.8 Judge the judge. You are using a language model to score summaries. Design a procedure that would detect the length bias, and one that would detect self-preference. What would you do if you found either?

23.9 Goodhart in practice. Choose a benchmark from any chapter of this book and describe a way to score well on it without possessing the underlying ability. Then propose one change to the benchmark that would close your loophole, and name what your change breaks.

23.10 The default that reports failure. Score the four candidates of this chapter with nltk.translate.bleu_score.sentence_bleu against the single reference “the cat is on the mat”. You will get the BLEU column exactly, 1.00001.0000, 0.00000.0000, 0.41720.4172 and 0.00000.0000. Now score “the cat sits on the mat”, which is one word from perfect, and watch it return 0.00000.0000 as well. Pass smoothing_function=SmoothingFunction().method1 and it becomes 0.25410.2541. Explain which of the two numbers you would report, why the function is off by default, and what it means that the two zeros in the printed table arrive for different reasons.

23.11 Predict, then score. Before running anything, predict whether BLEU or BERTScore will rank a correct paraphrase above a candidate with one wrong content word. Then score both with a library and compare.

23.12 Which metric? Choose a metric, or a combination, for each of three tasks, a translation system, a summariser and an open-ended chat model, and name what each choice cannot see.

Code for this chapter

Each one reproduces the tables above. Run it in the page, change an input and watch which numbers move.

From Natural Language Processing: From Corpus Statistics to Grounded LLMs, by Ramaseshan Ramachandran.