| # SIFQ — Giải thích toàn bộ Research & Mapping vào Code |
|
|
| > Tài liệu này đọc song song với `sifq_pdf.txt` và source code trong `src/`. |
| > Mỗi khái niệm trong paper đều có pointer đến file code tương ứng. |
| |
| --- |
| |
| ## 1. Vấn đề SIFQ giải quyết |
| |
| ### NFIQ2 có 3 nhược điểm lớn |
| |
| **Nhược điểm 1 — Matcher cũ làm target:** |
| NFIQ2 train supervised với target là match score của VeriFinger (minutiae-based, ~2010). Khi matcher hiện đại như MDGT/DINOv2 đánh giá ảnh khác, quality score không còn tương quan. |
| |
| **Nhược điểm 2 — Feature thiên về optical sensor:** |
| 5 feature tay của NFIQ2 (OCL, LCS, FDA, RVU, OFL) thiết kế cho contact optical. Fingerprint contactless hoặc flat press sẽ có Q thấp dù matcher hiện đại match được. |
| |
| **Nhược điểm 3 — Sensor bias:** |
| Cùng một ngón tay chụp bằng 2 sensor khác nhau → NFIQ2 cho 2 điểm chênh nhau 20–30 đơn vị. Metric đang đo sensor signature thay vì biometric quality thực sự. |
| |
| ### SIFQ giải quyết bằng cách nào? |
| |
| Thay vì dùng matcher score làm label, SIFQ dùng **3 tín hiệu tự giám sát bổ trợ nhau**: |
| |
| | Signal | Vai trò | Ràng buộc | |
| |--------|---------|-----------| |
| | `L_mat` — Matcher-as-teacher | Q phải tương quan với embedding quality của MDGT | Task-relevant | |
| | `L_sens` — Cross-sensor invariance | Q phải giống nhau cho cùng ngón tay ở 2 sensor khác nhau | Sensor-invariant | |
| | `L_deg` — Controlled degradation | Q phải giảm khi ảnh bị degraded (blur, noise, occlusion...) | Ordinal grounding | |
|
|
| Ba tín hiệu tạo **equilibrium**: Q không thể chỉ distill MDGT (vì L_sens ngăn sensor bias), không thể chỉ đo sensor difference (vì L_deg buộc phải predict degradation order), không thể chỉ rank degradation synthetic (vì L_mat kéo về matcher reality). |
| |
| **Điểm cân bằng duy nhất là Q đo đúng biometric quality thực sự.** Bảng dưới cho thấy nếu thiếu bất kỳ signal nào: |
| |
| | Nếu chỉ có... | Thì model sẽ... | |
| |--------------|----------------| |
| | Chỉ `L_mat` | Distill MDGT → không sensor-invariant | |
| | Chỉ `L_sens` | Cho tất cả ảnh cùng score → L_pair = 0 dễ dàng | |
| | Chỉ `L_deg` | Học ranking degradation synthetic, không transfer sang ảnh real | |
| | `L_mat + L_sens` | Không có ordinal grounding → score không có ý nghĩa tuyệt đối | |
| | `L_sens + L_deg` | Không liên kết với matcher reality | |
|
|
| **⚠️ Bài học từ v15–v19 (score collapse):** |
| Ngoài việc cần đủ 3 signal, còn cần đảm bảo: |
| 1. **`L_mat` cần per-image quality gradient thực sự**: Raw cosine với multi-sensor prototype |
| (proto_max_batches=0) → cosine varies with quality, not sensor. Partial prototype |
| (proto_max=150) → cosine bị sensor-bias → không phân biệt quality → collapse. |
| 2. **`L_deg` phải áp dụng cho SD302 chứ không chỉ FVC**: FVC-only L_deg → model học |
| quality function cho FVC nhưng SD302 không có per-image signal → SD302 collapse ở inference. |
| L_spread_ds (per-dataset spread, T27) ngăn score anchoring → an toàn để bật L_deg full cho SD302. |
| 3. **`L_spread_ds` là batch-level, không đủ**: Batch spread thỏa mãn bằng arbitrary ordering, |
| không phải quality. Phải kết hợp với per-image signal từ L_mat + L_deg. |
| |
| --- |
| |
| ## 2. Kiến trúc — 4 Components |
| |
| ``` |
| Image [B,1,224,224] |
| │ |
| ▼ |
| ┌────────────┐ |
| │ Backbone │ TinyViT-5M, grayscale |
| │ TinyViT │ forward_spatial() → [B,196,320] |
| └────────────┘ |
| │ |
| ├── mean(dim=1) → [B, 320] features ──────────────────────────┐ |
| │ │ |
| │ (SpatialConceptHead path: [B,196,320]) ▼ |
| ▼ (ConceptHead legacy: mean-pool → [B,320]) ┌──────────────────┐ |
| ┌──────────────────┐ │ SensorDisc │ |
| │ ConceptHead / │ [B,?]→ … →[B,6] ∈ [0,1] │ GRL(λ) → │ |
| │ SpatialConcept │ see §2.2 for both variants │ [B,64]→[B,Ns] │ |
| └──────────────────┘ └──────────────────┘ |
| │ concepts [B, 6] │ sensor_logits |
| ▼ ▼ |
| ┌──────────────────┐ adversarial sensor loss |
| │ ScoreAggregator │ [B,6]→[B,32]→[B,1]→Sigmoid→×100 |
| └──────────────────┘ |
| │ Q [B,1] ∈ [0, 100] |
| |
| outputs = { "score": Q, "concepts": C, "sensor_logits": S, "features": F } |
| ``` |
| |
| --- |
| |
| ### 2.1 Backbone — `src/models/backbone.py` |
| |
| | | | |
| |---|---| |
| | **Model** | `timm: tiny_vit_5m_224.dist_in22k` | |
| | **Input** | `[B, 1, 224, 224]` — grayscale | |
| | **Output** | `[B, 320]` — global average of spatial tokens | |
| |
| `forward_spatial()` extracts 14×14 token features → mean pool → `[B, 320]`. |
| |
| - TinyViT-5M (not 2M): 2M insufficient capacity for 3 simultaneous losses |
| - Not shared with MDGT: avoids circular dependency; on-sensor deployment target (<50ms ARM Cortex-A72) |
| |
| --- |
| |
| ### 2.2 Concept Head — `src/models/concept_head.py` |
| |
| Two implementations exist. The active version depends on the training flag: |
| |
| **`ConceptHead` (legacy — v16–v26, default `--spatial-concept-head` not set):** |
| ``` |
| Input: [B, 320] — globally-pooled backbone output |
| Linear(320→256) → LayerNorm → GELU → Linear(256→6) → Sigmoid |
| Output: [B, 6], each concept ∈ [0, 1] (high = better quality) |
| ``` |
| Loses all spatial structure before concept prediction. |
| |
| **`SpatialConceptHead` (v27+, enabled via `--spatial-concept-head`):** |
| ``` |
| Input: [B, 196, 320] — backbone.forward_spatial() (14×14 token map) |
| Shared trunk : Linear(320→128) → LayerNorm → GELU → [B, 196, 128] |
| Per-concept : 6 × Linear(128→1) → mean(dim=1) → [B, 6] |
| Activation : Sigmoid → [B, 6] ∈ (0, 1) |
| ``` |
| Each concept projection learns which spatial regions matter (ridge breaks for |
| `continuity`, orientation edges for `orientation_coherence`, bifurcation patches |
| for `minutiae_reliability`). Separate weights per concept reduce entanglement. |
| |
| `SIFQ.forward()` auto-dispatches via `concept_head.uses_spatial` attribute — |
| backward-compatible with all existing checkpoints. |
| |
| **6 concepts (all decrease with degradation — T25):** |
|
|
| | Idx | Name | Meaning | Supervised by | |
| |-----|------|---------|---------------| |
| | 0 | `orientation_coherence` | Ridge flow consistency | dry_skin, wet_press (T39) | |
| | 1 | `ridge_valley_clarity` | Sharp ridge-valley boundaries | blur, jpeg, wet_press, **noise (T42)** | |
| | 2 | `continuity` | Unbroken ridge lines | blur, jpeg | |
| | 3 | `noise_level` | Low noise (↑ = cleaner — T25) | noise | |
| | 4 | `contrast_uniformity` | Even foreground contrast | dry_skin | |
| | 5 | `minutiae_reliability` | Reliable minutiae extraction | occlusion, wet_press | |
| |
| **T42 changes (v32):** |
| - `continuity[2]` removed from `dry_skin`: dry_skin causes ridge fragmentation — at TinyViT patch scale (16×16 px) this looks identical to Gaussian noise texture (both = local high-frequency disruptions). When concept[2] is pulled down by dry_skin, concept[3] (noise_level) follows via shared feature paths → spurious crosstalk (v31 Spearman −0.758). Fix: dry_skin supervised by `contrast[4] + orientation[0]` only — these operate at multi-patch/regional scale, not shared with noise. |
| - `clarity[1]` added to `noise`: TinyViT 16×16 patch embed averages out pixel Gaussian noise (σ=5–30) → concept[3] receives almost no gradient signal from noise alone (v31: noise→noise_level ρ = −0.081). Gaussian noise blurs ridge-valley boundaries at patch scale — clarity[1] detects this → strong ViT signal → provides gradient that reinforces concept[3] in the correct direction. |
| |
| Concepts are not required to be independent — blur reducing both clarity and continuity is physically correct. `L_ortho` only prevents extreme redundancy. |
|
|
| --- |
|
|
| ### 2.3 Score Aggregator — `src/models/aggregator.py` |
|
|
| ``` |
| Linear(6→32) → GELU → Linear(32→1) → Sigmoid → ×100 |
| Output: [B, 1] ∈ [0, 100] (NFIQ2-compatible scale) |
| ``` |
|
|
| `Q(x) = Aggregator(concepts(backbone(x)))` |
|
|
| > **Important:** `outputs["score"]` is already in [0, 100]. Do not multiply by 100 again. Old bug did this → loss thresholds were off by 10×. |
|
|
| --- |
|
|
| ### 2.4 Sensor Discriminator — `src/models/sensor_discriminator.py` |
| |
| ``` |
| GRL(λ) → Linear(320→64) → ReLU → Linear(64→N_sensors) |
| ``` |
| |
| **Gradient Reversal Layer** (`src/models/grad_reverse.py`): |
| - Forward: `f(x) = x` |
| - Backward: `∂L/∂x → −λ · ∂L/∂x` |
| |
| The discriminator is trained to classify sensor identity. GRL forces the backbone to produce features the discriminator *cannot* distinguish → backbone sheds sensor signature. |
| |
| > **TODO:** Paper specifies discriminator should receive intermediate concept-branch features, not raw backbone features. Currently uses backbone output. Not yet implemented. |
| |
| --- |
| |
| ## 3. Ba Loss Functions |
| |
| ### 3.1 `L_mat` — Matcher-as-Teacher |
| |
| **File:** `src/losses/matcher_teacher.py` |
| **Teacher model:** `src/training/mdgt_teacher.py` — load từ `pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt` (DINOv2 ViT-S/14, frozen hoàn toàn) |
| |
| **Công thức:** |
| |
| $$q_{mat}(x) = \frac{\cos(\text{MDGT}(x),\ c_y) - \mu_y}{\sigma_y}$$ |
| |
| $$L_{mat} = \text{Huber}(Q_{normalized}(x),\ q_{mat}(x))$$ |
| |
| Trong đó: |
| - $c_y$ = prototype của identity $y$ (trung bình L2-normalized embeddings) |
| - $\mu_y, \sigma_y$ = mean/std cosine similarity trong class $y$ |
| - $Q_{normalized} = (Q/100 - 0.5) \times 2$ — đưa [0,100] về xấp xỉ [-1, 1] |
| |
| **Code mapping:** |
| |
| ```python |
| # Compute prototype: trung bình embeddings per identity |
| proto = F.normalize(stack(emb_list).mean(0), dim=-1) |
| |
| # v16 (T31): compute per-identity cosine stats (second pass, frozen teacher) |
| # stats[identity] = (mean_cos, std_cos) — min_sigma = 0.02 |
| stats = compute_identity_cos_stats(loss_mat, prototypes, proto_loader, device) |
| |
| # q_mat: cosine similarity normalize per-identity, clamp bằng tanh |
| cos = dot(emb[i], proto[identity_id]) |
| z = (cos − mu_i) / sigma_i |
| q_mat[i] = tanh(z) # ∈ (−1, 1), zero-centred |
|
|
| # Loss |
| pred_normalized = (score / 100.0 - 0.5) * 2.0 |
| return HuberLoss(pred_normalized, q_mat) |
| ``` |
| |
| **Vấn đề v15 (stats=None):** Raw cosine ≈ 0.85 cho mọi ảnh → teacher kéo tất cả score về 92.5, conflict với L_spread → score collapse. Xem TODO T31. |
|
|
| **v16 fix (T31):** Per-identity stats normalization + tanh → teacher target zero-centred, tương thích L_spread. Ảnh tốt hơn trung bình identity → target > 0 → Q > 50. Ảnh kém hơn → target < 0 → Q < 50. |
| |
| **v18 revert (T33a — `--no-mat-stats`):** Skip per-identity cosine stats hoàn toàn. Tất cả images (FVC + SD302) đều dùng raw cosine làm L_mat target → không còn FVC/SD302 quality signal asymmetry. Root cause v17: FVC images có stable per-image tanh targets (từ FVC-only stats) nhưng SD302 images chỉ có raw cosine constant ≈ 0.85 → model học shortcut "FVC=variable quality, SD302=fixed quality ~52.7" → GRL + L_pair triệt tiêu SD302 quality features vì không có L_mat gradient để duy trì chúng. Revert về v14 design: tất cả images dùng raw cosine → L_mat chỉ còn tác dụng anchor mean (không gây asymmetry). |
| |
| --- |
| |
| ### 3.2 `L_sens` — Cross-Sensor Invariance |
|
|
| **File:** `src/losses/sensor_invariance.py` |
|
|
| **Công thức:** |
|
|
| $$L_{pair} = \max(0,\ |Q(x_{s1}) - Q(x_{s2})| - \delta)$$ |
| |
| $$L_{adv} = -\log D(\text{sensor} \mid f(x))$$ |
|
|
| $$L_{sens} = L_{pair} + \lambda_{adv} \cdot \min(L_{adv},\ \ln N_{sensors})$$ |
| |
| Với $\delta = 0.05$, $\lambda_{adv} = 0.3$. Clamp $\min(L_{adv}, \ln N)$ ngăn GRL anti-correlation (T16). |
| |
| **Code mapping (v11 — GRL anti-correlation fix):** |
| |
| ```python |
| # Pairs: cùng identity_id + finger_id, khác sensor_id (built trong batch) |
| l_pair = relu((score_s1 - score_s2).abs() - 0.05).mean() |
| |
| # Adversarial: backbone phải fool sensor discriminator |
| l_adv = cross_entropy(sensor_logits, sensor_labels) |
| |
| # GRL anti-correlation fix (T16): clamp l_adv tại random-guess baseline. |
| # Nếu CE > log(num_sensors): backbone đã đủ confuse discriminator, dừng |
| # gradient reversal — tránh việc backbone học anti-encode sensor identity. |
| rand_ce = log(sensor_logits.size(1)) # log(32) ≈ 3.47 |
| l_adv_clamped = l_adv.clamp(max=rand_ce) |
| |
| # Returns (total, l_pair_detached, l_adv_detached) for diagnostics |
| return l_pair + 0.3 * l_adv_clamped, l_pair.detach(), l_adv.detach() |
| ``` |
| |
| **Quan sát v11 trước khi fix (T16):** `l_adv` dao động 7–16 trong S2–S4, gấp 2–4× random baseline log(32)≈3.47. Diễn giải: backbone không chỉ "mờ" sensor mà học predict sai sensor với high confidence (anti-correlation). Discriminator thích ngưỡc lại → cái cycle không dừng. Clamp ngăn vòng lặp này. |
| |
| **Pair building — `train_sifq.py::build_pair_indices()`:** |
| Group batch theo `(identity_id, finger_id)` → tất cả cặp khác sensor_id trong cùng group. |
| |
| **Quan hệ giữa `L_pair` và `L_adv` — hai cơ chế bổ trợ:** |
| |
| | | `L_pair` | `L_adv` (GRL) | |
| |--|---------|---------------| |
| | Ép ở tầng nào | **Output** — Q score phải bằng nhau | **Feature space** — backbone không được encode sensor info | |
| | Cách hoạt động | Hinge loss trực tiếp trên Q | Gradient reversal qua discriminator | |
| | Tại sao cần cả 2 | Chỉ ép output: backbone vẫn giữ sensor info ẩn trong features | Chỉ ép feature: Q vẫn có thể tái encode sensor qua concept head | |
| |
| **Dataset novelty:** SIFQ là method đầu tiên đưa explicit invariance constraint vào quality learning. NFIQ2 không có mechanism này. |
| |
| --- |
| |
| ### 3.3 `L_deg` — Controlled Degradation Ranking |
| |
| **File:** `src/losses/degradation_ranking.py` |
| **Pipeline:** `src/data/degradation.py` |
| |
| **Công thức:** |
| |
| $$L_{rank} = \max(0,\ Q(x_{high}) - Q(x_{low}) + m) + \max(0,\ Q(x_{low}) - Q(x_{clean}) + m)$$ |
| |
| $$L_{concept\_deg} = \sum_{(deg, c_{target})} \text{Huber}(c_{target}(x_{low}),\ c_{target}(x_{high}) + 0.1)$$ |
| |
| $$L_{deg} = L_{rank} + \gamma \cdot L_{concept\_deg}$$ |
| |
| Với $m=0.1$ (ranking margin), $\gamma=0.5$. |
| |
| **Degradation concept map (index) — T42 (v32) — current:** |
| |
| ```python |
| DEGRADATION_CONCEPT_MAP = { |
| "blur": [1, 2], # clarity↓, continuity↓ |
| "noise": [1, 3], # clarity↓ (T42 co-target), noise_level↓ |
| "jpeg": [2, 1], # continuity↓, clarity↓ |
| "occlusion": [5], # minutiae_reliability↓ only ← T38: reverted from [5,2] to paper |
| "dry_skin": [4, 0], # contrast_uniformity↓, orientation_coherence↓ ← T42: removed continuity |
| "wet_press": [1, 5, 0], # clarity↓, minutiae_reliability↓, orientation_coherence↓ (T39) |
| } |
| ``` |
| |
| **T42 physical reasoning (v32):** |
|
|
| | Change | Before | After | Physical reason | |
| |--------|--------|-------|-----------------| |
| | `noise` | `[3]` | `[1, 3]` | TinyViT patch embed (16×16 px) averages out pixel Gaussian noise σ=5–30 → concept[3] gradient ≈ 0 alone. But noise **also blurs ridge-valley edges** at patch scale (clarity[1]) → ViT detects this → provides training signal that anchors concept[3] in the correct direction. v31: noise→noise_level ρ = −0.081 (very weak). | |
| | `dry_skin` | `[4, 2, 0]` | `[4, 0]` | `continuity[2]` operates at **local patch scale** — same as Gaussian noise texture. dry_skin ridge fragmentation and pixel noise both create "high-frequency local disruptions" in 16×16 patches → shared backbone feature path → when concept[2] is pulled ↓ by dry_skin, concept[3] follows → spurious crosstalk (v31: dry_skin→noise_level ρ = −0.758). Removing continuity forces backbone to use `contrast[4]` (regional brightness gradient) + `orientation[0]` (multi-patch coherence field) — both are **regional-scale** features, not shared with noise. | |
|
|
| **T38 fix — wet_press `[1, 4]` → `[1, 5]` (reverted to paper design):** |
| |
| Root cause: `MorphologicalDilator` used a fixed 3×3 kernel — at 500 DPI, 1 erode iteration = ~1 px ridge expansion, too subtle. Model read level 1 as "good ink coverage" → `minutiae_reliability(level_1) > level_0` → non-monotonic → ρ > 0 (wrong). Consistently wrong: v14 = +0.565, v20 = +0.246, v21 = +0.307. |
| |
| Fix: Scale kernel + blur with severity in `degradation.py`: `ks = 3 + 2*iterations` (5×5/7×7/9×9), `sigma = 1.0 + 0.8*iterations` (1.8/2.6/3.4). Level 1 now visibly impairs bifurcations. Concept map KEPT at `[1, 5]` as designed. |
| |
| **T38 fix — occlusion `[5, 2]` → `[5]` (reverted to paper design) + coverage 55% → 40%:** |
|
|
| T26 added `continuity[2]` because occlusion signal was near-zero, and pushed coverage to 55%. Root cause of weak signal was actually the **unseeded random block positions in eval** — different levels placed blocks in different spots → Spearman ρ incoherent. Now fixed by `np.random.seed(level)` in `compute_crosstalk_matrix` (T38b). With deterministic eval, `[5]` alone provides a clean signal. Coverage reverted to paper range: `0.133 × level` → level 3 = 40% max. |
|
|
| **Note**: Training occlusion still uses random positions (generalization). Only eval is seeded. |
|
|
| **T30 (v15): SD302 concept-only L_deg** — Root cause regression v14: concept head chỉ thấy FVC texture khi bị degraded; eval trên SD302 images thất bại (noise→noise_level: -0.019). |
| - **T30a**: `concept_deg_gamma 0.5 → 2.0` — L_concept 4× mạnh hơn so với L_rank |
| - **T30b**: Apply degradation cho SD302 batch items, chỉ compute L_concept (không L_rank → không score collapse). Lần đầu tiên concept head thấy degraded SD302. |
| - **T30c**: `deg-every-n-steps 2` (giảm từ default 4, giới hạn bởi OOM: 3 forward pass/step với batch=64) |
| |
| **DegradationPipeline — 6 loại, 4 levels (0=clean, 1–3 tăng dần):** |
|
|
| | Type | Kỹ thuật | Severity range | |
| |------|---------|----------------| |
| | `blur` | GaussianBlur kernel $k = 2\lfloor 0.5 + level \times 0.83 \rfloor + 1$ | σ tăng theo level | |
| | `noise` | Additive Gaussian, $\sigma = 5 + level \times 8.3$ | 5→30 | |
| | `jpeg` | JPEG compression quality = $90 - level \times 25$ | 90→15 | |
| | `occlusion` | White block $= 13.3\% \times level$ coverage | 13%→40% | |
| | `dry_skin` | `DrySkinSimulator`: contrast reduce + crack lines | severity 1→3 | |
| | `wet_press` | `MorphologicalDilator`: kernel scales 5×5/7×7/9×9, sigma 1.8/2.6/3.4 | levels 1→3 | |
|
|
| **Code trong training loop (v6 fix):** |
|
|
| ```python |
| # Random sample 1 trong 6 types mỗi deg step |
| deg_type = random.choice(_DEG_TYPES) |
| level_lo = random.randint(1, 2) |
| level_hi = 3 |
| |
| # Tensor [B,1,H,W] float[0,1] → numpy [B,H,W] uint8 |
| imgs_np = (images[:,0].cpu().numpy() * 255).astype(np.uint8) |
| |
| # Apply degradation per image |
| imgs_low = stack([deg_pipeline.apply(img, deg_type, level_lo) for img in imgs_np]) |
| imgs_high = stack([deg_pipeline.apply(img, deg_type, level_hi) for img in imgs_np]) |
| |
| # Forward pass qua model |
| out_low = model(imgs_low_tensor) |
| out_high = model(imgs_high_tensor) |
| |
| l_deg = loss_deg(score_clean, out_low["score"], out_high["score"], |
| out_low["concepts"], out_high["concepts"], deg_type) |
| ``` |
|
|
| **Tất cả concepts GIẢM khi degradation tăng (v13 — T25 fix):** |
|
|
| ```python |
| # T25: Bỏ if c_idx == 3 special case. |
| # Tất cả concepts: high = better quality, low = worse quality. |
| # noise_level mới: high = ít nhiễu = tốt (ngược v12) |
| for c_idx in DEGRADATION_CONCEPT_MAP[deg_type]: |
| l_concept += huber(concepts_low[:, c_idx], concepts_high[:, c_idx] + 0.1) |
| # concepts_low[c] > concepts_high[c] + 0.1 |
| # → more degraded image has lower concept score |
| ``` |
|
|
| **Trước v13 (v12, BUG):** `noise_level` được push tăng theo degradation level. ScoreAggregator resolve conflict bằng cách invert direction → noise_level=-0.168 (Track 4, sai chiều). |
| |
| --- |
| |
| ### 3.4 `L_ortho` — Concept Decorrelation |
|
|
| **File:** `src/losses/orthogonality.py` |
|
|
| $$L_{ortho} = \| \text{off\_diag}(\text{corrcoef}(C)) \|_F^2$$ |
| |
| ```python |
| # Standardize per concept (zero-mean, unit-std across batch) |
| x = concepts - concepts.mean(dim=0, keepdim=True) |
| x = x / (x.std(dim=0, keepdim=True) + 1e-6) |
| corr = (x.T @ x) / max(1, x.shape[0] - 1) # [6, 6] Pearson corr |
| off_diag = corr - eye(6) |
| return (off_diag ** 2).sum() # Frobenius² of off-diagonal |
| ``` |
| |
| Regularize để concepts không hoàn toàn redundant. Không có weight — luôn cộng thẳng vào total loss. |
| |
| --- |
| |
| ### 3.5 Spread Loss (Uniformity) — thêm vào trong training loop |
| |
| **Không có file riêng** — implement trực tiếp trong `scripts/train_sifq.py`. |
|
|
| ```python |
| # uniform mode (v8 default) — force sorted Q-scores → linspace(10, 90) |
| q_sorted, _ = q_batch.sort() |
| target_unif = torch.linspace(10.0, 90.0, n_q, device=device) |
| l_spread = F.mse_loss(q_sorted / 100.0, target_unif / 100.0) |
| # Gradient ép trực tiếp phân bố score: ảnh tốt nhất → 90, xấu nhất → 10 |
| ``` |
|
|
| Weight lịch sử: v15 = 2.0 → v16/v17 = 4.0 → **v18 revert 2.0 (T33b)** → **v21 = 3.0** (`--spread-weight 3.0`). Default code = 4.0. W_SPREAD áp dụng cho **CẢ HAI** `L_spread_global` và `L_spread_sd302`. |
| |
| **Thay thế variance mode của v7** (`relu(10/100 - q_std/100)^2`, max=0.01) vốn bị bão hòa ngay từ đầu (spread=0.010 stuck toàn bộ training). |
|
|
| **v18 (T33b):** W_SPREAD revert về 2.0. W_SPREAD=4.0 cùng với gamma=2.0 làm tệ hơn v14 trong v15–v17. |
|
|
| **v21:** W_SPREAD=3.0 — trung dung giữa v14 (2.0) và v16/v17 (4.0), kết hợp với `--proto-max-batches 0` (full prototypes) và FVC-only L_deg. |
|
|
| --- |
|
|
| ### 3.6 Total Loss |
|
|
| $$L(t) = \alpha(t) \cdot L_{mat} + \beta(t) \cdot L_{sens} + \gamma(t) \cdot L_{deg} + L_{ortho} + w_{spread} \cdot (L_{spread} + L_{spread\_sd302})$$ |
|
|
| Trong đó: |
| - $L_{spread}$: MSE toàn batch (sorted Q → linspace(10,90)) |
| - $L_{spread\_sd302}$: MSE chỉ SD302 subset trong batch (≥8 ảnh) — ép SD302 spread riêng, tránh SD302 dùng FVC variation để thỏa spread (T27) |
| - $w_{spread}$ = 3.0 (v21) — áp cho **cả hai** thành phần spread |
|
|
| --- |
|
|
| ## 4. Training Stage Scheduler |
|
|
| **File:** `src/training/stage_scheduler.py` |
|
|
| | Stage | Epochs | α (mat) | β (sens) | γ (deg) | β/α | Mục đích | |
| |-------|--------|---------|----------|---------|-----|----------| |
| | S1 | 0–9 | 0.10 | **0.00** | 1.00 | 0 | Bootstrap quality ordering từ degradation | |
| | S1→S2 ramp | 10–19 | **0.10→0.28** | **0.00→0.27** | **1.00→0.64** | 0→0.96 | β ramps NHANH HƠN α — β/α → 1.0 ở S2 entry | |
| | S2 | 20–34 | 0.30 | 0.30 | 0.60 | **1.0** | Balanced: GRL pressure = mat pressure | |
| | S2→S3 ramp | 35–39 | **0.30→0.29** | **0.30→0.34** | **0.60→0.52** | >1.0 | β vượt α smooth | |
| | S3 + S4 | 40+ | 0.25 | 0.35 | **0.50** | **1.4** | β > α, γ floor = 0.50 | |
|
|
| > **v21 chạy 60 epochs** → S3 kết thúc ở ep59. S4 (ep60+) không được sử dụng. Code scheduler dùng `(40, 999)` làm sentinel nên logic không thay đổi — chỉ số epoch thực tế bị cắt ngắn bởi `--epochs 60`. |
|
|
| **GRL λ warm-up (DANN schedule):** |
|
|
| $$\lambda(p) = \min\!\left(0.6,\ \frac{2}{1+e^{-10p}}-1\right), \quad p = \frac{\text{epoch}}{\text{total\_epochs}}$$ |
| |
| - ep0: λ=0.000 |
| - ep10: λ=0.555 |
| - ep12+: λ=0.600 (cạn max) |
| |
| **Cosine LR decay (v8 mới):** LR decay từ 1e-4 → 5e-6 theo cosine. Trước với LR cố định → S4 oscillation (v7: loss tăng từ 0.53 lên 1.18 trong ep61-80). |
| |
| **Vì sao β/α phải = 1.0 ngay từ S2 (v11 vs v9):** |
| V9 bug: β/α = 0.50 trong S2 (α=0.40, β=0.20). PolyU contact vs contactless là cross-modality pairs cực mạnh — GRL với β quá thấp không đủ mạnh để override L_mat pressure, backbone vẫn encode sensor/modality signature. Kết quả: L_sens oscillate 2–3 suốt S2/S3. V11: β ramps nhanh hơn α (β Δ0.30 vs α Δ0.20 qua 10 epoch) → β/α = 1.0 NGAY KHI vào S2. GRL và L_mat có sức nặng bằng nhau từ đầu. |
| **PolyU treatment (v11):** PolyU chỉ góp vào L_sens. L_mat và L_deg mask out PolyU records (không compute prototype, không apply degradation cho PolyU images). |
| |
| **Vì sao β entry ramp quan trọng (v8 vs v7):** |
| V7: β nhảy 0→0.20 đột ngột tại ep10 → L_sens explosion: 0.77 (ep10) → 11.32 (ep18), mất 20 epoch phục hồi. |
|
|
| **Vì sao γ floor = 0.50 (v8/v9) thay vì 0.40 (v7):** |
| V7: L_deg plateau tại 0.104 từ ep43+ — chính xác bằng margin m=0.10. γ=0.50 giữ grounding mạnh hơn. |
| |
| --- |
| |
| ## 5. Dataset Pipeline |
| |
| **Files:** `src/data/nist302_loader.py`, `src/data/fvc_loader.py` |
| |
| ``` |
| dataset/ |
| ├── 302a/images/challengers/ → sensors: A, B, C, D, E, F, G, H (8 sensors) |
| │ └── A/roll/png/ filename: {subject}_{sensor}_{captype}_{finger}.png (4 tokens) |
| ├── 302b/images/baseline/ → sensors: R_500, S_500, U_500, V_500 (4 sensors) |
| │ └── U/500/roll/png/ filename: {subject}_{sensor}_{dpi}_{captype}_{finger}.png (5 tokens) |
| ├── nist_302d/images/auxiliary/ → sensors: flat_K, flat_L, flat_M, flat_P (4 sensors) |
| └── FVC_Dataset/ |
| ├── FVC2002/Dbs/Db1_a|Db2_a... filename: {subject}_{impression}.tif |
| └── FVC2004/Dbs/DB1_A|DB2_A... |
| ``` |
| |
| **Đầy đủ sau khi fix: 37,607 ảnh, 22 sensors** |
|
|
| | Dataset | Ảnh | Sensors | Role | Signal | |
| |---------|------|---------|------|--------| |
| | SD302-A (302a) | 13,630 | A–H (8) | Cross-sensor invariance | L_sens, L_mat | |
| | SD302-B (302b) | 11,796 | R,S,U,V (4) | Cross-sensor invariance | L_sens, L_mat | |
| | SD302-D (302d) | 5,141 | K,L,M,P (4) | Cross-sensor invariance | L_sens, L_mat | |
| | FVC2002 | 3,520 | 4 DBs | Matcher-teacher quality anchor | L_mat, L_deg | |
| | FVC2004 | 3,520 | 4 DBs | Matcher-teacher quality anchor | L_mat, L_deg | |
| | PolyU (contact) | 2,976 | 1 (polyu_contact) | Cross-modality hardest invariance | **L_sens ONLY** | |
| | PolyU (contactless) | 2,976 | 1 (polyu_contactless) | Cross-modality hardest invariance | **L_sens ONLY** | |
| |
| |
| > **† Lưu ý cột `noise_level`**: Giá trị theo hướng **model concept[3]**: `Cao` = ít nhiễu = ảnh sạch = tốt (ngược chiều với lượng noise vật lý trong ảnh). Bảng gốc dùng hướng image-domain (Thấp noise=sạch=tốt), nhưng đã được đổi sang hướng concept để nhất quán với kỳ vọng model output. Ví dụ: SD302a rất sạch → concept[3] dự kiến = `Cao`; FVC2004 DB3 nhiều noise → concept[3] dự kiến = `Thấp`. |
|
|
| **Tổng v11: 43,559 ảnh, 24 sensors, 2,612 eligible cross-sensor anchor groups** |
|
|
| **Tổng v14: 42,683 ảnh, 29 sensors** (sau khi loại `R_1000_slap`, `R_500_slap`, `S_500_slap` — ~1,700 non-segmented slap records). Anchor groups: 2,336 eligible. |
|
|
| **PolyU Cross-Fingerprint Database (v9+):** |
| 336 subjects × 6 impressions × 2 modalities = 5,952 ảnh. Cùng ngón tay được chụp bằng CMOS camera (contactless) và URU sensor (contact). Đây là cross-modality pairs mạnh nhất cho L_sens — harder invariance target so với cross-brand sensors trong SD302. File: `src/data/polyu_loader.py`. |
|
|
| **Tại sao SD302 không góp vào L_deg:** |
| SD302 toàn ảnh chất lượng cao (protocol NIST ảnh cần đạt chuẩn). Degradation synthetic trên nó là giả tạo, không phản ánh quality variation thực. FVC có 8 lần chụp cùng ngón tay với **chất lượng tự nhiên dao động** → MDGT xếp hạng thực sự giữa các impression → L_deg có signal vật lý. Thiết kế tách biệt vai trò: SD302 = sensor role, FVC = quality role. |
| |
| **Tại sao FVC cần thiết cho L_mat:** |
| SD302 chỉ có ảnh chất lượng cao → q_mat ≈ constant → L_mat tầm thường. FVC có 8 lần chụp cùng ngón tay (chất lượng thực sự dao động) → MDGT có thể xếp hạng các lần chụp trong cùng subject → q_mat có signal thực sự. |
|
|
| **Metadata parsing:** |
|
|
| | Filename format | Tokens | identity_id | finger_id | sensor_id | |
| |----------------|--------|-------------|-----------|----------| |
| | SD302-A: `00002303_A_roll_05.png` | 4 | `00002303` (stem[0]) | `F05` (stem[-1]) | path-based `A_roll_png` | |
| | SD302-B/D: `00002401_U_500_roll_07.png` | 5 | `00002401` | `F07` | `U_500_roll` | |
| | FVC: `042_3.tif` | 2 | `2002_db1_0042` | `f01` | `fvc2002_db1` | |
|
|
| **Audit kết quả (kiểm tra thực tế):** |
|
|
| - **Finger ID nhất quán across sensors ✅**: 2,000 (subject, finger) pairs xuất hiện ở ≥2 sensors trong cả 302a và 302b |
| - Ví dụ: subject `00002303`, finger `05` → xuất hiện ở cả 8 sensors A–H → cặp L_sens cực tốt |
| - 200 subjects xuất hiện trong cả 302b và 302d → cross-subset L_sens pairs |
| - FVC: mỗi subject có 1 ngón tay duy nhất (finger_id = `f01`) → không có cross-sensor pairs |
| |
| **Bug đã fix: 302a parser:** |
| Parser cũ yêu cầu `len(tokens) >= 5` nhưng 302a chỉ có 4 tokens → **13,630 ảnh bị bỏ hoàn toàn**. Đã sửa thành `>= 4`. Sensor_id từ path vẫn đúng (`A_roll_png`, `B_roll_png`...). |
|
|
| **Risk R1 (cập nhật):** Finger_id đã được xác nhận là nhất quán across sensors trong NIST SD302. Protocol NIST yêu cầu cùng ngón tay trình cho tất cả sensor → finger number có ý nghĩa vật lý. ✅ Không còn là risk. |
| |
| --- |
| |
| ## 6. Evaluation 5 Tracks |
| |
| ### Track 1 — Error Rejection Curve (Primary) |
| |
| **File:** `src/evaluation/erc.py` |
| |
| Sắp xếp ảnh theo Q tăng dần → reject bottom x% → compute FNMR tại FMR=1e-4 trên phần còn lại → plot curve. |
| |
| **AUC_ERC: thấp hơn = tốt hơn.** |
| |
| Kết quả v5: SIFQ=0.8884 vs Random=0.8937 → hơn Random 0.5% — quá yếu. |
| Kỳ vọng v6: L_deg hoạt động → ảnh degraded được score thấp hơn → reject đúng → FNMR giảm nhanh hơn. |
|
|
| --- |
|
|
| ### Track 2 — Sensor Invariance (Core novelty) |
|
|
| **File:** `src/evaluation/sensor_invariance.py` |
|
|
| **KS statistic** (Kolmogorov-Smirnov) giữa Q distributions của 2 sensors: `KS = 0` → giống hoàn toàn. |
|
|
| **Pearson correlation** giữa Q(x_s1) và Q(x_s2) cho paired samples: cao hơn = nhất quán hơn. |
|
|
| | Metric | v11 | v12 | v13 | v14 | v15 | v16 | v17 | v18 actual | v20 actual | **v21 target** | |
| |--------|-----|-----|-----|-----|-----|-----|-----|------------|------------|--------| |
| | mean_ks | 0.557 | 0.510 | 0.634 ❌ | **0.263 ✅** | 0.276 ❌ | 0.527 ❌ | 0.616 ❌ | **0.249 ⚠️** | **0.4936 ❌** | **≤0.27** | |
| | Pearson | — | -0.003 | +0.224 | **+0.294 ✅** | — | 0.046 ❌ | -0.002 ❌ | **0.007 ❌** | **0.0048 ❌** | **≥0.20** | |
| | q_std (inference) | — | — | — | ~15 | — | 0.33 ❌ | 0.60 ❌ | **0.01 ❌❌** | **0.007 ❌❌** | **>12** | |
| | n\_sensor\_pairs | 91 | 91 | 91 | 55 | 55 | 55 | **171** (302a added) | **171** | **171** | **≥100** (302a) | |
|
|
| > **v21 — 🚀 Active training** (T36 fix: full prototypes `--proto-max-batches 0` + FVC-only L_deg). Reasoning: v20 collapsed because `--deg-include-sd302` created a ~53.38 attractor; removing it restores the v14 mechanism where FVC genuine quality variation trains the backbone quality features that transfer to SD302 at inference. |
| **⚠️ v20 score collapse — KS misleading (same as v18 pattern)**: Training q_std≈18.3 (looks healthy) but inference q_std≈0.007. All sensors cluster near 53.38 (A_roll: std=0.007, range 53.364–53.403). Root cause: `--deg-include-sd302` applied L_rank to all clean SD302 images. L_rank only requires Q(clean)>Q(degraded), NOT that different clean images score differently → single ~53.38 attractor satisfies the constraint for all clean SD302. FVC-only signals (genuine quality variation) were blocked by this attractor. Fix: **v21 removes `--deg-include-sd302`**, keeps `--proto-max-batches 0`. |
| > **⚠️ v18 score collapse — KS misleading**: KS=0.249 vượt target "≤0.27" nhưng là **false positive** — tất cả sensors output score ≈54.64 (q_std≈0.01, range 54.62–54.65), phân bố trivially giống nhau vì model không phân biệt được images. Pearson=0.007 xác nhận: hoàn toàn không có cross-sensor ranking consistency. Root cause: T33 revert về raw cosine L_mat (constant ≈0.85 cho tất cả) + không có per-image quality signal → model collapse về trung bình ≈54.64. Concept head cũng collapse: orientation_coherence≈0.995 và noise_level≈0.982 stuck near 1.0; clarity≈0.032, continuity≈0.027, contrast≈0.04, minutiae≈0.027 stuck near 0. |
|
|
| **v13 regression trên KS**: Non-segmented slap sensors (`R_1000_slap`, `R_500_slap`, `S_500_slap`) tạo cụm score ~21.2 (std≈0) → kéo mean_KS lên 0.634. **Pearson cải thiện đáng kể** (+0.224 vs -0.003) — consistent relative ranking tốt hơn. |
| |
| **v14 fix**: Loại non-segmented slap khỏi training và eval (`--exclude-sensor R_1000_slap,R_500_slap,S_500_slap`). |
| |
| **v14 training actuals (60 epochs, from scratch):** |
| - `q_mean` = 52.6 (ep59) — centered tốt hơn v13 (~33 train-time) |
| - `q_std` = 15.5 (ep59) — plateau sau khi GRL equilibrium (peak S1 = 22.6 → drop về 14 khi β kick-in ep11) |
| - `l_pair` = 0.006 (ep59) — sensor invariance xuất sắc, gần bằng 0 |
| - `l_mat` = 0.270 — converged, giảm từ 0.378 (ep0) |
| - 3-phase dynamics: S1 (spread explosion ep0-10) → Transition (GRL compression ep11-15) → Equilibrium (stable ep16-59) |
|
|
| **v14 eval results:** mean_KS = **0.263** ✅ (giảm từ 0.634), Pearson = **+0.294** ✅ (tăng từ 0.224). |
| |
| **Đây là figure quan trọng nhất của paper.** Plot histogram Q per sensor — NFIQ2 expected các histogram tách biệt, SIFQ expected overlap cao. |
| |
| --- |
| |
| ### Track 4 — Concept Grounding (Interpretability claim) |
| |
| **File:** `src/evaluation/concept_grounding.py` |
|
|
|
|
| Sweep degradation level 0→3, tính Spearman ρ giữa level và concept score. |
|
|
| **Cross-talk matrix lý tưởng:** diagonal-heavy — mỗi degradation chỉ ảnh hưởng đến target concept của nó (Spearman ρ mạnh âm trên diagonal, gần 0 off-diagonal). |
|
|
| **Kết quả v13 (Spearman ρ):** |
|
|
| | degradation | orient. | clarity | continuity | noise_lvl | contrast | minutiae | |
| |-------------|---------|---------|-----------|-----------|----------|----------| |
| | **blur** | +0.19 | **-0.49** ✅ | -0.10 | +0.10 | +0.22 | +0.11 | |
| | **noise** | +0.05 | +0.46 | -0.12 | **-0.53** ✅ | -0.06 | -0.20 | |
| | **jpeg** | -0.11 | +0.03 | +0.03 | -0.08 | -0.04 | -0.02 | |
| | **occlusion** | +0.10 | -0.13 | -0.15 | +0.10 | -0.19 | **-0.09** ⚠️ | |
| | **dry_skin** | **-0.35** ✅ | +0.06 | +0.01 | -0.13 | **-0.38** ✅ | +0.01 | |
| | **wet_press** | -0.06 | **-0.48** ✅ | +0.24 | -0.16 | +0.44 | +0.33 | |
| |
| **Kết quả v14 (Spearman ρ):** |
| |
| | degradation | orient. | clarity | continuity | noise_lvl | contrast | minutiae | |
| |-------------|---------|---------|-----------|-----------|----------|----------| |
| | **blur** | +0.11 | **-0.19** ✅ | -0.003 | +0.08 | +0.22 | **+0.50** ❌ | |
| | **noise** | +0.001 | -0.16 | +0.03 | **-0.02** ⚠️ | +0.15 | +0.05 | |
| | **jpeg** | -0.18 | -0.07 | -0.10 | +0.08 | -0.11 | -0.09 | |
| | **occlusion** | +0.06 | +0.04 | **-0.12** ✅ | +0.18 | +0.07 | **+0.18** ❌ | |
| | **dry_skin** | +0.19 | -0.28 | **-0.56** ✅⬆ | **-0.56** ✅⬆ | **-0.62** ✅⬆ | +0.36 | |
| | **wet_press** | **-0.28** ✅ | -0.13 | +0.37 | -0.16 | +0.20 | **+0.57** ❌ | |
|
|
| **Nhận xét v14 so với v13:** |
| - ✅ **dry_skin**: cải thiện mạnh — clarity(-0.28), continuity(-0.56), noise_level(-0.56), contrast(-0.62) đều đúng chiều và mạnh hơn |
| - ✅ **Track 2 KS**: 0.634 → 0.263 (cải thiện lớn nhờ loại slap sensors) |
| - ✅ **Pearson**: 0.224 → 0.294 |
| - ⚠️ **noise→noise_level**: -0.533 (v13) → -0.019 (v14) — regression, gần bằng 0 |
| - ⚠️ **blur→clarity**: -0.490 (v13) → -0.187 (v14) — yếu hơn đáng kể |
| - ❌ **wet_press→minutiae**: +0.326 (v13) → +0.565 (v14) — sai chiều, tệ hơn |
| - ❌ **occlusion→minutiae**: -0.093 (v13) → +0.183 (v14) — flip sang sai chiều |
| |
| **Root cause v14 regression (T30):** Concept head chỉ thấy FVC texture khi degraded (FVC-only L_deg). Eval trên SD302 images — concept head không generalize. v15 fix bằng SD302 concept-only L_deg (T30b) + tăng gamma (T30a) + tăng tần suất (T30c). Eval v15: KS=0.2758 (tệ hơn v14), score range 24–56 (score collapse, không discrimination). |
|
|
| **Root cause v15 failure (T31 — v16 fix):** Score collapse toàn bộ 60 epochs (q_mean≈52.5, q_std≈16, score range 24–56). Chi tiết xem mục TODO T31. |
|
|
| --- |
|
|
| **Kết quả v18 (Spearman ρ — CONCEPT COLLAPSE + INVERSION):** |
|
|
| | degradation | orient. | clarity | continuity | noise_lvl | contrast | minutiae | |
| |-------------|---------|---------|-----------|-----------|----------|----------| |
| | **blur** | -0.572 ❌ | **+0.611** ❌❌ | +0.575 ❌❌ | -0.583 ❌ | +0.552 ❌ | -0.487 ❌ | |
| | **noise** | -0.410 ❌ | +0.288 ❌ | +0.368 ❌ | **-0.296** ✓ | +0.298 ❌ | +0.630 ❌❌ | |
| | **jpeg** | -0.097 | **+0.222** ❌ | +0.194 ❌ | -0.268 | +0.140 | -0.279 | |
| | **occlusion** | -0.162 | -0.151 ✓ | +0.042 ❌ | -0.150 | +0.063 | **-0.133** ✓ | |
| | **dry_skin** | +0.183 | -0.066 ✓ | +0.091 ❌ | +0.086 | **-0.247** ✓ | +0.230 ❌ | |
| | **wet_press** | -0.118 | **+0.217** ❌ | +0.196 ❌ | -0.320 | +0.140 | **-0.245** ✓ | |
| |
| **Chẩn đoán v18 concept collapse**: blur làm TĂNG clarity (+0.611) — đảo chiều hoàn toàn. Root cause: concept head bị stuck ở giá trị cực biên — orientation_coherence≈0.995 và noise_level≈0.982 (bão hòa gần 1.0); clarity≈0.032, continuity≈0.027, contrast≈0.04, minutiae≈0.027 (bão hòa gần 0.0). Khi degradation áp vào ảnh, không có dư địa để concept giảm thêm → bất kỳ thay đổi nhỏ nào đều là noise ngẫu nhiên, dẫn đến Spearman ρ không ổn định. Cùng cơ chế với score collapse (q_std≈0.01): model không phân biệt được input. |
|
|
| --- |
|
|
| ### Track 3 — Cross-Matcher Transfer (Reviewer defense) |
|
|
| Dùng Q của SIFQ (train với MDGT teacher) để tính ERC với **VeriFinger v12 match scores** (matcher chưa từng thấy). |
|
|
| Nếu AUC_ERC vẫn thấp → Q generalizable, không phải chỉ distill MDGT. |
| Hiện tại: chưa có VeriFinger license → bỏ qua hoặc dùng matcher khác. |
| |
| --- |
| |
| ### Track 5 — Human Correlation (Optional) |
| |
| Expert rate ảnh trên Likert 1–5, Spearman ρ với SIFQ score. Tốn công nhưng là evidence mạnh nhất. |
| |
| --- |
| |
| ## 7. File Map — Research Concept → Code |
| |
| | Khái niệm trong paper | File code | |
| |----------------------|-----------| |
| | Backbone (TinyViT-5M) | `src/models/backbone.py` | |
| | Concept Head (6 concepts, legacy v16–v26) | `src/models/concept_head.py::ConceptHead` | |
| | Concept Head (spatial, v27+) | `src/models/concept_head.py::SpatialConceptHead` | |
| | Score Aggregator Q(x) | `src/models/aggregator.py` | |
| | Gradient Reversal Layer | `src/models/grad_reverse.py` | |
| | Sensor Discriminator D | `src/models/sensor_discriminator.py` | |
| | SIFQ full model wrapper | `src/models/sifq.py` | |
| | $L_{mat}$ (Huber + prototype) | `src/losses/matcher_teacher.py` | |
| | $L_{sens}$ (pair + adversarial) | `src/losses/sensor_invariance.py` | |
| | $L_{deg}$ (ranking + concept) | `src/losses/degradation_ranking.py` | |
| | $L_{ortho}$ (decorrelation) | `src/losses/orthogonality.py` | |
| | MDGT teacher loader | `src/training/mdgt_teacher.py` | |
| | Stage scheduler α/β/γ | `src/training/stage_scheduler.py` | |
| | DegradationPipeline (6 types) | `src/data/degradation.py` | |
| | DrySkinSimulator | `src/data/degradation.py::DrySkinSimulator` | |
| | MorphologicalDilator | `src/data/degradation.py::MorphologicalDilator` | |
| | Dataset loader SD302 A/B/D | `src/data/nist302_loader.py` | |
| | Dataset loader FVC 2002/2004 | `src/data/fvc_loader.py` | |
| | Dataset loader PolyU (contactless↔contact) | `src/data/polyu_loader.py` | |
| | Cross-sensor pair builder | `scripts/train_sifq.py::build_pair_indices()` | |
| | Spread/Uniformity loss | `scripts/train_sifq.py` (inline) | |
| | Prototype computation | `scripts/train_sifq.py::compute_teacher_prototypes()` | |
| | Training main loop | `scripts/train_sifq.py::main()` | |
| | Track 1 ERC evaluation | `src/evaluation/erc.py` | |
| | Track 2 Sensor invariance | `src/evaluation/sensor_invariance.py` | |
| | Track 4 Concept grounding | `src/evaluation/concept_grounding.py` | |
| | Run training v21 (T36: full-proto + FVC-only L_deg, 60ep) | `scripts/run_train_v21.sh` | |
| | Run training v14 (segmented only, 60ep from scratch) | `scripts/run_train_v14.sh` | |
| | Run training v13 (80ep, resume v12) | `scripts/run_train_v13.sh` | |
| | Run eval v13 (exclude non-seg slap) | `scripts/run_eval_v13.sh` → `eval_results/v13_seg/` | |
| | Run inference | `scripts/run_infer.py` | |
| | Run evaluation | `scripts/run_eval.py` | |
| | Visualize score milestones | `visualize_score_milestones.py --exclude-sensor ...` | |
| | **MDGTv2 local pipeline** (DINOv2+TRAM+GNN) | `src/models/mdgt/pipeline.py` | |
| | MDGT teacher wrapper (loads local pipeline, frozen) | `src/training/mdgt_teacher.py` | |
| | Pre-cache teacher embeddings (one-time, startup) | `scripts/train_sifq.py::precompute_teacher_embeddings()` | |
| | Image preloading (RAM cache, uint8) | `scripts/train_sifq.py::RecordDataset._preload_images()` | |
| | GPU-native degradation (blur/noise/occlusion) | `scripts/train_sifq.py::_degrade_gpu()` | |
| | CPU degradation with preloaded numpy (jpeg/dry_skin/wet_press) | `scripts/train_sifq.py::_degrade_from_np()` | |
| | Vectorized prototype cosine (1 GPU sync vs ~100) | `src/losses/matcher_teacher.py::_compute_q_mat()` | |
|
|
| --- |
|
|
| ## 8. Luồng dữ liệu trong 1 training step (v21 — current) |
|
|
| **Cấu hình v21:** batch=128, W_SPREAD=3.0, deg_every_n_steps=2, deg_max_images=32, no-mat-stats, proto-max-batches=0, gpus=0+1 (DataParallel) |
|
|
| **Startup (1 lần trước khi train):** |
| ``` |
| 1. RecordDataset._preload_images() → np.empty([N, 224, 224], uint8) ~2 GB RAM |
| → __getitem__ trở thành: arr.copy().float().unsqueeze(0) / 255.0 (không đọc disk) |
| |
| 2. precompute_teacher_embeddings(teacher, train_ds) → Tensor[N, 256] CPU (float32) |
| → Frozen DINOv2+TRAM+GNN chạy 1 lần duy nhất trên toàn bộ N records |
| → Không bao giờ chạy lại trong training loop |
| |
| 3. compute_teacher_prototypes() → dict{identity_id → Tensor[256]} CPU |
| → MDGT prototype per identity (L2-normalized mean embeddings) — 1 lần |
| ``` |
|
|
| **Training step:** |
| ``` |
| Batch (B=128, CrossSensorBatchSampler: 16 anchor pairs + fill) |
| │ |
| ├─ images_np = batch["images_np"] ← [B, 224, 224] uint8, đã trong RAM (không từ GPU) |
| ├─ images = batch["images"].to(device) ← [B, 1, 224, 224] float32 trên GPU |
| │ |
| ├─ Forward SIFQ: model(images) → {score [B,1], concepts [B,6], sensor_logits [B,N_sensors], features [B,320]} |
| │ |
| ├─ L_mat: (chỉ SD302+FVC, bỏ PolyU) |
| │ ├─ emb_cache = emb_cache[record_idxs[_non_polyu_idx]] ← CPU lookup, O(1) |
| │ ├─ _compute_q_mat VECTORIZED (không per-sample .item() sync): |
| │ │ ├─ proto_mat = stack([prototypes[id] for id in ids]).to(device) ← 1 GPU transfer |
| │ │ ├─ cos_values = (emb * proto_mat).sum(dim=-1) ← 1 GPU kernel |
| │ │ ├─ cos_cpu = cos_values.cpu().tolist() ← 1 GPU sync |
| │ │ └─ apply tanh(z) nếu có stats, else raw_cosine (tất cả v21 dùng raw — --no-mat-stats) |
| │ └─ Huber(pred_normalized, q_mat) pred_normalized = (Q/100 - 0.5) × 2 |
| │ |
| ├─ L_sens: |
| │ ├─ build_pair_indices() → pairs (cùng finger, khác sensor) từ SD302 + PolyU trong batch |
| │ ├─ L_pair = relu(|Q(s1) - Q(s2)| - 0.05).mean() |
| │ ├─ L_adv = cross_entropy(sensor_logits, sensor_labels) ← GRL đảo gradient |
| │ ├─ L_adv_clamped = L_adv.clamp(max=log(num_sensors)) ← T16: ngăn anti-corr |
| │ └─ (L_pair + 0.3 × L_adv_clamped, L_pair, L_adv) |
| │ |
| ├─ L_deg (mỗi deg_every_n_steps=2 bước, chỉ FVC — tối đa deg_max_images=32): |
| │ ├─ deg_type = random.choice([blur, noise, jpeg, occlusion, dry_skin, wet_press]) |
| │ ├─ level_lo ∈ {1,2} random, level_hi = 3 |
| │ │ |
| │ ├─ GPU path (blur / noise / occlusion) — không transfer nào: |
| │ │ ├─ imgs_low = _degrade_gpu(images[_fvc_idx], deg_type, level_lo) |
| │ │ └─ imgs_high = _degrade_gpu(images[_fvc_idx], deg_type, level_hi) |
| │ │ |
| │ └─ CPU path (jpeg / dry_skin / wet_press) — đọc từ preloaded numpy, không GPU→CPU: |
| │ ├─ imgs_np = images_np[_fvc_idx] ← uint8, đã trong RAM |
| │ ├─ apply cv2 ops per image (GaussianBlur/imencode/erode/etc.) |
| │ ├─ imgs_low = stack(low_list).float().to(device) / 255.0 ← 1 CPU→GPU |
| │ └─ imgs_high = stack(high_list).float().to(device) / 255.0 ← 1 CPU→GPU |
| │ |
| │ model(imgs_low), model(imgs_high) → 2 SIFQ forward thêm |
| │ L_rank + gamma * L_concept_deg → L_deg |
| │ |
| ├─ L_ortho: standardize concepts → (x.T @ x) / (B-1) → off_diag Frobenius² |
| │ |
| ├─ L_spread_global: uniform MSE(sorted Q_batch / 100, linspace(10,90) / 100) |
| ├─ L_spread_sd302: uniform MSE(sorted Q_sd302 / 100, linspace(10,90) / 100) — nếu ≥8 SD302 |
| │ |
| │ [epoch-end: log train_l_pair, train_l_adv, train_q_mean, train_q_std] |
| │ |
| └─ total = α × L_mat + β × L_sens + γ × L_deg + L_ortho + 3.0 × L_spread_global + 3.0 × L_spread_sd302 |
| └── scaler.backward() → optimizer.step() → scaler.update() (AMP fp16) |
| ``` |
|
|
| **v21 config summary:** |
|
|
| | Param | Giá trị | Ghi chú | |
| |-------|---------|---------| |
| | batch_size | 128 | DataParallel → 64/GPU | |
| | W_SPREAD | 3.0 | --spread-weight 3.0 | |
| | deg_every_n_steps | 2 | Mỗi 2 bước có 1 deg step | |
| | deg_max_images | 32 | Tối đa 32 FVC images/step | |
| | concept_deg_gamma | 0.5 | L_concept weight trong L_deg | |
| | proto_max_batches | 0 | Full dataset (không cap) | |
| | no_mat_stats | True | Raw cosine target (không tanh) | |
| | sd302_concept_weight | 0.0 | T30b disabled | |
| | deg_include_sd302 | False | FVC-only L_deg (T27/T36) | |
|
|
| --- |
|
|
| ## 9. Điểm còn thiếu / TODO |
|
|
| | # | Vấn đề | Impact | Todo | |
| |---|--------|--------|------| |
| | T1 | `L_adv` input nên từ concept-intermediate, không phải backbone features | Trung bình | Sửa `SIFQ.forward()` + `SensorDiscriminator` input dim 320→256 | |
| | T2 | `L_mat` signal yếu vì q_mat ≈ constant với SD302 | ✅ Đã cải thiện (v8) | FVC2002+2004 đã được thêm → 8 impressions/subject → q_mat có real ranking signal | |
| | T3 | Finger_id heuristic không verified | ✅ Đã xác nhận | Audit thực tế: finger ID nhất quán across sensors trong SD302. Không còn là risk. | |
| | T4 | Không có FVC2002/2004 và PolyU CL2CB | ✅ Đã thêm (v9) | FVC2002+2004 (7,040) + PolyU (5,952 contact+contactless). PolyU = cross-modality L_sens mạnh nhất. | |
| | T5 | Track 3 chưa có VeriFinger | Thấp | Dùng matcher khác (FLaRE, AFR-Net open-source) | |
| | T6 | `L_mat` tốn compute nhưng gần như không contribute khi chỉ có SD302 | ✅ Đã xử lý (v8) | FVC thêm vào, L_mat già trị hơn | |
| | T7 | `L_spread` threshold 10/100 tùy ý — variance mode trivially saturates | ✅ Đã fix (v8) | Uniform mode: MSE(sorted Q, linspace(10,90)), weight=2.0 | |
| | T8 | `L_pair` trong `L_sens` sparse vì batch random ít khi có cross-sensor pair | ✅ Đã fix (v7) | `CrossSensorBatchSampler`: mỗi batch đảm bảo k_cross=16 nhóm cóp 2 samples từ khác sensor. | |
| | T9 | GRL λ cố định + stage transition nhảy bậc — shock tại ep10 (β: 0→0.20 đột ngột) | ✅ Đã fix (v8) | DANN warm-up từ ep0; β ramp linear ep10–14 + ep30–34 thay vì nhảy bậc | |
| | T13 | v8: chỉ ramp β, α/γ vẫn step change tại ep15 → sens oscillate 3–3.5 từ ep18 | ✅ Đã fix (v9) | Ramp ALL THREE (α, β, γ) cùng lúc ep10–19; không có step change nào trong toàn bộ schedule | |
| | T10 | Score collapse: spread=0.010 stuck (max penalty) trong toàn bộ v7 | ✅ Đã fix (v8) | Uniform spread mode: gradient trực tiếp ép phân bố score | |
| | T11 | L_deg plateau 0.104 (tại margin boundary m=0.10) từ ep43+ trong v7 | ✅ Đã fix (v8) | γ floor = 0.50 (was 0.40) giữ deg grounding mạnh hơn | |
| | T12 | S4 oscillation: loss tăng từ 0.53 lên 1.18 trong v7 ep61-80 | ✅ Đã fix (v8) | Cosine LR decay 1e-4 → 5e-6 ngăn oscillation giai đoạn finetune | |
| | T14 | `l_pair` và `l_adv` không được log riêng — chỉ thấy `train_l_sens` tổng hợp | ✅ Đã fix (v11) | `SensorInvarianceLoss.forward()` trả về `(total, l_pair, l_adv)` tuple; train script log `train_l_pair`, `train_l_adv` riêng | |
| | T15 | `q_mean` và `q_std` không được log ra metrics.jsonl — không thể monitor score distribution | ✅ Đã fix (v11) | Train script tích lũy `q_sum`/`q_sq_sum`/`q_count` qua từng step → tính epoch-level `train_q_mean`, `train_q_std` | |
| | T16 | GRL anti-correlation: `l_adv` >> `log(num_sensors)` suốt S2–S4 (ep20–47: 7–16 vs random=3.47) → backbone học predict sai sensor với high confidence → GRL game cycling không hội tụ | ✅ Đã fix (v11) | Clamp `l_adv` tại `log(num_sensors)` trước khi đưa vào total. Khi backbone đã đủ confuse discriminator (CE ≥ log N), gradient reversal dừng lại → equilibrium ổn định thay vì anti-correlation cycle | |
| | T17 | **Score collapse v11: 95% ảnh kẹt tại ~58.3** (inference SD302: mean=59.8, std=6.5, median=58.3). Root cause: L_deg chỉ apply cho FVC (16% batch) → L_spread được thỏa mãn batch-level nhờ FVC variation, nhưng SD302 images không có ordinal grounding → model học "SD302 = medium quality ~58" mà không có gradient để phân biệt. Slap sensors (R,S) cho ~88 do có ít samples và backbone capture type signal; roll/flat sensors cho ~58.3 uniform → sensor bias residual. | ⚠️ Fix sai (v12) → Đúng (v13) | **v12 (sai):** Apply L_deg cho ALL datasets. SD302 images anchored tại ~28 (near degraded floor), tệ hơn. **v13 (đúng):** Revert FVC-only L_deg + thêm per-dataset L_spread riêng cho SD302 subset. | |
| | T18 | **`MorphologicalDilator` sai chiều cho wet_press**: Dùng `cv2.dilate` thay vì `cv2.erode`. NIST fingerprints có ridges tối (dark ridges, light valleys). `cv2.dilate` expand vùng sáng → shrink ridges (mô phỏng ngón tay KHÔ, không phải ướt). Wet press cần ridges phình to, lấn vào valleys → phải dùng `cv2.erode` (expand dark regions). Bug giải thích tại sao Track 4 wet_press → clarity=+0.219 (sai chiều, phải âm): dilated image có ridges mảnh hơn → model thấy valleys rõ hơn → clarity tăng. | ✅ Fix (v12) | Đổi `cv2.dilate` → `cv2.erode` trong `MorphologicalDilator.__call__`. Erode expand ridges tối → ridges merge vào valleys → clarity giảm đúng chiều. | |
| | T19 | **`jpeg` và `occlusion` concept signal gần 0** (Track 4 eval v11: jpeg→clarity=-0.045, occlusion→minutiae=-0.032). L_concept_deg quá yếu so với các loss khác cho những type này. Occlusion max 30% coverage (level 3) không đủ khuất minutiae. | ✅ Fix (v12) | Tăng `--deg-every-n-steps` từ 2 → giữ 4 (compute balance sau T17 tăng batch size). Tăng L_concept_deg gamma từ 0.5 → 1.0 trong `DegradationRankingLoss`. Tăng occlusion level 3 từ 30% → 40% coverage. | |
| | T20 | **SD302 scores anchored tại ~28 trong v12** (target 10–90). T17 fix (L_deg on all datasets) dùng synthetic degradation làm ordinal anchor cho SD302. SD302 images trông như "level 1-2 degraded FVC" đối với model → anchor tại ~28 (gần degraded floor). Per-sensor: R/S slap non-segmented std=0.0 (fully collapsed), roll sensors mean=27-28 std=6-7, flat sensors mean=35-40 std=10-15. KS=0.51 vẫn fail vì sensor TYPE bias (slap vs roll vs flat). | ✅ Fix (v13) | Revert T17 (FVC-only L_deg) + Add per-dataset L_spread cho SD302 subset trong mỗi batch. SD302 images buộc phải compete với nhau để có spread [10,90] thay vì được anchored bởi synthetic degradation. | |
| | T21 | **Non-segmented slap collapse** (R_*_slap, S_*_slap std=0.0, score≈21.2 cố định). Full-hand slap images visually homogeneous → không có quality variation tự nhiên → model gán cùng score. v13 eval: sensors này kéo mean_KS từ 0.51 (v12) lên 0.634 (v13). | ✅ Fix (v14) | **T28**: `--exclude-sensor R_1000_slap,R_500_slap,S_500_slap` trong training và eval. Loại ~1,700 records. `run_infer.py`, `run_eval.py`, `train_sifq.py` đều có flag `--exclude-sensor`. Eval v13 chính xác: `run_eval_v13.sh` → `eval_results/v13_seg/`. | |
| | T22 | **Noise concept regression trong v12**: noise_level: +0.188 (v11) → **-0.168 (v12)** (sai chiều hoàn toàn). Root cause: `if c_idx == 3` special case trong `DegradationRankingLoss` push noise_level TĂNG theo degradation. ScoreAggregator (unconstrained MLP) có thể thỏa mãn L_rank bằng cách GIẢM noise_level + dùng positive weight → conflict được resolve bằng cách invert concept direction. Gamma=1.0 (T19) làm conflict mạnh hơn → model phải chọn một hướng nhất quán → chọn inverted direction. | ✅ Fix (v13) | T25: Remove `if c_idx == 3` special case trong `DegradationRankingLoss.forward()`. Tất cả concepts GIẢM theo degradation (high = better quality). Noise_level semantic: **low noise level = low noise = good** (trước: high noise_level = more noise). Consistent với tất cả concepts khác → ScoreAggregator dùng positive weights cho tất cả. | |
| | T23 | **Occlusion concept vẫn dead sau T19** (v12 eval: contin=+0.023, minutiae=+0.075 — sai chiều cả hai). Hai nguyên nhân: (1) `DEGRADATION_CONCEPT_MAP` chỉ supervise minutiae_reliability, bỏ qua continuity; (2) coverage 40% chưa đủ để affect minutiae feature. | ✅ Fix (v13) | T26: Thêm continuity (c_idx=2) vào `DEGRADATION_CONCEPT_MAP["occlusion"] = [5, 2]`. Tăng occlusion level 3 coverage từ 40% → 55% (`0.183 * level`). v13 kết quả: occlusion→minutiae=-0.09 (yếu, chưa đủ). v14 cần monitor. | |
| | T28 | **Non-segmented slap gây nhiễu training và eval** (v13: R_1000_slap score≈21.2 std=0, kéo mean_KS lên 0.634). Full-hand slap ảnh 4 ngón tay → backbone extract feature gần như giống nhau → score collapse về 21.2 cho mọi người. SensorDiscriminator phải waste GRL capacity để align cụm ~21 với segmented counterparts ~54. | ✅ Fix (v14) | T28: `--exclude-sensor R_1000_slap,R_500_slap,S_500_slap`. Loại ~1,700 records từ SD302-B/D. Thêm flag vào `train_sifq.py`, `run_infer.py`, `run_eval.py`, `visualize_score_milestones.py`. Script: `run_train_v14.sh`, `run_eval_v13.sh`. | |
| | T29 | **Epoch plateau quá sớm — 80 epochs lãng phí** (v13: loss converge từ epoch 20; ep20–79 flat). | ✅ Fix (v14) | T29: v14 train từ đầu (không resume) với **60 epochs**. LR cosine schedule 1e-4→0 trên 60 epochs. Nếu resume từ checkpoint: 30 epochs đủ. | |
| | T31 | **Score collapse v15 — tất cả ảnh score gần như giống nhau** (eval range 24–56, q_mean≈52.5 flat suốt 60 epochs). Root cause: `stats=None` trong mọi lần gọi `loss_mat()`. Khi stats=None: `q_mat = raw cosine ≈ 0.85` cho mọi ảnh (MDGT quality-robust → cosine ổn định ở mức cao cho mọi ảnh của cùng identity). L_mat kéo pred_score về `(0.85/2 + 0.5)×100 ≈ 92.5`; L_spread kéo về [10,90]; equilibrium tại q_mean≈52 không thay đổi. Không có gradient nào chỉ ra ảnh nào nên cao/thấp hơn ảnh khác → model chỉ đáp ứng **rank thứ tự** trong batch (L_spread) mà không phân biệt ảnh tốt/xấu thực sự. | ⚠️ Partial fix (v16 — tạo ra bug mới T32) | **T31a (per-identity cos stats):** Sau khi tính prototype, chạy second pass `compute_identity_cos_stats()` để tính `(mean_cos, std_cos)` per identity. Pass `stats=cos_stats` vào `loss_mat()`. **T31b (tanh scaling trong `_compute_q_mat`):** `q_mat = tanh((cos − μᵢ) / σᵢ)` → teacher target zero-centred ∈ (−1,1). **T31c (W_SPREAD 2.0→4.0):** Tăng spread weight. **Nhưng T31 tạo ra conflict mới: xem T32.** | |
| | T32 | **Score collapse v16 — NGHIÊM TRỌNG HƠN v15** (eval range 46.9–50.5, q_std=0.33! Training q_std=15.6 nhưng là false positive — driven bởi FVC trong training batch). Root cause: T31 per-identity stats conflict trực tiếp với L_pair. L_mat muốn **within-identity variation** (`q_mat=tanh((cos−μᵢ)/σᵢ)` → ảnh cùng identity phải score khác nhau). L_pair muốn **within-identity uniformity** (`|Q(s1)−Q(s2)|≤0.05` → cùng identity, khác sensor, score bằng nhau). Conflict không thể resolve → model output ~50 cho tất cả SD302. FVC không có L_pair → FVC spread OK → training q_std=15.6 driven by FVC only. Inference trên SD302-only → q_std=0.33. Sensor bias: roll sensors cluster ≈49.67 vs slap/flat ≈50.2 → KS=0.90 trong range 3.6pt → mean_KS=0.527 (tệ hơn cả v13). | ✅ Fix (v17) | **T32a (`compute_identity_cos_stats(fvc_only=True)`):** Chỉ tính stats cho FVC identities. FVC không có cross-sensor pairs → L_pair=0 → không conflict với L_mat within-identity signal. **T32b (`_compute_q_mat` fallback to raw cosine):** SD302 identities không có trong FVC-only stats → fallback về `raw_cosine ≈ 0.85` (v14 behaviour — constant target, chỉ anchor mean, không conflict với L_pair). FVC images giữ tanh normalization với FVC-specific stats. Files: `src/losses/matcher_teacher.py::_compute_q_mat`, `scripts/train_sifq.py::compute_identity_cos_stats`. | |
| | T33 | **Score collapse v17 — WORSE THAN v16** (eval SD302 range 18.1–53.0, tất cả đổ về ~52.7, q_std=0.60! Training q_std=16.59 OK nhưng false positive driven by FVC). Root cause (sâu hơn T32 đã fix): T32 loại bỏ L_mat vs L_pair CONFLICT nhưng không fix SCORE COLLAPSE. (1) SD302 raw cosine ≈ 0.85 là CONSTANT → L_mat không tạo per-image quality gradient cho SD302 → không có signal để phân biệt SD302 images. (2) GRL + L_pair triệt tiêu discriminative features từ SD302 backbone: GRL xóa sensor-correlated info (bao gồm quality-correlated-with-sensor); L_pair ép same-identity same-score → SD302 feature space bị flatten. (3) FVC có stable per-image tanh targets → model học quality function cho FVC. SD302 chỉ có inconsistent batch-relative spread signals → feature collapse về ~52.7. (4) FVC tanh targets (variable) vs SD302 raw cosine targets (constant) tạo asymmetry → model học shortcut "FVC=variable, SD302=52.7". W_SPREAD=4.0 + gamma=2.0 + sd302_concept_weight=1.0 làm tệ thêm so với v14. KS=0.616 ❌, Pearson=-0.002 ❌. | ✅ Fix (v18) | **T33: Revert tất cả additions từ v15–v17 về v14 baseline + thêm SD302-A.** T33a: `--no-mat-stats` — skip per-identity cosine stats hoàn toàn; tất cả images (FVC + SD302) dùng raw cosine làm L_mat target → không còn FVC/SD302 asymmetry. T33b: W_SPREAD=2.0 (revert từ 4.0). T33c: concept_deg_gamma=0.5 (revert từ 2.0). T33d: sd302_concept_weight=0.0 (revert T30b). T33e: deg-every-n-steps=4 (revert từ 2). NEW: SD302-A included (13,630 images, 8 sensors A-H) — v14 chỉ dùng B+D. Targets: q_std>12, score range 10–90, mean_KS≤0.27, Pearson≥0.25. | |
| | T35 | **Score collapse v15–v19 — two root causes (T33 fixed but v19 still collapsed).** v18 actual: q_std=0.01 ❌❌ (score range ~54.62–54.65). Training showed healthy q_std but inference collapse. Root cause 1 (dominant): Truncated prototypes `--proto-max-batches 150` → only 45% of dataset → SD302 gets 2–3 partial sensor prototypes → cosine is sensor-biased (not quality-correlated) → per-image L_mat gradient near-zero for SD302. Root cause 2: FVC-only L_deg leaves SD302 without ordinal grounding → L_spread_ds is batch-level only → collapses at inference. T35a fix: `--proto-max-batches 0` (full dataset, 15–25 min). T35b fix (proposed): `--deg-include-sd302` → apply L_rank to SD302 too. Note: T35b was WRONG — see T36. | ⚠️ Partial (v20: T35a ✅, T35b ❌) | T35a: Set `--proto-max-batches 0` (no cap). T35b: `--deg-include-sd302` flag (applies L_rank to FVC+SD302 instead of FVC-only). **T35b introduced new collapse — removed in v21.** | |
| | T36 | **Score collapse v20 — `--deg-include-sd302` creates ~53.38 attractor.** v20 training q_std=18.3 (healthy-looking) but ALL SD302 inference scores collapse to ~53.38 (q_std=0.007, range 53.20–53.41). Root cause: L_rank applied to SD302 clean images. L_rank only requires Q(clean)>Q(degraded)+m, NOT that different clean images score differently. Model satisfies L_rank by assigning same ~53.38 to ALL clean SD302 images + lower to degraded → gradient has no reason to differentiate clean images → stable ~53.38 attractor. L_spread_ds (batch-level) + L_pair reinforce attractor. Training q_std=18.3 is FALSE POSITIVE driven entirely by L_spread gradient — at inference (no gradient) model outputs its "natural" ~53.38 for all clean SD302. **Why v14 worked without --deg-include-sd302:** FVC genuine quality variation → MDGT cosine genuinely varies (0.75→0.93 per FVC impression) → L_mat gradient shapes backbone to be quality-discriminative → features TRANSFER to SD302 at inference. L_rank on SD302 blocks this transfer. eval_results/v20: mean_KS=0.4936 ❌, Pearson=0.0048 ❌. | ✅ Fix (v21 — Training) | **T36: Remove `--deg-include-sd302`.** Keep `--proto-max-batches 0` from T35a. FVC-only L_deg: genuine quality variation → L_mat gradient → quality-discriminative backbone → intrinsic SD302 quality scoring. One-line change in run_train_v21.sh vs run_train_v20.sh. | |
| | T37 | **CrossSensorBatchSampler k_cross=16 + full prototypes destroys quality discrimination.** v21: Pearson=0.092, dry_skin orientation=+0.87 ❌. Root cause: `CrossSensorBatchSampler` (added for T8) default k_cross=16 guarantees 16 cross-sensor pairs/batch. With full prototypes (nearly-constant L_mat targets ≈0.85–0.90 for all SD302), backbone over-optimises sensor invariance at expense of quality ordering → Pearson collapses. v14 used random batching (~1–2 pairs by chance). Additionally: DataParallel (--gpus 0,1) causes 4.3× slowdown for TinyViT-5M (v21: ~970s/epoch vs v20 single GPU: ~226s). Redundant double teacher pass (emb_cache + compute_teacher_prototypes both ran teacher on all 42K images). | ✅ Fix (v22 — Training) | **T37: (1) `--k-cross 0`** (disable CrossSensorBatchSampler, random batching like v14); **(2) `--gpus 0`** (single GPU, no DataParallel); **(3) `build_prototypes_from_cache()`** computes prototypes from emb_cache in O(N) CPU — no second teacher pass. All other params same as v21 (proto-max-batches=0, no-mat-stats, spread-weight=3.0, concept-deg-gamma=0.5, FVC-only L_deg). Expected: Pearson≥0.28, KS≤0.28, ~220s/epoch, correct concept grounding. | |
| | T38 (v22) | **minutiae_reliability wrong direction for wet_press; occlusion deviates from paper.** (1) `wet_press → minutiae_reliability[5]` consistently POSITIVE across all versions (v14=+0.565) — simulation 3×3 kernel too subtle at level 1 (~1 px expansion) so model reads it as "good ink". (2) `occlusion` concept map had `[5, 2]` (continuity added in T26) and coverage 55%, both deviating from paper design `[minutiae_reliability only, 10–40%]`. T26 added continuity as a crutch for weak signal, but root cause was unseeded eval (incoherent Spearman ρ across random block positions per level). | ✅ Fix (v22 — Code) | **T38a** (wet_press simulation): Scale `MorphologicalDilator` kernel `ks = 3 + 2*iterations` (5×5/7×7/9×9) + `sigma = 1.0 + 0.8*iterations`. Level 1 visibly impairs bifurcations. Concept map KEPT at `[1, 5]` (paper). **T38b** (occlusion): Revert concept map `[5, 2]` → `[5]`; coverage `0.183×level` → `0.133×level` (max 40%). **T38c** (occlusion eval): `np.random.seed(level)` in `compute_crosstalk_matrix` — deterministic block position per severity level. Files: `src/data/degradation.py`, `src/losses/degradation_ranking.py`, `src/evaluation/concept_grounding.py`. | |
| | T_old38 | **MDGTCheckpointTeacher phụ thuộc vào external `fingerprint_pad` package** (dynamic sys.path injection) — brittle, không versioned, khó deploy. | ✅ Fix (v21, cùng phiên) | Import từ `src/models/mdgt/pipeline.py::MDGTv2` (local). `_ensure_on_path()` và `fingerprint_pad` import đã bị xóa. `MDGTv2` constructor nhận thêm `gnn_heads` và `pool_heads` (absent trong external API cũ). File: `src/training/mdgt_teacher.py`. | |
| |
| |
| --- |
| |
| ## 10. Performance Engineering (v21) |
| |
| ### Bối cảnh |
| |
| Training ban đầu chạy ~3.5–5.7s/it. Sau 3 vòng tối ưu, root causes được xác định và fix: |
| |
| | Iteration | Thời gian | Root cause | |
| |-----------|-----------|------------| |
| | Before | 3.49 s/it (step 39) | Teacher DINOv2 forward mỗi step | |
| | After teacher cache | 4.05 s/it (step 6) | DataLoader disk IO bottleneck bị lộ | |
| | After image preload | 4.96 s/it (step 4) | CUDA warmup + _compute_q_mat GPU syncs | |
| | After vectorize q_mat | ~0.4 s/it (dự kiến, sau warmup) | — | |
| |
| > **Lưu ý:** Các measurement ở step 2–6 bao gồm CUDA kernel JIT compilation (one-time, 2–5s). Cần đến step 20–30 để đo steady-state. |
|
|
| ### Fix 1: Teacher Embedding Cache |
|
|
| **Vấn đề:** DINOv2 ViT-S/14 + TRAM + GNN forward chạy trên ~100 images mỗi step, mỗi epoch. Teacher là frozen → cùng image luôn cho cùng embedding. ~20,000 DINOv2 forward qua 60 epochs = pure waste. |
|
|
| **Thêm nữa:** Attention monkey-patch trong `DINOv2Backbone` vô hiệu hóa xformers, buộc dùng standard O(N²) attention + lưu 12 × `(B, 6, 257, 257)` attention maps per forward. |
|
|
| **Fix:** |
| ```python |
| # scripts/train_sifq.py |
| emb_cache = precompute_teacher_embeddings(teacher, train_ds, device, batch_size=128) |
| # → Tensor[N, 256] CPU float32, ~43 MB cho 42K records |
| |
| # Per step (thay vì teacher forward): |
| _cached_emb = emb_cache[record_idxs[_non_polyu_idx]] # O(1) lookup |
| loss_mat(..., cached_emb=_cached_emb) |
| ``` |
|
|
| **Tiết kiệm:** ~2–3s/it (DINOv2 forward) → 0 (lookup). Startup cost: ~2–3 min (1 lần duy nhất). |
|
|
| --- |
|
|
| ### Fix 2: Image Preloading |
|
|
| **Vấn đề:** Mỗi `RecordDataset.__getitem__` gọi `Image.open(path).convert("L")` + resize. Với 8 DataLoader workers và B=128, mỗi batch cần ~128 disk reads + PIL decode + resize. Đây là CPU/IO bottleneck ẩn sau teacher GPU time. |
|
|
| **Fix:** |
| ```python |
| # RecordDataset.__init__ |
| def _preload_images(self, image_size): |
| cache = np.empty((N, image_size, image_size), dtype=np.uint8) # ~2 GB |
| for i, rec in enumerate(self.records): |
| sample = next(loader.iter_samples([rec])) |
| cache[i] = (sample["image"].squeeze(0) * 255).byte().numpy() |
| self._image_cache = cache |
| |
| # __getitem__: O(1) numpy slice + dtype cast, no disk IO |
| image = torch.from_numpy(self._image_cache[idx].copy()).float().unsqueeze(0) / 255.0 |
| ``` |
|
|
| **Lợi ích kép:** `batch["images_np"]` (uint8 numpy trong batch) cho phép degradation CPU path đọc trực tiếp từ RAM, không cần `images[idx].cpu().numpy()`. |
|
|
| --- |
|
|
| ### Fix 3: Vectorized `_compute_q_mat` |
| |
| **Vấn đề:** `_compute_q_mat` gọi `torch.dot(emb[i], proto).item()` trong Python loop cho mỗi trong ~100 non-polyu samples. Mỗi `.item()` là một GPU synchronization barrier — CPU block cho đến khi GPU hoàn thành. ~100 syncs/step × ~10–100ms/sync = 1–10s overhead. |
|
|
| **Fix:** |
| ```python |
| # Trước: 100 syncs |
| for i, identity in enumerate(identity_ids): |
| cos = float(torch.dot(emb[i], proto).item()) # ← GPU sync! |
| |
| # Sau: 1 sync |
| proto_mat = torch.stack([prototypes[id] for id in identity_ids]).to(emb.device) # 1 transfer |
| proto_mat = F.normalize(proto_mat, dim=-1) |
| cos_values = (emb * proto_mat).sum(dim=-1) # 1 GPU kernel |
| cos_cpu = cos_values.float().cpu().tolist() # 1 sync |
| ``` |
|
|
| **Tiết kiệm:** ~100 GPU syncs → 1. Đây là fix quan trọng nhất sau khi teacher cache đã giải phóng bottleneck ẩn. |
|
|
| --- |
|
|
| ### Fix 4: GPU-Native Degradation |
|
|
| **Vấn đề:** Degradation loop cũ làm `images[_fvc_idx].detach().float().cpu().numpy()` → cv2 ops → `tensor.to(device)`. GPU→CPU là synchronous (stall pipeline). |
|
|
| **Fix:** |
| ```python |
| # _degrade_gpu: blur/noise/occlusion — full GPU, không transfer |
| if deg_type == "blur": |
| return TF.gaussian_blur(images, kernel_size) |
| if deg_type == "noise": |
| return (images + torch.randn_like(images) * sigma).clamp(0, 1) |
| if deg_type == "occlusion": |
| out = images.clone(); out[:, :, y:y+block, x:x+block] = 1.0; return out |
| |
| # _degrade_from_np: jpeg/dry_skin/wet_press — CPU nhưng đọc từ preloaded numpy |
| imgs = images_np[deg_idx] # [K, H, W] uint8, đã trong RAM |
| low = [deg_pipeline.apply(img, t, lo) for img in imgs] |
| ... → single CPU→GPU transfer (không GPU→CPU) |
| ``` |
|
|
| **Breakdown degradation types:** |
|
|
| | Type | Đường đi | Transfer cost | |
| |------|---------|---------------| |
| | blur | GPU (`TF.gaussian_blur`) | 0 | |
| | noise | GPU (`torch.randn_like`) | 0 | |
| | occlusion | GPU (tensor indexing) | 0 | |
| | jpeg | CPU+cv2 → GPU (1 transfer) | 1 CPU→GPU | |
| | dry_skin | CPU+cv2 → GPU (1 transfer) | 1 CPU→GPU | |
| | wet_press | CPU+cv2 → GPU (1 transfer) | 1 CPU→GPU | |
|
|
| --- |
|
|
| ### Tổng quan pipeline v21 |
|
|
| ``` |
| Startup (1 lần, ~3–5 phút): |
| _preload_images() ~2 min → 2 GB RAM |
| precompute_teacher_emb() ~2 min → 43 MB CPU tensor |
| compute_teacher_prototypes() ~1 min → dict[id → 256-D] |
| |
| Per step (~0.4 s steady-state): |
| DataLoader: ~1 ms (numpy slice + cast, no disk) |
| H2D transfer: ~5 ms (pin_memory) |
| SIFQ forward: ~100 ms (TinyViT-5M B=128, DataParallel 2×GPU) |
| L_mat: ~2 ms (emb_cache lookup + 1 GPU kernel + 1 sync) |
| L_sens: ~5 ms (pair indices + hinge loss) |
| L_deg (50%): ~150 ms (2 extra SIFQ forwards B=32 + GPU/CPU deg ops) |
| Backward: ~100 ms |
| Optimizer: ~20 ms |
| ───────────────────── |
| Total: ~0.35–0.55 s/it (estimate, post CUDA warmup) |
| ``` |
|
|