File size: 10,801 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
"""Tune, train and evaluate backbones for the Caveat classifier on data_v4_systems (brief steps 2-5).

Phases (run in order):
  tune    seed 42 only, validation only - test is never loaded
          fine-tuned: lr in {2e-5, 3e-5, 5e-5}, best epoch by val macro-F1; then the best lr again
                      with class-weighted cross-entropy (kept only if val macro-F1 doesn't drop AND
                      val prohibited recall improves)
          setfit:     num_iterations {10, 20} x num_epochs {1, 2}; each also scored with a
                      class-balanced logistic head, same keep rule
  final   best config per model, seeds 42/43/44, test_v4 (and the OOD set) evaluated once;
          per-row predictions saved; the seed-42 model is saved for export
  report  results_v4/report.md from the saved predictions (no training)

Usage: python train_v4.py --phase tune|final|report [--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, confusion_matrix, f1_score, recall_score

ROOT = Path(__file__).parent
LABELS = ["minimal_risk", "limited_risk", "high_risk", "prohibited"]  # matches published id2label
L2I = {l: i for i, l in enumerate(LABELS)}
PROHIB = L2I["prohibited"]
SEEDS = [42, 43, 44]

FINETUNE = {
    "distilbert": "distilbert-base-uncased",
    "legalbert": "nlpaueb/legal-bert-small-uncased",
}
SETFIT = {"setfit": "BAAI/bge-small-en-v1.5"}
LRS = [2e-5, 3e-5, 5e-5]
SETFIT_GRID = [(10, 1), (20, 1), (10, 2), (20, 2)]  # (num_iterations, num_epochs)
OOD = ROOT.parent / "eu-ai-act-risk-classification" / "synthetic" / "test.csv"

torch.set_num_threads(os.cpu_count())


# ---------- data ----------

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


def load_ood():
    df = pd.read_csv(OOD)
    df = df[df.label.isin(LABELS)]  # drops gpai / gpai_systemic_risk
    return df.text.tolist(), [L2I[l] for l in df.label], df.group.astype(str).tolist()


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


def val_scores(y, p):
    return {"macro_f1": f1_score(y, p, average="macro", labels=range(4), zero_division=0),
            "prohibited_recall": recall_score(y, p, labels=[PROHIB], average="macro", zero_division=0)}


def class_weights(y):
    counts = np.bincount(y, minlength=4)
    return torch.tensor(len(y) / (4 * counts), dtype=torch.float)


# ---------- fine-tuned models ----------

def train_finetune(ckpt, seed, lr, weighted, xtr, ytr, xva, yva, epochs=15, bs=16, log=""):
    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)
    enc = lambda xs: tok(xs, truncation=True, max_length=128, padding=True, return_tensors="pt")
    loss_fn = torch.nn.CrossEntropyLoss(weight=class_weights(ytr) if weighted else None)

    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, history = 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]
            logits = model(**enc([xtr[j] for j in b])).logits
            loss = loss_fn(logits, torch.tensor([ytr[j] for j in b]))
            loss.backward(); opt.step(); sched.step(); opt.zero_grad()
        v = val_scores(yva, predict(xva))
        history.append({k: round(x, 4) for k, x in v.items()})
        if best is None or v["macro_f1"] > best["macro_f1"]:
            best = {**v, "epoch": ep}
            state = {k: t.detach().clone() for k, t in model.state_dict().items()}
        print(f"  [{log}] epoch {ep:2d} val macro-F1 {v['macro_f1']:.3f} prohib recall {v['prohibited_recall']:.3f}", flush=True)
    model.load_state_dict(state)
    return model, tok, predict, {"val": best, "val_history": history}


# ---------- SetFit ----------

def train_setfit(ckpt, seed, iters, epochs, xtr, ytr):
    from datasets import Dataset
    from setfit import SetFitModel, Trainer, TrainingArguments
    from sklearn.linear_model import LogisticRegression

    seed_all(seed)
    model = SetFitModel.from_pretrained(ckpt, labels=list(range(4)))
    args = TrainingArguments(batch_size=16, num_epochs=epochs, num_iterations=iters, seed=seed,
                             output_dir=str(ROOT / "results_v4" / ".setfit_tmp"), save_strategy="no")
    Trainer(model=model, args=args, train_dataset=Dataset.from_dict({"text": xtr, "label": ytr})).train()
    # Same body, second head: class-balanced logistic regression on the train embeddings.
    balanced = LogisticRegression(class_weight="balanced", max_iter=1000).fit(model.encode(xtr), ytr)
    heads = {"default": model.model_head, "balanced": balanced}
    predict = lambda xs, head: heads[head].predict(model.encode(xs)).astype(int).tolist()
    return model, predict


# ---------- phases ----------

def keep_weighted(base, alt):
    """Brief step 3: keep the imbalance fix only if val macro-F1 doesn't drop and val prohibited recall improves."""
    return alt["macro_f1"] >= base["macro_f1"] and alt["prohibited_recall"] > base["prohibited_recall"]


