code / scripts /alt_test_reference.py
anonymous
[code] Reproduction bundle.
2e511b5
Raw
History Blame Contribute Delete
14.3 kB
"""Run the Alternative Annotator Test (Calderon et al., ACL 2025) on LEGEX
using the authors' original implementation (https://github.com/nitaytech/AltTest),
"""
import argparse
import contextlib
import csv
import io
import json
import sys
import warnings
from pathlib import Path
warnings.filterwarnings("ignore", category=RuntimeWarning)
REPO_ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(REPO_ROOT))
from legex.analysis.countries import CORE_COUNTRIES
from legex.analysis.iaa import (
FREE_TEXT_FIELDS,
MIN_INSTANCES_TEST,
load_candidate_annotations,
load_human_annotations,
)
from legex.evaluation import values_agree
# The five released candidates the paper's AAT covers. The AAT was frozen
# before the harvey-2 ingest; adding it would change the shipped CSVs and
# ANALYSIS.md, so it stays out deliberately.
MODELS = ("gpt-5.4-mini", "gemini/gemini-3.1-flash-lite", "harvey", "legora-1", "legora-2")
def load_reference_alt_test(alttest_dir: Path):
"""Extract ``alt_test`` and its helpers from the authors' notebook.
"""
nb_path = alttest_dir / "alt_test_example.ipynb"
if not nb_path.exists():
raise SystemExit(
f"{nb_path} not found, clone https://github.com/nitaytech/AltTest "
"and pass its path via --alttest."
)
nb = json.loads(nb_path.read_text(encoding="utf-8"))
cells = ["".join(c["source"]) for c in nb["cells"] if c["cell_type"] == "code"]
ns: dict = {}
ran = 0
for src in cells:
if src.lstrip().startswith("import ") or "def alt_test(" in src:
exec(compile(src, str(nb_path), "exec"), ns)
ran += 1
if "alt_test" not in ns:
raise SystemExit(f"could not find alt_test() in {nb_path} ({ran} cells run)")
return ns["alt_test"]
def field_scoring_function(field: str):
"""Mean tolerant agreement of one prediction against remaining annotators
"""
def score(pred, annotations) -> float:
return sum(values_agree(pred, ann, field) for ann in annotations) / len(annotations)
return score
def run_reference(
alt_test,
countries: list[str],
model: str,
epsilon: float,
prompt_version: str = "v3",
source: str = "full_text",
gold_dir: Path | None = None,
inference_dir: Path | None = None,
) -> list[dict]:
humans = load_human_annotations(countries, gold_dir=gold_dir)
candidate = load_candidate_annotations(
countries, prompt_version, source, model, inference_dir=inference_dir
)
fields = sorted(
{
f
for fmap in humans.values()
for f in fmap
if f not in FREE_TEXT_FIELDS
}
)
rows: list[dict] = []
for cc in countries:
annotators = sorted({an for (an, c, _) in humans if c == cc})
if len(annotators) < 3:
print(f"[{cc}] only {len(annotators)} annotators — skipped", file=sys.stderr)
continue
for field in fields:
humans_annotations = {
an: {
cid: fmap.get(field, "")
for (a, c, cid), fmap in humans.items()
if a == an and c == cc
}
for an in annotators
}
llm_annotations = {
cid: fmap.get(field, "")
for (m, c, cid), fmap in candidate.items()
if c == cc
}
# Non-trivial replay (legex-iaa convention): drop instances every
# human left empty — an empty prediction ties those for free.
nontrivial_ids = {
cid
for cid in llm_annotations
if any(
humans_annotations[an].get(cid, "")
for an in annotators
if cid in humans_annotations[an]
)
}
result: dict = {"candidate": model, "country": cc, "field": field}
for variant, keep in (("", None), ("_nontrivial", nontrivial_ids)):
h = humans_annotations
llm = llm_annotations
if keep is not None:
h = {
an: {cid: v for cid, v in anns.items() if cid in keep}
for an, anns in humans_annotations.items()
}
llm = {cid: v for cid, v in llm_annotations.items() if cid in keep}
buf = io.StringIO()
try:
with contextlib.redirect_stdout(buf):
winning_rate, advantage_prob = alt_test(
llm_annotations=llm,
humans_annotations=h,
scoring_function=field_scoring_function(field),
epsilon=epsilon,
q_fdr=0.05,
min_humans_per_instance=2,
min_instances_per_human=MIN_INSTANCES_TEST,
)
except ZeroDivisionError:
# Every annotator fell below min_instances_per_human
result[f"winning_rate{variant}"] = ""
result[f"advantage_probability{variant}"] = ""
result[f"passes{variant}"] = ""
continue
result[f"winning_rate{variant}"] = round(winning_rate, 4)
result[f"advantage_probability{variant}"] = round(advantage_prob, 4)
result[f"passes{variant}"] = int(winning_rate >= 0.5)
rows.append(result)
return rows
def model_slug(model: str) -> str:
return model.replace("/", "_")
def write_csv(rows: list[dict], path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader()
w.writerows(rows)
def compare(rows: list[dict], ours_csv: Path) -> int:
"""Print cell-level pass/fail agreement with legex-iaa's CSV and return the
number of disagreeing cells (pass/fail decision, either variant)."""
if not ours_csv.exists():
print(f" (no {ours_csv} to compare against)", file=sys.stderr)
return 0
ours: dict[tuple[str, str], dict] = {}
with ours_csv.open(newline="") as f:
for r in csv.DictReader(f):
ours[(r["country"], r["field"])] = r
disagreements = 0
for row in rows:
key = (row["country"], row["field"])
mine = ours.get(key)
if mine is None:
continue
for variant, ours_col in (("passes", "passes"), ("passes_nontrivial", "passes_nontrivial")):
ref_pass = row[variant]
our_pass = mine.get(ours_col, "")
if our_pass == "" or ref_pass == "":
continue
if int(our_pass) != ref_pass:
disagreements += 1
print(
f" DIFF {key[0]}/{key[1]} [{variant}]: "
f"reference={'pass' if ref_pass else 'fail'} "
f"(wr={row[variant.replace('passes', 'winning_rate')]}), "
f"legex-iaa={'pass' if int(our_pass) else 'fail'} "
f"(wr={mine.get(variant.replace('passes', 'winning_rate'), '?')})"
)
return disagreements
def pooled_scoring(pred, annotations) -> float:
"""pred/annotations are (field, value) tuples, mean tolerant agreement."""
field, value = pred
return sum(values_agree(value, ann[1], field) for ann in annotations) / len(annotations)
def run_pooled(
alt_test, countries, model, epsilon, nontrivial=False,
gold_dir: Path | None = None, inference_dir: Path | None = None,
):
"""One alt-test per jurisdiction; instance = (judgment, variable) cell.
This is the SummEval convention of Calderon et al. (each summary x aspect
pair is one instance) and the paper's headline design: with 10 structured
fields x 19-30 shared judgments, every annotator contributes n >= 190
effective instances, so the paired t-test applies without the n<30 caveat.
"""
humans = load_human_annotations(countries, gold_dir=gold_dir)
candidate = load_candidate_annotations(
countries, "v3", "full_text", model, inference_dir=inference_dir
)
fields = sorted(
{f for fmap in humans.values() for f in fmap if f not in FREE_TEXT_FIELDS}
)
results = []
for cc in countries:
annotators = sorted({an for (an, c, _) in humans if c == cc})
if len(annotators) < 3:
print(f"[{cc}] only {len(annotators)} annotators — skipped", file=sys.stderr)
continue
humans_annotations = {
an: {
(cid, f): (f, fmap.get(f, ""))
for (a, c, cid), fmap in humans.items()
if a == an and c == cc
for f in fields
}
for an in annotators
}
llm_annotations = {
(cid, f): (f, fmap.get(f, ""))
for (m, c, cid), fmap in candidate.items()
if c == cc
for f in fields
}
if nontrivial:
keep = {
iid
for iid in llm_annotations
if any(
humans_annotations[an][iid][1]
for an in annotators
if iid in humans_annotations[an]
)
}
llm_annotations = {k: v for k, v in llm_annotations.items() if k in keep}
humans_annotations = {
an: {k: v for k, v in anns.items() if k in keep}
for an, anns in humans_annotations.items()
}
if not llm_annotations:
print(f"[{cc}] {model}: No candidate annotations, we skip it", file=sys.stderr)
continue
buf = io.StringIO()
with contextlib.redirect_stdout(buf):
try:
winning_rate, advantage_prob = alt_test(
llm_annotations=llm_annotations,
humans_annotations=humans_annotations,
scoring_function=pooled_scoring,
epsilon=epsilon,
q_fdr=0.05,
min_humans_per_instance=2,
min_instances_per_human=30,
)
except ZeroDivisionError:
print(f"[{cc}] {model}: too few paired instances, we skip", file=sys.stderr)
continue
results.append((cc, winning_rate, advantage_prob))
return results
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--alttest", type=Path, required=True,
help="path to a clone of https://github.com/nitaytech/AltTest")
ap.add_argument("--countries", default=",".join(CORE_COUNTRIES),
help="comma-separated country codes (default: the 8 core "
"jurisdictions, all with 3 independent annotators)")
ap.add_argument("--epsilon", type=float, default=0.2,
help="cost-benefit tolerance (0.2 = expert annotators)")
ap.add_argument("--out", type=Path, default=Path("data/analysis/iaa"),
help="output directory for the CSVs")
ap.add_argument("--gold-dir", type=Path, default=None,
help="read annotations from published goldenset JSONL under "
"this directory instead of the XLSX workbooks")
ap.add_argument("--inference-dir", type=Path, default=None,
help="read candidate predictions from published inference "
"JSONL under this directory instead of the working files")
ap.add_argument("--per-field", action="store_true",
help="additionally run the fine-grained per-(jurisdiction, field) "
"variant (diagnostic; 19-30 instances per test)")
args = ap.parse_args()
alt_test = load_reference_alt_test(args.alttest)
countries = [c.strip() for c in args.countries.split(",") if c.strip()]
# Paper headline, pooled per jurisdiction.
pooled_rows: list[dict] = []
for model in MODELS:
for variant, nt in (("", False), ("_nontrivial", True)):
for cc, wr, rho in run_pooled(
alt_test, countries, model, args.epsilon, nontrivial=nt,
gold_dir=args.gold_dir, inference_dir=args.inference_dir,
):
row = next(
(r for r in pooled_rows if r["candidate"] == model and r["country"] == cc),
None,
)
if row is None:
row = {"candidate": model, "country": cc}
pooled_rows.append(row)
row[f"omega{variant}"] = round(wr, 4)
row[f"rho{variant}"] = round(rho, 4)
row[f"passes{variant}"] = int(wr >= 0.5)
out_csv = args.out / "alt_test_pooled.csv"
write_csv(pooled_rows, out_csv)
for model in MODELS:
rows = [r for r in pooled_rows if r["candidate"] == model]
cells = " ".join(
f"{r['country']}: omega={r['omega']:.2f} rho={r['rho']:.2f}"
f" (non-triv {r['omega_nontrivial']:.2f}/{r['rho_nontrivial']:.2f})"
for r in rows
)
print(f"{model:<30} {cells}")
print(f"pooled results -> {out_csv}")
# Per-(jurisdiction, field) cells
if args.per_field:
for model in MODELS:
rows = run_reference(
alt_test, countries, model, args.epsilon,
gold_dir=args.gold_dir, inference_dir=args.inference_dir,
)
if not rows:
print(f"{model}: no per-field results", file=sys.stderr)
continue
csv_path = args.out / f"alt_test_reference_{model_slug(model)}.csv"
write_csv(rows, csv_path)
n_pass = sum(r["passes"] for r in rows if r["passes"] != "")
n_test = sum(1 for r in rows if r["passes"] != "")
print(f"{model}: per-field {n_pass}/{n_test} cells pass -> {csv_path}")
if __name__ == "__main__":
main()