File size: 44,668 Bytes
cfc7a54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
from __future__ import annotations

import argparse
import json
import math
import os
import random
import sys
import time
from collections import defaultdict
from pathlib import Path

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.transforms.functional as TF
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm


ROOT = Path(__file__).resolve().parents[1]
SRC_ROOT = ROOT / "src"
if str(SRC_ROOT) not in sys.path:
    sys.path.insert(0, str(SRC_ROOT))

from data.cross_sensor_sampler import CrossSensorBatchSampler
from data.degradation import DegradationPipeline
from data.fvc_loader import FVCLoader, FVCPaths
from data.nist302_loader import NIST302Loader, NIST302Paths
from data.polyu_loader import PolyULoader
from losses.degradation_ranking import DegradationRankingLoss
from losses.matcher_teacher import MatcherTeacherLoss
from losses.orthogonality import OrthogonalityLoss
from losses.sensor_invariance import SensorInvarianceLoss
from models.aggregator import ScoreAggregator
from models.backbone import SIFQBackbone
from models.concept_head import ConceptHead, SpatialConceptHead
from models.grad_reverse import GradientReversalLayer
from models.sensor_discriminator import SensorDiscriminator
from models.sifq import SIFQ
from training.mdgt_teacher import MDGTCheckpointTeacher, DINOv2Teacher
from training.stage_scheduler import get_loss_weights, dann_progress


class RecordDataset(Dataset):
    """Unified dataset for SD302 + FVC records.

    For SD302 records the NIST302Loader is used; for FVC records the FVCLoader
    is used. The ``dataset`` field in each record determines which loader reads
    the image.

    ``preload=True`` (default) loads all images into a contiguous uint8 numpy
    array at init time.  __getitem__ then does only a cheap dtype cast with no
    disk IO, eliminating the DataLoader as the training bottleneck.
    Memory: N × H × W uint8 ≈ 2 GB for 42K images at 224×224.
    """

    def __init__(
        self,
        records: list[dict[str, str]],
        image_size: int,
        sensor_to_idx: dict[str, int],
        preload: bool = True,
    ):
        self.records = records
        self.nist_loader = NIST302Loader(image_size=image_size)
        self.fvc_loader = FVCLoader(image_size=image_size)
        self.sensor_to_idx = sensor_to_idx
        self._image_cache: np.ndarray | None = None

        if preload:
            self._preload_images(image_size)

    def _preload_images(self, image_size: int) -> None:
        N = len(self.records)
        cache = np.empty((N, image_size, image_size), dtype=np.uint8)
        for i, rec in enumerate(tqdm(self.records, desc="Preloading images", ncols=90, leave=True)):
            is_fvc = rec.get("dataset", "").startswith("fvc")
            loader = self.fvc_loader if is_fvc else self.nist_loader
            sample = next(loader.iter_samples([rec]))
            # sample["image"] is float32 [1, H, W] in [0, 1]
            cache[i] = (sample["image"].squeeze(0) * 255).byte().numpy()
        mem_mb = cache.nbytes / 1e6
        print(f"Image cache: {N} images  {mem_mb:.0f} MB")
        self._image_cache = cache

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

    def __getitem__(self, idx: int) -> dict[str, object]:
        rec = self.records[idx]
        if self._image_cache is not None:
            image_np = self._image_cache[idx]          # uint8 [H, W], shared RAM
            image = torch.from_numpy(image_np.copy()).float().unsqueeze(0) / 255.0
        else:
            is_fvc = rec.get("dataset", "").startswith("fvc")
            loader = self.fvc_loader if is_fvc else self.nist_loader
            img_t = next(loader.iter_samples([rec]))["image"]  # float [1, H, W]
            image_np = (img_t.squeeze(0) * 255).byte().numpy()
            image = img_t
        return {
            "image": image,
            "image_np": image_np,                      # uint8 [H, W] for degradation
            "identity_id": rec["identity_id"],
            "finger_id": rec["finger_id"],
            "sensor_id": rec["sensor_id"],
            "dataset": rec.get("dataset", "unknown"),
            "sensor_label": self.sensor_to_idx.get(rec["sensor_id"], 0),
            "record_idx": idx,
        }


def collate_fn(batch: list[dict[str, object]]) -> dict[str, object]:
    images = torch.stack([b["image"] for b in batch], dim=0)
    return {
        "images": images,
        "images_np": np.stack([b["image_np"] for b in batch], axis=0),   # [B, H, W] uint8
        "identity_ids": [str(b["identity_id"]) for b in batch],
        "finger_ids": [str(b["finger_id"]) for b in batch],
        "sensor_ids": [str(b["sensor_id"]) for b in batch],
        "datasets": [str(b.get("dataset", "unknown")) for b in batch],
        "sensor_labels": torch.tensor(
            [int(b["sensor_label"]) for b in batch], dtype=torch.long
        ),
        "record_idxs": torch.tensor(
            [int(b["record_idx"]) for b in batch], dtype=torch.long
        ),
    }


def build_pair_indices(batch: dict[str, object]) -> list[tuple[int, int]]:
    """Build cross-sensor pair indices from SD302 and PolyU records.

    FVC images have one finger per subject captured by a single sensor, so
    they cannot form cross-sensor pairs and are excluded here.
    PolyU has the strongest cross-sensor signal (contactless vs contact).
    """
    grouped: dict[tuple[str, str], list[int]] = defaultdict(list)
    identity_ids = batch["identity_ids"]
    finger_ids = batch["finger_ids"]
    sensor_ids = batch["sensor_ids"]
    datasets = batch.get("datasets", ["unknown"] * len(identity_ids))

    for idx, (key, ds) in enumerate(zip(zip(identity_ids, finger_ids), datasets)):
        if not ds.startswith("fvc"):  # SD302 + PolyU (v11: PolyU back in L_sens)
            grouped[key].append(idx)

    pairs: list[tuple[int, int]] = []
    for idxs in grouped.values():
        for i in range(len(idxs)):
            for j in range(i + 1, len(idxs)):
                a, b = idxs[i], idxs[j]
                if sensor_ids[a] != sensor_ids[b]:
                    pairs.append((a, b))
    return pairs


