anbinh39 commited on
Commit
cfc7a54
·
verified ·
1 Parent(s): 6e9cb06

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .claude/settings.local.json +10 -0
  2. .venv/.gitignore +1 -0
  3. .venv/.lock +0 -0
  4. .venv/CACHEDIR.TAG +1 -0
  5. .venv/pyvenv.cfg +5 -0
  6. archive/research_fingerjet.md +113 -0
  7. eval_results/sifq_report_v24.txt +151 -0
  8. eval_results/sifq_scores_v16.jsonl +0 -0
  9. eval_results/sifq_scores_v17.jsonl +0 -0
  10. eval_results/sifq_scores_v18.jsonl +0 -0
  11. eval_results/sifq_scores_v19.jsonl +0 -0
  12. eval_results/sifq_scores_v20.jsonl +0 -0
  13. eval_results/sifq_scores_v21.jsonl +0 -0
  14. eval_results/sifq_scores_v22.jsonl +0 -0
  15. eval_results/sifq_scores_v24.jsonl +0 -0
  16. eval_results/sifq_scores_v25.jsonl +0 -0
  17. eval_results/sifq_scores_v27.jsonl +0 -0
  18. eval_results/sifq_scores_v28.jsonl +0 -0
  19. eval_results/sifq_scores_v29.jsonl +0 -0
  20. eval_results/sifq_scores_v30.jsonl +0 -0
  21. eval_results/sifq_scores_v31.jsonl +0 -0
  22. eval_results/sifq_scores_v32.jsonl +0 -0
  23. logs/train_v26.log +0 -0
  24. rules/HOWTO_RUN.md +775 -0
  25. rules/SIFQ_explained.md +960 -0
  26. rules/plan.md +320 -0
  27. rules/sifq_pdf.txt +488 -0
  28. scripts/_gen_report_v24.py +207 -0
  29. scripts/gen_nfiq2_proxy_scores.py +162 -0
  30. scripts/run_eval_v16.sh +53 -0
  31. scripts/run_eval_v17.sh +57 -0
  32. scripts/run_eval_v18.sh +56 -0
  33. scripts/run_eval_v19.sh +56 -0
  34. scripts/run_eval_v20.sh +56 -0
  35. scripts/run_eval_v21.sh +56 -0
  36. scripts/run_eval_v23.sh +50 -0
  37. scripts/run_eval_v26.sh +50 -0
  38. scripts/run_eval_v27.sh +59 -0
  39. scripts/run_eval_v28.sh +50 -0
  40. scripts/run_eval_v29.sh +50 -0
  41. scripts/run_eval_v31.sh +52 -0
  42. scripts/run_eval_v32.sh +52 -0
  43. scripts/run_infer.py +158 -0
  44. scripts/run_smoke.sh +18 -0
  45. scripts/run_train_v16.sh +75 -0
  46. scripts/run_train_v17.sh +87 -0
  47. scripts/run_train_v18.sh +85 -0
  48. scripts/run_train_v19.sh +79 -0
  49. scripts/run_train_v20.sh +93 -0
  50. scripts/run_train_v21.sh +93 -0
