File size: 14,328 Bytes
e5f3768
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Production Trainer for Tamarillo/groundedness-guard (End-to-End Token-Span MIL + EMA).

Architecture: Standard `ModernBertForTokenClassification` (`0=supported, 1=hallucinated`),
zero `trust_remote_code`, 100% compatible with `KRLabsOrg/lettucedect-v2-mmbert-base` AND ONNX!
"""

from __future__ import annotations

import argparse
import contextlib
import gc
import json
import math
import os
import time
from collections import defaultdict
from pathlib import Path
from typing import Any

import numpy as np
import torch
import torch.nn as nn
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score
from torch.utils.data import DataLoader
from transformers import (
    AutoConfig,
    AutoModelForTokenClassification,
    AutoTokenizer,
    get_cosine_schedule_with_warmup,
    set_seed,
)

from train_mg_cpil import (
    LengthBucketBatchSampler,
    ListDataset,
    _encode_dataset,
    _load_jsonl,
    _topk_lme_mil,
    make_collate_fn,
)
from train_r2_tok import TOK_ID2LABEL, TOK_LABEL2ID, _clean_reinit_tok_head
from train_r3_tok import ModelEMA, compute_tok_mil_loss_v2


@torch.no_grad()
def evaluate_tok_v2(model: nn.Module, val_loader: DataLoader, device: str, use_bf16: bool) -> dict[str, float]:
    model.eval()
    p_max_list, p_mil_list, y_list = [], [], []
    dtype = torch.bfloat16 if use_bf16 else torch.float16
    for batch in val_loader:
        input_ids = batch["input_ids"].to(device, non_blocking=True)
        attention_mask = batch["attention_mask"].to(device, non_blocking=True)
        hyp_mask = batch["hyp_mask"].to(device, non_blocking=True)
        with torch.amp.autocast("cuda", dtype=dtype) if device == "cuda" else contextlib.nullcontext():
            logits = model(input_ids=input_ids, attention_mask=attention_mask).logits.float()
        probs_hal = torch.softmax(logits, dim=-1)[:, :, 1]
        max_hal = probs_hal.masked_fill(hyp_mask < 0.5, 0.0).max(dim=1).values
        p_cons_max = (1.0 - max_hal).cpu().numpy()

        z_hal = logits[:, :, 1] - logits[:, :, 0]
        z_mil, _ = _topk_lme_mil(z_hal, hyp_mask, k=6, beta=2.0)
        p_cons_mil = (1.0 - torch.sigmoid(z_mil)).cpu().numpy()

        p_max_list.append(p_cons_max)
        p_mil_list.append(p_cons_mil)
        y_list.append(batch["labels"].numpy())

    p1 = np.concatenate(p_max_list, axis=0)
    p1_mil = np.concatenate(p_mil_list, axis=0)
    y = np.concatenate(y_list, axis=0).astype(int)
    pred = (p1 >= 0.5).astype(int)
    pred_mil = (p1_mil >= 0.5).astype(int)
    acc = float(accuracy_score(y, pred))
    macro_f1 = float(f1_score(y, pred, average="macro", zero_division=0))
    macro_f1_mil = float(f1_score(y, pred_mil, average="macro", zero_division=0))
    hal_f1 = float(f1_score(1 - y, 1 - pred, zero_division=0))
    cons_f1 = float(f1_score(y, pred, zero_division=0))
    auc = float(roc_auc_score(y, p1)) if len(set(y.tolist())) == 2 else 0.5
    auc_mil = float(roc_auc_score(y, p1_mil)) if len(set(y.tolist())) == 2 else 0.5
    sel = 0.225 * macro_f1 + 0.225 * macro_f1_mil + 0.275 * auc + 0.275 * auc_mil
    model.train()
    return {
        "accuracy": round(acc, 5),
        "macro_f1": round(macro_f1, 5),
        "macro_f1_mil": round(macro_f1_mil, 5),
        "hal_f1": round(hal_f1, 5),
        "consistent_f1": round(cons_f1, 5),
        "roc_auc": round(auc, 5),
        "roc_auc_mil": round(auc_mil, 5),
        "selection_score": round(sel, 5),
    }


def _run_stage(
    stage_name: str,
    model: nn.Module,
    train_enc: list[dict[str, Any]],
    val_loader: DataLoader,
    pad_id: int,
    tokenizer: Any,
    out_dir: Path,
    device: str,
    use_bf16: bool,
    epochs: float,
    lr: float,
    batch_size: int,
    grad_accum: int,
    paired: bool,
    use_ema: bool,
    seed: int,
    best_score: float,
    best_metrics: dict[str, float],
    val_history: list[dict[str, Any]],
) -> tuple[float, dict[str, float]]:
    sampler = LengthBucketBatchSampler(train_enc, batch_size=batch_size, paired=paired, seed=seed)
    loader = DataLoader(
        ListDataset(train_enc),
        batch_sampler=sampler,
        collate_fn=make_collate_fn(pad_id, with_spans=True),
        num_workers=4,
        pin_memory=(device == "cuda"),
    )

    steps_per_epoch = max(1, math.ceil(len(loader) / grad_accum))
    total_steps = max(1, int(math.ceil(steps_per_epoch * epochs)))
    warmup_steps = max(150, int(0.10 * total_steps))
    eval_every = max(250, steps_per_epoch // 3)

    no_decay = ("bias", "LayerNorm.weight", "norm.weight")
    param_groups = [
        {"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], "lr": lr, "weight_decay": 0.01},
        {"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], "lr": lr, "weight_decay": 0.0},
    ]
    optimizer = torch.optim.AdamW(param_groups, betas=(0.9, 0.999), eps=1e-8)
    scheduler = get_cosine_schedule_with_warmup(optimizer, num_warmup_steps=warmup_steps, num_training_steps=total_steps)
    amp_dtype = torch.bfloat16 if use_bf16 else torch.float16
    scaler = torch.amp.GradScaler("cuda", enabled=(device == "cuda" and not use_bf16))
    ema: ModelEMA | None = None

    print(f"[{stage_name}] Start Tok-Span MIL: rows={len(train_enc):,}, steps={total_steps}, warmup={warmup_steps}, lr={lr}, ema={use_ema}")
    t0 = time.time()
    global_step = 0
    running = defaultdict(float)
    running_n = 0
    model.train()
    optimizer.zero_grad(set_to_none=True)

    for ep in range(int(math.ceil(epochs))):
        sampler.set_epoch(ep)
        accum_cnt = 0
        for step_idx, batch in enumerate(loader):
            if global_step >= total_steps:
                break
            input_ids = batch["input_ids"].to(device, non_blocking=True)
            attention_mask = batch["attention_mask"].to(device, non_blocking=True)
            labels = batch["labels"].to(device, non_blocking=True)

            with torch.amp.autocast("cuda", dtype=amp_dtype) if device == "cuda" else contextlib.nullcontext():
                logits = model(input_ids=input_ids, attention_mask=attention_mask).logits

            loss, st = compute_tok_mil_loss_v2(
                tok_logits_2=logits,
                labels=labels,
                group_ids=batch["group_ids"].to(device, non_blocking=True),
                hyp_mask=batch["hyp_mask"].to(device, non_blocking=True),
                span_labels=batch["span_labels"].to(device, non_blocking=True),
                use_pair_rank=paired,
                label_smooth=0.03,
            )
            for k, v in st.items():
                running[k] += v
            running["loss"] += float(loss.item())
            running_n += 1

            scaled = loss / grad_accum
            if scaler.is_enabled():
                scaler.scale(scaled).backward()
            else:
                scaled.backward()
            accum_cnt += 1

            if accum_cnt == grad_accum or (step_idx + 1 == len(loader)):
                if scaler.is_enabled():
                    scaler.unscale_(optimizer)
                gnorm = float(torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0).item())
                if scaler.is_enabled():
                    scaler.step(optimizer)
                    scaler.update()
                else:
                    optimizer.step()
                scheduler.step()
                optimizer.zero_grad(set_to_none=True)
                accum_cnt = 0
                global_step += 1

                if use_ema:
                    if global_step == warmup_steps:
                        ema = ModelEMA(model, decay=0.996)
                    elif ema is not None:
                        ema.update(model)

                if global_step % 200 == 0 or global_step == 10:
                    avg = {k: round(v / max(1, running_n), 4) for k, v in running.items()}
                    print(
                        f"[{stage_name} {global_step:4d}/{total_steps}] lr={scheduler.get_last_lr()[0]:.2e} "
                        f"gnorm={gnorm:.2f} elapsed={time.time() - t0:.0f}s {avg}",
                        flush=True,
                    )
                    running.clear()
                    running_n = 0

                if global_step % eval_every == 0 or global_step == total_steps:
                    vm = evaluate_tok_v2(model, val_loader, device, use_bf16)
                    vm["stage"] = stage_name
                    vm["step"] = global_step
                    vm["weights"] = "raw"
                    val_history.append(vm)
                    print(f"[val {stage_name} RAW @ {global_step}] {json.dumps(vm)}", flush=True)
                    if vm["selection_score"] > best_score and stage_name == "stage2":
                        best_score = vm["selection_score"]
                        best_metrics = dict(vm)
                        model.save_pretrained(str(out_dir), safe_serialization=True)
                        tokenizer.save_pretrained(str(out_dir))
                        print(f"[ckpt] New best RAW selection_score={best_score:.5f} saved!", flush=True)

                    if ema is not None and stage_name == "stage2":
                        bak = ema.swap_in(model)
                        vm_e = evaluate_tok_v2(model, val_loader, device, use_bf16)
                        vm_e["stage"] = stage_name
                        vm_e["step"] = global_step
                        vm_e["weights"] = "ema"
                        val_history.append(vm_e)
                        print(f"[val {stage_name} EMA @ {global_step}] {json.dumps(vm_e)}", flush=True)
                        if vm_e["selection_score"] > best_score:
                            best_score = vm_e["selection_score"]
                            best_metrics = dict(vm_e)
                            model.save_pretrained(str(out_dir), safe_serialization=True)
                            tokenizer.save_pretrained(str(out_dir))
                            print(f"[ckpt] New best EMA selection_score={best_score:.5f} saved!", flush=True)
                        ema.restore(model, bak)

    return best_score, best_metrics


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--base-model", type=str, required=True)
    parser.add_argument("--data-dir", type=str, required=True)
    parser.add_argument("--output-dir", type=str, required=True)
    parser.add_argument("--max-length", type=int, default=3584)
    parser.add_argument("--s1-lr", type=float, default=2.5e-5)
    parser.add_argument("--s2-lr", type=float, default=1.8e-5)
    parser.add_argument("--s2-epochs", type=float, default=1.5)
    parser.add_argument("--batch-size", type=int, default=16)
    parser.add_argument("--grad-accum", type=int, default=4)
    parser.add_argument("--seed", type=int, default=42)
    args = parser.parse_args()

    os.environ.setdefault("HF_HOME", "/tmp/hf")
    os.environ["TOKENIZERS_PARALLELISM"] = "true"
    os.environ["TORCH_COMPILE_DISABLE"] = "1"
    if hasattr(torch, "_dynamo"):
        torch._dynamo.config.disable = True
    set_seed(args.seed)

    data_dir = Path(args.data_dir)
    out_dir = Path(args.output_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    tokenizer = AutoTokenizer.from_pretrained(args.base_model, use_fast=True)
    cfg = AutoConfig.from_pretrained(args.base_model, num_labels=2, id2label=TOK_ID2LABEL, label2id=TOK_LABEL2ID)
    if hasattr(cfg, "reference_compile"):
        cfg.reference_compile = False

    model = AutoModelForTokenClassification.from_pretrained(args.base_model, config=cfg, ignore_mismatched_sizes=True)
    _clean_reinit_tok_head(model)
    if hasattr(model, "gradient_checkpointing_enable"):
        model.gradient_checkpointing_enable()

    device = "cuda" if torch.cuda.is_available() else "cpu"
    use_bf16 = device == "cuda" and torch.cuda.is_bf16_supported()
    model.to(device)
    pad_id = tokenizer.pad_token_id if tokenizer.pad_token_id is not None else 0

    val_rows = _load_jsonl(data_dir / "val.jsonl")
    val_enc = _encode_dataset(val_rows, tokenizer, args.max_length, with_spans=True)
    del val_rows
    val_loader = DataLoader(
        ListDataset(val_enc),
        batch_sampler=LengthBucketBatchSampler(val_enc, batch_size=32, paired=False, seed=args.seed),
        collate_fn=make_collate_fn(pad_id, with_spans=True),
        num_workers=2,
        pin_memory=(device == "cuda"),
    )

    t0 = time.time()
    best_score = -1.0
    best_metrics: dict[str, float] = {}
    val_history: list[dict[str, Any]] = []

    # STAGE 1: 112K Clean Semantic NLI Foundation (1.0 ep)
    s1_rows = _load_jsonl(data_dir / "stage1_nli.jsonl")
    s1_enc = _encode_dataset(s1_rows, tokenizer, 512, with_spans=True)
    del s1_rows
    gc.collect()
    best_score, best_metrics = _run_stage(
        "stage1", model, s1_enc, val_loader, pad_id, tokenizer, out_dir, device, use_bf16,
        epochs=1.0, lr=args.s1_lr, batch_size=32, grad_accum=2, paired=False, use_ema=False, seed=args.seed,
        best_score=best_score, best_metrics=best_metrics, val_history=val_history,
    )
    del s1_enc
    gc.collect()

    # STAGE 2: Length-Debiased Groundedness + Structured Data2Txt + 14-Lang PsiloQA + EMA
    s2_rows = _load_jsonl(data_dir / "stage2_grounded.jsonl")
    s2_enc = _encode_dataset(s2_rows, tokenizer, args.max_length, with_spans=True)
    del s2_rows
    gc.collect()
    best_score, best_metrics = _run_stage(
        "stage2", model, s2_enc, val_loader, pad_id, tokenizer, out_dir, device, use_bf16,
        epochs=args.s2_epochs, lr=args.s2_lr, batch_size=args.batch_size, grad_accum=args.grad_accum,
        paired=True, use_ema=True, seed=args.seed + 17,
        best_score=best_score, best_metrics=best_metrics, val_history=val_history,
    )

    summary = {
        "method": "prod_tok_span_mil_ema_v5",
        "base_model": args.base_model,
        "architecture": "ModernBertForTokenClassification",
        "id2label": TOK_ID2LABEL,
        "train_runtime_sec": round(time.time() - t0, 1),
        "best_val_metrics": best_metrics,
        "val_history": val_history,
    }
    (out_dir / "training_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")
    print("[train_tok] DONE!", json.dumps(best_metrics, indent=2))


if __name__ == "__main__":
    main()