| 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])) |
| |
| 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] |
| 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"] |
| image_np = (img_t.squeeze(0) * 255).byte().numpy() |
| image = img_t |
| return { |
| "image": image, |
| "image_np": image_np, |
| "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), |
| "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"): |
| 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 |
| 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: |
| |
| idxs = [i for i, ds in enumerate(_datasets) if ds.startswith("fvc")] |
| else: |
| |
| 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) |
| for j, idx in enumerate(record_idxs): |
| emb_list[idx] = emb[j].cpu() |
| return torch.stack(emb_list, dim=0) |
|
|
|
|
| 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 |
|
|
|
|
| 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] |
| 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) |
|
|
| |
| 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) |
|
|
| |
| 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)}") |
|
|
| |
| 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)}") |
|
|
| |
| 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 |
| ) |
| |
| 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) |
| |
| |
| |
| 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, |
| ) |
|
|
| 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) |
| |
| 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"] |
| |
| _datasets = batch.get("datasets", [""] * len(identity_ids)) |
| _non_polyu_idx = [i for i, ds in enumerate(_datasets) if ds != "polyu"] |
| |
| |
| |
| |
| |
| _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) |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| _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) |
| |
| _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, |
| ) |
|
|
| |
| |
| |
| |
| |
| 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"]) |
| |
| |
| |
| 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) |
| |
| |
| |
| |
| |
| _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: |
| 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))) |
| 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") |
|
|
| |
| 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() |
|
|