Skip to main content

Chapter 23. Generative and Multimodal Outputs

Northstar Trips’ fictional travel assistant gives a fluent itinerary, but the museum is closed that day; its image caption misses a safety sign, and its spoken answer mispronounces a street name. A generic “looks good” rating would not necessarily reveal any of these failures, even though each could matter to the traveler for a different reason.

Before selecting a metric, the team needs to decide what the output must do. A summary may need factual coverage; a translation, meaning and locale; an image, prompt adherence and visual safety; a video, temporal consistency; speech, intelligibility and turn-taking. Because no automatic score establishes overall quality on its own, deterministic checks, qualified review, and a validated model judge can contribute different evidence, provided the team understands what each can and cannot see.

The chapter follows that question across text, images, video, and audio. In each case, the calculations are a starting point for investigation rather than a replacement for the task contract or the people who depend on the result.

After this chapter you will be able to:

Illustrative material. Northstar Trips and its outputs are fictional teaching examples. The practical scenarios and numbers below are constructed for teaching, not observations from a deployed system; toy embeddings are identified as such. Treat each metric as evidence for one defined property, not as a universal quality score.

Evaluation contract

Step Multimodal-output example
Case Answer a traveler’s question using a supplied image, audio clip, or video with relevant and irrelevant details.
Observable evidence Output claims, cited regions or timestamps, modality transformations, and any downstream tool actions.
Oracle Verified attributes or source spans for factual claims; qualified, modality-competent rubric judgments for subjective qualities.
Metric Claim accuracy, critical omission rate, grounding, task completion, and subgroup results; keep preference separate.
Decision Block on critical factual or safety failures; require sufficient qualified review for subjective acceptance criteria.
Failure analysis Trace the miss to perception, alignment, context selection, generation, tool use, or an unsuitable evaluator.

23.1 What changes outside agents: task families, output types, and choosing metrics

The museum’s opening date and the pronunciation of a street name are both quality questions, but they do not have the same unit of evidence. Begin with the unit—a claim, sentence, audio segment, image region, video interval, complete artifact, or user interaction—then name the quality that matters, who depends on it, and which failure blocks release. A scorecard can distinguish non-negotiable constraints, such as no invented dates, from graded qualities, such as readability, while leaving room for uncertainty or abstention.

Match the metric to that task contract. Lexical overlap can help with constrained translation or transcription, but a correct paraphrase may share few words with its reference, while a learned similarity score may align with human judgments on one distribution and fail on another. Preference results also depend on sampling, rubric, context, and who reviewed the outputs, so put subgroup results and representative cases beside the aggregate.

23.2 Text generation tasks: summarization, translation, creative and structured output

Text generation already contains several different evaluation problems. A summary needs factual consistency with its source and coverage of decision-relevant details; a reference summary is not necessarily an exhaustive gold answer. Translation calls for separate attention to meaning, fluency, terminology, and locale conventions. Creative work needs a rubric tied to the brief and audience rather than one reference string, while structured output requires semantic checks on fields and their relationships as well as schema validation.

An audit can sample claims and map them to the source spans that support them. Although a judge can prioritize that review, consequential claims still need evidence. Add cases that turn on negation, numbers, dates, named entities, or conflicting source passages, because these small changes often expose a metric or evaluator’s blind spot.

23.2.1 Summarization metrics: definitions

Keep three questions separate: did the summary reuse the reference’s words, are its claims supported by the source, and did it include the facts that matter? Overlap, faithfulness, and coverage each address a different one of these questions.

Let \(s\) be the source, \(r\) a reference summary, and \(c\) the candidate. The code lower-cases and splits on whitespace; a real pipeline must normalise per language (§8.3).

