Run this model with HF Jobs

Run Tamarillo/ai-image-forensics-guard-tiny on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.

Paste one of these prompts into your coding agent:

Fine-tune on my dataset

Use HF Jobs to fine-tune https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.

Run batch inference

Use HF Jobs to run batch inference with https://huggingface.co/Tamarillo/ai-image-forensics-guard-tiny on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
File size: 19,570 Bytes
656e994
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
"""Family #12 v2 Trainer: CVPR-2025 B-Free Clean/Degraded Curriculum + Online Cross-Architecture Logit KD!

Key v2 Upgrades over v1:
  1. 35% Clean Native-Resolution Crop Branch (ZERO resize, ZERO JPEG re-compression when min(w,h) >= img_size)
     + 65% Symmetric Social-Media Degradation Branch (JPEG/WebP/double-JPEG/resize/blur/unsharp).
     Fixes v1's over-compression blindspot on crisp 16-ch FLUX/GPT-Image/Z-Image micro-artifacts while
     preserving #1 social_recompressed robustness!
  2. Online bf16 Cross-Architecture / Cross-Resolution Knowledge Distillation (SigLIP2-B-384 teacher ->
     ConvNeXtV2-T-384 `small` & DINOv2-S-224 `tiny`): feeds the EXACT same augmented PIL image through
     both student processor and teacher processor, combining FocalSmooth CE + 70% KL(T=2.0) + 30% logit MSE!
  3. Validation-only checkpoint selection (val EER / ROC-AUC) + post-hoc temperature calibration.json.
"""

from __future__ import annotations

import argparse
import copy
import io
import json
import math
import os
import random
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from PIL import Image, ImageEnhance, ImageFilter
from scipy.optimize import minimize_scalar
from sklearn.metrics import roc_auc_score, roc_curve
from torch.utils.data import DataLoader, Dataset, WeightedRandomSampler
from transformers import AutoImageProcessor, AutoModelForImageClassification, get_cosine_schedule_with_warmup

Image.MAX_IMAGE_PIXELS = None
ID2LABEL = {0: "artificial", 1: "human"}
LABEL2ID = {"artificial": 0, "human": 1}


def compute_eer(y_true_artificial: np.ndarray, p_artificial: np.ndarray) -> tuple[float, float]:
    fpr, tpr, _ = roc_curve(y_true_artificial, p_artificial)
    fnr = 1.0 - tpr
    idx = int(np.nanargmin(np.abs(fnr - fpr)))
    eer = float(0.5 * (fpr[idx] + fnr[idx]))
    auc = float(roc_auc_score(y_true_artificial, p_artificial))
    return eer, auc


def compute_ece(y_true: np.ndarray, probs: np.ndarray, n_bins: int = 15) -> float:
    bins = np.linspace(0.0, 1.0, n_bins + 1)
    ece = 0.0
    for i in range(n_bins):
        lo, hi = bins[i], bins[i + 1]
        m = (probs >= lo) & (probs <= hi if i == n_bins - 1 else probs < hi)
        if m.any():
            ece += float(m.mean()) * abs(float(y_true[m].mean()) - float(probs[m].mean()))
    return float(ece)


