10B.10 Inspect Scorers, Metrics, Epochs and the Statistics Inspect Reports (optional)

ProductionLesson 10 of 1825,039 wordsOptional12 parts
Module 10B · 0 of 7 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18

An Inspect run ends with a results panel: accuracy 0.733, stderr 0.102. Every word in that line is the product of a chain of decisions you may not know you made: which scorer turned each output into a verdict, how that verdict became a number, what happened to the samples the scorer could not judge, how several attempts at the same sample were combined, which formula produced the standard error and what it assumes about your data. This lesson opens that chain link by link. You will meet the scorer contract and the Score, Value and Target types; every built-in scorer with its exact matching rules, run on the same outputs; the scoring policy that decides what counts in the denominator; custom, dict-valued, store-reading, combined, cascaded and pre-computed scorers; every built-in metric with the formula from Inspect's source, checked by hand, including clustered standard errors on data where they matter; epochs and every built-in reducer, with pass@k and pass^k reconciled against the estimators of 10A.7; and, last, what Inspect's statistics do not cover (paired comparisons between runs, multiple comparisons, power) and how to do those with the evalkit tools of 10A.8 on data read from Inspect's logs. Every sample runs keyless on the mock model, every number shown was printed by a real run, and the important ones are recomputed with the standard library so you can see there is no magic.

What you'll learn

  • The scoring pipeline: scorer → Score per sample and epoch → reducer → metric → EvalScore, where each stage lands in the log, and why metrics see floats even with one epoch
  • The scorer protocol, @scorer, Score field by field, Value and the C/I/P/N constants, value_to_float() and its silent zero for unknown labels, Target and its concatenating .text, SampleScore
  • Every built-in scorer: includes, match (all four locations and numeric=True), pattern (with match_all), answer and its three AnswerPattern regexes, exact, f1, choice, math (with its optional extra), the perplexity scorers, and where the model graders are taught
  • The scoring policy: a verdict, an exception, Score.unscored() and None, what each does to scored_samples and the metric, score_on_error, the ScoreReason vocabulary, the "measurement instrument" rule, and why INCORRECT and NOANSWER are different facts with the same number
  • Custom scorers that production evals need: unit-tested without a run, dict-valued with per-key metrics, reading the solver's store, several scorers per task, multi_scorer() (including "every check must pass"), cascade(), precomputed_scores() for human labels, solver-set scores and intermediate scoring
  • Every built-in metric with its formula: accuracy, mean, std, var, stderr (CLT, ddof=1), clustered stderr and its C/(C−1) correction, bootstrap_stderr (unseeded), ci (t and bootstrap), ci_wilson (and its clustered Korn-Graubard form), grouped, aggregate, frequency, categorical, krippendorff_alpha; custom @metric with score views; headline_metric
  • Epochs: Epochs(n, reducer), --epochs, --epochs-reducer, --no-epochs-reducer and the trap that two of them do nothing on their own; every reducer (mean, median, mode, majority, max, at_least_k, pass_at_k, pass_k_k, collect) with its formula and a hand check; custom reducers that survive unscored epochs
  • What the reported standard error measures, what epochs do and do not do to the uncertainty, and how to compare two runs properly: paired differences, bootstrap intervals, permutation tests, cluster bootstraps, multiple comparisons and the minimum detectable effect, on Inspect log data with evalkit
  • A worked example that scores the triage eval on purpose and prints a report you can defend, a scoring checklist, a failure gallery and a decision table

What you don't need

  • An API key. Every runnable sample uses mockllm/model with scripted replies, as in 10B.8, 3.5, and its output is real.
  • Model grading in depth. model_graded_qa(), model_graded_fact(), grader roles, panels and validating a grader against human labels are 10B.11. This lesson uses a scripted grader in one sample (a cascade()), and shows the shape of a model-calling scorer, nothing more. The re-scoring workflow (--no-score, inspect score, edit_score) is there too.
  • The statistics from scratch. Confidence intervals, sample sizes and clustering were taught in 10A.2, Part 5 and 6.7; pass@k and pass^k in 10A.7, Part 5; paired comparisons, the minimum detectable effect and multiple comparisons in 10A.8, Part 2. Here they are mapped onto Inspect, with the formulas Inspect actually uses.
  • Logs and dataframes in depth. This lesson reads log.results, log.reductions and log.samples, and uses samples_df() once; the log schema, the reading API and the dataframes are 10B.13.

Setup

The same project as 10B.8 and 10B.9. If you are starting fresh:

bash
uv init inspect-lab --bare --python 3.13 && cd inspect-lab   # first time only
uv add inspect-ai
# or: pip install inspect-ai

Three samples need extras, and say so where they appear: the math() scorer needs uv add "inspect-ai[math]", the samples_df() comparison in 8.4 needs uv add pandas pyarrow, and the scorer unit tests in 5.2 need uv add pytest. Several samples import triage.py and fake_triage.py from 10B.8, Part 4 unchanged, one imports triage_task.py from 10B.9, Part 9, and the comparison samples import evalkit/compare.py and evalkit/cluster.py from 10A.8. Put every file in one folder (with evalkit/ as a package folder beside them, holding an empty __init__.py), and run each sample with uv run python <file>.py from that folder. The files that need nothing but the standard library say so and run with plain python3.

Versions (current at time of writing, read from PyPI on 24 November 2026): inspect-ai 0.3.292 (released 23 November 2026, MIT licence, Python ≥ 3.11). Every sample marked as run was executed on 24 November 2026 with Python 3.13.14 and inspect-ai 0.3.292 (plus pandas, pyarrow and pytest where named), and the output blocks are what those runs printed. The formulas quoted for metrics and reducers were read from the installed package source the same day, and the official documentation pages listed in Further resources were checked then too. Inspect is on 0.x and releases every few days; several features in this lesson (Score.unscored(), pass_k, krippendorff_alpha, headline_metric, ci_wilson(), cascade()) arrived between April and September 2026, and older tutorials do not show them (Part 12).


What you must be able to do after this lesson#

  • Trace an output through the four scoring stages to the reported number
  • Choose a built-in scorer (match, includes, answer, exact) and predict its result on a reply
  • Decide the policy for a sample: verdict, error, unscored or nothing
  • Write your own scorer with the @scorer decorator and value_to_float
  • Read Inspect's accuracy and standard error, and use ci_wilson() for accuracy
  • Set epochs and a reducer (mean, pass_at_k, pass_k, majority) and say what each reports
  • Score the triage eval on purpose and defend the scored number

Why this matters for an AI engineer#

You'll hear... You'll understand it after...
"The log says C but the metric says 1.0. Which is it?" 1.3
"We use our own labels, pass and fail." (And accuracy is mysteriously 0.) 2.5
"Just use match()." 3.3 and 3.11
"Accuracy went up after the grader started failing." 4.1 and 4.6
"The tool timed out but the sample still passed." 4.3
"Inspect has no pass rate across all our checks." 5.7
"Can we attach the human ratings to last week's run?" 5.9
"Stderr is 0.13, so we're fine." 6.4 and 7.10
"Our questions come ten per document. Does that matter?" 6.5
"Report it with a 95% interval." 6.7
"Break it down by intent." 6.8
"Run five epochs and report pass@k." Or pass^k? 7.3 to 7.6
"I passed --epochs-reducer and nothing changed." 7.2
"v2 scores 0.82 against v1's 0.73. Ship it." 8.3
"What's the smallest change this eval can even see?" 8.7

Part 1: From outputs to one number: the scoring pipeline#

1.1 Four stages, three places in the log#

When the solver chain has produced an output for a sample, Inspect turns it into the number on the results panel in four stages:

  1. Score. Every scorer in Task(scorer=...) runs on the finished TaskState and the sample's Target, and returns a Score (or declines, or fails: Part 4). This happens once per sample per epoch: with five epochs, a twelve-sample task produces sixty scores per scorer.
  2. Reduce. After all samples finish, for each scorer and each reducer (default mean), the epoch scores of one sample are reduced to one score. With one epoch there is still a reduction, and it matters (1.3).
  3. Metric. Each of the scorer's metrics runs over the list of reduced per-sample scores (one per sample) and returns a value: a float, or a mapping such as {"lower": ..., "upper": ...}.
  4. Record. Inspect writes one EvalScore per scorer × reducer into log.results.scores, the reduced per-sample values into log.reductions, and the raw per-epoch scores on each sample in log.samples.
flowchart LR
    subgraph per ["For every sample and every epoch"]
        S["Solver chain<br/>produces the output"] --> SC["Each scorer:<br/>score(state, target)"]
        SC --> V["Score<br/>value, answer, explanation,<br/>reason, metadata"]
    end
    V --> R["Reducer, per scorer<br/>(default mean, via value_to_float)<br/>epochs of one sample to one value"]
    R --> M["Reduced metrics<br/>accuracy, stderr, ci_wilson, grouped...<br/>over one value per sample"]
    V -.->|"unreduced view"| U["Unreduced metrics<br/>frequency, categorical, custom<br/>over every sample-epoch"]
    M --> E["EvalScore per scorer x reducer<br/>in log.results.scores"]
    U --> E
    R --> RD["log.reductions<br/>the values metrics saw"]
    V --> LS["log.samples[i].scores<br/>raw values, e.g. 'C'"]

Read the diagram as a contract. A scorer never sees other samples; a metric never sees the transcript; a reducer never sees other samples either. Each stage has one job, which is why you can swap any of them (a different reducer for the same scores, a different metric for the same reductions) without touching the others, and why re-scoring a log later (10B.11) never needs the model.

1.2 Watching the stages in a real log#

