File size: 6,726 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
"""Compare backbones for the Caveat in-browser classifier on the published
scenario-grouped split (train_v2 / val_v2 / test_v2).

Fine-tuned models use the same selection rule as the published checkpoint:
keep the epoch with the best validation macro-F1. SetFit has no per-epoch
selection, so it runs with fixed hyperparameters and val is only reported.

Usage: python compare.py [--seeds 42 43 44] [--models distilbert legalbert setfit]
"""
import argparse, json, os, random, time
from pathlib import Path

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

ROOT = Path(__file__).parent
DATA = ROOT / "data"
OUT = ROOT / "results"
LABELS = ["minimal_risk", "limited_risk", "high_risk", "prohibited"]  # matches published id2label
L2I = {l: i for i, l in enumerate(LABELS)}

FINETUNE = {
    "distilbert": "distilbert-base-uncased",
    "legalbert": "nlpaueb/legal-bert-small-uncased",
}
SETFIT = {"setfit": "BAAI/bge-small-en-v1.5"}

torch.set_num_threads(os.cpu_count())


def load(split):
    df = pd.read_csv(DATA / f"{split}_v2.csv")
    return df.text.tolist(), [L2I[l] for l in df.label]


def seed_all(s):
    random.seed(s); np.random.seed(s); torch.manual_seed(s)


def metrics(y, p):
    rep = classification_report(y, p, labels=range(4), target_names=LABELS, output_dict=True, zero_division=0)
    return {
        "accuracy": accuracy_score(y, p),
        "macro_f1": f1_score(y, p, average="macro", labels=range(4), zero_division=0),
        "prohibited_recall": rep["prohibited"]["recall"],
        "per_class": {l: {k: rep[l][k] for k in ("precision", "recall", "f1-score")} for l in LABELS},
        "confusion": confusion_matrix(y, p, labels=range(4)).tolist(),
    }


def run_finetune(name, ckpt, seed, epochs=15, lr=5e-5, bs=16):
    from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup

    seed_all(seed)
    tok = AutoTokenizer.from_pretrained(ckpt)
    model = AutoModelForSequenceClassification.from_pretrained(
        ckpt, num_labels=4, id2label=dict(enumerate(LABELS)), label2id=L2I)
    (xtr, ytr), (xva, yva), (xte, yte) = load("train"), load("val"), load("test")
    enc = lambda xs: tok(xs, truncation=True, max_length=128, padding=True, return_tensors="pt")

    def predict(xs):
        model.eval(); out = []
        with torch.no_grad():
            for i in range(0, len(xs), 64):
                out += model(**enc(xs[i:i + 64])).logits.argmax(-1).tolist()
        return out

    opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
    steps = epochs * ((len(xtr) + bs - 1) // bs)
    sched = get_linear_schedule_with_warmup(opt, int(0.1 * steps), steps)
    best, best_state, history = -1.0, None, []
    for ep in range(1, epochs + 1):
        model.train()
        idx = np.random.permutation(len(xtr))
        for i in range(0, len(idx), bs):
            b = idx[i:i + bs]
            loss = model(**enc([xtr[j] for j in b]), labels=torch.tensor([ytr[j] for j in b])).loss
            loss.backward(); opt.step(); sched.step(); opt.zero_grad()
        vf1 = f1_score(yva, predict(xva), average="macro", labels=range(4), zero_division=0)
        history.append(round(vf1, 4))
        if vf1 > best:
            best, best_ep = vf1, ep
            best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}
        print(f"  [{name} s{seed}] epoch {ep:2d} val macro-F1 {vf1:.3f}", flush=True)
    model.load_state_dict(best_state)
    res = metrics(yte, predict(xte))
    res.update(best_epoch=best_ep, val_macro_f1=best, val_history=history)
    return res


def run_setfit(name, ckpt, seed):
    from datasets import Dataset
    from setfit import SetFitModel, Trainer, TrainingArguments

    seed_all(seed)
    (xtr, ytr), (xva, yva), (xte, yte) = load("train"), load("val"), load("test")
    model = SetFitModel.from_pretrained(ckpt, labels=list(range(4)))
    args = TrainingArguments(batch_size=16, num_epochs=1, num_iterations=10, seed=seed)
    trainer = Trainer(model=model, args=args, train_dataset=Dataset.from_dict({"text": xtr, "label": ytr}))
    trainer.train()
    res = metrics(yte, [int(p) for p in model.predict(xte)])
    res["val_macro_f1"] = f1_score(yva, [int(p) for p in model.predict(xva)], average="macro", labels=range(4), zero_division=0)
    return res


def eval_published():
    """Sanity check: the published checkpoint on test_v2 should reproduce the card (76.5%)."""
    from transformers import AutoModelForSequenceClassification, AutoTokenizer
    ckpt = "Devseis/eu-ai-act-classifier-experiment"
    tok, model = AutoTokenizer.from_pretrained(ckpt), AutoModelForSequenceClassification.from_pretrained(ckpt).eval()
    xte, yte = load("test")
    with torch.no_grad():
        p = model(**tok(xte, truncation=True, max_length=128, padding=True, return_tensors="pt")).logits.argmax(-1).tolist()
    return metrics(yte, p)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--seeds", type=int, nargs="+", default=[42, 43, 44])
    ap.add_argument("--models", nargs="+", default=[*FINETUNE, *SETFIT])
    a = ap.parse_args()
    OUT.mkdir(exist_ok=True)

    pub = eval_published()
    print(f"published checkpoint on test_v2: acc {pub['accuracy']:.3f} macro-F1 {pub['macro_f1']:.3f} "
          f"prohibited recall {pub['prohibited_recall']:.3f}", flush=True)
    (OUT / "published.json").write_text(json.dumps(pub, indent=2))

    for m in a.models:
        for s in a.seeds:
            f = OUT / f"{m}_seed{s}.json"
            if f.exists():
                print(f"skip {f.name} (exists)"); continue
            t = time.time()
            r = run_finetune(m, FINETUNE[m], s) if m in FINETUNE else run_setfit(m, SETFIT[m], s)
            r["seconds"] = round(time.time() - t)
            f.write_text(json.dumps(r, indent=2))
            print(f"{m} seed {s}: acc {r['accuracy']:.3f} macro-F1 {r['macro_f1']:.3f} "
                  f"prohibited recall {r['prohibited_recall']:.3f} ({r['seconds']}s)", flush=True)

    rows = []
    for m in a.models:
        rs = [json.loads((OUT / f"{m}_seed{s}.json").read_text()) for s in a.seeds]
        row = {"model": m}
        for k in ("accuracy", "macro_f1", "prohibited_recall"):
            v = [r[k] for r in rs]
            row[k] = f"{np.mean(v):.3f} ± {np.std(v):.3f}"
        for l in LABELS[:3]:
            row[f"{l}_recall"] = f"{np.mean([r['per_class'][l]['recall'] for r in rs]):.3f}"
        rows.append(row)
    table = pd.DataFrame(rows).to_markdown(index=False)
    (OUT / "summary.md").write_text(table + "\n")
    print("\n" + table)


if __name__ == "__main__":
    main()