File size: 14,314 Bytes
2e511b5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | """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()
|