Objectives: LO-7.1, LO-7.2, LO-7.3, LO-7.4
Prerequisites: the Module 7 reading
Time: about 2.5 hours
In this lab you evaluate two versions of the dispatcher’s prompt, A and B. The data set has 40 hand-written ticket cases. Each case stores its ticket, its expected label, its kind (typical, edge, or adversarial), its split (development or held out), and three responses from each version. A second file holds 30 paired verdicts: a person’s and a model grader’s pass or fail for the same reply. You split the cases, grade the responses, measure the grader’s agreement with the person, compute Wilson’s interval, and compare A with B by a paired bootstrap.
No cell calls a real model. Every response and verdict was written for this course and is labeled as illustrative, so the numbers you compute describe this data set only.
Use a fresh kernel and run the cells from top to bottom. Fill each answer cell, then run its check. The checks raise errors until their exercises are complete. This notebook runs locally.
Setup¶
import sys
from collections import Counter
from math import isclose, sqrt
from random import Random
import re
from statistics import mean
from promptlab import load_json
cases = load_json("evaluation/cases.json")
judgments = load_json("evaluation/judgments.json")
import matplotlib
import matplotlib.pyplot as plt
print("Python", sys.version.split()[0])Inspect provenance and coverage¶
Before you look at version B’s responses, predict which kind of error an exact grader catches.
Keep the holdout split for the final check.
print(cases[0]["source"])
print(Counter(row["kind"] for row in cases))
print(Counter(row["split"] for row in cases))Exercise L7.1 (LO-7.1, LO-7.4, ★★, about 25 minutes)¶
Split by case rather than response. Return a pair (dev, holdout) of lists of cases, by
each case’s split field, without dropping or duplicating a case. The only split labels are
"dev" and "holdout". Raise ValueError if an id repeats or a split label is unfamiliar.
In your notes, add one case of each kind with the reason it belongs.
def split_rows(rows):
raise NotImplementedError("L7.1")dev, holdout = split_rows(cases)
assert (len(dev), len(holdout)) == (30, 10), \
f"Expected 30 development and 10 held-out cases; got {len(dev)} and {len(holdout)}."
assert {x["id"] for x in dev}.isdisjoint({x["id"] for x in holdout}), \
"A case appears in both splits; put each case in exactly one."
assert {"typical", "edge", "adversarial"} == {r["kind"] for r in cases}, \
"The bundled cases should include typical, edge, and adversarial kinds."
for bad, problem in (([cases[0], cases[0]], "a repeated id"),
([{**cases[0], "split": "test"}], "an unfamiliar split label")):
try:
split_rows(bad)
except ValueError:
continue
raise AssertionError(f"Raise ValueError for {problem}.")
print("passed")Exercise L7.2 (LO-7.2, ★★, about 25 minutes)¶
Separate format from correctness. Return a dictionary with two booleans, "format" and
"correct". The format passes when the entire text is Label: followed by repair,
billing, or account, with nothing before or after. A response is correct when it passes
the format and its queue equals expected.
def grade(text, expected):
raise NotImplementedError("L7.2")assert grade("Label: repair", "billing") == {"format": True, "correct": False}, \
"A well-formed label for the wrong queue passes format but isn't correct."
assert grade("billing", "billing") == {"format": False, "correct": False}, \
"Without the Label: prefix, the format fails, so the answer isn't correct."
assert grade("Label: billing", "billing") == {"format": True, "correct": True}, \
"The exact label for the expected queue is correct."
for text in ("Label: billing.", "Label: billing\n", "Label: billing, I think"):
assert grade(text, "billing") == {"format": False, "correct": False}, \
f"Match the entire text: {text!r} has extra characters after the label."
print("passed")Exercise L7.3 (LO-7.2, ★★, about 25 minutes)¶
Measure judge agreement. Each row has a "human" and a "judge" boolean: the person’s and
the model grader’s verdict on the same reply. Return a pair (observed, kappa): the share of
rows on which they agree, and Cohen’s kappa, which corrects that share for chance agreement.
Raise ValueError for zero rows, and return None for kappa when chance agreement is 1.
def agreement(rows):
raise NotImplementedError("L7.3")observed, kappa = agreement(judgments)
assert isclose(observed, 0.8), f"The person and the judge agree on 24 of 30 rows; got {observed}."
assert 0 < kappa < observed, \
f"With chance agreement above 0, kappa lies between 0 and the observed share; got {kappa}."
four = [{"human": h, "judge": j}
for h, j in ((True, True), (True, False), (False, False), (False, False))]
result = agreement(four)
assert isclose(result[0], 0.75) and isclose(result[1], 0.5), \
f"Count agreeing to fail as well as to pass: expected (0.75, 0.5) here; got {result!r}."
result = agreement([{"human": True, "judge": True}])
assert result == (1, None), \
f"Chance agreement is 1 here, so kappa is undefined: return None; got {result!r}."
try:
agreement([])
except ValueError:
pass
except Exception as error:
raise AssertionError(f"Raise ValueError for zero rows, not {type(error).__name__}.") from error
else:
raise AssertionError("Raise ValueError for zero rows.")
print("passed")Exercise L7.4 (LO-7.3, ★★, about 25 minutes)¶
Implement Wilson’s score interval. Return the lower and upper ends of the interval for
successes passes in total independent cases, from the reading’s formula, using z. Count
one verdict per case: repeated runs of one case aren’t independent trials. Floating-point
roundoff can push an end slightly outside the range from 0 to 1, so clamp each end to that
range. Raise ValueError for a total that isn’t positive, or a successes count outside the
range from 0 to total.
def wilson(successes, total, z=1.96):
raise NotImplementedError("L7.4")low, high = wilson(8, 10)
assert 0.48 < low < 0.50 and 0.94 < high < 0.95, \
f"Recheck the center and half-width from the reading for 8 of 10; got ({low:.4f}, {high:.4f})."
low, high = wilson(8, 10, z=1.645)
assert 0.53 < low < 0.55 and 0.92 < high < 0.94, \
f"Use the z argument instead of a fixed 1.96; got ({low:.4f}, {high:.4f}) for z = 1.645."
assert isclose(wilson(0, 6)[0], 0, abs_tol=1e-12), \
"With no passes, the lower end is 0: clamp any roundoff below 0."
assert isclose(wilson(6, 6)[1], 1, abs_tol=1e-12), \
"With every case passing, the upper end is 1: clamp any roundoff above 1."
for args in ((1, 0), (-1, 5), (6, 5)):
try:
wilson(*args)
except ValueError:
continue
except Exception as error:
raise AssertionError(f"wilson{args} should raise ValueError, not "
f"{type(error).__name__}.") from error
raise AssertionError(f"wilson{args} should raise ValueError: the count or total is invalid.")
print("passed")Exercise L7.5 (LO-7.3, LO-7.4, ★★, about 25 minutes)¶
Bootstrap pairs and read the plot. a[i] and b[i] are prompts A’s and B’s scores for the
same case. Return (estimate, lower, upper), where the estimate is the mean of the differences
b[i] - a[i]. Create Random(seed) inside the function, so every call gives the same result.
For each of repeats resamples, draw len(a) differences with replacement and take their
mean. Sort the means, and return the ones at positions int(0.025 * (repeats - 1)) and
int(0.975 * (repeats - 1)) as the bounds.
The check cell then compares A and B on the development cases, and inspects the held-out cases once. In its plot, the horizontal axis is B minus A, as a difference in the share of runs passed. Each line is a 95% paired bootstrap interval, and each dot is its estimate. Notice whether each interval crosses the dashed line at 0.
def paired(a, b, repeats=2000, seed=101):
raise NotImplementedError("L7.5")result = paired([0, 0], [1, 1])
assert result == (1, 1, 1), f"Every case improves by 1, so expect (1, 1, 1); got {result!r}."
a, b = [0, 1/3, 2/3, 1], [1/3, 2/3, 1, 1]
estimate, lower, upper = paired(a, b)
assert isclose(estimate, 0.25), f"The estimate is the mean of b[i] - a[i]; got {estimate}."
assert 0 <= lower <= estimate <= upper <= 1/3 + 1e-9, \
("Resample the per-case differences, so each case's two scores stay together. Every "
f"difference here is 0 or 1/3, so the bounds lie in [0, 1/3]; got ({lower}, {upper}).")
spread = [1 / (k + 2) for k in range(10)]
assert paired([0] * 10, spread) == paired([0] * 10, spread), \
"Create a fresh Random(seed) on every call, so repeated calls return the same result."
def case_scores(rows, version):
return [mean(grade(reply, r["expected"])["correct"] for reply in r[version]) for r in rows]
fig, ax = plt.subplots(figsize=(7, 3))
for position, (label, rows) in enumerate([("Development", dev), ("Held out", holdout)]):
estimate, lower, upper = paired(case_scores(rows, "A"), case_scores(rows, "B"))
assert lower <= estimate <= upper, \
f"{label}: the estimate should lie in its interval; got {estimate}, [{lower}, {upper}]."
ax.hlines(position, lower, upper, color="black")
ax.plot(estimate, position, "o", color="tab:blue")
print(label, f"change={estimate:.3f}, interval [{lower:.3f}, {upper:.3f}]")
ax.set_yticks([0, 1], ["Development", "Held out"])
ax.axvline(0, color="0.5", linestyle="--")
ax.set_xlabel("B minus A (difference in share of runs passed)")
ax.set_title("Paired case intervals on illustrative responses")
plt.show()
print("passed")Summary¶
You split the cases by case, so no ticket’s runs land on both sides of the held-out divide.
You graded format and correctness separately, and measured a model grader’s agreement with a person by percent agreement and by Cohen’s kappa.
You computed Wilson’s interval for one verdict per independent case, and compared A with B by a paired bootstrap that resamples whole cases, on illustrative responses.