def bfree_forensic_augment(im: Image.Image, target_size: int, rng: random.Random) -> Image.Image:
    """CVPR-2025 B-Free Clean/Degraded Curriculum:
    - 35% Clean Native-Pixel Branch: pure native crop (no destructive resize, no JPEG recompression)
      to preserve ultra-subtle 16-ch VAE & rectified-flow micro-artifacts.
    - 65% Symmetric Social-Media Degradation Branch: identical JPEG/WebP/double-JPEG/resize/blur/unsharp
      applied symmetrically to both authentic & synthetic images.
    """
    im = im.convert("RGB")
    w, h = im.size

    if rng.random() < 0.50:
        im = im.transpose(Image.Transpose.FLIP_LEFT_RIGHT)

    # Branch A (35%): Clean native-pixel crop (preserves high-frequency VAE decoder artifacts!)
    if rng.random() < 0.35:
        if min(w, h) >= target_size and rng.random() < 0.65:
            # Exact native-scale patch crop (no interpolation distortion!)
            cs = min(w, h, max(target_size, int(min(w, h) * rng.uniform(0.65, 1.0))))
            x0 = rng.randint(0, max(0, w - cs))
            y0 = rng.randint(0, max(0, h - cs))
            im = im.crop((x0, y0, x0 + cs, y0 + cs))
        return im

    # Branch B (65%): Symmetric realistic social-media degradation chain
    if rng.random() < 0.65 and min(w, h) >= 192:
        scale = rng.uniform(0.60, 0.98)
        ratio = rng.uniform(0.82, 1.22)
        area = w * h * scale
        cw = min(w, max(128, int(round(math.sqrt(area * ratio)))))
        ch = min(h, max(128, int(round(math.sqrt(area / ratio)))))
        x0 = rng.randint(0, max(0, w - cw))
        y0 = rng.randint(0, max(0, h - ch))
        im = im.crop((x0, y0, x0 + cw, y0 + ch))

    if rng.random() < 0.35:
        res_alg = rng.choice([Image.Resampling.BILINEAR, Image.Resampling.BICUBIC, Image.Resampling.LANCZOS])
        f = rng.uniform(0.45, 0.88)
        nw, nh = max(128, int(im.width * f)), max(128, int(im.height * f))
        im = im.resize((nw, nh), res_alg)

    r_filt = rng.random()
    if r_filt < 0.14:
        im = im.filter(ImageFilter.GaussianBlur(radius=rng.uniform(0.3, 1.1)))
    elif r_filt < 0.24:
        im = im.filter(ImageFilter.UnsharpMask(radius=rng.uniform(0.8, 1.8), percent=rng.randint(60, 140), threshold=2))

    if rng.random() < 0.28:
        im = ImageEnhance.Brightness(im).enhance(rng.uniform(0.91, 1.09))
        im = ImageEnhance.Contrast(im).enhance(rng.uniform(0.91, 1.10))
        im = ImageEnhance.Color(im).enhance(rng.uniform(0.91, 1.09))

    r_codec = rng.random()
    if r_codec < 0.45:
        buf = io.BytesIO()
        im.save(buf, format="JPEG", quality=rng.randint(35, 95))
        buf.seek(0)
        im = Image.open(buf).convert("RGB")
    elif r_codec < 0.65:
        buf = io.BytesIO()
        im.save(buf, format="WEBP", quality=rng.randint(40, 95))
        buf.seek(0)
        im = Image.open(buf).convert("RGB")
    elif r_codec < 0.85:
        b1 = io.BytesIO()
        im.save(b1, format="JPEG", quality=rng.randint(42, 85))
        b1.seek(0)
        im = Image.open(b1).convert("RGB")
        b2 = io.BytesIO()
        im.save(b2, format=rng.choice(["JPEG", "WEBP"]), quality=rng.randint(40, 80))
        b2.seek(0)
        im = Image.open(b2).convert("RGB")

    return im


class ForensicImageDataset(Dataset):
    def __init__(self, rows: list[dict[str, Any]]) -> None:
        self.rows = rows

    def __len__(self) -> int:
        return len(self.rows)

    def __getitem__(self, idx: int) -> dict[str, Any]:
        return self.rows[idx]


class ThreadedImageCollator:
    def __init__(
        self,
        processor: Any,
        img_size: int,
        is_train: bool,
        teacher_processor: Any | None = None,
        max_workers: int = 8,
    ) -> None:
        self.processor = processor
        self.teacher_processor = teacher_processor
        self.img_size = img_size
        self.is_train = is_train
        self.pool = ThreadPoolExecutor(max_workers=max_workers)

    def _load_one(self, r: dict[str, Any]) -> tuple[Image.Image, int]:
        try:
            im = Image.open(r["path"]).convert("RGB")
        except Exception:
            im = Image.new("RGB", (self.img_size, self.img_size), (128, 128, 128))
        if self.is_train:
            rng = random.Random(random.getrandbits(64))
            im = bfree_forensic_augment(im, self.img_size, rng)
        return im, int(r["label"])

    def __call__(self, batch: list[dict[str, Any]]) -> dict[str, torch.Tensor]:
        loaded = list(self.pool.map(self._load_one, batch))
        ims = [x[0] for x in loaded]
        ys = torch.tensor([x[1] for x in loaded], dtype=torch.long)
        out: dict[str, torch.Tensor] = {
            "pixel_values": self.processor(images=ims, return_tensors="pt")["pixel_values"],
            "labels": ys,
        }
        if self.teacher_processor is not None:
            out["t_pixel_values"] = self.teacher_processor(images=ims, return_tensors="pt")["pixel_values"]
        return out


