File size: 10,759 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
"""Win / tie / loss decomposition of the Alternative Annotator Test (AAT).

The AAT headline (``alt_test_pooled.csv``, ANALYSIS.md §3.2) reports the winning
rate ω and the advantage probability ρ. Inside the test, an instance is credited
to the candidate whenever it scores *at least as well* as the held-out human
(the indicator is ``1[s_llm >= s_human]``), so ties count for the candidate.

That is the correct convention for the question the AAT asks — *can this model
stand in for a human annotator?* — but it makes ρ unusable for the different
question *is this model better than a human?*. This script keeps the AAT's
leave-one-out comparison and, instead of collapsing it into ρ, writes out the
raw counts ρ is built from:

    for each held-out human j and each instance i = (judgment, variable)
        s_llm   = mean tolerant agreement of the candidate with the 2 remaining humans
        s_human = mean tolerant agreement of human j  with the same 2 humans
        -> llm_better  (s_llm > s_human)
           tie         (s_llm = s_human)
           human_better(s_llm < s_human)

    rho_alttest   = (llm_better + tie)     / n    <- the AAT's own definition
    rho_tiebroken = (llm_better + tie / 2) / n    <- ties split evenly

A tie only means "same score against the same two references", so it is worth
being explicit about what it contains. Ties are split two independent ways:

  by score level (with two references a score is 0, ½ or 1)
      tie_at_1     both matched both references — everybody agrees
      tie_at_half  each matched exactly one reference; this can only happen
                   when the two reference experts contradict each other, which
                   caps every possible score at ½
      tie_at_0     neither matched either reference — equally wrong, and still
                   credited to the candidate by ρ

  by whether the candidate actually gave the held-out human's answer
      tie_same     candidate ≈ held-out human (they really do agree)
      tie_diff     candidate ≉ held-out human — they gave *different* answers
                   that happen to be equally close to the references, so ρ
                   records a candidate win on a genuine disagreement

``refs_disagree`` counts, for context, the comparisons whose two reference
experts do not agree with each other in the first place.

This does not need the upstream AltTest clone: it is a direct, auditable
re-implementation of the comparison the reference implementation performs, and
it reproduces the reference ρ to within 0.02 on every jurisdiction.

Usage
-----
    uv run python scripts/alt_test_decomposition.py \
        [--countries ge,sg,tw] [--out data/analysis/iaa]
"""

import argparse
import csv
import sys
from collections import defaultdict
from pathlib import Path

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,
    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")

COUNTS = (
    "refs_disagree", "llm_better", "human_better",
    "tie", "tie_same", "tie_diff", "tie_at_1", "tie_at_half", "tie_at_0",
)
COLUMNS = [
    "candidate", "country", "variant", "n_comparisons",
    *COUNTS,
    "rho_alttest", "rho_tiebroken",
]


def score(prediction: str, references: list[str], field: str) -> float:
    """Mean tolerant agreement — the AAT scoring function used in LEGEX."""
    return sum(values_agree(prediction, r, field) for r in references) / len(references)