ROUGE-N [1]. Let \(G_n(x)\) be the multiset of \(n\)-grams of \(x\). The clipped overlap is \(O_n=\sum_{g}\min\big(\#_c(g),\#_r(g)\big)\), so a repeated word cannot be credited more often than the reference uses it.

\[ P_n=\frac{O_n}{|G_n(c)|},\qquad R_n=\frac{O_n}{|G_n(r)|},\qquad F_1=\frac{2P_nR_n}{P_n+R_n} \tag{1}\]

ROUGE-L replaces \(O_n\) with the length of the longest common subsequence \(\mathrm{LCS}(c,r)\), so it rewards word order but not paraphrase:

\[ P_L=\frac{\mathrm{LCS}(c,r)}{|c|},\qquad R_L=\frac{\mathrm{LCS}(c,r)}{|r|} \tag{2}\]

Faithfulness and coverage. Decompose \(c\) into atomic claims \(c_1,\dots,c_m\) and let an auditor mark \(e_j\in\{0,1\}\) when claim \(j\) is entailed by \(s\). Let \(K\) be the source’s key facts with importance weights \(w_k\ge 0\), and \(u_k=1\) when fact \(k\) appears in \(c\).

\[ F=\frac1m\sum_{j=1}^{m}e_j,\qquad C=\frac{\sum_{k\in K}w_k u_k}{\sum_{k\in K}w_k},\qquad F_\beta=\frac{(1+\beta^2)\,F\,C}{\beta^2F+C} \tag{3}\]

Under this convention, \(\beta>1\) gives coverage more weight and \(\beta<1\) gives faithfulness more weight. If a summary drives an action, do not let an unsupported number disappear in an average: make that failure a hard item-level gate.

Compression ratio compares token counts:

\[ \rho=\frac{|c|}{|s|} \tag{4}\]

It guards against a “summary” that is the source again, but a shorter result is not necessarily complete or faithful.

Correcting a judge’s pass rate. Suppose a model judge flags a share \(\hat q\) of summaries as faithful. Measured against adjudicated labels, it has sensitivity \(\mathrm{Se}=P(\text{flag}\mid\text{faithful})\) and specificity \(\mathrm{Sp}=P(\text{no flag}\mid\text{unfaithful})\). The flagged share satisfies \(q=\pi\,\mathrm{Se}+(1-\pi)(1-\mathrm{Sp})\), so the true faithful rate is

\[ \hat\pi=\frac{\hat q-(1-\mathrm{Sp})}{\mathrm{Se}+\mathrm{Sp}-1} \tag{5}\]

This is the Rogan–Gladen correction [2].

The correction is undefined when \(\mathrm{Se}+\mathrm{Sp}=1\). Below 1 the denominator is negative rather than undefined: the judge’s flag is inversely associated with the label under this model, and reversing its labels may be informative if that behavior is stable. Near 1 the correction is unstable in either direction. Sensitivity and specificity are estimates too, so carry their uncertainty through and check that their values apply to the target population. The lab helper is more restrictive than the formula: it rejects \(\mathrm{Se}+\mathrm{Sp}\leq1\) and clips its result to \([0,1]\). Inspect the unbounded calculation separately, since clipping can conceal incompatible estimates.

Worked example (Harbor & Pine, synthetic). The source says order 1004’s refund was approved Monday and the customer will receive 40 dollars within five business days. The ten-token reference summary is compared with three candidates:

Candidate Text
good order 1004 refund approved monday and the customer receives 40 dollars
bad order 1004 refund approved monday and the customer receives 400 dollars
paraphrase customer gets 40 dollars as the refund for order 1004 approved monday

Hand calculation for ROUGE-1 on “good”. Of the candidate’s 11 tokens, 9 appear in the reference. Using Equation 1 gives \(P_1=9/11\) and \(R_1=9/10\), then \(F_1=\frac{2\cdot(9/11)(9/10)}{9/11+9/10}=\frac{6}{7}=0.857\). In “bad”, 400 does not match 40; overlap drops to 8 and \(F_1=0.762\). For ROUGE-L, the longest common subsequence contains 8 tokens, so Equation 2 gives \(P_L=8/11\), \(R_L=8/10\), and an F1 of \(16/21=0.762\).

If the source contained 100 tokens under the same tokenizer, the 11-token “good” candidate would have compression ratio \(11/100=0.11\) by Equation 4. That says how much shorter it is, not whether the omitted delivery window matters.

Claim-level labels. The auditor splits each candidate into claims about the order/refund, approval day, and amount, then marks four source facts: order number, Monday, 40 dollars, and the five-business-day delivery window. All candidates omit that window, so the first and third cover three of four facts (\(C=3/4\)). “Bad” also states the wrong amount, making that claim unsupported and leaving the amount fact uncovered.

The equal-weight calculation can be adjusted to reflect the decision. For example, give the amount weight 3 and each other fact weight 1. The “bad” candidate covers only the order number and approval day, so Equation 3 gives \(C=(1+1)/(1+1+3+1)=1/3\). Its faithfulness is \(2/3\); with \(\beta=1\), the combined score is \(4/9\approx0.444\). Weighting changes the score, but it does not replace a hard gate on an incorrect refund amount.

from bookkit.generative_metrics import rouge_n, rouge_l, summary_quality

reference = "refund for order 1004 approved monday customer receives 40 dollars"
good = "order 1004 refund approved monday and the customer receives 40 dollars"
bad = "order 1004 refund approved monday and the customer receives 400 dollars"
para = "customer gets 40 dollars as the refund for order 1004 approved monday"

for name, cand in [("good", good), ("bad", bad), ("paraphrase", para)]:
    print(name, "rouge1 F1:", round(rouge_n(reference, cand, 1)["f1"], 3),
          "rougeL F1:", round(rouge_l(reference, cand)["f1"], 3))
print("good:", summary_quality([True, True, True], [True, True, True, False]))
print("bad: ", summary_quality([True, True, False], [True, True, False, False]))
good rouge1 F1: 0.857 rougeL F1: 0.762
bad rouge1 F1: 0.762 rougeL F1: 0.667
paraphrase rouge1 F1: 0.818 rougeL F1: 0.545
good: {'faithfulness': 1.0, 'coverage': 0.75, 'f_beta': 0.8571428571428571}
bad:  {'faithfulness': 0.6666666666666666, 'coverage': 0.5, 'f_beta': 0.5714285714285715}

Reading the numbers. Replacing 40 with 400 changes ROUGE-1 by just 0.095, from 0.857 to 0.762, even though the summary now promises ten times the refund. Claim faithfulness drops from 1.0 to 0.667, and \(F_\beta\) with \(\beta=1\) falls from 0.857 to 0.571. The paraphrase has the lowest ROUGE-L (0.545), yet all three claims are supported. The practical choice is clear: use overlap as a reference-similarity signal and inspect claims when factual correctness matters.

Correcting the judge. Suppose the judge marks 90% of summaries faithful, with adjudicated sensitivity \(\mathrm{Se}=0.95\) and specificity \(\mathrm{Sp}=0.80\). By Equation 5, \(\hat\pi=(0.90-0.20)/(0.95+0.80-1)=0.70/0.75=0.933\): in this example the raw rate understates faithfulness. At that rate, false rejections affect \(0.933\times0.05=4.7\%\) of all summaries, while false accepts affect \(0.067\times0.20=1.3\%\). If sensitivity falls to 0.85, the same observed 90% yields \((0.90-0.20)/(0.85+0.80-1)=1.08\), outside the possible range. That inconsistency is a warning about the measured rates, not a reason to clip and trust the result. Measure both sensitivity and specificity before deciding which way a raw pass rate is biased.

23.2.2 Embedding-based similarity: BERTScore (formulas only)

ROUGE and BLEU reward shared surface forms, whereas BERTScore [3] compares contextual token embeddings, which can give a paraphrase credit even when it uses different words. Because the calculation depends on a pretrained encoder, this section gives the definition and a hand calculation, not executable code.

Let the reference tokens \(x_1,\dots,x_k\) and candidate tokens \(\hat x_1,\dots,\hat x_l\) be mapped by an encoder to contextual vectors, each scaled to unit length so that the dot product is the cosine. With greedy matching:

\[ R=\frac1k\sum_{i=1}^{k}\max_{j}\,x_i^{\top}\hat x_j,\qquad P=\frac1l\sum_{j=1}^{l}\max_{i}\,x_i^{\top}\hat x_j,\qquad F=\frac{2PR}{P+R} \tag{6}\]

Read \(R\) as the mean best-match cosine for reference tokens, and \(P\) as the corresponding mean for candidate tokens. They are similarity averages, not fractions of tokens verified as correct; cosine values can be negative. Two optional refinements are:

\[ R_{\mathrm{idf}}=\frac{\sum_i \mathrm{idf}(x_i)\,\max_j x_i^{\top}\hat x_j}{\sum_i \mathrm{idf}(x_i)},\qquad \hat R=\frac{R-b}{1-b} \tag{7}\]

Inverse-document-frequency weights, estimated on a reference corpus, give common words less influence, while baseline rescaling subtracts a configuration-specific baseline \(b\) to spread scores over a more readable range. With a fixed \(b<1\), this affine transformation preserves ranking of the rescaled quantity; different baselines or configurations need not.

Limits. Greedy matching allows one candidate token to match multiple reference tokens; it does not enforce one-to-one fact coverage. Scores also depend on encoder, layer, and language, so compare results only within a fixed configuration. Embeddings may place a wrong number, date, or negation close to the right one. Test minimal pairs that differ in exactly one such detail and confirm the metric separates them before using it.

Worked example (toy vectors). The two-dimensional unit vectors below make the arithmetic easy; they do not come from a real encoder. The reference tokens are \((1,0)\) and \((0,1)\). The candidate tokens are \((0.8,0.6)\), \((0.6,0.8)\), and an unrelated \((0,-1)\).

\((0.8,0.6)\) \((0.6,0.8)\) \((0,-1)\) row max
ref \((1,0)\) 0.8 0.6 0 0.8
ref \((0,1)\) 0.6 0.8 \(-1\) 0.8
column max 0.8 0.8 0

Recall averages the row maxima: \(R=(0.8+0.8)/2=0.8\). Precision averages the column maxima: \(P=(0.8+0.8+0)/3=0.533\). Then \(F=2(0.533)(0.8)/(0.533+0.8)=0.64\). With an illustrative baseline \(b=0.5\), \(\hat R=(0.8-0.5)/(1-0.5)=0.6\).

The unrelated third token lowers precision without changing recall, which is why both numbers matter. A second copy lowers \(P\) to \(1.6/4=0.4\) and \(F\) to 0.533 while \(R\) remains 0.8. Thus unrelated padding reduces the score, while matching padding can inflate precision; a high \(P\) by itself is not evidence that the candidate is faithful.

For a separate toy example of Equation 7, imagine a common token has best-match cosine 0.9 and IDF weight 1, while a rarer destination name has cosine 0.5 and weight 3. Unweighted recall is \((0.9+0.5)/2=0.7\); IDF-weighted recall is \((1(0.9)+3(0.5))/(1+3)=0.6\). The mismatch on the destination has more influence, but the weights and cosines remain illustrative rather than encoder measurements.

23.3 Multilingual and cross-lingual evaluation

The summary example is in English, but neither a rubric nor a metric automatically carries over to every language. A strong global average can hide failures in low-resource languages, dialects, scripts, or locales. Check language identification, code-switching, transliteration, names, units, date formats, and culturally specific pragmatics, with reviewers qualified in the language and context under review. NLLB’s human-centered multilingual machine-translation work illustrates the breadth of coverage and evaluation questions involved [4].

Validate the judge separately in every target language by comparing blinded ratings with qualified human labels, measuring disagreement, and checking for preference toward a particular language or writing style. Back-translation can help diagnose changes, but it does not prove equivalence and may erase dialect or cultural meaning. Similarly, BLEU-like overlap can support constrained comparisons when references exist; it is not a stand-alone semantic score [5].

23.3.1 Multilingual metrics: definitions

BLEU [5]. With clipped \(n\)-gram precisions \(p_n\) (computed as in ROUGE, but divided by the candidate’s \(n\)-gram count), reference length \(r\) and candidate length \(c\) in tokens:

\[ \mathrm{BLEU}=\mathrm{BP}\cdot\exp\Big(\tfrac14\sum_{n=1}^{4}\log p_n\Big),\qquad \mathrm{BP}=\begin{cases}1 & c>r\\ e^{\,1-r/c} & c\le r\end{cases} \tag{8}\]

This lab implementation applies no smoothing: if any \(p_n=0\), BLEU is 0. For a short segment that can happen easily, so report a properly aggregated corpus BLEU rather than treating a sentence score as a verdict. The lab uses whitespace-delimited tokens, whereas other implementations use different tokenizers. Select and document an appropriate tokenizer or segmentation for each language, including Chinese, Japanese, and Thai.

For a concrete brevity penalty, suppose a translation reference is “the museum opens on monday” and the candidate is “the museum opens on.” All candidate \(n\)-grams through order 4 match, so each \(p_n=1\), but \(c=4\) and \(r=5\). Using Equation 8 gives \(\mathrm{BP}=e^{1-5/4}\approx0.779\) and a segment score of 0.779. The score notices the short output but does not tell us that the omitted day is essential.

chrF [6]. Compare character \(n\)-grams instead of words, ignoring spaces. For each \(n=1,\dots,6\) let \(\mathrm{chrP}_n\) and \(\mathrm{chrR}_n\) be the character \(n\)-gram precision and recall, and combine them with a recall-weighted \(F_\beta\) (\(\beta=2\)):

\[ \mathrm{chrF}_n=\frac{(1+\beta^2)\,\mathrm{chrP}_n\,\mathrm{chrR}_n}{\beta^2\,\mathrm{chrP}_n+\mathrm{chrR}_n},\qquad \mathrm{chrF}=\frac16\sum_{n=1}^{6}\mathrm{chrF}_n \tag{9}\]

The published metric averages precision and recall across \(n\) before combining them. bookkit instead averages the individual per-\(n\) scores. The results are close but not identical; name the implementation in your report.

For one character-bigram component, compare candidate “book” with reference “books.” All 3 candidate bigrams match, while only 3 of the reference’s 4 do: \(\mathrm{chrP}_2=1\) and \(\mathrm{chrR}_2=3/4\). With \(\beta=2\), Equation 9 gives \(\mathrm{chrF}_2=5(1)(0.75)/(4(1)+0.75)\approx0.789\). This is one component, not the complete six-order score.

Cross-lingual transfer gap. For a metric \(M\) with source-language items \(S\) and target-language items \(T\) scored by the same procedure:

\[ \Delta=\bar M_S-\bar M_T,\qquad \Delta_{\mathrm{rel}}=\frac{\Delta}{\bar M_S} \tag{10}\]

Interpret a gap only when the two item sets have comparable difficulty. In practice, translated parallel items are usually a better comparison than independently collected sets.

Language scorecard. With \(L\) languages, \(n_\ell\) items and mean score \(\bar M_\ell\):

\[ M_{\mathrm{pooled}}=\frac{\sum_\ell n_\ell\bar M_\ell}{\sum_\ell n_\ell},\qquad M_{\mathrm{macro}}=\frac1L\sum_\ell\bar M_\ell,\qquad M_{\min}=\min_\ell\bar M_\ell \tag{11}\]

The pooled mean describes the sampled mixture, not necessarily average traffic; the latter interpretation requires a representative sample or justified traffic weights. The macro mean, by contrast, gives each language equal weight, and the minimum identifies the lowest observed language score. Report all three with \(n_\ell\) and uncertainty, because small samples can make the observed minimum unstable.

Worked example (synthetic). Consider an agent with 90 English items at 0.92, 6 Swahili items at 0.55, and 4 Yoruba items at 0.48.

from bookkit.generative_metrics import bleu, chrf, language_scorecard, transfer_gap

ref = "please send the invoice to my office address"
para = "kindly mail the bill to my work address"
print("bleu exact:", round(bleu(ref, ref)["bleu"], 3))
print("bleu paraphrase:", round(bleu(ref, para)["bleu"], 3),
      "| chrF paraphrase:", round(chrf(ref, para), 3))
print(transfer_gap([0.91, 0.89, 0.93], [0.74, 0.70, 0.78]))
print(language_scorecard({"en": [0.92] * 90, "sw": [0.55] * 6, "yo": [0.48] * 4}))
bleu exact: 1.0
bleu paraphrase: 0.0 | chrF paraphrase: 0.255
{'source_mean': 0.91, 'target_mean': 0.7399999999999999, 'gap': 0.17000000000000015, 'relative_gap': 0.18681318681318698}
{'pooled': 0.8802, 'macro': 0.65, 'weighted': 0.65, 'worst_language': 'yo', 'worst_score': 0.48}

Reading the numbers. The paraphrase means the same as the reference but shares only four words (“the”, “to”, “my”, “address”), one bigram (“to my”), and no trigram. With \(p_3=0\), BLEU’s geometric mean becomes 0; chrF gives 0.255 because the strings share character sequences. Neither score establishes translation quality; each describes similarity to this one reference. The transfer gap is \(0.91-0.74=0.17\), or an 18.7% relative drop. The pooled result of 0.880 looks strong, while the macro mean is 0.65 and Yoruba is lowest at 0.48. That Yoruba estimate rests on only 4 items and is highly uncertain. The small denominator is a coverage gap, not evidence that the language is supported.

23.3.2 Learned translation metrics and validating any metric (formulas only)

COMET [7] is a trained regressor, not a similarity formula. A multilingual encoder maps the source \(s\), the hypothesis \(h\) and the reference \(r\) to sentence embeddings \(e_s,e_h,e_r\). In the original reference-based estimator these are combined into one feature vector, which a feed-forward network maps to a quality score:

\[ z=\big[\,e_h;\ e_r;\ e_h\odot e_s;\ e_h\odot e_r;\ |e_h-e_s|;\ |e_h-e_r|\,\big],\qquad \hat y=f_\theta(z) \tag{12}\]

The network is trained to match human quality scores \(y_i\) by minimising the mean squared error:

\[ \mathcal L(\theta)=\frac1N\sum_{i=1}^{N}\big(f_\theta(z_i)-y_i\big)^2 \tag{13}\]

Here \(\odot\) denotes element-wise multiplication and \([\cdot;\cdot]\) concatenation. Because COMET is trained, treat its output as a score on the checkpoint’s training-label scale, not a probability or percentage: it can rank systems on one test set, but it does not supply an absolute quality judgment. Validate it against human labels for every language pair you ship (§8.3.1), and record the checkpoint because a new checkpoint is a different instrument.

Worked example (toy training features). For a travel notice, suppose an encoder produced one-dimensional values \(e_s=0.5\), \(e_h=0.8\), and \(e_r=0.6\). Using Equation 12 gives \(z=[0.8,0.6,0.4,0.48,0.3,0.2]\). Suppose the network predicts 0.8 for this example and 0.5 for another, while their human labels are 0.9 and 0.7 on the chosen training scale. By Equation 13, their mean squared error is \(((0.8-0.9)^2+(0.5-0.7)^2)/2=0.025\). These invented vectors and scores only demonstrate the arithmetic; they are not output from a COMET checkpoint.

Validating any automatic metric against humans. For \(N\) segments, pair each metric value \(m_i\) with a human score \(h_i\) and report several views of association. Pearson \(r\) measures linear association, not absolute agreement; Spearman \(\rho\) is the Pearson correlation of the ranks. The following simplified Kendall-style \(\tau\) uses only pairs where both human and metric scores differ:

\[ \tau=\frac{C-D}{C+D} \tag{14}\]

Here \(C\) counts pairs where metric and humans prefer the same output, and \(D\) counts pairs where they disagree. Exclude ties in either score from this particular denominator, report how many were excluded, and use a tie-aware statistic when ties matter. Report segment-level and system-level correlations separately: one asks whether the metric ranks individual outputs, the other whether it ranks systems.

Comparing two systems with a metric. On the same \(N\) items, define each paired difference and its mean as

\[ d_i=m_{A,i}-m_{B,i},\qquad \hat\Delta=\frac1N\sum_i d_i \tag{15}\]

Resample the independent sampling units with replacement \(B\) times, retaining both system scores, recompute \(\hat\Delta^*\), and take the percentile interval (Appendix H.4.3). If segments share documents or speakers, resample at an appropriate cluster level. Although an interval above zero supports a positive metric difference under the sampling assumptions, it does not by itself establish human or practical superiority.

Worked example. Humans clearly prefer one output in 5 pairs, and the metric agrees on 4. Thus \(C=4\), \(D=1\), and \(\tau=(4-1)/(4+1)=0.6\). At just five pairs, one changed judgment moves \(\tau\) by 0.4; collect more pairs before using this estimate to make a decision.

For a separate paired comparison, suppose systems A and B receive metric scores \((0.8,0.6,0.9)\) and \((0.7,0.7,0.7)\) on the same three independent travel notices. The differences in Equation 15 are \((0.1,-0.1,0.2)\), averaging \(0.067\). A bootstrap draw of items \((1,1,3)\) would give \((0.1+0.1+0.2)/3=0.133\); repeat the resampling to construct an interval. Three notices are too few for a dependable release decision.

23.4 Image understanding and generation

An image adds another evidence boundary: the evaluator needs to know not only what the answer says, but which visual content was available and where it came from. For image understanding, keep answer accuracy, OCR character and field accuracy, region grounding, chart values, and document extraction separate, and save the original image, crop, resolution, and preprocessing version with each result, subject to access and retention controls. In a document workflow, even a correct answer tied to the wrong region may cause a harmful downstream action.

For image generation, score each requested attribute, composition, technical defects, and human preference; keep safety and disallowed content as explicit gates. One reference image rarely captures every valid way to satisfy a prompt. Use reviewed cases for text rendering, object counts, spatial relations, rare concepts, and demographic representation. CLIPScore can help measure image-text compatibility, but it does not cover the full quality decision [8].

23.4.1 Image metrics: definitions

Region grounding (understanding). For a predicted box \(B_p\) and a labelled box \(B_t\), each \((x_1,y_1,x_2,y_2)\):

\[ \mathrm{IoU}(B_p,B_t)=\frac{|B_p\cap B_t|}{|B_p|+|B_t|-|B_p\cap B_t|},\qquad \mathrm{Acc}@\tau=\frac1N\sum_{i=1}^{N}\mathbb 1\big[\mathrm{IoU}(B_p^{(i)},B_t^{(i)})\ge\tau\big] \tag{16}\]

Choose \(\tau\) to match the product consequence. At \(\tau=0.5\), a box passes when its overlap is half the combined area; that may still clip a document field used by a downstream crop.

Character error rate (OCR). With Levenshtein distance \(d_{\mathrm{lev}}\) over characters and reference length \(|r|\):

\[ \mathrm{CER}=\frac{d_{\mathrm{lev}}(r,h)}{|r|} \tag{17}\]

CER counts character edits, not incorrect fields: one mistaken amount digit contributes only one edit but can invalidate the invoice. For that reason, report exact-match accuracy for critical fields too.

Counting. For predicted counts \(\hat n_i\) and true counts \(n_i\):

\[ \mathrm{MAE}=\frac1N\sum_i|\hat n_i-n_i|,\qquad \mathrm{Exact}=\frac1N\sum_i\mathbb 1[\hat n_i=n_i] \tag{18}\]

CLIPScore (generation) [8]. With image and text embeddings \(v\) and \(t\) from the same encoder:

\[ \mathrm{CLIPScore}(v,t)=w\cdot\max\big(\cos(v,t),\,0\big),\qquad w=2.5 \tag{19}\]

This score measures compatibility in a particular encoder’s embedding space. It can miss a wrong object count, misspelled text in the image, or an unsafe detail.

Gated prompt adherence. Decompose the prompt into \(A\) checkable attributes (object, colour, count, spatial relation, rendered text) with indicators \(a_k\in\{0,1\}\) from reviewers. Let \(g\in\{0,1\}\) be the conjunction of hard gates (safety, disallowed content):

\[ \mathrm{Adh}=g\cdot\frac1A\sum_{k=1}^{A}a_k \tag{20}\]

Because the gate multiplies the attribute score, an unsafe image scores 0 even if every requested attribute is present. Use the gate for constraints that quality elsewhere cannot compensate for.

Bradley–Terry preference [9]. For pairwise human comparisons let \(W_{ij}\) be the number of times \(i\) beat \(j\). Strengths \(\pi_i>0\) define \(P(i\succ j)=\pi_i/(\pi_i+\pi_j)\), and the maximum-likelihood strengths satisfy the fixed point

\[ \pi_i\leftarrow\frac{\sum_{j}W_{ij}}{\sum_{j\ne i}\dfrac{W_{ij}+W_{ji}}{\pi_i+\pi_j}}, \tag{21}\]

normalised to sum to 1. The fitted strengths account for which systems were compared, but their interpretation depends on the Bradley–Terry assumptions, comparison design, and reviewer population. Disconnected comparison graphs or complete separation can prevent unique finite estimates; ties need an explicit treatment. Report uncertainty alongside fitted strengths.

Worked example (synthetic).

from bookkit.generative_metrics import (
    bradley_terry, character_error_rate, clip_score, counting_error,
    grounding_accuracy, iou, prompt_adherence,
)

print("iou:", round(iou((0, 0, 10, 10), (5, 5, 15, 15)), 4))
print("grounding@0.5:", grounding_accuracy(
    [(0, 0, 10, 10), (0, 0, 10, 10)], [(1, 1, 10, 10), (20, 20, 30, 30)]))
print("CER:", round(character_error_rate("TOTAL 40.00", "TOTAL 4O.OO"), 3))
print("counts:", counting_error([3, 5, 2], [3, 4, 2]))
print("clip:", round(clip_score([1.0, 0.0], [0.8, 0.6]), 3))
print("adherence:", prompt_adherence([True, True, False, True]),
      prompt_adherence([True, True, True, True], hard_gates_passed=False))
bt = bradley_terry({("A", "B"): 7, ("B", "A"): 3, ("B", "C"): 6, ("C", "B"): 4,
                    ("A", "C"): 8, ("C", "A"): 2})
print({k: round(v, 3) for k, v in bt.items()})
iou: 0.1429
grounding@0.5: 0.5
CER: 0.273
counts: {'mae': 0.3333333333333333, 'exact': 0.6666666666666666}
clip: 2.0
adherence: {'adherence': 0.75, 'raw_adherence': 0.75} {'adherence': 0.0, 'raw_adherence': 1.0}
{'A': 0.597, 'B': 0.245, 'C': 0.158}

Reading the numbers. The \(10\times10\) boxes overlap in a \(5\times5\) region, giving \(\mathrm{IoU}=25/(100+100-25)=0.143\), well below the 0.5 threshold. OCR changes the zeroes in “TOTAL 40.00” to letter O three times: \(\mathrm{CER}=3/11=0.273\), and the amount is unusable by a parser. The toy embeddings have cosine 0.8, so CLIPScore is \(2.5\times0.8=2.0\). Prompt adherence is 3/4, or 0.75; the safety gate then drives even a 4/4 attribute match to 0. Across the preference study, A wins 7 of 10 against B. The fitted strengths imply \(0.597/(0.597+0.245)=0.709\), close to the observed 0.70 pairwise rate; they were fitted across all three pairings, not to this pair alone.

The counting example in Equation 18 could represent bags in three travel photos: predicted counts \((3,5,2)\) against true counts \((3,4,2)\). The absolute errors are \((0,1,0)\), so MAE is \(1/3\) and exact-match accuracy is \(2/3\). Even this small average can matter when a missed bag affects a booking.

To see one step of the preference fit in Equation 21, start all three strengths at \(1/3\). A has 15 wins in total, and each of its two opponents was compared with it 10 times. Its updated strength is \(15/[10/(2/3)+10/(2/3)]=0.5\). The corresponding updates for B and C are 0.3 and 0.2; subsequent iterations lead to the fitted values above. These strengths summarize the specified comparison panel, not the preferences of all travelers.

23.4.2 Distribution metrics for image generation: FID and KID (formulas only)

The preceding image metrics score individual outputs, whereas distribution metrics compare a set of generated images with a set of real images. Fréchet Inception Distance (FID) [10] embeds both sets with a fixed pretrained network, fits a Gaussian to each, and measures the distance between them. The calculation requires that network, so this chapter gives the formula and hand examples, not code.

Let the real-set embeddings have mean \(\mu_r\) and covariance \(\Sigma_r\), and the generated set \(\mu_g\) and \(\Sigma_g\):

\[ \mathrm{FID}=\|\mu_r-\mu_g\|_2^2+\operatorname{Tr}\!\Big(\Sigma_r+\Sigma_g-2\big(\Sigma_r\Sigma_g\big)^{1/2}\Big) \tag{22}\]

The first term measures the squared shift in mean appearance; the covariance term captures changes in spread or structure. Lower is better, and 0 means the two fitted Gaussians coincide.

Worked example (one dimension, so the matrix square root is a square root). Set \(\mu_r=3,\ \sigma_r=1\) and \(\mu_g=4,\ \sigma_g=2\). In one dimension, \((\mu_r-\mu_g)^2+(\sigma_r-\sigma_g)^2\) is equivalent to the covariance expression because \(\sigma_r^2+\sigma_g^2-2\sigma_r\sigma_g=(\sigma_r-\sigma_g)^2\). Here \(\mathrm{FID}=(3-4)^2+(1-2)^2=1+1=2\). A matching mean with twice the spread gives 1; a shifted mean with matching spread also gives 1. The same total can therefore reflect different faults. Inspect the mean and covariance terms separately.

With diagonal covariance, the same shortcut applies to each of \(d\) embedding dimensions. For \(\mu_r=(3,4)\) and \(\sigma_r=(1,2)\) versus \(\mu_g=(0,0)\) and \(\sigma_g=(2,2)\), the result is \((9+16)+\big((1-2)^2+(2-2)^2\big)=25+1=26\). Real embeddings are 2048-dimensional and use full covariance, which requires the matrix square root and a large sample.

Limits.

  • Sample size bias. Finite-sample FID estimates are biased and can vary with sample size and the underlying distribution. Equal sample counts help comparability but do not remove system-dependent bias. Report sample sizes and uncertainty.
  • Gaussian assumption. Real embedding distributions need not be Gaussian; distinct image sets can share the same \(\mu\) and \(\Sigma\).
  • Encoder dependence. The network reflects its training distribution. Scores from different encoders cannot be compared, and an encoder may ignore details your product needs, such as rendered text or object counts.
  • No per-image meaning. FID cannot tell whether an individual image followed its prompt. Pair it with per-output checks; it is not a substitute for them.

Kernel Inception Distance (KID) [11] uses an unbiased estimate of squared maximum mean discrepancy (Appendix I.4.1), avoiding FID’s Gaussian assumption and small-sample bias. For real embeddings \(x_1,\dots,x_m\), generated embeddings \(y_1,\dots,y_n\), and a kernel \(k\), a common choice is the cubic polynomial \(k(x,y)=\big(x^\top y/d+1\big)^3\):

\[ \widehat{\mathrm{KID}}=\frac1{m(m-1)}\sum_{i\ne i'}k(x_i,x_{i'})+\frac1{n(n-1)}\sum_{j\ne j'}k(y_j,y_{j'})-\frac{2}{mn}\sum_{i,j}k(x_i,y_j) \tag{23}\]

