Sub topic 14
Run the eval and read per-slice results
You have a dataset with stable ids, tags, references, and a split. This chapter covers running the app over that dataset and turning the raw pass/fail results into a report you can act on.
This chapter assumes you can read Python and JSONL, and that you have a grader function like the exact-match one from earlier chapters. It also assumes you know what a proportion and a sample size are. It uses the case schema from this tutorial: id, input, reference, tags.
What a run produces
A run is one pass of your app over a fixed set of cases, with one grader applied. The useful output is not a single accuracy number. It is a record per case that you can slice and compare later.
Store at least these fields for every case:
- The case id, so you can join results to the dataset and to other runs.
- The tags, copied from the case, so slicing needs no second lookup.
- The raw app output, so you can read failures instead of guessing.
- The grader's verdict, and an error field if the app crashed.
Also record run metadata: dataset version, split, app version or prompt hash, model name, grader name, and timestamp. Without this, a score from last month is not comparable with a score today.
A runner that keeps every record
The runner below is self-contained. It treats an app crash as a failure instead of skipping the case. Skipping crashed cases silently raises your score, which is one of the most common reporting errors.
import json
import random
from collections import defaultdict
def grade(output, reference):
return output.strip().lower() == reference.strip().lower()
def run_eval(cases, app, grader=grade):
records = []
for c in cases:
error = None
try:
output = app(c["input"])
except Exception as exc:
output, error = "", repr(exc)
passed = error is None and grader(output, c["reference"])
records.append({
"id": c["id"],
"tags": c["tags"],
"output": output,
"error": error,
"passed": int(passed),
})
return records
def bootstrap_ci(scores, n_boot=1000, alpha=0.05, seed=0):
rng = random.Random(seed)
n = len(scores)
means = sorted(sum(rng.choices(scores, k=n)) / n for _ in range(n_boot))
lo = means[int(n_boot * alpha / 2)]
hi = means[int(n_boot * (1 - alpha / 2)) - 1]
return lo, hi
def slice_report(records):
by_tag = defaultdict(list)
for r in records:
for tag in r["tags"]:
by_tag[tag].append(r["passed"])
rows = []
for tag, scores in by_tag.items():
lo, hi = bootstrap_ci(scores)
rows.append((tag, len(scores), sum(scores) / len(scores), lo, hi))
return sorted(rows, key=lambda row: row[2])
def save_run(records, path, meta):
with open(path, "w", encoding="utf-8") as f:
f.write(json.dumps({"meta": meta}) + "\n")
for r in records:
f.write(json.dumps(r) + "\n")
if __name__ == "__main__":
cases = [
{"id": "r1", "input": "Return a laptop after 45 days?", "reference": "No", "tags": ["returns"]},
{"id": "r2", "input": "Return a phone after 10 days?", "reference": "Yes", "tags": ["returns"]},
{"id": "s1", "input": "Do you ship to Canada?", "reference": "Yes", "tags": ["shipping"]},
{"id": "s2", "input": "Do you ship to Mars?", "reference": "No", "tags": ["shipping", "adversarial"]},
]
stub_app = lambda text: "No" if "45" in text or "Mars" in text else "Yes"
records = run_eval(cases, stub_app)
save_run(records, "run_001.jsonl", {"dataset_version": "v3", "split": "dev"})
for tag, n, acc, lo, hi in slice_report(records):
print(f"{tag:12s} n={n} acc={acc:.2f} ci=[{lo:.2f}, {hi:.2f}]")Two details matter. bootstrap_ci uses a fixed seed, so the same records always give the same interval. And a case with several tags counts once in each of its slices, so slice sizes can add up to more than the number of cases.
Read the report from the bottom up
A report might look like this. The numbers are illustrative.
| Slice | Cases | Accuracy | 95% interval |
|---|---|---|---|
| adversarial | 12 | 0.50 | 0.25 to 0.75 |
| multi_turn | 30 | 0.67 | 0.50 to 0.83 |
| returns | 80 | 0.86 | 0.78 to 0.93 |
| shipping | 90 | 0.92 | 0.86 to 0.97 |
| overall | 200 | 0.84 | 0.79 to 0.89 |
Read it in this order:
- Look at slice sizes first. The adversarial slice has 12 cases. Its interval spans 50 points, so "0.50" tells you little beyond "probably weak". A narrow interval needs many cases, as the dataset-size chapter explained.
- Compare the worst slices to the overall number. The overall 0.84 hides the 0.50 and 0.67 slices. An average over an input mix that does not match production can look healthy while the slice users care about is failing.
- Check whether intervals overlap before ranking slices. Returns (0.86) and shipping (0.92) overlap, so you cannot say shipping is truly better from this data.
- Open the failing records. Read ten or twenty failed outputs in the worst slice. The score tells you where to look. The outputs tell you why.
Sort failures into causes
Each failed case has one of a few causes. Name the cause before changing anything, because the fixes differ.
- App error. The app gave a wrong answer. Fix the prompt, retrieval, or model.
- Grader error. The answer was acceptable but the grader rejected it. Exact match fails on "No, returns close after 30 days." against the reference "No." Fix or replace the grader.
- Case error. The reference is wrong, ambiguous, or out of date. Fix the case and bump the dataset version.
- Infrastructure error. Timeout, rate limit, malformed response. Retry, and count persistent errors as failures.
Compare two runs by pairing cases
When you change a prompt, you want to know whether the new version is better. Two overall accuracies with overlapping intervals will rarely answer that. Both runs score the same cases, so compare them case by case.
def paired_diff(records_a, records_b):
a = {r["id"]: r["passed"] for r in records_a}
b = {r["id"]: r["passed"] for r in records_b}
shared = sorted(a.keys() & b.keys())
fixed = [i for i in shared if a[i] == 0 and b[i] == 1]
broken = [i for i in shared if a[i] == 1 and b[i] == 0]
return {"shared": len(shared), "fixed": fixed, "broken": broken}The broken list is the regression list, and it is often more useful than the accuracy change. A change that fixes 8 cases and breaks 6 has a net gain of 2, but it is a different app. If the gain is within noise, treat it as no change. A rough check: if fixed and broken are both small and close in size, the difference is probably noise. A large gap in one direction, such as 15 fixed and 2 broken, is a real signal.
Handle nondeterminism
LLM apps often give different outputs for the same input. A single run is one sample from a distribution.
- Set temperature to 0 where the app allows it, but do not assume that makes output identical. Hosted models can still vary.
- For important comparisons, run each case several times and store the pass rate per case. Report the mean of those rates.
- If the same case passes in some runs and fails in others, flag it as flaky. Flaky cases are worth reading, because they often point to an unstable prompt or an ambiguous reference.
- Keep the repeat count the same across runs you compare.
Common errors when reading results
- Reporting only the overall score. Always show per-slice scores and sizes alongside it.
- Dropping crashed cases. Count them as failures, and report the error count separately.
- Tuning on the test split. Use the dev split while iterating. Run the test split rarely, and treat each look as spending a little of its value. Repeated peeking makes the test score optimistic.
- Comparing runs on different dataset versions. Check the version in the run metadata before comparing.
- Over-reading small slices. A slice with 10 cases can swing by 20 points on two cases.
- Chasing the metric. Rewriting prompts to fix the exact cases in the dev split can overfit to those cases. Check that fixes generalize, for example by writing a few new cases in the same slice.
What to do with the result
A report is useful when it ends in a decision. Typical outcomes:
- A slice is weak and the failures share a cause. Fix the app, then rerun the dev split and check
broken. - A slice has a wide interval. Add cases to that slice before drawing a conclusion.
- Many failures trace to the grader or the references. Repair them, bump the version, and rerun the baseline.
- Scores are stable and slices look healthy. Run the test split once, record the number, and ship.
Exercise
A run on 150 cases shows overall accuracy 0.88. The "multi_turn" slice has 15 cases, accuracy 0.60, and a 95% interval of 0.35 to 0.82. A teammate says multi-turn is clearly broken and wants to rewrite the app's conversation handling. What do you say, and what do you do next?
Show answer
The interval is wide because the slice is small, and 0.88 overall is hiding it. The data suggests multi-turn is weaker than average, but it does not show by how much. Read the 6 failing multi-turn outputs to find their cause and classify each as app, grader, case, or infrastructure error. If most are app errors with a shared pattern, the rewrite may be justified. Also add more multi-turn cases so the interval narrows before investing heavily.
Exercise
Prompt A passes 120 of 200 cases. Prompt B passes 126 of 200. A paired comparison shows B fixed 14 cases and broke 8. Is B clearly better? What should you check?
Show answer
Not clearly. The net gain is 6 cases (3 points), but 8 cases got worse, so B behaves differently from A rather than simply improving it. Read the 8 broken cases and look at their tags to see whether they cluster in an important slice. Rerun both prompts several times to see whether the fixed and broken cases are flaky. Choose B only if the regressions are acceptable and the gain holds across repeats.
Exercise
Your runner skips any case where the app raises an exception, and reports accuracy over the remaining cases. Why is this a problem, and how would you change run_eval?
Show answer
Crashes are usually concentrated in hard inputs, such as very long or malformed ones. Skipping them removes the hardest cases and inflates accuracy. Record the error, set the verdict to failed, and report the error count per slice. The run_eval in this chapter does this by setting passed to 0 when error is not None.