def decompose(
    countries: list[str],
    model: str,
    gold_dir: Path | None = None,
    inference_dir: Path | None = None,
) -> list[dict]:
    """One row per (country, variant) with the win/tie/loss counts."""
    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}
    )

    # country -> case_id -> annotator -> {field: value}
    by_case: dict[str, dict[str, dict[str, dict[str, str]]]] = defaultdict(
        lambda: defaultdict(dict)
    )
    for (annotator, cc, case_id), fmap in humans.items():
        by_case[cc][case_id][annotator] = fmap
    candidate_labels = {(cc, case_id): fmap for (_, cc, case_id), fmap in candidate.items()}

    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 variant in ("all", "nontrivial"):
            counts: dict[str, int] = defaultdict(int)
            for case_id, case_annotators in by_case[cc].items():
                # Keep only judgments all three experts labelled, so every
                # leave-one-out comparison has exactly two reference annotators
                # (the reference implementation's min_humans_per_instance=2).
                if len(case_annotators) < 3:
                    continue
                names = sorted(case_annotators)
                llm_labels = candidate_labels.get((cc, case_id), {})
                # No candidate output for this judgment (e.g. Legora's empty
                # Georgia export): skip, mirroring the pooled AAT runner.
                if not llm_labels:
                    continue
                for field in fields:
                    human_values = {n: case_annotators[n].get(field, "") for n in names}
                    llm_value = llm_labels.get(field, "")
                    for held_out in names:
                        references = [human_values[n] for n in names if n != held_out]
                        # Non-trivial: drop comparisons whose reference is empty
                        # throughout — there is nothing to be right or wrong about.
                        if variant == "nontrivial" and not any(references):
                            continue
                        if not values_agree(references[0], references[1], field):
                            counts["refs_disagree"] += 1
                        s_human = score(human_values[held_out], references, field)
                        s_llm = score(llm_value, references, field)
                        if s_llm > s_human:
                            counts["llm_better"] += 1
                        elif s_llm < s_human:
                            counts["human_better"] += 1
                        else:
                            counts["tie"] += 1
                            counts[{1.0: "tie_at_1", 0.5: "tie_at_half"}.get(s_llm, "tie_at_0")] += 1
                            same = values_agree(llm_value, human_values[held_out], field)
                            counts["tie_same" if same else "tie_diff"] += 1
            n = counts["llm_better"] + counts["tie"] + counts["human_better"]
            if not n:
                continue
            rows.append({
                "candidate": model,
                "country": cc,
                "variant": variant,
                "n_comparisons": n,
                **{c: counts[c] for c in COUNTS},
                "rho_alttest": round((counts["llm_better"] + counts["tie"]) / n, 4),
                "rho_tiebroken": round((counts["llm_better"] + counts["tie"] / 2) / n, 4),
            })
    return rows


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    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("--out", type=Path, default=Path("data/analysis/iaa"),
                    help="output directory for alt_test_decomposition.csv")
    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")
    args = ap.parse_args()

    countries = [c.strip() for c in args.countries.split(",") if c.strip()]
    rows = [
        r for model in MODELS
        for r in decompose(countries, model, args.gold_dir, args.inference_dir)
    ]
    if not rows:
        raise SystemExit("no comparisons — need 3+ annotators in at least one country")

    out_csv = args.out / "alt_test_decomposition.csv"
    out_csv.parent.mkdir(parents=True, exist_ok=True)
    with out_csv.open("w", encoding="utf-8", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=COLUMNS)
        writer.writeheader()
        writer.writerows(rows)

    for model in MODELS:
        pooled: dict[str, int] = defaultdict(int)
        for r in rows:
            if r["candidate"] == model and r["variant"] == "all":
                pooled["n_comparisons"] += r["n_comparisons"]
                for key in COUNTS:
                    pooled[key] += r[key]
        n = pooled["n_comparisons"]
        if not n:
            continue
        print(
            f"{model:<30} n={n:<5} "
            f"better {pooled['llm_better']:>4} ({pooled['llm_better'] / n:.0%})  "
            f"tie {pooled['tie']:>4} ({pooled['tie'] / n:.0%})  "
            f"worse {pooled['human_better']:>4} ({pooled['human_better'] / n:.0%})  "
            f"rho={(pooled['llm_better'] + pooled['tie']) / n:.2f} "
            f"(ties split {(pooled['llm_better'] + pooled['tie'] / 2) / n:.2f})\n"
            f"{'':<30} ties: same answer as expert {pooled['tie_same']} "
            f"({pooled['tie_same'] / pooled['tie']:.0%}), different answer "
            f"{pooled['tie_diff']} ({pooled['tie_diff'] / pooled['tie']:.0%}); "
            f"at 1 {pooled['tie_at_1']}, at ½ {pooled['tie_at_half']}, at 0 {pooled['tie_at_0']}; "
            f"references conflict in {pooled['refs_disagree']} of {n} comparisons "
            f"({pooled['refs_disagree'] / n:.0%})"
        )
    print(f"decomposition -> {out_csv}")


if __name__ == "__main__":
    main()