KID’s unbiased estimate of the population squared MMD, under independent samples and a fixed encoder and kernel, can be negative on a finite sample; that is valid, not an implementation error. Report uncertainty using a method appropriate to the sampling design. Small-sample KID can still have high variance and may miss differences to which its kernel is insensitive, so neither KID nor FID is automatically preferred for every decision.

Worked example (toy image features). Suppose two real destination images have scalar features \(x=(0,1)\) and two generated images have \(y=(0,2)\), using \(d=1\) in the cubic kernel. In Equation 23 the real within-set average is \(k(0,1)=1\), the generated within-set average is \(k(0,2)=1\), and the four cross-set values are \(1,1,1,27\), averaging \(7.5\). The estimate is \(1+1-2(7.5)=-13\). This deliberately tiny sample shows why an unbiased finite-sample estimate can be negative; it is not evidence of a negative population distance or a meaningful production comparison.

23.5 Video evaluation

An image score can describe a frame, but a video can fail in the relationship between frames. Record how frames were sampled, keep timestamps, and check event order, identity, motion, scene transitions, and support for answers about particular intervals. Because sparse samples can miss brief events, publish the sampling resolution and uncertainty.

For generated clips, have reviewers assess continuity, plausible motion, prompt satisfaction over time, and audio-video sync. Fréchet Video Distance compares generated and real video distributions using visual and temporal information, but it cannot show that one clip followed its prompt [12]. Include known failure controls such as identity drift, impossible object changes, and narration that conflicts with the scene.