def phase_tune(a, out):
    tdir = out / "tune"; tdir.mkdir(parents=True, exist_ok=True)
    xtr, ytr = load(a.data, a.suffix, "train"); xva, yva = load(a.data, a.suffix, "val")
    for m in a.models:
        f = tdir / f"{m}.json"
        if f.exists():
            print(f"skip tuning {m} (exists)"); continue
        runs = []
        if m in FINETUNE:
            for lr in LRS:
                t = time.time()
                _, _, _, r = train_finetune(FINETUNE[m], 42, lr, False, xtr, ytr, xva, yva, log=f"{m} lr {lr}")
                runs.append({"lr": lr, "weighted": False, **r, "seconds": round(time.time() - t)})
            base = max(runs, key=lambda r: r["val"]["macro_f1"])
            t = time.time()
            _, _, _, r = train_finetune(FINETUNE[m], 42, base["lr"], True, xtr, ytr, xva, yva, log=f"{m} lr {base['lr']} weighted")
            runs.append({"lr": base["lr"], "weighted": True, **r, "seconds": round(time.time() - t)})
            chosen = runs[-1] if keep_weighted(base["val"], runs[-1]["val"]) else base
            best = {"lr": chosen["lr"], "weighted": chosen["weighted"]}
        else:
            for iters, epochs in SETFIT_GRID:
                t = time.time()
                _, predict = train_setfit(SETFIT[m], 42, iters, epochs, xtr, ytr)
                secs = round(time.time() - t)
                for head in ("default", "balanced"):
                    runs.append({"num_iterations": iters, "num_epochs": epochs, "head": head,
                                 "val": val_scores(yva, predict(xva, head)), "seconds": secs})
                    print(f"  [{m} it{iters} ep{epochs} {head}] val {runs[-1]['val']}", flush=True)
            defaults = [r for r in runs if r["head"] == "default"]
            base = max(defaults, key=lambda r: r["val"]["macro_f1"])
            alt = next(r for r in runs if r["head"] == "balanced" and r["num_iterations"] == base["num_iterations"]
                       and r["num_epochs"] == base["num_epochs"])
            chosen = alt if keep_weighted(base["val"], alt["val"]) else base
            best = {k: chosen[k] for k in ("num_iterations", "num_epochs", "head")}
        f.write_text(json.dumps({"best": best, "runs": runs}, indent=2))
        print(f"TUNED {m}: {best}", flush=True)


def phase_final(a, out):
    fdir = out / "final"; fdir.mkdir(parents=True, exist_ok=True)
    xtr, ytr = load(a.data, a.suffix, "train"); xva, yva = load(a.data, a.suffix, "val")
    xte, yte = load(a.data, a.suffix, "test")
    ood = load_ood() if OOD.exists() else None
    for m in a.models:
        best = json.loads((out / "tune" / f"{m}.json").read_text())["best"]
        for s in SEEDS:
            f = fdir / f"{m}_seed{s}.json"
            if f.exists():
                print(f"skip {f.name} (exists)"); continue
            t = time.time()
            if m in FINETUNE:
                model, tok, predict, r = train_finetune(FINETUNE[m], s, best["lr"], best["weighted"],
                                                        xtr, ytr, xva, yva, log=f"{m} final s{s}")
                pred = predict
                if s == 42:
                    for w in model.parameters():  # legal-bert has non-contiguous weights; safetensors refuses them
                        w.data = w.data.contiguous()
                    d = out / "models" / m; model.save_pretrained(d); tok.save_pretrained(d)
            else:
                model, predict = train_setfit(SETFIT[m], s, best["num_iterations"], best["num_epochs"], xtr, ytr)
                pred = lambda xs: predict(xs, best["head"])
                r = {"val": val_scores(yva, pred(xva))}
                if s == 42:
                    model.save_pretrained(str(out / "models" / m))
            r.update(config=best, test_pred=pred(xte), seconds=round(time.time() - t))
            if ood:
                r["ood_pred"] = pred(ood[0])
            f.write_text(json.dumps(r, indent=2))
            p = r["test_pred"]
            print(f"FINAL {m} seed {s}: acc {accuracy_score(yte, p):.3f} "
                  f"macro-F1 {f1_score(yte, p, average='macro', labels=range(4), zero_division=0):.3f} "
                  f"prohib recall {recall_score(yte, p, labels=[PROHIB], average='macro', zero_division=0):.3f} "
                  f"({r['seconds']}s)", flush=True)


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--phase", choices=["tune", "final", "report"], required=True)
    ap.add_argument("--data", default="data_v4_systems")
    ap.add_argument("--suffix", default="v4")
    ap.add_argument("--out", default="results_v4")
    ap.add_argument("--models", nargs="+", default=[*FINETUNE, *SETFIT])
    a = ap.parse_args()
    out = ROOT / a.out; out.mkdir(exist_ok=True)
    if a.phase == "tune":
        phase_tune(a, out)
    elif a.phase == "final":
        phase_final(a, out)
    else:
        from report_v4 import write_report
        write_report(a, out)


if __name__ == "__main__":
    main()