@torch.no_grad()
def compute_teacher_prototypes(
    teacher_loss: MatcherTeacherLoss,
    loader: DataLoader,
    device: torch.device,
    max_batches: int | None = None,
) -> dict[str, torch.Tensor]:
    total = min(len(loader), max_batches) if max_batches else len(loader)
    buckets: dict[str, list[torch.Tensor]] = defaultdict(list)
    pbar = tqdm(loader, total=total, desc="Computing prototypes", ncols=90, leave=True)
    for step, batch in enumerate(pbar):
        if max_batches is not None and step >= max_batches:
            break
        images = batch["images"].to(device)
        with torch.autocast("cuda", dtype=torch.float16):
            emb = teacher_loss.mdgt(images)
        emb = nn.functional.normalize(emb.float(), dim=-1)
        _proto_datasets = batch.get("datasets", [""] * len(batch["identity_ids"]))
        for i, (identity_id, ds) in enumerate(zip(batch["identity_ids"], _proto_datasets)):
            if ds == "polyu":
                continue  # PolyU: L_sens only — no quality prototype needed
            buckets[identity_id].append(emb[i].detach().cpu())
        pbar.set_postfix({"identities": len(buckets)})

    out: dict[str, torch.Tensor] = {}
    for identity_id, vecs in buckets.items():
        proto = torch.stack(vecs, dim=0).mean(dim=0)
        out[identity_id] = nn.functional.normalize(proto, dim=-1)
    print(f"Prototypes computed: {len(out)} identities from {min(step+1, total)} batches")
    return out


@torch.no_grad()
def compute_identity_cos_stats(
    teacher_loss: MatcherTeacherLoss,
    prototypes: dict[str, torch.Tensor],
    loader: DataLoader,
    device: torch.device,
    max_batches: int | None = None,
    min_sigma: float = 0.02,
    fvc_only: bool = True,
) -> dict[str, tuple[float, float]]:
    """Compute per-identity (mean_cos, std_cos) for teacher-loss normalisation.

    T32 fix: fvc_only=True (default) restricts stats to FVC identities only.

    Rationale: per-identity stats enable tanh-normalised q_mat targets that
    give within-identity quality variation (better image → higher score).
    For SD302 images L_pair (L_sens) enforces |Q(s1)−Q(s2)|≤0.05 for the
    same finger across sensors, which *directly conflicts* with within-identity
    variation from L_mat.  The model resolves the conflict by outputting ~50
    for all SD302 images, collapsing quality discrimination at inference.

    FVC images have one finger per subject captured by a single sensor → no
    cross-sensor pairs → L_pair=0 for FVC.  Per-identity stats therefore
    provide uncontested within-identity quality ordering for FVC without
    fighting L_pair.

    SD302 identities not present in stats fall back to raw-cosine targets in
    _compute_q_mat (≈0.85, constant) — the same mean-anchoring behaviour as
    v14 (stats=None), which achieved KS=0.263.
    """
    buckets: dict[str, list[float]] = defaultdict(list)
    total = min(len(loader), max_batches) if max_batches else len(loader)
    dataset_label = "FVC only" if fvc_only else "SD302+FVC"
    pbar = tqdm(loader, total=total, desc=f"Computing cos stats ({dataset_label})", ncols=90, leave=True)
    for step, batch in enumerate(pbar):
        if max_batches is not None and step >= max_batches:
            break
        images = batch["images"].to(device)
        identity_ids = batch["identity_ids"]
        _datasets = batch.get("datasets", [""] * len(identity_ids))
        if fvc_only:
            # T32: only FVC identities — no L_pair conflict with within-identity variation
            idxs = [i for i, ds in enumerate(_datasets) if ds.startswith("fvc")]
        else:
            # Legacy: all non-PolyU (SD302 + FVC)
            idxs = [i for i, ds in enumerate(_datasets) if ds != "polyu"]
        if not idxs:
            continue
        idx_t = torch.tensor(idxs, device=device)
        with torch.autocast("cuda", dtype=torch.float16):
            emb = teacher_loss.mdgt(images[idx_t])
        emb = nn.functional.normalize(emb.float(), dim=-1)
        for j, orig_idx in enumerate(idxs):
            identity = identity_ids[orig_idx]
            if identity not in prototypes:
                continue
            proto = prototypes[identity].to(device)
            cos = float(torch.dot(emb[j], proto).item())
            buckets[identity].append(cos)
        pbar.set_postfix({"identities": len(buckets)})

    stats: dict[str, tuple[float, float]] = {}
    for identity, cos_list in buckets.items():
        arr = np.array(cos_list, dtype=np.float32)
        mu = float(arr.mean())
        sigma = max(float(arr.std()), min_sigma)
        stats[identity] = (mu, sigma)

    if stats:
        all_mu = [v[0] for v in stats.values()]
        all_sigma = [v[1] for v in stats.values()]
        print(
            f"Cos stats: {len(stats)} identities  "
            f"global_mu={np.mean(all_mu):.4f}  "
            f"global_sigma={np.mean(all_sigma):.4f}  "
            f"min_sigma={min(all_sigma):.4f}"
        )
    return stats


