File size: 13,491 Bytes
28e3615
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Brief step 5: build the results report from the saved final-run predictions (no training).

Confidence intervals: 1,000 bootstrap resamples of test *scenarios* (all 3 rows of a scenario move
together). Each resample scores all 3 seeds on the same scenarios and averages them, so the interval
is for the seed-averaged metric.

For v5 (README 4b) two reports are written: `report.md` on the full test_v5, and
`report_test_v4_subset.md` on the test_v4 rows only, which also carries the v4 legal-bert results so
the published model, v4 and v5 are compared on identical rows.
"""
import json
from pathlib import Path

import numpy as np
import pandas as pd
from sklearn.metrics import accuracy_score, confusion_matrix, f1_score, recall_score

from train_v4 import FINETUNE, LABELS, L2I, OOD, PROHIB, SEEDS, SETFIT, load, load_ood

ROOT = Path(__file__).parent
SEVERE = {L2I["minimal_risk"], L2I["limited_risk"]}
PARAMS = {"distilbert": "66M", "legalbert": "35M", "setfit": "33M + logistic head", "published": "66M",
          "legalbert (v4)": "35M", "legalbert (v5)": "35M"}
N_BOOT = 1000
NEW = {v: ROOT / "relabel_audit" / f"new_scenarios_{v}.csv" for v in ("v4", "v5", "v6")}


def norm(t):
    return t.lower().rstrip(".")


def scenario_ids(data, suffix, texts):
    sc = pd.read_csv(ROOT / data / f"scenarios_{suffix}.csv")
    S = [norm(t) for t in sc.text]
    def sid(t):
        t = t.lower(); hits = [i for i, x in enumerate(S) if x in t]
        return max(hits, key=lambda i: len(S[i]))
    return [sid(t) for t in texts], S


def area(legal_basis):
    lb = legal_basis.lower()
    if "downstream" in lb: return "Downstream builders"
    if "annex i" in lb: return "Annex I products"
    if "not a safety component" in lb or "art. 50" in lb: return "Contrasts"
    if "omnibus" in lb: return "Omnibus prohibitions"
    if "6(3)" in lb: return "Art 6(3)"
    return "Other"


def new_scenarios(suffix):
    """{scenario text: (version, area)} for scenarios added in v4 and, from v5 on, v5."""
    out = {}
    versions = [v for v in NEW if v <= suffix]
    for v in versions:
        df = pd.read_csv(NEW[v]); df = df[df.label.isin(LABELS)]
        for t, lb, lab in zip(df.text, df.legal_basis, df.label):
            out[norm(t)] = (v, area(lb) if v == "v4" else lab)
    return out


def scores(y, p):
    y, p = np.asarray(y), np.asarray(p)
    r = recall_score(y, p, labels=range(4), average=None, zero_division=0)
    return {"accuracy": accuracy_score(y, p),
            "macro_f1": f1_score(y, p, average="macro", labels=range(4), zero_division=0),
            **{f"recall_{l}": r[i] for i, l in enumerate(LABELS)}}


def boot_ci(y, preds, groups, rng):
    """preds: list over seeds of per-row predictions. Returns {metric: (lo, hi)} and the resampled macro-F1s."""
    y = np.asarray(y); preds = [np.asarray(p) for p in preds]
    uniq = np.unique(groups); rows = {g: np.flatnonzero(np.asarray(groups) == g) for g in uniq}
    acc, f1 = [], []
    for _ in range(N_BOOT):
        idx = np.concatenate([rows[g] for g in rng.choice(uniq, len(uniq), replace=True)])
        acc.append(np.mean([accuracy_score(y[idx], p[idx]) for p in preds]))
        f1.append(np.mean([f1_score(y[idx], p[idx], average="macro", labels=range(4), zero_division=0) for p in preds]))
    q = lambda v: (np.percentile(v, 2.5), np.percentile(v, 97.5))
    return {"accuracy": q(acc), "macro_f1": q(f1)}, np.array(f1)


def ms(v):
    return f"{np.mean(v):.3f} ± {np.std(v):.3f}"


def published_preds(xs):
    import torch
    from transformers import AutoModelForSequenceClassification, AutoTokenizer
    ckpt = "Devseis/eu-ai-act-classifier-experiment"
    tok, model = AutoTokenizer.from_pretrained(ckpt), AutoModelForSequenceClassification.from_pretrained(ckpt).eval()
    with torch.no_grad():
        return model(**tok(xs, truncation=True, max_length=128, padding=True, return_tensors="pt")).logits.argmax(-1).tolist()


def build(a, out, xte, yte, runs, ood_runs, subset_note, fname, rng):
    """Write one report. runs / ood_runs: {name: [per-seed prediction lists]} aligned with xte / the OOD rows."""
    sids, S = scenario_ids(a.data, a.suffix, xte)
    new = new_scenarios(a.suffix)
    row_new = [new.get(S[i]) for i in sids]  # None = original v3 scenario
    finals = [m for m in runs if m in FINETUNE or m in SETFIT]

    L = []
    w = L.append
    w(f"# Caveat classifier — {a.suffix} results{subset_note[0]}\n")
    w(f"Test rows: {subset_note[1]} — **{len(yte)} rows / {len(set(sids))} scenarios**. "
      f"Models trained here: mean ± std over seeds {SEEDS}. `published` is the existing DistilBERT checkpoint "
      "(trained on v2, one model), shown as the old baseline. 95% CIs: scenario-level bootstrap, "
      f"{N_BOOT} resamples, of the seed-averaged metric.\n")

    w("## Configurations (chosen on validation, seed 42)\n")
    w("| Model | Config | Val macro-F1 (tuning) | Val prohibited recall (tuning) |\n|---|---|---|---|")
    for m in finals:
        t = json.loads((out / "tune" / f"{m}.json").read_text())
        match = [r for r in t["runs"] if all(r.get(k) == v for k, v in t["best"].items())][0]
        src = f" — {t['source']}" if "source" in t else ""
        w(f"| {m} | `{json.dumps(t['best'])}`{src} | {match['val']['macro_f1']:.3f} | {match['val']['prohibited_recall']:.3f} |")
    w("")

    w("## Test results\n")
    w("| Model | Params | Accuracy | 95% CI | Macro-F1 | 95% CI | **Prohibited recall** | High | Limited | Minimal |")
    w("|---|---|---|---|---|---|---|---|---|---|")
    boot = {}
    for m, preds in runs.items():
        sc = [scores(yte, p) for p in preds]
        ci, boot[m] = boot_ci(yte, preds, sids, rng)
        g = lambda k: ms([s[k] for s in sc]) if len(sc) > 1 else f"{sc[0][k]:.3f}"
        w(f"| {m} | {PARAMS.get(m, '')} | {g('accuracy')} | {ci['accuracy'][0]:.3f}–{ci['accuracy'][1]:.3f} | {g('macro_f1')} | "
          f"{ci['macro_f1'][0]:.3f}–{ci['macro_f1'][1]:.3f} | **{g('recall_prohibited')}** | {g('recall_high_risk')} | "
          f"{g('recall_limited_risk')} | {g('recall_minimal_risk')} |")

    names = list(runs)
    if len(names) > 1:
        w("\n### Pairwise macro-F1 differences (same bootstrap resamples)\n")
        w("| A − B | Mean difference | 95% CI | Clear? |\n|---|---|---|---|")
        for i in range(len(names)):
            for j in range(i + 1, len(names)):
                d = boot[names[i]] - boot[names[j]]
                lo, hi = np.percentile(d, [2.5, 97.5])
                w(f"| {names[i]} − {names[j]} | {d.mean():+.3f} | {lo:+.3f} to {hi:+.3f} | {'yes' if lo > 0 or hi < 0 else 'no (overlaps 0)'} |")

    w("\n## Errors on prohibited scenarios\n")
    n_pro = sum(1 for y in yte if y == PROHIB)
    w(f"Rows summed over seeds (this test set has {n_pro} prohibited rows / {n_pro // 3} scenarios per seed). "
      "**Severe** = a banned practice labelled `minimal_risk` or `limited_risk`. The rate column makes models with "
      "different seed counts comparable.\n")
    w("| Model | Severe rows | Severe rate | Scenarios with any severe row | → high_risk rows | Minimal/limited → prohibited rows |")
    w("|---|---|---|---|---|---|")
    for m, preds in runs.items():
        sev = [i for p in preds for i, y in enumerate(yte) if y == PROHIB and p[i] in SEVERE]
        hi = sum(1 for p in preds for i, y in enumerate(yte) if y == PROHIB and p[i] == L2I["high_risk"])
        fp = sum(1 for p in preds for i, y in enumerate(yte) if y in SEVERE and p[i] == PROHIB)
        w(f"| {m} | {len(sev)} / {n_pro * len(preds)} | {len(sev) / (n_pro * len(preds)):.3f} | {len({sids[i] for i in sev})} | {hi} | {fp} |")

    w("\n## limited_risk, per scenario\n")
    w("Correct rows out of 3 × seeds. `*` = scenario added in v5.\n")
    lim = sorted({s for s, y in zip(sids, yte) if y == L2I["limited_risk"]}, key=lambda s: (row_new[sids.index(s)] is not None, s))
    w("| Scenario | " + " | ".join(runs) + " | Most common wrong answer |\n|---|" + "---|" * (len(runs) + 1))
    for s in lim:
        rows = [i for i, x in enumerate(sids) if x == s]
        cells, wrong = [], []
        for preds in runs.values():
            cells.append(f"{sum(p[i] == L2I['limited_risk'] for p in preds for i in rows)}/{len(rows) * len(preds)}")
            wrong += [LABELS[p[i]] for p in preds for i in rows if p[i] != L2I["limited_risk"]]
        mark = "*" if row_new[rows[0]] and row_new[rows[0]][0] == "v5" else ""
        top = pd.Series(wrong).value_counts().idxmax() if wrong else "–"
        w(f"| {mark}{S[s][:90]} | " + " | ".join(cells) + f" | {top} |")

    w("\n## Confusion matrices (summed over seeds; rows = true, columns = predicted)\n")
    short = ["minimal", "limited", "high", "prohib"]
    for m, preds in runs.items():
        C = sum(confusion_matrix(yte, p, labels=range(4)) for p in preds)
        w(f"**{m}**\n\n| true \\ pred | " + " | ".join(short) + " |\n|---|---|---|---|---|")
        for k in range(4):
            w(f"| {short[k]} | " + " | ".join(str(v) for v in C[k]) + " |")
        w("")

    w("## Subgroups (accuracy, mean over seeds)\n")
    w("The new-scenario groups are tiny: treat them as spot checks, not measurements.\n")
    groups = {"Original v3 scenarios": [r is None for r in row_new]}
    for v in sorted({r[0] for r in row_new if r}):
        groups[f"New {v} scenarios"] = [bool(r) and r[0] == v for r in row_new]
        for ar in sorted({r[1] for r in row_new if r and r[0] == v}):
            groups[f"  {v}: {ar}"] = [r == (v, ar) for r in row_new]
    w("| Subgroup | Rows / scenarios | " + " | ".join(runs) + " |\n|---|---|" + "---|" * len(runs))
    for gname, mask in groups.items():
        mask = np.array(mask); yy = np.array(yte)[mask]
        cells = [f"{np.mean([accuracy_score(yy, np.array(p)[mask]) for p in preds]):.3f}" for preds in runs.values()]
        w(f"| {gname} | {mask.sum()} / {len({s for s, k in zip(sids, mask) if k})} | " + " | ".join(cells) + " |")

    if ood_runs:
        xo, yo, go = load_ood()
        w("\n## Out-of-distribution check (synthetic v2.2 test set, GPAI rows dropped)\n")
        w(f"**{len(yo)} rows**, labels: " + ", ".join(f"{LABELS[k]} {sum(1 for y in yo if y == k)}" for k in range(4)) +
          ". Written in a different style by a different generator. CIs resample by the file's `group` column.\n")
        w("| Model | Accuracy | 95% CI | Macro-F1 | 95% CI | Prohibited recall | Limited recall | Severe rows |")
        w("|---|---|---|---|---|---|---|---|")
        for m, preds in ood_runs.items():
            sc = [scores(yo, p) for p in preds]
            ci, _ = boot_ci(yo, preds, go, rng)
            g = lambda k: ms([s[k] for s in sc]) if len(sc) > 1 else f"{sc[0][k]:.3f}"
            sev = sum(1 for p in preds for i, y in enumerate(yo) if y == PROHIB and p[i] in SEVERE)
            w(f"| {m} | {g('accuracy')} | {ci['accuracy'][0]:.3f}–{ci['accuracy'][1]:.3f} | {g('macro_f1')} | "
              f"{ci['macro_f1'][0]:.3f}–{ci['macro_f1'][1]:.3f} | {g('recall_prohibited')} | {g('recall_limited_risk')} | {sev} |")

    (out / fname).write_text("\n".join(L) + "\n")
    print("\n".join(L))


def write_report(a, out):
    rng = np.random.default_rng(0)
    xte, yte = load(a.data, a.suffix, "test")
    has_ood = OOD.exists()

    pf = out / f"published_{a.suffix}.json"
    if not pf.exists():
        pub = {"test_pred": published_preds(xte)}
        if has_ood: pub["ood_pred"] = published_preds(load_ood()[0])
        pf.write_text(json.dumps(pub))
    pub = json.loads(pf.read_text())

    models = {m: [json.loads((out / "final" / f"{m}_seed{s}.json").read_text()) for s in SEEDS]
              for m in a.models if (out / "final" / f"{m}_seed{SEEDS[-1]}.json").exists()}
    runs = {**{m: [r["test_pred"] for r in rs] for m, rs in models.items()}, "published": [pub["test_pred"]]}
    ood_runs = {**{m: [r["ood_pred"] for r in rs] for m, rs in models.items()}, "published": [pub["ood_pred"]]} if has_ood else None

    build(a, out, xte, yte, runs, ood_runs, ("", f"`{a.data}/test_{a.suffix}.csv`"), "report.md", rng)
    if a.suffix == "v4":
        return

    # previous-version subset: drop test rows of scenarios added in this version, and add the previous
    # version's legal-bert runs on the same rows (e.g. v6 report -> test_v5 rows, compared with v5)
    prev = f"v{int(a.suffix[1:]) - 1}"
    df = pd.read_csv(NEW[a.suffix]); later = {norm(t) for t in df[df.split == "test"].text}
    keep = [i for i, t in enumerate(xte) if not any(c in t.lower() for c in later)]
    xp, yp = [xte[i] for i in keep], [yte[i] for i in keep]
    sub = {m: [[p[i] for i in keep] for p in preds] for m, preds in runs.items()}
    px, _ = load(f"data_{prev}_systems", prev, "test")
    assert set(px) == set(xp), "subset rows must equal the previous test set"
    prev_final = ROOT / f"results_{prev}" / "final"
    name = f"legalbert ({prev})"
    if (prev_final / f"legalbert_seed{SEEDS[-1]}.json").exists():
        runs_prev = [json.loads((prev_final / f"legalbert_seed{s_}.json").read_text()) for s_ in SEEDS]
        by_text = [dict(zip(px, r["test_pred"])) for r in runs_prev]
        sub[name] = [[d[t] for t in xp] for d in by_text]
        if ood_runs:
            ood_runs = {**ood_runs, name: [r["ood_pred"] for r in runs_prev]}
    build(a, out, xp, yp, sub, ood_runs, (f" — test_{prev} subset", f"`{a.data}/test_{a.suffix}.csv` restricted to the test_{prev} rows"),
          f"report_test_{prev}_subset.md", rng)