Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- dataset/phase1_noise_20260906/code/.pytest_cache/.gitignore +2 -0
- dataset/phase1_noise_20260906/code/.pytest_cache/CACHEDIR.TAG +4 -0
- dataset/phase1_noise_20260906/code/.pytest_cache/README.md +8 -0
- dataset/phase1_noise_20260906/code/__pycache__/eval_phase1_clean_relative.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/__pycache__/train_phase1_clean_relative.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/docs/final_version_summary_2026-09-02.md +174 -0
- dataset/phase1_noise_20260906/code/docs/phase1_clean_relative_seven_evaluation.md +199 -0
- dataset/phase1_noise_20260906/code/docs/phase1_pipeline_reassessment_noise_v2.md +179 -0
- dataset/phase1_noise_20260906/code/docs/project_progress_and_ideas_2026-08-30.md +0 -0
- dataset/phase1_noise_20260906/code/docs/proposal_dose_guided_finetune_2026-09-02.md +159 -0
- dataset/phase1_noise_20260906/code/docs/staged_training_plan.md +262 -0
- dataset/phase1_noise_20260906/code/scripts/benchmark_phase1_gpu.py +83 -0
- dataset/phase1_noise_20260906/code/scripts/expand_phase1_noise.py +375 -0
- dataset/phase1_noise_20260906/code/scripts/fetch_phase1_extra.py +280 -0
- dataset/phase1_noise_20260906/code/scripts/prepare_phase1_seven.py +385 -0
- dataset/phase1_noise_20260906/code/scripts/report_phase1_seven.py +86 -0
- dataset/phase1_noise_20260906/code/scripts/run_phase1_seven_suite.py +224 -0
- dataset/phase1_noise_20260906/code/slides/README.md +17 -0
- dataset/phase1_noise_20260906/code/slides/build_deck.js +381 -0
- dataset/phase1_noise_20260906/code/src/__init__.py +0 -0
- dataset/phase1_noise_20260906/code/src/__pycache__/__init__.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/data/__init__.py +0 -0
- dataset/phase1_noise_20260906/code/src/data/clean_relative.py +377 -0
- dataset/phase1_noise_20260906/code/src/data/folder_crops.py +104 -0
- dataset/phase1_noise_20260906/code/src/data/phase1_v2.py +928 -0
- dataset/phase1_noise_20260906/code/src/data/phase2_v4.py +942 -0
- dataset/phase1_noise_20260906/code/src/data/rain13k_quarantine_v1.json +0 -0
- dataset/phase1_noise_20260906/code/src/data/rain13k_resized.py +721 -0
- dataset/phase1_noise_20260906/code/src/models/__init__.py +29 -0
- dataset/phase1_noise_20260906/code/src/models/__pycache__/__init__.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/__init__.py +63 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/__init__.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/constants.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/spatial_branch.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/transformer.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/wavelet_branch.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/constants.py +100 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/losses.py +296 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/metrics.py +215 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/model.py +345 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/spatial_branch.py +114 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/transformer.py +231 -0
- dataset/phase1_noise_20260906/code/src/models/degradation/wavelet_branch.py +161 -0
- dataset/phase1_noise_20260906/code/src/models/graph_encoder/__init__.py +48 -0
- dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/__init__.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/clean_relative.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/encoder.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/hvi.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/losses.cpython-312.pyc +0 -0
- dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/representation.cpython-312.pyc +0 -0
dataset/phase1_noise_20260906/code/.pytest_cache/.gitignore
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Created by pytest automatically.
|
| 2 |
+
*
|
dataset/phase1_noise_20260906/code/.pytest_cache/CACHEDIR.TAG
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Signature: 8a477f597d28d172789f06886806bc55
|
| 2 |
+
# This file is a cache directory tag created by pytest.
|
| 3 |
+
# For information about cache directory tags, see:
|
| 4 |
+
# https://bford.info/cachedir/spec.html
|
dataset/phase1_noise_20260906/code/.pytest_cache/README.md
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pytest cache directory #
|
| 2 |
+
|
| 3 |
+
This directory contains data from the pytest's cache plugin,
|
| 4 |
+
which provides the `--lf` and `--ff` options, as well as the `cache` fixture.
|
| 5 |
+
|
| 6 |
+
**Do not** commit this to version control.
|
| 7 |
+
|
| 8 |
+
See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information.
|
dataset/phase1_noise_20260906/code/__pycache__/eval_phase1_clean_relative.cpython-312.pyc
ADDED
|
Binary file (48.5 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/__pycache__/train_phase1_clean_relative.cpython-312.pyc
ADDED
|
Binary file (50.4 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/docs/final_version_summary_2026-09-02.md
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SCDC — Tổng hợp phiên bản cuối (nguồn cho slide)
|
| 2 |
+
|
| 3 |
+
*Trạng thái 2026-09-02. Mọi số là seed 42, validation nội bộ 317 ảnh (haze 100 · lowlight 100 · noise 19 · rain 98, center-crop 256) trừ khi ghi khác. Hình: `outputs/final_charts/*.png`, `outputs/phase2_v7_dgf8k_vis/*.png`, `outputs/scene008_dgf.png`.*
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## 1. Bài toán và claim đứng vững
|
| 8 |
+
|
| 9 |
+
**Blind all-in-one restoration**: một mạng, bốn suy hoá (haze / lowlight / noise / rain), không nhãn task lúc inference.
|
| 10 |
+
|
| 11 |
+
Claim đứng được bằng số:
|
| 12 |
+
1. **Unified two-step diffusion một mạng** (T = 2, exact posterior ResShift) thay pipeline hai mạng "diffusion + refiner": nội bộ 27,50 / 0,850 (vs gen-2 hai mạng 27,55 / 0,874) và **thắng hai mạng trên cả 3 bộ external** (rain +1,2 · haze +0,7 · scene008 +4,2 dB).
|
| 13 |
+
2. **Backbone Uformer/LeWin xoá "định luật drift"**: mọi trunk conv trước đó luôn hy sinh lowlight khi tối ưu dài (v4, v6, v6.1, v7-conv); Uformer từ scratch leo đơn điệu 8k → 16k → … với best == final ở mọi chu kỳ.
|
| 14 |
+
3. **Head full-res train-chung an toàn ngoài phân phối, refiner train-rời thì không** — cùng một dung lượng, khác chỗ đặt.
|
| 15 |
+
4. **Identity trên ảnh sạch**: 27,8 → 40,4 dB nhờ cặp identity trong fine-tune.
|
| 16 |
+
|
| 17 |
+
Claim phải nói cẩn thận (xem §7): vai trò của Phase-1 là **chẩn đoán + hỗ trợ haze**, không phải "điều kiện không thể thiếu" cho restoration.
|
| 18 |
+
|
| 19 |
+
---
|
| 20 |
+
|
| 21 |
+
## 2. Kiến trúc bản cuối (`uformer_dgf8k_seed42`, best @6000)
|
| 22 |
+
|
| 23 |
+
### Phase-1 — Blind Degradation Graph Encoder (`phase1_ll_v3`, đóng băng)
|
| 24 |
+
- Hai nhánh spatial + wavelet, thêm **LL-global branch** (Haar LL³ → attention 1-query + 14 thống kê photometric → 128-d) để giữ thông tin toàn cục (sửa lỗi "mất global").
|
| 25 |
+
- Đầu ra graph: 6 node token (4 known + 2 free/null), routing, severity 4 chiều (calibrated), spatial maps 16×16, content latent 64 px, unknown residual, global condition 256-d.
|
| 26 |
+
- Null/OOD: free slots học từ ảnh sạch + OOD tổng hợp (snow/blur/pixelate); OOD → free 55–60/60, novelty gap 3–4×, "honest-null" (free-mass tương quan âm với residual mưa).
|
| 27 |
+
|
| 28 |
+
### Phase-2 — v7 Unified two-step ResShift, backbone Uformer (~thông số dims 64/128/192/256, cond 256)
|
| 29 |
+
- **State**: pixel-unshuffle ×2, 12 kênh; anchor u_y; x0-prediction.
|
| 30 |
+
- **Lịch T = 2** (η = [0, 0,04, 0,98]); κ theo mẫu từ strengths của node (per-type κ calibrated).
|
| 31 |
+
- **Trunk**: LeWin blocks (window-attn 8×8 + LeFF + adaLN zero-init), cross-attention với 8 token graph ở 2 scale sâu, adaLN từ `global_vector`, MoE bank 5 expert (top-2) ở 7 vị trí, content inject @64 px, spatial inject @16 px.
|
| 32 |
+
- **Image head** (train-chung): tail NAFNet-lite 3 block × 48 kênh ở **full-res** (input restored ‖ y, zero-init) + **FiLM** đầu ra từ global condition (6 tham số).
|
| 33 |
+
- **Tháp Laplacian coarse-to-fine**: head zero-init ở 16/32/64 px trong không gian state, tái tạo telescoping với anchor u_y (identity chính xác khi δ = 0), deep supervision MSE λ = 0,1/0,2/0,3.
|
| 34 |
+
- **DGF**: token null học được cho `context` và `global_vector`; conditioning dropout p = 0,15; cặp identity q = 0,10; liều w ở inference (mặc định w = 1).
|
| 35 |
+
- **Inference**: 2 forward (coarse t=2 → posterior → fine t=1) + head; với liều w ≠ 1 thêm 1 forward null ở bước coarse.
|
| 36 |
+
|
| 37 |
+
### Mất mát composite (một optimizer)
|
| 38 |
+
coarse x0-MSE (fp32) + tháp MSE + fine [L1 + 0,1·VGG + 0,5·chroma(UV) + 0,5·luma(pool 8×8)] + gate anchor/correction.
|
| 39 |
+
|
| 40 |
+
---
|
| 41 |
+
|
| 42 |
+
## 3. Công thức huấn luyện (chuỗi warm-restart)
|
| 43 |
+
|
| 44 |
+
| Chu kỳ | Thay đổi | Steps | LR đỉnh | Kết quả (macro / SSIM) |
|
| 45 |
+
|---|---|---:|---:|---:|
|
| 46 |
+
| 1 | Uformer từ scratch, unified two-step | 8k | 1e-4 | 25,26 / 0,777 |
|
| 47 |
+
| 2 | + chroma loss (DDP 2 GPU) | 16k | 5e-5 | 26,44 / 0,808 |
|
| 48 |
+
| 3 | + luma loss | 8k | 3e-5 | 26,59 / 0,811 |
|
| 49 |
+
| 4 | + full-res tail + FiLM | 8k | 3e-5 | 27,43 / 0,846 |
|
| 50 |
+
| 5 | + DGF (null tokens, identity, tháp Laplacian) | 8k | 3e-5 | **27,50 / 0,850** (w=1); 27,54 @w=0,5 |
|
| 51 |
+
|
| 52 |
+
Hạ tầng: DDP 2×3090 (`find_unused_parameters=True` bắt buộc vì MoE hard-skip), EMA 0,9999, AMP + cơ chế `RecoverableAmpOverflow` (scaler dao động ở trần fp16 → auto-resume bằng supervisor, 0 step mất). Mỗi chu kỳ eval@0 trùng bitwise best chu kỳ trước (mọi thành phần mới zero-init/identity).
|
| 53 |
+
|
| 54 |
+
---
|
| 55 |
+
|
| 56 |
+
## 4. Kết quả nội bộ
|
| 57 |
+
|
| 58 |
+
### Bản cuối theo domain (dgf8k best @6000, w = 1)
|
| 59 |
+
|
| 60 |
+
| Domain | Degraded | Bản cuối | gen-2 (2 mạng) |
|
| 61 |
+
|---|---:|---:|---:|
|
| 62 |
+
| Haze | 17,31 | **32,73** | 30,2 |
|
| 63 |
+
| Noise | 27,33 | **35,99** | 36,9 |
|
| 64 |
+
| Lowlight | 9,77 | 18,74 | 20,3 |
|
| 65 |
+
| Rain | 21,25 | 22,53 | 22,8 |
|
| 66 |
+
| **Macro / SSIM** | 18,91 / 0,551 | **27,50 / 0,850** | 27,55 / 0,874 |
|
| 67 |
+
|
| 68 |
+
### Tiến hoá (hình 01)
|
| 69 |
+
22,68 (v4 1-step) → 23,41 (v7-conv) → 25,26 → 26,44 → 26,59 → 27,43 → 27,50.
|
| 70 |
+
|
| 71 |
+
### Sweep liều (DGF, val)
|
| 72 |
+
w = 0: 27,49 / **0,852**, lowlight 18,87, rain 22,62 · w = 0,5: **27,54** · w = 1: 27,50 · w = 1,25: 27,43. Đường cong phẳng (xem §7, định luật 4).
|
| 73 |
+
|
| 74 |
+
### Identity (ảnh sạch làm input, PSNR(f(x), x))
|
| 75 |
+
head8k 27,8 (noise 23,6 — phá ảnh sạch) → **DGF 40,4** (noise 41,4 · lowlight 36,2 · haze 43,8 · rain 40,2).
|
| 76 |
+
|
| 77 |
+
---
|
| 78 |
+
|
| 79 |
+
## 5. External held-out (hình 02) — PSNR / SSIM / LPIPS
|
| 80 |
+
|
| 81 |
+
| Bộ | Degraded | gen-2 (2 mạng) | head8k | **DGF (w=1)** |
|
| 82 |
+
|---|---:|---:|---:|---:|
|
| 83 |
+
| Rain locked (1200) | 22,56 | 26,71 / 0,833 / 0,108 | **28,02** / 0,836 / 0,125 | 27,88 / 0,834 / 0,124 |
|
| 84 |
+
| Haze held-out (300) | 18,17 | 31,18 / 0,971 / 0,010 | 31,71 / 0,974 / 0,010 | **31,87 / 0,975 / 0,009** |
|
| 85 |
+
| Noise scene008 (20) | **39,02** | 22,35 / 0,801 / 0,085 | 27,09 / 0,765 / 0,328 | 26,50 / **0,825** / 0,193 |
|
| 86 |
+
|
| 87 |
+
Ghi chú: rain nội bộ 22,5 bị GT lệch tone kéo thấp giả tạo — derain thật là 28 dB external. scene008 là cảnh vải **tối gần sạch**: mọi model đều "làm gì đó" (xem §7, định luật 6).
|
| 88 |
+
|
| 89 |
+
---
|
| 90 |
+
|
| 91 |
+
## 6. Ablation / probe (hình 03)
|
| 92 |
+
|
| 93 |
+
Probe leave-one-out ở inference trên head8k (full val):
|
| 94 |
+
|
| 95 |
+
| Tắt | Δ macro | Đọc |
|
| 96 |
+
|---|---:|---|
|
| 97 |
+
| `context` (cross-attn tokens) | −3,68 | đường sống 1 (noise −13,4, **lowlight +1,95**) |
|
| 98 |
+
| `global_vector` (adaLN) | −3,45 | đường sống 2 (haze −6,0, lowlight +0,55) |
|
| 99 |
+
| `unknown_residual` (field) | −0,74 | field Phase-1 hữu ích nhất |
|
| 100 |
+
| `global_condition` / `node_tokens` | −0,24 / −0,16 | |
|
| 101 |
+
| MoE gate + κ per-type (uniform) | −0,085 | cơ chế MoE ≈ không dùng ở inference |
|
| 102 |
+
| routing / severity / spatial maps / content latent | ≈ 0 | plug chết |
|
| 103 |
+
| Rút toàn bộ Phase-1 (chưa train null) | −7,79 | |
|
| 104 |
+
|
| 105 |
+
Kết luận cấu trúc: trunk dùng Phase-1 như một **bộ mô tả ảnh** (qua 2 đường), không dùng cấu trúc graph tường minh; 7 bank expert + content/spatial inject có thể prune.
|
| 106 |
+
|
| 107 |
+
---
|
| 108 |
+
|
| 109 |
+
## 7. Định luật rút ra (mỗi cái có số đo)
|
| 110 |
+
|
| 111 |
+
1. **Chain dài phá kết quả** (exposure bias): 1-step > 8-step; unified two-step chain-aware là điểm cân bằng.
|
| 112 |
+
2. **Drift law của conv-trunk** (lowlight bị hy sinh khi train dài) — Uformer + adaLN zero-init miễn nhiễm.
|
| 113 |
+
3. **Cùng dung lượng full-res: trong một graph/loss thì an toàn OOD, tách mạng thì overfit** (refiner −5 dB external; head train-chung giữ nguyên).
|
| 114 |
+
4. **Ablation tắt-điều-kiện trên model chưa có nhánh null đo "rụt rè off-manifold", không đo giá trị của điều kiện** — +1,95 lowlight biến mất sau khi nhánh null được train (w=0 chỉ +0,13).
|
| 115 |
+
5. **Warm-restart cosine = SGDR**: mỗi chu kỳ vắt thêm, lợi suất co (25,26 → +1,18 → +0,15 → +0,84 (head) → +0,07); "bão hoà" là do schedule, loss chưa từng phẳng ở LR còn sống.
|
| 116 |
+
6. **Identity phải được dạy bằng ảnh sạch giống phân phối triển khai** (tối, có vân, real-camera): identity nội bộ 40 dB không chuyển sang scene008.
|
| 117 |
+
7. **Overshoot lowlight cực đoan là trần thông tin**: input ~9,7 dB gần đen, độ sáng tuyệt đối của GT không có trong ảnh vào.
|
| 118 |
+
|
| 119 |
+
---
|
| 120 |
+
|
| 121 |
+
## 8. Hai thí nghiệm quyết định (đã xong)
|
| 122 |
+
|
| 123 |
+
### 8a. Control "không Phase-1" (p = 1, cùng recipe, cùng warm-start, eval hoàn toàn không điều kiện)
|
| 124 |
+
|
| 125 |
+
| Step | Không Phase-1 | Có Phase-1 (dgf8k) | Chênh |
|
| 126 |
+
|---:|---:|---:|---:|
|
| 127 |
+
| 0 | 20,43 | 27,43 | −7,0 |
|
| 128 |
+
| 2000 | 26,49 | 27,27 | −0,78 |
|
| 129 |
+
| 4000 | 26,73 | 27,46 | −0,74 |
|
| 130 |
+
| 6000 | 27,03 / 0,847 | 27,50 / 0,850 | −0,47 |
|
| 131 |
+
| 8000 | **27,05 / 0,846** | 27,45 / 0,850 | **−0,40** |
|
| 132 |
+
|
| 133 |
+
Phân bố chênh @8000: haze −1,85 · noise −0,58 · **lowlight +0,94 cho control** · rain −0,12. → **Phán quyết: chênh 0,40 dB (dải 0,2–0,5)** — Phase-1 giữ vai chẩn đoán / OOD / hỗ trợ haze (thông tin toàn cục airlight/transmission); restoration là công của trunk; với lowlight điều kiện gây over-drive. Caveat: control warm-start từ trọng số từng học có điều kiện — trả lời cho inference và fine-tune tiếp, chưa phải from-scratch. Hình: `outputs/final_charts/04_phase1_control.png`.
|
| 134 |
+
|
| 135 |
+
### 8b. Phase-1 ll_v4/v4b — sửa khái niệm noise (ĐÓNG, âm tính)
|
| 136 |
+
Với 8 scene SIDD, cả nhiễu tổng hợp (v4) lẫn transplant residual thật + hard negative sharpen (v4b, 50 epoch, best epoch 18 F1 0,774) đều đẩy khái niệm noise về "hạt tối kiểu SIDD":
|
| 137 |
+
|
| 138 |
+
| Ca | ll_v3 | v4 @20 | v4b best | v4b last |
|
| 139 |
+
|---|---:|---:|---:|---:|
|
| 140 |
+
| scene008 clean → noise | 0,41 | 0,81 | **0,90** | 0,67 |
|
| 141 |
+
| LOL clean GT → noise | 0,20 | 0,29 | 0,74 | 0,64 |
|
| 142 |
+
| SIDD val noise → noise | 0,04 | 0,03 | 0,08 | 0,05 |
|
| 143 |
+
| SIDD val noise → rain | 0,58 | 0,75 | 0,60 | 0,61 |
|
| 144 |
+
|
| 145 |
+
Kết luận: giới hạn dữ liệu (8 scene), không phải weight hay loss — mọi augmentation nhiễu đều tăng dương tính giả trên ảnh sạch tối/có vân và không dạy được ca thiếu. Nhánh đóng; giữ ll_v3 làm Phase-1 chính thức. Hướng còn lại nếu muốn quay lại: dữ liệu nhiễu thật đa scene (SIDD full / ELD / PolyU) hoặc ước lượng noise-level cổ điển làm đặc trưng.
|
| 146 |
+
|
| 147 |
+
---
|
| 148 |
+
|
| 149 |
+
## 9. Hạn chế và bước tiếp
|
| 150 |
+
|
| 151 |
+
- 1 seed cho mọi số; noise val n = 19 (1 scene); chưa test mixed degradation; chưa có zero-shot restoration cho suy hoá unseen (chỉ có detection).
|
| 152 |
+
- Bước tiếp có căn cứ: (i) identity pairs từ ảnh sạch tối/có vân thật (SIDD GT, LOL GT) ở trunk; (ii) prune plug chết (content/spatial inject, MoE bank) → mạng gọn hơn; (iii) seed 43/44 cho chu kỳ cuối; (iv) benchmark công khai để so với AirNet/PromptIR/DA-CLIP.
|
| 153 |
+
|
| 154 |
+
## 10. Tài sản
|
| 155 |
+
- Checkpoints (server 3090): `outputs/phase1_ll_v3/graph_encoder_best.pt`; `outputs/phase2_v7/{uformer_seed42,uformer16k_seed42,uformer_luma8k_seed42,uformer_head8k_seed42,uformer_dgf8k_seed42}/best.pt`.
|
| 156 |
+
- Scripts: `train_phase2_unified_v7.py`, `src/models/restoration/uformer_moe_v7.py`, `eval_v7_external.py`, `sweep_v7_dose.py`, `probe_v7_taps.py`, `visualize_v7_uformer.py`, `visualize_scene008.py`, `diagnose_phase1_routing.py`, `make_final_charts.py`.
|
| 157 |
+
- Số liệu JSON: `outputs/v7_*external*.json`, `outputs/v7_dgf_dose_sweep.json`, `outputs/v7_head_taps_*.json`, `outputs/v7_head8k_identity.json`, `outputs/phase1_ll_v*_routing_diag*.json`.
|
| 158 |
+
|
| 159 |
+
## 11. Cập nhật sau bản tổng hợp — hai run A/B (2026-09-03)
|
| 160 |
+
|
| 161 |
+
Hai run 8k warm-start từ dgf8k best, mỗi run một GPU, cùng recipe DGF + **clean-image prior** (cặp clean + Poisson-Gaussian, p = 0,20) + **tail full-res 6 block**; B thêm **Phase-1 nhìn toàn khung hình** (aspect-squash 256, hai đường cộng zero-init vào context và global_vector).
|
| 162 |
+
|
| 163 |
+
| | dgf8k (bản cuối cũ) | **A** `uformer_p5_8k_seed42` | **B** `uformer_p45_8k_seed42` |
|
| 164 |
+
|---|---|---|---|
|
| 165 |
+
| Val macro PSNR / SSIM (best @6000) | 27,50 / 0,850 | **27,90** / 0,859 | 27,81 / **0,861** |
|
| 166 |
+
| haze / lowlight / noise / rain (PSNR) | 32,9 / 19,0 / 36,0 / 22,6 | 33,08 / 19,05 / **36,95** / 22,53 | 32,55 / **19,43** / 36,72 / 22,52 |
|
| 167 |
+
| External rain 1200 | 27,88 / 0,834 | 27,87 / 0,837 | 27,79 / 0,835 |
|
| 168 |
+
| External haze 300 | 31,87 / 0,975 | 31,54 / 0,976 | **31,92** / 0,975 |
|
| 169 |
+
| External scene008 (gần sạch, input 39,0) | 26,50 / 0,825 | 27,13 / 0,853 | **28,15** / 0,855 |
|
| 170 |
+
|
| 171 |
+
- **#5 (noise kém refiner 0,9 dB): đóng dương.** Clean-image prior trong cùng một mạng đưa noise val lên 36,95 = refiner hai mạng (36,9); +0,41 dB macro so với dgf8k.
|
| 172 |
+
- **#4 (Phase-1 mất global): sửa đúng cơ chế, không đạt mốc tự đặt.** Toàn khung hình mang thông tin exposure toàn ảnh mà crop không có: lowlight +0,38, scene008 +1,0, haze external +0,38; nhưng val macro −0,10 (haze val chỉ 3 cảnh gốc, ngược dấu với haze external 300 cảnh). Claim đúng: *lựa chọn robustness*, không phải "cải thiện".
|
| 173 |
+
- **Chẩn đoán mới cho scene008:** một phép affine toàn cục trên output nâng 27,1 → 35,9 dB — lỗi là **exposure prior của trunk** (kéo tối ảnh sáng vừa, nâng sáng ảnh rất tối), không phải mất texture; Phase-1 và whole-frame context đều *giảm* lỗi này. Việc kế tiếp có bằng chứng: identity pairs từ ảnh clean đa dạng exposure.
|
| 174 |
+
- **Checkpoint bản cuối:** A cho bảng in-dist; B cho triển khai OOD. Ảnh vis: `outputs/phase2_v7/uformer_p5_8k_seed42/vis`, `outputs/phase2_v7/uformer_p45_8k_seed42/vis` (mỗi thư mục 4 lưới domain + `scene008.png`). Bảng tổng quan dữ liệu: `visualize_degradation_table.py`.
|
dataset/phase1_noise_20260906/code/docs/phase1_clean_relative_seven_evaluation.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Phase-1 clean-relative seven-degradation implementation and evaluation
|
| 2 |
+
|
| 3 |
+
Date: 2026-09-06 (Asia/Ho_Chi_Minh). Status: implementation/data verified; model-quality results pending.
|
| 4 |
+
|
| 5 |
+
## Decision and scope
|
| 6 |
+
|
| 7 |
+
Combine the structured subspace node proposal with functional, clean-relative
|
| 8 |
+
supervision. A successful representation must distinguish degradation factors,
|
| 9 |
+
encode useful within-type variation, transfer controlled corruption parameters
|
| 10 |
+
across held-out contents, and support measurable composition interventions.
|
| 11 |
+
Neither a class cluster nor a small clean norm alone establishes these properties.
|
| 12 |
+
|
| 13 |
+
Canonical known-type order: `rain, noise, haze, lowlight, snow, blur, jpeg`.
|
| 14 |
+
Snow is now a supervised known type, not an unknown/OOD training class. Two
|
| 15 |
+
additional free nodes are residual capacity, not independently identified classes.
|
| 16 |
+
The initial representation uses 256 dimensions and rank-8 node bases. A global
|
| 17 |
+
orthonormal bank or a consistent joint projection avoids double-counting shared
|
| 18 |
+
directions. Presence is independent sigmoid activation, not a categorical softmax.
|
| 19 |
+
Severity is supervised on explicitly known synthetic parameters; measured real-pair
|
| 20 |
+
residual strength is not called a physical severity ground truth.
|
| 21 |
+
|
| 22 |
+
The new implementation is versioned separately from the legacy Phase-1. It must
|
| 23 |
+
not silently remap seven labels into the old four-label/six-node contract. Phase-2,
|
| 24 |
+
its checkpoints, pre-gain and spatial expert consumers are unchanged in this task.
|
| 25 |
+
A future Phase-2 adapter is a separate evaluated change.
|
| 26 |
+
|
| 27 |
+
## Architecture and objectives
|
| 28 |
+
|
| 29 |
+
1. Spatial and multi-band wavelet evidence feed dual-domain attention, separate
|
| 30 |
+
content features and a blind single-image degradation descriptor.
|
| 31 |
+
2. Paired clean/degraded features provide an explicitly identity-anchored training
|
| 32 |
+
descriptor. A feature difference is evidence of change, not a proof that all
|
| 33 |
+
content dependence cancels. Inference never receives the paired clean image.
|
| 34 |
+
3. Orthonormal bases yield amplitudes/coordinates and a consistent residual.
|
| 35 |
+
Independent presence, supervised parameter heads and within-type coordinates
|
| 36 |
+
are kept distinct. Clean corresponds to zero degradation, not zero content.
|
| 37 |
+
4. A lightweight proxy decoder is included from the start. Clean/degraded
|
| 38 |
+
reconstruction and controlled cross-content transfer anchor functional meaning.
|
| 39 |
+
It is not claimed to recover a uniquely identifiable causal model.
|
| 40 |
+
5. Shared, ordered pair interactions are departures from additivity in this chosen
|
| 41 |
+
representation. They vanish exactly if either input factor is absent. A no-edge
|
| 42 |
+
run isolates their benefit, but keeps the evidence attention and therefore is
|
| 43 |
+
not a complete no-message-passing ablation. Family hierarchies are deferred to avoid duplicated
|
| 44 |
+
family bases and an unvalidated hard taxonomy.
|
| 45 |
+
|
| 46 |
+
Loss groups: clean origin and absence; paired content consistency plus functional
|
| 47 |
+
reconstruction to oppose content collapse; independent factor presence; known-node
|
| 48 |
+
support and constrained free capacity; synthetic parameter/severity supervision;
|
| 49 |
+
paired-to-blind agreement with supervised paired targets; matched-parameter
|
| 50 |
+
cross-content consistency; composition and functional transfer. All loss terms,
|
| 51 |
+
weights, finite-gradient failures and sample counts are logged.
|
| 52 |
+
|
| 53 |
+
## Data contract: no hidden subset training
|
| 54 |
+
|
| 55 |
+
Reference: [DA-CLIP repository](https://github.com/Algolzw/daclip-uir), which lists
|
| 56 |
+
ten tasks. Add motion blur and JPEG to the five existing degradation domains;
|
| 57 |
+
do not claim reproduction of DA-CLIP's full ten-task benchmark.
|
| 58 |
+
|
| 59 |
+
| Type | Source | Training and evaluation policy |
|
| 60 |
+
|---|---|---|
|
| 61 |
+
| Rain | Existing Rain13K-resized | All valid available train pairs; preserve audited quarantine and official-test isolation. Resized-source limitation remains explicit. |
|
| 62 |
+
| Noise | Existing SIDD Small sRGB | All available scene-isolated records, native aligned crops; no image downsampling that averages away noise. Not the full SIDD Medium/benchmark corpus. |
|
| 63 |
+
| Haze | Existing RESIDE bundle | All valid available pairs, grouped by clean source; do not retain the old 5,000-pair cap. Bundle is an extracted subset, not full RESIDE. |
|
| 64 |
+
| Lowlight | Existing LOLv2 real | All paired train inputs; validation/test roles fixed before fitting. Not LOLv2 synthetic unless separately obtained. |
|
| 65 |
+
| Snow | Snow100K train and separately acquired test | Audit all 50,000 local train pairs before duplicate/leakage exclusions; hold out content groups. Acquire official test if public download is accessible. |
|
| 66 |
+
| Motion blur | GoPro Large | All train pairs, validation by training scene; official test kept locked. The larger raw-video archive is unnecessary. |
|
| 67 |
+
| JPEG | DIV2K HR + Flickr2K HR | All clean-source training records, on-the-fly compression; source split before generation. DIV2K validation provides held-out sources, not a source pool for training. |
|
| 68 |
+
|
| 69 |
+
Downloader receipts record original URL, mirror URL/revision where applicable,
|
| 70 |
+
archive SHA-256, extraction counts and expanded bytes. Never execute downloaded
|
| 71 |
+
code. Missing or corrupt pairs, exact clean-content duplicates and conflicting
|
| 72 |
+
split assignments are errors or explicit audited exclusions, never silently skipped.
|
| 73 |
+
No validation/test record is moved into training to satisfy “all data.”
|
| 74 |
+
|
| 75 |
+
An epoch is a shuffled traversal of every admitted training record, without
|
| 76 |
+
replacement and without dropping the last batch. Record counts and coverage are
|
| 77 |
+
persisted. Class-weighted objectives address imbalance without pretending fixed
|
| 78 |
+
replacement sampling has visited all images. Synthetic controls supplement, not
|
| 79 |
+
replace, the real paired datasets.
|
| 80 |
+
|
| 81 |
+
Report three distinct quantities: original benchmark size, local discovered size,
|
| 82 |
+
and final split sizes after safety exclusions. “Full coverage” means the last
|
| 83 |
+
quantity, not unavailable original benchmark data.
|
| 84 |
+
|
| 85 |
+
## Fixed evaluation matrix
|
| 86 |
+
|
| 87 |
+
Use validation only for checkpoint selection. Lock test sources, synthetic seeds,
|
| 88 |
+
parameter grids, held-out unordered type pairs and operation orders before fitting.
|
| 89 |
+
Report macro averages and per-domain values; large Snow100K counts must not hide
|
| 90 |
+
failure on small SIDD/LOL domains. Test metrics never select a checkpoint.
|
| 91 |
+
|
| 92 |
+
| Question | Primary evidence | Necessary control / limitation |
|
| 93 |
+
|---|---|---|
|
| 94 |
+
| Does clean map to an identity? | Clean descriptor norm distribution, false-positive presence, clean proxy error | Include naturally dark/low-texture clean scenes; zero norm alone is insufficient. |
|
| 95 |
+
| Are known nodes discriminative? | Per-domain precision/recall/F1/AP, confusion, multi-label mixture presence | Report source/dataset confounding; no class-cluster-as-disentanglement claim. |
|
| 96 |
+
| Are coordinates richer than class × severity? | Matched generating parameters across disjoint contents; within-type parameter retrieval/prediction | Compare a rank-1/prototype baseline and report its differing capacity. |
|
| 97 |
+
| Is severity meaningful? | Synthetic parameter MAE, correlation and calibration per type and parameter regime | Real residual proxies reported separately; no universal scalar ordering assumed. |
|
| 98 |
+
| Does the global code leak content? | Cross-content consistency at matched parameters; held-out content predictability where estimable | Cosine separation alone is not evidence of independence; local physical fields may depend on content. |
|
| 99 |
+
| Can codes do useful work? | Cross-content re-degradation proxy error vs zero/shuffled code; factor-removal tests | Random noise evaluated with suitable statistics as well as pixel error; PSNR is not a causal proof. |
|
| 100 |
+
| Do edges improve composition? | Held-out mixture presence, parameter recovery, functional error, both matched orders | No-edge run; latent R² secondary only, with target variance and frozen-reference status. |
|
| 101 |
+
| Does unknown detection generalize? | Clean/known vs never-trained corruption AUROC/AUPR, stated probe types | Residual norm can miss OOD captured by free nodes; this is not leave-one-type/family-out validation. |
|
| 102 |
+
| Are conclusions reproducible? | Seeds 42/43/44, means and variability; manifest/config/source hashes | A trial does not establish convergence or benchmark superiority. |
|
| 103 |
+
|
| 104 |
+
Predeclared held-out composition candidates: rain+JPEG, noise+haze, snow+blur.
|
| 105 |
+
These pairs must be excluded in both orders from composition training. Distinguish
|
| 106 |
+
an unseen pair from a seen pair at unseen strengths. Synthetic renderers are named
|
| 107 |
+
approximations, not asserted exact generators of the real benchmarks.
|
| 108 |
+
|
| 109 |
+
Checkpoint ranking initially uses fixed validation macro-F1, with clean false
|
| 110 |
+
positives, functional metrics and per-domain scores reported alongside it. Passing
|
| 111 |
+
classification alone does not authorize a claim of a successful representation.
|
| 112 |
+
No numerical success threshold is backfilled after viewing test outcomes.
|
| 113 |
+
|
| 114 |
+
## Runs and operational gates
|
| 115 |
+
|
| 116 |
+
1. CPU unit tests: projection/orthogonality, exact pair identity, interaction zero
|
| 117 |
+
boundaries, shape/dtype/gradients, manifest leakage, deterministic synthesis,
|
| 118 |
+
source-wide epoch coverage, checkpoint/resume and metric degeneracy handling.
|
| 119 |
+
2. Independent code review, including archive extraction/path safety and source
|
| 120 |
+
split isolation. Fix accepted findings before the full-data launch.
|
| 121 |
+
3. ROCm smoke on physical GPU index 5: one visible GPU, bounded batch, actual
|
| 122 |
+
device identity, finite forward/backward, checkpoint reload and evaluation.
|
| 123 |
+
Smoke caps must appear in run metadata and never masquerade as the full run.
|
| 124 |
+
4. Initial full-data trial: seed 42, five complete epochs. Start conservatively at
|
| 125 |
+
real batch 16, synthetic subbatch 4, native 256 crops; adjust only from measured
|
| 126 |
+
memory/throughput and record the resulting configuration.
|
| 127 |
+
5. After a finite initial run: full held-out evaluation. Sequential matched-budget
|
| 128 |
+
no-edge and rank-1/prototype controls and seeds 43/44 quantify improvements and
|
| 129 |
+
variability. Keep them on the same requested GPU; no opportunistic other GPUs.
|
| 130 |
+
6. Produce machine-readable metrics and a human-readable result report, including
|
| 131 |
+
failures, unsupported evaluations and source-availability limitations. Full
|
| 132 |
+
convergence, a Phase-2 gain and semantic family OOD require later experiments.
|
| 133 |
+
|
| 134 |
+
Initial host audit: physical GPU 5 PCI `0000:AB:00.0`, MI325X 256-GiB-class device;
|
| 135 |
+
approximately 188 GiB already allocated by unrelated processes and 67 GiB free.
|
| 136 |
+
Do not kill or reconfigure those processes. Target a substantially smaller memory
|
| 137 |
+
footprint and confirm device mapping with ROCm visibility before launch. Root
|
| 138 |
+
filesystem initially had approximately 115 GB free. Reserve at least 25 GiB while
|
| 139 |
+
downloading/extracting. Existing checkpoints and datasets are not deletion targets.
|
| 140 |
+
|
| 141 |
+
Commit and push to `codex/phase1-clean-relative-seven`. Deploy an immutable archive
|
| 142 |
+
of the committed SHA on the server, preserving `/home/vunguyen/SCDC` and existing
|
| 143 |
+
outputs. Launch logs/checkpoints live in a new run directory. Persist source SHA,
|
| 144 |
+
manifest hash, exact command, PID/session and status so remote progress is auditable.
|
| 145 |
+
|
| 146 |
+
## Evidence log
|
| 147 |
+
|
| 148 |
+
The final manifest is `/home/vunguyen/data_bundle/phase1_seven_extra/manifest_v1.json`.
|
| 149 |
+
SHA-256: `8f7be16638ee544eb97245871ce1c6d884920bb2973c14a64a09e4db64f88e24`.
|
| 150 |
+
|
| 151 |
+
| Type | Train | Validation | Test |
|
| 152 |
+
|---|---:|---:|---:|
|
| 153 |
+
| Rain | 11,958 | 598 | 4,298 |
|
| 154 |
+
| Noise | 121 | 19 | 20 |
|
| 155 |
+
| Haze | 4,740 | 280 | 280 |
|
| 156 |
+
| Lowlight | 655 | 34 | 100 |
|
| 157 |
+
| Snow | 47,369 | 2,493 | 33,412 |
|
| 158 |
+
| Motion blur | 2,003 | 100 | 1,111 |
|
| 159 |
+
| JPEG | 3,278 | 172 | 100 |
|
| 160 |
+
| **Total** | **70,124** | **3,696** | **39,321** |
|
| 161 |
+
|
| 162 |
+
Audit decoded and hashed all 217,860 unique files, with zero invalid files.
|
| 163 |
+
The existing versioned Rain quarantine excludes 1,155 source training records.
|
| 164 |
+
After discovery, 138 Snow records overlapping protected test content/groups
|
| 165 |
+
were excluded (132 train, 6 validation). All exclusions are recorded in the
|
| 166 |
+
manifest; no remaining record cap applies. Exact decoded RGB and source-group
|
| 167 |
+
isolation are verified; perceptual near-duplicate detection was not performed.
|
| 168 |
+
|
| 169 |
+
Extra sources acquired: GoPro Large (2,103 train / 1,111 test pairs), DIV2K HR
|
| 170 |
+
(800 train / 100 validation images) and Flickr2K HR (2,650 images). The original
|
| 171 |
+
Snow100K test download was quota-blocked. The authors' [Histoformer dataset
|
| 172 |
+
mirror](https://github.com/sunshangquan/Histoformer#-datasets) supplied S/L test
|
| 173 |
+
partitions only (16,611 / 16,801 pairs); **test M is unavailable in this run**.
|
| 174 |
+
Receipts, archive hashes and pinned mirror revisions are retained under
|
| 175 |
+
`/home/vunguyen/data_bundle/phase1_seven_extra/`. Existing compressed/partial
|
| 176 |
+
archives and old checkpoints were not deleted.
|
| 177 |
+
|
| 178 |
+
Physical GPU 5 is pinned by `ROCR_VISIBLE_DEVICES=GPU-8169d457412f2f76`, with
|
| 179 |
+
`HIP_VISIBLE_DEVICES` and `CUDA_VISIBLE_DEVICES` unset. Its PCI bus is decimal
|
| 180 |
+
171 (`AB`). Raw PyTorch ordinal 5 maps to another card on this host; the launcher
|
| 181 |
+
asserts exactly one visible GPU and the expected PCI identity before training.
|
| 182 |
+
The actual ROCm native-256 FP32 smoke passed five forward/backward steps at real
|
| 183 |
+
batch 16 / synthetic batch 4: steady mean 0.2984 seconds per step and peak allocated
|
| 184 |
+
2,472,867,840 bytes. This is a synthetic software smoke, not a measured full-data
|
| 185 |
+
throughput or restoration result. Receipt: `phase1_seven_extra/gpu5_smoke.json`.
|
| 186 |
+
|
| 187 |
+
The fixed queue runs `full_seed42`, `no_composition_edges_seed42`, `rank1_seed42`,
|
| 188 |
+
`full_seed43`, `full_seed44` sequentially, each for five complete epochs. Each run
|
| 189 |
+
then evaluates all validation and test records plus 256 held-out controlled scenes
|
| 190 |
+
with evaluation seed 20260906. The summary includes only reports validated by the
|
| 191 |
+
queue; missing, partial or stale artifacts never contribute to seed means.
|
| 192 |
+
|
| 193 |
+
All 86 selected CPU tests passed on the server's Python 3.12.14 / torch 2.10 ROCm
|
| 194 |
+
7.0 environment (GPU visibility disabled for CPU tests), covering the new pipeline
|
| 195 |
+
and legacy v5/v6 regressions. Independent review also exercised exact
|
| 196 |
+
interrupted/resumed equality, all trainable gradients and 25 focused operational
|
| 197 |
+
tests. No blocking HIGH/CRITICAL review finding remains. Deployment SHA and actual
|
| 198 |
+
run status accompany the launch handoff. This document contains no measured
|
| 199 |
+
model-quality claims yet.
|
dataset/phase1_noise_20260906/code/docs/phase1_pipeline_reassessment_noise_v2.md
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Phase-1: mở rộng noise và đánh giá lại thiết kế
|
| 2 |
+
|
| 3 |
+
Ngày: 2026-09-06. Audit dựa trên source đóng băng `efdaf6e74d81030e11dc1451ddc34a0878d5e03a` và hai full-model seed 42/43 đã hoàn tất. Thay đổi trong nhánh noise-v2 chỉ liên quan dữ liệu; không nóng sửa model, objective hoặc run đang train. Các thí nghiệm bên dưới là đề xuất, chưa được chạy.
|
| 4 |
+
|
| 5 |
+
## Kết luận chính
|
| 6 |
+
|
| 7 |
+
Thiếu noise thật là một vấn đề thực tế, nhưng không giải thích hết các kết quả Phase-1. Phiên bản hiện tại có decomposition clean-relative, song **chưa buộc dự đoán/tái tạo suy giảm phải đi qua đúng node**, và **chưa buộc cạnh tạo ra đúng tác dụng của một tổ hợp suy giảm**. Cần tách cải thiện dữ liệu khỏi thay đổi kiến trúc/objective để biết điều gì có hiệu quả.
|
| 8 |
+
|
| 9 |
+
Định nghĩa nên hướng tới là mã *tham số/toán tử suy giảm* có thể chuyển giữa các cảnh, tách khỏi *tác động quan sát được trên ảnh*. Noise phụ thuộc tín hiệu và haze phụ thuộc ảnh sạch; không phải mọi residual vật lý đều phải độc lập với content.
|
| 10 |
+
|
| 11 |
+
## 1. Vì sao noise ít và mở rộng có thể sửa điều gì
|
| 12 |
+
|
| 13 |
+
Manifest v1 dùng SIDD Small: 121 cặp train trên 8 cảnh vật lý, 19 cặp validation trên 1 cảnh, 20 cặp test trên 1 cảnh. Mỗi record được lấy một crop native 256×256/epoch. Run 5 epoch vì thế chỉ có **605 lượt crop noise thật**, ngoài noise tổng hợp online.
|
| 14 |
+
|
| 15 |
+
[RESIDE](https://sites.google.com/view/reside-dehaze-datasets/) là bộ dữ liệu dehazing, không phải bộ cặp noisy/clean cho denoising. Có thể lấy ảnh sạch từ đó để tạo noise tổng hợp, nhưng ảnh haze có sẵn không được đổi nhãn thành noise. Lần mở rộng này dùng DIV2K/Flickr2K làm nền sạch theo recipe DA-CLIP và giữ RESIDE ở nhóm haze.
|
| 16 |
+
|
| 17 |
+
Noise chiếm 0,17255% trong 70.124 record train; Snow chiếm 67,5503%. Với shuffle thông thường và B16, xác suất một batch có noise thật xấp xỉ 2,73%. Trọng số loss noise 82,791 không bổ sung ảnh, cảnh hay lượt lấy crop. Root/content loss cũng không có cùng trọng số theo loại. Nền sạch của synthetic controls được lấy từ batch real nên vẫn chịu lệch nguồn.
|
| 18 |
+
|
| 19 |
+
SIDD Medium có 320 cặp nhưng vẫn 10 cảnh vật lý; nó tăng số lần chụp, không nhân đôi số cảnh. PolyU OriginalImages được giữ cho external test, không đưa các crop dẫn xuất của nó vào train. DIV2K/Flickr2K bổ sung nền sạch đa dạng cho noise tổng hợp, dùng đúng split đang có của từng ảnh sạch để không rò rỉ content giữa JPEG và noise.
|
| 20 |
+
|
| 21 |
+
Với PolyU, group trong manifest là camera/object filename của ảnh nguồn. Chưa kiểm tra độc lập cảnh vật lý giữa mọi camera; không suy số group này thành số quan sát thống kê độc lập. SIDD thì dùng physical-scene ID do dataset cung cấp.
|
| 22 |
+
|
| 23 |
+
Nguồn:
|
| 24 |
+
|
| 25 |
+
- [SIDD của tác giả](https://abdokamel.github.io/sidd/): Small 160 cặp, Medium 320 cặp; Full khoảng 24.000 noisy training shots, không phải 24.000 cảnh. License MIT. Nguồn tải Medium được kiểm tra là HTTP; lưu SHA256 quan sát và kiểm CRC, không tuyên bố có xác thực mật mã từ checksum tác giả.
|
| 26 |
+
- [PolyU, phiên bản cố định](https://github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset/tree/3af0f2646b267a00446fe4b7113a15e67bc80b4e): phân biệt 40 cặp OriginalImages với 100 cặp crop dẫn xuất. Giữ [license phi thương mại/nghiên cứu](https://github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset/blob/3af0f2646b267a00446fe4b7113a15e67bc80b4e/License.txt). Chỉ các ảnh decode hợp lệ mới được nhận, có audit cho mọi loại bỏ.
|
| 27 |
+
- [DA-CLIP dataset recipe](https://github.com/Algolzw/daclip-uir#dataset-links): dùng DIV2K/Flickr2K để tạo noisy/JPEG. Đây không phải cùng phân phối với nhiễu cảm biến SIDD.
|
| 28 |
+
|
| 29 |
+
### Kết quả mở rộng đã kiểm chứng trên server
|
| 30 |
+
|
| 31 |
+
| Dữ liệu / split | Train | Validation | Test |
|
| 32 |
+
|---|---:|---:|---:|
|
| 33 |
+
| Noise thật v1 — SIDD Small | 121 | 19 | 20 |
|
| 34 |
+
| SIDD sau hợp nhất Small + Medium, loại trùng | 242 | 38 | 40 |
|
| 35 |
+
| PolyU ngoài miền | 0 | 0 | 40 |
|
| 36 |
+
| Noise tổng hợp DF2K, số record | 19.668 | 1.032 | 600 |
|
| 37 |
+
| Nội dung ảnh sạch DF2K riêng biệt theo decoded RGB | 3.221 | 170 | 100 |
|
| 38 |
+
| Tổng record của cả 7 loại trong manifest mới | 89.913 | 4.747 | 39.981 |
|
| 39 |
+
|
| 40 |
+
Đã decode thành công toàn bộ **720 file của 360 cặp mới** và đọc/hash lại **3.550 đường dẫn nền sạch**. Trong 320 cặp Medium có 160 cặp trùng decoded noisy+clean với Small: nhận thêm 160 cặp SIDD và 40 cặp PolyU, không có ảnh hỏng hoặc xung đột split cần loại. Các file nguồn không bị xóa; 160 cặp trùng được ghi trong quarantine của phần bổ sung.
|
| 41 |
+
|
| 42 |
+
3.550 đường dẫn DF2K tương ứng 3.491 nội dung RGB riêng biệt: có 57 đường dẫn lặp nội dung trong train và 2 trong validation, đã tồn tại ở parent. Giữ nguyên parent; sáu record theo profile×dose trên mỗi đường dẫn là **biến thể synthetic**, không phải sáu cảnh mới. Tổng phần thêm là **21.500 record noise = 200 cặp thật + 21.300 record synthetic**. Toàn bộ 134.641 ID là duy nhất; không có clean hash hoặc dataset/group tràn qua split.
|
| 43 |
+
|
| 44 |
+
Noise nay chiếm 22,1436% record train, nhưng **98,7845% record trong chính lớp noise là synthetic**; noise thật chỉ chiếm 0,26915% toàn train. Nếu giữ `class_weights` hiện tại, trọng số noise tự giảm từ **82,791 xuống 0,64514** vì hàm này cân bằng loại, không cân bằng real/synthetic trong cùng loại (`train_phase1_clean_relative.py:47`). Vì vậy không được hiểu “thêm dữ liệu” là tự động tăng mức ưu tiên cho noise thật. Đây là lý do cần ablation sampling real/synthetic riêng và báo chất lượng trên noise thật riêng trước khi chọn recipe.
|
| 45 |
+
|
| 46 |
+
## 2. Pipeline đang thực sự chạy
|
| 47 |
+
|
| 48 |
+
Ảnh I đi qua spatial CNN và wavelet. Một bank learned queries đọc hai nguồn bằng attention, rồi trao đổi qua query self-attention. Chỉ trạng thái query 0 được lấy làm global feature h. Từ đó có:
|
| 49 |
+
|
| 50 |
+
- `c(I)`: feature map spatial H/8;
|
| 51 |
+
- `Δ(I) = W h(I)`: mã global 256 chiều;
|
| 52 |
+
- `a_k = U_kᵀΔ`: tọa độ chiếu vào 7 known node và 2 free node;
|
| 53 |
+
- đóng góp của node `U_k a_k` và residual trực giao;
|
| 54 |
+
- các head presence, severity, photometric và decoder đều có thể đọc toàn bộ Δ.
|
| 55 |
+
|
| 56 |
+
Nguồn: `src/models/graph_encoder/clean_relative.py`, `_evidence`, `decompose`, `_representation`, `compose`, `decode`.
|
| 57 |
+
|
| 58 |
+
| Thành phần | Thiết kế ban đầu mong muốn | Hiện tại |
|
| 59 |
+
|---|---|---|
|
| 60 |
+
| Key của node | Bộ dò U_k tham gia routing theo degradation | U_k là basis chiếu sau global descriptor; attention đọc ảnh dùng learned queries khác |
|
| 61 |
+
| Value | Tọa độ biến thể trong đúng node | Có coefficients và basis contribution; consumer vẫn có thể đọc toàn bộ Δ |
|
| 62 |
+
| Severity | Một trục/coefficient có nghĩa vật lý | Giám sát norm của coefficients, đồng thời có head severity riêng trên Δ |
|
| 63 |
+
| Cạnh | Tương tác có tác dụng kiểm được lên ảnh | MLP trên hai toàn bộ Δ + type IDs, học latent MSE |
|
| 64 |
+
| Họ cha–con | Shared/private basis theo họ | Chưa có; một QR chung ép các basis trực giao |
|
| 65 |
+
| Free/OOD | Giải thích phần chưa biết và phát hiện OOD | Free/residual bị regularize mềm; OOD probe dùng 1−max presence, không dùng residual norm |
|
| 66 |
+
| Giao diện Phase-2 | Adapter cho legacy 8×256 | Hiện xuất 9 node contributions ×256 + residual; chưa tích hợp Phase-2 |
|
| 67 |
+
|
| 68 |
+
## 3. Điểm cần sửa trong định nghĩa node
|
| 69 |
+
|
| 70 |
+
### 3.1 Phép trừ theo cặp chưa tự triệt tiêu content
|
| 71 |
+
|
| 72 |
+
Teacher dùng cùng linear head:
|
| 73 |
+
|
| 74 |
+
`Δ_teacher(I,J) = W[h(I)−h(J)] = Δ(I)−Δ(J)`.
|
| 75 |
+
|
| 76 |
+
Đây là một reference theo cặp, không phải teacher độc lập cung cấp tri thức degradation khác student. Phép trừ feature phi tuyến không bảo đảm content triệt tiêu. Giá trị số của distillation error tương ứng clean Δ, nhưng target bị detach nên gradient không giống một root loss trực tiếp độc lập trên clean encoder.
|
| 77 |
+
|
| 78 |
+
`c(I)≈c(J)` chỉ ép consistency của c; không ngăn Δ đồng thời chứa content. Trong probe dự đoán thumbnail sạch 4×4 RGB trên các cảnh tách biệt, thêm Δ vào baseline type×severity giảm MSE **46,06% ở seed42 và 47,88% ở seed43**. Đây là bằng chứng về một kênh thông tin content cụ thể, không phải phép đo mutual information hay chứng minh mọi phụ thuộc content đều vô ích.
|
| 79 |
+
|
| 80 |
+
Teacher `(J,J)` bằng 0 theo cấu trúc, nhưng blind encoder của ảnh sạch chưa đạt cùng điều đó: clean false-positive là **8,34%/8,87%**, mean‖Δ(J)‖ là **1,6856/1,7007**. Norm phụ thuộc thang latent/parameterization; không dùng riêng trị số tuyệt đối ấy để quy nguyên nhân thất bại.
|
| 81 |
+
|
| 82 |
+
### 3.2 Node chưa phải đường bắt buộc
|
| 83 |
+
|
| 84 |
+
Presence/severity heads đọc toàn bộ Δ (`model:211–212,289–292`), decoder cũng vậy (`220,370–374`). Invariance xuyên content chỉ phủ coefficients của 7 known nodes (`trainer:365`), không phủ free/residual. Vì thế kiến trúc cho phép thông tin đi vòng qua node được định danh.
|
| 85 |
+
|
| 86 |
+
Chưa đo phân bổ năng lượng nên **chưa chứng minh residual là thủ phạm**. Thí nghiệm phù hợp là đo năng lượng known/free/residual rồi so sánh consumer nhận known coefficients, residual-on/off và full Δ, không mặc định phải bỏ residual hoàn toàn.
|
| 87 |
+
|
| 88 |
+
Rank1 không phải baseline thuần class×severity hoặc cùng dung lượng: Δ vẫn 256 chiều, không gian bù danh nghĩa tăng từ 184 lên 247 chiều; không gian Δ thực có thể đạt còn bị linear head 128→256 giới hạn.
|
| 89 |
+
|
| 90 |
+
### 3.3 Origin proxy hiện là clean autoencoder
|
| 91 |
+
|
| 92 |
+
Proxy đang đo `G(c(J),0)≈J`, tức đầu vào content đã lấy từ ảnh sạch (`trainer:294`; `eval:125`). Nó **không phải** kiểm tra `G(c(I),0)≈J` từ ảnh hỏng. Vì vậy PSNR origin khoảng 22,5 dB không chứng minh xóa Δ sẽ làm sạch ảnh hỏng.
|
| 93 |
+
|
| 94 |
+
Cần bổ sung test dirty-content/zero-Δ và can thiệp: bỏ factor k có xóa đúng k, đồng thời giữ các factor còn lại không? Đây mới gần với định nghĩa vận hành của node.
|
| 95 |
+
|
| 96 |
+
## 4. Điểm thiếu trong học quan hệ
|
| 97 |
+
|
| 98 |
+
Trong `synthetic_objective`:
|
| 99 |
+
|
| 100 |
+
1. Single/second/mixed gọi `pair_objective(...include_anchor=False)` (`trainer:354–355`).
|
| 101 |
+
2. Proxy nằm trong nhánh `include_anchor`, nên không được áp dụng cho ba nhánh này (`286–297`).
|
| 102 |
+
3. Composed code chỉ học MSE với mixed teacher code detach (`359–362`).
|
| 103 |
+
4. Decoder transfer chỉ được học cho single đầu tiên (`368–370`), chưa cho composed code.
|
| 104 |
+
5. Factor removal được đo trong evaluation nhưng chưa có loss can thiệp tương ứng trong training.
|
| 105 |
+
|
| 106 |
+
Vì vậy encoder và edge có thể học khớp latent mà decoder chưa bị buộc thực hiện đúng tác dụng của tổ hợp. Đây là giả thuyết cơ chế từ code, không phải chứng minh nguyên nhân duy nhất của số đo.
|
| 107 |
+
|
| 108 |
+
| Heldout pairs, cả hai thứ tự | Learned edge | Own additive baseline | Edge tăng lỗi |
|
| 109 |
+
|---|---:|---:|---:|
|
| 110 |
+
| Full seed42 | 0,02868761 | 0,02332736 | 22,98% |
|
| 111 |
+
| Full seed43 | 0,02798944 | 0,02263501 | 23,66% |
|
| 112 |
+
|
| 113 |
+
Đây là count-weighted **lỗi 15 thống kê residual** trên 256 cảnh × 3 cặp × 2 thứ tự. Mọi cặp đo đều có rain/noise/snow. Không phải PSNR hoặc pixel L1: aggregate forward pixel L1 cải thiện nhưng reverse pixel L1 xấu hơn ở cả hai seed. Không được kết luận mọi metric đều xấu đi hoặc pixel error tổng thể đều tốt lên. Mixture controls dùng strength trong miền train; nhãn heldout-severity chỉ áp dụng controlled singles. Cả hai thứ tự của seen pairs đều đã được train, chưa có kiểm tra thứ tự bị giữ lại độc lập.
|
| 114 |
+
|
| 115 |
+
Thí nghiệm tiếp theo cho cạnh phải thêm functional loss trên `G(c, compose(Δ_a,Δ_b))`, so với đúng ảnh tổng hợp theo thứ tự; tách metric ảnh và metric phân phối/thống kê của noise. Chỉ thử sau khi single-node semantics được kiểm tra.
|
| 116 |
+
|
| 117 |
+
## 5. Noise còn thiếu gì ngoài số lượng
|
| 118 |
+
|
| 119 |
+
Recipe cũ cố định `sigma=.12*s`, `shot=.04*s`; read/shot luôn cùng thay đổi theo một scalar severity. Thêm nhiều ảnh sạch với nguyên recipe đó không chứng minh node rank8 học được các biến thể noise nhiều chiều.
|
| 120 |
+
|
| 121 |
+
Hai profile noise-v2 tạo coverage rõ ràng hơn nhưng cũng chưa phải toàn bộ camera/ISP/noise distribution. Cần một bài kiểm tra riêng với read/shot thay đổi độc lập, correlation/màu và realization khác nhau, giữ profile giống nhau khi đổi content. Với real noise không có target vật lý, giữ severity mask unknown, không suy ISO hoặc nhãn dataset thành severity giả.
|
| 122 |
+
|
| 123 |
+
Cụ thể, Gaussian noise-v2 có `sigma=.12*s`, với `s∈{.2,.4,.6}`: tương đương σ **6,12 / 12,24 / 18,36** trên thang 0–255 trước clipping. Profile phụ thuộc tín hiệu dùng `sigma=.02*s`, `shot=.12*s` và variance `sigma²+shot²*clean_RGB`. Đây là hai đường tham số cố định, không phải lưới read/shot độc lập. Ta tham khảo **nguồn nền sạch** từ DA-CLIP, chưa tái lập protocol noise-level 50 được ghi trong [script sinh LQ của DA-CLIP](https://github.com/Algolzw/daclip-uir/blob/main/scripts/generate_LQ.py). Cần thêm evaluation theo σ vật lý rộng hơn trước khi kết luận về noise nặng; không coi dose chuẩn hóa giữa các profile là cùng mức residual quan sát được.
|
| 124 |
+
|
| 125 |
+
Decoder deterministic hiện khớp 15 thống kê residual (mean/std và gradient/Laplacian RMS), không mô hình đầy đủ phân phối corruption có điều kiện. Noise seed được dùng lại trong matched-parameter transfer; cần thêm test đổi realization. Eval v1 cố ý đánh dấu within-factor noise probe unsupported vì không có non-dose target độc lập.
|
| 126 |
+
|
| 127 |
+
Một hạn chế nhãn khác: real dataset trả one-hot theo domain. Ảnh LOL có thể còn noise, nhưng nhãn hiện coi noise absent. Cần phân biệt nhãn domain với multi-label cơ chế vật lý; synthetic multi-hot chưa sửa được mọi nhãn âm không chắc của ảnh real.
|
| 128 |
+
|
| 129 |
+
## 6. Những tín hiệu tích cực và giới hạn
|
| 130 |
+
|
| 131 |
+
| Probe full model | Seed42 R² | Seed43 R² |
|
| 132 |
+
|---|---:|---:|
|
| 133 |
+
| Haze airlight, thêm coefficients ngoài severity | 0,3911 | 0,2533 |
|
| 134 |
+
| Blur orientation | −0,0600 | 0,1902 |
|
| 135 |
+
| Rain orientation | −0,0460 | −0,0072 |
|
| 136 |
+
|
| 137 |
+
Haze có tín hiệu lặp lại; blur có tín hiệu phụ thuộc seed, không thể nói hoàn toàn không học được. Test noise F1 0,1242/0,1556 chỉ có support20; seed43 recall0,70 nhưng precision0,0875. F1 thấp không đơn giản nghĩa là model không nhận biết noise; nhiều false positive đến từ domain khác, nhất là Rain/Snow.
|
| 138 |
+
|
| 139 |
+
Cả 7 severity regressions đều có R² âm trên controlled singles ngoại suy: train strength [0,08;0,70], test [0,80;0,98]. Noise MAE là 0,18208/0,21443. Đây là thất bại của phép thử ngoại suy cụ thể, với target variance nhỏ; không chứng minh model không học severity trong miền train. Evaluation tiếp theo cần tách interpolation và extrapolation.
|
| 140 |
+
|
| 141 |
+
Các kết quả này mới 5 epoch, chưa chứng minh hội tụ. OOD hiện chỉ là central-gray-occlusion probe; chưa có leave-type/family-out retraining. V1 còn giới hạn RESIDE subset, SIDD Small, Snow test S/L thiếu M và một crop cố định mỗi ảnh real. Noise-v2 không tự sửa các giới hạn của những bộ còn lại.
|
| 142 |
+
|
| 143 |
+
## 7. Chuỗi thí nghiệm nên làm sau data expansion
|
| 144 |
+
|
| 145 |
+
1. **Data-only:** giữ nguyên model/objective, khởi tạo from-scratch cùng seed; đánh giá lại trên legacy test cố định, expanded real-noise và synthetic-noise riêng. Không gộp hàng trăm synthetic samples vào để che kết quả noise thật. Tách `expanded-real-only` và `expanded-real+synthetic` nếu cần quy đóng góp: thêm synthetic records cũng bổ sung target severity và thay đổi phân bố noise profiles, không chỉ tăng ảnh SIDD; chưa có head/loss phân loại profile riêng. So sánh matched optimizer-step budget; 5 epoch trên manifest lớn không phải cùng compute. Nếu dùng full-coverage budget thì báo riêng.
|
| 146 |
+
2. **Sampling-only:** giữ data/model, thử cân bằng loại rồi cân bằng real/synthetic noise, chọn scene→capture→crop; tăng crop exposures của ảnh noise thật. Báo exposure và số ảnh/cảnh riêng. Không trộn đây vào ablation data-only.
|
| 147 |
+
3. **Node-only:** energy audit, consumer restriction/residual ablations; test `G(c(I),0)`, drop-one/retain-others, parameter probe ngoài severity, đổi realization giữ noise profile.
|
| 148 |
+
4. **Relation-only:** explicit mixed/composed functional loss; addition vs ordered correction, heldout pairs và thứ tự; chỉ thay objective này trong lượt so sánh tương ứng.
|
| 149 |
+
5. **Family/open-set:** sau khi node có ý nghĩa kiểm được, mới thử shared/private family basis và leave-type/family-out. Adapter Phase-2 là một thí nghiệm riêng.
|
| 150 |
+
|
| 151 |
+
Phần data-only cần giữ model/objective cũ nhưng dùng loader biết schema noise mới. Manifest mới dùng **schema 2**: frozen loader v1 sẽ từ chối ngay ở bước kiểm schema, trước khi có thể đọc nhầm ảnh nguồn sạch thành noisy image. Loader mới vẫn đọc được manifest v1; hạ schema của record noise tổng hợp xuống v1 cũng bị từ chối. Cũng không tái sử dụng nguyên launcher v1 vốn khóa manifest/source hash và ngân sách. Chưa khởi chạy bất kỳ training noise-v2 nào trong thay đổi này.
|
| 152 |
+
|
| 153 |
+
## 8. Artifact, tái lập và kiểm chứng
|
| 154 |
+
|
| 155 |
+
Nhánh dữ liệu riêng: `codex/phase1-noise-expansion`. Bản v1 đang chạy vẫn dùng release `/home/vunguyen/SCDC_releases/phase1_seven_efdaf6e`; không sửa release này, checkpoint, GPU mapping hoặc queue. Không tải SIDD Full trong đợt này, không sửa model/trainer/evaluator/sampler, không khởi chạy training noise-v2.
|
| 156 |
+
|
| 157 |
+
Server `kim.long-mi325x8`:
|
| 158 |
+
|
| 159 |
+
```text
|
| 160 |
+
Data root: /data/vunguyen13/SCDC_data/phase1_noise_20260906
|
| 161 |
+
Code: /data/vunguyen13/SCDC_data/phase1_noise_20260906/code
|
| 162 |
+
Manifest: /data/vunguyen13/SCDC_data/phase1_noise_20260906/manifest_noise_v2.json
|
| 163 |
+
Audit: /data/vunguyen13/SCDC_data/phase1_noise_20260906/manifest_build.audit.json
|
| 164 |
+
CPU check: /data/vunguyen13/SCDC_data/phase1_noise_20260906/actual_loader_verification.json
|
| 165 |
+
Python: /home/vunguyen/miniforge3/envs/mavt/bin/python
|
| 166 |
+
```
|
| 167 |
+
|
| 168 |
+
Manifest SHA256: `93212a3f2fa35db6511925c883c2c16a648a19dbe714fb76fd88c1f150d46c9f`.
|
| 169 |
+
|
| 170 |
+
Parent SHA256 không đổi: `8f7be16638ee544eb97245871ce1c6d884920bb2973c14a64a09e4db64f88e24`.
|
| 171 |
+
|
| 172 |
+
Các receipt tải/giải nén cùng root giữ URL, license, kích thước và SHA256 quan sát. Hai archive được verifier đọc và hash lại độc lập:
|
| 173 |
+
|
| 174 |
+
- SIDD Medium, 13.234.744.070 byte: `4387022a7bf1a35e2ebdc0c1c09697a5f964ea102b7fdcf5c0d8a38a1b233f98`.
|
| 175 |
+
- PolyU, 134.609.548 byte: `30a5c5739af1b27b3d3b8f68c1e2b00d0dd8d1ab836bb545377fe0e4dbfdd477`.
|
| 176 |
+
|
| 177 |
+
95 test tập trung pass trên local và server; reviewer độc lập chạy 124 test liên quan/legacy đều pass. Kiểm tra CPU trên ảnh thật pass 21 so sánh loader cũ/mới (7 loại × 3 split) và 13 mẫu đại diện noise theo source/profile/split: đúng native crop 256, không có identity giả, real severity không bị gán giả, noise tổng hợp đổi realization theo epoch train và replay cố định khi eval. Đây là smoke test đại diện cho loader, **không phải** đánh giá model trên toàn bộ manifest; kiểm decode/hash của dữ liệu mới là đầy đủ.
|
| 178 |
+
|
| 179 |
+
Kiểm tra hash trong bộ mở rộng luôn decode mới, bỏ qua cache theo size/mtime của helper cũ. Có regression test thay pixel nhưng giữ nguyên size và timestamp. Manifest được publish nguyên vẹn, từ chối overwrite; source hashes của generator/helper/loader nằm trong audit. Mọi record và split của parent được giữ nguyên và đã được verifier kiểm trực tiếp.
|
dataset/phase1_noise_20260906/code/docs/project_progress_and_ideas_2026-08-30.md
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
dataset/phase1_noise_20260906/code/docs/proposal_dose_guided_finetune_2026-09-02.md
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Đề xuất fine-tune: Dose-Guided Fine-Tuning (DGF) cho SCDC v7
|
| 2 |
+
|
| 3 |
+
*2026-09-02 — dựa trên probe §13.18 (head8k, 27,43/0,846).*
|
| 4 |
+
|
| 5 |
+
## 1. Bài toán, phát biểu hình thức
|
| 6 |
+
|
| 7 |
+
Trunk học f_θ(u_t, u_y, c) ≈ E[u₀ | u_t, u_y, c] với c = Φ(y) là biểu diễn graph của Phase-1.
|
| 8 |
+
Phân phối huấn luyện chỉ chứa y bị suy hoá trong dải đã thấy. Với input cần hiệu chỉnh
|
| 9 |
+
**nhỏ hơn liều trung bình của lớp** (ảnh sạch, ảnh nhẹ, ảnh có GT tối hơn kỳ vọng của lớp),
|
| 10 |
+
kỳ vọng có điều kiện bị kéo về hiệu chỉnh trung bình → *over-restoration*.
|
| 11 |
+
|
| 12 |
+
Bằng chứng đo được (probe, inference-time ablation trên full val):
|
| 13 |
+
|
| 14 |
+
| Quan sát | Số đo |
|
| 15 |
+
|---|---|
|
| 16 |
+
| Tắt `context` → lowlight | **+1,95 dB** (20,73 > gen-2 20,3) |
|
| 17 |
+
| Tắt `global_vector` → lowlight | +0,55 dB |
|
| 18 |
+
| scene008 (input 39,0 dB) → output | 27,1 dB (−11,9) |
|
| 19 |
+
| MoE gate / κ per-type / routing / severity | ≈ 0 đóng góp (gate-uniform −0,085) |
|
| 20 |
+
| Rút toàn bộ Phase-1 | −7,79 (19,64 ≈ degraded 18,91) |
|
| 21 |
+
|
| 22 |
+
Kết luận cấu trúc: c là **cú đẩy phân loại** vào attention/adaLN; hệ không có bậc tự do
|
| 23 |
+
"cường độ". Các tín hiệu được thiết kế cho việc đó (severity, κ per-type, strengths)
|
| 24 |
+
không được trunk dùng.
|
| 25 |
+
|
| 26 |
+
## 2. Liên hệ nghiên cứu
|
| 27 |
+
|
| 28 |
+
- **Điều khiển cường độ phục hồi (CNN)**: Deep Network Interpolation (Wang et al., CVPR 2019),
|
| 29 |
+
AdaFM (He et al., CVPR 2019), CFSNet — một knob liên tục cho strength. DGF là phiên bản
|
| 30 |
+
cho diffusion có điều kiện.
|
| 31 |
+
- **Classifier-free guidance** (Ho & Salimans, 2022): ε̂ = ε(∅) + w·(ε(c) − ε(∅)). Sinh ảnh dùng
|
| 32 |
+
w > 1 (bám điều kiện ↔ đa dạng). Phục hồi cần fidelity với input → khai thác miền **w ≤ 1**
|
| 33 |
+
("under-guidance"), ít được nghiên cứu. Guidance interval (Kynkäänniemi et al., 2024),
|
| 34 |
+
Autoguidance (Karras et al., 2024), CFG-rescale, và các phương pháp CFG động theo feedback
|
| 35 |
+
(arXiv 2509.16131) đều hội tụ về một điểm: **w là knob theo mẫu và theo bước, không phải hằng**.
|
| 36 |
+
- **Restoration diffusion có knob**: StableSR (CFW blend feature), DiffBIR/SUPIR (CFG với negative
|
| 37 |
+
prompt); DA-CLIP: condition embedding, không có liều.
|
| 38 |
+
- **Identity / over-processing trong all-in-one**: báo cáo LoViF 2026 (arXiv 2604.19445) ghi nhận
|
| 39 |
+
practice thay input bằng GT với p = 0,15 + identity loss; các work 2025 thêm "degradation
|
| 40 |
+
intensity head" để chỉnh strength theo mức độ suy hoá. Thành phần identity của DGF là practice
|
| 41 |
+
đã được cộng đồng hội tụ.
|
| 42 |
+
- **LoRA cho AIO diffusion**: Degradation-Aware LoRA (arXiv 2508.03373) — phương án B của DGF.
|
| 43 |
+
|
| 44 |
+
## 3. Phương pháp
|
| 45 |
+
|
| 46 |
+
### 3.1 Học nhánh null (conditioning dropout)
|
| 47 |
+
Trong fine-tune, với xác suất **p = 0,15** thay c bằng ∅: **token null học được** cho `context`
|
| 48 |
+
(8 token) và vector null cho `global_vector`, khởi tạo 0 (trùng ablation đã đo). Giữ nguyên
|
| 49 |
+
u_y — nhánh null vẫn thấy ảnh vào, chỉ mất chẩn đoán của Phase-1. Một mạng, hai hành vi.
|
| 50 |
+
Mất mát composite hiện hành không đổi.
|
| 51 |
+
|
| 52 |
+
### 3.2 Neo identity
|
| 53 |
+
Với xác suất **q = 0,10** dùng cặp sạch–sạch (x, x): buộc f(x) = x cho cả nhánh c (Phase-1 nhìn
|
| 54 |
+
ảnh sạch) lẫn nhánh ∅. Đây là nơi Phase-1 học "sạch" nghĩa là gì trong không gian điều kiện.
|
| 55 |
+
|
| 56 |
+
### 3.3 Inference: liều theo mẫu
|
| 57 |
+
x̂₀^(w) = x̂₀(∅) + w · (x̂₀(c) − x̂₀(∅)), trên không gian dự đoán x₀ (ResShift dự đoán x₀).
|
| 58 |
+
Áp ở **bước coarse t = 2** (quyết định toàn cục: exposure, màu, độ mù); bước fine t = 1 chạy
|
| 59 |
+
full-c (chi tiết) — biến thể "guidance interval". Đối chứng: áp cả hai bước.
|
| 60 |
+
|
| 61 |
+
Chọn w — ba mức, tăng dần:
|
| 62 |
+
1. **Hằng theo domain**, sweep trên val (baseline minh bạch).
|
| 63 |
+
2. **w = g(s)**, s = severity/độ tin cậy của Phase-1, g đơn điệu calibrate trên nửa val
|
| 64 |
+
(isotonic). Ảnh sạch → s ≈ 0 → w ≈ 0 → identity (đóng scene008); lowlight → w nhỏ;
|
| 65 |
+
noise/haze nặng → w ≈ 1. Đây là nơi severity coords có việc thật.
|
| 66 |
+
3. Head nhỏ dự đoán w từ c (tuỳ chọn, rủi ro overfit).
|
| 67 |
+
|
| 68 |
+
Chi phí: thêm 1 forward ở bước coarse → 3 forward thay vì 2 (+50 %). Distill sau nếu cần.
|
| 69 |
+
|
| 70 |
+
### 3.4 Cái gì được fine-tune
|
| 71 |
+
- **A (đề xuất chính)**: full trunk + head, warm-restart từ head8k, LR 3e-5 cosine 8k, EMA,
|
| 72 |
+
DDP — công thức đã chứng minh zero-drift. Thêm: token null (context 8×256, global 1×d).
|
| 73 |
+
- **B (nếu A làm tụt nhánh c > 0,1 dB)**: LoRA rank 8–16 chỉ trên hai đường sống
|
| 74 |
+
(k/v projection của cross-attention, `global_embedding`, Linear modulation của LeWin)
|
| 75 |
+
+ token null; đóng băng phần còn lại. Probe cho biết chính xác nơi conditioning đi vào,
|
| 76 |
+
nên LoRA đặt trúng chỗ và bảo toàn nghiệm head8k.
|
| 77 |
+
|
| 78 |
+
## 4. Dự đoán định lượng (kiểm chứng được)
|
| 79 |
+
|
| 80 |
+
| Đại lượng | Dự đoán |
|
| 81 |
+
|---|---|
|
| 82 |
+
| Lowlight, w ∈ [0, 0,3] tại coarse | ≥ +1,5 dB (cận trên đã đo +1,95 với nhánh null *chưa* train); mục tiêu ≥ 20,3 |
|
| 83 |
+
| Noise/haze/rain tại w = 1 | giữ ≥ 27,3 macro (dự phòng −0,1 do dropout) |
|
| 84 |
+
| scene008 | PSNR_out ≥ PSNR_in − 1 dB (hiện −11,9); LPIPS < 0,1 |
|
| 85 |
+
| Macro nội bộ | ≥ 27,8 nếu lowlight đạt 20,3 → vượt gen-2 (27,55) cả nội bộ |
|
| 86 |
+
|
| 87 |
+
## 5. Protocol đánh giá
|
| 88 |
+
|
| 89 |
+
1. Một run fine-tune 8k DDP (≈ 2 h).
|
| 90 |
+
2. Sweep w ∈ {0, 0,25, 0,5, 0,75, 1, 1,25, 1,5} × {coarse-only, both} trên val theo domain → bảng 2 chiều.
|
| 91 |
+
3. Calibrate g(s) trên nửa val, kiểm trên nửa còn lại (không chọn w trên tập báo cáo).
|
| 92 |
+
4. External 3 bộ locked + **identity test**: PSNR(f(x), x) trên ảnh sạch.
|
| 93 |
+
5. Seed 43 lặp fine-tune để có độ lệch chuẩn.
|
| 94 |
+
|
| 95 |
+
Tiêu chí thành công: lowlight ≥ 20,3 · macro ≥ 27,6 · scene008 ≥ 35 · external rain/haze không giảm > 0,1.
|
| 96 |
+
|
| 97 |
+
## 6. Rủi ro và đối sách
|
| 98 |
+
|
| 99 |
+
- Dropout làm yếu nhánh c → p nhỏ, theo dõi eval w = 1 mỗi 1k; fallback LoRA (B).
|
| 100 |
+
- Ngoại suy w > 1 trong x₀-space gây artifact → clamp [0, 1] mặc định; nếu thử w > 1 dùng rescale.
|
| 101 |
+
- Nhánh null học "phục hồi trung bình" thay vì identity → chính vì thế cần q > 0.
|
| 102 |
+
- g(s) phụ thuộc calibration severity Phase-1 (ρ = 0,58) → bắt đầu bằng per-domain, g(s) là nâng cấp.
|
| 103 |
+
- DDP: dropout bằng cách *thay token* (không bỏ nhánh) → graph không đổi → an toàn với find_unused.
|
| 104 |
+
|
| 105 |
+
## 7. Đóng góp
|
| 106 |
+
|
| 107 |
+
1. Định lượng lần đầu hiện tượng **conditioning over-drive** trong AIO diffusion (probe) và
|
| 108 |
+
chuyển guidance scale từ knob sinh ảnh (w > 1) thành **knob liều phục hồi** (w ≤ 1).
|
| 109 |
+
2. Đóng vòng representation → dose: severity của graph điều khiển w — tinh thần "expert chọn
|
| 110 |
+
trên graph" đặt ở nơi nó thực sự có tác dụng.
|
| 111 |
+
3. Một mạng, không refiner, không mạng phụ; chi phí +1 forward.
|
| 112 |
+
|
| 113 |
+
## Nguồn
|
| 114 |
+
|
| 115 |
+
- Ho & Salimans, *Classifier-Free Diffusion Guidance*, 2022.
|
| 116 |
+
- Kynkäänniemi et al., *Applying Guidance in a Limited Interval*, 2024. · Karras et al., *Autoguidance*, 2024.
|
| 117 |
+
- Dynamic CFG via online feedback: https://arxiv.org/pdf/2509.16131 · Revisiting CFG methods: https://arxiv.org/html/2608.16786
|
| 118 |
+
- LoViF 2026 AIO challenge report (identity replacement p = 0,15): https://arxiv.org/pdf/2604.19445
|
| 119 |
+
- Degradation-Aware LoRA for AIO diffusion: https://arxiv.org/pdf/2508.03373
|
| 120 |
+
- Uncertainty-aware diffusion bridge AIO: https://arxiv.org/pdf/2601.21592 · GenDeg: https://arxiv.org/abs/2411.17687
|
| 121 |
+
- AIO survey (TPAMI 2025): https://github.com/Harbinzzy/All-in-One-Image-Restoration-Survey
|
| 122 |
+
- Wang et al., *Deep Network Interpolation*, CVPR 2019 · He et al., *AdaFM*, CVPR 2019.
|
| 123 |
+
|
| 124 |
+
## 3.5 Decoder coarse-to-fine: Laplacian residual heads + liều theo thang (bổ sung 2026-09-02)
|
| 125 |
+
|
| 126 |
+
Hiện đường up của UNet đưa ra state 12-kênh một lần ở 128 px (half-res), rồi tail sửa ở 256 px.
|
| 127 |
+
Coarse-to-fine đúng nghĩa: mỗi tầng decoder **cam kết một ước lượng ở thang của nó**, tầng
|
| 128 |
+
sau chỉ thêm dải tần cao hơn.
|
| 129 |
+
|
| 130 |
+
**Tháp Laplacian với anchor u_y (giữ identity chính xác).** Gọi D_s là downsample về thang s
|
| 131 |
+
(16/32/64/128 px trong không gian state), U là upsample ×2 cố định. Định nghĩa dải tần của anchor
|
| 132 |
+
L_s(u_y) = D_s(u_y) − U(D_{s/2}(u_y)) (L_16 = D_16(u_y)). Mỗi tầng decoder có head zero-init
|
| 133 |
+
δ_s (12 kênh); ước lượng đệ quy:
|
| 134 |
+
|
| 135 |
+
u_16 = L_16(u_y) + δ_16
|
| 136 |
+
u_s = U(u_{s/2}) + L_s(u_y) + δ_s s = 32, 64, 128
|
| 137 |
+
x̂ = shuffle(u_128) + tail(...) tầng 256 px = dải cuối
|
| 138 |
+
|
| 139 |
+
Vì tổng telescoping của các L_s tái tạo đúng u_y, khi mọi δ = 0 thì u_128 = u_y — **warm-start
|
| 140 |
+
từ head8k giữ bitwise** (head hiện có trở thành δ_128, các head mới zero-init).
|
| 141 |
+
|
| 142 |
+
**Deep supervision.** Bước coarse: MSE(u_s, D_s(u_0)) với trọng số λ = 0,1 / 0,2 / 0,3 cho 16 / 32 / 64 px,
|
| 143 |
+
cộng mất mát 128 px hiện hành. Bước fine: composite full-res không đổi (L1 + VGG + chroma + luma
|
| 144 |
+
trên ảnh sau tail). Mỗi tầng học đúng dải tần của mình: tone/exposure/màu ở 16–32 px (nơi FiLM và
|
| 145 |
+
LL-global sống), cạnh và texture ở 64–128 px, noise residual ở 256 px.
|
| 146 |
+
|
| 147 |
+
**Liều theo thang (guidance interval trên không gian thang).** Kết hợp với §3.3: nội suy nhánh
|
| 148 |
+
∅/c **theo từng dải**, δ_s^(w) = δ_s(∅) + w_s·(δ_s(c) − δ_s(∅)), với lịch w_16 = w (liều toàn cục),
|
| 149 |
+
w_s tăng dần về 1 ở 128/256 px. Ý nghĩa: chẩn đoán của Phase-1 quyết định *bao nhiêu* ở thang
|
| 150 |
+
thô (exposure, màu, độ mù), còn chi tiết luôn được điều kiện đầy đủ. Phiên bản đầu dùng một w
|
| 151 |
+
chung cho bước coarse; lịch theo thang là ablation.
|
| 152 |
+
|
| 153 |
+
**Chi phí / rủi ro.** Ba head 1×1 (vài nghìn tham số), dải Laplacian tính từ u_y (rẻ), ba mất mát
|
| 154 |
+
phụ ở thang thấp (rẻ). Rủi ro chính: deep supervision ở thang thô có thể làm mờ nếu λ quá lớn —
|
| 155 |
+
giữ λ nhỏ và chỉ MSE (không perceptual) ở thang thô.
|
| 156 |
+
|
| 157 |
+
**Một run duy nhất.** DGF (§3.1–3.3) + tháp coarse-to-fine (§3.5) đều zero-init/identity tại
|
| 158 |
+
khởi tạo → eval@0 trùng head8k; các thành phần trực giao nên có thể ablate bằng cách tắt từng
|
| 159 |
+
phần ở inference.
|
dataset/phase1_noise_20260906/code/docs/staged_training_plan.md
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Staged Training Plan for Relation-Aware DC-AE
|
| 2 |
+
|
| 3 |
+
## Overview
|
| 4 |
+
|
| 5 |
+
This document describes the staged training strategy for the Relation-Aware DC-AE encoder, following the plan in `relation_aware_dcae_suggested_changes.md`.
|
| 6 |
+
|
| 7 |
+
## Current Status
|
| 8 |
+
|
| 9 |
+
### Implemented
|
| 10 |
+
- `src/models/relation_aware_encoder.py` - Full relation-aware encoder architecture
|
| 11 |
+
- `tests/test_relation_aware_encoder.py` - 28 passing tests
|
| 12 |
+
|
| 13 |
+
### Key Components
|
| 14 |
+
1. **Dual Relation Transformer Block** - Spatial + Channel attention with adaptive gate
|
| 15 |
+
2. **Multi-Scale Feature Extraction** - F32, F16, F8, F4 memory
|
| 16 |
+
3. **DegradationQueryAttention** - 4 learnable degradation queries
|
| 17 |
+
4. **LatentQueryAttention** - 16 latent queries for reconstruction
|
| 18 |
+
5. **OrthogonalityRegularization** - Node diversity regularization
|
| 19 |
+
|
| 20 |
+
---
|
| 21 |
+
|
| 22 |
+
## Staged Training Strategy
|
| 23 |
+
|
| 24 |
+
### Stage A: Structural Replacement
|
| 25 |
+
|
| 26 |
+
**Goal**: Replace late DC-AE stages with relation blocks, keep everything else frozen.
|
| 27 |
+
|
| 28 |
+
```
|
| 29 |
+
Frozen:
|
| 30 |
+
- Early DC-AE encoder layers
|
| 31 |
+
- DC-AE decoder
|
| 32 |
+
|
| 33 |
+
Trainable:
|
| 34 |
+
- Dual Relation Blocks (32×32, 16×16, 8×8, 4×4)
|
| 35 |
+
- Multi-scale projection
|
| 36 |
+
- Latent query head
|
| 37 |
+
- Degradation query head
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
**Training objective**:
|
| 41 |
+
```
|
| 42 |
+
L = λ_rec * L_reconstruction + λ_latent * L_latent_preservation
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Where:
|
| 46 |
+
- `L_reconstruction`: L1 loss between decoded image and original
|
| 47 |
+
- `L_latent_preservation`: L1 loss between new latent and DC-AE latent
|
| 48 |
+
|
| 49 |
+
**Duration**: 20-30 epochs
|
| 50 |
+
**Expected outcome**: Relation blocks learn to preserve reconstruction while introducing relational modeling.
|
| 51 |
+
|
| 52 |
+
---
|
| 53 |
+
|
| 54 |
+
### Stage B: Multi-Scale Relation Modeling
|
| 55 |
+
|
| 56 |
+
**Goal**: Enable degradation query attention to access multi-scale memory.
|
| 57 |
+
|
| 58 |
+
```
|
| 59 |
+
Frozen:
|
| 60 |
+
- Early DC-AE encoder
|
| 61 |
+
- DC-AE decoder
|
| 62 |
+
- Relation blocks from Stage A
|
| 63 |
+
|
| 64 |
+
Trainable:
|
| 65 |
+
- Degradation query attention
|
| 66 |
+
- Node projection MLP
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
**Training objective**:
|
| 70 |
+
```
|
| 71 |
+
L = λ_deg * L_degradation + λ_node * L_node_diversity
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Where:
|
| 75 |
+
- `L_degradation`: Clean-degraded displacement loss
|
| 76 |
+
- `L_node_diversity`: Orthogonality regularization on nodes
|
| 77 |
+
|
| 78 |
+
**Duration**: 20-30 epochs
|
| 79 |
+
**Expected outcome**: Nodes learn to capture different degradation axes.
|
| 80 |
+
|
| 81 |
+
---
|
| 82 |
+
|
| 83 |
+
### Stage C: End-to-End Fine-tuning
|
| 84 |
+
|
| 85 |
+
**Goal**: Fine-tune the complete encoder with all objectives.
|
| 86 |
+
|
| 87 |
+
```
|
| 88 |
+
Trainable:
|
| 89 |
+
- Everything (relation blocks, queries, projections)
|
| 90 |
+
- Optional: decoder
|
| 91 |
+
|
| 92 |
+
Frozen:
|
| 93 |
+
- DC-AE teacher (for latent preservation)
|
| 94 |
+
```
|
| 95 |
+
|
| 96 |
+
**Training objective**:
|
| 97 |
+
```
|
| 98 |
+
L = λ_rec * L_reconstruction
|
| 99 |
+
+ λ_latent * L_latent_preservation
|
| 100 |
+
+ λ_deg * L_degradation
|
| 101 |
+
+ λ_node * L_node_diversity
|
| 102 |
+
+ λ_clean * L_clean_anchor
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
**Duration**: 10-20 epochs
|
| 106 |
+
**Expected outcome**: All components jointly optimized for degradation representation.
|
| 107 |
+
|
| 108 |
+
---
|
| 109 |
+
|
| 110 |
+
## Integration with Stage B v2
|
| 111 |
+
|
| 112 |
+
### Current Pipeline (Stage B v2)
|
| 113 |
+
|
| 114 |
+
```
|
| 115 |
+
Image [B, 3, 256, 256]
|
| 116 |
+
↓
|
| 117 |
+
DC-AE Encoder (frozen)
|
| 118 |
+
↓
|
| 119 |
+
Latent [B, 128, 4, 4]
|
| 120 |
+
↓
|
| 121 |
+
dcae_descriptor()
|
| 122 |
+
↓
|
| 123 |
+
Descriptor [B, 512]
|
| 124 |
+
↓
|
| 125 |
+
DescriptorNodeProjector
|
| 126 |
+
↓
|
| 127 |
+
4 × Node [B, 4, 16]
|
| 128 |
+
↓
|
| 129 |
+
OrderedGraphComposer
|
| 130 |
+
↓
|
| 131 |
+
Composed displacement [B, 64]
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
### Proposed Pipeline (with Relation-Aware Encoder)
|
| 135 |
+
|
| 136 |
+
```
|
| 137 |
+
Image [B, 3, 256, 256]
|
| 138 |
+
↓
|
| 139 |
+
Relation-Aware DC-AE Encoder
|
| 140 |
+
├── Early DC-AE (frozen)
|
| 141 |
+
├── Dual Relation Blocks (trainable)
|
| 142 |
+
└── Multi-Scale Memory
|
| 143 |
+
↓
|
| 144 |
+
┌───────┴───────┐
|
| 145 |
+
↓ ↓
|
| 146 |
+
Latent Queries Degradation Queries
|
| 147 |
+
↓ ↓
|
| 148 |
+
[B, 128, 4, 4] [B, 4, 256]
|
| 149 |
+
↓ ↓
|
| 150 |
+
DC-AE Decoder NodeQueryProjector
|
| 151 |
+
↓
|
| 152 |
+
[B, 4, 16]
|
| 153 |
+
↓
|
| 154 |
+
OrderedGraphComposer
|
| 155 |
+
↓
|
| 156 |
+
Composed displacement [B, 64]
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
---
|
| 160 |
+
|
| 161 |
+
## New Training Losses
|
| 162 |
+
|
| 163 |
+
### For Relation-Aware Encoder
|
| 164 |
+
|
| 165 |
+
```python
|
| 166 |
+
# Degradation displacement loss
|
| 167 |
+
def degradation_displacement_loss(nodes_degraded, nodes_clean):
|
| 168 |
+
"""Clean images should have nodes near origin."""
|
| 169 |
+
return nodes_clean.norm(dim=-1).mean()
|
| 170 |
+
|
| 171 |
+
# Node orthogonality loss
|
| 172 |
+
def node_orthogonality_loss(nodes):
|
| 173 |
+
"""Nodes should represent different degradation axes."""
|
| 174 |
+
nodes_norm = F.normalize(nodes, dim=-1)
|
| 175 |
+
similarity = torch.bmm(nodes_norm, nodes_norm.transpose(1, 2))
|
| 176 |
+
mask = 1 - torch.eye(nodes.shape[1], device=nodes.device).unsqueeze(0)
|
| 177 |
+
return (similarity * mask).abs().sum() / mask.sum()
|
| 178 |
+
|
| 179 |
+
# Latent preservation loss
|
| 180 |
+
def latent_preservation_loss(latent_new, latent_dcae):
|
| 181 |
+
"""New latent should match DC-AE latent structure."""
|
| 182 |
+
return F.l1_loss(latent_new, latent_dcae.detach())
|
| 183 |
+
```
|
| 184 |
+
|
| 185 |
+
---
|
| 186 |
+
|
| 187 |
+
## Ablation Variants
|
| 188 |
+
|
| 189 |
+
Following the plan in `relation_aware_dcae_suggested_changes.md`:
|
| 190 |
+
|
| 191 |
+
| Variant | Description |
|
| 192 |
+
|---------|-------------|
|
| 193 |
+
| A0 | Original DC-AE + handcrafted descriptor (baseline) |
|
| 194 |
+
| A1 | Original DC-AE + Transformer descriptor |
|
| 195 |
+
| A2 | Original DC-AE + Node Query Attention |
|
| 196 |
+
| A3 | Replace late EfficientViT blocks with Dual Relation blocks |
|
| 197 |
+
| A4 | A3 + multi-scale relation memory |
|
| 198 |
+
| A5 | A4 + latent query aggregation |
|
| 199 |
+
| A6 | A5 + degradation query head |
|
| 200 |
+
| A7 | A6 + relation block at 64×64 |
|
| 201 |
+
| A8 | A7 + learnable PixelUnshuffle residual projection |
|
| 202 |
+
| A9 | A8 + optional frequency memory |
|
| 203 |
+
|
| 204 |
+
**Recommended first implementation**: A6 (full relation-aware with late blocks only)
|
| 205 |
+
|
| 206 |
+
---
|
| 207 |
+
|
| 208 |
+
## Next Steps
|
| 209 |
+
|
| 210 |
+
1. **Hook DC-AE encoder** to extract multi-scale features (F32, F16, F8, F4)
|
| 211 |
+
2. **Create training script** for Stage A (reconstruction + latent preservation)
|
| 212 |
+
3. **Integrate with stage_b_v2** by replacing `dcae_descriptor()` + `DescriptorNodeProjector`
|
| 213 |
+
4. **Run ablation A0-A6** to isolate improvements
|
| 214 |
+
|
| 215 |
+
---
|
| 216 |
+
|
| 217 |
+
## Memory Requirements
|
| 218 |
+
|
| 219 |
+
With the relation-aware encoder:
|
| 220 |
+
|
| 221 |
+
| Component | Memory Estimate (FP32) |
|
| 222 |
+
|-----------|----------------------|
|
| 223 |
+
| Dual Relation Blocks (4 stages) | ~200M params |
|
| 224 |
+
| Query Attention | ~50M params |
|
| 225 |
+
| Projections | ~10M params |
|
| 226 |
+
| **Total trainable** | ~260M params |
|
| 227 |
+
|
| 228 |
+
For comparison:
|
| 229 |
+
- DC-AE encoder: ~700M params (frozen)
|
| 230 |
+
- Stage B model: ~5M params (trainable)
|
| 231 |
+
|
| 232 |
+
**Total with relation-aware**: ~265M trainable params
|
| 233 |
+
|
| 234 |
+
---
|
| 235 |
+
|
| 236 |
+
## Expected Impact on JPEG E3
|
| 237 |
+
|
| 238 |
+
The main motivation for this change is improving JPEG E3 ρ (currently 0.62-0.70).
|
| 239 |
+
|
| 240 |
+
**Why it should help**:
|
| 241 |
+
|
| 242 |
+
1. **Multi-scale features**: JPEG artifacts (8×8 blocking) are most visible at 8×8, 16×16 resolutions
|
| 243 |
+
2. **Spatial attention**: Can learn to detect periodic blocking patterns
|
| 244 |
+
3. **Channel attention**: Can capture frequency-like combinations
|
| 245 |
+
4. **Query-based aggregation**: Can focus on artifact-relevant regions
|
| 246 |
+
|
| 247 |
+
**Expected improvement**: JPEG E3 ρ ≥ 0.80 (matching blur/noise/lowlight)
|
| 248 |
+
|
| 249 |
+
---
|
| 250 |
+
|
| 251 |
+
## Compatibility Notes
|
| 252 |
+
|
| 253 |
+
### DC-AE Decoder Compatibility
|
| 254 |
+
- Latent output must remain `[B, 128, 4, 4]`
|
| 255 |
+
- Use `LatentQueryAttention` to maintain compatibility
|
| 256 |
+
- Reconstruction quality should be preserved
|
| 257 |
+
|
| 258 |
+
### Stage B v2 Compatibility
|
| 259 |
+
- Node output shape: `[B, 4, 16]` (unchanged)
|
| 260 |
+
- Graph composer: unchanged
|
| 261 |
+
- All other losses: unchanged
|
| 262 |
+
- Selection policy: unchanged
|
dataset/phase1_noise_20260906/code/scripts/benchmark_phase1_gpu.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Finite native-resolution training smoke with explicit ROCm device evidence."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import sys
|
| 9 |
+
import time
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
|
| 13 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 14 |
+
sys.path.insert(0, str(ROOT))
|
| 15 |
+
from src.models.graph_encoder.clean_relative import CleanRelativeGraphEncoder # noqa: E402
|
| 16 |
+
from train_phase1_clean_relative import (LossWeights, atomic_json_save, controlled_batch, # noqa: E402
|
| 17 |
+
pair_objective, synthetic_objective, safe_optimizer_step)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def main():
|
| 21 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 22 |
+
parser.add_argument("--output", required=True, type=Path)
|
| 23 |
+
parser.add_argument("--batch-size", default=16, type=int)
|
| 24 |
+
parser.add_argument("--synthetic-batch-size", default=4, type=int)
|
| 25 |
+
parser.add_argument("--patch-size", default=256, type=int)
|
| 26 |
+
parser.add_argument("--steps", default=5, type=int)
|
| 27 |
+
parser.add_argument("--expected-pci-bus", default=171, type=int)
|
| 28 |
+
args = parser.parse_args()
|
| 29 |
+
if min(args.batch_size, args.synthetic_batch_size, args.patch_size, args.steps) <= 0:
|
| 30 |
+
parser.error("Dimensions and steps must be positive")
|
| 31 |
+
torch.set_num_threads(4)
|
| 32 |
+
if torch.cuda.device_count() != 1:
|
| 33 |
+
raise RuntimeError("Expose exactly one intended device before benchmarking")
|
| 34 |
+
properties = torch.cuda.get_device_properties(0)
|
| 35 |
+
if properties.pci_bus_id != args.expected_pci_bus:
|
| 36 |
+
raise RuntimeError(f"Wrong GPU PCI bus: {properties.pci_bus_id}")
|
| 37 |
+
device = torch.device("cuda:0")
|
| 38 |
+
torch.manual_seed(42)
|
| 39 |
+
model = CleanRelativeGraphEncoder().to(device).train()
|
| 40 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=2e-4)
|
| 41 |
+
clean_cpu = torch.rand(args.batch_size, 3, args.patch_size, args.patch_size)
|
| 42 |
+
clean = clean_cpu.to(device)
|
| 43 |
+
degraded = (clean + torch.randn_like(clean) * .04).clamp(0, 1)
|
| 44 |
+
presence = clean.new_zeros(args.batch_size, 7)
|
| 45 |
+
presence[:, 1] = 1
|
| 46 |
+
weights = LossWeights()
|
| 47 |
+
timings, losses = [], []
|
| 48 |
+
for step in range(args.steps):
|
| 49 |
+
torch.cuda.synchronize()
|
| 50 |
+
started = time.monotonic()
|
| 51 |
+
optimizer.zero_grad(set_to_none=True)
|
| 52 |
+
pair = model.forward_pair(degraded, clean)
|
| 53 |
+
loss, _ = pair_objective(model, pair, clean, degraded, presence,
|
| 54 |
+
clean.new_ones(args.batch_size), weights)
|
| 55 |
+
data = controlled_batch(clean_cpu, step, 42, args.synthetic_batch_size)
|
| 56 |
+
data = {key: value.to(device) if isinstance(value, torch.Tensor) else value for key, value in data.items()}
|
| 57 |
+
auxiliary, _ = synthetic_objective(model, data, weights, True)
|
| 58 |
+
loss = loss + auxiliary
|
| 59 |
+
if not bool(torch.isfinite(loss)):
|
| 60 |
+
raise FloatingPointError("Nonfinite smoke loss")
|
| 61 |
+
loss.backward()
|
| 62 |
+
accepted, norm = safe_optimizer_step(model, optimizer, 1.)
|
| 63 |
+
if not accepted:
|
| 64 |
+
raise FloatingPointError("Nonfinite smoke gradient")
|
| 65 |
+
torch.cuda.synchronize()
|
| 66 |
+
timings.append(time.monotonic() - started)
|
| 67 |
+
losses.append(float(loss.detach()))
|
| 68 |
+
print(json.dumps({"step": step, "seconds": timings[-1], "loss": losses[-1], "gradient_norm": norm}), flush=True)
|
| 69 |
+
report = {"status": "passed", "scope": "synthetic_software_smoke_not_dataset_training",
|
| 70 |
+
"device": str(properties), "pci_bus": properties.pci_bus_id,
|
| 71 |
+
"torch": torch.__version__, "hip": torch.version.hip,
|
| 72 |
+
"batch_size": args.batch_size, "patch_size": args.patch_size,
|
| 73 |
+
"synthetic_batch_size": args.synthetic_batch_size, "step_seconds": timings,
|
| 74 |
+
"steady_seconds_per_step": sum(timings[1:]) / max(1, len(timings) - 1),
|
| 75 |
+
"losses": losses, "peak_allocated_bytes": torch.cuda.max_memory_allocated(),
|
| 76 |
+
"peak_reserved_bytes": torch.cuda.max_memory_reserved(),
|
| 77 |
+
"free_total_bytes_after": torch.cuda.mem_get_info()}
|
| 78 |
+
atomic_json_save(report, args.output)
|
| 79 |
+
print(json.dumps(report), flush=True)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if __name__ == "__main__":
|
| 83 |
+
main()
|
dataset/phase1_noise_20260906/code/scripts/expand_phase1_noise.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Create manifest v2 by appending noise data to an unchanged frozen v1 parent.
|
| 3 |
+
|
| 4 |
+
No base record is removed, moved, or rewritten. Synthetic records reuse clean
|
| 5 |
+
files, not stored noisy images. New real pairs may be quarantined for duplicate
|
| 6 |
+
pixels or split conflicts. Invalid images fail unless explicitly quarantined.
|
| 7 |
+
The schema bump makes frozen v1 loaders fail before misreading online noise as
|
| 8 |
+
identity pairs. Base files and all existing records/splits remain unchanged.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
from collections import Counter, defaultdict
|
| 15 |
+
from copy import deepcopy
|
| 16 |
+
import hashlib
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
import re
|
| 21 |
+
import sys
|
| 22 |
+
import tempfile
|
| 23 |
+
|
| 24 |
+
from PIL import Image
|
| 25 |
+
|
| 26 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 27 |
+
sys.path.insert(0, str(PROJECT_ROOT))
|
| 28 |
+
|
| 29 |
+
from scripts.prepare_phase1_seven import _decode_cached, record # noqa: E402
|
| 30 |
+
from src.data.clean_relative import ( # noqa: E402
|
| 31 |
+
NOISE_PROFILES, _seed_from, image_files, validate_manifest,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
SPLITS = ("train", "val", "test")
|
| 35 |
+
STRENGTHS = (.2, .4, .6)
|
| 36 |
+
POLYU_REVISION = "3af0f2646b267a00446fe4b7113a15e67bc80b4e"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _empty():
|
| 40 |
+
return {split: [] for split in SPLITS}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _decode_fresh_metadata(path):
|
| 44 |
+
"""Reuse the parent RGB hash format but bypass its stat-keyed LRU cache.
|
| 45 |
+
|
| 46 |
+
File size and mtime can remain identical after a rewrite (including on
|
| 47 |
+
coarse-timestamp filesystems). Expansion is an integrity boundary, so a
|
| 48 |
+
cached decode cannot attest that source pixels still match the manifest.
|
| 49 |
+
The pinned parent helper's undecorated function performs a full fresh load.
|
| 50 |
+
"""
|
| 51 |
+
metadata = Path(path).stat()
|
| 52 |
+
return _decode_cached.__wrapped__(path, metadata.st_size, metadata.st_mtime_ns)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def discover_sidd_medium(root: Path, base_scene_splits: dict[str, str],
|
| 56 |
+
expected_pairs: int = 320) -> dict[str, list[dict]]:
|
| 57 |
+
"""Match each capture suffix, not merely the first file of each instance."""
|
| 58 |
+
grouped = defaultdict(dict)
|
| 59 |
+
for path in image_files(root):
|
| 60 |
+
match = re.fullmatch(r"(?:(\d{4})_)?(NOISY|GT)_SRGB_(\d+)", path.stem, re.IGNORECASE)
|
| 61 |
+
scene = re.fullmatch(r"(\d{4})_(\d{3})_.+", path.parent.name)
|
| 62 |
+
if not match or not scene or (match[1] and match[1] != scene[1]):
|
| 63 |
+
raise ValueError(f"Unrecognized SIDD Medium image/instance: {path}")
|
| 64 |
+
key = (path.parent, match[3])
|
| 65 |
+
role = match[2].upper()
|
| 66 |
+
if role in grouped[key]:
|
| 67 |
+
raise ValueError(f"Duplicate SIDD role/capture: {path}")
|
| 68 |
+
grouped[key][role] = path
|
| 69 |
+
result = _empty()
|
| 70 |
+
for (folder, capture), roles in sorted(grouped.items()):
|
| 71 |
+
if set(roles) != {"NOISY", "GT"}:
|
| 72 |
+
raise ValueError(f"SIDD unmatched NOISY/GT capture {folder}/{capture}")
|
| 73 |
+
group = folder.name.split("_")[1]
|
| 74 |
+
if not 1 <= int(group) <= 10:
|
| 75 |
+
raise ValueError(f"Unexpected SIDD physical scene: {group}")
|
| 76 |
+
prescribed = "val" if group == "006" else "test" if group == "008" else "train"
|
| 77 |
+
split = base_scene_splits.get(group, prescribed)
|
| 78 |
+
if split != prescribed:
|
| 79 |
+
raise ValueError(f"Base SIDD scene {group} disagrees with protected 006-val/008-test policy")
|
| 80 |
+
result[split].append(record(
|
| 81 |
+
roles["NOISY"], roles["GT"], "noise", "SIDD", group, "SIDD_Medium_sRGB",
|
| 82 |
+
noise_source="SIDD_Medium_sRGB", capture_id=capture, scene_instance=folder.name,
|
| 83 |
+
license="MIT", source_url="https://abdokamel.github.io/sidd/",
|
| 84 |
+
))
|
| 85 |
+
count = sum(map(len, result.values()))
|
| 86 |
+
if count != expected_pairs:
|
| 87 |
+
raise ValueError(f"SIDD Medium expected {expected_pairs} pairs, discovered {count}")
|
| 88 |
+
return result
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def discover_polyu(root: Path, expected_pairs: int = 40) -> dict[str, list[dict]]:
|
| 92 |
+
directories = ([root] if root.name == "OriginalImages" and root.is_dir()
|
| 93 |
+
else sorted(p for p in root.rglob("OriginalImages") if p.is_dir()))
|
| 94 |
+
if len(directories) != 1:
|
| 95 |
+
raise ValueError(f"Expected exactly one PolyU OriginalImages directory: {root}")
|
| 96 |
+
grouped = defaultdict(dict)
|
| 97 |
+
for path in image_files(directories[0]):
|
| 98 |
+
match = re.fullmatch(r"(.+)_(Real|mean)", path.stem, re.IGNORECASE)
|
| 99 |
+
if not match:
|
| 100 |
+
raise ValueError(f"Unrecognized PolyU original image: {path}")
|
| 101 |
+
role = match[2].lower()
|
| 102 |
+
if role in grouped[match[1]]:
|
| 103 |
+
raise ValueError(f"Duplicate PolyU role: {path}")
|
| 104 |
+
grouped[match[1]][role] = path
|
| 105 |
+
result = _empty()
|
| 106 |
+
for group, roles in sorted(grouped.items()):
|
| 107 |
+
if set(roles) != {"real", "mean"}:
|
| 108 |
+
raise ValueError(f"PolyU unmatched Real/mean scene: {group}")
|
| 109 |
+
result["test"].append(record(
|
| 110 |
+
roles["real"], roles["mean"], "noise", "PolyU", group, "PolyU_OriginalImages",
|
| 111 |
+
noise_source="PolyU_external", license="PolyU non-commercial research license",
|
| 112 |
+
source_revision=POLYU_REVISION,
|
| 113 |
+
source_url="https://github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset",
|
| 114 |
+
evaluation_role="external_test_only",
|
| 115 |
+
))
|
| 116 |
+
if len(result["test"]) != expected_pairs:
|
| 117 |
+
raise ValueError(f"PolyU expected {expected_pairs} original pairs, discovered {len(result['test'])}")
|
| 118 |
+
return result
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _audit_new_pairs(candidates, quarantine_invalid):
|
| 122 |
+
kept, excluded, decoded = _empty(), [], set()
|
| 123 |
+
for split in SPLITS:
|
| 124 |
+
for item in candidates[split]:
|
| 125 |
+
try:
|
| 126 |
+
clean, noisy = _decode_fresh_metadata(item["clean"]), _decode_fresh_metadata(item["degraded"])
|
| 127 |
+
decoded.update((item["clean"], item["degraded"]))
|
| 128 |
+
if (clean["width"], clean["height"]) != (noisy["width"], noisy["height"]):
|
| 129 |
+
raise ValueError("unaligned pair dimensions")
|
| 130 |
+
except (OSError, ValueError, Image.DecompressionBombError) as error:
|
| 131 |
+
if not quarantine_invalid:
|
| 132 |
+
raise ValueError(f"Invalid new noise pair {item['id']}: {error}") from error
|
| 133 |
+
excluded.append({**item, "original_split": split, "reason": "invalid_new_pair", "detail": str(error)})
|
| 134 |
+
continue
|
| 135 |
+
kept[split].append({**item, "clean_content_sha256": clean["rgb_sha256"],
|
| 136 |
+
"degraded_content_sha256": noisy["rgb_sha256"],
|
| 137 |
+
"width": clean["width"], "height": clean["height"]})
|
| 138 |
+
return kept, excluded, len(decoded)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def retain_new_candidates(base, candidates):
|
| 142 |
+
"""Protect immutable base splits even against transitive new scene bridges."""
|
| 143 |
+
parent = {}
|
| 144 |
+
|
| 145 |
+
def find(key):
|
| 146 |
+
parent.setdefault(key, key)
|
| 147 |
+
while parent[key] != key:
|
| 148 |
+
parent[key] = parent[parent[key]]
|
| 149 |
+
key = parent[key]
|
| 150 |
+
return key
|
| 151 |
+
|
| 152 |
+
def keys(item):
|
| 153 |
+
return ("content:" + item["clean_content_sha256"],
|
| 154 |
+
"group:" + json.dumps([item["dataset"], item["group"]]))
|
| 155 |
+
|
| 156 |
+
for source in (base, candidates):
|
| 157 |
+
for split in SPLITS:
|
| 158 |
+
for item in source[split]:
|
| 159 |
+
first, second = map(find, keys(item))
|
| 160 |
+
if first != second:
|
| 161 |
+
parent[first] = second
|
| 162 |
+
protected, requested = defaultdict(set), defaultdict(set)
|
| 163 |
+
for split in SPLITS:
|
| 164 |
+
for item in base[split]:
|
| 165 |
+
protected[find(keys(item)[0])].add(split)
|
| 166 |
+
for item in candidates[split]:
|
| 167 |
+
requested[find(keys(item)[0])].add(split)
|
| 168 |
+
pair_hashes = {
|
| 169 |
+
(r["type"], r["clean_content_sha256"], r["degraded_content_sha256"])
|
| 170 |
+
for split in SPLITS for r in base[split]
|
| 171 |
+
if not r.get("synthesis") and r.get("degraded_content_sha256")
|
| 172 |
+
}
|
| 173 |
+
kept, excluded = _empty(), []
|
| 174 |
+
for split in reversed(SPLITS):
|
| 175 |
+
for item in candidates[split]:
|
| 176 |
+
component = find(keys(item)[0])
|
| 177 |
+
locked = protected[component]
|
| 178 |
+
reason, winner = None, None
|
| 179 |
+
if len(locked) > 1:
|
| 180 |
+
reason = "new_component_bridges_protected_base_splits"
|
| 181 |
+
else:
|
| 182 |
+
winner = (next(iter(locked)) if locked
|
| 183 |
+
else max(requested[component], key=SPLITS.index))
|
| 184 |
+
if split != winner:
|
| 185 |
+
reason = "cross_split_content_or_group_overlap"
|
| 186 |
+
pair = (item["type"], item["clean_content_sha256"], item["degraded_content_sha256"])
|
| 187 |
+
if reason is None and pair in pair_hashes:
|
| 188 |
+
reason = "decoded_pair_duplicate"
|
| 189 |
+
if reason:
|
| 190 |
+
excluded.append({**item, "original_split": split, "reason": reason,
|
| 191 |
+
"protected_split": winner, "protected_base_splits": sorted(locked)})
|
| 192 |
+
else:
|
| 193 |
+
pair_hashes.add(pair)
|
| 194 |
+
kept[split].append(item)
|
| 195 |
+
return kept, excluded
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _synthetic_records(base, seed):
|
| 199 |
+
generated, source_paths = _empty(), set()
|
| 200 |
+
for split in SPLITS:
|
| 201 |
+
seen_paths = set()
|
| 202 |
+
for source in base[split]:
|
| 203 |
+
if source.get("synthesis") != "jpeg":
|
| 204 |
+
continue
|
| 205 |
+
if source["dataset"] not in ("DIV2K", "Flickr2K"):
|
| 206 |
+
raise ValueError(f"Explicit DF2K expansion received unexpected JPEG source {source['dataset']}")
|
| 207 |
+
if source["clean"] in seen_paths:
|
| 208 |
+
continue
|
| 209 |
+
seen_paths.add(source["clean"])
|
| 210 |
+
metadata = _decode_fresh_metadata(source["clean"])
|
| 211 |
+
if metadata["rgb_sha256"] != source["clean_content_sha256"]:
|
| 212 |
+
raise ValueError(f"Base JPEG clean file no longer matches audited pixels: {source['clean']}")
|
| 213 |
+
source_paths.add(source["clean"])
|
| 214 |
+
for profile in NOISE_PROFILES:
|
| 215 |
+
for strength in STRENGTHS:
|
| 216 |
+
identifier = hashlib.sha256(f"noise_v1\0{source['id']}\0{profile}\0{strength}".encode()).hexdigest()
|
| 217 |
+
params = {"severity": strength,
|
| 218 |
+
"sigma": (.12 if profile == "gaussian" else .02) * strength,
|
| 219 |
+
"shot": 0. if profile == "gaussian" else .12 * strength,
|
| 220 |
+
"noise_seed": _seed_from(seed, identifier, "noise_v1")}
|
| 221 |
+
generated[split].append({
|
| 222 |
+
"id": identifier, "clean": source["clean"], "degraded": source["clean"],
|
| 223 |
+
"type": "noise", "dataset": source["dataset"], "group": source["group"],
|
| 224 |
+
"source": source.get("source", source["id"]), "parent_record_id": source["id"],
|
| 225 |
+
"noise_source": "DF2K_explicit_synthetic", "synthesis": "noise",
|
| 226 |
+
"noise_synthesis_version": 1, "noise_profile": profile, "noise_parameters": params,
|
| 227 |
+
"clean_content_sha256": metadata["rgb_sha256"],
|
| 228 |
+
"degraded_content_sha256": metadata["rgb_sha256"],
|
| 229 |
+
"degraded_content_hash_role": "clean_source_before_online_synthesis",
|
| 230 |
+
"width": metadata["width"], "height": metadata["height"],
|
| 231 |
+
})
|
| 232 |
+
return generated, len(source_paths)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _summary(splits):
|
| 236 |
+
result = {}
|
| 237 |
+
for split in SPLITS:
|
| 238 |
+
rows = splits[split]
|
| 239 |
+
noise = [r for r in rows if r["type"] == "noise"]
|
| 240 |
+
real = [r for r in noise if not r.get("synthesis")]
|
| 241 |
+
synthetic = [r for r in noise if r.get("synthesis") == "noise"]
|
| 242 |
+
source_key = lambda r: r.get("noise_source", r["dataset"]) # noqa: E731
|
| 243 |
+
result[split] = {
|
| 244 |
+
"all_records": len(rows), "records_by_type": dict(Counter(r["type"] for r in rows)),
|
| 245 |
+
"noise_records_by_source": dict(Counter(source_key(r) for r in noise)),
|
| 246 |
+
"real_noise_records": len(real), "synthetic_noise_records": len(synthetic),
|
| 247 |
+
"real_noise_clean_images": len({r["clean_content_sha256"] for r in real}),
|
| 248 |
+
"synthetic_noise_clean_images": len({r["clean_content_sha256"] for r in synthetic}),
|
| 249 |
+
"real_noise_scene_or_source_groups": len({(r["dataset"], r["group"]) for r in real}),
|
| 250 |
+
"real_noise_groups_by_source": {
|
| 251 |
+
source: len({(r["dataset"], r["group"]) for r in real if source_key(r) == source})
|
| 252 |
+
for source in sorted({source_key(r) for r in real})},
|
| 253 |
+
}
|
| 254 |
+
return result
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def build_expansion(base, *, seed=20260906, sidd_medium_root=None, polyu_root=None,
|
| 258 |
+
expected_sidd_pairs=320, expected_polyu_pairs=40, quarantine_invalid=False,
|
| 259 |
+
base_receipt=None):
|
| 260 |
+
validate_manifest(base)
|
| 261 |
+
if base["schema_version"] != 1:
|
| 262 |
+
raise ValueError("Noise expansion requires a frozen schema_version=1 parent manifest")
|
| 263 |
+
if isinstance(seed, bool) or not isinstance(seed, int) or not 0 <= seed < 2 ** 31:
|
| 264 |
+
raise ValueError("seed must be an integer in [0,2**31)")
|
| 265 |
+
scene_splits = {r["group"]: split for split in SPLITS for r in base[split] if r["dataset"] == "SIDD"}
|
| 266 |
+
candidates = _empty()
|
| 267 |
+
for root, discover, kwargs in (
|
| 268 |
+
(sidd_medium_root, discover_sidd_medium, {"base_scene_splits": scene_splits, "expected_pairs": expected_sidd_pairs}),
|
| 269 |
+
(polyu_root, discover_polyu, {"expected_pairs": expected_polyu_pairs}),
|
| 270 |
+
):
|
| 271 |
+
if root is not None:
|
| 272 |
+
found = discover(Path(root), **kwargs)
|
| 273 |
+
for split in SPLITS:
|
| 274 |
+
candidates[split].extend(found[split])
|
| 275 |
+
discovered = sum(map(len, candidates.values()))
|
| 276 |
+
audited, invalid, decoded = _audit_new_pairs(candidates, quarantine_invalid)
|
| 277 |
+
admitted, conflicts = retain_new_candidates(base, audited)
|
| 278 |
+
synthetic, source_count = _synthetic_records(base, seed)
|
| 279 |
+
expanded = deepcopy(base)
|
| 280 |
+
expanded["schema_version"] = 2
|
| 281 |
+
for split in SPLITS:
|
| 282 |
+
expanded[split].extend(admitted[split] + synthetic[split])
|
| 283 |
+
assert expanded[split][:len(base[split])] == base[split]
|
| 284 |
+
validate_manifest(expanded)
|
| 285 |
+
quarantine = invalid + conflicts
|
| 286 |
+
if discovered != sum(map(len, admitted.values())) + len(quarantine):
|
| 287 |
+
raise AssertionError("New real noise coverage accounting failed")
|
| 288 |
+
expanded["noise_expansion"] = {
|
| 289 |
+
"version": 1, "seed": seed, "base_manifest": base_receipt,
|
| 290 |
+
"manifest_schema_version": 2, "parent_manifest_schema_version": 1,
|
| 291 |
+
"base_records_preserved": True, "base_split_assignments_preserved": True,
|
| 292 |
+
"summary": _summary(expanded), "new_real_discovered_pairs": discovered,
|
| 293 |
+
"new_real_admitted_pairs": sum(map(len, admitted.values())),
|
| 294 |
+
"new_real_decoded_files": decoded, "synthetic_source_paths_checked": source_count,
|
| 295 |
+
"quarantine": quarantine, "coverage_accounting_pass": True,
|
| 296 |
+
"quarantine_invalid_explicit": quarantine_invalid,
|
| 297 |
+
"generator_source_sha256": {
|
| 298 |
+
relative: hashlib.sha256((PROJECT_ROOT / relative).read_bytes()).hexdigest()
|
| 299 |
+
for relative in ("scripts/expand_phase1_noise.py", "scripts/prepare_phase1_seven.py",
|
| 300 |
+
"src/data/clean_relative.py")},
|
| 301 |
+
"group_semantics": {
|
| 302 |
+
"SIDD": "physical scene number, ignoring capture-instance and repeated shot",
|
| 303 |
+
"PolyU": "original camera/object filename group; not independently verified physical-scene independence",
|
| 304 |
+
"DIV2K/Flickr2K": "clean-image source identity, shared with parent JPEG split",
|
| 305 |
+
},
|
| 306 |
+
"sources": {"sidd_medium_root": str(sidd_medium_root) if sidd_medium_root else None,
|
| 307 |
+
"sidd_expected_pairs": expected_sidd_pairs if sidd_medium_root else None,
|
| 308 |
+
"polyu_root": str(polyu_root) if polyu_root else None,
|
| 309 |
+
"polyu_expected_pairs": expected_polyu_pairs if polyu_root else None,
|
| 310 |
+
"polyu_revision": POLYU_REVISION if polyu_root else None},
|
| 311 |
+
"synthesis": {
|
| 312 |
+
"profiles": list(NOISE_PROFILES), "strengths": list(STRENGTHS),
|
| 313 |
+
"variance_formula": "sigma**2 + shot**2 * clean_RGB; output clipped to [0,1]",
|
| 314 |
+
"units": "sigma: read-noise std; shot: sqrt(signal-dependent variance slope), normalized RGB",
|
| 315 |
+
"severity": "explicit normalized synthetic dose, NOT real noise ground truth",
|
| 316 |
+
"train_replay": "noise_seed = _seed_from(manifest_noise_seed, record_id, epoch, 'noise_v1')",
|
| 317 |
+
"evaluation_replay": "manifest noise_seed unchanged; fixed native center crop",
|
| 318 |
+
"parameter_coverage": "two fixed profile curves x three doses; NOT independent 2-D read/shot coverage",
|
| 319 |
+
},
|
| 320 |
+
"limitations": [
|
| 321 |
+
"Legacy audit describes the parent manifest; use noise_expansion.summary for current counts.",
|
| 322 |
+
"Manifest schema v2 deliberately rejects frozen v1 loaders; use the upgraded loader for online noise.",
|
| 323 |
+
"SIDD Medium adds captures, not new physical scenes beyond the existing ten.",
|
| 324 |
+
"Exact decoded RGB and scene groups only; no perceptual near-duplicate detection.",
|
| 325 |
+
"PolyU is external test only and subject to non-commercial research license.",
|
| 326 |
+
"PolyU has 40 original image pairs; cross-camera independence of physical scenes is not independently verified.",
|
| 327 |
+
"Legacy evaluator pools real and synthetic noise: source/profile-stratified evaluation is required before interpretation.",
|
| 328 |
+
],
|
| 329 |
+
}
|
| 330 |
+
return expanded
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def write_manifest_exclusive(output: Path, manifest: dict):
|
| 334 |
+
"""Publish a complete JSON atomically, without an overwrite race."""
|
| 335 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 336 |
+
handle, temporary = tempfile.mkstemp(prefix=output.name + ".", suffix=".tmp", dir=output.parent)
|
| 337 |
+
try:
|
| 338 |
+
with os.fdopen(handle, "w", encoding="utf-8") as stream:
|
| 339 |
+
json.dump(manifest, stream, indent=2, allow_nan=False)
|
| 340 |
+
stream.write("\n")
|
| 341 |
+
stream.flush()
|
| 342 |
+
os.fsync(stream.fileno())
|
| 343 |
+
os.link(temporary, output)
|
| 344 |
+
finally:
|
| 345 |
+
Path(temporary).unlink(missing_ok=True)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def main():
|
| 349 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 350 |
+
parser.add_argument("--base-manifest", type=Path, required=True)
|
| 351 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 352 |
+
parser.add_argument("--sidd-medium-root", type=Path)
|
| 353 |
+
parser.add_argument("--polyu-root", type=Path)
|
| 354 |
+
parser.add_argument("--expected-sidd-pairs", type=int, default=320)
|
| 355 |
+
parser.add_argument("--expected-polyu-pairs", type=int, default=40)
|
| 356 |
+
parser.add_argument("--seed", type=int, default=20260906)
|
| 357 |
+
parser.add_argument("--quarantine-invalid", action="store_true")
|
| 358 |
+
args = parser.parse_args()
|
| 359 |
+
if args.output.exists():
|
| 360 |
+
raise FileExistsError(args.output)
|
| 361 |
+
if args.expected_sidd_pairs <= 0 or args.expected_polyu_pairs <= 0:
|
| 362 |
+
parser.error("Expected source pair counts must be positive")
|
| 363 |
+
raw = args.base_manifest.read_bytes()
|
| 364 |
+
expanded = build_expansion(
|
| 365 |
+
json.loads(raw), seed=args.seed, sidd_medium_root=args.sidd_medium_root, polyu_root=args.polyu_root,
|
| 366 |
+
expected_sidd_pairs=args.expected_sidd_pairs, expected_polyu_pairs=args.expected_polyu_pairs,
|
| 367 |
+
quarantine_invalid=args.quarantine_invalid,
|
| 368 |
+
base_receipt={"path": str(args.base_manifest.resolve()), "sha256": hashlib.sha256(raw).hexdigest()},
|
| 369 |
+
)
|
| 370 |
+
write_manifest_exclusive(args.output, expanded)
|
| 371 |
+
print(json.dumps({"manifest": str(args.output.resolve()), **expanded["noise_expansion"]}, indent=2))
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
if __name__ == "__main__":
|
| 375 |
+
main()
|
dataset/phase1_noise_20260906/code/scripts/fetch_phase1_extra.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fetch explicitly selected public Phase-1 assets; never execute archive contents.
|
| 3 |
+
|
| 4 |
+
Original benchmark/source links are recorded alongside mirrors. Archives are kept
|
| 5 |
+
for reproducibility. Run one asset per process to make failures independently
|
| 6 |
+
resumable. No credentials or model checkpoints are downloaded by this script.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
from pathlib import Path, PurePosixPath
|
| 14 |
+
import shutil
|
| 15 |
+
import stat
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import tarfile
|
| 19 |
+
import time
|
| 20 |
+
import zipfile
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
ASSETS = {
|
| 24 |
+
"sidd_medium_srgb": {
|
| 25 |
+
"url": "http://130.63.97.225/share/SIDD_Medium_Srgb.zip",
|
| 26 |
+
"file": "SIDD_Medium_Srgb.zip", "directory": "sidd_medium_srgb",
|
| 27 |
+
"archive_bytes_expected": 13_234_744_070,
|
| 28 |
+
"source": "https://abdokamel.github.io/sidd/",
|
| 29 |
+
"original": "http://130.63.97.225/share/download_benchmark.html",
|
| 30 |
+
"license": "MIT", "expected_pairs": 320, "physical_scenes": 10,
|
| 31 |
+
"transport_note": "Author HTTP mirror; no published checksum pinned. Record observed SHA256; ZIP extraction verifies member CRCs. Not cryptographic source authentication.",
|
| 32 |
+
},
|
| 33 |
+
"polyu_original": {
|
| 34 |
+
"url": "https://codeload.github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset/zip/3af0f2646b267a00446fe4b7113a15e67bc80b4e",
|
| 35 |
+
"file": "PolyU_3af0f2646b267a00446fe4b7113a15e67bc80b4e.zip",
|
| 36 |
+
"directory": "polyu_original", "revision": "3af0f2646b267a00446fe4b7113a15e67bc80b4e",
|
| 37 |
+
"source": "https://github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset",
|
| 38 |
+
"license": "Non-commercial teaching, academic research and personal experimentation; retain License.txt",
|
| 39 |
+
"expected_original_pairs": 40, "original_image_bytes": 131_932_359,
|
| 40 |
+
"use": "external_test_only_original_images",
|
| 41 |
+
"scope_note": "Archive also contains 100 derived crop pairs; these are not additional scenes and are not admitted.",
|
| 42 |
+
},
|
| 43 |
+
"gopro": {
|
| 44 |
+
"repo": "snah/GOPRO_Large", "file": "GOPRO_Large.zip", "directory": "gopro",
|
| 45 |
+
"revision": "592978466ae510d2734b199cad2fc79a346bda1c", "archive_bytes_expected": 9540471600,
|
| 46 |
+
"sha256": "24532c036712515cf33803704421311c91f6a080e76049d7e5e7fd22389f128e",
|
| 47 |
+
"source": "https://github.com/Algolzw/daclip-uir#dataset-links",
|
| 48 |
+
"original": "https://drive.google.com/file/d/1y4wvPdOG3mojpFCHTqLgriexhbjoWVkK/view",
|
| 49 |
+
},
|
| 50 |
+
"div2k_train": {
|
| 51 |
+
"url": "https://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip",
|
| 52 |
+
"file": "DIV2K_train_HR.zip", "directory": "div2k_train",
|
| 53 |
+
"archive_bytes_expected": 3530603713,
|
| 54 |
+
"source": "https://data.vision.ee.ethz.ch/cvl/DIV2K/",
|
| 55 |
+
},
|
| 56 |
+
"div2k_valid": {
|
| 57 |
+
"url": "https://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_valid_HR.zip",
|
| 58 |
+
"file": "DIV2K_valid_HR.zip", "directory": "div2k_valid",
|
| 59 |
+
"source": "https://data.vision.ee.ethz.ch/cvl/DIV2K/",
|
| 60 |
+
},
|
| 61 |
+
"flickr2k": {
|
| 62 |
+
"repo": "yangtao9009/Flickr2K", "file": "Flickr2K.zip", "directory": "flickr2k",
|
| 63 |
+
"revision": "790432e75172aaf1c2c350825fb7b2b821603881", "archive_bytes_expected": 11645004887,
|
| 64 |
+
"sha256": "6efb757849c39926258108cee2111a9d26976c6e3726a09bf179834f17ba78f8",
|
| 65 |
+
"source": "https://github.com/Algolzw/daclip-uir#dataset-links",
|
| 66 |
+
"original": "https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar",
|
| 67 |
+
"mirror_note": "HR-only mirror also used by deepinv.datasets.Flickr2kHR",
|
| 68 |
+
},
|
| 69 |
+
"snow_test": {
|
| 70 |
+
"drive_id": "15z-A3i3Z2ybdKuyxwYRA8YKxIA8_kTDm",
|
| 71 |
+
"file": "Snow100K-testset.tar.gz", "directory": "snow_test",
|
| 72 |
+
"source": "https://sites.google.com/view/yunfuliu/desnownet",
|
| 73 |
+
},
|
| 74 |
+
"snow_l_gt": {"drive_id": "1GdEW9TpEzcViW_pjxscbitDOoHKkxlsR", "file": "snow_l_gt.zip", "directory": "snow_l_gt", "source": "https://github.com/sunshangquan/Histoformer#-datasets"},
|
| 75 |
+
"snow_l_synthetic": {"drive_id": "1OdpEbYnS_MRnmozTbTyOov5mq4di8Dl4", "file": "snow_l_synthetic.zip", "directory": "snow_l_synthetic", "source": "https://github.com/sunshangquan/Histoformer#-datasets"},
|
| 76 |
+
"snow_s_gt": {"drive_id": "1jxyAdI0eNLKqFH63AroFM-Rdx7WGgzBS", "file": "snow_s_gt.zip", "directory": "snow_s_gt", "source": "https://github.com/sunshangquan/Histoformer#-datasets"},
|
| 77 |
+
"snow_s_synthetic": {"drive_id": "1wXXg9lymva5kVvIV_l9zdDB9_G0q0WD8", "file": "snow_s_synthetic.zip", "directory": "snow_s_synthetic", "source": "https://github.com/sunshangquan/Histoformer#-datasets"},
|
| 78 |
+
}
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def monitored_download(command: list[str], root: Path, reserve_bytes: int) -> None:
|
| 82 |
+
"""Stop only our child downloader if shared-disk headroom is endangered."""
|
| 83 |
+
process = subprocess.Popen(command)
|
| 84 |
+
try:
|
| 85 |
+
while process.poll() is None:
|
| 86 |
+
# One GiB guard absorbs writes between polls and termination latency.
|
| 87 |
+
if shutil.disk_usage(root).free < reserve_bytes + 1024**3:
|
| 88 |
+
raise RuntimeError("Stopping own download to preserve shared-disk reserve")
|
| 89 |
+
time.sleep(1)
|
| 90 |
+
if process.returncode:
|
| 91 |
+
raise subprocess.CalledProcessError(process.returncode, command)
|
| 92 |
+
finally:
|
| 93 |
+
if process.poll() is None:
|
| 94 |
+
process.terminate()
|
| 95 |
+
try:
|
| 96 |
+
process.wait(timeout=10)
|
| 97 |
+
except subprocess.TimeoutExpired:
|
| 98 |
+
process.kill()
|
| 99 |
+
process.wait()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def guarded_copy(source, output, filesystem_root: Path, reserve_bytes: int) -> None:
|
| 103 |
+
"""Also protect extraction from concurrent writers on the shared filesystem."""
|
| 104 |
+
while True:
|
| 105 |
+
chunk = source.read(1024 * 1024)
|
| 106 |
+
if not chunk:
|
| 107 |
+
break
|
| 108 |
+
if shutil.disk_usage(filesystem_root).free < reserve_bytes + 1024**3:
|
| 109 |
+
raise RuntimeError("Stopping extraction to preserve shared-disk reserve")
|
| 110 |
+
output.write(chunk)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def digest(path: Path) -> str:
|
| 114 |
+
value = hashlib.sha256()
|
| 115 |
+
with path.open("rb") as handle:
|
| 116 |
+
for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""):
|
| 117 |
+
value.update(chunk)
|
| 118 |
+
return value.hexdigest()
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def atomic_json(path: Path, payload: dict) -> None:
|
| 122 |
+
temporary = path.with_suffix(path.suffix + ".tmp")
|
| 123 |
+
temporary.write_text(json.dumps(payload, indent=2) + "\n")
|
| 124 |
+
temporary.replace(path)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def safe_target(destination: Path, name: str) -> Path:
|
| 128 |
+
member = PurePosixPath(name)
|
| 129 |
+
if member.is_absolute() or ".." in member.parts or "\\" in name:
|
| 130 |
+
raise ValueError(f"Unsafe archive member: {name!r}")
|
| 131 |
+
target = destination.joinpath(*member.parts)
|
| 132 |
+
if not target.resolve().is_relative_to(destination.resolve()):
|
| 133 |
+
raise ValueError(f"Archive member escapes destination: {name!r}")
|
| 134 |
+
return target
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def extract_checked(archive: Path, destination: Path, reserve_bytes: int) -> dict:
|
| 138 |
+
"""Reject links/special files and check expanded disk budget before writing."""
|
| 139 |
+
files = 0
|
| 140 |
+
expanded = 0
|
| 141 |
+
if zipfile.is_zipfile(archive):
|
| 142 |
+
with zipfile.ZipFile(archive) as handle:
|
| 143 |
+
members = handle.infolist()
|
| 144 |
+
for member in members:
|
| 145 |
+
safe_target(destination, member.filename)
|
| 146 |
+
mode = stat.S_IFMT(member.external_attr >> 16)
|
| 147 |
+
if mode not in (0, stat.S_IFREG, stat.S_IFDIR):
|
| 148 |
+
raise ValueError("Archive contains link or special file")
|
| 149 |
+
expanded += member.file_size
|
| 150 |
+
if shutil.disk_usage(destination.parent).free < expanded + reserve_bytes:
|
| 151 |
+
raise RuntimeError(f"Insufficient space for {expanded} expanded bytes plus reserve")
|
| 152 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 153 |
+
for member in members:
|
| 154 |
+
target = safe_target(destination, member.filename)
|
| 155 |
+
if member.is_dir():
|
| 156 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 157 |
+
else:
|
| 158 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 159 |
+
with handle.open(member) as source, target.open("wb") as output:
|
| 160 |
+
guarded_copy(source, output, destination.parent, reserve_bytes)
|
| 161 |
+
files += 1
|
| 162 |
+
else:
|
| 163 |
+
with tarfile.open(archive, "r:*") as handle:
|
| 164 |
+
members = handle.getmembers()
|
| 165 |
+
for member in members:
|
| 166 |
+
safe_target(destination, member.name)
|
| 167 |
+
if not (member.isfile() or member.isdir()):
|
| 168 |
+
raise ValueError(f"Non-regular archive member: {member.name}")
|
| 169 |
+
expanded += member.size
|
| 170 |
+
if shutil.disk_usage(destination.parent).free < expanded + reserve_bytes:
|
| 171 |
+
raise RuntimeError(f"Insufficient space for {expanded} expanded bytes plus reserve")
|
| 172 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 173 |
+
for member in members:
|
| 174 |
+
target = safe_target(destination, member.name)
|
| 175 |
+
if member.isdir():
|
| 176 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 177 |
+
else:
|
| 178 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 179 |
+
source = handle.extractfile(member)
|
| 180 |
+
if source is None:
|
| 181 |
+
raise ValueError(f"Unreadable member {member.name}")
|
| 182 |
+
with source, target.open("wb") as output:
|
| 183 |
+
guarded_copy(source, output, destination.parent, reserve_bytes)
|
| 184 |
+
files += 1
|
| 185 |
+
return {"extracted_files": files, "expanded_bytes": expanded}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def fetch(asset: str, root: Path, reserve_gib: float = 25.0, transport: str = "curl") -> dict:
|
| 189 |
+
specification = dict(ASSETS[asset])
|
| 190 |
+
root = root.resolve()
|
| 191 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 192 |
+
archive_dir = root / "archives"
|
| 193 |
+
archive_dir.mkdir(exist_ok=True)
|
| 194 |
+
destination = root / specification["directory"]
|
| 195 |
+
receipt_path = root / f"{asset}.receipt.json"
|
| 196 |
+
receipt = None
|
| 197 |
+
if receipt_path.is_file():
|
| 198 |
+
receipt = json.loads(receipt_path.read_text())
|
| 199 |
+
for key in ("asset", "file", "repo", "revision", "sha256", "drive_id", "url"):
|
| 200 |
+
expected = asset if key == "asset" else specification.get(key)
|
| 201 |
+
if expected is not None and receipt.get(key) not in (None, expected):
|
| 202 |
+
raise ValueError(f"Existing receipt provenance differs at {key}")
|
| 203 |
+
if receipt.get("complete") and destination.is_dir():
|
| 204 |
+
print(json.dumps({"asset": asset, "status": "already_complete", "receipt": str(receipt_path)}), flush=True)
|
| 205 |
+
return receipt
|
| 206 |
+
reserve_bytes = int(reserve_gib * 1024**3)
|
| 207 |
+
if shutil.disk_usage(root).free < reserve_bytes:
|
| 208 |
+
raise RuntimeError("Disk already below reserved free space")
|
| 209 |
+
archive = archive_dir / specification["file"]
|
| 210 |
+
record = {"asset": asset, **specification, "started_unix": time.time(), "complete": False}
|
| 211 |
+
if receipt:
|
| 212 |
+
record["started_unix"] = receipt.get("started_unix", record["started_unix"])
|
| 213 |
+
if "repo" in specification:
|
| 214 |
+
# Public repository revisions and LFS hashes were independently resolved
|
| 215 |
+
# during source audit. Retrying does not query HEAD or change provenance.
|
| 216 |
+
url = f"https://huggingface.co/datasets/{specification['repo']}/resolve/{specification['revision']}/{specification['file']}?download=true"
|
| 217 |
+
else:
|
| 218 |
+
url = specification.get("url")
|
| 219 |
+
if url:
|
| 220 |
+
if receipt and receipt.get("download_url") not in (None, url):
|
| 221 |
+
raise ValueError("Existing partial download URL does not match pinned source")
|
| 222 |
+
record["download_url"] = url
|
| 223 |
+
atomic_json(receipt_path, record)
|
| 224 |
+
if not archive.is_file():
|
| 225 |
+
partial = archive.with_suffix(archive.suffix + ".part")
|
| 226 |
+
use_hf = transport == "hf" and "repo" in specification
|
| 227 |
+
already = partial.stat().st_size if partial.exists() and not use_hf else 0
|
| 228 |
+
# Known HF/archive sizes are exact. The conservative 10-GiB fallback is
|
| 229 |
+
# only a preflight estimate; live reserve checks also cover unknown sizes.
|
| 230 |
+
remaining = max(0, specification.get("archive_bytes_expected", 10 * 1024**3) - already)
|
| 231 |
+
if shutil.disk_usage(root).free < remaining + reserve_bytes + 1024**3:
|
| 232 |
+
raise RuntimeError(f"Insufficient headroom for {remaining} remaining archive bytes")
|
| 233 |
+
if use_hf:
|
| 234 |
+
code = "from huggingface_hub import hf_hub_download; import sys; print(hf_hub_download(sys.argv[1],sys.argv[2],repo_type='dataset',revision=sys.argv[3],local_dir=sys.argv[4],token=False))"
|
| 235 |
+
monitored_download([sys.executable, "-c", code, specification["repo"], specification["file"], specification["revision"], str(archive_dir)], root, reserve_bytes)
|
| 236 |
+
elif "drive_id" in specification:
|
| 237 |
+
code = "import gdown,sys; result=gdown.download(id=sys.argv[1],output=sys.argv[2],quiet=False,resume=True); sys.exit(0 if result else 1)"
|
| 238 |
+
monitored_download([sys.executable, "-c", code, specification["drive_id"], str(partial)], root, reserve_bytes)
|
| 239 |
+
else:
|
| 240 |
+
# cURL validates TLS, propagates errors and resumes only this asset's partial file.
|
| 241 |
+
monitored_download(["curl", "--fail", "--location", "--retry", "4", "--retry-delay", "5",
|
| 242 |
+
"--connect-timeout", "30", "--speed-time", "120", "--speed-limit", "1024",
|
| 243 |
+
"--continue-at", "-", "--output", str(partial), str(url)], root, reserve_bytes)
|
| 244 |
+
if not use_hf:
|
| 245 |
+
partial.replace(archive)
|
| 246 |
+
if specification.get("archive_bytes_expected") and archive.stat().st_size != specification["archive_bytes_expected"]:
|
| 247 |
+
raise ValueError(f"Archive size mismatch for {archive}; retained for inspection")
|
| 248 |
+
actual_hash = digest(archive)
|
| 249 |
+
if specification.get("sha256") and actual_hash != specification["sha256"]:
|
| 250 |
+
raise ValueError(f"Checksum mismatch for {archive}; retained for inspection")
|
| 251 |
+
record.update({"sha256_observed": actual_hash, "archive_bytes": archive.stat().st_size})
|
| 252 |
+
atomic_json(receipt_path, record)
|
| 253 |
+
# Never overwrite an unrelated existing extraction directory.
|
| 254 |
+
marker = destination / ".phase1_asset.json"
|
| 255 |
+
if destination.exists():
|
| 256 |
+
if not marker.is_file() or json.loads(marker.read_text()).get("archive_sha256") != actual_hash:
|
| 257 |
+
raise FileExistsError(f"Existing unowned extraction directory: {destination}")
|
| 258 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 259 |
+
atomic_json(marker, {"asset": asset, "archive_sha256": actual_hash})
|
| 260 |
+
record.update(extract_checked(archive, destination, reserve_bytes))
|
| 261 |
+
record.update({"complete": True, "completed_unix": time.time(), "destination": str(destination)})
|
| 262 |
+
atomic_json(receipt_path, record)
|
| 263 |
+
print(json.dumps(record), flush=True)
|
| 264 |
+
return record
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def main() -> None:
|
| 268 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 269 |
+
parser.add_argument("--asset", choices=ASSETS, required=True)
|
| 270 |
+
parser.add_argument("--root", type=Path, required=True)
|
| 271 |
+
parser.add_argument("--reserve-gib", type=float, default=25.0)
|
| 272 |
+
parser.add_argument("--transport", choices=("curl", "hf"), default="curl")
|
| 273 |
+
args = parser.parse_args()
|
| 274 |
+
if args.reserve_gib < 10:
|
| 275 |
+
parser.error("reserve-gib must be at least 10")
|
| 276 |
+
fetch(args.asset, args.root, args.reserve_gib, args.transport)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
if __name__ == "__main__":
|
| 280 |
+
main()
|
dataset/phase1_noise_20260906/code/scripts/prepare_phase1_seven.py
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build and audit all available seven-type pairs; never truncate datasets.
|
| 3 |
+
|
| 4 |
+
Official tests are locked. Validation is reserved by clean/scene group from
|
| 5 |
+
training. Where no official test exists locally, an explicitly labelled internal
|
| 6 |
+
group holdout is created. Exact decoded-RGB duplicate content cannot cross splits;
|
| 7 |
+
near duplicates/resized copies are not claimed to be detected by exact hashing.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
from collections import Counter
|
| 14 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 15 |
+
from functools import lru_cache
|
| 16 |
+
import hashlib
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
import sqlite3
|
| 20 |
+
import struct
|
| 21 |
+
import sys
|
| 22 |
+
import time
|
| 23 |
+
|
| 24 |
+
from PIL import Image
|
| 25 |
+
|
| 26 |
+
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
| 27 |
+
sys.path.insert(0, str(PROJECT_ROOT))
|
| 28 |
+
|
| 29 |
+
from src.data.clean_relative import ( # noqa: E402
|
| 30 |
+
TYPES, discover_exact_pairs, image_files, isolate_splits, validate_manifest,
|
| 31 |
+
)
|
| 32 |
+
from src.data.rain13k_resized import load_rain13k_resized # noqa: E402
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def record(degraded: Path, clean: Path, kind: str, dataset: str, group: str,
|
| 36 |
+
source: str, **extra) -> dict:
|
| 37 |
+
degraded, clean = degraded.resolve(), clean.resolve()
|
| 38 |
+
identifier = hashlib.sha256(f"{dataset}\0{source}\0{degraded}\0{clean}".encode()).hexdigest()
|
| 39 |
+
return {"id": identifier, "clean": str(clean), "degraded": str(degraded),
|
| 40 |
+
"type": kind, "dataset": dataset, "group": group, "source": source, **extra}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def split_training(records: list[dict], seed: int, val_fraction: float,
|
| 44 |
+
test_fraction: float = 0.) -> dict[str, list[dict]]:
|
| 45 |
+
"""Partition clean-content/scene components BEFORE selecting holdouts.
|
| 46 |
+
|
| 47 |
+
Multiple rain variants may have different GT filenames but identical pixels.
|
| 48 |
+
All such variants must be assigned together, not discarded after the split.
|
| 49 |
+
Invalid images remain for the later explicit invalid-pair audit.
|
| 50 |
+
"""
|
| 51 |
+
paths = sorted({r["clean"] for r in records if r.get("clean") and not r.get("clean_content_sha256")})
|
| 52 |
+
|
| 53 |
+
def clean_hash(path):
|
| 54 |
+
try:
|
| 55 |
+
return path, _decode_metadata(path)["rgb_sha256"]
|
| 56 |
+
except (OSError, ValueError, Image.DecompressionBombError):
|
| 57 |
+
return path, "unreadable:" + path
|
| 58 |
+
|
| 59 |
+
with ThreadPoolExecutor(max_workers=4) as pool:
|
| 60 |
+
hashes = dict(pool.map(clean_hash, paths))
|
| 61 |
+
parent = {}
|
| 62 |
+
|
| 63 |
+
def find(key):
|
| 64 |
+
parent.setdefault(key, key)
|
| 65 |
+
while parent[key] != key:
|
| 66 |
+
parent[key] = parent[parent[key]]
|
| 67 |
+
key = parent[key]
|
| 68 |
+
return key
|
| 69 |
+
|
| 70 |
+
for item in records:
|
| 71 |
+
group = f"group:{item.get('dataset', '')}:{item['group']}"
|
| 72 |
+
content = "content:" + (item.get("clean_content_sha256") or hashes.get(item.get("clean"), group))
|
| 73 |
+
first, second = find(group), find(content)
|
| 74 |
+
if first != second:
|
| 75 |
+
parent[max(first, second)] = min(first, second)
|
| 76 |
+
components = {item["id"]: find(f"group:{item.get('dataset', '')}:{item['group']}") for item in records}
|
| 77 |
+
groups = sorted(set(components.values()),
|
| 78 |
+
key=lambda group: hashlib.sha256(f"{seed}:{group}".encode()).digest())
|
| 79 |
+
if len(groups) < (3 if test_fraction > 0 else 2):
|
| 80 |
+
raise ValueError(f"Too few content/scene groups for safe split: {len(groups)}")
|
| 81 |
+
n_val = max(1, round(len(groups) * val_fraction))
|
| 82 |
+
n_test = max(1, round(len(groups) * test_fraction)) if test_fraction > 0 else 0
|
| 83 |
+
if n_val + n_test >= len(groups):
|
| 84 |
+
raise ValueError("Holdout fractions leave no training groups")
|
| 85 |
+
val = set(groups[:n_val])
|
| 86 |
+
test = set(groups[n_val:n_val + n_test])
|
| 87 |
+
result = {"train": [], "val": [], "test": []}
|
| 88 |
+
for item in records:
|
| 89 |
+
component = components[item["id"]]
|
| 90 |
+
split = "val" if component in val else "test" if component in test else "train"
|
| 91 |
+
result[split].append(item)
|
| 92 |
+
return result
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _find_named(root: Path, name: str) -> list[Path]:
|
| 96 |
+
return sorted({p for p in root.rglob(name) if p.is_dir()} | ({root} if root.name == name and root.is_dir() else set()))
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def discover(args) -> tuple[dict[str, list[dict]], dict]:
|
| 100 |
+
splits = {"train": [], "val": [], "test": []}
|
| 101 |
+
audit = {"availability": {}, "policies": {}, "discovery_exclusions": []}
|
| 102 |
+
|
| 103 |
+
def add(partitions):
|
| 104 |
+
for split in splits:
|
| 105 |
+
splits[split].extend(partitions.get(split, []))
|
| 106 |
+
|
| 107 |
+
# The upstream strict loader verifies the complete Kaggle target inventory
|
| 108 |
+
# before applying its versioned train/test contamination quarantine.
|
| 109 |
+
rain = load_rain13k_resized(args.rain13k_root, max_train_pairs=0, seed=args.seed,
|
| 110 |
+
quarantine_manifest=args.quarantine_manifest)
|
| 111 |
+
train = [record(i, j, "rain", "Rain13K", j.stem, "train") for i, j in rain.train_pairs]
|
| 112 |
+
add(split_training(train, args.seed, args.val_fraction))
|
| 113 |
+
for name, pairs in rain.official_test_pairs.items():
|
| 114 |
+
splits["test"].extend(record(i, j, "rain", "Rain13K", f"official:{name}:{j.stem}", name) for i, j in pairs)
|
| 115 |
+
audit["discovery_exclusions"].append({"dataset": "Rain13K", "reason": "versioned_train_test_quarantine",
|
| 116 |
+
"count": rain.quarantined_train_pair_count,
|
| 117 |
+
"evidence": str(Path(args.quarantine_manifest).resolve())})
|
| 118 |
+
audit["policies"]["Rain13K"] = "All surviving train pairs; grouped train validation; all five official test sets locked."
|
| 119 |
+
|
| 120 |
+
lol = args.data_root / "LOLv2" / "lolv2_hf"
|
| 121 |
+
train = [record(i, j, "lowlight", "LOLv2", j.stem, "Train")
|
| 122 |
+
for i, j in discover_exact_pairs(lol / "Train" / "Input", lol / "Train" / "GT")]
|
| 123 |
+
add(split_training(train, args.seed, args.val_fraction))
|
| 124 |
+
splits["test"].extend(record(i, j, "lowlight", "LOLv2", f"official:{j.stem}", "Test")
|
| 125 |
+
for i, j in discover_exact_pairs(lol / "Test" / "Input", lol / "Test" / "GT"))
|
| 126 |
+
audit["policies"]["LOLv2"] = "All local Train pairs with grouped validation; official Test locked."
|
| 127 |
+
|
| 128 |
+
reside = args.data_root / "RESIDE"
|
| 129 |
+
clean_lookup = {p.stem: p for p in image_files(reside / "clear")}
|
| 130 |
+
if len(clean_lookup) != len(image_files(reside / "clear")):
|
| 131 |
+
raise ValueError("RESIDE clean stems are ambiguous across subdirectories")
|
| 132 |
+
train = []
|
| 133 |
+
used = set()
|
| 134 |
+
for degraded in image_files(reside / "hazy"):
|
| 135 |
+
source = degraded.stem.split("_")[0]
|
| 136 |
+
if source not in clean_lookup:
|
| 137 |
+
raise ValueError(f"RESIDE unmatched degraded image: {degraded}")
|
| 138 |
+
used.add(source)
|
| 139 |
+
train.append(record(degraded, clean_lookup[source], "haze", "RESIDE", source, degraded.stem))
|
| 140 |
+
if not train:
|
| 141 |
+
raise ValueError("RESIDE has no pairs")
|
| 142 |
+
add(split_training(train, args.seed, args.val_fraction, args.val_fraction))
|
| 143 |
+
audit["availability"]["RESIDE"] = {"all_local_pairs": len(train), "unused_clean_files": len(set(clean_lookup) - used),
|
| 144 |
+
"full_original_benchmark_verified": False}
|
| 145 |
+
audit["policies"]["RESIDE"] = "ALL local hazy pairs (no first5000 cap); source-group internal validation and test; source bundle may be a benchmark subset."
|
| 146 |
+
|
| 147 |
+
sidd = args.data_root / "SIDD" / "SIDD_Small_sRGB_Only" / "Data"
|
| 148 |
+
if not sidd.is_dir():
|
| 149 |
+
raise FileNotFoundError(sidd)
|
| 150 |
+
train = []
|
| 151 |
+
for scene in sorted(p for p in sidd.iterdir() if p.is_dir()):
|
| 152 |
+
noisy = sorted(scene.glob("NOISY_SRGB_*"))
|
| 153 |
+
clean = sorted(scene.glob("GT_SRGB_*"))
|
| 154 |
+
parts = scene.name.split("_")
|
| 155 |
+
if len(noisy) != 1 or len(clean) != 1 or len(parts) < 3 or not parts[1].isdigit():
|
| 156 |
+
raise ValueError(f"SIDD requires one NOISY/GT pair and identifiable scene: {scene}")
|
| 157 |
+
train.append(record(noisy[0], clean[0], "noise", "SIDD", parts[1], scene.name))
|
| 158 |
+
# Preserve the previous audited ten-scene assignment when that source is used.
|
| 159 |
+
groups = sorted({r["group"] for r in train}, key=lambda g: (hashlib.sha256(g.encode()).digest(), g))
|
| 160 |
+
if len(groups) == 10:
|
| 161 |
+
val_group, test_group = groups[8], groups[9]
|
| 162 |
+
add({"train": [r for r in train if r["group"] not in (val_group, test_group)],
|
| 163 |
+
"val": [r for r in train if r["group"] == val_group],
|
| 164 |
+
"test": [r for r in train if r["group"] == test_group]})
|
| 165 |
+
else:
|
| 166 |
+
add(split_training(train, args.seed, args.val_fraction, args.val_fraction))
|
| 167 |
+
audit["policies"]["SIDD"] = "All local source pairs; scene-group internal holdouts; native crops, no downsampling; not official SIDD benchmark test."
|
| 168 |
+
|
| 169 |
+
snow_root = args.data_root / "Snow100K"
|
| 170 |
+
snow_train = snow_root / "train" / "all"
|
| 171 |
+
train = [record(i, j, "snow", "Snow100K", j.stem, "train")
|
| 172 |
+
for i, j in discover_exact_pairs(snow_train / "synthetic", snow_train / "gt")]
|
| 173 |
+
snow_tests = []
|
| 174 |
+
roots = [p for p in (snow_root / "test", args.snow_test_root) if p and p.is_dir()]
|
| 175 |
+
seen_snow_test_pairs = set()
|
| 176 |
+
for root in roots:
|
| 177 |
+
for gt in _find_named(root, "gt"):
|
| 178 |
+
synthetic = gt.parent / "synthetic"
|
| 179 |
+
if not synthetic.is_dir():
|
| 180 |
+
continue
|
| 181 |
+
for i, j in discover_exact_pairs(synthetic, gt):
|
| 182 |
+
key = (str(i.resolve()), str(j.resolve()))
|
| 183 |
+
if key in seen_snow_test_pairs:
|
| 184 |
+
continue
|
| 185 |
+
seen_snow_test_pairs.add(key)
|
| 186 |
+
snow_tests.append(record(i, j, "snow", "Snow100K", f"official:{j.stem}", str(gt.parent)))
|
| 187 |
+
add(split_training(train, args.seed, args.val_fraction, 0. if snow_tests else args.val_fraction))
|
| 188 |
+
splits["test"].extend(snow_tests)
|
| 189 |
+
audit["availability"]["Snow100K"] = {"all_local_train_pairs": len(train), "official_test_pairs": len(snow_tests)}
|
| 190 |
+
audit["policies"]["Snow100K"] = "All native paired training files; content-group validation; official test locked when present, otherwise explicit internal test holdout."
|
| 191 |
+
|
| 192 |
+
gopro_train, gopro_test = [], []
|
| 193 |
+
for sharp in _find_named(args.gopro_root, "sharp"):
|
| 194 |
+
blur = sharp.parent / "blur"
|
| 195 |
+
if not blur.is_dir():
|
| 196 |
+
raise ValueError(f"GoPro sharp directory lacks blur sibling: {sharp}")
|
| 197 |
+
relative = sharp.relative_to(args.gopro_root)
|
| 198 |
+
is_test = any(part.lower() in ("test", "testing") for part in relative.parts)
|
| 199 |
+
is_train = any(part.lower() in ("train", "training") for part in relative.parts)
|
| 200 |
+
if not is_test and not is_train:
|
| 201 |
+
raise ValueError(f"GoPro split cannot be established from path: {sharp}")
|
| 202 |
+
target = gopro_test if is_test else gopro_train
|
| 203 |
+
target.extend(record(i, j, "blur", "GoPro", sharp.parent.name, str(relative))
|
| 204 |
+
for i, j in discover_exact_pairs(blur, sharp))
|
| 205 |
+
if not gopro_train or not gopro_test:
|
| 206 |
+
raise ValueError("GoPro requires both complete train and official test scene/blur+sharp directories")
|
| 207 |
+
add(split_training(gopro_train, args.seed, args.val_fraction))
|
| 208 |
+
splits["test"].extend(gopro_test)
|
| 209 |
+
audit["availability"]["GoPro"] = {"all_local_train_pairs": len(gopro_train), "official_test_pairs": len(gopro_test)}
|
| 210 |
+
audit["policies"]["GoPro"] = "All native train pairs; whole training scenes reserved for validation; official test scenes locked."
|
| 211 |
+
|
| 212 |
+
jpeg_train, jpeg_test = [], []
|
| 213 |
+
jpeg_sources = [(args.div2k_root, "DIV2K"), (args.flickr2k_root, "Flickr2K")]
|
| 214 |
+
if getattr(args, "div2k_valid_root", None) is not None:
|
| 215 |
+
jpeg_sources.append((args.div2k_valid_root, "DIV2K"))
|
| 216 |
+
for root, dataset in jpeg_sources:
|
| 217 |
+
files = image_files(root)
|
| 218 |
+
if not files:
|
| 219 |
+
raise ValueError(f"No JPEG clean source images: {root}")
|
| 220 |
+
for clean in files:
|
| 221 |
+
relative = clean.relative_to(root)
|
| 222 |
+
lower_parts = (root.name.lower(),) + tuple(part.lower() for part in relative.parts[:-1])
|
| 223 |
+
# Do not accidentally train from super-resolution LR variants.
|
| 224 |
+
if any("_lr" in part or part in ("lr", "x2", "x3", "x4", "x8") for part in lower_parts):
|
| 225 |
+
raise ValueError(f"JPEG source contains LR variants; point root at original HR images: {clean}")
|
| 226 |
+
is_test = dataset == "DIV2K" and any("valid" in part or "test" in part for part in lower_parts)
|
| 227 |
+
item = record(clean, clean, "jpeg", dataset, clean.stem, str(relative), synthesis="jpeg")
|
| 228 |
+
(jpeg_test if is_test else jpeg_train).append(item)
|
| 229 |
+
availability = audit["availability"].setdefault(dataset, {"all_local_clean_images": 0, "source_roots": []})
|
| 230 |
+
availability["all_local_clean_images"] += len(files)
|
| 231 |
+
availability["source_roots"].append(str(root.resolve()))
|
| 232 |
+
add(split_training(jpeg_train, args.seed, args.val_fraction, 0. if jpeg_test else args.val_fraction))
|
| 233 |
+
splits["test"].extend(jpeg_test)
|
| 234 |
+
audit["policies"]["JPEG"] = "Actual on-the-fly JPEG on native DIV2K/Flickr2K HR crops; grouped train validation; DIV2K validation HR used as locked clean-image test when present (not a paired JPEG benchmark)."
|
| 235 |
+
return splits, audit
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _decode_metadata(path: str) -> dict:
|
| 239 |
+
metadata = Path(path).stat()
|
| 240 |
+
return _decode_cached(path, metadata.st_size, metadata.st_mtime_ns)
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@lru_cache(maxsize=200_000)
|
| 244 |
+
def _decode_cached(path: str, size: int, mtime_ns: int) -> dict:
|
| 245 |
+
# Keyed by file identity metadata so a changed input cannot reuse a stale
|
| 246 |
+
# in-process hash after the persistent SQLite cache correctly invalidates it.
|
| 247 |
+
with Image.open(path) as image:
|
| 248 |
+
rgb = image.convert("RGB")
|
| 249 |
+
rgb.load()
|
| 250 |
+
width, height = rgb.size
|
| 251 |
+
digest = hashlib.sha256(b"SCDC_RGB_V1\0" + struct.pack(">II", width, height))
|
| 252 |
+
digest.update(rgb.tobytes())
|
| 253 |
+
return {"width": width, "height": height, "rgb_sha256": digest.hexdigest()}
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
class ImageAuditCache:
|
| 257 |
+
"""Stat-invalidated decoded-pixel cache; SQLite updates remain in main thread."""
|
| 258 |
+
|
| 259 |
+
def __init__(self, path: Path):
|
| 260 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 261 |
+
self.db = sqlite3.connect(str(path))
|
| 262 |
+
self.db.execute("CREATE TABLE IF NOT EXISTS images(path TEXT PRIMARY KEY, size INTEGER, mtime_ns INTEGER, metadata TEXT)")
|
| 263 |
+
|
| 264 |
+
def get(self, path: str):
|
| 265 |
+
stat = Path(path).stat()
|
| 266 |
+
row = self.db.execute("SELECT size,mtime_ns,metadata FROM images WHERE path=?", (path,)).fetchone()
|
| 267 |
+
if row and row[0] == stat.st_size and row[1] == stat.st_mtime_ns:
|
| 268 |
+
return json.loads(row[2])
|
| 269 |
+
return None
|
| 270 |
+
|
| 271 |
+
def put(self, path: str, metadata: dict):
|
| 272 |
+
stat = Path(path).stat()
|
| 273 |
+
self.db.execute("INSERT OR REPLACE INTO images VALUES(?,?,?,?)",
|
| 274 |
+
(path, stat.st_size, stat.st_mtime_ns, json.dumps(metadata)))
|
| 275 |
+
|
| 276 |
+
def close(self):
|
| 277 |
+
self.db.commit()
|
| 278 |
+
self.db.close()
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def audit_files(splits, cache_path: Path, workers: int, exclude_invalid: bool):
|
| 282 |
+
paths = sorted({r[field] for records in splits.values() for r in records for field in ("clean", "degraded")})
|
| 283 |
+
cache = ImageAuditCache(cache_path)
|
| 284 |
+
metadata, errors, pending = {}, {}, []
|
| 285 |
+
try:
|
| 286 |
+
for path in paths:
|
| 287 |
+
try:
|
| 288 |
+
cached = cache.get(path)
|
| 289 |
+
if cached is None:
|
| 290 |
+
pending.append(path)
|
| 291 |
+
else:
|
| 292 |
+
metadata[path] = cached
|
| 293 |
+
except OSError as error:
|
| 294 |
+
errors[path] = str(error)
|
| 295 |
+
|
| 296 |
+
def decode_safe(path):
|
| 297 |
+
try:
|
| 298 |
+
return path, _decode_metadata(path), None
|
| 299 |
+
except (OSError, ValueError, Image.DecompressionBombError) as error:
|
| 300 |
+
return path, None, str(error)
|
| 301 |
+
|
| 302 |
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
| 303 |
+
for index, (path, data, error) in enumerate(pool.map(decode_safe, pending), 1):
|
| 304 |
+
if error:
|
| 305 |
+
errors[path] = error
|
| 306 |
+
else:
|
| 307 |
+
metadata[path] = data
|
| 308 |
+
cache.put(path, data)
|
| 309 |
+
if index % 1000 == 0:
|
| 310 |
+
cache.db.commit()
|
| 311 |
+
print(f"Decoded/hashed {index}/{len(pending)} new files; cached {len(paths) - len(pending)}", flush=True)
|
| 312 |
+
finally:
|
| 313 |
+
cache.close()
|
| 314 |
+
kept, excluded = {split: [] for split in splits}, []
|
| 315 |
+
for split, records in splits.items():
|
| 316 |
+
for item in records:
|
| 317 |
+
bad = [path for path in (item["clean"], item["degraded"]) if path in errors]
|
| 318 |
+
reason = None
|
| 319 |
+
if bad:
|
| 320 |
+
reason = {path: errors[path] for path in bad}
|
| 321 |
+
else:
|
| 322 |
+
clean, degraded = metadata[item["clean"]], metadata[item["degraded"]]
|
| 323 |
+
if (clean["width"], clean["height"]) != (degraded["width"], degraded["height"]):
|
| 324 |
+
reason = "unaligned_dimensions"
|
| 325 |
+
if reason:
|
| 326 |
+
excluded.append({**item, "original_split": split, "reason": "invalid_pair", "detail": reason})
|
| 327 |
+
else:
|
| 328 |
+
kept[split].append({**item, "clean_content_sha256": clean["rgb_sha256"],
|
| 329 |
+
"degraded_content_sha256": degraded["rgb_sha256"],
|
| 330 |
+
"width": clean["width"], "height": clean["height"]})
|
| 331 |
+
if excluded and not exclude_invalid:
|
| 332 |
+
raise ValueError(f"Found {len(excluded)} invalid pairs; first={excluded[0]}. Repair inputs or explicitly pass --exclude-invalid to retain an exclusion audit.")
|
| 333 |
+
return kept, excluded, {"unique_files": len(paths), "decoded_new_files": len(pending), "invalid_files": errors,
|
| 334 |
+
"hash_spec": "sha256(SCDC_RGB_V1 NUL + uint32_be(width,height) + decoded RGB bytes)",
|
| 335 |
+
"near_duplicate_detection": False}
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def main():
|
| 339 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 340 |
+
parser.add_argument("--data-root", type=Path, required=True)
|
| 341 |
+
parser.add_argument("--rain13k-root", type=Path, required=True)
|
| 342 |
+
parser.add_argument("--gopro-root", type=Path, required=True)
|
| 343 |
+
parser.add_argument("--div2k-root", type=Path, required=True)
|
| 344 |
+
parser.add_argument("--div2k-valid-root", type=Path, help="Separate official validation HR root when archives are extracted separately")
|
| 345 |
+
parser.add_argument("--flickr2k-root", type=Path, required=True)
|
| 346 |
+
parser.add_argument("--snow-test-root", type=Path)
|
| 347 |
+
parser.add_argument("--quarantine-manifest", type=Path, default=PROJECT_ROOT / "src/data/rain13k_quarantine_v1.json")
|
| 348 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 349 |
+
parser.add_argument("--hash-cache", type=Path)
|
| 350 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 351 |
+
parser.add_argument("--val-fraction", type=float, default=.05)
|
| 352 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 353 |
+
parser.add_argument("--exclude-invalid", action="store_true", help="Explicitly exclude corrupt/unaligned pairs and list every exclusion; default is fail closed.")
|
| 354 |
+
args = parser.parse_args()
|
| 355 |
+
if not 0 < args.val_fraction < .4 or args.workers < 1:
|
| 356 |
+
parser.error("Require 0 < val-fraction < .4 and workers >= 1")
|
| 357 |
+
started = time.time()
|
| 358 |
+
splits, audit = discover(args)
|
| 359 |
+
discovered = {split: dict(Counter(r["dataset"] for r in records)) for split, records in splits.items()}
|
| 360 |
+
discovered_count = sum(map(len, splits.values()))
|
| 361 |
+
print(json.dumps({"discovered_before_validation": discovered, "pairs": discovered_count}), flush=True)
|
| 362 |
+
cache_path = args.hash_cache or args.output.with_suffix(".image_hashes.sqlite")
|
| 363 |
+
splits, invalid, file_audit = audit_files(splits, cache_path, args.workers, args.exclude_invalid)
|
| 364 |
+
splits, leakage = isolate_splits(splits)
|
| 365 |
+
exclusions = invalid + leakage
|
| 366 |
+
retained = sum(map(len, splits.values()))
|
| 367 |
+
if retained + len(exclusions) != discovered_count:
|
| 368 |
+
raise AssertionError("Coverage accounting failed")
|
| 369 |
+
audit.update({"discovered_before_validation": discovered, "discovered_pairs_after_quarantine": discovered_count,
|
| 370 |
+
"retained_pairs": retained, "excluded_pairs_after_discovery": len(exclusions),
|
| 371 |
+
"coverage_accounting_pass": True, "implicit_record_cap": None, "file_validation": file_audit,
|
| 372 |
+
"exclusions": exclusions, "seed": args.seed, "elapsed_seconds": time.time() - started,
|
| 373 |
+
"test_lock": "No test samples may select checkpoints or tune hyperparameters; final test only after configuration freeze."})
|
| 374 |
+
manifest = {"schema_version": 1, "types": list(TYPES), **splits, "audit": audit}
|
| 375 |
+
audit["counts_by_type"] = validate_manifest(manifest, require_all_types=True)
|
| 376 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 377 |
+
temporary = args.output.with_name(args.output.name + ".tmp")
|
| 378 |
+
temporary.write_text(json.dumps(manifest, indent=2) + "\n")
|
| 379 |
+
temporary.replace(args.output)
|
| 380 |
+
print(json.dumps({"manifest": str(args.output.resolve()), "counts": audit["counts_by_type"],
|
| 381 |
+
"excluded_pairs": len(exclusions), "elapsed_seconds": audit["elapsed_seconds"]}, indent=2), flush=True)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
if __name__ == "__main__":
|
| 385 |
+
main()
|
dataset/phase1_noise_20260906/code/scripts/report_phase1_seven.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Summarize measured suite artifacts; missing runs are never counted as results."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import json
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import statistics
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def write_report(root: Path) -> dict:
|
| 12 |
+
config = json.loads((root / "suite_config.json").read_text())
|
| 13 |
+
state_path = root / "suite_status.json"
|
| 14 |
+
state = json.loads(state_path.read_text()) if state_path.exists() else {"status": "unknown"}
|
| 15 |
+
validated_runs = set(state.get("completed_runs", []))
|
| 16 |
+
rows, measured = [], {}
|
| 17 |
+
for name in config["commands"]:
|
| 18 |
+
path = root / name / "evaluation_test_best.json"
|
| 19 |
+
if not path.exists():
|
| 20 |
+
rows.append(f"| {name} | chưa có kết quả | — | — |")
|
| 21 |
+
continue
|
| 22 |
+
if name not in validated_runs:
|
| 23 |
+
rows.append(f"| {name} | kết quả chưa được queue xác minh | — | — |")
|
| 24 |
+
continue
|
| 25 |
+
report = json.loads(path.read_text())
|
| 26 |
+
real = report["real"]
|
| 27 |
+
if (report.get("manifest_sha256") != config["manifest_sha256"]
|
| 28 |
+
or report.get("training_scope") != "full_manifest"
|
| 29 |
+
or real.get("scope") != "all_records" or real.get("split") != "test"
|
| 30 |
+
or real.get("records_total") != real.get("records_evaluated")):
|
| 31 |
+
raise ValueError(f"Validated run {name} has inconsistent test-report provenance")
|
| 32 |
+
measured[name] = report
|
| 33 |
+
rows.append(f"| {name} | {real['records_evaluated']} | {real['classification']['macro_f1']:.4f} | {real['clean']['any_false_positive_rate_at_0_5']:.4f} |")
|
| 34 |
+
seed_scores = [measured[name]["real"]["classification"]["macro_f1"]
|
| 35 |
+
for name in ("full_seed42", "full_seed43", "full_seed44") if name in measured]
|
| 36 |
+
summary = {"suite_status": state.get("status"), "source_digest": config["source_digest"],
|
| 37 |
+
"manifest_sha256": config["manifest_sha256"], "measured_runs": list(measured),
|
| 38 |
+
"expected_runs": list(config["commands"]), "full_model_seeds_measured": len(seed_scores),
|
| 39 |
+
"macro_f1_seed_mean": statistics.mean(seed_scores) if seed_scores else None,
|
| 40 |
+
"macro_f1_seed_sample_std": statistics.stdev(seed_scores) if len(seed_scores) > 1 else None}
|
| 41 |
+
lines = ["# Phase-1: báo cáo thử nghiệm clean-relative, 7 loại suy giảm", "",
|
| 42 |
+
f"Trạng thái queue: **{state.get('status', 'unknown')}**. Đây là kết quả trial có ngân sách cố định, không phải bằng chứng đã hội tụ.", "",
|
| 43 |
+
f"Manifest SHA-256: `{config['manifest_sha256']}`.", "",
|
| 44 |
+
"| Run | Số cặp test đã đánh giá | Macro-F1 (7 loại) | Clean false-positive rate |",
|
| 45 |
+
"|---|---:|---:|---:|", *rows, "",
|
| 46 |
+
f"Có kết quả của {len(seed_scores)}/3 seed mô hình đầy đủ."]
|
| 47 |
+
if seed_scores:
|
| 48 |
+
lines += [f"Macro-F1 trung bình: {summary['macro_f1_seed_mean']:.4f}; "
|
| 49 |
+
+ (f"độ lệch chuẩn mẫu: {summary['macro_f1_seed_sample_std']:.4f}." if len(seed_scores) > 1 else "chưa đủ seed để tính độ lệch chuẩn."), ""]
|
| 50 |
+
primary = measured.get("full_seed42")
|
| 51 |
+
if primary:
|
| 52 |
+
lines += ["## Kết quả theo loại — full_seed42", "", "| Loại | Số cặp | F1 | AP |", "|---|---:|---:|---:|"]
|
| 53 |
+
for kind, values in primary["real"]["classification"]["per_domain"].items():
|
| 54 |
+
ap = "không xác định" if values["average_precision"] is None else f"{values['average_precision']:.4f}"
|
| 55 |
+
lines.append(f"| {kind} | {values['support']} | {values['f1']:.4f} | {ap} |")
|
| 56 |
+
lines += ["", "## Kiểm tra representation", "",
|
| 57 |
+
"Các báo cáo JSON từng run chứa: clean origin, severity/parameter probes, "
|
| 58 |
+
"content prediction trên scene tách biệt, chuyển mã blind/paired với zero/shuffle controls, "
|
| 59 |
+
"hợp thành hai thứ tự, loại bỏ yếu tố và OOD probe. Không suy ra kết luận disentanglement chỉ từ F1.", ""]
|
| 60 |
+
lines += ["## Giới hạn cần giữ khi diễn giải", "",
|
| 61 |
+
"- Mỗi ảnh real được đánh giá bằng một crop native cố định; không phải đánh giá restoration toàn khung ảnh.",
|
| 62 |
+
"- RESIDE và SIDD dùng đúng phiên bản local đã kiểm kê, không đại diện toàn bộ benchmark gốc.",
|
| 63 |
+
"- Snow100K test hiện là các phần S/L tải được; phần M của test gốc chưa có.",
|
| 64 |
+
"- Synthetic controls là xấp xỉ có tham số; real labels không tự cung cấp severity vật lý.",
|
| 65 |
+
"- no_composition_edges chỉ bỏ hiệu chỉnh tương tác có thứ tự; vẫn giữ attention trích bằng chứng.",
|
| 66 |
+
"- rank1 không phải baseline cùng số tham số; xem thêm baseline class×severity trong parameter probes.",
|
| 67 |
+
"- OOD mới là probe operator chưa thấy; leave-one-type/family-out cần các lần huấn luyện khác.",
|
| 68 |
+
"- Không có kết quả Phase-2 trong thử nghiệm này.", ""]
|
| 69 |
+
for filename, content in (("suite_summary.json", json.dumps(summary, indent=2) + "\n"),
|
| 70 |
+
("evaluation_report.md", "\n".join(lines))):
|
| 71 |
+
target = root / filename
|
| 72 |
+
temporary = target.with_suffix(target.suffix + ".tmp")
|
| 73 |
+
temporary.write_text(content)
|
| 74 |
+
temporary.replace(target)
|
| 75 |
+
return summary
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main():
|
| 79 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 80 |
+
parser.add_argument("--suite-root", type=Path, required=True)
|
| 81 |
+
args = parser.parse_args()
|
| 82 |
+
print(json.dumps(write_report(args.suite_root.resolve())))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
if __name__ == "__main__":
|
| 86 |
+
main()
|
dataset/phase1_noise_20260906/code/scripts/run_phase1_seven_suite.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Run a fixed, sequential full-data trial/ablation suite on one physical GPU.
|
| 3 |
+
|
| 4 |
+
Failures stop the queue; this launcher never silently changes code, data, GPU,
|
| 5 |
+
batch size, or training budget. Re-running requires --resume-suite and identical
|
| 6 |
+
configuration. It never launches Phase-2.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import fcntl
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import signal
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import time
|
| 19 |
+
|
| 20 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 21 |
+
sys.path.insert(0, str(ROOT))
|
| 22 |
+
from train_phase1_clean_relative import atomic_json_save, file_digest, source_provenance # noqa: E402
|
| 23 |
+
from src.data.clean_relative import validate_manifest # noqa: E402
|
| 24 |
+
from scripts.report_phase1_seven import write_report # noqa: E402
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
RUNS = (("full_seed42", 42, ()), ("no_composition_edges_seed42", 42, ("--no-edges",)),
|
| 28 |
+
("rank1_seed42", 42, ("--prototype-only",)), ("full_seed43", 43, ()),
|
| 29 |
+
("full_seed44", 44, ()))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def terminate_owned_group(child):
|
| 33 |
+
"""Only the new session/process group created for our own stage is targeted."""
|
| 34 |
+
try:
|
| 35 |
+
os.killpg(child.pid, signal.SIGTERM)
|
| 36 |
+
except ProcessLookupError:
|
| 37 |
+
return
|
| 38 |
+
try:
|
| 39 |
+
child.wait(timeout=10)
|
| 40 |
+
except subprocess.TimeoutExpired:
|
| 41 |
+
try:
|
| 42 |
+
os.killpg(child.pid, signal.SIGKILL)
|
| 43 |
+
except ProcessLookupError:
|
| 44 |
+
pass
|
| 45 |
+
child.wait()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def run_owned_command(command, environment, log, lock_fd, on_start):
|
| 49 |
+
child = subprocess.Popen(command, cwd=ROOT, env=environment, stdout=log,
|
| 50 |
+
stderr=subprocess.STDOUT, start_new_session=True,
|
| 51 |
+
pass_fds=(lock_fd,))
|
| 52 |
+
try:
|
| 53 |
+
on_start(child)
|
| 54 |
+
code = child.wait()
|
| 55 |
+
finally:
|
| 56 |
+
if child.poll() is None or child.returncode:
|
| 57 |
+
terminate_owned_group(child)
|
| 58 |
+
if code:
|
| 59 |
+
raise subprocess.CalledProcessError(code, command)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def validate_evaluation(report, manifest, manifest_sha, checkpoint_sha, split, args):
|
| 63 |
+
real, controlled = report.get("real", {}), report.get("controlled", {})
|
| 64 |
+
expected = {"split": split, "patch_size": args.patch_size, "seed": 20260906,
|
| 65 |
+
"synthetic_scenes": args.synthetic_scenes, "max_records": None,
|
| 66 |
+
"skip_controlled": False, "no_edges": False}
|
| 67 |
+
if (report.get("manifest_sha256") != manifest_sha or report.get("checkpoint_sha256") != checkpoint_sha
|
| 68 |
+
or report.get("training_scope") != "full_manifest"
|
| 69 |
+
or real.get("scope") != "all_records" or real.get("split") != split
|
| 70 |
+
or real.get("records_total") != len(manifest[split])
|
| 71 |
+
or real.get("records_evaluated") != len(manifest[split])
|
| 72 |
+
or controlled.get("status") != "measured" or controlled.get("source_split") != split
|
| 73 |
+
or controlled.get("requested_scenes") != args.synthetic_scenes
|
| 74 |
+
or any(report.get("arguments", {}).get(key) != value for key, value in expected.items())):
|
| 75 |
+
raise ValueError("Stale, incomplete or differently configured evaluation report; cannot satisfy this suite")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def commands(args, name: str, seed: int, flags: tuple):
|
| 79 |
+
directory = args.output_root / name
|
| 80 |
+
train = [args.python, "-u", str(ROOT / "train_phase1_clean_relative.py"),
|
| 81 |
+
"--manifest", str(args.manifest), "--output-dir", str(directory),
|
| 82 |
+
"--epochs", str(args.epochs), "--batch-size", str(args.batch_size),
|
| 83 |
+
"--synthetic-batch-size", str(args.synthetic_batch_size),
|
| 84 |
+
"--patch-size", str(args.patch_size), "--num-workers", str(args.workers),
|
| 85 |
+
"--threads", "4", "--device", "cuda", "--seed", str(seed),
|
| 86 |
+
"--save-every", "250", "--log-every", "25", *flags]
|
| 87 |
+
evaluations = []
|
| 88 |
+
for split in ("val", "test"):
|
| 89 |
+
evaluations.append([args.python, "-u", str(ROOT / "eval_phase1_clean_relative.py"),
|
| 90 |
+
"--checkpoint", str(directory / "best.pt"), "--manifest", str(args.manifest),
|
| 91 |
+
"--split", split, "--output", str(directory / f"evaluation_{split}_best.json"),
|
| 92 |
+
"--device", "cuda", "--batch-size", str(args.batch_size),
|
| 93 |
+
"--patch-size", str(args.patch_size), "--num-workers", str(args.workers),
|
| 94 |
+
"--threads", "4", "--seed", "20260906", "--synthetic-scenes", str(args.synthetic_scenes)])
|
| 95 |
+
return train, evaluations
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def main():
|
| 99 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 100 |
+
parser.add_argument("--manifest", type=Path, required=True)
|
| 101 |
+
parser.add_argument("--output-root", type=Path, required=True)
|
| 102 |
+
parser.add_argument("--python", default=sys.executable)
|
| 103 |
+
parser.add_argument("--epochs", type=int, default=5)
|
| 104 |
+
parser.add_argument("--batch-size", type=int, default=16)
|
| 105 |
+
parser.add_argument("--synthetic-batch-size", type=int, default=4)
|
| 106 |
+
parser.add_argument("--patch-size", type=int, default=256)
|
| 107 |
+
parser.add_argument("--synthetic-scenes", type=int, default=256)
|
| 108 |
+
parser.add_argument("--workers", type=int, default=4)
|
| 109 |
+
parser.add_argument("--gpu-uuid", default="GPU-8169d457412f2f76")
|
| 110 |
+
parser.add_argument("--expected-pci-bus", type=int, default=171)
|
| 111 |
+
parser.add_argument("--initial-only", action="store_true", help="Explicitly run only full_seed42, not all controls")
|
| 112 |
+
parser.add_argument("--resume-suite", action="store_true")
|
| 113 |
+
parser.add_argument("--dry-run", action="store_true")
|
| 114 |
+
args = parser.parse_args()
|
| 115 |
+
if min(args.epochs, args.batch_size, args.synthetic_batch_size, args.patch_size, args.synthetic_scenes) <= 0 or args.workers < 0:
|
| 116 |
+
parser.error("Invalid training budget or dimensions")
|
| 117 |
+
args.manifest = args.manifest.resolve()
|
| 118 |
+
args.output_root = args.output_root.resolve()
|
| 119 |
+
manifest = json.loads(args.manifest.read_text())
|
| 120 |
+
counts = validate_manifest(manifest, require_all_types=True)
|
| 121 |
+
if any(counts["test"][kind] == 0 for kind in manifest["types"]):
|
| 122 |
+
raise ValueError("Suite requires a declared held-out test source for all seven types")
|
| 123 |
+
runs = RUNS[:1] if args.initial_only else RUNS
|
| 124 |
+
plan = {name: commands(args, name, seed, flags) for name, seed, flags in runs}
|
| 125 |
+
if args.dry_run:
|
| 126 |
+
print(json.dumps({"counts": counts, "commands": plan}, indent=2))
|
| 127 |
+
return
|
| 128 |
+
args.output_root.mkdir(parents=True, exist_ok=True)
|
| 129 |
+
settings = {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items()
|
| 130 |
+
if key not in ("resume_suite", "dry_run")}
|
| 131 |
+
config = {"settings": settings, "manifest_sha256": file_digest(args.manifest), "counts": counts,
|
| 132 |
+
"source_digest": source_provenance()["source_digest"], "commands": plan,
|
| 133 |
+
"launcher_sha256": file_digest(__file__),
|
| 134 |
+
"reporter_sha256": file_digest(ROOT / "scripts/report_phase1_seven.py"),
|
| 135 |
+
"scope": "All admitted training records per epoch; explicit heldout/probe limitations in evaluation reports"}
|
| 136 |
+
# Same-user lock prevents a second copy of this queue, not other users' jobs.
|
| 137 |
+
lock_path = args.output_root.parent / f".phase1_{args.gpu_uuid}.lock"
|
| 138 |
+
with lock_path.open("a") as lock:
|
| 139 |
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
| 140 |
+
config_path = args.output_root / "suite_config.json"
|
| 141 |
+
if config_path.exists():
|
| 142 |
+
if not args.resume_suite:
|
| 143 |
+
raise FileExistsError("Existing suite requires --resume-suite")
|
| 144 |
+
old = json.loads(config_path.read_text())
|
| 145 |
+
if old != json.loads(json.dumps(config)):
|
| 146 |
+
raise ValueError("Suite configuration/source/manifest changed; refuse ambiguous resume")
|
| 147 |
+
else:
|
| 148 |
+
if any((args.output_root / name).exists() for name, _, _ in runs):
|
| 149 |
+
raise FileExistsError("New suite must not adopt pre-existing unowned run directories")
|
| 150 |
+
atomic_json_save(config, config_path)
|
| 151 |
+
environment = os.environ.copy()
|
| 152 |
+
for key in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES"):
|
| 153 |
+
environment.pop(key, None)
|
| 154 |
+
environment.update({"ROCR_VISIBLE_DEVICES": args.gpu_uuid, "OMP_NUM_THREADS": "4",
|
| 155 |
+
"OPENBLAS_NUM_THREADS": "4", "PYTHONUNBUFFERED": "1"})
|
| 156 |
+
verify = "import torch,sys; assert torch.cuda.device_count()==1; p=torch.cuda.get_device_properties(0); assert p.pci_bus_id==int(sys.argv[1]); print(p)"
|
| 157 |
+
subprocess.run([args.python, "-c", verify, str(args.expected_pci_bus)], env=environment, check=True)
|
| 158 |
+
status_path = args.output_root / "suite_status.json"
|
| 159 |
+
status = {"status": "running", "suite_pid": os.getpid(), "started_unix": time.time(), "completed_runs": [],
|
| 160 |
+
"gpu_uuid": args.gpu_uuid, "expected_pci_bus": args.expected_pci_bus}
|
| 161 |
+
|
| 162 |
+
def interrupted(signum, frame):
|
| 163 |
+
raise InterruptedError(f"Suite received signal {signum}; stopping owned stage")
|
| 164 |
+
|
| 165 |
+
signal.signal(signal.SIGTERM, interrupted)
|
| 166 |
+
|
| 167 |
+
def execute(command, run_name, stage):
|
| 168 |
+
directory = args.output_root / run_name
|
| 169 |
+
directory.mkdir(exist_ok=True)
|
| 170 |
+
log_path = directory / f"{stage}.log"
|
| 171 |
+
with log_path.open("a") as log:
|
| 172 |
+
def started(child):
|
| 173 |
+
status.update({"current_run": run_name, "stage": stage, "child_pid": child.pid,
|
| 174 |
+
"command": command, "log": str(log_path), "updated_unix": time.time()})
|
| 175 |
+
atomic_json_save(status, status_path)
|
| 176 |
+
# The child inherits the lock so parent SIGKILL cannot permit a
|
| 177 |
+
# concurrent queue to resume while this trainer still runs.
|
| 178 |
+
run_owned_command(command, environment, log, lock.fileno(), started)
|
| 179 |
+
status["child_pid"] = None
|
| 180 |
+
|
| 181 |
+
try:
|
| 182 |
+
for name, seed, flags in runs:
|
| 183 |
+
directory = args.output_root / name
|
| 184 |
+
train, evaluations = commands(args, name, seed, flags)
|
| 185 |
+
final_path = directory / "final_validation.json"
|
| 186 |
+
finished = json.loads(final_path.read_text()).get("status") == "completed" if final_path.exists() else False
|
| 187 |
+
if finished:
|
| 188 |
+
prior = json.loads((directory / "run_config.json").read_text())
|
| 189 |
+
final = json.loads(final_path.read_text())
|
| 190 |
+
if (prior.get("manifest_sha256") != config["manifest_sha256"]
|
| 191 |
+
or prior.get("provenance", {}).get("source_digest") != config["source_digest"]
|
| 192 |
+
or prior.get("scope") != "full_manifest" or final.get("epoch") != args.epochs
|
| 193 |
+
or final.get("cursor") != 0
|
| 194 |
+
or prior.get("arguments", {}).get("seed") != seed
|
| 195 |
+
or prior.get("arguments", {}).get("no_edges") != ("--no-edges" in flags)
|
| 196 |
+
or prior.get("model_config", {}).get("rank") != (1 if "--prototype-only" in flags else 8)):
|
| 197 |
+
raise ValueError("Completed run provenance/budget does not match suite")
|
| 198 |
+
if not finished:
|
| 199 |
+
if (directory / "last.pt").exists():
|
| 200 |
+
train += ["--resume", str(directory / "last.pt")]
|
| 201 |
+
execute(train, name, "train")
|
| 202 |
+
if json.loads(final_path.read_text()).get("status") != "completed":
|
| 203 |
+
raise RuntimeError(f"Run {name} did not complete its full epoch budget")
|
| 204 |
+
for split, command in zip(("val", "test"), evaluations):
|
| 205 |
+
report_path = directory / f"evaluation_{split}_best.json"
|
| 206 |
+
if not report_path.exists():
|
| 207 |
+
execute(command, name, f"eval_{split}")
|
| 208 |
+
report = json.loads(report_path.read_text())
|
| 209 |
+
validate_evaluation(report, manifest, config["manifest_sha256"],
|
| 210 |
+
file_digest(directory / "best.pt"), split, args)
|
| 211 |
+
status["completed_runs"].append(name)
|
| 212 |
+
atomic_json_save(status, status_path)
|
| 213 |
+
write_report(args.output_root)
|
| 214 |
+
status.update({"status": "completed", "completed_unix": time.time(), "child_pid": None})
|
| 215 |
+
atomic_json_save(status, status_path)
|
| 216 |
+
write_report(args.output_root)
|
| 217 |
+
except BaseException as error:
|
| 218 |
+
status.update({"status": "failed", "error": str(error), "updated_unix": time.time(), "child_pid": None})
|
| 219 |
+
atomic_json_save(status, status_path)
|
| 220 |
+
raise
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
if __name__ == "__main__":
|
| 224 |
+
main()
|
dataset/phase1_noise_20260906/code/slides/README.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Slide deck generator
|
| 2 |
+
|
| 3 |
+
`build_deck.js` builds `SCDC_Final_Deck.pptx` with pptxgenjs, styled after the
|
| 4 |
+
MAVT engineering-brief template (13.33x7.5 in, F4F5F6 ground, Arial + Courier
|
| 5 |
+
New, C75D3A accent, accent-bar panels, Courier footer with page numbers,
|
| 6 |
+
speaker notes). It expects the rendered figures under `outputs/` (charts from
|
| 7 |
+
`make_final_charts.py`, grids from `visualize_v7_uformer.py`,
|
| 8 |
+
`outputs/scene008_dgf.png`). Run from a directory whose parent holds `outputs/`
|
| 9 |
+
(the working copy lives in `outputs/deck/`):
|
| 10 |
+
|
| 11 |
+
```bash
|
| 12 |
+
cd outputs/deck && npm install pptxgenjs && node build_deck.js
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
Optional: `CONTROL_ROWS='[["Step",...],...]' CONTROL_NOTE='...' node build_deck.js`
|
| 16 |
+
fills the Phase-1 control table on slide 11. Rendering for QA on macOS without
|
| 17 |
+
LibreOffice: PowerPoint AppleScript `save ... as save as PDF`, then `pdftoppm`.
|
dataset/phase1_noise_20260906/code/slides/build_deck.js
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// SCDC final-report deck, styled after the MAVT engineering-brief template:
|
| 2 |
+
// 13.33x7.5 in, cool-grey ground, Arial + Courier New, rust accent, panels
|
| 3 |
+
// with a 0.03" accent bar, Courier footer with page number, speaker notes.
|
| 4 |
+
const pptxgen = require("pptxgenjs");
|
| 5 |
+
const path = require("path");
|
| 6 |
+
|
| 7 |
+
const ROOT = path.resolve(__dirname, "..");
|
| 8 |
+
const IMG = {
|
| 9 |
+
progression: path.join(ROOT, "final_charts/01_version_progression.png"),
|
| 10 |
+
external: path.join(ROOT, "final_charts/02_external.png"),
|
| 11 |
+
probe: path.join(ROOT, "final_charts/03_tap_probe.png"),
|
| 12 |
+
control: path.join(ROOT, "final_charts/04_phase1_control.png"),
|
| 13 |
+
haze: path.join(ROOT, "phase2_v7_dgf8k_vis/v7_uformer_haze.png"),
|
| 14 |
+
noise: path.join(ROOT, "phase2_v7_dgf8k_vis/v7_uformer_noise.png"),
|
| 15 |
+
lowlight: path.join(ROOT, "phase2_v7_dgf8k_vis/v7_uformer_lowlight.png"),
|
| 16 |
+
rain: path.join(ROOT, "phase2_v7_dgf8k_vis/v7_uformer_rain.png"),
|
| 17 |
+
scene008: path.join(ROOT, "scene008_dgf.png"),
|
| 18 |
+
};
|
| 19 |
+
const fs = require("fs");
|
| 20 |
+
|
| 21 |
+
// ---- template tokens
|
| 22 |
+
const BG = "F4F5F6", INK = "263042", INK2 = "374151", MUTED = "6B7280", FAINT = "9AA3AF";
|
| 23 |
+
const RULE = "D8DCE2", PANEL = "ECF1F5", WHITE = "FFFFFF", ACCENT = "C75D3A";
|
| 24 |
+
const SANS = "Arial", MONO = "Courier New";
|
| 25 |
+
const L = 0.75, W = 11.83, FOOT = "SCDC · Unified Restoration Diffusion · Final Report 2026";
|
| 26 |
+
|
| 27 |
+
const pres = new pptxgen();
|
| 28 |
+
pres.layout = "LAYOUT_WIDE";
|
| 29 |
+
pres.author = "SCDC";
|
| 30 |
+
pres.title = "SCDC — Final Version";
|
| 31 |
+
|
| 32 |
+
let page = 0;
|
| 33 |
+
function base(eyebrow, headline, sub, notes) {
|
| 34 |
+
const s = pres.addSlide();
|
| 35 |
+
page += 1;
|
| 36 |
+
s.background = { color: BG };
|
| 37 |
+
s.addText(eyebrow, { x: L, y: 0.62, w: W, h: 0.2, fontFace: MONO, fontSize: 9, color: ACCENT, charSpacing: 2, margin: 0 });
|
| 38 |
+
s.addText(headline, { x: L, y: 0.86, w: W, h: 0.46, fontFace: SANS, fontSize: 21, bold: true, color: INK, margin: 0, fit: "shrink" });
|
| 39 |
+
if (sub) s.addText(sub, { x: L, y: 1.4, w: W, h: 0.34, fontFace: SANS, fontSize: 11, color: INK2, margin: 0 });
|
| 40 |
+
s.addShape(pres.shapes.LINE, { x: L, y: 6.98, w: W, h: 0, line: { color: RULE, width: 0.75 } });
|
| 41 |
+
s.addText(FOOT, { x: L, y: 7.08, w: 6, h: 0.2, fontFace: MONO, fontSize: 8, color: FAINT, margin: 0 });
|
| 42 |
+
s.addText(String(page), { x: 12.2, y: 7.08, w: 0.38, h: 0.2, fontFace: MONO, fontSize: 8, color: FAINT, align: "right", margin: 0 });
|
| 43 |
+
if (notes) s.addNotes(notes);
|
| 44 |
+
return s;
|
| 45 |
+
}
|
| 46 |
+
function label(s, text, x, y, w) {
|
| 47 |
+
s.addText(text, { x, y, w, h: 0.18, fontFace: MONO, fontSize: 8.5, color: MUTED, charSpacing: 1.5, margin: 0 });
|
| 48 |
+
}
|
| 49 |
+
function panel(s, x, y, w, h, opts = {}) {
|
| 50 |
+
s.addShape(pres.shapes.RECTANGLE, { x, y, w, h, fill: { color: opts.fill || WHITE }, line: { color: RULE, width: 0.75 } });
|
| 51 |
+
if (opts.bar !== false) s.addShape(pres.shapes.RECTANGLE, { x: x - 0.02, y, w: 0.03, h, fill: { color: opts.barColor || ACCENT }, line: { color: opts.barColor || ACCENT, width: 0 } });
|
| 52 |
+
}
|
| 53 |
+
function body(s, lines, x, y, w, h, opts = {}) {
|
| 54 |
+
const runs = lines.map((t, i) => {
|
| 55 |
+
const o = typeof t === "string" ? { text: t } : t;
|
| 56 |
+
return { text: o.text, options: Object.assign({ breakLine: i < lines.length - 1, bold: !!o.bold, color: o.color || INK2, bullet: !!o.bullet, fontSize: o.size || opts.size || 10.5 }, o.options || {}) };
|
| 57 |
+
});
|
| 58 |
+
s.addText(runs, { x, y, w, h, fontFace: SANS, fontSize: opts.size || 10.5, color: INK2, valign: "top", margin: 0, paraSpaceAfter: opts.gap == null ? 3 : opts.gap });
|
| 59 |
+
}
|
| 60 |
+
function stat(s, value, caption, x, y, w, color) {
|
| 61 |
+
s.addText(value, { x, y, w, h: 0.42, fontFace: SANS, fontSize: 23, bold: true, color: color || INK, margin: 0 });
|
| 62 |
+
s.addText(caption, { x, y: y + 0.42, w, h: 0.34, fontFace: SANS, fontSize: 9, color: MUTED, margin: 0, valign: "top" });
|
| 63 |
+
}
|
| 64 |
+
function mono(s, text, x, y, w, h, size) {
|
| 65 |
+
s.addText(text, { x, y, w, h, fontFace: MONO, fontSize: size || 9.5, color: INK, margin: 0, valign: "top" });
|
| 66 |
+
}
|
| 67 |
+
function img(s, key, x, y, w, h) {
|
| 68 |
+
if (!fs.existsSync(IMG[key])) { panel(s, x, y, w, h, { bar: false }); mono(s, "[missing " + key + "]", x + 0.2, y + 0.2, w - 0.4, 0.3); return; }
|
| 69 |
+
s.addImage({ path: IMG[key], x, y, w, h, sizing: { type: "contain", w, h } });
|
| 70 |
+
}
|
| 71 |
+
function table(s, rows, x, y, colW, opts = {}) {
|
| 72 |
+
const rowH = opts.rowH || 0.27;
|
| 73 |
+
const data = rows.map((r, ri) => r.map((c, ci) => ({
|
| 74 |
+
text: String(c),
|
| 75 |
+
options: {
|
| 76 |
+
fontFace: ci === 0 ? SANS : MONO, fontSize: opts.size || 9.5,
|
| 77 |
+
bold: ri === 0 || (opts.boldCol != null && ci === opts.boldCol),
|
| 78 |
+
color: ri === 0 ? MUTED : INK, align: ci === 0 ? "left" : "right",
|
| 79 |
+
fill: { color: ri === 0 ? PANEL : WHITE }, margin: [2, 6, 2, 6],
|
| 80 |
+
border: { type: "solid", pt: 0.5, color: RULE },
|
| 81 |
+
},
|
| 82 |
+
})));
|
| 83 |
+
s.addTable(data, { x, y, colW, rowH, fontFace: SANS });
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
// ------------------------------------------------------------------ 1 · title
|
| 87 |
+
{
|
| 88 |
+
const s = pres.addSlide(); page += 1; s.background = { color: BG };
|
| 89 |
+
s.addText("SCDC / IMAGE RESTORATION · FINAL REPORT 2026", { x: L, y: 1.15, w: W, h: 0.22, fontFace: MONO, fontSize: 9.5, color: ACCENT, charSpacing: 2, margin: 0 });
|
| 90 |
+
s.addText("Blind all-in-one restoration", { x: L, y: 1.5, w: W, h: 0.8, fontFace: SANS, fontSize: 40, bold: true, color: INK, margin: 0 });
|
| 91 |
+
s.addText([{ text: "with ", options: {} }, { text: "one", options: { color: ACCENT } }, { text: " diffusion network", options: {} }], { x: L, y: 2.25, w: W, h: 0.8, fontFace: SANS, fontSize: 40, bold: true, color: INK, margin: 0 });
|
| 92 |
+
s.addText("Graph degradation representation · Unified two-step ResShift · Uformer trunk with a full-resolution head", { x: L, y: 3.15, w: W, h: 0.3, fontFace: SANS, fontSize: 12.5, color: INK2, margin: 0 });
|
| 93 |
+
const cols = [
|
| 94 |
+
["REPRESENTATION", "Phase-1 graph encoder: 4 node đã biết + 2 free/null, severity, OOD detection"],
|
| 95 |
+
["RESTORATION", "Phase-2: một mạng, T = 2, exact posterior, head full-res train-chung"],
|
| 96 |
+
["EVIDENCE", "27,50 / 0,850 nội bộ · thắng pipeline hai mạng trên cả 3 bộ external"],
|
| 97 |
+
];
|
| 98 |
+
cols.forEach((c, i) => {
|
| 99 |
+
const x = L + i * 3.95;
|
| 100 |
+
s.addShape(pres.shapes.LINE, { x, y: 4.15, w: 3.6, h: 0, line: { color: ACCENT, width: 1.5 } });
|
| 101 |
+
label(s, c[0], x, 4.3, 3.6);
|
| 102 |
+
body(s, [c[1]], x, 4.55, 3.55, 0.8, { size: 10.5 });
|
| 103 |
+
});
|
| 104 |
+
s.addText("haze · lowlight · noise · rain — không nhãn task lúc inference — seed 42, 2×RTX 3090", { x: L, y: 5.75, w: W, h: 0.25, fontFace: MONO, fontSize: 9, color: MUTED, margin: 0 });
|
| 105 |
+
s.addShape(pres.shapes.LINE, { x: L, y: 6.98, w: W, h: 0, line: { color: RULE, width: 0.75 } });
|
| 106 |
+
s.addText(FOOT, { x: L, y: 7.08, w: 6, h: 0.2, fontFace: MONO, fontSize: 8, color: FAINT, margin: 0 });
|
| 107 |
+
s.addText("1", { x: 12.2, y: 7.08, w: 0.38, h: 0.2, fontFace: MONO, fontSize: 8, color: FAINT, align: "right", margin: 0 });
|
| 108 |
+
s.addNotes("Bản cuối của SCDC: một mạng diffusion hai bước, có head full-res và FiLM, được điều kiện hoá bởi graph của Phase-1. Mọi số trong deck là seed 42; nội bộ 317 ảnh val; external là ba bộ locked.");
|
| 109 |
+
}
|
| 110 |
+
|
| 111 |
+
// ------------------------------------------------------------------ 2 · problem
|
| 112 |
+
{
|
| 113 |
+
const s = base("BÀI TOÁN · VÌ SAO PHẢI THỐNG NHẤT", "Bốn suy hoá, một model, không nhãn — pipeline hai mạng thì chắp vá",
|
| 114 |
+
"Điểm xuất phát của chu kỳ cuối: gen-2 = diffusion 1-step + refiner tách rời. Đẹp ở val nội bộ, nhưng là hai mạng ghép, và external lộ ngay.",
|
| 115 |
+
"Motivating problem: hai mạng ghép — refiner học riêng — overfit phân phối nội bộ. Directive của dự án: một pipeline thống nhất, hiệu quả với diffusion, không phải hai mạng chắp vá.");
|
| 116 |
+
label(s, "INPUT · ĐỘ KHÓ THEO DOMAIN (PSNR ẢNH VÀO)", L, 2.1, 6.5);
|
| 117 |
+
const doms = [["Haze", "17,3"], ["Lowlight", "9,8"], ["Noise", "27,3"], ["Rain", "21,3"]];
|
| 118 |
+
doms.forEach((d, i) => {
|
| 119 |
+
const x = L + i * 1.55;
|
| 120 |
+
s.addShape(pres.shapes.RECTANGLE, { x, y: 2.4, w: 1.35, h: 0.95, fill: { color: WHITE }, line: { color: RULE, width: 0.75 } });
|
| 121 |
+
s.addText(d[1], { x: x + 0.12, y: 2.47, w: 1.15, h: 0.45, fontFace: SANS, fontSize: 21, bold: true, color: INK, margin: 0 });
|
| 122 |
+
s.addText(d[0], { x: x + 0.12, y: 2.92, w: 1.15, h: 0.3, fontFace: MONO, fontSize: 8.5, color: MUTED, margin: 0 });
|
| 123 |
+
});
|
| 124 |
+
body(s, [
|
| 125 |
+
{ text: "Blind: ", bold: true, options: { color: INK } },
|
| 126 |
+
"Phase-1 phải tự suy loại và mức suy hoá; không có prompt, không có nhãn.",
|
| 127 |
+
{ text: "All-in-one: ", bold: true, options: { color: INK } },
|
| 128 |
+
"một bộ trọng số cho cả bốn — các task dễ giẫm nhau (định luật drift, slide 5).",
|
| 129 |
+
{ text: "Thước đo: ", bold: true, options: { color: INK } },
|
| 130 |
+
"macro PSNR/SSIM nội bộ (317 ảnh) + ba bộ external locked (rain 1200 · haze 300 · scene008 20).",
|
| 131 |
+
], L, 3.6, 6.4, 2.1, { size: 10.5, gap: 2 });
|
| 132 |
+
|
| 133 |
+
panel(s, 7.5, 2.1, 5.08, 3.55);
|
| 134 |
+
label(s, "GEN-2 TRƯỚC CHU KỲ CUỐI · HAI MẠNG", 7.75, 2.28, 4.6);
|
| 135 |
+
body(s, [
|
| 136 |
+
"y → Phase-1 → U-Net 1-step x̂₀ → RefinerDecoder (NAFNet-lite, train riêng) → x̂",
|
| 137 |
+
{ text: "Nội bộ 27,55 / 0,874 — nhưng:", bold: true, options: { color: INK } },
|
| 138 |
+
{ text: "refiner train rời overfit val: external noise −5 dB so với mạng thuần", bullet: true },
|
| 139 |
+
{ text: "hai optimizer, hai loss, hai checkpoint — không phải một quá trình diffusion", bullet: true },
|
| 140 |
+
{ text: "artifact nhỏ (snow lấm tấm) vẫn lọt", bullet: true },
|
| 141 |
+
], 7.75, 2.55, 4.65, 2.2, { size: 10.5 });
|
| 142 |
+
s.addText("Yêu cầu: giữ chất lượng của refiner nhưng nằm TRONG một mạng, một loss.", { x: 7.75, y: 4.95, w: 4.65, h: 0.55, fontFace: SANS, fontSize: 10.5, italic: true, color: ACCENT, margin: 0 });
|
| 143 |
+
|
| 144 |
+
panel(s, L, 5.9, 11.83, 0.85, { fill: PANEL });
|
| 145 |
+
s.addText([{ text: "Câu hỏi của chu kỳ cuối: ", options: { bold: true, color: INK } }, { text: "một mạng diffusion có đuổi kịp hai mạng không — và cái gì trong Phase-1 thực sự được dùng?", options: { color: INK2 } }], { x: L + 0.25, y: 6.1, w: 11.3, h: 0.5, fontFace: SANS, fontSize: 11, margin: 0 });
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
// ------------------------------------------------------------------ 3 · architecture
|
| 149 |
+
{
|
| 150 |
+
const s = base("KIẾN TRÚC · BẢN CUỐI (uformer_dgf8k, best @6000)", "Hai pha, một quá trình: graph chẩn đoán → diffusion hai bước → head full-res",
|
| 151 |
+
"Mọi thành phần mới đều zero-init/identity: eval@0 của từng chu kỳ trùng bitwise best chu kỳ trước.",
|
| 152 |
+
"Phase-1 đóng băng (ll_v3). Phase-2: pixel-unshuffle x2 thành state 12 kênh, anchor u_y, dự đoán x0. Coarse t=2 rồi posterior chính xác rồi fine t=1, sau đó pixel-shuffle và head full-res. Liều w ở inference là tuỳ chọn.");
|
| 153 |
+
// pipeline boxes
|
| 154 |
+
const boxes = [
|
| 155 |
+
["y", "ảnh vào", 0.9], ["Phase-1", "graph encoder\n(frozen)", 1.55], ["context ‖ adaLN", "8 token · global vec\n(2 đường sống)", 1.75],
|
| 156 |
+
["Uformer t=2", "coarse x̂₀\nx0-MSE + tháp", 1.55], ["posterior", "exact, κ theo mẫu", 1.35], ["Uformer t=1", "fine x̂₀\nL1+VGG+UV+Y", 1.55], ["head", "tail 256px + FiLM", 1.35], ["x̂", "ảnh ra", 0.9],
|
| 157 |
+
];
|
| 158 |
+
let x = L; const y = 2.05;
|
| 159 |
+
boxes.forEach((b, i) => {
|
| 160 |
+
const w = b[2];
|
| 161 |
+
const hi = i === 3 || i === 5;
|
| 162 |
+
s.addShape(pres.shapes.RECTANGLE, { x, y, w, h: 0.8, fill: { color: hi ? PANEL : WHITE }, line: { color: hi ? ACCENT : RULE, width: hi ? 1.25 : 0.75 } });
|
| 163 |
+
s.addText(b[0], { x: x + 0.08, y: y + 0.07, w: w - 0.16, h: 0.28, fontFace: MONO, fontSize: 9.5, bold: true, color: INK, margin: 0 });
|
| 164 |
+
s.addText(b[1], { x: x + 0.08, y: y + 0.36, w: w - 0.16, h: 0.42, fontFace: SANS, fontSize: 8, color: MUTED, margin: 0, valign: "top" });
|
| 165 |
+
if (i < boxes.length - 1) s.addText("→", { x: x + w - 0.02, y: y + 0.25, w: 0.24, h: 0.3, fontFace: SANS, fontSize: 12, color: FAINT, margin: 0, align: "center" });
|
| 166 |
+
x += w + 0.2;
|
| 167 |
+
});
|
| 168 |
+
// three detail panels
|
| 169 |
+
const P = [
|
| 170 |
+
["PHASE-1 · GRAPH ENCODER (ll_v3)", [
|
| 171 |
+
"Hai nhánh spatial + wavelet; LL-global branch (Haar LL³ + 14 thống kê photometric) giữ thông tin toàn cục",
|
| 172 |
+
"Đầu ra: 6 node token (4 known + 2 free), routing, severity 4-d calibrated, spatial maps 16×16, content 64 px, unknown residual, global condition 256-d",
|
| 173 |
+
"Null/OOD: free slots học từ ảnh sạch + OOD tổng hợp — OOD → free 55–60/60, novelty gap 3–4×",
|
| 174 |
+
]],
|
| 175 |
+
["PHASE-2 · TRUNK UFORMER, T = 2", [
|
| 176 |
+
"LeWin block: window-attn 8×8 + LeFF + adaLN zero-init; dims 64/128/192/256, cond 256",
|
| 177 |
+
"Cross-attention với 8 token graph ở 2 scale sâu; adaLN từ global_vector; MoE 5 expert top-2 ở 7 vị trí; per-type κ",
|
| 178 |
+
"η = [0 · 0,04 · 0,98]; fine step dựng từ chính prediction (detach) qua posterior chính xác",
|
| 179 |
+
]],
|
| 180 |
+
["IMAGE HEAD + DGF (train-chung)", [
|
| 181 |
+
"Tail NAFNet-lite 3×48 ở FULL-RES (restored ‖ y) + FiLM 6 tham số từ global condition",
|
| 182 |
+
"Tháp Laplacian 16/32/64 px với anchor u_y — identity chính xác khi δ = 0, deep supervision λ 0,1/0,2/0,3",
|
| 183 |
+
"Token null học được (context, global) · dropout p 0,15 · identity pairs q 0,10 · liều w ở inference",
|
| 184 |
+
]],
|
| 185 |
+
];
|
| 186 |
+
P.forEach((p, i) => {
|
| 187 |
+
const px = L + i * 3.98; const py = 3.25;
|
| 188 |
+
panel(s, px, py, 3.85, 2.3);
|
| 189 |
+
label(s, p[0], px + 0.25, py + 0.18, 3.5);
|
| 190 |
+
body(s, p[1].map(t => ({ text: t, bullet: true })), px + 0.25, py + 0.45, 3.45, 1.8, { size: 9.5, gap: 4 });
|
| 191 |
+
});
|
| 192 |
+
s.addText("Mất mát composite, một optimizer: coarse x0-MSE (fp32) + tháp MSE + fine [L1 + 0,1·VGG + 0,5·chroma(UV) + 0,5·luma(pool 8×8)] + gate anchor/correction", { x: L, y: 5.85, w: W, h: 0.5, fontFace: MONO, fontSize: 9, color: INK, margin: 0 });
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
// ------------------------------------------------------------------ 4 · method: unified two-step
|
| 196 |
+
{
|
| 197 |
+
const s = base("PHƯƠNG PHÁP · UNIFIED TWO-STEP RESSHIFT", "Refiner được nội hoá thành bước fine của chính quá trình diffusion",
|
| 198 |
+
"Hai bước trên cùng trọng số, điều kiện thời gian bằng adaLN — không mạng phụ, không optimizer thứ hai.",
|
| 199 |
+
"ResShift: u_t = u0 + eta_t (u_y - u0) + kappa sqrt(eta_t) eps. Với T=2, bước coarse quyết định nội dung toàn cục, bước fine đánh bóng. Bước fine được dựng từ dự đoán của chính model (detach) nên không có exposure bias.");
|
| 200 |
+
panel(s, L, 2.05, 5.75, 4.0);
|
| 201 |
+
label(s, "FORWARD / REVERSE (T = 2)", L + 0.25, 2.23, 5.3);
|
| 202 |
+
mono(s, "u_t = u₀ + η_t (u_y − u₀) + κ √η_t · ε\nη = [0, 0,04, 0,98]\n\ncoarse t=2: x̂₀ = f(u₂, u_y, c) → x0-MSE fp32\n u₁ ~ q(u₁ | u₂, x̂₀.detach)\n (posterior chính xác, κ theo mẫu)\nfine t=1: x̂₀' = f(u₁, u_y, c) → shuffle → head\n L1 + 0,1·VGG + 0,5·UV + 0,5·Y", L + 0.25, 2.5, 5.3, 2.0, 8.5);
|
| 203 |
+
body(s, [
|
| 204 |
+
{ text: "Vì sao T = 2 chứ không phải chain dài: ", bold: true, options: { color: INK } },
|
| 205 |
+
"đo được từ v4: chain 8 bước 22,04 < 1-step 22,68 (exposure bias). Hai bước chain-aware là điểm cân bằng: 23,41 với cùng trunk conv (+0,7).",
|
| 206 |
+
{ text: "Noise fine = torch.flip(noise coarse): ", bold: true, options: { color: INK } },
|
| 207 |
+
"kế hoạch nhiễu vẫn replay được theo record — mọi eval tái lập bitwise.",
|
| 208 |
+
], L + 0.25, 4.5, 5.3, 1.45, { size: 10, gap: 2 });
|
| 209 |
+
|
| 210 |
+
panel(s, 6.85, 2.05, 5.73, 4.0, { fill: PANEL });
|
| 211 |
+
label(s, "LIÊN HỆ VỚI GEN-2 HAI MẠNG", 7.1, 2.23, 5.2);
|
| 212 |
+
const map = [["gen-2", "bản cuối"], ["U-Net 1-step x̂₀ (MSE)", "bước coarse t = 2 (x0-MSE + tháp)"], ["RefinerDecoder train riêng (L1+VGG)", "bước fine t = 1 + head full-res, cùng loss"], ["2 optimizer · 2 checkpoint", "1 optimizer · 1 EMA · 1 checkpoint"], ["external noise −5 dB (overfit)", "external giữ nguyên hoặc tăng"]];
|
| 213 |
+
map.forEach((r, i) => {
|
| 214 |
+
const yy = 2.55 + i * 0.56;
|
| 215 |
+
s.addText(r[0], { x: 7.1, y: yy, w: 2.5, h: 0.5, fontFace: SANS, fontSize: 9.5, color: MUTED, margin: 0, valign: "middle" });
|
| 216 |
+
s.addText("→", { x: 9.6, y: yy, w: 0.3, h: 0.5, fontFace: SANS, fontSize: 11, color: FAINT, margin: 0, valign: "middle" });
|
| 217 |
+
s.addText(r[1], { x: 9.95, y: yy, w: 2.55, h: 0.5, fontFace: SANS, fontSize: 9.5, bold: i === 0, color: INK, margin: 0, valign: "middle" });
|
| 218 |
+
if (i < map.length - 1) s.addShape(pres.shapes.LINE, { x: 7.1, y: yy + 0.53, w: 5.35, h: 0, line: { color: RULE, width: 0.5 } });
|
| 219 |
+
});
|
| 220 |
+
s.addText("Định luật 3: cùng một dung lượng full-res — đặt trong cùng graph/loss/optimizer thì an toàn ngoài phân phối; tách thành mạng thứ hai thì overfit.", { x: L, y: 6.25, w: W, h: 0.5, fontFace: SANS, fontSize: 10.5, italic: true, color: ACCENT, margin: 0 });
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
// ------------------------------------------------------------------ 5 · backbone / drift law
|
| 224 |
+
{
|
| 225 |
+
const s = base("BACKBONE · VÌ SAO UFORMER", "Window-attention + adaLN zero-init xoá định luật drift của conv-trunk",
|
| 226 |
+
"Mọi trunk conv (v4, v6, v6.1, v7-conv) đều hy sinh lowlight khi tối ưu dài. Uformer từ scratch leo đơn điệu, best == final ở mọi chu kỳ.",
|
| 227 |
+
"Đây là phát hiện kiến trúc lớn nhất: cùng recipe, đổi block conv sang LeWin thì lowlight không còn bị hy sinh và không cần curriculum hay cứu checkpoint sớm.");
|
| 228 |
+
const rows = [["Biến thể (một mạng)", "Best macro", "SSIM", "Drift"], ["v4 chain 8-step", "22,04", "0,658", "−0,6"], ["v4 1-step", "22,68", "0,662", "—"], ["v7-conv unified (warm-start)", "23,41 @750", "0,703", "nặng sau 750"], ["v7-Uformer from scratch", "25,26 @8000", "0,777", "không"], ["… + 16k + 8k + 8k + 8k", "27,50", "0,850", "không"]];
|
| 229 |
+
table(s, rows, L, 2.1, [2.7, 1.2, 0.75, 1.65], { size: 9.5, rowH: 0.3 });
|
| 230 |
+
stat(s, "0", "chu kỳ bị drift trên Uformer (5 chu kỳ, 48k steps)", L, 4.25, 2.1, ACCENT);
|
| 231 |
+
stat(s, "23,41 → 22,16", "v7-conv: đỉnh @750 rồi sụp về @8000 (lowlight sụp trước)", L + 2.3, 4.25, 3.0);
|
| 232 |
+
stat(s, "+1,18 / +0,15 / +0,84 / +0,07", "lãi từng chu kỳ warm-restart (SGDR) — schedule quyết định “hội tụ”, loss chưa từng phẳng ở LR còn sống", L, 5.3, 6.2);
|
| 233 |
+
|
| 234 |
+
panel(s, 7.5, 2.1, 5.08, 3.9);
|
| 235 |
+
label(s, "LEWIN BLOCK · NHỮNG GÌ KHÁC CONV", 7.75, 2.28, 4.6);
|
| 236 |
+
body(s, [
|
| 237 |
+
{ text: "WindowAttention 8×8, rel-pos bias, tự thu window ở map nhỏ", bullet: true },
|
| 238 |
+
{ text: "LeFF: pointwise → depthwise → pointwise, GELU", bullet: true },
|
| 239 |
+
{ text: "adaLN 6 tham số zero-init từ (time ⊕ global_vector ⊕ strength prompt)", bullet: true },
|
| 240 |
+
{ text: "Cùng hợp đồng điều kiện với conv v6: cross-attn coarse, inject @64/@16, MoE bank, zero-init output", bullet: true },
|
| 241 |
+
{ text: "Cùng số tham số cỡ ~12M trunk; DDP 2 GPU cần find_unused_parameters (MoE hard-skip)", bullet: true },
|
| 242 |
+
], 7.75, 2.55, 4.65, 2.4, { size: 10, gap: 4 });
|
| 243 |
+
s.addText("Giả thuyết cơ chế: adaLN zero-init cho phép điều kiện thời gian/graph điều biến từng block mà không phá đường tắt identity; conv-trunk phải “chia sẻ” kênh giữa task nên lowlight (ít mẫu khó nhất) bị bỏ rơi.", { x: 7.75, y: 5.05, w: 4.65, h: 0.85, fontFace: SANS, fontSize: 9.5, italic: true, color: INK2, margin: 0 });
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
// ------------------------------------------------------------------ 6 · progression
|
| 247 |
+
{
|
| 248 |
+
const s = base("KẾT QUẢ · TIẾN HOÁ PHIÊN BẢN", "22,7 → 27,5 dB macro qua năm chu kỳ warm-restart, không chu kỳ nào lùi",
|
| 249 |
+
"Mỗi chu kỳ thêm đúng một cơ chế zero-init, eval@0 trùng bitwise chu kỳ trước — nên mỗi cột chênh là đóng góp của riêng cơ chế đó.",
|
| 250 |
+
"Chart: thanh xanh là một mạng, cam là tham chiếu hai mạng. Chú ý head full-res là bước nhảy SSIM lớn nhất — đúng chẩn đoán trần nửa độ phân giải.");
|
| 251 |
+
img(s, "progression", L, 2.0, 7.6, 4.0);
|
| 252 |
+
const items = [["+2,58", "Uformer scratch vs v7-conv: backbone", INK], ["+1,18", "chroma UV + 16k warm-restart: màu lowlight, chroma noise", INK], ["+0,84 / +0,035", "head full-res + FiLM: noise +2,6, SSIM nhảy lớn nhất", ACCENT], ["+0,07 / +12,6", "DGF: macro nhỏ, identity ảnh sạch 27,8 → 40,4 dB", INK]];
|
| 253 |
+
items.forEach((it, i) => stat(s, it[0], it[1], 8.65, 2.05 + i * 1.02, 3.9, it[2]));
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
// ------------------------------------------------------------------ 7 · internal results by domain
|
| 257 |
+
{
|
| 258 |
+
const s = base("KẾT QUẢ · NỘI BỘ THEO DOMAIN", "Haze, noise đã vượt/ngang hai mạng; lowlight, rain là hai mặt trận còn lại",
|
| 259 |
+
"dgf8k best @6000, liều w = 1. Sweep liều: w = 0,5 cho macro 27,54; w = 0 cho SSIM 0,852 — đường cong phẳng (slide 11).",
|
| 260 |
+
"Rain nội bộ bị GT lệch tone kéo thấp giả tạo — external rain 28,0 dB. Lowlight cực đoan là trần thông tin: input ~9,7 dB gần đen, độ sáng tuyệt đối của GT không có trong ảnh vào.");
|
| 261 |
+
const rows = [["Domain", "Degraded", "Bản cuối", "gen-2 (2 mạng)", "n"], ["Haze", "17,31", "32,73", "30,2", "100"], ["Noise", "27,33", "35,99", "36,9", "19"], ["Lowlight", "9,77", "18,74", "20,3", "100"], ["Rain", "21,25", "22,53", "22,8", "98"], ["Macro PSNR", "18,91", "27,50", "27,55", "317"], ["Macro SSIM", "0,551", "0,850", "0,874", ""]];
|
| 262 |
+
table(s, rows, L, 2.05, [1.6, 1.1, 1.15, 1.35, 0.6], { size: 10, rowH: 0.32, boldCol: 2 });
|
| 263 |
+
body(s, [
|
| 264 |
+
{ text: "Haze 32,7: ", bold: true, options: { color: INK } }, "vượt hai mạng 2,5 dB; FiLM + LL-global đúng địa bàn.",
|
| 265 |
+
{ text: "Noise 36,0: ", bold: true, options: { color: INK } }, "tail full-res +2,6; còn kém refiner 0,9 (n = 19, 1 scene).",
|
| 266 |
+
{ text: "Lowlight 18,7: ", bold: true, options: { color: INK } }, "cấu trúc tốt (SSIM 0,39 → 0,75), màu đã sửa bằng chroma, overshoot cực đoan là trần thông tin.",
|
| 267 |
+
{ text: "Rain 22,5: ", bold: true, options: { color: INK } }, "streak gỡ tốt, PSNR bị tone GT; external 28,0.",
|
| 268 |
+
], L, 4.5, 5.9, 1.9, { size: 10, gap: 2 });
|
| 269 |
+
img(s, "noise", 7.1, 1.95, 5.5, 4.5);
|
| 270 |
+
label(s, "NOISE · DEGRADED | BẢN CUỐI | GT · KHÔNG CHERRY-PICK", 7.1, 6.55, 5.5);
|
| 271 |
+
}
|
| 272 |
+
|
| 273 |
+
// ------------------------------------------------------------------ 8 · qualitative haze + rain
|
| 274 |
+
{
|
| 275 |
+
const s = base("ĐỊNH TÍNH · HAZE VÀ RAIN", "Khử mù gần trùng GT kể cả mù dày; derain sạch streak, phần thua là tone GT",
|
| 276 |
+
"Ba mẫu mỗi domain chọn máy móc theo record-id (đầu / giữa / cuối) — không cherry-pick. Mỗi ô ghi PSNR / SSIM so với GT.",
|
| 277 |
+
"Hàng zebra và bờ biển ở rain: streak gỡ tốt, SSIM tăng, nhưng PSNR giảm vì ảnh ra lệch tone toàn cục so với GT — đây là đặc thù của cặp dữ liệu rain, không phải lỗi derain.");
|
| 278 |
+
img(s, "haze", L, 1.95, 5.8, 4.9);
|
| 279 |
+
img(s, "rain", 6.78, 1.95, 5.8, 4.9);
|
| 280 |
+
}
|
| 281 |
+
|
| 282 |
+
// ------------------------------------------------------------------ 9 · qualitative lowlight + limits
|
| 283 |
+
{
|
| 284 |
+
const s = base("ĐỊNH TÍNH · LOWLIGHT VÀ HAI TRẦN ĐÃ XÁC LẬP", "Màu trở lại nhờ chroma loss; ca gần đen tuyệt đối là trần thông tin",
|
| 285 |
+
"Ghế sân vận động: 8k → nâu xám, bản cuối → xanh. Hai mẫu quạt (input 9,7 dB): overshoot còn nguyên qua chroma, luma, head, DGF.",
|
| 286 |
+
"Hai trần: (1) độ sáng tuyệt đối của GT không có trong ảnh vào gần đen; (2) scene008 tối có vân — model đọc tối thành lowlight và vân thành noise. Cả hai không sửa được bằng loss thêm.");
|
| 287 |
+
img(s, "lowlight", L, 1.95, 5.8, 4.9);
|
| 288 |
+
panel(s, 6.9, 1.95, 5.68, 4.9, { fill: PANEL });
|
| 289 |
+
label(s, "HAI TRẦN — ĐO ĐƯỢC, KHÔNG ĐOÁN", 7.15, 2.13, 5.2);
|
| 290 |
+
body(s, [
|
| 291 |
+
{ text: "1 · Overshoot lowlight cực đoan", bold: true, options: { color: INK } },
|
| 292 |
+
"Input ~9,7 dB gần đen tuyệt đối. Chroma loss, luma loss (pool 8×8), head, DGF: per-sample vẫn 12,3–12,8 dB trong khi aggregate lowlight tăng 18,0 → 18,8. Độ sáng tuyệt đối của GT là thông tin không tồn tại trong ảnh vào.",
|
| 293 |
+
{ text: "2 · Ảnh sạch tối, có vân (scene008)", bold: true, options: { color: INK } },
|
| 294 |
+
"Input 39–44 dB ≈ GT. Phase-1 gán clean GT là noise 0,41 / severity 0,33 — y hệt bản degraded. Nhánh null kéo sáng như lowlight (12,8 dB), nhánh có điều kiện làm mờ nhẹ (26–32).",
|
| 295 |
+
{ text: "Hệ quả thiết kế", bold: true, options: { color: INK } },
|
| 296 |
+
"Identity phải được dạy bằng ảnh sạch giống phân phối triển khai (tối, có vân, real-camera); identity nội bộ 40 dB không chuyển sang đây.",
|
| 297 |
+
], 7.15, 2.4, 5.2, 4.3, { size: 11, gap: 6 });
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
// ------------------------------------------------------------------ 10 · external
|
| 301 |
+
{
|
| 302 |
+
const s = base("KẾT QUẢ · EXTERNAL HELD-OUT", "Ngoài phân phối, một mạng thắng hai mạng trên cả ba bộ — bảng nội bộ đảo chiều",
|
| 303 |
+
"Cùng protocol locked: rain 1200 · RESIDE held-out 300 · SIDD scene008 20. PSNR / SSIM / LPIPS; số trên cột là PSNR.",
|
| 304 |
+
"Refiner của gen-2 overfit val nội bộ: external noise thua 4,7 dB. Head full-res train-chung của bản cuối giữ hoặc tăng external. scene008 vẫn không về identity vì lý do ở slide 9.");
|
| 305 |
+
img(s, "external", L, 1.95, 7.4, 3.4);
|
| 306 |
+
const rows = [["Bộ · PSNR / SSIM", "gen-2", "bản cuối"], ["Rain 1200", "26,71 / 0,833", "27,88 / 0,834"], ["Haze 300", "31,18 / 0,971", "31,87 / 0,975"], ["scene008", "22,35 / 0,801", "26,50 / 0,825"]];
|
| 307 |
+
table(s, rows, 8.45, 2.0, [1.35, 1.4, 1.4], { size: 9, rowH: 0.3 });
|
| 308 |
+
body(s, [
|
| 309 |
+
{ text: "Rain: ", bold: true, options: { color: INK } }, "+1,2 dB so với hai mạng; nội bộ 22,5 là số bị GT lệch tone.",
|
| 310 |
+
{ text: "Haze: ", bold: true, options: { color: INK } }, "+0,7; LPIPS 0,010 → 0,009 — gần trùng GT.",
|
| 311 |
+
{ text: "scene008: ", bold: true, options: { color: INK } }, "+4,2 dB và LPIPS 0,33 → 0,19 so với head8k, nhưng vẫn −12 so với input 39 dB (trần 2).",
|
| 312 |
+
], 8.45, 3.4, 4.1, 2.0, { size: 9.5, gap: 2 });
|
| 313 |
+
panel(s, L, 5.6, 11.83, 1.15, { fill: PANEL });
|
| 314 |
+
s.addText([{ text: "Định luật 3 (đo hai lần): ", options: { bold: true, color: INK } }, { text: "cùng dung lượng full-res, refiner train rời mất 5 dB external; head train chung trong một graph/loss/optimizer giữ nguyên — vị trí đặt dung lượng quyết định khái quát hoá, không phải dung lượng.", options: { color: INK2 } }], { x: L + 0.25, y: 5.78, w: 11.3, h: 0.8, fontFace: SANS, fontSize: 10.5, margin: 0 });
|
| 315 |
+
}
|
| 316 |
+
|
| 317 |
+
// ------------------------------------------------------------------ 11 · what Phase-1 is worth
|
| 318 |
+
{
|
| 319 |
+
const s = base("PHASE-1 ĐÁNG BAO NHIÊU · PROBE, DGF, CONTROL", "Trunk dùng Phase-1 như bộ mô tả ảnh qua hai đường; cấu trúc graph gần như không dùng",
|
| 320 |
+
"Probe leave-one-out ở inference (head8k), sweep liều sau DGF, và control p = 1 (không Phase-1, cùng recipe và warm-start).",
|
| 321 |
+
"Ba bằng chứng chồng nhau: probe cho thấy hai đường sống và các plug chết; DGF cho thấy nhánh null được train phục hồi gần bằng nhánh có điều kiện; control p=1 định lượng giá trị thật của Phase-1 — tập trung ở haze.");
|
| 322 |
+
img(s, "probe", L, 1.95, 6.1, 2.95);
|
| 323 |
+
panel(s, 7.1, 1.95, 5.48, 2.95);
|
| 324 |
+
label(s, "SWEEP LIỀU SAU DGF (val, coarse-step)", 7.35, 2.13, 5.0);
|
| 325 |
+
const rows = [["w", "macro", "SSIM", "low", "haze"], ["0", "27,49", "0,852", "18,87", "32,46"], ["0,5", "27,54", "0,851", "18,80", "32,77"], ["1", "27,50", "0,850", "18,74", "32,73"], ["1,25", "27,43", "0,849", "18,68", "32,55"]];
|
| 326 |
+
table(s, rows, 7.35, 2.38, [0.7, 1.0, 1.0, 1.0, 1.0], { size: 9, rowH: 0.26 });
|
| 327 |
+
s.addText("Phẳng: +1,95 lowlight của ablation biến mất khi nhánh null được train. Ablation trên model chưa có nhánh null đo “rụt rè off-manifold”, không đo giá trị của điều kiện (định luật 4).", { x: 7.35, y: 3.8, w: 5.0, h: 1.0, fontFace: SANS, fontSize: 9.5, italic: true, color: INK2, margin: 0 });
|
| 328 |
+
panel(s, L, 5.1, 11.83, 1.65, { fill: PANEL });
|
| 329 |
+
label(s, "BA SỐ ĐO ĐI CÙNG", L + 0.25, 5.28, 6);
|
| 330 |
+
stat(s, "−7,79 dB", "rút toàn bộ Phase-1 khỏi head8k (nhánh null CHƯA train) — ảo giác về giá trị điều kiện", L + 0.25, 5.55, 3.6);
|
| 331 |
+
stat(s, "−0,085 dB", "xoá hoàn toàn MoE gate + κ per-type: cơ chế liều cũ không được dùng", L + 4.1, 5.55, 3.6);
|
| 332 |
+
stat(s, "27,8 → 40,4 dB", "identity trên ảnh sạch trước/sau cặp identity (DGF) — ở mọi w", L + 7.95, 5.55, 3.6, ACCENT);
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
// ------------------------------------------------------------------ 12 · control: no Phase-1
|
| 336 |
+
{
|
| 337 |
+
const s = base("CONTROL · TRUNK CÓ CẦN PHASE-1 KHÔNG", "Tắt điều kiện, giữ nguyên recipe: khoảng cách co về ~0,5 dB và nằm ở haze",
|
| 338 |
+
"p = 1: mọi mẫu dùng token null khi fine-tune, eval hoàn toàn không điều kiện (cả hai bước). 1 GPU, batch 8 × accum 2.",
|
| 339 |
+
process.env.CONTROL_NOTES || "Control xuất phát 20,4 (nhánh null chưa train) và leo về sát model có điều kiện. Phần chênh còn lại tập trung ở haze — thông tin toàn cục airlight/transmission — và một phần noise; lowlight của control cao hơn (không bị over-drive).");
|
| 340 |
+
img(s, "control", L, 1.95, 7.3, 3.3);
|
| 341 |
+
const CONTROL_ROWS = JSON.parse(process.env.CONTROL_ROWS || "null") || [["Step", "2000", "4000", "6000", "8000"], ["Không Phase-1", "26,49", "26,73", "27,03", "đang chạy"], ["Có Phase-1", "27,27", "27,46", "27,50", "27,45"], ["Chênh", "−0,78", "−0,74", "−0,47", "—"]];
|
| 342 |
+
table(s, CONTROL_ROWS, 8.35, 2.0, [1.45, 0.7, 0.7, 0.7, 0.7], { size: 9, rowH: 0.28 });
|
| 343 |
+
label(s, "PHÂN BỐ CHÊNH THEO DOMAIN (" + (process.env.CONTROL_STEP || "@6000") + ")", 8.35, 3.3, 4.2);
|
| 344 |
+
const DOM = JSON.parse(process.env.CONTROL_DOMAINS || "null") || [["Haze", "−1,94"], ["Noise", "−0,67"], ["Lowlight", "+0,86"], ["Rain", "−0,13"]];
|
| 345 |
+
DOM.forEach((r, i) => {
|
| 346 |
+
const yy = 3.55 + i * 0.36;
|
| 347 |
+
s.addText(r[0], { x: 8.35, y: yy, w: 1.6, h: 0.32, fontFace: SANS, fontSize: 10, color: INK2, margin: 0, valign: "middle" });
|
| 348 |
+
s.addText(r[1], { x: 10.0, y: yy, w: 1.2, h: 0.32, fontFace: MONO, fontSize: 10.5, bold: true, color: r[1].startsWith("+") ? "1C7C54" : ACCENT, margin: 0, valign: "middle", align: "right" });
|
| 349 |
+
s.addText(i === 0 ? "control thua nhiều nhất" : i === 2 ? "control HƠN (không over-drive)" : "", { x: 11.3, y: yy, w: 1.3, h: 0.32, fontFace: SANS, fontSize: 8, color: MUTED, margin: 0, valign: "middle" });
|
| 350 |
+
});
|
| 351 |
+
panel(s, L, 5.55, 11.83, 1.05, { fill: PANEL });
|
| 352 |
+
s.addText([{ text: "Đọc cho claim: ", options: { bold: true, color: INK } }, { text: process.env.CONTROL_VERDICT || "chênh 0,2–0,5 dB → Phase-1 giữ vai chẩn đoán / OOD / hỗ trợ haze; restoration là công của trunk. Caveat: control warm-start từ trọng số từng học có điều kiện — trả lời cho inference và fine-tune tiếp, chưa phải from-scratch.", options: { color: INK2 } }], { x: L + 0.25, y: 5.72, w: 11.3, h: 0.8, fontFace: SANS, fontSize: 10.5, margin: 0, valign: "top" });
|
| 353 |
+
}
|
| 354 |
+
|
| 355 |
+
// ------------------------------------------------------------------ 13 · conclusions
|
| 356 |
+
{
|
| 357 |
+
const s = base("KẾT LUẬN · CLAIM ĐỨNG ĐƯỢC VÀ BƯỚC TIẾP", "Một mạng hai bước thay được hai mạng; Phase-1 là chẩn đoán + hỗ trợ haze",
|
| 358 |
+
"Mọi claim bên trái có số đo trong deck; mọi hạn chế bên phải là điều reviewer sẽ hỏi.",
|
| 359 |
+
"Kết luận trung thực: paper là về restoration diffusion thống nhất với các định luật đo được; phần representation phải được viết đúng vai trò của nó.");
|
| 360 |
+
panel(s, L, 2.0, 5.8, 3.5);
|
| 361 |
+
label(s, "ĐỨNG ĐƯỢC", L + 0.25, 2.18, 5.3);
|
| 362 |
+
body(s, [
|
| 363 |
+
{ text: "Unified two-step một mạng: 27,50 / 0,850 nội bộ; thắng hai mạng external cả 3 bộ", bullet: true },
|
| 364 |
+
{ text: "Uformer/LeWin xoá định luật drift: 5 chu kỳ, best == final", bullet: true },
|
| 365 |
+
{ text: "Head full-res train-chung an toàn OOD; refiner tách rời thì không", bullet: true },
|
| 366 |
+
{ text: "Identity ảnh sạch 27,8 → 40,4 dB (cặp identity)", bullet: true },
|
| 367 |
+
{ text: "Phase-1: OOD/null detection thật (55–60/60), honest-null; conditioning đáng ~0,5 dB, tập trung ở haze", bullet: true },
|
| 368 |
+
{ text: "Bảy định luật vận hành có số đo (drift, chain, vị trí dung lượng, ablation null, SGDR, identity phân phối, trần thông tin)", bullet: true },
|
| 369 |
+
], L + 0.25, 2.45, 5.3, 2.95, { size: 11, gap: 7 });
|
| 370 |
+
panel(s, 6.78, 2.0, 5.8, 3.5, { barColor: FAINT });
|
| 371 |
+
label(s, "HẠN CHẾ · BƯỚC TIẾP", 7.03, 2.18, 5.3);
|
| 372 |
+
body(s, [
|
| 373 |
+
{ text: "1 seed; noise val n = 19 (1 scene); chưa test mixed degradation; unseen degradation mới có detection, chưa có restoration", bullet: true },
|
| 374 |
+
{ text: "Khái niệm noise của Phase-1 lệch (SIDD noise thật → rain 0,58); hai lần sửa bằng augmentation đều âm tính — giới hạn 8 scene", bullet: true },
|
| 375 |
+
{ text: "Tiếp: identity pairs từ ảnh sạch tối/có vân thật ở trunk; prune plug chết (content/spatial inject, MoE bank)", bullet: true },
|
| 376 |
+
{ text: "Tiếp: seed 43/44 cho chu kỳ cuối; benchmark công khai để so AirNet / PromptIR / DA-CLIP", bullet: true },
|
| 377 |
+
{ text: "Câu hỏi mở: Phase-1 from scratch có cần cho trunk không — control mới trả lời cho trường hợp warm-start", bullet: true },
|
| 378 |
+
], 7.03, 2.45, 5.3, 2.95, { size: 11, gap: 7 });
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
pres.writeFile({ fileName: path.join(__dirname, "SCDC_Final_Deck.pptx") }).then(f => console.log("wrote", f));
|
dataset/phase1_noise_20260906/code/src/__init__.py
ADDED
|
File without changes
|
dataset/phase1_noise_20260906/code/src/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (166 Bytes). View file
|
|
|
dataset/phase1_noise_20260906/code/src/data/__init__.py
ADDED
|
File without changes
|
dataset/phase1_noise_20260906/code/src/data/clean_relative.py
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Uncapped paired data and explicitly approximate, controlled interventions.
|
| 2 |
+
|
| 3 |
+
Physical parameters are ground truth ONLY for the synthetic controls below.
|
| 4 |
+
Real datasets supply type/pair supervision, never invented physical labels.
|
| 5 |
+
All image crops are native-resolution; small images are padded, not resized.
|
| 6 |
+
Manifest v1 remains readable; explicit online noise requires manifest v2 so
|
| 7 |
+
older loaders reject these records instead of misreading them as clean pairs.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import hashlib
|
| 13 |
+
import io
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
import random
|
| 18 |
+
from typing import Any, Mapping, Sequence
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
from PIL import Image
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn.functional as F
|
| 24 |
+
from torch.utils.data import Dataset
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
TYPES = ("rain", "noise", "haze", "lowlight", "snow", "blur", "jpeg")
|
| 28 |
+
TYPE_ORDER = TYPES
|
| 29 |
+
IMAGE_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"})
|
| 30 |
+
NOISE_PROFILES = ("gaussian", "signal_dependent_gaussian")
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def validate_noise_record(record: Mapping[str, Any]) -> None:
|
| 34 |
+
"""Validate the versioned explicit-noise manifest contract, not old controls.
|
| 35 |
+
|
| 36 |
+
sigma is read-noise standard deviation and shot is the square root of the
|
| 37 |
+
signal-dependent variance slope, both in normalized RGB units. This is a
|
| 38 |
+
Gaussian approximation in RGB, not a claim to simulate the RAW camera ISP.
|
| 39 |
+
"""
|
| 40 |
+
if record.get("type") != "noise" or record.get("noise_profile") not in NOISE_PROFILES:
|
| 41 |
+
raise ValueError("Explicit noise requires type=noise and a known noise profile")
|
| 42 |
+
if record.get("noise_synthesis_version") != 1:
|
| 43 |
+
raise ValueError("Explicit noise requires noise_synthesis_version=1")
|
| 44 |
+
params = record.get("noise_parameters")
|
| 45 |
+
if not isinstance(params, dict) or set(params) != {"severity", "sigma", "shot", "noise_seed"}:
|
| 46 |
+
raise ValueError("Explicit noise parameters require exactly severity, sigma, shot, noise_seed")
|
| 47 |
+
for name in ("severity", "sigma", "shot"):
|
| 48 |
+
value = params[name]
|
| 49 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
| 50 |
+
raise ValueError(f"Explicit noise {name} must be finite numeric")
|
| 51 |
+
if not 0 <= value <= 1:
|
| 52 |
+
raise ValueError(f"Explicit noise {name} must lie in [0,1]")
|
| 53 |
+
if params["severity"] <= 0 or params["sigma"] ** 2 + params["shot"] ** 2 <= 0:
|
| 54 |
+
raise ValueError("Explicit noise must have positive dose and variance")
|
| 55 |
+
seed = params["noise_seed"]
|
| 56 |
+
if isinstance(seed, bool) or not isinstance(seed, int) or not 0 <= seed < 2 ** 31:
|
| 57 |
+
raise ValueError("Explicit noise_seed must be an integer in [0,2**31)")
|
| 58 |
+
if ((record["noise_profile"] == "gaussian" and params["shot"] != 0)
|
| 59 |
+
or (record["noise_profile"] == "signal_dependent_gaussian" and params["shot"] <= 0)):
|
| 60 |
+
raise ValueError("Explicit noise profile disagrees with signal-dependent variance")
|
| 61 |
+
if record.get("clean") != record.get("degraded"):
|
| 62 |
+
raise ValueError("Explicit noise stores only one clean source path; synthesize after cropping")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def image_files(directory: Path) -> list[Path]:
|
| 66 |
+
if not directory.is_dir():
|
| 67 |
+
raise FileNotFoundError(f"Missing image directory: {directory}")
|
| 68 |
+
return sorted(p for p in directory.rglob("*") if p.is_file() and p.suffix.lower() in IMAGE_EXTENSIONS)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def discover_exact_pairs(degraded_dir: Path, clean_dir: Path) -> list[tuple[Path, Path]]:
|
| 72 |
+
"""Require a bijection by relative filename; unmatched targets also fail."""
|
| 73 |
+
inputs = {p.relative_to(degraded_dir).as_posix(): p for p in image_files(degraded_dir)}
|
| 74 |
+
targets = {p.relative_to(clean_dir).as_posix(): p for p in image_files(clean_dir)}
|
| 75 |
+
if set(inputs) != set(targets):
|
| 76 |
+
raise ValueError(
|
| 77 |
+
f"pairing mismatch: {degraded_dir} / {clean_dir}; "
|
| 78 |
+
f"missing clean={sorted(set(inputs) - set(targets))[:10]}, "
|
| 79 |
+
f"missing degraded={sorted(set(targets) - set(inputs))[:10]}"
|
| 80 |
+
)
|
| 81 |
+
if not inputs:
|
| 82 |
+
raise ValueError(f"No image pairs: {degraded_dir}")
|
| 83 |
+
return [(inputs[name], targets[name]) for name in sorted(inputs)]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def isolate_splits(splits: Mapping[str, Sequence[dict]]) -> tuple[dict[str, list[dict]], list[dict]]:
|
| 87 |
+
"""Exclude lower-priority overlapping content/groups, including transitivity.
|
| 88 |
+
|
| 89 |
+
A connected component links decoded-identical clean images and a dataset's
|
| 90 |
+
scene/group. Locked test wins over validation, which wins over training.
|
| 91 |
+
Different degradations of the same clean within ONE split are retained.
|
| 92 |
+
"""
|
| 93 |
+
parent: dict[str, str] = {}
|
| 94 |
+
|
| 95 |
+
def find(key: str) -> str:
|
| 96 |
+
parent.setdefault(key, key)
|
| 97 |
+
while parent[key] != key:
|
| 98 |
+
parent[key] = parent[parent[key]]
|
| 99 |
+
key = parent[key]
|
| 100 |
+
return key
|
| 101 |
+
|
| 102 |
+
def union(a: str, b: str) -> None:
|
| 103 |
+
first, second = find(a), find(b)
|
| 104 |
+
if first != second:
|
| 105 |
+
parent[first] = second
|
| 106 |
+
|
| 107 |
+
def keys(record: dict) -> tuple[str, str]:
|
| 108 |
+
content = record.get("clean_content_sha256")
|
| 109 |
+
if not content:
|
| 110 |
+
raise ValueError(f"Missing clean content hash: {record.get('id')}")
|
| 111 |
+
return (f"content:{content}", f"group:{record['dataset']}:{record['group']}")
|
| 112 |
+
|
| 113 |
+
for split in ("train", "val", "test"):
|
| 114 |
+
for record in splits.get(split, []):
|
| 115 |
+
union(*keys(record))
|
| 116 |
+
priority = {"train": 0, "val": 1, "test": 2}
|
| 117 |
+
winner: dict[str, str] = {}
|
| 118 |
+
for split in priority:
|
| 119 |
+
for record in splits.get(split, []):
|
| 120 |
+
component = find(keys(record)[0])
|
| 121 |
+
if priority[split] > priority.get(winner.get(component, ""), -1):
|
| 122 |
+
winner[component] = split
|
| 123 |
+
kept = {split: [] for split in priority}
|
| 124 |
+
excluded = []
|
| 125 |
+
for split in priority:
|
| 126 |
+
for record in splits.get(split, []):
|
| 127 |
+
retained_split = winner[find(keys(record)[0])]
|
| 128 |
+
if retained_split == split:
|
| 129 |
+
kept[split].append(record)
|
| 130 |
+
else:
|
| 131 |
+
excluded.append({**record, "original_split": split, "protected_split": retained_split,
|
| 132 |
+
"reason": "cross_split_content_or_group_overlap"})
|
| 133 |
+
return kept, excluded
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def validate_manifest(manifest: Mapping[str, Any], *, require_all_types: bool = False) -> dict:
|
| 137 |
+
version = manifest.get("schema_version")
|
| 138 |
+
if version not in (1, 2) or tuple(manifest.get("types", ())) != TYPES:
|
| 139 |
+
raise ValueError("Manifest schema_version=1 or 2 and canonical seven-type order are required")
|
| 140 |
+
seen_ids: set[str] = set()
|
| 141 |
+
content_splits: dict[str, str] = {}
|
| 142 |
+
group_splits: dict[tuple[str, str], str] = {}
|
| 143 |
+
counts = {}
|
| 144 |
+
for split in ("train", "val", "test"):
|
| 145 |
+
records = manifest.get(split)
|
| 146 |
+
if not isinstance(records, list):
|
| 147 |
+
raise ValueError(f"Manifest {split} must be a list")
|
| 148 |
+
counts[split] = {kind: 0 for kind in TYPES}
|
| 149 |
+
for record in records:
|
| 150 |
+
for required in ("id", "clean", "degraded", "type", "dataset", "group", "clean_content_sha256"):
|
| 151 |
+
if required not in record or record[required] in (None, ""):
|
| 152 |
+
raise ValueError(f"Manifest record missing {required}: {record}")
|
| 153 |
+
if record["type"] not in TYPES:
|
| 154 |
+
raise ValueError(f"Unknown degradation type {record['type']}")
|
| 155 |
+
synthesis = record.get("synthesis")
|
| 156 |
+
if synthesis not in (None, "jpeg", "noise"):
|
| 157 |
+
raise ValueError(f"Unknown manifest synthesis {synthesis!r}")
|
| 158 |
+
if synthesis == "jpeg" and record["type"] != "jpeg":
|
| 159 |
+
raise ValueError("JPEG synthesis requires type=jpeg")
|
| 160 |
+
if synthesis == "noise":
|
| 161 |
+
if version != 2:
|
| 162 |
+
raise ValueError("Explicit noise synthesis requires manifest schema_version=2")
|
| 163 |
+
validate_noise_record(record)
|
| 164 |
+
if record["id"] in seen_ids:
|
| 165 |
+
raise ValueError(f"Duplicate record id {record['id']}")
|
| 166 |
+
seen_ids.add(record["id"])
|
| 167 |
+
content = record["clean_content_sha256"]
|
| 168 |
+
group = (record["dataset"], record["group"])
|
| 169 |
+
if content_splits.setdefault(content, split) != split or group_splits.setdefault(group, split) != split:
|
| 170 |
+
raise ValueError(f"Cross-split content/group leakage at {record['id']}")
|
| 171 |
+
counts[split][record["type"]] += 1
|
| 172 |
+
if require_all_types and split in ("train", "val") and any(counts[split][kind] == 0 for kind in TYPES):
|
| 173 |
+
raise ValueError(f"Every type must be represented in {split}: {counts[split]}")
|
| 174 |
+
return counts
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _seed_from(*parts: Any) -> int:
|
| 178 |
+
value = "\0".join(str(p) for p in parts)
|
| 179 |
+
return int.from_bytes(hashlib.sha256(value.encode()).digest()[:8], "big") % (2 ** 31)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class PairedDegradationDataset(Dataset):
|
| 183 |
+
"""One item per manifest record. No replacement, caps, or hidden filtering."""
|
| 184 |
+
|
| 185 |
+
def __init__(self, manifest_path: str | Path | Mapping[str, Any], split: str = "train",
|
| 186 |
+
crop_size: int = 128, seed: int = 42):
|
| 187 |
+
manifest = (dict(manifest_path) if isinstance(manifest_path, Mapping)
|
| 188 |
+
else json.loads(Path(manifest_path).read_text()))
|
| 189 |
+
validate_manifest(manifest)
|
| 190 |
+
if split not in ("train", "val", "test"):
|
| 191 |
+
raise ValueError(f"Unknown split {split}")
|
| 192 |
+
if crop_size <= 0:
|
| 193 |
+
raise ValueError("crop_size must be positive")
|
| 194 |
+
self.records = manifest[split]
|
| 195 |
+
self.split, self.crop_size, self.seed, self.epoch = split, crop_size, seed, 0
|
| 196 |
+
|
| 197 |
+
def set_epoch(self, epoch: int) -> None:
|
| 198 |
+
# Call before creating each epoch's iterator; persistent workers must
|
| 199 |
+
# be disabled unless the caller propagates this state to its workers.
|
| 200 |
+
self.epoch = int(epoch)
|
| 201 |
+
|
| 202 |
+
def __len__(self) -> int:
|
| 203 |
+
return len(self.records)
|
| 204 |
+
|
| 205 |
+
@staticmethod
|
| 206 |
+
def _read(path: str) -> torch.Tensor:
|
| 207 |
+
with Image.open(path) as image:
|
| 208 |
+
array = np.array(image.convert("RGB"), dtype=np.uint8, copy=True)
|
| 209 |
+
return torch.from_numpy(array).permute(2, 0, 1).float().div_(255.)
|
| 210 |
+
|
| 211 |
+
def __getitem__(self, index: int) -> dict[str, Any]:
|
| 212 |
+
record = self.records[index]
|
| 213 |
+
clean = self._read(record["clean"])
|
| 214 |
+
degraded = clean.clone() if record.get("synthesis") in ("jpeg", "noise") else self._read(record["degraded"])
|
| 215 |
+
if degraded.shape != clean.shape:
|
| 216 |
+
raise ValueError(f"Unaligned pair shapes at {record['id']}: {degraded.shape} vs {clean.shape}")
|
| 217 |
+
side = self.crop_size
|
| 218 |
+
height, width = clean.shape[-2:]
|
| 219 |
+
pad = (0, max(0, side - width), 0, max(0, side - height))
|
| 220 |
+
if any(pad):
|
| 221 |
+
clean, degraded = F.pad(clean, pad, mode="replicate"), F.pad(degraded, pad, mode="replicate")
|
| 222 |
+
height, width = clean.shape[-2:]
|
| 223 |
+
rng = random.Random(_seed_from(self.seed, self.epoch if self.split == "train" else 0, record["id"]))
|
| 224 |
+
top = rng.randrange(height - side + 1) if self.split == "train" else (height - side) // 2
|
| 225 |
+
left = rng.randrange(width - side + 1) if self.split == "train" else (width - side) // 2
|
| 226 |
+
clean = clean[:, top:top + side, left:left + side].contiguous()
|
| 227 |
+
degraded = degraded[:, top:top + side, left:left + side].contiguous()
|
| 228 |
+
label = TYPES.index(record["type"])
|
| 229 |
+
severity = torch.zeros(len(TYPES))
|
| 230 |
+
severity_mask = torch.zeros(len(TYPES), dtype=torch.bool)
|
| 231 |
+
if record.get("synthesis") == "jpeg":
|
| 232 |
+
epoch = self.epoch if self.split == "train" else 0
|
| 233 |
+
params = sample_degradation_parameters("jpeg", _seed_from(self.seed, epoch, record["id"], "jpeg"))
|
| 234 |
+
degraded, params = synthesize_degradation(clean, "jpeg", params)
|
| 235 |
+
severity[label], severity_mask[label] = params["severity"], True
|
| 236 |
+
elif record.get("synthesis") == "noise":
|
| 237 |
+
params = dict(record["noise_parameters"])
|
| 238 |
+
# The manifest seed replays evaluation independently of loader seed.
|
| 239 |
+
# Training changes only realization by epoch, never physical dose.
|
| 240 |
+
if self.split == "train":
|
| 241 |
+
params["noise_seed"] = _seed_from(params["noise_seed"], record["id"], self.epoch, "noise_v1")
|
| 242 |
+
degraded, params = synthesize_degradation(clean, "noise", params)
|
| 243 |
+
severity[label], severity_mask[label] = params["severity"], True
|
| 244 |
+
if self.split == "train" and rng.random() < .5:
|
| 245 |
+
clean, degraded = clean.flip(-1), degraded.flip(-1)
|
| 246 |
+
presence = torch.zeros(len(TYPES))
|
| 247 |
+
presence[label] = 1.
|
| 248 |
+
return {"clean": clean, "degraded": degraded, "label": torch.tensor(label, dtype=torch.long),
|
| 249 |
+
"presence": presence, "severity": severity, "severity_mask": severity_mask,
|
| 250 |
+
"record_id": record["id"], "group": record["group"], "dataset": record["dataset"],
|
| 251 |
+
"index": index, "type": record["type"]}
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def sample_degradation_parameters(kind: str, seed: int = 0, heldout: bool = False) -> dict[str, Any]:
|
| 255 |
+
"""Train strengths [.08,.70]; extrapolation strengths [.80,.98].
|
| 256 |
+
|
| 257 |
+
These approximate controls are not a claim to simulate all real examples.
|
| 258 |
+
JPEG's physical quality is integer 1..100, inverse to normalized severity.
|
| 259 |
+
"""
|
| 260 |
+
if kind not in TYPES:
|
| 261 |
+
raise ValueError(f"Unknown degradation {kind}")
|
| 262 |
+
rng = random.Random(seed)
|
| 263 |
+
severity = rng.uniform(.80, .98) if heldout else rng.uniform(.08, .70)
|
| 264 |
+
common = {"severity": severity}
|
| 265 |
+
if kind == "noise":
|
| 266 |
+
return {**common, "sigma": .12 * severity, "shot": .04 * severity,
|
| 267 |
+
"noise_seed": rng.randrange(2 ** 31)}
|
| 268 |
+
if kind == "haze":
|
| 269 |
+
return {**common, "transmission": 1. - .90 * severity,
|
| 270 |
+
"airlight": [rng.uniform(.7, 1.) for _ in range(3)]}
|
| 271 |
+
if kind == "lowlight":
|
| 272 |
+
return {**common, "gain": math.exp(-2.5 * severity), "gamma": 1. + .8 * severity}
|
| 273 |
+
if kind == "blur":
|
| 274 |
+
return {**common, "length": max(1, int(round(1. + 24. * severity))), "angle": rng.uniform(0., 180.)}
|
| 275 |
+
if kind == "rain":
|
| 276 |
+
return {**common, "density": .003 + .025 * severity, "opacity": .15 + .75 * severity,
|
| 277 |
+
"length": max(3, int(round(3. + 24. * severity))), "angle": rng.uniform(55., 125.),
|
| 278 |
+
"noise_seed": rng.randrange(2 ** 31)}
|
| 279 |
+
if kind == "snow":
|
| 280 |
+
return {**common, "density": .0005 + .008 * severity, "opacity": .2 + .75 * severity,
|
| 281 |
+
"radius": max(1, int(round(1. + 3. * severity))), "noise_seed": rng.randrange(2 ** 31)}
|
| 282 |
+
quality = max(1, min(100, int(round(100. - 95. * severity))))
|
| 283 |
+
return {"severity": (100. - quality) / 95., "quality": quality}
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def _line_kernel(length: int, angle: float, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
|
| 287 |
+
size = max(1, int(length))
|
| 288 |
+
size += 1 - size % 2
|
| 289 |
+
kernel = torch.zeros(size, size, device=device, dtype=dtype)
|
| 290 |
+
radius = (size - 1) / 2
|
| 291 |
+
steps = torch.linspace(-radius, radius, max(1, size * 4), device=device)
|
| 292 |
+
radians = math.radians(angle)
|
| 293 |
+
xx = (radius + steps * math.cos(radians)).round().long().clamp(0, size - 1)
|
| 294 |
+
yy = (radius + steps * math.sin(radians)).round().long().clamp(0, size - 1)
|
| 295 |
+
kernel[yy, xx] = 1.
|
| 296 |
+
return kernel / kernel.sum()
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def _filter(image: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
|
| 300 |
+
channels = image.shape[0]
|
| 301 |
+
pad = kernel.shape[-1] // 2
|
| 302 |
+
padded = F.pad(image.unsqueeze(0), (pad, pad, pad, pad), mode="replicate")
|
| 303 |
+
return F.conv2d(padded, kernel[None, None].expand(channels, 1, -1, -1), groups=channels)[0]
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def synthesize_degradation(clean: torch.Tensor, kind: str,
|
| 307 |
+
parameters: Mapping[str, Any] | None = None, seed: int = 0,
|
| 308 |
+
heldout: bool = False) -> tuple[torch.Tensor, dict[str, Any]]:
|
| 309 |
+
"""Apply one controlled CHW float-image operation without altering parameters.
|
| 310 |
+
|
| 311 |
+
Seeds are embedded in sampled stochastic parameters, so parameter transfer
|
| 312 |
+
preserves both physical settings and realization for same-shaped images.
|
| 313 |
+
JPEG is an actual Pillow JPEG encode/decode, not a differentiable surrogate.
|
| 314 |
+
"""
|
| 315 |
+
if kind not in TYPES or clean.ndim != 3 or clean.shape[0] != 3:
|
| 316 |
+
raise ValueError("Expected canonical degradation and RGB CHW image")
|
| 317 |
+
if not torch.is_floating_point(clean):
|
| 318 |
+
raise ValueError("clean must be floating point in [0,1]")
|
| 319 |
+
params = dict(parameters) if parameters is not None else sample_degradation_parameters(kind, seed, heldout)
|
| 320 |
+
if "severity" not in params or not 0. <= float(params["severity"]) <= 1.:
|
| 321 |
+
raise ValueError("parameters require severity in [0,1]")
|
| 322 |
+
if kind == "jpeg" and (not isinstance(params.get("quality"), int) or not 1 <= params["quality"] <= 100):
|
| 323 |
+
raise ValueError("JPEG quality must be an integer in [1,100]")
|
| 324 |
+
if float(params["severity"]) == 0.:
|
| 325 |
+
return clean.clone(), params
|
| 326 |
+
if kind in ("noise", "rain", "snow"):
|
| 327 |
+
if "noise_seed" not in params:
|
| 328 |
+
raise ValueError("Stochastic parameters require noise_seed for repeatable transfer")
|
| 329 |
+
generator = torch.Generator(device=clean.device).manual_seed(int(params["noise_seed"]))
|
| 330 |
+
if kind == "noise":
|
| 331 |
+
field = torch.randn(clean.shape, generator=generator, device=clean.device, dtype=clean.dtype)
|
| 332 |
+
result = clean + field * torch.sqrt(float(params["sigma"]) ** 2 + float(params.get("shot", 0.)) ** 2 * clean.clamp_min(0))
|
| 333 |
+
elif kind == "haze":
|
| 334 |
+
transmission = float(params["transmission"])
|
| 335 |
+
airlight = clean.new_tensor(params["airlight"]).reshape(3, 1, 1)
|
| 336 |
+
result = transmission * clean + (1. - transmission) * airlight
|
| 337 |
+
elif kind == "lowlight":
|
| 338 |
+
result = float(params["gain"]) * clean.clamp_min(0).pow(float(params["gamma"]))
|
| 339 |
+
elif kind == "blur":
|
| 340 |
+
result = _filter(clean, _line_kernel(int(params["length"]), float(params["angle"]), clean.device, clean.dtype))
|
| 341 |
+
elif kind == "rain":
|
| 342 |
+
field = (torch.rand((1, *clean.shape[-2:]), generator=generator, device=clean.device) < float(params["density"])).to(clean.dtype)
|
| 343 |
+
kernel = _line_kernel(int(params["length"]), float(params["angle"]), clean.device, clean.dtype)
|
| 344 |
+
streaks = (_filter(field, kernel) * int(params["length"])).clamp(0, 1)
|
| 345 |
+
result = clean + float(params["opacity"]) * streaks
|
| 346 |
+
elif kind == "snow":
|
| 347 |
+
field = (torch.rand((1, *clean.shape[-2:]), generator=generator, device=clean.device) < float(params["density"])).to(clean.dtype)
|
| 348 |
+
radius = int(params["radius"])
|
| 349 |
+
axis = torch.arange(-radius, radius + 1, device=clean.device, dtype=clean.dtype)
|
| 350 |
+
yy, xx = torch.meshgrid(axis, axis, indexing="ij")
|
| 351 |
+
kernel = torch.exp(-(xx.square() + yy.square()) / max(.5, radius ** 2 / 2.))
|
| 352 |
+
alpha = (float(params["opacity"]) * _filter(field, kernel)).clamp(0, 1)
|
| 353 |
+
result = clean * (1. - alpha) + alpha
|
| 354 |
+
else:
|
| 355 |
+
source = (clean.detach().cpu().clamp(0, 1).permute(1, 2, 0).numpy() * 255.).round().astype(np.uint8)
|
| 356 |
+
buffer = io.BytesIO()
|
| 357 |
+
Image.fromarray(source).save(buffer, format="JPEG", quality=params["quality"], subsampling=2)
|
| 358 |
+
buffer.seek(0)
|
| 359 |
+
with Image.open(buffer) as image:
|
| 360 |
+
array = np.array(image.convert("RGB"), copy=True)
|
| 361 |
+
result = torch.from_numpy(array).permute(2, 0, 1).to(device=clean.device, dtype=clean.dtype) / 255.
|
| 362 |
+
return result.clamp(0., 1.), params
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def synthesize_composition(clean: torch.Tensor, types: Sequence[str],
|
| 366 |
+
parameters: Sequence[Mapping[str, Any]] | None = None,
|
| 367 |
+
seed: int = 0, heldout: bool = False) -> tuple[torch.Tensor, list[dict[str, Any]]]:
|
| 368 |
+
"""Apply types left-to-right: ['noise','haze'] means haze(noise(clean))."""
|
| 369 |
+
if parameters is not None and len(parameters) != len(types):
|
| 370 |
+
raise ValueError("One parameter dictionary is required per composition step")
|
| 371 |
+
image = clean
|
| 372 |
+
used = []
|
| 373 |
+
for index, kind in enumerate(types):
|
| 374 |
+
params = None if parameters is None else parameters[index]
|
| 375 |
+
image, actual = synthesize_degradation(image, kind, params, _seed_from(seed, index, kind), heldout)
|
| 376 |
+
used.append(actual)
|
| 377 |
+
return image, used
|
dataset/phase1_noise_20260906/code/src/data/folder_crops.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Square crops from a flat folder of images (no labels, no pairs).
|
| 2 |
+
|
| 3 |
+
Used for the real-unknown pool (Snow100K synthetic snow) and the extra clean
|
| 4 |
+
pool (Snow100K gt) in Phase-1 v5, and for exposure-diverse identity pairs in
|
| 5 |
+
Phase-2 v8. Deterministic per (seed, epoch, index) so plans replay exactly.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import math
|
| 11 |
+
import random
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
from typing import Dict, Iterator, List, Sequence, Union
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import torch
|
| 17 |
+
from PIL import Image
|
| 18 |
+
from torch.utils.data import DataLoader, Dataset
|
| 19 |
+
|
| 20 |
+
_IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png", ".bmp")
|
| 21 |
+
_LANCZOS = getattr(getattr(Image, "Resampling", Image), "LANCZOS")
|
| 22 |
+
_FLIP = getattr(getattr(Image, "Transpose", Image), "FLIP_LEFT_RIGHT")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def list_image_files(root: Union[str, Path]) -> List[Path]:
|
| 26 |
+
root = Path(root)
|
| 27 |
+
if not root.is_dir():
|
| 28 |
+
raise FileNotFoundError("image folder not found: %s" % root)
|
| 29 |
+
return sorted(p for p in root.rglob("*") if p.suffix.lower() in _IMAGE_SUFFIXES)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _to_tensor(image: Image.Image) -> torch.Tensor:
|
| 33 |
+
array = np.asarray(image, dtype=np.float32) / 255.0
|
| 34 |
+
return torch.from_numpy(array).permute(2, 0, 1).contiguous()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class FolderCropDataset(Dataset):
|
| 38 |
+
"""Random (or centre) ``size`` crops; ``return_full`` adds the aspect-
|
| 39 |
+
squashed whole frame the way Phase2PairDataset does for global context."""
|
| 40 |
+
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
files: Sequence[Union[str, Path]],
|
| 44 |
+
size: int,
|
| 45 |
+
seed: int = 0,
|
| 46 |
+
deterministic: bool = False,
|
| 47 |
+
return_full: bool = False,
|
| 48 |
+
) -> None:
|
| 49 |
+
if not files:
|
| 50 |
+
raise ValueError("FolderCropDataset requires at least one file")
|
| 51 |
+
self.files = [Path(f) for f in files]
|
| 52 |
+
self.size = int(size)
|
| 53 |
+
self.seed = int(seed)
|
| 54 |
+
self.deterministic = bool(deterministic)
|
| 55 |
+
self.return_full = bool(return_full)
|
| 56 |
+
self.epoch = 0
|
| 57 |
+
|
| 58 |
+
def __len__(self) -> int:
|
| 59 |
+
return len(self.files)
|
| 60 |
+
|
| 61 |
+
def _open(self, index: int) -> Image.Image:
|
| 62 |
+
with Image.open(self.files[index]) as handle:
|
| 63 |
+
image = handle.convert("RGB")
|
| 64 |
+
width, height = image.size
|
| 65 |
+
if min(width, height) < self.size:
|
| 66 |
+
scale = self.size / min(width, height)
|
| 67 |
+
image = image.resize(
|
| 68 |
+
(max(self.size, int(math.ceil(width * scale))),
|
| 69 |
+
max(self.size, int(math.ceil(height * scale)))),
|
| 70 |
+
_LANCZOS,
|
| 71 |
+
)
|
| 72 |
+
return image
|
| 73 |
+
|
| 74 |
+
def __getitem__(self, index: int):
|
| 75 |
+
image = self._open(index)
|
| 76 |
+
width, height = image.size
|
| 77 |
+
if self.deterministic:
|
| 78 |
+
left, top, flip = (width - self.size) // 2, (height - self.size) // 2, False
|
| 79 |
+
else:
|
| 80 |
+
rng = random.Random((self.seed * 1000003 + self.epoch * 7919 + index) % (2 ** 63 - 1))
|
| 81 |
+
left = rng.randrange(width - self.size + 1)
|
| 82 |
+
top = rng.randrange(height - self.size + 1)
|
| 83 |
+
flip = bool(rng.getrandbits(1))
|
| 84 |
+
crop = image.crop((left, top, left + self.size, top + self.size))
|
| 85 |
+
if flip:
|
| 86 |
+
crop = crop.transpose(_FLIP)
|
| 87 |
+
if not self.return_full:
|
| 88 |
+
return _to_tensor(crop)
|
| 89 |
+
full = image.resize((self.size, self.size), _LANCZOS)
|
| 90 |
+
if flip:
|
| 91 |
+
full = full.transpose(_FLIP)
|
| 92 |
+
return {"crop": _to_tensor(crop), "full": _to_tensor(full)}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def infinite_batches(loader: DataLoader) -> Iterator:
|
| 96 |
+
"""Cycle a loader forever, bumping ``dataset.epoch`` so crops re-randomise."""
|
| 97 |
+
epoch = 0
|
| 98 |
+
while True:
|
| 99 |
+
dataset = getattr(loader, "dataset", None)
|
| 100 |
+
if dataset is not None and hasattr(dataset, "epoch"):
|
| 101 |
+
dataset.epoch = epoch
|
| 102 |
+
for batch in loader:
|
| 103 |
+
yield batch
|
| 104 |
+
epoch += 1
|
dataset/phase1_noise_20260906/code/src/data/phase1_v2.py
ADDED
|
@@ -0,0 +1,928 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Deterministic data generation for the corrected Phase 1 pilot.
|
| 2 |
+
|
| 3 |
+
The module separates source splitting, crop selection, and degradation sampling.
|
| 4 |
+
Every decision is derived from stable SHA256 keys, so manifests and generated
|
| 5 |
+
samples can be reconstructed without relying on process-global random state.
|
| 6 |
+
|
| 7 |
+
Combo names use underscores in place of the composition symbol. Regardless of
|
| 8 |
+
name, operators are always applied in camera order: blur, low-light, noise,
|
| 9 |
+
then JPEG.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import hashlib
|
| 15 |
+
import io
|
| 16 |
+
from collections.abc import Iterable, Mapping, Sequence
|
| 17 |
+
from dataclasses import asdict, dataclass
|
| 18 |
+
from functools import cache
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any, Dict, List, Literal, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn.functional as F
|
| 25 |
+
from PIL import Image
|
| 26 |
+
from torch.utils.data import Dataset
|
| 27 |
+
|
| 28 |
+
Mode = Literal["support", "validation_gap", "locked"]
|
| 29 |
+
|
| 30 |
+
# Canonical order for every degradation vector, classifier head, cache, and
|
| 31 |
+
# metric. Keep the legacy aliases because existing callers import them.
|
| 32 |
+
TYPE_ORDER: Tuple[str, ...] = ("blur", "lowlight", "noise", "jpeg")
|
| 33 |
+
DEGRADATIONS: Tuple[str, ...] = TYPE_ORDER
|
| 34 |
+
PHYSICAL_ORDER: Tuple[str, ...] = TYPE_ORDER
|
| 35 |
+
|
| 36 |
+
# N_B means the set {noise, blur}; the tuple records actual application order.
|
| 37 |
+
TRAIN_COMBINATIONS: Dict[str, Tuple[str, ...]] = {
|
| 38 |
+
"N_B": ("blur", "noise"),
|
| 39 |
+
"N_L": ("lowlight", "noise"),
|
| 40 |
+
"B_J": ("blur", "jpeg"),
|
| 41 |
+
"L_J": ("lowlight", "jpeg"),
|
| 42 |
+
}
|
| 43 |
+
UNSEEN_COMBINATIONS: Dict[str, Tuple[str, ...]] = {
|
| 44 |
+
"N_J": ("noise", "jpeg"),
|
| 45 |
+
"B_L": ("blur", "lowlight"),
|
| 46 |
+
"N_B_L": ("blur", "lowlight", "noise"),
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
# Values are physical operator parameters, not normalized labels.
|
| 50 |
+
SEVERITY_RANGES: Dict[str, Dict[str, Any]] = {
|
| 51 |
+
"noise": {
|
| 52 |
+
"train": (10.0, 50.0),
|
| 53 |
+
"gap": (25.0, 35.0),
|
| 54 |
+
"extrap": 70.0,
|
| 55 |
+
"discrete": False,
|
| 56 |
+
},
|
| 57 |
+
"blur": {
|
| 58 |
+
"train": (0.8, 2.4),
|
| 59 |
+
"gap": (1.4, 1.8),
|
| 60 |
+
"extrap": 3.0,
|
| 61 |
+
"discrete": False,
|
| 62 |
+
},
|
| 63 |
+
"lowlight": {
|
| 64 |
+
"train": (1.5, 3.0),
|
| 65 |
+
"gap": (2.0, 2.4),
|
| 66 |
+
"extrap": 3.5,
|
| 67 |
+
"discrete": False,
|
| 68 |
+
},
|
| 69 |
+
"jpeg": {
|
| 70 |
+
"train": (10, 50),
|
| 71 |
+
"gap": (25, 35),
|
| 72 |
+
"extrap": 5,
|
| 73 |
+
"discrete": True,
|
| 74 |
+
},
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@dataclass(frozen=True)
|
| 79 |
+
class CropRecord:
|
| 80 |
+
"""A serializable, deterministic crop from one clean source image."""
|
| 81 |
+
|
| 82 |
+
source_dataset: str
|
| 83 |
+
source_id: str
|
| 84 |
+
source_path: str
|
| 85 |
+
source_sha256: str
|
| 86 |
+
split: Literal["train", "val", "test"]
|
| 87 |
+
crop_index: int
|
| 88 |
+
top: int
|
| 89 |
+
left: int
|
| 90 |
+
size: int = 256
|
| 91 |
+
|
| 92 |
+
@property
|
| 93 |
+
def crop_id(self) -> str:
|
| 94 |
+
"""Return the stable identifier used to join crops and sample specs."""
|
| 95 |
+
|
| 96 |
+
return f"{self.split}:{self.source_id}:{self.crop_index}"
|
| 97 |
+
|
| 98 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 99 |
+
"""Return a JSON-compatible dictionary."""
|
| 100 |
+
|
| 101 |
+
return asdict(self)
|
| 102 |
+
|
| 103 |
+
@classmethod
|
| 104 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "CropRecord":
|
| 105 |
+
"""Reconstruct a crop record from :meth:`to_dict` output."""
|
| 106 |
+
|
| 107 |
+
return cls(**dict(value))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@dataclass(frozen=True)
|
| 111 |
+
class SampleSpec:
|
| 112 |
+
"""Serializable instructions for generating one degraded sample.
|
| 113 |
+
|
| 114 |
+
``components``, ``physical_values``, and ``severities`` share the same
|
| 115 |
+
order. For compositions, ``component_indices`` points to single-degradation
|
| 116 |
+
specs with the same crop and physical parameter.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
sample_index: int
|
| 120 |
+
crop_id: str
|
| 121 |
+
source_id: str
|
| 122 |
+
split: Literal["train", "val", "test"]
|
| 123 |
+
mode: Mode
|
| 124 |
+
degradation: str
|
| 125 |
+
regime: str
|
| 126 |
+
components: Tuple[str, ...]
|
| 127 |
+
physical_values: Tuple[float, ...]
|
| 128 |
+
severities: Tuple[float, ...]
|
| 129 |
+
component_indices: Tuple[int, ...] = ()
|
| 130 |
+
noise_seed: Optional[int] = None
|
| 131 |
+
|
| 132 |
+
@property
|
| 133 |
+
def is_composition(self) -> bool:
|
| 134 |
+
"""Whether this sample contains more than one degradation."""
|
| 135 |
+
|
| 136 |
+
return len(self.components) > 1
|
| 137 |
+
|
| 138 |
+
def to_dict(self) -> Dict[str, Any]:
|
| 139 |
+
"""Return a JSON-compatible dictionary."""
|
| 140 |
+
|
| 141 |
+
value = asdict(self)
|
| 142 |
+
value["components"] = list(self.components)
|
| 143 |
+
value["physical_values"] = list(self.physical_values)
|
| 144 |
+
value["severities"] = list(self.severities)
|
| 145 |
+
value["component_indices"] = list(self.component_indices)
|
| 146 |
+
return value
|
| 147 |
+
|
| 148 |
+
@classmethod
|
| 149 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "SampleSpec":
|
| 150 |
+
"""Reconstruct a sample spec from :meth:`to_dict` output."""
|
| 151 |
+
|
| 152 |
+
data = dict(value)
|
| 153 |
+
for name in (
|
| 154 |
+
"components",
|
| 155 |
+
"physical_values",
|
| 156 |
+
"severities",
|
| 157 |
+
"component_indices",
|
| 158 |
+
):
|
| 159 |
+
data[name] = tuple(data.get(name, ()))
|
| 160 |
+
return cls(**data)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def _digest_int(key: str) -> int:
|
| 164 |
+
return int.from_bytes(hashlib.sha256(key.encode("utf-8")).digest()[:8], "big")
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _unit_interval(key: str) -> float:
|
| 168 |
+
# Midpoints avoid ever sampling an inclusive gap boundary.
|
| 169 |
+
return (_digest_int(key) + 0.5) / float(2**64)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def _find_div2k_dir(data_root: Path, directory_name: str) -> Path:
|
| 173 |
+
candidates = (
|
| 174 |
+
data_root / directory_name,
|
| 175 |
+
data_root / "div2k" / directory_name,
|
| 176 |
+
)
|
| 177 |
+
for candidate in candidates:
|
| 178 |
+
if candidate.is_dir():
|
| 179 |
+
return candidate
|
| 180 |
+
raise FileNotFoundError(
|
| 181 |
+
f"Could not find {directory_name} under {data_root} or {data_root / 'div2k'}"
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _image_files(directory: Path) -> List[Path]:
|
| 186 |
+
suffixes = {".png", ".jpg", ".jpeg"}
|
| 187 |
+
files = [path for path in directory.iterdir() if path.suffix.lower() in suffixes]
|
| 188 |
+
if not files:
|
| 189 |
+
raise ValueError(f"No images found in {directory}")
|
| 190 |
+
return files
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _sha256_source_order(paths: Iterable[Path]) -> List[Path]:
|
| 194 |
+
return sorted(
|
| 195 |
+
paths,
|
| 196 |
+
key=lambda path: (hashlib.sha256(path.name.encode("utf-8")).digest(), path.name),
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _crop_records(
|
| 201 |
+
paths: Sequence[Path],
|
| 202 |
+
split: Literal["train", "val", "test"],
|
| 203 |
+
crop_size: int,
|
| 204 |
+
crops_per_source: int,
|
| 205 |
+
seed: int,
|
| 206 |
+
source_hashes: Mapping[Path, str],
|
| 207 |
+
) -> List[CropRecord]:
|
| 208 |
+
records: List[CropRecord] = []
|
| 209 |
+
for path in paths:
|
| 210 |
+
with Image.open(path) as image:
|
| 211 |
+
width, height = image.size
|
| 212 |
+
if width < crop_size or height < crop_size:
|
| 213 |
+
raise ValueError(
|
| 214 |
+
f"Source {path} is {width}x{height}, smaller than {crop_size}x{crop_size}"
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
source_dataset = "DIV2K"
|
| 218 |
+
source_id = f"{source_dataset}:{path.stem}"
|
| 219 |
+
for crop_index in range(crops_per_source):
|
| 220 |
+
prefix = f"{seed}:{path.name}:{crop_index}"
|
| 221 |
+
top = _digest_int(f"{prefix}:top") % (height - crop_size + 1)
|
| 222 |
+
left = _digest_int(f"{prefix}:left") % (width - crop_size + 1)
|
| 223 |
+
records.append(
|
| 224 |
+
CropRecord(
|
| 225 |
+
source_dataset=source_dataset,
|
| 226 |
+
source_id=source_id,
|
| 227 |
+
source_path=str(path.resolve()),
|
| 228 |
+
source_sha256=source_hashes[path],
|
| 229 |
+
split=split,
|
| 230 |
+
crop_index=crop_index,
|
| 231 |
+
top=top,
|
| 232 |
+
left=left,
|
| 233 |
+
size=crop_size,
|
| 234 |
+
)
|
| 235 |
+
)
|
| 236 |
+
return records
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _sha256_file(path: Path) -> str:
|
| 240 |
+
digest = hashlib.sha256()
|
| 241 |
+
with path.open("rb") as handle:
|
| 242 |
+
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
|
| 243 |
+
digest.update(chunk)
|
| 244 |
+
return digest.hexdigest()
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _source_hashes(paths: Sequence[Path]) -> Dict[Path, str]:
|
| 248 |
+
"""Hash each unique source file exactly once for manifest provenance."""
|
| 249 |
+
|
| 250 |
+
return {path: _sha256_file(path) for path in dict.fromkeys(paths)}
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def _reject_cross_split_duplicate_bytes(
|
| 254 |
+
split_paths: Mapping[str, Sequence[Path]], source_hashes: Mapping[Path, str]
|
| 255 |
+
) -> None:
|
| 256 |
+
owners: Dict[str, Tuple[str, Path]] = {}
|
| 257 |
+
for split, paths in split_paths.items():
|
| 258 |
+
for path in paths:
|
| 259 |
+
digest = source_hashes[path]
|
| 260 |
+
previous = owners.get(digest)
|
| 261 |
+
if previous is not None and previous[0] != split:
|
| 262 |
+
raise ValueError(
|
| 263 |
+
"Duplicate source bytes cross data splits: "
|
| 264 |
+
f"{previous[1]} ({previous[0]}) and {path} ({split})"
|
| 265 |
+
)
|
| 266 |
+
owners.setdefault(digest, (split, path))
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
def build_crop_manifest(
|
| 270 |
+
data_root: str | Path,
|
| 271 |
+
*,
|
| 272 |
+
train_cap: int = 720,
|
| 273 |
+
val_cap: int = 80,
|
| 274 |
+
test_cap: Optional[int] = None,
|
| 275 |
+
crop_size: int = 256,
|
| 276 |
+
crops_per_source: int = 4,
|
| 277 |
+
seed: int = 0,
|
| 278 |
+
include_locked: bool = True,
|
| 279 |
+
) -> List[CropRecord]:
|
| 280 |
+
"""Build the source-first DIV2K train/val/test crop manifest.
|
| 281 |
+
|
| 282 |
+
Sources in ``DIV2K_train_HR`` are ordered by SHA256 of their file names.
|
| 283 |
+
The first ``train_cap`` sources become train and the next ``val_cap`` become
|
| 284 |
+
validation. Every source in ``DIV2K_valid_HR`` is locked test data unless
|
| 285 |
+
``test_cap`` is set for a smoke run. The defaults implement the 720/80
|
| 286 |
+
support split and lock all 100 official validation images.
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
root = Path(data_root)
|
| 290 |
+
if train_cap < 0 or val_cap < 0:
|
| 291 |
+
raise ValueError("train_cap and val_cap must be non-negative")
|
| 292 |
+
if test_cap is not None and test_cap < 0:
|
| 293 |
+
raise ValueError("test_cap must be non-negative or None")
|
| 294 |
+
if crop_size <= 0 or crops_per_source <= 0:
|
| 295 |
+
raise ValueError("crop_size and crops_per_source must be positive")
|
| 296 |
+
|
| 297 |
+
support_dir = _find_div2k_dir(root, "DIV2K_train_HR")
|
| 298 |
+
support_sources = _sha256_source_order(_image_files(support_dir))
|
| 299 |
+
required = train_cap + val_cap
|
| 300 |
+
if len(support_sources) < required:
|
| 301 |
+
raise ValueError(
|
| 302 |
+
f"Need {required} DIV2K train sources, found {len(support_sources)}; "
|
| 303 |
+
"set smaller caps for a smoke run"
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
train_sources = support_sources[:train_cap]
|
| 307 |
+
val_sources = support_sources[train_cap:required]
|
| 308 |
+
locked_sources: List[Path] = []
|
| 309 |
+
if include_locked:
|
| 310 |
+
locked_dir = _find_div2k_dir(root, "DIV2K_valid_HR")
|
| 311 |
+
locked_sources = _sha256_source_order(_image_files(locked_dir))
|
| 312 |
+
if test_cap is not None:
|
| 313 |
+
locked_sources = locked_sources[:test_cap]
|
| 314 |
+
|
| 315 |
+
hashes = _source_hashes([*train_sources, *val_sources, *locked_sources])
|
| 316 |
+
_reject_cross_split_duplicate_bytes(
|
| 317 |
+
{"train": train_sources, "val": val_sources, "test": locked_sources}, hashes
|
| 318 |
+
)
|
| 319 |
+
train_ids = {path.stem for path in train_sources}
|
| 320 |
+
val_ids = {path.stem for path in val_sources}
|
| 321 |
+
test_ids = {path.stem for path in locked_sources}
|
| 322 |
+
if not train_ids.isdisjoint(val_ids):
|
| 323 |
+
raise ValueError("train and validation source IDs overlap")
|
| 324 |
+
if not train_ids.isdisjoint(test_ids):
|
| 325 |
+
raise ValueError("train and locked source IDs overlap")
|
| 326 |
+
if not val_ids.isdisjoint(test_ids):
|
| 327 |
+
raise ValueError("validation and locked source IDs overlap")
|
| 328 |
+
|
| 329 |
+
manifest = _crop_records(
|
| 330 |
+
train_sources, "train", crop_size, crops_per_source, seed, hashes
|
| 331 |
+
)
|
| 332 |
+
manifest += _crop_records(
|
| 333 |
+
val_sources, "val", crop_size, crops_per_source, seed, hashes
|
| 334 |
+
)
|
| 335 |
+
manifest += _crop_records(
|
| 336 |
+
locked_sources, "test", crop_size, crops_per_source, seed, hashes
|
| 337 |
+
)
|
| 338 |
+
expected = (len(train_sources) + len(val_sources) + len(locked_sources)) * crops_per_source
|
| 339 |
+
if len(manifest) != expected:
|
| 340 |
+
raise RuntimeError(
|
| 341 |
+
f"Crop manifest count mismatch: expected {expected}, got {len(manifest)}"
|
| 342 |
+
)
|
| 343 |
+
return manifest
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def build_locked_crop_manifest(
|
| 347 |
+
data_root: str | Path,
|
| 348 |
+
*,
|
| 349 |
+
test_cap: Optional[int] = None,
|
| 350 |
+
crop_size: int = 256,
|
| 351 |
+
crops_per_source: int = 4,
|
| 352 |
+
seed: int = 0,
|
| 353 |
+
) -> List[CropRecord]:
|
| 354 |
+
"""Build only the locked DIV2K validation manifest.
|
| 355 |
+
|
| 356 |
+
This separate entry point lets a train-only invocation avoid listing,
|
| 357 |
+
loading, or hashing any locked source bytes.
|
| 358 |
+
"""
|
| 359 |
+
|
| 360 |
+
if test_cap is not None and test_cap < 0:
|
| 361 |
+
raise ValueError("test_cap must be non-negative or None")
|
| 362 |
+
if crop_size <= 0 or crops_per_source <= 0:
|
| 363 |
+
raise ValueError("crop_size and crops_per_source must be positive")
|
| 364 |
+
locked_dir = _find_div2k_dir(Path(data_root), "DIV2K_valid_HR")
|
| 365 |
+
sources = _sha256_source_order(_image_files(locked_dir))
|
| 366 |
+
if test_cap is not None:
|
| 367 |
+
sources = sources[:test_cap]
|
| 368 |
+
hashes = _source_hashes(sources)
|
| 369 |
+
return _crop_records(sources, "test", crop_size, crops_per_source, seed, hashes)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@cache
|
| 373 |
+
def _verify_source_stat(
|
| 374 |
+
source_path: str,
|
| 375 |
+
expected_sha256: str,
|
| 376 |
+
stat_key: Tuple[int, int, int, int, int],
|
| 377 |
+
) -> None:
|
| 378 |
+
del stat_key
|
| 379 |
+
actual = _sha256_file(Path(source_path))
|
| 380 |
+
if actual != expected_sha256:
|
| 381 |
+
raise RuntimeError(
|
| 382 |
+
f"Source SHA256 mismatch for {source_path}: "
|
| 383 |
+
f"expected {expected_sha256}, got {actual}"
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
def _verify_source(record: CropRecord) -> None:
|
| 388 |
+
path = Path(record.source_path)
|
| 389 |
+
stat = path.stat()
|
| 390 |
+
stat_key = (
|
| 391 |
+
stat.st_dev,
|
| 392 |
+
stat.st_ino,
|
| 393 |
+
stat.st_size,
|
| 394 |
+
stat.st_mtime_ns,
|
| 395 |
+
stat.st_ctime_ns,
|
| 396 |
+
)
|
| 397 |
+
_verify_source_stat(str(path), record.source_sha256, stat_key)
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def validate_source_integrity(records: Sequence[CropRecord]) -> None:
|
| 401 |
+
"""Verify each unique source once before materializing a feature cache."""
|
| 402 |
+
|
| 403 |
+
expected_by_path: Dict[str, str] = {}
|
| 404 |
+
for record in records:
|
| 405 |
+
previous = expected_by_path.setdefault(record.source_path, record.source_sha256)
|
| 406 |
+
if previous != record.source_sha256:
|
| 407 |
+
raise ValueError(
|
| 408 |
+
f"Manifest records disagree on SHA256 for {record.source_path}"
|
| 409 |
+
)
|
| 410 |
+
for record in records:
|
| 411 |
+
if expected_by_path.pop(record.source_path, None) is not None:
|
| 412 |
+
_verify_source(record)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def load_clean_patch(record: CropRecord) -> torch.Tensor:
|
| 416 |
+
"""Load a SHA-verified manifest crop as an RGB CHW tensor in [0, 1]."""
|
| 417 |
+
|
| 418 |
+
_verify_source(record)
|
| 419 |
+
with Image.open(record.source_path) as image:
|
| 420 |
+
image = image.convert("RGB")
|
| 421 |
+
patch = image.crop(
|
| 422 |
+
(
|
| 423 |
+
record.left,
|
| 424 |
+
record.top,
|
| 425 |
+
record.left + record.size,
|
| 426 |
+
record.top + record.size,
|
| 427 |
+
)
|
| 428 |
+
)
|
| 429 |
+
array = np.asarray(patch, dtype=np.uint8).copy()
|
| 430 |
+
return torch.from_numpy(array).permute(2, 0, 1).float().div_(255.0)
|
| 431 |
+
|
| 432 |
+
|
| 433 |
+
def normalize_severity(degradation: str, physical_value: float) -> float:
|
| 434 |
+
"""Map a physical parameter to a monotonic normalized severity label."""
|
| 435 |
+
|
| 436 |
+
value = float(physical_value)
|
| 437 |
+
if degradation == "noise":
|
| 438 |
+
return value / 70.0
|
| 439 |
+
if degradation == "blur":
|
| 440 |
+
return value / 3.0
|
| 441 |
+
if degradation == "lowlight":
|
| 442 |
+
return (value - 1.0) / (3.5 - 1.0)
|
| 443 |
+
if degradation == "jpeg":
|
| 444 |
+
# Compression becomes physically stronger as quality falls.
|
| 445 |
+
return (100.0 - value) / 100.0
|
| 446 |
+
raise ValueError(f"Unknown degradation: {degradation}")
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def _sample_train_value(degradation: str, key: str, branch: int) -> float:
|
| 450 |
+
config = SEVERITY_RANGES[degradation]
|
| 451 |
+
train_min, train_max = config["train"]
|
| 452 |
+
gap_start, gap_end = config["gap"]
|
| 453 |
+
if config["discrete"]:
|
| 454 |
+
choices = (
|
| 455 |
+
list(range(int(train_min), int(gap_start)))
|
| 456 |
+
if branch == 0
|
| 457 |
+
else list(range(int(gap_end) + 1, int(train_max) + 1))
|
| 458 |
+
)
|
| 459 |
+
return float(choices[_digest_int(key) % len(choices)])
|
| 460 |
+
|
| 461 |
+
low, high = (train_min, gap_start) if branch == 0 else (gap_end, train_max)
|
| 462 |
+
return float(low + _unit_interval(key) * (high - low))
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def _noise_seed(key: str) -> int:
|
| 466 |
+
return _digest_int(f"noise:{key}") % (2**63 - 1)
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _gap_values(degradation: str, points: int) -> Tuple[float, ...]:
|
| 470 |
+
if points <= 0:
|
| 471 |
+
raise ValueError("gap_points must be positive")
|
| 472 |
+
gap_start, gap_end = SEVERITY_RANGES[degradation]["gap"]
|
| 473 |
+
if points == 1:
|
| 474 |
+
return ((float(gap_start) + float(gap_end)) / 2.0,)
|
| 475 |
+
if SEVERITY_RANGES[degradation]["discrete"]:
|
| 476 |
+
count = int(gap_end) - int(gap_start) + 1
|
| 477 |
+
if points > count:
|
| 478 |
+
raise ValueError(f"gap_points cannot exceed {count} for JPEG")
|
| 479 |
+
offsets = [round(index * (count - 1) / (points - 1)) for index in range(points)]
|
| 480 |
+
return tuple(float(int(gap_start) + offset) for offset in offsets)
|
| 481 |
+
step = (float(gap_end) - float(gap_start)) / (points - 1)
|
| 482 |
+
return tuple(float(gap_start) + index * step for index in range(points))
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _ordered_crops(crop_manifest: Sequence[CropRecord], mode: Mode) -> List[CropRecord]:
|
| 486 |
+
wanted = {
|
| 487 |
+
"support": {"train", "val"},
|
| 488 |
+
"validation_gap": {"val"},
|
| 489 |
+
"locked": {"test"},
|
| 490 |
+
}[mode]
|
| 491 |
+
selected = [record for record in crop_manifest if record.split in wanted]
|
| 492 |
+
split_rank = {"train": 0, "val": 1, "test": 2}
|
| 493 |
+
return sorted(
|
| 494 |
+
selected,
|
| 495 |
+
key=lambda record: (
|
| 496 |
+
split_rank[record.split],
|
| 497 |
+
record.source_id,
|
| 498 |
+
record.crop_index,
|
| 499 |
+
record.source_path,
|
| 500 |
+
),
|
| 501 |
+
)
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
def _append_single(
|
| 505 |
+
specs: List[SampleSpec],
|
| 506 |
+
record: CropRecord,
|
| 507 |
+
mode: Mode,
|
| 508 |
+
degradation: str,
|
| 509 |
+
physical_value: float,
|
| 510 |
+
regime: str,
|
| 511 |
+
key: str,
|
| 512 |
+
) -> int:
|
| 513 |
+
index = len(specs)
|
| 514 |
+
specs.append(
|
| 515 |
+
SampleSpec(
|
| 516 |
+
sample_index=index,
|
| 517 |
+
crop_id=record.crop_id,
|
| 518 |
+
source_id=record.source_id,
|
| 519 |
+
split=record.split,
|
| 520 |
+
mode=mode,
|
| 521 |
+
degradation=degradation,
|
| 522 |
+
regime=regime,
|
| 523 |
+
components=(degradation,),
|
| 524 |
+
physical_values=(float(physical_value),),
|
| 525 |
+
severities=(normalize_severity(degradation, physical_value),),
|
| 526 |
+
noise_seed=_noise_seed(key) if degradation == "noise" else None,
|
| 527 |
+
)
|
| 528 |
+
)
|
| 529 |
+
return index
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
def _append_combo(
|
| 533 |
+
specs: List[SampleSpec],
|
| 534 |
+
record: CropRecord,
|
| 535 |
+
mode: Mode,
|
| 536 |
+
combo_name: str,
|
| 537 |
+
components: Tuple[str, ...],
|
| 538 |
+
component_indices: Tuple[int, ...],
|
| 539 |
+
regime: str,
|
| 540 |
+
) -> None:
|
| 541 |
+
referenced = [specs[index] for index in component_indices]
|
| 542 |
+
values = tuple(spec.physical_values[0] for spec in referenced)
|
| 543 |
+
severities = tuple(spec.severities[0] for spec in referenced)
|
| 544 |
+
noise_specs = [spec for spec in referenced if spec.components == ("noise",)]
|
| 545 |
+
specs.append(
|
| 546 |
+
SampleSpec(
|
| 547 |
+
sample_index=len(specs),
|
| 548 |
+
crop_id=record.crop_id,
|
| 549 |
+
source_id=record.source_id,
|
| 550 |
+
split=record.split,
|
| 551 |
+
mode=mode,
|
| 552 |
+
degradation=combo_name,
|
| 553 |
+
regime=regime,
|
| 554 |
+
components=components,
|
| 555 |
+
physical_values=values,
|
| 556 |
+
severities=severities,
|
| 557 |
+
component_indices=component_indices,
|
| 558 |
+
noise_seed=noise_specs[0].noise_seed if noise_specs else None,
|
| 559 |
+
)
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def _validate_sample_specs(specs: Sequence[SampleSpec]) -> None:
|
| 564 |
+
order = {name: index for index, name in enumerate(PHYSICAL_ORDER)}
|
| 565 |
+
for position, spec in enumerate(specs):
|
| 566 |
+
if spec.sample_index != position:
|
| 567 |
+
raise ValueError("Sample indices must match list positions")
|
| 568 |
+
if "rain" in spec.components or spec.degradation == "rain":
|
| 569 |
+
raise ValueError("Rain is forbidden in Phase 1 sample specs")
|
| 570 |
+
if not (
|
| 571 |
+
len(spec.components) == len(spec.physical_values) == len(spec.severities)
|
| 572 |
+
):
|
| 573 |
+
raise ValueError("Sample components, physical values, and severities misalign")
|
| 574 |
+
if any(component not in order for component in spec.components):
|
| 575 |
+
raise ValueError(f"Unknown sample components: {spec.components}")
|
| 576 |
+
if tuple(sorted(spec.components, key=order.__getitem__)) != spec.components:
|
| 577 |
+
raise ValueError("Sample components are not in physical application order")
|
| 578 |
+
if spec.is_composition:
|
| 579 |
+
if len(spec.component_indices) != len(spec.components):
|
| 580 |
+
raise ValueError("Composition references do not align with components")
|
| 581 |
+
for component, value, reference_index in zip(
|
| 582 |
+
spec.components, spec.physical_values, spec.component_indices
|
| 583 |
+
):
|
| 584 |
+
if not 0 <= reference_index < position:
|
| 585 |
+
raise ValueError("Composition reference must point to an earlier sample")
|
| 586 |
+
reference = specs[reference_index]
|
| 587 |
+
if reference.is_composition:
|
| 588 |
+
raise ValueError("Composition reference must point to a single")
|
| 589 |
+
if reference.crop_id != spec.crop_id:
|
| 590 |
+
raise ValueError("Composition reference crosses crop boundaries")
|
| 591 |
+
if reference.components != (component,):
|
| 592 |
+
raise ValueError("Composition reference has the wrong component type")
|
| 593 |
+
if reference.physical_values != (value,):
|
| 594 |
+
raise ValueError("Composition reference has the wrong physical value")
|
| 595 |
+
if "noise" in spec.components:
|
| 596 |
+
noise_position = spec.components.index("noise")
|
| 597 |
+
noise_reference = specs[spec.component_indices[noise_position]]
|
| 598 |
+
if spec.noise_seed != noise_reference.noise_seed:
|
| 599 |
+
raise ValueError("Composition noise seed differs from its single")
|
| 600 |
+
else:
|
| 601 |
+
if spec.component_indices:
|
| 602 |
+
raise ValueError("Single-degradation spec cannot have component references")
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def build_sample_specs(
|
| 606 |
+
crop_manifest: Sequence[CropRecord],
|
| 607 |
+
mode: Mode = "support",
|
| 608 |
+
*,
|
| 609 |
+
seed: int = 0,
|
| 610 |
+
gap_points: int = 3,
|
| 611 |
+
) -> List[SampleSpec]:
|
| 612 |
+
"""Create deterministic support, validation-gap, or locked instructions.
|
| 613 |
+
|
| 614 |
+
Support mode emits two gap-excluding singles and the four seen train
|
| 615 |
+
combinations. Validation-gap and locked modes emit identical gap+extrap
|
| 616 |
+
singles followed by four seen and three unseen combinations, but consume
|
| 617 |
+
only val and test records respectively.
|
| 618 |
+
"""
|
| 619 |
+
|
| 620 |
+
if mode not in ("support", "validation_gap", "locked"):
|
| 621 |
+
raise ValueError("mode must be 'support', 'validation_gap', or 'locked'")
|
| 622 |
+
records = _ordered_crops(crop_manifest, mode)
|
| 623 |
+
specs: List[SampleSpec] = []
|
| 624 |
+
|
| 625 |
+
for record in records:
|
| 626 |
+
key_prefix = f"{seed}:{record.crop_id}"
|
| 627 |
+
if mode == "support":
|
| 628 |
+
references: Dict[str, List[int]] = {name: [] for name in DEGRADATIONS}
|
| 629 |
+
for degradation in DEGRADATIONS:
|
| 630 |
+
for branch in range(2):
|
| 631 |
+
key = f"{key_prefix}:{degradation}:{branch}"
|
| 632 |
+
value = _sample_train_value(degradation, key, branch)
|
| 633 |
+
references[degradation].append(
|
| 634 |
+
_append_single(
|
| 635 |
+
specs,
|
| 636 |
+
record,
|
| 637 |
+
mode,
|
| 638 |
+
degradation,
|
| 639 |
+
value,
|
| 640 |
+
"train",
|
| 641 |
+
key,
|
| 642 |
+
)
|
| 643 |
+
)
|
| 644 |
+
|
| 645 |
+
for combo_name, components in TRAIN_COMBINATIONS.items():
|
| 646 |
+
component_indices = tuple(
|
| 647 |
+
references[name][
|
| 648 |
+
_digest_int(
|
| 649 |
+
f"{key_prefix}:combo:{combo_name}:component:{name}:branch"
|
| 650 |
+
)
|
| 651 |
+
% 2
|
| 652 |
+
]
|
| 653 |
+
for name in components
|
| 654 |
+
)
|
| 655 |
+
_append_combo(
|
| 656 |
+
specs,
|
| 657 |
+
record,
|
| 658 |
+
mode,
|
| 659 |
+
combo_name,
|
| 660 |
+
components,
|
| 661 |
+
component_indices,
|
| 662 |
+
"seen_combo",
|
| 663 |
+
)
|
| 664 |
+
else:
|
| 665 |
+
gap_references: Dict[str, List[int]] = {name: [] for name in DEGRADATIONS}
|
| 666 |
+
for degradation in DEGRADATIONS:
|
| 667 |
+
for gap_number, value in enumerate(_gap_values(degradation, gap_points)):
|
| 668 |
+
key = f"{key_prefix}:{degradation}:gap:{gap_number}"
|
| 669 |
+
gap_references[degradation].append(
|
| 670 |
+
_append_single(
|
| 671 |
+
specs,
|
| 672 |
+
record,
|
| 673 |
+
mode,
|
| 674 |
+
degradation,
|
| 675 |
+
value,
|
| 676 |
+
"gap",
|
| 677 |
+
key,
|
| 678 |
+
)
|
| 679 |
+
)
|
| 680 |
+
extrap_value = float(SEVERITY_RANGES[degradation]["extrap"])
|
| 681 |
+
_append_single(
|
| 682 |
+
specs,
|
| 683 |
+
record,
|
| 684 |
+
mode,
|
| 685 |
+
degradation,
|
| 686 |
+
extrap_value,
|
| 687 |
+
"extrap",
|
| 688 |
+
f"{key_prefix}:{degradation}:extrap",
|
| 689 |
+
)
|
| 690 |
+
|
| 691 |
+
midpoint = gap_points // 2
|
| 692 |
+
for combo_name, components in TRAIN_COMBINATIONS.items():
|
| 693 |
+
component_indices = tuple(
|
| 694 |
+
gap_references[name][midpoint] for name in components
|
| 695 |
+
)
|
| 696 |
+
_append_combo(
|
| 697 |
+
specs,
|
| 698 |
+
record,
|
| 699 |
+
mode,
|
| 700 |
+
combo_name,
|
| 701 |
+
components,
|
| 702 |
+
component_indices,
|
| 703 |
+
"seen_combo",
|
| 704 |
+
)
|
| 705 |
+
for combo_name, components in UNSEEN_COMBINATIONS.items():
|
| 706 |
+
component_indices = tuple(
|
| 707 |
+
gap_references[name][midpoint] for name in components
|
| 708 |
+
)
|
| 709 |
+
_append_combo(
|
| 710 |
+
specs,
|
| 711 |
+
record,
|
| 712 |
+
mode,
|
| 713 |
+
combo_name,
|
| 714 |
+
components,
|
| 715 |
+
component_indices,
|
| 716 |
+
"unseen_combo",
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
expected_per_patch = 12 if mode == "support" else 4 * (gap_points + 1) + 7
|
| 720 |
+
expected = len(records) * expected_per_patch
|
| 721 |
+
if len(specs) != expected:
|
| 722 |
+
raise RuntimeError(
|
| 723 |
+
f"Sample-spec count mismatch: expected {expected}, got {len(specs)}"
|
| 724 |
+
)
|
| 725 |
+
_validate_sample_specs(specs)
|
| 726 |
+
return specs
|
| 727 |
+
|
| 728 |
+
|
| 729 |
+
def _validate_image(image: torch.Tensor) -> None:
|
| 730 |
+
if image.ndim != 3 or image.shape[0] != 3:
|
| 731 |
+
raise ValueError("Expected an RGB CHW tensor")
|
| 732 |
+
if not image.is_floating_point():
|
| 733 |
+
raise TypeError("Expected a floating-point image tensor")
|
| 734 |
+
|
| 735 |
+
|
| 736 |
+
def _gaussian_blur(image: torch.Tensor, sigma: float) -> torch.Tensor:
|
| 737 |
+
if sigma <= 0:
|
| 738 |
+
raise ValueError("Gaussian blur sigma must be positive")
|
| 739 |
+
work = image.float()
|
| 740 |
+
radius = max(1, int(np.ceil(3.0 * sigma)))
|
| 741 |
+
coordinates = torch.arange(-radius, radius + 1, device=work.device, dtype=work.dtype)
|
| 742 |
+
kernel_1d = torch.exp(-(coordinates**2) / (2.0 * sigma**2))
|
| 743 |
+
kernel_1d /= kernel_1d.sum()
|
| 744 |
+
kernel = torch.outer(kernel_1d, kernel_1d)
|
| 745 |
+
kernel = kernel.expand(work.shape[0], 1, -1, -1)
|
| 746 |
+
mode = "reflect" if radius < min(work.shape[-2:]) else "replicate"
|
| 747 |
+
padded = F.pad(work.unsqueeze(0), (radius, radius, radius, radius), mode=mode)
|
| 748 |
+
blurred = F.conv2d(padded, kernel, groups=work.shape[0]).squeeze(0)
|
| 749 |
+
return blurred.to(dtype=image.dtype).clamp_(0.0, 1.0)
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
def _pil_jpeg(image: torch.Tensor, quality: int) -> torch.Tensor:
|
| 753 |
+
if not 1 <= quality <= 100:
|
| 754 |
+
raise ValueError("JPEG quality must be an integer in [1, 100]")
|
| 755 |
+
device, dtype = image.device, image.dtype
|
| 756 |
+
array = (
|
| 757 |
+
image.detach()
|
| 758 |
+
.cpu()
|
| 759 |
+
.clamp(0.0, 1.0)
|
| 760 |
+
.mul(255.0)
|
| 761 |
+
.round()
|
| 762 |
+
.to(torch.uint8)
|
| 763 |
+
.permute(1, 2, 0)
|
| 764 |
+
.numpy()
|
| 765 |
+
)
|
| 766 |
+
buffer = io.BytesIO()
|
| 767 |
+
Image.fromarray(array).save(
|
| 768 |
+
buffer,
|
| 769 |
+
format="JPEG",
|
| 770 |
+
quality=quality,
|
| 771 |
+
subsampling=0,
|
| 772 |
+
optimize=False,
|
| 773 |
+
)
|
| 774 |
+
buffer.seek(0)
|
| 775 |
+
with Image.open(buffer) as decoded:
|
| 776 |
+
decoded.load()
|
| 777 |
+
result = np.asarray(decoded.convert("RGB"), dtype=np.uint8).copy()
|
| 778 |
+
return (
|
| 779 |
+
torch.from_numpy(result)
|
| 780 |
+
.permute(2, 0, 1)
|
| 781 |
+
.to(device=device, dtype=dtype)
|
| 782 |
+
.div_(255.0)
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
def apply_single(
|
| 787 |
+
image: torch.Tensor,
|
| 788 |
+
degradation: str,
|
| 789 |
+
physical_value: float,
|
| 790 |
+
*,
|
| 791 |
+
noise_seed: int = 0,
|
| 792 |
+
) -> torch.Tensor:
|
| 793 |
+
"""Apply one degradation using its physical parameter.
|
| 794 |
+
|
| 795 |
+
Noise ``physical_value`` is sigma in 8-bit intensity units, blur is Gaussian
|
| 796 |
+
sigma, low-light is gamma in ``x ** gamma``, and JPEG is an integer PIL
|
| 797 |
+
quality. The local noise seed does not modify global Torch RNG state.
|
| 798 |
+
"""
|
| 799 |
+
|
| 800 |
+
_validate_image(image)
|
| 801 |
+
value = float(physical_value)
|
| 802 |
+
if degradation == "noise":
|
| 803 |
+
if value < 0:
|
| 804 |
+
raise ValueError("Noise sigma must be non-negative")
|
| 805 |
+
generator = torch.Generator(device="cpu")
|
| 806 |
+
generator.manual_seed(int(noise_seed))
|
| 807 |
+
noise = torch.randn(image.shape, generator=generator, dtype=torch.float32)
|
| 808 |
+
noise = noise.to(device=image.device, dtype=image.dtype).mul_(value / 255.0)
|
| 809 |
+
return (image + noise).clamp(0.0, 1.0)
|
| 810 |
+
if degradation == "blur":
|
| 811 |
+
return _gaussian_blur(image, value)
|
| 812 |
+
if degradation == "lowlight":
|
| 813 |
+
if value < 1.0:
|
| 814 |
+
raise ValueError("Low-light gamma must be at least 1")
|
| 815 |
+
return image.clamp(0.0, 1.0).pow(value)
|
| 816 |
+
if degradation == "jpeg":
|
| 817 |
+
quality = int(value)
|
| 818 |
+
if value != quality:
|
| 819 |
+
raise ValueError("JPEG quality must be discrete")
|
| 820 |
+
return _pil_jpeg(image, quality)
|
| 821 |
+
raise ValueError(f"Unknown degradation: {degradation}")
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
def apply_composition(
|
| 825 |
+
image: torch.Tensor,
|
| 826 |
+
physical_values: Mapping[str, float],
|
| 827 |
+
*,
|
| 828 |
+
noise_seed: int = 0,
|
| 829 |
+
) -> torch.Tensor:
|
| 830 |
+
"""Apply a component mapping in fixed physical camera order."""
|
| 831 |
+
|
| 832 |
+
unknown = set(physical_values) - set(DEGRADATIONS)
|
| 833 |
+
if unknown:
|
| 834 |
+
raise ValueError(f"Unknown degradation components: {sorted(unknown)}")
|
| 835 |
+
if len(physical_values) < 2:
|
| 836 |
+
raise ValueError("A composition requires at least two components")
|
| 837 |
+
result = image
|
| 838 |
+
for degradation in PHYSICAL_ORDER:
|
| 839 |
+
if degradation in physical_values:
|
| 840 |
+
result = apply_single(
|
| 841 |
+
result,
|
| 842 |
+
degradation,
|
| 843 |
+
physical_values[degradation],
|
| 844 |
+
noise_seed=noise_seed,
|
| 845 |
+
)
|
| 846 |
+
return result
|
| 847 |
+
|
| 848 |
+
|
| 849 |
+
class ControlledDegradationDataset(Dataset):
|
| 850 |
+
"""Materialize deterministic clean/degraded pairs from manifests and specs."""
|
| 851 |
+
|
| 852 |
+
def __init__(
|
| 853 |
+
self,
|
| 854 |
+
crop_manifest: Sequence[CropRecord],
|
| 855 |
+
sample_specs: Optional[Sequence[SampleSpec]] = None,
|
| 856 |
+
*,
|
| 857 |
+
mode: Mode = "support",
|
| 858 |
+
seed: int = 0,
|
| 859 |
+
gap_points: int = 3,
|
| 860 |
+
) -> None:
|
| 861 |
+
self.crop_manifest = list(crop_manifest)
|
| 862 |
+
self.specs = (
|
| 863 |
+
list(sample_specs)
|
| 864 |
+
if sample_specs is not None
|
| 865 |
+
else build_sample_specs(
|
| 866 |
+
self.crop_manifest,
|
| 867 |
+
mode=mode,
|
| 868 |
+
seed=seed,
|
| 869 |
+
gap_points=gap_points,
|
| 870 |
+
)
|
| 871 |
+
)
|
| 872 |
+
self.sample_specs = self.specs
|
| 873 |
+
self._crops = {record.crop_id: record for record in self.crop_manifest}
|
| 874 |
+
if len(self._crops) != len(self.crop_manifest):
|
| 875 |
+
raise ValueError("Crop IDs must be unique")
|
| 876 |
+
missing = {spec.crop_id for spec in self.specs} - set(self._crops)
|
| 877 |
+
if missing:
|
| 878 |
+
raise ValueError(f"Sample specs reference missing crops: {sorted(missing)}")
|
| 879 |
+
_validate_sample_specs(self.specs)
|
| 880 |
+
|
| 881 |
+
def __len__(self) -> int:
|
| 882 |
+
return len(self.specs)
|
| 883 |
+
|
| 884 |
+
def __getitem__(self, index: int) -> Dict[str, Any]:
|
| 885 |
+
spec = self.specs[index]
|
| 886 |
+
clean = load_clean_patch(self._crops[spec.crop_id])
|
| 887 |
+
values = dict(zip(spec.components, spec.physical_values))
|
| 888 |
+
if spec.is_composition:
|
| 889 |
+
degraded = apply_composition(
|
| 890 |
+
clean,
|
| 891 |
+
values,
|
| 892 |
+
noise_seed=spec.noise_seed or 0,
|
| 893 |
+
)
|
| 894 |
+
else:
|
| 895 |
+
degraded = apply_single(
|
| 896 |
+
clean,
|
| 897 |
+
spec.components[0],
|
| 898 |
+
spec.physical_values[0],
|
| 899 |
+
noise_seed=spec.noise_seed or 0,
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
severity_vector = torch.zeros(len(PHYSICAL_ORDER), dtype=torch.float32)
|
| 903 |
+
physical_vector = torch.zeros(len(PHYSICAL_ORDER), dtype=torch.float32)
|
| 904 |
+
component_references = torch.full((len(PHYSICAL_ORDER),), -1, dtype=torch.long)
|
| 905 |
+
for component_number, (component, value, severity) in enumerate(
|
| 906 |
+
zip(spec.components, spec.physical_values, spec.severities)
|
| 907 |
+
):
|
| 908 |
+
position = PHYSICAL_ORDER.index(component)
|
| 909 |
+
severity_vector[position] = severity
|
| 910 |
+
physical_vector[position] = value
|
| 911 |
+
if spec.is_composition:
|
| 912 |
+
component_references[position] = spec.component_indices[component_number]
|
| 913 |
+
|
| 914 |
+
return {
|
| 915 |
+
"clean": clean,
|
| 916 |
+
"degraded": degraded,
|
| 917 |
+
"type": spec.degradation,
|
| 918 |
+
"severity": max(spec.severities),
|
| 919 |
+
"severity_vector": severity_vector,
|
| 920 |
+
"physical_values": physical_vector,
|
| 921 |
+
"component_indices": component_references,
|
| 922 |
+
"sample_index": spec.sample_index,
|
| 923 |
+
"source_id": spec.source_id,
|
| 924 |
+
"crop_id": spec.crop_id,
|
| 925 |
+
"split": spec.split,
|
| 926 |
+
"mode": spec.mode,
|
| 927 |
+
"regime": spec.regime,
|
| 928 |
+
}
|
dataset/phase1_noise_20260906/code/src/data/phase2_v4.py
ADDED
|
@@ -0,0 +1,942 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Leakage-safe paired data contracts for Phase-2 restoration.
|
| 2 |
+
|
| 3 |
+
Only the Phase-1 train and validation sources are reconstructed here. Locked
|
| 4 |
+
test sets deliberately have no representation in this module or its manifest
|
| 5 |
+
schema, which makes accidentally touching them during optimization difficult.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import math
|
| 13 |
+
import os
|
| 14 |
+
import random
|
| 15 |
+
import re
|
| 16 |
+
import tempfile
|
| 17 |
+
from dataclasses import asdict, dataclass
|
| 18 |
+
from pathlib import Path, PurePosixPath
|
| 19 |
+
from typing import Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from PIL import Image
|
| 24 |
+
from torch.utils.data import Dataset, Sampler
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
BRANCH_ORDER: Tuple[str, ...] = ("rain", "noise", "haze", "lowlight")
|
| 28 |
+
BRANCH_TO_INDEX = {name: index for index, name in enumerate(BRANCH_ORDER)}
|
| 29 |
+
EXPECTED_COUNTS: Tuple[int, int] = (18261, 317)
|
| 30 |
+
EXPECTED_DIGESTS: Tuple[str, str] = (
|
| 31 |
+
"769bcff66a209ffbf5195868f7f479309f1350a5bfb367c9e2c3a94d43cbba46",
|
| 32 |
+
"86f0c9723a4c89da6ed1be0da487094bc2938dd5e97e5c5ab68369bd16f8c38d",
|
| 33 |
+
)
|
| 34 |
+
EXPECTED_QUARANTINE_COUNT = 1155
|
| 35 |
+
SUPPORTED_EXTENSIONS = frozenset((".png", ".jpg", ".jpeg"))
|
| 36 |
+
_HEX64 = re.compile(r"^[0-9a-f]{64}$")
|
| 37 |
+
|
| 38 |
+
try:
|
| 39 |
+
_LANCZOS = Image.Resampling.LANCZOS
|
| 40 |
+
except AttributeError: # Pillow < 9
|
| 41 |
+
_LANCZOS = Image.LANCZOS
|
| 42 |
+
try:
|
| 43 |
+
_FLIP_LEFT_RIGHT = Image.Transpose.FLIP_LEFT_RIGHT
|
| 44 |
+
except AttributeError: # Pillow < 9
|
| 45 |
+
_FLIP_LEFT_RIGHT = Image.FLIP_LEFT_RIGHT
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
@dataclass(frozen=True)
|
| 49 |
+
class RestorationRecord:
|
| 50 |
+
degraded: Path
|
| 51 |
+
clean: Path
|
| 52 |
+
degradation: str
|
| 53 |
+
dataset: str
|
| 54 |
+
source_id: str
|
| 55 |
+
split_group: str
|
| 56 |
+
clean_content_sha256: str
|
| 57 |
+
|
| 58 |
+
def __post_init__(self) -> None:
|
| 59 |
+
object.__setattr__(self, "degraded", Path(self.degraded))
|
| 60 |
+
object.__setattr__(self, "clean", Path(self.clean))
|
| 61 |
+
if self.degradation not in BRANCH_TO_INDEX:
|
| 62 |
+
raise ValueError("unknown degradation: %r" % (self.degradation,))
|
| 63 |
+
for name in ("dataset", "source_id", "split_group"):
|
| 64 |
+
value = getattr(self, name)
|
| 65 |
+
if not isinstance(value, str) or not value:
|
| 66 |
+
raise ValueError("%s must be a non-empty string" % name)
|
| 67 |
+
if not isinstance(self.clean_content_sha256, str) or _HEX64.fullmatch(
|
| 68 |
+
self.clean_content_sha256
|
| 69 |
+
) is None:
|
| 70 |
+
raise ValueError("clean_content_sha256 must be 64 lowercase hex digits")
|
| 71 |
+
|
| 72 |
+
@property
|
| 73 |
+
def label(self) -> int:
|
| 74 |
+
return BRANCH_TO_INDEX[self.degradation]
|
| 75 |
+
|
| 76 |
+
@property
|
| 77 |
+
def record_id(self) -> str:
|
| 78 |
+
payload = "\0".join(
|
| 79 |
+
(
|
| 80 |
+
self.dataset,
|
| 81 |
+
self.source_id,
|
| 82 |
+
str(self.degraded),
|
| 83 |
+
str(self.clean),
|
| 84 |
+
self.clean_content_sha256,
|
| 85 |
+
)
|
| 86 |
+
)
|
| 87 |
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
| 88 |
+
|
| 89 |
+
def to_dict(self) -> Dict[str, object]:
|
| 90 |
+
value = asdict(self)
|
| 91 |
+
value["degraded"] = str(self.degraded)
|
| 92 |
+
value["clean"] = str(self.clean)
|
| 93 |
+
value["label"] = self.label
|
| 94 |
+
value["record_id"] = self.record_id
|
| 95 |
+
return value
|
| 96 |
+
|
| 97 |
+
@classmethod
|
| 98 |
+
def from_dict(cls, value: Mapping[str, object]) -> "RestorationRecord":
|
| 99 |
+
if not isinstance(value, Mapping):
|
| 100 |
+
raise ValueError("manifest record must be an object")
|
| 101 |
+
expected = {
|
| 102 |
+
"degraded",
|
| 103 |
+
"clean",
|
| 104 |
+
"degradation",
|
| 105 |
+
"dataset",
|
| 106 |
+
"source_id",
|
| 107 |
+
"split_group",
|
| 108 |
+
"clean_content_sha256",
|
| 109 |
+
"label",
|
| 110 |
+
"record_id",
|
| 111 |
+
}
|
| 112 |
+
if set(value) != expected:
|
| 113 |
+
raise ValueError("manifest record fields do not match the v4 schema")
|
| 114 |
+
record = cls(
|
| 115 |
+
degraded=Path(_required_string(value, "degraded")),
|
| 116 |
+
clean=Path(_required_string(value, "clean")),
|
| 117 |
+
degradation=_required_string(value, "degradation"),
|
| 118 |
+
dataset=_required_string(value, "dataset"),
|
| 119 |
+
source_id=_required_string(value, "source_id"),
|
| 120 |
+
split_group=_required_string(value, "split_group"),
|
| 121 |
+
clean_content_sha256=_required_string(value, "clean_content_sha256"),
|
| 122 |
+
)
|
| 123 |
+
label = value["label"]
|
| 124 |
+
if (
|
| 125 |
+
isinstance(label, bool)
|
| 126 |
+
or not isinstance(label, int)
|
| 127 |
+
or label != record.label
|
| 128 |
+
or not isinstance(value["record_id"], str)
|
| 129 |
+
or value["record_id"] != record.record_id
|
| 130 |
+
):
|
| 131 |
+
raise ValueError("manifest record derived identity mismatch")
|
| 132 |
+
return record
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@dataclass(frozen=True)
|
| 136 |
+
class TrainValSplits:
|
| 137 |
+
train: Tuple[RestorationRecord, ...]
|
| 138 |
+
val: Tuple[RestorationRecord, ...]
|
| 139 |
+
quarantine_count: int
|
| 140 |
+
|
| 141 |
+
def __post_init__(self) -> None:
|
| 142 |
+
object.__setattr__(self, "train", tuple(self.train))
|
| 143 |
+
object.__setattr__(self, "val", tuple(self.val))
|
| 144 |
+
if (
|
| 145 |
+
isinstance(self.quarantine_count, bool)
|
| 146 |
+
or not isinstance(self.quarantine_count, int)
|
| 147 |
+
or self.quarantine_count < 0
|
| 148 |
+
):
|
| 149 |
+
raise ValueError("quarantine_count must be a non-negative integer")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _required_string(value: Mapping[str, object], key: str) -> str:
|
| 153 |
+
item = value.get(key)
|
| 154 |
+
if not isinstance(item, str) or not item:
|
| 155 |
+
raise ValueError("%s must be a non-empty string" % key)
|
| 156 |
+
return item
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def _sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str:
|
| 160 |
+
digest = hashlib.sha256()
|
| 161 |
+
with path.open("rb") as handle:
|
| 162 |
+
while True:
|
| 163 |
+
chunk = handle.read(chunk_size)
|
| 164 |
+
if not chunk:
|
| 165 |
+
break
|
| 166 |
+
digest.update(chunk)
|
| 167 |
+
return digest.hexdigest()
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def _image_map(directory: Path, label: str, recursive: bool = False) -> Dict[str, Path]:
|
| 171 |
+
if not directory.is_dir():
|
| 172 |
+
raise FileNotFoundError("%s missing directory: %s" % (label, directory))
|
| 173 |
+
candidates = directory.rglob("*") if recursive else directory.iterdir()
|
| 174 |
+
files: Dict[str, Path] = {}
|
| 175 |
+
for path in candidates:
|
| 176 |
+
if path.suffix.lower() not in SUPPORTED_EXTENSIONS or not path.is_file():
|
| 177 |
+
continue
|
| 178 |
+
key = path.relative_to(directory).as_posix() if recursive else path.name
|
| 179 |
+
if key in files:
|
| 180 |
+
raise ValueError("%s duplicate image key: %s" % (label, key))
|
| 181 |
+
files[key] = path
|
| 182 |
+
if not files:
|
| 183 |
+
raise ValueError("%s contains no supported images" % label)
|
| 184 |
+
return {key: files[key] for key in sorted(files)}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _paired_paths(
|
| 188 |
+
degraded_dir: Path, clean_dir: Path, label: str, recursive: bool = False
|
| 189 |
+
) -> List[Tuple[str, Path, Path]]:
|
| 190 |
+
degraded = _image_map(degraded_dir, "%s input" % label, recursive)
|
| 191 |
+
clean = _image_map(clean_dir, "%s target" % label, recursive)
|
| 192 |
+
if set(degraded) != set(clean):
|
| 193 |
+
missing_clean = sorted(set(degraded) - set(clean))[:5]
|
| 194 |
+
missing_degraded = sorted(set(clean) - set(degraded))[:5]
|
| 195 |
+
raise ValueError(
|
| 196 |
+
"%s pairing is not bijective; missing clean=%r missing degraded=%r"
|
| 197 |
+
% (label, missing_clean, missing_degraded)
|
| 198 |
+
)
|
| 199 |
+
return [(name, degraded[name], clean[name]) for name in sorted(degraded)]
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def _load_quarantine_paths(path: Path) -> Tuple[frozenset, int, int]:
|
| 203 |
+
try:
|
| 204 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 205 |
+
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
| 206 |
+
raise ValueError("malformed Rain13K quarantine manifest: %s" % exc) from exc
|
| 207 |
+
if not isinstance(payload, dict) or payload.get("schema_version") != 1:
|
| 208 |
+
raise ValueError("Rain13K quarantine manifest schema_version must be 1")
|
| 209 |
+
dataset = payload.get("dataset")
|
| 210 |
+
summary = payload.get("summary")
|
| 211 |
+
groups = payload.get("excluded_train_targets")
|
| 212 |
+
if not isinstance(dataset, dict) or not isinstance(summary, dict) or not isinstance(groups, list):
|
| 213 |
+
raise ValueError("Rain13K quarantine manifest has malformed top-level fields")
|
| 214 |
+
if dataset.get("handle") != "hngphchi/rain13k-resized" or dataset.get("version") != 1:
|
| 215 |
+
raise ValueError("Rain13K quarantine manifest identifies the wrong dataset")
|
| 216 |
+
train_count = dataset.get("train_pair_count")
|
| 217 |
+
affected = summary.get("affected_train_pairs")
|
| 218 |
+
group_count = summary.get("excluded_train_target_groups")
|
| 219 |
+
if (
|
| 220 |
+
isinstance(train_count, bool)
|
| 221 |
+
or not isinstance(train_count, int)
|
| 222 |
+
or isinstance(affected, bool)
|
| 223 |
+
or not isinstance(affected, int)
|
| 224 |
+
or isinstance(group_count, bool)
|
| 225 |
+
or not isinstance(group_count, int)
|
| 226 |
+
or group_count != len(groups)
|
| 227 |
+
):
|
| 228 |
+
raise ValueError("Rain13K quarantine manifest count fields are malformed")
|
| 229 |
+
excluded = set()
|
| 230 |
+
for group in groups:
|
| 231 |
+
if not isinstance(group, dict) or not isinstance(group.get("train_targets"), list):
|
| 232 |
+
raise ValueError("Rain13K quarantine group is malformed")
|
| 233 |
+
if not group["train_targets"]:
|
| 234 |
+
raise ValueError("Rain13K quarantine group has no train targets")
|
| 235 |
+
for target in group["train_targets"]:
|
| 236 |
+
if not isinstance(target, dict):
|
| 237 |
+
raise ValueError("Rain13K quarantine target is malformed")
|
| 238 |
+
relative = target.get("relative_path")
|
| 239 |
+
if not isinstance(relative, str):
|
| 240 |
+
raise ValueError("Rain13K quarantine relative_path is malformed")
|
| 241 |
+
file_hash = target.get("file_sha256")
|
| 242 |
+
if (
|
| 243 |
+
not isinstance(file_hash, str)
|
| 244 |
+
or _HEX64.fullmatch(file_hash.lower()) is None
|
| 245 |
+
):
|
| 246 |
+
raise ValueError("Rain13K quarantine file_sha256 is malformed")
|
| 247 |
+
pure = PurePosixPath(relative)
|
| 248 |
+
if (
|
| 249 |
+
pure.is_absolute()
|
| 250 |
+
or pure.as_posix() != relative
|
| 251 |
+
or pure.parts[:2] != ("train_resized", "target")
|
| 252 |
+
or len(pure.parts) < 3
|
| 253 |
+
or ".." in pure.parts
|
| 254 |
+
):
|
| 255 |
+
raise ValueError("unsafe Rain13K quarantine relative_path: %r" % relative)
|
| 256 |
+
if relative in excluded:
|
| 257 |
+
raise ValueError("duplicate Rain13K quarantine path: %s" % relative)
|
| 258 |
+
excluded.add(relative)
|
| 259 |
+
if len(excluded) != affected:
|
| 260 |
+
raise ValueError("Rain13K quarantine affected pair count mismatch")
|
| 261 |
+
return frozenset(excluded), train_count, affected
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _make_record(
|
| 265 |
+
degraded: Path,
|
| 266 |
+
clean: Path,
|
| 267 |
+
degradation: str,
|
| 268 |
+
dataset: str,
|
| 269 |
+
source_id: str,
|
| 270 |
+
split_group: str,
|
| 271 |
+
clean_hash: Optional[str] = None,
|
| 272 |
+
) -> RestorationRecord:
|
| 273 |
+
return RestorationRecord(
|
| 274 |
+
degraded=degraded,
|
| 275 |
+
clean=clean,
|
| 276 |
+
degradation=degradation,
|
| 277 |
+
dataset=dataset,
|
| 278 |
+
source_id=source_id,
|
| 279 |
+
split_group=split_group,
|
| 280 |
+
clean_content_sha256=clean_hash or _sha256_file(clean),
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _build_rain_train_val(
|
| 285 |
+
rain_root: Path, quarantine_manifest: Path
|
| 286 |
+
) -> Tuple[List[RestorationRecord], List[RestorationRecord], int]:
|
| 287 |
+
excluded, expected_raw_train, affected = _load_quarantine_paths(quarantine_manifest)
|
| 288 |
+
raw_train = _paired_paths(
|
| 289 |
+
rain_root / "train_resized" / "input",
|
| 290 |
+
rain_root / "train_resized" / "target",
|
| 291 |
+
"Rain13K train_resized",
|
| 292 |
+
recursive=True,
|
| 293 |
+
)
|
| 294 |
+
if len(raw_train) != expected_raw_train:
|
| 295 |
+
raise ValueError(
|
| 296 |
+
"Rain13K raw train count mismatch: expected %d, got %d"
|
| 297 |
+
% (expected_raw_train, len(raw_train))
|
| 298 |
+
)
|
| 299 |
+
observed_names = {
|
| 300 |
+
"train_resized/target/%s" % relative for relative, _, _ in raw_train
|
| 301 |
+
}
|
| 302 |
+
missing = excluded - observed_names
|
| 303 |
+
if missing:
|
| 304 |
+
raise ValueError("quarantine references absent Rain13K train paths: %r" % sorted(missing)[:5])
|
| 305 |
+
|
| 306 |
+
train = []
|
| 307 |
+
for relative, degraded, clean in raw_train:
|
| 308 |
+
quarantine_key = "train_resized/target/%s" % relative
|
| 309 |
+
if quarantine_key in excluded:
|
| 310 |
+
continue
|
| 311 |
+
content_hash = _sha256_file(clean)
|
| 312 |
+
train.append(
|
| 313 |
+
_make_record(
|
| 314 |
+
degraded,
|
| 315 |
+
clean,
|
| 316 |
+
"rain",
|
| 317 |
+
"Rain13K",
|
| 318 |
+
"train_resized:%s" % degraded.name,
|
| 319 |
+
content_hash,
|
| 320 |
+
content_hash,
|
| 321 |
+
)
|
| 322 |
+
)
|
| 323 |
+
if len(train) != expected_raw_train - affected:
|
| 324 |
+
raise ValueError("Rain13K quarantined train count mismatch")
|
| 325 |
+
|
| 326 |
+
raw_val = _paired_paths(
|
| 327 |
+
rain_root / "test_resized" / "Test100" / "input",
|
| 328 |
+
rain_root / "test_resized" / "Test100" / "target",
|
| 329 |
+
"Rain13K Test100",
|
| 330 |
+
recursive=True,
|
| 331 |
+
)
|
| 332 |
+
if len(raw_val) != 98:
|
| 333 |
+
raise ValueError("Rain13K Test100 audited count must be 98")
|
| 334 |
+
val = []
|
| 335 |
+
for _, degraded, clean in raw_val:
|
| 336 |
+
content_hash = _sha256_file(clean)
|
| 337 |
+
val.append(
|
| 338 |
+
_make_record(
|
| 339 |
+
degraded,
|
| 340 |
+
clean,
|
| 341 |
+
"rain",
|
| 342 |
+
"Rain13K",
|
| 343 |
+
"Test100:%s" % degraded.name,
|
| 344 |
+
content_hash,
|
| 345 |
+
content_hash,
|
| 346 |
+
)
|
| 347 |
+
)
|
| 348 |
+
return train, val, affected
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def _build_lol_train_val(data_root: Path) -> Tuple[List[RestorationRecord], List[RestorationRecord]]:
|
| 352 |
+
root = data_root / "LOLv2" / "lolv2_hf"
|
| 353 |
+
|
| 354 |
+
def build(split: str, expected: int) -> List[RestorationRecord]:
|
| 355 |
+
pairs = _paired_paths(
|
| 356 |
+
root / split / "Input", root / split / "GT", "LOLv2 %s" % split
|
| 357 |
+
)
|
| 358 |
+
if len(pairs) != expected:
|
| 359 |
+
raise ValueError("LOLv2 %s audited count must be %d" % (split, expected))
|
| 360 |
+
records = []
|
| 361 |
+
for _, degraded, clean in pairs:
|
| 362 |
+
content_hash = _sha256_file(clean)
|
| 363 |
+
records.append(
|
| 364 |
+
_make_record(
|
| 365 |
+
degraded,
|
| 366 |
+
clean,
|
| 367 |
+
"lowlight",
|
| 368 |
+
"LOLv2",
|
| 369 |
+
degraded.stem,
|
| 370 |
+
content_hash,
|
| 371 |
+
content_hash,
|
| 372 |
+
)
|
| 373 |
+
)
|
| 374 |
+
return records
|
| 375 |
+
|
| 376 |
+
return build("Train", 689), build("Test", 100)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def _directory_image_names(directory: Path, label: str) -> List[str]:
|
| 380 |
+
if not directory.is_dir():
|
| 381 |
+
raise FileNotFoundError("%s missing directory: %s" % (label, directory))
|
| 382 |
+
try:
|
| 383 |
+
names = os.listdir(str(directory))
|
| 384 |
+
except OSError as exc:
|
| 385 |
+
raise ValueError("could not enumerate %s: %s" % (label, exc)) from exc
|
| 386 |
+
return sorted(name for name in names if Path(name).suffix.lower() in SUPPORTED_EXTENSIONS)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def _build_reside_train_val(
|
| 390 |
+
data_root: Path,
|
| 391 |
+
) -> Tuple[List[RestorationRecord], List[RestorationRecord]]:
|
| 392 |
+
root = data_root / "RESIDE"
|
| 393 |
+
hazy_dir, clear_dir = root / "hazy", root / "clear"
|
| 394 |
+
hazy_names = _directory_image_names(hazy_dir, "RESIDE hazy")
|
| 395 |
+
if len(hazy_names) < 5000:
|
| 396 |
+
raise ValueError("RESIDE requires at least 5000 sorted hazy images")
|
| 397 |
+
selected_hazy = hazy_names[:5000]
|
| 398 |
+
if not clear_dir.is_dir():
|
| 399 |
+
raise FileNotFoundError("RESIDE clear missing directory: %s" % clear_dir)
|
| 400 |
+
|
| 401 |
+
selected = []
|
| 402 |
+
for name in selected_hazy:
|
| 403 |
+
degraded = hazy_dir / name
|
| 404 |
+
source = Path(name).stem.split("_")[0]
|
| 405 |
+
if not source or "_" not in Path(name).stem:
|
| 406 |
+
raise ValueError("malformed RESIDE hazy filename: %s" % name)
|
| 407 |
+
# Canonical RESIDE ITS uses exactly ``clear/<source>.jpg``. Resolving
|
| 408 |
+
# the selected source directly avoids enumerating the 1,918 clear
|
| 409 |
+
# sources held out beyond the first-5000 Phase-1 support contract.
|
| 410 |
+
clean = clear_dir / (source + ".jpg")
|
| 411 |
+
if not degraded.is_file() or not clean.is_file():
|
| 412 |
+
raise ValueError("RESIDE selected pair is not made of regular files: %s" % name)
|
| 413 |
+
selected.append((degraded, clean, source))
|
| 414 |
+
|
| 415 |
+
val_pairs = selected[:100]
|
| 416 |
+
val_groups = {source for _, _, source in val_pairs}
|
| 417 |
+
train_pairs = [pair for pair in selected[100:] if pair[2] not in val_groups]
|
| 418 |
+
if len(train_pairs) != 4895 or len(val_pairs) != 100:
|
| 419 |
+
raise ValueError("RESIDE audited split count mismatch")
|
| 420 |
+
hashes: Dict[str, str] = {}
|
| 421 |
+
|
| 422 |
+
def records(pairs: Sequence[Tuple[Path, Path, str]]) -> List[RestorationRecord]:
|
| 423 |
+
output = []
|
| 424 |
+
for degraded, clean, source in pairs:
|
| 425 |
+
content_hash = hashes.get(source)
|
| 426 |
+
if content_hash is None:
|
| 427 |
+
content_hash = _sha256_file(clean)
|
| 428 |
+
hashes[source] = content_hash
|
| 429 |
+
output.append(
|
| 430 |
+
_make_record(
|
| 431 |
+
degraded,
|
| 432 |
+
clean,
|
| 433 |
+
"haze",
|
| 434 |
+
"RESIDE",
|
| 435 |
+
degraded.stem,
|
| 436 |
+
source,
|
| 437 |
+
content_hash,
|
| 438 |
+
)
|
| 439 |
+
)
|
| 440 |
+
return output
|
| 441 |
+
|
| 442 |
+
return records(train_pairs), records(val_pairs)
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def _sidd_scene_number(source_id: str) -> str:
|
| 446 |
+
parts = source_id.split("_")
|
| 447 |
+
if len(parts) < 3 or len(parts[1]) != 3 or not parts[1].isdigit():
|
| 448 |
+
raise ValueError("malformed SIDD source directory: %s" % source_id)
|
| 449 |
+
return parts[1]
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def _build_sidd_train_val(
|
| 453 |
+
data_root: Path,
|
| 454 |
+
) -> Tuple[List[RestorationRecord], List[RestorationRecord]]:
|
| 455 |
+
root = data_root / "SIDD" / "SIDD_Small_sRGB_Only" / "Data"
|
| 456 |
+
if not root.is_dir():
|
| 457 |
+
raise FileNotFoundError("SIDD Data directory does not exist: %s" % root)
|
| 458 |
+
# The audited SIDD-small corpus has scenes 001..010. Derive the first nine
|
| 459 |
+
# from that public schema, then glob only those scene patterns: the tenth
|
| 460 |
+
# (locked) scene is never listed, statted, or represented by a Path object.
|
| 461 |
+
audited_scenes = tuple("%03d" % number for number in range(1, 11))
|
| 462 |
+
ordered_scenes = sorted(
|
| 463 |
+
audited_scenes,
|
| 464 |
+
key=lambda scene: (hashlib.sha256(scene.encode("utf-8")).digest(), scene),
|
| 465 |
+
)
|
| 466 |
+
train_scenes = frozenset(ordered_scenes[:8])
|
| 467 |
+
val_scenes = frozenset(ordered_scenes[8:9])
|
| 468 |
+
by_scene: Dict[str, List[str]] = {}
|
| 469 |
+
for scene in ordered_scenes[:9]:
|
| 470 |
+
matches = sorted(path.name for path in root.glob("*_%s_*" % scene))
|
| 471 |
+
if not matches:
|
| 472 |
+
raise ValueError("SIDD selected scene %s has no source directories" % scene)
|
| 473 |
+
for name in matches:
|
| 474 |
+
if _sidd_scene_number(name) != scene:
|
| 475 |
+
raise ValueError("SIDD scene glob returned malformed source: %s" % name)
|
| 476 |
+
by_scene[scene] = matches
|
| 477 |
+
|
| 478 |
+
def build(scenes: frozenset) -> List[RestorationRecord]:
|
| 479 |
+
output = []
|
| 480 |
+
for scene in ordered_scenes[:9]:
|
| 481 |
+
if scene not in scenes:
|
| 482 |
+
continue
|
| 483 |
+
for source_id in by_scene[scene]:
|
| 484 |
+
source_dir = root / source_id
|
| 485 |
+
if not source_dir.is_dir():
|
| 486 |
+
raise ValueError("selected SIDD source is not a directory: %s" % source_id)
|
| 487 |
+
members = sorted(os.listdir(str(source_dir)))
|
| 488 |
+
noisy = [name for name in members if name.startswith("NOISY_SRGB_")]
|
| 489 |
+
clean = [name for name in members if name.startswith("GT_SRGB_")]
|
| 490 |
+
if len(noisy) != 1 or len(clean) != 1:
|
| 491 |
+
raise ValueError("SIDD source %s must contain one NOISY/GT pair" % source_id)
|
| 492 |
+
degraded_path = source_dir / noisy[0]
|
| 493 |
+
clean_path = source_dir / clean[0]
|
| 494 |
+
if not degraded_path.is_file() or not clean_path.is_file():
|
| 495 |
+
raise ValueError("selected SIDD pair is not made of regular files")
|
| 496 |
+
output.append(
|
| 497 |
+
_make_record(
|
| 498 |
+
degraded_path,
|
| 499 |
+
clean_path,
|
| 500 |
+
"noise",
|
| 501 |
+
"SIDD",
|
| 502 |
+
source_id,
|
| 503 |
+
scene,
|
| 504 |
+
)
|
| 505 |
+
)
|
| 506 |
+
return output
|
| 507 |
+
|
| 508 |
+
train, val = build(train_scenes), build(val_scenes)
|
| 509 |
+
if len(train) != 121 or len(val) != 19:
|
| 510 |
+
raise ValueError("SIDD audited train/validation count mismatch")
|
| 511 |
+
return train, val
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
def _assert_train_val_isolation(splits: TrainValSplits) -> None:
|
| 515 |
+
train_groups = {(record.dataset, record.split_group) for record in splits.train}
|
| 516 |
+
val_groups = {(record.dataset, record.split_group) for record in splits.val}
|
| 517 |
+
overlap = train_groups & val_groups
|
| 518 |
+
if overlap:
|
| 519 |
+
raise ValueError("source leakage between train and validation: %r" % sorted(overlap)[:5])
|
| 520 |
+
train_content = {record.clean_content_sha256 for record in splits.train}
|
| 521 |
+
val_content = {record.clean_content_sha256 for record in splits.val}
|
| 522 |
+
content_overlap = train_content & val_content
|
| 523 |
+
if content_overlap:
|
| 524 |
+
raise ValueError("clean-content leakage between train and validation")
|
| 525 |
+
for label, records in (("train", splits.train), ("validation", splits.val)):
|
| 526 |
+
identifiers = [record.record_id for record in records]
|
| 527 |
+
if len(identifiers) != len(set(identifiers)):
|
| 528 |
+
raise ValueError("duplicate %s restoration records" % label)
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def build_train_val_splits(
|
| 532 |
+
data_root: Union[str, Path],
|
| 533 |
+
rain_root: Union[str, Path],
|
| 534 |
+
quarantine_manifest: Union[str, Path],
|
| 535 |
+
) -> TrainValSplits:
|
| 536 |
+
"""Reconstruct exactly the Phase-1 support splits without any locked data."""
|
| 537 |
+
|
| 538 |
+
data_path = Path(data_root).expanduser()
|
| 539 |
+
rain_path = Path(rain_root).expanduser()
|
| 540 |
+
quarantine_path = Path(quarantine_manifest).expanduser()
|
| 541 |
+
rain_train, rain_val, quarantine_count = _build_rain_train_val(
|
| 542 |
+
rain_path, quarantine_path
|
| 543 |
+
)
|
| 544 |
+
lol_train, lol_val = _build_lol_train_val(data_path)
|
| 545 |
+
reside_train, reside_val = _build_reside_train_val(data_path)
|
| 546 |
+
sidd_train, sidd_val = _build_sidd_train_val(data_path)
|
| 547 |
+
splits = TrainValSplits(
|
| 548 |
+
train=tuple(rain_train + lol_train + reside_train + sidd_train),
|
| 549 |
+
val=tuple(rain_val + lol_val + reside_val + sidd_val),
|
| 550 |
+
quarantine_count=quarantine_count,
|
| 551 |
+
)
|
| 552 |
+
if (len(splits.train), len(splits.val)) != EXPECTED_COUNTS:
|
| 553 |
+
raise ValueError(
|
| 554 |
+
"live train/validation counts differ from audited contract: expected %r, got %r"
|
| 555 |
+
% (EXPECTED_COUNTS, (len(splits.train), len(splits.val)))
|
| 556 |
+
)
|
| 557 |
+
if quarantine_count != EXPECTED_QUARANTINE_COUNT:
|
| 558 |
+
raise ValueError("live quarantine count differs from audited contract")
|
| 559 |
+
_assert_train_val_isolation(splits)
|
| 560 |
+
for label, records in (("train", splits.train), ("validation", splits.val)):
|
| 561 |
+
if set(record.degradation for record in records) != set(BRANCH_ORDER):
|
| 562 |
+
raise ValueError("%s split does not contain all four degradations" % label)
|
| 563 |
+
return splits
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def split_digest(records: Sequence[RestorationRecord]) -> str:
|
| 567 |
+
digest = hashlib.sha256(b"SCDC_PHASE1_SPLIT_V2\0")
|
| 568 |
+
for record in records:
|
| 569 |
+
digest.update(record.record_id.encode("ascii"))
|
| 570 |
+
digest.update(b"\n")
|
| 571 |
+
return digest.hexdigest()
|
| 572 |
+
|
| 573 |
+
|
| 574 |
+
def validate_clean_file_integrity(splits: TrainValSplits) -> None:
|
| 575 |
+
"""Re-hash each unique train/validation clean file once before a run.
|
| 576 |
+
|
| 577 |
+
Manifest identities protect serialization, while this explicit preflight
|
| 578 |
+
protects against files being deleted, replaced, or modified after the
|
| 579 |
+
manifest was written. It is intentionally not called from ``__getitem__``.
|
| 580 |
+
"""
|
| 581 |
+
|
| 582 |
+
expected_by_path: Dict[Path, str] = {}
|
| 583 |
+
for record in tuple(splits.train) + tuple(splits.val):
|
| 584 |
+
previous = expected_by_path.setdefault(
|
| 585 |
+
record.clean, record.clean_content_sha256
|
| 586 |
+
)
|
| 587 |
+
if previous != record.clean_content_sha256:
|
| 588 |
+
raise ValueError(
|
| 589 |
+
"manifest records disagree on expected SHA256 for clean file %s"
|
| 590 |
+
% record.clean
|
| 591 |
+
)
|
| 592 |
+
for clean_path, expected in expected_by_path.items():
|
| 593 |
+
if not clean_path.exists():
|
| 594 |
+
raise FileNotFoundError("clean file is missing: %s" % clean_path)
|
| 595 |
+
if not clean_path.is_file():
|
| 596 |
+
raise ValueError("clean path is not a regular file: %s" % clean_path)
|
| 597 |
+
actual = _sha256_file(clean_path)
|
| 598 |
+
if actual != expected:
|
| 599 |
+
raise ValueError(
|
| 600 |
+
"clean file SHA256 drift for %s: expected %s, got %s"
|
| 601 |
+
% (clean_path, expected, actual)
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def path_relocation_back_map() -> List[Tuple[str, str]]:
|
| 606 |
+
"""``SCDC_PATH_RELOCATION="NEW_PREFIX=OLD_PREFIX,NEW=OLD"``: how the data
|
| 607 |
+
roots on this host map back to the roots the canonical digests and the
|
| 608 |
+
Phase-1 checkpoint provenance were computed with (record ids hash the
|
| 609 |
+
absolute paths, so a relocated copy of the data has different local
|
| 610 |
+
digests while being the same audited split)."""
|
| 611 |
+
|
| 612 |
+
value = os.environ.get("SCDC_PATH_RELOCATION", "").strip()
|
| 613 |
+
if not value:
|
| 614 |
+
return []
|
| 615 |
+
pairs = []
|
| 616 |
+
for item in value.split(","):
|
| 617 |
+
if "=" not in item:
|
| 618 |
+
raise ValueError("SCDC_PATH_RELOCATION entries must be NEW=OLD: %r" % item)
|
| 619 |
+
new, old = item.split("=", 1)
|
| 620 |
+
pairs.append((new, old))
|
| 621 |
+
return pairs
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
def canonical_split_digest(records: Sequence[RestorationRecord]) -> str:
|
| 625 |
+
"""Split digest as it would read at the canonical (original) data roots."""
|
| 626 |
+
|
| 627 |
+
back = path_relocation_back_map()
|
| 628 |
+
if not back:
|
| 629 |
+
return split_digest(records)
|
| 630 |
+
|
| 631 |
+
def relocate(path: Path) -> Path:
|
| 632 |
+
text = str(path)
|
| 633 |
+
for new, old in back:
|
| 634 |
+
if text.startswith(new):
|
| 635 |
+
return Path(old + text[len(new):])
|
| 636 |
+
return path
|
| 637 |
+
|
| 638 |
+
canonical = [
|
| 639 |
+
RestorationRecord(
|
| 640 |
+
degraded=relocate(r.degraded), clean=relocate(r.clean), degradation=r.degradation,
|
| 641 |
+
dataset=r.dataset, source_id=r.source_id, split_group=r.split_group,
|
| 642 |
+
clean_content_sha256=r.clean_content_sha256,
|
| 643 |
+
)
|
| 644 |
+
for r in records
|
| 645 |
+
]
|
| 646 |
+
return split_digest(canonical)
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def validate_splits_against_checkpoint(
|
| 650 |
+
splits: TrainValSplits,
|
| 651 |
+
checkpoint: Mapping[str, object],
|
| 652 |
+
expected_counts: Optional[Tuple[int, int]] = EXPECTED_COUNTS,
|
| 653 |
+
expected_digests: Optional[Tuple[str, str]] = EXPECTED_DIGESTS,
|
| 654 |
+
) -> None:
|
| 655 |
+
_assert_train_val_isolation(splits)
|
| 656 |
+
counts = (len(splits.train), len(splits.val))
|
| 657 |
+
digests = (canonical_split_digest(splits.train), canonical_split_digest(splits.val))
|
| 658 |
+
if expected_counts is not None and counts != tuple(expected_counts):
|
| 659 |
+
raise ValueError("local train/validation counts do not match the canonical contract")
|
| 660 |
+
if expected_digests is not None and digests != tuple(expected_digests):
|
| 661 |
+
raise ValueError("local train/validation split digests do not match the canonical contract")
|
| 662 |
+
provenance = checkpoint.get("provenance") if isinstance(checkpoint, Mapping) else None
|
| 663 |
+
if not isinstance(provenance, Mapping):
|
| 664 |
+
raise ValueError("checkpoint has no Phase-1 provenance object")
|
| 665 |
+
checkpoint_counts = provenance.get("counts")
|
| 666 |
+
checkpoint_digests = provenance.get("split_digests")
|
| 667 |
+
if not isinstance(checkpoint_counts, Mapping) or not isinstance(checkpoint_digests, Mapping):
|
| 668 |
+
raise ValueError("checkpoint provenance omits train/validation contracts")
|
| 669 |
+
for key, label, actual_count, actual_digest in (
|
| 670 |
+
("train", "training", counts[0], digests[0]),
|
| 671 |
+
("val", "validation", counts[1], digests[1]),
|
| 672 |
+
):
|
| 673 |
+
count_object = checkpoint_counts.get(key)
|
| 674 |
+
if not isinstance(count_object, Mapping) or count_object.get("pairs") != actual_count:
|
| 675 |
+
raise ValueError("checkpoint %s split count mismatch" % label)
|
| 676 |
+
if checkpoint_digests.get(key) != actual_digest:
|
| 677 |
+
raise ValueError("checkpoint %s split digest mismatch" % label)
|
| 678 |
+
if provenance.get("quarantined_rain_train_pairs") != splits.quarantine_count:
|
| 679 |
+
raise ValueError("checkpoint quarantine count mismatch")
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
def save_train_val_manifest(path: Union[str, Path], splits: TrainValSplits) -> None:
|
| 683 |
+
_assert_train_val_isolation(splits)
|
| 684 |
+
destination = Path(path)
|
| 685 |
+
destination.parent.mkdir(parents=True, exist_ok=True)
|
| 686 |
+
payload = {
|
| 687 |
+
"schema_version": 1,
|
| 688 |
+
"quarantine_count": splits.quarantine_count,
|
| 689 |
+
"train_digest": split_digest(splits.train),
|
| 690 |
+
"val_digest": split_digest(splits.val),
|
| 691 |
+
"train": [record.to_dict() for record in splits.train],
|
| 692 |
+
"val": [record.to_dict() for record in splits.val],
|
| 693 |
+
}
|
| 694 |
+
temporary_name = None
|
| 695 |
+
try:
|
| 696 |
+
with tempfile.NamedTemporaryFile(
|
| 697 |
+
mode="w",
|
| 698 |
+
encoding="utf-8",
|
| 699 |
+
dir=str(destination.parent),
|
| 700 |
+
prefix=".%s." % destination.name,
|
| 701 |
+
suffix=".tmp",
|
| 702 |
+
delete=False,
|
| 703 |
+
) as handle:
|
| 704 |
+
temporary_name = handle.name
|
| 705 |
+
json.dump(payload, handle, indent=2, sort_keys=True)
|
| 706 |
+
handle.write("\n")
|
| 707 |
+
handle.flush()
|
| 708 |
+
os.fsync(handle.fileno())
|
| 709 |
+
os.replace(temporary_name, str(destination))
|
| 710 |
+
temporary_name = None
|
| 711 |
+
finally:
|
| 712 |
+
if temporary_name is not None:
|
| 713 |
+
try:
|
| 714 |
+
os.unlink(temporary_name)
|
| 715 |
+
except FileNotFoundError:
|
| 716 |
+
pass
|
| 717 |
+
|
| 718 |
+
|
| 719 |
+
def load_train_val_manifest(path: Union[str, Path]) -> TrainValSplits:
|
| 720 |
+
try:
|
| 721 |
+
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
| 722 |
+
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
| 723 |
+
raise ValueError("malformed Phase-2 train/validation manifest: %s" % exc) from exc
|
| 724 |
+
if not isinstance(payload, dict):
|
| 725 |
+
raise ValueError("Phase-2 manifest root must be an object")
|
| 726 |
+
if any("locked" in str(key).lower() or str(key).lower() == "test" for key in payload):
|
| 727 |
+
raise ValueError("locked/test keys are forbidden in a Phase-2 optimization manifest")
|
| 728 |
+
expected = {
|
| 729 |
+
"schema_version",
|
| 730 |
+
"quarantine_count",
|
| 731 |
+
"train_digest",
|
| 732 |
+
"val_digest",
|
| 733 |
+
"train",
|
| 734 |
+
"val",
|
| 735 |
+
}
|
| 736 |
+
if set(payload) != expected or payload.get("schema_version") != 1:
|
| 737 |
+
raise ValueError("Phase-2 train/validation manifest schema mismatch")
|
| 738 |
+
if not isinstance(payload["train"], list) or not isinstance(payload["val"], list):
|
| 739 |
+
raise ValueError("Phase-2 manifest train and val must be arrays")
|
| 740 |
+
quarantine_count = payload["quarantine_count"]
|
| 741 |
+
if isinstance(quarantine_count, bool) or not isinstance(quarantine_count, int):
|
| 742 |
+
raise ValueError("Phase-2 manifest quarantine_count must be an integer")
|
| 743 |
+
splits = TrainValSplits(
|
| 744 |
+
train=tuple(RestorationRecord.from_dict(value) for value in payload["train"]),
|
| 745 |
+
val=tuple(RestorationRecord.from_dict(value) for value in payload["val"]),
|
| 746 |
+
quarantine_count=quarantine_count,
|
| 747 |
+
)
|
| 748 |
+
if payload["train_digest"] != split_digest(splits.train):
|
| 749 |
+
raise ValueError("Phase-2 manifest training split digest mismatch")
|
| 750 |
+
if payload["val_digest"] != split_digest(splits.val):
|
| 751 |
+
raise ValueError("Phase-2 manifest validation split digest mismatch")
|
| 752 |
+
_assert_train_val_isolation(splits)
|
| 753 |
+
return splits
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def _open_rgb(path: Path) -> Image.Image:
|
| 757 |
+
try:
|
| 758 |
+
with Image.open(str(path)) as image:
|
| 759 |
+
return image.convert("RGB").copy()
|
| 760 |
+
except Exception as exc:
|
| 761 |
+
raise RuntimeError("failed to decode image %s: %s" % (path, exc)) from exc
|
| 762 |
+
|
| 763 |
+
|
| 764 |
+
def _pil_to_tensor(image: Image.Image) -> torch.Tensor:
|
| 765 |
+
array = np.asarray(image, dtype=np.uint8).copy()
|
| 766 |
+
return torch.from_numpy(array).permute(2, 0, 1).float().div_(255.0)
|
| 767 |
+
|
| 768 |
+
|
| 769 |
+
class Phase2PairDataset(Dataset):
|
| 770 |
+
"""Aligned native-pair crops; labels are returned only for sampling/logging."""
|
| 771 |
+
|
| 772 |
+
def __init__(
|
| 773 |
+
self,
|
| 774 |
+
records: Sequence[RestorationRecord],
|
| 775 |
+
crop_size: int = 256,
|
| 776 |
+
training: bool = True,
|
| 777 |
+
upscale_small: bool = True,
|
| 778 |
+
) -> None:
|
| 779 |
+
if crop_size <= 0:
|
| 780 |
+
raise ValueError("crop_size must be positive")
|
| 781 |
+
if not records:
|
| 782 |
+
raise ValueError("Phase2PairDataset requires at least one record")
|
| 783 |
+
self.records = tuple(records)
|
| 784 |
+
self.crop_size = int(crop_size)
|
| 785 |
+
self.training = bool(training)
|
| 786 |
+
self.upscale_small = bool(upscale_small)
|
| 787 |
+
|
| 788 |
+
def __len__(self) -> int:
|
| 789 |
+
return len(self.records)
|
| 790 |
+
|
| 791 |
+
def __getitem__(self, item: object) -> Dict[str, object]:
|
| 792 |
+
if self.training:
|
| 793 |
+
if not isinstance(item, (tuple, list)) or len(item) != 2:
|
| 794 |
+
raise TypeError("training items require (record_index, sample_seed)")
|
| 795 |
+
index, sample_seed = item
|
| 796 |
+
if not isinstance(index, (int, np.integer)) or not isinstance(
|
| 797 |
+
sample_seed, (int, np.integer)
|
| 798 |
+
):
|
| 799 |
+
raise TypeError("record_index and sample_seed must be integers")
|
| 800 |
+
effective_sample_seed = int(sample_seed)
|
| 801 |
+
rng = random.Random(effective_sample_seed)
|
| 802 |
+
else:
|
| 803 |
+
if not isinstance(item, (int, np.integer)):
|
| 804 |
+
raise TypeError("validation items require an integer record index")
|
| 805 |
+
index = item
|
| 806 |
+
effective_sample_seed = -1
|
| 807 |
+
rng = None
|
| 808 |
+
index = int(index)
|
| 809 |
+
record = self.records[index]
|
| 810 |
+
degraded, clean = _open_rgb(record.degraded), _open_rgb(record.clean)
|
| 811 |
+
if degraded.size != clean.size:
|
| 812 |
+
raise ValueError(
|
| 813 |
+
"paired images must have the same native size: %s is %r vs %r"
|
| 814 |
+
% (record.record_id, degraded.size, clean.size)
|
| 815 |
+
)
|
| 816 |
+
width, height = degraded.size
|
| 817 |
+
if min(width, height) < self.crop_size:
|
| 818 |
+
if not self.upscale_small:
|
| 819 |
+
raise ValueError("native pair is smaller than crop_size")
|
| 820 |
+
scale = float(self.crop_size) / min(width, height)
|
| 821 |
+
resized = (
|
| 822 |
+
max(self.crop_size, int(math.ceil(width * scale))),
|
| 823 |
+
max(self.crop_size, int(math.ceil(height * scale))),
|
| 824 |
+
)
|
| 825 |
+
degraded = degraded.resize(resized, _LANCZOS)
|
| 826 |
+
clean = clean.resize(resized, _LANCZOS)
|
| 827 |
+
width, height = resized
|
| 828 |
+
if rng is None:
|
| 829 |
+
left = (width - self.crop_size) // 2
|
| 830 |
+
top = (height - self.crop_size) // 2
|
| 831 |
+
flip = False
|
| 832 |
+
else:
|
| 833 |
+
left = rng.randrange(width - self.crop_size + 1)
|
| 834 |
+
top = rng.randrange(height - self.crop_size + 1)
|
| 835 |
+
flip = bool(rng.getrandbits(1))
|
| 836 |
+
box = (left, top, left + self.crop_size, top + self.crop_size)
|
| 837 |
+
# Whole-frame views (aspect-squashed to crop_size) carry the context
|
| 838 |
+
# that lies OUTSIDE the crop — sky/airlight, global exposure, flat
|
| 839 |
+
# regions for noise level — which a crop-only encoder cannot see.
|
| 840 |
+
full_degraded = degraded.resize((self.crop_size, self.crop_size), _LANCZOS)
|
| 841 |
+
full_clean = clean.resize((self.crop_size, self.crop_size), _LANCZOS)
|
| 842 |
+
degraded, clean = degraded.crop(box), clean.crop(box)
|
| 843 |
+
if flip:
|
| 844 |
+
degraded = degraded.transpose(_FLIP_LEFT_RIGHT)
|
| 845 |
+
clean = clean.transpose(_FLIP_LEFT_RIGHT)
|
| 846 |
+
full_degraded = full_degraded.transpose(_FLIP_LEFT_RIGHT)
|
| 847 |
+
full_clean = full_clean.transpose(_FLIP_LEFT_RIGHT)
|
| 848 |
+
return {
|
| 849 |
+
"degraded": _pil_to_tensor(degraded),
|
| 850 |
+
"clean": _pil_to_tensor(clean),
|
| 851 |
+
"full_degraded": _pil_to_tensor(full_degraded),
|
| 852 |
+
"full_clean": _pil_to_tensor(full_clean),
|
| 853 |
+
"label": record.label,
|
| 854 |
+
"degradation": record.degradation,
|
| 855 |
+
"source_id": record.source_id,
|
| 856 |
+
"record_id": record.record_id,
|
| 857 |
+
"sample_seed": effective_sample_seed,
|
| 858 |
+
}
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
def _seed_from_parts(*parts: object) -> int:
|
| 862 |
+
digest = hashlib.sha256(b"SCDC_PHASE2_SAMPLER_V1\0")
|
| 863 |
+
for part in parts:
|
| 864 |
+
digest.update(str(part).encode("utf-8"))
|
| 865 |
+
digest.update(b"\0")
|
| 866 |
+
return int.from_bytes(digest.digest()[:8], "big") % (2 ** 63 - 1)
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
class DeterministicBalancedBatchSampler(Sampler):
|
| 870 |
+
"""Exact local class balance with replayable crop seeds and DDP rank shards."""
|
| 871 |
+
|
| 872 |
+
def __init__(
|
| 873 |
+
self,
|
| 874 |
+
labels: Sequence[int],
|
| 875 |
+
batch_size: int,
|
| 876 |
+
steps: int,
|
| 877 |
+
seed: int,
|
| 878 |
+
start_microstep: int = 0,
|
| 879 |
+
rank: int = 0,
|
| 880 |
+
world_size: int = 1,
|
| 881 |
+
) -> None:
|
| 882 |
+
if batch_size <= 0 or batch_size % len(BRANCH_ORDER):
|
| 883 |
+
raise ValueError("batch_size must be positive and divisible by four")
|
| 884 |
+
if steps <= 0:
|
| 885 |
+
raise ValueError("steps must be positive")
|
| 886 |
+
if start_microstep < 0 or start_microstep > steps:
|
| 887 |
+
raise ValueError("start_microstep must be between zero and steps")
|
| 888 |
+
if world_size <= 0 or rank < 0 or rank >= world_size:
|
| 889 |
+
raise ValueError("rank must satisfy 0 <= rank < world_size")
|
| 890 |
+
self.by_class: List[Tuple[int, ...]] = []
|
| 891 |
+
for class_index in range(len(BRANCH_ORDER)):
|
| 892 |
+
indices = tuple(
|
| 893 |
+
position for position, label in enumerate(labels) if int(label) == class_index
|
| 894 |
+
)
|
| 895 |
+
if not indices:
|
| 896 |
+
raise ValueError("balanced sampler has an empty class")
|
| 897 |
+
self.by_class.append(indices)
|
| 898 |
+
if any(int(label) not in range(len(BRANCH_ORDER)) for label in labels):
|
| 899 |
+
raise ValueError("balanced sampler received an invalid label")
|
| 900 |
+
self.batch_size = int(batch_size)
|
| 901 |
+
self.steps = int(steps)
|
| 902 |
+
self.seed = int(seed)
|
| 903 |
+
self.start_microstep = int(start_microstep)
|
| 904 |
+
self.rank = int(rank)
|
| 905 |
+
self.world_size = int(world_size)
|
| 906 |
+
self.per_class = self.batch_size // len(BRANCH_ORDER)
|
| 907 |
+
|
| 908 |
+
def __len__(self) -> int:
|
| 909 |
+
return self.steps - self.start_microstep
|
| 910 |
+
|
| 911 |
+
def __iter__(self) -> Iterator[List[Tuple[int, int]]]:
|
| 912 |
+
for microstep in range(self.start_microstep, self.steps):
|
| 913 |
+
generator = torch.Generator()
|
| 914 |
+
generator.manual_seed(_seed_from_parts(self.seed, microstep, "draw"))
|
| 915 |
+
local: List[Tuple[int, int]] = []
|
| 916 |
+
global_per_class = self.per_class * self.world_size
|
| 917 |
+
for class_index, indices in enumerate(self.by_class):
|
| 918 |
+
draws = torch.randint(
|
| 919 |
+
len(indices), (global_per_class,), generator=generator
|
| 920 |
+
).tolist()
|
| 921 |
+
start = self.rank * self.per_class
|
| 922 |
+
stop = start + self.per_class
|
| 923 |
+
for global_slot in range(start, stop):
|
| 924 |
+
record_index = indices[draws[global_slot]]
|
| 925 |
+
sample_seed = _seed_from_parts(
|
| 926 |
+
self.seed,
|
| 927 |
+
microstep,
|
| 928 |
+
class_index,
|
| 929 |
+
global_slot,
|
| 930 |
+
record_index,
|
| 931 |
+
"crop",
|
| 932 |
+
)
|
| 933 |
+
local.append((record_index, sample_seed))
|
| 934 |
+
permutation = torch.randperm(len(local), generator=generator).tolist()
|
| 935 |
+
yield [local[position] for position in permutation]
|
| 936 |
+
|
| 937 |
+
|
| 938 |
+
def seed_worker(worker_id: int) -> None:
|
| 939 |
+
del worker_id
|
| 940 |
+
seed = torch.initial_seed() % (2 ** 32)
|
| 941 |
+
random.seed(seed)
|
| 942 |
+
np.random.seed(seed)
|
dataset/phase1_noise_20260906/code/src/data/rain13k_quarantine_v1.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
dataset/phase1_noise_20260906/code/src/data/rain13k_resized.py
ADDED
|
@@ -0,0 +1,721 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Strict, side-effect-free loader for the Kaggle Rain13K-resized dataset.
|
| 2 |
+
|
| 3 |
+
This module only discovers and validates local files. Downloading the dataset is
|
| 4 |
+
an explicit, separate operation handled by ``download_rain13k.py``.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import random
|
| 12 |
+
import re
|
| 13 |
+
from dataclasses import dataclass
|
| 14 |
+
from pathlib import Path, PurePosixPath
|
| 15 |
+
from types import MappingProxyType
|
| 16 |
+
from typing import FrozenSet, Mapping, Optional, Tuple, Union
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
DATASET_HANDLE = "hngphchi/rain13k-resized"
|
| 20 |
+
DATASET_VERSION = 1
|
| 21 |
+
QUARANTINE_SCHEMA_VERSION = 1
|
| 22 |
+
DECODED_RGB_SHA256_SPEC = (
|
| 23 |
+
"sha256(b'SCDC_RGB_V1\\0' || uint32_be(width) || uint32_be(height) || "
|
| 24 |
+
"row_major_RGB_uint8_bytes)"
|
| 25 |
+
)
|
| 26 |
+
FILE_SHA256_SPEC = "sha256(raw on-disk target file bytes)"
|
| 27 |
+
TARGET_INVENTORY_ALGORITHM = (
|
| 28 |
+
"sha256(domain_prefix_bytes || concatenated_sorted_records)"
|
| 29 |
+
)
|
| 30 |
+
TARGET_INVENTORY_DOMAIN_PREFIX = b"SCDC_RAIN13K_TARGET_INVENTORY_V1\0"
|
| 31 |
+
TARGET_INVENTORY_FILE_SELECTION = (
|
| 32 |
+
"regular files that are immediate children of each included_target_dirs "
|
| 33 |
+
"entry; relative paths are POSIX paths rooted at the Kaggle dataset "
|
| 34 |
+
"version directory"
|
| 35 |
+
)
|
| 36 |
+
TARGET_INVENTORY_RECORD_FORMAT = (
|
| 37 |
+
"relative_path_utf8 || 0x00 || lowercase_raw_file_sha256_hex_ascii || 0x0a"
|
| 38 |
+
)
|
| 39 |
+
TARGET_INVENTORY_SORT_ORDER = (
|
| 40 |
+
"ascending lexicographic order of relative_path UTF-8 bytes"
|
| 41 |
+
)
|
| 42 |
+
TARGET_INVENTORY_DIRS = (
|
| 43 |
+
"train_resized/target",
|
| 44 |
+
"test_resized/Rain100H/target",
|
| 45 |
+
"test_resized/Rain100L/target",
|
| 46 |
+
"test_resized/Test100/target",
|
| 47 |
+
"test_resized/Test1200/target",
|
| 48 |
+
"test_resized/Test2800/target",
|
| 49 |
+
)
|
| 50 |
+
SUPPORTED_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png"})
|
| 51 |
+
OFFICIAL_TEST_SETS = ("Rain100H", "Rain100L", "Test100", "Test1200", "Test2800")
|
| 52 |
+
_SHA256_HEX = re.compile(r"^[0-9a-fA-F]{64}$")
|
| 53 |
+
|
| 54 |
+
ImagePair = Tuple[Path, Path]
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@dataclass(frozen=True)
|
| 58 |
+
class Rain13KResizedSplits:
|
| 59 |
+
"""Validated train pairs and isolated official-test pairs."""
|
| 60 |
+
|
| 61 |
+
train_pairs: Tuple[ImagePair, ...]
|
| 62 |
+
official_test_pairs: Mapping[str, Tuple[ImagePair, ...]]
|
| 63 |
+
quarantined_train_pair_count: int
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
@dataclass(frozen=True)
|
| 67 |
+
class _QuarantineSpec:
|
| 68 |
+
file_hashes: FrozenSet[str]
|
| 69 |
+
expected_hash_by_relative_path: Mapping[str, str]
|
| 70 |
+
expected_pair_count: int
|
| 71 |
+
expected_evidence_count: int
|
| 72 |
+
train_pair_count: int
|
| 73 |
+
official_test_pair_count: int
|
| 74 |
+
total_pair_count: int
|
| 75 |
+
target_inventory_digest: str
|
| 76 |
+
inventory_record_count_by_dir: Mapping[str, int]
|
| 77 |
+
inventory_raw_bytes_by_dir: Mapping[str, int]
|
| 78 |
+
inventory_total_raw_bytes: int
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _supported_files(directory: Path) -> Mapping[str, Path]:
|
| 82 |
+
files = (
|
| 83 |
+
path
|
| 84 |
+
for path in directory.rglob("*")
|
| 85 |
+
if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS
|
| 86 |
+
)
|
| 87 |
+
return {
|
| 88 |
+
path.relative_to(directory).as_posix(): path
|
| 89 |
+
for path in sorted(files, key=lambda item: item.relative_to(directory).as_posix())
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _preview(names: Tuple[str, ...], limit: int = 5) -> str:
|
| 94 |
+
displayed = ", ".join(names[:limit])
|
| 95 |
+
remaining = len(names) - limit
|
| 96 |
+
if remaining > 0:
|
| 97 |
+
displayed += f", ... (+{remaining} more)"
|
| 98 |
+
return displayed
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _load_bijective_pairs(split_root: Path, label: str) -> Tuple[ImagePair, ...]:
|
| 102 |
+
input_dir = split_root / "input"
|
| 103 |
+
target_dir = split_root / "target"
|
| 104 |
+
for role, directory in (("input", input_dir), ("target", target_dir)):
|
| 105 |
+
if not directory.exists():
|
| 106 |
+
raise FileNotFoundError(
|
| 107 |
+
f"Rain13K-resized {label} is missing required {role} directory: "
|
| 108 |
+
f"{directory}"
|
| 109 |
+
)
|
| 110 |
+
if not directory.is_dir():
|
| 111 |
+
raise NotADirectoryError(
|
| 112 |
+
f"Rain13K-resized {label} {role} path is not a directory: "
|
| 113 |
+
f"{directory}"
|
| 114 |
+
)
|
| 115 |
+
|
| 116 |
+
input_files = _supported_files(input_dir)
|
| 117 |
+
target_files = _supported_files(target_dir)
|
| 118 |
+
if not input_files and not target_files:
|
| 119 |
+
raise ValueError(
|
| 120 |
+
f"Rain13K-resized {label} contains no supported image files "
|
| 121 |
+
f"({', '.join(sorted(SUPPORTED_EXTENSIONS))})"
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
input_names = set(input_files)
|
| 125 |
+
target_names = set(target_files)
|
| 126 |
+
missing_targets = tuple(sorted(input_names - target_names))
|
| 127 |
+
missing_inputs = tuple(sorted(target_names - input_names))
|
| 128 |
+
if missing_targets or missing_inputs:
|
| 129 |
+
details = []
|
| 130 |
+
if missing_targets:
|
| 131 |
+
details.append(f"missing target for: {_preview(missing_targets)}")
|
| 132 |
+
if missing_inputs:
|
| 133 |
+
details.append(f"missing input for: {_preview(missing_inputs)}")
|
| 134 |
+
raise ValueError(
|
| 135 |
+
f"Rain13K-resized {label} input/target pairing mismatch by exact "
|
| 136 |
+
f"relative filename; {'; '.join(details)}"
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
return tuple(
|
| 140 |
+
(input_files[relative_name], target_files[relative_name])
|
| 141 |
+
for relative_name in sorted(input_names)
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _validated_sha256(value: object, label: str) -> str:
|
| 146 |
+
if not isinstance(value, str) or _SHA256_HEX.fullmatch(value) is None:
|
| 147 |
+
raise ValueError(f"Rain13K quarantine manifest {label} must be 64 hex digits")
|
| 148 |
+
return value.lower()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _required_nonnegative_int(
|
| 152 |
+
mapping: Mapping[str, object],
|
| 153 |
+
key: str,
|
| 154 |
+
label: str,
|
| 155 |
+
) -> int:
|
| 156 |
+
value = mapping.get(key)
|
| 157 |
+
if isinstance(value, bool) or not isinstance(value, int) or value < 0:
|
| 158 |
+
raise ValueError(
|
| 159 |
+
f"Rain13K quarantine manifest {label}.{key} must be a "
|
| 160 |
+
"non-negative integer"
|
| 161 |
+
)
|
| 162 |
+
return value
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _required_directory_counts(
|
| 166 |
+
value: object,
|
| 167 |
+
label: str,
|
| 168 |
+
) -> Mapping[str, int]:
|
| 169 |
+
if not isinstance(value, dict) or set(value) != set(TARGET_INVENTORY_DIRS):
|
| 170 |
+
raise ValueError(
|
| 171 |
+
f"Rain13K quarantine manifest {label} must contain exactly the six "
|
| 172 |
+
"target inventory directories"
|
| 173 |
+
)
|
| 174 |
+
counts = {
|
| 175 |
+
relative_dir: _required_nonnegative_int(value, relative_dir, label)
|
| 176 |
+
for relative_dir in TARGET_INVENTORY_DIRS
|
| 177 |
+
}
|
| 178 |
+
return MappingProxyType(counts)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _load_quarantine_manifest(path: Union[str, Path]) -> _QuarantineSpec:
|
| 182 |
+
manifest_path = Path(path).expanduser()
|
| 183 |
+
if not manifest_path.exists():
|
| 184 |
+
raise FileNotFoundError(
|
| 185 |
+
f"Rain13K quarantine manifest does not exist: {manifest_path}"
|
| 186 |
+
)
|
| 187 |
+
if not manifest_path.is_file():
|
| 188 |
+
raise ValueError(
|
| 189 |
+
f"Rain13K quarantine manifest is not a regular file: {manifest_path}"
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
try:
|
| 193 |
+
payload = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 194 |
+
except (OSError, UnicodeError, json.JSONDecodeError) as exc:
|
| 195 |
+
raise ValueError(
|
| 196 |
+
f"Rain13K quarantine manifest has malformed JSON: {manifest_path}: {exc}"
|
| 197 |
+
) from exc
|
| 198 |
+
if not isinstance(payload, dict):
|
| 199 |
+
raise ValueError("Rain13K quarantine manifest root must be a JSON object")
|
| 200 |
+
|
| 201 |
+
schema_version = payload.get("schema_version")
|
| 202 |
+
if (
|
| 203 |
+
isinstance(schema_version, bool)
|
| 204 |
+
or not isinstance(schema_version, int)
|
| 205 |
+
or schema_version != QUARANTINE_SCHEMA_VERSION
|
| 206 |
+
):
|
| 207 |
+
raise ValueError(
|
| 208 |
+
"Rain13K quarantine manifest schema_version must be "
|
| 209 |
+
f"{QUARANTINE_SCHEMA_VERSION}, got {schema_version!r}"
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
dataset = payload.get("dataset")
|
| 213 |
+
if not isinstance(dataset, dict):
|
| 214 |
+
raise ValueError("Rain13K quarantine manifest dataset must be an object")
|
| 215 |
+
if dataset.get("handle") != DATASET_HANDLE:
|
| 216 |
+
raise ValueError(
|
| 217 |
+
"Rain13K quarantine manifest dataset handle must be "
|
| 218 |
+
f"{DATASET_HANDLE!r}, got {dataset.get('handle')!r}"
|
| 219 |
+
)
|
| 220 |
+
dataset_version = dataset.get("version")
|
| 221 |
+
if (
|
| 222 |
+
isinstance(dataset_version, bool)
|
| 223 |
+
or not isinstance(dataset_version, int)
|
| 224 |
+
or dataset_version != DATASET_VERSION
|
| 225 |
+
):
|
| 226 |
+
raise ValueError(
|
| 227 |
+
"Rain13K quarantine manifest dataset version must be "
|
| 228 |
+
f"{DATASET_VERSION}, got {dataset_version!r}"
|
| 229 |
+
)
|
| 230 |
+
|
| 231 |
+
train_pair_count = _required_nonnegative_int(
|
| 232 |
+
dataset,
|
| 233 |
+
"train_pair_count",
|
| 234 |
+
"dataset",
|
| 235 |
+
)
|
| 236 |
+
official_test_pair_count = _required_nonnegative_int(
|
| 237 |
+
dataset,
|
| 238 |
+
"official_test_pair_count",
|
| 239 |
+
"dataset",
|
| 240 |
+
)
|
| 241 |
+
total_pair_count = _required_nonnegative_int(
|
| 242 |
+
dataset,
|
| 243 |
+
"total_pair_count",
|
| 244 |
+
"dataset",
|
| 245 |
+
)
|
| 246 |
+
if train_pair_count + official_test_pair_count != total_pair_count:
|
| 247 |
+
raise ValueError(
|
| 248 |
+
"Rain13K quarantine manifest dataset pair counts are inconsistent"
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
inventory = dataset.get("target_inventory_v1")
|
| 252 |
+
if not isinstance(inventory, dict):
|
| 253 |
+
raise ValueError(
|
| 254 |
+
"Rain13K quarantine manifest dataset.target_inventory_v1 must be "
|
| 255 |
+
"an object"
|
| 256 |
+
)
|
| 257 |
+
exact_inventory_strings = {
|
| 258 |
+
"algorithm": TARGET_INVENTORY_ALGORITHM,
|
| 259 |
+
"domain_prefix_hex": TARGET_INVENTORY_DOMAIN_PREFIX.hex(),
|
| 260 |
+
"file_selection": TARGET_INVENTORY_FILE_SELECTION,
|
| 261 |
+
"record_format": TARGET_INVENTORY_RECORD_FORMAT,
|
| 262 |
+
"sort_order": TARGET_INVENTORY_SORT_ORDER,
|
| 263 |
+
}
|
| 264 |
+
for key, expected in exact_inventory_strings.items():
|
| 265 |
+
if inventory.get(key) != expected:
|
| 266 |
+
raise ValueError(
|
| 267 |
+
"Rain13K quarantine manifest target inventory specification "
|
| 268 |
+
f"mismatch for {key}: expected {expected!r}, "
|
| 269 |
+
f"got {inventory.get(key)!r}"
|
| 270 |
+
)
|
| 271 |
+
if inventory.get("included_target_dirs") != list(TARGET_INVENTORY_DIRS):
|
| 272 |
+
raise ValueError(
|
| 273 |
+
"Rain13K quarantine manifest target inventory directories do not "
|
| 274 |
+
"match the v1 specification"
|
| 275 |
+
)
|
| 276 |
+
target_inventory_digest = _validated_sha256(
|
| 277 |
+
inventory.get("digest_sha256"),
|
| 278 |
+
"dataset.target_inventory_v1.digest_sha256",
|
| 279 |
+
)
|
| 280 |
+
inventory_record_count = _required_nonnegative_int(
|
| 281 |
+
inventory,
|
| 282 |
+
"record_count",
|
| 283 |
+
"dataset.target_inventory_v1",
|
| 284 |
+
)
|
| 285 |
+
inventory_total_raw_bytes = _required_nonnegative_int(
|
| 286 |
+
inventory,
|
| 287 |
+
"total_raw_bytes",
|
| 288 |
+
"dataset.target_inventory_v1",
|
| 289 |
+
)
|
| 290 |
+
inventory_record_count_by_dir = _required_directory_counts(
|
| 291 |
+
inventory.get("record_count_by_dir"),
|
| 292 |
+
"dataset.target_inventory_v1.record_count_by_dir",
|
| 293 |
+
)
|
| 294 |
+
inventory_raw_bytes_by_dir = _required_directory_counts(
|
| 295 |
+
inventory.get("raw_bytes_by_dir"),
|
| 296 |
+
"dataset.target_inventory_v1.raw_bytes_by_dir",
|
| 297 |
+
)
|
| 298 |
+
if sum(inventory_record_count_by_dir.values()) != inventory_record_count:
|
| 299 |
+
raise ValueError(
|
| 300 |
+
"Rain13K quarantine manifest target inventory record counts are "
|
| 301 |
+
"inconsistent"
|
| 302 |
+
)
|
| 303 |
+
if sum(inventory_raw_bytes_by_dir.values()) != inventory_total_raw_bytes:
|
| 304 |
+
raise ValueError(
|
| 305 |
+
"Rain13K quarantine manifest target inventory raw byte counts are "
|
| 306 |
+
"inconsistent"
|
| 307 |
+
)
|
| 308 |
+
if inventory_record_count != total_pair_count:
|
| 309 |
+
raise ValueError(
|
| 310 |
+
"Rain13K quarantine manifest target inventory record count must "
|
| 311 |
+
"equal dataset.total_pair_count"
|
| 312 |
+
)
|
| 313 |
+
if (
|
| 314 |
+
inventory_record_count_by_dir["train_resized/target"]
|
| 315 |
+
!= train_pair_count
|
| 316 |
+
):
|
| 317 |
+
raise ValueError(
|
| 318 |
+
"Rain13K quarantine manifest train target inventory count does not "
|
| 319 |
+
"match dataset.train_pair_count"
|
| 320 |
+
)
|
| 321 |
+
if (
|
| 322 |
+
inventory_record_count - train_pair_count
|
| 323 |
+
!= official_test_pair_count
|
| 324 |
+
):
|
| 325 |
+
raise ValueError(
|
| 326 |
+
"Rain13K quarantine manifest official target inventory count does "
|
| 327 |
+
"not match dataset.official_test_pair_count"
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
hash_spec = payload.get("hash_spec")
|
| 331 |
+
expected_hash_spec = {
|
| 332 |
+
"decoded_rgb_sha256": DECODED_RGB_SHA256_SPEC,
|
| 333 |
+
"file_sha256": FILE_SHA256_SPEC,
|
| 334 |
+
}
|
| 335 |
+
if hash_spec != expected_hash_spec:
|
| 336 |
+
raise ValueError(
|
| 337 |
+
"Rain13K quarantine manifest hash_spec does not exactly match the "
|
| 338 |
+
"v1 hash specification"
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
summary = payload.get("summary")
|
| 342 |
+
if not isinstance(summary, dict):
|
| 343 |
+
raise ValueError("Rain13K quarantine manifest summary must be an object")
|
| 344 |
+
expected_pair_count = _required_nonnegative_int(
|
| 345 |
+
summary,
|
| 346 |
+
"affected_train_pairs",
|
| 347 |
+
"summary",
|
| 348 |
+
)
|
| 349 |
+
expected_group_count = _required_nonnegative_int(
|
| 350 |
+
summary,
|
| 351 |
+
"excluded_train_target_groups",
|
| 352 |
+
"summary",
|
| 353 |
+
)
|
| 354 |
+
expected_evidence_count = _required_nonnegative_int(
|
| 355 |
+
summary,
|
| 356 |
+
"evidence_edges",
|
| 357 |
+
"summary",
|
| 358 |
+
)
|
| 359 |
+
expected_unique_hashes = _required_nonnegative_int(
|
| 360 |
+
summary,
|
| 361 |
+
"unique_excluded_train_file_sha256",
|
| 362 |
+
"summary",
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
groups = payload.get("excluded_train_targets")
|
| 366 |
+
if not isinstance(groups, list):
|
| 367 |
+
raise ValueError(
|
| 368 |
+
"Rain13K quarantine manifest excluded_train_targets must be an array"
|
| 369 |
+
)
|
| 370 |
+
if len(groups) != expected_group_count:
|
| 371 |
+
raise ValueError(
|
| 372 |
+
"Rain13K quarantine manifest group count mismatch: summary declares "
|
| 373 |
+
f"{expected_group_count}, found {len(groups)}"
|
| 374 |
+
)
|
| 375 |
+
|
| 376 |
+
target_hashes = {}
|
| 377 |
+
file_hashes = set()
|
| 378 |
+
evidence_count = 0
|
| 379 |
+
for group_index, group in enumerate(groups):
|
| 380 |
+
if not isinstance(group, dict):
|
| 381 |
+
raise ValueError(
|
| 382 |
+
"Rain13K quarantine manifest excluded_train_targets"
|
| 383 |
+
f"[{group_index}] must be an object"
|
| 384 |
+
)
|
| 385 |
+
_validated_sha256(
|
| 386 |
+
group.get("decoded_rgb_sha256"),
|
| 387 |
+
f"excluded_train_targets[{group_index}].decoded_rgb_sha256",
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
evidence_items = group.get("evidence")
|
| 391 |
+
if not isinstance(evidence_items, list):
|
| 392 |
+
raise ValueError(
|
| 393 |
+
"Rain13K quarantine manifest excluded_train_targets"
|
| 394 |
+
f"[{group_index}].evidence must be an array"
|
| 395 |
+
)
|
| 396 |
+
evidence_count += len(evidence_items)
|
| 397 |
+
for evidence_index, evidence in enumerate(evidence_items):
|
| 398 |
+
if not isinstance(evidence, dict):
|
| 399 |
+
raise ValueError(
|
| 400 |
+
"Rain13K quarantine manifest evidence entry must be an object"
|
| 401 |
+
)
|
| 402 |
+
_validated_sha256(
|
| 403 |
+
evidence.get("test_decoded_rgb_sha256"),
|
| 404 |
+
"excluded_train_targets"
|
| 405 |
+
f"[{group_index}].evidence[{evidence_index}]"
|
| 406 |
+
".test_decoded_rgb_sha256",
|
| 407 |
+
)
|
| 408 |
+
|
| 409 |
+
train_targets = group.get("train_targets")
|
| 410 |
+
if not isinstance(train_targets, list) or not train_targets:
|
| 411 |
+
raise ValueError(
|
| 412 |
+
"Rain13K quarantine manifest excluded_train_targets"
|
| 413 |
+
f"[{group_index}].train_targets must be a non-empty array"
|
| 414 |
+
)
|
| 415 |
+
for target_index, target in enumerate(train_targets):
|
| 416 |
+
if not isinstance(target, dict):
|
| 417 |
+
raise ValueError(
|
| 418 |
+
"Rain13K quarantine manifest train target entry must be an object"
|
| 419 |
+
)
|
| 420 |
+
relative_path = target.get("relative_path")
|
| 421 |
+
if not isinstance(relative_path, str) or not relative_path:
|
| 422 |
+
raise ValueError(
|
| 423 |
+
"Rain13K quarantine manifest train target relative_path "
|
| 424 |
+
"must be a non-empty string"
|
| 425 |
+
)
|
| 426 |
+
normalized = PurePosixPath(relative_path)
|
| 427 |
+
if (
|
| 428 |
+
normalized.is_absolute()
|
| 429 |
+
or normalized.as_posix() != relative_path
|
| 430 |
+
or normalized.parts[:2] != ("train_resized", "target")
|
| 431 |
+
or len(normalized.parts) < 3
|
| 432 |
+
or ".." in normalized.parts
|
| 433 |
+
):
|
| 434 |
+
raise ValueError(
|
| 435 |
+
"Rain13K quarantine manifest train target relative_path must "
|
| 436 |
+
"be canonical and under train_resized/target: "
|
| 437 |
+
f"{relative_path!r}"
|
| 438 |
+
)
|
| 439 |
+
if relative_path in target_hashes:
|
| 440 |
+
raise ValueError(
|
| 441 |
+
"Rain13K quarantine manifest contains duplicate train target "
|
| 442 |
+
f"path: {relative_path}"
|
| 443 |
+
)
|
| 444 |
+
file_hash = _validated_sha256(
|
| 445 |
+
target.get("file_sha256"),
|
| 446 |
+
"excluded_train_targets"
|
| 447 |
+
f"[{group_index}].train_targets[{target_index}].file_sha256",
|
| 448 |
+
)
|
| 449 |
+
target_hashes[relative_path] = file_hash
|
| 450 |
+
file_hashes.add(file_hash)
|
| 451 |
+
|
| 452 |
+
if len(target_hashes) != expected_pair_count:
|
| 453 |
+
raise ValueError(
|
| 454 |
+
"Rain13K quarantine manifest affected pair count mismatch: summary "
|
| 455 |
+
f"declares {expected_pair_count}, found {len(target_hashes)}"
|
| 456 |
+
)
|
| 457 |
+
if expected_unique_hashes != len(file_hashes):
|
| 458 |
+
raise ValueError(
|
| 459 |
+
"Rain13K quarantine manifest unique file SHA256 count mismatch: "
|
| 460 |
+
f"summary declares {expected_unique_hashes!r}, found {len(file_hashes)}"
|
| 461 |
+
)
|
| 462 |
+
if evidence_count != expected_evidence_count:
|
| 463 |
+
raise ValueError(
|
| 464 |
+
"Rain13K quarantine manifest evidence count mismatch: summary "
|
| 465 |
+
f"declares {expected_evidence_count}, found {evidence_count}"
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
per_test = payload.get("per_test")
|
| 469 |
+
if not isinstance(per_test, dict) or set(per_test) != set(OFFICIAL_TEST_SETS):
|
| 470 |
+
raise ValueError(
|
| 471 |
+
"Rain13K quarantine manifest per_test must contain exactly the five "
|
| 472 |
+
"official test sets"
|
| 473 |
+
)
|
| 474 |
+
for test_name in OFFICIAL_TEST_SETS:
|
| 475 |
+
test_summary = per_test[test_name]
|
| 476 |
+
if not isinstance(test_summary, dict):
|
| 477 |
+
raise ValueError(
|
| 478 |
+
f"Rain13K quarantine manifest per_test.{test_name} must be an object"
|
| 479 |
+
)
|
| 480 |
+
implicated_hashes = test_summary.get(
|
| 481 |
+
"implicated_train_decoded_rgb_sha256"
|
| 482 |
+
)
|
| 483 |
+
if not isinstance(implicated_hashes, list):
|
| 484 |
+
raise ValueError(
|
| 485 |
+
"Rain13K quarantine manifest "
|
| 486 |
+
f"per_test.{test_name}.implicated_train_decoded_rgb_sha256 "
|
| 487 |
+
"must be an array"
|
| 488 |
+
)
|
| 489 |
+
for hash_index, decoded_hash in enumerate(implicated_hashes):
|
| 490 |
+
_validated_sha256(
|
| 491 |
+
decoded_hash,
|
| 492 |
+
f"per_test.{test_name}.implicated_train_decoded_rgb_sha256"
|
| 493 |
+
f"[{hash_index}]",
|
| 494 |
+
)
|
| 495 |
+
|
| 496 |
+
return _QuarantineSpec(
|
| 497 |
+
file_hashes=frozenset(file_hashes),
|
| 498 |
+
expected_hash_by_relative_path=MappingProxyType(target_hashes),
|
| 499 |
+
expected_pair_count=expected_pair_count,
|
| 500 |
+
expected_evidence_count=expected_evidence_count,
|
| 501 |
+
train_pair_count=train_pair_count,
|
| 502 |
+
official_test_pair_count=official_test_pair_count,
|
| 503 |
+
total_pair_count=total_pair_count,
|
| 504 |
+
target_inventory_digest=target_inventory_digest,
|
| 505 |
+
inventory_record_count_by_dir=inventory_record_count_by_dir,
|
| 506 |
+
inventory_raw_bytes_by_dir=inventory_raw_bytes_by_dir,
|
| 507 |
+
inventory_total_raw_bytes=inventory_total_raw_bytes,
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
def _sha256_file(path: Path) -> str:
|
| 512 |
+
digest = hashlib.sha256()
|
| 513 |
+
with path.open("rb") as source:
|
| 514 |
+
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
| 515 |
+
digest.update(chunk)
|
| 516 |
+
return digest.hexdigest()
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _verify_target_inventory(
|
| 520 |
+
dataset_root: Path,
|
| 521 |
+
train_pairs: Tuple[ImagePair, ...],
|
| 522 |
+
official_test_pairs: Mapping[str, Tuple[ImagePair, ...]],
|
| 523 |
+
spec: _QuarantineSpec,
|
| 524 |
+
) -> Mapping[str, str]:
|
| 525 |
+
if len(train_pairs) != spec.train_pair_count:
|
| 526 |
+
raise ValueError(
|
| 527 |
+
"Rain13K v1 train pair count mismatch: expected "
|
| 528 |
+
f"{spec.train_pair_count}, got {len(train_pairs)}"
|
| 529 |
+
)
|
| 530 |
+
observed_official_pairs = sum(len(pairs) for pairs in official_test_pairs.values())
|
| 531 |
+
if observed_official_pairs != spec.official_test_pair_count:
|
| 532 |
+
raise ValueError(
|
| 533 |
+
"Rain13K v1 official test pair count mismatch: expected "
|
| 534 |
+
f"{spec.official_test_pair_count}, got {observed_official_pairs}"
|
| 535 |
+
)
|
| 536 |
+
if len(train_pairs) + observed_official_pairs != spec.total_pair_count:
|
| 537 |
+
raise ValueError("Rain13K v1 total pair count does not match the manifest")
|
| 538 |
+
for test_name, pairs in official_test_pairs.items():
|
| 539 |
+
relative_dir = f"test_resized/{test_name}/target"
|
| 540 |
+
expected_count = spec.inventory_record_count_by_dir[relative_dir]
|
| 541 |
+
if len(pairs) != expected_count:
|
| 542 |
+
raise ValueError(
|
| 543 |
+
f"Rain13K v1 {test_name} pair count mismatch: expected "
|
| 544 |
+
f"{expected_count}, got {len(pairs)}"
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
records = []
|
| 548 |
+
target_hashes = {}
|
| 549 |
+
observed_record_counts = {}
|
| 550 |
+
observed_raw_bytes = {}
|
| 551 |
+
for relative_dir in TARGET_INVENTORY_DIRS:
|
| 552 |
+
target_dir = dataset_root / relative_dir
|
| 553 |
+
target_files = tuple(path for path in target_dir.iterdir() if path.is_file())
|
| 554 |
+
observed_record_counts[relative_dir] = len(target_files)
|
| 555 |
+
observed_raw_bytes[relative_dir] = sum(
|
| 556 |
+
path.stat().st_size for path in target_files
|
| 557 |
+
)
|
| 558 |
+
for target_path in target_files:
|
| 559 |
+
relative_path = target_path.relative_to(dataset_root).as_posix()
|
| 560 |
+
file_hash = _sha256_file(target_path)
|
| 561 |
+
records.append((relative_path, file_hash))
|
| 562 |
+
target_hashes[relative_path] = file_hash
|
| 563 |
+
|
| 564 |
+
if observed_record_counts != dict(spec.inventory_record_count_by_dir):
|
| 565 |
+
raise ValueError(
|
| 566 |
+
"Rain13K v1 target inventory record counts do not match the manifest"
|
| 567 |
+
)
|
| 568 |
+
if observed_raw_bytes != dict(spec.inventory_raw_bytes_by_dir):
|
| 569 |
+
raise ValueError(
|
| 570 |
+
"Rain13K v1 target inventory raw byte counts do not match the manifest"
|
| 571 |
+
)
|
| 572 |
+
if sum(observed_raw_bytes.values()) != spec.inventory_total_raw_bytes:
|
| 573 |
+
raise ValueError(
|
| 574 |
+
"Rain13K v1 target inventory total raw bytes do not match the manifest"
|
| 575 |
+
)
|
| 576 |
+
|
| 577 |
+
inventory_digest = hashlib.sha256(TARGET_INVENTORY_DOMAIN_PREFIX)
|
| 578 |
+
for relative_path, file_hash in sorted(
|
| 579 |
+
records,
|
| 580 |
+
key=lambda record: record[0].encode("utf-8"),
|
| 581 |
+
):
|
| 582 |
+
inventory_digest.update(relative_path.encode("utf-8"))
|
| 583 |
+
inventory_digest.update(b"\0")
|
| 584 |
+
inventory_digest.update(file_hash.encode("ascii"))
|
| 585 |
+
inventory_digest.update(b"\n")
|
| 586 |
+
actual_inventory_digest = inventory_digest.hexdigest()
|
| 587 |
+
if actual_inventory_digest != spec.target_inventory_digest:
|
| 588 |
+
raise ValueError(
|
| 589 |
+
"Rain13K v1 target inventory digest mismatch: expected "
|
| 590 |
+
f"{spec.target_inventory_digest}, got {actual_inventory_digest}"
|
| 591 |
+
)
|
| 592 |
+
|
| 593 |
+
return MappingProxyType(target_hashes)
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def _apply_quarantine(
|
| 597 |
+
dataset_root: Path,
|
| 598 |
+
train_pairs: Tuple[ImagePair, ...],
|
| 599 |
+
spec: _QuarantineSpec,
|
| 600 |
+
target_hashes: Mapping[str, str],
|
| 601 |
+
) -> Tuple[Tuple[ImagePair, ...], int]:
|
| 602 |
+
kept_pairs = []
|
| 603 |
+
seen_manifest_paths = set()
|
| 604 |
+
quarantined_count = 0
|
| 605 |
+
|
| 606 |
+
for pair in train_pairs:
|
| 607 |
+
target_path = pair[1]
|
| 608 |
+
relative_path = target_path.relative_to(dataset_root).as_posix()
|
| 609 |
+
actual_hash = target_hashes.get(relative_path)
|
| 610 |
+
if actual_hash is None:
|
| 611 |
+
raise ValueError(
|
| 612 |
+
"Rain13K v1 target inventory omitted train target: "
|
| 613 |
+
f"{relative_path}"
|
| 614 |
+
)
|
| 615 |
+
expected_hash = spec.expected_hash_by_relative_path.get(relative_path)
|
| 616 |
+
if expected_hash is not None:
|
| 617 |
+
seen_manifest_paths.add(relative_path)
|
| 618 |
+
if actual_hash != expected_hash:
|
| 619 |
+
raise ValueError(
|
| 620 |
+
"Rain13K quarantine manifest file_sha256 mismatch for "
|
| 621 |
+
f"{relative_path}: expected {expected_hash}, got {actual_hash}"
|
| 622 |
+
)
|
| 623 |
+
|
| 624 |
+
if actual_hash in spec.file_hashes:
|
| 625 |
+
quarantined_count += 1
|
| 626 |
+
else:
|
| 627 |
+
kept_pairs.append(pair)
|
| 628 |
+
|
| 629 |
+
missing_paths = sorted(
|
| 630 |
+
set(spec.expected_hash_by_relative_path) - seen_manifest_paths
|
| 631 |
+
)
|
| 632 |
+
if missing_paths:
|
| 633 |
+
raise ValueError(
|
| 634 |
+
"Rain13K quarantine manifest references train targets absent from "
|
| 635 |
+
f"this dataset: {_preview(tuple(missing_paths))}"
|
| 636 |
+
)
|
| 637 |
+
if quarantined_count != spec.expected_pair_count:
|
| 638 |
+
raise ValueError(
|
| 639 |
+
"Rain13K quarantine manifest matched an unexpected number of train "
|
| 640 |
+
f"pairs: expected {spec.expected_pair_count}, got {quarantined_count}"
|
| 641 |
+
)
|
| 642 |
+
|
| 643 |
+
return tuple(kept_pairs), quarantined_count
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def _validate_max_train_pairs(max_train_pairs: Optional[int]) -> None:
|
| 647 |
+
if max_train_pairs is None:
|
| 648 |
+
return
|
| 649 |
+
if isinstance(max_train_pairs, bool) or not isinstance(max_train_pairs, int):
|
| 650 |
+
raise TypeError("max_train_pairs must be an integer, zero, or None")
|
| 651 |
+
if max_train_pairs < 0:
|
| 652 |
+
raise ValueError("max_train_pairs must be non-negative")
|
| 653 |
+
|
| 654 |
+
|
| 655 |
+
def load_rain13k_resized(
|
| 656 |
+
root: Union[str, Path],
|
| 657 |
+
max_train_pairs: Optional[int] = 0,
|
| 658 |
+
seed: int = 42,
|
| 659 |
+
quarantine_manifest: Optional[Union[str, Path]] = None,
|
| 660 |
+
) -> Rain13KResizedSplits:
|
| 661 |
+
"""Load local Rain13K-resized pairs after strict structure validation.
|
| 662 |
+
|
| 663 |
+
A configured quarantine manifest is verified against dataset version 1 and
|
| 664 |
+
applied to raw target-file SHA256 hashes before ``max_train_pairs``. A cap
|
| 665 |
+
of zero or ``None`` retains every non-quarantined train pair. Official test
|
| 666 |
+
pairs are always returned separately and are never merged into training.
|
| 667 |
+
"""
|
| 668 |
+
|
| 669 |
+
dataset_root = Path(root).expanduser()
|
| 670 |
+
if not dataset_root.exists():
|
| 671 |
+
raise FileNotFoundError(
|
| 672 |
+
f"Rain13K-resized root does not exist: {dataset_root}. "
|
| 673 |
+
"Run download_rain13k.py and pass its resolved path via "
|
| 674 |
+
"--rain13k-root."
|
| 675 |
+
)
|
| 676 |
+
if not dataset_root.is_dir():
|
| 677 |
+
raise NotADirectoryError(
|
| 678 |
+
f"Rain13K-resized root is not a directory: {dataset_root}"
|
| 679 |
+
)
|
| 680 |
+
dataset_root = dataset_root.resolve()
|
| 681 |
+
_validate_max_train_pairs(max_train_pairs)
|
| 682 |
+
|
| 683 |
+
train_pairs = _load_bijective_pairs(
|
| 684 |
+
dataset_root / "train_resized",
|
| 685 |
+
"train_resized",
|
| 686 |
+
)
|
| 687 |
+
official_test_pairs = {
|
| 688 |
+
test_name: _load_bijective_pairs(
|
| 689 |
+
dataset_root / "test_resized" / test_name,
|
| 690 |
+
f"test_resized/{test_name}",
|
| 691 |
+
)
|
| 692 |
+
for test_name in OFFICIAL_TEST_SETS
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
quarantined_train_pair_count = 0
|
| 696 |
+
if quarantine_manifest is not None:
|
| 697 |
+
quarantine_spec = _load_quarantine_manifest(quarantine_manifest)
|
| 698 |
+
target_hashes = _verify_target_inventory(
|
| 699 |
+
dataset_root,
|
| 700 |
+
train_pairs,
|
| 701 |
+
official_test_pairs,
|
| 702 |
+
quarantine_spec,
|
| 703 |
+
)
|
| 704 |
+
train_pairs, quarantined_train_pair_count = _apply_quarantine(
|
| 705 |
+
dataset_root,
|
| 706 |
+
train_pairs,
|
| 707 |
+
quarantine_spec,
|
| 708 |
+
target_hashes,
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
if max_train_pairs is not None and 0 < max_train_pairs < len(train_pairs):
|
| 712 |
+
selected_indices = sorted(
|
| 713 |
+
random.Random(seed).sample(range(len(train_pairs)), max_train_pairs)
|
| 714 |
+
)
|
| 715 |
+
train_pairs = tuple(train_pairs[index] for index in selected_indices)
|
| 716 |
+
|
| 717 |
+
return Rain13KResizedSplits(
|
| 718 |
+
train_pairs=train_pairs,
|
| 719 |
+
official_test_pairs=MappingProxyType(official_test_pairs),
|
| 720 |
+
quarantined_train_pair_count=quarantined_train_pair_count,
|
| 721 |
+
)
|
dataset/phase1_noise_20260906/code/src/models/__init__.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Models package for SCDC.
|
| 2 |
+
|
| 3 |
+
Deployed Phase-1 lives in :mod:`src.models.graph_encoder`; Phase-2 restoration
|
| 4 |
+
stacks live in :mod:`src.models.restoration`. The dual-domain degradation
|
| 5 |
+
transformer (:mod:`src.models.degradation`) is kept as the spatial/wavelet
|
| 6 |
+
reference lineage.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from .degradation import (
|
| 10 |
+
TYPE_ORDER,
|
| 11 |
+
QUERY_NAMES,
|
| 12 |
+
UNKNOWN_INDEX,
|
| 13 |
+
NUM_KNOWN_TYPES,
|
| 14 |
+
NUM_TYPE_CLASSES,
|
| 15 |
+
DualDomainDegradationTransformer,
|
| 16 |
+
DegradationLosses,
|
| 17 |
+
create_degradation_transformer,
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
"TYPE_ORDER",
|
| 22 |
+
"QUERY_NAMES",
|
| 23 |
+
"UNKNOWN_INDEX",
|
| 24 |
+
"NUM_KNOWN_TYPES",
|
| 25 |
+
"NUM_TYPE_CLASSES",
|
| 26 |
+
"DualDomainDegradationTransformer",
|
| 27 |
+
"DegradationLosses",
|
| 28 |
+
"create_degradation_transformer",
|
| 29 |
+
]
|
dataset/phase1_noise_20260906/code/src/models/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (765 Bytes). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/degradation/__init__.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dual-Domain Degradation Transformer package.
|
| 2 |
+
|
| 3 |
+
Replaces the previous DC-AE-displacement / FastDualDomainEncoder classifiers:
|
| 4 |
+
the classifier is now a dedicated dual-domain transformer that never touches
|
| 5 |
+
DC-AE. DC-AE remains the frozen latent space for restoration only.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from .constants import (
|
| 9 |
+
NUM_KNOWN_TYPES,
|
| 10 |
+
NUM_TYPE_CLASSES,
|
| 11 |
+
QUERY_NAMES,
|
| 12 |
+
TYPE_ORDER,
|
| 13 |
+
UNKNOWN_INDEX,
|
| 14 |
+
multi_hot,
|
| 15 |
+
severity_vector,
|
| 16 |
+
type_index,
|
| 17 |
+
)
|
| 18 |
+
from .losses import DegradationLosses, LossConfig
|
| 19 |
+
from .metrics import (
|
| 20 |
+
ClassificationReport,
|
| 21 |
+
classification_report,
|
| 22 |
+
gate_s0_check_embedding,
|
| 23 |
+
gate_s0_check_pair,
|
| 24 |
+
primary_type_index,
|
| 25 |
+
predicted_type_index,
|
| 26 |
+
severity_correlations,
|
| 27 |
+
)
|
| 28 |
+
from .model import (
|
| 29 |
+
DOMAIN_NAMES,
|
| 30 |
+
DualDomainDegradationTransformer,
|
| 31 |
+
SeverityMapLoss,
|
| 32 |
+
count_trainable_parameters,
|
| 33 |
+
create_degradation_transformer,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
__all__ = [
|
| 37 |
+
# Constants
|
| 38 |
+
"TYPE_ORDER",
|
| 39 |
+
"QUERY_NAMES",
|
| 40 |
+
"NUM_KNOWN_TYPES",
|
| 41 |
+
"NUM_TYPE_CLASSES",
|
| 42 |
+
"UNKNOWN_INDEX",
|
| 43 |
+
"type_index",
|
| 44 |
+
"multi_hot",
|
| 45 |
+
"severity_vector",
|
| 46 |
+
# Model
|
| 47 |
+
"DualDomainDegradationTransformer",
|
| 48 |
+
"SeverityMapLoss",
|
| 49 |
+
"DOMAIN_NAMES",
|
| 50 |
+
"count_trainable_parameters",
|
| 51 |
+
"create_degradation_transformer",
|
| 52 |
+
# Losses
|
| 53 |
+
"DegradationLosses",
|
| 54 |
+
"LossConfig",
|
| 55 |
+
# Metrics and gates
|
| 56 |
+
"ClassificationReport",
|
| 57 |
+
"classification_report",
|
| 58 |
+
"gate_s0_check_pair",
|
| 59 |
+
"gate_s0_check_embedding",
|
| 60 |
+
"primary_type_index",
|
| 61 |
+
"predicted_type_index",
|
| 62 |
+
"severity_correlations",
|
| 63 |
+
]
|
dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.36 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/constants.cpython-312.pyc
ADDED
|
Binary file (4.62 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/spatial_branch.cpython-312.pyc
ADDED
|
Binary file (8.05 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/transformer.cpython-312.pyc
ADDED
|
Binary file (13.7 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/degradation/__pycache__/wavelet_branch.cpython-312.pyc
ADDED
|
Binary file (9.58 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/degradation/constants.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Canonical degradation constants for the Dual-Domain Degradation Transformer.
|
| 2 |
+
|
| 3 |
+
Gate S2: there is exactly one label order in the whole pipeline. Every spec,
|
| 4 |
+
cache, classifier head, severity vector, and metric must derive from
|
| 5 |
+
``TYPE_ORDER`` here. The order matches the physical camera application order
|
| 6 |
+
in :mod:`src.data.phase1_v2` and the equality is asserted at import time so a
|
| 7 |
+
future reorder cannot silently desynchronize features and labels.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from typing import Sequence, Tuple
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
|
| 16 |
+
# Allow override for extended type sets
|
| 17 |
+
_EXTENDED_TYPE_ORDER: Tuple[str, ...] = None
|
| 18 |
+
_EXTENDED_NUM_KNOWN: int = None
|
| 19 |
+
_EXTENDED_NUM_CLASSES: int = None
|
| 20 |
+
|
| 21 |
+
def set_extended_types(type_order: Tuple[str, ...]):
|
| 22 |
+
"""Set extended type order for multi-dataset training."""
|
| 23 |
+
global _EXTENDED_TYPE_ORDER, _EXTENDED_NUM_KNOWN, _EXTENDED_NUM_CLASSES
|
| 24 |
+
_EXTENDED_TYPE_ORDER = type_order
|
| 25 |
+
_EXTENDED_NUM_KNOWN = len(type_order)
|
| 26 |
+
_EXTENDED_NUM_CLASSES = _EXTENDED_NUM_KNOWN + 1 # known + unknown
|
| 27 |
+
|
| 28 |
+
from ...data.phase1_v2 import TYPE_ORDER as _BASE_TYPE_ORDER
|
| 29 |
+
|
| 30 |
+
# Export TYPE_ORDER for backwards compatibility
|
| 31 |
+
TYPE_ORDER = _BASE_TYPE_ORDER
|
| 32 |
+
|
| 33 |
+
NUM_KNOWN_TYPES: int = 4 # default: blur, lowlight, noise, jpeg
|
| 34 |
+
UNKNOWN_INDEX: int = NUM_KNOWN_TYPES # 4
|
| 35 |
+
NUM_TYPE_CLASSES: int = NUM_KNOWN_TYPES + 1 # 4 known + unknown
|
| 36 |
+
QUERY_NAMES: Tuple[str, ...] = ("Qblur", "Qlowlight", "Qnoise", "Qjpeg", "Qunknown")
|
| 37 |
+
|
| 38 |
+
_BASE_TYPE_TO_INDEX = {name: index for index, name in enumerate(_BASE_TYPE_ORDER)}
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _get_type_order():
|
| 42 |
+
return _EXTENDED_TYPE_ORDER if _EXTENDED_TYPE_ORDER else _BASE_TYPE_ORDER
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _get_num_known():
|
| 46 |
+
return _EXTENDED_NUM_KNOWN if _EXTENDED_NUM_KNOWN else NUM_KNOWN_TYPES
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _get_num_classes():
|
| 50 |
+
return _EXTENDED_NUM_CLASSES if _EXTENDED_NUM_CLASSES else NUM_TYPE_CLASSES
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _type_to_index(name: str) -> int:
|
| 54 |
+
"""Return the canonical index of a degradation name."""
|
| 55 |
+
if _EXTENDED_TYPE_ORDER:
|
| 56 |
+
return _EXTENDED_TYPE_ORDER.index(name)
|
| 57 |
+
return _BASE_TYPE_TO_INDEX[name]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def type_index(name: str) -> int:
|
| 61 |
+
"""Return the canonical index of a known degradation name."""
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
return _type_to_index(name)
|
| 65 |
+
except ValueError as error:
|
| 66 |
+
raise KeyError(
|
| 67 |
+
f"Unknown degradation '{name}'. Known types: {TYPE_ORDER}"
|
| 68 |
+
) from error
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def multi_hot(components: Sequence[str]) -> torch.Tensor:
|
| 72 |
+
"""Return a ``NUM_TYPE_CLASSES`` float target vector for a sample.
|
| 73 |
+
|
| 74 |
+
Positions of present components are 1.0. A clean sample is all-zero;
|
| 75 |
+
``unknown`` is reserved for explicit outlier-exposure corruptions rather
|
| 76 |
+
than conflating "no degradation" with "unseen degradation".
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
vector = torch.zeros(NUM_TYPE_CLASSES, dtype=torch.float32)
|
| 80 |
+
seen = set()
|
| 81 |
+
for component in components:
|
| 82 |
+
try:
|
| 83 |
+
idx = _type_to_index(component)
|
| 84 |
+
except ValueError:
|
| 85 |
+
raise KeyError(f"Unknown degradation component: {component}")
|
| 86 |
+
if component not in seen:
|
| 87 |
+
vector[idx] = 1.0
|
| 88 |
+
seen.add(component)
|
| 89 |
+
return vector
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def severity_vector(components: Sequence[str], severities: Sequence[float]) -> torch.Tensor:
|
| 93 |
+
"""Scatter normalized severities into canonical ``NUM_KNOWN_TYPES`` order."""
|
| 94 |
+
|
| 95 |
+
if len(components) != len(severities):
|
| 96 |
+
raise ValueError("components and severities must align")
|
| 97 |
+
vector = torch.zeros(NUM_KNOWN_TYPES, dtype=torch.float32)
|
| 98 |
+
for component, severity in zip(components, severities):
|
| 99 |
+
vector[_type_to_index(component)] = float(severity)
|
| 100 |
+
return vector
|
dataset/phase1_noise_20260906/code/src/models/degradation/losses.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Losses for the Dual-Domain Degradation Transformer.
|
| 2 |
+
|
| 3 |
+
Total objective::
|
| 4 |
+
|
| 5 |
+
L = lt*L_type + ls*L_severity + lr*L_ranking + lc*L_clean_zero
|
| 6 |
+
+ lp*L_pair + ld*L_domain_agreement
|
| 7 |
+
|
| 8 |
+
* ``L_type``: sigmoid focal loss over the five query logits (multi-hot targets
|
| 9 |
+
so compositions are supported natively).
|
| 10 |
+
* ``L_severity``: SmoothL1 restricted to active degradation types.
|
| 11 |
+
* ``L_ranking``: margin ranking that keeps severity ordering between samples
|
| 12 |
+
of the same type (tensorized pairwise).
|
| 13 |
+
* ``L_clean_zero``: a clean image must map close to the origin (embedding
|
| 14 |
+
norm plus suppressed type/severity mass).
|
| 15 |
+
* ``L_pair``: same crop + same type embeddings keep direction and grow with
|
| 16 |
+
severity.
|
| 17 |
+
* ``L_domain_agreement``: single-domain predictions must not contradict the
|
| 18 |
+
dual-domain prediction.
|
| 19 |
+
|
| 20 |
+
All reductions are tensorized; no Python double loops over the batch.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
from dataclasses import dataclass
|
| 26 |
+
from typing import Dict, Optional
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
import torch.nn as nn
|
| 30 |
+
import torch.nn.functional as F
|
| 31 |
+
from torch import Tensor
|
| 32 |
+
|
| 33 |
+
from .constants import UNKNOWN_INDEX
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class LossConfig:
|
| 38 |
+
lambda_type: float = 2.0 # Increased: type is priority
|
| 39 |
+
lambda_severity: float = 0.5 # Decreased: secondary
|
| 40 |
+
lambda_ranking: float = 0.1 # Decreased
|
| 41 |
+
lambda_clean_zero: float = 0.3 # Decreased
|
| 42 |
+
lambda_pair: float = 0.1 # Decreased
|
| 43 |
+
lambda_domain_agreement: float = 0.05 # Decreased
|
| 44 |
+
lambda_unknown_exposure: float = 0.2
|
| 45 |
+
# Severity penalty pushing absent-type predictions to zero.
|
| 46 |
+
lambda_absent_severity: float = 0.1 # Decreased
|
| 47 |
+
# Focal hyper-parameters.
|
| 48 |
+
focal_gamma: float = 2.0
|
| 49 |
+
focal_alpha: float = 0.25
|
| 50 |
+
# Ranking margins.
|
| 51 |
+
rank_margin: float = 0.05
|
| 52 |
+
severity_gap: float = 0.05
|
| 53 |
+
# Pair consistency.
|
| 54 |
+
pair_direction_margin: float = 0.5
|
| 55 |
+
pair_magnitude_margin: float = 0.02
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def sigmoid_focal_loss(
|
| 59 |
+
logits: Tensor,
|
| 60 |
+
targets: Tensor,
|
| 61 |
+
gamma: float = 2.0,
|
| 62 |
+
alpha: float = 0.25,
|
| 63 |
+
) -> Tensor:
|
| 64 |
+
"""Multi-label binary focal loss, averaged over batch and classes."""
|
| 65 |
+
|
| 66 |
+
probs = torch.sigmoid(logits)
|
| 67 |
+
ce = F.binary_cross_entropy_with_logits(logits, targets, reduction="none")
|
| 68 |
+
p_t = probs * targets + (1.0 - probs) * (1.0 - targets)
|
| 69 |
+
alpha_t = alpha * targets + (1.0 - alpha) * (1.0 - targets)
|
| 70 |
+
return (alpha_t * (1.0 - p_t).pow(gamma) * ce).mean()
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def ranking_loss(
|
| 74 |
+
severity_pred: Tensor,
|
| 75 |
+
severity_target: Tensor,
|
| 76 |
+
active_mask: Tensor,
|
| 77 |
+
margin: float = 0.05,
|
| 78 |
+
min_gap: float = 0.05,
|
| 79 |
+
) -> Tensor:
|
| 80 |
+
"""Pairwise margin ranking within shared active types.
|
| 81 |
+
|
| 82 |
+
severity_pred/target: [B, K]; active_mask: [B, K] bool.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
total = severity_pred.new_zeros(())
|
| 86 |
+
count = 0
|
| 87 |
+
for k in range(severity_pred.shape[1]):
|
| 88 |
+
idx = active_mask[:, k].nonzero(as_tuple=True)[0]
|
| 89 |
+
if idx.numel() < 2:
|
| 90 |
+
continue
|
| 91 |
+
pred = severity_pred[idx, k]
|
| 92 |
+
target = severity_target[idx, k]
|
| 93 |
+
diff_t = target.unsqueeze(0) - target.unsqueeze(1) # [i, j] = target_j - target_i
|
| 94 |
+
pair_mask = diff_t.abs() >= min_gap
|
| 95 |
+
if not pair_mask.any():
|
| 96 |
+
continue
|
| 97 |
+
sign = torch.sign(diff_t)
|
| 98 |
+
# pred_j should exceed pred_i by `margin` whenever target_j > target_i.
|
| 99 |
+
violation = F.relu(margin - sign * (pred.unsqueeze(0) - pred.unsqueeze(1)))
|
| 100 |
+
total = total + (violation * pair_mask).sum()
|
| 101 |
+
count += int(pair_mask.sum().item())
|
| 102 |
+
if count == 0:
|
| 103 |
+
return severity_pred.new_zeros(())
|
| 104 |
+
return total / count
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def clean_zero_loss(
|
| 108 |
+
embedding: Tensor,
|
| 109 |
+
type_logits: Tensor,
|
| 110 |
+
severity: Tensor,
|
| 111 |
+
) -> Dict[str, Tensor]:
|
| 112 |
+
"""Clean images must sit at the origin of every output space."""
|
| 113 |
+
|
| 114 |
+
embed_norm = embedding.norm(dim=-1).mean()
|
| 115 |
+
type_mass = torch.sigmoid(type_logits).mean()
|
| 116 |
+
severity_mass = severity.mean()
|
| 117 |
+
return {
|
| 118 |
+
"clean_zero": embed_norm + type_mass + severity_mass,
|
| 119 |
+
"clean_embed_norm": embed_norm.detach(),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _pairs_by_key(keys: Tensor):
|
| 124 |
+
"""Yield all index pairs sharing an identical key value."""
|
| 125 |
+
|
| 126 |
+
unique = torch.unique(keys)
|
| 127 |
+
for value in unique:
|
| 128 |
+
idx = (keys == value).nonzero(as_tuple=True)[0]
|
| 129 |
+
n = idx.numel()
|
| 130 |
+
if n < 2:
|
| 131 |
+
continue
|
| 132 |
+
grid = torch.triu_indices(n, n, offset=1, device=keys.device)
|
| 133 |
+
yield idx[grid[0]], idx[grid[1]]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def pair_loss(
|
| 137 |
+
embedding: Tensor,
|
| 138 |
+
crop_keys: Tensor,
|
| 139 |
+
type_keys: Tensor,
|
| 140 |
+
severity_target: Tensor,
|
| 141 |
+
active_mask: Tensor,
|
| 142 |
+
direction_margin: float = 0.5,
|
| 143 |
+
magnitude_margin: float = 0.02,
|
| 144 |
+
) -> Tensor:
|
| 145 |
+
"""Same crop + same type pairs: aligned direction, monotone magnitude."""
|
| 146 |
+
|
| 147 |
+
valid = type_keys >= 0
|
| 148 |
+
if valid.sum() < 2:
|
| 149 |
+
return embedding.new_zeros(())
|
| 150 |
+
embedding = embedding[valid]
|
| 151 |
+
crop_keys = crop_keys[valid]
|
| 152 |
+
type_keys = type_keys[valid]
|
| 153 |
+
severity_target = severity_target[valid]
|
| 154 |
+
active_mask = active_mask[valid]
|
| 155 |
+
|
| 156 |
+
normed = F.normalize(embedding, dim=-1)
|
| 157 |
+
norms = embedding.norm(dim=-1)
|
| 158 |
+
total = embedding.new_zeros(())
|
| 159 |
+
count = 0
|
| 160 |
+
for i, j in _pairs_by_key(crop_keys * 1000 + type_keys):
|
| 161 |
+
shared_types = active_mask[i] & active_mask[j]
|
| 162 |
+
if not shared_types.any():
|
| 163 |
+
continue
|
| 164 |
+
cosine = (normed[i] * normed[j]).sum(dim=-1)
|
| 165 |
+
total = total + F.relu(direction_margin - cosine).sum()
|
| 166 |
+
sev_i = (severity_target[i] * shared_types).sum(dim=-1)
|
| 167 |
+
sev_j = (severity_target[j] * shared_types).sum(dim=-1)
|
| 168 |
+
sign = torch.sign(sev_i - sev_j)
|
| 169 |
+
violation = F.relu(magnitude_margin - sign * (norms[i] - norms[j]))
|
| 170 |
+
equal = (sign == 0).float()
|
| 171 |
+
total = total + (violation * (1.0 - equal)).sum()
|
| 172 |
+
count += int(shared_types.sum().item())
|
| 173 |
+
if count == 0:
|
| 174 |
+
return embedding.new_zeros(())
|
| 175 |
+
return total / count
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def domain_agreement_loss(pred_a: dict, pred_b: dict) -> Dict[str, Tensor]:
|
| 179 |
+
"""Single-domain vs dual-domain consistency."""
|
| 180 |
+
|
| 181 |
+
prob_a = torch.sigmoid(pred_a["type_logits"])
|
| 182 |
+
prob_b = torch.sigmoid(pred_b["type_logits"])
|
| 183 |
+
type_consistency = 0.5 * (
|
| 184 |
+
F.mse_loss(prob_a, prob_b.detach())
|
| 185 |
+
+ F.mse_loss(prob_b, prob_a.detach())
|
| 186 |
+
)
|
| 187 |
+
cos = F.cosine_similarity(
|
| 188 |
+
pred_a["degradation_embedding"], pred_b["degradation_embedding"], dim=-1
|
| 189 |
+
).mean()
|
| 190 |
+
agreement = type_consistency + (1.0 - cos)
|
| 191 |
+
return {"domain_agreement": agreement, "domain_cosine": cos.detach()}
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class DegradationLosses(nn.Module):
|
| 195 |
+
"""Weighted combination of all degradation-classifier losses."""
|
| 196 |
+
|
| 197 |
+
def __init__(self, config: Optional[LossConfig] = None):
|
| 198 |
+
super().__init__()
|
| 199 |
+
self.config = config or LossConfig()
|
| 200 |
+
|
| 201 |
+
def forward(
|
| 202 |
+
self,
|
| 203 |
+
preds: dict,
|
| 204 |
+
multi_hot: Tensor,
|
| 205 |
+
severity_target: Tensor,
|
| 206 |
+
active_mask: Tensor,
|
| 207 |
+
crop_keys: Optional[Tensor] = None,
|
| 208 |
+
type_keys: Optional[Tensor] = None,
|
| 209 |
+
domain_preds: Optional[dict] = None,
|
| 210 |
+
clean_preds: Optional[dict] = None,
|
| 211 |
+
unknown_preds: Optional[dict] = None,
|
| 212 |
+
domain_anchor_preds: Optional[dict] = None,
|
| 213 |
+
) -> Dict[str, Tensor]:
|
| 214 |
+
cfg = self.config
|
| 215 |
+
components: Dict[str, Tensor] = {}
|
| 216 |
+
|
| 217 |
+
components["type"] = sigmoid_focal_loss(
|
| 218 |
+
preds["type_logits"], multi_hot, cfg.focal_gamma, cfg.focal_alpha
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
errors = F.smooth_l1_loss(preds["severity"], severity_target, reduction="none", beta=0.1)
|
| 222 |
+
components["severity"] = (errors * active_mask.float()).sum() / active_mask.float().sum().clamp_min(1.0)
|
| 223 |
+
if cfg.lambda_absent_severity > 0:
|
| 224 |
+
absent = (~active_mask).float()
|
| 225 |
+
absent_err = preds["severity"].abs() * absent
|
| 226 |
+
components["severity_absent"] = absent_err.sum() / absent.sum().clamp_min(1.0)
|
| 227 |
+
|
| 228 |
+
components["ranking"] = ranking_loss(
|
| 229 |
+
preds["severity"],
|
| 230 |
+
severity_target,
|
| 231 |
+
active_mask,
|
| 232 |
+
margin=cfg.rank_margin,
|
| 233 |
+
min_gap=cfg.severity_gap,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
if clean_preds is not None:
|
| 237 |
+
clean_components = clean_zero_loss(
|
| 238 |
+
clean_preds["degradation_embedding"],
|
| 239 |
+
clean_preds["type_logits"],
|
| 240 |
+
clean_preds["severity"],
|
| 241 |
+
)
|
| 242 |
+
components.update(clean_components)
|
| 243 |
+
|
| 244 |
+
if unknown_preds is not None:
|
| 245 |
+
unknown_target = torch.zeros_like(unknown_preds["type_logits"])
|
| 246 |
+
unknown_target[:, UNKNOWN_INDEX] = 1.0
|
| 247 |
+
components["unknown_type"] = sigmoid_focal_loss(
|
| 248 |
+
unknown_preds["type_logits"],
|
| 249 |
+
unknown_target,
|
| 250 |
+
cfg.focal_gamma,
|
| 251 |
+
cfg.focal_alpha,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
if (
|
| 255 |
+
crop_keys is not None
|
| 256 |
+
and type_keys is not None
|
| 257 |
+
and (crop_keys * 1000 + type_keys).unique().numel() < crop_keys.numel()
|
| 258 |
+
):
|
| 259 |
+
pair_embedding = preds["degradation_embedding"]
|
| 260 |
+
if clean_preds is not None:
|
| 261 |
+
pair_embedding = (
|
| 262 |
+
pair_embedding - clean_preds["degradation_embedding"]
|
| 263 |
+
)
|
| 264 |
+
components["pair"] = pair_loss(
|
| 265 |
+
pair_embedding,
|
| 266 |
+
crop_keys,
|
| 267 |
+
type_keys,
|
| 268 |
+
severity_target,
|
| 269 |
+
active_mask,
|
| 270 |
+
cfg.pair_direction_margin,
|
| 271 |
+
cfg.pair_magnitude_margin,
|
| 272 |
+
)
|
| 273 |
+
else:
|
| 274 |
+
components["pair"] = preds["degradation_embedding"].new_zeros(())
|
| 275 |
+
|
| 276 |
+
if domain_preds is not None:
|
| 277 |
+
components.update(
|
| 278 |
+
domain_agreement_loss(domain_anchor_preds or preds, domain_preds)
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
total = (
|
| 282 |
+
cfg.lambda_type * components["type"]
|
| 283 |
+
+ cfg.lambda_unknown_exposure
|
| 284 |
+
* components.get("unknown_type", preds["type_logits"].new_zeros(()))
|
| 285 |
+
+ cfg.lambda_severity * components["severity"]
|
| 286 |
+
+ cfg.lambda_ranking * components["ranking"]
|
| 287 |
+
+ cfg.lambda_clean_zero * components.get("clean_zero", preds["type_logits"].new_zeros(()))
|
| 288 |
+
+ cfg.lambda_pair * components.get("pair", preds["type_logits"].new_zeros(()))
|
| 289 |
+
+ cfg.lambda_domain_agreement
|
| 290 |
+
* components.get("domain_agreement", preds["type_logits"].new_zeros(()))
|
| 291 |
+
)
|
| 292 |
+
if "severity_absent" in components:
|
| 293 |
+
total = total + cfg.lambda_absent_severity * components["severity_absent"]
|
| 294 |
+
|
| 295 |
+
components["total"] = total
|
| 296 |
+
return {key: value for key, value in components.items()}
|
dataset/phase1_noise_20260906/code/src/models/degradation/metrics.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sanity gates and evaluation metrics for the degradation classifier.
|
| 2 |
+
|
| 3 |
+
Gate S0: a degraded image must actually differ from its clean source, and the
|
| 4 |
+
classifier's embedding displacement must be non-zero.
|
| 5 |
+
Gate S1: overfit a tiny split (run from the trainer ``--gate overfit``).
|
| 6 |
+
Gate S2: canonical label order is enforced by importing
|
| 7 |
+
:func:`src.models.degradation.constants` (raises on mismatch).
|
| 8 |
+
Gate S3: ablation presets A0..A6 are built by :func:`create_degradation_transformer`.
|
| 9 |
+
|
| 10 |
+
Metrics include raw accuracy, predicted-class histogram, confusion matrix and
|
| 11 |
+
Hungarian-matched accuracy so a label permutation can never hide as "low but
|
| 12 |
+
real" performance.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
from itertools import permutations
|
| 19 |
+
from typing import Dict
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from torch import Tensor
|
| 24 |
+
|
| 25 |
+
from .constants import NUM_KNOWN_TYPES, TYPE_ORDER
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def gate_s0_check_pair(
|
| 29 |
+
clean: Tensor,
|
| 30 |
+
degraded: Tensor,
|
| 31 |
+
l1_threshold: float = 1e-4,
|
| 32 |
+
) -> Dict[str, object]:
|
| 33 |
+
"""Assert the degradation operator actually modified the image."""
|
| 34 |
+
|
| 35 |
+
if clean.shape != degraded.shape:
|
| 36 |
+
raise ValueError("clean/degraded shape mismatch")
|
| 37 |
+
l1 = (clean - degraded).abs().mean().item()
|
| 38 |
+
max_abs = (clean - degraded).abs().max().item()
|
| 39 |
+
passed = l1 > l1_threshold
|
| 40 |
+
return {
|
| 41 |
+
"passed": bool(passed),
|
| 42 |
+
"l1": l1,
|
| 43 |
+
"max_abs": max_abs,
|
| 44 |
+
"threshold": l1_threshold,
|
| 45 |
+
"reason": None if passed else f"L1(clean, degraded)={l1:.6f} <= {l1_threshold}",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def gate_s0_check_embedding(
|
| 50 |
+
embedding_clean: Tensor,
|
| 51 |
+
embedding_degraded: Tensor,
|
| 52 |
+
min_displacement: float = 0.0,
|
| 53 |
+
) -> Dict[str, object]:
|
| 54 |
+
"""E(degraded) - E(clean) must not vanish."""
|
| 55 |
+
|
| 56 |
+
delta = embedding_degraded - embedding_clean
|
| 57 |
+
displacement = delta.norm(dim=-1)
|
| 58 |
+
max_abs = delta.abs().flatten(1).max(dim=1).values
|
| 59 |
+
mean_norm = displacement.mean().item()
|
| 60 |
+
min_max_abs = max_abs.min().item()
|
| 61 |
+
return {
|
| 62 |
+
"passed": bool(min_max_abs > min_displacement),
|
| 63 |
+
"mean_embedding_displacement": mean_norm,
|
| 64 |
+
"min_max_abs_displacement": min_max_abs,
|
| 65 |
+
"min_required": min_displacement,
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
@dataclass
|
| 70 |
+
class ClassificationReport:
|
| 71 |
+
accuracy: float
|
| 72 |
+
hungarian_accuracy: float
|
| 73 |
+
confusion_matrix: np.ndarray # [4 targets, 5 predictions]
|
| 74 |
+
predicted_histogram: np.ndarray # [5] including unknown
|
| 75 |
+
multilabel_macro_f1: float
|
| 76 |
+
composition_exact_match: float
|
| 77 |
+
composition_jaccard: float
|
| 78 |
+
class_order: tuple = TYPE_ORDER
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def primary_type_index(multi_hot: Tensor) -> Tensor:
|
| 82 |
+
"""Canonical index of the first active known type; unknown -> 4."""
|
| 83 |
+
|
| 84 |
+
known = multi_hot[:, :NUM_KNOWN_TYPES]
|
| 85 |
+
first = known.float().argmax(dim=1)
|
| 86 |
+
has_type = known.float().sum(dim=1) > 0
|
| 87 |
+
return torch.where(has_type, first, torch.full_like(first, NUM_KNOWN_TYPES))
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def predicted_type_index(type_logits: Tensor) -> Tensor:
|
| 91 |
+
"""Argmax prediction including the unknown class."""
|
| 92 |
+
|
| 93 |
+
return type_logits.argmax(dim=1)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def classification_report(
|
| 97 |
+
type_logits: Tensor,
|
| 98 |
+
multi_hot_targets: Tensor,
|
| 99 |
+
) -> ClassificationReport:
|
| 100 |
+
# Four-class accuracy and permutation checks are defined on singles only;
|
| 101 |
+
# compositions are multi-label and have no unambiguous primary class.
|
| 102 |
+
singles = multi_hot_targets[:, :NUM_KNOWN_TYPES].sum(dim=1) == 1
|
| 103 |
+
targets = primary_type_index(multi_hot_targets[singles]).cpu().numpy()
|
| 104 |
+
preds = predicted_type_index(type_logits[singles]).cpu().numpy()
|
| 105 |
+
|
| 106 |
+
accuracy = float((preds == targets).mean()) if len(targets) else 0.0
|
| 107 |
+
confusion = np.zeros((NUM_KNOWN_TYPES, NUM_KNOWN_TYPES + 1), dtype=np.int64)
|
| 108 |
+
histogram = np.zeros(NUM_KNOWN_TYPES + 1, dtype=np.int64)
|
| 109 |
+
for target, pred in zip(targets, preds):
|
| 110 |
+
histogram[pred] += 1
|
| 111 |
+
if target < NUM_KNOWN_TYPES:
|
| 112 |
+
confusion[target, pred] += 1
|
| 113 |
+
|
| 114 |
+
hungarian = _hungarian_accuracy_from_confusion(
|
| 115 |
+
confusion[:, :NUM_KNOWN_TYPES],
|
| 116 |
+
denominator=int(confusion.sum()),
|
| 117 |
+
)
|
| 118 |
+
|
| 119 |
+
known_targets = multi_hot_targets[:, :NUM_KNOWN_TYPES].bool().cpu().numpy()
|
| 120 |
+
known_predictions = (
|
| 121 |
+
type_logits[:, :NUM_KNOWN_TYPES].sigmoid() >= 0.5
|
| 122 |
+
).cpu().numpy()
|
| 123 |
+
f1_values = []
|
| 124 |
+
for index in range(NUM_KNOWN_TYPES):
|
| 125 |
+
target = known_targets[:, index]
|
| 126 |
+
prediction = known_predictions[:, index]
|
| 127 |
+
tp = np.logical_and(target, prediction).sum()
|
| 128 |
+
fp = np.logical_and(~target, prediction).sum()
|
| 129 |
+
fn = np.logical_and(target, ~prediction).sum()
|
| 130 |
+
denominator = 2 * tp + fp + fn
|
| 131 |
+
f1_values.append(2 * tp / denominator if denominator else 0.0)
|
| 132 |
+
composition_rows = known_targets.sum(axis=1) > 1
|
| 133 |
+
if composition_rows.any():
|
| 134 |
+
target_compositions = known_targets[composition_rows]
|
| 135 |
+
predicted_compositions = known_predictions[composition_rows]
|
| 136 |
+
exact_match = float(
|
| 137 |
+
np.all(target_compositions == predicted_compositions, axis=1).mean()
|
| 138 |
+
)
|
| 139 |
+
intersection = np.logical_and(
|
| 140 |
+
target_compositions, predicted_compositions
|
| 141 |
+
).sum(axis=1)
|
| 142 |
+
union = np.logical_or(target_compositions, predicted_compositions).sum(axis=1)
|
| 143 |
+
jaccard = float(np.mean(intersection / union))
|
| 144 |
+
else:
|
| 145 |
+
exact_match = 0.0
|
| 146 |
+
jaccard = 0.0
|
| 147 |
+
return ClassificationReport(
|
| 148 |
+
accuracy=accuracy,
|
| 149 |
+
hungarian_accuracy=hungarian,
|
| 150 |
+
confusion_matrix=confusion,
|
| 151 |
+
predicted_histogram=histogram,
|
| 152 |
+
multilabel_macro_f1=float(np.mean(f1_values)),
|
| 153 |
+
composition_exact_match=exact_match,
|
| 154 |
+
composition_jaccard=jaccard,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _hungarian_accuracy_from_confusion(
|
| 159 |
+
confusion: np.ndarray,
|
| 160 |
+
denominator: int | None = None,
|
| 161 |
+
) -> float:
|
| 162 |
+
# Four classes have only 4! = 24 assignments. Exhaustive maximization is
|
| 163 |
+
# exactly equivalent to Hungarian matching here and avoids a heavyweight
|
| 164 |
+
# SciPy dependency in the training/evaluation path.
|
| 165 |
+
rows = np.arange(confusion.shape[0])
|
| 166 |
+
matched = max(
|
| 167 |
+
int(confusion[rows, np.asarray(columns)].sum())
|
| 168 |
+
for columns in permutations(range(confusion.shape[1]), confusion.shape[0])
|
| 169 |
+
)
|
| 170 |
+
total = int(confusion.sum()) if denominator is None else denominator
|
| 171 |
+
return matched / total if total else 0.0
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _rankdata(values: np.ndarray) -> np.ndarray:
|
| 175 |
+
"""Average ranks for ties, equivalent to scipy.stats.rankdata."""
|
| 176 |
+
|
| 177 |
+
order = np.argsort(values, kind="mergesort")
|
| 178 |
+
sorted_values = values[order]
|
| 179 |
+
ranks = np.empty(len(values), dtype=np.float64)
|
| 180 |
+
start = 0
|
| 181 |
+
while start < len(values):
|
| 182 |
+
end = start + 1
|
| 183 |
+
while end < len(values) and sorted_values[end] == sorted_values[start]:
|
| 184 |
+
end += 1
|
| 185 |
+
ranks[order[start:end]] = (start + end - 1) / 2.0
|
| 186 |
+
start = end
|
| 187 |
+
return ranks
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _spearman(x: np.ndarray, y: np.ndarray) -> float:
|
| 191 |
+
x_rank = _rankdata(np.asarray(x))
|
| 192 |
+
y_rank = _rankdata(np.asarray(y))
|
| 193 |
+
if np.ptp(x_rank) == 0 or np.ptp(y_rank) == 0:
|
| 194 |
+
return float("nan")
|
| 195 |
+
return float(np.corrcoef(x_rank, y_rank)[0, 1])
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def severity_correlations(
|
| 199 |
+
severity_pred: Tensor,
|
| 200 |
+
severity_target: Tensor,
|
| 201 |
+
active_mask: Tensor,
|
| 202 |
+
) -> Dict[str, float]:
|
| 203 |
+
"""Per-type Spearman rho between predictions and labels."""
|
| 204 |
+
|
| 205 |
+
report: Dict[str, float] = {}
|
| 206 |
+
pred = severity_pred.detach().cpu().numpy()
|
| 207 |
+
target = severity_target.detach().cpu().numpy()
|
| 208 |
+
mask = active_mask.detach().cpu().numpy()
|
| 209 |
+
for k, name in enumerate(TYPE_ORDER):
|
| 210 |
+
rows = mask[:, k].astype(bool)
|
| 211 |
+
if rows.sum() >= 3 and np.ptp(target[rows, k]) > 0:
|
| 212 |
+
report[name] = _spearman(pred[rows, k], target[rows, k])
|
| 213 |
+
if mask.sum() >= 3:
|
| 214 |
+
report["overall"] = _spearman(pred[mask], target[mask])
|
| 215 |
+
return report
|
dataset/phase1_noise_20260906/code/src/models/degradation/model.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dual-Domain Degradation Transformer (full model).
|
| 2 |
+
|
| 3 |
+
Pipeline::
|
| 4 |
+
|
| 5 |
+
degraded image ──┬─► Pixel/illumination stem ──► spatial tokens (H/16)
|
| 6 |
+
│ │
|
| 7 |
+
├─► Haar 3-level wavelet encoder ► wavelet tokens (4x4)
|
| 8 |
+
│ │
|
| 9 |
+
└────────────► Dual-domain query transformer ◄────┘
|
| 10 |
+
│
|
| 11 |
+
Type · severity · confidence · degradation embedding
|
| 12 |
+
│
|
| 13 |
+
(frozen DC-AE stays outside: restoration latent space only)
|
| 14 |
+
|
| 15 |
+
Outputs::
|
| 16 |
+
|
| 17 |
+
{
|
| 18 |
+
"degradation_embedding": [B, 128],
|
| 19 |
+
"type_logits": [B, 5], # blur|lowlight|noise|jpeg|unknown
|
| 20 |
+
"confidence": [B, 5],
|
| 21 |
+
"severity": [B, 4], # normalized, canonical TYPE_ORDER
|
| 22 |
+
"spatial_severity_map": [B, 4, H/8, W/8],
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
The ``domains`` argument selects which key/value streams the queries may
|
| 26 |
+
attend to (ablations A0/A1); ``modality_dropout`` randomly disables a domain
|
| 27 |
+
per sample during training; ``shuffle_wavelet=True`` rolls the wavelet stream
|
| 28 |
+
across the batch (control A6).
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
from __future__ import annotations
|
| 32 |
+
|
| 33 |
+
from typing import Optional, Sequence, Tuple
|
| 34 |
+
|
| 35 |
+
import torch
|
| 36 |
+
import torch.nn.functional as F
|
| 37 |
+
from torch import Tensor, nn
|
| 38 |
+
|
| 39 |
+
from .constants import NUM_KNOWN_TYPES, NUM_TYPE_CLASSES
|
| 40 |
+
from .losses import LossConfig
|
| 41 |
+
from .spatial_branch import SpatialBranch
|
| 42 |
+
from .transformer import DegradationHeads, DualDomainFusion
|
| 43 |
+
from .wavelet_branch import WaveletBranch
|
| 44 |
+
|
| 45 |
+
DOMAIN_NAMES = ("spatial", "wavelet")
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _single_query_heads(hidden_dim: int, embed_dim: int) -> nn.Module:
|
| 49 |
+
"""A3-style heads fed by one generic readout query."""
|
| 50 |
+
|
| 51 |
+
class SingleQueryHeads(nn.Module):
|
| 52 |
+
def __init__(self):
|
| 53 |
+
super().__init__()
|
| 54 |
+
self.type_proj = nn.Linear(hidden_dim, NUM_TYPE_CLASSES)
|
| 55 |
+
self.severity_proj = nn.Linear(hidden_dim, NUM_KNOWN_TYPES)
|
| 56 |
+
self.embedding_proj = nn.Sequential(
|
| 57 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 58 |
+
nn.GELU(),
|
| 59 |
+
nn.Linear(hidden_dim, embed_dim),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
def forward(self, query_states: Tensor) -> dict:
|
| 63 |
+
pooled = query_states.mean(dim=1) # [B, H]
|
| 64 |
+
type_logits = self.type_proj(pooled)
|
| 65 |
+
return {
|
| 66 |
+
"type_logits": type_logits,
|
| 67 |
+
"confidence": torch.sigmoid(type_logits),
|
| 68 |
+
"severity": torch.sigmoid(self.severity_proj(pooled)),
|
| 69 |
+
"degradation_embedding": self.embedding_proj(pooled),
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
return SingleQueryHeads()
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ConcatFusion(nn.Module):
|
| 76 |
+
"""A2 baseline: global pooling + concat instead of cross attention."""
|
| 77 |
+
|
| 78 |
+
def __init__(self, token_dim: int, hidden_dim: int, num_queries: int):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.num_queries = num_queries
|
| 81 |
+
self.mlp = nn.Sequential(
|
| 82 |
+
nn.Linear(token_dim * 2, hidden_dim * 2),
|
| 83 |
+
nn.GELU(),
|
| 84 |
+
nn.Linear(hidden_dim * 2, hidden_dim),
|
| 85 |
+
nn.LayerNorm(hidden_dim),
|
| 86 |
+
)
|
| 87 |
+
self.query_embed = nn.Parameter(torch.zeros(num_queries, hidden_dim))
|
| 88 |
+
nn.init.trunc_normal_(self.query_embed, std=0.02)
|
| 89 |
+
|
| 90 |
+
def forward(self, spatial_tokens: Tensor, wavelet_tokens: Tensor, active_domains=None) -> Tensor:
|
| 91 |
+
spatial = spatial_tokens.mean(dim=1)
|
| 92 |
+
wavelet = wavelet_tokens.mean(dim=1)
|
| 93 |
+
if active_domains is not None:
|
| 94 |
+
spatial = spatial * active_domains[:, 0, None].to(spatial.dtype)
|
| 95 |
+
wavelet = wavelet * active_domains[:, 1, None].to(wavelet.dtype)
|
| 96 |
+
pooled = torch.cat([spatial, wavelet], dim=-1)
|
| 97 |
+
context = self.mlp(pooled).unsqueeze(1) # [B, 1, H]
|
| 98 |
+
return context + self.query_embed.unsqueeze(0)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class DualDomainDegradationTransformer(nn.Module):
|
| 102 |
+
def __init__(
|
| 103 |
+
self,
|
| 104 |
+
token_dim: int = 96,
|
| 105 |
+
hidden_dim: int = 192,
|
| 106 |
+
embed_dim: int = 128,
|
| 107 |
+
num_blocks: int = 4,
|
| 108 |
+
num_heads: int = 4,
|
| 109 |
+
num_queries: int = 5,
|
| 110 |
+
fusion_mode: str = "transformer",
|
| 111 |
+
shuffle_wavelet: bool = False,
|
| 112 |
+
blocks_per_stage: int = 4,
|
| 113 |
+
):
|
| 114 |
+
super().__init__()
|
| 115 |
+
if fusion_mode not in ("transformer", "concat"):
|
| 116 |
+
raise ValueError("fusion_mode must be 'transformer' or 'concat'")
|
| 117 |
+
self.fusion_mode = fusion_mode
|
| 118 |
+
self.shuffle_wavelet = shuffle_wavelet
|
| 119 |
+
self.hidden_dim = hidden_dim
|
| 120 |
+
|
| 121 |
+
self.spatial_branch = SpatialBranch(token_dim=token_dim, blocks_per_stage=blocks_per_stage)
|
| 122 |
+
self.wavelet_branch = WaveletBranch(token_dim=token_dim)
|
| 123 |
+
self.severity_map_refine = nn.Sequential(
|
| 124 |
+
nn.Conv2d(token_dim, token_dim, kernel_size=3, padding=1, groups=token_dim),
|
| 125 |
+
nn.Conv2d(token_dim, token_dim, kernel_size=1),
|
| 126 |
+
nn.GELU(),
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
if fusion_mode == "transformer" and num_queries == 1:
|
| 130 |
+
self.fusion = DualDomainFusion(
|
| 131 |
+
token_dim=token_dim,
|
| 132 |
+
hidden_dim=hidden_dim,
|
| 133 |
+
num_queries=1,
|
| 134 |
+
num_blocks=num_blocks,
|
| 135 |
+
num_heads=num_heads,
|
| 136 |
+
)
|
| 137 |
+
self.heads = _single_query_heads(hidden_dim, embed_dim)
|
| 138 |
+
elif fusion_mode == "transformer":
|
| 139 |
+
if num_queries != NUM_TYPE_CLASSES:
|
| 140 |
+
raise ValueError(
|
| 141 |
+
"Transformer fusion expects one query per type class "
|
| 142 |
+
f"({NUM_TYPE_CLASSES}) or a single generic query (1)."
|
| 143 |
+
)
|
| 144 |
+
self.fusion = DualDomainFusion(
|
| 145 |
+
token_dim=token_dim,
|
| 146 |
+
hidden_dim=hidden_dim,
|
| 147 |
+
num_queries=num_queries,
|
| 148 |
+
num_blocks=num_blocks,
|
| 149 |
+
num_heads=num_heads,
|
| 150 |
+
)
|
| 151 |
+
self.heads = DegradationHeads(hidden_dim=hidden_dim, embed_dim=embed_dim)
|
| 152 |
+
else:
|
| 153 |
+
self.fusion = ConcatFusion(
|
| 154 |
+
token_dim=token_dim, hidden_dim=hidden_dim, num_queries=num_queries
|
| 155 |
+
)
|
| 156 |
+
self.heads = _single_query_heads(hidden_dim, embed_dim)
|
| 157 |
+
|
| 158 |
+
self.severity_map_head = nn.Conv2d(token_dim, NUM_KNOWN_TYPES, kernel_size=1)
|
| 159 |
+
|
| 160 |
+
# ------------------------------------------------------------------
|
| 161 |
+
# Domain availability
|
| 162 |
+
# ------------------------------------------------------------------
|
| 163 |
+
@staticmethod
|
| 164 |
+
def sample_active_domains(
|
| 165 |
+
batch_size: int,
|
| 166 |
+
device: torch.device,
|
| 167 |
+
domains: Sequence[str] = DOMAIN_NAMES,
|
| 168 |
+
p_drop: float = 0.0,
|
| 169 |
+
) -> Tensor:
|
| 170 |
+
"""Per-sample boolean availability [B, 2] with optional dropout."""
|
| 171 |
+
|
| 172 |
+
unknown = set(domains) - set(DOMAIN_NAMES)
|
| 173 |
+
if unknown or not domains:
|
| 174 |
+
raise ValueError(f"domains must be a non-empty subset of {DOMAIN_NAMES}")
|
| 175 |
+
if not 0.0 <= p_drop <= 1.0:
|
| 176 |
+
raise ValueError("p_drop must be in [0, 1]")
|
| 177 |
+
mask = torch.zeros(batch_size, 2, dtype=torch.bool, device=device)
|
| 178 |
+
mask[:, 0] = "spatial" in domains
|
| 179 |
+
mask[:, 1] = "wavelet" in domains
|
| 180 |
+
if p_drop <= 0 or not mask.any():
|
| 181 |
+
return mask
|
| 182 |
+
candidates = torch.rand(batch_size, 2, device=device) < p_drop
|
| 183 |
+
active = mask & ~(candidates & mask)
|
| 184 |
+
empty = ~active.any(dim=1)
|
| 185 |
+
if empty.any():
|
| 186 |
+
# Restore a sole requested domain. If both were requested and
|
| 187 |
+
# dropped, retain one at random instead of producing an invalid
|
| 188 |
+
# all-masked sample.
|
| 189 |
+
active[empty] = mask[empty]
|
| 190 |
+
dual_empty = empty & (mask.sum(dim=1) == 2)
|
| 191 |
+
if dual_empty.any():
|
| 192 |
+
rows = dual_empty.nonzero(as_tuple=True)[0]
|
| 193 |
+
choices = torch.randint(0, 2, (rows.numel(),), device=device)
|
| 194 |
+
active[rows] = False
|
| 195 |
+
active[rows, choices] = True
|
| 196 |
+
return active
|
| 197 |
+
|
| 198 |
+
# ------------------------------------------------------------------
|
| 199 |
+
# Forward
|
| 200 |
+
# ------------------------------------------------------------------
|
| 201 |
+
def _forward_impl(
|
| 202 |
+
self,
|
| 203 |
+
image: Tensor,
|
| 204 |
+
domains: Sequence[str],
|
| 205 |
+
p_drop: float = 0.0,
|
| 206 |
+
wavelet_permutation: Tensor | None = None,
|
| 207 |
+
) -> dict:
|
| 208 |
+
if image.ndim != 4 or image.shape[1] != 3:
|
| 209 |
+
raise ValueError(f"Expected BCHW RGB input, got {tuple(image.shape)}")
|
| 210 |
+
if image.shape[-2] != image.shape[-1] or image.shape[-1] % 16 != 0:
|
| 211 |
+
raise ValueError("Input must be square with height/width divisible by 16")
|
| 212 |
+
spatial = self.spatial_branch(image)
|
| 213 |
+
wavelet_tokens = self.wavelet_branch(image)["tokens"]
|
| 214 |
+
if self.shuffle_wavelet and (self.training or wavelet_permutation is not None):
|
| 215 |
+
if wavelet_permutation is not None:
|
| 216 |
+
if wavelet_permutation.shape != (image.shape[0],):
|
| 217 |
+
raise ValueError("wavelet_permutation must have shape [B]")
|
| 218 |
+
wavelet_tokens = wavelet_tokens[wavelet_permutation]
|
| 219 |
+
|
| 220 |
+
active = self.sample_active_domains(
|
| 221 |
+
image.shape[0], image.device, domains=domains, p_drop=p_drop
|
| 222 |
+
)
|
| 223 |
+
query_states = self.fusion(spatial["tokens"], wavelet_tokens, active)
|
| 224 |
+
preds = self.heads(query_states)
|
| 225 |
+
preds["spatial_severity_map"] = torch.sigmoid(
|
| 226 |
+
self.severity_map_head(self.severity_map_refine(spatial["feat_s8"]))
|
| 227 |
+
) # [B, 4, H/8, W/8]
|
| 228 |
+
preds["query_states"] = query_states
|
| 229 |
+
preds["active_domains"] = active
|
| 230 |
+
return preds
|
| 231 |
+
|
| 232 |
+
def encode(self, image: Tensor, domains: Sequence[str] = DOMAIN_NAMES) -> dict:
|
| 233 |
+
return self._forward_impl(image, domains)
|
| 234 |
+
|
| 235 |
+
def encode_with_modality_dropout(
|
| 236 |
+
self,
|
| 237 |
+
image: Tensor,
|
| 238 |
+
p_drop: float,
|
| 239 |
+
domains: Sequence[str] = DOMAIN_NAMES,
|
| 240 |
+
) -> dict:
|
| 241 |
+
"""Training-time forward pass with stochastic per-sample modality dropout."""
|
| 242 |
+
|
| 243 |
+
return self._forward_impl(image, domains, p_drop=p_drop)
|
| 244 |
+
|
| 245 |
+
def forward(
|
| 246 |
+
self,
|
| 247 |
+
image: Tensor,
|
| 248 |
+
domains: Sequence[str] = DOMAIN_NAMES,
|
| 249 |
+
p_drop: float = 0.0,
|
| 250 |
+
wavelet_permutation: Tensor | None = None,
|
| 251 |
+
) -> dict:
|
| 252 |
+
if not 0.0 <= p_drop <= 1.0:
|
| 253 |
+
raise ValueError("p_drop must be in [0, 1]")
|
| 254 |
+
if p_drop > 0 and self.training:
|
| 255 |
+
return self._forward_impl(
|
| 256 |
+
image,
|
| 257 |
+
domains,
|
| 258 |
+
p_drop=p_drop,
|
| 259 |
+
wavelet_permutation=wavelet_permutation,
|
| 260 |
+
)
|
| 261 |
+
return self._forward_impl(
|
| 262 |
+
image,
|
| 263 |
+
domains,
|
| 264 |
+
wavelet_permutation=wavelet_permutation,
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# ------------------------------------------------------------------
|
| 268 |
+
# Domain-agreement support
|
| 269 |
+
# ------------------------------------------------------------------
|
| 270 |
+
def solo_domain_forward(self, image: Tensor, domain: str) -> dict:
|
| 271 |
+
"""Prediction using exactly one domain (for L_domain_agreement)."""
|
| 272 |
+
|
| 273 |
+
if domain not in DOMAIN_NAMES:
|
| 274 |
+
raise ValueError(f"domain must be one of {DOMAIN_NAMES}")
|
| 275 |
+
return self.encode(image, domains=(domain,))
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
class SeverityMapLoss(nn.Module):
|
| 279 |
+
"""Weak supervision for the spatial severity map.
|
| 280 |
+
|
| 281 |
+
Region-level labels do not exist in Phase 1, so the map is pulled toward
|
| 282 |
+
the broadcast global severity of its active types. This keeps the head
|
| 283 |
+
calibrated globally until region annotations are introduced.
|
| 284 |
+
"""
|
| 285 |
+
|
| 286 |
+
def __init__(self, weight: float = 0.25):
|
| 287 |
+
super().__init__()
|
| 288 |
+
self.weight = weight
|
| 289 |
+
|
| 290 |
+
def forward(
|
| 291 |
+
self,
|
| 292 |
+
severity_map: Tensor,
|
| 293 |
+
severity_target: Tensor,
|
| 294 |
+
spatial_active: Tensor | None = None,
|
| 295 |
+
) -> Tensor:
|
| 296 |
+
target = severity_target[:, :, None, None].expand_as(severity_map)
|
| 297 |
+
error = F.smooth_l1_loss(severity_map, target, beta=0.1, reduction="none")
|
| 298 |
+
if spatial_active is None:
|
| 299 |
+
return self.weight * error.mean()
|
| 300 |
+
mask = spatial_active[:, None, None, None].to(error.dtype)
|
| 301 |
+
denominator = mask.sum() * error.shape[1] * error.shape[2] * error.shape[3]
|
| 302 |
+
if denominator == 0:
|
| 303 |
+
return error.new_zeros(())
|
| 304 |
+
return self.weight * (error * mask).sum() / denominator
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def create_degradation_transformer(
|
| 308 |
+
ablation: Optional[str] = None,
|
| 309 |
+
loss_config: Optional[LossConfig] = None,
|
| 310 |
+
**overrides,
|
| 311 |
+
) -> Tuple[DualDomainDegradationTransformer, LossConfig]:
|
| 312 |
+
"""Build the model (+ default losses) for an ablation gate preset.
|
| 313 |
+
|
| 314 |
+
A0 pixel-only / A1 wavelet-only are enforced at training time through
|
| 315 |
+
``domains``; A2 swaps cross attention for concat fusion; A3 uses a single
|
| 316 |
+
generic query; A4/A5 (and default) use per-type degradation queries;
|
| 317 |
+
A6 adds the shuffled-wavelet control.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
config = loss_config or LossConfig()
|
| 321 |
+
kwargs = dict(overrides)
|
| 322 |
+
|
| 323 |
+
if ablation == "A2":
|
| 324 |
+
kwargs.setdefault("fusion_mode", "concat")
|
| 325 |
+
kwargs.setdefault("num_queries", 1)
|
| 326 |
+
elif ablation == "A3":
|
| 327 |
+
kwargs.setdefault("num_queries", 1)
|
| 328 |
+
elif ablation == "A6":
|
| 329 |
+
kwargs.setdefault("shuffle_wavelet", True)
|
| 330 |
+
elif ablation not in (None, "A0", "A1", "A4", "A5"):
|
| 331 |
+
raise ValueError(f"Unknown ablation preset: {ablation}")
|
| 332 |
+
|
| 333 |
+
model = DualDomainDegradationTransformer(**kwargs)
|
| 334 |
+
# A0-A4 isolate architecture. Pair/clean regularization enters only at
|
| 335 |
+
# A5; A6 is the same objective with shuffled wavelet correspondence.
|
| 336 |
+
if ablation in ("A0", "A1", "A2", "A3", "A4"):
|
| 337 |
+
config.lambda_clean_zero = 0.0
|
| 338 |
+
config.lambda_pair = 0.0
|
| 339 |
+
if ablation in ("A0", "A1", "A6"):
|
| 340 |
+
config.lambda_domain_agreement = 0.0
|
| 341 |
+
return model, config
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def count_trainable_parameters(model: nn.Module) -> int:
|
| 345 |
+
return sum(p.numel() for p in model.parameters() if p.requires_grad)
|
dataset/phase1_noise_20260906/code/src/models/degradation/spatial_branch.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pixel / illumination spatial branch of the degradation transformer.
|
| 2 |
+
|
| 3 |
+
Low-level hierarchical convolution stem. The input is augmented with physics
|
| 4 |
+
motivated channels that make blur, noise and low-light artifacts visible to a
|
| 5 |
+
small CNN:
|
| 6 |
+
|
| 7 |
+
* RGB (3ch)
|
| 8 |
+
* linear luminance ``Y``
|
| 9 |
+
* log luminance ``log(Y + eps)`` (critical for low-light)
|
| 10 |
+
* local illumination map (heavy low-pass of ``Y``)
|
| 11 |
+
* gradient magnitude (Sobel on ``Y``)
|
| 12 |
+
|
| 13 |
+
Pipeline: conv stem stride 4 -> patch merge -> stage block -> severity map
|
| 14 |
+
head tap at H/8 -> patch merge -> stage block -> 16x16 tokens (dim 96).
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn.functional as F
|
| 21 |
+
from torch import Tensor, nn
|
| 22 |
+
|
| 23 |
+
LUMINANCE_WEIGHTS = (0.2126, 0.7152, 0.0722)
|
| 24 |
+
LOG_EPS = 1e-4
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _luminance(image: Tensor) -> Tensor:
|
| 28 |
+
weights = image.new_tensor(LUMINANCE_WEIGHTS).view(1, 3, 1, 1)
|
| 29 |
+
return (image * weights).sum(dim=1, keepdim=True)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _sobel_magnitude(luma: Tensor) -> Tensor:
|
| 33 |
+
kernel_x = luma.new_tensor(
|
| 34 |
+
[[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]]
|
| 35 |
+
).view(1, 1, 3, 3)
|
| 36 |
+
kernel_y = kernel_x.transpose(-2, -1).contiguous()
|
| 37 |
+
padded = F.pad(luma, (1, 1, 1, 1), mode="reflect")
|
| 38 |
+
gx = F.conv2d(padded, kernel_x)
|
| 39 |
+
gy = F.conv2d(padded, kernel_y)
|
| 40 |
+
return torch.sqrt(gx * gx + gy * gy + 1e-12)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ConvStageBlock(nn.Module):
|
| 44 |
+
"""Depthwise-separable residual block with pointwise expansion."""
|
| 45 |
+
|
| 46 |
+
def __init__(self, dim: int, expansion: int = 4):
|
| 47 |
+
super().__init__()
|
| 48 |
+
hidden = dim * expansion
|
| 49 |
+
self.norm = nn.GroupNorm(1, dim)
|
| 50 |
+
self.dw = nn.Conv2d(dim, dim, 3, padding=1, groups=dim)
|
| 51 |
+
self.pw1 = nn.Conv2d(dim, hidden, 1)
|
| 52 |
+
self.pw2 = nn.Conv2d(hidden, dim, 1)
|
| 53 |
+
|
| 54 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 55 |
+
y = self.norm(x)
|
| 56 |
+
y = self.dw(y)
|
| 57 |
+
y = self.pw2(F.gelu(self.pw1(y)))
|
| 58 |
+
return x + y
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class PatchMerge(nn.Module):
|
| 62 |
+
"""Merge a 2x2 neighborhood into one token; keeps the channel width."""
|
| 63 |
+
|
| 64 |
+
def __init__(self, dim: int):
|
| 65 |
+
super().__init__()
|
| 66 |
+
self.norm = nn.LayerNorm(4 * dim)
|
| 67 |
+
self.proj = nn.Linear(4 * dim, dim)
|
| 68 |
+
|
| 69 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 70 |
+
b, c, h, w = x.shape
|
| 71 |
+
x = x.reshape(b, c, h // 2, 2, w // 2, 2)
|
| 72 |
+
x = x.permute(0, 2, 4, 3, 5, 1).reshape(b, h // 2, w // 2, 4 * c)
|
| 73 |
+
return self.proj(self.norm(x)).permute(0, 3, 1, 2)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class SpatialBranch(nn.Module):
|
| 77 |
+
"""Hierarchical pixel/illumination encoder.
|
| 78 |
+
|
| 79 |
+
Returns spatial tokens at H/16 (default 16x16 for 256px crops, dim 96) plus
|
| 80 |
+
the H/8 feature map used by the spatial severity-map head.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
def __init__(self, token_dim: int = 96, in_channels: int = 7, blocks_per_stage: int = 2):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.token_dim = token_dim
|
| 86 |
+
self.stem = nn.Sequential(
|
| 87 |
+
nn.Conv2d(in_channels, token_dim, kernel_size=7, stride=4, padding=3),
|
| 88 |
+
nn.GroupNorm(1, token_dim),
|
| 89 |
+
nn.GELU(),
|
| 90 |
+
ConvStageBlock(token_dim),
|
| 91 |
+
)
|
| 92 |
+
self.merge_s8 = PatchMerge(token_dim)
|
| 93 |
+
self.stage_s8 = nn.Sequential(*[ConvStageBlock(token_dim) for _ in range(blocks_per_stage)])
|
| 94 |
+
self.merge_s16 = PatchMerge(token_dim)
|
| 95 |
+
self.stage_s16 = nn.Sequential(*[ConvStageBlock(token_dim) for _ in range(blocks_per_stage)])
|
| 96 |
+
|
| 97 |
+
@staticmethod
|
| 98 |
+
def build_input(image: Tensor) -> Tensor:
|
| 99 |
+
if image.ndim != 4 or image.shape[1] != 3:
|
| 100 |
+
raise ValueError(f"Expected NCHW RGB image, got {tuple(image.shape)}")
|
| 101 |
+
luma = _luminance(image)
|
| 102 |
+
log_luma = torch.log(luma.clamp_min(LOG_EPS))
|
| 103 |
+
illumination = F.avg_pool2d(
|
| 104 |
+
luma, kernel_size=15, stride=1, padding=7, count_include_pad=False
|
| 105 |
+
)
|
| 106 |
+
gradient = _sobel_magnitude(luma)
|
| 107 |
+
return torch.cat([image, luma, log_luma, illumination, gradient], dim=1)
|
| 108 |
+
|
| 109 |
+
def forward(self, image: Tensor) -> dict:
|
| 110 |
+
feat = self.stem(self.build_input(image)) # H/4
|
| 111 |
+
feat_s8 = self.stage_s8(self.merge_s8(feat)) # H/8
|
| 112 |
+
feat_s16 = self.stage_s16(self.merge_s16(feat_s8)) # H/16
|
| 113 |
+
tokens = feat_s16.flatten(2).transpose(1, 2) # [B, (H/16)^2, C]
|
| 114 |
+
return {"tokens": tokens, "feat_s8": feat_s8, "feat_s16": feat_s16}
|
dataset/phase1_noise_20260906/code/src/models/degradation/transformer.py
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Dual-domain fusion transformer with degradation queries.
|
| 2 |
+
|
| 3 |
+
Five learned queries (one per known degradation plus ``unknown``) cross-attend
|
| 4 |
+
into the spatial tokens and the wavelet tokens, then pass an FFN. No full
|
| 5 |
+
self-attention over thousands of tokens is used; only the five queries do the
|
| 6 |
+
heavy lifting, which keeps the block cheap.
|
| 7 |
+
|
| 8 |
+
Per-domain updates can be disabled per sample, which implements explicit
|
| 9 |
+
domain selection and stochastic modality dropout without ever presenting an
|
| 10 |
+
all-masked memory to ``MultiheadAttention``.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from torch import Tensor, nn
|
| 18 |
+
|
| 19 |
+
from .constants import NUM_TYPE_CLASSES, NUM_KNOWN_TYPES
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class CrossAttentionBlock(nn.Module):
|
| 23 |
+
"""Pre-norm multi-head cross attention with residual."""
|
| 24 |
+
|
| 25 |
+
def __init__(self, hidden_dim: int, num_heads: int):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.norm_q = nn.LayerNorm(hidden_dim)
|
| 28 |
+
self.norm_kv = nn.LayerNorm(hidden_dim)
|
| 29 |
+
self.attn = nn.MultiheadAttention(hidden_dim, num_heads, batch_first=True, dropout=0.1)
|
| 30 |
+
# Initialize attention weights
|
| 31 |
+
for p in self.attn.parameters():
|
| 32 |
+
if p.dim() > 1:
|
| 33 |
+
nn.init.xavier_uniform_(p)
|
| 34 |
+
|
| 35 |
+
def forward(
|
| 36 |
+
self,
|
| 37 |
+
queries: Tensor,
|
| 38 |
+
kv: Tensor,
|
| 39 |
+
active: Tensor | None = None,
|
| 40 |
+
) -> Tensor:
|
| 41 |
+
residual = queries
|
| 42 |
+
q = self.norm_q(queries)
|
| 43 |
+
k = self.norm_kv(kv)
|
| 44 |
+
out, _ = self.attn(q, k, k, need_weights=False)
|
| 45 |
+
if active is not None:
|
| 46 |
+
out = out * active[:, None, None].to(dtype=out.dtype)
|
| 47 |
+
return residual + out
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class FeedForwardBlock(nn.Module):
|
| 51 |
+
def __init__(self, hidden_dim: int, expansion: int = 4):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.norm = nn.LayerNorm(hidden_dim)
|
| 54 |
+
self.fc1 = nn.Linear(hidden_dim, hidden_dim * expansion)
|
| 55 |
+
self.fc2 = nn.Linear(hidden_dim * expansion, hidden_dim)
|
| 56 |
+
# Initialize
|
| 57 |
+
nn.init.xavier_uniform_(self.fc1.weight)
|
| 58 |
+
nn.init.xavier_uniform_(self.fc2.weight)
|
| 59 |
+
|
| 60 |
+
def forward(self, x: Tensor) -> Tensor:
|
| 61 |
+
return x + self.fc2(F.gelu(self.fc1(self.norm(x))))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class QuerySelfAttention(nn.Module):
|
| 65 |
+
"""Self-attention among the handful of degradation queries.
|
| 66 |
+
|
| 67 |
+
Cheap (five tokens) and lets queries calibrate each other, which
|
| 68 |
+
stabilizes the per-type confidence head.
|
| 69 |
+
"""
|
| 70 |
+
|
| 71 |
+
def __init__(self, hidden_dim: int, num_heads: int):
|
| 72 |
+
super().__init__()
|
| 73 |
+
self.norm = nn.LayerNorm(hidden_dim)
|
| 74 |
+
self.attn = nn.MultiheadAttention(hidden_dim, num_heads, batch_first=True, dropout=0.1)
|
| 75 |
+
# Initialize attention weights
|
| 76 |
+
for p in self.attn.parameters():
|
| 77 |
+
if p.dim() > 1:
|
| 78 |
+
nn.init.xavier_uniform_(p)
|
| 79 |
+
|
| 80 |
+
def forward(self, queries: Tensor) -> Tensor:
|
| 81 |
+
x = self.norm(queries)
|
| 82 |
+
out, _ = self.attn(x, x, x, need_weights=False)
|
| 83 |
+
return queries + out
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class DualDomainFusion(nn.Module):
|
| 87 |
+
"""Query-based dual-domain transformer.
|
| 88 |
+
|
| 89 |
+
Args:
|
| 90 |
+
token_dim: input width of spatial and wavelet tokens.
|
| 91 |
+
hidden_dim: transformer width.
|
| 92 |
+
num_queries: number of degradation queries (5 by default).
|
| 93 |
+
num_blocks: number of [cross(spatial), cross(wavelet), FFN] blocks.
|
| 94 |
+
num_heads: attention heads.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
SPATIAL_DOMAIN = 0
|
| 98 |
+
WAVELET_DOMAIN = 1
|
| 99 |
+
|
| 100 |
+
def __init__(
|
| 101 |
+
self,
|
| 102 |
+
token_dim: int = 96,
|
| 103 |
+
hidden_dim: int = 192,
|
| 104 |
+
num_queries: int = 5,
|
| 105 |
+
num_blocks: int = 4,
|
| 106 |
+
num_heads: int = 4,
|
| 107 |
+
):
|
| 108 |
+
super().__init__()
|
| 109 |
+
self.hidden_dim = hidden_dim
|
| 110 |
+
self.num_queries = num_queries
|
| 111 |
+
self.input_proj_spatial = nn.Linear(token_dim, hidden_dim)
|
| 112 |
+
self.input_proj_wavelet = nn.Linear(token_dim, hidden_dim)
|
| 113 |
+
self.domain_embed = nn.Parameter(torch.zeros(2, hidden_dim))
|
| 114 |
+
nn.init.xavier_uniform_(self.domain_embed)
|
| 115 |
+
|
| 116 |
+
# Learnable positional embedding stored on a 16x16 grid; interpolated
|
| 117 |
+
# for other spatial token resolutions.
|
| 118 |
+
self.pos_spatial = nn.Parameter(torch.zeros(256, hidden_dim))
|
| 119 |
+
nn.init.xavier_uniform_(self.pos_spatial)
|
| 120 |
+
self.pos_wavelet = nn.Parameter(torch.zeros(20, hidden_dim))
|
| 121 |
+
nn.init.xavier_uniform_(self.pos_wavelet)
|
| 122 |
+
|
| 123 |
+
# Initialize queries with class-specific patterns
|
| 124 |
+
self.queries = nn.Parameter(torch.zeros(num_queries, hidden_dim))
|
| 125 |
+
nn.init.xavier_uniform_(self.queries)
|
| 126 |
+
# Add small bias to each query to make them initially different
|
| 127 |
+
for i in range(num_queries):
|
| 128 |
+
self.queries.data[i, i * (hidden_dim // num_queries):(i + 1) * (hidden_dim // num_queries)] += 0.1
|
| 129 |
+
|
| 130 |
+
self.cross_spatial = nn.ModuleList(
|
| 131 |
+
[CrossAttentionBlock(hidden_dim, num_heads) for _ in range(num_blocks)]
|
| 132 |
+
)
|
| 133 |
+
self.cross_wavelet = nn.ModuleList(
|
| 134 |
+
[CrossAttentionBlock(hidden_dim, num_heads) for _ in range(num_blocks)]
|
| 135 |
+
)
|
| 136 |
+
self.query_self_attn = nn.ModuleList(
|
| 137 |
+
[QuerySelfAttention(hidden_dim, num_heads) for _ in range(num_blocks)]
|
| 138 |
+
)
|
| 139 |
+
self.ffns = nn.ModuleList(
|
| 140 |
+
[FeedForwardBlock(hidden_dim) for _ in range(num_blocks)]
|
| 141 |
+
)
|
| 142 |
+
self.final_norm = nn.LayerNorm(hidden_dim)
|
| 143 |
+
|
| 144 |
+
def _interpolate_pos(self, grid_h: int, grid_w: int) -> Tensor:
|
| 145 |
+
base = self.pos_spatial.reshape(16, 16, self.hidden_dim).permute(2, 0, 1)
|
| 146 |
+
if grid_h == 16 and grid_w == 16:
|
| 147 |
+
return self.pos_spatial
|
| 148 |
+
pos = F.interpolate(base.unsqueeze(0), size=(grid_h, grid_w), mode="bicubic", align_corners=False)
|
| 149 |
+
return pos.squeeze(0).flatten(1).t()
|
| 150 |
+
|
| 151 |
+
def forward(
|
| 152 |
+
self,
|
| 153 |
+
spatial_tokens: Tensor,
|
| 154 |
+
wavelet_tokens: Tensor,
|
| 155 |
+
active_domains: Tensor = None,
|
| 156 |
+
) -> Tensor:
|
| 157 |
+
"""Return final query states [B, num_queries, hidden].
|
| 158 |
+
|
| 159 |
+
``active_domains`` [B, 2]: optional per-sample domain availability;
|
| 160 |
+
used for modality dropout and ablations.
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
b = spatial_tokens.shape[0]
|
| 164 |
+
kv_spatial = self.input_proj_spatial(spatial_tokens)
|
| 165 |
+
kv_wavelet = self.input_proj_wavelet(wavelet_tokens)
|
| 166 |
+
|
| 167 |
+
grid_h = int(kv_spatial.shape[1] ** 0.5)
|
| 168 |
+
pos = self._interpolate_pos(grid_h, grid_h)[: kv_spatial.shape[1]]
|
| 169 |
+
kv_spatial = kv_spatial + pos + self.domain_embed[self.SPATIAL_DOMAIN]
|
| 170 |
+
|
| 171 |
+
n_wav = kv_wavelet.shape[1]
|
| 172 |
+
kv_wavelet = (
|
| 173 |
+
kv_wavelet
|
| 174 |
+
+ self.pos_wavelet[:n_wav]
|
| 175 |
+
+ self.domain_embed[self.WAVELET_DOMAIN]
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
if active_domains is None:
|
| 179 |
+
active_domains = torch.ones(b, 2, dtype=torch.bool, device=kv_spatial.device)
|
| 180 |
+
if active_domains.shape != (b, 2):
|
| 181 |
+
raise ValueError("active_domains must be [B, 2]")
|
| 182 |
+
if not active_domains.any(dim=1).all():
|
| 183 |
+
raise ValueError("Every sample needs at least one active domain")
|
| 184 |
+
|
| 185 |
+
queries = self.queries.unsqueeze(0).expand(b, -1, -1)
|
| 186 |
+
for cross_s, cross_w, self_attn, ffn in zip(
|
| 187 |
+
self.cross_spatial, self.cross_wavelet, self.query_self_attn, self.ffns
|
| 188 |
+
):
|
| 189 |
+
queries = cross_s(
|
| 190 |
+
queries,
|
| 191 |
+
kv_spatial,
|
| 192 |
+
active_domains[:, self.SPATIAL_DOMAIN],
|
| 193 |
+
)
|
| 194 |
+
queries = cross_w(
|
| 195 |
+
queries,
|
| 196 |
+
kv_wavelet,
|
| 197 |
+
active_domains[:, self.WAVELET_DOMAIN],
|
| 198 |
+
)
|
| 199 |
+
queries = self_attn(queries)
|
| 200 |
+
queries = ffn(queries)
|
| 201 |
+
return self.final_norm(queries)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class DegradationHeads(nn.Module):
|
| 205 |
+
"""Prediction heads on top of the query states."""
|
| 206 |
+
|
| 207 |
+
def __init__(self, hidden_dim: int = 192, embed_dim: int = 128):
|
| 208 |
+
super().__init__()
|
| 209 |
+
# Query k owns class k: one logit per query -> [B, 5].
|
| 210 |
+
self.type_head = nn.Linear(hidden_dim, 1)
|
| 211 |
+
# Known-type queries predict their own normalized severity.
|
| 212 |
+
self.severity_head = nn.Linear(hidden_dim, 1)
|
| 213 |
+
self.embedding_head = nn.Sequential(
|
| 214 |
+
nn.Linear(hidden_dim * NUM_TYPE_CLASSES, hidden_dim),
|
| 215 |
+
nn.GELU(),
|
| 216 |
+
nn.Linear(hidden_dim, embed_dim),
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
def forward(self, query_states: Tensor) -> dict:
|
| 220 |
+
type_logits = self.type_head(query_states).squeeze(-1) # [B, 5]
|
| 221 |
+
severity = torch.sigmoid(
|
| 222 |
+
self.severity_head(query_states[:, :NUM_KNOWN_TYPES]).squeeze(-1)
|
| 223 |
+
) # [B, 4]
|
| 224 |
+
flat = query_states.flatten(1)
|
| 225 |
+
embedding = self.embedding_head(flat) # [B, embed_dim]
|
| 226 |
+
return {
|
| 227 |
+
"type_logits": type_logits,
|
| 228 |
+
"confidence": torch.sigmoid(type_logits),
|
| 229 |
+
"severity": severity,
|
| 230 |
+
"degradation_embedding": embedding,
|
| 231 |
+
}
|
dataset/phase1_noise_20260906/code/src/models/degradation/wavelet_branch.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Wavelet frequency branch of the degradation transformer.
|
| 2 |
+
|
| 3 |
+
Fixed 3-level Haar DWT. Every band is pooled to a common 4x4 grid (mean map,
|
| 4 |
+
local RMS energy map, log-energy map) before concatenation, so all bands
|
| 5 |
+
contribute tokens at the same resolution. A global summary vector adds the
|
| 6 |
+
low-light aware statistics that pure high-frequency descriptors miss:
|
| 7 |
+
|
| 8 |
+
* LL1/LL2/LL3 energies and the log ratio of LL vs high-frequency energy
|
| 9 |
+
* local contrast relative to LL
|
| 10 |
+
* dark-region occupancy at several luminance thresholds
|
| 11 |
+
* per-band global log-energy scalars
|
| 12 |
+
|
| 13 |
+
Output: 16 map tokens + 4 summary tokens of dim ``token_dim``.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
from typing import Dict
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from torch import Tensor, nn
|
| 23 |
+
|
| 24 |
+
POOL = 4
|
| 25 |
+
DARK_THRESHOLDS = (0.05, 0.10, 0.20)
|
| 26 |
+
BAND_ORDER = ("lh", "hl", "hh")
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def haar_dwt3(image: Tensor) -> Dict[str, Tensor]:
|
| 30 |
+
"""Return the twelve Haar bands of a BCHW image."""
|
| 31 |
+
|
| 32 |
+
def step(x: Tensor):
|
| 33 |
+
h, w = x.shape[-2] // 2 * 2, x.shape[-1] // 2 * 2
|
| 34 |
+
x = x[..., :h, :w]
|
| 35 |
+
ll = (
|
| 36 |
+
x[..., 0::2, 0::2]
|
| 37 |
+
+ x[..., 0::2, 1::2]
|
| 38 |
+
+ x[..., 1::2, 0::2]
|
| 39 |
+
+ x[..., 1::2, 1::2]
|
| 40 |
+
) / 2.0
|
| 41 |
+
lh = (
|
| 42 |
+
x[..., 0::2, 0::2]
|
| 43 |
+
+ x[..., 0::2, 1::2]
|
| 44 |
+
- x[..., 1::2, 0::2]
|
| 45 |
+
- x[..., 1::2, 1::2]
|
| 46 |
+
) / 2.0
|
| 47 |
+
hl = (
|
| 48 |
+
x[..., 0::2, 0::2]
|
| 49 |
+
- x[..., 0::2, 1::2]
|
| 50 |
+
+ x[..., 1::2, 0::2]
|
| 51 |
+
- x[..., 1::2, 1::2]
|
| 52 |
+
) / 2.0
|
| 53 |
+
hh = (
|
| 54 |
+
x[..., 0::2, 0::2]
|
| 55 |
+
- x[..., 0::2, 1::2]
|
| 56 |
+
- x[..., 1::2, 0::2]
|
| 57 |
+
+ x[..., 1::2, 1::2]
|
| 58 |
+
) / 2.0
|
| 59 |
+
return ll, lh, hl, hh
|
| 60 |
+
|
| 61 |
+
ll1, lh1, hl1, hh1 = step(image)
|
| 62 |
+
ll2, lh2, hl2, hh2 = step(ll1)
|
| 63 |
+
ll3, lh3, hl3, hh3 = step(ll2)
|
| 64 |
+
return {
|
| 65 |
+
"ll1": ll1, "lh1": lh1, "hl1": hl1, "hh1": hh1,
|
| 66 |
+
"ll2": ll2, "lh2": lh2, "hl2": hl2, "hh2": hh2,
|
| 67 |
+
"ll3": ll3, "lh3": lh3, "hl3": hl3, "hh3": hh3,
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class WaveletBranch(nn.Module):
|
| 72 |
+
def __init__(self, channels: int = 3, token_dim: int = 96, num_summary_tokens: int = 4):
|
| 73 |
+
super().__init__()
|
| 74 |
+
self.token_dim = token_dim
|
| 75 |
+
self.num_summary_tokens = num_summary_tokens
|
| 76 |
+
self.band_features = 3 * channels # mean map, rms map, log-rms map
|
| 77 |
+
num_bands = 12
|
| 78 |
+
self.map_proj = nn.Sequential(
|
| 79 |
+
nn.Conv2d(num_bands * self.band_features, token_dim * 2, kernel_size=1),
|
| 80 |
+
nn.GELU(),
|
| 81 |
+
nn.Conv2d(token_dim * 2, token_dim, kernel_size=1),
|
| 82 |
+
nn.GroupNorm(1, token_dim),
|
| 83 |
+
nn.GELU(),
|
| 84 |
+
)
|
| 85 |
+
# Level LL/HF energies + ratio + contrast (4 x 3 levels)
|
| 86 |
+
# + occupancy(3) + luma stats(2) + per-band log-energy(12)
|
| 87 |
+
stats_dim = 29
|
| 88 |
+
self.summary_proj = nn.Sequential(
|
| 89 |
+
nn.Linear(stats_dim, token_dim * num_summary_tokens),
|
| 90 |
+
nn.GELU(),
|
| 91 |
+
nn.LayerNorm(token_dim * num_summary_tokens),
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def band_maps(self, bands: Dict[str, Tensor]) -> Tensor:
|
| 95 |
+
maps = []
|
| 96 |
+
for level in ("1", "2", "3"):
|
| 97 |
+
for prefix in ("ll",) + BAND_ORDER:
|
| 98 |
+
band = bands[f"{prefix}{level}"]
|
| 99 |
+
pooled = F.adaptive_avg_pool2d(band, POOL)
|
| 100 |
+
rms = torch.sqrt(
|
| 101 |
+
F.adaptive_avg_pool2d(band * band, POOL).clamp_min(1e-8)
|
| 102 |
+
)
|
| 103 |
+
maps.extend([pooled, rms, torch.log(rms + 1e-4)])
|
| 104 |
+
return torch.cat(maps, dim=1)
|
| 105 |
+
|
| 106 |
+
@staticmethod
|
| 107 |
+
def global_stats(bands: Dict[str, Tensor]) -> Tensor:
|
| 108 |
+
features = []
|
| 109 |
+
for level in ("1", "2", "3"):
|
| 110 |
+
hf_rms = torch.sqrt(
|
| 111 |
+
F.adaptive_avg_pool2d(
|
| 112 |
+
sum((bands[f"{p}{level}"] ** 2 for p in BAND_ORDER)), POOL
|
| 113 |
+
).clamp_min(1e-8)
|
| 114 |
+
).mean(dim=1) # [B, 4, 4]
|
| 115 |
+
ll_abs = bands[f"ll{level}"].abs().mean(dim=1, keepdim=True)
|
| 116 |
+
ll_pooled = F.adaptive_avg_pool2d(ll_abs, POOL).squeeze(1) # [B, 4, 4]
|
| 117 |
+
ll_energy = ll_pooled.mean(dim=(1, 2))
|
| 118 |
+
hf_energy = hf_rms.mean(dim=(1, 2))
|
| 119 |
+
features.append(torch.log(ll_energy + 1e-4))
|
| 120 |
+
features.append(torch.log(hf_energy + 1e-4))
|
| 121 |
+
# LL vs high-frequency energy ratio (log space).
|
| 122 |
+
features.append(torch.log((ll_energy + 1e-4) / (hf_energy + 1e-4)))
|
| 123 |
+
# Local contrast relative to LL.
|
| 124 |
+
contrast = (hf_rms / (ll_pooled + 0.05)).mean(dim=(1, 2))
|
| 125 |
+
features.append(torch.log(contrast + 1e-4))
|
| 126 |
+
if level == "1":
|
| 127 |
+
weights = bands["ll1"].new_tensor(
|
| 128 |
+
[0.2126, 0.7152, 0.0722]
|
| 129 |
+
).view(1, 3, 1, 1)
|
| 130 |
+
# Haar LL1 uses /2, so its DC response is 2x the local RGB
|
| 131 |
+
# mean. Undo that scale before applying raw-image thresholds.
|
| 132 |
+
luma = (bands["ll1"] * weights).sum(dim=1) / 2.0
|
| 133 |
+
for threshold in DARK_THRESHOLDS:
|
| 134 |
+
features.append((luma < threshold).float().mean(dim=(1, 2)))
|
| 135 |
+
features.append(luma.mean(dim=(1, 2)))
|
| 136 |
+
features.append(luma.std(dim=(1, 2)))
|
| 137 |
+
for name in (
|
| 138 |
+
"ll1", "lh1", "hl1", "hh1",
|
| 139 |
+
"ll2", "lh2", "hl2", "hh2",
|
| 140 |
+
"ll3", "lh3", "hl3", "hh3",
|
| 141 |
+
):
|
| 142 |
+
band = bands[name]
|
| 143 |
+
energy = (band * band).mean(dim=(1, 2, 3)).clamp_min(1e-8)
|
| 144 |
+
features.append(torch.log(energy))
|
| 145 |
+
return torch.stack(features, dim=1)
|
| 146 |
+
|
| 147 |
+
def forward(self, image: Tensor) -> dict:
|
| 148 |
+
if image.ndim != 4 or image.shape[1] != 3:
|
| 149 |
+
raise ValueError(f"Expected NCHW RGB image, got {tuple(image.shape)}")
|
| 150 |
+
bands = haar_dwt3(image)
|
| 151 |
+
map_feats = self.map_proj(self.band_maps(bands)) # [B, D, 4, 4]
|
| 152 |
+
b, d = map_feats.shape[:2]
|
| 153 |
+
map_tokens = map_feats.flatten(2).transpose(1, 2) # [B, 16, D]
|
| 154 |
+
stats = self.global_stats(bands)
|
| 155 |
+
summary = self.summary_proj(stats).reshape(b, self.num_summary_tokens, d)
|
| 156 |
+
tokens = torch.cat([map_tokens, summary], dim=1)
|
| 157 |
+
return {"tokens": tokens, "stats": stats, "bands": bands}
|
| 158 |
+
|
| 159 |
+
@staticmethod
|
| 160 |
+
def num_tokens() -> int:
|
| 161 |
+
return POOL * POOL + 4
|
dataset/phase1_noise_20260906/code/src/models/graph_encoder/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Graph Encoder Package."""
|
| 2 |
+
|
| 3 |
+
from .representation import (
|
| 4 |
+
GraphRepresentation,
|
| 5 |
+
BranchAnchor,
|
| 6 |
+
GraphConfig,
|
| 7 |
+
SEMANTIC_BRANCH_NAMES,
|
| 8 |
+
SEMANTIC_BRANCH_COLORS,
|
| 9 |
+
aggregate_graph_condition,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
from .encoder import (
|
| 13 |
+
CleanRootAnchor,
|
| 14 |
+
SemanticBranch,
|
| 15 |
+
FreeLatentNodes,
|
| 16 |
+
SpatialEncoder,
|
| 17 |
+
GraphStatePredictor,
|
| 18 |
+
NodeTokenGenerator,
|
| 19 |
+
BlindDegradationGraphEncoder,
|
| 20 |
+
create_graph_encoder,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
from .losses import (
|
| 24 |
+
GraphLoss,
|
| 25 |
+
RootLoss,
|
| 26 |
+
DistillationLoss,
|
| 27 |
+
BranchSeparationLoss,
|
| 28 |
+
GeodesicSeverityLoss,
|
| 29 |
+
RankingLoss,
|
| 30 |
+
ContentInvarianceLoss,
|
| 31 |
+
CompositionLoss,
|
| 32 |
+
SparseRoutingLoss,
|
| 33 |
+
UtilityLoss,
|
| 34 |
+
TypeClassificationLoss,
|
| 35 |
+
CombinedGraphLoss,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
__all__ = [
|
| 39 |
+
"GraphRepresentation", "BranchAnchor", "GraphConfig",
|
| 40 |
+
"SEMANTIC_BRANCH_NAMES", "SEMANTIC_BRANCH_COLORS",
|
| 41 |
+
"CleanRootAnchor", "SemanticBranch", "FreeLatentNodes",
|
| 42 |
+
"SpatialEncoder", "GraphStatePredictor", "NodeTokenGenerator",
|
| 43 |
+
"BlindDegradationGraphEncoder", "create_graph_encoder",
|
| 44 |
+
"GraphLoss", "RootLoss", "DistillationLoss", "BranchSeparationLoss",
|
| 45 |
+
"GeodesicSeverityLoss", "RankingLoss", "ContentInvarianceLoss",
|
| 46 |
+
"CompositionLoss", "SparseRoutingLoss", "UtilityLoss",
|
| 47 |
+
"TypeClassificationLoss", "CombinedGraphLoss",
|
| 48 |
+
]
|
dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.21 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/clean_relative.cpython-312.pyc
ADDED
|
Binary file (32.1 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/encoder.cpython-312.pyc
ADDED
|
Binary file (36 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/hvi.cpython-312.pyc
ADDED
|
Binary file (8.37 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/losses.cpython-312.pyc
ADDED
|
Binary file (19.9 kB). View file
|
|
|
dataset/phase1_noise_20260906/code/src/models/graph_encoder/__pycache__/representation.cpython-312.pyc
ADDED
|
Binary file (9.99 kB). View file
|
|
|