@torch.no_grad()
def precompute_teacher_embeddings(
    teacher: nn.Module,
    dataset: RecordDataset,
    device: torch.device,
    batch_size: int = 64,
) -> torch.Tensor:
    """Run frozen teacher on all training records once; return CPU Tensor [N, D].

    The teacher is frozen, so its output for any given image is constant.
    Caching eliminates the DINOv2+TRAM+GNN forward pass from every training step.
    """
    loader = DataLoader(
        dataset, batch_size=batch_size, shuffle=False,
        num_workers=4, collate_fn=collate_fn, pin_memory=(device.type == "cuda"),
    )
    N = len(dataset)
    emb_list: list[torch.Tensor | None] = [None] * N
    teacher.eval()
    amp_enabled = device.type == "cuda"
    pbar = tqdm(loader, desc="Caching teacher embeddings", ncols=90, leave=True)
    for batch in pbar:
        images = batch["images"].to(device)
        record_idxs = batch["record_idxs"].tolist()
        with torch.autocast("cuda", dtype=torch.float16, enabled=amp_enabled):
            emb = F.normalize(teacher(images).float(), dim=-1)  # [b, D]
        for j, idx in enumerate(record_idxs):
            emb_list[idx] = emb[j].cpu()
    return torch.stack(emb_list, dim=0)  # [N, D] float32 on CPU


def _degrade_gpu(
    images: torch.Tensor,
    deg_type: str,
    level: int,
) -> torch.Tensor | None:
    """Apply degradation entirely on GPU. Returns None for types needing CPU (jpeg/dry_skin/wet_press)."""
    if level <= 0:
        return images.clone()
    if deg_type == "blur":
        k = int(0.5 + level * 0.83) * 2 + 1
        return TF.gaussian_blur(images, k)
    if deg_type == "noise":
        sigma = (5.0 + level * 8.3) / 255.0
        return (images + torch.randn_like(images) * sigma).clamp(0, 1)
    if deg_type == "occlusion":
        out = images.clone()
        H, W = out.shape[2], out.shape[3]
        block = max(1, int(min(H, W) * 0.183 * level))
        x = random.randint(0, max(0, W - block))
        y = random.randint(0, max(0, H - block))
        out[:, :, y:y + block, x:x + block] = 1.0
        return out
    return None  # jpeg / dry_skin / wet_press → caller uses CPU path