23.5.1 Video metrics: definitions

Event recall, precision and order. Let the reference be an ordered event list \(E=(e_1,\dots,e_m)\) and the model’s description \(\hat E\), with matched set \(M=E\cap\hat E\) (matching is by a controlled event vocabulary or an adjudicated alignment, not free text):

\[ \mathrm{Rec}_{\mathrm{ev}}=\frac{|M|}{|E|},\qquad \mathrm{Prec}_{\mathrm{ev}}=\frac{|M|}{|\hat E|},\qquad \mathrm{Ord}=\frac{\mathrm{LCS}(E|_M,\hat E|_M)}{|M|} \tag{24}\]

Recall exposes omissions; precision exposes unsupported events; and \(\mathrm{Ord}\in[0,1]\) measures how many matched events retain their order (\(E|_M\) is \(E\) restricted to \(M\)). This set notation assumes uniquely identifiable events and one-to-one matching. Repeated events require explicit instance-level alignment rather than collapsing duplicates. Report undefined denominators separately, including order fidelity when no events match. A summary may recall every event and still reorder them, which matters when sequence carries the meaning of a safety procedure or recipe.

Temporal IoU and moment retrieval. For a predicted span \([s_p,e_p]\) and a true span \([s_t,e_t]\) in seconds, with overlap \(o=\max\big(0,\min(e_p,e_t)-\max(s_p,s_t)\big)\):