class FocalSmoothLoss(nn.Module):
    def __init__(self, gamma: float = 1.0, smoothing: float = 0.03) -> None:
        super().__init__()
        self.gamma = gamma
        self.smoothing = smoothing

    def forward(self, logits: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
        log_p = F.log_softmax(logits, dim=-1)
        p = log_p.exp()
        n_cls = logits.size(-1)
        with torch.no_grad():
            smooth_t = torch.full_like(log_p, self.smoothing / (n_cls - 1))
            smooth_t.scatter_(1, targets.unsqueeze(1), 1.0 - self.smoothing)
        pt = p.gather(1, targets.unsqueeze(1)).squeeze(1).clamp(1e-6, 1.0)
        focal = (1.0 - pt) ** self.gamma
        ce = -(smooth_t * log_p).sum(dim=-1)
        return (focal * ce).mean()


def evaluate_val(model: nn.Module, loader: DataLoader, device: torch.device, use_bf16: bool = True) -> tuple[float, float, np.ndarray, np.ndarray]:
    model.eval()
    all_logits, all_labels = [], []
    with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
        for batch in loader:
            pv = batch["pixel_values"].to(device, non_blocking=True)
            z = model(pixel_values=pv).logits.float().cpu().numpy()
            all_logits.append(z)
            all_labels.append(batch["labels"].numpy())
    logits = np.concatenate(all_logits, axis=0)
    labels = np.concatenate(all_labels, axis=0)
    ex = np.exp(logits - logits.max(axis=-1, keepdims=True))
    p_art = (ex / ex.sum(axis=-1, keepdims=True))[:, 0]
    y_art = (labels == 0).astype(np.int32)
    eer, auc = compute_eer(y_art, p_art)
    return eer, auc, logits, labels


def fit_calibration(logits: np.ndarray, labels: np.ndarray) -> dict[str, Any]:
    y_art = (labels == 0).astype(np.int32)
    t_logits = torch.tensor(logits, dtype=torch.float32)
    t_labels = torch.tensor(labels, dtype=torch.long)

    def nll(temp: float) -> float:
        return float(F.cross_entropy(t_logits / temp, t_labels).item())

    opt = minimize_scalar(nll, bounds=(0.25, 4.0), method="bounded")
    T = float(opt.x)
    probs = torch.softmax(t_logits / T, dim=-1).numpy()
    p_art = probs[:, 0]
    eer, auc = compute_eer(y_art, p_art)
    ece = compute_ece(y_art, p_art)
    real_scores = p_art[y_art == 0]
    return {
        "temperature": round(T, 4),
        "val_eer": round(eer, 5),
        "val_auc": round(auc, 5),
        "calibrated_ece_artificial": round(ece, 5),
        "thr_val_5pct_fpr": round(float(np.quantile(real_scores, 0.95)), 4),
        "thr_val_1pct_fpr": round(float(np.quantile(real_scores, 0.99)), 4),
        "id2label": ID2LABEL,
    }


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--backbone", type=str, required=True)
    ap.add_argument("--img-size", type=int, default=224)
    ap.add_argument("--train-jsonl", type=str, required=True)
    ap.add_argument("--val-jsonl", type=str, required=True)
    ap.add_argument("--out-dir", type=str, required=True)
    ap.add_argument("--teacher-dir", type=str, default="")
    ap.add_argument("--kd-weight", type=float, default=0.45)
    ap.add_argument("--kd-temp", type=float, default=2.0)
    ap.add_argument("--epochs", type=int, default=5)
    ap.add_argument("--samples-per-epoch", type=int, default=0, help="0 = len(train_rows)")
    ap.add_argument("--batch-size", type=int, default=64)
    ap.add_argument("--grad-accum", type=int, default=1)
    ap.add_argument("--lr", type=float, default=3e-5)
    ap.add_argument("--seed", type=int, default=2026)
    args = ap.parse_args()

    os.environ["HF_HOME"] = "/tmp/hf"
    torch.multiprocessing.set_sharing_strategy("file_system")
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)

    torch.backends.cuda.matmul.allow_tf32 = True
    torch.backends.cudnn.allow_tf32 = True
    use_bf16 = True
    device = torch.device("cuda")
    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    train_rows = [json.loads(l) for l in Path(args.train_jsonl).read_text(encoding="utf-8").splitlines() if l.strip()]
    val_rows = [json.loads(l) for l in Path(args.val_jsonl).read_text(encoding="utf-8").splitlines() if l.strip()]

    processor = AutoImageProcessor.from_pretrained(args.backbone)
    model = AutoModelForImageClassification.from_pretrained(
        args.backbone,
        num_labels=2,
        id2label=ID2LABEL,
        label2id=LABEL2ID,
        ignore_mismatched_sizes=True,
    ).to(device)
    # Fix transformers==4.51.3 ConvNextV2GRN bug: torch.linalg.norm(ord=2, dim=(1,2)) dispatches to matrix_norm (SVD!)
    # instead of vector L2 norm — 100x slower & breaks bf16! Replace with true vector_norm (Frobenius L2).
    _patched_grn_cls: set[type] = set()
    for _mod in model.modules():
        _cls = _mod.__class__
        if _cls.__name__ == "ConvNextV2GRN" and _cls not in _patched_grn_cls:
            def _grn_fast(self, hidden_states):
                x = hidden_states.float()
                gx = torch.linalg.vector_norm(x, ord=2, dim=(1, 2), keepdim=True)
                nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)
                w = self.weight if hasattr(self, "weight") else self.gamma
                b = self.bias if hasattr(self, "bias") else self.beta
                return (w.float() * (x * nx) + b.float() + x).to(hidden_states.dtype)
            _cls.forward = _grn_fast
            _patched_grn_cls.add(_cls)
    n_params = sum(p.numel() for p in model.parameters()) / 1e6

    teacher_model = None
    teacher_proc = None
    if args.teacher_dir:
        print(f"[kd] Loading teacher from {args.teacher_dir} (bf16, kd_weight={args.kd_weight}, T={args.kd_temp})...", flush=True)
        teacher_proc = AutoImageProcessor.from_pretrained(args.teacher_dir)
        teacher_model = AutoModelForImageClassification.from_pretrained(args.teacher_dir, torch_dtype=torch.bfloat16).to(device).eval()
        for p in teacher_model.parameters():
            p.requires_grad_(False)

    print(f"[train_v2] {args.backbone} ({n_params:.2f}M) @ {args.img_size}px | train={len(train_rows):,}, val={len(val_rows):,} | kd={bool(teacher_model)}", flush=True)

    weights = [float(r.get("weight", 1.0)) for r in train_rows]
    n_spe = args.samples_per_epoch if args.samples_per_epoch > 0 else len(train_rows)
    sampler = WeightedRandomSampler(weights, num_samples=n_spe, replacement=True)

    train_col = ThreadedImageCollator(processor, args.img_size, is_train=True, teacher_processor=teacher_proc, max_workers=8)
    val_col = ThreadedImageCollator(processor, args.img_size, is_train=False, teacher_processor=None, max_workers=8)
    train_loader = DataLoader(ForensicImageDataset(train_rows), batch_size=args.batch_size, sampler=sampler, num_workers=0, collate_fn=train_col, pin_memory=True, drop_last=True)
    val_loader = DataLoader(ForensicImageDataset(val_rows), batch_size=args.batch_size, shuffle=False, num_workers=0, collate_fn=val_col, pin_memory=True)

    head_params, body_params = [], []
    for name, p in model.named_parameters():
        if not p.requires_grad:
            continue
        if any(k in name for k in ("classifier", "head")):
            head_params.append(p)
        else:
            body_params.append(p)
    opt = torch.optim.AdamW([
        {"params": body_params, "lr": args.lr, "weight_decay": 0.02},
        {"params": head_params, "lr": args.lr * 5.0, "weight_decay": 0.01},
    ])
    total_steps = max(1, (len(train_loader) // args.grad_accum) * args.epochs)
    sched = get_cosine_schedule_with_warmup(opt, num_warmup_steps=int(0.08 * total_steps), num_training_steps=total_steps)
    criterion = FocalSmoothLoss(gamma=1.0, smoothing=0.03)

    ema_model = copy.deepcopy(model).eval()
    for p in ema_model.parameters():
        p.requires_grad_(False)
    ema_decay = 0.996

    best_eer = 1.0
    best_state: dict[str, torch.Tensor] | None = None
    t0 = time.time()

    for ep in range(1, args.epochs + 1):
        model.train()
        opt.zero_grad(set_to_none=True)
        run_loss = 0.0
        for step, batch in enumerate(train_loader, 1):
            pv = batch["pixel_values"].to(device, non_blocking=True)
            y = batch["labels"].to(device, non_blocking=True)
            with torch.amp.autocast("cuda", dtype=torch.bfloat16, enabled=use_bf16):
                logits = model(pixel_values=pv).logits.float()
            sup_loss = criterion(logits, y)
            if teacher_model is not None and args.kd_weight > 0.0:
                tpv = batch["t_pixel_values"].to(device, non_blocking=True)
                with torch.no_grad(), torch.amp.autocast("cuda", dtype=torch.bfloat16):
                    t_logits = teacher_model(pixel_values=tpv).logits.float()
                T = args.kd_temp
                kl = F.kl_div(F.log_softmax(logits / T, dim=-1), F.softmax(t_logits / T, dim=-1), reduction="batchmean") * (T * T)
                s_std = (logits - logits.mean(dim=0, keepdim=True)) / (logits.std(dim=0, keepdim=True) + 1e-4)
                t_std = (t_logits - t_logits.mean(dim=0, keepdim=True)) / (t_logits.std(dim=0, keepdim=True) + 1e-4)
                kd_loss = 0.70 * kl + 0.30 * F.mse_loss(s_std, t_std)
                loss = ((1.0 - args.kd_weight) * sup_loss + args.kd_weight * kd_loss) / args.grad_accum
            else:
                loss = sup_loss / args.grad_accum

            loss.backward()
            run_loss += float(loss.item()) * args.grad_accum

            if step % args.grad_accum == 0 or step == len(train_loader):
                torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
                opt.step()
                sched.step()
                opt.zero_grad(set_to_none=True)
                with torch.no_grad():
                    for pe, pm in zip(ema_model.parameters(), model.parameters()):
                        pe.data.mul_(ema_decay).add_(pm.data, alpha=1.0 - ema_decay)

        val_eer, val_auc, _, _ = evaluate_val(ema_model, val_loader, device, use_bf16=use_bf16)
        raw_eer, raw_auc, _, _ = evaluate_val(model, val_loader, device, use_bf16=use_bf16)
        use_ema = val_eer <= raw_eer
        cur_eer = val_eer if use_ema else raw_eer
        print(
            f"  [ep {ep}/{args.epochs}] loss={run_loss/len(train_loader):.4f} | "
            f"ema_val_eer={val_eer*100:.2f}% auc={val_auc:.4f} | raw_val_eer={raw_eer*100:.2f}% auc={raw_auc:.4f} | "
            f"elapsed={(time.time()-t0)/60:.1f}m",
            flush=True,
        )
        if cur_eer < best_eer:
            best_eer = cur_eer
            src_m = ema_model if use_ema else model
            best_state = {k: v.detach().cpu().clone() for k, v in src_m.state_dict().items()}
            # Incremental checkpoint save for Spot resilience!
            src_m_cpu = copy.deepcopy(src_m).cpu()
            src_m_cpu.save_pretrained(out_dir, safe_serialization=True)
            processor.save_pretrained(out_dir)

    assert best_state is not None
    model.load_state_dict(best_state)
    model.eval()
    final_eer, final_auc, val_logits, val_labels = evaluate_val(model, val_loader, device, use_bf16=use_bf16)
    cal = fit_calibration(val_logits, val_labels)
    print(f"[DONE] Best val EER={final_eer*100:.2f}% AUC={final_auc:.4f} | cal={cal}", flush=True)

    model.cpu().save_pretrained(out_dir, safe_serialization=True)
    processor.save_pretrained(out_dir)
    (out_dir / "calibration.json").write_text(json.dumps(cal, indent=2), encoding="utf-8")
    summary = {
        "backbone": args.backbone,
        "teacher_dir": args.teacher_dir or None,
        "kd_weight": args.kd_weight if teacher_model is not None else 0.0,
        "params_m": round(n_params, 2),
        "img_size": args.img_size,
        "train_examples": len(train_rows),
        "val_examples": len(val_rows),
        "epochs": args.epochs,
        "best_val_eer": round(final_eer, 5),
        "best_val_auc": round(final_auc, 5),
        "train_minutes": round((time.time() - t0) / 60.0, 2),
    }
    (out_dir / "train_summary.json").write_text(json.dumps(summary, indent=2), encoding="utf-8")


if __name__ == "__main__":
    main()