This script runs includes() on two samples (one the mock's reply contains, one it does not) and prints what the log holds at each stage. The second half is the first pitfall of the lesson, reproduced: a scorer that returns home-made labels.

python
# s02_pipeline.py: where scores live (sample, reductions, results), and custom labels (lesson 10B.10)
from inspect_ai import Epochs, Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import (Score, Target, accuracy, includes, mean_score,
                               scorer, stderr, value_to_float)
from inspect_ai.solver import TaskState

DATA = [Sample(id="a", input="x", target="mockllm"),      # the mock's reply contains "mockllm"
        Sample(id="b", input="y", target="banana")]       # ...but not "banana"

# 1. One built-in scorer: what the log keeps at each stage.
log = eval(Task(dataset=DATA, scorer=includes()), model="mockllm/model",
           log_dir="logs", display="none")[0]
print("per-sample scores :", {s.id: s.scores["includes"].value for s in log.samples})
print("reductions        :", [(r.scorer, r.reducer, [(x.sample_id, x.value) for x in r.samples])
                              for r in log.reductions])
es = log.results.scores[0]
print("results.scores[0] :", f"name={es.name} scorer={es.scorer} reducer={es.reducer}",
      f"scored={es.scored_samples} unscored={es.unscored_samples}",
      {k: round(m.value, 3) for k, m in es.metrics.items()})


# 2. A scorer with home-made labels "pass"/"fail", declared twice: with the
#    default float conversion, and with a converter that knows the labels.
def pass_or_fail(state: TaskState, target: Target) -> Score:
    return Score(value="pass" if target.text in state.output.completion else "fail")


@scorer(metrics=[accuracy(), stderr()])
def pass_fail():
    async def score(state: TaskState, target: Target) -> Score:
        return pass_or_fail(state, target)
    return score


TO_FLOAT = value_to_float(correct="pass", incorrect="fail")


@scorer(metrics=[accuracy(to_float=TO_FLOAT), stderr(to_float=TO_FLOAT)])
def pass_fail_converted():
    async def score(state: TaskState, target: Target) -> Score:
        return pass_or_fail(state, target)
    return score


variants = {
    "no converter": dict(scorer=pass_fail()),
    "converter on metrics only": dict(scorer=pass_fail_converted()),
    "converter on metrics + reducer": dict(scorer=pass_fail_converted(),
                                           epochs=Epochs(1, mean_score(value_to_float=TO_FLOAT))),
}
for label, kwargs in variants.items():
    log = eval(Task(dataset=DATA, **kwargs), model="mockllm/model", log_dir="logs", display="none")[0]
    print(f"{label:31} accuracy = {log.results.scores[0].metrics['accuracy'].value}")
bash
uv run python s02_pipeline.py
Output · real6 lines
per-sample scores : {'a': 'C', 'b': 'I'}
reductions        : [('includes', None, [('a', 1.0), ('b', 0.0)])]
results.scores[0] : name=includes scorer=includes reducer=None scored=2 unscored=0 {'accuracy': 0.5, 'stderr': 0.5}
no converter                    accuracy = 0.0
converter on metrics only       accuracy = 0.0
converter on metrics + reducer  accuracy = 0.5

The first three lines are the three places in the log:

  • log.samples[i].scores keeps the scorer's own value, 'C' and 'I'. This is what the viewer shows and what you read when you debug a sample.
  • log.reductions holds the value each sample contributed to the metrics, after reduction: 1.0 and 0.0. The reducer is shown as None because the task declared none (the default mean applied).
  • log.results.scores holds one EvalScore with the scorer's name, the reducer, the coverage counts (scored_samples, unscored_samples) and the metrics. Accuracy 0.5 is one of two, and the standard error of two values 1 and 0 is 0.5.

The last three lines are 2.5's subject, but look now: a scorer that says "pass" for a correct answer reports accuracy 0.0, and even giving the metric a converter that knows "pass" does not help. Only when the reducer also gets the converter does the number come out right. The reason is the pipeline: the reducer runs first and has already turned "pass" into 0.0 before the metric sees anything.

1.3 Why metrics see floats even with one epoch#

The documentation says it plainly on the custom-scorers page: the default epoch reducer converts each value with value_to_float() before metrics run, including when there is only one epoch. So, in a normal run:

  • metrics receive floats (1.0, 0.0, 0.5), never the letters C, I, P;
  • the sample's own score in the log still says C;
  • a custom metric that does arithmetic on score.score.value works by accident, because the reducer converted for it, and breaks the moment reducers are switched off (7.8 reproduces the crash).

This is also why 10B.8, 7.3 found reductions full of floats for a scorer that returned letters. When a number in the results looks inconsistent with the per-sample letters, read log.reductions: it is exactly the list the metric was computed from.

1.4 Vocabulary: scorer, score, metric, reducer#

10A.3, 1.4 separated graders, metrics and judges. Inspect's names line up with that vocabulary like this:

Inspect What it is 10A.3's word evalkit
Scorer (@scorer) A function from one sample's final state and target to a Score Grader (deterministic) or judge (model-based) Scorer.score(example, output)
Score One sample's verdict, with the extracted answer and an explanation Grade Score(name, value, passed, detail)
Reducer (@score_reducer) Combines one sample's epoch scores into one (repeat aggregation, 10A.8, 2.2) repeats= rows, then your own grouping
Metric (@metric) Summarizes all samples' reduced scores for one scorer Metric EvalReport.pass_rate, mean_score, compare.py
EvalScore The results of one scorer × reducer: metrics plus coverage counts (report row) EvalReport

Two consequences worth stating now. First, Inspect has no passed flag: the value is the verdict, and a pass/fail interpretation comes from how the value converts to a float. Second, metrics belong to scorers, so there is no built-in "row passes only if every scorer passes" (10B.8, 4.8 found this); 5.7 builds it.

1.5 What this lesson adds to 10B.8 and 10B.9#

10B.8 ported the triage eval with two custom scorers and reconciled its numbers with evalkit; 10B.9 built the production-shaped triage task with a deliberately small scorer and promised better ones. This lesson keeps both running examples and adds what they skipped:

Earlier lesson left open Answered in
"a multi_scorer() with a reducer that takes the minimum" for the all-checks pass rate (10B.8, 4.8) 5.7
The repair rate "as a metric (a store-reading scorer)" (10B.9, Part 9) 5.4
"one epoch, so run-to-run variation is invisible" (10B.9, Part 9) Part 7 and Part 9
"Inspect reports the standard error; it does not report an interval by default, and it does not compare runs" (10B.8, 10.4) Part 6 and Part 8
Slices with grouped() (10B.8, 4.2; 10B.9, 2.5) 6.8
The choice() scorer and answer() after chain_of_thought() (10B.9, 4.4 and 6.6) 3.5 and 3.7
Solver-set scores and the in-solver score() (10B.9, 7.6) 5.10

Part 2: The scorer contract and the scoring types#

2.1 The Scorer protocol and @scorer#

A scorer is any async callable with this shape (the Scorer protocol):

python
from inspect_ai.scorer import Score, Target
from inspect_ai.solver import TaskState


async def score(state: TaskState, target: Target) -> Score | None:
    ...

You almost never write one bare. You write a scorer factory decorated with @scorer, whose job is to take options, declare the metrics and return the async function:

python
from inspect_ai.scorer import CORRECT, INCORRECT, Score, Scorer, Target, accuracy, scorer, stderr
from inspect_ai.solver import TaskState


@scorer(metrics=[accuracy(), stderr()])
def mentions_refund_window(days: int = 30) -> Scorer:
    """C if the reply states the refund window, e.g. '30 days'."""
    async def score(state: TaskState, target: Target) -> Score:
        reply = state.output.completion
        ok = f"{days} days" in reply
        return Score(value=CORRECT if ok else INCORRECT,
                     answer=reply[:200],
                     explanation="window stated" if ok else f"no '{days} days' in reply")
    return score

The rules, all enforced or relied on by Inspect 0.3.292:

Rule Why
metrics= is required (pass [] for none) Metrics belong to the scorer; a task can override them for all scorers with Task(metrics=...) (6.1)
metrics is a list, a dict from score keys (or globs such as "*") to lists, or a list mixing both Dict forms are for dict-valued scores (5.3)
The inner function must be async def A sync function raises TypeError: '<name>' is not declared as an async callable. when the task is built (10B.8, 9.4)
@scorer(name="...") overrides the registered name The name is the score's name in the log, the results and the dataframes; it defaults to the factory's function name
Extra keyword arguments to @scorer are stored as scorer metadata Rarely needed
Factory arguments are recorded in the log So inspect score and re-scoring can rebuild the scorer by name (10B.11)
Resolve models inside score(), not in the factory Model roles are bound when the eval runs (10B.9, 7.3 showed the same rule for solvers)

What the scorer receives is the whole TaskState, not just the text: state.output.completion (the final reply), state.messages (the conversation, including tool calls), state.metadata (the sample's metadata), state.store (whatever solvers recorded, 5.4), state.sample_id and state.epoch. That is the main difference from an evalkit scorer, which saw (example, output): an Inspect scorer can grade the process as well as the answer.

2.2 Score, field by field#

Score is a Pydantic model: Score(*, value, answer=None, explanation=None, reason=None, metadata=None, history=[]).

Field What to put there Where it shows up
value The verdict: a letter, a number, a bool, a list or a dict (2.3) Converted to a float for reducers and metrics
answer The thing you compared: the extracted letter, the parsed labels, the number found The viewer's sample list; the docs say to "strive to always return an answer"
explanation Why, for a human: "priority wrong (P2 vs P1)", or the grader's reasoning The viewer's score panel
reason A short machine-readable outcome label from the ScoreReason vocabulary, or your own string (4.4) Filters in analysis; score_<name>_reason columns in dataframes
metadata Structured detail: the individual checks, the grading prompt, counts The log; analysis code
history The edit trail when a score is changed after the run Written by edit_score() (10B.11); you do not set it

Score has accessors (as_str(), as_int(), as_float(), as_bool(), as_list(), as_dict()) and a class method, Score.unscored(*, reason=None, answer=None, explanation=None, metadata=None), which builds a score whose value is NaN (Part 4).

2.3 Value and the C/I/P/N constants#

Value is a union: a str, int, float or bool; a sequence of those; or a mapping from strings to those (or None). By convention, a categorical verdict uses four constants exported from inspect_ai.scorer:

Constant Value Means value_to_float()
CORRECT "C" The answer is right 1.0
INCORRECT "I" The answer is wrong (including empty or unparsable) 0.0
PARTIAL "P" Partly right 0.5
NOANSWER "N" No answer was given (a refusal, an abstention) 0.0

There is a fifth, UNCHANGED, used only when editing scores. Numbers are fine too: 10B.8's triage_labels returns a float in [0, 1] for partial credit, and nothing stops a scorer returning a latency in milliseconds or a count of citations. A value is not restricted to [0, 1]; only some metrics require that (ci_wilson() raises on values outside it).

2.4 value_to_float(): how values become numbers#

Metrics and the default reducer convert values with value_to_float(correct="C", incorrect="I", partial="P", noanswer="N"), which returns a converter function. Its rules, from the source and the probe below:

  1. If the value equals one of the four labels (compared with == first), map it: correct 1.0, partial 0.5, incorrect and no-answer 0.0. (Because the comparison is ==, a numeric custom label also captures equal values of other types: with correct=1, both True and 1.0 count as correct.)
  2. Other numbers and booleans are cast to float. (With the default labels, this is how True becomes 1.0 and False 0.0: they equal none of "C", "I", "P" or "N".)
  3. Strings are lower-cased: "yes" and "true" become 1.0, "no" and "false" 0.0, and numeric strings ("0.25") are parsed.
  4. Anything else becomes 0.0, with only a logged warning: an unknown string such as "pass", a list, a dict.
python
# s01_types.py: Score, Value, value_to_float and Target, poked at directly (lesson 10B.10)
import logging

from inspect_ai.scorer import (CORRECT, INCORRECT, NOANSWER, PARTIAL, Score,
                               Target, value_to_float)

logging.basicConfig(level=logging.WARNING, format="  log %(levelname)s: %(message)s")

print("constants:", CORRECT, INCORRECT, PARTIAL, NOANSWER)

# 1. How metrics and the default reducer turn values into floats.
to_float = value_to_float()
for v in ["C", "P", "I", "N", True, 0.7, 3, "yes", "No", "0.25", "pass", ["C"]]:
    print(f"value_to_float({v!r:8}) -> {to_float(v)}")

# 2. Your own labels need your own converter (pass it to metrics AND reducers).
custom = value_to_float(correct="pass", incorrect="fail")
print("custom:", custom("pass"), custom("fail"), custom("C"))

# 3. Score.as_float() does not convert labels.
s = Score(value=CORRECT, answer="P1|technical", explanation="both labels right")
try:
    s.as_float()
except ValueError as e:
    print("Score('C').as_float() ->", type(e).__name__, e)
print("Score('C').as_str() ->", s.as_str(), "| unscored value:", Score.unscored(reason="grader_failed").value)

# 4. Target: a list of acceptable answers, and what .text does with it.
t = Target(["Paris", "paris, France"])
print("list(target):", list(t), "| len:", len(t), "| .text:", repr(t.text))
print("Target('P2|billing').text:", Target("P2|billing").text)
bash
uv run python s01_types.py
Output · real21 lines
constants: C I P N
value_to_float('C'     ) -> 1.0
value_to_float('P'     ) -> 0.5
value_to_float('I'     ) -> 0.0
value_to_float('N'     ) -> 0.0
value_to_float(True    ) -> 1.0
value_to_float(0.7     ) -> 0.7
value_to_float(3       ) -> 3.0
value_to_float('yes'   ) -> 1.0
value_to_float('No'    ) -> 0.0
value_to_float('0.25'  ) -> 0.25
  log WARNING: Unable to convert value to float: pass
value_to_float('pass'  ) -> 0.0
  log WARNING: Unable to convert value to float: ['C']
value_to_float(['C']   ) -> 0.0
  log WARNING: Unable to convert value to float: c
custom: 1.0 0.0 0.0
Score('C').as_float() -> ValueError could not convert string to float: 'C'
Score('C').as_str() -> C | unscored value: nan
list(target): ['Paris', 'paris, France'] | len: 2 | .text: 'Parisparis, France'
Target('P2|billing').text: P2|billing

Rule 4 is the dangerous one, because it fails in the direction that looks like a model problem. A scorer that returns "Correct" (capital C, full word) instead of "C", or "PASS", or a list, produces a run in which accuracy is lower than it should be, and the only symptom is a warning line in the log. And look at the custom: line: a converter built for "pass"/"fail" maps the standard "C" to 0.0 as well (the warning printed c, the lower-cased value it could not convert). A custom converter replaces the label set; it does not extend it.

2.5 Home-made labels, and the converter in two places#

If you want labels of your own ("pass"/"fail", "grounded"/"ungrounded"), the converter must reach both places that convert values: the reducer and every metric. 1.2 showed the failure in three steps: no converter gives 0.0, a converter on the metrics alone still gives 0.0 (the reducer had already zeroed the values), and only both together give the right 0.5. The working pattern:

python
from inspect_ai import Epochs, Task
from inspect_ai.scorer import accuracy, mean_score, stderr, value_to_float

TO_FLOAT = value_to_float(correct="pass", incorrect="fail")

# 1. on the scorer:  @scorer(metrics=[accuracy(to_float=TO_FLOAT), stderr(to_float=TO_FLOAT)])
# 2. on the task:    Task(..., epochs=Epochs(1, mean_score(value_to_float=TO_FLOAT)))

The simpler policy, and the one this course recommends: return the built-in constants (CORRECT, INCORRECT, PARTIAL, NOANSWER) or plain numbers, and put your vocabulary in answer, explanation or metadata. Then the defaults are right everywhere, including in tools you did not write (Inspect View, evals_df(), other people's analysis code).

2.6 Target#

The scorer's second argument wraps the sample's target (10B.9, 2.3): Target(target: str | Sequence[str]). It has .target (always a list), is iterable, has len(), and has .text. The probe above shows the trap: Target(["Paris", "paris, France"]).text is 'Parisparis, France', the elements joined with no separator.

So:

  • With one target string (the triage task's "P2|billing"), target.text is the string, and that is what 10B.8's scorers use.
  • With several acceptable answers, iterate: any(t.lower() in reply.lower() for t in target). That is what the built-in text scorers do: the installed includes(), match() and friends loop over the targets and return CORRECT on the first match.
  • The custom-scorers page shows includes() implemented with target.text; the installed source iterates instead. Follow the source: a custom scorer that uses .text on a list target compares against a string nobody wrote.

2.7 SampleScore: what a metric receives#

Metrics do not receive bare Scores. They receive list[SampleScore], where SampleScore(*, score, sample_id=None, sample_metadata=None, scorer=None) carries the reduced score plus the sample's id and metadata. The metadata is how grouped() and clustered stderr() know which slice or cluster a sample belongs to (Part 6), and the id is how a metric that sees unreduced scores can tell epochs of the same sample apart (7.9). Reducers, in contrast, receive a plain list[Score]: they only ever see one sample.


Part 3: The built-in scorers, opened up#

3.1 The catalogue#

Inspect ships these scorers in inspect_ai.scorer (0.3.292). The default metrics are what you get if you do not override them.

Scorer Signature Compares Default metrics
includes includes(ignore_case=True) Any target is a substring of the output accuracy, stderr
match match(location="end", *, ignore_case=True, numeric=False) The output begins with, ends with, contains, or equals a target, after normalizing accuracy, stderr
pattern pattern(pattern, ignore_case=True, match_all=False) Regex capture groups (or the whole match) against the targets accuracy, stderr
answer answer(pattern) with "letter", "word" or "line" What follows the last ANSWER: accuracy, stderr
exact exact() Normalized output equals a normalized target mean, stderr
f1 f1(answer_fn=None, stop_words=None) Token-overlap F1 with the best target (a float) mean, stderr
choice choice() The letter(s) multiple_choice() marked against the target letter(s) accuracy, stderr
math math(*, timeout=2.0) Mathematical equivalence (LaTeX, fractions, sets, algebra) accuracy, stderr
perplexity perplexity() Per-token negative log-likelihood from prompt logprobs perplexity_per_token, perplexity_per_seq
target_perplexity target_perplexity(num_target_tokens=None, target_text_key="target_text") Negative log-likelihood of the target tokens only perplexity metrics
model_graded_qa, model_graded_fact see 10B.11 A grader model's verdict accuracy, stderr

Every text scorer works on state.output.completion (the last assistant reply's text), iterates the target list, and returns CORRECT on the first acceptable target. None of them reads the rest of the conversation.

3.2 includes()#

CORRECT if any target string appears anywhere in the output, case-insensitively by default (ignore_case=False to change it). It is the most forgiving scorer and the easiest to fool: the output "Is it billing or technical? Could be either." "includes" both billing and technical. Use it for facts that must be mentioned (a refund window, a product name, a canary phrase in a safety test) and pair it with something stricter when the answer is a choice between options.

The empty-target trap belongs here: "" is contained in every string, so a sample with no target passes includes() whatever the model says (10B.9, 2.2; reproduced again in 3.11).

3.3 match(), including numeric=True#

match() normalizes both sides (strips surrounding whitespace, casefolds unless ignore_case=False, and strips punctuation, except in numeric mode) and then compares at a location:

location Passes when the normalized output... Typical use
"end" (default) ends with the target "think out loud, then give the answer last" prompts
"begin" starts with the target "answer first, then explain" prompts
"any" contains the target like includes(), after normalization
"exact" equals the target a bare answer, nothing else

With numeric=True, the target is cleaned of currency symbols ($, €, £), thousands separators and */_ emphasis; if it is then a number, numbers are extracted from the output (the first for begin, the last for end, any of them for any) and compared numerically. This is the scorer for "what is the invoice total?" questions, and the probe in 3.11 shows where each location wins and loses: "Total: 1,234.50 (was 1,300.00)" passes with begin and any but fails with the default end, because the last number in the reply is the old price.

3.4 pattern()#

pattern(pattern, ignore_case=True, match_all=False) runs a regular expression over the output. With capture groups, the captured groups are compared with the targets: by default the sample passes if any group matches a target; with match_all=True, every group must match. Without groups, the whole match is compared. If the regex finds nothing, the score is INCORRECT with reason="invalid_response_format": the model did not produce the format you asked for, and the score says so in a way you can count (4.4).

The probe's part D shows the match_all difference on "priority=P1 escalate=P2" with target P1: one group matches, so the default passes and match_all=True fails.

3.5 answer() and AnswerPattern#

answer() extracts whatever follows the last ANSWER: in the reply, which pairs with prompts that say "end with ANSWER: ", including the chain_of_thought() template (10B.9, 6.6). Its argument picks one of three regexes, exported as AnswerPattern (exact text from 0.3.292):

Argument AnswerPattern regex Extracts
"letter" (?is)ANSWER\s*:\s*([A-Za-z])(?:[^\w]|\n|$)(?!.*ANSWER\s*:) A single letter, followed by a non-word character or the end
"word" (?is)ANSWER\s*:\s*(\S+?)(?=[.,;:!?]?\s*(?:\n|$))(?!.*ANSWER\s*:) One word, optionally followed by one punctuation mark, that ends its line
"line" (?i)ANSWER\s*:\s*([^\n]+)\s*\Z The rest of the line, which must be the reply's last line

(The \| above is a table escape; the regexes contain a plain |.) The negative lookahead (?!.*ANSWER\s*:) is what makes "last one wins": a model that writes ANSWER: A while thinking and ANSWER: B at the end is scored on B. Part C of the probe in 3.11 shows what each pattern extracts from three replies, and two surprises: "word" rejects a two-word answer (billing team) outright, and "letter" rejects ANSWER: billing. because the letter b is followed by another letter. Pick the pattern to match the slot your prompt defines, and test it on real replies before trusting it.

3.6 exact() and f1()#

Both normalize SQuAD-style: casefold, remove punctuation, normalize numbers, drop the articles a, an, the, and collapse whitespace.

  • exact() requires the normalized output to equal a normalized target. " paris " equals "Paris"; "The answer is 42" does not equal "42". An empty normalized target never matches (unlike includes()). Its values are numbers, so its default metric is mean().
  • f1() computes token-overlap F1 between the normalized output and each target and keeps the best: precision is the share of output tokens found in the target, recall the share of target tokens found in the output. "The answer is 42" against "42" gives tokens answer is 42 (the article is dropped) against 42: precision 1/3, recall 1, F1 0.5. Pass answer_fn to extract the answer first (for example, the text after ANSWER:), and stop_words to drop more tokens.

10A.3, 4.1 explained what token F1 rewards and where it misleads (word overlap is not meaning); those warnings apply unchanged.

3.7 choice()#

choice() scores the multiple-choice format of 10B.9, 4.4: it reads which choices the multiple_choice() solver marked as selected, compares them with the target letter (or letters: "A,B" or a list for multiple correct answers), and maps shuffled choices back correctly, so a sample whose choices were shuffled is scored on the option the model picked, not on the letter's position. It raises a scoring error for a sample with no choices. Use it only with multiple_choice(); for a free-text "pick a letter" prompt, answer("letter") is the scorer.

3.8 math()#

math() decides mathematical equivalence: it extracts the answer (a \boxed{} expression, or the last number or expression in the reply), parses both sides with a grammar that does not evaluate arbitrary code, and compares them with SymPy in a worker thread with a timeout (default 2 seconds). It needs an optional extra; without it, building the scorer fails (part F of the probe in 3.11):

bash
uv add "inspect-ai[math]"
# or: pip install "inspect-ai[math]"

The error message names a single package (latex2sympy2-extended); the documented and complete fix is the extra, which also installs the ANTLR runtime the parser needs. With the extra installed:

python
# s03b_math.py: math() with the [math] extra installed (lesson 10B.10)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import math as math_scorer

REPLIES = {"half": "So the probability is \\boxed{0.5}",
           "frac": "The answer is \\boxed{\\frac{2}{4}}",
           "alg": "Expanding gives \\boxed{x^2 + 2x + 1}",
           "wrong": "I get \\boxed{1/3}",
           "plain": "The answer is 1/2"}
TARGETS = {"half": "\\frac{1}{2}", "frac": "1/2", "alg": "(x+1)^2", "wrong": "1/2", "plain": "1/2"}

model = get_model("mockllm/model", memoize=False, custom_outputs=lambda i, t, tc, c:
                  ModelOutput.from_content(model="mockllm", content=REPLIES[i[-1].text]))
log = eval(Task(dataset=[Sample(id=k, input=k, target=TARGETS[k]) for k in REPLIES],
                scorer=math_scorer()), model=model, log_dir="logs", display="none")[0]
for s in sorted(log.samples, key=lambda s: s.id):
    sc = s.scores["math"]
    print(f"{s.id:6} target={TARGETS[s.id]:12} value={sc.value}  answer={sc.answer!r}  reason={sc.reason}")
print({k: round(m.value, 3) for k, m in log.results.scores[0].metrics.items()})
bash
uv run python s03b_math.py
Output · real6 lines
alg    target=(x+1)^2      value=C  answer='x^2 + 2x + 1'  reason=None
frac   target=1/2          value=C  answer='\\frac{2}{4}'  reason=None
half   target=\frac{1}{2}  value=C  answer='0.5'  reason=None
plain  target=1/2          value=C  answer='1/2'  reason=None
wrong  target=1/2          value=I  answer='1/3'  reason=None
{'accuracy': 0.8, 'stderr': 0.2}

0.5 equals \frac{1}{2}, \frac{2}{4} equals 1/2, x^2 + 2x + 1 equals (x+1)^2, and a reply with no \boxed{} is still scored on its last expression. That is exactly what string scorers cannot do: match() would fail three of the four correct answers. Use math() for quantitative answers (pricing calculations, unit conversions, a maths tutor product) and keep a few adversarial cases in the set ("1/3" against "0.33") so you know where your tolerance lies.

3.9 perplexity() and target_perplexity()#

These score a model's likelihood of text rather than its generated answer: perplexity() from the per-token log-probabilities of the prompt, target_perplexity() from the log-probabilities of the target tokens only. They need a provider that returns prompt log-probabilities (the docs use vLLM; hosted APIs generally do not), so they are for teams evaluating self-hosted models, which is outside this course's scope. They were not run for this lesson; the perplexity page is the reference if you need them.

3.10 model_graded_qa() and model_graded_fact()#

When no string rule can decide (open-ended answers, tone, "does this summary cover the incident?"), Inspect's built-in graders ask a model. They have their own template, nonce-marked prompt, grade extraction, grader roles, panels and failure modes, and they need their own validation against human labels; all of that is 10B.11. For this lesson, two facts are enough: a grader is a scorer like any other (it returns a Score, here usually C/I/P), and when it cannot produce a verdict it returns Score.unscored(reason="grader_failed"), which takes the sample out of the denominator (Part 4).

3.11 All of them on the same outputs#

The fastest way to learn the scorers is to run them side by side on outputs you chose. This script feeds fixed replies through a mock and prints every scorer's verdict and reason per sample. When a task has the same scorer twice, Inspect names the second match1, the third match2, and so on (5.6), so read the names in the order of the scorer= list.

python
# s03_builtin.py: every text scorer on the same fixed outputs (lesson 10B.10)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import answer, exact, f1, includes, match, pattern


def fixed_model(replies: dict[str, str]):
    """A mock whose reply is looked up by the sample input (safe under concurrency)."""
    def reply(input, tools, tool_choice, config):
        return ModelOutput.from_content(model="mockllm", content=replies[input[-1].text])
    return get_model("mockllm/model", custom_outputs=reply, memoize=False)


def run(samples, replies, scorers, show_reason=True):
    log = eval(Task(dataset=samples, scorer=scorers), model=fixed_model(replies),
               log_dir="logs", display="none")[0]
    for s in sorted(log.samples, key=lambda s: str(s.id)):
        cells = []
        for name, sc in s.scores.items():
            v = round(sc.value, 2) if isinstance(sc.value, float) else sc.value
            cells.append(f"{name}={v}" + (f"({sc.reason})" if show_reason and sc.reason else ""))
        print(f"  {s.id}: " + "  ".join(cells))
    print("  metrics:", {e.name: {k: round(m.value, 3) for k, m in e.metrics.items()}
                         for e in log.results.scores})


# A. Five outputs, eight scorers. (id, output, target)
CASES = [("q1", "The answer is 42", "42"),
         ("q2", "Reasoning...\nANSWER: B", "B"),
         ("q3", "  paris  ", "Paris"),
         ("q4", "the quick brown fox", "quick brown dog"),
         ("q5", "", "x")]
print("A. eight scorers on five fixed outputs")
run([Sample(id=i, input=i, target=t) for i, _, t in CASES], {i: o for i, o, _ in CASES},
    [match(), match(location="any"), match(location="exact"), includes(),
     pattern(r"(\d+)"), answer("letter"), exact(), f1()])

# B. Numbers: an invoice total written three ways. Target 1234.5.
INVOICES = [("inv1", "Total due: $1,234.50"), ("inv2", "It is 1234.5 dollars"),
            ("inv3", "Total: 1,234.50 (was 1,300.00)"), ("inv4", "the answer: 12")]
print("B. match() vs match(numeric=True), target 1234.5")
run([Sample(id=i, input=i, target="1234.5") for i, _ in INVOICES], dict(INVOICES),
    [match(), match(numeric=True), match(location="begin", numeric=True),
     match(location="any", numeric=True)])

# C. answer(): what each pattern extracts. The LAST "ANSWER:" in the reply wins.
REPLIES = {"r1": "ANSWER: A looked right at first.\nOn reflection:\nANSWER: B",
           "r2": "The ticket is about money.\nANSWER: billing.",
           "r3": "ANSWER: billing team"}
print("C. what answer('letter' | 'word' | 'line') extracts")
log = eval(Task(dataset=[Sample(id=k, input=k, target="B") for k in REPLIES],
                scorer=[answer("letter"), answer("word"), answer("line")]),
           model=fixed_model(REPLIES), log_dir="logs", display="none")[0]
for s in sorted(log.samples, key=lambda s: s.id):
    got = {n: (sc.answer if sc.reason is None else sc.reason) for n, sc in s.scores.items()}
    print(f"  {s.id} {REPLIES[s.id]!r:58} -> {got}")

# D. pattern() with two groups: any group vs match_all.
print("D. pattern() with two capture groups, target 'P1'")
run([Sample(id="p", input="p", target="P1")],
    {"p": "priority=P1 escalate=P2"},
    [pattern(r"priority=(P\d) escalate=(P\d)"),
     pattern(r"priority=(P\d) escalate=(P\d)", match_all=True)])

# E. The empty target again: every text scorer except exact() and f1() accepts any output.
print("E. Sample with no target (target == '')")
run([Sample(id="empty", input="e")], {"e": "anything at all"},
    [includes(), match(), match(location="any"), exact(), f1()])

# F. math() needs the optional extra: without it, building the scorer fails.
from inspect_ai.scorer import math as math_scorer   # noqa: E402  (named to avoid shadowing `math`)
try:
    math_scorer()
except Exception as e:
    print("F. math() without the extra ->", type(e).__name__ + ":", " ".join(str(e).split()))
bash
uv run python s03_builtin.py
Output · real24 lines
A. eight scorers on five fixed outputs
  q1: match=C  match1=C  match2=I  includes=C  pattern=C  answer=I(invalid_response_format)  exact=I  f1=0.5
  q2: match=C  match1=C  match2=I  includes=C  pattern=I(invalid_response_format)  answer=C  exact=I  f1=0.5
  q3: match=C  match1=C  match2=C  includes=C  pattern=I(invalid_response_format)  answer=I(invalid_response_format)  exact=C  f1=1.0
  q4: match=I  match1=I  match2=I  includes=I  pattern=I(invalid_response_format)  answer=I(invalid_response_format)  exact=I  f1=0.67
  q5: match=I(no_response)  match1=I(no_response)  match2=I(no_response)  includes=I(no_response)  pattern=I(no_response)  answer=I(no_response)  exact=I(no_response)  f1=0.0(no_response)
  metrics: {'match': {'accuracy': 0.6, 'stderr': 0.245}, 'match1': {'accuracy': 0.6, 'stderr': 0.245}, 'match2': {'accuracy': 0.2, 'stderr': 0.2}, 'includes': {'accuracy': 0.6, 'stderr': 0.245}, 'pattern': {'accuracy': 0.2, 'stderr': 0.2}, 'answer': {'accuracy': 0.2, 'stderr': 0.2}, 'exact': {'mean': 0.2, 'stderr': 0.2}, 'f1': {'mean': 0.534, 'stderr': 0.162}}
B. match() vs match(numeric=True), target 1234.5
  inv1: match=I  match1=C  match2=C  match3=C
  inv2: match=I  match1=C  match2=C  match3=C
  inv3: match=I  match1=I  match2=C  match3=C
  inv4: match=I  match1=I  match2=I  match3=I
  metrics: {'match': {'accuracy': 0.0, 'stderr': 0.0}, 'match1': {'accuracy': 0.5, 'stderr': 0.289}, 'match2': {'accuracy': 0.75, 'stderr': 0.25}, 'match3': {'accuracy': 0.75, 'stderr': 0.25}}
C. what answer('letter' | 'word' | 'line') extracts
  r1 'ANSWER: A looked right at first.\nOn reflection:\nANSWER: B' -> {'answer': 'B', 'answer1': 'B', 'answer2': 'B'}
  r2 'The ticket is about money.\nANSWER: billing.'             -> {'answer': 'invalid_response_format', 'answer1': 'billing', 'answer2': 'billing.'}
  r3 'ANSWER: billing team'                                     -> {'answer': 'invalid_response_format', 'answer1': 'invalid_response_format', 'answer2': 'billing team'}
D. pattern() with two capture groups, target 'P1'
  p: pattern=C  pattern1=I
  metrics: {'pattern': {'accuracy': 1.0, 'stderr': 0.0}, 'pattern1': {'accuracy': 0.0, 'stderr': 0.0}}
E. Sample with no target (target == '')
  empty: includes=C  match=C  match1=C  exact=I  f1=0.0
  metrics: {'includes': {'accuracy': 1.0, 'stderr': 0.0}, 'match': {'accuracy': 1.0, 'stderr': 0.0}, 'match1': {'accuracy': 1.0, 'stderr': 0.0}, 'exact': {'mean': 0.0, 'stderr': 0.0}, 'f1': {'mean': 0.0, 'stderr': 0.0}}
F. math() without the extra -> PrerequisiteError: [bold]ERROR[/bold]: math() scorer requires optional dependencies. Install with: [bold]pip install latex2sympy2-extended==1.11.0[/bold]

Read part A as a table of design choices, row by row:

  • q1, "The answer is 42" vs 42. match() (end) and match(any) pass, match(exact) and exact() fail, answer() finds no ANSWER: and says invalid_response_format, f1 gives partial credit 0.5. One output, four different verdicts, all correct by their own rules.
  • q2, a reasoned reply ending ANSWER: B. answer("letter") is the right tool and passes; pattern(r"(\d+)") finds no digits and flags the format; exact() fails because the reasoning is part of the output.
  • q3, " paris " vs Paris. Every normalizing scorer passes; this is what normalization is for.
  • q4, "the quick brown fox" vs "quick brown dog". Only f1 sees two of three words overlapping (0.67). Whether that deserves credit is your decision, not the scorer's.
  • q5, an empty reply. Every scorer says I (or 0.0) with reason="no_response": the model gave nothing, and the reason lets you count that separately from wrong answers.

Part B is the invoice: plain match() fails every formatted number, numeric=True fixes the currency and thousands separators, and only begin/any survive a reply that mentions a second number after the answer. Part C shows the three answer() patterns, part D match_all, part E the empty target (every scorer except exact() and f1() accepts any output), and part F the missing extra for math() (the [bold] tags are rich-text markup inside the error message itself).

3.12 When the output does not match: the shared rules#

The standard-scorers page states the rules all text scorers share, and the probe confirms them:

Situation includes, match, exact pattern, answer f1
Output does not match INCORRECT, no reason (not applicable) low or 0.0
The expected format is absent (not applicable) INCORRECT, reason="invalid_response_format" (not applicable)
Empty or whitespace-only output INCORRECT, reason="no_response" INCORRECT, reason="no_response" 0.0, reason="no_response"

Every one of these is a verdict: it stays in the denominator and counts as 0. That is deliberate. An unparsable or empty reply is the model's failure to do what was asked, and leaving it out of the metric would reward a model for failing in an unreadable way (4.5).

3.13 Choosing a built-in scorer, and the evalkit equivalents#

Your answer looks like Use Watch out for evalkit (10A.3) twin
A fact that must be mentioned anywhere includes() Hedged replies naming every option; empty targets contains_any
A short answer at the end of a free reply match() (end) or answer("word") Trailing chatter; numbers after the answer normalized_match
A number, possibly formatted match(numeric=True) with the right location Several numbers in the reply numeric_match
A slot you defined in the prompt ("ANSWER: x") answer() with the matching pattern word rejects multi-word answers; letter needs a non-letter after it regex_match
A custom format (a field, a code) pattern() Format failures are verdicts (invalid_response_format) regex_match
A bare answer that must be exactly right exact() Articles and punctuation are dropped before comparing exact_match / normalized_match
Extractive QA with partial credit f1() Overlap is not meaning token_f1
A multiple-choice letter from multiple_choice() choice() Only with that solver exact_match on the letter
A mathematical expression math() with the [math] extra Timeout on hard expressions numeric_match (numbers only)
JSON, several fields, business rules A custom scorer (Part 5) Return an answer and a reason json_field_match, schema_valid
Open-ended quality model_graded_qa() (10B.11) Needs validation against humans judges.py

The normalization rules differ in detail from evalkit's normalize_text() (10A.3, 2.1): Inspect's exact() and f1() drop articles, evalkit's default does not. When you port an eval, run both on a fixed set of outputs and reconcile the verdicts before comparing numbers, exactly as 10B.8, 4.8 did for the triage scorers.


Part 4: The scoring policy: verdict, error, unscored or nothing#

Deep-dive

Inspect's documentation has a page called Scoring Policy, and it is the most important page in the scoring section, because it decides the denominator. Two runs with the same verdicts on the samples that were scored can report different accuracies because they disagree about which samples count. This part teaches the policy, reproduces every case, and adds one case the docs do not mention.

4.1 Four outcomes and what each does to the denominator#

A scorer can end in four ways:

The scorer... Inspect records In the metric's denominator? Counted as
returns a Score with a real value the score Yes scored_samples
returns Score.unscored(reason=...) a score whose value is NaN, with the reason No unscored_samples (after epoch reduction)
returns None no score entry for this scorer No nowhere
raises an exception sample.error; this scorer produces no score No the sample is an error; fail_on_error and retry_on_error apply
flowchart TD
    A["Scorer runs on a finished sample"] --> B{"What did it do?"}
    B -->|"returned Score(value=...)"| C["Verdict: counts in the denominator<br/>INCORRECT and NOANSWER count as 0"]
    B -->|"returned Score.unscored(reason=...)"| D["Value is NaN: excluded from metrics<br/>counted in unscored_samples"]
    B -->|"returned None"| E["No score entry at all<br/>not counted anywhere"]
    B -->|"raised an exception"| F["Recorded in sample.error<br/>this scorer gives no score<br/>fail_on_error / retry_on_error apply"]
    C --> G["Who failed?"]
    G -->|"the model under test:<br/>empty, unparsable, refusal"| H["Keep it as INCORRECT<br/>reason: no_response, invalid_response_format, refusal"]
    G -->|"the instrument:<br/>grader or scorer could not decide"| D

Each outcome has a meaning, and choosing the right one is part of writing a scorer:

  • A verdict means "I judged this answer." Wrong, empty and unparsable answers are verdicts (INCORRECT with a reason), because the model under test failed.
  • Unscored means "the instrument could not judge this answer": the grader gave no verdict, an external checker was unavailable, the reference data was missing. The sample is excluded, and the count is kept so you can see how much was excluded.
  • None means "this sample is outside my scope": a scorer that only applies to tickets with attachments, or a repair-rate scorer on a control run that has no repair loop (5.4). It leaves no trace.
  • An exception means "the scorer itself broke." It is a bug to fix, not a measurement.

4.2 The four outcomes, reproduced#

The docs' worked example has one correct, one incorrect, one raise and one unscored sample, and states the result: accuracy 1/2, two scored, one unscored. This script reproduces it and adds the fifth case, None, plus the solver-error variant of the next section and the all-unscored edge case.

python
# s04_policy.py: verdict vs raise vs Score.unscored() vs None, and what each does to the number (lesson 10B.10)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import (CORRECT, INCORRECT, Score, Target, accuracy,
                               scorer, stderr)
from inspect_ai.solver import Generate, TaskState, generate, solver

OUTCOME = {"right": "verdict C", "wrong": "verdict I", "crash": "raise",
           "unsure": "Score.unscored()", "offtopic": "return None"}


@scorer(metrics=[accuracy(), stderr()])
def policy_demo():
    async def score(state: TaskState, target: Target) -> Score | None:
        kind = state.sample_id
        if kind == "right":
            return Score(value=CORRECT, answer="ok")
        if kind == "wrong":
            return Score(value=INCORRECT, answer="nope")
        if kind == "crash":
            raise RuntimeError("scorer bug: KeyError on a field the output lacked")
        if kind == "unsure":
            return Score.unscored(reason="grader_failed", explanation="no verdict found")
        return None                      # "offtopic": outside this scorer's scope
    return score


def report(label, log):
    es = log.results.scores[0] if log.results.scores else None
    metrics = {k: round(m.value, 3) for k, m in es.metrics.items()} if es else {}
    print(f"{label}: status={log.status} total={log.results.total_samples} "
          f"completed={log.results.completed_samples} "
          f"scored={es and es.scored_samples} unscored={es and es.unscored_samples} {metrics}")
    for s in sorted(log.samples, key=lambda s: s.id):
        sc = (s.scores or {}).get("policy_demo")
        shown = None if sc is None else (sc.value, sc.reason)
        print(f"   {s.id:9} {OUTCOME.get(s.id, ''):17} score={shown}  error={bool(s.error)}")


DATA = [Sample(id=k, input=k) for k in OUTCOME]

# 1. The four outcomes. fail_on_error=False so the raising sample does not stop the task.
log = eval(Task(dataset=DATA, scorer=policy_demo(), fail_on_error=False),
           model="mockllm/model", log_dir="logs", display="none")[0]
report("1. four outcomes", log)


# 2. A SOLVER error with score_on_error=True: the partial state is scored and counts.
@solver
def flaky_tool():
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state = await generate(state)
        if state.sample_id == "crash":
            raise RuntimeError("tool call failed: upstream 503")
        return state
    return solve


@scorer(metrics=[accuracy(), stderr()])
def strict():
    async def score(state: TaskState, target: Target) -> Score:
        ok = state.sample_id in ("right",)
        return Score(value=CORRECT if ok else INCORRECT)
    return score


for flag in (False, True):
    log = eval(Task(dataset=DATA[:3], solver=flaky_tool(), scorer=strict(),
                    fail_on_error=False, score_on_error=flag),
               model="mockllm/model", log_dir="logs", display="none")[0]
    es = log.results.scores[0]
    print(f"2. solver error, score_on_error={flag}: scored={es.scored_samples} "
          f"accuracy={es.metrics['accuracy'].value:.3f}")

# 3. Every sample unscored: the metrics are NaN, not 0.
log = eval(Task(dataset=[Sample(id="unsure", input="u")], scorer=policy_demo()),
           model="mockllm/model", log_dir="logs", display="none")[0]
es = log.results.scores[0]
print("3. all unscored:", {k: m.value for k, m in es.metrics.items()},
      f"scored={es.scored_samples} unscored={es.unscored_samples}")
bash
uv run python s04_policy.py
Output · real9 lines
1. four outcomes: status=success total=5 completed=4 scored=2 unscored=1 {'accuracy': 0.5, 'stderr': 0.5}
   crash     raise             score=None  error=True
   offtopic  return None       score=None  error=False
   right     verdict C         score=('C', None)  error=False
   unsure    Score.unscored()  score=(nan, 'grader_failed')  error=False
   wrong     verdict I         score=('I', None)  error=False
2. solver error, score_on_error=False: scored=2 accuracy=0.500
2. solver error, score_on_error=True: scored=3 accuracy=0.333
3. all unscored: {'accuracy': nan, 'stderr': nan} scored=0 unscored=1

Block 1 is the policy in one place. Five samples, total=5; four completed (the one whose scorer raised is an error); two scored (right, wrong); one unscored (unsure); and offtopic appears in no count at all. Accuracy is 1 of 2, not 1 of 5, 1 of 4 or 1 of 3. The run's status is still success, because fail_on_error=False allowed one error.

Block 3 is the edge case to remember: when every sample is unscored, the metrics are nan, not 0. A dashboard that turns nan into a blank, or a gate that compares nan >= 0.8 (which is False but for the wrong reason), hides a run in which nothing was measured.

4.3 Errors in the solver: score_on_error, and the silent TimeoutError#

Block 2 of the output is about errors that happen before scoring, in the solver (a tool call that fails, a parser that throws). By default an errored sample is not scored: score_on_error=False gave scored=2, accuracy 1/2. With Task(score_on_error=True) (or --score-on-error), Inspect runs the scorers on whatever state the sample had reached, and the scorer's verdict counts: scored=3, accuracy 1/3, the docs' "1/3" case. Which is right depends on what you are measuring:

Policy Use when The number means
score_on_error=False (default) Errors are infrastructure (a 503 from a tool host, a sandbox crash) and you will retry or report them Quality on the samples that ran
score_on_error=True Errors are the system's own failures (the agent's tool call was malformed and crashed it) Quality including the failures a user would see

Either way, report the error count next to the number (4.6), and see 10B.12 for retry_on_error and error thresholds.

Now the case the documentation does not mention. A solver that lets a TimeoutError escape (an asyncio.wait_for with no except, an HTTP client's timeout) does not produce an error at all:

python
# s04b_timeout.py: a TimeoutError that escapes a solver is NOT a sample error (lesson 10B.10)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import includes
from inspect_ai.solver import Generate, TaskState, solver


@solver
def slow_tool(exc: str):
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state = await generate(state)
        if state.sample_id == "b":
            raise {"timeout": TimeoutError, "runtime": RuntimeError}[exc]("tool call took too long")
        return state
    return solve


for exc in ("runtime", "timeout"):
    log = eval(Task(dataset=[Sample(id=i, input=i, target="mockllm") for i in "abc"],
                    solver=slow_tool(exc), scorer=includes(), fail_on_error=False),
               model="mockllm/model", log_dir="logs", display="none")[0]
    es = log.results.scores[0]
    b = next(s for s in log.samples if s.id == "b")
    print(f"{exc:8} status={log.status} scored={es.scored_samples} "
          f"accuracy={es.metrics['accuracy'].value:.3f} | sample b: error={b.error is not None} "
          f"score={b.scores and b.scores['includes'].value}")

# The only trace: a warning recorded as a logger event in sample b's transcript.
print("sample b logger events:", [e.message.message for e in b.events if e.event == "logger"])
bash
uv run python s04b_timeout.py
Output · real3 lines
runtime  status=success scored=2 accuracy=1.000 | sample b: error=True score={}
timeout  status=success scored=3 accuracy=1.000 | sample b: error=False score=C
sample b logger events: ['sample=b\nUnexpected timeout error reached top of sample stack. Are you handling TimeoutError when applying timeouts?']

With a RuntimeError, sample b is an error, is not scored, and accuracy is 1.0 over 2 samples. With a TimeoutError and nothing else changed, sample b has no error, is scored on its partial state (here it had already generated, so it passed), and counts in a denominator of 3. Inspect's source treats an unexpected TimeoutError at the top of the sample as a mis-handled timeout: it logs a warning ("Unexpected timeout error reached top of sample stack. Are you handling TimeoutError when applying timeouts?") into the sample's transcript, and scores the most recent state. The only trace is that logger event.

What this means for you as an engineer: in solvers and tools, catch your own timeouts and either convert them into a deliberate outcome (a tool result the agent sees, an INCORRECT verdict with a reason) or re-raise them as a different exception type, so the scoring policy sees what really happened. Inspect's own time limits are not affected: they raise a limit error and are recorded as a sample limit (10B.15).

4.4 ScoreReason: who failed, in a word#

Score.reason is a short machine-readable label. Inspect's vocabulary (ScoreReason), with the actor each one blames:

Reason Actor Set by Value
invalid_response_format The model under test pattern, answer, your scorers A verdict (INCORRECT)
no_response The model under test Every text scorer on an empty reply; model graders A verdict
refusal The model under test Your scorers A verdict
grader_failed The grader (instrument) Model graders without a usable verdict Unscored (NaN)
scoring_failed The scorer (instrument) multi_scorer when every component declined; your scorers Unscored
excluded An operator, after the run exclude_samples() / inspect log exclude Unscored
zeroed An operator, after the run zero_samples() / inspect log zero A verdict copied from an "empty attempt" run

Custom strings are allowed (reason="summary_too_long"), and the reasons appear as score_<name>_reason columns when you read sample scores into a dataframe (10B.13). Use the built-in ones where they fit: other people's tooling understands them. The operator reasons belong to the post-run workflow of 10B.11.

4.5 The measurement-instrument rule#

The policy rests on one idea from the docs: a scorer, and especially a model grader, is part of the measurement instrument. That gives a simple test for every failure:

  • If the model under test failed (empty reply, wrong format, refusal, nonsense), it is a verdict against the model: INCORRECT, in the denominator. Excluding it would reward the failure.
  • If the instrument failed (the grader returned no grade, the checker was down), it says nothing about the model: unscored, out of the denominator, and counted.

The rule cuts both ways. A scorer that returns Score.unscored() whenever the model's JSON does not parse is a scorer that lets a model improve its accuracy by breaking its output format. And a scorer that returns INCORRECT whenever the grader times out blames the model for the grader's outage. Before you choose unscored, ask: "whose fault was this?"

4.6 Coverage: always report what was not scored#

Unscored, declined and errored samples shrink the denominator silently: the metric is computed over what is left, and nothing in the number says how much is left. A run in which the grader failed on the hardest 20% of samples can report a higher accuracy than a run in which it did not. So every Inspect number you quote should carry its coverage, from the EvalScore and the results:

Field Where Meaning
scored_samples log.results.scores[i] Samples whose reduced score counted
unscored_samples log.results.scores[i] Samples reduced to NaN (all epochs unscored, or a reducer that returned NaN)
total_samples, completed_samples log.results Sample-epochs planned and completed (errors are the difference)
log.eval.dataset.samples the header How many samples the dataset had

A one-line coverage rule for reports: "accuracy 0.733 over 12 of 12 samples (0 unscored, 0 errors)". If the counts are not all there, the number is not finished.

4.7 INCORRECT versus NOANSWER#

INCORRECT and NOANSWER both convert to 0.0, and the default mean reducer erases the difference before any metric runs. But they are different facts: a non-clinical health FAQ bot that declines to answer a question about medication doses may be doing exactly what you want, and one that answers wrongly is not. If your scorer distinguishes them, keep the distinction visible with a metric that sees the raw labels:

python
# s17_noanswer.py: INCORRECT and NOANSWER both count 0 in accuracy; frequency() keeps them apart (lesson 10B.10)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import (CORRECT, INCORRECT, NOANSWER, Score, Target,
                               accuracy, frequency, scorer)
from inspect_ai.solver import TaskState

VERDICTS = {"m1": CORRECT, "m2": CORRECT, "m3": INCORRECT, "m4": NOANSWER, "m5": NOANSWER}


@scorer(metrics=[accuracy(), frequency(categories=["C", "I", "N"])])
def medical_faq():
    """A (scripted) scorer for a non-clinical FAQ bot: N = the bot declined to answer."""
    async def score(state: TaskState, target: Target) -> Score:
        return Score(value=VERDICTS[state.sample_id])
    return score


for epochs in (1, 2):
    log = eval(Task(dataset=[Sample(id=k, input=k) for k in VERDICTS], scorer=medical_faq(),
                    epochs=epochs), model="mockllm/model", log_dir="logs", display="none")[0]
    for es in log.results.scores:
        print(f"epochs={epochs} reducer={es.reducer} scored={es.scored_samples}",
              {k: round(v.value, 3) for k, v in es.metrics.items()})
bash
uv run python s17_noanswer.py
Output · real4 lines
epochs=1 reducer=mean scored=5 {'accuracy': 0.4}
epochs=1 reducer=None scored=5 {'C': 0.4, 'I': 0.2, 'N': 0.4}
epochs=2 reducer=mean scored=5 {'accuracy': 0.4}
epochs=2 reducer=None scored=10 {'C': 0.4, 'I': 0.2, 'N': 0.4}

Accuracy says 0.4 and nothing else. frequency(categories=["C", "I", "N"]) says 40% correct, 20% wrong and 40% declined: a very different product from "60% wrong". frequency() is declared to see unreduced scores (every sample-epoch), which is why it is reported as its own EvalScore with reducer None, and why with two epochs it counts ten observations (scored=10) while accuracy still counts five samples (7.9).

4.8 A scoring policy for your own scorers#

Write the policy down before you write the scorer, and put it in the scorer's docstring:

  1. What is a verdict? List the outcomes that are the model's responsibility (wrong, empty, unparsable, refused, over length) and the value and reason each gets.
  2. What is unscored? List the instrument failures (grader without a verdict, missing reference, checker unavailable) and give each a reason.
  3. What is out of scope? Return None only for samples the scorer was never meant to judge, and make that a property of the sample (metadata), not of the output.
  4. What may raise? Nothing on any model output: parse defensively, and let only genuine bugs raise. 5.2 tests this.
  5. How will coverage be reported? Name the counts that will appear next to the number.
  6. Partial credit or binary? If partial, say how it maps to [0, 1] and which metric summarizes it (mean(), not accuracy(), so the number is named for what it is).

Part 5: Writing your own scorers#

Built-in scorers cover strings. Product evals need more: a JSON contract with several fields, business rules that read metadata, checks on what the agent did rather than what it said, combinations of checks, human ratings. This part builds each, on the triage eval.

5.1 Anatomy of a good custom scorer#

10B.8's triage_format and triage_labels already show the shape. Here is what makes a scorer production-grade, as a checklist you can hold any scorer against:

Property In triage_format / triage_labels
Parses defensively and never raises on model output parse_json() returns None on anything unparsable
Returns an answer (what was compared) The parsed JSON, or `"P2
Returns an explanation a reviewer can act on "keys=['priority']; category=None; summary not a string"
Uses a reason for machine-readable failure classes invalid_response_format
Puts structured detail in metadata {"checks": {"priority": ..., "category": ..., "summary": ...}}
Reads rules from sample metadata, not from the output allow_empty_summary
Uses built-in constants or numbers for value CORRECT/INCORRECT; a float in [0, 1]
Names its metric for what it is accuracy() for a verdict, mean() for partial credit
Is cheap and deterministic Pure Python, no model call

5.2 Testing a scorer without running an eval#

A scorer is an async function of (TaskState, Target), so you can call it directly with a hand-built state, no eval and no model. TaskState's constructor is documented as internal (Inspect builds it during a run), but it is public in the package and takes the fields a scorer reads, which makes it the simplest unit-test seam:

python
# test_scorers.py: unit-test scorers on hand-written outputs, no eval run and no model (lesson 10B.10)
import asyncio

import pytest

from inspect_ai.model import ModelOutput
from inspect_ai.scorer import CORRECT, INCORRECT, Target
from inspect_ai.solver import TaskState

from triage import triage_format, triage_labels


def state_with(output: str, metadata: dict | None = None) -> TaskState:
    """A TaskState that looks like a finished sample whose model replied `output`."""
    return TaskState(model="mockllm/model", sample_id="t", epoch=1, input="ticket text",
                     messages=[], output=ModelOutput.from_content(model="mockllm", content=output),
                     metadata=metadata or {})


def score(scorer, output: str, target: str, metadata: dict | None = None):
    return asyncio.run(scorer(state_with(output, metadata), Target(target)))


GOOD = '{"priority": "P1", "category": "technical", "summary": "API returns 403 after deploy."}'


@pytest.mark.parametrize("output, expected", [
    (GOOD, CORRECT),
    ("```json\n" + GOOD + "\n```", CORRECT),                       # fences are tolerated
    ('{"priority": "P1", "category": "tech", "summary": "x"}', INCORRECT),   # bad enum
    ('{"priority": "P1"}', INCORRECT),                              # missing keys
    ("", INCORRECT),                                                # empty reply
])
def test_format(output, expected):
    assert score(triage_format(), output, "P1|technical").value == expected


def test_format_reason_is_machine_readable():
    assert score(triage_format(), "no json here", "P1|technical").reason == "invalid_response_format"


def test_labels_partial_credit():
    wrong_priority = GOOD.replace('"P1"', '"P2"')
    s = score(triage_labels(), wrong_priority, "P1|technical")
    assert s.value == pytest.approx(2 / 3)
    assert s.metadata["checks"] == {"priority": False, "category": True, "summary": True}


def test_labels_empty_summary_only_allowed_when_flagged():
    empty = '{"priority": "P3", "category": "other", "summary": ""}'
    assert score(triage_labels(), empty, "P3|other", {"allow_empty_summary": "1"}).value == 1.0
    assert score(triage_labels(), empty, "P3|other").value == pytest.approx(2 / 3)


def test_labels_never_crash_on_garbage():
    for junk in ["{", "null", "[1, 2]", '{"priority": null}', "\x00"]:
        assert 0.0 <= score(triage_labels(), junk, "P1|technical").value <= 1.0
bash
uv add pytest   # once
uv run pytest -q test_scorers.py
Output · real2 lines
.........                                                                [100%]
9 passed in 0.36s

Nine tests in a third of a second. Keep a table of tricky outputs per scorer (fences, missing keys, wrong enum, empty, garbage) and a "never crash" test over junk inputs: it is how you keep rule 4 of the policy (4.8) true as the scorer evolves. 10A.3, Part 7 showed how to push this further with property-based tests. 10B.9, 7.9 tested solvers the same way.

5.3 Dict-valued scores and per-key metrics#

A single scorer can return several numbers at once by making value a dict. Each key then becomes its own score in the results, with its own metrics, declared in a dict on @scorer:

  • metrics={"*": [mean()]} applies mean() to every key;
  • metrics={"*": [mean()], "labels": [mean(), stderr()]} adds a standard error for one key;
  • metrics=[{"a": [mean()]}, some_whole_value_metric()] mixes per-key and whole-value metrics.

This is the natural shape for "field-level accuracy" reports, where one parse of the output feeds several checks. The first block of this script defines triage_fields; the rest of the script is used in 5.6 and 5.7:

python
# s05_custom_scorers.py: dict-valued scores, combining scorers, name suffixes (lesson 10B.10)
from inspect_ai import Task, eval
from inspect_ai.scorer import (CORRECT, Score, ScoreReducer, Scorer, Target, mean,
                               multi_scorer, score_reducer, scorer, stderr,
                               value_to_float)
from inspect_ai.solver import TaskState, generate, prompt_template

from fake_triage import scripted_model
from triage import (CATEGORIES, PRIORITIES, PROMPT_TEMPLATE, parse_json,
                    triage_format, triage_labels, triage_samples)


# 1. One scorer, one dict-valued Score: each key gets its own metrics.
@scorer(metrics={"*": [mean()], "labels": [mean(), stderr()]})
def triage_fields() -> Scorer:
    async def score(state: TaskState, target: Target) -> Score:
        obj = parse_json(state.output.completion) or {}
        want_priority, want_category = target.text.split("|")
        well_formed = (set(obj) == {"priority", "category", "summary"}
                       and obj.get("priority") in PRIORITIES
                       and obj.get("category") in CATEGORIES)
        priority_ok = obj.get("priority") == want_priority
        category_ok = obj.get("category") == want_category
        return Score(
            value={"format": float(well_formed),
                   "priority": float(priority_ok),
                   "category": float(category_ok),
                   "labels": float(priority_ok and category_ok)},
            answer=f"{obj.get('priority')}|{obj.get('category')}",
        )
    return score


# 2. "A sample passes only if every check passes", as a multi_scorer reduction.
@score_reducer(name="all_pass")
def all_pass() -> ScoreReducer:
    to_float = value_to_float()

    def reduce(scores: list[Score]) -> Score:
        values = [to_float(s.value) for s in scores]
        return Score(value=CORRECT if values and all(v == 1.0 for v in values) else "I",
                     explanation=f"component values: {values}")
    return reduce


def base_task(scorer) -> Task:
    return Task(dataset=triage_samples(),
                solver=[prompt_template(PROMPT_TEMPLATE), generate()], scorer=scorer)


runs = {
    "dict-valued": triage_fields(),
    "multi_scorer all_pass": multi_scorer([triage_format(), triage_labels()], all_pass()),
    "multi_scorer at_least_2": multi_scorer([triage_format(), triage_labels()], "at_least_2"),
    "multi_scorer mean": multi_scorer([triage_format(), triage_labels()], "mean"),
    "same scorer twice": [triage_format(), triage_format()],
}
for label, sc in runs.items():
    log = eval(base_task(sc), model=scripted_model(), log_dir="logs", display="none")[0]
    print(f"{label}:")
    for es in log.results.scores:
        print(f"   {es.name:14} scored={es.scored_samples}",
              {k: round(m.value, 3) for k, m in es.metrics.items()})
    if label == "dict-valued":
        t02 = next(s for s in log.samples if s.id == "T02").scores["triage_fields"]
        print("   T02 value:", t02.value, "| answer:", t02.answer)
    if label == "multi_scorer all_pass":
        t02 = next(s for s in log.samples if s.id == "T02").scores["multi_scorer"]
        print("   T02:", t02.value, "|", t02.explanation)
bash
uv run python s05_custom_scorers.py
Output · real16 lines
dict-valued:
   format         scored=12 {'mean': 0.917}
   priority       scored=12 {'mean': 0.917}
   category       scored=12 {'mean': 0.833}
   labels         scored=12 {'mean': 0.833, 'stderr': 0.112}
   T02 value: {'format': 1.0, 'priority': 0.0, 'category': 0.0, 'labels': 0.0} | answer: P2|billing
multi_scorer all_pass:
   multi_scorer   scored=12 {'accuracy': 0.833, 'stderr': 0.112}
   T02: I | component values: [1.0, 0.3333333333333333]
multi_scorer at_least_2:
   multi_scorer   scored=12 {'accuracy': 0.833, 'stderr': 0.112}
multi_scorer mean:
   multi_scorer   scored=12 {'accuracy': 0.903, 'stderr': 0.072}
same scorer twice:
   triage_format  scored=12 {'accuracy': 0.917, 'stderr': 0.083}
   triage_format1 scored=12 {'accuracy': 0.917, 'stderr': 0.083}

The dict-valued block: one scorer produced four results, named after the keys. Format 0.917 (T11's prose), priority 0.917 (T02's), category 0.833 (T02 and T11), and labels (both right) 0.833 with its own standard error. T02's value shows the whole dict, and its answer the labels it compared. This is the report a triage team wants: not "0.833" but "priority is fine, category is where we lose".

Two cautions. The keys of the dict are the score names in the results, so they share a namespace with other scorers' names. And a task-level Task(metrics=[...]) replaces the per-key metrics too; 6.9 shows aggregate(), the metric for picking one key when you do that.

5.4 A scorer that reads the store: the repair rate#

10B.9, Part 9 built a generate_with_repair solver that records its attempts in a RepairLog store model, and noted that "a model that needs repairs on 30% of tickets costs more and fails more under load than one that needs none", so the repair rate should be reported next to accuracy. A scorer can read the store with store_as() exactly as the solver wrote it. This file goes in 10B.9's triage/ folder, beside triage_task.py:

python
# s06_store_scorer.py: a scorer that reads the solver's store: the repair rate (lesson 10B.10)
# Run from the triage/ folder of lesson 10B.9 (it reads tickets.jsonl and triage_system.txt).
from inspect_ai import eval, task_with
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import Score, Scorer, Target, mean, scorer, stderr
from inspect_ai.solver import TaskState
from inspect_ai.util import store_as

from triage_task import RepairLog, triage, triage_match


@scorer(metrics=[mean(), stderr()])
def needed_repair() -> Scorer:
    """1.0 if the repair loop had to ask again. Reads the store, not the output."""
    async def score(state: TaskState, target: Target) -> Score:
        repair = store_as(RepairLog)
        if repair.attempts == 0:                      # a control solver: no repair loop ran
            return None
        return Score(value=float(repair.attempts > 1), answer=str(repair.attempts),
                     explanation="; ".join(repair.problems) or "first reply was valid")
    return score


REPLIES = {   # the same scripted model as lesson 10B.9's run_triage.py
    "charged twice": '{"category": "billing", "priority": "P3"}',
    "log in": '{"category": "technical", "priority": "P1"}',
    "second admin": '{"category": "account", "priority": "P3"}',
    "hacked": '{"category": "account", "priority": "P1"}',
    "standing desks": "Sure! This looks like a shipping question.",
    "crashes": '{"category": "technical", "priority": "P2"}',
    "quick fix": '{"category": "other", "priority": "P3"}',
    "downgrade": '{"category": "billing", "priority": "P3"}',
}


def scripted(input, tools, tool_choice, config):
    text = "\n".join(m.text for m in input)
    if "rejected" in input[-1].text:
        return ModelOutput.from_content(model="mockllm",
                                        content='{"category": "shipping", "priority": "P2"}')
    return ModelOutput.from_content(model="mockllm",
                                    content=next(v for k, v in REPLIES.items() if k in text))


model = get_model("mockllm/model", custom_outputs=scripted, memoize=False)
for variant in ("default", "oracle"):
    task = task_with(triage(solver=variant), scorer=[triage_match(), needed_repair()])
    log = eval(task, model=model, log_dir="logs", display="none")[0]
    for es in log.results.scores:
        print(f"{variant:8} {es.name:14} scored={es.scored_samples}",
              {k: round(m.value, 3) for k, m in es.metrics.items()})
    if variant == "default":
        t05 = next(s for s in log.samples if s.id == "T05").scores["needed_repair"]
        print("         T05 needed_repair:", t05.value, "| attempts", t05.answer, "|", t05.explanation)
bash
cd triage && uv run python s06_store_scorer.py
Output · real5 lines
default  triage_match   scored=8 {'accuracy': 0.875, 'stderr': 0.125}
default  needed_repair  scored=8 {'mean': 0.125, 'stderr': 0.125}
         T05 needed_repair: 1.0 | attempts 2 | not valid JSON (Expecting value)
oracle   triage_match   scored=8 {'accuracy': 1.0, 'stderr': 0.0}
oracle   needed_repair  scored=0 {'mean': nan, 'stderr': nan}

The default solver's run now reports two numbers: accuracy 0.875 and a repair rate of 0.125 (T05, whose first reply was prose). On the oracle control, needed_repair returns None (no repair loop ran, so the question does not apply), and the result is scored=0 with nan metrics: out of scope, visibly. Scorers like this measure the process, not the answer, and they are the bridge to agent evaluation, where the store and the message history carry the trajectory (10B.14, 10B.16).

5.5 Scorers that call a model#

When the check needs judgement, a scorer can call a model. The pattern, which 10B.11 develops into a validated grader:

python
from inspect_ai.model import get_model
from inspect_ai.scorer import CORRECT, INCORRECT, Score, Scorer, Target, accuracy, scorer, stderr
from inspect_ai.solver import TaskState


@scorer(metrics=[accuracy(), stderr()])
def summary_names_issue() -> Scorer:
    """C if a grader model says the summary names the concrete issue."""
    async def score(state: TaskState, target: Target) -> Score:
        grader = get_model(role="grader")              # resolved per call, never in the factory
        result = await grader.generate(
            "Does this one-sentence ticket summary name the concrete issue? "
            "Reply YES or NO on the last line.\n\nSummary: " + state.output.completion)
        lines = result.completion.strip().splitlines()
        verdict = lines[-1].strip().upper() if lines else ""
        if verdict not in ("YES", "NO"):              # the instrument failed, not the model
            return Score.unscored(reason="grader_failed", explanation=result.completion)
        return Score(value=CORRECT if verdict == "YES" else INCORRECT,
                     answer=state.output.completion, explanation=result.completion)
    return score

The scoring-policy choices are the ones from Part 4: an unreadable verdict is the grader's failure, so it is unscored, not INCORRECT. What this sketch leaves out (the grader role's binding and its silent fallback to the model under test, generation settings, prompt-injection-resistant templates, panels, validation against human labels) is exactly what 10B.11 covers; do not ship a model-calling scorer without it.

5.6 Several scorers on one task#

Task(scorer=[a(), b(), c()]) runs every scorer on every sample. Each scorer keeps its own score per sample and its own metrics, and the order of results follows the list. Three behaviours to know.

Name suffixing. Two scorers with the same registered name are renamed in order: triage_format, triage_format1 (the last block of 5.3's output), and in 3.11 match, match1, match2, match3. Code that looks results up by name must expect this; giving the scorers distinct names with @scorer(name=...) or distinct factories avoids it.

Partial survival. Scores are kept as each scorer completes. If the second scorer raises, the first scorer's score survives next to sample.error, and still counts in the first scorer's metrics:

python
# s05b_partial.py: one of two scorers raises: what survives (lesson 10B.10)
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import Score, Target, accuracy, includes, scorer
from inspect_ai.solver import TaskState


@scorer(metrics=[accuracy()])
def needs_json():
    async def score(state: TaskState, target: Target) -> Score:
        import json
        return Score(value="C" if json.loads(state.output.completion) else "I")   # raises on prose
    return score


log = eval(Task(dataset=[Sample(id="a", input="a", target="mockllm")],
                scorer=[includes(), needs_json()], fail_on_error=False),
           model="mockllm/model", log_dir="logs", display="none")[0]
s = log.samples[0]
print("sample scores:", {k: v.value for k, v in s.scores.items()})
print("sample error :", s.error.message.splitlines()[-1] if s.error else None)
print("results      :", [(es.name, es.scored_samples, {k: v.value for k, v in es.metrics.items()})
                         for es in log.results.scores])
bash
uv run python s05b_partial.py
Output · real3 lines
sample scores: {'includes': 'C'}
sample error : JSONDecodeError('Expecting value: line 1 column 1 (char 0)')
results      : [('includes', 1, {'accuracy': 1.0, 'stderr': 0.0}), ('needs_json', 0, {'accuracy': nan})]

The sample is an error, yet includes counted it (scored=1, accuracy 1.0) while needs_json has no score at all (scored=0, nan). So within one run, different scorers can have different denominators. Compare scored_samples across scorers before you compare their metrics.

No combined verdict. There is still no "the sample passes if every scorer passes" number. That is the next section.

5.7 multi_scorer(): one score from several, and "every check must pass"#

multi_scorer(scorers, reducer) runs a list of scorers concurrently on the same sample and reduces their scores into one score, named multi_scorer, using a reducer: any built-in reducer name (7.3) or a custom @score_reducer. Components that return None are dropped; if all of them decline, the result is Score.unscored(reason="scoring_failed"). The metrics of the combined score come from the first scorer in the list.

10B.8, 4.8 left a promise: evalkit's pass rate requires every scorer to pass, and Inspect has no built-in for it. Look back at the output of 5.3:

multi_scorer([triage_format(), triage_labels()], ...) Per-sample rule Result Reproduces
custom all_pass() reducer C only if every component converts to exactly 1.0 0.833 evalkit's pass rate, 83.3%
"at_least_2" 1 if at least 2 components are ≥ 1.0 (with two components: all of them) 0.833 the same, with a built-in reducer
"mean" the mean of the components 0.903 evalkit's mean score, 0.903

Both of 10A.1's headline numbers are now first-class Inspect scores, computed per sample, logged, and visible in the viewer. T02's combined explanation (component values: [1.0, 0.333...]) shows why it failed: format fine, labels wrong. "min" is not a built-in reducer name, which is why the custom all_pass() is shown; for a fixed number of components, at_least_<n> with n equal to the count does the same job.

5.8 cascade(): cheap first, expensive only when needed#

cascade(threshold=1.0, **scorers) runs named stages in order and stops at the first stage whose value converts to at least threshold. Stages that decline (None) or are unscored are skipped. The result is one score named cascade, with metadata["decided_by"] naming the stage that decided. The use: let a cheap deterministic check accept the obvious passes, and pay for a model grader only on the rest.

python
# s07_cascade_precomputed.py: cascade(), precomputed_scores() and scores set inside solvers (lesson 10B.10)
import json

from inspect_ai import Task, eval, score
from inspect_ai.dataset import Sample
from inspect_ai.model import ModelOutput, get_model
from inspect_ai.scorer import (Score, Scorer, cascade, includes, mean,
                               model_graded_qa, precomputed_scores, scorer)
from inspect_ai.scorer import score as score_now          # the in-solver function
from inspect_ai.solver import Generate, TaskState, generate, solver


def reply(text: str) -> ModelOutput:
    return ModelOutput.from_content(model="mockllm", content=text)


# --- 1. cascade(): a cheap deterministic stage first, a (mock) grader only when it fails.
ANSWERS = {"refund": "You can request a refund within 30 days of purchase.",
           "returns": "Returns are accepted for a month after delivery.",
           "exchange": "Exchanges are possible for two weeks."}
GRADER_CALLS = []


def grader_fn(input, tools, tool_choice, config):
    prompt = input[-1].text
    submission = prompt.rsplit("[BEGIN SUBMISSION", 1)[1]   # the LAST marker is the real field
    GRADER_CALLS.append(submission.split("\n")[1])
    return reply("Equivalent to thirty days. GRADE: C" if "a month" in submission
                 else "Not the same period. GRADE: I")


faq_model = get_model("mockllm/model", memoize=False,
                      custom_outputs=lambda i, t, tc, c: reply(ANSWERS[i[-1].text]))
grader = get_model("mockllm/model", custom_outputs=grader_fn, memoize=False)
log = eval(Task(dataset=[Sample(id=k, input=k, target="30 days") for k in ANSWERS],
                scorer=cascade(keyword=includes(), grader=model_graded_qa(model=grader))),
           model=faq_model, log_dir="logs", display="none")[0]
print("1. cascade:", {k: round(m.value, 3) for k, m in log.results.scores[0].metrics.items()},
      "| score name:", log.results.scores[0].name)
for s in sorted(log.samples, key=lambda s: s.id):
    sc = next(iter(s.scores.values()))
    print(f"   {s.id:8} value={sc.value} decided_by={sc.metadata.get('decided_by')}")
print("   grader was called for:", sorted(GRADER_CALLS))

# --- 2. precomputed_scores(): attach human ratings to an existing log, without re-running it.
base = eval(Task(dataset=[Sample(id=k, input=k, target="30 days") for k in ANSWERS],
                 scorer=includes()), model=faq_model, log_dir="logs", display="none")[0]
with open("human_ratings.jsonl", "w") as f:          # what a labelling tool might export
    for rec in [{"id": "refund", "value": 5, "explanation": "clear and correct"},
                {"id": "returns", "value": 4},
                {"id": "unknown-id", "value": 1}]:   # matches no sample: ignored
        f.write(json.dumps(rec) + "\n")


@scorer(metrics=[mean()])
def human_clarity() -> Scorer:
    return precomputed_scores("human_ratings.jsonl")


rescored = score(base, human_clarity(), action="append")
for es in rescored.results.scores:
    print(f"2. {es.name:14} scored={es.scored_samples} unscored={es.unscored_samples}",
          {k: round(m.value, 3) for k, m in es.metrics.items()})
print("   per sample:", {s.id: (s.scores.get("human_clarity").value if "human_clarity" in s.scores else "no score entry") for s in sorted(rescored.samples, key=lambda s: s.id)})


# --- 3. Scores from inside a solver: state.scores, and intermediate scoring with score().
@solver
def answer_then_check():
    async def solve(state: TaskState, generate: Generate) -> TaskState:
        state = await generate(state)
        interim = await score_now(state)            # runs the task's scorers right now
        state.scores = {"first_try": interim[0]}    # keep it as a score of its own
        return state
    return solve


log = eval(Task(dataset=[Sample(id=k, input=k, target="30 days") for k in ANSWERS],
                solver=answer_then_check(), scorer=includes()),
           model=faq_model, log_dir="logs", display="none")[0]
print("3. results:", [(es.name, {k: round(m.value, 3) for k, m in es.metrics.items()})
                      for es in log.results.scores])
s = next(x for x in log.samples if x.id == "refund")
print("   refund scores:", {k: v.value for k, v in s.scores.items()},
      "| score events:", sum(1 for e in s.events if e.event == "score"))
bash
uv run python s07_cascade_precomputed.py
Output · real10 lines
1. cascade: {'accuracy': 0.667, 'stderr': 0.333} | score name: cascade
   exchange value=I decided_by=grader
   refund   value=C decided_by=keyword
   returns  value=C decided_by=grader
   grader was called for: ['Exchanges are possible for two weeks.', 'Returns are accepted for a month after delivery.']
2. includes       scored=3 unscored=0 {'accuracy': 0.333, 'stderr': 0.333}
2. human_clarity  scored=2 unscored=0 {'mean': 4.5}
   per sample: {'exchange': 'no score entry', 'refund': 5, 'returns': 4}
3. results: [('includes', {'accuracy': 0.333, 'stderr': 0.333}), ('first_try', {'accuracy': 0.333, 'stderr': 0.333})]
   refund scores: {'includes': 'C', 'first_try': 'C'} | score events: 3

Block 1: refund contains "30 days", so the keyword stage decided it and the grader was never called. returns ("a month") failed the keyword stage and was accepted by the (scripted) grader; exchange ("two weeks") went to the grader and failed there. The grader was called twice instead of three times; on a real eval where most answers pass the cheap check, the saving is most of the grading bill.

The docs' caution is the whole design rule: earlier stages must not produce false positives, because a pass from stage 1 is never re-checked. A keyword stage that accepts "within 30 days, unless you've used the product" would pass a wrong answer without a second look. Make the early stages strict (exact, schema-valid, known-good strings) and let the expensive stage handle everything uncertain. And note the scripted grader's comment: Inspect's default grading prompt contains a [BEGIN SUBMISSION marker in its preamble, so a mock grader must look for the last marker to find the real submission (10B.11 shows the whole prompt). 10B.11, 9.3 runs a cascade in front of a real grading template and shows the false positive on negated answers.

5.9 precomputed_scores(): human labels and scores from elsewhere#

precomputed_scores(scores, on_missing="unscored", metrics=None) is a scorer that reads scores from a file instead of computing them: a JSON array or JSON Lines file of records with an id matching a sample id, a value, and optionally epoch, answer, explanation and metadata. Its purpose is to attach scores produced outside Inspect (human ratings from a labelling tool, another system's checker) to an existing log with score() or inspect score, so they live next to the automated scores and use the same metrics machinery. To give the score a name, wrap it in your own @scorer factory, as block 2 of the script above does with human_clarity; the factory's metrics apply.

Block 2 attached two human clarity ratings (5 and 4) to an existing run with score(base, human_clarity(), action="append"), which returns a new EvalLog with the extra scorer (the original includes result is kept). The record for an unknown id was ignored. Look at the coverage, though: the sample with no rating (exchange) got no score entry at all, and the result says scored=2 unscored=0. The docstring says such samples are "left unscored"; in 0.3.292 they are not counted as unscored, they are simply absent. So the human-rating coverage of this run (2 of 3) is visible only if you count it yourself; on_missing="error" is the setting for a file that must cover every sample.

This is where 10A.5's label sets meet Inspect: export the human labels, attach them with precomputed_scores(), and the log then holds the judge's verdicts and the humans' side by side, ready for the agreement statistics of 6.11 and 10A.5's tools. 10B.11 builds that workflow end to end.

5.10 Scores set by solvers, and intermediate scoring#

Two less common ways to produce scores, both shown in block 3 of the script above:

  • Solver-set scores. A solver may assign state.scores = {"name": Score(...)}. Those scores are merged with the task's scorers' results and get metrics of their own (block 3 shows first_try reported with accuracy and stderr). Use it for a verdict that only the solver can know (did the first attempt pass, how many tool calls did the plan need).
  • Intermediate scoring. Inside a solver, await score(state) runs the task's scorers on the current state now and returns their scores, for example to decide whether to retry or to record how good the first attempt was. Block 3's sample shows three score events in its transcript: the intermediate one, the solver-set one and the final scoring.

What this means for you as an engineer: an intermediate score that feeds back into the solver (retry until the scorer says C) makes the scorer part of the system under test. The final score then measures "the model plus a retry loop that sees the grader", which is a different system from production unless production has the same check. Report it as such, or do not do it.


Part 6: Metrics and their formulas#

Deep-dive

A metric turns one scorer's per-sample values into a summary. Inspect's built-ins are short functions, and every formula below was read from the installed 0.3.292 source and checked by recomputing it with the standard library. Knowing the formulas is what lets you say what a number assumes, which is the difference between quoting it and defending it.

6.1 What a metric is, and where it is declared#

A metric is a factory decorated with @metric that returns a function (scores: list[SampleScore]) -> Value. It is registered as inspect_ai/<name> for the built-ins. You attach metrics in one of two places:

Where Effect
@scorer(metrics=[...]) The scorer's own metrics: they travel with the scorer to every task that uses it
Task(metrics=[...]) (or task_with(..., metrics=...)) Replaces the metrics of every scorer in the task, including per-key metrics of dict-valued scores

The replacement is total: with Task(metrics=[grouped(accuracy(), "edge")]) the task's scorers report only the grouped values, not their own accuracy and standard error (6.8, block 1e). If you want the default metrics plus more, list them all: Task(metrics=[accuracy(), stderr(), ci_wilson()]).

Most metrics take a to_float converter (default value_to_float()), which is the hook 2.5 used for home-made labels. A metric returns a float, or a mapping (as ci() and grouped() do), whose keys become separate metric names in the results.

6.2 accuracy() and mean()#

Both compute sum(to_float(value)) / n over the reduced scores, and the functions return 0.0 when handed an empty list. (A run in which every sample is unscored still reports nan, as 4.2 showed: do not rely on either value to mean "nothing was measured"; check scored_samples.) They are the same formula with different names; the convention is accuracy() for verdicts (C/I) and mean() for numeric scores (partial credit, F1, a 1 to 5 rating), so that the name tells a reader what kind of number it is. The docs' recommendation, which this course follows: name the number for what it is.

6.3 std() and var()#

The sample standard deviation and variance with ddof=1 (dividing by n − 1, not n), returning 0 when there are fewer than two scores. For binary scores they are determined by the accuracy (var = n/(n−1) · p(1−p)), so they add little; for partial-credit and numeric scores they describe the spread, which is worth reporting when the mean hides a split ("half the summaries are perfect, half are empty" and "every summary is middling" can share a mean of 0.5).

6.4 stderr(): the standard error Inspect reports#

stderr() is the Central Limit Theorem standard error of the mean:

text
stderr = std(values, ddof=1) / sqrt(n)        (0 when n < 2)

where values are the reduced per-sample scores and n is the number of scored samples. Three things follow, and each matters when you read a results panel:

  1. n is the number of samples, not samples × epochs. Epochs are reduced first, so five epochs of twelve tickets give n = 12 (7.10 explains why that is right).
  2. It assumes the samples are independent draws from the population you care about. When samples come in groups (ten questions per document, the turns of one conversation, several tickets from one customer), that assumption fails, and the standard error is too small (6.5).
  3. A zero is not certainty. stderr is 0 with one sample, with all-identical scores (the oracle and null runs of 10B.8, 10.2), and on any slice of size one. Read it with n.

The usual "mean ± 1.96 × stderr" interval is a normal approximation that misbehaves near 0 and 1 and at small n; 10B.8, 10.4 showed it running past 1.0 at 11 of 12. Use an interval metric instead (6.7).

6.5 Clustered standard errors#

stderr(cluster="doc") computes a clustered standard error, grouping samples by a metadata key. The formula in Inspect's source (which cites Appendix A of Evan Miller's paper Adding Error Bars to Evals, and adds a finite-cluster correction the paper does not use):

text
mean          = average of all n values
residual_c    = sum over the samples i in cluster c of (value_i - mean)
stderr_cluster = sqrt( sum over clusters c of residual_c^2  *  C / (C - 1) ) / n

with C the number of clusters. It returns 0 with fewer than two clusters and raises ValueError if any sample lacks the key (a missing key, None or NaN all count as missing). The idea, from 10A.2, 6.7: samples in a cluster tend to pass or fail together, so the cluster, not the sample, is closer to the independent unit. When cluster means differ, residuals inside a cluster add up instead of cancelling, and the clustered error grows.

The research sheet behind this track ran this metric on a toy set in which every cluster had the same pass rate, and got exactly 0: when every cluster mean equals the grand mean, every residual_c is 0. That is a property of the toy data, not of clustering, and it would teach the opposite of the truth. Here is a realistic set instead: sixteen docs_qa-style questions written from four help-centre documents, where the documents differ in difficulty (the pricing page is easy, the audit-logs page is a mess). The verdicts are fixed in metadata so every number can be checked by hand:

python
# s08_metrics.py: every summary metric on one set of fixed verdicts (lesson 10B.10)
# 16 docs_qa-style questions written from 4 documents. The verdicts are fixed in
# metadata so every number below can be checked by hand (s08b_by_hand.py does).
from inspect_ai import Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import (CORRECT, INCORRECT, Score, Target, accuracy,
                               bootstrap_stderr, ci, ci_wilson, grouped, scorer,
                               std, stderr, var)
from inspect_ai.solver import TaskState

# correct answers per document (out of 4 questions each): unequal on purpose
PASSES = {"pricing": 4, "sso-setup": 3, "data-export": 1, "audit-logs": 0}


def questions(passes: dict[str, int]) -> list[Sample]:
    return [Sample(id=f"{doc}-q{q}", input=f"question {q} about {doc}",
                   metadata={"doc": doc, "verdict": CORRECT if q <= k else INCORRECT})
            for doc, k in passes.items() for q in range(1, 5)]


@scorer(metrics=[])
def fixed_verdict():
    """Returns the verdict stored in the sample's metadata (a stand-in for a real scorer)."""
    async def score(state: TaskState, target: Target) -> Score:
        return Score(value=state.metadata["verdict"])
    return score


METRICS = [accuracy(), stderr(), stderr(cluster="doc"), bootstrap_stderr(), std(), var(),
           ci(), ci(cluster="doc"), ci_wilson(), ci_wilson(cluster="doc"),
           grouped(accuracy(), "doc")]


def run(passes: dict[str, int]) -> dict[str, float]:
    log = eval(Task(dataset=questions(passes), scorer=fixed_verdict(), metrics=METRICS),
               model="mockllm/model", log_dir="logs", display="none")[0]
    return {k: round(m.value, 4) for k, m in log.results.scores[0].metrics.items()}


print("A. unequal documents", PASSES)
for name, value in run(PASSES).items():
    print(f"   {name:16} {value}")

EQUAL = {doc: 2 for doc in PASSES}
print("B. equal documents (every document 2 of 4)", EQUAL)
b = run(EQUAL)
print("   accuracy", b["accuracy"], "| stderr", b["stderr"], "| stderr2 (clustered)", b["stderr2"])

print("C. bootstrap_stderr is unseeded: three runs of A ->",
      [run(PASSES)["bootstrap_stderr"] for _ in range(3)])
bash
uv run python s08_metrics.py

The output below is real; the bootstrap_stderr values are unseeded and change on every run.

Output · real23 lines
A. unequal documents {'pricing': 4, 'sso-setup': 3, 'data-export': 1, 'audit-logs': 0}
   accuracy         0.5
   stderr           0.1291
   stderr2          0.2282
   bootstrap_stderr 0.1225
   std              0.5164
   var              0.2667
   lower            0.2248
   upper            0.7752
   lower2           -0.2263
   upper2           1.2263
   lower3           0.28
   upper3           0.72
   lower4           0.0882
   upper4           0.9118
   pricing          1.0
   sso-setup        0.75
   data-export      0.25
   audit-logs       0.0
   all              0.5
B. equal documents (every document 2 of 4) {'pricing': 2, 'sso-setup': 2, 'data-export': 2, 'audit-logs': 2}
   accuracy 0.5 | stderr 0.1291 | stderr2 (clustered) 0.0
C. bootstrap_stderr is unseeded: three runs of A -> [0.1187, 0.1228, 0.1297]

And the same numbers from the formulas, with nothing but the standard library (python3 s08b_by_hand.py):

python
# s08b_by_hand.py: recompute s08's numbers with the standard library only (lesson 10B.10)
import math
import statistics

PASSES = {"pricing": 4, "sso-setup": 3, "data-export": 1, "audit-logs": 0}
scores = {doc: [1.0] * k + [0.0] * (4 - k) for doc, k in PASSES.items()}
flat = [s for doc_scores in scores.values() for s in doc_scores]
n, C = len(flat), len(scores)
mean = statistics.fmean(flat)

# CLT standard error, sample std with ddof=1 (what stderr() computes)
se = statistics.stdev(flat) / math.sqrt(n)

# Clustered standard error, the formula in Inspect's source:
#   sqrt( sum over clusters of (sum of residuals in the cluster)^2  *  C/(C-1) ) / n
resid_sums = {doc: sum(s - mean for s in doc_scores) for doc, doc_scores in scores.items()}
se_cluster = math.sqrt(sum(r * r for r in resid_sums.values()) * C / (C - 1)) / n

# t intervals: t with n-1 degrees of freedom, or C-1 when clustered.
# 97.5% quantiles from a t table: t(15) = 2.1314, t(3) = 3.1824
t15, t3 = 2.1314, 3.1824


def wilson(k: int, n: int, z: float = 1.959964) -> tuple[float, float]:
    p = k / n
    centre = (p + z * z / (2 * n)) / (1 + z * z / n)
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
    return centre - half, centre + half


print(f"accuracy {mean:.4f}   std {statistics.stdev(flat):.4f}   var {statistics.variance(flat):.4f}")
print(f"stderr {se:.4f}   clustered stderr {se_cluster:.4f}   ratio {se_cluster / se:.2f}")
print("residual sum per document:", {d: round(r, 2) for d, r in resid_sums.items()})
print(f"ci() t interval           [{mean - t15 * se:.4f}, {mean + t15 * se:.4f}]")
print(f"ci(cluster) t interval    [{mean - t3 * se_cluster:.4f}, {mean + t3 * se_cluster:.4f}]")
lo, hi = wilson(int(sum(flat)), n)
print(f"Wilson interval           [{lo:.4f}, {hi:.4f}]")
print(f"design effect (se_cluster/se)^2 = {(se_cluster / se) ** 2:.2f}"
      f" -> {n} questions carry about as much information as {n / (se_cluster / se) ** 2:.1f} independent ones")

# Clustered Wilson: shrink n to the Korn-Graubard effective size p(1-p)/se_cluster^2,
# and use t(C-1) instead of z.
n_eff = min(mean * (1 - mean) / se_cluster ** 2, n)
lo, hi = wilson(int(sum(flat)) * n_eff / n, n_eff, z=t3)   # same p, smaller n
print(f"clustered Wilson: effective n {n_eff:.2f} -> [{lo:.4f}, {hi:.4f}]")
Output · real8 lines
accuracy 0.5000   std 0.5164   var 0.2667
stderr 0.1291   clustered stderr 0.2282   ratio 1.77
residual sum per document: {'pricing': 2.0, 'sso-setup': 1.0, 'data-export': -1.0, 'audit-logs': -2.0}
ci() t interval           [0.2248, 0.7752]
ci(cluster) t interval    [-0.2263, 1.2263]
Wilson interval           [0.2800, 0.7200]
design effect (se_cluster/se)^2 = 3.12 -> 16 questions carry about as much information as 5.1 independent ones
clustered Wilson: effective n 4.80 -> [0.0882, 0.9118]

Every metric Inspect printed is reproduced, and the comparison is the lesson:

Unclustered Clustered by document
Standard error 0.129 0.228 (1.77× wider)
95% t interval (ci) [0.225, 0.775] [−0.226, 1.226]
95% Wilson interval (ci_wilson) [0.280, 0.720] [0.088, 0.912]
What it says "about 50%, give or take 25 points" "we have four documents; it could be almost anything"

Block B makes the trap explicit: give every document 2 of 4 and the clustered standard error is 0.0, smaller than the unclustered 0.129. With equal cluster means, the cluster-level evidence really does have no spread; with four clusters that is luck, not information. Clustered errors are honest when clusters differ, and fragile when there are few clusters.

What this means for you as an engineer:

  • Tag the source of dependence in metadata at load time (doc, conversation_id, customer, seed_ticket), so the cluster is available to every metric (10B.9, 2.5).
  • Report the clustered error whenever samples share a source, and count your clusters: with fewer than about 10 to 20 clusters, any clustered estimate is itself noisy, which is why the t interval uses C − 1 degrees of freedom and blows up at C = 4.
  • The design effect (se_cluster / se)^2 translates the result into sample sizes: 3.12 here, so sixteen questions carry about as much information as five independent ones. Size the next dataset by documents, not by questions (10A.2, Part 5).
  • The clustered error can come out smaller than the plain one (block B, and the worked example in Part 9). Do not choose between them by which is smaller; choose by the data's structure, decided before you look.

6.6 bootstrap_stderr()#

bootstrap_stderr(num_samples=1000, to_float=...) resamples the values with replacement 1,000 times and reports the standard deviation of the resampled means. It is a reasonable estimate of the same quantity as stderr() (about 0.12 against 0.1291 above), but the resampling uses np.random.choice without a seed, so the number changes from run to run (block C: 0.1187, 0.1228, 0.1297 on three identical runs in the printed output; your re-run will show three other values). Do not use it where reproducibility matters (a CI gate, a published number); stderr() and the seeded bootstraps of evalkit (10A.8, 4.1) are deterministic.

6.7 Intervals: ci() and ci_wilson()#

Inspect reports no interval unless you ask. Two metrics produce one, as a mapping with lower and upper keys:

Metric Signature Method
ci ci(level=0.95, method="t", num_samples=1000, to_float=..., cluster=None) method="t": mean ± t(n−1) × stderr, or with cluster, t(C−1) × clustered stderr. method="bootstrap": a percentile bootstrap (a cluster bootstrap with cluster), unseeded. Collapses to the point with fewer than two values
ci_wilson ci_wilson(level=0.95, to_float=..., cluster=None) The Wilson score interval for a proportion. Values must lie in [0, 1] (others raise ValueError); partial values such as 0.5 are accepted and give a conservative interval. With cluster, the sample size is shrunk to the Korn-Graubard effective size p(1−p) / clustered_variance (capped at n) and t(C−1) replaces z; it needs at least two clusters. If p̂ is exactly 0 or 1, or the clustered variance is 0 (block B's equal cluster means), n is left unadjusted and only the t value changes

Inspect's docs say it directly: prefer ci_wilson() over ci() for binary scores such as accuracy. The t interval is symmetric and unbounded, so it runs outside [0, 1] near the edges and with few clusters (the [−0.226, 1.226] above); Wilson stays inside [0, 1] and is well calibrated at small n and near 0 or 1, which is where eval accuracies live. Use ci() for genuinely continuous scores (a mean rating, F1), and ci(method="bootstrap") only where its run-to-run variation does not matter.

6.8 grouped(): metrics per slice#

grouped(metric, group_key, *, all="samples", all_label="all", value_to_float=..., name_template="{group_name}") applies a metric to each group of samples sharing a metadata value, which is Inspect's built-in answer to evalkit's slice_breakdown():

Option Effect
all="samples" (default) Adds an all entry computed over every sample (the ordinary overall metric)
all="groups" Adds an all entry that is the mean of the group values (each slice weighted equally)
all=False No all entry
name_template How each group's metric is named, e.g. "labels_{group_name}"
all_label The name of the all entry

Every sample must have the key (a missing key raises). On the triage eval, by intent and by edge case:

python
# s09_grouped.py: per-slice metrics, category distributions and dict keys on the triage eval (lesson 10B.10)
from inspect_ai import Task, eval
from inspect_ai.scorer import (Score, Scorer, Target, accuracy, aggregate,
                               categorical, grouped, mean, scorer, stderr)
from inspect_ai.solver import TaskState, generate, prompt_template

from fake_triage import scripted_model
from triage import PROMPT_TEMPLATE, parse_json, triage_format, triage_labels, triage_samples


def run(scorer, metrics=None, epochs=None):
    task = Task(dataset=triage_samples(), solver=[prompt_template(PROMPT_TEMPLATE), generate()],
                scorer=scorer, metrics=metrics, epochs=epochs)
    return eval(task, model=scripted_model(), log_dir="logs", display="none")[0]


def show(label, log):
    for es in log.results.scores:
        print(f"{label} [{es.name}]", {k: round(m.value, 3) for k, m in es.metrics.items()})


# 1. grouped(): the labels score per intent. Three ways to compute the "all" entry.
show("1a all='samples'", run(triage_labels(), [grouped(mean(), "intent")]))
show("1b all='groups' ", run(triage_labels(), [grouped(mean(), "intent", all="groups")]))
show("1c all=False    ", run(triage_labels(), [grouped(mean(), "intent", all=False,
                                                       name_template="labels_{group_name}")]))
# A grouped stderr: one number per slice, each from only that slice's samples.
show("1d stderr       ", run(triage_labels(), [grouped(stderr(), "intent", all=False)]))
# Task(metrics=...) REPLACES the scorer's own metrics for every scorer in the task.
show("1e two scorers  ", run([triage_format(), triage_labels()], [grouped(accuracy(), "edge", all=False)]))


# 2. categorical(): the distribution of what the model PREDICTED (not whether it was right).
@scorer(metrics=categorical(["billing", "technical", "account", "shipping", "other", "unparsed"]))
def predicted_category() -> Scorer:
    async def score(state: TaskState, target: Target) -> Score:
        obj = parse_json(state.output.completion) or {}
        return Score(value=obj.get("category") or "unparsed")
    return score


show("2  categorical  ", run(predicted_category()))
show("2b with epochs=2", run(predicted_category(), epochs=2))


# 3. aggregate(): one key of a dict-valued score, through any metric.
@scorer(metrics={"*": [mean()]})
def checks() -> Scorer:
    async def score(state: TaskState, target: Target) -> Score:
        obj = parse_json(state.output.completion) or {}
        want_priority, want_category = target.text.split("|")
        return Score(value={"priority": float(obj.get("priority") == want_priority),
                            "category": float(obj.get("category") == want_category)})
    return score


show("3  aggregate    ", run(checks(), [aggregate("category", mean()),
                                         aggregate("category", stderr())]))
bash
uv run python s09_grouped.py
Output · real9 lines
1a all='samples' [triage_labels] {'billing': 0.778, 'technical': 0.778, 'account': 1.0, 'shipping': 1.0, 'other': 1.0, 'all': 0.889}
1b all='groups'  [triage_labels] {'billing': 0.778, 'technical': 0.778, 'account': 1.0, 'shipping': 1.0, 'other': 1.0, 'all': 0.911}
1c all=False     [triage_labels] {'labels_billing': 0.778, 'labels_technical': 0.778, 'labels_account': 1.0, 'labels_shipping': 1.0, 'labels_other': 1.0}
1d stderr        [triage_labels] {'billing': 0.222, 'technical': 0.222, 'account': 0.0, 'shipping': 0.0, 'other': 0.0}
1e two scorers   [triage_format] {'multi-intent': 1.0, 'outage': 1.0, 'how-to': 1.0, 'security': 1.0, 'stale-tracking': 1.0, 'bug-report': 1.0, 'no-request': 1.0, 'downgrade': 1.0, 'empty': 1.0, 'typos': 0.0, 'non-english': 1.0}
1e two scorers   [triage_labels] {'multi-intent': 1.0, 'outage': 0.667, 'how-to': 1.0, 'security': 1.0, 'stale-tracking': 1.0, 'bug-report': 1.0, 'no-request': 1.0, 'downgrade': 1.0, 'empty': 1.0, 'typos': 0.333, 'non-english': 1.0}
2  categorical   [predicted_category] {'billing': 0.25, 'technical': 0.167, 'account': 0.25, 'shipping': 0.083, 'other': 0.167, 'unparsed': 0.083}
2b with epochs=2 [predicted_category] {'billing': 0.25, 'technical': 0.167, 'account': 0.25, 'shipping': 0.083, 'other': 0.167, 'unparsed': 0.083}
3  aggregate     [checks] {'aggregate': 0.833, 'aggregate2': 0.112}

Blocks 1a to 1c: the labels mean per intent is 0.778 for billing and technical (T11's and T02's partial credit) and 1.0 elsewhere. The two kinds of all differ: 0.889 is the mean over twelve tickets; 0.911 is the mean of five slice values, in which the one shipping ticket weighs as much as the three billing tickets. Use all="groups" when each slice matters equally to the business (every language, every customer tier), and say so next to the number.

Block 1d is the warning: grouped(stderr(), ...) gives 0.222 for the three-ticket slices and 0.0 for shipping and other, which have one and two samples (and identical scores). A slice of one has no measurable uncertainty, not zero uncertainty. 10A.2, 5.4 set the floor (about 30 cases per slice before a slice number means anything); on twelve tickets, slices are for reading failures, not for decisions. grouped() does not report slice sizes, so count them yourself (collections.Counter(s.metadata["intent"] for s in dataset)).

Block 1e shows the replacement rule of 6.1: with Task(metrics=[grouped(...)]) both scorers report only per-edge values, eleven slices of mostly one sample each. Slicing a small set by a fine-grained key produces many numbers and little information, and invites the multiple-comparisons problem of 8.6.

6.9 aggregate(): one key of a dict-valued score#

aggregate(key, agg, *, to_float=None, on_missing="error") extracts one key from each dict-valued score and feeds it to any metric. Block 3 above uses it to get the category accuracy and its standard error from the checks scorer. Its options: on_missing="error" (default) raises when a sample's dict lacks the key (or has None), "skip" drops the sample (which shrinks n and changes the standard error), and "zero" counts it as 0.0 (a constant denominator, which the docstring recommends when you want one). A per-key NaN is always skipped, and if every sample is skipped the result is NaN.

Two notes from the output: aggregate metrics are named aggregate, aggregate2 and so on, whatever key they read, so keep a comment next to the metrics list; and because Task(metrics=...) replaced the scorer's {"*": [mean()]}, the per-key results disappeared. Per-key metrics on the scorer (5.3) are usually the clearer choice; aggregate() is for applying a metric to one key from outside the scorer.

6.10 frequency() and categorical()#

frequency(categories=None, normalize=True) reports the share (or, with normalize=False, the count) of each distinct value. It is declared to see unreduced scores, so it counts every sample-epoch. categorical(categories) is a convenience that returns [frequency(categories=...)], listing every category so that zero-count categories still appear; it accepts a list of strings or a StrEnum.

Block 2 uses it for something accuracy cannot show: the distribution of what the model predicted (25% billing, 16.7% technical, 25% account, 8.3% shipping, 16.7% other, 8.3% unparsed), regardless of correctness. Compare it with the label distribution of your dataset and you see bias at a glance: a model that over-predicts billing will show it here before it shows in accuracy. With two epochs (block 2b) the shares are the same because the scripted model is deterministic; with a real model, the unreduced view counts every attempt. 4.7 used frequency() to keep INCORRECT and NOANSWER apart.

6.11 krippendorff_alpha(): agreement between judges#

krippendorff_alpha(level="nominal", to_float=None) measures agreement between several raters (judges, graders, humans) beyond chance, with level "nominal" (labels are categories), "ordinal" (ordered: a 1 vs 3 disagreement is worse than 1 vs 2) or "interval". It needs each sample's score value to be the list of per-rater ratings, which is what multi_scorer([...], "collect") produces. 10A.5, 3.5 taught the statistic and its interpretation bands (about 0.8 and above reliable, 0.667 to 0.8 tentative).

The second half of this script has three scripted judges rate eight ticket summaries from 1 to 3:

python
# s12_headline_alpha.py: headline_metric, and agreement between several judges (lesson 10B.10)
from inspect_ai import Epochs, Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.log import HeadlineMetric
from inspect_ai.scorer import (Score, Target, krippendorff_alpha, mean,
                               multi_scorer, scorer)
from inspect_ai.solver import TaskState, generate, prompt_template

from flaky_triage import make_flaky_model, triage_correct
from triage import PROMPT_TEMPLATE, triage_format, triage_samples


def triage_task(**kwargs) -> Task:
    return Task(dataset=triage_samples(), solver=[prompt_template(PROMPT_TEMPLATE), generate()],
                scorer=[triage_format(), triage_correct()],
                epochs=Epochs(5, ["mean", "pass_k_2"]), **kwargs)


for label, headline in [("default", None),
                        ("scorer name", "triage_correct"),
                        ("full spec", HeadlineMetric(scorer="triage_correct", reducer="pass_k_2",
                                                     metric="accuracy"))]:
    log = eval(triage_task(headline_metric=headline), model=make_flaky_model(),
               log_dir="logs", display="none")[0]
    h = log.results.headline                     # names the number; the value is in results.scores
    value = next(es.metrics[h.metric].value for es in log.results.scores
                 if es.name == h.score and es.reducer == h.reducer)
    print(f"{label:12} -> {h.scorer}/{h.metric} ({h.reducer}) = {value:.3f}")


# Three (scripted) judges rate summary quality 1-3; collect keeps all three ratings.
RATINGS = {  # sample id -> (judge A, judge B, judge C)
    "s1": (3, 3, 3), "s2": (2, 2, 3), "s3": (1, 1, 1), "s4": (3, 2, 3),
    "s5": (2, 2, 2), "s6": (1, 2, 1), "s7": (3, 3, 3), "s8": (1, 1, 2)}


@scorer(metrics=[mean()])
def judge(index: int):
    async def score(state: TaskState, target: Target) -> Score:
        return Score(value=RATINGS[state.sample_id][index])
    return score


log = eval(Task(dataset=[Sample(id=k, input=k) for k in RATINGS],
                scorer=multi_scorer([judge(0), judge(1), judge(2)], "collect"),
                metrics=[krippendorff_alpha(level="ordinal"),
                         krippendorff_alpha(level="nominal")]),
           model="mockllm/model", log_dir="logs", display="none")[0]
print("collected:", {s.id: s.scores["multi_scorer"].value for s in log.samples if s.id in ("s2", "s4")})
print("alpha:", {k: round(v.value, 4) for k, v in log.results.scores[0].metrics.items()})
bash
uv run python s12_headline_alpha.py
Output · real5 lines
default      -> triage_format/accuracy (mean) = 0.917
scorer name  -> triage_correct/accuracy (mean) = 0.733
full spec    -> triage_correct/accuracy (pass_k_2) = 0.633
collected: {'s2': [2, 2, 3], 's4': [3, 2, 3]}
alpha: {'krippendorff_alpha': 0.7585, 'krippendorff_alpha2': 0.5183}

collect kept the three ratings per sample ([2, 2, 3], [3, 2, 3]). Ordinal alpha is 0.76, nominal alpha 0.52: the judges mostly disagree by one step, which the ordinal level treats as a near miss and the nominal level as a full disagreement. Choose the level that matches the scale before you compute it. And evalkit's nominal alpha from 10A.5 gives the same number on the same ratings (python3 s12b_alpha_by_hand.py):

text
evalkit nominal alpha = 0.5183

krippendorff_alpha measures judges against each other. High agreement between three LLM judges can mean three judges sharing one bias; whether any of them agrees with humans is a calibration question, answered with human labels (10A.5, and in Inspect with precomputed_scores() plus 10B.11). 10B.11, 6.4 applies krippendorff_alpha to grader panels.

6.12 Custom metrics and score views#

A custom metric is a factory returning a function of list[SampleScore]:

python
from inspect_ai.scorer import Metric, SampleScore, metric, value_to_float


@metric
def pass_rate(threshold: float = 0.5) -> Metric:
    """Share of samples whose score reaches `threshold` (for partial-credit scorers)."""
    to_float = value_to_float()

    def compute(scores: list[SampleScore]) -> float:
        if not scores:
            return 0.0
        return sum(to_float(s.score.value) >= threshold for s in scores) / len(scores)

    return compute

Three rules make custom metrics correct:

  1. Convert with value_to_float(), never as_float(). The docs' own example uses score.score.as_float(); it works only because the default reducer has already turned "C" into 1.0, and it crashes with ValueError: could not convert string to float: 'C' when reducers are disabled (7.8 reproduces it).
  2. Handle the empty list. Return 0.0 (as the built-ins do) or NaN, but do not divide by zero.
  3. Choose a score view. @metric(scores="auto" | "reduced" | "unreduced") decides what the metric receives: "auto" (the default) gets reduced scores unless reducers are disabled; "reduced" gets one score per sample and requires a reducer; "unreduced" gets one score per sample-epoch, which is what you need to measure anything within a sample across epochs. With several reducers, reduced metrics run once per reducer and unreduced metrics once. 7.9 builds an unreduced flip_rate().

Name the factory @metric(name="...") if the function name is not what you want in the results.

6.13 The headline metric#

Inspect needs one number to show in the viewer's log list, the progress display and the score_headline_* columns of evals_df(). By default it is the first metric of the first score: in the script above, triage_format/accuracy (0.917), because triage_format was listed first. That is rarely the number the team cares about. Nominate it:

  • Task(headline_metric="triage_correct") picks a scorer (its first metric, first reducer);
  • Task(headline_metric=HeadlineMetric(scorer=..., score=..., metric=..., reducer=...)), from inspect_ai.log, picks exactly (reducer names as logged, for example pass_k_2).

The output shows all three: the default chose the format check, naming the scorer chose triage_correct with the mean reducer (0.733), and the full spec chose the reliability number, pass^2 (0.633). log.results.headline records which metric was chosen (a HeadlineMetric, not the value), so the script looks the value up in log.results.scores. An unmatched declaration warns and falls back to the default. Set it on every task whose results someone else reads: the viewer's list is where people form opinions.

6.14 Metric names, collisions and the dataframe columns#

Names are how numbers are found later, and Inspect generates some of them:

Situation Names produced
Two scorers with the same name match, match1, match2
Two interval metrics lower/upper, lower2/upper2
Two aggregate() metrics aggregate, aggregate2
A grouped() all entry that collides with an existing name all2
A dict-valued score one score per key, named by the key
Several reducers one EvalScore per scorer × reducer (same name, different reducer)
Unreduced metrics a separate EvalScore with reducer None
evals_df() columns score_<scorer>_<metric> (e.g. score_triage_format_accuracy), also with a single non-default reducer such as Epochs(5, "pass_k_2"); the reducer is inserted, score_<scorer>_<reducer>_<metric> (e.g. score_triage_correct_pass_k_2_accuracy), only when a scorer has several reducers reporting the same metric; plus score_headline_name, score_headline_score, score_headline_metric, score_headline_value and score_headline_stderr. Select columns by prefix (10B.13, 8.2)

Analysis code that indexes log.results.scores[0].metrics["accuracy"] breaks quietly when someone adds a scorer at the front of the list or a second interval metric. Look results up by (name, reducer, metric), as the reporting scripts in this lesson do, and use the headline metric for the one number that must not move.


Part 7: Epochs and reducers#

7.1 Why run a sample more than once#

A real model given the same prompt twice can answer differently (02.5, Part 7). One run gives one draw per sample, and a sample that is right 3 times in 5 looks exactly like one that is right every time if the single draw happened to succeed. An epoch is one pass over the whole dataset; with n epochs every sample is run n times, each with a fresh TaskState, and scored each time. A reducer then turns a sample's n scores into one value before the metrics run. Epochs answer three different questions, and the reducer is how you pick one:

  • How often is one attempt right? The expected per-attempt success: mean.
  • Can the system do it at all, given several tries? Capability: pass_at_k.
  • Does it work every time? Reliability, the experience of the unlucky user: pass_k_k or at_least_k.

10A.7, 5.1 drew this distinction for agents and 10A.8, 2.2 for CI. Inspect builds it in: the reducer is part of the task definition and part of the log.

flowchart TD
    Q["What question should the number answer?"] --> A{"Per attempt, or per user?"}
    A -->|"How often is one attempt right?"| M["mean<br/>(expected per-attempt success)"]
    A -->|"Can it ever do this, given k tries?"| P["pass_at_k<br/>(capability, best of k)"]
    A -->|"Does it work every time, k times running?"| K["pass_k_k or at_least_k<br/>(reliability, the unlucky user)"]
    A -->|"What would a vote of k attempts say?"| V{"Ties allowed?"}
    V -->|"no: need more than half"| MJ["majority<br/>(ties and failed votes are unscored)"]
    V -->|"yes: most common wins"| MO["mode"]
    A -->|"Keep every value for later"| CO["collect<br/>(e.g. for krippendorff_alpha)"]

7.2 Setting epochs: Task, eval() and the command line#

Where How Notes
On the task Task(epochs=3) Three epochs, default reducer mean
Task(epochs=Epochs(5, "mode")) Epochs(epochs, reducer) from inspect_ai
Task(epochs=Epochs(5, ["mean", "pass_at_2", "pass_k_2"])) Several reducers: one EvalScore per scorer × reducer
In Python eval(task, epochs=5) An int keeps the task's reducers
eval(task, epochs=Epochs(5, "max")) An Epochs replaces them
On the CLI --epochs 5 Keeps the task's reducers
--epochs 5 --epochs-reducer pass_at_2,mean Replaces them (comma-separated)
--epochs 5 --no-epochs-reducer Disables reduction (7.8)
Environment INSPECT_EVAL_EPOCHS, INSPECT_EVAL_EPOCHS_REDUCER, INSPECT_EVAL_NO_EPOCHS_REDUCER The CLI's environment variables

The CLI has a trap the help text does not mention: --epochs-reducer and --no-epochs-reducer do nothing on their own. The installed source builds the override only "if epochs" was given, and says so in a docstring ("--epochs-reducer alone is ignored"). This task file declares five epochs with two reducers and a keyless model on the task (as 10B.8, 4.10 did, so it runs from the CLI without a key):

python
# triage_epochs.py: the triage task with epochs and reducers declared on the Task (lesson 10B.10)
from inspect_ai import Epochs, Task, task
from inspect_ai.solver import generate, prompt_template

from flaky_triage import make_flaky_model, triage_correct
from triage import PROMPT_TEMPLATE, triage_samples


@task
def triage_epochs() -> Task:
    return Task(
        dataset=triage_samples(),
        solver=[prompt_template(PROMPT_TEMPLATE), generate()],
        scorer=triage_correct(),
        epochs=Epochs(5, ["mean", "pass_k_2"]),   # the task's own default
        model=make_flaky_model(),                 # keyless stand-in (a Task model beats --model)
    )

and this script runs it six ways, keeping only the lines that matter from each results panel:

bash
# s15_cli.sh: the epochs flags on the command line (lesson 10B.10)
run() {
  echo "\$ inspect eval triage_epochs.py $*"
  inspect eval triage_epochs.py --log-dir logs-cli --display plain "$@" 2>&1 \
    | grep -E "^(epochs:|triage_correct|accuracy|stderr)" | sed 's/ *$//' | awk '!seen[$0]++'
}
run
run --epochs 3
run --epochs 3 --epochs-reducer at_least_2
run --epochs-reducer at_least_2
run --no-epochs-reducer
run --epochs 5 --no-epochs-reducer
bash
uv run bash s15_cli.sh
Output · real30 lines
$ inspect eval triage_epochs.py 
epochs: 5, epochs_reducer: mean,pass_k_2, dataset: (samples)
triage_correct         triage_correct
accuracy        0.733  accuracy        0.633
stderr          0.102  stderr          0.123
$ inspect eval triage_epochs.py --epochs 3
epochs: 3, epochs_reducer: mean,pass_k_2, dataset: (samples)
triage_correct         triage_correct
accuracy        0.833  accuracy        0.778
stderr          0.096  stderr          0.118
$ inspect eval triage_epochs.py --epochs 3 --epochs-reducer at_least_2
epochs: 3, epochs_reducer: at_least_2, dataset: (samples)
triage_correct
accuracy        0.833
stderr          0.112
$ inspect eval triage_epochs.py --epochs-reducer at_least_2
epochs: 5, epochs_reducer: mean,pass_k_2, dataset: (samples)
triage_correct         triage_correct
accuracy        0.733  accuracy        0.633
stderr          0.102  stderr          0.123
$ inspect eval triage_epochs.py --no-epochs-reducer
epochs: 5, epochs_reducer: mean,pass_k_2, dataset: (samples)
triage_correct         triage_correct
accuracy        0.733  accuracy        0.633
stderr          0.102  stderr          0.123
$ inspect eval triage_epochs.py --epochs 5 --no-epochs-reducer
epochs: 5, epochs_reducer: none, dataset: (samples)
triage_correct
accuracy        0.733
stderr          0.058

Read the six runs in pairs:

  • Default and --epochs 3. The task's reducers (mean,pass_k_2) survive a change in the number of epochs. With three epochs the scripted model only gets to give each ticket its first three answers, so the numbers move (0.733 to 0.833): fewer epochs, different draws.
  • --epochs 3 --epochs-reducer at_least_2. With --epochs, the reducer flag replaces the task's reducers: one result column instead of two.
  • --epochs-reducer at_least_2 alone, and --no-epochs-reducer alone. Ignored, silently: the header still says epochs_reducer: mean,pass_k_2. Always read that header line (or log.eval.config.epochs_reducer) to confirm what ran.
  • --epochs 5 --no-epochs-reducer. Now reduction is off (epochs_reducer: none), and the standard error drops from 0.102 to 0.058. That is not more precision: 7.8 explains why it is wrong.

7.3 The built-in reducers#

Every reducer receives the list of one sample's epoch scores and returns one Score. Built-ins, by the names you pass as strings (and their factory functions in inspect_ai.scorer):

Name Factory Per-sample result Answers
"mean" mean_score(value_to_float=...) Mean of the epoch values; NaN epochs ignored Expected per-attempt success (the default)
"median" median_score() Median A robust central value for numeric scores
"mode" mode_score() Most common value (plurality) What the system usually says
"majority" majority_score() The value held by more than half of all epochs, else NaN (unscored); unscored epochs count in the total; votes recorded in metadata["panel"] A strict vote
"max" max_score() Maximum Best case (for binary scores, "any success")
"at_least_{k}" at_least(k, value=1.0) 1 if at least k epochs reach value, else 0 "Succeeds at least k times"
"pass_at_{k}" pass_at(k, value=1.0) Unbiased pass@k: 1 − C(n−c, k) / C(n, k) Capability with k attempts
"pass_k_{k}" pass_k(k, value=1.0) pass^k: C(c, k) / C(n, k) Reliability over k attempts
"collect" collect_score() The list of all epoch values Keep everything (for krippendorff_alpha, or your own analysis)

In the formulas, n is the number of scored epochs of the sample and c the number that reached value (by default 1.0, so partial credit counts as failure). The built-in reducers keep answer, explanation and reason only when they are identical across epochs, and keep the first epoch's metadata. An epoch whose score was excluded by an operator is removed before reduction; other NaN (unscored) epochs reach the reducer (7.7).

7.4 One run, ten reducers, checked by hand#

To make epochs measurable without a key, the scripted model below is right on a fixed number of each ticket's five attempts (SUCCESSES), using a per-ticket call counter. Inspect runs epochs concurrently, so which attempt comes back right is not fixed, but the set of outcomes per ticket is, and every reducer is order-free, so the numbers are reproducible. It also defines triage_correct, a binary scorer (both labels right) that pass@k needs:

python
# flaky_triage.py: a scripted model that is right on some epochs and wrong on others (lesson 10B.10)
"""A stand-in for a real, non-deterministic model, so epochs have something to measure.

SUCCESSES says how many of 5 attempts at each ticket come back right. The k-th
call for a ticket is right if k < SUCCESSES[ticket], so the SET of outcomes per
ticket is fixed even though Inspect runs epochs concurrently in any order; every
reducer (mean, pass@k, majority...) is order-free, so the numbers are reproducible.
"""
import json
import threading
from collections import Counter

from inspect_ai.model import ChatMessage, GenerateConfig, Model, ModelOutput, get_model
from inspect_ai.scorer import (CORRECT, INCORRECT, Score, Scorer, Target,
                               accuracy, scorer, stderr)
from inspect_ai.solver import TaskState

from triage import TICKETS, parse_json

SUCCESSES = {"T01": 5, "T02": 1, "T03": 5, "T04": 4, "T05": 5, "T06": 3,
             "T07": 5, "T08": 5, "T09": 2, "T10": 5, "T11": 0, "T12": 4}
WRONG = {"P1": "P3", "P2": "P3", "P3": "P2"}          # a plausible wrong priority


def answer(tid: str, right: bool) -> str:
    ref = next(ref for t, _text, ref, _m in TICKETS if t == tid)
    priority, category = ref.split("|")
    if tid == "T11" and not right:                    # T11 keeps its format failure
        return 'Sure! I would mark it P2. Here is the JSON: {"priority": "P2"}'
    return json.dumps({"priority": priority if right else WRONG[priority],
                       "category": category, "summary": "One-line summary."})


def make_flaky_model(successes: dict[str, int] = SUCCESSES, attempts: int = 5) -> Model:
    calls: Counter[str] = Counter()
    lock = threading.Lock()

    def reply(input: list[ChatMessage], tools, tool_choice, config: GenerateConfig) -> ModelOutput:
        prompt = input[-1].text
        tid = next((t for t, text, _r, _m in TICKETS if text and text in prompt), "T10")
        with lock:
            k = calls[tid] % attempts
            calls[tid] += 1
        return ModelOutput.from_content(model="mockllm", content=answer(tid, k < successes[tid]))

    return get_model("mockllm/model", custom_outputs=reply, memoize=False)


@scorer(metrics=[accuracy(), stderr()])
def triage_correct() -> Scorer:
    """Binary: C only if the reply parses and BOTH labels are right (summary ignored)."""
    async def score(state: TaskState, target: Target) -> Score:
        obj = parse_json(state.output.completion)
        if obj is None:
            return Score(value=INCORRECT, answer=state.output.completion,
                         reason="invalid_response_format")
        got = f"{obj.get('priority')}|{obj.get('category')}"
        return Score(value=CORRECT if got == target.text else INCORRECT, answer=got)
    return score

Now one task with ten reducers:

python
# s10_epochs_reducers.py: one run, five epochs, every built-in reducer (lesson 10B.10)
from inspect_ai import Epochs, Task, eval
from inspect_ai.solver import generate, prompt_template

from flaky_triage import make_flaky_model, triage_correct
from triage import PROMPT_TEMPLATE, triage_samples

REDUCERS = ["mean", "median", "mode", "majority", "max",
            "at_least_3", "pass_at_2", "pass_at_5", "pass_k_2", "pass_k_5"]

task = Task(dataset=triage_samples(),
            solver=[prompt_template(PROMPT_TEMPLATE), generate()],
            scorer=triage_correct(),
            epochs=Epochs(5, REDUCERS))
log = eval(task, model=make_flaky_model(), log_dir="logs", display="none")[0]

print("config:", log.eval.config.epochs, "epochs | reducers:", log.eval.config.epochs_reducer)
print("samples in log:", len(log.samples), "(12 tickets x 5 epochs)")
for es in log.results.scores:
    m = {k: round(v.value, 4) for k, v in es.metrics.items()}
    print(f"  {es.reducer:11} scored={es.scored_samples}  {m}")

# per-sample view: the epoch verdicts and what three reducers made of them
by_id: dict[str, list[str]] = {}
for s in log.samples:
    by_id.setdefault(s.id, []).append(s.scores["triage_correct"].value)
red = {r.reducer: {x.sample_id: x.value for x in r.samples} for r in log.reductions}
for tid in sorted(by_id):
    v = sorted(by_id[tid])
    print(f"  {tid} epochs={''.join(v)} c={v.count('C')}  mean={red['mean'][tid]:.1f}"
          f"  pass_at_2={red['pass_at_2'][tid]:.2f}  pass_k_2={red['pass_k_2'][tid]:.2f}")
bash
uv run python s10_epochs_reducers.py
Output · real24 lines
config: 5 epochs | reducers: ['mean', 'median', 'mode', 'majority', 'max', 'at_least_3', 'pass_at_2', 'pass_at_5', 'pass_k_2', 'pass_k_5']
samples in log: 60 (12 tickets x 5 epochs)
  mean        scored=12  {'accuracy': 0.7333, 'stderr': 0.1025}
  median      scored=12  {'accuracy': 0.75, 'stderr': 0.1306}
  mode        scored=12  {'accuracy': 0.75, 'stderr': 0.1306}
  majority    scored=12  {'accuracy': 0.75, 'stderr': 0.1306}
  max         scored=12  {'accuracy': 0.9167, 'stderr': 0.0833}
  at_least_3  scored=12  {'accuracy': 0.75, 'stderr': 0.1306}
  pass_at_2   scored=12  {'accuracy': 0.8333, 'stderr': 0.0924}
  pass_at_5   scored=12  {'accuracy': 0.9167, 'stderr': 0.0833}
  pass_k_2    scored=12  {'accuracy': 0.6333, 'stderr': 0.1233}
  pass_k_5    scored=12  {'accuracy': 0.5, 'stderr': 0.1508}
  T01 epochs=CCCCC c=5  mean=1.0  pass_at_2=1.00  pass_k_2=1.00
  T02 epochs=CIIII c=1  mean=0.2  pass_at_2=0.40  pass_k_2=0.00
  T03 epochs=CCCCC c=5  mean=1.0  pass_at_2=1.00  pass_k_2=1.00
  T04 epochs=CCCCI c=4  mean=0.8  pass_at_2=1.00  pass_k_2=0.60
  T05 epochs=CCCCC c=5  mean=1.0  pass_at_2=1.00  pass_k_2=1.00
  T06 epochs=CCCII c=3  mean=0.6  pass_at_2=0.90  pass_k_2=0.30
  T07 epochs=CCCCC c=5  mean=1.0  pass_at_2=1.00  pass_k_2=1.00
  T08 epochs=CCCCC c=5  mean=1.0  pass_at_2=1.00  pass_k_2=1.00
  T09 epochs=CCIII c=2  mean=0.4  pass_at_2=0.70  pass_k_2=0.10
  T10 epochs=CCCCC c=5  mean=1.0  pass_at_2=1.00  pass_k_2=1.00
  T11 epochs=IIIII c=0  mean=0.0  pass_at_2=0.00  pass_k_2=0.00
  T12 epochs=CCCCI c=4  mean=0.8  pass_at_2=1.00  pass_k_2=0.60

Sixty sample-epochs, twelve reduced values per reducer, ten different headline numbers from the same sixty verdicts, from 0.50 to 0.917. Every one is right; they answer different questions:

Reducer Value Says
max, pass_at_5 0.917 11 of 12 tickets are solved at least once in five tries (only T11 never is)
pass_at_2 0.833 With two tries, the chance of at least one success, averaged over tickets
median, mode, majority, at_least_3 0.75 9 tickets succeed in at least 3 of 5 attempts
mean 0.733 One attempt succeeds 73% of the time (44 of 60)
pass_k_2 0.633 The chance that two attempts in a row both succeed
pass_k_5 0.50 Only 6 tickets succeed every time

The standard-library recomputation, using the same pass_at_k and pass_hat_k formulas as 10A.7's agent_eval.py (simplified: 10A.7's versions return None when n < k or n <= 0; that guard is omitted here because every ticket has n = 5) (python3 s10b_by_hand.py):

python
# s10b_by_hand.py: s10's reducer numbers from 10A.7's estimators, standard library only (lesson 10B.10)
import math
import statistics

SUCCESSES = {"T01": 5, "T02": 1, "T03": 5, "T04": 4, "T05": 5, "T06": 3,
             "T07": 5, "T08": 5, "T09": 2, "T10": 5, "T11": 0, "T12": 4}
N = 5                                                   # epochs per ticket


def pass_at_k(n: int, c: int, k: int) -> float:         # 10A.7's formula, without its n < k guard
    if c <= 0:
        return 0.0
    if n - c < k:
        return 1.0
    return 1.0 - math.comb(n - c, k) / math.comb(n, k)


def pass_hat_k(n: int, c: int, k: int) -> float:        # 10A.7's formula (pass^k), without its n < k guard
    return 0.0 if c < k else math.comb(c, k) / math.comb(n, k)


per_ticket = {
    "mean": [c / N for c in SUCCESSES.values()],
    "majority": [1.0 if c > N / 2 else 0.0 for c in SUCCESSES.values()],
    "max": [1.0 if c > 0 else 0.0 for c in SUCCESSES.values()],
    "pass_at_2": [pass_at_k(N, c, 2) for c in SUCCESSES.values()],
    "pass_k_2": [pass_hat_k(N, c, 2) for c in SUCCESSES.values()],
    "pass_k_5": [pass_hat_k(N, c, 5) for c in SUCCESSES.values()],
}
for name, values in per_ticket.items():
    se = statistics.stdev(values) / math.sqrt(len(values))
    print(f"{name:9} accuracy={statistics.fmean(values):.4f}  stderr={se:.4f}")
Output · real6 lines
mean      accuracy=0.7333  stderr=0.1025
majority  accuracy=0.7500  stderr=0.1306
max       accuracy=0.9167  stderr=0.0833
pass_at_2 accuracy=0.8333  stderr=0.0924
pass_k_2  accuracy=0.6333  stderr=0.1233
pass_k_5  accuracy=0.5000  stderr=0.1508

Every value and every standard error matches Inspect's. Inspect's pass_at and pass_k are the same estimators as evalkit's, applied per sample and then averaged.

7.5 pass@k and pass^k, exactly#

Per ticket, with n scored attempts of which c succeeded:

  • pass@k (pass_at_{k}) = 1 − C(n−c, k) / C(n, k): the probability that a random draw of k of the n attempts contains at least one success. It is the unbiased estimator from the Codex paper, Chen et al. 2021. It is 1.0 whenever n − c < k (you cannot draw k failures), so T04 (4 of 5) scores 1.0 at k = 2, and in 7.7 a sample right once in four attempts scores 1.0 at k = 4.
  • pass^k (pass_k_{k}) = C(c, k) / C(n, k): the probability that all k drawn attempts succeeded, from the τ-bench paper. T04 scores 6/10 = 0.6 at k = 2.
  • at_least_{k} is a threshold, not an estimator: 1 if c ≥ k. With k = n it equals pass^n.

Rules Inspect enforces: asking for pass_at_5 or pass_k_5 with fewer than five epochs is refused before the run starts (PrerequisiteError: Reducer 'pass_at_5' requires 5 epochs however evaluation has only 4 epochs, reproduced in 7.7). If a sample ends up with fewer than k scored epochs (some were unscored), its pass@k is NaN and it becomes unscored. And the estimators need n ≥ k with room to spare: pass@k with k = n is just "any success", and its variance across reruns is high. 10A.7, 5.4 recommends 4 to 8 trials for development and 8 to 16 before gating on pass^k.

7.6 majority versus mode, and ties#

mode returns the most common value, breaking ties by taking one of them; majority requires strictly more than half of all epochs, counting unscored epochs in the total, and returns NaN (unscored) otherwise. With an even number of epochs, a 2-2 split is a tie: mode picks a side, majority declines. The next script's output shows it on sample b (CCII): mode gave C, majority gave nan.

Which to use is a policy decision. majority is honest about ambiguity and shrinks the denominator when votes split (report unscored_samples); mode always gives an answer and hides the split. For self-consistency style evals (sample several answers, take the most common) mode is the conventional choice; for a gate that should not count a coin-flip as a pass, majority with an odd number of epochs. The same reducers combine grader panels in model grading, where a tie under majority is unscored since 0.3.262 (10B.11).

7.7 Unscored epochs and custom reducers#

When a scorer returns Score.unscored() on some epochs (a grader that failed once), the reducer sees NaN values. The built-in mean ignores them; other reducers treat them according to their own rule; a custom reducer must handle them or it will propagate them. This script gives five samples fixed verdict schedules over four epochs (U is an unscored epoch) and runs seven reducers, plus an unreduced metric and two failure cases:

python
# s11_reducer_edges.py: ties, too-few epochs, unscored epochs, custom reducers and metric views (lesson 10B.10)
import math

from inspect_ai import Epochs, Task, eval
from inspect_ai.dataset import Sample
from inspect_ai.scorer import (CORRECT, INCORRECT, Metric, SampleScore, Score,
                               ScoreReducer, Target, accuracy, metric, scorer,
                               score_reducer, value_to_float)
from inspect_ai.solver import TaskState

# Verdict schedules per sample, one letter per epoch; "U" means the grader failed (unscored).
SCHEDULE = {"a": "CCCC", "b": "CCII", "c": "CIII", "d": "UICC", "e": "UUUU"}
SEEN: dict[str, int] = {}


@scorer(metrics=[accuracy()])
def scheduled():
    async def score(state: TaskState, target: Target) -> Score:
        k = SEEN.get(state.sample_id, 0)
        SEEN[state.sample_id] = k + 1
        v = SCHEDULE[state.sample_id][k % 4]
        if v == "U":
            return Score.unscored(reason="grader_failed")
        return Score(value=v)
    return score


@score_reducer(name="worst_naive")
def worst_naive() -> ScoreReducer:
    to_float = value_to_float()
    def reduce(scores: list[Score]) -> Score:
        return Score(value=min(to_float(s.value) for s in scores))   # NaN slips through
    return reduce


@score_reducer(name="worst")
def worst() -> ScoreReducer:
    to_float = value_to_float()
    def reduce(scores: list[Score]) -> Score:
        values = [v for v in (to_float(s.value) for s in scores) if not math.isnan(v)]
        if not values:
            return Score.unscored(reason="scoring_failed")
        return Score(value=min(values))
    return reduce


@metric(scores="unreduced")
def flip_rate() -> Metric:
    """Share of samples whose scored epochs did not all agree (sees every sample-epoch)."""
    to_float = value_to_float()
    def compute(scores: list[SampleScore]) -> float:
        by_sample: dict = {}
        for s in scores:
            v = to_float(s.score.value)
            if not math.isnan(v):
                by_sample.setdefault(s.sample_id, set()).add(v)
        return sum(len(v) > 1 for v in by_sample.values()) / len(by_sample) if by_sample else 0.0
    return compute


def run(epochs, metrics=None):
    SEEN.clear()
    task = Task(dataset=[Sample(id=k, input=k) for k in SCHEDULE], scorer=scheduled(),
                epochs=epochs, metrics=metrics)
    return eval(task, model="mockllm/model", log_dir="logs", display="none")[0]


log = run(Epochs(4, ["mean", "majority", "mode", "pass_at_2", "pass_at_4",
                     worst_naive(), worst()]), metrics=[accuracy(), flip_rate()])
print("4 epochs; schedules:", SCHEDULE)
for es in log.results.scores:
    print(f"  {str(es.reducer):11} scored={es.scored_samples} unscored={es.unscored_samples} "
          f"{ {k: round(v.value, 3) for k, v in es.metrics.items()} }")
for r in log.reductions:
    if r.reducer in ("majority", "mode", "worst_naive", "worst"):
        print(f"  {r.reducer:11} per sample:",
              {x.sample_id: (round(x.value, 2) if isinstance(x.value, float) else x.value)
               for x in r.samples})


# Asking for pass@5 from 4 epochs is refused before anything runs.
try:
    run(Epochs(4, "pass_at_5"))
except Exception as e:
    print("pass_at_5 with 4 epochs ->", type(e).__name__ + ":", str(e).strip())


# A metric written the way the docs' example writes it: Score.as_float().
@metric
def mean_as_float() -> Metric:
    def compute(scores: list[SampleScore]) -> float:
        return sum(s.score.as_float() for s in scores) / len(scores)
    return compute


for label, ep in [("default reducer", 2), ("reducers disabled", Epochs(2, []))]:
    log = run(ep, metrics=[mean_as_float()])
    print(f"as_float metric, {label}: status={log.status}",
          log.error.message.splitlines()[-1][:90] if log.error else
          {k: round(v.value, 3) for k, v in log.results.scores[0].metrics.items()})
bash
uv run python s11_reducer_edges.py
Output · real16 lines
4 epochs; schedules: {'a': 'CCCC', 'b': 'CCII', 'c': 'CIII', 'd': 'UICC', 'e': 'UUUU'}
  mean        scored=4 unscored=1 {'accuracy': 0.604}
  majority    scored=2 unscored=3 {'accuracy': 0.5}
  mode        scored=4 unscored=1 {'accuracy': 0.75}
  pass_at_2   scored=4 unscored=1 {'accuracy': 0.833}
  pass_at_4   scored=3 unscored=2 {'accuracy': 1.0}
  worst_naive scored=3 unscored=2 {'accuracy': 0.333}
  worst       scored=4 unscored=1 {'accuracy': 0.25}
  None        scored=15 unscored=5 {'flip_rate': 0.75}
  majority    per sample: {'a': 'C', 'b': nan, 'c': 'I', 'd': nan, 'e': nan}
  mode        per sample: {'a': 'C', 'b': 'C', 'c': 'I', 'd': 'C', 'e': nan}
  worst_naive per sample: {'a': 1.0, 'b': 0.0, 'c': 0.0, 'd': nan, 'e': nan}
  worst       per sample: {'a': 1.0, 'b': 0.0, 'c': 0.0, 'd': 0.0, 'e': nan}
pass_at_5 with 4 epochs -> PrerequisiteError: Reducer 'pass_at_5' requires 5 epochs however evaluation has only 4 epochs.
as_float metric, default reducer: status=success {'mean_as_float': 0.625}
as_float metric, reducers disabled: status=error ValueError("could not convert string to float: 'C'")

Check each reducer against the schedules (a CCCC, b CCII, c CIII, d UICC, e UUUU):

  • mean: d is mean of its three scored epochs, 2/3; e has none and is unscored. (1 + 0.5 + 0.25 + 0.667) / 4 = 0.604.
  • majority: b is a 2-2 tie and d has two C out of four epochs (the unscored epoch counts in the total), so both are nan; only a and c are scored, and the denominator fell to 2.
  • mode: decides b (as C) and d (as C), scored 4.
  • pass_at_2: d has 3 scored epochs with 2 successes, so n − c = 1 < 2 and it scores 1.0.
  • pass_at_4: d has fewer than 4 scored epochs and is unscored; c, right once in four, scores 1.0 (any 4 of 4 contain the success).
  • worst_naive: Python's min() with a NaN first returns NaN, so d became unscored and the reducer reported 0.333 over 3 samples, higher than the true worst-case 0.25, because the sample it lost was a failure.
  • worst: the same reducer with a NaN guard: d reduces to 0.0 and the number is 0.25 over 4.

The custom reducer pattern, with the guard:

python
import math

from inspect_ai.scorer import Score, ScoreReducer, score_reducer, value_to_float


@score_reducer(name="worst")
def worst() -> ScoreReducer:
    """The minimum over scored epochs; unscored if no epoch was scored."""
    to_float = value_to_float()

    def reduce(scores: list[Score]) -> Score:
        values = [v for v in (to_float(s.value) for s in scores) if not math.isnan(v)]
        if not values:
            return Score.unscored(reason="scoring_failed")
        return Score(value=min(values))

    return reduce

score_reducer(func=None, *, name=None) registers it; pass the factory call (worst()) wherever a reducer name is accepted (Epochs(5, worst()), multi_scorer([...], worst())). Return a Score, convert with value_to_float(), decide explicitly what an all-unscored sample becomes, and carry over answer or metadata if your analysis needs them (the built-ins keep the first epoch's metadata).

7.8 Turning reducers off#

Epochs(n, []) in Python, or --epochs n --no-epochs-reducer on the CLI, disables reduction. Metrics then receive every sample-epoch as if each were an independent sample. Two consequences, both reproduced above:

  1. The standard error is computed over n × epochs values. In 7.2 the same 44 successes out of 60 gave a standard error of 0.058 instead of 0.102. The five attempts at one ticket are not five independent tickets (they share the ticket's difficulty), so the smaller number overstates the precision, exactly the clustering problem of 6.5 with the sample as the cluster.
  2. Metrics receive raw values. The last two lines of 7.7's output show a custom metric written with as_float(), as the docs' example writes it: it works with the default reducer (0.625) and fails the whole run with reducers disabled (status=error, ValueError("could not convert string to float: 'C'")).

There are good reasons to see unreduced scores (per-attempt distributions, flip rates), and the right tool for them is an unreduced metric, not switching reduction off for the whole task.

7.9 Unreduced metrics: seeing every epoch#

A metric declared with @metric(scores="unreduced") receives every sample-epoch score, with sample_id to tell them apart, while the task's other metrics still see reduced scores. 7.7's flip_rate() uses it to measure instability: the share of samples whose scored epochs did not all agree. It reported 0.75 (samples b, c and d flipped; a did not; e had no scored epoch), as a separate EvalScore with reducer None and scored=15 unscored=5 (sample-epochs, not samples).

A flip rate is one of the most useful numbers an eval with epochs can give you, and Inspect does not compute it by default. A model at 0.80 accuracy with a 5% flip rate is predictable: the same tickets fail every time, so you can find them and fix them. A model at 0.80 with a 40% flip rate fails different tickets on different days, which users experience as unreliability and which no prompt fix aimed at "the failing tickets" will cure.

7.10 What epochs do to the uncertainty#

The reported stderr is computed over reduced per-sample values, so adding epochs does not increase n. Is that right, and what do epochs buy? A standard-library simulation of the scripted model's true success rates answers both (python3 s14_epochs_sim.py):

python
# s14_epochs_sim.py: what epochs do (and do not do) to the uncertainty, simulated (lesson 10B.10)
# Standard library only. Each ticket has a true success rate; a "run" draws `epochs`
# attempts per ticket, reduces them with the mean (as Inspect does), and reports
# accuracy and Inspect's stderr over the 12 reduced values.
import math
import random
import statistics

TRUE_RATE = [1.0, 0.2, 1.0, 0.8, 1.0, 0.6, 1.0, 1.0, 0.4, 1.0, 0.0, 0.8]   # flaky_triage.py / 5
rng = random.Random(7)


def one_run(epochs: int) -> tuple[float, float]:
    reduced = [sum(rng.random() < p for _ in range(epochs)) / epochs for p in TRUE_RATE]
    return statistics.fmean(reduced), statistics.stdev(reduced) / math.sqrt(len(reduced))


print(f"true accuracy of this model on these 12 tickets: {statistics.fmean(TRUE_RATE):.3f}")
for epochs in (1, 5, 20, 100):
    runs = [one_run(epochs) for _ in range(2000)]
    acc = [a for a, _ in runs]
    print(f"epochs={epochs:>3}: rerun-to-rerun SD of accuracy {statistics.stdev(acc):.3f}"
          f" | average reported stderr {statistics.fmean(se for _, se in runs):.3f}")
Output · real5 lines
true accuracy of this model on these 12 tickets: 0.733
epochs=  1: rerun-to-rerun SD of accuracy 0.081 | average reported stderr 0.131
epochs=  5: rerun-to-rerun SD of accuracy 0.037 | average reported stderr 0.108
epochs= 20: rerun-to-rerun SD of accuracy 0.018 | average reported stderr 0.104
epochs=100: rerun-to-rerun SD of accuracy 0.008 | average reported stderr 0.103

Two different uncertainties, and epochs touch only one of them:

  • Rerun noise (how much the number moves if you run the same twelve tickets again) shrinks with the square root of the number of epochs: 0.081 with one epoch, 0.037 with five, 0.008 with a hundred. Epochs make a measurement repeatable.
  • Sampling uncertainty (how much the number would move with a different twelve tickets from the same kind of traffic) does not shrink at all: the reported standard error levels off at about 0.10, because it measures how different tickets are from each other, and only more tickets change that. Epochs do not make a measurement general.

The reported stderr is (approximately) the second kind plus a fading share of the first, which is the right quantity for the question "how good is this model on traffic like this?". So Inspect's choice of n is correct, and the practical rule follows: spend on epochs until rerun noise is small compared with the standard error (here, 3 to 5 epochs), then spend on more samples. 10A.7, 5.4 reached the same rule for agents ("more tasks beats more trials").

7.11 Epochs, caching and determinism#

Three interactions to check before you trust an epoch-based number:

  • Caching. Inspect's response cache keys on the epoch by default (CachePolicy(per_epoch=True)), so epoch 2 is a new model call, not a replay of epoch 1. A cache policy with per_epoch=False replays a cached answer into most epochs (concurrent epochs that start before it is written still call the model: 10B.12, 6.4 measured 20 calls instead of 12), so the epoch spread is meaningless; it is the "warm cache" trap of 10A.8, 2.2. 10B.12 covers caching.
  • Deterministic settings. Temperature 0 (where a provider still accepts it, 02.5) or a deterministic mock makes epochs repeat the same answer: they cost time and measure nothing (10B.8, Exercise 4). Epochs measure the variance of the system as configured for production; configure the eval the same way.
  • Model graders are another source of variance. With a model-graded scorer, each epoch also re-grades, so the epoch spread mixes the model's variance with the grader's. If you need them apart, re-score one fixed set of outputs several times (10B.11).

7.12 How many epochs, how many samples#

Goal Epochs Reducer(s) Samples
A cheap regression gate on a stable model 1 (default mean) As many as the budget allows
Measuring per-attempt quality of a non-deterministic model 3 to 5 mean More samples first; see 8.7
Capability ("can it solve these at all?") k or more pass_at_{k} Hard tasks, many of them
Reliability before release (agents, customer-facing automation) 8 to 16 pass_k_{k} or at_least_{k}, plus mean Enough tasks that each fails sometimes
Self-consistency / voting odd number mode or majority
Measuring instability 3 or more mean plus an unreduced flip-rate metric

Whatever you choose, log it (Inspect does), name the reducer next to the number, and keep the same epochs and reducers for runs you intend to compare.


Part 8: The statistics Inspect reports, and the ones it does not#

Deep-dive

8.1 What the default numbers mean, exactly#

With no metrics declared beyond the built-in scorers' defaults, an Inspect result is, per scorer and per reducer:

  • the mean (accuracy or mean) of the reduced per-sample values, over the scored samples only;
  • the CLT standard error of that mean, std(ddof=1) / sqrt(n), with n the number of scored samples, assuming samples are independent;
  • the coverage counts scored_samples and unscored_samples (and, in the results header, the completed and total sample-epochs).

No interval, no cluster adjustment, no comparison with any other run. Everything else is opt-in: intervals with ci_wilson() or ci(), clustering with cluster=, slices with grouped(), reliability with reducers, agreement with krippendorff_alpha(). Part 6 and Part 7 covered those. This part covers what is not there at all.

8.2 What Inspect does not do#

Question Inspect 0.3.292 Where the answer lives
Is run B better than run A on the same samples? No paired comparison (no paired bootstrap, permutation test or McNemar test) evalkit/compare.py, 10A.8, 2.3, on per-sample data from the logs (8.3)
Same, when samples come in groups No evalkit/cluster.py, 10A.8, 2.7 (8.5)
I compared 12 slices and 3 models: which differences are real? No multiple-comparison correction 10A.8, 2.6 (8.6)
How many samples do I need to see a 5-point change? No power or minimum-detectable-effect calculation min_detectable_effect(), 10A.8, 2.4 (8.7)
Does my grader agree with humans? krippendorff_alpha measures agreement between judges; no calibration against human labels 10A.5, and 10B.11 for the Inspect workflow
Should this run block the release? No gate; inspect eval exits 0 even when the run failed A gate over the log (8.8, 10B.8, 9.6)
Did the system get flakier? No flip-rate or variance tracking across runs An unreduced metric (7.9) and your experiment tracking (10A.8, Part 7)

None of this is a criticism of Inspect: a log is a record of one run, and comparisons are between runs. The good news is that the logs hold exactly the per-sample data these methods need, and the evalkit code from 10A.8 runs on it unchanged.

flowchart LR
    L1["Log A<br/>(baseline)"] --> X["Check: both success,<br/>same task version,<br/>full coverage"]
    L2["Log B<br/>(candidate)"] --> X
    X --> J["Per-sample reduced values<br/>(log.reductions or samples_df)<br/>joined on sample id"]
    J --> D["Paired differences B - A"]
    D --> S["evalkit compare.py:<br/>paired bootstrap CI,<br/>sign-flip p, effect size, MDE"]
    D --> C["evalkit cluster.py:<br/>paired cluster bootstrap<br/>when samples share a source"]
    S --> G["Gate decision<br/>(10A.8 evaluate_gate)"]
    C --> G

8.3 Comparing two runs, paired#

The scenario: prompt v2 against prompt v1 on the triage eval, five epochs each (two scripted models stand in for the two prompts: v2 fixes three tickets more often and breaks one). The panels will say 0.733 and 0.817. Is v2 better?

python
# s13_compare_runs.py: is prompt v2 better than v1? Paired statistics on two Inspect logs (lesson 10B.10)
import math
import statistics

from inspect_ai import Epochs, Task, eval
from inspect_ai.log import EvalLog
from inspect_ai.solver import generate, prompt_template

from evalkit.compare import (min_detectable_effect, paired_bootstrap_ci, paired_diffs,
                             paired_effect_size, sign_flip_permutation_p)
from flaky_triage import SUCCESSES, make_flaky_model, triage_correct
from triage import PROMPT_TEMPLATE, triage_samples

# v2 (a new prompt, say) fixes three tickets more often and breaks one.
V2 = dict(SUCCESSES, T02=4, T06=4, T09=5, T04=2)


def run(successes: dict[str, int], log_dir: str) -> EvalLog:
    task = Task(dataset=triage_samples(), solver=[prompt_template(PROMPT_TEMPLATE), generate()],
                scorer=triage_correct(), epochs=Epochs(5, "mean"), version=1)
    return eval(task, model=make_flaky_model(successes), log_dir=log_dir, display="none")[0]


def per_sample(log: EvalLog) -> dict[str, float]:
    """The reduced value each sample contributed to the metric (mean over its 5 epochs)."""
    assert log.status == "success"
    reduction = next(r for r in log.reductions if r.scorer == "triage_correct")
    return {str(x.sample_id): x.value for x in reduction.samples}


v1, v2 = run(SUCCESSES, "logs-v1"), run(V2, "logs-v2")
assert v1.eval.task_version == v2.eval.task_version        # never compare across versions
a, b = per_sample(v1), per_sample(v2)

# What Inspect prints: two accuracies, each with its own stderr.
for name, log in (("v1", v1), ("v2", v2)):
    m = log.results.scores[0].metrics
    print(f"{name}: accuracy {m['accuracy'].value:.3f}  stderr {m['stderr'].value:.3f}")

# What the decision needs: the paired difference, with evalkit's 10A.8 tools.
diffs = paired_diffs(a, b)
mean, lo, hi = paired_bootstrap_ci(diffs)
print(f"paired diff v2-v1: {mean:+.3f}  95% CI [{lo:+.3f}, {hi:+.3f}]  over {len(diffs)} tickets")
print(f"sign-flip p = {sign_flip_permutation_p(diffs):.3f}   effect size d = {paired_effect_size(diffs):.2f}")
print("non-zero differences:", {k: round(b[k] - a[k], 1) for k in sorted(a) if b[k] != a[k]})

# Naive unpaired view, for contrast: SE of a difference of two independent means.
se_unpaired = math.sqrt(statistics.variance(a.values()) / len(a) + statistics.variance(b.values()) / len(b))
se_paired = statistics.stdev(diffs) / math.sqrt(len(diffs))
print(f"stderr of the difference: unpaired {se_unpaired:.3f} vs paired {se_paired:.3f}")

# Before the next run: what could 12 tickets detect at all?
sd = statistics.stdev(diffs)
for n in (12, 50, 200):
    print(f"MDE with n={n:>3} paired tickets (sd of diffs {sd:.2f}): {min_detectable_effect(n, sd):.3f}")
bash
uv run python s13_compare_runs.py
Output · real9 lines
v1: accuracy 0.733  stderr 0.102
v2: accuracy 0.817  stderr 0.090
paired diff v2-v1: +0.083  95% CI [-0.050, +0.233]  over 12 tickets
sign-flip p = 0.377   effect size d = 0.30
non-zero differences: {'T02': 0.6, 'T04': -0.4, 'T06': 0.2, 'T09': 0.6}
stderr of the difference: unpaired 0.137 vs paired 0.080
MDE with n= 12 paired tickets (sd of diffs 0.28): 0.223
MDE with n= 50 paired tickets (sd of diffs 0.28): 0.109
MDE with n=200 paired tickets (sd of diffs 0.28): 0.055

Read it in the order a reviewer should:

  1. Preconditions. Both runs succeeded (per_sample asserts it), and both have the same task version (the script asserts it). Comparing across task versions compares different measurements (10B.8, 4.5).
  2. The pairs. per_sample() reads log.reductions, the exact values the metric used, keyed by sample id; paired_diffs() keeps only tickets both runs scored. Joining on the dataset id (never on position: log.samples is ordered by epoch then id, not dataset order) is what makes the comparison paired.
  3. The estimate. v2 − v1 = +0.083, with a 95% paired bootstrap interval of [−0.050, +0.233]. The interval includes zero: at this sample size, you cannot tell whether v2 is better. The sign-flip permutation p-value (0.38) and the effect size (0.30, small) say the same.
  4. Where the difference comes from. Four tickets changed: three improved, T04 got worse. That is the error-analysis view; a release decision should look at T04 before anything else.
  5. Why pairing matters. The standard error of the difference is 0.137 if you treat the runs as independent (what you would get from two results panels) and 0.080 paired, because each ticket's difficulty cancels out. Pairing is free precision; never compare two Inspect panels by eye.

8.4 The same comparison from samples_df()#

For larger analyses (many runs, many models), read the logs into a dataframe (10B.13 teaches the dataframes in depth). samples_df() needs pandas and pyarrow (uv add pandas pyarrow), returns one row per sample per epoch, and keeps raw score values ("C"/"I"), so you reduce epochs yourself:

python
# s13b_samples_df.py: the same paired data from samples_df() (needs pandas and pyarrow) (lesson 10B.10)
from inspect_ai.analysis import samples_df
from inspect_ai.log import list_eval_logs

from evalkit.compare import paired_bootstrap_ci

frames = {}
for run in ("v1", "v2"):
    newest = list_eval_logs(f"logs-{run}")[0]          # newest first
    df = samples_df(newest, quiet=True)                 # one row per sample PER EPOCH
    df["correct"] = (df["score_triage_correct"] == "C").astype(float)
    frames[run] = df
print("rows per log:", len(frames["v1"]), "| columns used:", ["id", "epoch", "score_triage_correct"])

# Reduce epochs yourself (here: the mean, matching the task's reducer), then pair on the dataset id.
per_id = {run: df.groupby("id")["correct"].mean() for run, df in frames.items()}
joined = per_id["v1"].to_frame("v1").join(per_id["v2"].to_frame("v2"), how="inner")
joined["diff"] = joined["v2"] - joined["v1"]
print(joined[joined["diff"] != 0])
mean, lo, hi = paired_bootstrap_ci(joined["diff"].tolist())
print(f"paired diff {mean:+.3f}  95% CI [{lo:+.3f}, {hi:+.3f}]")
bash
uv run python s13b_samples_df.py
Output · real8 lines
rows per log: 60 | columns used: ['id', 'epoch', 'score_triage_correct']
      v1   v2  diff
id                 
T02  0.2  0.8   0.6
T04  0.8  0.4  -0.4
T06  0.6  0.8   0.2
T09  0.4  1.0   0.6
paired diff +0.083  95% CI [-0.050, +0.233]

The same four changed tickets and the same interval. Two details that bite: the dataset id is the id column (sample_id is a generated unique id, different in every log, useless for joining), and the reduction is yours to get right (here the mean, to match the task's reducer; with pass_k_2 you would compute pass^2 per ticket).

8.5 Grouped samples: the paired cluster bootstrap#

If samples share a source, the paired comparison has the same independence problem as the standard error (6.5): tickets from one customer tend to improve or regress together. 10A.8, 2.7's paired_cluster_bootstrap_ci resamples whole groups of differences. Fed from the same two logs, grouping tickets by the six customer accounts the worked example in Part 9 assigns:

python
# s13c_cluster_compare.py: the v1/v2 comparison again, resampling customers instead of tickets (lesson 10B.10)
from inspect_ai.log import list_eval_logs, read_eval_log

from evalkit.cluster import paired_cluster_bootstrap_ci
from evalkit.compare import paired_bootstrap_ci
from triage_scored import CUSTOMER          # ticket id -> customer account (6 accounts)


def reduced(log_dir: str) -> dict[str, float]:
    log = read_eval_log(list_eval_logs(log_dir)[0], header_only=True)   # reductions come with the header
    red = next(r for r in log.reductions if r.scorer == "triage_correct")
    return {str(x.sample_id): x.value for x in red.samples}


a, b = reduced("logs-v1"), reduced("logs-v2")
diffs = {tid: b[tid] - a[tid] for tid in sorted(a.keys() & b.keys())}

by_customer: dict[str, list[float]] = {}
for tid, d in diffs.items():
    by_customer.setdefault(CUSTOMER[tid], []).append(d)

m, lo, hi = paired_bootstrap_ci(list(diffs.values()))
print(f"per-ticket bootstrap  : {m:+.3f}  CI [{lo:+.3f}, {hi:+.3f}]  ({len(diffs)} tickets)")
m, lo, hi = paired_cluster_bootstrap_ci(by_customer)
print(f"per-customer bootstrap: {m:+.3f}  CI [{lo:+.3f}, {hi:+.3f}]  ({len(by_customer)} customers)")
bash
uv run python s13c_cluster_compare.py
Output · real2 lines
per-ticket bootstrap  : +0.083  CI [-0.050, +0.233]  (12 tickets)
per-customer bootstrap: +0.083  CI [-0.083, +0.317]  (6 customers)

The interval widens from [−0.050, +0.233] to [−0.083, +0.317]: six customers are six observations. Note also that a header-only read (header_only=True) includes the reductions for .eval logs, so a comparison like this never needs to load the samples (10B.8, 7.2).

8.6 Many slices, many comparisons#

grouped() makes it easy to print a number per intent, per language, per customer tier, for every model you try. Each additional comparison is another chance for noise to look like a finding: at a 5% false-positive rate, one slice in twenty will "differ" by chance. 10A.8, 2.6 gave the rules, and they apply to Inspect output unchanged:

  • Decide the slices that gate before you run (three to five that matter), and treat the rest as exploration.
  • Widen intervals when you scan many slices (Bonferroni: for k comparisons, use a 1 − 0.05/k confidence level; ci_wilson(level=0.99) for five slices).
  • Label small-slice differences "needs more data", never "regression", and check slice sizes first (6.8).
  • Do not re-run until green. Re-running a borderline eval and keeping the better run is a multiple comparison too (10A.8, 2.5).

8.7 Power before the run: the minimum detectable effect#

The last block of 8.3's output answers the question to ask before spending on a run: with the observed spread of per-ticket differences (standard deviation 0.28), twelve paired tickets can reliably detect a difference of about 0.22 (22 points); fifty can detect 0.11, and two hundred 0.055. v2's true improvement (0.083 here) is below what twelve tickets can see, which is why the comparison came out inconclusive, and it would have been predictable.

Use min_detectable_effect() from 10A.8, 2.4 with a standard deviation from a pilot run, and size the dataset (and choose epochs, 7.10) so that the smallest change you care about is above the minimum detectable effect. If it is not, a "no significant difference" result means "we could not tell", and should be reported that way.

8.8 Gating on Inspect numbers#

A CI gate over Inspect results combines 10B.8, 9.6's log gate (status success, full coverage) with this lesson's statistics. The rules, in order:

  1. Fail on a failed run: status not success, or scored_samples below the dataset size minus an allowed margin (report errors and unscored separately).
  2. Hard floors on point estimates for must-pass checks (format validity, a safety canary): triage_format accuracy must be 1.0 on the regression set, with a minimum number of samples so a three-sample run cannot pass.
  3. Non-regression judged on the paired interval, not the point estimate: fail only when the paired (or cluster-paired) interval shows a drop larger than the tolerance; warn when the interval straddles it. evalkit.compare.evaluate_gate() implements exactly this (10A.8, 2.5); feed it the per-sample values from log.reductions.
  4. Reliability floors with reducers: for agent or automation tasks, gate on pass_k_k per task or overall, with enough epochs (7.12).
  5. Record what was gated: the scorer, metric, reducer, sample count, interval and both log files, in the CI output.

10B.12 puts this into a CI job with eval sets and retries.


Part 9: Worked example: the triage eval, scored on purpose#

10B.8 ported the triage eval with the scoring it happened to have. This part rebuilds its scoring and statistics the way you would for a number that will be quoted in a release decision, using everything in Parts 2 to 8. The dataset, prompt and scorers of 10B.8 are reused unchanged; the model is flaky_triage.py's scripted stand-in, so epochs have variance to measure.

9.1 The task#

python
# triage_scored.py: the triage eval with scoring and statistics chosen on purpose (lesson 10B.10)
from inspect_ai import Epochs, Task, task
from inspect_ai.dataset import Sample
from inspect_ai.log import HeadlineMetric
from inspect_ai.scorer import (accuracy, ci_wilson, grouped, mean, multi_scorer,
                               stderr)
from inspect_ai.solver import generate, prompt_template

from flaky_triage import triage_correct
from triage import PROMPT_TEMPLATE, triage_format, triage_labels, triage_samples

# Suppose the twelve tickets came from six customer accounts. Tickets from one
# account share context (plan, history, writing style), so they are not independent.
CUSTOMER = {"T01": "c1", "T08": "c1", "T11": "c1", "T02": "c2", "T09": "c2",
            "T03": "c3", "T12": "c3", "T04": "c4", "T05": "c4",
            "T06": "c5", "T07": "c5", "T10": "c6"}


def samples() -> list[Sample]:
    out = []
    for s in triage_samples():
        s.metadata = {**(s.metadata or {}), "customer": CUSTOMER[str(s.id)]}
        out.append(s)
    return out


@task
def triage_scored(epochs: int = 5) -> Task:
    return Task(
        dataset=samples(),
        solver=[prompt_template(PROMPT_TEMPLATE), generate()],
        scorer=[
            triage_correct(),                                     # the decision metric
            triage_format(),                                      # the contract, tracked separately
            multi_scorer([triage_format(), triage_labels()], "mean"),   # evalkit's mean score
        ],
        metrics=[accuracy(), stderr(), stderr(cluster="customer"),
                 ci_wilson(cluster="customer"), grouped(mean(), "intent", all=False)],
        epochs=Epochs(epochs, ["mean", "pass_k_2"]),
        headline_metric=HeadlineMetric(scorer="triage_correct", reducer="mean", metric="accuracy"),
        version=2,                       # bumped: new scorers and metrics, not comparable with v1 runs
    )

Every choice in the file, and why:

Choice Why
triage_correct first, as the decision metric Binary (both labels right), so accuracy and pass^k mean what they say; 7.5 needs a binary success
triage_format kept as its own scorer The contract is a must-pass floor, tracked separately from correctness (8.8)
multi_scorer([...], "mean") evalkit's mean score as a first-class number, for continuity with 10A.1's reports (5.7)
A customer metadata key Tickets from one account are not independent; the clusters must exist at load time to be used by metrics (6.5)
stderr() and stderr(cluster="customer") Report both: the plain one for comparison with other runs, the clustered one because it matches the data's structure
ci_wilson(cluster="customer") An interval, bounded in [0, 1], that accounts for clustering (6.7)
grouped(mean(), "intent", all=False) Slices for error analysis, not for gating (they are tiny)
Epochs(5, ["mean", "pass_k_2"]) Per-attempt quality and two-in-a-row reliability (7.3)
headline_metric=HeadlineMetric(...) The viewer and evals_df() show the decision metric, not the first scorer's first metric (6.13)
version=2 New scorers and metrics: results are not comparable with version 1 runs (10B.8, 4.5)
epochs as a task parameter -T epochs=10 for a characterization run without editing the file

Task(metrics=...) replaces every scorer's metrics, so the list has to include accuracy() and stderr() explicitly (6.1).

9.2 The run and an honest report#

The report function prints, for every scorer × reducer, everything 4.6 and 8.1 say a number needs: coverage against the dataset size, the estimate, both standard errors and the interval, with the headline marked.

python
# s16_worked_example.py: run triage_scored and print the report a reader can defend (lesson 10B.10)
from inspect_ai import eval
from inspect_ai.log import EvalLog

from flaky_triage import make_flaky_model
from triage_scored import triage_scored


def honest_report(log: EvalLog) -> None:
    assert log.status == "success", f"run did not finish: {log.status}"
    h = log.results.headline
    print(f"task {log.eval.task} v{log.eval.task_version} | model {log.eval.model} | "
          f"epochs {log.eval.config.epochs} | log {log.location.rsplit('/', 1)[-1][:40]}...")
    for es in log.results.scores:
        m = {k: v.value for k, v in es.metrics.items()}
        slices = {k: round(v, 2) for k, v in m.items() if k in ("billing", "technical",
                  "account", "shipping", "other")}
        star = "*" if (es.name, es.reducer) == (h.score, h.reducer) else " "
        print(f"{star} {es.name:14} {es.reducer:9} {es.scored_samples}/{log.eval.dataset.samples} scored"
              f"  acc {m['accuracy']:.3f}  se {m['stderr']:.3f}  se(cluster) {m['stderr2']:.3f}"
              f"  95% Wilson(cluster) [{m['lower']:.3f}, {m['upper']:.3f}]")
        if es.name == "triage_correct":
            print(f"    per intent (mean): {slices}")


log = eval(triage_scored(), model=make_flaky_model(), log_dir="logs-scored", display="none")[0]
honest_report(log)
bash
uv run python s16_worked_example.py
Output · real9 lines
task triage_scored v2 | model mockllm/model | epochs 5 | log 2026-11-24T17-30-31-00-00_triage-scored_...
* triage_correct mean      12/12 scored  acc 0.733  se 0.102  se(cluster) 0.096  95% Wilson(cluster) [0.374, 0.927]
    per intent (mean): {'billing': 0.67, 'technical': 0.4, 'account': 0.87, 'shipping': 1.0, 'other': 1.0}
  triage_correct pass_k_2  12/12 scored  acc 0.633  se 0.123  se(cluster) 0.120  95% Wilson(cluster) [0.295, 0.877]
    per intent (mean): {'billing': 0.67, 'technical': 0.13, 'account': 0.73, 'shipping': 1.0, 'other': 1.0}
  triage_format  mean      12/12 scored  acc 0.917  se 0.083  se(cluster) 0.075  95% Wilson(cluster) [0.547, 0.990]
  triage_format  pass_k_2  12/12 scored  acc 0.917  se 0.083  se(cluster) 0.075  95% Wilson(cluster) [0.547, 0.990]
  multi_scorer   mean      12/12 scored  acc 0.900  se 0.068  se(cluster) 0.055  95% Wilson(cluster) [0.530, 0.986]
  multi_scorer   pass_k_2  12/12 scored  acc 0.633  se 0.123  se(cluster) 0.120  95% Wilson(cluster) [0.295, 0.877]

9.3 Reading it#

  • Coverage first. Every scorer and reducer scored 12 of 12 samples: no errors, no unscored samples. Only now are the numbers worth reading.
  • The headline (marked *): per-attempt correctness 0.733, standard error 0.102. The clustered standard error is slightly smaller (0.096): with six customers whose average results happen to be similar, the cluster-level spread is small. That is not a reason to prefer it, and with six clusters it is itself very uncertain, which the clustered Wilson interval reflects: [0.374, 0.927], wide because it uses a t critical value with 5 degrees of freedom (2.57 instead of 1.96); the Korn-Graubard effective n, about 21, is capped at the 12 tickets, so the t value is the only widening. The honest one-line summary: "between roughly 40% and 90% of attempts are fully correct; twelve tickets from six customers cannot narrow it further".
  • Reliability (pass_k_2): 0.633. If two customers with similar tickets each get one triage, the chance that both are right is about 63%. For an automated routing system this, not 0.733, is the number that predicts complaints.
  • Slices: technical tickets are the weak spot (0.40 per attempt, 0.13 for two in a row), driven by T02 and T09. With three technical tickets, that is a lead for error analysis (10A.1, Part 4), not a finding.
  • The format contract: 0.917 under both reducers (T11 fails every time, so the reducer makes no difference). As a must-pass floor of 1.0, this run fails the gate regardless of correctness.
  • The multi-scorer mean (0.900, printed as acc only because its metric was inherited from triage_format, 5.7; it is a mean of partial credit, not an accuracy) is the continuity number for anyone comparing with 10A.1's evalkit reports. Its pass_k_2 row (0.633) shows a pitfall of task-wide reducers: the reducer applies to every scorer, and pass^2 of a partial-credit mean counts only epochs where the mean reached 1.0. It equals triage_correct's pass^2 here only because every correctly labelled reply in this script also has a valid format and summary; with a real model the two would differ, and the row has no clear meaning. Do not report it.

What this example still leaves out, deliberately: a real model (run it with --model and a key, 10B.12), a dataset big enough for decisions (8.7), and a comparison against the previous version, which is 8.3's script applied to two logs of this task.


Part 10: Methodology: defending a scored number#

Deep-dive

10.1 Validating scorers before trusting them#

A scorer is an instrument, and an instrument is validated before it measures anything. The checks, from cheapest to most thorough:

  1. Unit tests on hand-written outputs (5.2): the formats you expect, the formats you fear (fences, prose, missing fields, empty), and a never-crash test on junk.
  2. Oracle and null controls (10B.8, 10.2, 10B.9, 10.1): the oracle must score 1.0 on every scorer and the null 0.0; for multiple choice, a constant-letter control gives the chance baseline (10B.9, 10.1). A scorer that cannot reach both ends cannot be trusted anywhere in between.
  3. A side-by-side run on fixed outputs (3.11): when you choose between scorers, or port one from evalkit, run both on the same outputs and read every disagreement.
  4. Read the extremes. Sort samples by score and read the top and bottom few transcripts: high scores that should not be (a hedged answer includes() accepted), low scores that should not be (a correct answer the regex missed).
  5. Agreement with humans for any scorer with judgement in it (model graders, fuzzy matching thresholds): a labelled sample, attached with precomputed_scores() (5.9), and 10A.5's agreement statistics. 10B.11 runs this for Inspect's graders.
  6. Re-validate on change. A new scorer version, a new Inspect release (the built-in graders' prompts change between releases), a new output format: bump the task version and repeat 1 to 4.

10.2 A checklist before you quote a number#

10B.8, 10.5 gave the checklist for a first run. For a scored number with statistics, add:

  • The scorer, metric and reducer are named next to the number ("triage_correct accuracy, mean of 5 epochs").
  • Coverage is reported: scored of total, unscored, errors, for each scorer you quote (4.6), and you know why anything was unscored.
  • Unparsable and empty outputs are verdicts (INCORRECT with a reason), not unscored (4.5).
  • No custom labels reach metrics without converters on both the reducer and the metrics (2.5); no value_to_float warnings in the log.
  • Solvers do not let TimeoutError escape (4.3).
  • An interval is reported (ci_wilson() for binary scores), clustered when samples share a source (6.5, 6.7).
  • Slices are reported with their sizes, and gating slices were chosen before the run (6.8, 8.6).
  • With epochs: the epochs and reducers in the log header are the ones you intended (7.2), the cache is per epoch, and the flip rate is known (7.9).
  • Comparisons with another run are paired on sample id, use the same task version, epochs and reducers, and come with a paired interval (8.3); "no difference" is reported with the minimum detectable effect (8.7).
  • The headline metric is set, so the viewer shows the number you mean (6.13).

Every row was reproduced with inspect-ai 0.3.292 in this lesson unless marked as from the documentation. Most fail silently: no error, a plausible wrong number.

Symptom Cause Fix
Accuracy is 0 (or low) and the outputs look right Custom labels ("pass", "Correct") converted to 0.0 by value_to_float() (2.4) Return CORRECT/INCORRECT, or converters on reducer and metrics
Converter on the metric, still 0 The reducer converted first (1.2) Epochs(n, mean_score(value_to_float=...)) too
A custom converter makes "C" count as 0 A custom converter replaces the label set (2.4) One label vocabulary per scorer
Custom metric crashes with could not convert string to float: 'C' Score.as_float() with reducers disabled (7.8) value_to_float() in metrics
Every sample passes includes() Empty targets (3.11) Validate targets at load time; run the null control
Multi-answer target never matches in your scorer Target.text concatenates without a separator (2.6) Iterate the Target
match(numeric=True) fails on a correct total The reply mentions another number after it (3.3) location="begin" or "any", or answer() with a defined slot
answer("word") marks correct multi-word answers as format failures The word pattern accepts one word (3.5) answer("line")
math() fails to build Optional extra missing (3.8) uv add "inspect-ai[math]"
Accuracy rises when the grader gets worse Unscored samples leave the denominator (4.1) Report coverage; investigate unscored counts
Metrics are nan Every sample unscored (4.2) Treat as a failed run, not a missing number
A tool timeout counted as a pass TimeoutError escaping a solver is scored as if nothing happened (4.3) Catch timeouts in solvers and tools
Two scorers report different scored_samples One raised after the other scored (5.6) Compare coverage before metrics
Human ratings attached, coverage unclear precomputed_scores() leaves unmatched samples with no score entry (5.9) Count coverage yourself, or on_missing="error"
Results indexed by name break after adding a scorer Suffixing (match1), lower2, aggregate2, all2 (6.14) Look up by (name, reducer, metric)
Clustered standard error is 0 Equal cluster means, or one cluster (6.5) Count clusters; prefer the data's structure over the smaller number
ci() runs below 0 or above 1 t interval with few samples or clusters (6.7) ci_wilson() for binary scores
Bootstrap numbers change between identical runs bootstrap_stderr() and ci(method="bootstrap") are unseeded (6.6) stderr(), or seeded bootstraps in evalkit
A slice reports stderr 0 The slice has one sample (6.8) Count slice sizes; 30 per slice before decisions
The task's own accuracy and stderr disappeared Task(metrics=...) replaces every scorer's metrics (6.1) List every metric you want
The viewer shows the wrong number Default headline is the first scorer's first metric (6.13) headline_metric=
--epochs-reducer did nothing Ignored without --epochs (7.2) Pass both; read the header
Standard error shrank when reducers were disabled Sample-epochs treated as independent (7.8) Keep a reducer; use unreduced metrics for per-epoch views
A "worst case" reducer reports a better number NaN propagated through min(), dropping a failing sample (7.7) Guard NaN in custom reducers
majority shrinks the denominator Ties and unscored votes are NaN (7.6) Odd epochs; report unscored; or mode
pass_at_5 refused before the run Fewer epochs than k (7.5) epochs >= k
Epochs show zero (or suspiciously low) variance Deterministic model or settings, or a non-per-epoch cache, which replays cached answers into most epochs (7.11, 10B.12, 6.4) Production settings; per_epoch=True
"v2 is better" from two panels Unpaired reading of noise (8.3) Paired interval on per-sample values
A partial-credit scorer's pass^k is meaningless Task-wide reducers apply to every scorer (9.3) Report reducers only for scorers where they mean something

10.4 Decision table#

Decision Choose When
Scorer type A built-in text scorer The answer is a string with a fixed rule (3.13)
A custom scorer Structured output, business rules, metadata-dependent checks, process checks
cascade() Most answers are decidable cheaply and a few need a grader
A model grader No rule can decide; and only with validation (10B.11)
Score values CORRECT/INCORRECT (+ PARTIAL, NOANSWER) Verdicts
A float in [0, 1] Partial credit, with mean()
A dict Several field-level checks from one parse (5.3)
Failure handling INCORRECT + reason The model under test failed
Score.unscored(reason=...) The instrument failed
None The sample is out of the scorer's scope
Combining checks multi_scorer(..., all_pass()) or "at_least_<n>" "Every check must pass"
multi_scorer(..., "mean") An average over checks, named as such
Separate scorers Checks with different roles (a floor and a quality metric)
Uncertainty stderr() Always (it is the default)
stderr(cluster=...) + ci_wilson(cluster=...) Samples share a source and there are enough clusters to estimate
ci_wilson() Binary scores
ci() Continuous scores
Epochs 1 Gates on a stable configuration; cost-limited suites
3 to 5, mean Per-attempt quality of a non-deterministic system
8 to 16, pass_k_k Reliability claims
Comparing runs evalkit paired bootstrap on log.reductions Same samples, same task version
Paired cluster bootstrap Samples share a source

Part 11: evalkit ↔ Inspect for scoring and statistics#

Reference

11.1 The mapping#

10B.8, Part 8 mapped the whole harness. This is the scoring and statistics half in detail, against the names in 10A.10, Appendix A.

evalkit Inspect What differs
Scorer.score(example, output) -> Score (core.py) @scorer factory returning async def score(state, target) -> Score Sees the whole TaskState (messages, metadata, store); metrics declared on the scorer
Score(name, value, passed, detail) Score(value, answer, explanation, reason, metadata) No name (the scorer's name), no passed (the value is the verdict); values may be labels, numbers, lists, dicts
FunctionScorer (core.py), case_scorer (scorers.py) A small @scorer factory
exact_match, normalized_match exact(), match(location="exact") Inspect's normalization drops articles
contains_any includes() Iterates the target list
regex_match pattern(), answer() Format failures carry reason="invalid_response_format"
numeric_match match(numeric=True) Location decides which number is read
token_f1 f1() SQuAD normalization
json_field_match, schema_valid Custom scorer; dict-valued for per-field metrics No built-in JSON scorer
Row error captured, counted as failure Exception → sample.error, excluded from metrics; score_on_error=True to score partial state Opposite default for the denominator
(no equivalent) Score.unscored(reason=...), None Explicit instrument failure and out-of-scope outcomes
EvalReport.pass_rate (all scorers pass) multi_scorer([...], all_pass()) or "at_least_<n>" Built here in 5.7
EvalReport.mean_score multi_scorer([...], "mean") Same number (0.903 on the triage fixture)
slice_breakdown() grouped(metric, "key") Slice sizes are not reported
MetricSummary with bootstrap_mean_ci (compare.py) accuracy/mean + stderr + ci_wilson/ci Inspect's bootstraps are unseeded; its default is the CLT error
cluster_bootstrap_ci (10A.2) stderr(cluster=), ci(cluster=), ci_wilson(cluster=) Analytic clustered error with a C/(C−1) correction, not a bootstrap
repeats= epochs= / Epochs(n, reducer) Reduced per sample before metrics; reducer explicit and logged
pass_at_k, pass_hat_k, wilson_interval (agent_eval.py) pass_at_{k}, pass_k_{k} reducers; ci_wilson() Same estimators (7.4)
krippendorff_alpha (judge_validation.py, 10A.5) krippendorff_alpha() metric with multi_scorer(..., "collect") Same nominal statistic (6.11); adds ordinal and interval levels
paired_diffs, paired_bootstrap_ci, sign_flip_permutation_p, paired_effect_size, min_detectable_effect, evaluate_gate (compare.py) None Run evalkit on log.reductions or samples_df() (8.3)
paired_cluster_bootstrap_ci (cluster.py) None Same, grouping by a metadata key (8.5)
Human labels in judge_validation.py precomputed_scores() attaches them to a log Agreement statistics remain 10A.5's code

What this means for you as an engineer: Inspect replaces evalkit's scorer plumbing and per-run summaries with better-engineered, logged versions, and adds reducers, clustered errors and a scoring policy that evalkit never had. It does not replace the comparison statistics: compare.py and cluster.py stay in your toolkit, now fed from Inspect logs.

11.2 Corrections to 10A.10#

Checked against inspect-ai 0.3.292 on 24 November 2026. 10B.8, 8.3 lists the full set; these are the ones about scoring and statistics, with where this lesson shows the current behaviour:

10A.10, 4.5 says As of 0.3.292
Partial credit: "Score.value in [0,1]" Score.value is any Value (labels, numbers, lists, dicts); metrics convert with value_to_float(), and unknown labels silently become 0 (2.3, 2.4)
Repeats: "--epochs / sample-level epochs" No sample-level epochs: epochs are set on the task, eval() or --epochs, reduced per sample by an explicit reducer before metrics; --epochs-reducer needs --epochs (Part 7)
Slices: "dataset metadata columns" Slicing is the grouped() metric (or grouping samples_df() by metadata_* columns) (6.8)
A scorer: "model_graded_fact, includes, exact, ..." Also match (with numeric=True), pattern, answer, f1, choice, math (needs the [math] extra), the perplexity scorers, and multi_scorer, cascade, precomputed_scores (Part 3, Part 5)
"In evalkit and Inspect AI the judge is your code" True for custom scorers; the built-in graders' prompts are Inspect's (10B.11)
10A.10's exact_json example returns Score(value=1.0 ...) / 0.0 with accuracy() Works, but returns no reason; an unparsable output should carry reason="invalid_response_format" so format failures can be counted (4.4)

10A.10's failure gallery should also gain this lesson's silent-failure rows: custom labels counted as zero, unscored samples leaving the denominator, the escaping TimeoutError, --epochs-reducer without --epochs, and unseeded bootstrap metrics.


Part 12: Older code and tutorials#

Reference

Current APIs first; when you meet older code, this is what replaced it (as of 0.3.292).

You may see Use instead Notes
Task(epochs_reducer=...) Task(epochs=Epochs(n, reducer)) Still accepted with a deprecation warning, but only applied when epochs= is an integer; on its own (no epochs=) it is silently ignored and the run uses one epoch and the default reducer
A scorer returning Score(value=NaN) or a sentinel string for "could not grade" Score.unscored(reason=...) Score.unscored() since 0.3.214 (29 April 2026)
Hand-written pass^k reducers The pass_k_{k} reducer (pass_k()) Since 0.3.224 (20 May 2026)
Agreement computed outside Inspect krippendorff_alpha() Since 0.3.258 (11 August 2026)
"The first scorer is the headline" Task(headline_metric=...) Since 0.3.261 (30 August 2026)
ci() for accuracies ci_wilson() Since 0.3.262 (2 September 2026)
Hand-written "cheap check, then grader" scorers cascade() Since 0.3.262
Grader panels where "earliest model wins ties" Strict majority, ties unscored; reducer="mode" for the old behaviour Breaking change in 0.3.262; the models page still describes the old rule (10B.11)
Custom metrics using score.score.as_float() (the docs' own example) value_to_float()(score.score.value) Works only while reducers convert for you (7.8)
includes() shown with target.text (the custom-scorers page) Iterate the Target The installed scorer iterates (2.6)
@scorer([accuracy(), stderr()]) (positional, in 10A.10's sketch) @scorer(metrics=[accuracy(), stderr()]) Both work; the keyword form is what the docs use and reads better
exclude_samples() / zero_samples() returning a DispositionResult They return None Breaking change in 0.3.292 (10B.11)

Older posts and courses will not mention any of the 2026 features; the CHANGELOG gives each feature's release, and help(...) on the installed package is the final word.


Common misconceptions#

Misconception Reality
"The log says C, so the metric used C." The reducer converted it to 1.0 first, even with one epoch; log.reductions holds what the metric used (1.3).
"Score.value must be between 0 and 1." Any Value: labels, numbers, lists, dicts. Only some metrics (ci_wilson()) require [0, 1] (2.3).
"My labels pass/fail work if I give the metric a converter." The reducer converts first; it needs the converter too, and a custom converter no longer understands C (2.5).
"Accuracy is over all the samples." Over the scored samples: errors, unscored samples and out-of-scope samples leave the denominator (4.1).
"If the model's output can't be parsed, the sample should be unscored." That rewards broken output. The model failed: INCORRECT with reason="invalid_response_format". Unscored is for instrument failures (4.5).
"Any exception in a solver makes the sample an error." A TimeoutError that escapes a solver is scored as if nothing happened (4.3).
"includes() and match() are basically the same." match() normalizes and anchors (end by default); numeric mode, locations and empty-reply handling differ (3.11).
"Inspect can't compute evalkit's pass rate." multi_scorer([...], all_pass()) or "at_least_<n>" reproduces it exactly, and "mean" reproduces the mean score (5.7).
"The standard error tells me how much the number would change if I re-ran it." It mostly measures how different samples are from each other; re-run noise is a smaller, separate component that epochs shrink (7.10).
"More epochs give a tighter interval." n is the number of samples; epochs make the number repeatable, not general. More samples tighten it (7.10).
"A clustered standard error is always bigger." It can be smaller (equal cluster means, or chance with few clusters); choose it by the data's structure, not by its size (6.5).
"ci() is the interval to use." For binary scores the docs recommend ci_wilson(); ci()'s t interval leaves [0, 1] at small n or few clusters (6.7).
"pass@k and pass^k are the same idea with different k." pass@k is "at least one of k succeeds" (capability); pass^k is "all k succeed" (reliability). Same run: 0.833 vs 0.633 (7.4).
"--epochs-reducer pass_at_2 changes the reducer." Only together with --epochs; alone it is silently ignored (7.2).
"Disabling reducers gives more data, so a better standard error." It treats epochs of one sample as independent samples: a falsely small error (7.8).
"v2's accuracy is higher than v1's, so v2 is better." Compare paired per-sample values with an interval; here +0.083 with an interval spanning zero (8.3).
"High Krippendorff's alpha means the judges are right." It means the judges agree with each other; agreement with humans is a separate check (6.11).

Key takeaways#

  • The pipeline: per sample and epoch, each scorer returns a Score; per scorer and reducer, epochs are reduced to one value per sample (always, even with one epoch, converting labels to floats); metrics run over those values; one EvalScore per scorer × reducer lands in log.results.scores, with the reduced values in log.reductions.
  • Score carries value, answer, explanation, reason and metadata. Return CORRECT/INCORRECT/PARTIAL/NOANSWER or numbers; value_to_float() turns unknown labels into 0 with only a warning, and Score.as_float() does not convert labels. Iterate a Target; its .text concatenates.
  • Built-in scorers differ in normalization, anchoring and format handling: includes, match (four locations, numeric=True), pattern (match_all), answer (last ANSWER: wins; letter, word, line), exact and f1 (SQuAD normalization), choice, math (needs inspect-ai[math]). Empty replies are INCORRECT with no_response; missing formats invalid_response_format.
  • The scoring policy decides the denominator: a verdict counts, Score.unscored() is excluded and counted, None is excluded and not counted, an exception is a sample error. Model failures are verdicts; instrument failures are unscored. Always report coverage. Catch TimeoutError in solvers.
  • Custom scorers should parse defensively, return an answer and a reason, be unit-tested on a hand-built TaskState, and can be dict-valued (per-key metrics), read the store (process metrics), call models (with 10B.11's care), be combined with multi_scorer() (including "every check must pass") or cascade(), and take human labels through precomputed_scores().
  • Metric formulas: accuracy/mean are the mean; std/var use ddof=1; stderr is std/sqrt(n) over reduced samples; clustered stderr is sqrt(Σ_c residual_c² · C/(C−1)) / n; bootstrap_stderr and bootstrap intervals are unseeded; ci_wilson() is the interval for binary scores (clustered: Korn-Graubard effective n and t(C−1)); grouped() slices; frequency() sees every epoch; krippendorff_alpha() needs collect.
  • Task(metrics=...) replaces every scorer's metrics; set headline_metric so the viewer shows the number you mean; look results up by (name, reducer, metric) because Inspect suffixes duplicate names.
  • Epochs and reducers: mean (per attempt), pass_at_k (capability), pass_k_k/at_least_k (reliability), mode/majority (votes; majority leaves ties unscored), max, median, collect. The same verdicts gave 0.50 to 0.917 depending on the reducer: name it with every number. --epochs-reducer needs --epochs; disabling reducers understates the error; custom reducers must handle NaN.
  • Epochs make a number repeatable, samples make it general. The reported standard error levels off as epochs grow; spend on 3 to 5 epochs, then on samples. Measure instability with an unreduced flip-rate metric.
  • Inspect does not compare runs. Paired bootstrap, permutation tests, cluster bootstraps, multiple-comparison discipline and the minimum detectable effect come from evalkit's compare.py and cluster.py, fed with log.reductions or samples_df(), joined on sample id.

Terms introduced in this lesson#

Term One-line definition
Scoring pipeline (Inspect) Score per sample and epoch, reduce per sample, compute metrics per scorer and reducer, record EvalScores
value_to_float() Inspect's converter from score values to floats: C 1, P 0.5, I/N 0, numbers cast, unknown values 0 with a warning
Target The scorer's view of a sample's target: a list of acceptable answers; iterate it, since .text concatenates
SampleScore What a metric receives: a reduced score plus the sample's id and metadata
AnswerPattern The three regexes answer() uses (letter, word, line), each binding to the last ANSWER:
reason / ScoreReason A machine-readable label on a Score naming the failure class and its actor (invalid_response_format, no_response, grader_failed...)
Scoring policy (Inspect) The rules deciding which samples count: verdicts count, unscored and None do not, errors are excluded
Unscored score Score.unscored(): a NaN value marking an instrument failure, excluded from metrics and counted in unscored_samples
Measurement-instrument rule Model-under-test failures are verdicts; scorer or grader failures are unscored
score_on_error Task option to score the partial state of samples whose solver raised, so they count in the metric
Dict-valued score A Score whose value is a dict; each key becomes its own score with its own metrics
multi_scorer() Runs several scorers on a sample and reduces their scores into one with a reducer
cascade() Runs scorer stages in order and stops at the first that passes a threshold, recording decided_by
precomputed_scores() A scorer that applies scores from a JSON or JSONL file (for example human ratings) to a log by sample id
Intermediate scoring Calling the task's scorers from inside a solver with inspect_ai.scorer.score(state)
Clustered standard error A standard error that treats groups of related samples (a metadata key) as the independent units
Korn-Graubard effective sample size p(1−p) divided by the clustered variance: the sample size ci_wilson(cluster=...) uses
ci_wilson() Inspect's Wilson score interval metric, bounded in [0, 1], recommended for binary scores
grouped() A metric wrapper that computes a metric per metadata group, with an optional all entry
aggregate() A metric wrapper that applies a metric to one key of dict-valued scores
frequency() / categorical() Metrics reporting the share of each categorical value, over every sample-epoch
Score view Whether a metric receives reduced scores (one per sample) or unreduced scores (one per sample-epoch)
Headline metric The single metric the viewer and evals_df() show for a task; set with headline_metric
Reducer (Inspect) A function combining one sample's epoch scores into one score before metrics (mean, pass_at_k, majority...)
Epochs The Epochs(n, reducer) object setting the number of epochs and the reducer(s)
majority vs mode Strict more-than-half vote (ties unscored) versus most common value
at_least_k Reducer giving 1 when at least k epochs succeed
Epoch flip rate The share of samples whose epoch verdicts disagree: a measure of instability
Rerun noise vs sampling uncertainty Variation from re-running the same samples (shrinks with epochs) versus from which samples were drawn (shrinks with more samples)

Exercises#

All exercises run keyless with this lesson's files. exercises.py in the lesson's work folder checked the numeric answers.

  1. Labels and converters (2.4, 2.5). With conv = value_to_float(correct="pass", incorrect="fail"), predict conv("PASS"), conv("pass") and conv("Fail"), then run them. What does this tell you about scorers that emit labels from model text?
  2. Summary length as a metric (5.1, 6.3, 6.8). Write a scorer summary_words that returns the number of words in the parsed summary (0 when unparsable) as a number, with metrics mean(), std() and grouped(mean(), "intent"). Run it on the triage task with fake_triage.py. Why is accuracy() the wrong metric for it, and why does ci_wilson() raise?
  3. The wrong policy (4.5). Change triage_format so that an unparsable output returns Score.unscored(reason="invalid_response_format"). Predict the new accuracy with fake_triage.py and the coverage counts. Why is the new number misleading?
  4. Clusters that matter (6.5). In s08_metrics.py, change the documents to 4, 4, 0 and 0 correct out of 4. Predict the accuracy, the plain standard error and the clustered standard error by hand, then run it.
  5. Reducers by hand (7.3, 7.5). A ticket is right in 3 of 5 epochs. Compute its pass_at_3, pass_k_3, at_least_3, majority and mean values, then check with a one-sample task.
  6. Flip rate (7.9). Add flip_rate() from s11_reducer_edges.py to the triage task with make_flaky_model() and five epochs (as Task(metrics=[...])). Predict the value from SUCCESSES before running.
  7. A bigger fix (8.3). In s13_compare_runs.py, let v2 also fix T11 completely (T11=5). Predict the mean paired difference. Does the 95% interval now exclude zero? What would you tell the team?
  8. A gate (8.8, Part 9). Write gate_scored.py that reads the newest log in logs-scored and exits 1 unless: status is success; every scorer and reducer has scored_samples equal to the dataset size; triage_format (mean reducer) accuracy is 1.0; and the headline metric is at least 0.7. Does the worked example's run pass?
  9. Cascade false positives (5.8). The FAQ question is "How long do I have to request a refund?" and the true answer is 30 days. Add a reply "Refunds can take up to 30 days to reach your card; requests must be made within 7 days." to s07_cascade_precomputed.py (target 30 days). Which stage decides it, and is the verdict right? How would you make the first stage safer?
  10. Power (8.7). With a standard deviation of paired differences of 0.28, how many paired tickets do you need for a minimum detectable effect of 0.05 at α = 0.05 and 80% power? Use min_detectable_effect() in a loop.
Answers and what you should see
  1. 0.0, 1.0, 0.0 (real run). A custom converter compares labels exactly before lower-casing, so "PASS" and "Fail" are unknown and count as 0. A scorer that copies a label out of model text must normalize it (.strip().lower()) to the converter's spelling, or, better, map it to CORRECT/INCORRECT in the scorer.
  2. The fake's summaries are short sentences, T10's is empty and T11 is unparsable (0). accuracy() would compute the same mean but call a word count an "accuracy"; name it mean(). ci_wilson() raises ValueError because values above 1 have no binomial reading. std() shows the spread (the empty and unparsable summaries pull it up), and the grouped means show which intents get longer summaries.
  3. T11 becomes unscored: scored=11, unscored=1, accuracy 11/11 = 1.0. The model's format failure has disappeared from the metric, so a model that fails more often in unreadable ways would look better. The policy is wrong: the model under test failed, so it is a verdict (INCORRECT).
  4. Accuracy 0.5 and plain standard error 0.1291 (unchanged: still 8 of 16). Residual sums are +2, +2, −2, −2; sum of squares 16, times 4/3 is 21.33, square root 4.62, divided by 16 is 0.2887 (the real run printed 0.2887): wider than 6.5's 0.2282 because the documents differ more.
  5. n = 5, c = 3: pass_at_3 = 1 − C(2, 3)/C(5, 3) = 1.0 (only 2 failures, so any 3 draws contain a success); pass_k_3 = C(3, 3)/C(5, 3) = 1/10 = 0.1; at_least_3 = 1; majority = C (3 of 5 is more than half); mean = 0.6.
  6. Tickets with 0 < c < 5 flip: T02, T04, T06, T09, T12, so 5/12 = 0.417 (the real run printed 0.417). T11 (always wrong) and the always-right tickets do not flip; T11 is a stable failure, which is easier to fix than a flaky one.
  7. (0.6 − 0.4 + 0.2 + 0.6 + 1.0) / 12 = +0.167. The real run's interval was [−0.017, +0.383]: still (just) including zero with twelve tickets. Tell the team the direction is promising, T04's regression needs a look, and the eval cannot confirm a difference this size; run it on a larger set (8.7).
  8. Read with read_eval_log(list_eval_logs("logs-scored")[0], header_only=True), compare es.scored_samples with log.eval.dataset.samples, find triage_format with reducer mean, and look up the headline via log.results.headline. The worked example's run fails the gate: triage_format accuracy is 0.917 (T11 never produces valid JSON), even though the headline 0.733 is above 0.7. That is the point of a separate format floor.
  9. The keyword stage (includes()) finds "30 days" in the reply and decides C, and the grader is never asked. The verdict is wrong: the reply gives 7 days as the request window, and the 30 days it mentions is the processing time. A pass from an early stage is never re-checked, so the first stage must only accept unambiguous passes: an exact phrase in a defined slot (answer("line") on "ANSWER: 30 days"), or a regex anchored to the meaning ("request a refund within 30 days"), with everything else left to the grader.
  10. 247 paired tickets (min_detectable_effect(247, 0.28) is 0.0499; the real loop printed 247). Twelve tickets could only detect about 0.22.

Check yourself#

  1. Name the four stages between a model's output and the number on the results panel, and where each stage's result lives in the log.
  2. Why do metrics receive 1.0 when the scorer returned "C", even with one epoch?
  3. What does value_to_float() return for "P", True, "0.25", "Correct" and ["C"]?
  4. Why is Target.text dangerous with a list target, and what should a scorer do instead?
  5. match() and match(numeric=True) on the reply "Total: 1,234.50 (was 1,300.00)" with target 1234.5: which pass, and with which location?
  6. What do answer("letter"), answer("word") and answer("line") extract from "ANSWER: billing team"?
  7. List the four ways a scorer can end and what each does to the denominator.
  8. An unparsable reply and an unparsable grader verdict: which is a verdict and which is unscored, and why?
  9. What happens to a sample whose solver raises TimeoutError, and what should you do about it?
  10. How do you compute evalkit's pass rate and mean score in Inspect?
  11. Write the clustered standard error formula Inspect uses. When can it be zero, and why is that not reassuring?
  12. Why do Inspect's docs recommend ci_wilson() over ci() for accuracy?
  13. A task declares Epochs(5, ["mean", "pass_k_2"]). What do --epochs 3, --epochs-reducer at_least_2 and --epochs 5 --no-epochs-reducer each do?
  14. Five epochs of a ticket gave C C I C I. Give the mean, pass_at_2, pass_k_2 and majority values.
  15. Two runs report 0.733 and 0.817. What three things do you need before saying the second is better?

Further resources#

Official documentation (every URL checked on 24 November 2026; each page also exists as Markdown by adding .md, and llms.txt indexes them):

Source and papers:

Within this course: 10A.2, Part 5 and 6.7 (sample sizes and clustering), 10A.3 (deterministic graders), 10A.5 (agreement and calibration), 10A.7, Part 5 (pass@k, pass^k, Wilson), 10A.8, Part 2 (paired comparisons, MDE, multiple comparisons), and next, 10B.11 for model grading and validating the grader.


← 10B.9: Inspect Datasets, Solvers and Task Configuration (optional) | Module 10B overview | 10B.11: Model Grading in Inspect, and Validating the Grader (optional) →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close