\[ \mathrm{tIoU}=\frac{o}{(e_p-s_p)+(e_t-s_t)-o},\qquad R@\tau=\frac1Q\sum_{q=1}^{Q}\mathbb 1[\mathrm{tIoU}_q\ge\tau] \tag{25}\]

Temporal consistency (generation). For frame embeddings \(f_1,\dots,f_T\) from a fixed encoder:

\[ \mathrm{TC}=\frac1{T-1}\sum_{t=1}^{T-1}\cos(f_t,f_{t+1}) \tag{26}\]

Low temporal consistency can flag flicker or identity drift, although a legitimate scene cut lowers it too, so calculate within shots. A high score is not a quality guarantee: a frozen clip scores 1.

Frame-sampling coverage. For sampled timestamps \(\mathcal T\) and event spans \(\{[a_k,b_k]\}_{k=1}^K\):

\[ \mathrm{Cov}=\frac1K\sum_{k=1}^{K}\mathbb 1\big[\exists\,t\in\mathcal T:\ a_k\le t\le b_k\big] \tag{27}\]

When the judge sees only sampled frames, \(\mathrm{Cov}\) describes the fraction of annotated event intervals hit by a sample. It is not a guarantee of visual evidence: a sampled frame may be occluded or uninformative. Nor is it an unconditional upper bound on inference, since other context or provided text may reveal an event. Report it as a sampling diagnostic alongside what the judge actually received.

Worked example (synthetic). The reference events are enters, picks up box, opens door, leaves. The model reports enters, opens door, picks up box, waves.

from bookkit.generative_metrics import (
    event_recall_order, frame_sampling_coverage, moment_retrieval_recall,
    temporal_consistency, temporal_iou,
)

truth_events = ["enters", "picks_up_box", "opens_door", "leaves"]
pred_events = ["enters", "opens_door", "picks_up_box", "waves"]
print(event_recall_order(truth_events, pred_events))
print("tIoU:", round(temporal_iou((10, 20), (15, 25)), 4))
print("R@0.5:", moment_retrieval_recall([(10, 20), (40, 50)], [(15, 25), (41, 51)]))
print("consistency:", round(temporal_consistency([[1, 0], [0.9, 0.1], [0.2, 0.9]]), 4))
print("sampling coverage:", frame_sampling_coverage([0, 10, 20, 30], [(8, 12), (14, 16), (28, 33)]))
{'event_recall': 0.75, 'event_precision': 0.75, 'order_fidelity': 0.6666666666666666}
tIoU: 0.3333
R@0.5: 0.5
consistency: 0.6586
sampling coverage: 0.6666666666666666

Reading the numbers. The description includes 3 of 4 reference events, so \(\mathrm{Rec}_{\mathrm{ev}}=0.75\). Three of its four claims are real, so \(\mathrm{Prec}_{\mathrm{ev}}=0.75\); “waves” is unsupported. The three matched events appear in reference order as enters, picks up box, opens door, but the model swaps the last two. The longest common subsequence is 2, giving \(\mathrm{Ord}=2/3\). The spans \([10,20]\) and \([15,25]\) overlap for 5 s within a 15 s union, so \(\mathrm{tIoU}=1/3\) and the first query misses the 0.5 threshold. The second overlap is 9 s within an 11 s union, so it passes and \(R@0.5=1/2\).

The consecutive frame cosines are 0.994 and 0.323, averaging 0.659. Inspect the second transition: the large change may indicate a meaningful scene change or a continuity fault. Samples at 0, 10, 20, and 30 s hit the 8–12 s and 28–33 s events but miss 14–16 s. Thus \(\mathrm{Cov}=2/3\), and the sampled frames do not directly show the missed interval; other context could still provide evidence about it.

23.5.2 Fréchet Video Distance (formulas only)

Fréchet Video Distance (FVD) [12] follows the FID construction but uses embeddings from a pretrained video network. These embeddings respond to motion and temporal structure, not only individual frames. Because the network is required, this section gives the definition only.

Let \(\phi(v)\in\mathbb R^d\) be the video encoder’s embedding of clip \(v\). Fit \((\mu_r,\Sigma_r)\) to embeddings of real clips and \((\mu_g,\Sigma_g)\) to generated clips:

\[ \mathrm{FVD}=\|\mu_r-\mu_g\|_2^2+\operatorname{Tr}\!\Big(\Sigma_r+\Sigma_g-2\big(\Sigma_r\Sigma_g\big)^{1/2}\Big) \tag{28}\]