.claude/settings.local.json ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(find /home/aiserver/works/fingerprint/sifq -name \"train_v16.log\" 2>/dev/null; find /home/aiserver/works/fingerprint -name \"train_v16.log\" 2>/dev/null)",
5
+ "Read(//home/aiserver/works/fingerprint/**)",
6
+ "Bash(grep -E \"^\\\\[Ep|^\\\\[Val|^Ep [0-9]+.*\\\\]$|val_loss|val_eer|EER|AUC|Rank|✓|✗|saved|checkpoint|best\")",
7
+ "Bash(grep -v \"^\\\\[S[12]\\\\]$\")"
8
+ ]
9
+ }
10
+ }
.venv/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ *
.venv/.lock ADDED
File without changes
.venv/CACHEDIR.TAG ADDED
@@ -0,0 +1 @@
 
 
1
+ Signature: 8a477f597d28d172789f06886806bc55
.venv/pyvenv.cfg ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ home = /home/aiserver/.local/share/uv/python/cpython-3.11.12-linux-x86_64-gnu/bin
2
+ implementation = CPython
3
+ uv = 0.7.2
4
+ version_info = 3.11.12
5
+ include-system-site-packages = false
archive/research_fingerjet.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Read [](file:///home/aiserver/works/fingerprint/sifq/rules/SIFQ_explained.md#1-1), lines 1 to 100
2
+
3
+ Read [](file:///home/aiserver/works/fingerprint/sifq/rules/plan.md#1-1), lines 1 to 80
4
+
5
+ Read [](file:///home/aiserver/works/fingerprint/sifq/rules/SIFQ_explained.md#100-100), lines 100 to 200
6
+
7
+ Read [](file:///home/aiserver/works/fingerprint/sifq/src/evaluation/concept_grounding.py)
8
+
9
+ Read [](file:///home/aiserver/works/fingerprint/sifq/src/losses/degradation_ranking.py#1-1), lines 1 to 80
10
+
11
+ Read [](file:///home/aiserver/works/fingerprint/sifq/rules/sifq_pdf.txt#1-1), lines 1 to 100
12
+
13
+ Hãy để tôi đọc thêm phần đánh giá và design của concept 5 để phân tích kỹ hơn.
14
+
15
+ Read [](file:///home/aiserver/works/fingerprint/sifq/rules/sifq_pdf.txt#100-100), lines 100 to 200
16
+
17
+ Read [](file:///home/aiserver/works/fingerprint/sifq/src/losses/degradation_ranking.py#80-80), lines 80 to 120
18
+
19
+ ## Phân tích lý thuyết: SIFQ concept 5 vs FingerJetFX OSE
20
+
21
+ ### Tóm tắt: Phù hợp có điều kiện — nhưng có 3 cảnh báo quan trọng
22
+
23
+ ---
24
+
25
+ ### 1. Alignment vật lý: ✅ Cùng phenomenon
26
+
27
+ | | SIFQ concept 5 | FingerJetFX OSE (NFIQ2) |
28
+ |---|---|---|
29
+ | **Đo gì** | Latent proxy: "điều kiện để minutiae extraction thành công" | Trực tiếp: trích xuất minutiae + gán confidence |
30
+ | **Output** | Scalar ∈ [0,1] — toàn cục (global image) | Minutiae count + per-minutiae quality + OFL/LCS features |
31
+ | **Supervision** | Occlusion, wet_press degradation | Hand-engineered, VeriFinger-based |
32
+
33
+ Hai approach đều hướng về cùng một câu hỏi: *"Liệu có thể trích xuất minutiae đáng tin cậy từ ảnh này không?"* → Alignment vật lý hợp lý.
34
+
35
+ ---
36
+
37
+ ### 2. Vấn đề coverage gap: ⚠️ Concept 5 quá hẹp
38
+
39
+ FingerJetFX minutiae reliability bị ảnh hưởng bởi **nhiều degradation**:
40
+
41
+ | Degradation | FingerJetFX | SIFQ concept 5 hiện tại |
42
+ |---|---|---|
43
+ | Blur | Ridge endings mờ → không xác định minutiae position | ❌ Không supervise concept 5 |
44
+ | Noise | False minutiae tăng | ❌ Không supervise concept 5 |
45
+ | JPEG | Blocking artifacts tạo false minutiae | ❌ Không supervise concept 5 |
46
+ | Occlusion | Mất minutiae vùng bị che | ✅ Supervise concept 5 |
47
+ | Wet press | Ridge merging → false terminations | ✅ Supervise concept 5 |
48
+ | Dry skin | Ridge gaps → false bifurcations | ❌ Không supervise concept 5 |
49
+
50
+ **Hệ quả:** SIFQ concept 5 sẽ cho kết quả đúng với occlusion/wet_press nhưng có thể không phản ứng đúng với blur/noise/dry_skin theo nghĩa "minutiae reliability" đầy đủ — trong khi FingerJetFX sẽ bị ảnh hưởng bởi tất cả.
51
+
52
+ ---
53
+
54
+ ### 3. Sensor bias của FingerJetFX: ❌ Mâu thuẫn với novelty
55
+
56
+ Đây là vấn đề lý thuyết **nghiêm trọng nhất**:
57
+
58
+ ```
59
+ FingerJetFX được thiết kế cho optical contact fingerprint.
60
+ Trên contactless hoặc cross-sensor → minutiae count systematic shift.
61
+ ```
62
+
63
+ SIFQ concept 5 **được thiết kế để sensor-invariant**. Nếu validate concept 5 cross-sensor bằng FingerJetFX:
64
+ - FingerJetFX sẽ cho minutiae count **khác nhau** cho cùng ngón tay ở 2 sensor
65
+ - SIFQ concept 5 (nếu hoạt động đúng) sẽ cho giá trị **tương tự** → hai metric **không đồng ý**
66
+ - Kết luận sai: "SIFQ concept 5 không tương quan với FingerJetFX" — nhưng thực ra đây là **bằng chứng novelty**, không phải failure
67
+
68
+ **Dùng FingerJetFX làm oracle cross-sensor sẽ penalize đúng cái mà SIFQ cố gắng làm tốt hơn.**
69
+
70
+ ---
71
+
72
+ ### 4. Cách dùng FingerJetFX đúng cho novelty của bạn
73
+
74
+ **Hợp lệ — within-sensor correlation:**
75
+ ```
76
+ Cùng sensor, nhiều ảnh khác nhau:
77
+ Spearman(SIFQ concept 5, FingerJetFX minutiae count) → nên > 0.30
78
+ ```
79
+ Chứng minh concept 5 capture được signal vật lý thực sự.
80
+
81
+ **Novelty proof — cross-sensor stability comparison:**
82
+ ```
83
+ Same finger, sensor A vs sensor B:
84
+ KS(FingerJetFX minutiae count, across sensors) >> KS(SIFQ concept 5, across sensors)
85
+ ```
86
+ Đây là bằng chứng mạnh nhất: FingerJetFX bị sensor bias nghiêm trọng, SIFQ concept 5 ổn định hơn → đây là contribution chính của bài báo.
87
+
88
+ **Rất thú vị — divergence case:**
89
+ Tìm ảnh contactless mà FingerJetFX cho minutiae count thấp (vì đặc trưng texture khác) nhưng MDGT vẫn match tốt và SIFQ Q cao → cho thấy SIFQ captures "modern matcher utility" không phải "VeriFinger-era minutiae utility".
90
+
91
+ ---
92
+
93
+ ### 5. Vấn đề thiết kế cần xem xét nếu muốn validate nghiêm túc
94
+
95
+ Concept 5 trong paper được định nghĩa là *"synthesis of previous 3 concepts + own signal from occlusion"*. Nhưng implementation hiện tại **chỉ có occlusion + wet_press**. Nếu muốn concept 5 thực sự đại diện cho "minutiae reliability" đầy đủ như FingerJetFX:
96
+
97
+ **Option A (nhẹ):** Thêm `dry_skin: [5]` vào DEGRADATION_CONCEPT_MAP — dry skin tạo ridge gaps → false bifurcations → minutiae unreliable. Về mặt vật lý có cơ sở.
98
+
99
+ **Option B (mạnh hơn):** Thêm blur vào concept 5 supervision — blur không xác định được minutiae position chính xác là failure mode của mọi minutiae extractor. Nhưng cần cẩn thận: concept 1 (clarity) và 2 (continuity) đã được blur supervise → thêm concept 5 vào blur có thể tạo entanglement không cần thiết.
100
+
101
+ ---
102
+
103
+ ### Kết luận lý thuyết
104
+
105
+ | Câu hỏi | Kết luận |
106
+ |---|---|
107
+ | FingerJetFX có đo cùng phenomenon? | ✅ Có, nhưng minutiae trực tiếp thay vì latent proxy |
108
+ | Validation within-sensor có hợp lệ? | ✅ Hợp lệ, expected Spearman > 0.30 |
109
+ | Validation cross-sensor có hợp lệ? | ❌ Không — FingerJetFX có sensor bias, sẽ mislead |
110
+ | Dùng FingerJetFX làm oracle cho novelty? | ❌ Mâu thuẫn — novelty SIFQ là vượt qua giới hạn này |
111
+ | FingerJetFX có giúp chứng minh novelty? | ✅ Nếu so sánh KS stability của FingerJetFX vs SIFQ cross-sensor |
112
+
113
+ Thiết kế evaluation phù hợp: FingerJetFX dùng làm **baseline comparison** ("SIFQ ổn định hơn FingerJetFX trong điều kiện cross-sensor"), không phải **ground truth oracle** cho concept 5.
eval_results/sifq_report_v24.txt ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ======================================================================
2
+ SIFQ -- Concept Quality Model: Ly thuyet & Ket qua (v24)
3
+ Generated: 2026-06-01 17:17
4
+ ======================================================================
5
+
6
+ 1. DINH NGHIA 6 CONCEPTS
7
+ ----------------------------------------------------------------------
8
+ Tat ca concepts: cao = chat luong tot hon, dau ra trong [0, 1].
9
+
10
+ # Concept Y nghia vat ly
11
+ -- -------------------------- -----------------------------------------------
12
+ 0 orientation_coherence Ridge flow nhat quan, local orientation field smooth
13
+ 1 ridge_valley_clarity Bien ridge-valley sac net, contrast cuc bo cao
14
+ 2 continuity Ridge lines lien tuc, khong bi dut gay
15
+ 3 noise_level It nhieu ngau nhien (cao = it noise = tot)
16
+ 4 contrast_uniformity Contrast deu tren toan foreground
17
+ 5 minutiae_reliability Minutiae co the trich xuat chinh xac
18
+
19
+ Degradation Concept Map (v25 -- T40):
20
+ blur -> [clarity[1], continuity[2], orient_coh[0]]
21
+ noise -> [noise_level[3], contrast_u[4]]
22
+ jpeg -> [continuity[2], clarity[1], contrast_u[4]]
23
+ occlusion -> [minutiae_reliability[5]]
24
+ dry_skin -> [contrast_u[4], continuity[2], orient_coh[0]]
25
+ wet_press -> [clarity[1], minutiae_rel[5], orient_coh[0]]
26
+
27
+ Ly do thiet ke map nhu vay:
28
+ - Moi concept phai duoc giam sat boi >= 2 loai degradation (tranh single-
29
+ point-of-failure: 1 degradation target 1 concept -> signal yeu, de bi
30
+ gradient interference invert chieu).
31
+ - Chon degradation phu hop vat ly: jpeg blocking -> contrast bands (khong
32
+ chi ridge artifacts), blur -> orientation blur (khong chi clarity loss).
33
+
34
+
35
+ 2. CO CHE TRAINING CONCEPT (L_concept)
36
+ ----------------------------------------------------------------------
37
+ Voi moi cap anh (mild degradation vs severe degradation cung loai):
38
+
39
+ L_concept = SUM Huber( c_mild[c], c_severe[c] + 0.1 )
40
+ c in targets(degradation_type)
41
+
42
+ -> Anh degradation nhe phai co concept cao hon anh degradation nang >= 0.1
43
+ -> Model hoc tung concept phan ung dung chieu voi loai hu hong tuong ung
44
+
45
+ Ket hop ranking loss:
46
+ L_rank = relu(Q_severe - Q_mild + m) + relu(Q_mild - Q_clean + m)
47
+ -> Q giam theo thu tu: clean > mild_deg > severe_deg
48
+
49
+ L_deg = L_rank + gamma * L_concept
50
+ gamma = 2.0 (v24) -> 1.5 (v25)
51
+ - gamma qua cao (2.0): gradient conflict qua manh -> noise_level inversion
52
+ - gamma qua thap (0.5, v22): blur->continuity FAIL (+0.261)
53
+ - gamma = 1.5: compromise, du manh cho blur/jpeg, khong gay inversion
54
+
55
+
56
+ 3. VAN DE CONCEPT SATURATION
57
+ ----------------------------------------------------------------------
58
+ Nguyen nhan goc: L_concept chi train tren synthetic degradation pairs.
59
+ Voi real fingerprint images, KHONG co gradient dinh huong concept.
60
+ -> Concept troi ve gia tri mac dinh cua backbone features.
61
+
62
+ Hau qua trong v24 (42,683 real fingerprint images):
63
+
64
+ Concept mean std rho_Q Tinh trang
65
+ ---------------------------- ------ ----- ------ ---------------------------
66
+ orientation_coherence 0.111 0.048 -0.480 !! Saturated LOW -- T39 overcorrected
67
+ ridge_valley_clarity 0.050 0.074 +0.085 !! Near-dead -- low variance
68
+ continuity 0.043 0.029 +0.138 !! Near-dead -- low variance
69
+ noise_level 0.543 0.340 -0.989 !! DOMINATES Q (rho=-0.989)
70
+ contrast_uniformity 0.049 0.081 -0.131 !! Near-dead -- low variance
71
+ minutiae_reliability 0.868 0.033 -0.672 !! Saturated HIGH -- dead (range 0.84-0.93)
72
+
73
+ Vong lap nguy hiem (self-reinforcing collapse):
74
+ ScoreAggregator chon noise_level (std=0.340, cao nhat)
75
+ -> gradient tap trung update noise pathway
76
+ -> cac concept khac it duoc update -> variance thap hon
77
+ -> cang bi bo qua -> variance cang thap (vong lap)
78
+
79
+ He qua: Q ≈ f(noise_level) -- model thuc chat la "noise detector",
80
+ khong phai "quality estimator" da khai niem.
81
+
82
+
83
+ 4. KET QUA v24
84
+ ----------------------------------------------------------------------
85
+ Track 2 -- Sensor Invariance:
86
+ Mean KS (cross-sensor) = 0.1263 [goal <= 0.30] PASS
87
+ Cross-sensor Pearson = 0.8004 [goal >= 0.20] PASS
88
+
89
+ Y nghia: cung mot ngon tay chup bang cac sensor khac nhau -> SIFQ cho
90
+ score nhat quan. KS thap = phan bo giong nhau, Pearson cao = ranking on dinh.
91
+ NFIQ2 thuong co KS > 0.5 cho cross-sensor pairs.
92
+
93
+ Track 4 -- Concept Grounding (rho < 0 = PASS):
94
+ Degradation Concept rho Status
95
+ ------------ ---------------------------- ------- ------
96
+ blur ridge_valley_clarity -0.483 PASS
97
+ blur continuity -0.459 PASS
98
+ noise noise_level +0.365 FAIL <--
99
+ jpeg continuity -0.412 PASS
100
+ jpeg ridge_valley_clarity -0.345 PASS
101
+ occlusion minutiae_reliability -0.055 PASS
102
+ dry_skin contrast_uniformity +0.051 FAIL <--
103
+ dry_skin continuity -0.114 PASS
104
+ dry_skin orientation_coherence +0.008 FAIL <--
105
+ wet_press ridge_valley_clarity -0.042 PASS
106
+ wet_press minutiae_reliability -0.081 PASS
107
+ wet_press orientation_coherence -0.448 PASS
108
+
109
+ Result: 9/12 pairs PASS
110
+
111
+ 3 failures phan tich:
112
+
113
+ [1] noise -> noise_level (rho=+0.365):
114
+ Regression tu v22 (-0.052, OK) -> v24 (+0.365, FAIL).
115
+ gamma=2.0 + T39 (orient_coh added to dry_skin/wet_press) thay doi
116
+ gradient landscape cua ScoreAggregator. Noise la degradation duy nhat
117
+ target noise_level -> single-point pressure -> de bi invert.
118
+
119
+ [2] dry_skin -> contrast_u (rho=+0.051):
120
+ Persistent qua cac phien ban (v22: +0.504). Dry_skin la degradation
121
+ DUY NHAT target contrast_uniformity -> signal yeu, de bi gradient
122
+ tu cac loss khac at di.
123
+
124
+ [3] dry_skin -> orient_coh (rho=+0.008):
125
+ T39 moi them orient_coh vao dry_skin, nhung wet_press->orient_coh
126
+ hoat dong tot (-0.448). Ly do: wet_press + blur deu co orientation
127
+ disruption manh, nhung dry_skin tao ra orientation noise khong nhat
128
+ quan -> khong du signal de orient_coh feature phan biet.
129
+
130
+
131
+ 5. v25 -- T40 FIXES (dang chay)
132
+ ----------------------------------------------------------------------
133
+ Thay doi so voi v24:
134
+
135
+ gamma: 2.0 -> 1.5
136
+
137
+ blur: [1, 2] -> [1, 2, 0] (them orient_coh[0])
138
+ noise: [3] -> [3, 4] (them contrast_u[4])
139
+ jpeg: [2, 1] -> [2, 1, 4] (them contrast_u[4])
140
+ dry_skin / wet_press / occlusion: khong doi
141
+
142
+ Ket qua ky vong:
143
+ - noise->noise_lv: +0.365 -> negative (gamma thap + noise 2-concept)
144
+ - dry_skin->contrast_u: +0.051 -> negative (3 degs co-supervise contrast_u)
145
+ - dry_skin->orient_coh: +0.008 -> negative (blur gives orient_coh strong signal)
146
+ - Cac pairs da PASS: giu nguyen (blur/jpeg/occlusion/wet_press)
147
+ - Track 2: giu PASS (KS, Pearson khong thay doi co ban)
148
+
149
+ ======================================================================
150
+ END
151
+ ======================================================================
eval_results/sifq_scores_v16.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v17.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v18.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v19.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v20.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v21.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v22.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v24.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v25.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v27.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v28.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v29.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v30.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v31.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
eval_results/sifq_scores_v32.jsonl ADDED
The diff for this file is too large to render. See raw diff
 
logs/train_v26.log ADDED
The diff for this file is too large to render. See raw diff
 
rules/HOWTO_RUN.md ADDED
@@ -0,0 +1,775 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SIFQ — Hướng dẫn chạy
2
+
3
+ Tất cả lệnh chạy từ thư mục gốc: `/home/aiserver/works/fingerprint`
4
+
5
+ | Version | Status | Epochs | Highlights |
6
+ |---------|--------|--------|------------|
7
+ | v11 | ✅ Done | 80 | PolyU back in L_sens |
8
+ | v12 | ✅ Done | 80 | T17–T19 concept fixes |
9
+ | v13 | ✅ Done | 80 | Revert T17, per-dataset L_spread, occlusion fix |
10
+ | v14 | ✅ Done | 60 | Exclude non-segmented slap; KS=0.263 ✅, Pearson=0.294 ✅; dry_skin ↑↑ |
11
+ | v15 | ✅ Done | 60 | T30: SD302 concept-only L_deg + gamma=2.0; KS=0.2758 (tệ), score collapse (24–56) ❌ |
12
+ | v16 | ✅ Done | 60 | T31: per-identity cos stats + tanh; score collapse 46.9–50.5 ❌ (worse!); KS=0.527 ❌ |
13
+ | v17 | ✅ Done | 60 | T32: FVC-only cos stats; score collapse ALL SD302 at 52.7, q_std=0.60 ❌; KS=0.616 ❌ |
14
+ | v18 | ✅ Done ❌ | 60 | T33: revert v14 loss + SD302-A; **score collapse** q_std≈0.01, KS=0.249⚠️(false positive), Pearson=0.007❌; concept head stuck near bounds |
15
+ | v19 | ✅ Done ❌ | 60 | T34: true revert to v14 — spread-weight=3.0, deg-every-n-steps=2; score collapse ALL ~53.1x, q_std≈0.01 ❌ |
16
+ | v20 | ✅ Done ❌ | 60 | T35: full prototypes (proto-max=0) + L_deg on SD302; score collapse q_std≈0.007 ❌ — --deg-include-sd302 was wrong fix |
17
+ | v21 | ✅ Done ❌ | 60 | T36: full prototypes + FVC-only L_deg; KS=0.312, Pearson=0.092 ❌ — CrossSensorBatchSampler k_cross=16 destroyed quality discrimination |
18
+ | v22 | ✅ Done | 60 | T37: fix k_cross=0 + single GPU; KS=0.278, Pearson=0.546 |
19
+ | v24 | ✅ Done | 60 | Best: KS=0.126 ✅, Pearson=0.800 ✅, q_std~22 |
20
+ | v25 | ❌ Done | 60 | gamma=1.5 too weak; KS=0.213, Pearson=0.620 |
21
+ | v26 | ✅ Done | 60 | gamma=2.0 restored |
22
+ | v27 | ✅ Done | 60 | SpatialConceptHead |
23
+ | v28 | ✅ Done | 60 | No L_mat (--no-mat); KS=0.1346, Pearson=0.7645 |
24
+ | v29 | ❌ Done | 60 | T41 concept map + ortho-weight 3.0 + concept-spread-weight 1.0; KS=0.2985, Pearson=0.1448 |
25
+ | v31 | ✅ Done | 60 | DINOv2-ViTS/14 teacher (public); KS=0.1152, Pearson=0.8858 — best so far |
26
+ | v32 | 🚀 Next | 60 | T42: dry_skin[4,0] + noise[1,3] — fix noise_level crosstalk + weak noise signal |
27
+
28
+ ---
29
+
30
+ ## 1. Smoke test (kiểm tra pipeline ~2 phút)
31
+
32
+ ```bash
33
+ cd /home/aiserver/works/fingerprint
34
+ bash sifq/scripts/run_smoke.sh
35
+ ```
36
+
37
+ Kết quả ở `sifq/checkpoints_smoke/last.pt` và `metrics.jsonl`.
38
+
39
+ ---
40
+
41
+ ## 2. Full training v21 — Active 🚀 (60 epochs, từ đầu)
42
+
43
+ > **v21 — T36: Full prototypes + FVC-only L_deg (remove --deg-include-sd302).**
44
+ >
45
+ > **Root cause of v20 failure (new diagnosis):**
46
+ >
47
+ > v20 training showed q_std≈18.3 (healthy) but ALL SD302 inference scores collapsed to ~53.38
48
+ > (q_std≈0.007). The `--proto-max-batches 0` fix (T35a) was correct. But `--deg-include-sd302`
49
+ > (T35b) was WRONG and caused the collapse:
50
+ >
51
+ > - L_rank on SD302 says: Q(clean) > Q(low_deg) + m > Q(high_deg) + m
52
+ > - The model satisfies this with a single ~53.38 for ALL clean SD302 images + lower for degraded
53
+ > - L_rank does NOT require different clean images to score differently → attractor at ~53.38
54
+ > - L_spread_ds (batch-level) + L_pair reinforce the collapse
55
+ >
56
+ > **Why v14 worked without --deg-include-sd302:**
57
+ > FVC genuine quality variation → MDGT raw cosine genuinely varies (0.75→0.93) per impression
58
+ > → L_mat gradient shapes backbone to be quality-discriminative → transfers to SD302 at inference.
59
+ > L_rank on SD302 BLOCKS this transfer by creating the stable ~53.38 attractor.
60
+ >
61
+ > **T36 fix:** Remove `--deg-include-sd302`. Keep `--proto-max-batches 0`.
62
+ > FVC-only L_deg: genuine quality signal trains backbone → SD302 scored by intrinsic quality.
63
+
64
+ > **v20 — T35: Full prototypes + L_deg on SD302. Fix root causes of ALL v15–v19 failures.**
65
+ >
66
+ > **Root cause analysis (v19 failure = same collapse as v15–v18):**
67
+ >
68
+ > v19 was supposed to reproduce v14 exactly but STILL collapsed (all scores ~53.1x, q_std≈0.01).
69
+ > The "spread-weight/deg-every-n-steps mismatch" explanation was wrong. Two deeper root causes:
70
+ >
71
+ > **Root cause 1 — Truncated prototypes (T35a):**
72
+ > - v14's code had NO `--proto-max-batches` cap → prototypes computed on full 42,683 images
73
+ > - When this param was added (default=150 batches = ~19,200 images = 45% of data), SD302 identities
74
+ > went from full 19-sensor multi-sensor prototypes to 2–3 sensor partial prototypes
75
+ > - Full prototype: raw cosine varies with image quality across sensors (quality-discriminative)
76
+ > - Partial prototype: raw cosine correlates with WHICH sensors are in the prototype window
77
+ > → sensor-biased, NOT quality-correlated → no per-image quality gradient for SD302 → collapse
78
+ >
79
+ > **Root cause 2 — FVC-only L_deg leaves SD302 without ordinal grounding (T35b):**
80
+ > - T27 reverted T17 (L_deg on all images) because clean SD302 anchored at ~28
81
+ > - But T27 ITSELF introduced per-dataset L_spread_ds — which prevents anchoring
82
+ > - With L_spread_ds forcing SD302 to span [10,90], re-enabling full L_rank for SD302 is now safe
83
+ > - L_deg (L_rank + L_concept) on SD302 provides the only stable per-image quality signal
84
+ > for SD302 at inference (synthetic degradation response ≈ ridge quality proxy)
85
+ >
86
+ > **T35 fixes:**
87
+ > 1. **T35a — `--proto-max-batches 0`**: Full dataset prototype computation. Cost: ~10–15 min
88
+ > overhead at epoch 0 (334 batches vs 150). Restores genuine per-image L_mat quality signal.
89
+ > 2. **T35b — `--deg-include-sd302`**: Apply full L_deg (L_rank + L_concept) to SD302 images.
90
+ > L_spread_ds prevents the T17 score anchoring issue. Per-image ordinal grounding for SD302.
91
+ >
92
+ > **All other settings from v19 kept unchanged:**
93
+ > - `--no-mat-stats`, `--spread-weight 3.0`, `--deg-every-n-steps 2`
94
+ > - `--concept-deg-gamma 0.5`, `--sd302-concept-weight 0.0`
95
+ > - SD302-A included, `--batch-size 128`, `--gpus 0`
96
+
97
+ ## 2. Full training v22 — 🚀 Next run (60 epochs, từ đầu)
98
+
99
+ > **v22 — T37: Fix ALL bugs from v15–v21. First correct run with full dataset.**
100
+ >
101
+ > **Three bugs caused v15–v21 to fail:**
102
+ >
103
+ > **BUG 1 — CrossSensorBatchSampler k_cross=16:**
104
+ > - k_cross=16 forces 16 guaranteed pairs/batch = 8–16× more L_sens pressure
105
+ > - With full prototypes (nearly-constant L_mat targets), backbone over-optimises sensor
106
+ > invariance and loses quality discrimination → Pearson collapses to ~0.09 (v21)
107
+ > - **Fix: `--k-cross 0` (random batching)**
108
+ >
109
+ > **BUG 2 — proto-max-batches default=150:**
110
+ > - Only 45% of dataset used for prototypes → partial sensor prototypes → sensor-biased cosine
111
+ > - **Fix: `--proto-max-batches 0` (full dataset)**
112
+ >
113
+ > **BUG 3 — DataParallel (--gpus 0,1) causes 4.3× slowdown for TinyViT-5M:**
114
+ > - **Fix: `--gpus 0` (single GPU)**
115
+ >
116
+ > **BONUS — Redundant teacher double-pass eliminated:**
117
+ > - Now `build_prototypes_from_cache()` computes prototypes from emb_cache (O(N) CPU)
118
+
119
+ > **Note on high L_sens / pair loss in v22:**
120
+ > v22 includes SD302-A (8 diverse roll sensors per finger). L_mat targets vary by sensor
121
+ > for the same finger → L_pair starts high (~12 at S2 onset) and decreases gradually.
122
+ > This is EXPECTED with a richer dataset — not a failure. q_std=21–22 (best quality
123
+ > discrimination so far). L_sens equilibrium is found by ep60.
124
+
125
+ ```bash
126
+ cd /home/aiserver/works/fingerprint
127
+ version=v32
128
+ nohup bash sifq/scripts/run_train_$version.sh > sifq/logs/train_$version.log 2>&1 &
129
+ echo "PID: $!"
130
+ tail -f sifq/logs/train_$version.log
131
+
132
+ pkill -f train_sifq.py
133
+ ```
134
+
135
+ **Expected results (research design goals, 171 sensor pairs):**
136
+
137
+ | Metric | v21 ❌ | v22 (ep51) | v22 goal |
138
+ |--------|--------|--------|----------|
139
+ | q_std (train) | ~17.7 | **~22** ✅ | ≥18 |
140
+ | epoch time | ~970s ❌ | **~220s** ✅ | ≤250s |
141
+ | Track 2 mean_KS | 0.312 | — (training) | **≤0.30** |
142
+ | Track 2 Pearson | +0.092 ❌ | — (training) | **≥0.20** |
143
+ | Concept grounding | dry_skin+0.83 ❌ | — (training) | **all targets negative ρ** |
144
+
145
+ **Dấu hiệu v22 đang train đúng:**
146
+
147
+ | Epoch | Dấu hiệu tốt |
148
+ |-------|-------------|
149
+ | ep 0 | Startup nhanh (~teacher 1 pass + cache); epoch ~220s |
150
+ | ep 0–10 | q_std tăng nhanh 1→10→18; l_mat ~0.18–0.20; l_deg > 0 |
151
+ | ep 12+ | l_pair cao (~12) khi S2 bắt đầu — BÌNH THƯỜNG với SD302-A 8 sensors |
152
+ | ep 20–50 | l_pair giảm dần (12→4→2); adv tăng về rand_ce; q_std ~20–22 ✅ |
153
+ | ep 40–60 | Stable: l_spread ≈0.002, q_mean ~52, q_std ~21–22 |
154
+
155
+ ---
156
+
157
+ ## 3. Full training v21 — Done ❌ (60 epochs)
158
+ | ep 20+ | `train_l_pair` → 0.01–0.05, q_std ổn định 12–18 |
159
+
160
+ > **Key difference from v20:** `train_q_std` in v20 was also 18.3 (false positive driven by L_spread).
161
+ > In v21, watch for **INFERENCE q_std > 5** at end — run a quick spot-check:
162
+ > `python sifq/scripts/run_infer.py --checkpoint sifq/checkpoints/v21/last.pt --max-samples 200 --output /tmp/spot.jsonl && python -c "import json,statistics; s=[json.loads(l)['q_score'] for l in open('/tmp/spot.jsonl')]; print(f'std={statistics.stdev(s):.2f} range=[{min(s):.1f},{max(s):.1f}]')"`
163
+
164
+ ```bash
165
+ cd /home/aiserver/works/fingerprint
166
+ nohup bash sifq/scripts/run_train_v21.sh > sifq/logs/train_v21.log 2>&1 &
167
+ echo "PID: $!"
168
+ tail -f sifq/logs/train_v21.log
169
+ ```
170
+
171
+ - Checkpoint: `sifq/checkpoints/v21/last.pt`
172
+ - Train từ đầu, LR: `1e-4` cosine → 5e-6, Batch: `128`, GPU: `0`
173
+ - **Auto-eval** sau training: kết quả ở `sifq/eval_results/v21/`
174
+
175
+ ---
176
+
177
+ ## 2b. Eval v21 — Chạy thủ công nếu cần
178
+
179
+ ```bash
180
+ cd /home/aiserver/works/fingerprint
181
+ nohup bash sifq/scripts/run_eval_v32.sh > sifq/eval_v32.log 2>&1 &
182
+ echo "PID: $!"
183
+ ```
184
+
185
+ Kết quả ở `sifq/eval_results/v21/`.
186
+
187
+ ---
188
+
189
+ ## 2c. Full training v20 — Completed ❌ (score collapse)
190
+
191
+ > **v20 actual results:** q_std≈0.007 (collapsed), mean_KS=0.4936 ❌, Pearson=0.0048 ❌.
192
+ > Root cause: `--deg-include-sd302` applied L_rank to all clean SD302 → stable ~53.38 attractor.
193
+ > See v21 for fix.
194
+
195
+ ---
196
+
197
+ ## 2d. Eval v20 — Chạy thủ công nếu cần
198
+
199
+ ```bash
200
+ cd /home/aiserver/works/fingerprint
201
+ nohup bash sifq/scripts/run_eval_v20.sh > sifq/eval_v20.log 2>&1 &
202
+ echo "PID: $!"
203
+ ```
204
+
205
+ Kết quả ở `sifq/eval_results/v20/`.
206
+
207
+ ---
208
+
209
+ ## 2c. Full training v19 — Completed ❌ (score collapse — 60 epochs)
210
+
211
+ > **v19 — T34: True revert to v14 hyperparameters (FAILED — same collapse as v18).**
212
+ > Root cause was NOT the spread/deg values (those were already correct in v19).
213
+ > Real root cause: truncated prototypes + FVC-only L_deg. See v20 analysis above.
214
+
215
+ ---
216
+
217
+ ## 2. Full training v18 — Completed ❌ (score collapse — 60 epochs)
218
+
219
+ > **v18 — T33: revert toward v14 + include SD302-A.**
220
+ >
221
+ > Root cause từ v17 eval:
222
+ > - T32 chỉ remove explicit L_mat vs L_pair conflict, nhưng SD302 VẪNN collapse → q_std=0.60 at inference.
223
+ > - FVC tanh targets (variable) vs SD302 raw cosine targets (constant) tạo asymmetry → model học shortcut "FVC=variable, SD302=52.7".
224
+ > - W_SPREAD=4.0 + gamma=2.0 + sd302_concept_weight=1.0 làm tệ thêm so với v14.
225
+ >
226
+ > **T33 fixes: revert tất cả additions từ v15–v17:**
227
+ > 1. **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.
228
+ > 2. **T33b — W_SPREAD = 2.0** (revert từ 4.0 — v14 level)
229
+ > 3. **T33c — concept_deg_gamma = 0.5** (revert từ 2.0 — v14 default)
230
+ > 4. **T33d — sd302_concept_weight = 0.0** (revert T30b — v14 default)
231
+ > 5. **T33e — deg-every-n-steps = 4** (revert từ 2 — v14 default)
232
+ > 6. **NEW — SD302-A included**: 13,630 images, 8 sensors (A-H) trong training (v14 chỉ dùng B+D)
233
+
234
+ ```bash
235
+ cd /home/aiserver/works/fingerprint
236
+ nohup bash sifq/scripts/run_train_v18.sh > sifq/logs/train_v18.log 2>&1 &
237
+ echo "PID: $!"
238
+ tail -f sifq/logs/train_v18.log
239
+ ```
240
+
241
+ - Checkpoint: `sifq/checkpoints/v18/last.pt`
242
+ - Metrics: `sifq/checkpoints/v18/metrics.jsonl`
243
+ - Train từ đầu (không resume)
244
+ - LR: `1e-4` cosine → 5e-6
245
+ - Batch: `128`
246
+ - **Auto-eval** sau training: kết quả ở `sifq/eval_results/v18/`
247
+
248
+ **Kết quả v18 thực tế (FAILED — score collapse):**
249
+
250
+ | Metric | v14 ✅ | v17 ❌ | v18 actual ❌ | Target |
251
+ |--------|--------|--------|--------------|--------|
252
+ | q_std (inference) | ~15 | 0.60 | **0.01 ❌❌** | **>12** |
253
+ | Score range | 10–90 | 18–53 | **54.62–54.65 ❌** | **10–90** |
254
+ | Track 2 mean_KS | 0.263 | 0.616 | **0.249 ⚠️** | **≤0.27** |
255
+ | Track 2 Pearson | +0.294 | -0.002 | **0.007 ❌** | **≥0.25** |
256
+ | n_sensor_pairs | 55 | 171 | **171** | **≥100** |
257
+
258
+ > **⚠️ v18 KS=0.249 là false positive**: Model không phân biệt được images — tất cả sensors cho cùng score ≈54.64. KS thấp vì các phân bố trivially giống nhau (đều là Dirac delta tại 54.64). Root cause mới: raw cosine L_mat hằng số (~0.85) không tạo per-image quality gradient → model collapse về mean. Cần T34: tìm cách tạo per-image quality signal mà không gây FVC/SD302 asymmetry.
259
+
260
+ **Dấu hiệu v18 đang train đúng:**
261
+
262
+ | Epoch | Dấu hiệu tốt |
263
+ |-------|-------------|
264
+ | ep 0–10 | `train_q_std` tăng > 15, `train_l_mat` giảm (~0.25–0.35) |
265
+ | ep 11–20 | `train_l_pair` giảm (GRL kick-in), q_std giảm tạm (~12-15) |
266
+ | ep 20+ | `train_l_pair` → 0.01–0.05, q_std ổn định 12–18 |
267
+
268
+ ---
269
+
270
+ ## 2a. Eval v18 — Chạy thủ công nếu cần
271
+
272
+ ```bash
273
+ cd /home/aiserver/works/fingerprint
274
+ nohup bash sifq/scripts/run_eval_v18.sh > sifq/eval_v18.log 2>&1 &
275
+ echo "PID: $!"
276
+ ```
277
+
278
+ Kết quả ở `sifq/eval_results/v18/`.
279
+
280
+ ---
281
+
282
+ ## 2. Full training v19 — Active 🚀 (60 epochs, từ đầu)
283
+
284
+ > **v19 — T34: True revert to v14 hyperparameters.**
285
+ >
286
+ > Root cause từ v18 failure:
287
+ > - v18 comments nói "revert to v14" nhưng dùng sai giá trị:
288
+ > - `--spread-weight 2.0` (v14 thực tế: **3.0** — sai 50%)
289
+ > - `--deg-every-n-steps 4` (v14 thực tế: **2** — sai 2×)
290
+ > - Hai sai số này làm L_spread + L_deg yếu hơn v14 → backbone không học được quality-discriminative features → inference collapse (q_std≈0.01).
291
+ > - Xác nhận bằng `diff run_train_v14.sh run_train_v18.sh`.
292
+ >
293
+ > **T34 fixes:**
294
+ > 1. **T34a — `--spread-weight 3.0`**: Restore v14 actual value. Gradient L_spread mạnh hơn buộc backbone phân biệt quality.
295
+ > 2. **T34b — `--deg-every-n-steps 2`**: Restore v14 actual value. 2× tần suất L_deg → ordinal grounding mạnh hơn.
296
+ >
297
+ > **Giữ nguyên từ v18:**
298
+ > - `--no-mat-stats`: cần thiết để reproduce v14 pre-T31 behavior với code hiện tại
299
+ > - `--concept-deg-gamma 0.5`, `--sd302-concept-weight 0.0` (v14 defaults)
300
+ > - SD302-A included (v18 addition, giữ lại)
301
+ > - `--batch-size 128`, `--gpus 0`
302
+
303
+ ```bash
304
+ cd /home/aiserver/works/fingerprint
305
+ nohup bash sifq/scripts/run_train_v19.sh > sifq/logs/train_v19.log 2>&1 &
306
+ echo "PID: $!"
307
+ tail -f sifq/logs/train_v19.log
308
+ ```
309
+
310
+ - Checkpoint: `sifq/checkpoints/v19/last.pt`
311
+ - Metrics: `sifq/checkpoints/v19/metrics.jsonl`
312
+ - Train từ đầu (không resume)
313
+ - LR: `1e-4` cosine → 5e-6
314
+ - Batch: `128`, GPU: `0`
315
+ - **Auto-eval** sau training: kết quả ở `sifq/eval_results/v19/`
316
+
317
+ **Expected results (target = v14 baseline):**
318
+
319
+ | Metric | v14 ✅ | v18 ❌ | v19 target |
320
+ |--------|--------|--------|-----------|
321
+ | q_std (inference) | ~15.5 | 0.01 | **>12** |
322
+ | Score range | 10–90 | 54.62–54.65 | **10–90** |
323
+ | Track 2 mean_KS | 0.263 | 0.249⚠️ | **≤0.27 (real)** |
324
+ | Track 2 Pearson | +0.294 | 0.007 | **≥0.25** |
325
+
326
+ **Dấu hiệu v19 đang train đúng:**
327
+
328
+ | Epoch | Dấu hiệu tốt |
329
+ |-------|-------------|
330
+ | ep 0–10 | `train_q_std` > 15, `train_l_mat` giảm (~0.25–0.35) |
331
+ | ep 11–20 | `train_l_pair` giảm (GRL kick-in), q_std giảm tạm (~12–15) |
332
+ | ep 20+ | `train_l_pair` → 0.01–0.05, q_std ổn định 12–18 |
333
+
334
+ ---
335
+
336
+ ## 2b. Eval v19 — Chạy thủ công nếu cần
337
+
338
+ ```bash
339
+ cd /home/aiserver/works/fingerprint
340
+ nohup bash sifq/scripts/run_eval_v19.sh > sifq/eval_v19.log 2>&1 &
341
+ echo "PID: $!"
342
+ ```
343
+
344
+ Kết quả ở `sifq/eval_results/v19/`.
345
+
346
+ ---
347
+
348
+ ## 3. Full training v17 — Completed (60 epochs) ✅ (score collapse ❌)
349
+
350
+ > **v17 thất bại**: Score collapse nghiêm trọng — tất cả SD302 images output ~52.7 (q_std=0.60 at inference). Training q_std=16.59 vẫn ổn (driven by FVC). KS=0.616 ❌.
351
+ >
352
+ > **Root cause v17 (sâu hơn T32 đã fix)**:
353
+ > - T32 fix (FVC-only stats, SD302 raw cosine fallback) đã loại bỏ L_mat vs L_pair CONFLICT nhưng không fix SCORE COLLAPSE.
354
+ > - SD302 raw cosine ≈ 0.85 là CONSTANT cho tất cả images → L_mat không phân biệt được SD302 identities với nhau → không có per-image quality signal cho SD302.
355
+ > - 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.
356
+ > - L_spread_ds tạo relative constraints per-batch nhưng KHÔNG CONSISTENT qua các batches → average score cho mỗi SD302 image settle về ~52.7.
357
+ > - FVC images: có stable per-image tanh targets → model học được quality function. SD302: chỉ có inconsistent batch-relative spread signals → feature collapse.
358
+ >
359
+ > **v16 root cause (T32 mục tiêu)**:
360
+
361
+ > **v17 là training hiện tại.** Root cause từ v16 eval:
362
+ > - **Score collapse nghiêm trọng**: inference q_std=0.33, range 46.9–50.5 (tệ hơn v15!). Training q_std=15.6 trông ổn nhưng driven bởi FVC images. Inference chỉ chạy SD302 → collapse.
363
+ > - **T32 — Root cause**: T31's per-identity stats conflict trực tiếp với L_pair.
364
+ > - L_mat (T31b): `q_mat = tanh((cos−μᵢ)/σᵢ)` → muốn **within-identity variation** (ảnh khác nhau của cùng ngón tay nên score khác nhau)
365
+ > - L_pair: `|Q(s1)−Q(s2)| ≤ 0.05` → muốn **within-identity uniformity** (cùng ngón tay, khác sensor, phải score bằng nhau)
366
+ > - Hai loss conflict → model giải quyết bằng output ~50 cho tất cả SD302. FVC không có L_pair → spread được → training q_std=15.6 driven by FVC only.
367
+ >
368
+ > **v17 fixes (T32): FVC-only per-identity stats**
369
+ > 1. **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.
370
+ > 2. **T32b — `_compute_q_mat` fallback to raw cosine**: SD302 identities không có trong stats → dùng raw cosine (~0.85, hằng số) giống v14. Không còn conflict với L_pair.
371
+ > 3. **Giữ nguyên**: W_SPREAD=4.0, concept_deg_gamma=2.0, sd302_concept_weight=1.0, deg-every=2.
372
+
373
+ ```bash
374
+ cd /home/aiserver/works/fingerprint
375
+ nohup bash sifq/scripts/run_train_v17.sh > sifq/logs/train_v17.log 2>&1 &
376
+ echo "PID: $!"
377
+ tail -f sifq/logs/train_v17.log
378
+ ```
379
+
380
+ - Checkpoint: `sifq/checkpoints/v17/last.pt`
381
+ - Metrics: `sifq/checkpoints/v17/metrics.jsonl`
382
+ - Train từ đầu (không resume)
383
+ - LR: `1e-4` cosine → 5e-6
384
+ - Batch: `128`
385
+ - **Auto-eval** sau training: kết quả ở `sifq/eval_results/v17/`
386
+
387
+ **Kết quả v17 (thực tế so với target):**
388
+
389
+ | Metric | v14 | v16 | Target v17 | Thực tế v17 |
390
+ |--------|-----|-----|------------|-------------|
391
+ | Score range (eval, SD302) | — | 46.9–50.5 ❌ | **0–100** | 18.1–53.0 (all ~52.7) ❌ |
392
+ | q_std (inference) | — | 0.33 ❌ | **>10** | **0.60** ❌ (worse collapse) |
393
+ | q_std (train, final) | ~15.5 | 15.6 | ~15–20 | 16.59 ✅ |
394
+ | Track 2 mean_KS | 0.263 ✅ | 0.527 ❌ | **≤0.27** | **0.616** ❌ |
395
+ | Track 2 Pearson | 0.294 ✅ | 0.046 ❌ | **≥0.25** | **-0.002** ❌ |
396
+
397
+ **Dấu hiệu v17 đang train đúng (watch trong log):**
398
+
399
+ | Epoch | Dấu hiệu tốt |
400
+ |-------|-------------|
401
+ | ep 0–5 | `train_l_mat` bắt đầu giảm (~0.15–0.25) — FVC quality signal hoạt động |
402
+ | ep 0–10 | `train_q_std` tăng lên > 15 (L_spread có tác dụng trên mixed batch) |
403
+ | ep 11–15 | `train_l_pair` giảm nhanh (GRL kick-in), q_std giảm tạm thời |
404
+ | ep 20+ | `train_l_pair` → 0.01–0.05, `train_q_std` ≥ 12, ổn định |
405
+
406
+ ---
407
+
408
+ ## 2a. Eval v17 — Chạy thủ công nếu cần
409
+
410
+ Auto-eval đã được tích hợp vào `run_train_v17.sh`. Nếu cần chạy lại riêng:
411
+
412
+ ```bash
413
+ cd /home/aiserver/works/fingerprint
414
+ nohup bash sifq/scripts/run_eval_v17.sh > sifq/eval_v17.log 2>&1 &
415
+ echo "PID: $!"
416
+ ```
417
+
418
+ Kết quả ở `sifq/eval_results/v17/`.
419
+
420
+ ---
421
+
422
+ ## 2b. Full training v16 — Completed (60 epochs) ✅ (score collapse ❌)
423
+
424
+ > **v16 thất bại**: score collapse 46.9–50.5 (tệ hơn v15!), KS=0.527. Root cause: T31 conflict với L_pair → T32 fix.
425
+
426
+ ```bash
427
+ # Xem kết quả v16 eval
428
+ cat sifq/eval_results/v16/eval_summary.json
429
+ ```
430
+
431
+ - Checkpoint: `sifq/checkpoints/v16/last.pt`
432
+ - Eval kết quả: `sifq/eval_results/v16/`
433
+
434
+ ---
435
+
436
+ ## 2c. Full training v15 — Completed (60 epochs) ✅ (score collapse ❌)
437
+
438
+ > **v15 thất bại**: score range 24–56 (score collapse), KS=0.2758 (tệ hơn v14). Root cause: T31.
439
+
440
+ ```bash
441
+ # Chỉ xem logs — không cần chạy lại
442
+ cat sifq/eval_v15.log
443
+ cat sifq/checkpoints_full_v15/metrics.jsonl | tail -5
444
+ ```
445
+
446
+ ---
447
+
448
+ ## 2c. Full training v14 — Completed (60 epochs, từ đầu) ✅
449
+
450
+ ```bash
451
+ nohup bash sifq/scripts/run_eval_v15.sh > sifq/eval_v15.log 2>&1 &
452
+ echo "PID: $!"
453
+ ```
454
+
455
+ Kết quả ở `sifq/eval_results/v15/`.
456
+
457
+ ---
458
+
459
+ ## 2c. Full training v14 — Completed (60 epochs, từ đầu) ✅
460
+
461
+ > **v14 đã train xong.** Nguyên nhân gốc từ v13 eval:
462
+ > 1. **T28 — Non-segmented slap std≈0**: `R_1000_slap`, `R_500_slap`, `S_500_slap` là ảnh 4 ngón tay → backbone cho score ~21.2 cho mọi người (std=0). Kéo mean_KS từ 0.51 (v12) lên 0.634 (v13 — tệ hơn). Loại khỏi training và eval.
463
+ > 2. **T29 — Train từ đầu (không resume)**: backbone TinyViT từ IN22k pretrained, concept head + aggregator ngẫu nhiên → cần 60 epochs để converge đầy đủ.
464
+
465
+ ```bash
466
+ cd /home/aiserver/works/fingerprint
467
+ nohup bash sifq/scripts/run_train_v14.sh > sifq/train_v14.log 2>&1 &
468
+ echo "PID: $!"
469
+ tail -f sifq/train_v14.log
470
+ ```
471
+
472
+ - Checkpoint: `sifq/checkpoints_full_v14/last.pt`
473
+ - Metrics: `sifq/checkpoints_full_v14/metrics.jsonl`
474
+ - Train từ đầu (không resume)
475
+ - **Sensors bị loại**: `R_1000_slap`, `R_500_slap`, `S_500_slap` (~1,700 records)
476
+ - **Dataset**: 42,683 records, 29 sensors
477
+
478
+ **Kết quả training v14 (60 epochs):**
479
+
480
+ | Metric | v13 | v14 thực tế | Trend |
481
+ |--------|-----|-------------|-------|
482
+ | `q_mean` (train) | ~33 | **52.6** | ✅ Centered tốt hơn hẳn |
483
+ | `q_std` (train) | 12.5 | **~15.5** | ✅ Spread ổn định |
484
+ | `l_pair` (ep59) | — | **0.006** | ✅ Sensor invariance xuất sắc |
485
+ | `l_mat` (ep59) | — | **0.270** | ✅ Converged tốt |
486
+ | `l_spread` (ep59) | — | **0.025** | ✅ Ổn định |
487
+ | Eval (KS/Pearson) | 0.634 / 0.224 | **0.263 / 0.294** ✅ | Target ✅ |
488
+
489
+ **3-phase training dynamics (quan sát được lần đầu ở v14 do train from scratch):**
490
+
491
+ | Phase | Epochs | q_std | l_pair | Mô tả |
492
+ |-------|--------|-------|--------|-------|
493
+ | S1 — Spread | 0–10 | 1 → 22.6 | 0.47 → 25 | GRL λ warm-up, L_spread mở rộng phân bố |
494
+ | Transition | 11–15 | 22.6 → 14 | 24 → 0.13 | β kick-in, GRL triệt tiêu sensor signature |
495
+ | Equilibrium | 16–59 | ~15.5 | → 0.006 | l_pair/l_mat converged, l_spread stable |
496
+
497
+ **Kết quả eval v14 (Track 2 + Track 4):**
498
+
499
+ | Track | Metric | v12 | v13 | v14 |
500
+ |-------|--------|-----|-----|-----|
501
+ | Track 2 | mean_KS | 0.510 | 0.634 ❌ | **0.263** ✅ |
502
+ | Track 2 | Pearson | -0.003 | +0.224 | **+0.294** ✅ |
503
+ | Track 2 | n\_sensor\_pairs | 91 | 91 | 55 (slap loại) |
504
+ | Track 4 | dry_skin → contrast | — | -0.376 | **-0.623** ✅⬆ |
505
+ | Track 4 | dry_skin → continuity | — | +0.009 | **-0.563** ✅⬆ |
506
+ | Track 4 | blur → clarity | — | -0.490 ✅ | -0.187 ⚠️ (yếu hơn) |
507
+ | Track 4 | noise → noise_level | — | -0.533 ✅ | -0.019 ⚠️ (regression) |
508
+ | Track 4 | wet_press → minutiae | — | +0.326 ❌ | +0.565 ❌ (tệ hơn) |
509
+
510
+ **Expected improvements v14 — đã đạt:**
511
+
512
+ | Track | Metric | v13 | Target v14 |
513
+ |-------|--------|-----|------------|
514
+ | Score | Sensor clusters | 3 cụm (~21, ~50, ~55) | **2 cụm hoặc phẳng** (slap đã loại) |
515
+ | Track 2 | mean_KS | 0.634 ❌ | **<0.35** ✅ |
516
+ | Track 2 | Pearson | 0.224 | **≥0.25** |
517
+ | Train | Epochs | 80 | **60** (from scratch) |
518
+
519
+ ---
520
+
521
+ ## 2d. Eval v14 — Chạy sau khi training xong ⭐
522
+
523
+ > **Bước tiếp theo bắt buộc** sau khi v14 training completed.
524
+
525
+ ```bash
526
+ # Bước 1: Inference — sinh Q scores
527
+ python sifq/scripts/run_infer.py \
528
+ --checkpoint sifq/checkpoints_full_v14/last.pt \
529
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
530
+ --output sifq/eval_results/sifq_scores_v14.jsonl
531
+
532
+ # Bước 2: Eval — Track 2 + Track 4
533
+ python sifq/scripts/run_eval.py \
534
+ --sifq-scores sifq/eval_results/sifq_scores_v14.jsonl \
535
+ --checkpoint sifq/checkpoints_full_v14/last.pt \
536
+ --out-dir sifq/eval_results/v14 \
537
+ --skip-track1
538
+
539
+ # Bước 3: Visual score milestones
540
+ mkdir -p sifq/eval_results/v14
541
+ python sifq/visualize_score_milestones.py \
542
+ --scores sifq/eval_results/sifq_scores_v14.jsonl \
543
+ --output sifq/eval_results/v14/milestone_samples.png \
544
+ --n_buckets 8
545
+ ```
546
+
547
+ ---
548
+
549
+ ## 2b. Eval v13 (chính xác, exclude non-segmented slap)
550
+
551
+ ```bash
552
+ bash sifq/scripts/run_eval_v13.sh
553
+ ```
554
+
555
+ Kết quả ở `sifq/eval_results/v13_seg/` (exclude `R/S_*_slap`).
556
+
557
+ ---
558
+
559
+ ## 2c. Full training v13 — Completed (80 epochs)
560
+
561
+ > **v13 là training hiện tại.** Phân tích sau v12 eval cho thấy T17 fix (L_deg on all datasets) là sai về nguyên tắc:
562
+ > 1. **T20 — SD302 anchored tại ~28**: Synthetic degradation trên SD302 kéo clean images về gần degraded floor (~28). SD302 toàn ảnh chất lượng cao → synthetic degradation không phản ánh quality variation thực → anchoring sai.
563
+ > 2. **T21 — Non-segmented slap std=0**: Full-hand slap images visually homogeneous → model gán cùng score (behavior đúng, không cần fix).
564
+ > 3. **T22 — Noise concept regression**: `noise_level: +0.188 (v11) → -0.168 (v12)`. Old `c_idx==3` special case gây conflict với L_rank → model invert noise_level direction.
565
+ > 4. **T23 — Occlusion vẫn dead**: 40% coverage chưa đủ + continuity concept không được supervise.
566
+ >
567
+ > **v13 fixes:**
568
+ > - **T27**: Revert T17 (FVC-only L_deg) + **per-dataset L_spread** cho SD302 subset riêng (prevents SD302 collapse mà không cần synthetic degradation anchoring).
569
+ > - **T25**: Remove `c_idx==3` special case. Tất cả concepts giảm với degradation (high=better).
570
+ > - **T26**: Occlusion: add continuity (c_idx=2) to DEGRADATION_CONCEPT_MAP + coverage 40%→55%.
571
+
572
+ ```bash
573
+ cd /home/aiserver/works/fingerprint
574
+ nohup bash sifq/scripts/run_train_v13.sh > sifq/train_v13.log 2>&1 &
575
+ echo "PID: $!"
576
+ tail -f sifq/train_v13.log
577
+ ```
578
+
579
+ - Checkpoint: `sifq/checkpoints_full_v13/last.pt`
580
+ - Metrics: `sifq/checkpoints_full_v13/metrics.jsonl`
581
+ - Resume từ: `sifq/checkpoints_full_v12/last.pt`
582
+
583
+ **Expected improvements v13:**
584
+
585
+ | Track | Metric | v11 | v12 | Target v13 |
586
+ |-------|--------|-----|-----|----------|
587
+ | Score | q_std (inference) | 6.47 | 12.53 | **>18** (spread đều, bao gồm SD302 roll/flat) |
588
+ | Score | mean | 59.81 | 33.63 | **45–65** (SD302 anchored đúng chỗ) |
589
+ | Track 2 | mean_KS | 0.5566 | 0.5100 | **<0.20** (sensor type bias vẫn còn nhưng giảm) |
590
+ | Track 4 | wet_press → clarity | +0.219 ❌ | -0.647 ✅ | giữ ✅ |
591
+ | Track 4 | noise → noise_level | +0.188 ✅ | -0.168 ❌ | **positive ✅** (T25 fix) |
592
+ | Track 4 | occlusion → continuity | -0.029 ❌ | +0.023 ❌ | **negative ✅** (T26 fix) |
593
+ | Track 4 | occlusion → minutiae | -0.032 ❌ | +0.075 ❌ | **negative ✅** (T26 fix) |
594
+
595
+ ---
596
+
597
+ ## 2b. Full training v11 — Completed (80 epochs)
598
+
599
+ > v11 đã train xong. Checkpoint tại `sifq/checkpoints_full_v11/last.pt`.
600
+ > 1. **PolyU trở lại L_sens** — contact vs contactless pairs là tín hiệu L_sens mạnh nhất (2,612 anchor groups thay vì 2,276)
601
+ > 2. **PolyU bị mask khỏi L_mat** — không compute prototype / teacher loss cho PolyU
602
+ > 3. **PolyU bị mask khỏi L_deg** — không apply degradation cho PolyU images
603
+ > 4. **Schedule mới: β/α = 1.0 ngay từ S2 (ep20)** — β ramp nhanh hơn α trong ep10–19
604
+ > - S2: α=0.30 β=0.30 γ=0.60 (β/α=1.0) thay vì α=0.40 β=0.20 của v9
605
+ > - S3: α=0.25 β=0.35 γ=0.50 (β/α=1.4)
606
+ > + Root cause của v9 oscillation: β/α=0.50 trong S2 quá yếu — GRL không đủ override L_mat với PolyU cross-modality pairs
607
+
608
+ ```bash
609
+ cd /home/aiserver/works/fingerprint
610
+ nohup bash sifq/scripts/run_train_v14.sh > sifq/train_v14.log 2>&1 &
611
+ echo "PID: $!"
612
+
613
+ # Theo dõi log
614
+ tail -f sifq/train_v11.log
615
+ ```
616
+
617
+ - Dữ liệu: SD302-A/B/D + FVC2002 + FVC2004 + PolyU = **43,559 ảnh, 24 sensors**
618
+ - L_sens anchors: SD302 (~2,276 groups) + PolyU (336 cross-modal groups) = 2,612 total
619
+ - L_mat: SD302 + FVC (PolyU masked)
620
+ - L_deg: FVC only (SD302 + PolyU masked)
621
+ - Checkpoint: `sifq/checkpoints_full_v11/last.pt`
622
+ - Metrics: `sifq/checkpoints_full_v11/metrics.jsonl`
623
+ - Thời gian ước tính: **~9 giờ** (2× RTX A4000, DataParallel, 453 steps/epoch)
624
+
625
+ Kiểm tra nhanh training đang chạy:
626
+
627
+ ```bash
628
+ # Xem loss mới nhất
629
+ tail -5 sifq/checkpoints_full_v11/metrics.jsonl | python3 -c "
630
+ import sys, json
631
+ for l in sys.stdin: r=json.loads(l); print(f'ep{r[\"epoch\"]:02d} deg={r[\"train_l_deg\"]:.4f} sens={r[\"train_l_sens\"]:.4f} spread={r[\"train_l_spread\"]:.4f} lr={r[\"lr\"]:.2e} total={r[\"train_total\"]:.4f}')
632
+ "
633
+ ```
634
+
635
+ **Expected trends v11:**
636
+
637
+ | Loss | S1 (ep0-9) | S2 (ep20-34) | S3 (ep40+) |
638
+ |------|-----------|-------------|------------|
639
+ | `L_deg` | 0.10 → **<0.05** | giữ <0.05 | giữ <0.05 (γ=0.50) |
640
+ | `L_sens` | tracked only | **<1.5** (β/α=1.0 → GRL cân bằng) | <1.0 |
641
+ | `spread` | **giảm rõ** (uniform mode) | tiếp tục giảm | → ~0 |
642
+ | `L_mat` | flat ~0.3 | giảm (có FVC signal) | flat ~0.01 |
643
+
644
+ ---
645
+
646
+ ## 3. Inference — sinh Q scores từ model đã train
647
+
648
+ ```bash
649
+ cd /home/aiserver/works/fingerprint
650
+ source .venv/bin/activate
651
+
652
+ python sifq/scripts/run_infer.py \
653
+ --checkpoint sifq/checkpoints_full_v11/last.pt \
654
+ --output sifq/eval_results/sifq_scores_v11.jsonl
655
+ ```
656
+
657
+ Output: `sifq/eval_results/sifq_scores_v11.jsonl` — mỗi dòng là 1 ảnh với Q score + 6 concepts.
658
+
659
+ ---
660
+
661
+ ## 4. Evaluation — verify SOTA
662
+
663
+ ### 4a. Nhanh: chỉ Track 2 (sensor invariance) + Track 4 (concept grounding)
664
+
665
+ ```bash
666
+ python sifq/scripts/run_eval.py \
667
+ --sifq-scores sifq/eval_results/sifq_scores_v11.jsonl \
668
+ --checkpoint sifq/checkpoints_full_v11/last.pt \
669
+ --out-dir sifq/eval_results \
670
+ --skip-track1
671
+ ```
672
+
673
+ ### 4b. Đầy đủ: Track 1 (ERC) + Track 2 + Track 4
674
+
675
+ ```bash
676
+ python sifq/scripts/run_eval.py \
677
+ --sifq-scores sifq/eval_results/sifq_scores_v11.jsonl \
678
+ --checkpoint sifq/checkpoints_full_v11/last.pt \
679
+ --out-dir sifq/eval_results \
680
+ --max-pairs 3000
681
+ ```
682
+
683
+ ### 4c. Có NFIQ2 baseline (so sánh trực tiếp với SOTA)
684
+
685
+ ```bash
686
+ # NFIQ2 is not on PyPI — generate proxy scores using image quality heuristics:
687
+ python sifq/scripts/gen_nfiq2_proxy_scores.py \
688
+ --sifq-scores sifq/eval_results/sifq_scores_v11.jsonl \
689
+ --output /tmp/nfiq2_scores.jsonl
690
+ python sifq/scripts/run_eval.py \
691
+ --sifq-scores sifq/eval_results/sifq_scores_v11.jsonl \
692
+ --checkpoint sifq/checkpoints_full_v11/last.pt \
693
+ --out-dir sifq/eval_results \
694
+ --nfiq2-scores /tmp/nfiq2_scores.jsonl
695
+ ```
696
+
697
+ ---
698
+
699
+ ## 5. Xem kết quả
700
+
701
+ ```bash
702
+ # Bảng số
703
+ cat sifq/eval_results/eval_summary.json
704
+
705
+ # Plots (mở file)
706
+ ls sifq/eval_results/*.png
707
+ ```
708
+
709
+ | File | Nội dung |
710
+ |------|----------|
711
+ | `eval_summary.json` | Tất cả metrics (AUC_ERC, KS statistic, Pearson) |
712
+ | `plot_erc.png` | Track 1 — ERC curve, AUC thấp hơn là tốt hơn |
713
+ | `plot_sensor_hist.png` | Track 2 — Q distribution per sensor |
714
+ | `plot_sensor_scatter.png` | Track 2 — scatter Q_s1 vs Q_s2 |
715
+ | `plot_crosstalk.png` | Track 4 — concept grounding heatmap |
716
+
717
+ ---
718
+
719
+ ## 6. Tiêu chí SOTA rank 1
720
+
721
+ | Track | Metric | v5 | v7 nofvc | Target v11 |
722
+ |-------|--------|-----|---------|----------|
723
+ | Track 1 (ERC) | AUC_ERC | 0.8884 | — | < NFIQ2 proxy |
724
+ | Track 2 (Sensor) | mean_KS | 0.326 | 0.326 (collapse) | < 0.10 |
725
+ | Track 2 (Sensor) | Pearson cross-sensor | 0.179 | — | > 0.70 |
726
+ | Track 4 (Concepts) | blur → clarity rho | +0.483 ❌ | — | negative |
727
+ | Track 4 (Concepts) | occlusion → minutiae rho | -0.013 ❌ | — | negative |
728
+
729
+ ---
730
+
731
+ ## Checkpoint paths (hiện tại)
732
+
733
+ | Thành phần | Path |
734
+ |-----------|------|
735
+ | MDGT teacher | `pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt` |
736
+ | NIST SD302-A | `dataset/302a/images/challengers` |
737
+ | NIST SD302-B | `dataset/302b/images/baseline` |
738
+ | NIST SD302-D | `dataset/nist_302d/images/auxiliary` |
739
+ | FVC2002 | `dataset/FVC_Dataset/FVC2002` |
740
+ | FVC2004 | `dataset/FVC_Dataset/FVC2004` |
741
+ | PolyU | `dataset/PolyU` |
742
+ | SIFQ v18 (done, score collapse q_std≈0.01, Pearson=0.007 ❌) | `sifq/checkpoints/v18/last.pt` |
743
+ | SIFQ v17 (done, score collapse 18.1–53.0, q_std=0.60 ❌) | `sifq/checkpoints/v17/last.pt` |
744
+ | SIFQ v16 (done, score collapse 46.9–50.5 ❌) | `sifq/checkpoints/v16/last.pt` |
745
+ | SIFQ v15 (done, score collapse 24–56 ❌) | `sifq/checkpoints_full_v15/last.pt` |
746
+ | SIFQ v14 (eval done, KS=0.263 ✅) | `sifq/checkpoints_full_v14/last.pt` |
747
+ | SIFQ v13 (completed) | `sifq/checkpoints_full_v13/last.pt` |
748
+ | SIFQ v12 (completed) | `sifq/checkpoints_full_v12/last.pt` |
749
+ | SIFQ v11 (completed, score collapse ~58.3) | `sifq/checkpoints_full_v11/last.pt` |
750
+ | SIFQ v10 (stopped, PolyU excluded from L_sens) | `sifq/checkpoints_full_v10/last.pt` |
751
+ | SIFQ v9 (stopped ep63, β/α=0.50 too weak) | `sifq/checkpoints_full_v9/last.pt` |
752
+ | SIFQ v8 (stopped ep22, sens stuck 3-3.5) | `sifq/checkpoints_full_v8/last.pt` |
753
+ | SIFQ v7 nofvc (ref) | `sifq/checkpoints_full_v7_nofvc/last.pt` |
754
+
755
+ ## Lịch sử checkpoint
756
+
757
+ | Version | Epochs | Vấn đề | Trạng thái |
758
+ |---------|--------|--------|----------|
759
+ | `checkpoints_full/` | 21 | beta=0 bug → GRL tắt | Lỗi |
760
+ | `checkpoints_full_v2/` | 50 | spread loss bimodal | Lỗi |
761
+ | `checkpoints_full_v3/` | 30 | Q collapse, deg dead | Lỗi |
762
+ | `checkpoints_full_v5/` | 25 | Chỉ noise degradation | l_deg≈0 |
763
+ | `checkpoints_full_v6/` | 80 | Full deg pipeline | Ref |
764
+ | `checkpoints_full_v7_nofvc/` | 80 | Score collapse (spread=0.010), L_sens explosion ep17-18, γ=0.40 làm L_deg plateau 0.104 | Ref |
765
+ | `checkpoints_full_v8/` | 22 | Uniform spread, β ramp, γ=0.50, cosine LR, FVC — dừng ep22 vì α/γ step change tại ep15 gây sens oscillate 3–3.5 | Stopped |
766
+ | `checkpoints_full_v9/` | 63 | Ramp ALL THREE (α/β/γ) ep10–19 + PolyU — dừng ep63 vì β/α=0.50 trong S2 quá yếu, sens oscillate 2–3 suốt S2/S3 | Stopped |
767
+ | `checkpoints_full_v10/` | early | PolyU excluded từ L_sens — dừng sớm, sai thiết kế | Stopped |
768
+ | `checkpoints_full_v11/` | 80 | Score collapse: 95% ảnh tại ~58.3, wet_press concept sai chiều | Completed |
769
+ | `checkpoints_full_v12/` | 80 | T17+T18+T19: L_deg all datasets, fix wet_press erode, gamma=1.0 | Completed |
770
+ | `checkpoints_full_v13/` | 80 | Revert T17, per-dataset L_spread, T25 noise fix, T26 occlusion fix | Completed |
771
+ | `checkpoints_full_v14/` | 60 | Train from scratch; exclude non-seg slap; KS=0.263; Pearson=0.294 | Completed |
772
+ | `checkpoints_full_v15/` | 60 | T30: SD302 concept-only L_deg, gamma=2.0; score collapse 24–56 ❌ | Completed |
773
+ | `checkpoints/v16/` | 60 | T31: per-identity stats ALL datasets; score collapse 46.9–50.5 ❌; L_mat vs L_pair conflict | Completed |
774
+ | `checkpoints/v17/` | 60 | T32: FVC-only stats; score collapse 18.1–53.0 (q_std=0.60 ❌); GRL suppresses SD302 quality | Completed |
775
+ | `checkpoints/v18/` | 60 | T33: --no-mat-stats + W_SPREAD=2.0 + gamma=0.5 + SD302-A; revert to v14 design; score collapse q_std≈0.01, KS=0.249⚠️(false positive) ❌ | Completed ❌ |
rules/SIFQ_explained.md ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SIFQ — Giải thích toàn bộ Research & Mapping vào Code
2
+
3
+ > Tài liệu này đọc song song với `sifq_pdf.txt` và source code trong `src/`.
4
+ > Mỗi khái niệm trong paper đều có pointer đến file code tương ứng.
5
+
6
+ ---
7
+
8
+ ## 1. Vấn đề SIFQ giải quyết
9
+
10
+ ### NFIQ2 có 3 nhược điểm lớn
11
+
12
+ **Nhược điểm 1 — Matcher cũ làm target:**
13
+ 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.
14
+
15
+ **Nhược điểm 2 — Feature thiên về optical sensor:**
16
+ 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.
17
+
18
+ **Nhược điểm 3 — Sensor bias:**
19
+ 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ự.
20
+
21
+ ### SIFQ giải quyết bằng cách nào?
22
+
23
+ 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**:
24
+
25
+ | Signal | Vai trò | Ràng buộc |
26
+ |--------|---------|-----------|
27
+ | `L_mat` — Matcher-as-teacher | Q phải tương quan với embedding quality của MDGT | Task-relevant |
28
+ | `L_sens` — Cross-sensor invariance | Q phải giống nhau cho cùng ngón tay ở 2 sensor khác nhau | Sensor-invariant |
29
+ | `L_deg` — Controlled degradation | Q phải giảm khi ảnh bị degraded (blur, noise, occlusion...) | Ordinal grounding |
30
+
31
+ 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).
32
+
33
+ **Đ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:
34
+
35
+ | Nếu chỉ có... | Thì model sẽ... |
36
+ |--------------|----------------|
37
+ | Chỉ `L_mat` | Distill MDGT → không sensor-invariant |
38
+ | Chỉ `L_sens` | Cho tất cả ảnh cùng score → L_pair = 0 dễ dàng |
39
+ | Chỉ `L_deg` | Học ranking degradation synthetic, không transfer sang ảnh real |
40
+ | `L_mat + L_sens` | Không có ordinal grounding → score không có ý nghĩa tuyệt đối |
41
+ | `L_sens + L_deg` | Không liên kết với matcher reality |
42
+
43
+ **⚠️ Bài học từ v15–v19 (score collapse):**
44
+ Ngoài việc cần đủ 3 signal, còn cần đảm bảo:
45
+ 1. **`L_mat` cần per-image quality gradient thực sự**: Raw cosine với multi-sensor prototype
46
+ (proto_max_batches=0) → cosine varies with quality, not sensor. Partial prototype
47
+ (proto_max=150) → cosine bị sensor-bias → không phân biệt quality → collapse.
48
+ 2. **`L_deg` phải áp dụng cho SD302 chứ không chỉ FVC**: FVC-only L_deg → model học
49
+ quality function cho FVC nhưng SD302 không có per-image signal → SD302 collapse ở inference.
50
+ L_spread_ds (per-dataset spread, T27) ngăn score anchoring → an toàn để bật L_deg full cho SD302.
51
+ 3. **`L_spread_ds` là batch-level, không đủ**: Batch spread thỏa mãn bằng arbitrary ordering,
52
+ không phải quality. Phải kết hợp với per-image signal từ L_mat + L_deg.
53
+
54
+ ---
55
+
56
+ ## 2. Kiến trúc — 4 Components
57
+
58
+ ```
59
+ Image [B,1,224,224]
60
+
61
+
62
+ ┌────────────┐
63
+ │ Backbone │ TinyViT-5M, grayscale
64
+ │ TinyViT │ forward_spatial() → [B,196,320]
65
+ └────────────┘
66
+
67
+ ├── mean(dim=1) → [B, 320] features ──────────────────────────┐
68
+ │ │
69
+ │ (SpatialConceptHead path: [B,196,320]) ▼
70
+ ▼ (ConceptHead legacy: mean-pool → [B,320]) ┌──────────────────┐
71
+ ┌──────────────────┐ │ SensorDisc │
72
+ │ ConceptHead / │ [B,?]→ … →[B,6] ∈ [0,1] │ GRL(λ) → │
73
+ │ SpatialConcept │ see §2.2 for both variants │ [B,64]→[B,Ns] │
74
+ └──────────────────┘ └──────────────────┘
75
+ │ concepts [B, 6] │ sensor_logits
76
+ ▼ ▼
77
+ ┌──────────────────┐ adversarial sensor loss
78
+ │ ScoreAggregator │ [B,6]→[B,32]→[B,1]→Sigmoid→×100
79
+ └──────────────────┘
80
+ │ Q [B,1] ∈ [0, 100]
81
+
82
+ outputs = { "score": Q, "concepts": C, "sensor_logits": S, "features": F }
83
+ ```
84
+
85
+ ---
86
+
87
+ ### 2.1 Backbone — `src/models/backbone.py`
88
+
89
+ | | |
90
+ |---|---|
91
+ | **Model** | `timm: tiny_vit_5m_224.dist_in22k` |
92
+ | **Input** | `[B, 1, 224, 224]` — grayscale |
93
+ | **Output** | `[B, 320]` — global average of spatial tokens |
94
+
95
+ `forward_spatial()` extracts 14×14 token features → mean pool → `[B, 320]`.
96
+
97
+ - TinyViT-5M (not 2M): 2M insufficient capacity for 3 simultaneous losses
98
+ - Not shared with MDGT: avoids circular dependency; on-sensor deployment target (<50ms ARM Cortex-A72)
99
+
100
+ ---
101
+
102
+ ### 2.2 Concept Head — `src/models/concept_head.py`
103
+
104
+ Two implementations exist. The active version depends on the training flag:
105
+
106
+ **`ConceptHead` (legacy — v16–v26, default `--spatial-concept-head` not set):**
107
+ ```
108
+ Input: [B, 320] — globally-pooled backbone output
109
+ Linear(320→256) → LayerNorm → GELU → Linear(256→6) → Sigmoid
110
+ Output: [B, 6], each concept ∈ [0, 1] (high = better quality)
111
+ ```
112
+ Loses all spatial structure before concept prediction.
113
+
114
+ **`SpatialConceptHead` (v27+, enabled via `--spatial-concept-head`):**
115
+ ```
116
+ Input: [B, 196, 320] — backbone.forward_spatial() (14×14 token map)
117
+ Shared trunk : Linear(320→128) → LayerNorm → GELU → [B, 196, 128]
118
+ Per-concept : 6 × Linear(128→1) → mean(dim=1) → [B, 6]
119
+ Activation : Sigmoid → [B, 6] ∈ (0, 1)
120
+ ```
121
+ Each concept projection learns which spatial regions matter (ridge breaks for
122
+ `continuity`, orientation edges for `orientation_coherence`, bifurcation patches
123
+ for `minutiae_reliability`). Separate weights per concept reduce entanglement.
124
+
125
+ `SIFQ.forward()` auto-dispatches via `concept_head.uses_spatial` attribute —
126
+ backward-compatible with all existing checkpoints.
127
+
128
+ **6 concepts (all decrease with degradation — T25):**
129
+
130
+ | Idx | Name | Meaning | Supervised by |
131
+ |-----|------|---------|---------------|
132
+ | 0 | `orientation_coherence` | Ridge flow consistency | dry_skin, wet_press (T39) |
133
+ | 1 | `ridge_valley_clarity` | Sharp ridge-valley boundaries | blur, jpeg, wet_press, **noise (T42)** |
134
+ | 2 | `continuity` | Unbroken ridge lines | blur, jpeg |
135
+ | 3 | `noise_level` | Low noise (↑ = cleaner — T25) | noise |
136
+ | 4 | `contrast_uniformity` | Even foreground contrast | dry_skin |
137
+ | 5 | `minutiae_reliability` | Reliable minutiae extraction | occlusion, wet_press |
138
+
139
+ **T42 changes (v32):**
140
+ - `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.
141
+ - `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.
142
+
143
+ Concepts are not required to be independent — blur reducing both clarity and continuity is physically correct. `L_ortho` only prevents extreme redundancy.
144
+
145
+ ---
146
+
147
+ ### 2.3 Score Aggregator — `src/models/aggregator.py`
148
+
149
+ ```
150
+ Linear(6→32) → GELU → Linear(32→1) → Sigmoid → ×100
151
+ Output: [B, 1] ∈ [0, 100] (NFIQ2-compatible scale)
152
+ ```
153
+
154
+ `Q(x) = Aggregator(concepts(backbone(x)))`
155
+
156
+ > **Important:** `outputs["score"]` is already in [0, 100]. Do not multiply by 100 again. Old bug did this → loss thresholds were off by 10×.
157
+
158
+ ---
159
+
160
+ ### 2.4 Sensor Discriminator — `src/models/sensor_discriminator.py`
161
+
162
+ ```
163
+ GRL(λ) → Linear(320→64) → ReLU → Linear(64→N_sensors)
164
+ ```
165
+
166
+ **Gradient Reversal Layer** (`src/models/grad_reverse.py`):
167
+ - Forward: `f(x) = x`
168
+ - Backward: `∂L/∂x → −λ · ∂L/∂x`
169
+
170
+ The discriminator is trained to classify sensor identity. GRL forces the backbone to produce features the discriminator *cannot* distinguish → backbone sheds sensor signature.
171
+
172
+ > **TODO:** Paper specifies discriminator should receive intermediate concept-branch features, not raw backbone features. Currently uses backbone output. Not yet implemented.
173
+
174
+ ---
175
+
176
+ ## 3. Ba Loss Functions
177
+
178
+ ### 3.1 `L_mat` — Matcher-as-Teacher
179
+
180
+ **File:** `src/losses/matcher_teacher.py`
181
+ **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)
182
+
183
+ **Công thức:**
184
+
185
+ $$q_{mat}(x) = \frac{\cos(\text{MDGT}(x),\ c_y) - \mu_y}{\sigma_y}$$
186
+
187
+ $$L_{mat} = \text{Huber}(Q_{normalized}(x),\ q_{mat}(x))$$
188
+
189
+ Trong đó:
190
+ - $c_y$ = prototype của identity $y$ (trung bình L2-normalized embeddings)
191
+ - $\mu_y, \sigma_y$ = mean/std cosine similarity trong class $y$
192
+ - $Q_{normalized} = (Q/100 - 0.5) \times 2$ — đưa [0,100] về xấp xỉ [-1, 1]
193
+
194
+ **Code mapping:**
195
+
196
+ ```python
197
+ # Compute prototype: trung bình embeddings per identity
198
+ proto = F.normalize(stack(emb_list).mean(0), dim=-1)
199
+
200
+ # v16 (T31): compute per-identity cosine stats (second pass, frozen teacher)
201
+ # stats[identity] = (mean_cos, std_cos) — min_sigma = 0.02
202
+ stats = compute_identity_cos_stats(loss_mat, prototypes, proto_loader, device)
203
+
204
+ # q_mat: cosine similarity normalize per-identity, clamp bằng tanh
205
+ cos = dot(emb[i], proto[identity_id])
206
+ z = (cos − mu_i) / sigma_i
207
+ q_mat[i] = tanh(z) # ∈ (−1, 1), zero-centred
208
+
209
+ # Loss
210
+ pred_normalized = (score / 100.0 - 0.5) * 2.0
211
+ return HuberLoss(pred_normalized, q_mat)
212
+ ```
213
+
214
+ **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.
215
+
216
+ **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.
217
+
218
+ **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).
219
+
220
+ ---
221
+
222
+ ### 3.2 `L_sens` — Cross-Sensor Invariance
223
+
224
+ **File:** `src/losses/sensor_invariance.py`
225
+
226
+ **Công thức:**
227
+
228
+ $$L_{pair} = \max(0,\ |Q(x_{s1}) - Q(x_{s2})| - \delta)$$
229
+
230
+ $$L_{adv} = -\log D(\text{sensor} \mid f(x))$$
231
+
232
+ $$L_{sens} = L_{pair} + \lambda_{adv} \cdot \min(L_{adv},\ \ln N_{sensors})$$
233
+
234
+ Với $\delta = 0.05$, $\lambda_{adv} = 0.3$. Clamp $\min(L_{adv}, \ln N)$ ngăn GRL anti-correlation (T16).
235
+
236
+ **Code mapping (v11 — GRL anti-correlation fix):**
237
+
238
+ ```python
239
+ # Pairs: cùng identity_id + finger_id, khác sensor_id (built trong batch)
240
+ l_pair = relu((score_s1 - score_s2).abs() - 0.05).mean()
241
+
242
+ # Adversarial: backbone phải fool sensor discriminator
243
+ l_adv = cross_entropy(sensor_logits, sensor_labels)
244
+
245
+ # GRL anti-correlation fix (T16): clamp l_adv tại random-guess baseline.
246
+ # Nếu CE > log(num_sensors): backbone đã đủ confuse discriminator, dừng
247
+ # gradient reversal — tránh việc backbone học anti-encode sensor identity.
248
+ rand_ce = log(sensor_logits.size(1)) # log(32) ≈ 3.47
249
+ l_adv_clamped = l_adv.clamp(max=rand_ce)
250
+
251
+ # Returns (total, l_pair_detached, l_adv_detached) for diagnostics
252
+ return l_pair + 0.3 * l_adv_clamped, l_pair.detach(), l_adv.detach()
253
+ ```
254
+
255
+ **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.
256
+
257
+ **Pair building — `train_sifq.py::build_pair_indices()`:**
258
+ Group batch theo `(identity_id, finger_id)` → tất cả cặp khác sensor_id trong cùng group.
259
+
260
+ **Quan hệ giữa `L_pair` và `L_adv` — hai cơ chế bổ trợ:**
261
+
262
+ | | `L_pair` | `L_adv` (GRL) |
263
+ |--|---------|---------------|
264
+ | Ép ở tầng nào | **Output** — Q score phải bằng nhau | **Feature space** — backbone không được encode sensor info |
265
+ | Cách hoạt động | Hinge loss trực tiếp trên Q | Gradient reversal qua discriminator |
266
+ | 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 |
267
+
268
+ **Dataset novelty:** SIFQ là method đầu tiên đưa explicit invariance constraint vào quality learning. NFIQ2 không có mechanism này.
269
+
270
+ ---
271
+
272
+ ### 3.3 `L_deg` — Controlled Degradation Ranking
273
+
274
+ **File:** `src/losses/degradation_ranking.py`
275
+ **Pipeline:** `src/data/degradation.py`
276
+
277
+ **Công thức:**
278
+
279
+ $$L_{rank} = \max(0,\ Q(x_{high}) - Q(x_{low}) + m) + \max(0,\ Q(x_{low}) - Q(x_{clean}) + m)$$
280
+
281
+ $$L_{concept\_deg} = \sum_{(deg, c_{target})} \text{Huber}(c_{target}(x_{low}),\ c_{target}(x_{high}) + 0.1)$$
282
+
283
+ $$L_{deg} = L_{rank} + \gamma \cdot L_{concept\_deg}$$
284
+
285
+ Với $m=0.1$ (ranking margin), $\gamma=0.5$.
286
+
287
+ **Degradation concept map (index) — T42 (v32) — current:**
288
+
289
+ ```python
290
+ DEGRADATION_CONCEPT_MAP = {
291
+ "blur": [1, 2], # clarity↓, continuity↓
292
+ "noise": [1, 3], # clarity↓ (T42 co-target), noise_level↓
293
+ "jpeg": [2, 1], # continuity↓, clarity↓
294
+ "occlusion": [5], # minutiae_reliability↓ only ← T38: reverted from [5,2] to paper
295
+ "dry_skin": [4, 0], # contrast_uniformity↓, orientation_coherence↓ ← T42: removed continuity
296
+ "wet_press": [1, 5, 0], # clarity↓, minutiae_reliability↓, orientation_coherence↓ (T39)
297
+ }
298
+ ```
299
+
300
+ **T42 physical reasoning (v32):**
301
+
302
+ | Change | Before | After | Physical reason |
303
+ |--------|--------|-------|-----------------|
304
+ | `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). |
305
+ | `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. |
306
+
307
+ **T38 fix — wet_press `[1, 4]` → `[1, 5]` (reverted to paper design):**
308
+
309
+ 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.
310
+
311
+ 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.
312
+
313
+ **T38 fix — occlusion `[5, 2]` → `[5]` (reverted to paper design) + coverage 55% → 40%:**
314
+
315
+ 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.
316
+
317
+ **Note**: Training occlusion still uses random positions (generalization). Only eval is seeded.
318
+
319
+ **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).
320
+ - **T30a**: `concept_deg_gamma 0.5 → 2.0` — L_concept 4× mạnh hơn so với L_rank
321
+ - **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.
322
+ - **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)
323
+
324
+ **DegradationPipeline — 6 loại, 4 levels (0=clean, 1–3 tăng dần):**
325
+
326
+ | Type | Kỹ thuật | Severity range |
327
+ |------|---------|----------------|
328
+ | `blur` | GaussianBlur kernel $k = 2\lfloor 0.5 + level \times 0.83 \rfloor + 1$ | σ tăng theo level |
329
+ | `noise` | Additive Gaussian, $\sigma = 5 + level \times 8.3$ | 5→30 |
330
+ | `jpeg` | JPEG compression quality = $90 - level \times 25$ | 90→15 |
331
+ | `occlusion` | White block $= 13.3\% \times level$ coverage | 13%→40% |
332
+ | `dry_skin` | `DrySkinSimulator`: contrast reduce + crack lines | severity 1→3 |
333
+ | `wet_press` | `MorphologicalDilator`: kernel scales 5×5/7×7/9×9, sigma 1.8/2.6/3.4 | levels 1→3 |
334
+
335
+ **Code trong training loop (v6 fix):**
336
+
337
+ ```python
338
+ # Random sample 1 trong 6 types mỗi deg step
339
+ deg_type = random.choice(_DEG_TYPES)
340
+ level_lo = random.randint(1, 2)
341
+ level_hi = 3
342
+
343
+ # Tensor [B,1,H,W] float[0,1] → numpy [B,H,W] uint8
344
+ imgs_np = (images[:,0].cpu().numpy() * 255).astype(np.uint8)
345
+
346
+ # Apply degradation per image
347
+ imgs_low = stack([deg_pipeline.apply(img, deg_type, level_lo) for img in imgs_np])
348
+ imgs_high = stack([deg_pipeline.apply(img, deg_type, level_hi) for img in imgs_np])
349
+
350
+ # Forward pass qua model
351
+ out_low = model(imgs_low_tensor)
352
+ out_high = model(imgs_high_tensor)
353
+
354
+ l_deg = loss_deg(score_clean, out_low["score"], out_high["score"],
355
+ out_low["concepts"], out_high["concepts"], deg_type)
356
+ ```
357
+
358
+ **Tất cả concepts GIẢM khi degradation tăng (v13 — T25 fix):**
359
+
360
+ ```python
361
+ # T25: Bỏ if c_idx == 3 special case.
362
+ # Tất cả concepts: high = better quality, low = worse quality.
363
+ # noise_level mới: high = ít nhiễu = tốt (ngược v12)
364
+ for c_idx in DEGRADATION_CONCEPT_MAP[deg_type]:
365
+ l_concept += huber(concepts_low[:, c_idx], concepts_high[:, c_idx] + 0.1)
366
+ # concepts_low[c] > concepts_high[c] + 0.1
367
+ # → more degraded image has lower concept score
368
+ ```
369
+
370
+ **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).
371
+
372
+ ---
373
+
374
+ ### 3.4 `L_ortho` — Concept Decorrelation
375
+
376
+ **File:** `src/losses/orthogonality.py`
377
+
378
+ $$L_{ortho} = \| \text{off\_diag}(\text{corrcoef}(C)) \|_F^2$$
379
+
380
+ ```python
381
+ # Standardize per concept (zero-mean, unit-std across batch)
382
+ x = concepts - concepts.mean(dim=0, keepdim=True)
383
+ x = x / (x.std(dim=0, keepdim=True) + 1e-6)
384
+ corr = (x.T @ x) / max(1, x.shape[0] - 1) # [6, 6] Pearson corr
385
+ off_diag = corr - eye(6)
386
+ return (off_diag ** 2).sum() # Frobenius² of off-diagonal
387
+ ```
388
+
389
+ Regularize để concepts không hoàn toàn redundant. Không có weight — luôn cộng thẳng vào total loss.
390
+
391
+ ---
392
+
393
+ ### 3.5 Spread Loss (Uniformity) — thêm vào trong training loop
394
+
395
+ **Không có file riêng** — implement trực tiếp trong `scripts/train_sifq.py`.
396
+
397
+ ```python
398
+ # uniform mode (v8 default) — force sorted Q-scores → linspace(10, 90)
399
+ q_sorted, _ = q_batch.sort()
400
+ target_unif = torch.linspace(10.0, 90.0, n_q, device=device)
401
+ l_spread = F.mse_loss(q_sorted / 100.0, target_unif / 100.0)
402
+ # Gradient ép trực tiếp phân bố score: ảnh tốt nhất → 90, xấu nhất → 10
403
+ ```
404
+
405
+ 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`.
406
+
407
+ **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).
408
+
409
+ **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.
410
+
411
+ **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.
412
+
413
+ ---
414
+
415
+ ### 3.6 Total Loss
416
+
417
+ $$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})$$
418
+
419
+ Trong đó:
420
+ - $L_{spread}$: MSE toàn batch (sorted Q → linspace(10,90))
421
+ - $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)
422
+ - $w_{spread}$ = 3.0 (v21) — áp cho **cả hai** thành phần spread
423
+
424
+ ---
425
+
426
+ ## 4. Training Stage Scheduler
427
+
428
+ **File:** `src/training/stage_scheduler.py`
429
+
430
+ | Stage | Epochs | α (mat) | β (sens) | γ (deg) | β/α | Mục đích |
431
+ |-------|--------|---------|----------|---------|-----|----------|
432
+ | S1 | 0–9 | 0.10 | **0.00** | 1.00 | 0 | Bootstrap quality ordering từ degradation |
433
+ | 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 |
434
+ | S2 | 20–34 | 0.30 | 0.30 | 0.60 | **1.0** | Balanced: GRL pressure = mat pressure |
435
+ | S2→S3 ramp | 35–39 | **0.30→0.29** | **0.30→0.34** | **0.60→0.52** | >1.0 | β vượt α smooth |
436
+ | S3 + S4 | 40+ | 0.25 | 0.35 | **0.50** | **1.4** | β > α, γ floor = 0.50 |
437
+
438
+ > **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`.
439
+
440
+ **GRL λ warm-up (DANN schedule):**
441
+
442
+ $$\lambda(p) = \min\!\left(0.6,\ \frac{2}{1+e^{-10p}}-1\right), \quad p = \frac{\text{epoch}}{\text{total\_epochs}}$$
443
+
444
+ - ep0: λ=0.000
445
+ - ep10: λ=0.555
446
+ - ep12+: λ=0.600 (cạn max)
447
+
448
+ **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).
449
+
450
+ **Vì sao β/α phải = 1.0 ngay từ S2 (v11 vs v9):**
451
+ 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.
452
+ **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).
453
+
454
+ **Vì sao β entry ramp quan trọng (v8 vs v7):**
455
+ 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.
456
+
457
+ **Vì sao γ floor = 0.50 (v8/v9) thay vì 0.40 (v7):**
458
+ 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.
459
+
460
+ ---
461
+
462
+ ## 5. Dataset Pipeline
463
+
464
+ **Files:** `src/data/nist302_loader.py`, `src/data/fvc_loader.py`
465
+
466
+ ```
467
+ dataset/
468
+ ├── 302a/images/challengers/ → sensors: A, B, C, D, E, F, G, H (8 sensors)
469
+ │ └── A/roll/png/ filename: {subject}_{sensor}_{captype}_{finger}.png (4 tokens)
470
+ ├── 302b/images/baseline/ → sensors: R_500, S_500, U_500, V_500 (4 sensors)
471
+ │ └── U/500/roll/png/ filename: {subject}_{sensor}_{dpi}_{captype}_{finger}.png (5 tokens)
472
+ ├── nist_302d/images/auxiliary/ → sensors: flat_K, flat_L, flat_M, flat_P (4 sensors)
473
+ └── FVC_Dataset/
474
+ ├── FVC2002/Dbs/Db1_a|Db2_a... filename: {subject}_{impression}.tif
475
+ └── FVC2004/Dbs/DB1_A|DB2_A...
476
+ ```
477
+
478
+ **Đầy đủ sau khi fix: 37,607 ảnh, 22 sensors**
479
+
480
+ | Dataset | Ảnh | Sensors | Role | Signal |
481
+ |---------|------|---------|------|--------|
482
+ | SD302-A (302a) | 13,630 | A–H (8) | Cross-sensor invariance | L_sens, L_mat |
483
+ | SD302-B (302b) | 11,796 | R,S,U,V (4) | Cross-sensor invariance | L_sens, L_mat |
484
+ | SD302-D (302d) | 5,141 | K,L,M,P (4) | Cross-sensor invariance | L_sens, L_mat |
485
+ | FVC2002 | 3,520 | 4 DBs | Matcher-teacher quality anchor | L_mat, L_deg |
486
+ | FVC2004 | 3,520 | 4 DBs | Matcher-teacher quality anchor | L_mat, L_deg |
487
+ | PolyU (contact) | 2,976 | 1 (polyu_contact) | Cross-modality hardest invariance | **L_sens ONLY** |
488
+ | PolyU (contactless) | 2,976 | 1 (polyu_contactless) | Cross-modality hardest invariance | **L_sens ONLY** |
489
+
490
+
491
+ > **† 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`.
492
+
493
+ **Tổng v11: 43,559 ảnh, 24 sensors, 2,612 eligible cross-sensor anchor groups**
494
+
495
+ **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.
496
+
497
+ **PolyU Cross-Fingerprint Database (v9+):**
498
+ 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`.
499
+
500
+ **Tại sao SD302 không góp vào L_deg:**
501
+ 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.
502
+
503
+ **Tại sao FVC cần thiết cho L_mat:**
504
+ 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ự.
505
+
506
+ **Metadata parsing:**
507
+
508
+ | Filename format | Tokens | identity_id | finger_id | sensor_id |
509
+ |----------------|--------|-------------|-----------|----------|
510
+ | SD302-A: `00002303_A_roll_05.png` | 4 | `00002303` (stem[0]) | `F05` (stem[-1]) | path-based `A_roll_png` |
511
+ | SD302-B/D: `00002401_U_500_roll_07.png` | 5 | `00002401` | `F07` | `U_500_roll` |
512
+ | FVC: `042_3.tif` | 2 | `2002_db1_0042` | `f01` | `fvc2002_db1` |
513
+
514
+ **Audit kết quả (kiểm tra thực tế):**
515
+
516
+ - **Finger ID nhất quán across sensors ✅**: 2,000 (subject, finger) pairs xuất hiện ở ≥2 sensors trong cả 302a và 302b
517
+ - Ví dụ: subject `00002303`, finger `05` → xuất hiện ở cả 8 sensors A–H → cặp L_sens cực tốt
518
+ - 200 subjects xuất hiện trong cả 302b và 302d → cross-subset L_sens pairs
519
+ - FVC: mỗi subject có 1 ngón tay duy nhất (finger_id = `f01`) → không có cross-sensor pairs
520
+
521
+ **Bug đã fix: 302a parser:**
522
+ 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`...).
523
+
524
+ **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.
525
+
526
+ ---
527
+
528
+ ## 6. Evaluation 5 Tracks
529
+
530
+ ### Track 1 — Error Rejection Curve (Primary)
531
+
532
+ **File:** `src/evaluation/erc.py`
533
+
534
+ 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.
535
+
536
+ **AUC_ERC: thấp hơn = tốt hơn.**
537
+
538
+ Kết quả v5: SIFQ=0.8884 vs Random=0.8937 → hơn Random 0.5% — quá yếu.
539
+ 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.
540
+
541
+ ---
542
+
543
+ ### Track 2 — Sensor Invariance (Core novelty)
544
+
545
+ **File:** `src/evaluation/sensor_invariance.py`
546
+
547
+ **KS statistic** (Kolmogorov-Smirnov) giữa Q distributions của 2 sensors: `KS = 0` → giống hoàn toàn.
548
+
549
+ **Pearson correlation** giữa Q(x_s1) và Q(x_s2) cho paired samples: cao hơn = nhất quán hơn.
550
+
551
+ | Metric | v11 | v12 | v13 | v14 | v15 | v16 | v17 | v18 actual | v20 actual | **v21 target** |
552
+ |--------|-----|-----|-----|-----|-----|-----|-----|------------|------------|--------|
553
+ | mean_ks | 0.557 | 0.510 | 0.634 ❌ | **0.263 ✅** | 0.276 ❌ | 0.527 ❌ | 0.616 ❌ | **0.249 ⚠️** | **0.4936 ❌** | **≤0.27** |
554
+ | Pearson | — | -0.003 | +0.224 | **+0.294 ✅** | — | 0.046 ❌ | -0.002 ❌ | **0.007 ❌** | **0.0048 ❌** | **≥0.20** |
555
+ | q_std (inference) | — | — | — | ~15 | — | 0.33 ❌ | 0.60 ❌ | **0.01 ❌❌** | **0.007 ❌❌** | **>12** |
556
+ | n\_sensor\_pairs | 91 | 91 | 91 | 55 | 55 | 55 | **171** (302a added) | **171** | **171** | **≥100** (302a) |
557
+
558
+ > **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.
559
+ **⚠️ 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`.
560
+ > **⚠️ 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.
561
+
562
+ **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.
563
+
564
+ **v14 fix**: Loại non-segmented slap khỏi training và eval (`--exclude-sensor R_1000_slap,R_500_slap,S_500_slap`).
565
+
566
+ **v14 training actuals (60 epochs, from scratch):**
567
+ - `q_mean` = 52.6 (ep59) — centered tốt hơn v13 (~33 train-time)
568
+ - `q_std` = 15.5 (ep59) — plateau sau khi GRL equilibrium (peak S1 = 22.6 → drop về 14 khi β kick-in ep11)
569
+ - `l_pair` = 0.006 (ep59) — sensor invariance xuất sắc, gần bằng 0
570
+ - `l_mat` = 0.270 — converged, giảm từ 0.378 (ep0)
571
+ - 3-phase dynamics: S1 (spread explosion ep0-10) → Transition (GRL compression ep11-15) → Equilibrium (stable ep16-59)
572
+
573
+ **v14 eval results:** mean_KS = **0.263** ✅ (giảm từ 0.634), Pearson = **+0.294** ✅ (tăng từ 0.224).
574
+
575
+ **Đâ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.
576
+
577
+ ---
578
+
579
+ ### Track 4 — Concept Grounding (Interpretability claim)
580
+
581
+ **File:** `src/evaluation/concept_grounding.py`
582
+
583
+
584
+ Sweep degradation level 0→3, tính Spearman ρ giữa level và concept score.
585
+
586
+ **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).
587
+
588
+ **Kết quả v13 (Spearman ρ):**
589
+
590
+ | degradation | orient. | clarity | continuity | noise_lvl | contrast | minutiae |
591
+ |-------------|---------|---------|-----------|-----------|----------|----------|
592
+ | **blur** | +0.19 | **-0.49** ✅ | -0.10 | +0.10 | +0.22 | +0.11 |
593
+ | **noise** | +0.05 | +0.46 | -0.12 | **-0.53** ✅ | -0.06 | -0.20 |
594
+ | **jpeg** | -0.11 | +0.03 | +0.03 | -0.08 | -0.04 | -0.02 |
595
+ | **occlusion** | +0.10 | -0.13 | -0.15 | +0.10 | -0.19 | **-0.09** ⚠️ |
596
+ | **dry_skin** | **-0.35** ✅ | +0.06 | +0.01 | -0.13 | **-0.38** ✅ | +0.01 |
597
+ | **wet_press** | -0.06 | **-0.48** ✅ | +0.24 | -0.16 | +0.44 | +0.33 |
598
+
599
+ **Kết quả v14 (Spearman ρ):**
600
+
601
+ | degradation | orient. | clarity | continuity | noise_lvl | contrast | minutiae |
602
+ |-------------|---------|---------|-----------|-----------|----------|----------|
603
+ | **blur** | +0.11 | **-0.19** ✅ | -0.003 | +0.08 | +0.22 | **+0.50** ❌ |
604
+ | **noise** | +0.001 | -0.16 | +0.03 | **-0.02** ⚠️ | +0.15 | +0.05 |
605
+ | **jpeg** | -0.18 | -0.07 | -0.10 | +0.08 | -0.11 | -0.09 |
606
+ | **occlusion** | +0.06 | +0.04 | **-0.12** ✅ | +0.18 | +0.07 | **+0.18** ❌ |
607
+ | **dry_skin** | +0.19 | -0.28 | **-0.56** ✅⬆ | **-0.56** ✅⬆ | **-0.62** ✅⬆ | +0.36 |
608
+ | **wet_press** | **-0.28** ✅ | -0.13 | +0.37 | -0.16 | +0.20 | **+0.57** ❌ |
609
+
610
+ **Nhận xét v14 so với v13:**
611
+ - ✅ **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
612
+ - ✅ **Track 2 KS**: 0.634 → 0.263 (cải thiện lớn nhờ loại slap sensors)
613
+ - ✅ **Pearson**: 0.224 → 0.294
614
+ - ⚠️ **noise→noise_level**: -0.533 (v13) → -0.019 (v14) — regression, gần bằng 0
615
+ - ⚠️ **blur→clarity**: -0.490 (v13) → -0.187 (v14) — yếu hơn đáng kể
616
+ - ❌ **wet_press→minutiae**: +0.326 (v13) → +0.565 (v14) — sai chiều, tệ hơn
617
+ - ❌ **occlusion→minutiae**: -0.093 (v13) → +0.183 (v14) — flip sang sai chiều
618
+
619
+ **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).
620
+
621
+ **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.
622
+
623
+ ---
624
+
625
+ **Kết quả v18 (Spearman ρ — CONCEPT COLLAPSE + INVERSION):**
626
+
627
+ | degradation | orient. | clarity | continuity | noise_lvl | contrast | minutiae |
628
+ |-------------|---------|---------|-----------|-----------|----------|----------|
629
+ | **blur** | -0.572 ❌ | **+0.611** ❌❌ | +0.575 ❌❌ | -0.583 ❌ | +0.552 ❌ | -0.487 ❌ |
630
+ | **noise** | -0.410 ❌ | +0.288 ❌ | +0.368 ❌ | **-0.296** ✓ | +0.298 ❌ | +0.630 ❌❌ |
631
+ | **jpeg** | -0.097 | **+0.222** ❌ | +0.194 ❌ | -0.268 | +0.140 | -0.279 |
632
+ | **occlusion** | -0.162 | -0.151 ✓ | +0.042 ❌ | -0.150 | +0.063 | **-0.133** ✓ |
633
+ | **dry_skin** | +0.183 | -0.066 ✓ | +0.091 ❌ | +0.086 | **-0.247** ✓ | +0.230 ❌ |
634
+ | **wet_press** | -0.118 | **+0.217** ❌ | +0.196 ❌ | -0.320 | +0.140 | **-0.245** ✓ |
635
+
636
+ **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.
637
+
638
+ ---
639
+
640
+ ### Track 3 — Cross-Matcher Transfer (Reviewer defense)
641
+
642
+ 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).
643
+
644
+ Nếu AUC_ERC vẫn thấp → Q generalizable, không phải chỉ distill MDGT.
645
+ Hiện tại: chưa có VeriFinger license → bỏ qua hoặc dùng matcher khác.
646
+
647
+ ---
648
+
649
+ ### Track 5 — Human Correlation (Optional)
650
+
651
+ 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.
652
+
653
+ ---
654
+
655
+ ## 7. File Map — Research Concept → Code
656
+
657
+ | Khái niệm trong paper | File code |
658
+ |----------------------|-----------|
659
+ | Backbone (TinyViT-5M) | `src/models/backbone.py` |
660
+ | Concept Head (6 concepts, legacy v16–v26) | `src/models/concept_head.py::ConceptHead` |
661
+ | Concept Head (spatial, v27+) | `src/models/concept_head.py::SpatialConceptHead` |
662
+ | Score Aggregator Q(x) | `src/models/aggregator.py` |
663
+ | Gradient Reversal Layer | `src/models/grad_reverse.py` |
664
+ | Sensor Discriminator D | `src/models/sensor_discriminator.py` |
665
+ | SIFQ full model wrapper | `src/models/sifq.py` |
666
+ | $L_{mat}$ (Huber + prototype) | `src/losses/matcher_teacher.py` |
667
+ | $L_{sens}$ (pair + adversarial) | `src/losses/sensor_invariance.py` |
668
+ | $L_{deg}$ (ranking + concept) | `src/losses/degradation_ranking.py` |
669
+ | $L_{ortho}$ (decorrelation) | `src/losses/orthogonality.py` |
670
+ | MDGT teacher loader | `src/training/mdgt_teacher.py` |
671
+ | Stage scheduler α/β/γ | `src/training/stage_scheduler.py` |
672
+ | DegradationPipeline (6 types) | `src/data/degradation.py` |
673
+ | DrySkinSimulator | `src/data/degradation.py::DrySkinSimulator` |
674
+ | MorphologicalDilator | `src/data/degradation.py::MorphologicalDilator` |
675
+ | Dataset loader SD302 A/B/D | `src/data/nist302_loader.py` |
676
+ | Dataset loader FVC 2002/2004 | `src/data/fvc_loader.py` |
677
+ | Dataset loader PolyU (contactless↔contact) | `src/data/polyu_loader.py` |
678
+ | Cross-sensor pair builder | `scripts/train_sifq.py::build_pair_indices()` |
679
+ | Spread/Uniformity loss | `scripts/train_sifq.py` (inline) |
680
+ | Prototype computation | `scripts/train_sifq.py::compute_teacher_prototypes()` |
681
+ | Training main loop | `scripts/train_sifq.py::main()` |
682
+ | Track 1 ERC evaluation | `src/evaluation/erc.py` |
683
+ | Track 2 Sensor invariance | `src/evaluation/sensor_invariance.py` |
684
+ | Track 4 Concept grounding | `src/evaluation/concept_grounding.py` |
685
+ | Run training v21 (T36: full-proto + FVC-only L_deg, 60ep) | `scripts/run_train_v21.sh` |
686
+ | Run training v14 (segmented only, 60ep from scratch) | `scripts/run_train_v14.sh` |
687
+ | Run training v13 (80ep, resume v12) | `scripts/run_train_v13.sh` |
688
+ | Run eval v13 (exclude non-seg slap) | `scripts/run_eval_v13.sh` → `eval_results/v13_seg/` |
689
+ | Run inference | `scripts/run_infer.py` |
690
+ | Run evaluation | `scripts/run_eval.py` |
691
+ | Visualize score milestones | `visualize_score_milestones.py --exclude-sensor ...` |
692
+ | **MDGTv2 local pipeline** (DINOv2+TRAM+GNN) | `src/models/mdgt/pipeline.py` |
693
+ | MDGT teacher wrapper (loads local pipeline, frozen) | `src/training/mdgt_teacher.py` |
694
+ | Pre-cache teacher embeddings (one-time, startup) | `scripts/train_sifq.py::precompute_teacher_embeddings()` |
695
+ | Image preloading (RAM cache, uint8) | `scripts/train_sifq.py::RecordDataset._preload_images()` |
696
+ | GPU-native degradation (blur/noise/occlusion) | `scripts/train_sifq.py::_degrade_gpu()` |
697
+ | CPU degradation with preloaded numpy (jpeg/dry_skin/wet_press) | `scripts/train_sifq.py::_degrade_from_np()` |
698
+ | Vectorized prototype cosine (1 GPU sync vs ~100) | `src/losses/matcher_teacher.py::_compute_q_mat()` |
699
+
700
+ ---
701
+
702
+ ## 8. Luồng dữ liệu trong 1 training step (v21 — current)
703
+
704
+ **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)
705
+
706
+ **Startup (1 lần trước khi train):**
707
+ ```
708
+ 1. RecordDataset._preload_images() → np.empty([N, 224, 224], uint8) ~2 GB RAM
709
+ → __getitem__ trở thành: arr.copy().float().unsqueeze(0) / 255.0 (không đọc disk)
710
+
711
+ 2. precompute_teacher_embeddings(teacher, train_ds) → Tensor[N, 256] CPU (float32)
712
+ → Frozen DINOv2+TRAM+GNN chạy 1 lần duy nhất trên toàn bộ N records
713
+ → Không bao giờ chạy lại trong training loop
714
+
715
+ 3. compute_teacher_prototypes() → dict{identity_id → Tensor[256]} CPU
716
+ → MDGT prototype per identity (L2-normalized mean embeddings) — 1 lần
717
+ ```
718
+
719
+ **Training step:**
720
+ ```
721
+ Batch (B=128, CrossSensorBatchSampler: 16 anchor pairs + fill)
722
+
723
+ ├─ images_np = batch["images_np"] ← [B, 224, 224] uint8, đã trong RAM (không từ GPU)
724
+ ├─ images = batch["images"].to(device) ← [B, 1, 224, 224] float32 trên GPU
725
+
726
+ ├─ Forward SIFQ: model(images) → {score [B,1], concepts [B,6], sensor_logits [B,N_sensors], features [B,320]}
727
+
728
+ ├─ L_mat: (chỉ SD302+FVC, bỏ PolyU)
729
+ │ ├─ emb_cache = emb_cache[record_idxs[_non_polyu_idx]] ← CPU lookup, O(1)
730
+ │ ├─ _compute_q_mat VECTORIZED (không per-sample .item() sync):
731
+ │ │ ├─ proto_mat = stack([prototypes[id] for id in ids]).to(device) ← 1 GPU transfer
732
+ │ │ ├─ cos_values = (emb * proto_mat).sum(dim=-1) ← 1 GPU kernel
733
+ │ │ ├─ cos_cpu = cos_values.cpu().tolist() ← 1 GPU sync
734
+ │ │ └─ apply tanh(z) nếu có stats, else raw_cosine (tất cả v21 dùng raw — --no-mat-stats)
735
+ │ └─ Huber(pred_normalized, q_mat) pred_normalized = (Q/100 - 0.5) × 2
736
+
737
+ ├─ L_sens:
738
+ │ ├─ build_pair_indices() → pairs (cùng finger, khác sensor) từ SD302 + PolyU trong batch
739
+ │ ├─ L_pair = relu(|Q(s1) - Q(s2)| - 0.05).mean()
740
+ │ ├─ L_adv = cross_entropy(sensor_logits, sensor_labels) ← GRL đảo gradient
741
+ │ ├─ L_adv_clamped = L_adv.clamp(max=log(num_sensors)) ← T16: ngăn anti-corr
742
+ │ └─ (L_pair + 0.3 × L_adv_clamped, L_pair, L_adv)
743
+
744
+ ├─ L_deg (mỗi deg_every_n_steps=2 bước, chỉ FVC — tối đa deg_max_images=32):
745
+ │ ├─ deg_type = random.choice([blur, noise, jpeg, occlusion, dry_skin, wet_press])
746
+ │ ├─ level_lo ∈ {1,2} random, level_hi = 3
747
+ │ │
748
+ │ ├─ GPU path (blur / noise / occlusion) — không transfer nào:
749
+ │ │ ├─ imgs_low = _degrade_gpu(images[_fvc_idx], deg_type, level_lo)
750
+ │ │ └─ imgs_high = _degrade_gpu(images[_fvc_idx], deg_type, level_hi)
751
+ │ │
752
+ │ └─ CPU path (jpeg / dry_skin / wet_press) — đọc từ preloaded numpy, không GPU→CPU:
753
+ │ ├─ imgs_np = images_np[_fvc_idx] ← uint8, đã trong RAM
754
+ │ ├─ apply cv2 ops per image (GaussianBlur/imencode/erode/etc.)
755
+ │ ├─ imgs_low = stack(low_list).float().to(device) / 255.0 ← 1 CPU→GPU
756
+ │ └─ imgs_high = stack(high_list).float().to(device) / 255.0 ← 1 CPU→GPU
757
+
758
+ │ model(imgs_low), model(imgs_high) → 2 SIFQ forward thêm
759
+ │ L_rank + gamma * L_concept_deg → L_deg
760
+
761
+ ├─ L_ortho: standardize concepts → (x.T @ x) / (B-1) → off_diag Frobenius²
762
+
763
+ ├─ L_spread_global: uniform MSE(sorted Q_batch / 100, linspace(10,90) / 100)
764
+ ├─ L_spread_sd302: uniform MSE(sorted Q_sd302 / 100, linspace(10,90) / 100) — nếu ≥8 SD302
765
+
766
+ │ [epoch-end: log train_l_pair, train_l_adv, train_q_mean, train_q_std]
767
+
768
+ └─ total = α × L_mat + β × L_sens + γ × L_deg + L_ortho + 3.0 × L_spread_global + 3.0 × L_spread_sd302
769
+ └── scaler.backward() → optimizer.step() → scaler.update() (AMP fp16)
770
+ ```
771
+
772
+ **v21 config summary:**
773
+
774
+ | Param | Giá trị | Ghi chú |
775
+ |-------|---------|---------|
776
+ | batch_size | 128 | DataParallel → 64/GPU |
777
+ | W_SPREAD | 3.0 | --spread-weight 3.0 |
778
+ | deg_every_n_steps | 2 | Mỗi 2 bước có 1 deg step |
779
+ | deg_max_images | 32 | Tối đa 32 FVC images/step |
780
+ | concept_deg_gamma | 0.5 | L_concept weight trong L_deg |
781
+ | proto_max_batches | 0 | Full dataset (không cap) |
782
+ | no_mat_stats | True | Raw cosine target (không tanh) |
783
+ | sd302_concept_weight | 0.0 | T30b disabled |
784
+ | deg_include_sd302 | False | FVC-only L_deg (T27/T36) |
785
+
786
+ ---
787
+
788
+ ## 9. Điểm còn thiếu / TODO
789
+
790
+ | # | Vấn đề | Impact | Todo |
791
+ |---|--------|--------|------|
792
+ | 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 |
793
+ | 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 |
794
+ | 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. |
795
+ | 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. |
796
+ | T5 | Track 3 chưa có VeriFinger | Thấp | Dùng matcher khác (FLaRE, AFR-Net open-source) |
797
+ | 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 |
798
+ | 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 |
799
+ | 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. |
800
+ | 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 |
801
+ | 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 |
802
+ | 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 |
803
+ | 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 |
804
+ | 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 |
805
+ | 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 |
806
+ | 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` |
807
+ | 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 |
808
+ | 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. |
809
+ | 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. |
810
+ | 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. |
811
+ | 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. |
812
+ | 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/`. |
813
+ | 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ả. |
814
+ | 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. |
815
+ | 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`. |
816
+ | 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 đủ. |
817
+ | 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.** |
818
+ | 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`. |
819
+ | 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. |
820
+ | 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.** |
821
+ | 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. |
822
+ | 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. |
823
+ | 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`. |
824
+ | 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`. |
825
+
826
+
827
+ ---
828
+
829
+ ## 10. Performance Engineering (v21)
830
+
831
+ ### Bối cảnh
832
+
833
+ 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:
834
+
835
+ | Iteration | Thời gian | Root cause |
836
+ |-----------|-----------|------------|
837
+ | Before | 3.49 s/it (step 39) | Teacher DINOv2 forward mỗi step |
838
+ | After teacher cache | 4.05 s/it (step 6) | DataLoader disk IO bottleneck bị lộ |
839
+ | After image preload | 4.96 s/it (step 4) | CUDA warmup + _compute_q_mat GPU syncs |
840
+ | After vectorize q_mat | ~0.4 s/it (dự kiến, sau warmup) | — |
841
+
842
+ > **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.
843
+
844
+ ### Fix 1: Teacher Embedding Cache
845
+
846
+ **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.
847
+
848
+ **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.
849
+
850
+ **Fix:**
851
+ ```python
852
+ # scripts/train_sifq.py
853
+ emb_cache = precompute_teacher_embeddings(teacher, train_ds, device, batch_size=128)
854
+ # → Tensor[N, 256] CPU float32, ~43 MB cho 42K records
855
+
856
+ # Per step (thay vì teacher forward):
857
+ _cached_emb = emb_cache[record_idxs[_non_polyu_idx]] # O(1) lookup
858
+ loss_mat(..., cached_emb=_cached_emb)
859
+ ```
860
+
861
+ **Tiết kiệm:** ~2–3s/it (DINOv2 forward) → 0 (lookup). Startup cost: ~2–3 min (1 lần duy nhất).
862
+
863
+ ---
864
+
865
+ ### Fix 2: Image Preloading
866
+
867
+ **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.
868
+
869
+ **Fix:**
870
+ ```python
871
+ # RecordDataset.__init__
872
+ def _preload_images(self, image_size):
873
+ cache = np.empty((N, image_size, image_size), dtype=np.uint8) # ~2 GB
874
+ for i, rec in enumerate(self.records):
875
+ sample = next(loader.iter_samples([rec]))
876
+ cache[i] = (sample["image"].squeeze(0) * 255).byte().numpy()
877
+ self._image_cache = cache
878
+
879
+ # __getitem__: O(1) numpy slice + dtype cast, no disk IO
880
+ image = torch.from_numpy(self._image_cache[idx].copy()).float().unsqueeze(0) / 255.0
881
+ ```
882
+
883
+ **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()`.
884
+
885
+ ---
886
+
887
+ ### Fix 3: Vectorized `_compute_q_mat`
888
+
889
+ **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.
890
+
891
+ **Fix:**
892
+ ```python
893
+ # Trước: 100 syncs
894
+ for i, identity in enumerate(identity_ids):
895
+ cos = float(torch.dot(emb[i], proto).item()) # ← GPU sync!
896
+
897
+ # Sau: 1 sync
898
+ proto_mat = torch.stack([prototypes[id] for id in identity_ids]).to(emb.device) # 1 transfer
899
+ proto_mat = F.normalize(proto_mat, dim=-1)
900
+ cos_values = (emb * proto_mat).sum(dim=-1) # 1 GPU kernel
901
+ cos_cpu = cos_values.float().cpu().tolist() # 1 sync
902
+ ```
903
+
904
+ **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.
905
+
906
+ ---
907
+
908
+ ### Fix 4: GPU-Native Degradation
909
+
910
+ **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).
911
+
912
+ **Fix:**
913
+ ```python
914
+ # _degrade_gpu: blur/noise/occlusion — full GPU, không transfer
915
+ if deg_type == "blur":
916
+ return TF.gaussian_blur(images, kernel_size)
917
+ if deg_type == "noise":
918
+ return (images + torch.randn_like(images) * sigma).clamp(0, 1)
919
+ if deg_type == "occlusion":
920
+ out = images.clone(); out[:, :, y:y+block, x:x+block] = 1.0; return out
921
+
922
+ # _degrade_from_np: jpeg/dry_skin/wet_press — CPU nhưng đọc từ preloaded numpy
923
+ imgs = images_np[deg_idx] # [K, H, W] uint8, đã trong RAM
924
+ low = [deg_pipeline.apply(img, t, lo) for img in imgs]
925
+ ... → single CPU→GPU transfer (không GPU→CPU)
926
+ ```
927
+
928
+ **Breakdown degradation types:**
929
+
930
+ | Type | Đường đi | Transfer cost |
931
+ |------|---------|---------------|
932
+ | blur | GPU (`TF.gaussian_blur`) | 0 |
933
+ | noise | GPU (`torch.randn_like`) | 0 |
934
+ | occlusion | GPU (tensor indexing) | 0 |
935
+ | jpeg | CPU+cv2 → GPU (1 transfer) | 1 CPU→GPU |
936
+ | dry_skin | CPU+cv2 → GPU (1 transfer) | 1 CPU→GPU |
937
+ | wet_press | CPU+cv2 → GPU (1 transfer) | 1 CPU→GPU |
938
+
939
+ ---
940
+
941
+ ### Tổng quan pipeline v21
942
+
943
+ ```
944
+ Startup (1 lần, ~3–5 phút):
945
+ _preload_images() ~2 min → 2 GB RAM
946
+ precompute_teacher_emb() ~2 min → 43 MB CPU tensor
947
+ compute_teacher_prototypes() ~1 min → dict[id → 256-D]
948
+
949
+ Per step (~0.4 s steady-state):
950
+ DataLoader: ~1 ms (numpy slice + cast, no disk)
951
+ H2D transfer: ~5 ms (pin_memory)
952
+ SIFQ forward: ~100 ms (TinyViT-5M B=128, DataParallel 2×GPU)
953
+ L_mat: ~2 ms (emb_cache lookup + 1 GPU kernel + 1 sync)
954
+ L_sens: ~5 ms (pair indices + hinge loss)
955
+ L_deg (50%): ~150 ms (2 extra SIFQ forwards B=32 + GPU/CPU deg ops)
956
+ Backward: ~100 ms
957
+ Optimizer: ~20 ms
958
+ ─────────────────────
959
+ Total: ~0.35–0.55 s/it (estimate, post CUDA warmup)
960
+ ```
rules/plan.md ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SIFQ — Plan & Experiment Tracker
2
+
3
+ Dùng file này để: ghi kế hoạch trước khi thay đổi code, track tiến độ, và revert khi cần.
4
+
5
+ ---
6
+
7
+ ## Active Experiments
8
+
9
+ ### v32 — Done ❌
10
+ **Goal:** Fix two concept grounding failures in v31 via T42 concept map
11
+ **Key changes from v31:** T42 concept map (2 changes):
12
+ - `dry_skin: [4, 2, 0] → [4, 0]` — remove continuity
13
+ - `noise: [3] → [1, 3]` — add clarity as co-target
14
+ **Script:** `scripts/run_train_v32.sh`
15
+ **Result:** KS=0.1375, Pearson=0.7892 — Track 2 regression vs v31 (KS +0.022, Pearson -0.097)
16
+ **Track 4 regressions vs v31:**
17
+ - blur→clarity: +0.046 ✗ (was -0.305 ✓)
18
+ - noise→clarity: +0.114 ✗ (was -0.236 ✓)
19
+ - noise→noise_level: +0.121 ✗ (was -0.081 ✓)
20
+ - occlusion→minutiae: +0.121 ✗ (was -0.123 ✓)
21
+ - wet_press→minutiae: +0.676 ✗ (was -0.695 ✓)
22
+ **Root cause:** Adding clarity[1] to noise map caused clarity concept to absorb noise-degradation gradient, destroying its response to blur. Removing continuity[2] from dry_skin destabilised concept interactions across other degradation types.
23
+ **Reverted:** concept map → T39 (restored `noise:[3]`, `dry_skin:[4,2,0]`)
24
+ **Status:** Failed — reverted to T39 concept map
25
+
26
+ ---
27
+
28
+ ### v31 — Done ✅
29
+ **Goal:** Benchmark DINOv2-ViTS/14 as public teacher replacing unpublished MDGT
30
+ **Key change from v28:** `--teacher dinov2` (frozen DINOv2-ViTS/14 CLS token [B,384])
31
+ **Script:** `scripts/run_train_v31.sh`
32
+ **Result:** KS=0.1152, Pearson=0.8858, q_std≥15 ✅ — **best Track 2 so far**
33
+ **Concept issues:** dry_skin→noise_level Spearman -0.758 (spurious, noise_level NOT in target);
34
+ blur→continuity +0.214 (wrong direction); noise→noise_level -0.081 (weak signal)
35
+ **Status:** Complete
36
+
37
+ ---
38
+
39
+ ### v29 — Done ❌
40
+ **Goal:** Fix concept grounding failures in v28 — T41 concept map + anti-saturation losses
41
+ **Key changes from v28:**
42
+ - T41 concept map: jpeg→[1], dry_skin→[4,0], noise→[1,3] (fix gradient conflicts + noise inversion)
43
+ - `--ortho-weight 3.0` (vs 1.0 default) — push saturated concepts apart
44
+ - `--concept-spread-weight 1.0` — penalise concepts with batch std < 0.20
45
+ **Script:** `scripts/run_train_v29.sh`
46
+ **Result:** KS=0.2985, Pearson=0.1448 — catastrophic sensor invariance regression
47
+ **Root cause of failure:** `--concept-spread-weight 1.0` forces per-batch concept diversity
48
+ which amplifies sensor-specific texture features, destroying cross-sensor score alignment.
49
+ G_roll_png and H_roll_png particularly affected (KS 0.86 and 0.77 vs other sensors).
50
+ **Status:** Failed — reverted to v28 code base (train_sifq.py, degradation_ranking.py T39)
51
+
52
+ ---
53
+
54
+ ### v28 — Done ✅
55
+ **Goal:** Validate matcher-free quality learning — L_mat disabled entirely (`--no-mat`)
56
+ **Key change from v26:** No MDGT teacher. Loss = L_sens + L_deg + L_ortho + L_spread only.
57
+ **Script:** `scripts/run_train_v28.sh`
58
+ **Result:** KS=0.1346, Pearson=0.7645, q_std~23.2 (60 epochs)
59
+ **Concept issues found:** continuity collapsed (mean=0.068), noise_level inverted (+0.56), orient_coh saturated (0.94), contrast_uni saturated (0.85), clarity flat (std=0.043). Only minutiae_rel discriminating.
60
+ **Paper claim:** ✅ "SIFQ quality is self-supervised — no external matcher needed" validated by KS close to v24
61
+ **Status:** Complete → concept grounding needs fix (next experiment TBD)
62
+
63
+ ---
64
+
65
+ ### v26 — Đang train 🚀
66
+ **Goal:** Verify v25 regression root cause = gamma=1.5 (not T40 concept map)
67
+ **Key change from v25:** `--concept-deg-gamma 2.0` (restored), DEGRADATION_CONCEPT_MAP reverted to T39
68
+ **Script:** `scripts/run_train_v26.sh`
69
+ **Log:** `logs/train_v26.log`
70
+ **Expected:** KS ≈ 0.126, Pearson ≈ 0.80 (match v24)
71
+ **Eval:** `scripts/run_eval_v26.sh` (auto-runs after training)
72
+ **Status:** Training in progress
73
+
74
+ ### v27 — Pending ⏳
75
+ **Goal:** Validate SpatialConceptHead (14×14 spatial tokens) improves concept grounding
76
+ **Key change from v26:** `--spatial-concept-head` flag — `SpatialConceptHead` replaces `ConceptHead`
77
+ **Script:** `scripts/run_train_v27.sh`
78
+ **Expected:** KS ≈ v26, Track 4 diagonal stronger (especially orientation_coherence, continuity, minutiae_reliability)
79
+ **Blocker:** Wait for v26 to confirm KS/Pearson target first
80
+ **Status:** Code ready, not launched
81
+
82
+ ---
83
+
84
+ ## Code Change Log
85
+
86
+ ### 2026-06-04 — T42 concept map: 2 changes for v32
87
+
88
+ **Files changed:**
89
+ - `src/losses/degradation_ranking.py` — T42 DEGRADATION_CONCEPT_MAP:
90
+ - `dry_skin: [4,2,0] → [4,0]` (removed continuity [2])
91
+ - `noise: [3] → [1,3]` (added clarity [1] as co-target)
92
+
93
+ **Root cause (dry_skin):** v31 shows noise_level (c=3) Spearman -0.758 with dry_skin (NOT in target).
94
+ Continuity [2] shares backbone patch-scale features (~16×16) with noise texture → cross-activation.
95
+ Fix: use contrast[4] + orientation[0] (regional features at multi-patch scale) only.
96
+
97
+ **Root cause (noise):** v31 shows noise→noise_level Spearman only -0.081 (nearly no signal).
98
+ TinyViT 16×16 patch embed averages out pixel Gaussian noise (σ=5–30) → concept[3] gradient ≈ 0.
99
+ Adding clarity[1] anchors noise degradation to ridge-valley blur (detectable at patch scale).
100
+
101
+ **Backward compatibility:** ⚠️ Modifies shared DEGRADATION_CONCEPT_MAP.
102
+
103
+ **Revert T42 → T39:**
104
+ ```python
105
+ "noise": [3],
106
+ "dry_skin": [4, 2, 0],
107
+ ```
108
+
109
+ ---
110
+
111
+ ### 2026-06-03 — DINOv2Teacher: replace MDGT with public DINOv2-ViTS/14
112
+
113
+ **Files changed:**
114
+ - `src/training/mdgt_teacher.py` — Added `DINOv2Teacher` class: frozen DINOv2-ViTS/14 (via `torch.hub`), handles grayscale→RGB channel repeat + ImageNet normalization internally, returns L2-normalized [B, 384] CLS embeddings. `MDGTCheckpointTeacher` unchanged.
115
+ - `src/train.py` — Added `--teacher {dinov2,mdgt}` arg (default=`dinov2`). Import `DINOv2Teacher`. Instantiation in `main()` dispatches on `args.teacher`. `--mdgt-checkpoint` arg remains but only used when `--teacher=mdgt`.
116
+
117
+ **Root cause / motivation:** MDGT is unpublished work → not reproducible by reviewers → academic integrity risk. DINOv2-ViTS/14 is public (Meta, ICLR 2024), cite-able, and `torch.hub` reproducible.
118
+
119
+ **Expected Pearson impact:** DINOv2 raw → expect Pearson ~0.55–0.70 vs 0.80 with MDGT. Run v31 to benchmark.
120
+
121
+ **Backward compatibility:** ✅ All existing scripts using `--teacher mdgt --mdgt-checkpoint <path>` unaffected.
122
+
123
+ **Revert:**
124
+ ```bash
125
+ # train.py: change --teacher default back to "mdgt"
126
+ # or pass --teacher mdgt --mdgt-checkpoint <ckpt_path> explicitly
127
+ ```
128
+
129
+ ---
130
+
131
+ ### 2026-06-02 — T41 concept map + anti-saturation losses (v29)
132
+
133
+ **Files changed:**
134
+ - `src/losses/degradation_ranking.py` — T41 DEGRADATION_CONCEPT_MAP:
135
+ - `jpeg: [2,1] → [1]` (remove continuity — JPEG artifacts wrong gradient direction in v28)
136
+ - `dry_skin: [4,2,0] → [4,0]` (remove continuity — gradient conflict, Spearman+0.10 wrong)
137
+ - `noise: [3] → [1,3]` (add clarity co-target — noise blurs ridges, anchors concept 3)
138
+ - `scripts/train_sifq.py` — Added `--ortho-weight` (default 1.0) and `--concept-spread-weight` (default 0.0) args; l_orth now weighted; per-concept spread loss (std < 0.20 → penalty) added to total loss; logged as `l_cspread` in running dict and epoch print
139
+
140
+ **Root cause:** v28 concept collapse/inversion diagnosed via inference stats:
141
+ - continuity std=0.076, mean=0.068 → dead concept (3 conflicting grad sources: blur✓, jpeg✗, dry_skin✗)
142
+ - noise_level Spearman +0.56 → inverted (Gaussian noise increases texture energy in TinyViT)
143
+ - orient_coh mean=0.942, contrast_uni mean=0.851 → L_ortho=1.0 too weak to break saturation
144
+
145
+ **Backward compatibility:** ✅ `--ortho-weight` default=1.0, `--concept-spread-weight` default=0.0 → all v16-v28 unaffected.
146
+
147
+ **Revert T41 → T39:**
148
+ ```python
149
+ # degradation_ranking.py DEGRADATION_CONCEPT_MAP:
150
+ "noise": [3],
151
+ "jpeg": [2, 1],
152
+ "dry_skin": [4, 2, 0],
153
+ ```
154
+
155
+ ---
156
+
157
+ ### 2026-06-02 — --no-mat flag (v28 teacher-free experiment)
158
+
159
+ **Files changed:**
160
+ - `scripts/train_sifq.py` — Added `--no-mat` flag; MDGT teacher/emb_cache/prototypes wrapped in `if not args.no_mat`; training loop forces `l_mat = 0.0` when flag is set
161
+
162
+ **Backward compatibility:** ✅ Default `--no-mat=False` — all existing versions unaffected.
163
+
164
+ **Revert:** Remove `--no-mat` block in `parse_args()` and restore unconditional MDGT instantiation in `main()`.
165
+
166
+ ---
167
+
168
+ ### 2026-06-01 — SpatialConceptHead
169
+
170
+ **Files changed:**
171
+ - `src/models/concept_head.py` — Added `SpatialConceptHead` class
172
+ - `src/models/sifq.py` — `SIFQ.forward()` dispatches via `concept_head.uses_spatial`
173
+ - `src/models/__init__.py` — Export `SpatialConceptHead`
174
+ - `scripts/train_sifq.py` — `--spatial-concept-head` flag (default=False)
175
+ - `src/train.py` — same flag
176
+ - `scripts/run_eval.py` — auto-detect from `ckpt["config"]["spatial_concept_head"]`
177
+ - `scripts/run_infer.py` — same auto-detect
178
+ - `rules/SIFQ_explained.md` — Section 2.2 updated, diagram updated, File Map updated
179
+
180
+
181
+ **Backward compatibility:** ✅ All v16–v26 checkpoints load cleanly without flag.
182
+
183
+ ---
184
+
185
+ ### 2026-06-01 — T39 concept map revert + gamma restore (v26)
186
+
187
+ **Problem:** v25 used gamma=1.5 AND T40 concept map. Regression KS 0.126→0.213.
188
+ **Root cause identified:** gamma=1.5 too weak during S1→S2 ramp.
189
+ - v24 (gamma=2.0): spread stable ~0.003, q_std grows 18→22 monotonically
190
+ - v25 (gamma=1.5): spread spikes to 0.028, q_std collapses 22→10 (epochs 13–16)
191
+
192
+ **Files changed:**
193
+ - `src/losses/degradation_ranking.py` — T40 reverted to T39 DEGRADATION_CONCEPT_MAP
194
+ - `scripts/run_train_v26.sh` — `--concept-deg-gamma 2.0`
195
+
196
+ **DEGRADATION_CONCEPT_MAP T39 (current, correct):**
197
+ ```python
198
+ "blur": [1, 2]
199
+ "noise": [3]
200
+ "jpeg": [2, 1]
201
+ "occlusion": [5]
202
+ "dry_skin": [4, 2, 0]
203
+ "wet_press": [1, 5, 0]
204
+ ```
205
+
206
+ **Revert target:** T40 map (v25):
207
+ ```python
208
+ "blur": [1, 2, 0] # + orient_coh
209
+ "noise": [3, 4] # + contrast_u
210
+ "jpeg": [2, 1, 4] # + contrast_u
211
+ "occlusion": [5]
212
+ "dry_skin": [4, 2, 0]
213
+ "wet_press": [1, 5, 0]
214
+ ```
215
+ **Do NOT revert to T40** unless v26 confirms gamma=2.0 alone is insufficient and T39 concept grounding is weaker than expected.
216
+
217
+ ---
218
+
219
+ ## Revert Cookbook
220
+
221
+ ### Revert concept map to previous version
222
+ ```bash
223
+ # Check what the map looked like in a specific git commit:
224
+ git log --oneline src/losses/degradation_ranking.py
225
+ git show <commit>:sifq/src/losses/degradation_ranking.py | grep -A 30 "DEGRADATION_CONCEPT_MAP"
226
+
227
+ # Edit directly:
228
+ # src/losses/degradation_ranking.py — DEGRADATION_CONCEPT_MAP dict
229
+ ```
230
+
231
+ ### Revert to v24 hyperparameters (known good baseline)
232
+ ```bash
233
+ # Key v24 flags (from scripts/run_train_v24.sh):
234
+ --concept-deg-gamma 2.0
235
+ --spread-weight 3.0
236
+ --spread-mode uniform
237
+ --deg-every-n-steps 2
238
+ --no-mat-stats
239
+ --proto-max-batches 0
240
+ --k-cross 0
241
+ --batch-size 96
242
+ ```
243
+
244
+ ### Load and inspect a checkpoint
245
+ ```python
246
+ import torch
247
+ ckpt = torch.load("checkpoints/v24/last.pt", map_location="cpu", weights_only=False)
248
+ print(ckpt["metrics"]) # KS, Pearson, q_std, etc.
249
+ print(ckpt["config"]) # all argparse flags used
250
+ print(ckpt["epoch"]) # which epoch
251
+ ```
252
+
253
+ ### Compare two checkpoints' configs
254
+ ```python
255
+ import torch, json
256
+ c24 = torch.load("checkpoints/v24/last.pt", map_location="cpu", weights_only=False)["config"]
257
+ c25 = torch.load("checkpoints/v25/last.pt", map_location="cpu", weights_only=False)["config"]
258
+ for k in c24:
259
+ if c24.get(k) != c25.get(k):
260
+ print(f"{k}: v24={c24.get(k)} v25={c25.get(k)}")
261
+ ```
262
+
263
+ ### Run eval manually on any checkpoint
264
+ ```bash
265
+ cd /home/aiserver/works/fingerprint
266
+
267
+ # Step 1: Inference
268
+ python sifq/scripts/run_infer.py \
269
+ --checkpoint sifq/checkpoints/vXX/last.pt \
270
+ --root-302a dataset/302a/images/challengers \
271
+ --root-302b dataset/302b/images/baseline \
272
+ --root-302d dataset/nist_302d/images/auxiliary \
273
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
274
+ --output sifq/eval_results/sifq_scores_vXX.jsonl
275
+
276
+ # Step 2: Track 2 + Track 4
277
+ python sifq/scripts/run_eval.py \
278
+ --sifq-scores sifq/eval_results/sifq_scores_vXX.jsonl \
279
+ --checkpoint sifq/checkpoints/vXX/last.pt \
280
+ --out-dir sifq/eval_results/vXX \
281
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
282
+ --skip-track1
283
+ ```
284
+
285
+ ### Smoke test (~2 min)
286
+ ```bash
287
+ cd /home/aiserver/works/fingerprint
288
+ bash sifq/scripts/run_smoke.sh
289
+ ```
290
+
291
+ ---
292
+
293
+ ## Decision Log
294
+
295
+ ### Why not T40 concept map?
296
+ T40 added `orient_coh` to blur/noise/jpeg. Reverted in v26 because root cause of v25 regression was **gamma=1.5**, not concept map. T40 change had no confirmed benefit. Defer until v26 evaluation is done.
297
+
298
+ ### Why FVC-only L_deg (not SD302)?
299
+ SD302 images are all high quality by protocol → clean images satisfy L_rank at a single ~53 attractor → blocks quality discrimination signal from L_mat. FVC has genuine quality variation (8 impressions/subject) → MDGT cosine varies → L_mat gradient meaningful → transfers to SD302 at inference. (v20 root cause analysis)
300
+
301
+ ### Why --no-mat-stats?
302
+ Per-identity cosine stats (T31) created asymmetry: FVC has stable tanh targets, SD302 gets raw cosine ~0.85 constant. Backbone learned "FVC=quality-variable, SD302=fixed" → no L_mat gradient for SD302 → GRL destroyed SD302 features. (v17 root cause)
303
+
304
+ ### Why --k-cross 0?
305
+ k_cross>0 forces k guaranteed cross-sensor pairs per batch → over-constrains L_sens → backbone over-optimises sensor invariance → loses quality discrimination → Pearson collapses to ~0.09. (v21 root cause)
306
+
307
+ ### Why --proto-max-batches 0?
308
+ Partial prototypes (150 batches = 45% data) → SD302 identities have 2–3 sensor prototypes instead of full 19-sensor → cosine correlates with WHICH sensors in prototype window (sensor-biased) → no quality gradient for SD302. (v19/v20 root cause)
309
+
310
+ ### Why gamma must be ≥ 2.0?
311
+ During S1→S2 ramp, mat loss is introduced alongside existing deg loss. If deg loss too weak (gamma=1.5), mat loss dominates momentarily → spread spikes → model partially collapses and never fully recovers. gamma=2.0 keeps deg strong enough to maintain ordinal grounding through the ramp. (v25 root cause)
312
+
313
+ ---
314
+
315
+ ## Pending Research Questions
316
+
317
+ - [ ] **v26 eval:** Does restoring gamma=2.0 fully recover v24 KS/Pearson? (expected: yes)
318
+ - [ ] **v27 eval:** Does SpatialConceptHead improve Track 4 diagonal ρ vs v26?
319
+ - [ ] **noise→noise_level:** v24 Track 4 shows +0.365 (wrong direction). Defer to v28.
320
+ - [ ] **T40 revisit:** Once v26/v27 stable, evaluate if blur/noise/jpeg → orient_coh improves orientation_coherence grounding.
rules/sifq_pdf.txt ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ SIFQ: Sensor-Invariant Fingerprint Quality Assessment
2
+ A Self-Supervised, Concept-Grounded Alternative to NFIQ2
3
+ Research Design Document
4
+ Author: Bình An
5
+ Collaborator / Drafting: Claude
6
+ Version 0.1 · Research Design
7
+
8
+ 1. Tóm tắt ý tưởng
9
+ SIFQ (Sensor-Invariant Fingerprint Quality) là một framework đánh giá chất lượng vân tay được huấn luyện
10
+ hoàn toàn theo hướng self-supervised và weakly-supervised, không phụ thuộc vào nhãn chất lượng do
11
+ con người đánh. Khác với NFIQ2 (SOTA) vốn dùng match score từ VeriFinger-era matcher làm supervision
12
+ gián tiếp và chịu sensor-bias rõ rệt khi đánh giá dữ liệu cross-modality, SIFQ kết hợp ba tín hiệu huấn luyện
13
+ bổ trợ nhau: matcher embedding concentration từ MDGT làm teacher, cross-sensor invariance enforced
14
+ trên paired data, và controlled degradation ranking trên synthetic perturbations.
15
+ Đầu ra của SIFQ gồm một vector concepts có thể diễn giải (ridge clarity, orientation coherence, continuity,
16
+ noise level, contrast uniformity, minutiae reliability) và một scalar utility score tương thích thang đo
17
+ NFIQ2. Đóng góp cốt lõi về mặt phương pháp luận là việc attack trực diện vấn đề sensor-bias mà literature
18
+ hiện tại chưa giải quyết, và lần đầu tiên đưa concept bottleneck vào fingerprint quality assessment.
19
+ Tài liệu trình bày kiến trúc, ba loss functions, training protocol bốn stage, evaluation protocol năm track,
20
+ các rủi ro chính cùng mitigation tương ứng, và mối quan hệ với các dự án MDGT/OMFR hiện đang triển
21
+ khai song song.
22
+
23
+ 2. Động lực và tuyên bố vấn đề
24
+ 2.1. Hạn chế của NFIQ2 trong bối cảnh matcher hiện đại
25
+ NFIQ2 được phát triển cuối thập niên 2010 và trở thành chuẩn ISO/IEC 29794-4. Tuy nhiên đang gặp 3 vấn
26
+ đề lớn trong bối cảnh biometric hiện đại.
27
+ Thứ nhất, NFIQ2 học supervised với target là match score của VeriFinger. Điều này đóng khung quality
28
+ như một utility predictor cho một matcher cụ thể, không nhất thiết chuyển giao được sang matcher khác,
29
+ đặc biệt là deep matcher dựa trên learned embeddings như FLaRE, AFR-Net. Khi matcher thay đổi
30
+ paradigm từ minutiae-based sang representation-based, quality signal cũng cần được recalibrate.
31
+ Thứ hai, các feature tay trong NFIQ2 (OCL, LCS, FDA, RVU, OFL) được thiết kế trên giả định sensor optical
32
+ contact đồng nhất. Khi áp dụng lên contactless fingerprint hoặc latent prints, nhiều feature trả về giá trị
33
+ cực thấp vì đặc tính thống kê của ảnh khác biệt căn bản, dẫn đến Q(x) thấp mặc dù matcher hiện đại vẫn
34
+ có thể match tốt những ảnh này.
35
+ Thứ ba, NFIQ2 không có cơ chế bảo đảm sensor invariance. Trong quan sát thực nghiệm trên NIST SD302
36
+ mà chúng tôi ghi nhận trong quá trình phát triển MDGT, cùng một ngón tay capture trên hai sensor khác
37
+ nhau thường nhận được NFIQ2 score khác biệt 20-30 điểm, nghĩa là metric đang capture sensor signature
38
+ nhiều hơn biometric content.
39
+
40
+ Tóm lại, th NFIQ2 chỉ đánh giá tốt với Minuatie, còn với các model trên fix-length hoặc feature khác thì
41
+ giở. Đặc biệt lại khi kiểm định cùng 2 sensors, 1 ngón tay sẽ trả về 2 điểm NFIQ2 khác nhau
42
+
43
+ 2.2. Vấn đề sensor-bias từ kinh nghiệm MDGT
44
+ Trong quá trình phát triển MDGT trên NIST SD302, chúng tôi quan sát thấy hiện tượng shortcut learning:
45
+ impostor similarity trong cùng một sensor cao hơn genuine similarity cross-sensor. Điều này cho thấy
46
+ không chỉ matcher mà mọi feature extractor có khả năng capture sensor identity thay vì biometric identity
47
+ khi không có cơ chế debiasing rõ ràng. Quality predictor nếu huấn luyện ngây thơ cũng sẽ mắc cùng failure
48
+ mode.
49
+ Một quality metric đáng tin cậy cho biometric system cần bất biến với sensor, chỉ phản ánh thông tin
50
+ ridge-valley thực chất. Đây là một gap mà literature hiện tại chưa lấp và là cơ hội về mặt nghiên cứu.
51
+
52
+ 2.3. Nhu cầu về task-aware và interpretable quality
53
+ Trong một fingerprint biometric pipeline hiện đại, một ảnh có thể có chất lượng khác nhau tuỳ task. Ảnh
54
+ contactless có thể tốt cho identity matching nhưng tệ cho liveness/PAD vì thiếu texture bề mặt. Một
55
+ quality score duy nhất không thể phục vụ mọi downstream task. SIFQ đưa ra giải pháp thông qua concept
56
+ decomposition, cho phép downstream system quyết định concept nào quan trọng cho task của nó.
57
+ Ngoài ra, khi operator ở sensor nhận thông báo quality thấp, việc biết được vấn đề nằm ở concept nào
58
+ (noise quá cao, ridge clarity kém, occlusion) cho phép hướng dẫn re-capture hiệu quả hơn, thay vì chỉ báo
59
+ chung một con số.
60
+
61
+ 3. Related works
62
+ 3.1. Fingerprint quality assessment
63
+ NFIQ (2004) và phiên bản kế nhiệm NFIQ2 (2016, sau này trở thành ISO/IEC 29794-4) là hai baseline chính.
64
+ NFIQ2 dùng tập hợp 14 features bao gồm orientation certainty, minutiae count and quality, ridge-valley
65
+ uniformity, frequency domain analysis, tổng hợp qua một random forest hoặc gradient boosting classifier
66
+ regress về match score. Hạn chế đã phân tích ở Mục 2.1.
67
+ MiDeCon (Tapia et al., 2022) thử nghiệm deep quality estimation nhưng vẫn huấn luyện supervised với
68
+ NFIQ2 labels làm pseudo-ground-truth, vô hình chung kế thừa các bias của NFIQ2. Một số nghiên cứu sử
69
+ dụng CNN để classify quality tốt/xấu dưới dạng binary task, nhưng mất đi tính ordinal của quality score.
70
+
71
+ 3.2. Face quality methods áp dụng cho fingerprint
72
+ SER-FIQ (Terhörst et al., 2020) giới thiệu stochastic embedding robustness như quality signal: với một ảnh
73
+ x, chạy multiple forward passes với dropout kích hoạt, quality là độ ổn định của embeddings. Không cần
74
+ labels nhưng đòi hỏi dropout trong architecture và nhiều forward passes lúc inference.
75
+ SDD-FIQA (Ou et al., 2021) sử dụng similarity distribution distance: với mỗi sample, so sánh genuine và
76
+ impostor similarity distributions, quality là mức độ tách biệt. Yêu cầu identity labels.
77
+
78
+ CR-FIQA (Boutros et al., 2023) là closest conceptual analog: quality được định nghĩa là class-center ratio,
79
+ hiệu giữa intra-class distance và nearest inter-class distance trong embedding space. Được train như
80
+ regression head trên matcher backbone, không cần labels ngoài identity.
81
+ Điểm chung của ba method này là chúng được phát triển cho face, nơi mà cross-sensor/cross-modality
82
+ không phải vấn đề chính. Khi chuyển sang fingerprint, đặc biệt với các dataset cross-modality như PolyU
83
+ CL2CB, chúng sẽ kế thừa sensor-bias của backbone matcher.
84
+
85
+ 3.3. Concept bottleneck models
86
+ Koh et al. (2020) đề xuất Concept Bottleneck Models: thay vì map input trực tiếp đến target, model học
87
+ trước một tập concepts có tên, rồi concepts predict target. Được chứng minh cho tác vụ classification trên
88
+ medical imaging và birds. Chưa có công bố nào đưa concept bottleneck vào fingerprint quality assessment.
89
+ Áp dụng concept bottleneck vào fingerprint quality có ba lợi ích: interpretability (operator biết vấn đề cụ
90
+ thể), controllability (có thể intervene vào concept values để test what-if), và regularization (concepts
91
+ grounded ngăn model overfit vào spurious correlations).
92
+
93
+ 3.4. So sánh tóm tắt
94
+ Method
95
+
96
+ Supervision
97
+
98
+ Teacher
99
+
100
+ Sensorinvariant
101
+
102
+ Interpretable
103
+ concepts
104
+
105
+ Domain
106
+
107
+ NFIQ2
108
+
109
+ Supervised
110
+
111
+ VeriFinger
112
+ scores
113
+
114
+ No
115
+
116
+ Partial (handcrafted)
117
+
118
+ Fingerprint
119
+
120
+ SER-FIQ
121
+
122
+ Self-supervised
123
+
124
+ Dropoutensemble
125
+
126
+ No
127
+
128
+ No
129
+
130
+ Face
131
+
132
+ SDD-FIQA
133
+
134
+ Weaklysupervised
135
+
136
+ Similarity
137
+ distribution
138
+
139
+ No
140
+
141
+ No
142
+
143
+ Face
144
+
145
+ 4. Phương pháp đề xuất
146
+ 4.1. Tổng quan kiến trúc
147
+ SIFQ gồm ba thành phần chính. Backbone là một ViT nhẹ, đề xuất TinyViT-2M hoặc MobileViT tương
148
+ đương, nhận input 1-channel fingerprint image (hoặc 3-channel sau Gabor stem nếu muốn share
149
+ preprocessing với MDGT) và trả về feature map spatial tại resolution 14x14. Concept head là một MLP với
150
+ k output nodes, mỗi node là một concept scalar trong khoảng [0,1] thông qua sigmoid activation.
151
+ Aggregator là một MLP nhỏ nhận concept vector và predict scalar Q(x) trong thang [0,100].
152
+ Chọn backbone không share weights với MDGT có hai lý do. Thứ nhất, SIFQ cần deploy được on-sensor
153
+ với latency thấp (mục tiêu dưới 50ms trên ARM Cortex-A72), MDGT quá nặng. Thứ hai, giữ hai model tách
154
+
155
+ biệt tránh circular dependency giữa quality và matching, nơi mà improvement ở một bên ngẫu nhiên dẫn
156
+ đến degradation ở bên kia do shared representation drift.
157
+
158
+ 4.2. Concept set
159
+ Chọn k=6 concepts đầu tiên, có thể mở rộng trong follow-up. Lựa chọn concepts dựa trên các yếu tố đã
160
+ được fingerprint expert community công nhận và có thể induce được bằng controlled degradation.
161
+ 1. orientation_coherence: độ nhất quán của orientation field trong các local patches. Cao khi ridge
162
+ flow smooth, thấp khi có đứt gãy hoặc chỗ chuyển hướng đột ngột.
163
+ 2. ridge_valley_clarity: độ sắc nét của biên ridge-valley. Thấp khi blur, compression, hoặc dry skin
164
+ làm mờ boundary.
165
+ 3. continuity: mức độ liên tục của ridge lines. Giảm khi có gap, fragmentation, hoặc overbinarization.
166
+ 4. noise_level: mức nhiễu background và foreground. Tăng với sensor noise, JPEG artifacts, scan
167
+ noise.
168
+ 5. contrast_uniformity: độ đồng đều contrast across foreground. Thấp khi dry skin, uneven
169
+ pressure, partial contact.
170
+ 6. minutiae_reliability: expected reliability của minutiae extraction. Tổng hợp từ ba concepts
171
+ trước nhưng có signal riêng khi occlusion hoặc edge-cropping xảy ra.
172
+ Lưu ý rằng concepts không cần độc lập hoàn toàn về mặt toán học. Blur affect cả ridge_valley_clarity và
173
+ continuity đồng thời, điều này chấp nhận được và được reflect trong degradation-concept mapping ở
174
+ Mục 4.4.
175
+
176
+ 4.3. Ba tín hiệu huấn luyện
177
+ 4.3.1. Signal 1: Matcher-as-teacher (L_mat)
178
+ Cho mỗi identity y có đủ samples (tối thiểu 5 samples per identity), compute class prototype c_y là trung
179
+ bình của MDGT embeddings đã L2-normalize. Với mỗi sample x có label y, quality signal từ matcher là:
180
+ q_mat(x) = ( cos(MDGT(x), c_y) − mu_y ) / sigma_y
181
+
182
+ trong đó mu_y và sigma_y là mean và standard deviation của cosine similarity trong class y. Việc chuẩn
183
+ hoá per-identity giúp tránh bias toward identities có ít intra-variance (tức là identities có nhiều sample rất
184
+ giống nhau thì không được ưu tiên hơn identities có variance lớn hơn một cách tự nhiên).
185
+ SIFQ được huấn luyện regress q_mat(x) bằng Huber loss, robust hơn MSE khi có outliers:
186
+ L_mat = Huber( Q_normalized(x), q_mat(x) )
187
+
188
+ MDGT được frozen trong suốt training. L_mat một mình không đủ vì nó kế thừa toàn bộ bias của MDGT
189
+ bao gồm sensor-bias.
190
+
191
+ 4.3.2. Signal 2: Cross-sensor invariance (L_sens)
192
+ Cho mỗi paired sample (x_s1, x_s2) cùng ngón tay khác sensor, enforce ràng buộc Q bất biến qua margin:
193
+ L_pair = max( 0, | Q(x_s1) − Q(x_s2) | − delta )
194
+
195
+ Margin delta = 0.05 cho phép fluctuation nhỏ nhưng penalize drift hệ thống. Ngoài pairwise constraint,
196
+ một adversarial term được thêm vào để enforce global invariance:
197
+ L_adv = − log D(sensor | f_intermediate(x))
198
+
199
+ trong đó D là một sensor classifier nhận intermediate features từ concept head và cố gắng predict sensor
200
+ type. Backbone và concept head được train ngược lại để fool D thông qua gradient reversal layer
201
+ (lambda_adv = 0.3 mặc định). Tổng loss:
202
+ L_sens = L_pair + lambda_adv * L_adv
203
+
204
+ Đây là contribution cốt lõi về mặt novelty. NFIQ2 hoàn toàn không có mechanism tương tự, và các face
205
+ quality method cũng không vì face thường capture trong single modality. SIFQ là method đầu tiên đưa
206
+ invariance constraint trực tiếp vào quality learning.
207
+
208
+ 4.3.3. Signal 3: Controlled degradation ranking (L_deg)
209
+ Build một degradation pipeline sáu loại, mỗi loại có bốn levels cường độ. Với mỗi clean image x, sample
210
+ hai levels i < j trong cùng degradation type, và enforce ordinal ranking:
211
+ L_rank = max( 0, Q(x_j) − Q(x_i) + m ) + max( 0, Q(x_i) − Q(x) + m )
212
+
213
+ với margin m = 0.1. Ngoài ranking loss trên scalar Q, thêm một supervision concept-level quan trọng: mỗi
214
+ degradation type được gán một hoặc nhiều target concepts, và concepts tương ứng phải phản ứng
215
+ monotonically theo level. Ví dụ, với blur, ridge_valley_clarity và continuity đều phải giảm khi level tăng.
216
+ Mapping cụ thể được trình bày trong Mục 4.4. Concept supervision này transform concepts từ latent
217
+ variables vô nghĩa thành grounded representations. Nếu không có bước này, concepts chỉ là 6 output
218
+ neurons tình cờ được đặt tên, không có quan hệ nào với tên của chúng.
219
+ L_concept_deg = sum over (degradation, target_concept) of Huber(
220
+ c_target(x_level), expected_response(level) )
221
+
222
+ Tổng loss cho degradation signal:
223
+ L_deg = L_rank + gamma * L_concept_deg
224
+
225
+ với gamma = 0.5.
226
+
227
+ 4.3.4. Tổng loss và trade-off có chủ ý
228
+ Tổng loss tại epoch t:
229
+ L(t) = alpha(t) * L_mat + beta(t) * L_sens + gamma_stage(t) * L_deg + L_ortho
230
+
231
+ trong đó alpha và beta ramp theo stage (xem Mục 5), L_ortho là một decorrelation loss nhẹ trên concept
232
+ activations để hạn chế entanglement:
233
+
234
+ L_ortho = || off_diag( corr(concept_activations) ) ||_F^2
235
+
236
+ Balance giữa 3 loại signal. Đây là điểm conceptual quan trọng nhất. L_mat kéo Q theo hướng behavior
237
+ của MDGT (kể cả bias). L_sens đẩy Q rời khỏi bất cứ signature nào của sensor. L_deg cung cấp ordinal
238
+ anchor độc lập với cả hai. Khi huấn luyện đồng thời, ba lực tạo ra một equilibrium mà Q phải học quality
239
+ nghĩa là gì không phụ thuộc sensor, nhưng vẫn predictive cho matcher hiện đại, và có grounding ordinal
240
+ thực tế. Nếu chỉ dùng L_mat, Q clone bias của MDGT. Nếu chỉ L_sens, Q không có task relevance. Nếu chỉ
241
+ L_deg, Q chỉ predict mức độ xuống cấp synthetic.
242
+
243
+ 4.4 Các loại concept-degradation
244
+ Bảng sau định nghĩa cách mỗi loại degradation ảnh hưởng đến concepts nào. Đây là core của concept
245
+ grounding mechanism.
246
+ Degradation type
247
+
248
+ Physical simulation
249
+
250
+ Target concept(s)
251
+
252
+ Expected response
253
+
254
+ Blur
255
+
256
+ Gaussian kernel, sigma 0.5
257
+ to 3.0
258
+
259
+ ridge_valley_clarity,
260
+ continuity
261
+
262
+ Both decrease
263
+ monotonically
264
+
265
+ Noise
266
+
267
+ Additive Gaussian, sigma
268
+ 5 to 30
269
+
270
+ noise_level
271
+
272
+ Increases
273
+ monotonically
274
+
275
+ JPEG compression
276
+
277
+ Quality factor 90 to 15
278
+
279
+ continuity,
280
+ ridge_valley_clarity
281
+
282
+ Both decrease
283
+
284
+ Partial occlusion
285
+
286
+ Random mask, coverage
287
+ 10% to 40%
288
+
289
+ minutiae_reliability
290
+
291
+ Decreases with
292
+ coverage
293
+
294
+ Dry skin
295
+
296
+ Local contrast reduction +
297
+ fragmentation
298
+
299
+ contrast_uniformity,
300
+ continuity
301
+
302
+ Both decrease
303
+
304
+ Pressure (wet)
305
+
306
+ Morphological dilation,
307
+ ridge thickening
308
+
309
+ ridge_valley_clarity,
310
+ minutiae_reliability
311
+
312
+ Both decrease
313
+
314
+ Lưu ý thiết kế. Một degradation có thể ảnh hưởng nhiều concepts, điều này phản ánh thực tế ngoài đời.
315
+ Blur thực tế giảm cả clarity và continuity. Mapping không cần hoàn hảo, chỉ cần đủ tín hiệu để concepts
316
+ học được hướng đúng. Cross-talk không mong muốn giữa concepts được regulate bởi L_ortho và được
317
+ measure trong Track 4 của evaluation.
318
+
319
+ 5. Datasets
320
+ SIFQ dựa vào bốn dataset chính. Cấu hình yêu cầu paired data cho L_sens, identity labels cho L_mat, và
321
+ clean images cho L_deg.
322
+
323
+ Dataset
324
+
325
+ Paired?
326
+
327
+ Identity
328
+ labels?
329
+
330
+ Role in SIFQ
331
+
332
+ Signal used
333
+
334
+ Single-sensor
335
+
336
+ Yes
337
+
338
+ Matcher-teacher training,
339
+ degradation base images
340
+
341
+ L_mat, L_deg
342
+
343
+ NIST SD302 a/b/d
344
+
345
+ Yes (multisensor)
346
+
347
+ Yes
348
+
349
+ Cross-sensor invariance
350
+ training, matcher-teacher
351
+
352
+ L_sens, L_mat
353
+
354
+ PolyU CL2CB
355
+
356
+ Yes (crossmodality)
357
+
358
+ Yes
359
+
360
+ Hardest invariance case:
361
+ contactless vs contact
362
+
363
+ L_sens
364
+
365
+ NIST SD300
366
+
367
+ No
368
+
369
+ Partial
370
+
371
+ Held-out evaluation only
372
+
373
+ Evaluation, no training
374
+
375
+ FVC2002/2004
376
+
377
+ Điểm quan trọng cần xác nhận sớm là paired structure của NIST SD302. Cần metadata đảm bảo same
378
+ finger ID persistent across sensors, không chỉ same subject ID. Nếu chỉ có subject ID, việc pair dựa trên
379
+ finger position dễ sai và cần manual audit cho một subset.
380
+ PolyU CL2CB là trường hợp invariance khó nhất (contactless vs contact) và cũng là case thuyết phục nhất
381
+ nếu SIFQ xử lý tốt. Dataset này nhỏ, chủ yếu dùng cho L_sens và evaluation Track 2, không đủ cho general
382
+ training.
383
+
384
+ 7. Evaluation Protocol
385
+ Năm evaluation tracks được thiết kế để address từng claim cụ thể của paper, kèm theo vai trò rhetorical
386
+ trong narrative. Các tracks không đồng quyền, Track 1 và 2 là primary, Track 3-5 là supporting.
387
+ #
388
+
389
+ Track
390
+
391
+ Metric
392
+
393
+ Role in narrative
394
+
395
+ 1
396
+
397
+ Error Rejection Curve
398
+
399
+ FNMR@FMR=1e-4 vs rejection
400
+ ratio; AUC_ERC
401
+
402
+ Primary utility metric, directly
403
+ comparable to NFIQ2
404
+
405
+ 2
406
+
407
+ Sensor invariance
408
+
409
+ KS statistic across sensor
410
+ populations; cross-sensor Pearson
411
+ of Q
412
+
413
+ Core novelty claim figure
414
+
415
+ 3
416
+
417
+ Cross-matcher transfer
418
+
419
+ Q correlation with VeriFinger and
420
+ AFR-Net error rates
421
+
422
+ Rebuts the 'only distills MDGT'
423
+ critique
424
+
425
+ 4
426
+
427
+ Concept grounding
428
+
429
+ Spearman rho between degradation
430
+ level and concept score; cross-talk
431
+ matrix
432
+
433
+ Validates interpretability claim
434
+
435
+ 5
436
+
437
+ Human correlation
438
+ (optional)
439
+
440
+ Spearman rho with expert Likert
441
+ ratings on 300 to 500 images
442
+
443
+ Strongest rhetorical evidence if
444
+ available
445
+
446
+ 7.1. Track 1: Error Rejection Curve
447
+
448
+ Đây là metric chuẩn trong quality literature, cho biết quality score hữu ích thế nào khi dùng để reject
449
+ samples. Sắp xếp samples theo Q tăng dần, reject bottom x%, compute FNMR tại FMR fixed trên phần còn
450
+ lại. Plot curve FNMR vs rejection ratio. Q tốt giảm FNMR nhanh khi tăng rejection.
451
+ Baseline so sánh: NFIQ2 (industry standard), SER-FIQ và CR-FIQA (state-of-the-art self-supervised từ face
452
+ domain adapted cho fingerprint). Matcher dùng để tính FNMR: cả VeriFinger v12 (classical) lẫn MDGT
453
+ (deep). Thử nghiệm trên FVC2004, NIST SD302 single-sensor subset, PolyU CL2CB.
454
+ Metric tổng hợp: AUC_ERC (area under ERC curve). Thấp hơn là tốt hơn.
455
+
456
+ 7.2. Track 2: Sensor-invariance quantification
457
+ Đây là figure KEY của paper, cần plot rõ ràng và ấn tượng. Trên NIST SD302, tách samples theo sensor,
458
+ plot histogram của Q cho mỗi sensor trên cùng một axis. NFIQ2 expected cho histograms rất khác nhau
459
+ giữa optical và capacitive. SIFQ expected cho histograms overlap cao.
460
+ Metric định lượng: Kolmogorov-Smirnov statistic giữa Q distributions cross-sensor. Thấp hơn là tốt hơn.
461
+ Thêm một bảng với từng cặp sensor và KS của từng method. Thêm một scatter plot Q_sensor1 vs
462
+ Q_sensor2 cho paired samples, Pearson correlation. Cao hơn là tốt hơn.
463
+ Đây là track mà SIFQ phải win rõ ràng, nếu không paper mất contribution cốt lõi.
464
+
465
+ 7.3. Track 3: Cross-matcher transfer
466
+ Sau khi train SIFQ với MDGT teacher, evaluate khả năng generalize sang matcher khác. Compute ERC của
467
+ SIFQ với VeriFinger v12 làm matcher (metric tính FNMR dựa trên VeriFinger scores). Nếu Q vẫn giảm FNMR
468
+ effectively, chứng tỏ SIFQ không chỉ distill MDGT mà học được general quality signal.
469
+ Track này address reviewer concern phổ biến: 'ông chỉ dạy SIFQ bắt chước MDGT'. Nếu Q giảm FNMR trên
470
+ matcher chưa từng thấy, critique đó bị refute.
471
+
472
+ 7.4. Track 4: Concept grounding
473
+ Validate claim interpretability. Với mỗi degradation type, sweep level từ 0 (clean) đến max, plot response
474
+ của mỗi concept. Tính Spearman correlation giữa degradation level và concept response. Target concepts
475
+ phải có rho cao (gần 1 hoặc -1), non-target concepts phải có rho thấp.
476
+ Plot cross-talk matrix: hàng là degradation type, cột là concept, cell là Spearman rho. Matrix lý tưởng có
477
+ diagonal-heavy pattern (mỗi degradation ảnh hưởng chủ yếu đến target concept của nó). Matrix dày đặc
478
+ cho thấy concept entanglement, cần mitigation.
479
+
480
+ 7.5. Track 5: Human correlation (tuỳ chọn)
481
+
482
+ Mời 2-3 fingerprint examiners (ví dụ từ phòng forensic hoặc academia partner) rate 300 đến 500 ảnh trên
483
+ Likert scale 1-5. Compute Spearman rho giữa expert rating trung bình và SIFQ score. Bonus: concept-level
484
+ rating, expert rate từng concept riêng, so với SIFQ concept scores.
485
+ Track này tốn công (2-3 ngày expert time, cần ethics clearance) nhưng nếu có kết quả tích cực thì là
486
+ evidence rhetorical mạnh nhất. Optional và có thể để cho follow-up paper.
487
+
488
+
scripts/_gen_report_v24.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json, numpy as np
2
+ from scipy.stats import spearmanr
3
+ from datetime import datetime
4
+
5
+ records = [json.loads(l) for l in open('eval_results/sifq_scores_v24.jsonl')]
6
+ CNAMES = ['orientation_coherence','ridge_valley_clarity','continuity','noise_level','contrast_uniformity','minutiae_reliability']
7
+ concepts = np.array([r['concepts'] for r in records])
8
+ qs = np.array([r['q_score'] for r in records])
9
+
10
+ d = json.load(open('eval_results/v24/eval_summary.json'))
11
+ t2 = d['track2_sensor_invariance']['SIFQ']
12
+ t4 = d['track4_concept_grounding']
13
+
14
+ TARGETS = {
15
+ 'blur': ['ridge_valley_clarity', 'continuity'],
16
+ 'noise': ['noise_level'],
17
+ 'jpeg': ['continuity', 'ridge_valley_clarity'],
18
+ 'occlusion': ['minutiae_reliability'],
19
+ 'dry_skin': ['contrast_uniformity', 'continuity', 'orientation_coherence'],
20
+ 'wet_press': ['ridge_valley_clarity', 'minutiae_reliability', 'orientation_coherence'],
21
+ }
22
+
23
+ SEP = '=' * 70
24
+ SEP2 = '-' * 70
25
+
26
+ lines = [
27
+ SEP,
28
+ 'SIFQ -- Concept Quality Model: Ly thuyet & Ket qua (v24)',
29
+ f'Generated: {datetime.now().strftime("%Y-%m-%d %H:%M")}',
30
+ SEP,
31
+ '',
32
+ '1. DINH NGHIA 6 CONCEPTS',
33
+ SEP2,
34
+ 'Tat ca concepts: cao = chat luong tot hon, dau ra trong [0, 1].',
35
+ '',
36
+ ' # Concept Y nghia vat ly',
37
+ ' -- -------------------------- -----------------------------------------------',
38
+ ' 0 orientation_coherence Ridge flow nhat quan, local orientation field smooth',
39
+ ' 1 ridge_valley_clarity Bien ridge-valley sac net, contrast cuc bo cao',
40
+ ' 2 continuity Ridge lines lien tuc, khong bi dut gay',
41
+ ' 3 noise_level It nhieu ngau nhien (cao = it noise = tot)',
42
+ ' 4 contrast_uniformity Contrast deu tren toan foreground',
43
+ ' 5 minutiae_reliability Minutiae co the trich xuat chinh xac',
44
+ '',
45
+ ' Degradation Concept Map (v25 -- T40):',
46
+ ' blur -> [clarity[1], continuity[2], orient_coh[0]]',
47
+ ' noise -> [noise_level[3], contrast_u[4]]',
48
+ ' jpeg -> [continuity[2], clarity[1], contrast_u[4]]',
49
+ ' occlusion -> [minutiae_reliability[5]]',
50
+ ' dry_skin -> [contrast_u[4], continuity[2], orient_coh[0]]',
51
+ ' wet_press -> [clarity[1], minutiae_rel[5], orient_coh[0]]',
52
+ '',
53
+ ' Ly do thiet ke map nhu vay:',
54
+ ' - Moi concept phai duoc giam sat boi >= 2 loai degradation (tranh single-',
55
+ ' point-of-failure: 1 degradation target 1 concept -> signal yeu, de bi',
56
+ ' gradient interference invert chieu).',
57
+ ' - Chon degradation phu hop vat ly: jpeg blocking -> contrast bands (khong',
58
+ ' chi ridge artifacts), blur -> orientation blur (khong chi clarity loss).',
59
+ '',
60
+ '',
61
+ '2. CO CHE TRAINING CONCEPT (L_concept)',
62
+ SEP2,
63
+ 'Voi moi cap anh (mild degradation vs severe degradation cung loai):',
64
+ '',
65
+ ' L_concept = SUM Huber( c_mild[c], c_severe[c] + 0.1 )',
66
+ ' c in targets(degradation_type)',
67
+ '',
68
+ ' -> Anh degradation nhe phai co concept cao hon anh degradation nang >= 0.1',
69
+ ' -> Model hoc tung concept phan ung dung chieu voi loai hu hong tuong ung',
70
+ '',
71
+ 'Ket hop ranking loss:',
72
+ ' L_rank = relu(Q_severe - Q_mild + m) + relu(Q_mild - Q_clean + m)',
73
+ ' -> Q giam theo thu tu: clean > mild_deg > severe_deg',
74
+ '',
75
+ ' L_deg = L_rank + gamma * L_concept',
76
+ ' gamma = 2.0 (v24) -> 1.5 (v25)',
77
+ ' - gamma qua cao (2.0): gradient conflict qua manh -> noise_level inversion',
78
+ ' - gamma qua thap (0.5, v22): blur->continuity FAIL (+0.261)',
79
+ ' - gamma = 1.5: compromise, du manh cho blur/jpeg, khong gay inversion',
80
+ '',
81
+ '',
82
+ '3. VAN DE CONCEPT SATURATION',
83
+ SEP2,
84
+ 'Nguyen nhan goc: L_concept chi train tren synthetic degradation pairs.',
85
+ 'Voi real fingerprint images, KHONG co gradient dinh huong concept.',
86
+ '-> Concept troi ve gia tri mac dinh cua backbone features.',
87
+ '',
88
+ 'Hau qua trong v24 (42,683 real fingerprint images):',
89
+ '',
90
+ ' Concept mean std rho_Q Tinh trang',
91
+ ' ---------------------------- ------ ----- ------ ---------------------------',
92
+ ]
93
+
94
+ STATUS = {
95
+ 'noise_level': '!! DOMINATES Q (rho=-0.989)',
96
+ 'minutiae_reliability': '!! Saturated HIGH -- dead (range 0.84-0.93)',
97
+ 'orientation_coherence':'!! Saturated LOW -- T39 overcorrected',
98
+ 'ridge_valley_clarity': '!! Near-dead -- low variance',
99
+ 'continuity': '!! Near-dead -- low variance',
100
+ 'contrast_uniformity': '!! Near-dead -- low variance',
101
+ }
102
+
103
+ for i, name in enumerate(CNAMES):
104
+ c = concepts[:, i]
105
+ rho, _ = spearmanr(c, qs)
106
+ status = STATUS.get(name, 'OK')
107
+ lines.append(f' {name:<28} {c.mean():>6.3f} {c.std():>6.3f} {rho:>+7.3f} {status}')
108
+
109
+ lines += [
110
+ '',
111
+ ' Vong lap nguy hiem (self-reinforcing collapse):',
112
+ ' ScoreAggregator chon noise_level (std=0.340, cao nhat)',
113
+ ' -> gradient tap trung update noise pathway',
114
+ ' -> cac concept khac it duoc update -> variance thap hon',
115
+ ' -> cang bi bo qua -> variance cang thap (vong lap)',
116
+ '',
117
+ ' He qua: Q ≈ f(noise_level) -- model thuc chat la "noise detector",',
118
+ ' khong phai "quality estimator" da khai niem.',
119
+ '',
120
+ '',
121
+ '4. KET QUA v24',
122
+ SEP2,
123
+ ]
124
+
125
+ ks = t2['mean_ks_across_sensors']
126
+ pearson = t2['cross_sensor_pearson']
127
+ lines += [
128
+ ' Track 2 -- Sensor Invariance:',
129
+ f' Mean KS (cross-sensor) = {ks:.4f} [goal <= 0.30] {"PASS" if ks <= 0.30 else "FAIL"}',
130
+ f' Cross-sensor Pearson = {pearson:.4f} [goal >= 0.20] {"PASS" if pearson >= 0.20 else "FAIL"}',
131
+ '',
132
+ ' Y nghia: cung mot ngon tay chup bang cac sensor khac nhau -> SIFQ cho',
133
+ ' score nhat quan. KS thap = phan bo giong nhau, Pearson cao = ranking on dinh.',
134
+ ' NFIQ2 thuong co KS > 0.5 cho cross-sensor pairs.',
135
+ '',
136
+ ' Track 4 -- Concept Grounding (rho < 0 = PASS):',
137
+ f' {"Degradation":<12} {"Concept":<28} {"rho":>7} Status',
138
+ f' {"------------":<12} {"----------------------------":<28} {"-------":>7} ------',
139
+ ]
140
+
141
+ pass_count = total = 0
142
+ for row in t4:
143
+ deg = row['degradation']
144
+ for concept in TARGETS.get(deg, []):
145
+ rho = row.get(concept)
146
+ if rho is None:
147
+ continue
148
+ total += 1
149
+ ok = rho < 0
150
+ if ok:
151
+ pass_count += 1
152
+ status = 'PASS' if ok else 'FAIL <--'
153
+ lines.append(f' {deg:<12} {concept:<28} {rho:>+7.3f} {status}')
154
+
155
+ lines += [
156
+ '',
157
+ f' Result: {pass_count}/{total} pairs PASS',
158
+ '',
159
+ ' 3 failures phan tich:',
160
+ '',
161
+ ' [1] noise -> noise_level (rho=+0.365):',
162
+ ' Regression tu v22 (-0.052, OK) -> v24 (+0.365, FAIL).',
163
+ ' gamma=2.0 + T39 (orient_coh added to dry_skin/wet_press) thay doi',
164
+ ' gradient landscape cua ScoreAggregator. Noise la degradation duy nhat',
165
+ ' target noise_level -> single-point pressure -> de bi invert.',
166
+ '',
167
+ ' [2] dry_skin -> contrast_u (rho=+0.051):',
168
+ ' Persistent qua cac phien ban (v22: +0.504). Dry_skin la degradation',
169
+ ' DUY NHAT target contrast_uniformity -> signal yeu, de bi gradient',
170
+ ' tu cac loss khac at di.',
171
+ '',
172
+ ' [3] dry_skin -> orient_coh (rho=+0.008):',
173
+ ' T39 moi them orient_coh vao dry_skin, nhung wet_press->orient_coh',
174
+ ' hoat dong tot (-0.448). Ly do: wet_press + blur deu co orientation',
175
+ ' disruption manh, nhung dry_skin tao ra orientation noise khong nhat',
176
+ ' quan -> khong du signal de orient_coh feature phan biet.',
177
+ '',
178
+ '',
179
+ '5. v25 -- T40 FIXES (dang chay)',
180
+ SEP2,
181
+ ' Thay doi so voi v24:',
182
+ '',
183
+ ' gamma: 2.0 -> 1.5',
184
+ '',
185
+ ' blur: [1, 2] -> [1, 2, 0] (them orient_coh[0])',
186
+ ' noise: [3] -> [3, 4] (them contrast_u[4])',
187
+ ' jpeg: [2, 1] -> [2, 1, 4] (them contrast_u[4])',
188
+ ' dry_skin / wet_press / occlusion: khong doi',
189
+ '',
190
+ ' Ket qua ky vong:',
191
+ ' - noise->noise_lv: +0.365 -> negative (gamma thap + noise 2-concept)',
192
+ ' - dry_skin->contrast_u: +0.051 -> negative (3 degs co-supervise contrast_u)',
193
+ ' - dry_skin->orient_coh: +0.008 -> negative (blur gives orient_coh strong signal)',
194
+ ' - Cac pairs da PASS: giu nguyen (blur/jpeg/occlusion/wet_press)',
195
+ ' - Track 2: giu PASS (KS, Pearson khong thay doi co ban)',
196
+ '',
197
+ SEP,
198
+ 'END',
199
+ SEP,
200
+ ]
201
+
202
+ txt = '\n'.join(lines)
203
+ with open('eval_results/sifq_report_v24.txt', 'w', encoding='utf-8') as f:
204
+ f.write(txt)
205
+ print(txt)
206
+ print()
207
+ print('>>> Saved: eval_results/sifq_report_v24.txt')
scripts/gen_nfiq2_proxy_scores.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate NFIQ2-proxy quality scores using image heuristics.
2
+
3
+ NFIQ2 is not available as a pip package and requires building from source.
4
+ This script approximates it using:
5
+ - Gabor filter energy at fingerprint ridge frequencies (8–16 px/cycle)
6
+ - Block-wise local contrast (RMS of intensity)
7
+ - Laplacian variance (sharpness)
8
+
9
+ The three signals are fused and rescaled to [0, 100], matching NFIQ2 convention
10
+ (higher = better quality). Scores are written as JSONL with the same schema
11
+ expected by run_eval.py:
12
+ {"image_path": "...", "q_score": 73.2}
13
+
14
+ Usage (reads image paths from an existing scores file, e.g. sifq_scores.jsonl):
15
+ python sifq/scripts/gen_nfiq2_proxy_scores.py \
16
+ --sifq-scores sifq/eval_results/sifq_scores.jsonl \
17
+ --output /tmp/nfiq2_scores.jsonl
18
+
19
+ Or scan a directory directly:
20
+ python sifq/scripts/gen_nfiq2_proxy_scores.py \
21
+ --image-dir dataset/302b/images/baseline \
22
+ --output /tmp/nfiq2_scores.jsonl
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import json
28
+ import sys
29
+ from pathlib import Path
30
+
31
+ import cv2
32
+ import numpy as np
33
+
34
+
35
+ # ---------------------------------------------------------------------------
36
+ # Quality features
37
+ # ---------------------------------------------------------------------------
38
+
39
+ def _gabor_energy(gray: np.ndarray, image_size: int = 224) -> float:
40
+ """Mean Gabor filter energy at typical fingerprint ridge frequencies."""
41
+ img = cv2.resize(gray, (image_size, image_size)).astype(np.float32) / 255.0
42
+ total = 0.0
43
+ count = 0
44
+ for theta_deg in range(0, 180, 30):
45
+ theta = np.deg2rad(theta_deg)
46
+ # wavelength in pixels: 8–16 px for 500 dpi prints at 224px crops
47
+ for wavelength in (8, 12, 16):
48
+ sigma = wavelength * 0.56
49
+ kern = cv2.getGaborKernel(
50
+ (31, 31), sigma, theta, wavelength, gamma=0.5, psi=0,
51
+ ktype=cv2.CV_32F,
52
+ )
53
+ filtered = cv2.filter2D(img, cv2.CV_32F, kern)
54
+ total += float(np.mean(filtered ** 2))
55
+ count += 1
56
+ return total / count if count else 0.0
57
+
58
+
59
+ def _local_contrast(gray: np.ndarray, block: int = 16) -> float:
60
+ """Mean RMS contrast over non-overlapping blocks."""
61
+ img = cv2.resize(gray, (224, 224)).astype(np.float32)
62
+ h, w = img.shape
63
+ vals = []
64
+ for r in range(0, h - block + 1, block):
65
+ for c in range(0, w - block + 1, block):
66
+ patch = img[r : r + block, c : c + block]
67
+ vals.append(float(np.std(patch)))
68
+ return float(np.mean(vals)) if vals else 0.0
69
+
70
+
71
+ def _laplacian_var(gray: np.ndarray) -> float:
72
+ """Variance of Laplacian — sharpness metric."""
73
+ img = cv2.resize(gray, (224, 224))
74
+ lap = cv2.Laplacian(img, cv2.CV_64F)
75
+ return float(np.var(lap))
76
+
77
+
78
+ def _quality_score(image_path: str) -> float | None:
79
+ img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
80
+ if img is None:
81
+ return None
82
+ g_energy = _gabor_energy(img)
83
+ contrast = _local_contrast(img)
84
+ lap_var = _laplacian_var(img)
85
+ # Combine: each signal contributes roughly equally after normalisation.
86
+ # Raw typical ranges (empirical, 500-dpi fingerprints at 224 px):
87
+ # g_energy ~[0.0001, 0.006]
88
+ # contrast ~[5, 60]
89
+ # lap_var ~[50, 3000]
90
+ score = (
91
+ np.clip(g_energy / 0.006, 0.0, 1.0) * 0.40 +
92
+ np.clip(contrast / 60.0, 0.0, 1.0) * 0.35 +
93
+ np.clip(lap_var / 3000.0, 0.0, 1.0) * 0.25
94
+ )
95
+ return round(float(score) * 100.0, 2)
96
+
97
+
98
+ # ---------------------------------------------------------------------------
99
+ # CLI
100
+ # ---------------------------------------------------------------------------
101
+
102
+ def parse_args() -> argparse.Namespace:
103
+ p = argparse.ArgumentParser(description="Generate NFIQ2-proxy quality scores")
104
+ src = p.add_mutually_exclusive_group(required=True)
105
+ src.add_argument(
106
+ "--sifq-scores", type=str,
107
+ help="Path to SIFQ scores JSONL; image paths are read from 'image_path' field",
108
+ )
109
+ src.add_argument(
110
+ "--image-dir", type=str,
111
+ help="Root directory to scan recursively for .png/.bmp/.wsq images",
112
+ )
113
+ p.add_argument("--output", type=str, default="/tmp/nfiq2_scores.jsonl")
114
+ p.add_argument(
115
+ "--extensions", type=str, default="png,bmp,wsq,jpg,jpeg",
116
+ help="Comma-separated file extensions to scan (only with --image-dir)",
117
+ )
118
+ return p.parse_args()
119
+
120
+
121
+ def collect_paths(args: argparse.Namespace) -> list[str]:
122
+ if args.sifq_scores:
123
+ paths: list[str] = []
124
+ with open(args.sifq_scores, encoding="utf-8") as f:
125
+ for line in f:
126
+ line = line.strip()
127
+ if line:
128
+ paths.append(json.loads(line)["image_path"])
129
+ return paths
130
+ # --image-dir
131
+ exts = {f".{e.lstrip('.')}" for e in args.extensions.split(",")}
132
+ return [
133
+ str(p) for p in Path(args.image_dir).rglob("*")
134
+ if p.suffix.lower() in exts
135
+ ]
136
+
137
+
138
+ def main() -> None:
139
+ args = parse_args()
140
+ paths = collect_paths(args)
141
+ print(f"Scoring {len(paths)} images → {args.output}")
142
+
143
+ out = Path(args.output)
144
+ out.parent.mkdir(parents=True, exist_ok=True)
145
+
146
+ skipped = 0
147
+ with out.open("w", encoding="utf-8") as fout:
148
+ for i, p in enumerate(paths):
149
+ score = _quality_score(p)
150
+ if score is None:
151
+ skipped += 1
152
+ continue
153
+ fout.write(json.dumps({"image_path": p, "q_score": score}) + "\n")
154
+ if (i + 1) % 1000 == 0:
155
+ print(f" {i + 1}/{len(paths)} (skipped={skipped})")
156
+
157
+ print(f"Done. Written {len(paths) - skipped} records, skipped {skipped}.")
158
+ print(f"Output: {out}")
159
+
160
+
161
+ if __name__ == "__main__":
162
+ main()
scripts/run_eval_v16.sh ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v16: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ VENV="$REPO_ROOT/.venv"
8
+ VERSION="v16"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ source "$VENV/bin/activate"
15
+ cd "$REPO_ROOT"
16
+
17
+ mkdir -p "$OUTDIR"
18
+
19
+ # ── Inference ──────────────────────────────────────────────────────────────
20
+ if [[ ! -f "$SCORES" ]]; then
21
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
22
+ python sifq/scripts/run_infer.py \
23
+ --checkpoint "$CKPT" \
24
+ --exclude-sensor "$EXCLUDE" \
25
+ --output "$SCORES"
26
+ echo "[eval_${VERSION}] Inference done: $SCORES"
27
+ else
28
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
29
+ fi
30
+
31
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
32
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
33
+ python sifq/scripts/run_eval.py \
34
+ --sifq-scores "$SCORES" \
35
+ --checkpoint "$CKPT" \
36
+ --out-dir "$OUTDIR" \
37
+ --exclude-sensor "$EXCLUDE" \
38
+ --skip-track1
39
+
40
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
41
+
42
+ # ── Visual score milestones ────────────────────────────────────────────────
43
+ echo "[eval_${VERSION}] Generating score milestone samples..."
44
+ python sifq/scripts/visualize_score_milestones.py \
45
+ --scores "$SCORES" \
46
+ --output "$OUTDIR/milestone_samples.png" \
47
+ --n_buckets 8
48
+
49
+ echo "[eval_${VERSION}] Milestone image: $OUTDIR/milestone_samples.png"
50
+
51
+ echo ""
52
+ echo "=== SUMMARY ==="
53
+ cat "$OUTDIR/eval_summary.json"
scripts/run_eval_v17.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v17: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ VENV="/home/aiserver/miniconda3"
8
+ VERSION="v17"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ export PATH="$VENV/bin:$PATH"
15
+ cd "$REPO_ROOT"
16
+
17
+ mkdir -p "$OUTDIR"
18
+
19
+ # ── Inference ──────────────────────────────────────────────────────────────
20
+ if [[ ! -f "$SCORES" ]]; then
21
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
22
+ python sifq/scripts/run_infer.py \
23
+ --checkpoint "$CKPT" \
24
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
25
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
26
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
27
+ --exclude-sensor "$EXCLUDE" \
28
+ --output "$SCORES"
29
+ echo "[eval_${VERSION}] Inference done: $SCORES"
30
+ else
31
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
32
+ fi
33
+
34
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
35
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
36
+ python sifq/scripts/run_eval.py \
37
+ --sifq-scores "$SCORES" \
38
+ --checkpoint "$CKPT" \
39
+ --out-dir "$OUTDIR" \
40
+ --exclude-sensor "$EXCLUDE" \
41
+ --skip-track1
42
+
43
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
44
+
45
+ # ── Visual score milestones ────────────────────────────────────────────────
46
+ echo "[eval_${VERSION}] Generating score milestone samples..."
47
+ python sifq/scripts/visualize_score_milestones.py \
48
+ --scores "$SCORES" \
49
+ --output "$OUTDIR/milestone_samples.png" \
50
+ --n_buckets 8 \
51
+ --version "$VERSION"
52
+
53
+ echo "[eval_${VERSION}] Milestone image: $OUTDIR/milestone_samples.png"
54
+
55
+ echo ""
56
+ echo "=== SUMMARY ==="
57
+ cat "$OUTDIR/eval_summary.json"
scripts/run_eval_v18.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v18: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v18"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
51
+
52
+ echo "[eval_${VERSION}] Milestone image: $OUTDIR/milestone_samples.png"
53
+
54
+ echo ""
55
+ echo "=== SUMMARY ==="
56
+ cat "$OUTDIR/eval_summary.json"
scripts/run_eval_v19.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v19: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v19"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
51
+
52
+ echo "[eval_${VERSION}] Milestone image: $OUTDIR/milestone_samples.png"
53
+
54
+ echo ""
55
+ echo "=== SUMMARY ==="
56
+ cat "$OUTDIR/eval_summary.json"
scripts/run_eval_v20.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v20: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v20"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
51
+
52
+ echo "[eval_${VERSION}] Milestone image: $OUTDIR/milestone_samples.png"
53
+
54
+ echo ""
55
+ echo "=== SUMMARY ==="
56
+ cat "$OUTDIR/eval_summary.json"
scripts/run_eval_v21.sh ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v21: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v21"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
51
+
52
+ echo "[eval_${VERSION}] Milestone image: $OUTDIR/milestone_samples.png"
53
+
54
+ echo ""
55
+ echo "=== SUMMARY ==="
56
+ cat "$OUTDIR/eval_summary.json"
scripts/run_eval_v23.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v23: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v23"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
scripts/run_eval_v26.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v26: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v26"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
scripts/run_eval_v27.sh ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v27: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v27"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
19
+ python sifq/scripts/run_infer.py \
20
+ --checkpoint "$CKPT" \
21
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
22
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
23
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
24
+ --exclude-sensor "$EXCLUDE" \
25
+ --output "$SCORES"
26
+
27
+ # ── Inference ──────────────────────────────────────────────────────────────
28
+ # if [[ ! -f "$SCORES" ]]; then
29
+ # echo "[eval_${VERSION}] Running inference on $CKPT ..."
30
+ # python sifq/scripts/run_infer.py \
31
+ # --checkpoint "$CKPT" \
32
+ # --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
33
+ # --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
34
+ # --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
35
+ # --exclude-sensor "$EXCLUDE" \
36
+ # --output "$SCORES"
37
+ # echo "[eval_${VERSION}] Inference done: $SCORES"
38
+ # else
39
+ # echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
40
+ # fi
41
+
42
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
43
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
44
+ python sifq/scripts/run_eval.py \
45
+ --sifq-scores "$SCORES" \
46
+ --checkpoint "$CKPT" \
47
+ --out-dir "$OUTDIR" \
48
+ --exclude-sensor "$EXCLUDE" \
49
+ --skip-track1
50
+
51
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
52
+
53
+ # ── Visual score milestones ────────────────────────────────────────────────
54
+ echo "[eval_${VERSION}] Generating score milestone samples..."
55
+ python sifq/scripts/visualize_score_milestones.py \
56
+ --scores "$SCORES" \
57
+ --output "$OUTDIR/milestone_samples.png" \
58
+ --n_buckets 8 \
59
+ --version "$VERSION"
scripts/run_eval_v28.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v28: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v28"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
scripts/run_eval_v29.sh ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v29: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v29"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
scripts/run_eval_v31.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v31: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v31"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
51
+
52
+ echo "[eval_${VERSION}] All done."
scripts/run_eval_v32.sh ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Eval v32: inference + Track 2 + Track 4 + visual score milestones.
3
+
4
+ set -euo pipefail
5
+
6
+ REPO_ROOT="/home/aiserver/works/fingerprint"
7
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
8
+ VERSION="v32"
9
+ CKPT="$REPO_ROOT/sifq/checkpoints/${VERSION}/last.pt"
10
+ SCORES="$REPO_ROOT/sifq/eval_results/sifq_scores_${VERSION}.jsonl"
11
+ OUTDIR="$REPO_ROOT/sifq/eval_results/${VERSION}"
12
+ EXCLUDE="R_1000_slap,R_500_slap,S_500_slap"
13
+
14
+ cd "$REPO_ROOT"
15
+
16
+ mkdir -p "$OUTDIR"
17
+
18
+ # ── Inference ──────────────────────────────────────────────────────────────
19
+ if [[ ! -f "$SCORES" ]]; then
20
+ echo "[eval_${VERSION}] Running inference on $CKPT ..."
21
+ python sifq/scripts/run_infer.py \
22
+ --checkpoint "$CKPT" \
23
+ --root-302a "$REPO_ROOT/dataset/302a/images/challengers" \
24
+ --root-302b "$REPO_ROOT/dataset/302b/images/baseline" \
25
+ --root-302d "$REPO_ROOT/dataset/nist_302d/images/auxiliary" \
26
+ --exclude-sensor "$EXCLUDE" \
27
+ --output "$SCORES"
28
+ echo "[eval_${VERSION}] Inference done: $SCORES"
29
+ else
30
+ echo "[eval_${VERSION}] Scores file already exists: $SCORES (skipping inference)"
31
+ fi
32
+
33
+ # ── Evaluation (Track 2 + Track 4) ────────────────────────────────────────
34
+ echo "[eval_${VERSION}] Running evaluation (Track 2 + Track 4, exclude: $EXCLUDE)..."
35
+ python sifq/scripts/run_eval.py \
36
+ --sifq-scores "$SCORES" \
37
+ --checkpoint "$CKPT" \
38
+ --out-dir "$OUTDIR" \
39
+ --exclude-sensor "$EXCLUDE" \
40
+ --skip-track1
41
+
42
+ echo "[eval_${VERSION}] Eval done. Results in $OUTDIR"
43
+
44
+ # ── Visual score milestones ────────────────────────────────────────────────
45
+ echo "[eval_${VERSION}] Generating score milestone samples..."
46
+ python sifq/scripts/visualize_score_milestones.py \
47
+ --scores "$SCORES" \
48
+ --output "$OUTDIR/milestone_samples.png" \
49
+ --n_buckets 8 \
50
+ --version "$VERSION"
51
+
52
+ echo "[eval_${VERSION}] All done."
scripts/run_infer.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Inference script: run trained SIFQ on a dataset and save per-image scores.
2
+
3
+ Output JSON format (one line per image):
4
+ {"image_path": ..., "q_score": 73.2, "concepts": [0.8, 0.6, ...],
5
+ "identity_id": "00002401", "finger_id": "F07", "sensor_id": "U_500_roll"}
6
+
7
+ Usage:
8
+ python scripts/run_infer.py --checkpoint checkpoints/v16/last.pt \\
9
+ --root-302b dataset/302b/images/baseline \\
10
+ --output /tmp/sifq_scores.jsonl
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import torch
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+ SRC_ROOT = ROOT / "src"
23
+ if str(SRC_ROOT) not in sys.path:
24
+ sys.path.insert(0, str(SRC_ROOT))
25
+
26
+ from data.nist302_loader import NIST302Loader, NIST302Paths
27
+ from models.aggregator import ScoreAggregator
28
+ from models.backbone import SIFQBackbone
29
+ from models.concept_head import ConceptHead, SpatialConceptHead
30
+ from models.sensor_discriminator import SensorDiscriminator
31
+ from models.sifq import SIFQ
32
+
33
+
34
+ def load_model(checkpoint_path: str, device: torch.device, num_sensors: int = 10) -> SIFQ:
35
+ ckpt = torch.load(checkpoint_path, map_location=device, weights_only=False)
36
+ # Infer num_sensors from checkpoint metrics ("n_sensors" key saved by train_sifq.py)
37
+ num_sensors = ckpt.get("metrics", {}).get("n_sensors", num_sensors)
38
+
39
+ backbone = SIFQBackbone(model_name="tiny_vit_5m_224.dist_in22k", pretrained=False)
40
+ # Detect architecture from saved config — spatial head was introduced in v27
41
+ _use_spatial = ckpt.get("config", {}).get("spatial_concept_head", False)
42
+ if _use_spatial:
43
+ concept_head = SpatialConceptHead(in_dim=backbone.feature_dim)
44
+ else:
45
+ concept_head = ConceptHead(in_dim=backbone.feature_dim)
46
+ aggregator = ScoreAggregator(k=6)
47
+ sensor_disc = SensorDiscriminator(in_dim=backbone.feature_dim, num_sensors=num_sensors)
48
+ model = SIFQ(backbone, concept_head, aggregator, sensor_disc)
49
+ model.load_state_dict(ckpt["model"], strict=True)
50
+ model.to(device).eval()
51
+ return model
52
+
53
+
54
+ def parse_args() -> argparse.Namespace:
55
+ p = argparse.ArgumentParser(description="SIFQ inference — generate quality scores")
56
+ p.add_argument("--checkpoint", type=str, required=True,
57
+ help="Path to trained SIFQ checkpoint (last.pt or best.pt)")
58
+ p.add_argument("--root-302a", type=str, default="",
59
+ help="Root for NIST SD302-A challengers (optional)")
60
+ p.add_argument("--root-302b", type=str,
61
+ default="/home/aiserver/works/fingerprint/dataset/302b/images/baseline",
62
+ help="Root for NIST SD302-B baseline")
63
+ p.add_argument("--root-302d", type=str,
64
+ default="/home/aiserver/works/fingerprint/dataset/nist_302d/images/auxiliary",
65
+ help="Root for NIST SD302-D auxiliary")
66
+ p.add_argument("--image-size", type=int, default=224)
67
+ p.add_argument("--batch-size", type=int, default=32)
68
+ p.add_argument("--num-workers", type=int, default=2)
69
+ p.add_argument("--output", type=str, default="/tmp/sifq_scores.jsonl",
70
+ help="Output JSONL file path")
71
+ p.add_argument("--max-samples", type=int, default=-1,
72
+ help="Cap number of images for quick eval; -1 means all")
73
+ p.add_argument("--exclude-sensor", type=str, default="",
74
+ help="Comma-separated sensor_ids to skip inference on. "
75
+ "E.g. 'R_1000_slap,R_500_slap,S_500_slap'")
76
+ return p.parse_args()
77
+
78
+
79
+ @torch.no_grad()
80
+ def main() -> None:
81
+ args = parse_args()
82
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
83
+
84
+ # --- Load model ---
85
+ print(f"Loading checkpoint: {args.checkpoint}")
86
+ model = load_model(args.checkpoint, device)
87
+ print(f"Model loaded. Device: {device}")
88
+
89
+ # --- Discover records ---
90
+ paths = NIST302Paths(
91
+ root_302a=args.root_302a or "",
92
+ root_302b=args.root_302b,
93
+ root_302d=args.root_302d,
94
+ )
95
+ loader = NIST302Loader(image_size=args.image_size)
96
+ records = loader.discover(paths)
97
+ if args.exclude_sensor:
98
+ excluded = {s.strip() for s in args.exclude_sensor.split(",") if s.strip()}
99
+ records = [r for r in records if r["sensor_id"] not in excluded]
100
+ print(f"After excluding sensors {excluded}: {len(records)} records remain")
101
+ if args.max_samples > 0:
102
+ records = records[:args.max_samples]
103
+ print(f"Discovered {len(records)} records")
104
+
105
+ # --- Batch inference ---
106
+ output_path = Path(args.output)
107
+ output_path.parent.mkdir(parents=True, exist_ok=True)
108
+
109
+ batch_records: list[dict] = []
110
+ batch_tensors: list[torch.Tensor] = []
111
+
112
+ def flush_batch() -> None:
113
+ if not batch_tensors:
114
+ return
115
+ images = torch.stack(batch_tensors, dim=0).to(device)
116
+ outputs = model(images)
117
+ scores = outputs["score"].squeeze(-1).cpu().tolist()
118
+ concepts_batch = outputs["concepts"].cpu().tolist()
119
+ for rec, q, conc in zip(batch_records, scores, concepts_batch):
120
+ row = {
121
+ "image_path": rec["image_path"],
122
+ "identity_id": rec["identity_id"],
123
+ "finger_id": rec["finger_id"],
124
+ "sensor_id": rec["sensor_id"],
125
+ "dataset": rec["dataset"],
126
+ "q_score": round(float(q), 3),
127
+ "concepts": [round(float(c), 4) for c in conc],
128
+ }
129
+ with open(output_path, "a", encoding="utf-8") as f:
130
+ f.write(json.dumps(row) + "\n")
131
+ batch_records.clear()
132
+ batch_tensors.clear()
133
+
134
+ # Clear output file
135
+ output_path.write_text("")
136
+
137
+ n_done = 0
138
+ for sample in loader.iter_samples(records):
139
+ batch_records.append({
140
+ "image_path": sample["image_path"],
141
+ "identity_id": sample["identity_id"],
142
+ "finger_id": sample["finger_id"],
143
+ "sensor_id": sample["sensor_id"],
144
+ "dataset": sample["dataset"],
145
+ })
146
+ batch_tensors.append(sample["image"])
147
+ if len(batch_tensors) >= args.batch_size:
148
+ flush_batch()
149
+ n_done += args.batch_size
150
+ if n_done % 500 == 0:
151
+ print(f" {n_done}/{len(records)} done")
152
+
153
+ flush_batch()
154
+ print(f"Done. Scores saved to: {output_path}")
155
+
156
+
157
+ if __name__ == "__main__":
158
+ main()
scripts/run_smoke.sh ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Smoke test: 1 epoch, 50 samples, no multiprocessing
3
+ # Verifies the full pipeline runs end-to-end in ~1-2 minutes
4
+ set -euo pipefail
5
+
6
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
7
+ ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
8
+ VENV="$ROOT/../.venv"
9
+
10
+ [[ -f "$VENV/bin/activate" ]] && source "$VENV/bin/activate"
11
+
12
+ python "$SCRIPT_DIR/train_sifq.py" \
13
+ --epochs 1 \
14
+ --batch-size 8 \
15
+ --max-train-samples 80 \
16
+ --num-workers 0 \
17
+ --save-dir "$ROOT/checkpoints/smoke" \
18
+ "$@"
scripts/run_train_v16.sh ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # v16 training — Fix score collapse / no discrimination từ v15.
3
+ #
4
+ # Root cause analysis (v15 failure):
5
+ #
6
+ # Tất cả ảnh được score gần như giống nhau (range 24–56, thay vì 0–100).
7
+ # Model không phân biệt được ảnh tốt/xấu.
8
+ #
9
+ # Nguyên nhân chính: stats=None trong mọi lần gọi loss_mat().
10
+ #
11
+ # Khi stats=None:
12
+ # q_mat = raw cosine ≈ 0.85 cho mọi ảnh (MDGT quality-robust)
13
+ # → model tối ưu pred_score → (0.85/2 + 0.5)×100 ≈ 92.5 cho tất cả
14
+ # → L_spread kéo về [10,90], L_mat kéo về 92.5
15
+ # → equilibrium tại q_mean ≈ 52 không thay đổi suốt 60 epoch
16
+ #
17
+ # v16 fixes:
18
+ # T31a — Per-identity cosine stats (compute_identity_cos_stats):
19
+ # Sau khi tính prototype, chạy second pass để tính (mean_cos, std_cos)
20
+ # per identity. Pass stats vào loss_mat() → target được normalize:
21
+ # q_mat = tanh((cos - mu_i) / sigma_i)
22
+ # Ảnh tốt hơn trung bình của identity → target > 0 → score > 50.
23
+ # Ảnh kém hơn → target < 0 → score < 50.
24
+ # L_mat và L_spread giờ CÙNG chiều thay vì conflict.
25
+ #
26
+ # T31b — tanh scaling trong _compute_q_mat:
27
+ # tanh maps z ∈ (-∞,+∞) về (-1,1), tương thích với
28
+ # pred_normalized = (score/100 - 0.5) × 2 ∈ [-1,1].
29
+ # Không cần clamp thủ công, không có extreme target.
30
+ #
31
+ # T31c — Tăng W_SPREAD từ 2.0 → 4.0:
32
+ # Với teacher target đã zero-centred, tăng spread weight
33
+ # giúp model học spread nhanh hơn mà không conflict.
34
+ #
35
+ # T31d — deg-every-n-steps 1 (thay vì 2):
36
+ # L_deg mỗi step = 2× signal so với v15. FVC-only ranking.
37
+ #
38
+ # Train từ đầu, 60 epochs, LR=1e-4 cosine.
39
+
40
+ set -euo pipefail
41
+
42
+ REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
43
+ source "${REPO_ROOT}/.venv/bin/activate"
44
+
45
+ VERSION="v16"
46
+ SAVE_DIR="${REPO_ROOT}/sifq/checkpoints/${VERSION}"
47
+ LOG_FILE="${REPO_ROOT}/sifq/logs/train_${VERSION}.log"
48
+ EVAL_SCRIPT="${REPO_ROOT}/sifq/scripts/run_eval_${VERSION}.sh"
49
+
50
+ python "${REPO_ROOT}/sifq/scripts/train_sifq.py" \
51
+ --root-302a "${REPO_ROOT}/dataset/302a/images/challengers" \
52
+ --root-302b "${REPO_ROOT}/dataset/302b/images/baseline" \
53
+ --root-302d "${REPO_ROOT}/dataset/nist_302d/images/auxiliary" \
54
+ --root-fvc2002 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2002" \
55
+ --root-fvc2004 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2004" \
56
+ --root-polyu "${REPO_ROOT}/dataset/PolyU" \
57
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
58
+ --mdgt-checkpoint "${REPO_ROOT}/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt" \
59
+ --epochs 60 \
60
+ --batch-size 128 \
61
+ --image-size 224 \
62
+ --lr 1e-4 \
63
+ --spread-mode uniform \
64
+ --spread-weight 4.0 \
65
+ --concept-deg-gamma 2.0 \
66
+ --sd302-concept-weight 1.0 \
67
+ --deg-every-n-steps 2 \
68
+ --min-sigma 0.02 \
69
+ --max-train-samples -1 \
70
+ --num-workers 8 \
71
+ --gpus 0 \
72
+ --save-dir "${SAVE_DIR}"
73
+
74
+ echo "[auto-eval] Training done. Starting eval ${VERSION}..."
75
+ bash "${EVAL_SCRIPT}" >> "${LOG_FILE}" 2>&1
scripts/run_train_v17.sh ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # v17 training — T32: fix score collapse from v16 (L_mat vs L_pair conflict).
3
+ #
4
+ # Root cause analysis (v16 failure):
5
+ #
6
+ # Score collapse nghiêm trọng hơn v15: q_std=0.33 ở inference (range 46.9–50.5).
7
+ # Training q_std=15.6 bề ngoài ổn nhưng KHÔNG phản ánh thực tế:
8
+ # - q_std=15.6 được tạo bởi FVC images trong training batch (có quality variation)
9
+ # - SD302 images trong training cũng bị collapse về ~50 nhưng bị che bởi FVC
10
+ # - Inference chỉ chạy trên SD302 → q_std=0.33 (hoàn toàn sụp đổ)
11
+ #
12
+ # Root cause (T32): Per-identity stats (T31) tạo L_mat targets conflict trực tiếp
13
+ # với L_pair:
14
+ # - L_mat (T31b): q_mat = tanh((cos−μᵢ)/σᵢ) → muốn score khác nhau cho ảnh
15
+ # khác nhau của cùng identity (within-identity variation)
16
+ # - L_pair: |Q(s1)−Q(s2)| ≤ 0.05 → ép tất cả ảnh cùng identity có score
17
+ # giống nhau (within-identity uniformity)
18
+ # - Hai loss xung đột → model giải quyết bằng cách output ~50 cho tất cả
19
+ # SD302 images. Training q_std=15.6 driven by FVC (no L_pair conflict).
20
+ # - Inference (SD302 only): q_std=0.33, range 46.9–50.5.
21
+ # - KS=0.527 (tệ hơn v14=0.263): residual sensor bias giữa roll/flat sensors
22
+ # trong range tiny (0.5pt) với intra-sensor std ~0.1 → CDF shapes khác nhau.
23
+ #
24
+ # v17 fix (T32): FVC-only per-identity stats trong L_mat
25
+ #
26
+ # T32a — compute_identity_cos_stats(fvc_only=True):
27
+ # Chỉ tính (mean_cos, std_cos) cho FVC identities.
28
+ # FVC không có cross-sensor pairs → L_pair=0 → không conflict với L_mat.
29
+ # FVC q_mat = tanh((cos−μ_fvc)/σ_fvc) → proper quality ordering ✅
30
+ #
31
+ # T32b — _compute_q_mat fallback to raw cosine:
32
+ # SD302 identities KHÔNG có trong stats → fallback về raw cosine (~0.85).
33
+ # Đây là v14 behaviour (stats=None) đã cho KS=0.263 ✅.
34
+ # Không còn conflict với L_pair → SD302 scores có thể spread.
35
+ #
36
+ # Giữ nguyên từ v16:
37
+ # - W_SPREAD=4.0 (T31c)
38
+ # - concept_deg_gamma=2.0 (T30a)
39
+ # - sd302_concept_weight=1.0 (T30b)
40
+ # - deg-every-n-steps=2
41
+ #
42
+ # Expected improvements vs v16:
43
+ # - Score range: 0–100 (thay vì 46.9–50.5)
44
+ # - KS: ≤0.27 (target v14 = 0.263)
45
+ # - Pearson: ≥0.25 (target v14 = 0.294)
46
+ # - FVC quality ordering: tốt hơn v14 (per-identity tanh targets)
47
+ #
48
+ # Train từ đầu, 60 epochs, LR=1e-4 cosine.
49
+
50
+ set -euo pipefail
51
+
52
+ REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
53
+ source "${REPO_ROOT}/sifq/.venv/bin/activate"
54
+
55
+ VERSION="v17"
56
+ SAVE_DIR="${REPO_ROOT}/sifq/checkpoints/${VERSION}"
57
+ LOG_FILE="${REPO_ROOT}/sifq/logs/train_${VERSION}.log"
58
+ EVAL_SCRIPT="${REPO_ROOT}/sifq/scripts/run_eval_${VERSION}.sh"
59
+
60
+ mkdir -p "${REPO_ROOT}/sifq/logs"
61
+
62
+ python "${REPO_ROOT}/sifq/scripts/train_sifq.py" \
63
+ --root-302a "${REPO_ROOT}/dataset/302a/images/challengers" \
64
+ --root-302b "${REPO_ROOT}/dataset/302b/images/baseline" \
65
+ --root-302d "${REPO_ROOT}/dataset/nist_302d/images/auxiliary" \
66
+ --root-fvc2002 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2002" \
67
+ --root-fvc2004 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2004" \
68
+ --root-polyu "${REPO_ROOT}/dataset/PolyU" \
69
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
70
+ --mdgt-checkpoint "${REPO_ROOT}/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt" \
71
+ --epochs 60 \
72
+ --batch-size 128 \
73
+ --image-size 224 \
74
+ --lr 1e-4 \
75
+ --spread-mode uniform \
76
+ --spread-weight 4.0 \
77
+ --concept-deg-gamma 2.0 \
78
+ --sd302-concept-weight 1.0 \
79
+ --deg-every-n-steps 2 \
80
+ --min-sigma 0.02 \
81
+ --max-train-samples -1 \
82
+ --num-workers 8 \
83
+ --gpus 0 \
84
+ --save-dir "${SAVE_DIR}"
85
+
86
+ echo "[auto-eval] Training done. Starting eval ${VERSION}..."
87
+ bash "${EVAL_SCRIPT}" >> "${LOG_FILE}" 2>&1
scripts/run_train_v18.sh ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # v18 training — T33: revert to v14 loss design + include SD302-A.
3
+ #
4
+ # Root cause analysis (v17 failure):
5
+ #
6
+ # Score collapse persists despite T32 fix: all SD302 images → ~52.7, q_std=0.60.
7
+ # Training q_std=16.59 looks healthy but driven by FVC only (same pattern as v15/v16).
8
+ #
9
+ # Deeper root cause (T33):
10
+ # T32 removed explicit L_mat vs L_pair conflict (SD302 gets raw cosine fallback),
11
+ # but FVC still gets tanh-normalised targets (high variation) while SD302 gets
12
+ # constant raw cosine targets. Model learns to distinguish "FVC mode" (variable)
13
+ # from "SD302 mode" (constant) — dataset shortcut. At inference (SD302 only): collapse.
14
+ #
15
+ # Additional factors in v15–v17 that didn't exist in v14 (which worked):
16
+ # - W_SPREAD 2.0 → 4.0 (stronger spread pressure amplifies FVC/SD302 asymmetry)
17
+ # - concept_deg_gamma 0.5/1.0 → 2.0 (stronger concept loss may destabilise SD302 features)
18
+ # - sd302_concept_weight 0 → 1.0 (T30b concept deg on SD302 adds noise to SD302 features)
19
+ # - deg-every-n-steps 4 → 2 (more frequent deg steps = more FVC-specific gradients)
20
+ #
21
+ # v18 fix (T33): revert all v15–v17 additions, add SD302-A as new data
22
+ #
23
+ # T33a — --no-mat-stats: Disable per-identity cosine stats entirely.
24
+ # ALL identities (FVC + SD302) use raw cosine as L_mat target (v14 behaviour).
25
+ # Eliminates FVC/SD302 quality signal asymmetry. Model must treat both datasets
26
+ # similarly — SD302 cannot shortcut to constant output.
27
+ #
28
+ # T33b — W_SPREAD = 2.0: Revert from 4.0. Lower spread pressure → backbone retains
29
+ # more discriminative features for SD302. v14 used ~2.0.
30
+ #
31
+ # T33c — concept_deg_gamma = 0.5: Revert from 2.0 to v14 default.
32
+ #
33
+ # T33d — sd302_concept_weight = 0.0: Disable SD302 concept degradation (default, v14).
34
+ #
35
+ # T33e — deg-every-n-steps = 4: Revert to original (v14). Fewer FVC-only deg steps.
36
+ #
37
+ # NEW vs v14 — SD302-A: Include dataset/302a/images/challengers (13,630 images, sensors A-H).
38
+ # More cross-sensor pairs for L_sens. More GRL training signal. Better coverage.
39
+ #
40
+ # Expected improvements vs v14:
41
+ # - Score spread: q_std > 10 at inference (like v14 ~15)
42
+ # - KS: ~0.26 (v14 baseline), potentially better with 8 new SD302-A sensors
43
+ # - Pearson: ~0.29 (v14 baseline)
44
+ # - More sensor-type coverage (8 SD302-A sensors vs 4 SD302-B + 4 SD302-D in v14)
45
+ #
46
+ # Train from scratch, 60 epochs, LR=1e-4 cosine.
47
+
48
+ set -euo pipefail
49
+
50
+ REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
51
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
52
+
53
+ VERSION="v18"
54
+ SAVE_DIR="${REPO_ROOT}/sifq/checkpoints/${VERSION}"
55
+ LOG_FILE="${REPO_ROOT}/sifq/logs/train_${VERSION}.log"
56
+ EVAL_SCRIPT="${REPO_ROOT}/sifq/scripts/run_eval_${VERSION}.sh"
57
+
58
+ mkdir -p "${REPO_ROOT}/sifq/logs"
59
+
60
+ python "${REPO_ROOT}/sifq/scripts/train_sifq.py" \
61
+ --root-302a "${REPO_ROOT}/dataset/302a/images/challengers" \
62
+ --root-302b "${REPO_ROOT}/dataset/302b/images/baseline" \
63
+ --root-302d "${REPO_ROOT}/dataset/nist_302d/images/auxiliary" \
64
+ --root-fvc2002 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2002" \
65
+ --root-fvc2004 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2004" \
66
+ --root-polyu "${REPO_ROOT}/dataset/PolyU" \
67
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
68
+ --mdgt-checkpoint "${REPO_ROOT}/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt" \
69
+ --epochs 60 \
70
+ --batch-size 128 \
71
+ --image-size 224 \
72
+ --lr 1e-4 \
73
+ --spread-mode uniform \
74
+ --spread-weight 2.0 \
75
+ --concept-deg-gamma 0.5 \
76
+ --sd302-concept-weight 0.0 \
77
+ --deg-every-n-steps 4 \
78
+ --no-mat-stats \
79
+ --max-train-samples -1 \
80
+ --num-workers 8 \
81
+ --gpus 0 \
82
+ --save-dir "${SAVE_DIR}"
83
+
84
+ echo "[auto-eval] Training done. Starting eval ${VERSION}..."
85
+ bash "${EVAL_SCRIPT}" >> "${LOG_FILE}" 2>&1
scripts/run_train_v19.sh ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # v19 training — T34: true revert to v14 hyperparameters (fix v18 misconfiguration).
3
+ #
4
+ # Root cause analysis (v18 failure):
5
+ #
6
+ # v18 claimed to "revert to v14 design" but used WRONG hyperparameters:
7
+ # v18: --spread-weight 2.0 (v14 actual: 3.0 ← wrong)
8
+ # v18: --deg-every-n-steps 4 (v14 actual: 2 ← wrong)
9
+ # v18 comments were incorrect — v14 actually used spread-weight=3.0 and
10
+ # deg-every-n-steps=2 (confirmed via diff of original run_train_v14.sh).
11
+ #
12
+ # These weaker settings were the root cause of v18 score collapse (q_std≈0.01):
13
+ # - L_spread at 2.0 was insufficient to force per-image quality differentiation
14
+ # - L_deg at every 4 steps provided half the degradation grounding vs v14
15
+ # - Combined result: backbone learned no quality-discriminative features → inference collapse
16
+ #
17
+ # v19 fix (T34): use v14 ACTUAL hyperparameters
18
+ #
19
+ # T34a — --spread-weight 3.0: Restore v14 value (v18 used 2.0, docs erroneously said "v14=~2.0").
20
+ # Stronger L_spread gradient forces backbone to differentiate quality across images.
21
+ #
22
+ # T34b — --deg-every-n-steps 2: Restore v14 value (v18 used 4).
23
+ # 2× more frequent L_deg provides stronger ordinal quality signal.
24
+ #
25
+ # KEPT from v18:
26
+ # - --no-mat-stats: Required to reproduce v14 pre-T31 behavior with current code.
27
+ # v14 predated per-identity cosine stats (T31). Current code default tries to compute
28
+ # stats; --no-mat-stats disables this, giving same raw cosine L_mat as original v14.
29
+ # - --sd302-concept-weight 0.0: disable SD302 concept-only L_deg (v14 default)
30
+ # - --concept-deg-gamma 0.5: v14 default
31
+ # - SD302-A included (302a challengers): added in v18, kept here for better sensor coverage
32
+ # - --batch-size 128 on --gpus 0 (v14 used 96×2 GPU, effective per-GPU is similar)
33
+ #
34
+ # Expected improvements vs v18:
35
+ # - Score spread: q_std > 10 at inference (like v14 ~15.5)
36
+ # - Track 2 mean_KS: ~0.26 (v14 baseline, not false positive like v18)
37
+ # - Track 2 Pearson: ~0.29 (v14 baseline)
38
+ # - Score range: 10–90 (vs v18: 54.62–54.65 collapsed)
39
+ #
40
+ # Train from scratch, 60 epochs, LR=1e-4 cosine.
41
+
42
+ set -euo pipefail
43
+
44
+ REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
45
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
46
+
47
+ VERSION="v19"
48
+ SAVE_DIR="${REPO_ROOT}/sifq/checkpoints/${VERSION}"
49
+ LOG_FILE="${REPO_ROOT}/sifq/logs/train_${VERSION}.log"
50
+ EVAL_SCRIPT="${REPO_ROOT}/sifq/scripts/run_eval_${VERSION}.sh"
51
+
52
+ mkdir -p "${REPO_ROOT}/sifq/logs"
53
+
54
+ python "${REPO_ROOT}/sifq/scripts/train_sifq.py" \
55
+ --root-302a "${REPO_ROOT}/dataset/302a/images/challengers" \
56
+ --root-302b "${REPO_ROOT}/dataset/302b/images/baseline" \
57
+ --root-302d "${REPO_ROOT}/dataset/nist_302d/images/auxiliary" \
58
+ --root-fvc2002 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2002" \
59
+ --root-fvc2004 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2004" \
60
+ --root-polyu "${REPO_ROOT}/dataset/PolyU" \
61
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
62
+ --mdgt-checkpoint "${REPO_ROOT}/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt" \
63
+ --epochs 60 \
64
+ --batch-size 128 \
65
+ --image-size 224 \
66
+ --lr 1e-4 \
67
+ --spread-mode uniform \
68
+ --spread-weight 3.0 \
69
+ --concept-deg-gamma 0.5 \
70
+ --sd302-concept-weight 0.0 \
71
+ --deg-every-n-steps 2 \
72
+ --no-mat-stats \
73
+ --max-train-samples -1 \
74
+ --num-workers 8 \
75
+ --gpus 0 \
76
+ --save-dir "${SAVE_DIR}"
77
+
78
+ echo "[auto-eval] Training done. Starting eval ${VERSION}..."
79
+ bash "${EVAL_SCRIPT}" >> "${LOG_FILE}" 2>&1
scripts/run_train_v20.sh ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # v20 training — T35: full prototypes + L_deg on SD302.
3
+ #
4
+ # Root cause analysis (v19 failure — same collapse as v15–v18):
5
+ #
6
+ # v19 was supposed to reproduce v14 exactly but STILL collapsed (q_std≈0.01
7
+ # at inference, all scores 53.1x). This means the "v14 hyperparameter diff"
8
+ # explanation (spread-weight and deg-every-n-steps) was wrong. Two deeper root
9
+ # causes identified by analysing every code change since v14:
10
+ #
11
+ # Root cause 1 — Truncated prototypes (T35a):
12
+ # v14's code had NO --proto-max-batches cap; prototypes were computed on the
13
+ # full dataset (42,683 images, ~334 batches). When this parameter was added
14
+ # (default 150 batches = ~19,200 images, 45% of data), SD302 identities went
15
+ # from having full 19-sensor multi-sensor prototypes to 2–3 sensor partial
16
+ # prototypes.
17
+ # Full prototype → raw cosine varies with image quality across all sensors
18
+ # (quality-discriminative, sensor-invariant).
19
+ # Partial proto → raw cosine correlated with which sensors are in the
20
+ # prototype window (sensor-biased, quality-agnostic) →
21
+ # no per-image quality gradient for SD302 → collapse.
22
+ #
23
+ # Root cause 2 — FVC-only L_deg (T27, unchanged since v13):
24
+ # T27 reverted T17 (L_deg on all images) because clean SD302 images anchored
25
+ # at ~28 when there was no per-dataset spread. T27 itself introduced
26
+ # per-dataset L_spread_ds. Now that L_spread_ds forces SD302 to span [10,90],
27
+ # re-enabling full L_rank for SD302 is safe: L_spread_ds prevents the
28
+ # anchoring, and L_rank orders SD302 images by their synthetic degradation
29
+ # response (a proxy for ridge clarity / quality). This gives the ONLY stable
30
+ # per-image quality signal for SD302 at inference.
31
+ #
32
+ # v20 fixes (T35):
33
+ # T35a — --proto-max-batches 0: Compute prototypes on the full training set.
34
+ # Full multi-sensor prototypes restore per-image L_mat quality signal
35
+ # for SD302 (raw cosine varies with quality, not sensor).
36
+ # Cost: ~10–15 extra minutes at epoch 0 for prototype computation.
37
+ #
38
+ # T35b — --deg-include-sd302: Apply full L_deg (L_rank + L_concept) to SD302
39
+ # images in addition to FVC. L_spread_ds (present since v13) prevents
40
+ # score anchoring at ~28. Provides robust per-image ordinal quality
41
+ # grounding for SD302 independent of root cause 1.
42
+ #
43
+ # All other settings kept from v19 (which correctly reproduced v14 hyperparams):
44
+ # --spread-weight 3.0 --deg-every-n-steps 2 --no-mat-stats
45
+ # --concept-deg-gamma 0.5 --sd302-concept-weight 0.0
46
+ # --batch-size 128 --gpus 0 --epochs 60
47
+ #
48
+ # Expected improvements vs v19:
49
+ # q_std (inference) : >12 (v19: ~0.01)
50
+ # Score range : 10–90 (v19: 53.10–53.16)
51
+ # Track 2 mean_KS : ≤0.27 real (v19: 0.3706 with collapsed distributions)
52
+ # Track 2 Pearson : ≥0.25 (v19: -0.0123)
53
+
54
+ set -euo pipefail
55
+
56
+ REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
57
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
58
+
59
+ VERSION="v20"
60
+ SAVE_DIR="${REPO_ROOT}/sifq/checkpoints/${VERSION}"
61
+ LOG_FILE="${REPO_ROOT}/sifq/logs/train_${VERSION}.log"
62
+ EVAL_SCRIPT="${REPO_ROOT}/sifq/scripts/run_eval_${VERSION}.sh"
63
+
64
+ mkdir -p "${REPO_ROOT}/sifq/logs"
65
+
66
+ python "${REPO_ROOT}/sifq/scripts/train_sifq.py" \
67
+ --root-302a "${REPO_ROOT}/dataset/302a/images/challengers" \
68
+ --root-302b "${REPO_ROOT}/dataset/302b/images/baseline" \
69
+ --root-302d "${REPO_ROOT}/dataset/nist_302d/images/auxiliary" \
70
+ --root-fvc2002 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2002" \
71
+ --root-fvc2004 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2004" \
72
+ --root-polyu "${REPO_ROOT}/dataset/PolyU" \
73
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
74
+ --mdgt-checkpoint "${REPO_ROOT}/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt" \
75
+ --epochs 60 \
76
+ --batch-size 128 \
77
+ --image-size 224 \
78
+ --lr 1e-4 \
79
+ --spread-mode uniform \
80
+ --spread-weight 3.0 \
81
+ --concept-deg-gamma 0.5 \
82
+ --sd302-concept-weight 0.0 \
83
+ --deg-every-n-steps 2 \
84
+ --deg-include-sd302 \
85
+ --no-mat-stats \
86
+ --proto-max-batches 0 \
87
+ --max-train-samples -1 \
88
+ --num-workers 8 \
89
+ --gpus 0 \
90
+ --save-dir "${SAVE_DIR}"
91
+
92
+ echo "[auto-eval] Training done. Starting eval ${VERSION}..."
93
+ bash "${EVAL_SCRIPT}" >> "${LOG_FILE}" 2>&1
scripts/run_train_v21.sh ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # v21 training — T36: full prototypes + FVC-only L_deg (remove --deg-include-sd302).
3
+ #
4
+ # Root cause analysis (v20 failure — same collapse as v15–v19):
5
+ #
6
+ # v20 training showed healthy q_std≈18.3 across all 60 epochs but INFERENCE
7
+ # collapsed (all SD302 sensors score ~53.38, q_std≈0.007, concepts stuck at
8
+ # [0.994, 0.008, ...]). The T35 diagnosis was right about truncated
9
+ # prototypes (root cause 1) but the second fix (--deg-include-sd302) was
10
+ # WRONG and caused the collapse:
11
+ #
12
+ # Root cause — L_rank on SD302 creates a stable attractor at ~53.38 (T35b was wrong):
13
+ # SD302 images are ALL high quality (controlled NIST acquisition protocol).
14
+ # With --deg-include-sd302, L_rank says:
15
+ # Q(clean_SD302) > Q(low_deg_SD302) + m
16
+ # Q(low_deg_SD302) > Q(high_deg_SD302) + m
17
+ # The model satisfies this constraint by assigning a single "clean score" (~53.38)
18
+ # to ALL clean SD302 images and lower scores to degraded variants. There is
19
+ # NO gradient pushing different clean SD302 images apart — L_rank only requires
20
+ # clean > degraded, not that clean images differ from each other. Combined with
21
+ # L_spread_ds (batch-level, arbitrary ordering) and L_pair (same-identity
22
+ # same-score pressure), the model collapses all clean SD302 to ~53.38 at inference.
23
+ #
24
+ # Why v14 worked without --deg-include-sd302:
25
+ # FVC has GENUINE quality variation (8 impressions per subject with naturally
26
+ # different quality — blur, dry, wet, pressure). MDGT raw cosine to prototype
27
+ # GENUINELY varies (~0.75 worst to ~0.93 best) for FVC subjects. L_mat gradient
28
+ # on FVC shapes the backbone to be quality-discriminative. At inference on SD302,
29
+ # the backbone's learned quality features transfer (ridge clarity, noise level,
30
+ # ridge continuity) → SD302 images scored by intrinsic quality, not batch rank.
31
+ # This transfer mechanism is BLOCKED when L_rank on SD302 creates the ~53.38
32
+ # attractor that overrides the learned quality representation.
33
+ #
34
+ # v21 fix (T36):
35
+ # T36 — Remove --deg-include-sd302. Revert to FVC-only L_deg (T27 original design).
36
+ # Keep --proto-max-batches 0 (T35a, the correct fix from v20).
37
+ # L_deg applied only to FVC images: genuine quality variation → genuine L_mat
38
+ # gradient → backbone learns quality features that transfer to SD302 at inference.
39
+ # L_spread_ds still applied to SD302 to force batch-level spread (prevents batch-
40
+ # collapse without creating the attractor problem).
41
+ #
42
+ # All other settings kept from v20:
43
+ # --no-mat-stats --spread-weight 3.0 --deg-every-n-steps 2
44
+ # --concept-deg-gamma 0.5 --sd302-concept-weight 0.0
45
+ # --batch-size 128 --gpus 0 --epochs 60
46
+ # SD302-A+B+D included (full 30K sensor-invariant images, 19 sensors)
47
+ #
48
+ # Expected improvements vs v20:
49
+ # q_std (inference) : >12 (v20: ~0.007)
50
+ # Score range : 10–90 (v20: 53.20–53.41)
51
+ # Track 2 mean_KS : ≤0.30 (v20: 0.4936 — driven by sensor clusters, not quality)
52
+ # Track 2 Pearson : ≥0.20 (v20: 0.0048)
53
+ # Concept grounding : blur→clarity<0, noise→noise_level<0, etc.
54
+
55
+ set -euo pipefail
56
+
57
+ REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
58
+ export PATH="/home/aiserver/miniconda3/bin:$PATH"
59
+
60
+ VERSION="v21"
61
+ SAVE_DIR="${REPO_ROOT}/sifq/checkpoints/${VERSION}"
62
+ LOG_FILE="${REPO_ROOT}/sifq/logs/train_${VERSION}.log"
63
+ EVAL_SCRIPT="${REPO_ROOT}/sifq/scripts/run_eval_${VERSION}.sh"
64
+
65
+ mkdir -p "${REPO_ROOT}/sifq/logs"
66
+
67
+ python "${REPO_ROOT}/sifq/scripts/train_sifq.py" \
68
+ --root-302a "${REPO_ROOT}/dataset/302a/images/challengers" \
69
+ --root-302b "${REPO_ROOT}/dataset/302b/images/baseline" \
70
+ --root-302d "${REPO_ROOT}/dataset/nist_302d/images/auxiliary" \
71
+ --root-fvc2002 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2002" \
72
+ --root-fvc2004 "${REPO_ROOT}/dataset/FVC_Dataset/FVC2004" \
73
+ --root-polyu "${REPO_ROOT}/dataset/PolyU" \
74
+ --exclude-sensor "R_1000_slap,R_500_slap,S_500_slap" \
75
+ --mdgt-checkpoint "${REPO_ROOT}/pad/TRAM-downstream/checkpoint/checkpoints_dinov2_tram/best_eer.pt" \
76
+ --epochs 60 \
77
+ --batch-size 128 \
78
+ --image-size 224 \
79
+ --lr 1e-4 \
80
+ --spread-mode uniform \
81
+ --spread-weight 3.0 \
82
+ --concept-deg-gamma 0.5 \
83
+ --sd302-concept-weight 0.0 \
84
+ --deg-every-n-steps 2 \
85
+ --no-mat-stats \
86
+ --proto-max-batches 0 \
87
+ --max-train-samples -1 \
88
+ --num-workers 8 \
89
+ --gpus 0,1 \
90
+ --save-dir "${SAVE_DIR}"
91
+
92
+ echo "[auto-eval] Training done. Starting eval ${VERSION}..."
93
+ bash "${EVAL_SCRIPT}" >> "${LOG_FILE}" 2>&1