def _degrade_from_np(
    images_np: np.ndarray,
    deg_idx: list[int],
    deg_pipeline: "DegradationPipeline",
    deg_type: str,
    level_lo: int,
    level_hi: int,
    device: torch.device,
) -> tuple[torch.Tensor, torch.Tensor]:
    """CPU-path degradation using pre-loaded numpy batch (no GPU→CPU copy)."""
    imgs = images_np[deg_idx]           # [K, H, W] uint8 already in RAM
    low_list  = [deg_pipeline.apply(img, deg_type, level_lo) for img in imgs]
    high_list = [deg_pipeline.apply(img, deg_type, level_hi) for img in imgs]
    imgs_low  = torch.from_numpy(np.stack(low_list)).float().unsqueeze(1).to(device) / 255.0
    imgs_high = torch.from_numpy(np.stack(high_list)).float().unsqueeze(1).to(device) / 255.0
    return imgs_low, imgs_high


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Train SIFQ with MDGT teacher flow")
    parser.add_argument(
        "--root-302a",
        type=str,
        default="/home/aiserver/works/fingerprint/dataset/302a/images/challengers",
    )
    parser.add_argument(
        "--root-302b",
        type=str,
        default="/home/aiserver/works/fingerprint/dataset/302b/images/baseline",
    )
    parser.add_argument(
        "--root-302d",
        type=str,
        default="/home/aiserver/works/fingerprint/dataset/nist_302d/images/auxiliary",
    )
    parser.add_argument(
        "--root-fvc2002",
        type=str,
        default="/home/aiserver/works/fingerprint/dataset/FVC_Dataset/FVC2002",
        help="Root of FVC2002 year folder (containing Dbs/). Empty string to skip.",
    )
    parser.add_argument(
        "--root-fvc2004",
        type=str,
        default="/home/aiserver/works/fingerprint/dataset/FVC_Dataset/FVC2004",
        help="Root of FVC2004 year folder. Empty string to skip.",
    )
    parser.add_argument(
        "--teacher",
        type=str,
        default="dinov2_raw",
        choices=["dinov2_raw", "dinov2", "mdgt"],
        help="Teacher model for L_mat. 'dinov2_raw' = frozen raw DINOv2 CLS embedding "
             "(no TRAM/GNN/checkpoint); 'dinov2' is a backward-compatible alias. "
             "'mdgt' = MDGT checkpoint (requires --mdgt-checkpoint). Default: dinov2_raw.",
    )
    parser.add_argument(
        "--dinov2-model",
        type=str,
        default="dinov2_vits14",
        choices=["dinov2_vits14", "dinov2_vitb14", "dinov2_vitl14", "dinov2_vitg14"],
        help="Raw DINOv2 torch.hub model when --teacher is dinov2_raw/dinov2. "
             "vits14 is fastest; vitb14/vitl14 may generalize better but cost more memory/time.",
    )
    parser.add_argument(
        "--mdgt-checkpoint",
        type=str,
        default="/home/aiserver/works/fingerprint/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt",
        help="Path to MDGT checkpoint. Only used when --teacher=mdgt.",
    )
    parser.add_argument("--epochs", type=int, default=1)
    parser.add_argument("--batch-size", type=int, default=16)
    parser.add_argument(
        "--teacher-batch-size",
        type=int,
        default=0,
        help="Batch size for one-time teacher embedding cache. 0 = use --batch-size. "
             "Set lower for larger raw DINOv2 models to avoid OOM.",
    )
    parser.add_argument("--image-size", type=int, default=224)
    parser.add_argument("--lr", type=float, default=1e-4)
    parser.add_argument(
        "--max-train-samples",
        type=int,
        default=800,
        help="Max records for training subset; <=0 means use all discovered records.",
    )
    parser.add_argument("--num-workers", type=int, default=2)
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--save-dir", type=str, default="/home/aiserver/works/fingerprint/sifq/checkpoints/v16")
    parser.add_argument(
        "--resume", type=str, default="",
        help="Path to checkpoint to resume weights from (model only, not optimizer).",
    )
    parser.add_argument("--fixed-alpha", type=float, default=-1.0,
                        help="Override stage-scheduler alpha for all epochs. -1 = use scheduler.")
    parser.add_argument("--fixed-beta",  type=float, default=-1.0)
    parser.add_argument("--fixed-gamma", type=float, default=-1.0)
    parser.add_argument(
        "--spread-weight", type=float, default=4.0,
        help="Weight for spread/uniformity loss (W_SPREAD). Default 4.0 (v16+). "
             "v15 and earlier used 2.0.",
    )
    parser.add_argument(
        "--spread-mode", type=str, default="uniform", choices=["uniform", "variance"],
        help="'uniform': force sorted Q-scores to linspace(10,90) per batch (original). "
             "'variance': soft hinge penalty when batch std < --spread-target-std.",
    )
    parser.add_argument(
        "--spread-target-std", type=float, default=10.0,
        help="Target minimum std for Q-scores (0-100 scale) when --spread-mode=variance.",
    )
    parser.add_argument(
        "--deg-every-n-steps", type=int, default=4,
        help="Run degradation forward passes every N steps (1=every step, 4=original).",
    )
    parser.add_argument(
        "--deg-max-images", type=int, default=32,
        help="Max images per L_deg step (T17: L_deg on all datasets, not FVC-only). "
             "Limits the extra memory from 2 additional forward passes. Default 32.",
    )
    parser.add_argument(
        "--gpus",
        type=str,
        default="0,1",
        help="Comma-separated GPU indices to use, e.g. '0,1'. Empty string = all GPUs.",
    )
    parser.add_argument(
        "--no-amp",
        action="store_true",
        default=False,
        help="Disable automatic mixed precision (fp16). Default: AMP enabled on CUDA.",
    )
    parser.add_argument(
        "--proto-max-batches",
        type=int,
        default=150,
        help="Max batches for initial prototype computation. 0 = full dataset. Default 150 (~14400 images).",
    )
    parser.add_argument(
        "--k-cross",
        type=int,
        default=16,
        help="Cross-sensor anchor pairs per batch. Each contributes 2 samples from different sensors. 0 = disable stratified sampler.",
    )
    parser.add_argument(
        "--root-polyu",
        type=str,
        default="",
        help="Root of PolyU cross-fingerprint database (folder containing "
             "contact-based_fingerprints/ and processed_contactless_2d_fingerprint_images/). "
             "Empty string to skip.",
    )
    parser.add_argument(
        "--exclude-sensor",
        type=str,
        default="",
        help="Comma-separated sensor_ids to exclude from training. "
             "E.g. 'R_1000_slap,R_500_slap,S_500_slap' to remove non-segmented slap images.",
    )
    parser.add_argument(
        "--concept-deg-gamma", type=float, default=0.5,
        help="T30: gamma weight for L_concept inside DegradationRankingLoss "
             "(concept_deg = gamma * sum Huber). Default 0.5 (original). "
             "Set to 2.0 in v15 to strengthen concept grounding.",
    )
    parser.add_argument(
        "--sd302-concept-weight", type=float, default=0.0,
        help="T30: weight for SD302 concept-only L_deg (no L_rank, avoids score "
             "collapse). 0.0 = disabled (v14 behaviour). Set to 1.0 in v15.",
    )
    parser.add_argument(
        "--min-sigma", type=float, default=0.02,
        help="Minimum per-identity cosine std for teacher-loss normalisation. "
             "Prevents division by near-zero std for single-sample identities. "
             "Default 0.02 ≈ typical within-identity cosine std.",
    )
    parser.add_argument(
        "--no-mat-stats",
        action="store_true",
        default=False,
        help="T33: Skip per-identity cosine stats for L_mat — all images use raw cosine "
             "as teacher target (v14 behaviour). Prevents FVC/SD302 asymmetric quality "
             "signal that causes SD302 feature collapse.",
    )
    parser.add_argument(
        "--deg-include-sd302",
        action="store_true",
        default=False,
        help="T35b: Include SD302 images in L_deg (full L_rank, not concept-only). "
             "T27 reverted L_deg to FVC-only because clean SD302 images anchored at ~28 "
             "when there was no per-dataset spread. Now that per-dataset L_spread_ds "
             "is in place (T27 also added it), applying full L_rank to SD302 is safe: "
             "L_spread_ds forces SD302 to span [10,90] while L_rank orders them by "
             "degradation response. Together they give per-image quality grounding for "
             "SD302 at inference without score anchoring.",
    )
    parser.add_argument(
        "--spatial-concept-head",
        action="store_true",
        default=False,
        help="Use SpatialConceptHead (v27+): operates on backbone's 14×14 spatial token "
             "map [B, 196, 320] instead of the globally-pooled vector [B, 320]. "
             "Each concept has a separate linear projection over the spatial tokens, "
             "which better captures orientation_coherence, continuity, and "
             "minutiae_reliability. Incompatible with checkpoints trained without this flag.",
    )
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    random.seed(args.seed)
    torch.manual_seed(args.seed)

    # GPU setup
    if args.gpus:
        os.environ["CUDA_VISIBLE_DEVICES"] = args.gpus
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    n_gpus = torch.cuda.device_count()
    print(f"Device: {device}  |  GPUs visible: {n_gpus} {[torch.cuda.get_device_name(i) for i in range(n_gpus)]}")

    save_dir = Path(args.save_dir)
    save_dir.mkdir(parents=True, exist_ok=True)

    # --- Discover SD302 records (L_sens + L_mat + L_deg) ---
    paths = NIST302Paths(args.root_302a, args.root_302b, args.root_302d)
    nist_loader = NIST302Loader(image_size=args.image_size)
    sd302_records = nist_loader.discover(paths)
    print(f"SD302 records discovered: {len(sd302_records)}")

    # --- Discover FVC records (L_mat priority + L_deg) ---
    fvc_paths = FVCPaths(
        root_fvc2002=args.root_fvc2002,
        root_fvc2004=args.root_fvc2004,
    )
    fvc_loader = FVCLoader(image_size=args.image_size)
    fvc_records = fvc_loader.discover(fvc_paths)
    print(f"FVC records discovered: {len(fvc_records)}")

    # --- Discover PolyU records (L_sens cross-modality + L_mat + L_deg) ---
    polyu_records: list[dict[str, str]] = []
    if args.root_polyu:
        polyu_loader = PolyULoader(image_size=args.image_size)
        polyu_records = polyu_loader.discover(args.root_polyu)
        print(f"PolyU records discovered: {len(polyu_records)}")
    else:
        print("PolyU: skipped (--root-polyu not set)")

    records = sd302_records + fvc_records + polyu_records
    if not records:
        raise RuntimeError("No records discovered. Check dataset roots.")

    if args.exclude_sensor:
        excluded = {s.strip() for s in args.exclude_sensor.split(",") if s.strip()}
        before = len(records)
        records = [r for r in records if r["sensor_id"] not in excluded]
        print(f"Excluded sensors {excluded}: {before}{len(records)} records")

    random.shuffle(records)
    if args.max_train_samples > 0:
        records = records[: min(len(records), args.max_train_samples)]

    sensors = sorted({r["sensor_id"] for r in records})
    sensor_to_idx = {s: i for i, s in enumerate(sensors)}

    train_ds = RecordDataset(records=records, image_size=args.image_size, sensor_to_idx=sensor_to_idx)
    _use_persistent = args.num_workers > 0
    _loader_kwargs = dict(
        num_workers=args.num_workers,
        pin_memory=(device.type == "cuda"),
        persistent_workers=_use_persistent,
        prefetch_factor=(4 if _use_persistent else None),
        collate_fn=collate_fn,
    )
    if args.k_cross > 0:
        cross_sampler = CrossSensorBatchSampler(
            records=records,
            batch_size=args.batch_size,
            k_cross=args.k_cross,
            seed=args.seed,
        )
        train_loader = DataLoader(train_ds, batch_sampler=cross_sampler, **_loader_kwargs)
    else:
        train_loader = DataLoader(
            train_ds, batch_size=args.batch_size, shuffle=True,
            drop_last=True, **_loader_kwargs
        )
    # Separate loader without drop_last so ALL identities get prototypes
    proto_loader = DataLoader(
        train_ds,
        batch_size=args.batch_size,
        shuffle=False,
        num_workers=args.num_workers,
        pin_memory=(device.type == "cuda"),
        persistent_workers=_use_persistent,
        prefetch_factor=(4 if _use_persistent else None),
        collate_fn=collate_fn,
        drop_last=False,
    )

    backbone = SIFQBackbone(model_name="tiny_vit_5m_224.dist_in22k", pretrained=True)
    if args.spatial_concept_head:
        concept_head = SpatialConceptHead(in_dim=backbone.feature_dim)
        print("ConceptHead: SpatialConceptHead (14×14 spatial tokens → per-concept projection)")
    else:
        concept_head = ConceptHead(in_dim=backbone.feature_dim)
        print("ConceptHead: ConceptHead (global-average-pooled vector — legacy)")
    aggregator = ScoreAggregator(k=6)
    sensor_disc = SensorDiscriminator(in_dim=backbone.feature_dim, num_sensors=len(sensors))
    model = SIFQ(backbone, concept_head, aggregator, sensor_disc).to(device)
    if args.resume:
        ckpt_resume = torch.load(args.resume, map_location=device, weights_only=False)
        model.load_state_dict(ckpt_resume["model"], strict=True)
        print(f"Resumed model weights from: {args.resume}")
    if n_gpus > 1:
        model = nn.DataParallel(model)
        print(f"Using DataParallel on {n_gpus} GPUs")

    if args.teacher in {"dinov2_raw", "dinov2"}:
        teacher = DINOv2Teacher(device=str(device), model_name=args.dinov2_model).to(device)
        print(f"Teacher: raw DINOv2 {args.dinov2_model} (frozen CLS — torch.hub)")
    else:
        teacher = MDGTCheckpointTeacher(
            checkpoint_path=args.mdgt_checkpoint,
            device=str(device),
        ).to(device)
        print(f"Teacher: MDGT checkpoint {args.mdgt_checkpoint}")

    loss_mat = MatcherTeacherLoss(mdgt_model=teacher, delta=1.0)
    loss_sens = SensorInvarianceLoss(delta=0.05, lambda_adv=0.3)
    loss_deg = DegradationRankingLoss(margin=0.1, gamma=args.concept_deg_gamma)
    loss_orth = OrthogonalityLoss()
    deg_pipeline = DegradationPipeline()
    _DEG_TYPES = ["blur", "noise", "jpeg", "occlusion", "dry_skin", "wet_press"]
    W_SPREAD = args.spread_weight
    _UNIF_LO, _UNIF_HI = 10.0, 90.0
    _SPREAD_TARGET_STD = args.spread_target_std

    optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-4)
    # Cosine annealing: LR decays from args.lr to eta_min over all epochs.
    # Prevents the oscillation seen in S4 where fixed LR was too high for a
    # fine-tuning phase.  eta_min = lr/20 keeps gradient flow alive at the end.
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
        optimizer, T_max=max(1, args.epochs), eta_min=args.lr / 20.0
    )
    amp = (not args.no_amp) and (device.type == "cuda")
    scaler = torch.amp.GradScaler("cuda", enabled=amp)
    print(f"AMP fp16: {'enabled' if amp else 'disabled'}")

    print("Pre-caching teacher embeddings for all training records (one-time cost)...")
    teacher_batch_size = args.teacher_batch_size if args.teacher_batch_size > 0 else args.batch_size
    emb_cache = precompute_teacher_embeddings(teacher, train_ds, device, batch_size=teacher_batch_size)
    print(f"Teacher cache: {emb_cache.shape[0]} records × {emb_cache.shape[1]}-D  ({emb_cache.numel() * 4 / 1e6:.1f} MB fp32)")

    proto_max = args.proto_max_batches if args.proto_max_batches > 0 else None
    print(f"Computing initial prototypes (max_batches={proto_max or 'all'})...")
    prototypes = compute_teacher_prototypes(loss_mat, proto_loader, device, max_batches=proto_max)

    if args.no_mat_stats:
        print("Skipping per-identity cosine stats (--no-mat-stats / T33 v14 behaviour) — raw cosine targets for all identities.")
        cos_stats = None
    else:
        print("Computing per-identity cosine statistics for teacher-loss normalisation (FVC only — T32)...")
        cos_stats = compute_identity_cos_stats(
            loss_mat, prototypes, proto_loader, device,
            max_batches=proto_max,
            min_sigma=args.min_sigma,
            fvc_only=True,  # T32: avoid L_mat vs L_pair conflict for SD302 images
        )

    metrics_path = save_dir / "metrics.jsonl"
    with metrics_path.open("w", encoding="utf-8") as f:
        pass

    stage_names = {(0, 10): "S1:deg_only", (10, 20): "S1→S2:ramp", (20, 35): "S2:+mat", (35, 40): "S2→S3:ramp", (40, 999): "S3:+sens"}

    def get_stage_name(ep: int) -> str:
        for (lo, hi), name in stage_names.items():
            if lo <= ep < hi:
                return name
        return "S4:finetune"

    total_steps = len(train_loader)
    print(f"\nTraining: {args.epochs} epochs | {len(records)} samples | {total_steps} steps/epoch | batch={args.batch_size}\n")

    for epoch in range(args.epochs):
        model.train()
        alpha, beta, gamma_stage = get_loss_weights(epoch)
        if args.fixed_alpha >= 0:
            alpha, beta, gamma_stage = args.fixed_alpha, args.fixed_beta, args.fixed_gamma
        stage = get_stage_name(epoch)
        # DANN warm-up: update GRL lambda each epoch
        grl_lambda = GradientReversalLayer.dann_lambda(
            dann_progress(epoch, args.epochs), lambda_max=0.6
        )
        disc = model.module.sensor_disc if isinstance(model, nn.DataParallel) else model.sensor_disc
        disc.set_grl_lambda(grl_lambda)
        t0 = time.time()

        running = {"total": 0.0, "l_mat": 0.0, "l_sens": 0.0, "l_pair": 0.0, "l_adv": 0.0,
                   "l_deg": 0.0, "l_orth": 0.0, "l_spread": 0.0, "l_spread_ds": 0.0}
        q_sum, q_sq_sum, q_count = 0.0, 0.0, 0
        steps = 0

        pbar = tqdm(
            train_loader,
            desc=f"Ep {epoch+1:03d}/{args.epochs} [{stage}]",
            ncols=110,
            leave=False,
        )
        for step_idx, batch in enumerate(pbar):
            images = batch["images"].to(device)
            sensor_labels = batch["sensor_labels"].to(device)
            identity_ids = batch["identity_ids"]
            record_idxs = batch["record_idxs"]          # [B] int64 on CPU
            # Per design: FVC=(L_mat,L_deg)  SD302=(L_sens,L_mat)  PolyU=(L_sens only)
            _datasets = batch.get("datasets", [""] * len(identity_ids))
            _non_polyu_idx = [i for i, ds in enumerate(_datasets) if ds != "polyu"]     # L_mat: SD302+FVC
            # T27: Revert T17 — L_deg back to FVC-only.
            # T17 fix (L_deg on ALL datasets) caused SD302 images to anchor at ~28
            # (just above the synthetic degradation floor), which is wrong. SD302 images
            # are naturally high-quality; synthetic degradation is not a valid quality proxy.
            # SD302 ordinal grounding is now handled by per-dataset L_spread (below).
            _fvc_idx = [i for i, ds in enumerate(_datasets) if ds.startswith("fvc")]

            with torch.autocast("cuda", dtype=torch.float16, enabled=amp):
                outputs = model(images)

                if _non_polyu_idx:
                    _cached_emb = emb_cache[record_idxs[_non_polyu_idx]]
                    l_mat = loss_mat(
                        pred_score=outputs["score"][_non_polyu_idx],
                        images=None,
                        identity_ids=[identity_ids[i] for i in _non_polyu_idx],
                        prototypes=prototypes,
                        stats=cos_stats,
                        cached_emb=_cached_emb,
                    )
                else:
                    l_mat = torch.tensor(0.0, device=device)

                pairs = build_pair_indices(batch)
                if pairs:
                    idx_a = torch.tensor([p[0] for p in pairs], device=device)
                    idx_b = torch.tensor([p[1] for p in pairs], device=device)
                    l_sens, _l_pair, _l_adv = loss_sens(
                        score_s1=outputs["score"][idx_a],
                        score_s2=outputs["score"][idx_b],
                        sensor_logits=outputs["sensor_logits"],
                        sensor_labels=sensor_labels,
                    )
                else:
                    l_sens = torch.tensor(0.0, device=device)
                    _l_pair = torch.tensor(0.0)
                    _l_adv = torch.tensor(0.0)

                # Degradation: FVC-only by default (T27 reverts T17).
                # T35b (--deg-include-sd302): include SD302 in L_deg as well.
                # T27 originally reverted T17 because clean SD302 images anchored
                # at ~28 when there was no per-dataset spread. With per-dataset
                # L_spread_ds (introduced in T27 itself), applying full L_rank to
                # SD302 is now safe: L_spread_ds prevents anchoring by forcing SD302
                # scores to span [10,90], and L_rank orders them by degradation
                # response (a quality-relevant signal). This provides per-image
                # quality grounding for SD302 at inference that was previously missing.
                _deg_candidate_idx = _non_polyu_idx if args.deg_include_sd302 else _fvc_idx
                if gamma_stage > 0 and step_idx % args.deg_every_n_steps == 0 and _deg_candidate_idx:
                    deg_type = random.choice(_DEG_TYPES)
                    level_lo = random.randint(1, 2)
                    level_hi = 3
                    _deg_idx = _deg_candidate_idx
                    if args.deg_max_images > 0 and len(_deg_idx) > args.deg_max_images:
                        _deg_idx = random.sample(_deg_idx, args.deg_max_images)
                    _deg_idx_t = torch.tensor(_deg_idx, device=device)
                    # GPU path for blur/noise/occlusion; CPU path (no GPU→CPU copy) for others
                    _imgs_sub = images[_deg_idx_t]
                    imgs_low  = _degrade_gpu(_imgs_sub, deg_type, level_lo)
                    imgs_high = _degrade_gpu(_imgs_sub, deg_type, level_hi)
                    if imgs_low is None:
                        imgs_low, imgs_high = _degrade_from_np(
                            batch["images_np"], _deg_idx, deg_pipeline,
                            deg_type, level_lo, level_hi, device,
                        )
                    out_low = model(imgs_low)
                    out_high = model(imgs_high)
                    l_deg = loss_deg(
                        score_clean=outputs["score"][_deg_idx_t],
                        score_low=out_low["score"],
                        score_high=out_high["score"],
                        concepts_low=out_low["concepts"],
                        concepts_high=out_high["concepts"],
                        degradation_type=deg_type,
                    )

                    # T30 (v15): SD302 concept-only L_deg.
                    # Concept head never saw degraded SD302 texture → concept
                    # grounding fails on SD302 eval images. Apply degradation to
                    # SD302 batch items but skip L_rank (avoids score collapse
                    # that caused T27 revert). Only supervise concept direction.
                    if args.sd302_concept_weight > 0:
                        _sd302_deg_idx = [i for i, ds in enumerate(_datasets)
                                          if ds.startswith("nist_sd302")]
                        if _sd302_deg_idx:
                            if args.deg_max_images > 0 and len(_sd302_deg_idx) > args.deg_max_images:
                                _sd302_deg_idx = random.sample(_sd302_deg_idx, args.deg_max_images)
                            _sd302_deg_t = torch.tensor(_sd302_deg_idx, device=device)
                            _imgs_sd302 = images[_sd302_deg_t]
                            imgs_low_sd302  = _degrade_gpu(_imgs_sd302, deg_type, level_lo)
                            imgs_high_sd302 = _degrade_gpu(_imgs_sd302, deg_type, level_hi)
                            if imgs_low_sd302 is None:
                                imgs_low_sd302, imgs_high_sd302 = _degrade_from_np(
                                    batch["images_np"], _sd302_deg_idx, deg_pipeline,
                                    deg_type, level_lo, level_hi, device,
                                )
                            out_low_sd302 = model(imgs_low_sd302)
                            out_high_sd302 = model(imgs_high_sd302)
                            l_deg_sd302 = loss_deg(
                                score_clean=outputs["score"][_sd302_deg_t],
                                score_low=out_low_sd302["score"],
                                score_high=out_high_sd302["score"],
                                concepts_low=out_low_sd302["concepts"],
                                concepts_high=out_high_sd302["concepts"],
                                degradation_type=deg_type,
                                concept_only=True,
                            )
                            l_deg = l_deg + args.sd302_concept_weight * l_deg_sd302
                else:
                    l_deg = torch.tensor(0.0, device=device)
                    deg_type = "—"

                l_orth = loss_orth(outputs["concepts"])
                # Spread / uniformity loss — two modes:
                # 'uniform': force sorted batch Q-scores to match linspace(10,90) [original].
                # 'variance': soft hinge — only penalize when batch std < target_std.
                q_batch = outputs["score"].squeeze(-1)
                if args.spread_mode == "uniform":
                    q_sorted, _ = q_batch.sort()
                    n_q = len(q_sorted)
                    target_unif = torch.linspace(_UNIF_LO, _UNIF_HI, n_q, device=device)
                    l_spread = F.mse_loss(q_sorted / 100.0, target_unif / 100.0)
                    # T27: Per-dataset spread for SD302 subset.
                    # The global L_spread on a mixed batch (FVC+SD302+PolyU) satisfies
                    # the spread constraint using FVC/PolyU variation, leaving SD302 images
                    # free to collapse (v11 bug at ~58.3). Per-dataset spread forces SD302
                    # images in each batch to span [10,90] independently.
                    _sd302_idx = [i for i, ds in enumerate(_datasets)
                                  if ds.startswith("nist_sd302")]
                    if len(_sd302_idx) >= 8:
                        _sd302_t = torch.tensor(_sd302_idx, device=device)
                        q_sd302_sorted, _ = q_batch[_sd302_t].sort()
                        n_sd = len(q_sd302_sorted)
                        target_sd = torch.linspace(_UNIF_LO, _UNIF_HI, n_sd, device=device)
                        l_spread_ds = F.mse_loss(q_sd302_sorted / 100.0, target_sd / 100.0)
                    else:
                        l_spread_ds = torch.tensor(0.0, device=device)
                else:  # variance mode: penalize collapse only
                    q_std = q_batch.std()
                    l_spread = F.relu(_SPREAD_TARGET_STD / 100.0 - q_std / 100.0) ** 2
                    l_spread_ds = torch.tensor(0.0, device=device)
                total = alpha * l_mat + beta * l_sens + gamma_stage * l_deg + l_orth + W_SPREAD * l_spread + W_SPREAD * l_spread_ds

            optimizer.zero_grad(set_to_none=True)
            scaler.scale(total).backward()
            scaler.unscale_(optimizer)
            nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
            scaler.step(optimizer)
            scaler.update()

            running["total"] += float(total.item())
            running["l_mat"] += float(l_mat.item())
            running["l_sens"] += float(l_sens.item())
            running["l_pair"] += float(_l_pair.item())
            running["l_adv"] += float(_l_adv.item())
            running["l_deg"] += float(l_deg.item())
            running["l_orth"] += float(l_orth.item())
            running["l_spread"] += float(l_spread.item())
            running["l_spread_ds"] += float(l_spread_ds.item())
            _q = q_batch.detach().float()
            q_sum += float(_q.sum().item())
            q_sq_sum += float((_q ** 2).sum().item())
            q_count += _q.numel()
            steps += 1
            pbar.set_postfix({
                "loss": f"{total.item():.3f}",
                "pair": f"{_l_pair.item():.3f}",
                "adv": f"{_l_adv.item():.3f}",
                "sprd": f"{l_spread.item():.3f}",
            })

        elapsed = time.time() - t0
        avg = {k: v / max(1, steps) for k, v in running.items()}
        current_lr = optimizer.param_groups[0]["lr"]
        _q_mean = q_sum / max(1, q_count)
        _q_std = (q_sq_sum / max(1, q_count) - _q_mean ** 2) ** 0.5
        _rand_ce = math.log(max(2, len(sensors)))  # random-guess CE baseline
        print(
            f"Epoch {epoch+1:03d}/{args.epochs} [{stage}]  "
            f"loss={avg['total']:.4f}  mat={avg['l_mat']:.4f}  "
            f"sens={avg['l_sens']:.4f}  pair={avg['l_pair']:.4f}  adv={avg['l_adv']:.4f}(rand={_rand_ce:.2f})  "
            f"deg={avg['l_deg']:.4f}  orth={avg['l_orth']:.4f}  spread={avg['l_spread']:.4f}  "
            f"q_mean={_q_mean:.1f}  q_std={_q_std:.1f}  "
            f"α={alpha:.2f} β={beta:.2f} γ={gamma_stage:.2f} λ_grl={grl_lambda:.3f}  "
            f"lr={current_lr:.2e}  {elapsed:.0f}s"
        )

        row = {
            "epoch": epoch,
            "alpha": alpha,
            "beta": beta,
            "gamma": gamma_stage,
            "grl_lambda": round(grl_lambda, 4),
            "lr": current_lr,
            "train_total": avg["total"],
            "train_l_mat": avg["l_mat"],
            "train_l_sens": avg["l_sens"],
            "train_l_pair": avg["l_pair"],
            "train_l_adv": avg["l_adv"],
            "train_l_deg": avg["l_deg"],
            "train_l_orth": avg["l_orth"],
            "train_l_spread": avg["l_spread"],
            "train_q_mean": round(_q_mean, 3),
            "train_q_std": round(_q_std, 3),
            "rand_ce_baseline": round(_rand_ce, 4),
            "n_samples": len(records),
            "n_sensors": len(sensors),
            "elapsed_sec": round(elapsed, 1),
        }
        with metrics_path.open("a", encoding="utf-8") as f:
            f.write(json.dumps(row) + "\n")

        # Save state_dict from underlying module when using DataParallel
        model_state = model.module.state_dict() if isinstance(model, nn.DataParallel) else model.state_dict()
        torch.save(
            {
                "epoch": epoch,
                "model": model_state,
                "optimizer": optimizer.state_dict(),
                "scheduler": scheduler.state_dict(),
                "metrics": row,
                "config": vars(args),
            },
            save_dir / "last.pt",
        )
        scheduler.step()

    print(f"Training finished. Checkpoint: {save_dir / 'last.pt'}")
    print(f"Metrics: {metrics_path}")


if __name__ == "__main__":
    main()