The arithmetic is the same as §8.4.2, including the one-dimensional hand calculation. The difference is which video properties move the score—and which failures it still misses.

  • What it can detect. Unnatural motion, flicker, and broken physics can shift embedding statistics. A system with sharp frames but incoherent motion may therefore look worse than it does under an image-only metric.
  • Preprocessing sensitivity. Frame count, resolution, resizing, clip length, and decoding all affect \(\phi(v)\). Compare FVD only under identical preprocessing, and record that pipeline beside the result.
  • Sample size. Like FID, finite-sample FVD is biased and video datasets are often small. Use comparable sample sizes, report them, and assess uncertainty; matching \(n\) does not eliminate bias.
  • Distribution, not prompt. A low score says a generated set resembles real video. It does not show that a particular clip followed its prompt, preserved identity, or synchronized with audio. Keep per-clip event, order, consistency, and reviewer checks as release gates.
  • Content mismatch. If the real set contains different scene types from the generated set, FVD may reflect that content difference rather than quality.

Worked example. Under the one-dimensional shortcut, a real set with \(\mu_r=0,\ \sigma_r=1\) and generated set with \(\mu_g=0,\ \sigma_g=1.5\) gives \(\mathrm{FVD}=0+(1-1.5)^2=0.25\). If a frame-sampler change shifts the generated mean to \(\mu_g=0.5\) while spread stays fixed, the score becomes \(0.25+0.25=0.5\). The total alone does not identify which distribution property changed. Report both terms.

23.6 Audio and speech

Audio presents a different kind of evidence again. For speech recognition, WER counts substitutions, deletions, and insertions against a reference transcript, but tokenization and normalization choices affect the result, and a word error may or may not change meaning. Report WER by language, accent, noise, and domain; separately check names, numbers, and task-critical phrases. Whisper’s large-scale multilingual work is one reminder to test beyond a clean benchmark [13].

For speech generation, use suitable listeners and a controlled protocol to rate intelligibility, pronunciation, naturalness, prosody, and voice consistency. For voice agents, also record end-of-turn latency, interruption handling, barge-in, repair, and task completion. Split latency into audio capture, endpointing, model response, and playback so a slow turn has an actionable diagnosis.

23.6.1 Audio and speech metrics: definitions

Word error rate. Let \(r\) be the reference transcript with \(N\) words, and let \(S\), \(D\), \(I\) be the substitutions, deletions and insertions in the minimum-cost alignment of the hypothesis to \(r\):

\[ \mathrm{WER}=\frac{S+D+I}{N} \tag{29}\]

WER can exceed 1 because insertions have no cap at \(N\). Its components help localize failures: deletions may point to endpointing or noise clipping, insertions to hallucinated speech, and substitutions to acoustic or vocabulary confusion. Apply the same case, punctuation, and numeral normalization to both transcripts, and publish the normalizer.

Sentence error rate counts utterances with one or more word errors:

\[ \mathrm{SER}=\frac1U\sum_u\mathbb 1[h_u\ne r_u] \tag{30}\]

It captures exact transcript mismatch, not whether a command worked: some word differences preserve the intended action, while an apparently small error can change it. Task completion therefore needs to be measured separately.

Real-time factor. For processing time \(T_{\mathrm{proc}}\) on audio of duration \(T_{\mathrm{audio}}\):

\[ \mathrm{RTF}=\frac{T_{\mathrm{proc}}}{T_{\mathrm{audio}}} \tag{31}\]

\(\mathrm{RTF}<1\) means processing takes less time than the audio duration. Caller-perceived latency also includes endpointing and playback, so RTF is not a turn-latency measure.

Mean opinion score. Listeners rate samples from 1 to 5. With \(n\) ratings, mean \(\bar x\) and sample standard deviation \(s\):

\[ \mathrm{MOS}=\bar x,\qquad \bar x\pm t_{n-1,\,0.975}\frac{s}{\sqrt n} \tag{32}\]

The code uses \(z=1.96\) by default, which gives a narrower interval than the corresponding Student-\(t\) calculation at small \(n\) (2.365 for \(n=8\)). The latter is also an approximation for bounded ratings and assumes independent observations; repeated ratings from the same listener or clip require a design-aware interval, such as a suitable clustered bootstrap or mixed model. Listener panel, playback device, and the other samples in a session all affect MOS, so compare systems within one study design.

Turn latency. For end-of-turn latencies \(\ell_1,\dots,\ell_n\) in milliseconds and budget \(b\), report the median \(\ell_{(50)}\), 95th percentile \(\ell_{(95)}\) (linearly interpolated between order statistics), and share of turns within budget, \(\frac1n\sum_i\mathbb 1[\ell_i\le b]\). The mean can hide the delays callers notice most.

Worked example (synthetic).

from bookkit.generative_metrics import (
    mean_opinion_score, real_time_factor, sentence_error_rate,
    turn_latency_summary, wer_components,
)

print(wer_components("turn left at the museum then stop", "turn left the museum and then stop"))
print("SER:", sentence_error_rate(
    ["turn left", "stop here", "go home"], ["turn left", "stop there", "go home"]))
print("RTF:", real_time_factor(3.0, 12.0))
print(mean_opinion_score([4, 5, 4, 3, 4, 5, 4, 4]))
print(turn_latency_summary([420, 510, 480, 1300, 530, 495, 610, 470], budget_ms=800))
{'wer': 0.2857142857142857, 'substitutions': 0, 'deletions': 1, 'insertions': 1, 'reference_words': 7}
SER: 0.3333333333333333
RTF: 0.25
{'mos': 4.125, 'ci_low': 3.6808997860842667, 'ci_high': 4.569100213915733, 'n': 8}
{'p50': 502.5, 'p95': 1058.5000000000002, 'within_budget': 0.875}

Reading the numbers. The seven-word reference loses “at” and gains “and”: \(S=0\), \(D=1\), \(I=1\), so \(\mathrm{WER}=2/7=0.286\). These function-word edits preserve meaning, which is why WER needs a task-critical phrase check. One of three utterances contains an error, giving \(\mathrm{SER}=1/3\). Processing 12 seconds of audio in 3 seconds gives \(\mathrm{RTF}=0.25\). The eight listener ratings average 4.125, with a 95% interval of \([3.68, 4.57]\) using \(z=1.96\). Using the \(n=8\) Student-\(t\) quantile of 2.365 moves the lower bound to 3.59; the normal interval was optimistic. Latency has a 502.5 ms median and 87.5% of turns within the 800 ms budget. One turn still took 1300 ms, and the 95th percentile is 1058.5 ms. The median alone would hide that tail.

23.7 Multimodal judges and metrics

The preceding measures depend on explicit references or features. A vision-language or audio-capable judge can also rank outputs, flag rubric violations, or triage a large sample, but it introduces another source of error. Before relying on it, compare it with modality-competent human review, test prompt and position sensitivity, check evidence grounding, and count abstentions. Training-data blind spots can lead a judge to miss small or brief details with confidence.

For a human preference study, randomize presentation order, hide system identity, recruit the population whose experience matters, and define the question in advance. Report ties and uncertainty; a convenience sample does not establish universal preference. For high-stakes factual attributes, use instrumented checks or qualified labelers unless the multimodal judge has been validated for that use [14], [15].

23.7.1 Validating a multimodal judge

The metrics above score outputs, but a multimodal judge is itself a measurement instrument. Validate it against qualified human labels for each modality, report uncertainty, and test that its judgment changes when relevant media evidence changes.

Agreement with an interval. If the judge and human agree on \(a\) of \(n\) items, observed agreement is \(\hat p=a/n\). The Wilson score interval [16] remains within \([0,1]\) and behaves well for small samples:

\[ \frac{\hat p+\dfrac{z^2}{2n}\ \pm\ z\sqrt{\dfrac{\hat p(1-\hat p)}{n}+\dfrac{z^2}{4n^2}}}{1+\dfrac{z^2}{n}} \tag{33}\]

Chance-corrected agreement. Cohen’s kappa uses observed agreement \(p_o\) and expected agreement \(p_e\) from the raters’ marginal accept rates (§5.4.2):

\[ \kappa=\frac{p_o-p_e}{1-p_e} \tag{34}\]

Show it beside raw agreement: if both judge and reviewer usually accept, raw agreement may look high even when the judge adds little.

Media-ablation test. A judge may score well by reading the text alone, even when it ignores the image, audio, or video. Run each item with the media and again with only its text description; record agreement with the human in both conditions. Let \(b\) count items correct only with media and \(c\) items correct only without. If media has no effect, discordant cases should split evenly. The exact two-sided sign-test p-value (McNemar’s exact test) is

\[ p=\min\Big(1,\ 2\cdot\frac{1}{2^{\,b+c}}\sum_{k=0}^{\min(b,c)}\binom{b+c}{k}\Big) \tag{35}\]

The paired agreement gap is \(\hat p_{\mathrm{media}}-\hat p_{\mathrm{text}}\). The exact test assumes independent item pairs and evaluates a particular null of equal discordance probabilities; it does not prove that the judge uses media correctly or quantify the value of every modality. If there are no discordant pairs, use a p-value of 1 and report the absence of discordance.

Evidence grounding. A timestamp or image-region citation makes a judge’s evidence claim checkable. Let \(\hat\sigma_i\) be its citation (possibly none) and \(\sigma_i\) the true evidence span:

\[ \text{citation rate}=\frac1n\sum_i\mathbb 1[\hat\sigma_i\ne\varnothing],\qquad \text{grounded rate}=\frac1n\sum_i\mathbb 1\big[\hat\sigma_i\ne\varnothing\wedge\mathrm{IoU}(\hat\sigma_i,\sigma_i)\ge\tau\big] \tag{36}\]

Report grounded-given-cited as well, because a judge that cites rarely but accurately can have the same overall grounded rate as one that cites often but loosely; the conditional rate distinguishes them.

Worked example (synthetic, 10 items per modality). Human and judge accept/reject labels are fixed fixtures in code/ch12/lab_generative_metrics.py; no model or media is involved.

from bookkit.generative_metrics import (
    evidence_grounding_rate, modality_ablation_gap, wilson_interval,
)
from bookkit.judge_eval import cohen_kappa

human = {
    "image": [True, True, False, False, True, False, True, False, True, True],
    "audio": [True, False, False, True, True, False, True, True, False, True],
    "video": [True, False, True, False, False, True, False, True, True, False],
}
judge = {
    "image": [True, True, False, False, True, False, True, False, False, True],
    "audio": [True, False, True, True, True, False, False, True, False, True],
    "video": [True, True, True, True, False, False, True, False, True, True],
}
with_media = [True, True, True, False, True, True, True, False, True, True]
without = [True, False, False, False, True, False, True, False, True, False]

for m in human:
    agree = sum(h == j for h, j in zip(human[m], judge[m]))
    lo, hi = wilson_interval(agree, len(human[m]))
    print(m, "agree", agree / 10, "CI", (round(lo, 2), round(hi, 2)),
          "kappa", round(cohen_kappa(human[m], judge[m]), 3))
print(modality_ablation_gap(with_media, without))
print(evidence_grounding_rate(
    [(10, 20), None, (40, 52), (5, 6)], [(12, 22), (30, 40), (41, 51), (50, 60)]))
image agree 0.9 CI (0.6, 0.98) kappa 0.8
audio agree 0.8 CI (0.49, 0.94) kappa 0.583
video agree 0.4 CI (0.17, 0.69) kappa -0.2
{'agree_with_media': 0.8, 'agree_without_media': 0.4, 'gap': 0.4, 'b': 4, 'c': 0, 'p_value': 0.125}
{'citation_rate': 0.75, 'grounded_rate': 0.5, 'grounded_given_cited': 0.6666666666666666}

Reading the numbers. Image agreement is 9/10. The human accepts 6 items and the judge accepts 5, so marginal expected agreement is \(p_e=(0.6)(0.5)+(0.4)(0.5)=0.5\); Equation 34 gives \((0.9-0.5)/(1-0.5)=0.80\). Substituting \(\hat p=0.9\), \(n=10\), and \(z=1.96\) into Equation 33 gives approximately \([0.60,0.98]\). That interval is broad: ten items are not enough to validate the judge. Audio agreement is lower (\(\kappa=0.58\)). Video agreement is only 4/10, with \(\kappa=-0.2\) below chance; do not use this judge for video until the failure is understood and retested, regardless of its image result.

With media, the judge agrees on 8/10 items; with text alone, 4/10. Four items change from wrong to right when media is present, and none change the other way, so \(b=4\) and \(c=0\). The exact p-value is \(2\times\binom{4}{0}/2^4=0.125\). Four discordant cases are too few for conventional significance, despite the directional pattern; even five all in one direction give \(p=0.0625\). For grounding, 3/4 items have a citation (75%); 2 of those 3 overlap the true span at IoU \(\ge0.5\). That yields a 50% grounded rate overall and 67% grounded-given-cited.

Reading a modality scorecard. For each modality, check the metric definition, unit, denominator, and uncertainty interval. Ask what a trivial system would score. A headline such as “judge agreement 70%” is misleading if video agreement is at chance while image agreement is high; those are different instruments.

23.8 Cross-modal safety, bias, and fairness

Validating each modality separately is necessary, but it can miss failures at their boundaries: spoken content can contradict subtitles, an image can add harmful detail absent from its prompt, OCR can miss a warning, or a screenshot can expose a private document. Evaluate the complete artifact the user sees, along with every transformation that produced it.

Choose representative slices with input from affected communities and domain experts. Do not treat demographic labels as interchangeable or infer sensitive identity from appearance or voice without a legitimate, governed purpose. Measure error differences with adequate denominators, document what the data cannot show, and provide an escalation path for harmful outputs.

23.9 Multimodal inputs and outputs inside agents

When these outputs belong to an agent, the evaluation must follow evidence beyond the generated artifact. A voice agent may need to remember a spoken preference, inspect a photo, and call a booking tool, so follow synchronized evidence through perception, state tracking, tool choice, and final response. Keep timestamps, transformations, and provenance, and preserve the timing and crops needed to reproduce the decision.

Test components and the complete task: OCR can extract the right value while the agent ignores it, and a correct final answer can still conceal that a private image went to an unauthorized tool. For that reason, pair outcome checks with trajectory, privacy, and safety evidence from Chapters 5, 22, and 27.

Chapter summary

Across modalities, the same discipline applies: identify the decision, then collect evidence that actually bears on it.

  • Choose a task-specific unit, metric, and decision rule.
  • Keep factuality, coverage, fluency, preference, and schema validity distinct.
  • Report results by language and locale; validate judges in each one.
  • Preserve spatial, temporal, and transformation evidence across modalities.
  • Combine automatic checks with qualified review, and state what each misses.
  • Check safety, fairness, and privacy across the complete user-visible experience.

For product managers. Which languages and modalities will the product support, and what counts as acceptable for each task? Review examples, reviewer coverage, and subgroup denominators alongside preference results. Confirm consent, retention, and access controls for voice, image, and video data.

Hands-on lab (Python)

Run python code\ch12\lab_generative_metrics.py with code on Python’s module search path for the worked examples in §8.2.1–8.7.1. The ch12 directory is a retained legacy lab identifier. The lab uses the pure-standard-library module code/bookkit/generative_metrics.py and hand-written fixtures; it processes no model output, image, audio, or video. You can check the numbers manually, and the relevant unit tests check the functions against those calculations. CLIPScore and temporal consistency accept vectors computed elsewhere; the encoder is not included. BERTScore, COMET, FID, KID, and FVD (§8.2.2, §8.3.2, §8.4.2, §8.5.2) appear as formulas and hand calculations because they require pretrained networks; they are not implemented in bookkit.

The scorecard lab makes missing evidence explicit. Run python code\ch12\lab_multimodal.py to see WER and a modality scorecard computed from synthetic references and transcripts. It then prints the shared evaluation record from Appendix D. No image, video, or speech model is called.

from bookkit.multimodal_eval import word_error_rate, scorecard
from bookkit.system_eval import evaluation_record

wer = word_error_rate("turn left at the museum", "turn left by the museum")
scores = scorecard(
    {"text_factuality": 1.0, "audio_latency_ms": 850},
    required={"text_factuality", "audio_latency_ms", "visual_safety"},
)
print(wer)
print(scores)
print(evaluation_record(
    claim="The multimodal answer meets required factual and safety checks",
    case_id="multimodal-turn-01@v1",
    evidence_ref="fixture://ch12/transcript-and-scorecard",
    oracle={"id": "transcript-reference-v1", "result": "incomplete" if scores["missing"] else "pass"},
    metric={"name": "word_error_rate_and_required_scores", "value": {"wer": wer, **scores}, "denominator": 1},
    decision={"result": "insufficient_evidence" if scores["missing"] else "pass", "reason": "required modality score missing" if scores["missing"] else "synthetic fixture gates passed"},
    failure_category="missing_required_modality_score" if scores["missing"] else None,
))
0.2
{'scores': {'audio_latency_ms': 850, 'text_factuality': 1.0}, 'missing': ['visual_safety']}
{'claim': 'The multimodal answer meets required factual and safety checks', 'case_id': 'multimodal-turn-01@v1', 'evidence_ref': 'fixture://ch12/transcript-and-scorecard', 'oracle': {'id': 'transcript-reference-v1', 'result': 'incomplete'}, 'metric': {'name': 'word_error_rate_and_required_scores', 'value': {'wer': 0.2, 'scores': {'audio_latency_ms': 850, 'text_factuality': 1.0}, 'missing': ['visual_safety']}, 'denominator': 1}, 'decision': {'result': 'insufficient_evidence', 'reason': 'required modality score missing'}, 'failure_category': 'missing_required_modality_score'}

Exercises

Use these exercises to connect each calculation to the decision it can—and cannot—support.

  1. Design. Create a scorecard for video summarization that distinguishes event recall, order, and unsupported claims.
  2. Conceptual. Why can a low WER coexist with a serious transcription failure?
  3. Hands-on. Add a hallucinated date to a summary and define a source-grounded check for it.
  4. Study design. Plan a blinded preference study for generated images, including reviewer population, ties, and uncertainty.
  5. Discussion. How could averaging quality across languages mask a harmful failure for a smaller language community?
  6. Hands-on (summarization). Add a candidate that drops the amount entirely instead of changing it. Compute ROUGE-1, faithfulness and coverage, and explain which of the three should change and which should not.
  7. Conceptual (multilingual). Show with the BLEU formula why a correct paraphrase can score exactly 0, and say which of chrF or BLEU you would report for Finnish, and why.
  8. Hands-on (speech). Recompute the MOS interval with the Student-\(t\) quantile for \(n=8\). Then, assuming the same sample mean and standard deviation and independent ratings, calculate an illustrative interval for \(n=30\). How much narrower is it, and why might that assumption fail in a real panel?
  9. Hands-on (video). Construct a model description with \(\mathrm{Rec}_{\mathrm{ev}}=1\) and \(\mathrm{Ord}=0.5\). Describe a product where that failure is harmless and one where it is not.
  10. Study design (judge). The video judge above has \(\kappa=-0.2\) on ten items. What assumptions about prevalence, the target effect, desired power, and sampling design would you need to estimate the sample size for an agreement study? What would you do with the judge in the meantime?
  11. Conceptual (judge correction). A judge has \(\mathrm{Sp}=0.80\) and flags 90% of items. Using Rogan–Gladen, find the sensitivity below which the corrected rate is 1 or more, and the sensitivity at which the formula becomes undefined. What does each threshold tell you about trusting that judge’s pass rate?
  12. Hand calculation (BERTScore). Using the toy vectors in §8.2.2, replace the unrelated candidate token with \((0.6,0.8)\). Recompute \(R\), \(P\) and \(F\) and say what changed and what did not.
  13. Hand calculation (FID). For one-dimensional embeddings with \(\mu_r=0,\ \sigma_r=2\) and \(\mu_g=1,\ \sigma_g=1\), compute FID. Then find a second generated set with a different mean and spread that gives the same value, and say what that implies for reporting.
  14. Conceptual (FID vs. KID). You have 300 generated images and 300 real ones. How would you choose between reporting FID, KID, or both, and what uncertainty and per-output evidence would you report beside them?
  15. Design (metric validation). Plan a study to validate a learned translation metric for one language pair you ship: how many segments, who labels them, which correlations you report, and what result would make you reject the metric.

Further reading

The following sources provide the original metric definitions and further context for the evaluation designs in this chapter:

  • Lin, ROUGE, for n-gram and longest-common-subsequence overlap scores for summaries [1].
  • Papineni et al., BLEU, for a reference-based translation metric and its intended use [5].
  • Popović, chrF, for a character n-gram F-score that suits morphologically rich languages [6].
  • Zhang et al., BERTScore, for embedding-based text similarity [3].
  • Rei et al., COMET, for a trained neural translation-quality estimator [7].
  • Heusel et al., for the Fréchet Inception Distance [10].
  • Bińkowski et al., for the kernel-based, unbiased alternative to FID [11].
  • Bradley and Terry, for the paired-comparison model used for preference ranking [9].
  • Wilson, for the score interval used for small-sample agreement [16].
  • Rogan and Gladen, for correcting an observed rate for an imperfect classifier [2].
  • NLLB Team et al., for human-centered multilingual machine translation [4].
  • Hessel et al., CLIPScore, for reference-free image-text compatibility and its limitations [8].
  • Unterthiner et al., for Fréchet Video Distance and temporal video-generation evaluation [12].
  • Radford et al., Whisper, for large-scale multilingual speech recognition [13].
  • Zheng et al., Judging LLM-as-a-Judge, for model-judge agreement and bias considerations [14].
  • Artstein and Poesio, for inter-annotator agreement and its interpretation [15].
  • Gebru et al., Datasheets for Datasets, for documenting populations, collection, and limitations [17].
[1]
C.-Y. Lin, “ROUGE: A package for automatic evaluation of summaries,” in Text summarization branches out, 2004, pp. 74–81. Available: https://aclanthology.org/W04-1013/
[2]
W. J. Rogan and B. Gladen, “Estimating prevalence from the results of a screening test,” American Journal of Epidemiology, vol. 107, no. 1, pp. 71–76, 1978.
[3]
T. Zhang, V. Kishore, F. Wu, K. Q. Weinberger, and Y. Artzi, “BERTScore: Evaluating text generation with BERT,” in International conference on learning representations (ICLR), 2020. Available: https://openreview.net/forum?id=SkeHuCVFDr
[4]
NLLB Team et al., “No language left behind: Scaling human-centered machine translation.” 2022. Available: https://arxiv.org/abs/2207.04672
[5]
K. Papineni, S. Roukos, T. Ward, and W.-J. Zhu, “BLEU: A method for automatic evaluation of machine translation,” in Proceedings of the 40th annual meeting of the association for computational linguistics, 2002, pp. 311–318. doi: 10.3115/1073083.1073135.
[6]
M. Popović, “ChrF: Character n-gram F-score for automatic MT evaluation,” in Proceedings of the tenth workshop on statistical machine translation, 2015, pp. 392–395. doi: 10.18653/v1/W15-3049.
[7]
R. Rei, C. Stewart, A. C. Farinha, and A. Lavie, “COMET: A neural framework for MT evaluation,” in Proceedings of the 2020 conference on empirical methods in natural language processing (EMNLP), 2020, pp. 2685–2702. doi: 10.18653/v1/2020.emnlp-main.213.
[8]
J. Hessel, A. Holtzman, M. Forbes, R. Le Bras, and Y. Choi, “CLIPScore: A reference-free evaluation metric for image captioning,” in Proceedings of the 2021 conference on empirical methods in natural language processing, 2021. doi: 10.18653/v1/2021.emnlp-main.595.
[9]
R. A. Bradley and M. E. Terry, “Rank analysis of incomplete block designs: I. The method of paired comparisons,” Biometrika, vol. 39, no. 3/4, pp. 324–345, 1952.
[10]
M. Heusel, H. Ramsauer, T. Unterthiner, B. Nessler, and S. Hochreiter, “GANs trained by a two time-scale update rule converge to a local Nash equilibrium,” in Advances in neural information processing systems (NeurIPS), 2017.
[11]
M. Bińkowski, D. J. Sutherland, M. Arbel, and A. Gretton, “Demystifying MMD GANs,” in International conference on learning representations (ICLR), 2018.
[12]
T. Unterthiner, S. van Steenkiste, K. Kurach, R. Marinier, M. Michalski, and S. Gelly, “Towards accurate generative models of video: A new metric and challenges.” 2018. Available: https://arxiv.org/abs/1812.01717
[13]
A. Radford, J. W. Kim, T. Xu, G. Brockman, C. McLeavey, and I. Sutskever, “Robust speech recognition via large-scale weak supervision.” 2022. Available: https://arxiv.org/abs/2212.04356
[14]
L. Zheng et al., “Judging LLM-as-a-judge with MT-bench and chatbot arena,” in Advances in neural information processing systems, 2023. Available: https://proceedings.neurips.cc/paper_files/paper/2023/hash/91f18a1287b398d378ef22505bf41832-Abstract-Datasets_and_Benchmarks.html
[15]
R. Artstein and M. Poesio, “Inter-coder agreement for computational linguistics,” Computational Linguistics, vol. 34, no. 4, pp. 555–596, 2008, doi: 10.1162/coli.07-034-R2.
[16]
E. B. Wilson, “Probable inference, the law of succession, and statistical inference,” Journal of the American Statistical Association, vol. 22, no. 158, pp. 209–212, 1927.
[17]
T. Gebru et al., “Datasheets for datasets,” Communications of the ACM, vol. 64, no. 12, pp. 86–92, 2021, doi: 10.1145/3458723.