anbinh39 commited on
Commit
47e8532
·
verified ·
1 Parent(s): 754772a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. dataset/phase1_noise_20260906/code/diagnose_phase1_routing.py +77 -0
  2. dataset/phase1_noise_20260906/code/download_all_datasets.sh +118 -0
  3. dataset/phase1_noise_20260906/code/download_rain200h.sh +61 -0
  4. dataset/phase1_noise_20260906/code/eval_full_frame.py +424 -0
  5. dataset/phase1_noise_20260906/code/eval_gen2_external.py +61 -0
  6. dataset/phase1_noise_20260906/code/eval_phase1_clean_relative.py +475 -0
  7. dataset/phase1_noise_20260906/code/eval_pipeline_external.py +143 -0
  8. dataset/phase1_noise_20260906/code/eval_v7_external.py +147 -0
  9. dataset/phase1_noise_20260906/code/gate_phase1.sh +48 -0
  10. dataset/phase1_noise_20260906/code/hf_bundle_upload.py +193 -0
  11. dataset/phase1_noise_20260906/code/infer_scdc_pipeline.py +200 -0
  12. dataset/phase1_noise_20260906/code/make_final_charts.py +177 -0
  13. dataset/phase1_noise_20260906/code/probe_color_space.py +291 -0
  14. dataset/phase1_noise_20260906/code/probe_phase1_scale.py +240 -0
  15. dataset/phase1_noise_20260906/code/probe_pregain.py +61 -0
  16. dataset/phase1_noise_20260906/code/probe_scene008_tone.py +129 -0
  17. dataset/phase1_noise_20260906/code/probe_v11_memory.py +96 -0
  18. dataset/phase1_noise_20260906/code/quick_eval_every.sh +32 -0
  19. dataset/phase1_noise_20260906/code/run_ablation_C_only.sh +73 -0
  20. dataset/phase1_noise_20260906/code/run_ablation_C_then_eval.sh +88 -0
  21. dataset/phase1_noise_20260906/code/run_ablation_photometric.sh +94 -0
  22. dataset/phase1_noise_20260906/code/run_ablation_seq.sh +96 -0
  23. dataset/phase1_noise_20260906/code/run_phase1_v5c.sh +53 -0
  24. dataset/phase1_noise_20260906/code/run_phase1_v5d.sh +43 -0
  25. dataset/phase1_noise_20260906/code/run_phase1_v5e.sh +57 -0
  26. dataset/phase1_noise_20260906/code/run_uformer_dgf8k.sh +87 -0
  27. dataset/phase1_noise_20260906/code/run_uformer_head8k.sh +85 -0
  28. dataset/phase1_noise_20260906/code/run_uformer_luma8k.sh +84 -0
  29. dataset/phase1_noise_20260906/code/run_uformer_nophase1.sh +87 -0
  30. dataset/phase1_noise_20260906/code/run_uformer_p45.sh +87 -0
  31. dataset/phase1_noise_20260906/code/run_uformer_p5.sh +87 -0
  32. dataset/phase1_noise_20260906/code/run_uformer_v10.sh +137 -0
  33. dataset/phase1_noise_20260906/code/run_uformer_v10ab_resume.sh +71 -0
  34. dataset/phase1_noise_20260906/code/run_uformer_v11.sh +221 -0
  35. dataset/phase1_noise_20260906/code/run_uformer_v11_mi325x.sh +120 -0
  36. dataset/phase1_noise_20260906/code/run_uformer_v8a.sh +93 -0
  37. dataset/phase1_noise_20260906/code/run_uformer_v8b.sh +93 -0
  38. dataset/phase1_noise_20260906/code/run_uformer_v8c.sh +93 -0
  39. dataset/phase1_noise_20260906/code/run_uformer_v9b.sh +103 -0
  40. dataset/phase1_noise_20260906/code/run_v12_mi325x.sh +40 -0
  41. dataset/phase1_noise_20260906/code/run_v8_after_v5.sh +91 -0
  42. dataset/phase1_noise_20260906/code/run_v8_postrun.sh +35 -0
  43. dataset/phase1_noise_20260906/code/supervise_uformer16k.sh +70 -0
  44. dataset/phase1_noise_20260906/code/test_train_graph_encoder_v2.py +908 -0
  45. dataset/phase1_noise_20260906/code/train_graph_encoder_v2.py +0 -0
  46. dataset/phase1_noise_20260906/code/train_phase1_clean_relative.py +596 -0
  47. dataset/phase1_noise_20260906/code/train_phase2_gated_resshift_v5.py +1145 -0
  48. dataset/phase1_noise_20260906/code/train_phase2_graph_moe_v6.py +468 -0
  49. dataset/phase1_noise_20260906/code/train_phase2_graph_resshift_v4.py +2119 -0
  50. dataset/phase1_noise_20260906/code/train_phase2_unified_v7.py +1354 -0
dataset/phase1_noise_20260906/code/diagnose_phase1_routing.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Routing / severity diagnosis of a Phase-1 checkpoint on the cases that
3
+ exposed the noise-concept drift: SIDD val noisy inputs and their clean GT,
4
+ scene008 (locked, nearly clean, dark textured), and lowlight inputs.
5
+ Prints mean routing per node and mean severity per branch for each group."""
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ from pathlib import Path
12
+
13
+ import torch
14
+
15
+ import eval_pipeline_external as ext
16
+ import train_graph_encoder_v2 as p1
17
+ import train_phase2_graph_resshift_v4 as v4
18
+ from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest
19
+
20
+ NODES = ("rain", "noise", "haze", "lowlight", "free1", "free2")
21
+
22
+
23
+ def _summary(phase1, batch: torch.Tensor) -> dict:
24
+ with torch.no_grad():
25
+ rep = phase1(batch)
26
+ routing = rep.routing_probs.mean(0).tolist()
27
+ severity = rep.severity_coords.mean(0).tolist()
28
+ argmax = rep.routing_probs.argmax(1)
29
+ return {
30
+ "routing": {n: round(v, 3) for n, v in zip(NODES, routing)},
31
+ "severity": {n: round(v, 3) for n, v in zip(NODES[:4], severity)},
32
+ "argmax_share": {n: round(float((argmax == i).float().mean()), 2) for i, n in enumerate(NODES)},
33
+ "mean_luma": round(float(batch.mean()), 3),
34
+ "n": int(batch.shape[0]),
35
+ }
36
+
37
+
38
+ def main() -> None:
39
+ parser = argparse.ArgumentParser(description=__doc__)
40
+ parser.add_argument("--checkpoint", type=Path, required=True)
41
+ parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json"))
42
+ parser.add_argument("--output", type=Path, default=None)
43
+ args = parser.parse_args()
44
+ device = torch.device("cuda")
45
+ import hashlib
46
+ sha = hashlib.sha256(args.checkpoint.read_bytes()).hexdigest()
47
+ phase1, _ = v4.build_frozen_phase1(args.checkpoint, sha, device)
48
+
49
+ p1_args = p1.build_parser().parse_args([])
50
+ splits = p1.build_data_splits(p1_args)
51
+ noise_locked = [r for r in splits.locked_test if r.degradation == "noise"]
52
+ ds = ext.PairCropDataset(noise_locked)
53
+ s8_deg = torch.stack([ds[i]["degraded"] for i in range(len(noise_locked))]).to(device)
54
+ s8_cln = torch.stack([ds[i]["clean"] for i in range(len(noise_locked))]).to(device)
55
+
56
+ vs = load_train_val_manifest(args.manifest)
57
+ vd = Phase2PairDataset(vs.val, crop_size=256, training=False, upscale_small=True)
58
+ groups = {}
59
+ for domain in ("noise", "lowlight", "rain", "haze"):
60
+ idx = [i for i, r in enumerate(vs.val) if r.degradation == domain][:20]
61
+ groups["val_%s_input" % domain] = torch.stack([vd[i]["degraded"] for i in idx]).to(device)
62
+ groups["val_%s_clean" % domain] = torch.stack([vd[i]["clean"] for i in idx]).to(device)
63
+ groups["scene008_input"] = s8_deg
64
+ groups["scene008_clean"] = s8_cln
65
+
66
+ report = {"checkpoint": str(args.checkpoint), "sha256": sha}
67
+ for name, batch in groups.items():
68
+ report[name] = _summary(phase1, batch)
69
+ r = report[name]
70
+ print("%-22s route %-58s sev %s" % (name, json.dumps(r["routing"]), json.dumps(r["severity"])))
71
+ if args.output:
72
+ args.output.write_text(json.dumps(report, indent=2))
73
+ print("WROTE", args.output)
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()
dataset/phase1_noise_20260906/code/download_all_datasets.sh ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Download all 5 datasets locally then upload to server
3
+ # Run this on your LOCAL machine (with internet access)
4
+
5
+ set -e
6
+
7
+ LOCAL_DIR="/Users/nguyenbinhan/Downloads/datasets"
8
+ SERVER="3090"
9
+ REMOTE_DIR="/home/admin_mcn/data"
10
+
11
+ mkdir -p "$LOCAL_DIR"
12
+
13
+ echo "=============================================="
14
+ echo "Downloading SCDC Datasets"
15
+ echo "=============================================="
16
+
17
+ # 1. Rain200H
18
+ echo ""
19
+ echo "[1/5] Downloading Rain200H..."
20
+ cd "$LOCAL_DIR"
21
+ if [ ! -d "Rain200H" ]; then
22
+ wget --no-check-certificate -q "https://drive.usercontent.google.com/download?id=1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF&export=download&confirm=t" -O Rain200H.zip 2>/dev/null || echo "wget failed, try manual download"
23
+ if [ -f Rain200H.zip ] && [ $(stat -f%z Rain200H.zip 2>/dev/null || stat -c%s Rain200H.zip 2>/dev/null) -gt 1000000 ]; then
24
+ unzip -q Rain200H.zip -d Rain200H
25
+ rm Rain200H.zip
26
+ echo " Rain200H downloaded!"
27
+ else
28
+ echo " Download failed. Please manually download from:"
29
+ echo " https://drive.google.com/file/d/1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF/view"
30
+ mkdir -p Rain200H
31
+ fi
32
+ else
33
+ echo " Rain200H already exists"
34
+ fi
35
+
36
+ # 2. LOLv2
37
+ echo ""
38
+ echo "[2/5] Downloading LOLv2..."
39
+ cd "$LOCAL_DIR"
40
+ if [ ! -d "LOLv2" ]; then
41
+ echo " Please download LOLv2 manually from: https://daooshee.github.io/FOVDFE/"
42
+ echo " Expected structure: LOLv2/LOLv2/Real_captured/"
43
+ mkdir -p LOLv2/LOLv2/Real_captured
44
+ fi
45
+
46
+ # 3. RESIDE (OTS)
47
+ echo ""
48
+ echo "[3/5] Downloading RESIDE..."
49
+ cd "$LOCAL_DIR"
50
+ if [ ! -d "RESIDE" ]; then
51
+ echo " Please download RESIDE manually from: https://github.com/x懦yzzz/RESIDE"
52
+ echo " Expected structure: RESIDE/OTS/OTS/"
53
+ mkdir -p RESIDE/OTS/OTS
54
+ fi
55
+
56
+ # 4. GOPRO
57
+ echo ""
58
+ echo "[4/5] Downloading GOPRO..."
59
+ cd "$LOCAL_DIR"
60
+ if [ ! -d "GOPRO" ]; then
61
+ echo " Please download GOPRO manually from: https://github.com/SeungjunNah/DeepDeblur"
62
+ echo " Expected structure: GOPRO/train/blur/, GOPRO/train/sharp/"
63
+ mkdir -p GOPRO/train/blur GOPRO/train/sharp GOPRO/test/blur GOPRO/test/sharp
64
+ fi
65
+
66
+ # 5. SIDD
67
+ echo ""
68
+ echo "[5/5] Downloading SIDD..."
69
+ cd "$LOCAL_DIR"
70
+ if [ ! -d "SIDD" ]; then
71
+ echo " SIDD requires registration at: https://sid.epfl.ch/"
72
+ echo " Please download manually after registration."
73
+ mkdir -p SIDD/SIDD_Benchmark
74
+ fi
75
+
76
+ echo ""
77
+ echo "=============================================="
78
+ echo "Upload to Server"
79
+ echo "=============================================="
80
+
81
+ echo ""
82
+ echo "Uploading Rain200H..."
83
+ if [ -d "$LOCAL_DIR/Rain200H" ]; then
84
+ if [ -d "$LOCAL_DIR/Rain200H/train_c" ] || [ -d "$LOCAL_DIR/Rain200H/rainy_image_extractions" ]; then
85
+ tar -czvf /tmp/rain200h.tar.gz -C "$LOCAL_DIR" Rain200H 2>/dev/null
86
+ scp /tmp/rain200h.tar.gz $SERVER:$REMOTE_DIR/
87
+ ssh $SERVER "cd $REMOTE_DIR && tar -xzvf rain200h.tar.gz && rm rain200h.tar.gz"
88
+ rm /tmp/rain200h.tar.gz
89
+ echo " Rain200H uploaded!"
90
+ else
91
+ echo " Rain200H folder exists but structure is unexpected"
92
+ ls "$LOCAL_DIR/Rain200H/"
93
+ fi
94
+ else
95
+ echo " Rain200H not found locally"
96
+ fi
97
+
98
+ echo ""
99
+ echo "=============================================="
100
+ echo "Summary"
101
+ echo "=============================================="
102
+ echo ""
103
+ echo "Datasets at $LOCAL_DIR:"
104
+ for dir in Rain200H LOLv2 RESIDE GOPRO SIDD; do
105
+ if [ -d "$LOCAL_DIR/$dir" ]; then
106
+ count=$(find "$LOCAL_DIR/$dir" -type f \( -name "*.png" -o -name "*.jpg" \) 2>/dev/null | wc -l)
107
+ echo " OK $dir ($count images)"
108
+ else
109
+ echo " MISSING $dir (not downloaded)"
110
+ fi
111
+ done
112
+
113
+ echo ""
114
+ echo "Datasets on server $SERVER:"
115
+ ssh $SERVER "ls -la $REMOTE_DIR/ 2>/dev/null || echo 'Remote dir not found'"
116
+
117
+ echo ""
118
+ echo "Done!"
dataset/phase1_noise_20260906/code/download_rain200h.sh ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Download Rain200H dataset for deraining
3
+ # Link: https://drive.google.com/file/d/1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF/view
4
+
5
+ set -e
6
+
7
+ DATA_ROOT="/home/admin_mcn/data"
8
+ RAIN_DIR="$DATA_ROOT/Rain200H"
9
+ mkdir -p "$RAIN_DIR"
10
+
11
+ echo "=============================================="
12
+ echo "Downloading Rain200H Dataset"
13
+ echo "=============================================="
14
+
15
+ # Method 1: Using gdown (if available)
16
+ if command -v gdown &> /dev/null; then
17
+ echo "Using gdown..."
18
+ cd "$DATA_ROOT"
19
+ gdown 1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF -O Rain200H.zip
20
+ unzip -q Rain200H.zip -d Rain200H
21
+ rm Rain200H.zip
22
+ # Method 2: Using wget/curl with direct link
23
+ else
24
+ echo "Installing gdown..."
25
+ pip3 install gdown
26
+
27
+ echo "Downloading from Google Drive..."
28
+ cd "$DATA_ROOT"
29
+ gdown 1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF -O Rain200H.zip
30
+
31
+ echo "Extracting..."
32
+ unzip -q Rain200H.zip -d Rain200H
33
+ rm Rain200H.zip
34
+ fi
35
+
36
+ echo "Checking structure..."
37
+ ls -la "$RAIN_DIR/"
38
+
39
+ # Verify dataset structure
40
+ if [ -d "$RAIN_DIR/train_c" ] || [ -d "$RAIN_DIR/Rain200H/train_c" ]; then
41
+ echo ""
42
+ echo "=============================================="
43
+ echo "Rain200H Dataset Ready!"
44
+ echo "=============================================="
45
+ echo "Structure:"
46
+ find "$RAIN_DIR" -type d | head -10
47
+ echo ""
48
+ echo "Sample counts:"
49
+ if [ -d "$RAIN_DIR/train_c" ]; then
50
+ echo " Train clean: $(ls "$RAIN_DIR/train_c/" 2>/dev/null | wc -l) images"
51
+ elif [ -d "$RAIN_DIR/Rain200H/train_c" ]; then
52
+ echo " Train clean: $(ls "$RAIN_DIR/Rain200H/train_c/" 2>/dev/null | wc -l) images"
53
+ fi
54
+ else
55
+ echo ""
56
+ echo "WARNING: Dataset structure not as expected."
57
+ echo "Please check $RAIN_DIR manually."
58
+ fi
59
+
60
+ echo ""
61
+ echo "Done!"
dataset/phase1_noise_20260906/code/eval_full_frame.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Native-resolution, full-image evaluation of a v7-family checkpoint.
3
+
4
+ Why a second protocol: ``eval_pipeline_external.py`` measures 256 center
5
+ crops taken AFTER ``_resize_center_crop`` (short side -> 256), i.e. every
6
+ external image is downscaled first (Test1200 384 -> 256 = 0.67x, RESIDE
7
+ 0.62x, SIDD scene008 ~12x). Downscaling averages real noise away (scene008
8
+ input reads 39 dB "nearly clean") and moves every set to a scale the trunk
9
+ never trained on (Phase-2 trains on NATIVE 256 crops). Published numbers are
10
+ full images at native resolution, so this evaluator restores the whole
11
+ image at native scale with overlapping 256 tiles (the training crop size),
12
+ Phase-1 per tile plus the aspect-squashed whole frame for global-context
13
+ models, optional x8 dihedral test-time augmentation, and reports RGB and
14
+ Y-channel PSNR/SSIM (deraining papers report Y) plus LPIPS.
15
+
16
+ Groups: rain_locked (Test100+Test1200, 384x384), noise_locked_scene008 (SIDD
17
+ scene 008 at native 12 MP), haze_heldout (300 RESIDE), lowlight_lolv2_test
18
+ (the 100 LOLv2-real test images = the lowlight val split, directly
19
+ comparable to published LOLv2-real numbers).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import math
27
+ from pathlib import Path
28
+ from typing import Callable, Dict, List, Optional, Sequence, Tuple
29
+
30
+ import torch
31
+ from torch import Tensor
32
+ import torch.nn.functional as F
33
+ from torch.utils.data import DataLoader, Dataset
34
+
35
+ import train_graph_encoder_v2 as p1
36
+ import train_phase2_graph_resshift_v4 as v4
37
+
38
+ RestoreFn = Callable[[Tensor, Sequence[str], Optional[Tensor]], Tensor]
39
+
40
+ _LANCZOS = getattr(getattr(__import__("PIL.Image", fromlist=["Image"]), "Resampling", None), "LANCZOS", None)
41
+
42
+
43
+ # ---- dihedral test-time augmentation -------------------------------------- #
44
+ def dihedral_transform(image: Tensor, index: int) -> Tensor:
45
+ """Apply one of the 8 square symmetries (index 0 = identity).
46
+
47
+ index = 4 * flip + rotation, rotation in {0,1,2,3} quarter turns
48
+ counter-clockwise, flip = horizontal mirror applied FIRST.
49
+ """
50
+
51
+ if not 0 <= int(index) < 8:
52
+ raise ValueError("dihedral index must be in [0, 8)")
53
+ out = image
54
+ if index >= 4:
55
+ out = torch.flip(out, dims=(-1,))
56
+ return torch.rot90(out, k=int(index) % 4, dims=(-2, -1))
57
+
58
+
59
+ def dihedral_inverse(image: Tensor, index: int) -> Tensor:
60
+ """Undo ``dihedral_transform(_, index)``."""
61
+
62
+ if not 0 <= int(index) < 8:
63
+ raise ValueError("dihedral index must be in [0, 8)")
64
+ out = torch.rot90(image, k=-(int(index) % 4), dims=(-2, -1))
65
+ if index >= 4:
66
+ out = torch.flip(out, dims=(-1,))
67
+ return out
68
+
69
+
70
+ # ---- tiling --------------------------------------------------------------- #
71
+ def tile_boxes(height: int, width: int, tile: int, overlap: int) -> List[Tuple[int, int]]:
72
+ """Top-left corners of ``tile``-sized boxes covering an image of at least
73
+ ``tile`` in both dimensions; the last row/column is flush with the edge."""
74
+
75
+ if tile <= 0 or overlap < 0 or overlap >= tile:
76
+ raise ValueError("need 0 <= overlap < tile")
77
+ if height < tile or width < tile:
78
+ raise ValueError("image must be at least one tile in both dimensions")
79
+ stride = tile - overlap
80
+
81
+ def starts(length: int) -> List[int]:
82
+ positions = list(range(0, max(length - tile, 0) + 1, stride))
83
+ if positions[-1] != length - tile:
84
+ positions.append(length - tile)
85
+ return positions
86
+
87
+ return [(top, left) for top in starts(height) for left in starts(width)]
88
+
89
+
90
+ def blend_weights(tile: int, overlap: int, device=None, dtype=torch.float32) -> Tensor:
91
+ """[1,1,tile,tile] raised-cosine ramp over ``overlap`` pixels on every
92
+ edge, 1 in the interior; complementary ramps of adjacent tiles sum to 1."""
93
+
94
+ ramp = torch.ones(tile, device=device, dtype=dtype)
95
+ if overlap > 0:
96
+ positions = (torch.arange(overlap, device=device, dtype=dtype) + 0.5) / float(overlap)
97
+ edge = 0.5 - 0.5 * torch.cos(math.pi * positions)
98
+ ramp[:overlap] = edge
99
+ ramp[tile - overlap:] = torch.flip(edge, dims=(0,))
100
+ return (ramp.view(-1, 1) * ramp.view(1, -1)).view(1, 1, tile, tile)
101
+
102
+
103
+ def _pad_to_tile(image: Tensor, tile: int) -> Tuple[Tensor, Tuple[int, int]]:
104
+ height, width = int(image.shape[-2]), int(image.shape[-1])
105
+ pad_h, pad_w = max(tile - height, 0), max(tile - width, 0)
106
+ if pad_h == 0 and pad_w == 0:
107
+ return image, (height, width)
108
+ mode = "reflect" if pad_h < height and pad_w < width else "replicate"
109
+ return F.pad(image, (0, pad_w, 0, pad_h), mode=mode), (height, width)
110
+
111
+
112
+ @torch.no_grad()
113
+ def restore_tiled(
114
+ restore: RestoreFn,
115
+ image: Tensor,
116
+ record_id: str,
117
+ *,
118
+ tile: int = 256,
119
+ overlap: int = 64,
120
+ tile_batch: int = 8,
121
+ full_frame: Optional[Tensor] = None,
122
+ ) -> Tensor:
123
+ """Restore one [1,3,H,W] image with overlapping tiles.
124
+
125
+ ``restore(tiles [N,3,tile,tile], record_ids, full_frame [N,3,s,s] | None)``
126
+ returns the restored tiles. Every tile gets a distinct record id so the
127
+ record-keyed sampler noise stays deterministic per tile.
128
+ """
129
+
130
+ if image.ndim != 4 or image.shape[0] != 1:
131
+ raise ValueError("restore_tiled expects a single [1,3,H,W] image")
132
+ padded, (height, width) = _pad_to_tile(image, tile)
133
+ boxes = tile_boxes(int(padded.shape[-2]), int(padded.shape[-1]), tile, overlap)
134
+ weights = blend_weights(tile, overlap, device=padded.device, dtype=torch.float32)
135
+ canvas = torch.zeros(1, padded.shape[1], padded.shape[-2], padded.shape[-1],
136
+ device=padded.device, dtype=torch.float32)
137
+ total = torch.zeros(1, 1, padded.shape[-2], padded.shape[-1],
138
+ device=padded.device, dtype=torch.float32)
139
+ for start in range(0, len(boxes), max(int(tile_batch), 1)):
140
+ chunk = boxes[start:start + max(int(tile_batch), 1)]
141
+ tiles = torch.cat([padded[..., t:t + tile, l:l + tile] for t, l in chunk], dim=0)
142
+ ids = ["%s|tile%d" % (record_id, start + k) for k in range(len(chunk))]
143
+ full = None if full_frame is None else full_frame.expand(len(chunk), -1, -1, -1)
144
+ restored = restore(tiles, ids, full).float()
145
+ if restored.shape != tiles.shape:
146
+ raise ValueError("restore must return tiles of the input shape")
147
+ for k, (t, l) in enumerate(chunk):
148
+ canvas[..., t:t + tile, l:l + tile] += restored[k:k + 1] * weights
149
+ total[..., t:t + tile, l:l + tile] += weights
150
+ return (canvas / total)[..., :height, :width]
151
+
152
+
153
+ # Every scale of the trunk must stay divisible by the 8x8 window: image/2
154
+ # (pixel-unshuffle) then three /2 stages -> the image must be a multiple of
155
+ # 2 * 8 * 8 = 128 for the relative-position bias to apply at all four scales.
156
+ WHOLE_IMAGE_MULTIPLE = 128
157
+
158
+
159
+ @torch.no_grad()
160
+ def restore_whole(
161
+ restore: RestoreFn,
162
+ image: Tensor,
163
+ record_id: str,
164
+ *,
165
+ multiple: int = WHOLE_IMAGE_MULTIPLE,
166
+ full_frame: Optional[Tensor] = None,
167
+ ) -> Tensor:
168
+ """Restore one [1,3,H,W] image in a single pass (no tiles): reflect-pad
169
+ to a multiple of ``multiple`` so the window attention keeps its native
170
+ 8x8 windows at every scale, then crop back. Removes the per-tile
171
+ conditioning/exposure inconsistency of tiled inference."""
172
+
173
+ if image.ndim != 4 or image.shape[0] != 1:
174
+ raise ValueError("restore_whole expects a single [1,3,H,W] image")
175
+ height, width = int(image.shape[-2]), int(image.shape[-1])
176
+ pad_h, pad_w = (-height) % multiple, (-width) % multiple
177
+ padded = image
178
+ if pad_h or pad_w:
179
+ mode = "reflect" if pad_h < height and pad_w < width else "replicate"
180
+ padded = F.pad(image, (0, pad_w, 0, pad_h), mode=mode)
181
+ restored = restore(padded, ["%s|whole" % record_id], full_frame).float()
182
+ if restored.shape != padded.shape:
183
+ raise ValueError("restore must return an image of the input shape")
184
+ return restored[..., :height, :width]
185
+
186
+
187
+ # TTA sets. x2 = identity + horizontal mirror only: rotations and the
188
+ # vertical flip change the orientation of rain streaks and put the sky at the
189
+ # bottom, which the model never saw (measured on v9a15k, tiled: x8 costs
190
+ # -2.4 dB on Test1200 and -1.0 dB on haze while helping isotropic noise).
191
+ TTA_TRANSFORMS = {1: (0,), 2: (0, 4), 8: tuple(range(8))}
192
+
193
+
194
+ @torch.no_grad()
195
+ def restore_full_frame(
196
+ restore: RestoreFn,
197
+ image: Tensor,
198
+ record_id: str,
199
+ *,
200
+ tta: int = 1,
201
+ full_frame: Optional[Tensor] = None,
202
+ whole_max_pixels: int = 0,
203
+ **tiling,
204
+ ) -> Tensor:
205
+ """Restoration averaged over ``tta`` dihedral transforms (1 or 8).
206
+
207
+ Images with at most ``whole_max_pixels`` pixels are restored in one pass
208
+ (``restore_whole``); larger ones (or all, when 0) with overlapping tiles.
209
+ """
210
+
211
+ if int(tta) not in TTA_TRANSFORMS:
212
+ raise ValueError("tta must be 1, 2 or 8")
213
+ pixels = int(image.shape[-2]) * int(image.shape[-1])
214
+ whole = int(whole_max_pixels) > 0 and pixels <= int(whole_max_pixels)
215
+ outputs = []
216
+ for index in TTA_TRANSFORMS[int(tta)]:
217
+ transformed = dihedral_transform(image, index)
218
+ full = None if full_frame is None else dihedral_transform(full_frame, index)
219
+ tag = "%s|d%d" % (record_id, index)
220
+ if whole:
221
+ restored = restore_whole(restore, transformed, tag, full_frame=full)
222
+ else:
223
+ restored = restore_tiled(restore, transformed, tag, full_frame=full, **tiling)
224
+ outputs.append(dihedral_inverse(restored, index))
225
+ return torch.stack(outputs, dim=0).mean(dim=0).clamp(0.0, 1.0)
226
+
227
+
228
+ # ---- metrics -------------------------------------------------------------- #
229
+ def rgb_to_y601(image: Tensor) -> Tensor:
230
+ """BT.601 luma of an RGB [B,3,H,W] batch in [0,1] -> Y in [16,235]/255."""
231
+
232
+ if image.ndim != 4 or image.shape[1] != 3:
233
+ raise ValueError("rgb_to_y601 expects [B,3,H,W]")
234
+ r, g, b = image[:, 0:1].float(), image[:, 1:2].float(), image[:, 2:3].float()
235
+ return (16.0 + 65.481 * r + 128.553 * g + 24.966 * b) / 255.0
236
+
237
+
238
+ def psnr_y_per_image(prediction: Tensor, target: Tensor) -> Tensor:
239
+ return v4.rgb_psnr_per_image(rgb_to_y601(prediction), rgb_to_y601(target))
240
+
241
+
242
+ def ssim_y_per_image(prediction: Tensor, target: Tensor) -> Tensor:
243
+ return v4.rgb_ssim_per_image(rgb_to_y601(prediction), rgb_to_y601(target))
244
+
245
+
246
+ def lpips_center(lpips_fn, prediction: Tensor, target: Tensor, max_side: int = 1024) -> Tensor:
247
+ """LPIPS on the full image, or on a central ``max_side`` window for very
248
+ large images (the AlexNet features of a 12 MP frame do not fit)."""
249
+
250
+ height, width = prediction.shape[-2:]
251
+ if height > max_side or width > max_side:
252
+ top, left = max((height - max_side) // 2, 0), max((width - max_side) // 2, 0)
253
+ prediction = prediction[..., top:top + max_side, left:left + max_side]
254
+ target = target[..., top:top + max_side, left:left + max_side]
255
+ return lpips_fn(prediction * 2 - 1, target * 2 - 1).flatten()
256
+
257
+
258
+ # ---- data ----------------------------------------------------------------- #
259
+ class FullFrameDataset(Dataset):
260
+ """Native pairs (upscaled only when smaller than ``crop`` on the short
261
+ side, exactly Phase2PairDataset's rule) plus the aspect-squashed whole
262
+ frame used by global-context models."""
263
+
264
+ def __init__(self, records: Sequence, crop: int = 256) -> None:
265
+ self.records = list(records)
266
+ self.crop = int(crop)
267
+
268
+ def __len__(self) -> int:
269
+ return len(self.records)
270
+
271
+ def __getitem__(self, index: int):
272
+ record = self.records[index]
273
+ degraded, clean = p1._native_open_pair(record, self.crop)
274
+ full = degraded.resize((self.crop, self.crop), _LANCZOS)
275
+ return {
276
+ "degraded": p1._pil_to_tensor(degraded),
277
+ "clean": p1._pil_to_tensor(clean),
278
+ "full_degraded": p1._pil_to_tensor(full),
279
+ "record_id": record.record_id,
280
+ }
281
+
282
+
283
+ def external_groups(haze_count: int = 300) -> Dict[str, list]:
284
+ p1_args = p1.build_parser().parse_args([])
285
+ splits = p1.build_data_splits(p1_args)
286
+ rain = [r for r in splits.locked_test if r.degradation == "rain"]
287
+ noise = [r for r in splits.locked_test if r.degradation == "noise"]
288
+ lowlight = [r for r in splits.val if r.degradation == "lowlight"]
289
+ reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE")
290
+ used = {
291
+ r.split_group for r in list(splits.train) + list(splits.val)
292
+ if r.degradation == "haze"
293
+ }
294
+ haze = [r for r in reside[5000:] if r.split_group not in used][:haze_count]
295
+ return {
296
+ "rain_locked": rain,
297
+ "noise_locked_scene008": noise,
298
+ "haze_heldout": haze,
299
+ "lowlight_lolv2_test": lowlight,
300
+ }
301
+
302
+
303
+ def _mean(values: List[float]) -> float:
304
+ return float(sum(values) / len(values)) if values else float("nan")
305
+
306
+
307
+ @torch.no_grad()
308
+ def evaluate_group_full_frame(
309
+ restore: RestoreFn,
310
+ records: Sequence,
311
+ name: str,
312
+ device: torch.device,
313
+ lpips_fn=None,
314
+ *,
315
+ tta: int = 1,
316
+ tile: int = 256,
317
+ overlap: int = 64,
318
+ tile_batch: int = 8,
319
+ use_full_frame: bool = True,
320
+ workers: int = 2,
321
+ whole_max_pixels: int = 0,
322
+ ) -> Dict[str, object]:
323
+ loader = DataLoader(FullFrameDataset(records, crop=tile), batch_size=1,
324
+ shuffle=False, num_workers=workers)
325
+ keys = ("psnr", "ssim", "psnr_y", "ssim_y", "lpips")
326
+ acc = {kind: {k: [] for k in keys} for kind in ("restored", "degraded")}
327
+ sizes = []
328
+ for batch in loader:
329
+ degraded = batch["degraded"].to(device)
330
+ clean = batch["clean"].to(device)
331
+ full = batch["full_degraded"].to(device) if use_full_frame else None
332
+ record_id = str(batch["record_id"][0])
333
+ restored = restore_full_frame(
334
+ restore, degraded, record_id, tta=tta, full_frame=full,
335
+ tile=tile, overlap=overlap, tile_batch=tile_batch,
336
+ whole_max_pixels=whole_max_pixels,
337
+ )
338
+ sizes.append([int(degraded.shape[-2]), int(degraded.shape[-1])])
339
+ for kind, image in (("restored", restored), ("degraded", degraded)):
340
+ slot = acc[kind]
341
+ slot["psnr"] += v4.rgb_psnr_per_image(image, clean).cpu().tolist()
342
+ slot["ssim"] += v4.rgb_ssim_per_image(image, clean).cpu().tolist()
343
+ slot["psnr_y"] += psnr_y_per_image(image, clean).cpu().tolist()
344
+ slot["ssim_y"] += ssim_y_per_image(image, clean).cpu().tolist()
345
+ if lpips_fn is not None:
346
+ slot["lpips"] += lpips_center(lpips_fn, image, clean).cpu().tolist()
347
+ report = {
348
+ "n": len(records),
349
+ "protocol": {"tile": tile, "overlap": overlap, "tta": int(tta), "native": True,
350
+ "full_frame_context": bool(use_full_frame),
351
+ "whole_max_pixels": int(whole_max_pixels)},
352
+ "sizes_hw": sizes[:3],
353
+ }
354
+ for kind, slot in acc.items():
355
+ report[kind] = {k: _mean(v) for k, v in slot.items() if v}
356
+ print(name, json.dumps(report, sort_keys=True), flush=True)
357
+ return report
358
+
359
+
360
+ def main(argv: Optional[Sequence[str]] = None) -> None:
361
+ parser = argparse.ArgumentParser(description=__doc__)
362
+ parser.add_argument("--run-dir", type=Path, required=True)
363
+ parser.add_argument("--output", type=Path, required=True)
364
+ parser.add_argument("--groups", default="rain_locked,noise_locked_scene008,haze_heldout,lowlight_lolv2_test")
365
+ parser.add_argument("--tta", type=int, default=1, choices=(1, 2, 8),
366
+ help="1 = none, 2 = + horizontal mirror (orientation-safe), 8 = full dihedral")
367
+ parser.add_argument("--tile", type=int, default=256)
368
+ parser.add_argument("--overlap", type=int, default=64)
369
+ parser.add_argument("--tile-batch", type=int, default=8)
370
+ parser.add_argument("--haze-count", type=int, default=300)
371
+ parser.add_argument("--dose", type=float, default=None)
372
+ parser.add_argument("--photometric-dose", type=float, default=None)
373
+ parser.add_argument(
374
+ "--whole-max-pixels", type=int, default=0,
375
+ help="restore images up to this many pixels in ONE pass (pad to x128) "
376
+ "instead of tiles; 0 = always tile. 1.2e6 covers LOL/RESIDE/Test1200.",
377
+ )
378
+ parser.add_argument("--pregain-dose", type=float, default=None,
379
+ help="scale of the v10 input pre-gain log-gain (None = 1.0; 0 = off)")
380
+ parser.add_argument("--colour-dose", type=float, default=None,
381
+ help="scale of the v12 global colour head (None = 1.0; 0 = off)")
382
+ parser.add_argument("--checkpoint", default="best.pt",
383
+ help="file inside --run-dir to evaluate (best.pt, last.pt, milestone_%08d.pt)")
384
+ parser.add_argument("--no-lpips", action="store_true")
385
+ parser.add_argument("--limit", type=int, default=0, help="debug: first N records per group")
386
+ args = parser.parse_args(argv)
387
+
388
+ from eval_v7_external import V7Pipeline
389
+
390
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
391
+ pipeline = V7Pipeline(args.run_dir, device, dose=args.dose, photometric_dose=args.photometric_dose,
392
+ checkpoint=args.checkpoint, pregain_dose=args.pregain_dose,
393
+ colour_dose=args.colour_dose)
394
+ seed = int(pipeline.args.eval_seed)
395
+
396
+ def restore(tiles: Tensor, ids: Sequence[str], full: Optional[Tensor]) -> Tensor:
397
+ return pipeline.restore(tiles, record_ids=list(ids), seed=seed, full_degraded=full)["restored"]
398
+
399
+ lpips_fn = None
400
+ if not args.no_lpips:
401
+ import lpips
402
+
403
+ lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device)
404
+ groups = external_groups(args.haze_count)
405
+ report = {"run_dir": str(args.run_dir), "dose": args.dose,
406
+ "photometric_dose": args.photometric_dose, "tta": int(args.tta),
407
+ "whole_max_pixels": int(args.whole_max_pixels),
408
+ "checkpoint": pipeline.checkpoint_name, "checkpoint_step": pipeline.checkpoint_step,
409
+ "pregain_dose": args.pregain_dose}
410
+ for name in [g.strip() for g in args.groups.split(",") if g.strip()]:
411
+ records = groups[name]
412
+ if args.limit > 0:
413
+ records = records[: args.limit]
414
+ report[name] = evaluate_group_full_frame(
415
+ restore, records, name, device, lpips_fn,
416
+ tta=args.tta, tile=args.tile, overlap=args.overlap, tile_batch=args.tile_batch,
417
+ whole_max_pixels=args.whole_max_pixels,
418
+ )
419
+ args.output.write_text(json.dumps(report, indent=2, sort_keys=True))
420
+ print("WROTE", args.output, flush=True)
421
+
422
+
423
+ if __name__ == "__main__":
424
+ main()
dataset/phase1_noise_20260906/code/eval_gen2_external.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Official + external evaluation of the gen-2 pipeline (v6.1 + refiner)."""
3
+ import json
4
+ from pathlib import Path
5
+
6
+ import torch
7
+
8
+ import train_refiner_a as tr
9
+ import eval_pipeline_external as ext
10
+ import train_graph_encoder_v2 as p1
11
+ from src.models.restoration.refiner_decoder import RefinerDecoder
12
+ import train_phase2_graph_resshift_v4 as v4
13
+
14
+
15
+ class Gen2Pipeline:
16
+ def __init__(self, device):
17
+ self.device = device
18
+ self.regressor, self.phase1, self.args = tr.load_frozen_regressor(
19
+ device, kind="v6", run_dir=Path("outputs/phase2_moe_v6/v61_seed42")
20
+ )
21
+ state = torch.load("outputs/refiner_v6_v1/refiner_best.pt", map_location="cpu")
22
+ refiner = RefinerDecoder()
23
+ refiner.load_state_dict(state["refiner_state_dict"], strict=True)
24
+ self.refiner = refiner.to(device).eval()
25
+ print("refiner best step:", state["step"], "macro:", round(state["macro_refined_psnr"], 3))
26
+
27
+ @torch.no_grad()
28
+ def restore(self, degraded, record_ids=None, seed=20260830):
29
+ degraded = degraded.to(self.device)
30
+ x0 = tr.one_step_x0(self.regressor, self.phase1, degraded,
31
+ [str(r) for r in record_ids], seed, "initial")
32
+ px, size = v4.pad_to_multiple(x0, multiple=4)
33
+ py, _ = v4.pad_to_multiple(degraded, multiple=4)
34
+ out = self.refiner(px, py)
35
+ h, w = size
36
+ return {"x0_hat": x0, "restored": out[..., :h, :w]}
37
+
38
+
39
+ def main():
40
+ import lpips
41
+ device = torch.device("cuda")
42
+ pipeline = Gen2Pipeline(device)
43
+ lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device)
44
+ p1_args = p1.build_parser().parse_args([])
45
+ splits = p1.build_data_splits(p1_args)
46
+ rain = [r for r in splits.locked_test if r.degradation == "rain"]
47
+ noise = [r for r in splits.locked_test if r.degradation == "noise"]
48
+ reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE")
49
+ used = {r.split_group for r in list(splits.train) + list(splits.val) if r.degradation == "haze"}
50
+ haze = [r for r in reside[5000:] if r.split_group not in used][:300]
51
+ report = {
52
+ "rain_locked": ext.evaluate_group(pipeline, rain, "rain_locked", lpips_fn),
53
+ "noise_locked_scene008": ext.evaluate_group(pipeline, noise, "noise_locked", lpips_fn),
54
+ "haze_heldout": ext.evaluate_group(pipeline, haze, "haze_heldout", lpips_fn),
55
+ }
56
+ Path("outputs/gen2_external_v1.json").write_text(json.dumps(report, indent=2, sort_keys=True))
57
+ print("WROTE outputs/gen2_external_v1.json")
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()
dataset/phase1_noise_20260906/code/eval_phase1_clean_relative.py ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Auditable real/synthetic evaluation for seven clean-relative factors.
2
+
3
+ Test is an explicitly requested evaluation split, never a training selector.
4
+ Missing targets, collapsed targets, and unimplemented claims remain explicit.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ from pathlib import Path
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+ import torch
16
+ from torch import Tensor
17
+ import torch.nn.functional as F
18
+ from torch.utils.data import DataLoader
19
+
20
+ from train_phase1_clean_relative import (
21
+ TYPE_ORDER, HELDOUT_PAIRS, TRAIN_PAIRS, atomic_json_save, file_digest,
22
+ functional_error, record_labels, residual_statistics, scene_component_ids, selected_indices,
23
+ )
24
+
25
+
26
+ def average_precision(targets, scores) -> float | None:
27
+ """Threshold-grouped AP: ties cannot gain an arbitrary ranking advantage."""
28
+ labels = np.asarray(targets, dtype=np.int64)
29
+ values = np.asarray(scores, dtype=np.float64)
30
+ positives = int(labels.sum())
31
+ if positives == 0:
32
+ return None
33
+ if len(labels) != len(values) or not np.isfinite(values).all():
34
+ raise ValueError("Invalid average-precision inputs")
35
+ order = np.argsort(-values, kind="stable")
36
+ labels, values = labels[order], values[order]
37
+ cumulative = np.cumsum(labels)
38
+ ends = np.r_[np.flatnonzero(values[:-1] != values[1:]), len(values) - 1]
39
+ true_positive = cumulative[ends]
40
+ recalls = true_positive / positives
41
+ precisions = true_positive / (ends + 1)
42
+ return float(np.sum(np.diff(np.r_[0.0, recalls]) * precisions))
43
+
44
+
45
+ def classification_report(labels: Tensor, logits: Tensor) -> dict[str, Any]:
46
+ labels, logits = labels.cpu(), logits.detach().float().cpu()
47
+ if len(labels) == 0:
48
+ raise ValueError("No records to evaluate")
49
+ probabilities = logits.sigmoid()
50
+ predicted = logits.argmax(1)
51
+ confusion = torch.bincount(labels * 7 + predicted, minlength=49).reshape(7, 7)
52
+ domains = {}
53
+ f1s, aps, supported_f1s = [], [], []
54
+ for i, name in enumerate(TYPE_ORDER):
55
+ tp = int(confusion[i, i])
56
+ support, predicted_count = int(confusion[i].sum()), int(confusion[:, i].sum())
57
+ precision = tp / predicted_count if predicted_count else 0.0
58
+ recall = tp / support if support else 0.0
59
+ f1 = 2 * tp / (support + predicted_count) if support + predicted_count else 0.0
60
+ ap = average_precision((labels == i).numpy(), probabilities[:, i].numpy())
61
+ domains[name] = {"support": support, "precision": precision, "recall": recall, "f1": f1, "average_precision": ap}
62
+ f1s.append(f1)
63
+ if support:
64
+ supported_f1s.append(f1)
65
+ if ap is not None:
66
+ aps.append(ap)
67
+ return {"type_order": TYPE_ORDER, "records": len(labels), "confusion": confusion.tolist(), "per_domain": domains,
68
+ "accuracy": float((predicted == labels).float().mean()), "macro_f1": float(np.mean(f1s)),
69
+ "macro_f1_supported": float(np.mean(supported_f1s)), "supported_classes": len(supported_f1s),
70
+ "macro_average_precision_supported": float(np.mean(aps)) if aps else None,
71
+ "interpretation": "Single manifest-domain argmax; probabilities remain independent presence scores"}
72
+
73
+
74
+ def regression_report(targets, predictions) -> dict[str, Any]:
75
+ target, prediction = np.asarray(targets, dtype=float), np.asarray(predictions, dtype=float)
76
+ if not target.size:
77
+ return {"count": 0, "mae": None, "r2": None, "pearson": None, "target_variance": None}
78
+ variance = float(np.var(target))
79
+ residual = float(np.sum((target - prediction) ** 2))
80
+ total = float(np.sum((target - np.mean(target)) ** 2))
81
+ correlation = float(np.corrcoef(target, prediction)[0, 1]) if variance > 1e-12 and float(np.var(prediction)) > 1e-12 and len(target) > 1 else None
82
+ return {"count": int(target.size), "mae": float(np.mean(np.abs(target - prediction))),
83
+ "r2": 1 - residual / total if total > 1e-12 else None, "pearson": correlation,
84
+ "target_variance": variance}
85
+
86
+
87
+ def binary_auc(known_scores, unknown_scores) -> float | None:
88
+ """Mann–Whitney AUC, including half credit for ties."""
89
+ known, unknown = np.asarray(known_scores), np.asarray(unknown_scores)
90
+ if not len(known) or not len(unknown):
91
+ return None
92
+ return float(np.mean(unknown[:, None] > known[None, :]) + 0.5 * np.mean(unknown[:, None] == known[None, :]))
93
+
94
+
95
+ def _loader(manifest, split, patch_size, batch_size, workers, cap, seed):
96
+ from src.data.clean_relative import PairedDegradationDataset
97
+
98
+ dataset = PairedDegradationDataset(manifest, split=split, crop_size=patch_size, seed=seed)
99
+ labels = record_labels(dataset)
100
+ selected = selected_indices(labels, cap, seed)
101
+ if not selected:
102
+ raise ValueError(f"Manifest split {split!r} is empty")
103
+ loader = DataLoader(dataset, batch_size=batch_size, sampler=selected, drop_last=False, num_workers=workers,
104
+ generator=torch.Generator().manual_seed(seed), persistent_workers=False)
105
+ return dataset, selected, loader
106
+
107
+
108
+ @torch.inference_mode()
109
+ def evaluate_real(model, manifest: str, split: str, device, batch_size: int = 16, patch_size: int = 128,
110
+ workers: int = 0, max_records: int | None = None, seed: int = 42,
111
+ functional_enabled: bool = True) -> dict[str, Any]:
112
+ dataset, selected, loader = _loader(manifest, split, patch_size, batch_size, workers, max_records, seed)
113
+ previous_mode = model.training
114
+ model.eval()
115
+ labels, logits, clean_probabilities, clean_norms, deltas = [], [], [], [], []
116
+ paired_content, shuffled_content = [], []
117
+ clean_proxy_l1, clean_proxy_psnr = [], []
118
+ physical = {name: {"target": [], "prediction": []} for name in TYPE_ORDER}
119
+ try:
120
+ for batch in loader:
121
+ pair = model.forward_pair(batch["degraded"].to(device), batch["clean"].to(device))
122
+ student, clean = pair["student"], pair["clean"]
123
+ if functional_enabled:
124
+ target_clean = batch["clean"].to(device)
125
+ origin = model.decode(clean["content"], torch.zeros_like(clean["delta"]), target_clean.shape[-2:])
126
+ error = origin - target_clean
127
+ clean_proxy_l1.extend(error.abs().flatten(1).mean(1).cpu().tolist())
128
+ clean_proxy_psnr.extend((-10 * error.square().flatten(1).mean(1).clamp_min(1e-12).log10()).cpu().tolist())
129
+ labels.append(batch["label"])
130
+ logits.append(student["presence_logits"].float().cpu())
131
+ clean_probabilities.append(clean["presence_logits"].sigmoid().float().cpu())
132
+ clean_norms.append(clean["delta"].norm(dim=1).float().cpu())
133
+ deltas.append(student["delta"].float().cpu())
134
+ for k, name in enumerate(TYPE_ORDER):
135
+ mask = batch["severity_mask"][:, k]
136
+ physical[name]["target"].extend(batch["severity"][mask, k].tolist())
137
+ physical[name]["prediction"].extend(student["severity"].cpu()[mask, k].tolist())
138
+ paired_content.append((student["content"] - clean["content"]).square().flatten(1).mean(1).cpu())
139
+ if len(batch["clean"]) > 1:
140
+ shuffled_content.append((student["content"] - clean["content"].roll(1, 0)).square().flatten(1).mean(1).cpu())
141
+ finally:
142
+ model.train(previous_mode)
143
+ probabilities, norms, delta = torch.cat(clean_probabilities), torch.cat(clean_norms), torch.cat(deltas)
144
+ report = {
145
+ "split": split, "records_total": len(dataset), "records_evaluated": len(selected),
146
+ "scope": "all_records" if len(selected) == len(dataset) else "explicitly_capped",
147
+ "image_protocol": f"One deterministic paired {patch_size}x{patch_size} native crop per record; not full-image restoration",
148
+ "classification": classification_report(torch.cat(labels), torch.cat(logits)),
149
+ "clean": {"any_false_positive_rate_at_0_5": float((probabilities > 0.5).any(1).float().mean()),
150
+ "per_factor_false_positive_rate_at_0_5": dict(zip(TYPE_ORDER, (probabilities > 0.5).float().mean(0).tolist())),
151
+ "delta_norm_mean": float(norms.mean()), "delta_norm_p95": float(torch.quantile(norms, 0.95)), "delta_norm_max": float(norms.max())},
152
+ "clean_origin_proxy": {"status": "measured" if functional_enabled else "unsupported_without_trained_proxy",
153
+ "rgb_l1": _mean(clean_proxy_l1), "psnr_mean_db": _mean(clean_proxy_psnr),
154
+ "definition": "G(content(clean), zero_delta) against clean; peak=1, MSE floor=1e-12, outputs not clamped"},
155
+ "representation": {"mean_coordinate_variance": float(delta.var(0, unbiased=False).mean()), "mean_norm": float(delta.norm(dim=1).mean())},
156
+ "paired_content": {"matched_feature_mse": float(torch.cat(paired_content).mean()),
157
+ "within_batch_shuffled_feature_mse": float(torch.cat(shuffled_content).mean()) if shuffled_content else None,
158
+ "interpretation": "Paired-feature consistency diagnostic; not an independence test"},
159
+ "manifest_physical_severity": {
160
+ name: {"status": "measured_from_explicit_parameter_mask" if item["target"] else "unsupported_without_physical_targets",
161
+ **regression_report(item["target"], item["prediction"])} for name, item in physical.items()},
162
+ "severity_interpretation": "Only supplied synthetic parameter masks are scored, e.g. generated JPEG; real domain names are not physical severity measurements",
163
+ }
164
+ return report
165
+
166
+
167
+ def _content_probe(baseline, descriptor, content, group_ids) -> dict[str, Any]:
168
+ """Does a global code predict observable scene information beyond type/dose?"""
169
+ groups = np.asarray(group_ids)
170
+ unique = np.unique(groups)
171
+ if len(unique) < 4:
172
+ return {"status": "insufficient_data", "reason": "Need at least four distinct source scenes for a disjoint probe split"}
173
+ train = np.isin(groups, unique[:len(unique) // 2])
174
+ test = ~train
175
+ target = np.asarray(content, dtype=np.float64)
176
+
177
+ def fit_error(features):
178
+ features = np.asarray(features, dtype=np.float64)
179
+ center, scale = features[train].mean(0), features[train].std(0).clip(1e-4)
180
+ normalized = (features - center) / scale
181
+ normalized = np.column_stack((np.ones(len(normalized)), normalized))
182
+ penalty = np.eye(normalized.shape[1])
183
+ penalty[0, 0] = 0
184
+ coefficients = np.linalg.solve(normalized[train].T @ normalized[train] + penalty, normalized[train].T @ target[train])
185
+ return float(np.mean((normalized[test] @ coefficients - target[test]) ** 2))
186
+
187
+ base = np.asarray(baseline)
188
+ base_error = fit_error(base)
189
+ augmented_error = fit_error(np.concatenate((base, np.asarray(descriptor)), axis=1))
190
+ variance = float(target[test].var(0).mean())
191
+ return {"status": "measured", "train_scenes": int(len(unique) // 2), "test_scenes": int(len(unique) - len(unique) // 2),
192
+ "baseline": "Ridge regression from type one-hot plus type-by-normalized-physical-severity",
193
+ "target": "Clean 4x4 RGB thumbnail, fixed observable rather than learned teacher target",
194
+ "baseline_mse": base_error, "baseline_plus_delta_mse": augmented_error,
195
+ "heldout_target_variance": variance,
196
+ "baseline_r2": 1 - base_error / variance if variance > 1e-12 else None,
197
+ "baseline_plus_delta_r2": 1 - augmented_error / variance if variance > 1e-12 else None,
198
+ "relative_improvement": (base_error - augmented_error) / base_error if base_error > 1e-12 else None,
199
+ "interpretation": "Positive held-out improvement is evidence of this specific content-prediction channel; not a proof of independence or universally undesirable content dependence"}
200
+
201
+
202
+ def physical_parameter_probe(rows: list[dict], kind: str) -> dict[str, Any]:
203
+ """Test within-factor information beyond dose, against fixed physical targets."""
204
+ groups = [row["scene"] for row in rows]
205
+ if len(set(groups)) < 8:
206
+ return {"status": "insufficient_data", "reason": "Need at least eight distinct source scenes for this physical-parameter probe"}
207
+ if kind not in ("rain", "blur", "haze"):
208
+ return {"status": "unsupported", "reason": "No independently varied non-dose physical target in this synthetic operator"}
209
+ if kind == "haze":
210
+ target = [row["parameters"]["airlight"] for row in rows]
211
+ target_name = "airlight RGB"
212
+ else:
213
+ angles = np.deg2rad([row["parameters"]["angle"] for row in rows])
214
+ target = np.column_stack((np.sin(2 * angles), np.cos(2 * angles)))
215
+ target_name = "sin(2*orientation), cos(2*orientation), respecting 180-degree line symmetry"
216
+ report = _content_probe([[row["parameters"]["severity"]] for row in rows],
217
+ [row["coefficients"] for row in rows], target, groups)
218
+ report["baseline"] = "Within-type normalized physical severity (type is constant); fixed ridge alpha=1"
219
+ report["target"] = target_name
220
+ report["interpretation"] = "Held-out-scene recovery of independently varied physical parameters from the active factor coordinates beyond a severity-only baseline"
221
+ report["factor_rank"] = len(rows[0]["coefficients"])
222
+ report["baseline_plus_factor_coefficients_mse"] = report.pop("baseline_plus_delta_mse")
223
+ report["baseline_plus_factor_coefficients_r2"] = report.pop("baseline_plus_delta_r2")
224
+ return report
225
+
226
+
227
+ def _mean(values):
228
+ return float(np.mean(values)) if values else None
229
+
230
+
231
+ def _scene_indices(dataset, count: int, seed: int) -> list[int]:
232
+ """Select distinct manifest scene groups, not many variants of one image."""
233
+ by_scene = {}
234
+ for i, scene in enumerate(scene_component_ids(dataset.records)):
235
+ by_scene.setdefault(scene, i)
236
+ order = np.random.default_rng(seed).permutation(len(by_scene))[:count]
237
+ values = list(by_scene.values())
238
+ return [values[int(i)] for i in order]
239
+
240
+
241
+ @torch.inference_mode()
242
+ def evaluate_controlled(model, manifest: str, split: str, device, batch_size=8, patch_size=128,
243
+ scenes=28, seed=42, use_edges=True, functional_enabled=True) -> dict[str, Any]:
244
+ from src.data.clean_relative import PairedDegradationDataset, sample_degradation_parameters, synthesize_composition, synthesize_degradation
245
+
246
+ dataset = PairedDegradationDataset(manifest, split=split, crop_size=patch_size, seed=seed)
247
+ indices = _scene_indices(dataset, scenes, seed)
248
+ if not indices:
249
+ return {"status": "unsupported", "reason": "No source scenes"}
250
+ model.eval()
251
+ severity = {name: {"target": [], "prediction": [], "parameters": []} for name in TYPE_ORDER}
252
+ transfer = {name: [] for name in TYPE_ORDER}
253
+ transfer_controls = {name: {mode: [] for mode in ("blind", "zero", "shuffled_paired")} for name in TYPE_ORDER}
254
+ physical_rows = {name: [] for name in TYPE_ORDER}
255
+ drop = {name: [] for name in TYPE_ORDER}
256
+ drop_baseline = {name: [] for name in TYPE_ORDER}
257
+ mixed_result = {"heldout_pairs": [], "seen_pairs_both_orders_new_scenes": []}
258
+ hf_statistics = {name: [] for name in TYPE_ORDER}
259
+ known_uncertainty, unknown_uncertainty = [], []
260
+ probe_baseline, probe_descriptor, probe_content, probe_groups = [], [], [], []
261
+ single_targets, single_logits, mixed_targets, mixed_logits = [], [], [], []
262
+ swap_differences = []
263
+ for start in range(0, len(indices), batch_size):
264
+ current = indices[start:start + batch_size]
265
+ x_cpu = torch.stack([dataset[i]["clean"] for i in current])
266
+ x = x_cpu.to(device)
267
+ clean_rep = model(x)
268
+ # Roll against all selected scenes, so the final batch of one still has distinct content.
269
+ other_indices = [indices[(start + i + 1) % len(indices)] for i in range(len(current))]
270
+ other_cpu = torch.stack([dataset[i]["clean"] for i in other_indices])
271
+ other = other_cpu.to(device)
272
+ other_clean_rep = model(other)
273
+ for k, name in enumerate(TYPE_ORDER):
274
+ ys, transferred_targets, targets, params = [], [], [], []
275
+ for j in range(len(current)):
276
+ sample_seed = seed + current[j] * 1009 + k * 29
277
+ param = sample_degradation_parameters(name, sample_seed, heldout=True)
278
+ y, _ = synthesize_degradation(x_cpu[j], name, parameters=param, seed=sample_seed)
279
+ target, _ = synthesize_degradation(other_cpu[j], name, parameters=param, seed=sample_seed)
280
+ ys.append(y)
281
+ transferred_targets.append(target)
282
+ targets.append(float(param["severity"]))
283
+ params.append(param)
284
+ y, other_y = torch.stack(ys).to(device), torch.stack(transferred_targets).to(device)
285
+ pair = model.forward_pair(y, x)
286
+ rep = pair["student"]
287
+ severity[name]["target"].extend(targets)
288
+ severity[name]["prediction"].extend(rep["severity"][:, k].cpu().tolist())
289
+ severity[name]["parameters"].extend(params)
290
+ for j, param in enumerate(params):
291
+ physical_rows[name].append({"scene": current[j], "parameters": param,
292
+ "coefficients": rep["coefficients"][j, k].cpu().tolist()})
293
+ single_targets.extend([k] * len(current))
294
+ single_logits.append(rep["presence_logits"].cpu())
295
+ known_uncertainty.extend((1 - rep["presence_logits"].sigmoid().max(1).values).cpu().tolist())
296
+ if len(indices) > 1:
297
+ if functional_enabled:
298
+ transferred = model.decode(other_clean_rep["content"], pair["teacher"]["delta"], x.shape[-2:])
299
+ transfer[name].extend(functional_error(transferred, other_y, other, torch.full((len(x),), k, device=device)).cpu().tolist())
300
+ hf_error = (residual_statistics(transferred - other)[:, 6:] - residual_statistics(other_y - other)[:, 6:]).abs().mean(1)
301
+ hf_statistics[name].extend(hf_error.cpu().tolist())
302
+ control_codes = {"blind": rep["delta"], "zero": torch.zeros_like(rep["delta"])}
303
+ if len(x) > 1:
304
+ control_codes["shuffled_paired"] = pair["teacher"]["delta"].roll(1, 0)
305
+ for mode, code in control_codes.items():
306
+ control = model.decode(other_clean_rep["content"], code, x.shape[-2:])
307
+ errors = functional_error(control, other_y, other, torch.full((len(x),), k, device=device)).cpu().tolist()
308
+ if mode == "shuffled_paired":
309
+ errors = [value for j, value in enumerate(errors) if params[j] != params[(j - 1) % len(x)]]
310
+ transfer_controls[name][mode].extend(errors)
311
+ other_teacher = model.encode_pair(other_y, other)
312
+ swap_differences.extend((pair["teacher"]["coefficients"][:, :7] - other_teacher["coefficients"][:, :7]).square().flatten(1).mean(1).cpu().tolist())
313
+ if functional_enabled:
314
+ dropped_delta = model.drop_factor(pair["teacher"]["delta"], k)
315
+ dropped = model.decode(clean_rep["content"], dropped_delta, x.shape[-2:])
316
+ untouched = model.decode(clean_rep["content"], pair["teacher"]["delta"], x.shape[-2:])
317
+ drop[name].extend((dropped - x).abs().flatten(1).mean(1).cpu().tolist())
318
+ drop_baseline[name].extend((untouched - x).abs().flatten(1).mean(1).cpu().tolist())
319
+ one_hot = np.eye(7)[k]
320
+ content = F.adaptive_avg_pool2d(x, (4, 4)).flatten(1).cpu().tolist()
321
+ for j, target in enumerate(targets):
322
+ probe_baseline.append(np.r_[one_hot, one_hot * target])
323
+ probe_descriptor.append(rep["delta"][j].cpu().numpy())
324
+ probe_content.append(content[j])
325
+ probe_groups.append(current[j])
326
+ for regime, candidate_pairs in (("heldout_pairs", HELDOUT_PAIRS), ("seen_pairs_both_orders_new_scenes", TRAIN_PAIRS[:3])):
327
+ for a, b in candidate_pairs:
328
+ ya, yb, yab, yba = [], [], [], []
329
+ for j, index in enumerate(current):
330
+ sample_seed = seed + index * 1009 + TYPE_ORDER.index(a) * 29
331
+ pa = sample_degradation_parameters(a, sample_seed, heldout=False)
332
+ pb = sample_degradation_parameters(b, sample_seed + 1, heldout=False)
333
+ ya.append(synthesize_degradation(x_cpu[j], a, parameters=pa, seed=sample_seed)[0])
334
+ yb.append(synthesize_degradation(x_cpu[j], b, parameters=pb, seed=sample_seed + 1)[0])
335
+ yab.append(synthesize_composition(x_cpu[j], (a, b), parameters=(pa, pb), seed=sample_seed)[0])
336
+ yba.append(synthesize_composition(x_cpu[j], (b, a), parameters=(pb, pa), seed=sample_seed)[0])
337
+ first = model.encode_pair(torch.stack(ya).to(device), x)
338
+ second = model.encode_pair(torch.stack(yb).to(device), x)
339
+ ab = model.encode_pair(torch.stack(yab).to(device), x)
340
+ ba_pair = model.forward_pair(torch.stack(yba).to(device), x)
341
+ ba = ba_pair["teacher"]
342
+ composed = model.compose(first["delta"], second["delta"], TYPE_ORDER.index(a), TYPE_ORDER.index(b), use_edges=use_edges)
343
+ reverse = model.compose(second["delta"], first["delta"], TYPE_ORDER.index(b), TYPE_ORDER.index(a), use_edges=use_edges)
344
+ additive = first["delta"] + second["delta"]
345
+ raw_target = (ab["delta"] - ba["delta"])
346
+ result = {"pair": [a, b], "count": len(current),
347
+ "forward_latent_mse": float(F.mse_loss(composed, ab["delta"])),
348
+ "forward_additive_latent_mse": float(F.mse_loss(additive, ab["delta"])),
349
+ "reverse_latent_mse": float(F.mse_loss(reverse, ba["delta"])),
350
+ "reverse_additive_latent_mse": float(F.mse_loss(additive, ba["delta"])),
351
+ "order_difference_mse": float(F.mse_loss(composed - reverse, raw_target)),
352
+ "order_target_mean_square": float(raw_target.square().mean())}
353
+ if functional_enabled:
354
+ stochastic = a in ("rain", "noise", "snow") or b in ("rain", "noise", "snow")
355
+ error_labels = torch.full((len(x),), 1 if stochastic else TYPE_ORDER.index(a), device=device)
356
+ for direction, code, observed in (("forward", composed, torch.stack(yab).to(device)),
357
+ ("reverse", reverse, torch.stack(yba).to(device))):
358
+ decoded = model.decode(clean_rep["content"], code, x.shape[-2:])
359
+ additive_decoded = model.decode(clean_rep["content"], additive, x.shape[-2:])
360
+ result[direction + "_functional_error"] = float(functional_error(decoded, observed, x, error_labels).mean())
361
+ result[direction + "_additive_functional_error"] = float(functional_error(additive_decoded, observed, x, error_labels).mean())
362
+ result[direction + "_pixel_l1"] = float((decoded - observed).abs().mean())
363
+ result[direction + "_additive_pixel_l1"] = float((additive_decoded - observed).abs().mean())
364
+ result[direction + "_residual_hf_l1"] = float((residual_statistics(decoded - x)[:, 6:] - residual_statistics(observed - x)[:, 6:]).abs().mean())
365
+ # Counterfactual removal targets are remaining operators applied to clean.
366
+ for removed, remaining, remaining_image in ((a, b, torch.stack(yb).to(device)), (b, a, torch.stack(ya).to(device))):
367
+ labels_remaining = torch.full((len(x),), TYPE_ORDER.index(remaining), device=device)
368
+ for mode, code in (("paired", ba["delta"]), ("blind", ba_pair["student"]["delta"])):
369
+ dropped = model.decode(clean_rep["content"], model.drop_factor(code, TYPE_ORDER.index(removed)), x.shape[-2:])
370
+ untouched = model.decode(clean_rep["content"], code, x.shape[-2:])
371
+ prefix = f"reverse_drop_{removed}_retain_{remaining}_{mode}"
372
+ result[prefix + "_error"] = float(functional_error(dropped, remaining_image, x, labels_remaining).mean())
373
+ result[prefix + "_before_drop_error"] = float(functional_error(untouched, remaining_image, x, labels_remaining).mean())
374
+ else:
375
+ result["external_functional_status"] = "unsupported_without_trained_proxy"
376
+ mixed_result[regime].append(result)
377
+ target = torch.zeros(len(x), 7)
378
+ target[:, TYPE_ORDER.index(a)] = target[:, TYPE_ORDER.index(b)] = 1
379
+ mixed_targets.append(target)
380
+ mixed_logits.append(ba_pair["student"]["presence_logits"].cpu())
381
+ # Explicit unseen operator probe; not seven-family leave-one-out training.
382
+ occluded = x.clone()
383
+ h, w = x.shape[-2:]
384
+ occluded[:, :, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.5
385
+ unknown = model(occluded)
386
+ unknown_uncertainty.extend((1 - unknown["presence_logits"].sigmoid().max(1).values).cpu().tolist())
387
+ target = torch.cat(mixed_targets)
388
+ probability = torch.cat(mixed_logits).sigmoid()
389
+ binary = probability > 0.5
390
+ mixed_ap = {name: average_precision(target[:, k].numpy(), probability[:, k].numpy()) for k, name in enumerate(TYPE_ORDER)}
391
+ return {
392
+ "status": "measured", "source_split": split, "distinct_source_scenes": len(indices), "requested_scenes": scenes,
393
+ "severity_regime": "Held-out normalized physical severity range supplied by synthetic operators",
394
+ "single_classification": classification_report(torch.tensor(single_targets), torch.cat(single_logits)),
395
+ "severity": {name: {**regression_report(item["target"], item["prediction"]), "physical_parameter_examples": item["parameters"][:3],
396
+ "target_definition": "Normalized generating parameter; never inferred from real domain labels"} for name, item in severity.items()},
397
+ "within_factor_parameter_probes": {name: physical_parameter_probe(rows, name) for name, rows in physical_rows.items()},
398
+ "cross_content_transfer": {"status": "measured" if functional_enabled and len(indices) > 1 else "unsupported_without_trained_proxy_and_distinct_content",
399
+ "per_domain_error": {name: _mean(values) for name, values in transfer.items()},
400
+ "paired_teacher_error": {name: _mean(values) for name, values in transfer.items()},
401
+ "controls": {name: {mode: {"count": len(values), "error": _mean(values)} for mode, values in modes.items()} for name, modes in transfer_controls.items()},
402
+ "shuffled_baseline": "Same factor but mismatched generating parameters within batch; skipped if no distinct donor is available",
403
+ "native_hf_residual_statistics_l1": {name: _mean(values) for name, values in hf_statistics.items()},
404
+ "matched_parameter_coefficient_mse": _mean(swap_differences),
405
+ "metric": "RGB L1 for deterministic types; residual mean/std and gradient/Laplacian RMS L1 for rain/noise/snow",
406
+ "limitation": "Deterministic proxy cannot generate a full conditional noise distribution"},
407
+ "factor_drop": {name: {"clean_l1_after_drop": _mean(drop[name]), "clean_l1_before_drop": _mean(drop_baseline[name])} for name in TYPE_ORDER},
408
+ "factor_drop_interpretation": "Controlled decoder intervention test; not a real-world causal identification claim",
409
+ "mixed": {"per_batch_results": mixed_result, "exact_presence_match_at_0_5": float((binary == target.bool()).all(1).float().mean()),
410
+ "per_factor_average_precision": mixed_ap,
411
+ "order_split": "Both orders of seen pairs are trained; unseen composition generalization is tested on heldout pairs in both orders, not an independently heldout order of a seen pair",
412
+ "external_functional_targets": "Actual synthesized forward/reverse images; mixed-node removal targets the remaining operator on clean; additive and before-drop baselines included",
413
+ "target_definition": "Latent composition targets are jointly learned; errors measure agreement, not physical identifiability",
414
+ "basis_reference_noncollapse": "Consult real representation variance and order_target_mean_square alongside latent errors"},
415
+ "content_probe": _content_probe(probe_baseline, probe_descriptor, probe_content, probe_groups),
416
+ "unseen_operator_probe": {"operator": "central gray occlusion", "score": "1 - maximum known presence probability",
417
+ "auc": binary_auc(known_uncertainty, unknown_uncertainty),
418
+ "known_count": len(known_uncertainty), "unknown_count": len(unknown_uncertainty),
419
+ "limitation": "One controlled unseen-operator probe, not calibrated open-set recognition"},
420
+ "family_leave_one_out": {"status": "requires_retraining", "plan": "Train seven additional models, excluding one family's real and synthetic training examples each time; all seven families are known in this checkpoint"},
421
+ }
422
+
423
+
424
+ def build_parser() -> argparse.ArgumentParser:
425
+ parser = argparse.ArgumentParser(description=__doc__)
426
+ parser.add_argument("--checkpoint", required=True)
427
+ parser.add_argument("--manifest", required=True)
428
+ parser.add_argument("--split", choices=("val", "test"), default="val")
429
+ parser.add_argument("--output")
430
+ parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
431
+ parser.add_argument("--batch-size", type=int, default=16)
432
+ parser.add_argument("--patch-size", type=int, default=128)
433
+ parser.add_argument("--num-workers", type=int, default=4)
434
+ parser.add_argument("--threads", type=int, default=4)
435
+ parser.add_argument("--seed", type=int, default=42)
436
+ parser.add_argument("--max-records", type=int, help="Explicit cap; omitted evaluates all real split records")
437
+ parser.add_argument("--synthetic-scenes", type=int, default=28)
438
+ parser.add_argument("--skip-controlled", action="store_true")
439
+ parser.add_argument("--no-edges", action="store_true", help="Inference ablation, separately labeled from retraining without edges")
440
+ return parser
441
+
442
+
443
+ def main(argv: list[str] | None = None) -> dict[str, Any]:
444
+ args = build_parser().parse_args(argv)
445
+ if min(args.batch_size, args.patch_size, args.threads, args.synthetic_scenes) <= 0 or args.num_workers < 0:
446
+ raise ValueError("Invalid batch, crop, thread, synthetic scene, or worker count")
447
+ torch.set_num_threads(args.threads)
448
+ from src.models.graph_encoder.clean_relative import CleanRelativeConfig, CleanRelativeGraphEncoder
449
+
450
+ checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False)
451
+ config = CleanRelativeConfig(**checkpoint["model_config"])
452
+ device = torch.device(args.device)
453
+ model = CleanRelativeGraphEncoder(config).to(device)
454
+ model.load_state_dict(checkpoint["model"])
455
+ report = {"checkpoint": str(Path(args.checkpoint).resolve()), "checkpoint_sha256": file_digest(args.checkpoint),
456
+ "checkpoint_step": checkpoint["global_step"], "training_scope": checkpoint["run_config"]["scope"],
457
+ "manifest_sha256": file_digest(args.manifest), "arguments": vars(args),
458
+ "real": evaluate_real(model, args.manifest, args.split, device, args.batch_size, args.patch_size,
459
+ args.num_workers, args.max_records, args.seed,
460
+ functional_enabled=not checkpoint["run_config"]["arguments"].get("no_proxy", False))}
461
+ if not args.skip_controlled:
462
+ report["controlled"] = evaluate_controlled(model, args.manifest, args.split, device, min(args.batch_size, 8),
463
+ args.patch_size, args.synthetic_scenes, args.seed,
464
+ use_edges=not args.no_edges and not checkpoint["run_config"]["arguments"]["no_edges"],
465
+ functional_enabled=not checkpoint["run_config"]["arguments"].get("no_proxy", False))
466
+ else:
467
+ report["controlled"] = {"status": "explicitly_skipped"}
468
+ output = Path(args.output) if args.output else Path(args.checkpoint).parent / f"evaluation_{args.split}_{Path(args.checkpoint).stem}.json"
469
+ atomic_json_save(report, output)
470
+ print(json.dumps({"output": str(output), "real": report["real"]}), flush=True)
471
+ return report
472
+
473
+
474
+ if __name__ == "__main__":
475
+ main()
dataset/phase1_noise_20260906/code/eval_pipeline_external.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Held-out evaluation of pipeline A on data Phase 2 never touched.
3
+
4
+ Sources:
5
+ rain_locked Rain13K Test100+Test1200 (Phase-1 locked test, 1.200 pairs)
6
+ noise_locked SIDD scene 008 (locked, 20 pairs)
7
+ haze_heldout RESIDE hazy images beyond the first-5000 training window,
8
+ filtered so no clean source overlaps train/val groups.
9
+
10
+ Center-crop 256 protocol, record-keyed noise, PSNR/SSIM/LPIPS for both the
11
+ one-step regression and the refined output.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ from pathlib import Path
19
+ from typing import Dict, List, Sequence
20
+
21
+ import torch
22
+ from torch.utils.data import DataLoader, Dataset
23
+
24
+ import infer_scdc_pipeline as pipe
25
+ import train_phase2_graph_resshift_v4 as v4
26
+ import train_graph_encoder_v2 as p1
27
+
28
+
29
+ class PairCropDataset(Dataset):
30
+ def __init__(self, records: Sequence, size: int = 256) -> None:
31
+ self.records = list(records)
32
+ self.size = size
33
+
34
+ def __len__(self) -> int:
35
+ return len(self.records)
36
+
37
+ def __getitem__(self, index: int):
38
+ record = self.records[index]
39
+ degraded, clean = p1.load_pair_uint8(record, self.size)
40
+ # Whole-frame view (aspect-squashed) for global-context models.
41
+ full = p1._open_rgb(record.degraded).resize((self.size, self.size))
42
+ return {
43
+ "degraded": p1._pil_to_tensor(degraded),
44
+ "clean": p1._pil_to_tensor(clean),
45
+ "full_degraded": p1._pil_to_tensor(full),
46
+ "record_id": record.record_id,
47
+ }
48
+
49
+
50
+ def evaluate_group(
51
+ pipeline: "pipe.SCDCPipeline", records: Sequence, name: str, lpips_fn
52
+ ) -> Dict[str, object]:
53
+ loader = DataLoader(
54
+ PairCropDataset(records), batch_size=8, shuffle=False, num_workers=4
55
+ )
56
+ acc: Dict[str, Dict[str, List[float]]] = {}
57
+ with torch.no_grad():
58
+ for batch in loader:
59
+ clean = batch["clean"].to(pipeline.device)
60
+ extra = {}
61
+ if "full_degraded" in batch and getattr(pipeline, "accepts_full_frame", False):
62
+ extra["full_degraded"] = batch["full_degraded"]
63
+ result = pipeline.restore(
64
+ batch["degraded"],
65
+ record_ids=[str(v) for v in batch["record_id"]],
66
+ seed=int(pipeline.args.eval_seed),
67
+ **extra,
68
+ )
69
+ for kind in ("x0_hat", "restored"):
70
+ slot = acc.setdefault(
71
+ kind, {"psnr": [], "ssim": [], "lpips": []}
72
+ )
73
+ slot["psnr"] += v4.rgb_psnr_per_image(
74
+ result[kind], clean
75
+ ).cpu().tolist()
76
+ slot["ssim"] += v4.rgb_ssim_per_image(
77
+ result[kind], clean
78
+ ).cpu().tolist()
79
+ slot["lpips"] += lpips_fn(
80
+ result[kind] * 2 - 1, clean * 2 - 1
81
+ ).flatten().cpu().tolist()
82
+ report = {"n": len(records)}
83
+ for kind, values in acc.items():
84
+ report[kind] = {
85
+ metric: sum(items) / len(items) for metric, items in values.items()
86
+ }
87
+ print(name, json.dumps(report, sort_keys=True), flush=True)
88
+ return report
89
+
90
+
91
+ def main() -> None:
92
+ parser = argparse.ArgumentParser(description=__doc__)
93
+ parser.add_argument(
94
+ "--refiner", type=Path,
95
+ default=Path("outputs/refiner_a_v1/refiner_best.pt"),
96
+ )
97
+ parser.add_argument(
98
+ "--output", type=Path,
99
+ default=Path("outputs/pipeline_eval_external_v1.json"),
100
+ )
101
+ parser.add_argument("--haze-count", type=int, default=300)
102
+ args = parser.parse_args()
103
+
104
+ device = torch.device("cuda")
105
+ pipeline = pipe.SCDCPipeline(args.refiner, device, sample_steps=1)
106
+
107
+ import lpips
108
+
109
+ lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device)
110
+
111
+ p1_args = p1.build_parser().parse_args([])
112
+ splits = p1.build_data_splits(p1_args)
113
+ rain_locked = [r for r in splits.locked_test if r.degradation == "rain"]
114
+ noise_locked = [r for r in splits.locked_test if r.degradation == "noise"]
115
+
116
+ # Held-out RESIDE: everything past the training window, minus any record
117
+ # whose clean source group appears in train or val.
118
+ reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE")
119
+ used_groups = {
120
+ r.split_group for r in list(splits.train) + list(splits.val)
121
+ if r.degradation == "haze"
122
+ }
123
+ haze_heldout = [
124
+ r for r in reside[5000:] if r.split_group not in used_groups
125
+ ][: args.haze_count]
126
+
127
+ report = {
128
+ "rain_locked_test100_1200": evaluate_group(
129
+ pipeline, rain_locked, "rain_locked", lpips_fn
130
+ ),
131
+ "noise_locked_sidd_scene008": evaluate_group(
132
+ pipeline, noise_locked, "noise_locked", lpips_fn
133
+ ),
134
+ "haze_heldout_reside": evaluate_group(
135
+ pipeline, haze_heldout, "haze_heldout", lpips_fn
136
+ ),
137
+ }
138
+ args.output.write_text(json.dumps(report, indent=2, sort_keys=True))
139
+ print("WROTE", args.output, flush=True)
140
+
141
+
142
+ if __name__ == "__main__":
143
+ main()
dataset/phase1_noise_20260906/code/eval_v7_external.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """External held-out evaluation of a pure v7 checkpoint (no refiner).
3
+
4
+ Reuses the gen-2 external protocol verbatim (same locked rain/noise sets,
5
+ same RESIDE held-out selection, same crops/metrics via
6
+ ``eval_pipeline_external.evaluate_group``) so numbers are directly
7
+ comparable with ``outputs/gen2_external_v1.json``.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ from pathlib import Path
15
+
16
+ import torch
17
+
18
+ import eval_pipeline_external as ext
19
+ import train_graph_encoder_v2 as p1
20
+ import train_phase2_graph_moe_v6 as v6
21
+ import train_phase2_graph_resshift_v4 as v4
22
+ from visualize_v7_uformer import _load_run_args
23
+
24
+
25
+ class V7Pipeline:
26
+ def __init__(
27
+ self, run_dir: Path, device: torch.device, dose: float = None,
28
+ photometric_dose: float = None, checkpoint: str = "best.pt",
29
+ pregain_dose: float = None, colour_dose: float = None,
30
+ ) -> None:
31
+ import train_phase2_unified_v7 as v7
32
+
33
+ self.device = device
34
+ self.dose = dose
35
+ self.pregain_dose = pregain_dose
36
+ self.colour_dose = colour_dose
37
+ self.photometric_dose = photometric_dose
38
+ self.args = _load_run_args(run_dir)
39
+ # Any checkpoint of the run (best.pt, last.pt, milestone_%08d.pt): the
40
+ # val-macro selector behind best.pt is known to be a poor proxy for
41
+ # the external sets, so milestones/last are evaluated too.
42
+ self.checkpoint_name = str(checkpoint)
43
+ checkpoint = v4._torch_load(run_dir / self.checkpoint_name, map_location="cpu")
44
+ self.model = v7._build_v7_restorer(self.args, device)
45
+ self.model.load_state_dict(
46
+ checkpoint["ema_state_dict"]["shadow"], strict=True
47
+ )
48
+ self.model.eval()
49
+ self.phase1, _ = v4.build_frozen_phase1(
50
+ self.args.phase1_checkpoint, self.args.phase1_sha256, device
51
+ )
52
+ self.checkpoint_step = int(checkpoint["step"])
53
+ print("v7 checkpoint %s step: %d" % (self.checkpoint_name, self.checkpoint_step))
54
+
55
+ accepts_full_frame = True
56
+
57
+ @torch.no_grad()
58
+ def restore(self, degraded, record_ids=None, seed=20260830, full_degraded=None):
59
+ import train_phase2_unified_v7 as v7
60
+
61
+ degraded = degraded.to(self.device)
62
+ restored = v7.sample_unified_restoration(
63
+ self.model, self.phase1, degraded,
64
+ seed=int(seed), record_ids=[str(r) for r in record_ids],
65
+ dose=self.dose,
66
+ pregain_dose=self.pregain_dose,
67
+ colour_dose=self.colour_dose,
68
+ full_degraded=None if full_degraded is None else full_degraded.to(self.device),
69
+ photometric_dose=self.photometric_dose,
70
+ )
71
+ # No refiner stage: the diffusion output IS the pipeline output.
72
+ return {"x0_hat": restored, "restored": restored}
73
+
74
+
75
+ def degraded_baseline(records, device) -> dict:
76
+ from torch.utils.data import DataLoader
77
+
78
+ loader = DataLoader(
79
+ ext.PairCropDataset(records), batch_size=16, shuffle=False, num_workers=4
80
+ )
81
+ psnr, ssim = [], []
82
+ for batch in loader:
83
+ clean = batch["clean"].to(device)
84
+ degraded = batch["degraded"].to(device)
85
+ psnr += v4.rgb_psnr_per_image(degraded, clean).cpu().tolist()
86
+ ssim += v4.rgb_ssim_per_image(degraded, clean).cpu().tolist()
87
+ return {
88
+ "psnr": sum(psnr) / len(psnr),
89
+ "ssim": sum(ssim) / len(ssim),
90
+ }
91
+
92
+
93
+ def main() -> None:
94
+ import lpips
95
+
96
+ parser = argparse.ArgumentParser(description=__doc__)
97
+ parser.add_argument(
98
+ "--run-dir", type=Path,
99
+ default=Path("outputs/phase2_v7/uformer_luma8k_seed42"),
100
+ )
101
+ parser.add_argument(
102
+ "--output", type=Path, default=Path("outputs/v7_external_v1.json")
103
+ )
104
+ parser.add_argument(
105
+ "--dose", type=float, default=None,
106
+ help="DGF guidance dose at the coarse step (None = plain conditioned)",
107
+ )
108
+ parser.add_argument(
109
+ "--photometric-dose", type=float, default=None,
110
+ help="scale of the v8 global exposure head deltas (None = 1.0; 0 = off)",
111
+ )
112
+ parser.add_argument("--checkpoint", default="best.pt", help="file inside --run-dir to evaluate")
113
+ args = parser.parse_args()
114
+
115
+ device = torch.device("cuda")
116
+ pipeline = V7Pipeline(args.run_dir, device, dose=args.dose, photometric_dose=args.photometric_dose,
117
+ checkpoint=args.checkpoint)
118
+ lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device)
119
+
120
+ p1_args = p1.build_parser().parse_args([])
121
+ splits = p1.build_data_splits(p1_args)
122
+ rain = [r for r in splits.locked_test if r.degradation == "rain"]
123
+ noise = [r for r in splits.locked_test if r.degradation == "noise"]
124
+ reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE")
125
+ used = {
126
+ r.split_group
127
+ for r in list(splits.train) + list(splits.val)
128
+ if r.degradation == "haze"
129
+ }
130
+ haze = [r for r in reside[5000:] if r.split_group not in used][:300]
131
+
132
+ report = {"run_dir": str(args.run_dir), "dose": args.dose, "photometric_dose": args.photometric_dose,
133
+ "checkpoint": pipeline.checkpoint_name, "checkpoint_step": pipeline.checkpoint_step}
134
+ for name, records in (
135
+ ("rain_locked", rain),
136
+ ("noise_locked_scene008", noise),
137
+ ("haze_heldout", haze),
138
+ ):
139
+ group = ext.evaluate_group(pipeline, records, name, lpips_fn)
140
+ group["degraded_baseline"] = degraded_baseline(records, device)
141
+ report[name] = group
142
+ args.output.write_text(json.dumps(report, indent=2, sort_keys=True))
143
+ print("WROTE", args.output)
144
+
145
+
146
+ if __name__ == "__main__":
147
+ main()
dataset/phase1_noise_20260906/code/gate_phase1.sh ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -u; cd /home/admin_mcn/scdc_ban; PY=/home/admin_mcn/anaconda3/bin/python
3
+ gate_for() { # $1 = run name ; writes outputs/$1_gate.json ; prints pass/score
4
+ local name=$1 ckpt=outputs/$1/graph_encoder_best.pt
5
+ CUDA_VISIBLE_DEVICES=0 $PY visualize_phase1_graph.py --checkpoint $ckpt --output-dir outputs/phase1_vis/$name > outputs/phase1_vis_$name.log 2>&1
6
+ CAND=$name CUDA_VISIBLE_DEVICES=0 $PY - <<'PYEOF' > outputs/${name}_gate.log 2>&1
7
+ import glob, hashlib, json, math, os, torch, numpy as np
8
+ from pathlib import Path
9
+ from PIL import Image
10
+ import train_phase2_graph_resshift_v4 as v4
11
+ from visualize_phase1_graph import encode, NODES
12
+ name = os.environ["CAND"]
13
+ files = sorted(glob.glob("/home/admin_mcn/data/Snow100K/realistic/**/*.jpg", recursive=True))
14
+ def load(f):
15
+ im = Image.open(f).convert("RGB"); w, h = im.size; s = 256 / min(w, h)
16
+ if s > 1: im = im.resize((max(256, math.ceil(w * s)), max(256, math.ceil(h * s))), Image.LANCZOS); w, h = im.size
17
+ l, t = (w - 256) // 2, (h - 256) // 2
18
+ return torch.from_numpy(np.asarray(im.crop((l, t, l + 256, t + 256)), dtype=np.float32) / 255.).permute(2, 0, 1)
19
+ imgs = torch.stack([load(f) for f in files])
20
+ ck = Path("outputs/%s/graph_encoder_best.pt" % name)
21
+ p1, _ = v4.build_frozen_phase1(ck, hashlib.sha256(ck.read_bytes()).hexdigest(), torch.device("cuda"))
22
+ enc = encode(p1, imgs.cuda())
23
+ route = dict(zip(NODES, enc["routing"].mean(0).tolist()))
24
+ summary = json.load(open("outputs/phase1_vis/%s/summary.json" % name))
25
+ conf = summary["confusion"]
26
+ row = lambda prefix: next(v for k, v in conf.items() if k.startswith(prefix))
27
+ hist = json.load(open("outputs/%s/history.json" % name))
28
+ best_f1 = max(e["val"].get("macro_f1", 0.0) for e in hist if "val" in e)
29
+ gates = {
30
+ "snow_real_free": (route["free1"] + route["free2"], 0.70, ">="),
31
+ # not worse than ll_v3 (0.46 haze->rain on the same val); the +0.3 dB
32
+ # claim for v8 does not depend on Phase-1 routing improving, only on it
33
+ # not regressing and on photometric_state existing.
34
+ "haze_to_rain_max": (row("Haze input")["rain"], 0.46, "<="),
35
+ "rain_to_rain_min": (row("Rain input")["rain"], 0.55, ">="),
36
+ "lowlight_to_lowlight_min": (row("Low-light input")["lowlight"], 0.85, ">="),
37
+ }
38
+ passed = {k: (v[0] >= v[1] if v[2] == ">=" else v[0] <= v[1]) for k, v in gates.items()}
39
+ report = {"candidate": name, "sha256": hashlib.sha256(ck.read_bytes()).hexdigest(), "snow_real_routing": route,
40
+ "gates": {k: {"value": v[0], "threshold": v[1], "pass": passed[k]} for k, v in gates.items()},
41
+ "n_pass": int(sum(passed.values())), "pass": bool(all(passed.values())), "best_val_macro_f1": best_f1,
42
+ "noise_recall": row("Noise input")["noise"]}
43
+ Path("outputs/%s_gate.json" % name).write_text(json.dumps(report, indent=2))
44
+ print(json.dumps(report))
45
+ PYEOF
46
+ $PY -c "import json;d=json.load(open('outputs/${name}_gate.json'));print('%d %d %.4f'%(int(d['pass']),d['n_pass'],d['best_val_macro_f1']))"
47
+ }
48
+ gate_for $1
dataset/phase1_noise_20260906/code/hf_bundle_upload.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Bundle exactly the data this project trains/evaluates on and upload it to
3
+ a Hugging Face dataset repo.
4
+
5
+ Contents (all paths inside the tars are relative to two roots, recorded in
6
+ manifests/path_roots.json so the absolute paths in the manifests can be
7
+ rewritten on another machine):
8
+ Rain13K.tar every Rain13K file referenced by the Phase-1 splits
9
+ (train / val / locked test) and the Phase-2 manifest
10
+ RESIDE_used.tar the RESIDE hazy/clear files used in training/val plus
11
+ the 300 held-out evaluation scenes
12
+ LOLv2.tar LOLv2-real (train + test), as extracted
13
+ SIDD_Small.tar SIDD Small sRGB (all 160 scenes; 121 train / 19 val /
14
+ 20 locked scene 008)
15
+ Snow100K_gt.tar, Snow100K_synthetic.tar the clean pool and the real-OOD
16
+ pool used by Phase-1 v5 / Phase-2 identity pairs
17
+ manifests/ Phase-2 train/val manifest, quarantine list, file lists
18
+ per split, path roots, README
19
+ Token: HF_TOKEN environment variable only (never written to disk here).
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import os
27
+ import subprocess
28
+ import sys
29
+ import time
30
+ from pathlib import Path
31
+
32
+ HOME = Path("/home/admin_mcn")
33
+ ROOTS = { # absolute prefix -> archive prefix
34
+ str(HOME / "data") + "/": "data/",
35
+ str(HOME / ".cache" / "kagglehub") + "/": "kagglehub/",
36
+ }
37
+ REPO = "Anbinh93/image_restoration"
38
+
39
+
40
+ def relative(path: str) -> str:
41
+ for prefix, target in ROOTS.items():
42
+ if path.startswith(prefix):
43
+ return target + path[len(prefix):]
44
+ raise ValueError("file outside the known roots: %s" % path)
45
+
46
+
47
+ def collect() -> dict:
48
+ sys.path.insert(0, str(HOME / "scdc_ban"))
49
+ import train_graph_encoder_v2 as p1
50
+ import eval_full_frame as ff
51
+
52
+ groups = ff.external_groups(300)
53
+ args = p1.build_parser().parse_args([])
54
+ splits = p1.build_data_splits(args)
55
+ manifest = json.load(open(HOME / "scdc_ban/outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json"))
56
+ lists: dict = {}
57
+
58
+ def add(name, records):
59
+ files = set()
60
+ for r in records:
61
+ files.add(str(r.degraded)); files.add(str(r.clean))
62
+ lists[name] = sorted(files)
63
+
64
+ add("phase1_train", splits.train); add("phase1_val", splits.val); add("phase1_locked_test", splits.locked_test)
65
+ add("haze_heldout_300", groups["haze_heldout"])
66
+ m = set()
67
+ for key in ("train", "val"):
68
+ for r in manifest[key]:
69
+ for f in ("degraded", "clean"):
70
+ if f in r:
71
+ m.add(str(r[f]))
72
+ lists["phase2_manifest"] = sorted(m)
73
+ return lists
74
+
75
+
76
+ def main() -> None:
77
+ parser = argparse.ArgumentParser(description=__doc__)
78
+ parser.add_argument("--staging", type=Path, default=HOME / "hf_staging/image_restoration")
79
+ parser.add_argument("--dry-run", action="store_true")
80
+ parser.add_argument("--skip-tar", action="store_true", help="tars already built; only upload")
81
+ args = parser.parse_args()
82
+ staging = args.staging
83
+ (staging / "manifests").mkdir(parents=True, exist_ok=True)
84
+
85
+ lists = collect()
86
+ every = set()
87
+ for files in lists.values():
88
+ every.update(files)
89
+ by_dataset = {"Rain13K": [], "RESIDE_used": [], "LOLv2": [], "SIDD_Small": []}
90
+ for f in sorted(every):
91
+ if "kagglehub" in f or "rain13k" in f.lower():
92
+ by_dataset["Rain13K"].append(f)
93
+ elif "/RESIDE/" in f:
94
+ by_dataset["RESIDE_used"].append(f)
95
+ elif "/LOLv2/" in f:
96
+ by_dataset["LOLv2"].append(f)
97
+ elif "/SIDD/" in f:
98
+ by_dataset["SIDD_Small"].append(f)
99
+ else:
100
+ raise SystemExit("unclassified file: %s" % f)
101
+ # whole folders for the pools and the small datasets (LOLv2 / SIDD complete)
102
+ folders = {
103
+ "LOLv2": str(HOME / "data/LOLv2/lolv2_hf"),
104
+ "SIDD_Small": str(HOME / "data/SIDD/SIDD_Small_sRGB_Only"),
105
+ "Snow100K_gt": str(HOME / "data/Snow100K/train/all/gt"),
106
+ "Snow100K_synthetic": str(HOME / "data/Snow100K/train/all/synthetic"),
107
+ }
108
+ summary = {}
109
+ for name, files in by_dataset.items():
110
+ size = sum(os.path.getsize(f) for f in files if os.path.exists(f))
111
+ summary[name] = {"files": len(files), "bytes": size}
112
+ for name, folder in folders.items():
113
+ total = sum(p.stat().st_size for p in Path(folder).rglob("*") if p.is_file())
114
+ summary[name + "(folder)"] = {"bytes": total}
115
+ print("SUMMARY", json.dumps(summary), flush=True)
116
+ for name, files in lists.items():
117
+ (staging / "manifests" / ("%s_files.txt" % name)).write_text("\n".join(relative(f) for f in files) + "\n")
118
+ (staging / "manifests" / "path_roots.json").write_text(json.dumps(ROOTS, indent=2))
119
+ for src in (HOME / "scdc_ban/outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json",
120
+ HOME / "scdc_ban/src/data/rain13k_quarantine_v1.json"):
121
+ if src.exists():
122
+ (staging / "manifests" / src.name).write_text(src.read_text())
123
+ (staging / "README.md").write_text(README)
124
+ if args.dry_run:
125
+ return
126
+
127
+ def tar(name: str, entries: list, listfile: bool) -> None:
128
+ out = staging / ("%s.tar" % name)
129
+ if out.exists() and args.skip_tar:
130
+ return
131
+ cmd = ["tar", "-cf", str(out), "-C", str(HOME),
132
+ "--transform", "s|^\\.cache/kagglehub/|kagglehub/|"]
133
+ if listfile:
134
+ lst = staging / "manifests" / ("_%s.lst" % name)
135
+ lst.write_text("\n".join(os.path.relpath(f, HOME) for f in entries) + "\n")
136
+ cmd += ["-T", str(lst)]
137
+ else:
138
+ cmd += [os.path.relpath(entries[0], HOME)]
139
+ t0 = time.time()
140
+ subprocess.run(cmd, check=True)
141
+ print("TAR %s %.2f GB in %.0fs" % (name, out.stat().st_size / 2**30, time.time() - t0), flush=True)
142
+
143
+ tar("Rain13K", by_dataset["Rain13K"], True)
144
+ tar("RESIDE_used", by_dataset["RESIDE_used"], True)
145
+ for name, folder in folders.items():
146
+ tar(name, [folder], False)
147
+ for lst in (staging / "manifests").glob("_*.lst"):
148
+ lst.unlink()
149
+
150
+ from huggingface_hub import HfApi
151
+
152
+ token = os.environ.get("HF_TOKEN")
153
+ if not token:
154
+ raise SystemExit("HF_TOKEN is not set")
155
+ api = HfApi(token=token)
156
+ api.create_repo(REPO, repo_type="dataset", exist_ok=True)
157
+ t0 = time.time()
158
+ api.upload_large_folder(repo_id=REPO, repo_type="dataset", folder_path=str(staging),
159
+ num_workers=4, print_report_every=60)
160
+ print("UPLOAD done in %.0f min -> https://huggingface.co/datasets/%s" % ((time.time() - t0) / 60, REPO), flush=True)
161
+
162
+
163
+ README = """---
164
+ license: other
165
+ task_categories: [image-to-image]
166
+ tags: [image-restoration, deraining, dehazing, denoising, low-light]
167
+ ---
168
+ # SCDC image restoration data bundle
169
+
170
+ Exactly the files used by the SCDC project (blind degradation graph encoder +
171
+ unified two-step ResShift restorer): https://github.com/anbinh93/SCDC
172
+
173
+ | Archive | Content |
174
+ |---|---|
175
+ | `Rain13K.tar` | Rain13K pairs referenced by the Phase-1 splits (train / val / locked Test100+Test1200) and the Phase-2 manifest |
176
+ | `RESIDE_used.tar` | RESIDE hazy/clear files used for training/validation plus the 300 held-out evaluation scenes |
177
+ | `LOLv2.tar` | LOLv2-real, train (689) + test (100) |
178
+ | `SIDD_Small.tar` | SIDD Small sRGB, all 160 scenes (121 train / 19 val / 20 locked = scene 008) |
179
+ | `Snow100K_gt.tar`, `Snow100K_synthetic.tar` | Snow100K training gt (clean pool) and synthetic snow (real-unknown pool) |
180
+ | `manifests/` | `train_val_manifest_v1.json` (Phase-2 train/val, sha digests), `rain13k_quarantine_v1.json`, per-split file lists, `path_roots.json` |
181
+
182
+ Paths inside the archives are relative to two roots (see `manifests/path_roots.json`):
183
+ `/home/admin_mcn/data/` -> `data/` and `/home/admin_mcn/.cache/kagglehub/` -> `kagglehub/`.
184
+ To reuse the manifests on another machine, extract everything under one directory
185
+ and rewrite the two absolute prefixes in the JSON files to that directory.
186
+
187
+ All datasets belong to their original authors and keep their original licenses
188
+ (research use): Rain13K (Jiang et al. / MPRNet compilation), RESIDE (Li et al.),
189
+ LOLv2 (Yang et al.), SIDD (Abdelhamed et al.), Snow100K (Liu et al.).
190
+ """
191
+
192
+ if __name__ == "__main__":
193
+ main()
dataset/phase1_noise_20260906/code/infer_scdc_pipeline.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Complete SCDC inference pipeline (option A, two-stage).
3
+
4
+ degraded -> frozen Phase-1 -> diffusion U-Net (1-step x0 by default,
5
+ optional k-step chain) -> refiner decoder -> restored image
6
+
7
+ Usage:
8
+ # per-domain evaluation on the locked val split
9
+ python infer_scdc_pipeline.py --refiner outputs/refiner_a_v1/refiner_best.pt --eval
10
+
11
+ # restore arbitrary images from a directory
12
+ python infer_scdc_pipeline.py --refiner ... --images in_dir --output out_dir
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import argparse
18
+ import json
19
+ from pathlib import Path
20
+ from typing import Dict, Optional, Sequence
21
+
22
+ import torch
23
+ from torch import Tensor
24
+ from torch.utils.data import DataLoader
25
+
26
+ import train_phase2_graph_resshift_v4 as v4
27
+ from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest
28
+ from src.models.restoration.refiner_decoder import RefinerDecoder
29
+
30
+ V4_RUN = Path("outputs/phase2_graph_resshift_v4/gate_d5_seed42")
31
+
32
+
33
+ class SCDCPipeline:
34
+ """Frozen Phase-1 + frozen one-step regressor + refiner decoder."""
35
+
36
+ def __init__(
37
+ self,
38
+ refiner_checkpoint: Optional[Path],
39
+ device: torch.device,
40
+ sample_steps: int = 1,
41
+ ) -> None:
42
+ if sample_steps < 1:
43
+ raise ValueError("sample_steps must be >= 1")
44
+ self.device = device
45
+ self.sample_steps = int(sample_steps)
46
+ cfg = json.loads((V4_RUN / "run_config.json").read_text())
47
+ args = argparse.Namespace(**cfg)
48
+ for key in ("manifest", "data_root", "phase1_checkpoint"):
49
+ setattr(args, key, Path(str(getattr(args, key))))
50
+ self.args = args
51
+ self.regressor = v4._build_restorer(args, device)
52
+ checkpoint = v4._torch_load(V4_RUN / "best.pt")
53
+ self.regressor.load_state_dict(
54
+ checkpoint["ema_state_dict"]["shadow"], strict=True
55
+ )
56
+ self.regressor.eval()
57
+ for parameter in self.regressor.parameters():
58
+ parameter.requires_grad_(False)
59
+ self.phase1, _ = v4.build_frozen_phase1(
60
+ args.phase1_checkpoint, args.phase1_sha256, device
61
+ )
62
+ self.refiner: Optional[RefinerDecoder] = None
63
+ if refiner_checkpoint is not None:
64
+ state = torch.load(str(refiner_checkpoint), map_location="cpu")
65
+ refiner = RefinerDecoder()
66
+ refiner.load_state_dict(state["refiner_state_dict"], strict=True)
67
+ self.refiner = refiner.to(device).eval()
68
+
69
+ @torch.no_grad()
70
+ def regress_x0(
71
+ self, degraded: Tensor, record_ids: Optional[Sequence[str]], seed: int
72
+ ) -> Tensor:
73
+ if self.sample_steps > 1:
74
+ return v4.sample_restoration(
75
+ self.regressor, self.phase1, degraded,
76
+ seed=seed, record_ids=list(record_ids) if record_ids else None,
77
+ )
78
+ padded, size = v4.pad_to_multiple(degraded, multiple=16)
79
+ representation = self.phase1(padded)
80
+ condition = self.regressor.build_condition(representation)
81
+ uy = v4.pixel_unshuffle2(padded)
82
+ noise = v4._noise_for_records(
83
+ uy, list(record_ids) if record_ids else None, seed=seed, stage="initial"
84
+ )
85
+ eta_terminal = self.regressor.schedule.eta[-1].to(uy.device, uy.dtype)
86
+ kappa = self.regressor.schedule.kappa.to(uy.device, uy.dtype)
87
+ u_terminal = uy + kappa * torch.sqrt(eta_terminal) * noise
88
+ timesteps = torch.full(
89
+ (uy.shape[0],), self.regressor.schedule.timesteps,
90
+ device=uy.device, dtype=torch.long,
91
+ )
92
+ u0_hat = self.regressor.predict_x0(u_terminal, uy, timesteps, condition)
93
+ out = v4.pixel_shuffle2(u0_hat)
94
+ height, width = size
95
+ return out[..., :height, :width].clamp(0.0, 1.0)
96
+
97
+ @torch.no_grad()
98
+ def restore(
99
+ self,
100
+ degraded: Tensor,
101
+ record_ids: Optional[Sequence[str]] = None,
102
+ seed: int = 20260830,
103
+ ) -> Dict[str, Tensor]:
104
+ degraded = degraded.to(self.device)
105
+ x0_hat = self.regress_x0(degraded, record_ids, seed)
106
+ if self.refiner is None:
107
+ return {"x0_hat": x0_hat, "restored": x0_hat}
108
+ padded_x0, size = v4.pad_to_multiple(x0_hat, multiple=4)
109
+ padded_y, _ = v4.pad_to_multiple(degraded, multiple=4)
110
+ refined = self.refiner(padded_x0, padded_y)
111
+ height, width = size
112
+ return {"x0_hat": x0_hat, "restored": refined[..., :height, :width]}
113
+
114
+
115
+ def run_eval(pipeline: SCDCPipeline, output: Path) -> None:
116
+ splits = load_train_val_manifest(pipeline.args.manifest)
117
+ loader = DataLoader(
118
+ Phase2PairDataset(splits.val, crop_size=256, training=False,
119
+ upscale_small=True),
120
+ batch_size=8, shuffle=False, num_workers=4,
121
+ )
122
+ acc: Dict[str, Dict[str, list]] = {}
123
+ for batch in loader:
124
+ clean = batch["clean"].to(pipeline.device)
125
+ result = pipeline.restore(
126
+ batch["degraded"],
127
+ record_ids=[str(v) for v in batch["record_id"]],
128
+ seed=int(pipeline.args.eval_seed),
129
+ )
130
+ for name in ("x0_hat", "restored"):
131
+ psnr = v4.rgb_psnr_per_image(result[name], clean).cpu().tolist()
132
+ ssim = v4.rgb_ssim_per_image(result[name], clean).cpu().tolist()
133
+ for domain, p, s in zip(
134
+ [str(v) for v in batch["degradation"]], psnr, ssim
135
+ ):
136
+ slot = acc.setdefault(name, {}).setdefault(
137
+ domain, {"psnr": [], "ssim": []}
138
+ )
139
+ slot["psnr"].append(p)
140
+ slot["ssim"].append(s)
141
+ report: Dict[str, object] = {"sample_steps": pipeline.sample_steps}
142
+ for name, domains in acc.items():
143
+ block = {}
144
+ for domain, values in sorted(domains.items()):
145
+ block[domain] = {
146
+ "psnr": sum(values["psnr"]) / len(values["psnr"]),
147
+ "ssim": sum(values["ssim"]) / len(values["ssim"]),
148
+ "count": len(values["psnr"]),
149
+ }
150
+ block["macro_psnr"] = sum(v["psnr"] for v in block.values()) / len(block)
151
+ block["macro_ssim"] = sum(
152
+ v["ssim"] for v in block.values() if isinstance(v, dict)
153
+ ) / len([v for v in block.values() if isinstance(v, dict)])
154
+ report[name] = block
155
+ output.parent.mkdir(parents=True, exist_ok=True)
156
+ output.write_text(json.dumps(report, indent=2, sort_keys=True))
157
+ print(json.dumps(report, indent=2, sort_keys=True))
158
+
159
+
160
+ def run_images(pipeline: SCDCPipeline, images: Path, output: Path) -> None:
161
+ from PIL import Image
162
+ import numpy as np
163
+
164
+ output.mkdir(parents=True, exist_ok=True)
165
+ paths = sorted(
166
+ p for p in images.iterdir()
167
+ if p.suffix.lower() in (".png", ".jpg", ".jpeg", ".bmp")
168
+ )
169
+ for path in paths:
170
+ array = np.asarray(
171
+ Image.open(path).convert("RGB"), dtype=np.float32
172
+ ) / 255.0
173
+ tensor = torch.from_numpy(array).permute(2, 0, 1).unsqueeze(0)
174
+ restored = pipeline.restore(tensor)["restored"][0]
175
+ out = (restored.clamp(0, 1).cpu().permute(1, 2, 0).numpy() * 255).astype(
176
+ "uint8"
177
+ )
178
+ Image.fromarray(out).save(output / path.name)
179
+ print("restored", path.name, flush=True)
180
+
181
+
182
+ def main() -> None:
183
+ parser = argparse.ArgumentParser(description=__doc__)
184
+ parser.add_argument("--refiner", type=Path, default=None)
185
+ parser.add_argument("--sample-steps", type=int, default=1)
186
+ parser.add_argument("--eval", action="store_true")
187
+ parser.add_argument("--images", type=Path, default=None)
188
+ parser.add_argument("--output", type=Path,
189
+ default=Path("outputs/pipeline_eval.json"))
190
+ args = parser.parse_args()
191
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
192
+ pipeline = SCDCPipeline(args.refiner, device, sample_steps=args.sample_steps)
193
+ if args.eval:
194
+ run_eval(pipeline, args.output)
195
+ if args.images is not None:
196
+ run_images(pipeline, args.images, args.output)
197
+
198
+
199
+ if __name__ == "__main__":
200
+ main()
dataset/phase1_noise_20260906/code/make_final_charts.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Static slide charts for the SCDC final report (matplotlib, light surface).
3
+
4
+ Palette: validated categorical slots (blue, orange, aqua, yellow) in fixed
5
+ order; text in ink tokens; thin marks; recessive grid; no dual axes.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ from pathlib import Path
13
+
14
+ import matplotlib
15
+
16
+ matplotlib.use("Agg")
17
+ import matplotlib.pyplot as plt
18
+
19
+ SURFACE = "#fcfcfb"
20
+ INK = "#0b0b0b"
21
+ INK2 = "#52514e"
22
+ GRID = "#e6e5e1"
23
+ C = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"] # fixed categorical order
24
+ NEUTRAL = "#b9b8b3"
25
+
26
+
27
+ def _style(ax, title, xlabel=""):
28
+ ax.set_facecolor(SURFACE)
29
+ for side in ("top", "right", "left"):
30
+ ax.spines[side].set_visible(False)
31
+ ax.spines["bottom"].set_color(GRID)
32
+ ax.tick_params(colors=INK2, length=0)
33
+ ax.grid(axis="x", color=GRID, linewidth=0.8)
34
+ ax.set_axisbelow(True)
35
+ ax.set_title(title, loc="left", color=INK, fontsize=12, fontweight="semibold")
36
+ if xlabel:
37
+ ax.set_xlabel(xlabel, color=INK2)
38
+
39
+
40
+ def chart_progression(out: Path) -> None:
41
+ rows = [
42
+ ("v4 ResShift 1-step (conv, 8-step train)", 22.68, 0.662, NEUTRAL),
43
+ ("v7 unified 2-step (conv, warm-start)", 23.41, 0.703, NEUTRAL),
44
+ ("v7 Uformer, from scratch 8k", 25.26, 0.777, C[0]),
45
+ ("+ chroma loss, warm-restart 16k", 26.44, 0.808, C[0]),
46
+ ("+ luma loss, 8k", 26.59, 0.811, C[0]),
47
+ ("+ full-res head + FiLM, 8k", 27.43, 0.846, C[0]),
48
+ ("+ DGF (null tokens, identity, pyramid), 8k", 27.50, 0.850, C[0]),
49
+ ("ref: Pipeline A (2 networks)", 26.76, 0.863, C[1]),
50
+ ("ref: gen-2 (2 networks)", 27.55, 0.874, C[1]),
51
+ ]
52
+ fig, ax = plt.subplots(figsize=(10, 5.2), facecolor=SURFACE)
53
+ names = [r[0] for r in rows][::-1]
54
+ vals = [r[1] for r in rows][::-1]
55
+ cols = [r[3] for r in rows][::-1]
56
+ ssim = [r[2] for r in rows][::-1]
57
+ import numpy as np
58
+ pos = np.arange(len(names))
59
+ bars = ax.barh(pos, vals, color=cols, height=0.62, align="center")
60
+ ax.set_yticks(pos)
61
+ ax.set_yticklabels(names, color=INK, fontsize=9)
62
+ for y, v, s in zip(pos, vals, ssim):
63
+ ax.text(v + 0.06, y, "%.2f dB · SSIM %.3f" % (v, s),
64
+ va="center", ha="left", color=INK, fontsize=9)
65
+ ax.set_xlim(22, 28.6)
66
+ _style(ax, "Internal validation: macro PSNR by version\n(one network in blue, two-network references in orange)", "PSNR (dB)")
67
+ fig.tight_layout()
68
+ fig.savefig(str(out), dpi=160, facecolor=SURFACE)
69
+ plt.close(fig)
70
+
71
+
72
+ def chart_external(out: Path) -> None:
73
+ sets = ["Rain (locked, 1200)", "Haze (held-out, 300)", "Noise scene008 (20)"]
74
+ series = [
75
+ ("Degraded input", [22.56, 18.17, 39.02], NEUTRAL),
76
+ ("gen-2, two networks", [26.71, 31.18, 22.35], C[1]),
77
+ ("head8k, one network", [28.02, 31.71, 27.09], C[0]),
78
+ ("DGF (w=1), one network", [27.88, 31.87, 26.50], C[2]),
79
+ ]
80
+ fig, ax = plt.subplots(figsize=(10, 4.6), facecolor=SURFACE)
81
+ import numpy as np
82
+ x = np.arange(len(sets))
83
+ w = 0.19
84
+ for i, (label, vals, col) in enumerate(series):
85
+ bars = ax.bar(x + (i - 1.5) * w, vals, width=w - 0.02, color=col, label=label)
86
+ for b, v in zip(bars, vals):
87
+ ax.text(b.get_x() + b.get_width() / 2, v + 0.4, "%.1f" % v, ha="center", va="bottom", color=INK, fontsize=8)
88
+ ax.set_xticks(x)
89
+ ax.set_xticklabels(sets, color=INK)
90
+ ax.set_ylim(15, 42)
91
+ ax.grid(axis="y", color=GRID, linewidth=0.8)
92
+ ax.grid(False, axis="x")
93
+ _style(ax, "External held-out PSNR\n(one network beats the two-network pipeline out of distribution)", "")
94
+ ax.set_ylabel("PSNR (dB)", color=INK2)
95
+ ax.legend(frameon=False, ncol=2, loc="upper center", fontsize=9)
96
+ fig.tight_layout()
97
+ fig.savefig(str(out), dpi=160, facecolor=SURFACE)
98
+ plt.close(fig)
99
+
100
+
101
+ def chart_probe(out: Path) -> None:
102
+ rows = [
103
+ ("context (cross-attention tokens)", -3.68),
104
+ ("global_vector (adaLN)", -3.45),
105
+ ("unknown_residual (field)", -0.74),
106
+ ("global_condition (field)", -0.24),
107
+ ("node_tokens (field)", -0.16),
108
+ ("MoE gate + per-type κ (uniform)", -0.085),
109
+ ("routing_probs (field)", -0.05),
110
+ ("severity_coords (field)", -0.03),
111
+ ("spatial maps 16×16 (inject)", -0.01),
112
+ ("content latent 64 px (inject)", 0.00),
113
+ ]
114
+ fig, ax = plt.subplots(figsize=(10, 4.8), facecolor=SURFACE)
115
+ names = [r[0] for r in rows][::-1]
116
+ vals = [r[1] for r in rows][::-1]
117
+ cols = [C[0] if v < -1 else (C[3] if v < -0.1 else NEUTRAL) for v in vals]
118
+ import numpy as np
119
+ pos = np.arange(len(names))
120
+ ax.barh(pos, vals, color=cols, height=0.62, align="center")
121
+ ax.set_yticks(pos)
122
+ ax.set_yticklabels(names, color=INK, fontsize=9)
123
+ for y, v in zip(pos, vals):
124
+ if v < -0.3:
125
+ ax.text(v - 0.05, y, "%+.2f dB" % v, va="center", ha="right", color=INK, fontsize=9)
126
+ else:
127
+ ax.text(0.06, y, "%+.2f dB" % v, va="center", ha="left", color=INK, fontsize=9)
128
+ ax.set_xlim(-4.2, 0.6)
129
+ _style(ax, "Inference-time ablation (head8k)\nmacro PSNR change when one Phase-1 tap is removed", "Δ macro PSNR (dB)")
130
+ fig.tight_layout()
131
+ fig.savefig(str(out), dpi=160, facecolor=SURFACE)
132
+ plt.close(fig)
133
+
134
+
135
+ def chart_control(out: Path, control: dict, conditioned: dict) -> None:
136
+ steps = sorted(set(control) & set(conditioned))
137
+ fig, ax = plt.subplots(figsize=(10, 4.4), facecolor=SURFACE)
138
+ ax.plot(steps, [conditioned[s] for s in steps], color=C[0], linewidth=2, marker="o", markersize=5, label="with Phase-1 (DGF p=0.15, eval w=1)")
139
+ ax.plot(steps, [control[s] for s in steps], color=C[1], linewidth=2, marker="o", markersize=5, label="no Phase-1 (p=1, unconditional)")
140
+ for s in (steps[-1],):
141
+ ax.text(s - 120, conditioned[s] + 0.12, "%.2f" % conditioned[s], color=INK, fontsize=9, ha="right")
142
+ ax.text(s - 120, control[s] - 0.3, "%.2f" % control[s], color=INK, fontsize=9, ha="right")
143
+ ax.set_xlabel("fine-tune step", color=INK2)
144
+ ax.set_ylabel("macro PSNR (dB)", color=INK2)
145
+ ax.grid(axis="y", color=GRID, linewidth=0.8)
146
+ ax.grid(False, axis="x")
147
+ _style(ax, "Does the trunk need Phase-1?\n(same recipe and warm start; conditioning on vs. off)", "")
148
+ ax.legend(frameon=False, loc="lower right", fontsize=9)
149
+ fig.tight_layout()
150
+ fig.savefig(str(out), dpi=160, facecolor=SURFACE)
151
+ plt.close(fig)
152
+
153
+
154
+ def main() -> None:
155
+ parser = argparse.ArgumentParser(description=__doc__)
156
+ parser.add_argument("--out-dir", type=Path, default=Path("outputs/final_charts"))
157
+ parser.add_argument("--control-metrics", type=Path, default=None)
158
+ parser.add_argument("--conditioned-metrics", type=Path, default=None)
159
+ args = parser.parse_args()
160
+ args.out_dir.mkdir(parents=True, exist_ok=True)
161
+ chart_progression(args.out_dir / "01_version_progression.png")
162
+ chart_external(args.out_dir / "02_external.png")
163
+ chart_probe(args.out_dir / "03_tap_probe.png")
164
+ if args.control_metrics and args.conditioned_metrics:
165
+ def evals(path):
166
+ out = {}
167
+ for line in open(path):
168
+ r = json.loads(line)
169
+ if r.get("event") == "evaluation":
170
+ out[int(r["step"])] = float(r["macro_psnr"])
171
+ return out
172
+ chart_control(args.out_dir / "04_phase1_control.png", evals(args.control_metrics), evals(args.conditioned_metrics))
173
+ print("charts written to", args.out_dir)
174
+
175
+
176
+ if __name__ == "__main__":
177
+ main()
dataset/phase1_noise_20260906/code/probe_color_space.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Does an HVI colour state buy Phase-1 / Phase-2 anything? Three measurements,
3
+ no training required.
4
+
5
+ H1 Representation: per-image colour features in HVI (hvi_colour_stats) vs the
6
+ current photometric stats (RGB/luma) vs YUV chroma stats — 5-fold linear
7
+ probe for {rain, noise, haze, lowlight, clean, real snow}; also a
8
+ colour-only variant (chroma features alone) to isolate the colour space.
9
+ H2 Error anatomy of the current Phase-2 (run A): how much of the remaining
10
+ squared error sits in the HV (colour) plane vs the I plane, per domain.
11
+ H3 Controllability ceiling: per-image GLOBAL fits on the output — I affine
12
+ (exposure knob), HV affine (colour knob: 2x2 matrix + bias), both — and
13
+ the PSNR each recovers. An upper bound on what a per-image colour
14
+ conditioning could deliver.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import glob
21
+ import json
22
+ import math
23
+ from pathlib import Path
24
+ from typing import Dict, List, Sequence, Tuple
25
+
26
+ import numpy as np
27
+ import torch
28
+
29
+ import eval_pipeline_external as ext
30
+ import train_graph_encoder_v2 as p1
31
+ import train_phase2_graph_resshift_v4 as v4
32
+ import train_phase2_unified_v7 as v7
33
+ from eval_v7_external import V7Pipeline
34
+ from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest
35
+ from src.models.graph_encoder.encoder import photometric_stats
36
+ from src.models.graph_encoder.hvi import (
37
+ HVI_STAT_NAMES, hvi_colour_stats, hvi_to_rgb, rgb_to_hvi,
38
+ )
39
+
40
+ DOMAINS = ("rain", "noise", "haze", "lowlight")
41
+ CLASSES = ("rain", "noise", "haze", "lowlight", "clean", "snow_real")
42
+ _EPS = 1e-8
43
+
44
+
45
+ # --------------------------------------------------------------------------- #
46
+ # feature sets
47
+ # --------------------------------------------------------------------------- #
48
+ def _hh1_mad(plane: torch.Tensor) -> torch.Tensor:
49
+ x = plane[:, None]
50
+ hh = (x[..., 0::2, 0::2] - x[..., 0::2, 1::2] - x[..., 1::2, 0::2] + x[..., 1::2, 1::2]) / 2.0
51
+ return hh.abs().flatten(1).median(dim=1).values / 0.6745
52
+
53
+
54
+ def yuv_stats(rgb: torch.Tensor) -> torch.Tensor:
55
+ uv = v7.rgb_to_uv(rgb)
56
+ y = v7.rgb_to_luma(rgb)[:, 0]
57
+ radius = uv.norm(dim=1).flatten(1)
58
+ yf = y.flatten(1)
59
+ return torch.stack((
60
+ uv[:, 0].flatten(1).mean(1), uv[:, 1].flatten(1).mean(1),
61
+ radius.mean(1), radius.std(1), radius.quantile(0.95, dim=1),
62
+ _hh1_mad(uv[:, 0]), _hh1_mad(uv[:, 1]),
63
+ yf.mean(1), yf.std(1), yf.quantile(0.05, dim=1), yf.quantile(0.95, dim=1),
64
+ ), dim=1)
65
+
66
+
67
+ FEATURE_SETS = {
68
+ "rgb_photometric14": lambda x, k: photometric_stats(x),
69
+ "yuv11": lambda x, k: yuv_stats(x),
70
+ "hvi13": lambda x, k: hvi_colour_stats(x, k),
71
+ # colour-only slices (no luminance information at all)
72
+ "rgb_colour3": lambda x, k: photometric_stats(x)[:, 6:9],
73
+ "yuv_colour7": lambda x, k: yuv_stats(x)[:, :7],
74
+ "hvi_colour7": lambda x, k: hvi_colour_stats(x, k)[:, :7],
75
+ }
76
+
77
+
78
+ @torch.no_grad()
79
+ def features_for(images: torch.Tensor, k: float, batch: int = 32) -> Dict[str, np.ndarray]:
80
+ out: Dict[str, List[torch.Tensor]] = {n: [] for n in FEATURE_SETS}
81
+ for start in range(0, images.shape[0], batch):
82
+ chunk = images[start:start + batch].float()
83
+ for name, fn in FEATURE_SETS.items():
84
+ out[name].append(fn(chunk, k).float().cpu())
85
+ return {n: torch.cat(v).numpy() for n, v in out.items()}
86
+
87
+
88
+ # --------------------------------------------------------------------------- #
89
+ # linear probe (torch multinomial logistic regression, 5-fold stratified)
90
+ # --------------------------------------------------------------------------- #
91
+ def _fit_logreg(x: torch.Tensor, y: torch.Tensor, n_classes: int, l2: float = 1e-3) -> torch.nn.Linear:
92
+ model = torch.nn.Linear(x.shape[1], n_classes)
93
+ opt = torch.optim.LBFGS(model.parameters(), lr=0.5, max_iter=300, line_search_fn="strong_wolfe")
94
+ counts = torch.bincount(y, minlength=n_classes).float().clamp_min(1)
95
+ weight = counts.sum() / (n_classes * counts) # class-balanced CE
96
+
97
+ def closure():
98
+ opt.zero_grad()
99
+ loss = torch.nn.functional.cross_entropy(model(x), y, weight=weight)
100
+ loss = loss + l2 * model.weight.square().sum()
101
+ loss.backward()
102
+ return loss
103
+
104
+ opt.step(closure)
105
+ return model
106
+
107
+
108
+ def linear_probe(features: np.ndarray, labels: np.ndarray, n_classes: int, folds: int = 5, seed: int = 0) -> Dict[str, object]:
109
+ rng = np.random.RandomState(seed)
110
+ fold_of = np.zeros(len(labels), dtype=int)
111
+ for c in range(n_classes):
112
+ idx = np.where(labels == c)[0]
113
+ rng.shuffle(idx)
114
+ for f, chunk in enumerate(np.array_split(idx, folds)):
115
+ fold_of[chunk] = f
116
+ confusion = np.zeros((n_classes, n_classes), dtype=np.int64)
117
+ for f in range(folds):
118
+ tr, te = fold_of != f, fold_of == f
119
+ mu, sd = features[tr].mean(0), features[tr].std(0) + 1e-6
120
+ xtr = torch.tensor((features[tr] - mu) / sd, dtype=torch.float32)
121
+ xte = torch.tensor((features[te] - mu) / sd, dtype=torch.float32)
122
+ model = _fit_logreg(xtr, torch.tensor(labels[tr]), n_classes)
123
+ with torch.no_grad():
124
+ pred = model(xte).argmax(1).numpy()
125
+ for t, p in zip(labels[te], pred):
126
+ confusion[t, p] += 1
127
+ recall = confusion.diagonal() / confusion.sum(1).clip(min=1)
128
+ return {
129
+ "balanced_accuracy": float(recall.mean()),
130
+ "per_class_recall": {CLASSES[i]: float(recall[i]) for i in range(n_classes)},
131
+ "confusion": confusion.tolist(),
132
+ }
133
+
134
+
135
+ # --------------------------------------------------------------------------- #
136
+ # H2 / H3 on Phase-2 outputs
137
+ # --------------------------------------------------------------------------- #
138
+ def _lstsq(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
139
+ """Least squares a @ x = b (a [N,p], b [N,q]) via normal equations."""
140
+ ata = a.T @ a + 1e-6 * torch.eye(a.shape[1], device=a.device, dtype=a.dtype)
141
+ return torch.linalg.solve(ata, a.T @ b)
142
+
143
+
144
+ def _psnr(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
145
+ return v4.rgb_psnr_per_image(x.clamp(0, 1), y)
146
+
147
+
148
+ @torch.no_grad()
149
+ def error_anatomy(restored: torch.Tensor, clean: torch.Tensor, k: float) -> Dict[str, torch.Tensor]:
150
+ hvi_r, hvi_c = rgb_to_hvi(restored, k), rgb_to_hvi(clean, k)
151
+ err = (hvi_r - hvi_c).square().flatten(2).mean(2) # [B,3]
152
+ uv_err = (v7.rgb_to_uv(restored) - v7.rgb_to_uv(clean)).square().flatten(2).mean(2).sum(1)
153
+ y_err = (v7.rgb_to_luma(restored) - v7.rgb_to_luma(clean)).square().flatten(1).mean(1)
154
+ n = restored.shape[0]
155
+ i_fit, hv_fit, both = [], [], []
156
+ for i in range(n):
157
+ r, c = hvi_r[i].double(), hvi_c[i].double()
158
+ ones = torch.ones_like(r[2].flatten())
159
+ # intensity affine
160
+ a_i = torch.stack((r[2].flatten(), ones), 1)
161
+ coef = _lstsq(a_i, c[2].flatten()[:, None])
162
+ i_new = (a_i @ coef).reshape(r[2].shape).clamp(0, 1)
163
+ # HV affine (2x2 + bias)
164
+ a_hv = torch.stack((r[0].flatten(), r[1].flatten(), ones), 1)
165
+ coef_hv = _lstsq(a_hv, torch.stack((c[0].flatten(), c[1].flatten()), 1))
166
+ hv_new = (a_hv @ coef_hv).T.reshape(2, *r[0].shape)
167
+ i_fit.append(torch.stack((r[0], r[1], i_new)).float())
168
+ hv_fit.append(torch.stack((hv_new[0].float(), hv_new[1].float(), r[2].float())))
169
+ both.append(torch.stack((hv_new[0].float(), hv_new[1].float(), i_new.float())))
170
+ to_rgb = lambda lst: hvi_to_rgb(torch.stack(lst), k)
171
+ return {
172
+ "mse_H": err[:, 0], "mse_V": err[:, 1], "mse_I": err[:, 2],
173
+ "mse_UV": uv_err, "mse_Y": y_err,
174
+ "psnr_raw": _psnr(restored, clean),
175
+ "psnr_I_affine": _psnr(to_rgb(i_fit), clean),
176
+ "psnr_HV_affine": _psnr(to_rgb(hv_fit), clean),
177
+ "psnr_both": _psnr(to_rgb(both), clean),
178
+ "psnr_hvi_roundtrip": _psnr(hvi_to_rgb(hvi_r, k), clean),
179
+ }
180
+
181
+
182
+ # --------------------------------------------------------------------------- #
183
+ def _load_dir_images(pattern: str, size: int = 256) -> torch.Tensor:
184
+ from PIL import Image
185
+ files = sorted(glob.glob(pattern, recursive=True))
186
+ out = []
187
+ for f in files:
188
+ im = Image.open(f).convert("RGB")
189
+ w, h = im.size
190
+ s = size / min(w, h)
191
+ if s > 1:
192
+ im = im.resize((max(size, math.ceil(w * s)), max(size, math.ceil(h * s))), Image.LANCZOS)
193
+ w, h = im.size
194
+ l, t = (w - size) // 2, (h - size) // 2
195
+ im = im.crop((l, t, l + size, t + size))
196
+ out.append(torch.from_numpy(np.asarray(im, dtype=np.float32) / 255.0).permute(2, 0, 1))
197
+ return torch.stack(out)
198
+
199
+
200
+ def main() -> None:
201
+ parser = argparse.ArgumentParser(description=__doc__)
202
+ parser.add_argument("--run-dir", type=Path, default=Path("outputs/phase2_v7/uformer_p5_8k_seed42"))
203
+ parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json"))
204
+ parser.add_argument("--snow-glob", default="/home/admin_mcn/data/Snow100K/realistic/**/*.jpg")
205
+ parser.add_argument("--output", type=Path, default=Path("outputs/color_space_probe.json"))
206
+ parser.add_argument("--k", type=float, default=0.2)
207
+ parser.add_argument("--device", default="cuda")
208
+ args = parser.parse_args()
209
+ device = torch.device(args.device)
210
+
211
+ splits = load_train_val_manifest(args.manifest)
212
+ dataset = Phase2PairDataset(splits.val, crop_size=256, training=False, upscale_small=True)
213
+ groups: Dict[str, torch.Tensor] = {}
214
+ pairs: Dict[str, Tuple[torch.Tensor, torch.Tensor, List[str], torch.Tensor]] = {}
215
+ for d in DOMAINS:
216
+ idx = [i for i, r in enumerate(splits.val) if r.degradation == d]
217
+ items = [dataset[i] for i in idx]
218
+ deg = torch.stack([it["degraded"] for it in items])
219
+ cln = torch.stack([it["clean"] for it in items])
220
+ full = torch.stack([it["full_degraded"] for it in items])
221
+ groups[d] = deg
222
+ groups["clean_" + d] = cln
223
+ pairs[d] = (deg, cln, [it["record_id"] for it in items], full)
224
+ p1_args = p1.build_parser().parse_args([])
225
+ ext_splits = p1.build_data_splits(p1_args)
226
+ s8 = [r for r in ext_splits.locked_test if r.degradation == "noise"]
227
+ ds8 = ext.PairCropDataset(s8)
228
+ it8 = [ds8[i] for i in range(len(s8))]
229
+ groups["scene008_input"] = torch.stack([it["degraded"] for it in it8])
230
+ groups["scene008_clean"] = torch.stack([it["clean"] for it in it8])
231
+ pairs["scene008"] = (groups["scene008_input"], groups["scene008_clean"],
232
+ [it["record_id"] for it in it8], torch.stack([it["full_degraded"] for it in it8]))
233
+ groups["snow_real"] = _load_dir_images(args.snow_glob)
234
+ print("groups:", {k: int(v.shape[0]) for k, v in groups.items()})
235
+
236
+ # ---- H1 ------------------------------------------------------------- #
237
+ feats_by_group = {g: features_for(x.to(device), args.k) for g, x in groups.items()}
238
+ label_of = {d: i for i, d in enumerate(DOMAINS)}
239
+ rows, labels = {n: [] for n in FEATURE_SETS}, []
240
+ for g, feats in feats_by_group.items():
241
+ if g in label_of:
242
+ lab = label_of[g]
243
+ elif g.startswith("clean_") or g.startswith("scene008"):
244
+ lab = CLASSES.index("clean")
245
+ else:
246
+ lab = CLASSES.index("snow_real")
247
+ n = next(iter(feats.values())).shape[0]
248
+ labels.extend([lab] * n)
249
+ for name in FEATURE_SETS:
250
+ rows[name].append(feats[name])
251
+ labels = np.array(labels)
252
+ h1 = {}
253
+ for name in FEATURE_SETS:
254
+ h1[name] = linear_probe(np.concatenate(rows[name]), labels, len(CLASSES))
255
+ print("H1 %-20s bal.acc %.3f recall %s" % (
256
+ name, h1[name]["balanced_accuracy"],
257
+ " ".join("%s=%.2f" % (c[:5], v) for c, v in h1[name]["per_class_recall"].items())))
258
+ union = np.concatenate([np.concatenate(rows[n]) for n in ("rgb_photometric14", "hvi13")], axis=1)
259
+ h1["rgb14+hvi13"] = linear_probe(union, labels, len(CLASSES))
260
+ print("H1 %-20s bal.acc %.3f" % ("rgb14+hvi13", h1["rgb14+hvi13"]["balanced_accuracy"]))
261
+ # group-mean HVI stats (for the report)
262
+ h1["group_mean_hvi"] = {g: dict(zip(HVI_STAT_NAMES, np.round(f["hvi13"].mean(0), 4).tolist()))
263
+ for g, f in feats_by_group.items()}
264
+
265
+ # ---- H2 / H3 -------------------------------------------------------- #
266
+ pipe = V7Pipeline(args.run_dir, device)
267
+ h23 = {}
268
+ for name, (deg, cln, ids, full) in pairs.items():
269
+ acc: Dict[str, List[torch.Tensor]] = {}
270
+ for start in range(0, deg.shape[0], 8):
271
+ sl = slice(start, start + 8)
272
+ restored = pipe.restore(deg[sl].to(device), record_ids=ids[sl],
273
+ full_degraded=full[sl].to(device))["restored"].float().clamp(0, 1)
274
+ for key, val in error_anatomy(restored, cln[sl].to(device), args.k).items():
275
+ acc.setdefault(key, []).append(val.cpu())
276
+ means = {k: float(torch.cat(v).mean()) for k, v in acc.items()}
277
+ hv = means["mse_H"] + means["mse_V"]
278
+ means["share_HV_of_HVI"] = hv / (hv + means["mse_I"] + _EPS)
279
+ means["share_UV_of_YUV"] = means["mse_UV"] / (means["mse_UV"] + means["mse_Y"] + _EPS)
280
+ means["n"] = int(deg.shape[0])
281
+ h23[name] = means
282
+ print("H2/H3 %-9s n=%3d psnr raw %.2f | I-affine %.2f | HV-affine %.2f | both %.2f | HV share(HVI) %.2f UV share(YUV) %.2f | roundtrip %.1f" % (
283
+ name, means["n"], means["psnr_raw"], means["psnr_I_affine"], means["psnr_HV_affine"],
284
+ means["psnr_both"], means["share_HV_of_HVI"], means["share_UV_of_YUV"], means["psnr_hvi_roundtrip"]))
285
+
286
+ args.output.write_text(json.dumps({"run_dir": str(args.run_dir), "k": args.k, "H1": h1, "H2H3": h23}, indent=2))
287
+ print("WROTE", args.output)
288
+
289
+
290
+ if __name__ == "__main__":
291
+ main()
dataset/phase1_noise_20260906/code/probe_phase1_scale.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Does Phase-1's resize-centre-crop policy hide the degradation it must detect?
3
+
4
+ The Phase-1 trainer (``train_graph_encoder_v2.PairDataset``) resizes every pair
5
+ so the short side is 256 and takes ONE centre crop. SIDD frames are ~4000x3000,
6
+ so the noise class is seen at ~12x downsampling (sensor noise averaged away);
7
+ Rain13K (384), LOL (600x400) and RESIDE (~550x413) are seen at ~1.5x. Phase-2
8
+ and the Phase-1 dashboard consume native-resolution 256 crops instead.
9
+
10
+ This probe routes the SAME validation pairs through one or more Phase-1
11
+ checkpoints under three policies and reports the routing per domain (and per
12
+ ISO for SIDD):
13
+
14
+ A trainer policy resize short side -> 256, centre crop
15
+ B native centre Phase-2 policy (upscale only if smaller than 256)
16
+ C native random K random native crops per pair (mean over crops)
17
+
18
+ It also routes the Snow100K ``gt`` clean pool stratified by a dark-channel
19
+ haze proxy, with RESIDE hazy / clear and Rain13K / LOL clean crops as
20
+ reference distributions, to test whether the pool carries haze-like cues.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import json
27
+ import random
28
+ from collections import defaultdict
29
+ from pathlib import Path
30
+ from typing import Dict, List, Sequence, Tuple
31
+
32
+ import torch
33
+ import torch.nn.functional as F
34
+ from PIL import Image
35
+
36
+ import train_graph_encoder_v2 as v2
37
+ import train_phase2_graph_resshift_v4 as v4
38
+ from src.data.folder_crops import list_image_files
39
+
40
+ NODES = ("rain", "noise", "haze", "lowlight", "free1", "free2")
41
+ DOMAIN_INDEX = {"rain": 0, "noise": 1, "haze": 2, "lowlight": 3}
42
+
43
+
44
+ def native_centre_crop(image: Image.Image, size: int) -> Image.Image:
45
+ width, height = image.size
46
+ if min(width, height) < size:
47
+ scale = float(size) / min(width, height)
48
+ image = image.resize(
49
+ (max(size, int(round(width * scale))), max(size, int(round(height * scale)))),
50
+ v2._LANCZOS,
51
+ )
52
+ width, height = image.size
53
+ left, top = (width - size) // 2, (height - size) // 2
54
+ return image.crop((left, top, left + size, top + size))
55
+
56
+
57
+ def native_random_crops(image: Image.Image, size: int, count: int, seed: int) -> List[Image.Image]:
58
+ width, height = image.size
59
+ if min(width, height) < size:
60
+ return [native_centre_crop(image, size)] * count
61
+ rng = random.Random(seed)
62
+ crops = []
63
+ for _ in range(count):
64
+ left = rng.randrange(width - size + 1)
65
+ top = rng.randrange(height - size + 1)
66
+ crops.append(image.crop((left, top, left + size, top + size)))
67
+ return crops
68
+
69
+
70
+ def sidd_iso(source_id: str) -> str:
71
+ parts = Path(source_id).name.split("_")
72
+ return parts[3] if len(parts) > 3 else "?"
73
+
74
+
75
+ def dark_channel_mean(images: torch.Tensor, patch: int = 15) -> torch.Tensor:
76
+ """Mean of the dark channel (He et al.): low for clear scenes, high for haze."""
77
+ minimum = images.amin(dim=1, keepdim=True)
78
+ dark = -F.max_pool2d(-minimum, patch, stride=1, padding=patch // 2)
79
+ return dark.mean(dim=(1, 2, 3))
80
+
81
+
82
+ def luma_contrast(images: torch.Tensor) -> torch.Tensor:
83
+ luma = 0.299 * images[:, 0] + 0.587 * images[:, 1] + 0.114 * images[:, 2]
84
+ return luma.flatten(1).std(dim=1)
85
+
86
+
87
+ @torch.no_grad()
88
+ def route(phase1, images: torch.Tensor, device: torch.device, batch: int = 16) -> torch.Tensor:
89
+ probs = []
90
+ for start in range(0, images.shape[0], batch):
91
+ rep = phase1(images[start:start + batch].to(device))
92
+ probs.append(rep.routing_probs.float().cpu())
93
+ return torch.cat(probs)
94
+
95
+
96
+ def distribution(probs: torch.Tensor) -> Dict[str, float]:
97
+ argmax = probs.argmax(dim=1)
98
+ return {node: round(float((argmax == i).float().mean()), 3) for i, node in enumerate(NODES)}
99
+
100
+
101
+ def quantiles(values: torch.Tensor) -> Dict[str, float]:
102
+ qs = torch.tensor([0.1, 0.25, 0.5, 0.75, 0.9])
103
+ return {"q%d" % int(q * 100): round(float(v), 4) for q, v in zip(qs, torch.quantile(values, qs))}
104
+
105
+
106
+ def run(argv: Sequence[str] | None = None) -> Dict[str, object]:
107
+ parser = argparse.ArgumentParser(description=__doc__)
108
+ parser.add_argument("--checkpoint", action="append", required=True,
109
+ help="tag=path, repeatable")
110
+ parser.add_argument("--k-random", type=int, default=4)
111
+ parser.add_argument("--pool-root", default="/home/admin_mcn/data/Snow100K/train/all/gt")
112
+ parser.add_argument("--pool-count", type=int, default=512)
113
+ parser.add_argument("--image-size", type=int, default=256)
114
+ parser.add_argument("--output", type=Path, default=Path("outputs/phase1_scale_probe.json"))
115
+ parser.add_argument("--device", default="cuda")
116
+ args = parser.parse_args(argv)
117
+ device = torch.device(args.device)
118
+ size = args.image_size
119
+
120
+ splits = v2.build_data_splits(v2.build_parser().parse_args([]))
121
+ records = list(splits.val)
122
+ print("val records: %d" % len(records), flush=True)
123
+
124
+ # ---- load crops once ------------------------------------------------- #
125
+ per_policy: Dict[str, List[torch.Tensor]] = {"A": [], "B": [], "C": []}
126
+ meta: List[Tuple[str, str, str]] = [] # (domain, dataset, source_id)
127
+ clean_native: Dict[str, List[torch.Tensor]] = defaultdict(list)
128
+ hazy_native: List[torch.Tensor] = []
129
+ for index, record in enumerate(records):
130
+ degraded = v2._open_rgb(record.degraded)
131
+ clean = v2._open_rgb(record.clean)
132
+ per_policy["A"].append(v2._pil_to_tensor(v2._resize_center_crop(degraded, size)))
133
+ per_policy["B"].append(v2._pil_to_tensor(native_centre_crop(degraded, size)))
134
+ crops = native_random_crops(degraded, size, args.k_random, seed=1000 + index)
135
+ per_policy["C"].append(torch.stack([v2._pil_to_tensor(c) for c in crops]))
136
+ meta.append((record.degradation, record.dataset, record.source_id))
137
+ clean_native[record.degradation].append(v2._pil_to_tensor(native_centre_crop(clean, size)))
138
+ if record.degradation == "haze":
139
+ hazy_native.append(per_policy["B"][-1])
140
+ if index % 50 == 0:
141
+ print("loaded %d/%d" % (index, len(records)), flush=True)
142
+ images_a = torch.stack(per_policy["A"])
143
+ images_b = torch.stack(per_policy["B"])
144
+ images_c = torch.stack(per_policy["C"]) # [N, K, 3, H, W]
145
+
146
+ # ---- clean pool + haze proxy ---------------------------------------- #
147
+ pool_files = list_image_files(Path(args.pool_root))
148
+ rng = random.Random(20260903)
149
+ pool_files = rng.sample(pool_files, min(args.pool_count, len(pool_files)))
150
+ pool = torch.stack([
151
+ v2._pil_to_tensor(native_centre_crop(v2._open_rgb(path), size)) for path in pool_files
152
+ ])
153
+ dcp_pool = dark_channel_mean(pool)
154
+ contrast_pool = luma_contrast(pool)
155
+ reference = {
156
+ "snow100k_gt_pool": {"dcp": quantiles(dcp_pool), "contrast": quantiles(contrast_pool)},
157
+ "reside_hazy_val": {"dcp": quantiles(dark_channel_mean(torch.stack(hazy_native)))},
158
+ }
159
+ for domain, crops in clean_native.items():
160
+ stacked = torch.stack(crops)
161
+ reference["%s_clean_gt_val" % domain] = {
162
+ "dcp": quantiles(dark_channel_mean(stacked)),
163
+ "contrast": quantiles(luma_contrast(stacked)),
164
+ }
165
+ thresholds = torch.quantile(dcp_pool, torch.tensor([0.25, 0.5, 0.75]))
166
+ pool_quartile = torch.bucketize(dcp_pool, thresholds)
167
+
168
+ # ---- route through each checkpoint ---------------------------------- #
169
+ results: Dict[str, object] = {"reference_dcp": reference, "checkpoints": {}}
170
+ for spec in args.checkpoint:
171
+ tag, path = spec.split("=", 1)
172
+ sha = v2.sha256_file(Path(path))
173
+ phase1, _ = v4.build_frozen_phase1(Path(path), sha, device)
174
+ probs = {
175
+ "A": route(phase1, images_a, device),
176
+ "B": route(phase1, images_b, device),
177
+ "C": route(phase1, images_c.flatten(0, 1), device).view(len(records), args.k_random, -1).mean(dim=1),
178
+ }
179
+ report: Dict[str, object] = {"sha256": sha[:16], "domains": {}, "sidd_by_iso": {}, "pool": {}}
180
+ for domain, di in DOMAIN_INDEX.items():
181
+ rows = [i for i, m in enumerate(meta) if m[0] == domain]
182
+ entry = {}
183
+ for policy, p in probs.items():
184
+ sub = p[rows]
185
+ entry[policy] = {
186
+ "argmax": distribution(sub),
187
+ "own_prob_mean": round(float(sub[:, di].mean()), 3),
188
+ "free_prob_mean": round(float(sub[:, 4:].sum(dim=1).mean()), 3),
189
+ }
190
+ entry["agreement_A_B"] = round(float((probs["A"][rows].argmax(1) == probs["B"][rows].argmax(1)).float().mean()), 3)
191
+ report["domains"][domain] = entry
192
+ noise_rows = [i for i, m in enumerate(meta) if m[0] == "noise"]
193
+ by_iso: Dict[str, List[int]] = defaultdict(list)
194
+ for i in noise_rows:
195
+ by_iso[sidd_iso(meta[i][2])].append(i)
196
+ for iso, rows in sorted(by_iso.items()):
197
+ report["sidd_by_iso"][iso] = {
198
+ "n": len(rows),
199
+ **{policy: {"noise_prob": round(float(p[rows][:, 1].mean()), 3),
200
+ "argmax": distribution(p[rows])} for policy, p in probs.items()},
201
+ }
202
+ pool_probs = route(phase1, pool, device)
203
+ report["pool"]["all"] = distribution(pool_probs)
204
+ for q in range(4):
205
+ rows = (pool_quartile == q).nonzero(as_tuple=True)[0]
206
+ report["pool"]["dcp_quartile_%d" % (q + 1)] = {
207
+ "n": int(rows.numel()),
208
+ "dcp_mean": round(float(dcp_pool[rows].mean()), 4),
209
+ "argmax": distribution(pool_probs[rows]),
210
+ "haze_prob_mean": round(float(pool_probs[rows][:, 2].mean()), 3),
211
+ }
212
+ results["checkpoints"][tag] = report
213
+
214
+ print("=== %s (%s)" % (tag, sha[:12]))
215
+ for domain, entry in report["domains"].items():
216
+ print(" %-8s A own=%.2f free=%.2f | B own=%.2f free=%.2f | C own=%.2f free=%.2f | agree(A,B)=%.2f" % (
217
+ domain, entry["A"]["own_prob_mean"], entry["A"]["free_prob_mean"],
218
+ entry["B"]["own_prob_mean"], entry["B"]["free_prob_mean"],
219
+ entry["C"]["own_prob_mean"], entry["C"]["free_prob_mean"], entry["agreement_A_B"]))
220
+ print(" A argmax %s" % entry["A"]["argmax"])
221
+ print(" B argmax %s" % entry["B"]["argmax"])
222
+ for iso, entry in report["sidd_by_iso"].items():
223
+ print(" SIDD ISO %s n=%d noise_prob A=%.2f B=%.2f C=%.2f B argmax %s" % (
224
+ iso, entry["n"], entry["A"]["noise_prob"], entry["B"]["noise_prob"], entry["C"]["noise_prob"], entry["B"]["argmax"]))
225
+ print(" pool all: %s" % report["pool"]["all"])
226
+ for q in range(4):
227
+ e = report["pool"]["dcp_quartile_%d" % (q + 1)]
228
+ print(" pool DCP q%d (mean %.3f): haze_prob %.2f argmax %s" % (q + 1, e["dcp_mean"], e["haze_prob_mean"], e["argmax"]))
229
+ del phase1
230
+ torch.cuda.empty_cache()
231
+
232
+ print("reference DCP: %s" % json.dumps(reference, indent=None))
233
+ args.output.parent.mkdir(parents=True, exist_ok=True)
234
+ args.output.write_text(json.dumps(results, indent=2))
235
+ print("saved %s" % args.output)
236
+ return results
237
+
238
+
239
+ if __name__ == "__main__":
240
+ run()
dataset/phase1_noise_20260906/code/probe_pregain.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Print the v10 input pre-gain the model predicts per external group
3
+ (mean / min / max log-gain and gain), using the same Phase-1 crop + whole
4
+ frame inputs the sampler uses. Diagnoses e.g. a gain > 1 on bright hazy
5
+ images (clipping) vs the intended gain on low-light inputs."""
6
+
7
+ import argparse
8
+ import json
9
+ from pathlib import Path
10
+
11
+ import torch
12
+
13
+ import eval_full_frame as ff
14
+ import train_phase2_graph_resshift_v4 as v4
15
+ from eval_v7_external import V7Pipeline
16
+
17
+
18
+ def main() -> None:
19
+ parser = argparse.ArgumentParser(description=__doc__)
20
+ parser.add_argument("--run-dir", type=Path, required=True)
21
+ parser.add_argument("--checkpoint", default="best.pt")
22
+ parser.add_argument("--groups", default="lowlight_lolv2_test,haze_heldout,rain_locked,noise_locked_scene008")
23
+ parser.add_argument("--limit", type=int, default=40)
24
+ parser.add_argument("--output", type=Path, default=None)
25
+ args = parser.parse_args()
26
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
+ pipeline = V7Pipeline(args.run_dir, device, checkpoint=args.checkpoint)
28
+ restorer = v4.unwrap_module(pipeline.model)
29
+ if getattr(restorer, "exposure_pregain", None) is None:
30
+ raise SystemExit("this run has no exposure pre-gain")
31
+ groups = ff.external_groups()
32
+ report = {}
33
+ for name in [g.strip() for g in args.groups.split(",") if g.strip()]:
34
+ dataset = ff.FullFrameDataset(groups[name][: args.limit])
35
+ gains = []
36
+ with torch.no_grad():
37
+ for index in range(len(dataset)):
38
+ item = dataset[index]
39
+ degraded = item["degraded"].unsqueeze(0).to(device)
40
+ full = item["full_degraded"].unsqueeze(0).to(device)
41
+ # centre 256 crop as a Phase-1 tile, like the sampler's tiles
42
+ h, w = degraded.shape[-2:]
43
+ top, left = max((h - 256) // 2, 0), max((w - 256) // 2, 0)
44
+ crop = degraded[..., top:top + 256, left:left + 256]
45
+ rep = pipeline.phase1(crop)
46
+ if getattr(restorer, "ctx_full_proj", None) is not None:
47
+ rep.full_frame = pipeline.phase1(full)
48
+ rep.full_image = full
49
+ log_gain = restorer.exposure_pregain.log_gain(crop, rep)
50
+ gains.append(float(log_gain[0]))
51
+ t = torch.tensor(gains)
52
+ report[name] = {"n": len(gains), "log_gain_mean": float(t.mean()), "log_gain_min": float(t.min()),
53
+ "log_gain_max": float(t.max()), "gain_mean": float(t.exp().mean()),
54
+ "frac_gain_gt_1.05": float((t > 0.05).float().mean())}
55
+ print(name, json.dumps(report[name]), flush=True)
56
+ if args.output:
57
+ args.output.write_text(json.dumps(report, indent=2))
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()
dataset/phase1_noise_20260906/code/probe_scene008_tone.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Is the scene008 (nearly clean, dark textured) failure a global tone shift?
3
+
4
+ For every locked scene008 record: mean luma of input / restored / GT, per-channel
5
+ mean shift restored-GT, PSNR of the raw output, and PSNR after a single global
6
+ affine correction (gain+bias fitted on luma against GT). If the corrected PSNR
7
+ recovers most of the gap, the model is applying an exposure lift, not
8
+ destroying texture. Also reports the val degraded baselines per domain so
9
+ in-distribution gains can be read against the input quality.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ from pathlib import Path
17
+
18
+ import torch
19
+
20
+ import eval_pipeline_external as ext
21
+ import train_graph_encoder_v2 as p1
22
+ import train_phase2_graph_resshift_v4 as v4
23
+ from eval_v7_external import V7Pipeline
24
+ from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest
25
+ from visualize_v7_uformer import _load_run_args
26
+
27
+ LUMA = (0.299, 0.587, 0.114)
28
+
29
+
30
+ def luma(x: torch.Tensor) -> torch.Tensor:
31
+ return sum(x[:, c] * w for c, w in enumerate(LUMA))
32
+
33
+
34
+ def affine_match(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
35
+ """Per-image global gain+bias on all channels fitted by least squares on luma."""
36
+ out = []
37
+ for p, t in zip(pred, target):
38
+ lp, lt = luma(p[None])[0].flatten(), luma(t[None])[0].flatten()
39
+ var = lp.var()
40
+ gain = ((lp - lp.mean()) * (lt - lt.mean())).mean() / var if var > 1e-8 else 1.0
41
+ bias = lt.mean() - gain * lp.mean()
42
+ out.append((p * gain + bias).clamp(0, 1))
43
+ return torch.stack(out)
44
+
45
+
46
+ def scene008(pipe: V7Pipeline, device, dose) -> dict:
47
+ p1_args = p1.build_parser().parse_args([])
48
+ splits = p1.build_data_splits(p1_args)
49
+ records = [r for r in splits.locked_test if r.degradation == "noise"]
50
+ dataset = ext.PairCropDataset(records)
51
+ rows = []
52
+ pipe.dose = dose
53
+ for start in range(0, len(records), 8):
54
+ items = [dataset[i] for i in range(start, min(start + 8, len(records)))]
55
+ degraded = torch.stack([it["degraded"] for it in items]).to(device)
56
+ clean = torch.stack([it["clean"] for it in items]).to(device)
57
+ ids = [it["record_id"] for it in items]
58
+ # Whole-frame view must reach the pipeline, otherwise a --global-context
59
+ # model silently runs without its full-frame branch (not deployment).
60
+ full = (torch.stack([it["full_degraded"] for it in items]).to(device)
61
+ if "full_degraded" in items[0] else None)
62
+ with torch.no_grad():
63
+ restored = pipe.restore(
64
+ degraded, record_ids=ids, full_degraded=full
65
+ )["restored"].float().clamp(0, 1)
66
+ matched = affine_match(restored, clean)
67
+ for i, rid in enumerate(ids):
68
+ rows.append({
69
+ "record_id": rid,
70
+ "luma_input": float(luma(degraded[i:i+1]).mean()),
71
+ "luma_restored": float(luma(restored[i:i+1]).mean()),
72
+ "luma_gt": float(luma(clean[i:i+1]).mean()),
73
+ "rgb_shift": [float((restored[i, c] - clean[i, c]).mean()) for c in range(3)],
74
+ "psnr_input": float(v4.rgb_psnr_per_image(degraded[i:i+1], clean[i:i+1])[0]),
75
+ "psnr_restored": float(v4.rgb_psnr_per_image(restored[i:i+1], clean[i:i+1])[0]),
76
+ "psnr_affine_matched": float(v4.rgb_psnr_per_image(matched[i:i+1], clean[i:i+1])[0]),
77
+ "ssim_restored": float(v4.rgb_ssim_per_image(restored[i:i+1], clean[i:i+1])[0]),
78
+ "ssim_affine_matched": float(v4.rgb_ssim_per_image(matched[i:i+1], clean[i:i+1])[0]),
79
+ })
80
+ mean = lambda k: sum(r[k] for r in rows) / len(rows)
81
+ return {
82
+ "n": len(rows), "dose": dose, "rows": rows,
83
+ "mean": {k: mean(k) for k in ("luma_input", "luma_restored", "luma_gt", "psnr_input",
84
+ "psnr_restored", "psnr_affine_matched",
85
+ "ssim_restored", "ssim_affine_matched")},
86
+ }
87
+
88
+
89
+ def val_baselines(run_args, device) -> dict:
90
+ splits = load_train_val_manifest(run_args.manifest)
91
+ dataset = Phase2PairDataset(splits.val, crop_size=run_args.crop_size, training=False)
92
+ acc = {}
93
+ for index, record in enumerate(splits.val):
94
+ item = dataset[index]
95
+ d, c = item["degraded"][None].to(device), item["clean"][None].to(device)
96
+ entry = acc.setdefault(record.degradation, {"psnr": [], "ssim": []})
97
+ entry["psnr"].append(float(v4.rgb_psnr_per_image(d, c)[0]))
98
+ entry["ssim"].append(float(v4.rgb_ssim_per_image(d, c)[0]))
99
+ return {k: {"n": len(v["psnr"]), "psnr": sum(v["psnr"]) / len(v["psnr"]),
100
+ "ssim": sum(v["ssim"]) / len(v["ssim"])} for k, v in acc.items()}
101
+
102
+
103
+ def main() -> None:
104
+ parser = argparse.ArgumentParser(description=__doc__)
105
+ parser.add_argument("--run-dir", type=Path, required=True)
106
+ parser.add_argument("--output", type=Path, required=True)
107
+ parser.add_argument("--skip-val-baseline", action="store_true")
108
+ args = parser.parse_args()
109
+ device = torch.device("cuda")
110
+ pipe = V7Pipeline(args.run_dir, device)
111
+ report = {
112
+ "run_dir": str(args.run_dir),
113
+ "scene008_dose1": scene008(pipe, device, None),
114
+ "scene008_dose0": scene008(pipe, device, 0.0),
115
+ "val_degraded_baseline": (
116
+ None if args.skip_val_baseline
117
+ else val_baselines(_load_run_args(args.run_dir), device)
118
+ ),
119
+ }
120
+ args.output.write_text(json.dumps(report, indent=2))
121
+ for key in ("scene008_dose1", "scene008_dose0"):
122
+ m = report[key]["mean"]
123
+ print(key, " ".join("%s=%.3f" % (k, v) for k, v in m.items()))
124
+ print("val_degraded_baseline", json.dumps(report["val_degraded_baseline"]))
125
+ print("WROTE", args.output)
126
+
127
+
128
+ if __name__ == "__main__":
129
+ main()
dataset/phase1_noise_20260906/code/probe_v11_memory.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Peak-memory / throughput probe for a v7-family training configuration.
3
+
4
+ Builds the restorer exactly as the trainer would (same parser + builder),
5
+ runs ``--steps`` training micro-steps on synthetic batches at the given crop
6
+ and batch size with AMP, and prints peak allocated memory and step time so a
7
+ launcher can pick the batch size for each progressive-resolution stage
8
+ (v11) before committing both GPUs. Phase-1 is replaced by a synthetic
9
+ representation of the right shapes (its footprint is small and frozen).
10
+
11
+ Usage: probe_v11_memory.py --crop 384 --batch 4 [--grad-checkpoint] -- <trainer args>
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import json
18
+ import sys
19
+ import time
20
+ from types import SimpleNamespace
21
+
22
+ import torch
23
+
24
+ import train_phase2_unified_v7 as v7
25
+
26
+
27
+ def synthetic_representation(batch: int, crop: int, device) -> SimpleNamespace:
28
+ latent = crop // 4
29
+ rep = SimpleNamespace(
30
+ content_latent=torch.randn(batch, 128, latent, latent, device=device),
31
+ node_tokens=torch.randn(batch, 6, 256, device=device),
32
+ routing_probs=torch.softmax(torch.randn(batch, 6, device=device), dim=-1),
33
+ severity_coords=torch.rand(batch, 4, device=device),
34
+ spatial_maps=torch.rand(batch, 4, 16, 16, device=device),
35
+ unknown_residual=torch.randn(batch, 256, device=device),
36
+ global_condition=torch.randn(batch, 256, device=device),
37
+ photometric_state=torch.randn(batch, v7.PHOTOMETRIC_STATE_DIM, device=device),
38
+ )
39
+ full = SimpleNamespace(**{k: (v.clone() if isinstance(v, torch.Tensor) else v) for k, v in vars(rep).items()})
40
+ rep.full_frame = full
41
+ rep.full_image = torch.rand(batch, 3, 256, 256, device=device)
42
+ return rep
43
+
44
+
45
+ def main(argv=None) -> None:
46
+ argv = list(sys.argv[1:] if argv is None else argv)
47
+ if "--" not in argv:
48
+ raise SystemExit("usage: probe_v11_memory.py --crop N --batch N [--steps N] -- <trainer args>")
49
+ split = argv.index("--")
50
+ parser = argparse.ArgumentParser(description=__doc__)
51
+ parser.add_argument("--crop", type=int, required=True)
52
+ parser.add_argument("--batch", type=int, required=True)
53
+ parser.add_argument("--steps", type=int, default=3)
54
+ parser.add_argument("--output", default=None)
55
+ probe = parser.parse_args(argv[:split])
56
+ args = v7.build_parser().parse_args(argv[split + 1:] + ["--allow-scratch"])
57
+ device = torch.device("cuda")
58
+ model = v7._build_v7_restorer(args, device)
59
+ model.train()
60
+ optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5)
61
+ scaler = torch.cuda.amp.GradScaler()
62
+ torch.cuda.reset_peak_memory_stats(device)
63
+ timings = []
64
+ for step in range(int(probe.steps)):
65
+ clean = torch.rand(probe.batch, 3, probe.crop, probe.crop, device=device)
66
+ degraded = torch.rand(probe.batch, 3, probe.crop, probe.crop, device=device)
67
+ rep = synthetic_representation(probe.batch, probe.crop, device)
68
+ timesteps = torch.full((probe.batch,), 2, device=device, dtype=torch.long)
69
+ torch.cuda.synchronize()
70
+ start = time.time()
71
+ with torch.cuda.amp.autocast(enabled=True):
72
+ result = model.training_loss(clean, degraded, rep, timesteps)
73
+ scaler.scale(result.loss).backward()
74
+ scaler.unscale_(optimizer)
75
+ torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
76
+ scaler.step(optimizer)
77
+ scaler.update()
78
+ optimizer.zero_grad(set_to_none=True)
79
+ torch.cuda.synchronize()
80
+ timings.append(time.time() - start)
81
+ peak = torch.cuda.max_memory_allocated(device) / 2 ** 30
82
+ params = sum(p.numel() for p in model.parameters()) / 1e6
83
+ report = {
84
+ "crop": probe.crop, "batch": probe.batch, "params_M": round(params, 2),
85
+ "peak_gib": round(peak, 2), "step_s": round(sum(timings[1:]) / max(len(timings) - 1, 1), 3),
86
+ "grad_checkpoint": bool(getattr(args, "grad_checkpoint", False)),
87
+ "blocks_per_stage": list(v7.blocks_per_stage(args)),
88
+ }
89
+ print("PROBE " + json.dumps(report), flush=True)
90
+ if probe.output:
91
+ with open(probe.output, "w") as handle:
92
+ json.dump(report, handle)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
dataset/phase1_noise_20260906/code/quick_eval_every.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Quick external check of a running stage every N steps (user request):
3
+ # when the train log passes each target step, snapshot last.pt and run the
4
+ # whole-image full-frame evaluator on LOLv2 / haze / Test1200 (no LPIPS, no
5
+ # 12 MP scene008) on the given GPU, sharing it with training.
6
+ # Usage: quick_eval_every.sh <run_name> <gpu> <step1,step2,...>
7
+ set -u
8
+ cd /home/admin_mcn/scdc_ban
9
+ PY=/home/admin_mcn/anaconda3/bin/python
10
+ RUN=$1; GPU=$2; TARGETS=${3//,/ }
11
+ RUN_DIR=outputs/phase2_v7/$RUN
12
+ LOG=outputs/phase2_v7/${RUN}_train.log
13
+ log() { echo "[quick $(date +%H:%M:%S)] $*"; }
14
+ current_step() { grep "\"event\": \"train\"" "$LOG" 2>/dev/null | tail -n 1 | grep -o "\"step\": [0-9]*" | grep -o "[0-9]*"; }
15
+ for target in $TARGETS; do
16
+ while true; do
17
+ s=$(current_step); s=${s:-0}
18
+ if [ "$s" -ge "$target" ]; then break; fi
19
+ if ! pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN" >/dev/null && ! pgrep -f "[r]un_uformer_v11.sh" >/dev/null; then log "trainer gone before $target; exiting"; exit 0; fi
20
+ sleep 120
21
+ done
22
+ sleep 60 # let last.pt (written every 250 steps) settle
23
+ snap=$RUN_DIR/snapshot_${target}.pt
24
+ cp "$RUN_DIR/last.pt" "$snap"
25
+ step=$($PY -c "import torch; print(torch.load('$snap', map_location='cpu')['step'])")
26
+ log "snapshot for target $target = last.pt at step $step"
27
+ CUDA_VISIBLE_DEVICES=$GPU $PY -u eval_full_frame.py --run-dir "$RUN_DIR" --checkpoint "snapshot_${target}.pt" \
28
+ --groups lowlight_lolv2_test,haze_heldout,rain_locked --whole-max-pixels 1200000 --tta 1 --no-lpips \
29
+ --output outputs/quick_${RUN}_${target}.json >> outputs/phase2_v7/quick_eval_${RUN}.log 2>&1 \
30
+ && log "wrote outputs/quick_${RUN}_${target}.json" || log "eval FAILED at $target"
31
+ done
32
+ log "done"
dataset/phase1_noise_20260906/code/run_ablation_C_only.sh ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Photometric ablation on the MI325X host (user request 2026-09-05):
3
+ # A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5
4
+ # B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run)
5
+ # C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6
6
+ # All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then
7
+ # whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt.
8
+ set -u
9
+ cd /home/vunguyen/SCDC
10
+ PY=/home/vunguyen/miniforge3/envs/mavt/bin/python
11
+ export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data
12
+ export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1
13
+ export SCDC_PATH_RELOCATION=/home/vunguyen/data_bundle/extract/data/=/home/admin_mcn/data/,/home/vunguyen/data_bundle/extract/kagglehub/=/home/admin_mcn/.cache/kagglehub/
14
+ export OMP_NUM_THREADS=8
15
+ export PYTORCH_ALLOC_CONF=expandable_segments:True
16
+ # Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A).
17
+ free_gpus() {
18
+ rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \
19
+ | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' '
20
+ }
21
+ PHASE1=outputs/phase1_v5f/graph_encoder_best.pt
22
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
23
+ WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt
24
+ WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1)
25
+ POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt
26
+ STEPS=${STEPS:-5000}
27
+ EVLOG=outputs/phase2_v7/ablation_photometric_evals.log
28
+ WHOLE="--whole-max-pixels 1200000"
29
+ log() { echo "[abl $(date +%H:%M:%S)] $*"; }
30
+
31
+ BASE="--backbone uformer --timesteps 2 \
32
+ --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \
33
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
34
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
35
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
36
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
37
+ --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \
38
+ --kappa 0.11607981286942959 \
39
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
40
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
41
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
42
+ --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \
43
+ --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \
44
+ --extra-clean-root $POOLS --extra-clean-prob 0.6 \
45
+ --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \
46
+ --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \
47
+ --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \
48
+ --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \
49
+ --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \
50
+ --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02"
51
+ PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02"
52
+ COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05"
53
+
54
+ launch() { # name gpu extra
55
+ local name=$1 gpu=$2 extra=$3
56
+ # shellcheck disable=SC2086
57
+ CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \
58
+ >> outputs/phase2_v7/${name}_train.log 2>&1 &
59
+ log "launched $name on GPU$gpu pid $!"
60
+ }
61
+ wait_done() { # name
62
+ local name=$1 run_dir=outputs/phase2_v7/$1
63
+ while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done
64
+ if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi
65
+ }
66
+ run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; }
67
+
68
+ # C_colour only, on a given GPU (GPU 6 is contested by another tenant on this host)
69
+ GC=${GC:-5}
70
+ rm -rf outputs/phase2_v7/abl_C_colour
71
+ launch abl_C_colour "$GC" "$PHOTO $COLOUR"
72
+ wait_done abl_C_colour
73
+ log "C_colour finished"
dataset/phase1_noise_20260906/code/run_ablation_C_then_eval.sh ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Photometric ablation on the MI325X host (user request 2026-09-05):
3
+ # A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5
4
+ # B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run)
5
+ # C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6
6
+ # All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then
7
+ # whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt.
8
+ set -u
9
+ cd /home/vunguyen/SCDC
10
+ PY=/home/vunguyen/miniforge3/envs/mavt/bin/python
11
+ export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data
12
+ export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1
13
+ export SCDC_PATH_RELOCATION=/home/vunguyen/data_bundle/extract/data/=/home/admin_mcn/data/,/home/vunguyen/data_bundle/extract/kagglehub/=/home/admin_mcn/.cache/kagglehub/
14
+ export OMP_NUM_THREADS=8
15
+ export PYTORCH_ALLOC_CONF=expandable_segments:True
16
+ # Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A).
17
+ free_gpus() {
18
+ rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \
19
+ | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' '
20
+ }
21
+ PHASE1=outputs/phase1_v5f/graph_encoder_best.pt
22
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
23
+ WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt
24
+ WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1)
25
+ POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt
26
+ STEPS=${STEPS:-5000}
27
+ EVLOG=outputs/phase2_v7/ablation_photometric_evals.log
28
+ WHOLE="--whole-max-pixels 1200000"
29
+ log() { echo "[abl $(date +%H:%M:%S)] $*"; }
30
+
31
+ BASE="--backbone uformer --timesteps 2 \
32
+ --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \
33
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
34
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
35
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
36
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
37
+ --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \
38
+ --kappa 0.11607981286942959 \
39
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
40
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
41
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
42
+ --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \
43
+ --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \
44
+ --extra-clean-root $POOLS --extra-clean-prob 0.6 \
45
+ --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \
46
+ --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \
47
+ --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \
48
+ --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \
49
+ --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \
50
+ --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02"
51
+ PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02"
52
+ COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05"
53
+
54
+ launch() { # name gpu extra
55
+ local name=$1 gpu=$2 extra=$3
56
+ # shellcheck disable=SC2086
57
+ CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \
58
+ >> outputs/phase2_v7/${name}_train.log 2>&1 &
59
+ log "launched $name on GPU$gpu pid $!"
60
+ }
61
+ wait_done() { # name
62
+ local name=$1 run_dir=outputs/phase2_v7/$1
63
+ while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done
64
+ if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi
65
+ }
66
+ run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; }
67
+
68
+ # C_colour (relaunch after an external kill) + its evals + the comparison table.
69
+ GC=${GC:-5}
70
+ while pgrep -f "[e]val_full_frame.py" >/dev/null; do sleep 30; done # let the A/B evals finish first
71
+ rm -rf outputs/phase2_v7/abl_C_colour
72
+ launch abl_C_colour "$GC" "$PHOTO $COLOUR"
73
+ wait_done abl_C_colour
74
+ run_eval $GC eval_full_frame.py --run-dir outputs/phase2_v7/abl_C_colour --checkpoint last.pt --output outputs/abl_C_colour_fullframe_whole_v1.json --tta 1 $WHOLE
75
+ run_eval $GC eval_full_frame.py --run-dir outputs/phase2_v7/abl_C_colour --checkpoint last.pt --output outputs/abl_C_colour_nodose_fullframe_whole_v1.json --tta 1 $WHOLE --colour-dose 0
76
+ $PY - <<'PYEOF'
77
+ import json, os
78
+ rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"),
79
+ ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")]
80
+ print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008")
81
+ for name, p in rows:
82
+ if not os.path.exists(p): print(name, "missing"); continue
83
+ r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f]
84
+ print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % (
85
+ name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"),
86
+ g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips")))
87
+ PYEOF
88
+ log "ablation finished"
dataset/phase1_noise_20260906/code/run_ablation_photometric.sh ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Photometric ablation on the MI325X host (user request 2026-09-05):
3
+ # A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5
4
+ # B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run)
5
+ # C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6
6
+ # All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then
7
+ # whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt.
8
+ set -u
9
+ cd /home/vunguyen/SCDC
10
+ PY=/home/vunguyen/miniforge3/envs/mavt/bin/python
11
+ export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data
12
+ export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1
13
+ export SCDC_PATH_RELOCATION=/home/vunguyen/data_bundle/extract/data/=/home/admin_mcn/data/,/home/vunguyen/data_bundle/extract/kagglehub/=/home/admin_mcn/.cache/kagglehub/
14
+ export OMP_NUM_THREADS=8
15
+ export PYTORCH_ALLOC_CONF=expandable_segments:True
16
+ # Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A).
17
+ free_gpus() {
18
+ rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \
19
+ | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' '
20
+ }
21
+ PHASE1=outputs/phase1_v5f/graph_encoder_best.pt
22
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
23
+ WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt
24
+ WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1)
25
+ POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt
26
+ STEPS=${STEPS:-5000}
27
+ EVLOG=outputs/phase2_v7/ablation_photometric_evals.log
28
+ WHOLE="--whole-max-pixels 1200000"
29
+ log() { echo "[abl $(date +%H:%M:%S)] $*"; }
30
+
31
+ BASE="--backbone uformer --timesteps 2 \
32
+ --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \
33
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
34
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
35
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
36
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
37
+ --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \
38
+ --kappa 0.11607981286942959 \
39
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
40
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
41
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
42
+ --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \
43
+ --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \
44
+ --extra-clean-root $POOLS --extra-clean-prob 0.6 \
45
+ --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \
46
+ --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \
47
+ --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \
48
+ --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \
49
+ --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \
50
+ --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02"
51
+ PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02"
52
+ COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05"
53
+
54
+ launch() { # name gpu extra
55
+ local name=$1 gpu=$2 extra=$3
56
+ # shellcheck disable=SC2086
57
+ CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \
58
+ >> outputs/phase2_v7/${name}_train.log 2>&1 &
59
+ log "launched $name on GPU$gpu pid $!"
60
+ }
61
+ wait_done() { # name
62
+ local name=$1 run_dir=outputs/phase2_v7/$1
63
+ while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done
64
+ if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi
65
+ }
66
+ run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; }
67
+
68
+ read -r GA GC _ <<< "$(free_gpus)"
69
+ [ -n "${GA:-}" ] && [ -n "${GC:-}" ] || { log "need two free GPUs, found: '$(free_gpus)'"; exit 1; }
70
+ log "using GPUs $GA (A_nophoto) and $GC (C_colour)"
71
+ launch abl_A_nophoto "$GA" ""
72
+ launch abl_C_colour "$GC" "$PHOTO $COLOUR"
73
+ wait_done abl_A_nophoto; wait_done abl_C_colour
74
+ # B = the stage-A run at the same step count
75
+ B_CKPT=outputs/phase2_v7/uformer_v11a_256_x/milestone_00005000.pt
76
+ [ -f $B_CKPT ] || log "WARNING: $B_CKPT missing"
77
+ ( run_eval $GA eval_full_frame.py --run-dir outputs/phase2_v7/abl_A_nophoto --checkpoint last.pt --output outputs/abl_A_nophoto_fullframe_whole_v1.json --tta 1 $WHOLE
78
+ run_eval $GA eval_full_frame.py --run-dir outputs/phase2_v7/uformer_v11a_256_x --checkpoint milestone_00005000.pt --output outputs/abl_B_photo_fullframe_whole_v1.json --tta 1 $WHOLE ) &
79
+ ( run_eval $GC eval_full_frame.py --run-dir outputs/phase2_v7/abl_C_colour --checkpoint last.pt --output outputs/abl_C_colour_fullframe_whole_v1.json --tta 1 $WHOLE
80
+ run_eval $GC eval_full_frame.py --run-dir outputs/phase2_v7/abl_C_colour --checkpoint last.pt --output outputs/abl_C_colour_nodose_fullframe_whole_v1.json --tta 1 $WHOLE --colour-dose 0 ) &
81
+ wait
82
+ $PY - <<'PYEOF'
83
+ import json, os
84
+ rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"),
85
+ ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")]
86
+ print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008")
87
+ for name, p in rows:
88
+ if not os.path.exists(p): print(name, "missing"); continue
89
+ r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f]
90
+ print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % (
91
+ name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"),
92
+ g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips")))
93
+ PYEOF
94
+ log "ablation finished"
dataset/phase1_noise_20260906/code/run_ablation_seq.sh ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Photometric ablation on the MI325X host (user request 2026-09-05):
3
+ # A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5
4
+ # B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run)
5
+ # C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6
6
+ # All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then
7
+ # whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt.
8
+ set -u
9
+ cd /home/vunguyen/SCDC
10
+ PY=/home/vunguyen/miniforge3/envs/mavt/bin/python
11
+ export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data
12
+ export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1
13
+ export SCDC_PATH_RELOCATION=/home/vunguyen/data_bundle/extract/data/=/home/admin_mcn/data/,/home/vunguyen/data_bundle/extract/kagglehub/=/home/admin_mcn/.cache/kagglehub/
14
+ export OMP_NUM_THREADS=8
15
+ export PYTORCH_ALLOC_CONF=expandable_segments:True
16
+ # Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A).
17
+ free_gpus() {
18
+ rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \
19
+ | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' '
20
+ }
21
+ PHASE1=outputs/phase1_v5f/graph_encoder_best.pt
22
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
23
+ WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt
24
+ WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1)
25
+ POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt
26
+ STEPS=${STEPS:-5000}
27
+ EVLOG=outputs/phase2_v7/ablation_photometric_evals.log
28
+ WHOLE="--whole-max-pixels 1200000"
29
+ log() { echo "[abl $(date +%H:%M:%S)] $*"; }
30
+
31
+ BASE="--backbone uformer --timesteps 2 \
32
+ --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \
33
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
34
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
35
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
36
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
37
+ --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \
38
+ --kappa 0.11607981286942959 \
39
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
40
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
41
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
42
+ --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \
43
+ --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \
44
+ --extra-clean-root $POOLS --extra-clean-prob 0.6 \
45
+ --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \
46
+ --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \
47
+ --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \
48
+ --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \
49
+ --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \
50
+ --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02"
51
+ PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02"
52
+ COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05"
53
+
54
+ launch() { # name gpu extra
55
+ local name=$1 gpu=$2 extra=$3
56
+ # shellcheck disable=SC2086
57
+ CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \
58
+ >> outputs/phase2_v7/${name}_train.log 2>&1 &
59
+ log "launched $name on GPU$gpu pid $!"
60
+ }
61
+ wait_done() { # name
62
+ local name=$1 run_dir=outputs/phase2_v7/$1
63
+ while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done
64
+ if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi
65
+ }
66
+ run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; }
67
+
68
+ # Sequential variant for a contested host: A (already running or launched) then C on ONE device.
69
+ GA=${GA:-5}; GC=${GC:-5}
70
+ running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir outputs/phase2_v7/$1" >/dev/null; }
71
+ if ! running abl_A_nophoto && ! grep -q "\"step\": $STEPS" outputs/phase2_v7/abl_A_nophoto/metrics.jsonl 2>/dev/null; then
72
+ rm -rf outputs/phase2_v7/abl_A_nophoto; launch abl_A_nophoto "$GA" ""
73
+ fi
74
+ wait_done abl_A_nophoto
75
+ rm -rf outputs/phase2_v7/abl_C_colour
76
+ launch abl_C_colour "$GC" "$PHOTO $COLOUR"
77
+ wait_done abl_C_colour
78
+ B_CKPT=outputs/phase2_v7/uformer_v11a_256_x/milestone_00005000.pt
79
+ [ -f $B_CKPT ] || log "WARNING: $B_CKPT missing"
80
+ run_eval $GA eval_full_frame.py --run-dir outputs/phase2_v7/abl_A_nophoto --checkpoint last.pt --output outputs/abl_A_nophoto_fullframe_whole_v1.json --tta 1 $WHOLE
81
+ run_eval $GA eval_full_frame.py --run-dir outputs/phase2_v7/uformer_v11a_256_x --checkpoint milestone_00005000.pt --output outputs/abl_B_photo_fullframe_whole_v1.json --tta 1 $WHOLE
82
+ run_eval $GC eval_full_frame.py --run-dir outputs/phase2_v7/abl_C_colour --checkpoint last.pt --output outputs/abl_C_colour_fullframe_whole_v1.json --tta 1 $WHOLE
83
+ run_eval $GC eval_full_frame.py --run-dir outputs/phase2_v7/abl_C_colour --checkpoint last.pt --output outputs/abl_C_colour_nodose_fullframe_whole_v1.json --tta 1 $WHOLE --colour-dose 0
84
+ $PY - <<'PYEOF'
85
+ import json, os
86
+ rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"),
87
+ ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")]
88
+ print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008")
89
+ for name, p in rows:
90
+ if not os.path.exists(p): print(name, "missing"); continue
91
+ r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f]
92
+ print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % (
93
+ name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"),
94
+ g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips")))
95
+ PYEOF
96
+ log "ablation finished"
dataset/phase1_noise_20260906/code/run_phase1_v5c.sh ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Phase-1 v5c pair (2026-09-03): the v5b recipe under the NATIVE crop policy
3
+ # (Phase-2 parity; SIDD seen at native resolution instead of ~12x downsampled).
4
+ # GPU0 phase1_v5c native + SupCon on known+paired-clean only (embed-members known_clean)
5
+ # GPU1 phase1_v5c_ab native + v5b SupCon membership (all) -> isolates the crop policy
6
+ # Both share one native SIDD cache; the second run starts only after the first
7
+ # has finished prebuilding it (severity_calibration.json appears after prebuild).
8
+ # Usage: bash run_phase1_v5c.sh (launch both)
9
+ # ONLY=v5c bash run_phase1_v5c.sh (launch one: v5c | v5c_ab)
10
+ set -u
11
+ cd /home/admin_mcn/scdc_ban
12
+ PY=/home/admin_mcn/anaconda3/bin/python
13
+ CACHE=outputs/phase1_cache/sidd_native_256
14
+ DATA=/home/admin_mcn/data
15
+ COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \
16
+ --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \
17
+ --workers 8 --no-amp --seed 42 \
18
+ --photometric --photometric-dim 128 --photometric-weight 0.5 \
19
+ --embed-weight 0.25 --embed-temperature 0.1 \
20
+ --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \
21
+ --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \
22
+ --reside-limit 5000 --reside-val-count 100 --run-final-test \
23
+ --crop-policy native --sidd-native-crops 32 --cache-root $CACHE"
24
+
25
+ launch() { # $1 = run name, $2 = gpu, $3 = embed members
26
+ local name=$1 gpu=$2 members=$3
27
+ mkdir -p outputs/$name
28
+ CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON \
29
+ --embed-members $members --output-dir outputs/$name \
30
+ > outputs/${name}_train.log 2>&1 < /dev/null &
31
+ echo "[v5c] launched $name on GPU$gpu (embed-members=$members) pid $!"
32
+ }
33
+
34
+ wait_for_cache() { # wait until the first run wrote its calibration (cache prebuilt)
35
+ local name=$1
36
+ for _ in $(seq 1 240); do
37
+ if [ -f outputs/$name/severity_calibration.json ]; then return 0; fi
38
+ if grep -q Traceback outputs/${name}_train.log 2>/dev/null; then echo "[v5c] $name crashed before cache"; return 1; fi
39
+ sleep 15
40
+ done
41
+ echo "[v5c] timed out waiting for $name cache"; return 1
42
+ }
43
+
44
+ ONLY=${ONLY:-both}
45
+ case "$ONLY" in
46
+ v5c) launch phase1_v5c 0 known_clean ;;
47
+ v5c_ab) launch phase1_v5c_ab 1 all ;;
48
+ both)
49
+ launch phase1_v5c 0 known_clean
50
+ wait_for_cache phase1_v5c && launch phase1_v5c_ab 1 all
51
+ ;;
52
+ *) echo "ONLY must be v5c | v5c_ab | both"; exit 2 ;;
53
+ esac
dataset/phase1_noise_20260906/code/run_phase1_v5d.sh ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Phase-1 v5d pair (2026-09-03): v5c_ab recipe (native crops, v5b losses,
3
+ # SupCon members = all) + weight EMA (0.999) for evaluation/selection and the
4
+ # balanced selection key (0.5*F1 + 0.5*mean null terms), two seeds.
5
+ # GPU0 phase1_v5d seed 42
6
+ # GPU1 phase1_v5d_s43 seed 43
7
+ # Shares the native SIDD cache built by v5c; severity calibration is copied
8
+ # from phase1_v5c (same records, same policy -> same fingerprint).
9
+ # Usage: bash run_phase1_v5d.sh (both)
10
+ # ONLY=v5d|v5d_s43 bash run_phase1_v5d.sh
11
+ set -u
12
+ cd /home/admin_mcn/scdc_ban
13
+ PY=/home/admin_mcn/anaconda3/bin/python
14
+ CACHE=outputs/phase1_cache/sidd_native_256
15
+ DATA=/home/admin_mcn/data
16
+ COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \
17
+ --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \
18
+ --workers 8 --no-amp \
19
+ --photometric --photometric-dim 128 --photometric-weight 0.5 \
20
+ --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \
21
+ --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \
22
+ --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \
23
+ --reside-limit 5000 --reside-val-count 100 --run-final-test \
24
+ --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \
25
+ --ema-decay 0.999 --selection balanced"
26
+
27
+ launch() { # $1 = run name, $2 = gpu, $3 = seed
28
+ local name=$1 gpu=$2 seed=$3
29
+ mkdir -p outputs/$name
30
+ [ -f outputs/$name/severity_calibration.json ] || cp outputs/phase1_v5c/severity_calibration.json outputs/$name/ 2>/dev/null
31
+ CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON \
32
+ --seed $seed --output-dir outputs/$name \
33
+ > outputs/${name}_train.log 2>&1 < /dev/null &
34
+ echo "[v5d] launched $name on GPU$gpu (seed $seed) pid $!"
35
+ }
36
+
37
+ ONLY=${ONLY:-both}
38
+ case "$ONLY" in
39
+ v5d) launch phase1_v5d 0 42 ;;
40
+ v5d_s43) launch phase1_v5d_s43 1 43 ;;
41
+ both) launch phase1_v5d 0 42; sleep 20; launch phase1_v5d_s43 1 43 ;;
42
+ *) echo "ONLY must be v5d | v5d_s43 | both"; exit 2 ;;
43
+ esac
dataset/phase1_noise_20260906/code/run_phase1_v5e.sh ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Phase-1 v5e pair (2026-09-04): v5c_ab recipe (native crops, v5b losses,
3
+ # SupCon all, raw-weight eval, F1 selection) + residual-aware training crops
4
+ # and a crop-level severity floor.
5
+ # GPU0 phase1_v5e --crop-select residual --crop-candidates 4 --severity-floor 0.05
6
+ # GPU1 phase1_v5e_ab --crop-select residual --crop-candidates 4 (no floor -> isolates the floor)
7
+ # Each launch can wait for a previous run's "Training complete" (WAIT0 / WAIT1 =
8
+ # path of that run's train log) so it starts as soon as the GPU frees up.
9
+ # Usage: WAIT0=outputs/phase1_v5d_train.log WAIT1=outputs/phase1_v5d_s43_train.log bash run_phase1_v5e.sh
10
+ set -u
11
+ cd /home/admin_mcn/scdc_ban
12
+ PY=/home/admin_mcn/anaconda3/bin/python
13
+ CACHE=outputs/phase1_cache/sidd_native_256
14
+ DATA=/home/admin_mcn/data
15
+ COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \
16
+ --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \
17
+ --workers 8 --no-amp --seed 42 \
18
+ --photometric --photometric-dim 128 --photometric-weight 0.5 \
19
+ --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \
20
+ --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \
21
+ --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \
22
+ --reside-limit 5000 --reside-val-count 100 --run-final-test \
23
+ --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \
24
+ --crop-select residual --crop-candidates 4"
25
+
26
+ wait_log() { # $1 = train log to wait for ("" = no wait)
27
+ [ -z "$1" ] && return 0
28
+ while ! grep -q "Training complete" "$1" 2>/dev/null; do
29
+ if grep -q Traceback "$1" 2>/dev/null && ! pgrep -f "[t]rain_graph_encoder_v2.py.*$(basename ${1%_train.log})" >/dev/null; then
30
+ echo "[v5e] $1 crashed; launching anyway"; return 0
31
+ fi
32
+ sleep 120
33
+ done
34
+ sleep 30
35
+ }
36
+
37
+ launch() { # $1 = run name, $2 = gpu, $3 = extra flags
38
+ local name=$1 gpu=$2 extra=$3
39
+ mkdir -p outputs/$name
40
+ [ -f outputs/$name/severity_calibration.json ] || cp outputs/phase1_v5c/severity_calibration.json outputs/$name/ 2>/dev/null
41
+ CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON $extra \
42
+ --output-dir outputs/$name > outputs/${name}_train.log 2>&1 < /dev/null &
43
+ echo "[v5e] $(date +%H:%M) launched $name on GPU$gpu ($extra) pid $!"
44
+ }
45
+
46
+ ONLY=${ONLY:-both}
47
+ WAIT0=${WAIT0:-}; WAIT1=${WAIT1:-}
48
+ case "$ONLY" in
49
+ v5e) wait_log "$WAIT0"; launch phase1_v5e 0 "--severity-floor 0.05" ;;
50
+ v5e_ab) wait_log "$WAIT1"; launch phase1_v5e_ab 1 "--severity-floor 0.0" ;;
51
+ both)
52
+ ( wait_log "$WAIT0"; launch phase1_v5e 0 "--severity-floor 0.05" ) &
53
+ ( wait_log "$WAIT1"; launch phase1_v5e_ab 1 "--severity-floor 0.0" ) &
54
+ wait
55
+ ;;
56
+ *) echo "ONLY must be v5e | v5e_ab | both"; exit 2 ;;
57
+ esac
dataset/phase1_noise_20260906/code/run_uformer_dgf8k.sh ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch + auto-resume supervisor for the v7-uformer luma run.
3
+ # First launch warm-starts from the 16k+chroma best; every relaunch after a
4
+ # designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on
5
+ # completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS.
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_DIR=outputs/phase2_v7/uformer_dgf8k_seed42
9
+ LOG=outputs/phase2_v7/uformer_dgf8k_train.log
10
+ PY=/home/admin_mcn/anaconda3/bin/python
11
+ MAX_RESTARTS=20
12
+ FINAL_STEP=8000
13
+ WARMSTART=outputs/phase2_v7/uformer_head8k_seed42/best.pt
14
+ WARMSTART_SHA=0168e543c6025514e7b98ef7ddd9e191de2bdcaca9072e0a796fadcf503cbc9c
15
+
16
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_dgf8k_seed42" >/dev/null; }
17
+ is_complete() {
18
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
19
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
20
+ }
21
+
22
+ launch() {
23
+ if [ "$1" = "fresh" ]; then
24
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
25
+ else
26
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
27
+ fi
28
+ # shellcheck disable=SC2086
29
+ nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \
30
+ train_phase2_unified_v7.py \
31
+ --ddp --ddp-find-unused --backbone uformer --timesteps 2 \
32
+ $SOURCE_FLAGS \
33
+ --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \
34
+ --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \
35
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
36
+ --output-dir "$RUN_DIR" \
37
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
38
+ --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \
39
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
40
+ --cond-dropout-prob 0.15 --identity-pair-prob 0.10 \
41
+ --kappa 0.11607981286942959 \
42
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
43
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
44
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
45
+ --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \
46
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
47
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
48
+ --milestone-steps 4000 \
49
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
50
+ }
51
+
52
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
53
+
54
+ restarts=0
55
+ seen_overflows=$(overflow_count)
56
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)"
57
+ launch fresh
58
+ sleep 90
59
+
60
+ while true; do
61
+ if is_complete; then
62
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
63
+ break
64
+ fi
65
+ if ! is_running; then
66
+ current=$(overflow_count)
67
+ if [ "$current" -gt "$seen_overflows" ]; then
68
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
69
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
70
+ break
71
+ fi
72
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
73
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
74
+ break
75
+ fi
76
+ seen_overflows=$current
77
+ restarts=$((restarts + 1))
78
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
79
+ launch resume
80
+ sleep 90
81
+ else
82
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
83
+ break
84
+ fi
85
+ fi
86
+ sleep 45
87
+ done
dataset/phase1_noise_20260906/code/run_uformer_head8k.sh ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch + auto-resume supervisor for the v7-uformer luma run.
3
+ # First launch warm-starts from the 16k+chroma best; every relaunch after a
4
+ # designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on
5
+ # completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS.
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_DIR=outputs/phase2_v7/uformer_head8k_seed42
9
+ LOG=outputs/phase2_v7/uformer_head8k_train.log
10
+ PY=/home/admin_mcn/anaconda3/bin/python
11
+ MAX_RESTARTS=20
12
+ FINAL_STEP=8000
13
+ WARMSTART=outputs/phase2_v7/uformer_luma8k_seed42/best.pt
14
+ WARMSTART_SHA=42c11eda0df3d4c3645a7013a831a5e965915d252895c2de58b5048d286e7817
15
+
16
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_head8k_seed42" >/dev/null; }
17
+ is_complete() {
18
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
19
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
20
+ }
21
+
22
+ launch() {
23
+ if [ "$1" = "fresh" ]; then
24
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
25
+ else
26
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
27
+ fi
28
+ # shellcheck disable=SC2086
29
+ nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \
30
+ train_phase2_unified_v7.py \
31
+ --ddp --ddp-find-unused --backbone uformer --timesteps 2 \
32
+ $SOURCE_FLAGS \
33
+ --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \
34
+ --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \
35
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
36
+ --output-dir "$RUN_DIR" \
37
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
38
+ --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \
39
+ --kappa 0.11607981286942959 \
40
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
41
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
42
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
43
+ --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \
44
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
45
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
46
+ --milestone-steps 4000 \
47
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
48
+ }
49
+
50
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
51
+
52
+ restarts=0
53
+ seen_overflows=$(overflow_count)
54
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)"
55
+ launch fresh
56
+ sleep 90
57
+
58
+ while true; do
59
+ if is_complete; then
60
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
61
+ break
62
+ fi
63
+ if ! is_running; then
64
+ current=$(overflow_count)
65
+ if [ "$current" -gt "$seen_overflows" ]; then
66
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
67
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
68
+ break
69
+ fi
70
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
71
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
72
+ break
73
+ fi
74
+ seen_overflows=$current
75
+ restarts=$((restarts + 1))
76
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
77
+ launch resume
78
+ sleep 90
79
+ else
80
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
81
+ break
82
+ fi
83
+ fi
84
+ sleep 45
85
+ done
dataset/phase1_noise_20260906/code/run_uformer_luma8k.sh ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch + auto-resume supervisor for the v7-uformer luma run.
3
+ # First launch warm-starts from the 16k+chroma best; every relaunch after a
4
+ # designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on
5
+ # completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS.
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_DIR=outputs/phase2_v7/uformer_luma8k_seed42
9
+ LOG=outputs/phase2_v7/uformer_luma8k_train.log
10
+ PY=/home/admin_mcn/anaconda3/bin/python
11
+ MAX_RESTARTS=20
12
+ FINAL_STEP=8000
13
+ WARMSTART=outputs/phase2_v7/uformer16k_seed42/best.pt
14
+ WARMSTART_SHA=809241a2a2e11c1d5e87b292827a97a2d71aa86a7684996caf903bf870532c43
15
+
16
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_luma8k_seed42" >/dev/null; }
17
+ is_complete() {
18
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
19
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
20
+ }
21
+
22
+ launch() {
23
+ if [ "$1" = "fresh" ]; then
24
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
25
+ else
26
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
27
+ fi
28
+ # shellcheck disable=SC2086
29
+ nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \
30
+ train_phase2_unified_v7.py \
31
+ --ddp --ddp-find-unused --backbone uformer --timesteps 2 \
32
+ $SOURCE_FLAGS \
33
+ --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \
34
+ --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \
35
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
36
+ --output-dir "$RUN_DIR" \
37
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
38
+ --kappa 0.11607981286942959 \
39
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
40
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
41
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
42
+ --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \
43
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
44
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
45
+ --milestone-steps 4000 \
46
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
47
+ }
48
+
49
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
50
+
51
+ restarts=0
52
+ seen_overflows=$(overflow_count)
53
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)"
54
+ launch fresh
55
+ sleep 90
56
+
57
+ while true; do
58
+ if is_complete; then
59
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
60
+ break
61
+ fi
62
+ if ! is_running; then
63
+ current=$(overflow_count)
64
+ if [ "$current" -gt "$seen_overflows" ]; then
65
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
66
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
67
+ break
68
+ fi
69
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
70
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
71
+ break
72
+ fi
73
+ seen_overflows=$current
74
+ restarts=$((restarts + 1))
75
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
76
+ launch resume
77
+ sleep 90
78
+ else
79
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
80
+ break
81
+ fi
82
+ fi
83
+ sleep 45
84
+ done
dataset/phase1_noise_20260906/code/run_uformer_nophase1.sh ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch + auto-resume supervisor for the v7-uformer luma run.
3
+ # First launch warm-starts from the 16k+chroma best; every relaunch after a
4
+ # designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on
5
+ # completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS.
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_DIR=outputs/phase2_v7/uformer_nophase1_8k_seed42
9
+ LOG=outputs/phase2_v7/uformer_nophase1_train.log
10
+ PY=/home/admin_mcn/anaconda3/bin/python
11
+ MAX_RESTARTS=20
12
+ FINAL_STEP=8000
13
+ WARMSTART=outputs/phase2_v7/uformer_head8k_seed42/best.pt
14
+ WARMSTART_SHA=0168e543c6025514e7b98ef7ddd9e191de2bdcaca9072e0a796fadcf503cbc9c
15
+
16
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_nophase1_8k_seed42" >/dev/null; }
17
+ is_complete() {
18
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
19
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
20
+ }
21
+
22
+ launch() {
23
+ if [ "$1" = "fresh" ]; then
24
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
25
+ else
26
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
27
+ fi
28
+ # shellcheck disable=SC2086
29
+ CUDA_VISIBLE_DEVICES=0 nohup "$PY" \
30
+ train_phase2_unified_v7.py \
31
+ --backbone uformer --timesteps 2 \
32
+ $SOURCE_FLAGS \
33
+ --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \
34
+ --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \
35
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
36
+ --output-dir "$RUN_DIR" \
37
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
38
+ --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \
39
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
40
+ --cond-dropout-prob 1.0 --identity-pair-prob 0.10 \
41
+ --kappa 0.11607981286942959 \
42
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
43
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
44
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
45
+ --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \
46
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
47
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
48
+ --milestone-steps 4000 \
49
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
50
+ }
51
+
52
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
53
+
54
+ restarts=0
55
+ seen_overflows=$(overflow_count)
56
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)"
57
+ launch fresh
58
+ sleep 90
59
+
60
+ while true; do
61
+ if is_complete; then
62
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
63
+ break
64
+ fi
65
+ if ! is_running; then
66
+ current=$(overflow_count)
67
+ if [ "$current" -gt "$seen_overflows" ]; then
68
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
69
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
70
+ break
71
+ fi
72
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
73
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
74
+ break
75
+ fi
76
+ seen_overflows=$current
77
+ restarts=$((restarts + 1))
78
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
79
+ launch resume
80
+ sleep 90
81
+ else
82
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
83
+ break
84
+ fi
85
+ fi
86
+ sleep 45
87
+ done
dataset/phase1_noise_20260906/code/run_uformer_p45.sh ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch + auto-resume supervisor for the v7-uformer luma run.
3
+ # First launch warm-starts from the 16k+chroma best; every relaunch after a
4
+ # designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on
5
+ # completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS.
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_DIR=outputs/phase2_v7/uformer_p45_8k_seed42
9
+ LOG=outputs/phase2_v7/uformer_p45_train.log
10
+ PY=/home/admin_mcn/anaconda3/bin/python
11
+ MAX_RESTARTS=20
12
+ FINAL_STEP=8000
13
+ WARMSTART=outputs/phase2_v7/uformer_dgf8k_seed42/best.pt
14
+ WARMSTART_SHA=f92dc6d37ffe4e8a55ce723a1acf51042bf9821b98eefeaebb8ba140b7ce0f97
15
+
16
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_p45_8k_seed42" >/dev/null; }
17
+ is_complete() {
18
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
19
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
20
+ }
21
+
22
+ launch() {
23
+ if [ "$1" = "fresh" ]; then
24
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
25
+ else
26
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
27
+ fi
28
+ # shellcheck disable=SC2086
29
+ CUDA_VISIBLE_DEVICES=1 nohup "$PY" \
30
+ train_phase2_unified_v7.py \
31
+ --backbone uformer --timesteps 2 \
32
+ $SOURCE_FLAGS \
33
+ --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \
34
+ --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \
35
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
36
+ --output-dir "$RUN_DIR" \
37
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
38
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
39
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
40
+ --cond-dropout-prob 0.15 --identity-pair-prob 0.10 --noise-pair-prob 0.20 --global-context \
41
+ --kappa 0.11607981286942959 \
42
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
43
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
44
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
45
+ --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \
46
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
47
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
48
+ --milestone-steps 4000 \
49
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
50
+ }
51
+
52
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
53
+
54
+ restarts=0
55
+ seen_overflows=$(overflow_count)
56
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)"
57
+ launch fresh
58
+ sleep 90
59
+
60
+ while true; do
61
+ if is_complete; then
62
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
63
+ break
64
+ fi
65
+ if ! is_running; then
66
+ current=$(overflow_count)
67
+ if [ "$current" -gt "$seen_overflows" ]; then
68
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
69
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
70
+ break
71
+ fi
72
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
73
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
74
+ break
75
+ fi
76
+ seen_overflows=$current
77
+ restarts=$((restarts + 1))
78
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
79
+ launch resume
80
+ sleep 90
81
+ else
82
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
83
+ break
84
+ fi
85
+ fi
86
+ sleep 45
87
+ done
dataset/phase1_noise_20260906/code/run_uformer_p5.sh ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Launch + auto-resume supervisor for the v7-uformer luma run.
3
+ # First launch warm-starts from the 16k+chroma best; every relaunch after a
4
+ # designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on
5
+ # completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS.
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_DIR=outputs/phase2_v7/uformer_p5_8k_seed42
9
+ LOG=outputs/phase2_v7/uformer_p5_train.log
10
+ PY=/home/admin_mcn/anaconda3/bin/python
11
+ MAX_RESTARTS=20
12
+ FINAL_STEP=8000
13
+ WARMSTART=outputs/phase2_v7/uformer_dgf8k_seed42/best.pt
14
+ WARMSTART_SHA=f92dc6d37ffe4e8a55ce723a1acf51042bf9821b98eefeaebb8ba140b7ce0f97
15
+
16
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_p5_8k_seed42" >/dev/null; }
17
+ is_complete() {
18
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
19
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
20
+ }
21
+
22
+ launch() {
23
+ if [ "$1" = "fresh" ]; then
24
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
25
+ else
26
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
27
+ fi
28
+ # shellcheck disable=SC2086
29
+ CUDA_VISIBLE_DEVICES=0 nohup "$PY" \
30
+ train_phase2_unified_v7.py \
31
+ --backbone uformer --timesteps 2 \
32
+ $SOURCE_FLAGS \
33
+ --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \
34
+ --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \
35
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
36
+ --output-dir "$RUN_DIR" \
37
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
38
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
39
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
40
+ --cond-dropout-prob 0.15 --identity-pair-prob 0.10 --noise-pair-prob 0.20 \
41
+ --kappa 0.11607981286942959 \
42
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
43
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
44
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
45
+ --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \
46
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
47
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
48
+ --milestone-steps 4000 \
49
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
50
+ }
51
+
52
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
53
+
54
+ restarts=0
55
+ seen_overflows=$(overflow_count)
56
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)"
57
+ launch fresh
58
+ sleep 90
59
+
60
+ while true; do
61
+ if is_complete; then
62
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
63
+ break
64
+ fi
65
+ if ! is_running; then
66
+ current=$(overflow_count)
67
+ if [ "$current" -gt "$seen_overflows" ]; then
68
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
69
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
70
+ break
71
+ fi
72
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
73
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
74
+ break
75
+ fi
76
+ seen_overflows=$current
77
+ restarts=$((restarts + 1))
78
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
79
+ launch resume
80
+ sleep 90
81
+ else
82
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
83
+ break
84
+ fi
85
+ fi
86
+ sleep 45
87
+ done
dataset/phase1_noise_20260906/code/run_uformer_v10.sh ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # v10 chain (2026-09-04): runs AFTER uformer_v9a15k_seed42 finishes.
3
+ # 1. wait until the 15k trainer is gone (eval@15000, early stop, or death)
4
+ # 2. GPU0 evals of v9a15k best.pt: locked crop protocol (comparable to A/B/v9a-4k),
5
+ # native full-frame protocol (eval_full_frame.py) for v9a15k, A, v9a-4k, B,
6
+ # scene008 tone probe, then full-frame x8 TTA for v9a15k
7
+ # 3. GPU1 v10 = A recipe on Phase-1 v5f, warm-start v9a15k best (EMA)
8
+ # + whole-frame context + photometric head + exposure-diverse identity
9
+ # pairs from SIDD-train-GT / LOL-train-GT / Snow100K-gt (balanced)
10
+ # + v10 input pre-gain (Retinex-style) + global attention at stages 2,3
11
+ # 4. GPU0 v10_ab = v10 minus pre-gain and global attention (isolates the two new blocks),
12
+ # launched when the evals are done
13
+ # Each run has its own AMP-overflow supervisor (resume from overflow_recovery.pt).
14
+ set -u
15
+ cd /home/admin_mcn/scdc_ban
16
+ PY=/home/admin_mcn/anaconda3/bin/python
17
+ SRC_NAME=uformer_v9a15k_seed42
18
+ SRC_RUN=outputs/phase2_v7/$SRC_NAME
19
+ SRC_LOG=outputs/phase2_v7/uformer_v9a15k_train.log
20
+ PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt}
21
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
22
+ POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt
23
+ STEPS=${STEPS:-8000}
24
+ MAX_RESTARTS=20
25
+ export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128
26
+
27
+ log() { echo "[v10 $(date +%H:%M:%S)] $*"; }
28
+ src_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$SRC_NAME" >/dev/null; }
29
+ src_complete() {
30
+ grep -q "\"event\": \"evaluation\".*\"step\": 15000\|\"step\": 15000.*\"event\": \"evaluation\"" "$SRC_RUN/metrics.jsonl" 2>/dev/null \
31
+ || grep -q "\[early-stop\] training ended" "$SRC_LOG" 2>/dev/null
32
+ }
33
+
34
+ # ---- 1. wait for the source run ------------------------------------------ #
35
+ quiet=0
36
+ while true; do
37
+ if src_complete && ! src_running; then log "source run complete"; break; fi
38
+ if ! src_running; then
39
+ quiet=$((quiet + 1))
40
+ if [ "$quiet" -ge 6 ]; then log "source trainer absent for 6 polls without completion; proceeding with its best.pt"; break; fi
41
+ else
42
+ quiet=0
43
+ fi
44
+ sleep 60
45
+ done
46
+ sleep 30
47
+ WARM=$SRC_RUN/best.pt
48
+ WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1)
49
+ log "warm start $WARM sha=$WARM_SHA phase1=$PHASE1 sha=$PHASE1_SHA"
50
+
51
+ # ---- shared recipe ---------------------------------------------------------- #
52
+ COMMON="--backbone uformer --timesteps 2 \
53
+ --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \
54
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
55
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
56
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
57
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
58
+ --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \
59
+ --kappa 0.11607981286942959 \
60
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
61
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
62
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
63
+ --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \
64
+ --learning-rate 3e-5 --max-steps $STEPS --run-until-step $STEPS \
65
+ --eval-steps 0,500,1000,2000,3000,4000,5000,6000,7000,8000 --milestone-steps 4000,8000 \
66
+ --freeze-encoder-steps 1000 --early-stop-patience 4 --early-stop-min-delta 0.02 \
67
+ --seed 42 --eval-seed 20260830 \
68
+ --global-context --photometric-head --photometric-dropout 0.1 \
69
+ --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \
70
+ --extra-clean-root $POOLS --extra-clean-prob 0.6"
71
+ V10_EXTRA="--exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --global-attention-scales 2,3"
72
+
73
+ launch() { # $1 name $2 gpu $3 fresh|resume $4 extra flags
74
+ local name=$1 gpu=$2 mode=$3 extra=$4
75
+ local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log
76
+ local source
77
+ if [ "$mode" = "fresh" ]; then
78
+ source="--warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema"
79
+ else
80
+ source="--resume $run_dir/overflow_recovery.pt"
81
+ fi
82
+ # shellcheck disable=SC2086
83
+ CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $COMMON $extra $source \
84
+ --output-dir "$run_dir" >> "$log" 2>&1 &
85
+ log "launched $name on GPU$gpu ($mode) pid $!"
86
+ }
87
+
88
+ supervise() { # $1 name $2 gpu $3 extra flags
89
+ local name=$1 gpu=$2 extra=$3
90
+ local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log
91
+ running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; }
92
+ complete() {
93
+ grep -q "\"event\": \"evaluation\".*\"step\": $STEPS\|\"step\": $STEPS.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \
94
+ || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null
95
+ }
96
+ overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; }
97
+ local restarts=0 seen
98
+ seen=$(overflows)
99
+ if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$name" "$gpu" resume "$extra"; else launch "$name" "$gpu" fresh "$extra"; fi
100
+ sleep 180
101
+ while true; do
102
+ if complete; then log "$name complete (eval @$STEPS or early stop)"; return 0; fi
103
+ if ! running; then
104
+ local current; current=$(overflows)
105
+ if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then
106
+ restarts=$((restarts + 1)); seen=$current
107
+ log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
108
+ launch "$name" "$gpu" resume "$extra"; sleep 180
109
+ else
110
+ log "$name process died WITHOUT a new overflow (or budget exhausted); giving up"; return 1
111
+ fi
112
+ fi
113
+ sleep 45
114
+ done
115
+ }
116
+
117
+ # ---- 3. v10 on GPU1 (starts immediately) ----------------------------------- #
118
+ ( supervise uformer_v10_8k_seed42 1 "$V10_EXTRA" ) &
119
+ V10_PID=$!
120
+
121
+ # ---- 2. evals of the source run on GPU0 ------------------------------------ #
122
+ run_eval() { log "eval: $*"; CUDA_VISIBLE_DEVICES=0 $PY -u "$@" >> outputs/phase2_v7/uformer_v10_evals.log 2>&1 || log "eval FAILED: $*"; }
123
+ run_eval eval_v7_external.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_external_v1.json
124
+ run_eval eval_full_frame.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_fullframe_v1.json --tta 1
125
+ run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_p5_8k_seed42 --output outputs/v7_p5_fullframe_v1.json --tta 1
126
+ run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_v9a_8k_seed42 --output outputs/v7_v9a4k_fullframe_v1.json --tta 1
127
+ run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_p45_8k_seed42 --output outputs/v7_p45_fullframe_v1.json --tta 1
128
+ run_eval probe_scene008_tone.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_scene008_tone.json --skip-val-baseline
129
+ run_eval eval_full_frame.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_fullframe_tta8_v1.json --tta 8
130
+ log "evals done"
131
+
132
+ # ---- 4. ablation on GPU0 ---------------------------------------------------- #
133
+ ( supervise uformer_v10ab_8k_seed42 0 "" ) &
134
+ AB_PID=$!
135
+ wait $V10_PID; log "v10 supervisor exited ($?)"
136
+ wait $AB_PID; log "v10_ab supervisor exited ($?)"
137
+ log "chain finished"
dataset/phase1_noise_20260906/code/run_uformer_v10ab_resume.sh ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Resume uformer_v10ab_8k_seed42 from its overflow_recovery.pt after the
3
+ # 08:12 resume died on a contract mismatch (code synced mid-run added
4
+ # architecture keys; the runtime now tolerates added keys). Same recipe as
5
+ # run_uformer_v10.sh (v10_ab = COMMON without the v10 extras), GPU0, with the
6
+ # same overflow supervisor.
7
+ set -u
8
+ cd /home/admin_mcn/scdc_ban
9
+ PY=/home/admin_mcn/anaconda3/bin/python
10
+ NAME=uformer_v10ab_8k_seed42
11
+ RUN_DIR=outputs/phase2_v7/$NAME
12
+ LOG=outputs/phase2_v7/${NAME}_train.log
13
+ STEPS=8000
14
+ GPU=${GPU:-0}
15
+ MAX_RESTARTS=20
16
+ PHASE1=outputs/phase1_v5f/graph_encoder_best.pt
17
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
18
+ POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt
19
+ export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128
20
+ log() { echo "[v10ab-resume $(date +%H:%M:%S)] $*"; }
21
+
22
+ COMMON="--backbone uformer --timesteps 2 \
23
+ --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \
24
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
25
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
26
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
27
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
28
+ --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \
29
+ --kappa 0.11607981286942959 \
30
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
31
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
32
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
33
+ --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \
34
+ --learning-rate 3e-5 --max-steps $STEPS --run-until-step $STEPS \
35
+ --eval-steps 0,500,1000,2000,3000,4000,5000,6000,7000,8000 --milestone-steps 4000,8000 \
36
+ --freeze-encoder-steps 1000 --early-stop-patience 4 --early-stop-min-delta 0.02 \
37
+ --seed 42 --eval-seed 20260830 \
38
+ --global-context --photometric-head --photometric-dropout 0.1 \
39
+ --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \
40
+ --extra-clean-root $POOLS --extra-clean-prob 0.6"
41
+
42
+ running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $RUN_DIR" >/dev/null; }
43
+ complete() {
44
+ grep -q "\"event\": \"evaluation\".*\"step\": $STEPS\|\"step\": $STEPS.*\"event\": \"evaluation\"" "$RUN_DIR/metrics.jsonl" 2>/dev/null \
45
+ || grep -q "\[early-stop\] training ended" "$LOG" 2>/dev/null
46
+ }
47
+ overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null | head -n 1); echo "${n:-0}"; }
48
+ launch() {
49
+ # shellcheck disable=SC2086
50
+ CUDA_VISIBLE_DEVICES=$GPU nohup $PY -u train_phase2_unified_v7.py $COMMON \
51
+ --resume $RUN_DIR/overflow_recovery.pt --output-dir "$RUN_DIR" >> "$LOG" 2>&1 &
52
+ log "launched resume on GPU$GPU pid $!"
53
+ }
54
+
55
+ [ -f "$RUN_DIR/overflow_recovery.pt" ] || { log "no overflow_recovery.pt; nothing to resume"; exit 1; }
56
+ if running; then log "already running"; exit 0; fi
57
+ restarts=0; seen=$(overflows)
58
+ launch; sleep 180
59
+ while true; do
60
+ if complete; then log "complete"; break; fi
61
+ if ! running; then
62
+ current=$(overflows)
63
+ if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ]; then
64
+ restarts=$((restarts + 1)); seen=$current
65
+ log "relaunch #$restarts from overflow_recovery.pt (overflows=$current)"; launch; sleep 180
66
+ else
67
+ log "died WITHOUT a new overflow; giving up"; break
68
+ fi
69
+ fi
70
+ sleep 45
71
+ done
dataset/phase1_noise_20260906/code/run_uformer_v11.sh ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # v11 chain (2026-09-05): capacity + budget + progressive resolution, both GPUs (DDP).
3
+ # 0. wait until the v10 chain is finished (no v10 supervisor, no trainer processes)
4
+ # 1. native full-frame + crop evals of v10 and v10_ab (GPU0 / GPU1 in parallel), then
5
+ # pick the warm start among {v10, v10_ab, v9a15k} by the mean of the four
6
+ # full-frame group PSNRs (lowlight LOLv2, rain Test1200 Y-channel, haze, scene008)
7
+ # 2. memory probe (GPU0) to pick per-stage batch sizes
8
+ # 3. stage A crop 256, 24k steps, DDP x2, LR 5e-5
9
+ # stage B crop 320, 8k steps, DDP x2, LR 3e-5, warm-start best of A
10
+ # stage C crop 384, 8k steps, DDP x2 (or 1 GPU + grad checkpoint if the probe says so), LR 2e-5
11
+ # recipe = v10 (pre-gain, global attention 2,3, whole-frame context, photometric head,
12
+ # exposure-diverse identity pools) + --extra-blocks-per-stage 0,2,4,4 (13.4M -> ~28.8M)
13
+ # 4. full-frame evals after every stage (TTA 1), TTA 8 after stage C
14
+ set -u
15
+ cd /home/admin_mcn/scdc_ban
16
+ PY=/home/admin_mcn/anaconda3/bin/python
17
+ PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt}
18
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
19
+ POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt
20
+ MAX_RESTARTS=20
21
+ MEM_BUDGET_GIB=${MEM_BUDGET_GIB:-19.5}
22
+ export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128
23
+ EVLOG=outputs/phase2_v7/uformer_v11_evals.log
24
+
25
+ log() { echo "[v11 $(date +%H:%M:%S)] $*"; }
26
+ trainers_running() { pgrep -f "[t]rain_phase2_unified_v7.py" >/dev/null; }
27
+ v10_chain_running() { pgrep -f "[r]un_uformer_v10.sh" >/dev/null; }
28
+
29
+ # ---- 0. wait for the GPUs ------------------------------------------------- #
30
+ while v10_chain_running || trainers_running; do sleep 120; done
31
+ log "GPUs free"
32
+ sleep 30
33
+
34
+ # ---- 1. evals of the v10 pair + warm-start selection ---------------------- #
35
+ run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; }
36
+ # WARM_OVERRIDE=<checkpoint path> skips the evaluation sweep and the
37
+ # selection (user request 2026-09-05: start DDP training right away).
38
+ if [ -n "${WARM_OVERRIDE:-}" ]; then
39
+ WARM=$WARM_OVERRIDE
40
+ WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1)
41
+ log "warm start OVERRIDE: $WARM sha=$WARM_SHA (evaluation sweep skipped)"
42
+ fi
43
+ if [ -z "${WARM_OVERRIDE:-}" ]; then
44
+ # Whole-image single pass for images <= 1.2 MP (LOL / RESIDE / Test1200); the
45
+ # 12 MP SIDD frames stay tiled. Tiling costs -2.1 dB on LOLv2 (per-tile
46
+ # exposure inconsistency), so every full-frame number below uses this mode.
47
+ WHOLE="--whole-max-pixels 1200000"
48
+ # best.pt is picked by val macro, which is a poor proxy for the external
49
+ # sets, so every candidate run is evaluated at best / milestone / last and
50
+ # the warm start is the best (run, checkpoint) pair on the full-frame score.
51
+ ckpt_tag() { echo "$1" | sed 's/\.pt$//; s/milestone_0*/m/'; }
52
+ eval_run_checkpoints() { # $1 gpu $2 run $3 tag $4.. checkpoints
53
+ local gpu=$1 run=$2 tag=$3; shift 3
54
+ run_eval "$gpu" eval_v7_external.py --run-dir outputs/phase2_v7/$run --output outputs/v7_${tag}_external_v1.json
55
+ for ck in "$@"; do
56
+ [ -f outputs/phase2_v7/$run/$ck ] || { log "skip missing $run/$ck"; continue; }
57
+ run_eval "$gpu" eval_full_frame.py --run-dir outputs/phase2_v7/$run --checkpoint "$ck" \
58
+ --output outputs/v7_${tag}_$(ckpt_tag "$ck")_fullframe_whole_v1.json --tta 1 $WHOLE
59
+ done
60
+ }
61
+ ( eval_run_checkpoints 0 uformer_v10_8k_seed42 v10 best.pt milestone_00004000.pt last.pt
62
+ eval_run_checkpoints 0 uformer_v9a15k_seed42 v9a15k best.pt milestone_00008000.pt last.pt ) &
63
+ ( eval_run_checkpoints 1 uformer_v10ab_8k_seed42 v10ab best.pt milestone_00004000.pt last.pt ) &
64
+ wait
65
+ SELECTION=$($PY - <<'PYEOF'
66
+ import glob, json, os, re, sys
67
+ runs = {"v10": "uformer_v10_8k_seed42", "v10ab": "uformer_v10ab_8k_seed42", "v9a15k": "uformer_v9a15k_seed42"}
68
+ def score(path):
69
+ r = json.load(open(path))
70
+ try:
71
+ return (r["lowlight_lolv2_test"]["restored"]["psnr"] + r["rain_locked"]["restored"]["psnr_y"]
72
+ + r["haze_heldout"]["restored"]["psnr"] + r["noise_locked_scene008"]["restored"]["psnr"]) / 4.0, r.get("checkpoint", "best.pt")
73
+ except KeyError:
74
+ return None, None
75
+ scores = {}
76
+ for tag, run in runs.items():
77
+ for path in glob.glob("outputs/v7_%s_*_fullframe_whole_v1.json" % tag):
78
+ value, ck = score(path)
79
+ if value is not None and ck and os.path.exists("outputs/phase2_v7/%s/%s" % (run, ck)):
80
+ scores[(run, ck)] = value
81
+ if not scores:
82
+ print("uformer_v9a15k_seed42 best.pt")
83
+ else:
84
+ (run, ck) = max(scores, key=scores.get)
85
+ print(run, ck)
86
+ sys.stderr.write("warm-start scores: %s\n" % json.dumps({"%s/%s" % k: round(v, 3) for k, v in sorted(scores.items())}))
87
+ PYEOF
88
+ )
89
+ read -r SOURCE SOURCE_CKPT <<< "$SELECTION"
90
+ log "warm start selected: $SOURCE/$SOURCE_CKPT"
91
+ WARM=outputs/phase2_v7/$SOURCE/$SOURCE_CKPT
92
+ WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1)
93
+ fi
94
+
95
+ # ---- shared recipe -------------------------------------------------------- #
96
+ RECIPE="--backbone uformer --timesteps 2 \
97
+ --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \
98
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
99
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
100
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
101
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
102
+ --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \
103
+ --kappa 0.11607981286942959 \
104
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
105
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
106
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
107
+ --workers 4 --seed 42 --eval-seed 20260830 \
108
+ --global-context --photometric-head --photometric-dropout 0.1 \
109
+ --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \
110
+ --extra-clean-root $POOLS --extra-clean-prob 0.6 \
111
+ --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02 \
112
+ --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4"
113
+
114
+ # ---- 2. memory probe ------------------------------------------------------ #
115
+ probe() { # $1 crop $2 batch $3 extra -> peak GiB or 99 on failure
116
+ local out; out=$(CUDA_VISIBLE_DEVICES=0 $PY -u probe_v11_memory.py --crop "$1" --batch "$2" --steps 3 -- $RECIPE $3 --output-dir outputs/phase2_v7/_probe 2>>$EVLOG | grep "^PROBE")
117
+ echo "$out" >> $EVLOG
118
+ echo "$out" | $PY -c "import sys,json; l=sys.stdin.read().strip(); print(json.loads(l[6:])['peak_gib'] if l.startswith('PROBE') else 99)"
119
+ }
120
+ fits() { $PY -c "import sys; sys.exit(0 if float('$1') <= float('$MEM_BUDGET_GIB') else 1)"; }
121
+ pick_batch() { # $1 crop -> "batch accum" for DDP x2 with effective batch 16 (stdout = result only)
122
+ local crop=$1 peak
123
+ for cfg in "8 1" "4 2" "2 4"; do
124
+ set -- $cfg
125
+ peak=$(probe "$crop" "$1" "")
126
+ log "probe crop=$crop batch=$1 -> peak ${peak} GiB" >&2
127
+ if fits "$peak"; then echo "$1 $2"; return 0; fi
128
+ done
129
+ echo "0 0"
130
+ }
131
+
132
+ # ---- supervisor ----------------------------------------------------------- #
133
+ launch() { # name gpus mode(fresh|resume) crop batch accum steps lr evalsteps milestones extra warm
134
+ local name=$1 gpus=$2 mode=$3 crop=$4 batch=$5 accum=$6 steps=$7 lr=$8 evals=$9 miles=${10} extra=${11} warm=${12}
135
+ local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log source
136
+ if [ "$mode" = "fresh" ]; then
137
+ source="--warmstart-v6 $warm --warmstart-v6-sha256 $(sha256sum $warm | cut -d' ' -f1) --warmstart-weight-source ema"
138
+ else
139
+ source="--resume $run_dir/overflow_recovery.pt"
140
+ fi
141
+ local common="$RECIPE $extra $source --output-dir $run_dir --crop-size $crop \
142
+ --batch-size $batch --grad-accum $accum --eval-batch-size 4 \
143
+ --learning-rate $lr --max-steps $steps --run-until-step $steps \
144
+ --eval-steps $evals --milestone-steps $miles \
145
+ --freeze-encoder-steps 1000 --early-stop-patience ${PATIENCE:-0} --early-stop-min-delta 0.02"
146
+ # shellcheck disable=SC2086
147
+ if [ "$gpus" = "0,1" ]; then
148
+ CUDA_VISIBLE_DEVICES=0,1 nohup $PY -m torch.distributed.run --nproc_per_node=2 --master_port=29531 \
149
+ train_phase2_unified_v7.py --ddp --ddp-find-unused $common >> "$log" 2>&1 &
150
+ else
151
+ CUDA_VISIBLE_DEVICES=$gpus nohup $PY -u train_phase2_unified_v7.py $common >> "$log" 2>&1 &
152
+ fi
153
+ log "launched $name on GPU$gpus ($mode, crop $crop, batch ${batch}x${accum}, $steps steps) pid $!"
154
+ }
155
+
156
+ supervise() { # same args as launch (mode ignored)
157
+ local name=$1 gpus=$2 steps=$7
158
+ local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log
159
+ running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; }
160
+ complete() {
161
+ grep -q "\"event\": \"evaluation\".*\"step\": $steps\|\"step\": $steps.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \
162
+ || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null
163
+ }
164
+ overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; }
165
+ local restarts=0 seen; seen=$(overflows)
166
+ if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$1" "$2" resume "${@:4}"; else launch "$1" "$2" fresh "${@:4}"; fi
167
+ sleep 240
168
+ while true; do
169
+ if complete; then log "$name complete"; return 0; fi
170
+ if ! running; then
171
+ local current; current=$(overflows)
172
+ if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then
173
+ restarts=$((restarts + 1)); seen=$current
174
+ log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
175
+ launch "$1" "$2" resume "${@:4}"; sleep 240
176
+ else
177
+ log "$name died WITHOUT a new overflow (or budget exhausted); stopping the chain"; return 1
178
+ fi
179
+ fi
180
+ sleep 60
181
+ done
182
+ }
183
+
184
+ stage_evals() { # $1 run name $2 tag $3 tta
185
+ run_eval 0 eval_v7_external.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_external_v1.json
186
+ run_eval 0 eval_full_frame.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_last_fullframe_whole_v1.json --tta 1 $WHOLE
187
+ run_eval 1 eval_full_frame.py --run-dir outputs/phase2_v7/$1 --checkpoint best.pt --output outputs/v7_${2}_best_fullframe_whole_v1.json --tta 1 $WHOLE
188
+ if [ "$3" = "8" ]; then
189
+ # orientation-safe x2 (mirror) for every group; the full dihedral x8 only
190
+ # for isotropic noise (x8 costs -2.4 dB on rain / -1.0 dB on haze)
191
+ run_eval 0 eval_full_frame.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_last_fullframe_whole_tta2_v1.json --tta 2 $WHOLE
192
+ run_eval 0 eval_full_frame.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_last_scene008_tta8_v1.json --tta 8 --groups noise_locked_scene008
193
+ run_eval 1 probe_scene008_tone.py --run-dir outputs/phase2_v7/$1 --output outputs/v7_${2}_scene008_tone.json --skip-val-baseline
194
+ fi
195
+ }
196
+
197
+ # ---- 3. stages ------------------------------------------------------------ #
198
+ A=uformer_v11a_256_seed42; B=uformer_v11b_320_seed42; C=uformer_v11c_384_seed42
199
+
200
+ read -r BA AA <<< "$(pick_batch 256)"
201
+ [ "$BA" = "0" ] && { log "no batch fits at 256; aborting"; exit 1; }
202
+ supervise $A 0,1 fresh 256 "$BA" "$AA" 24000 5e-5 0,1000,2000,4000,6000,8000,10000,12000,14000,16000,18000,20000,22000,24000 8000,16000,24000 "" "$WARM" || exit 1
203
+ stage_evals $A v11a 1
204
+
205
+ read -r BB AB <<< "$(pick_batch 320)"
206
+ [ "$BB" = "0" ] && { log "no batch fits at 320; aborting"; exit 1; }
207
+ # Stages warm-start from the END of the previous stage (last.pt = cosine
208
+ # schedule fully annealed): best.pt is picked by val macro, which does not
209
+ # track the external sets and can stay at the step-0 checkpoint.
210
+ supervise $B 0,1 fresh 320 "$BB" "$AB" 8000 3e-5 0,1000,2000,3000,4000,5000,6000,7000,8000 4000,8000 "" outputs/phase2_v7/$A/last.pt || exit 1
211
+ stage_evals $B v11b 1
212
+
213
+ read -r BC AC <<< "$(pick_batch 384)"
214
+ if [ "$BC" = "0" ]; then
215
+ log "384 does not fit without checkpointing on 2 ranks; running stage C on ONE GPU with --grad-checkpoint (batch 4 x accum 4)"
216
+ supervise $C 0 fresh 384 4 4 8000 2e-5 0,1000,2000,3000,4000,5000,6000,7000,8000 4000,8000 "--grad-checkpoint" outputs/phase2_v7/$B/last.pt || exit 1
217
+ else
218
+ supervise $C 0,1 fresh 384 "$BC" "$AC" 8000 2e-5 0,1000,2000,3000,4000,5000,6000,7000,8000 4000,8000 "" outputs/phase2_v7/$B/last.pt || exit 1
219
+ fi
220
+ stage_evals $C v11c 8
221
+ log "chain finished"
dataset/phase1_noise_20260906/code/run_uformer_v11_mi325x.sh ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # v11 on the MI325X host (kim.long-mi325x8), ONE GPU (default 7), no DDP.
3
+ # Same recipe as run_uformer_v11.sh; the 256 GB card takes the whole
4
+ # effective batch in one micro-batch, so batch/LR/steps are re-scaled:
5
+ # stage A crop 256 BATCH_A (probe: 2.6 GiB/sample) LR_A STEPS_A
6
+ # stage B crop 320 BATCH_B LR_B STEPS_B warm-start A/last.pt
7
+ # stage C crop 384 BATCH_C LR_C STEPS_C warm-start B/last.pt
8
+ # Data roots come from the HF bundle (SCDC_DATA_ROOT / SCDC_RAIN13K_ROOT).
9
+ set -u
10
+ cd /home/vunguyen/SCDC
11
+ PY=/home/vunguyen/miniforge3/envs/mavt/bin/python
12
+ export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data
13
+ export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1
14
+ # map this host's roots back to the canonical ones for the audited split digests
15
+ export SCDC_PATH_RELOCATION=/home/vunguyen/data_bundle/extract/data/=/home/admin_mcn/data/,/home/vunguyen/data_bundle/extract/kagglehub/=/home/admin_mcn/.cache/kagglehub/
16
+ GPU=${GPU:-7}
17
+ PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt}
18
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
19
+ TAG=${TAG:-x} # run-name suffix: x = v11 on MI325X, v12 = Phase-1 v6
20
+ WARM=${WARM:-outputs/phase2_v7/uformer_v10_8k_seed42/best.pt}
21
+ # identity-pair clean pools: TRAIN-split SIDD/LOL GTs only (built by make_clean_pools.py), plus Snow100K gt
22
+ POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt
23
+ # Probe on GPU 7 (30M params, crop 256): batch 16 -> 42 GiB 0.42 s (38 img/s),
24
+ # batch 32 -> 84 GiB 0.67 s (48 img/s), batch 64 -> 167 GiB 1.56 s (41 img/s),
25
+ # batch 96 OOM. Compute saturates at 32, so 32 gives the most images/s AND the
26
+ # most optimizer steps per hour; LR scaled by sqrt(32/16) from the 5e-5 recipe.
27
+ BATCH_A=${BATCH_A:-32}; LR_A=${LR_A:-7e-5}; STEPS_A=${STEPS_A:-20000}
28
+ BATCH_B=${BATCH_B:-20}; LR_B=${LR_B:-5e-5}; STEPS_B=${STEPS_B:-6000}
29
+ BATCH_C=${BATCH_C:-14}; LR_C=${LR_C:-3e-5}; STEPS_C=${STEPS_C:-6000}
30
+ WORKERS=${WORKERS:-32}
31
+ EXTRA_WORKERS=${EXTRA_WORKERS:-12}
32
+ export OMP_NUM_THREADS=${OMP_NUM_THREADS:-8}
33
+ MAX_RESTARTS=20
34
+ EVLOG=outputs/phase2_v7/uformer_v11_${TAG}_evals.log
35
+ WHOLE="--whole-max-pixels 1200000"
36
+ log() { echo "[v11x $(date +%H:%M:%S)] $*"; }
37
+
38
+ RECIPE="--backbone uformer --timesteps 2 \
39
+ --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \
40
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
41
+ --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
42
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
43
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
44
+ --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \
45
+ --kappa 0.11607981286942959 \
46
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
47
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
48
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
49
+ --workers $WORKERS --extra-clean-workers $EXTRA_WORKERS --seed 42 --eval-seed 20260830 \
50
+ --global-context --photometric-head --photometric-dropout 0.1 \
51
+ --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \
52
+ --extra-clean-root $POOLS --extra-clean-prob 0.6 \
53
+ --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02 \
54
+ --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4"
55
+
56
+ launch() { # name mode(fresh|resume) crop batch steps lr evalsteps milestones warm
57
+ local name=$1 mode=$2 crop=$3 batch=$4 steps=$5 lr=$6 evals=$7 miles=$8 warm=$9
58
+ local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log source
59
+ if [ "$mode" = "fresh" ]; then
60
+ source="--warmstart-v6 $warm --warmstart-v6-sha256 $(sha256sum $warm | cut -d' ' -f1) --warmstart-weight-source ema"
61
+ else
62
+ source="--resume $run_dir/overflow_recovery.pt"
63
+ fi
64
+ # shellcheck disable=SC2086
65
+ CUDA_VISIBLE_DEVICES=$GPU nohup $PY -u train_phase2_unified_v7.py $RECIPE $source --output-dir $run_dir \
66
+ --crop-size $crop --batch-size $batch --grad-accum 1 --eval-batch-size 16 \
67
+ --learning-rate $lr --max-steps $steps --run-until-step $steps \
68
+ --eval-steps $evals --milestone-steps $miles \
69
+ --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02 >> "$log" 2>&1 &
70
+ log "launched $name on GPU$GPU ($mode, crop $crop, batch $batch, $steps steps, lr $lr) pid $!"
71
+ }
72
+
73
+ supervise() { # same args as launch minus mode: name crop batch steps lr evals miles warm
74
+ local name=$1 steps=$4
75
+ local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log
76
+ running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; }
77
+ complete() {
78
+ grep -q "\"event\": \"evaluation\".*\"step\": $steps\|\"step\": $steps.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \
79
+ || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null
80
+ }
81
+ overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; }
82
+ local restarts=0 seen; seen=$(overflows)
83
+ if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$1" resume "${@:2}"; else launch "$1" fresh "${@:2}"; fi
84
+ sleep 240
85
+ while true; do
86
+ if complete; then log "$name complete"; return 0; fi
87
+ if ! running; then
88
+ local current; current=$(overflows)
89
+ if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then
90
+ restarts=$((restarts + 1)); seen=$current
91
+ log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
92
+ launch "$1" resume "${@:2}"; sleep 240
93
+ else
94
+ log "$name died WITHOUT a new overflow (or budget exhausted); stopping the chain"; return 1
95
+ fi
96
+ fi
97
+ sleep 60
98
+ done
99
+ }
100
+
101
+ run_eval() { log "eval: $*"; CUDA_VISIBLE_DEVICES=$GPU $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; }
102
+ stage_evals() { # run tag tta
103
+ run_eval eval_v7_external.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_external_v1.json
104
+ run_eval eval_full_frame.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_last_fullframe_whole_v1.json --tta 1 $WHOLE
105
+ run_eval eval_full_frame.py --run-dir outputs/phase2_v7/$1 --checkpoint best.pt --output outputs/v7_${2}_best_fullframe_whole_v1.json --tta 1 $WHOLE
106
+ if [ "$3" = "8" ]; then
107
+ run_eval eval_full_frame.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_last_fullframe_whole_tta2_v1.json --tta 2 $WHOLE
108
+ run_eval eval_full_frame.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_last_scene008_tta8_v1.json --tta 8 --groups noise_locked_scene008
109
+ fi
110
+ }
111
+
112
+ A=uformer_v11a_256_$TAG; B=uformer_v11b_320_$TAG; C=uformer_v11c_384_$TAG
113
+ log "warm start $WARM sha=$(sha256sum $WARM | cut -d' ' -f1) phase1 sha=$PHASE1_SHA GPU=$GPU"
114
+ supervise $A 256 "$BATCH_A" "$STEPS_A" "$LR_A" 0,1000,2000,4000,6000,8000,10000,12000,14000,16000,18000,20000 5000,10000,15000,20000 "$WARM" || exit 1
115
+ stage_evals $A v11a$TAG 1
116
+ supervise $B 320 "$BATCH_B" "$STEPS_B" "$LR_B" 0,1000,2000,3000,4000,5000,6000 3000,6000 outputs/phase2_v7/$A/last.pt || exit 1
117
+ stage_evals $B v11b$TAG 1
118
+ supervise $C 384 "$BATCH_C" "$STEPS_C" "$LR_C" 0,1000,2000,3000,4000,5000,6000 3000,6000 outputs/phase2_v7/$B/last.pt || exit 1
119
+ stage_evals $C v11c$TAG 8
120
+ log "chain finished"
dataset/phase1_noise_20260906/code/run_uformer_v8a.sh ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # v8a: Phase-2 on Phase-1 v5 — A recipe (clean prior + tail 6) + whole-frame
3
+ # context (B) + global exposure controllable head + exposure-diverse identity
4
+ # pairs (Snow100K gt pool); chroma loss space = uv. Warm-start from A best.
5
+ # Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt).
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_NAME=uformer_v8a_8k_seed42
9
+ RUN_DIR=outputs/phase2_v7/$RUN_NAME
10
+ LOG=outputs/phase2_v7/uformer_v8a_train.log
11
+ PY=/home/admin_mcn/anaconda3/bin/python
12
+ MAX_RESTARTS=20
13
+ FINAL_STEP=8000
14
+ WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt
15
+ WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1)
16
+ PHASE1=${PHASE1_CKPT:-outputs/phase1_v5/graph_encoder_best.pt}
17
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
18
+
19
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; }
20
+ is_complete() {
21
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
22
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
23
+ }
24
+
25
+ launch() {
26
+ if [ "$1" = "fresh" ]; then
27
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
28
+ else
29
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
30
+ fi
31
+ # shellcheck disable=SC2086
32
+ CUDA_VISIBLE_DEVICES=0 nohup "$PY" \
33
+ train_phase2_unified_v7.py \
34
+ --backbone uformer --timesteps 2 \
35
+ $SOURCE_FLAGS \
36
+ --phase1-checkpoint $PHASE1 \
37
+ --phase1-sha256 $PHASE1_SHA \
38
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
39
+ --output-dir "$RUN_DIR" \
40
+ --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
41
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
42
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
43
+ --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \
44
+ --photometric-head --photometric-dropout 0.15 \
45
+ --identity-exposure-jitter 0.9 \
46
+ --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \
47
+ --kappa 0.11607981286942959 \
48
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
49
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
50
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
51
+ --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \
52
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
53
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
54
+ --milestone-steps 4000 \
55
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
56
+ }
57
+
58
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
59
+
60
+ restarts=0
61
+ seen_overflows=$(overflow_count)
62
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA"
63
+ launch fresh
64
+ sleep 90
65
+
66
+ while true; do
67
+ if is_complete; then
68
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
69
+ break
70
+ fi
71
+ if ! is_running; then
72
+ current=$(overflow_count)
73
+ if [ "$current" -gt "$seen_overflows" ]; then
74
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
75
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
76
+ break
77
+ fi
78
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
79
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
80
+ break
81
+ fi
82
+ seen_overflows=$current
83
+ restarts=$((restarts + 1))
84
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
85
+ launch resume
86
+ sleep 90
87
+ else
88
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
89
+ break
90
+ fi
91
+ fi
92
+ sleep 45
93
+ done
dataset/phase1_noise_20260906/code/run_uformer_v8b.sh ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # v8b: Phase-2 on Phase-1 v5 — A recipe (clean prior + tail 6) + whole-frame
3
+ # context (B) + global exposure controllable head + exposure-diverse identity
4
+ # pairs (Snow100K gt pool); chroma loss space = hv. Warm-start from A best.
5
+ # Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt).
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_NAME=uformer_v8b_8k_seed42
9
+ RUN_DIR=outputs/phase2_v7/$RUN_NAME
10
+ LOG=outputs/phase2_v7/uformer_v8b_train.log
11
+ PY=/home/admin_mcn/anaconda3/bin/python
12
+ MAX_RESTARTS=20
13
+ FINAL_STEP=8000
14
+ WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt
15
+ WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1)
16
+ PHASE1=${PHASE1_CKPT:-outputs/phase1_v5/graph_encoder_best.pt}
17
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
18
+
19
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; }
20
+ is_complete() {
21
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
22
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
23
+ }
24
+
25
+ launch() {
26
+ if [ "$1" = "fresh" ]; then
27
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
28
+ else
29
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
30
+ fi
31
+ # shellcheck disable=SC2086
32
+ CUDA_VISIBLE_DEVICES=1 nohup "$PY" \
33
+ train_phase2_unified_v7.py \
34
+ --backbone uformer --timesteps 2 \
35
+ $SOURCE_FLAGS \
36
+ --phase1-checkpoint $PHASE1 \
37
+ --phase1-sha256 $PHASE1_SHA \
38
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
39
+ --output-dir "$RUN_DIR" \
40
+ --fine-chroma-weight 0.5 --fine-chroma-space hv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
41
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
42
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
43
+ --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \
44
+ --photometric-head --photometric-dropout 0.15 \
45
+ --identity-exposure-jitter 0.9 \
46
+ --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \
47
+ --kappa 0.11607981286942959 \
48
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
49
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
50
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
51
+ --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \
52
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
53
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
54
+ --milestone-steps 4000 \
55
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
56
+ }
57
+
58
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
59
+
60
+ restarts=0
61
+ seen_overflows=$(overflow_count)
62
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA"
63
+ launch fresh
64
+ sleep 90
65
+
66
+ while true; do
67
+ if is_complete; then
68
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
69
+ break
70
+ fi
71
+ if ! is_running; then
72
+ current=$(overflow_count)
73
+ if [ "$current" -gt "$seen_overflows" ]; then
74
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
75
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
76
+ break
77
+ fi
78
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
79
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
80
+ break
81
+ fi
82
+ seen_overflows=$current
83
+ restarts=$((restarts + 1))
84
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
85
+ launch resume
86
+ sleep 90
87
+ else
88
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
89
+ break
90
+ fi
91
+ fi
92
+ sleep 45
93
+ done
dataset/phase1_noise_20260906/code/run_uformer_v8c.sh ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # v8c: identical recipe to v8a (uv chroma) but conditioned on Phase-1 v5b
3
+ # (HVI photometric branch, real-snow OOD). Isolates the Phase-1 choice vs v8a
4
+ # (ll_v3). Warm-start from A best (trunk was trained under ll_v3 conditioning).
5
+ # Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt).
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_NAME=uformer_v8c_8k_seed42
9
+ RUN_DIR=outputs/phase2_v7/$RUN_NAME
10
+ LOG=outputs/phase2_v7/uformer_v8c_train.log
11
+ PY=/home/admin_mcn/anaconda3/bin/python
12
+ MAX_RESTARTS=20
13
+ FINAL_STEP=8000
14
+ WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt
15
+ WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1)
16
+ PHASE1=${PHASE1_CKPT:-outputs/phase1_v5b/graph_encoder_best.pt}
17
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
18
+
19
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; }
20
+ is_complete() {
21
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
22
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
23
+ }
24
+
25
+ launch() {
26
+ if [ "$1" = "fresh" ]; then
27
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
28
+ else
29
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
30
+ fi
31
+ # shellcheck disable=SC2086
32
+ CUDA_VISIBLE_DEVICES=1 nohup "$PY" \
33
+ train_phase2_unified_v7.py \
34
+ --backbone uformer --timesteps 2 \
35
+ $SOURCE_FLAGS \
36
+ --phase1-checkpoint $PHASE1 \
37
+ --phase1-sha256 $PHASE1_SHA \
38
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
39
+ --output-dir "$RUN_DIR" \
40
+ --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
41
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
42
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
43
+ --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \
44
+ --photometric-head --photometric-dropout 0.15 \
45
+ --identity-exposure-jitter 0.9 \
46
+ --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \
47
+ --kappa 0.11607981286942959 \
48
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
49
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
50
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
51
+ --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \
52
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
53
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
54
+ --milestone-steps 4000 \
55
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
56
+ }
57
+
58
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
59
+
60
+ restarts=0
61
+ seen_overflows=$(overflow_count)
62
+ echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA"
63
+ launch fresh
64
+ sleep 90
65
+
66
+ while true; do
67
+ if is_complete; then
68
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
69
+ break
70
+ fi
71
+ if ! is_running; then
72
+ current=$(overflow_count)
73
+ if [ "$current" -gt "$seen_overflows" ]; then
74
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
75
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
76
+ break
77
+ fi
78
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
79
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
80
+ break
81
+ fi
82
+ seen_overflows=$current
83
+ restarts=$((restarts + 1))
84
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
85
+ launch resume
86
+ sleep 90
87
+ else
88
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
89
+ break
90
+ fi
91
+ fi
92
+ sleep 45
93
+ done
dataset/phase1_noise_20260906/code/run_uformer_v9b.sh ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # v9b: Phase-2 on Phase-1 v5f — A recipe + whole-frame context (B) + global
3
+ # exposure controllable head + exposure-diverse identity pairs (Snow100K gt);
4
+ # chroma loss space = uv. Warm-start from A best. Pairs with v9a (plain A
5
+ # recipe on the same Phase-1) to separate 'better Phase-1' from 'v8 features'.
6
+ # Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt).
7
+ set -u
8
+ cd /home/admin_mcn/scdc_ban
9
+ RUN_NAME=uformer_v9b_8k_seed42
10
+ RUN_DIR=outputs/phase2_v7/$RUN_NAME
11
+ LOG=outputs/phase2_v7/uformer_v9b_train.log
12
+ PY=/home/admin_mcn/anaconda3/bin/python
13
+ MAX_RESTARTS=20
14
+ FINAL_STEP=8000
15
+ WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt
16
+ WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1)
17
+ PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt}
18
+ PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1)
19
+
20
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; }
21
+ is_complete() {
22
+ grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \
23
+ "$RUN_DIR/metrics.jsonl" 2>/dev/null
24
+ }
25
+
26
+ launch() {
27
+ if [ "$1" = "fresh" ]; then
28
+ SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema"
29
+ else
30
+ SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt"
31
+ fi
32
+ # shellcheck disable=SC2086
33
+ # The whole-frame context path peaks at ~22 GB of the 24 GB card with
34
+ # batch 8, which OOMs as soon as a resume adds the optimizer moments up
35
+ # front. Half the micro-batch, twice the accumulation: same effective
36
+ # batch 16, ~11 GB peak.
37
+ CUDA_VISIBLE_DEVICES=1 PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 nohup "$PY" \
38
+ train_phase2_unified_v7.py \
39
+ --backbone uformer --timesteps 2 \
40
+ $SOURCE_FLAGS \
41
+ --phase1-checkpoint $PHASE1 \
42
+ --phase1-sha256 $PHASE1_SHA \
43
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
44
+ --output-dir "$RUN_DIR" \
45
+ --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \
46
+ --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \
47
+ --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \
48
+ --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \
49
+ --photometric-head --photometric-dropout 0.15 \
50
+ --identity-exposure-jitter 0.9 \
51
+ --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \
52
+ --kappa 0.11607981286942959 \
53
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
54
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
55
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
56
+ --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \
57
+ --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \
58
+ --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \
59
+ --milestone-steps 4000 \
60
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
61
+ }
62
+
63
+ overflow_count() { local n; n=$(grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null | head -n 1); echo "${n:-0}"; }
64
+
65
+ restarts=0
66
+ seen_overflows=$(overflow_count)
67
+ if [ -f "$RUN_DIR/overflow_recovery.pt" ]; then
68
+ echo "[supervisor] resuming from an existing overflow_recovery.pt phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows in log: $seen_overflows)"
69
+ launch resume
70
+ else
71
+ echo "[supervisor] fresh launch phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows in log: $seen_overflows)"
72
+ launch fresh
73
+ fi
74
+ sleep 90
75
+
76
+ while true; do
77
+ if is_complete; then
78
+ echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting"
79
+ break
80
+ fi
81
+ if ! is_running; then
82
+ current=$(overflow_count)
83
+ if [ "$current" -gt "$seen_overflows" ]; then
84
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
85
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
86
+ break
87
+ fi
88
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
89
+ echo "[supervisor] overflow logged but no recovery checkpoint; exiting"
90
+ break
91
+ fi
92
+ seen_overflows=$current
93
+ restarts=$((restarts + 1))
94
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
95
+ launch resume
96
+ sleep 90
97
+ else
98
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
99
+ break
100
+ fi
101
+ fi
102
+ sleep 45
103
+ done
dataset/phase1_noise_20260906/code/run_v12_mi325x.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # v12 on the MI325X host, ONE GPU (default 5):
3
+ # stage 0 Phase-1 v6 = v5f recipe + oriented Haar bands (rain vs snow/noise)
4
+ # + root weight 1.0 (clean images collapse to the root in global space)
5
+ # + OOD global margin 0.25 (snow away from known-type centroids)
6
+ # stage 1+ Phase-2 v11 recipe chained on Phase-1 v6 (run_uformer_v11_mi325x.sh, TAG=v12)
7
+ set -u
8
+ cd /home/vunguyen/SCDC
9
+ PY=/home/vunguyen/miniforge3/envs/mavt/bin/python
10
+ export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data
11
+ export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1
12
+ GPU=${GPU:-5}
13
+ NAME=phase1_v6
14
+ CACHE=outputs/phase1_cache/sidd_native_256
15
+ log() { echo "[v12 $(date +%H:%M:%S)] $*"; }
16
+
17
+ COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \
18
+ --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \
19
+ --workers 12 --no-amp --seed 42 \
20
+ --photometric --photometric-dim 128 --photometric-weight 0.5 \
21
+ --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \
22
+ --ood-real-root $SCDC_DATA_ROOT/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \
23
+ --extra-clean-root $SCDC_DATA_ROOT/Snow100K/train/all/gt --extra-null-weight 0.05 \
24
+ --reside-limit 5000 --reside-val-count 100 --run-final-test \
25
+ --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \
26
+ --crop-select random --severity-floor 0.05 \
27
+ --ll-oriented-bands --root-weight 1.0 --ood-global-margin-weight 0.25"
28
+
29
+ mkdir -p outputs/$NAME
30
+ [ -f outputs/$NAME/severity_calibration.json ] || cp outputs/phase1_v5f/severity_calibration.json outputs/$NAME/ 2>/dev/null
31
+ if ! grep -q "Training complete" outputs/${NAME}_train.log 2>/dev/null; then
32
+ log "stage 0: Phase-1 v6 on GPU$GPU"
33
+ # shellcheck disable=SC2086
34
+ CUDA_VISIBLE_DEVICES=$GPU $PY -u train_graph_encoder_v2.py $COMMON --output-dir outputs/$NAME > outputs/${NAME}_train.log 2>&1
35
+ grep -q "Training complete" outputs/${NAME}_train.log || { log "Phase-1 v6 did not finish; see outputs/${NAME}_train.log"; exit 1; }
36
+ fi
37
+ log "Phase-1 v6 done: $(grep -o 'best.*' outputs/${NAME}_train.log | tail -n 1 | cut -c1-120)"
38
+ [ -f outputs/$NAME/graph_encoder_best.pt ] || { log "no graph_encoder_best.pt"; exit 1; }
39
+ log "stage 1+: Phase-2 v12 chain on GPU$GPU"
40
+ PHASE1_CKPT=outputs/$NAME/graph_encoder_best.pt TAG=v12 GPU=$GPU bash run_uformer_v11_mi325x.sh
dataset/phase1_noise_20260906/code/run_v8_after_v5.sh ADDED
@@ -0,0 +1,91 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Chain: wait for the Phase-1 v5 candidates to finish, run the sanity
3
+ # dashboard + real-snow gate on each, pick the best passing candidate, then
4
+ # launch the two Phase-2 v8 supervisors (v8a GPU0 = UV chroma, v8b GPU1 = HV
5
+ # chroma) on it. Stops before spending 2x8h GPU when no candidate passes.
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ PY=/home/admin_mcn/anaconda3/bin/python
9
+ CANDIDATES=${CANDIDATES:-"phase1_v5 phase1_v5b"}
10
+
11
+ wait_for() { # $1 = run name
12
+ local dir=outputs/$1 log=outputs/$1_train.log
13
+ while true; do
14
+ if [ -f "$dir/locked_test_metrics.json" ] && grep -q "Training complete" "$log" 2>/dev/null; then return 0; fi
15
+ if grep -q "Traceback" "$log" 2>/dev/null && ! pgrep -f "[t]rain_graph_encoder_v2.py.*$1" >/dev/null; then
16
+ local age=$(( $(date +%s) - $(stat -c %Y "$log") ))
17
+ if [ "$age" -gt 120 ]; then echo "[chain] $1 crashed (log idle ${age}s)"; return 1; fi
18
+ fi
19
+ sleep 120
20
+ done
21
+ }
22
+
23
+ gate_for() { # $1 = run name ; writes outputs/$1_gate.json ; prints pass/score
24
+ local name=$1 ckpt=outputs/$1/graph_encoder_best.pt
25
+ CUDA_VISIBLE_DEVICES=0 $PY visualize_phase1_graph.py --checkpoint $ckpt --output-dir outputs/phase1_vis/$name > outputs/phase1_vis_$name.log 2>&1
26
+ CAND=$name CUDA_VISIBLE_DEVICES=0 $PY - <<'PYEOF' > outputs/${name}_gate.log 2>&1
27
+ import glob, hashlib, json, math, os, torch, numpy as np
28
+ from pathlib import Path
29
+ from PIL import Image
30
+ import train_phase2_graph_resshift_v4 as v4
31
+ from visualize_phase1_graph import encode, NODES
32
+ name = os.environ["CAND"]
33
+ files = sorted(glob.glob("/home/admin_mcn/data/Snow100K/realistic/**/*.jpg", recursive=True))
34
+ def load(f):
35
+ im = Image.open(f).convert("RGB"); w, h = im.size; s = 256 / min(w, h)
36
+ if s > 1: im = im.resize((max(256, math.ceil(w * s)), max(256, math.ceil(h * s))), Image.LANCZOS); w, h = im.size
37
+ l, t = (w - 256) // 2, (h - 256) // 2
38
+ return torch.from_numpy(np.asarray(im.crop((l, t, l + 256, t + 256)), dtype=np.float32) / 255.).permute(2, 0, 1)
39
+ imgs = torch.stack([load(f) for f in files])
40
+ ck = Path("outputs/%s/graph_encoder_best.pt" % name)
41
+ p1, _ = v4.build_frozen_phase1(ck, hashlib.sha256(ck.read_bytes()).hexdigest(), torch.device("cuda"))
42
+ enc = encode(p1, imgs.cuda())
43
+ route = dict(zip(NODES, enc["routing"].mean(0).tolist()))
44
+ summary = json.load(open("outputs/phase1_vis/%s/summary.json" % name))
45
+ conf = summary["confusion"]
46
+ row = lambda prefix: next(v for k, v in conf.items() if k.startswith(prefix))
47
+ hist = json.load(open("outputs/%s/history.json" % name))
48
+ best_f1 = max(e["val"].get("macro_f1", 0.0) for e in hist if "val" in e)
49
+ gates = {
50
+ "snow_real_free": (route["free1"] + route["free2"], 0.70, ">="),
51
+ # not worse than ll_v3 (0.46 haze->rain on the same val); the +0.3 dB
52
+ # claim for v8 does not depend on Phase-1 routing improving, only on it
53
+ # not regressing and on photometric_state existing.
54
+ "haze_to_rain_max": (row("Haze input")["rain"], 0.46, "<="),
55
+ "rain_to_rain_min": (row("Rain input")["rain"], 0.55, ">="),
56
+ "lowlight_to_lowlight_min": (row("Low-light input")["lowlight"], 0.85, ">="),
57
+ }
58
+ passed = {k: (v[0] >= v[1] if v[2] == ">=" else v[0] <= v[1]) for k, v in gates.items()}
59
+ report = {"candidate": name, "sha256": hashlib.sha256(ck.read_bytes()).hexdigest(), "snow_real_routing": route,
60
+ "gates": {k: {"value": v[0], "threshold": v[1], "pass": passed[k]} for k, v in gates.items()},
61
+ "n_pass": int(sum(passed.values())), "pass": bool(all(passed.values())), "best_val_macro_f1": best_f1,
62
+ "noise_recall": row("Noise input")["noise"]}
63
+ Path("outputs/%s_gate.json" % name).write_text(json.dumps(report, indent=2))
64
+ print(json.dumps(report))
65
+ PYEOF
66
+ $PY -c "import json;d=json.load(open('outputs/${name}_gate.json'));print('%d %d %.4f'%(int(d['pass']),d['n_pass'],d['best_val_macro_f1']))"
67
+ }
68
+
69
+ best_name=""; best_key=""
70
+ for cand in $CANDIDATES; do
71
+ echo "[chain] waiting for $cand"
72
+ if ! wait_for $cand; then continue; fi
73
+ sleep 20
74
+ echo "[chain] $cand done: $(sha256sum outputs/$cand/graph_encoder_best.pt | cut -c1-16); dashboard + gate"
75
+ read -r pass npass f1 <<< "$(gate_for $cand)"
76
+ echo "[chain] $cand gate pass=$pass n_pass=$npass best_val_f1=$f1 (outputs/${cand}_gate.json)"
77
+ key=$(printf "%d.%d.%s" "$pass" "$npass" "$f1")
78
+ if [ -z "$best_name" ] || [ "$(printf '%s\n%s\n' "$best_key" "$key" | sort -t. -k1,1n -k2,2n -k3,3n | tail -1)" = "$key" ]; then
79
+ best_name=$cand; best_key=$key
80
+ fi
81
+ done
82
+ if [ -z "$best_name" ]; then echo "[chain] no candidate finished; aborting"; exit 1; fi
83
+ if [ "${best_key%%.*}" != "1" ]; then
84
+ echo "[chain] GATE FAIL for every candidate (best=$best_name key=$best_key); NOT launching v8"; exit 2
85
+ fi
86
+ export PHASE1_CKPT=outputs/$best_name/graph_encoder_best.pt
87
+ echo "[chain] GATE PASS -> $best_name ($PHASE1_CKPT); launching v8a (GPU0) and v8b (GPU1)"
88
+ nohup bash run_uformer_v8a.sh > outputs/phase2_v7/uformer_v8a_supervisor.log 2>&1 < /dev/null &
89
+ sleep 120
90
+ nohup bash run_uformer_v8b.sh > outputs/phase2_v7/uformer_v8b_supervisor.log 2>&1 < /dev/null &
91
+ echo "[chain] both supervisors launched"
dataset/phase1_noise_20260906/code/run_v8_postrun.sh ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # After both v8 supervisors finish: per-run external eval, global-knob probe
3
+ # (how much of the oracle exposure gain the head captured), scene008 tone
4
+ # probe, qualitative grids; then the Phase-2 dose sweep for the head.
5
+ set -u
6
+ cd /home/admin_mcn/scdc_ban
7
+ PY=/home/admin_mcn/anaconda3/bin/python
8
+ done_run() { grep -q "run complete" "outputs/phase2_v7/uformer_$1_supervisor.log" 2>/dev/null; }
9
+ dead_run() { grep -qE "not restarting|exhausted|no recovery" "outputs/phase2_v7/uformer_$1_supervisor.log" 2>/dev/null; }
10
+ A_TAG=${A_TAG:-v8a}; B_TAG=${B_TAG:-v8b}
11
+ echo "[postrun] waiting for $A_TAG and $B_TAG supervisors"
12
+ while true; do
13
+ a_ok=0; b_ok=0
14
+ if done_run $A_TAG || dead_run $A_TAG; then a_ok=1; fi
15
+ if done_run $B_TAG || dead_run $B_TAG; then b_ok=1; fi
16
+ if [ "$a_ok" = 1 ] && [ "$b_ok" = 1 ]; then break; fi
17
+ sleep 300
18
+ done
19
+ sleep 60
20
+ pkill -f "[t]rain_phase2_unified_v7.py.*uformer_v8" 2>/dev/null; sleep 20
21
+ for pair in "$A_TAG 0" "$B_TAG 1"; do
22
+ set -- $pair; TAG=$1; GPU=$2; R=outputs/phase2_v7/uformer_${TAG}_8k_seed42
23
+ if [ ! -f "$R/best.pt" ]; then echo "[postrun] $TAG has no best.pt; skipping"; continue; fi
24
+ (
25
+ CUDA_VISIBLE_DEVICES=$GPU $PY eval_v7_external.py --run-dir $R --output outputs/v7_${TAG}_external_v1.json
26
+ CUDA_VISIBLE_DEVICES=$GPU $PY eval_v7_external.py --run-dir $R --output outputs/v7_${TAG}_external_pdose0.json --photometric-dose 0
27
+ CUDA_VISIBLE_DEVICES=$GPU $PY probe_global_knob.py --run-dir $R --output outputs/global_knob_probe_${TAG}.json
28
+ CUDA_VISIBLE_DEVICES=$GPU $PY probe_scene008_tone.py --run-dir $R --output outputs/v7_${TAG}_scene008_tone.json --skip-val-baseline
29
+ CUDA_VISIBLE_DEVICES=$GPU $PY visualize_v7_uformer.py --run-dir $R --per-domain 3
30
+ CUDA_VISIBLE_DEVICES=$GPU $PY visualize_scene008.py --run-dir $R --output $R/vis/scene008.png --count 3
31
+ echo "[postrun] $TAG done"
32
+ ) > outputs/phase2_v7/${TAG}_postrun.log 2>&1 &
33
+ done
34
+ wait
35
+ echo "POSTRUN-ALL-DONE"
dataset/phase1_noise_20260906/code/supervise_uformer16k.sh ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Auto-resume supervisor for outputs/phase2_v7/uformer16k_seed42.
3
+ # Relaunches training from overflow_recovery.pt after each designed
4
+ # RecoverableAmpOverflow exit; stops on completion (step 16000 evaluated),
5
+ # on any non-overflow failure, or after MAX_RESTARTS.
6
+ set -u
7
+ cd /home/admin_mcn/scdc_ban
8
+ RUN_DIR=outputs/phase2_v7/uformer16k_seed42
9
+ LOG=outputs/phase2_v7/uformer16k_train.log
10
+ PY=/home/admin_mcn/anaconda3/bin/python
11
+ MAX_RESTARTS=20
12
+ restarts=0
13
+
14
+ is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer16k_seed42" >/dev/null; }
15
+ is_complete() { grep -q '"event": "evaluation".*"step": 16000\|"step": 16000.*"event": "evaluation"' "$RUN_DIR/metrics.jsonl" 2>/dev/null; }
16
+
17
+ launch() {
18
+ nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \
19
+ train_phase2_unified_v7.py \
20
+ --ddp --ddp-find-unused --backbone uformer --timesteps 2 \
21
+ --resume "$RUN_DIR/overflow_recovery.pt" \
22
+ --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \
23
+ --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \
24
+ --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \
25
+ --output-dir "$RUN_DIR" \
26
+ --fine-chroma-weight 0.5 --fine-vgg-weight 0.1 \
27
+ --kappa 0.11607981286942959 \
28
+ --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \
29
+ --eta-end 0.99 --min-noise 0.2 --power 0.3 \
30
+ --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \
31
+ --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \
32
+ --learning-rate 5e-5 --max-steps 16000 --run-until-step 16000 \
33
+ --eval-steps 0,1000,2000,3000,4000,6000,8000,10000,12000,14000,16000 \
34
+ --milestone-steps 4000,8000,12000 \
35
+ --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 &
36
+ }
37
+
38
+ overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; }
39
+
40
+ seen_overflows=$(overflow_count)
41
+ echo "[supervisor] start; overflows so far: $seen_overflows"
42
+
43
+ while true; do
44
+ if is_complete; then
45
+ echo "[supervisor] run complete (eval @16000 present); exiting"
46
+ break
47
+ fi
48
+ if ! is_running; then
49
+ current=$(overflow_count)
50
+ if [ "$current" -gt "$seen_overflows" ] || [ "$restarts" -eq 0 ]; then
51
+ if [ "$restarts" -ge "$MAX_RESTARTS" ]; then
52
+ echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting"
53
+ break
54
+ fi
55
+ if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then
56
+ echo "[supervisor] no recovery checkpoint; refusing to relaunch"
57
+ break
58
+ fi
59
+ seen_overflows=$current
60
+ restarts=$((restarts + 1))
61
+ echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)"
62
+ launch
63
+ sleep 90
64
+ else
65
+ echo "[supervisor] process died WITHOUT a new overflow; not restarting"
66
+ break
67
+ fi
68
+ fi
69
+ sleep 45
70
+ done
dataset/phase1_noise_20260906/code/test_train_graph_encoder_v2.py ADDED
@@ -0,0 +1,908 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ from types import SimpleNamespace
3
+
4
+ import math
5
+
6
+ import pytest
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ import train_graph_encoder_v2 as v2
11
+ from src.models.graph_encoder.representation import aggregate_graph_condition
12
+
13
+
14
+ def _record(index, degradation="haze", group=None, dataset="RESIDE"):
15
+ source = str(index)
16
+ return v2.PairRecord(
17
+ degraded=Path("/deg") / (source + ".png"),
18
+ clean=Path("/clean") / (source + ".png"),
19
+ degradation=degradation,
20
+ dataset=dataset,
21
+ source_id=source,
22
+ split_group=group or source,
23
+ )
24
+
25
+
26
+ def _png(path, value=0):
27
+ path.parent.mkdir(parents=True, exist_ok=True)
28
+ v2.Image.new("RGB", (12, 8), color=(value, value, value)).save(path)
29
+
30
+
31
+ def test_real_branch_order_preserves_deployed_positional_semantics():
32
+ assert v2.BRANCH_ORDER == ("rain", "noise", "haze", "lowlight")
33
+ assert v2.BRANCH_TO_INDEX == {
34
+ "rain": 0,
35
+ "noise": 1,
36
+ "haze": 2,
37
+ "lowlight": 3,
38
+ }
39
+
40
+
41
+ def test_reside_first_5000_has_source_isolated_first_100_validation():
42
+ records = []
43
+ records.extend(_record(i, group="val-a") for i in range(95))
44
+ records.extend(_record(i + 95, group="val-leak") for i in range(5))
45
+ records.extend(_record(i + 100, group="val-leak") for i in range(5))
46
+ records.extend(_record(i + 105) for i in range(4895))
47
+
48
+ train, val = v2.split_reside_records(records, limit=5000, val_count=100)
49
+
50
+ assert len(val) == 100
51
+ assert len(train) == 4895
52
+ assert {r.split_group for r in train}.isdisjoint(
53
+ {r.split_group for r in val}
54
+ )
55
+
56
+
57
+ def test_sidd_split_is_scene_disjoint_with_audited_live_counts():
58
+ scene_counts = {
59
+ "001": 28, "002": 15, "003": 15, "004": 15, "005": 19,
60
+ "006": 19, "007": 20, "008": 20, "009": 6, "010": 3,
61
+ }
62
+ records = []
63
+ index = 0
64
+ for scene, count in scene_counts.items():
65
+ for _ in range(count):
66
+ records.append(_record(index, "noise", scene, "SIDD"))
67
+ index += 1
68
+
69
+ train, val, locked = v2.split_sidd_records(records)
70
+
71
+ assert (len(train), len(val), len(locked)) == (121, 19, 20)
72
+ groups = [{r.split_group for r in split} for split in (train, val, locked)]
73
+ assert groups[0].isdisjoint(groups[1])
74
+ assert groups[0].isdisjoint(groups[2])
75
+ assert groups[1].isdisjoint(groups[2])
76
+ assert groups[1] == {"006"}
77
+ assert groups[2] == {"008"}
78
+
79
+
80
+ def test_sidd_scene_number_is_second_folder_token():
81
+ assert v2.sidd_scene_number("0192_009_IP_00100_00200_3200_N") == "009"
82
+ with pytest.raises(ValueError, match="SIDD source directory"):
83
+ v2.sidd_scene_number("malformed")
84
+
85
+
86
+ def test_live_layout_discovery_and_source_leakage_guard(tmp_path):
87
+ lol = tmp_path / "lol"
88
+ _png(lol / "Train/Input/00001.png", 10)
89
+ _png(lol / "Train/GT/00001.png", 20)
90
+ assert len(v2.discover_lol_records(lol, "Train")) == 1
91
+
92
+ reside = tmp_path / "reside"
93
+ _png(reside / "clear/0001.jpg", 20)
94
+ _png(reside / "hazy/0001_0.8_0.1.jpg", 10)
95
+ assert v2.discover_reside_records(reside)[0].split_group == "0001"
96
+
97
+ sidd = tmp_path / "sidd"
98
+ for scene in range(1, 11):
99
+ source = sidd / ("%04d_%03d_IP_00100_00200_3200_N" % (scene, scene))
100
+ _png(source / "NOISY_SRGB_010.PNG", 10)
101
+ _png(source / "GT_SRGB_010.PNG", 20)
102
+ sidd_records = v2.discover_sidd_records(sidd)
103
+ parts = v2.split_sidd_records(sidd_records)
104
+ assert [len(part) for part in parts] == [8, 1, 1]
105
+
106
+ shared = _record(0, group="same")
107
+ splits = v2.DataSplits((shared,), (shared,), (), 0)
108
+ with pytest.raises(ValueError, match="source leakage"):
109
+ v2.assert_split_isolation(splits)
110
+
111
+ shared_clean = tmp_path / "shared-clean.png"
112
+ _png(shared_clean, 77)
113
+ train = v2.PairRecord(
114
+ shared_clean, shared_clean, "rain", "Rain13K", "a", "rain-a"
115
+ )
116
+ val = v2.PairRecord(
117
+ shared_clean, shared_clean, "lowlight", "LOLv2", "b", "lol-b"
118
+ )
119
+ with pytest.raises(ValueError, match="clean-content leakage"):
120
+ v2.assert_split_isolation(v2.DataSplits((train,), (val,), (), 0))
121
+
122
+
123
+ def test_rain_adapter_uses_quarantine_and_only_test100_test1200(monkeypatch, tmp_path):
124
+ pairs = []
125
+ for index in range(3):
126
+ degraded = tmp_path / ("d%d.png" % index)
127
+ clean = tmp_path / ("c%d.png" % index)
128
+ _png(degraded, index)
129
+ _png(clean, index + 1)
130
+ pairs.append((degraded, clean))
131
+ captured = {}
132
+
133
+ def fake_loader(root, **kwargs):
134
+ captured.update(kwargs)
135
+ return SimpleNamespace(
136
+ train_pairs=(pairs[0],),
137
+ official_test_pairs={"Test100": (pairs[1],), "Test1200": (pairs[2],)},
138
+ quarantined_train_pair_count=1155,
139
+ )
140
+
141
+ monkeypatch.setattr(v2, "load_rain13k_resized", fake_loader)
142
+ train, val, locked, count = v2.build_rain_records(tmp_path, tmp_path / "q.json")
143
+ assert (len(train), len(val), len(locked), count) == (1, 1, 1, 1155)
144
+ assert captured["max_train_pairs"] == 0
145
+ assert captured["quarantine_manifest"] == tmp_path / "q.json"
146
+
147
+
148
+ def test_build_data_splits_composes_domains_and_checks_counts(monkeypatch, tmp_path):
149
+ rain = _record(1, "rain", "r1", "Rain13K")
150
+ low_train = _record(2, "lowlight", "l1", "LOLv2")
151
+ low_val = _record(3, "lowlight", "l2", "LOLv2")
152
+ haze_train = _record(4, "haze", "h1", "RESIDE")
153
+ haze_val = _record(5, "haze", "h2", "RESIDE")
154
+ noise_train = _record(6, "noise", "n1", "SIDD")
155
+ noise_val = _record(7, "noise", "n2", "SIDD")
156
+ noise_test = _record(8, "noise", "n3", "SIDD")
157
+ monkeypatch.setattr(v2, "build_rain_records", lambda *args: ([rain], [rain], [rain], 1))
158
+ monkeypatch.setattr(
159
+ v2, "discover_lol_records",
160
+ lambda root, split: [low_train] if split == "Train" else [low_val],
161
+ )
162
+ monkeypatch.setattr(v2, "discover_reside_records", lambda root: [haze_train, haze_val])
163
+ monkeypatch.setattr(v2, "split_reside_records", lambda *args: ([haze_train], [haze_val]))
164
+ monkeypatch.setattr(v2, "discover_sidd_records", lambda root: [noise_train, noise_val, noise_test])
165
+ monkeypatch.setattr(
166
+ v2, "split_sidd_records", lambda records: ([noise_train], [noise_val], [noise_test])
167
+ )
168
+ monkeypatch.setattr(v2, "assert_split_isolation", lambda splits: None)
169
+ args = v2.build_parser().parse_args(
170
+ ["--data-root", str(tmp_path), "--allow-count-mismatch"]
171
+ )
172
+ splits = v2.build_data_splits(args)
173
+ assert (len(splits.train), len(splits.val), len(splits.locked_test)) == (4, 4, 2)
174
+
175
+
176
+ def test_sidd_cache_is_main_process_only_and_calibration_is_persisted(tmp_path):
177
+ records = []
178
+ for index, degradation in enumerate(v2.BRANCH_ORDER):
179
+ degraded = tmp_path / degradation / "degraded.png"
180
+ clean = tmp_path / degradation / "clean.png"
181
+ _png(degraded, 40 + index * 10)
182
+ _png(clean, 10)
183
+ records.append(
184
+ v2.PairRecord(
185
+ degraded, clean, degradation,
186
+ "SIDD" if degradation == "noise" else degradation,
187
+ str(index), str(index),
188
+ )
189
+ )
190
+ cache = tmp_path / "cache"
191
+ calibration = {
192
+ name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0}
193
+ for name in v2.BRANCH_ORDER
194
+ }
195
+ dataset = v2.PairDataset(records, 8, calibration, cache)
196
+ dataset.prepare_cache()
197
+ assert len(list(cache.glob("*.png"))) == 2
198
+ sample = dataset[1]
199
+ assert sample["degraded"].shape == (3, 8, 8)
200
+ assert 0 <= sample["severity"] <= 1
201
+
202
+ output = tmp_path / "calibration.json"
203
+ fitted = v2.fit_training_calibration(records, 8, output, cache)
204
+ first_fingerprint = v2.json.loads(output.read_text(encoding="utf-8"))["fingerprint"]
205
+ assert set(fitted) == set(v2.BRANCH_ORDER)
206
+ assert all(values["pixel_q95"] > 0 for values in fitted.values())
207
+ assert v2.fit_training_calibration(records, 8, output, cache) == fitted
208
+
209
+ sidd_record = records[1]
210
+ old_paths = dataset._cache_paths(sidd_record)
211
+ old_mtime = sidd_record.degraded.stat().st_mtime_ns
212
+ _png(sidd_record.degraded, 222)
213
+ v2.os.utime(
214
+ sidd_record.degraded,
215
+ ns=(old_mtime + 1_000_000_000, old_mtime + 1_000_000_000),
216
+ )
217
+ new_paths = dataset._cache_paths(sidd_record)
218
+ assert new_paths != old_paths
219
+ dataset.prepare_cache()
220
+ assert all(path.is_file() for path in new_paths)
221
+ v2.fit_training_calibration(records, 8, output, cache)
222
+ second_fingerprint = v2.json.loads(output.read_text(encoding="utf-8"))["fingerprint"]
223
+ assert second_fingerprint != first_fingerprint
224
+
225
+
226
+ def test_balanced_batch_sampler_is_exact_and_seeded_with_replacement():
227
+ labels = [0, 0, 0, 1, 2, 3]
228
+ sampler_a = v2.BalancedBatchSampler(labels, batch_size=8, steps=3, seed=17)
229
+ sampler_b = v2.BalancedBatchSampler(labels, batch_size=8, steps=3, seed=17)
230
+
231
+ batches_a = list(sampler_a)
232
+ assert batches_a == list(sampler_b)
233
+ assert len(batches_a) == 3
234
+ for batch in batches_a:
235
+ assert [labels[i] for i in batch].count(0) == 2
236
+ assert [labels[i] for i in batch].count(1) == 2
237
+ assert [labels[i] for i in batch].count(2) == 2
238
+ assert [labels[i] for i in batch].count(3) == 2
239
+ with pytest.raises(ValueError, match="divisible"):
240
+ v2.BalancedBatchSampler(labels, batch_size=6, steps=1, seed=17)
241
+
242
+
243
+ def test_severity_proxy_is_deterministic_and_bounded():
244
+ clean = torch.zeros(3, 4, 4)
245
+ degraded = torch.full((3, 4, 4), 0.25)
246
+ first = v2.residual_mae_severity(degraded, clean, 0.1, 0.4)
247
+ second = v2.residual_mae_severity(degraded, clean, 0.1, 0.4)
248
+ assert first.item() == pytest.approx(0.5)
249
+ assert torch.equal(first, second)
250
+ with pytest.raises(ValueError, match="p95"):
251
+ v2.residual_mae_severity(degraded, clean, 0.4, 0.4)
252
+
253
+
254
+ def test_spatial_supervision_rewards_selected_branch_and_suppresses_inactive():
255
+ clean = torch.zeros(2, 3, 8, 8)
256
+ degraded = torch.ones(2, 3, 8, 8)
257
+ labels = torch.tensor([0, 2])
258
+ q95 = torch.ones(4)
259
+ good = torch.zeros(2, 4, 2, 2)
260
+ good[0, 0] = 1
261
+ good[1, 2] = 1
262
+ bad = 1 - good
263
+
264
+ good_loss, good_metrics = v2.spatial_supervision_loss(
265
+ good, degraded, clean, labels, q95
266
+ )
267
+ bad_loss, _ = v2.spatial_supervision_loss(
268
+ bad, degraded, clean, labels, q95
269
+ )
270
+
271
+ assert good_loss < bad_loss
272
+ assert good_metrics["spatial_selected_mae"] == pytest.approx(0.0)
273
+ assert good_metrics["spatial_inactive_activation"] == pytest.approx(0.0)
274
+
275
+
276
+ def test_clean_forward_keeps_bn_statistics_frozen_but_allows_gradients():
277
+ class TinyGraph(nn.Module):
278
+ def __init__(self):
279
+ super().__init__()
280
+ self.bn = nn.BatchNorm2d(3)
281
+
282
+ def forward_student(self, image):
283
+ return self.bn(image)
284
+
285
+ model = TinyGraph().train()
286
+ before = model.bn.running_mean.clone()
287
+ clean = torch.randn(2, 3, 4, 4, requires_grad=True)
288
+
289
+ result = v2.forward_clean_bn_safe(model, clean)
290
+ result.sum().backward()
291
+
292
+ assert torch.equal(model.bn.running_mean, before)
293
+ assert clean.grad is not None
294
+ assert model.training and model.bn.training
295
+
296
+
297
+ def test_free_tokens_are_scaled_by_absolute_posterior_mass():
298
+ class ZeroBranch:
299
+ def get_branch_embedding(self, severity):
300
+ return torch.zeros(severity.shape[0], 1)
301
+
302
+ tokens = torch.tensor([[[0.0], [10.0], [20.0]]])
303
+ routing = torch.tensor([[1.0, 0.0, 0.0]])
304
+ result = aggregate_graph_condition(
305
+ tokens, routing, torch.zeros(1, 1), [ZeroBranch()]
306
+ )
307
+ assert torch.equal(result, torch.zeros_like(result))
308
+
309
+
310
+ def test_semantic_token_affects_condition_only_when_its_route_is_active():
311
+ class ZeroBranch:
312
+ def get_branch_embedding(self, severity):
313
+ return torch.zeros(severity.shape[0], 1)
314
+
315
+ base = torch.tensor([[[1.0], [0.0], [0.0]]])
316
+ changed = torch.tensor([[[3.0], [0.0], [0.0]]])
317
+ active = torch.tensor([[1.0, 0.0, 0.0]])
318
+ inactive = torch.tensor([[0.0, 0.5, 0.5]])
319
+ args = (torch.zeros(1, 1), [ZeroBranch()])
320
+
321
+ assert not torch.equal(
322
+ aggregate_graph_condition(base, active, *args),
323
+ aggregate_graph_condition(changed, active, *args),
324
+ )
325
+ assert torch.equal(
326
+ aggregate_graph_condition(base, inactive, *args),
327
+ aggregate_graph_condition(changed, inactive, *args),
328
+ )
329
+
330
+
331
+ @pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16])
332
+ def test_aggregation_preserves_amp_dtype(dtype):
333
+ class ZeroBranch:
334
+ def get_branch_embedding(self, severity):
335
+ return severity.new_zeros((severity.shape[0], 2))
336
+
337
+ result = aggregate_graph_condition(
338
+ torch.ones(1, 3, 2, dtype=dtype),
339
+ torch.tensor([[1.0, 0.0, 0.0]], dtype=dtype),
340
+ torch.zeros(1, 1, dtype=dtype),
341
+ [ZeroBranch()],
342
+ )
343
+ assert result.dtype == dtype
344
+
345
+
346
+ def test_validation_metrics_include_per_class_and_safe_constant_correlation():
347
+ metrics = v2.compute_validation_metrics(
348
+ labels=[0, 0, 1, 1],
349
+ predictions=[0, 4, 1, 5],
350
+ severity_targets=[0.5, 0.5, 0.2, 0.8],
351
+ severity_predictions=[0.5, 0.5, 0.3, 0.7],
352
+ unknown_routing=[0.1, 0.2, 0.3, 0.4],
353
+ entropies=[0.2, 0.2, 0.4, 0.4],
354
+ losses=[1.0, 1.0, 2.0, 2.0],
355
+ spatial_mae=[0.1, 0.1, 0.2, 0.2],
356
+ inactive_activation=[0.0, 0.0, 0.1, 0.1],
357
+ )
358
+ assert metrics["accuracy"] == 0.5
359
+ assert metrics["macro_f1"] < 1.0
360
+ assert metrics["balanced_accuracy"] == 0.5
361
+ assert len(metrics["confusion_matrix"]) == 4
362
+ assert all(len(row) == 6 for row in metrics["confusion_matrix"])
363
+ assert metrics["per_class"]["rain"]["severity_spearman"] == 0.0
364
+ assert "spatial_selected_mae" in metrics["per_class"]["noise"]
365
+
366
+
367
+ def test_checkpoint_keeps_phase2_schema_and_trainer_state_separate(tmp_path):
368
+ model = nn.Linear(2, 2)
369
+ head = nn.Linear(2, 4)
370
+ payload = v2.make_checkpoint(
371
+ model=model,
372
+ aux_classifier=head,
373
+ optimizer=None,
374
+ scheduler=None,
375
+ scaler=None,
376
+ epoch=0,
377
+ best_score=0.2,
378
+ config={"branch_order": list(v2.BRANCH_ORDER)},
379
+ provenance={"counts": {"train": 1}},
380
+ history=[{"epoch": 0}],
381
+ severity_calibration={"rain": {"p05": 0.1, "p95": 0.5}},
382
+ )
383
+ assert payload["model_state_dict"].keys() == model.state_dict().keys()
384
+ assert "global_type_head" in payload["trainer_state"]
385
+ assert payload["branch_order"] == list(v2.BRANCH_ORDER)
386
+
387
+
388
+ def test_checkpoint_loader_rejects_legacy_aggregation_or_branch_semantics(tmp_path):
389
+ model = nn.Linear(2, 2)
390
+ checkpoint_path = tmp_path / "legacy.pt"
391
+ torch.save(
392
+ {
393
+ "model_state_dict": model.state_dict(),
394
+ "aggregation_version": 1,
395
+ "branch_order": ["blur", "noise", "jpeg", "lowlight"],
396
+ },
397
+ checkpoint_path,
398
+ )
399
+ with pytest.raises(ValueError, match="aggregation_version"):
400
+ v2._load_encoder_checkpoint(checkpoint_path, model, None, torch.device("cpu"))
401
+
402
+
403
+ def test_cli_requires_explicit_final_test_and_has_output_path():
404
+ args = v2.build_parser().parse_args([])
405
+ assert args.output_dir
406
+ assert args.run_final_test is False
407
+
408
+
409
+ def test_checkpoint_selection_is_lexicographic_by_macro_f1():
410
+ better_f1 = {"macro_f1": 0.81, "severity_mae": 0.9, "spatial_selected_mae": 0.9}
411
+ better_aux = {"macro_f1": 0.80, "severity_mae": 0.0, "spatial_selected_mae": 0.0}
412
+ assert v2.selection_key(better_f1) > v2.selection_key(better_aux)
413
+
414
+
415
+ def test_supervised_objective_is_finite_and_backpropagates_all_core_losses():
416
+ def graph(batch=2, dim=4):
417
+ return SimpleNamespace(
418
+ routing_probs=torch.softmax(torch.randn(batch, 6, requires_grad=True), -1),
419
+ severity_coords=torch.sigmoid(torch.randn(batch, 4, requires_grad=True)),
420
+ global_condition=torch.randn(batch, dim, requires_grad=True),
421
+ content_latent=torch.randn(batch, dim, 2, 2, requires_grad=True),
422
+ spatial_maps=torch.sigmoid(torch.randn(batch, 4, 2, 2, requires_grad=True)),
423
+ unknown_residual=torch.randn(batch, dim, requires_grad=True),
424
+ )
425
+
426
+ objective = v2.Phase1GraphObjective(node_dim=4)
427
+ degraded = torch.ones(2, 3, 8, 8)
428
+ clean = torch.zeros_like(degraded)
429
+ labels = torch.tensor([0, 2])
430
+ result = objective(
431
+ graph(), graph(), degraded, clean, labels,
432
+ torch.tensor([0.3, 0.7]), torch.ones(4), torch.zeros(1, 4),
433
+ )
434
+ result["total"].backward()
435
+
436
+ assert torch.isfinite(result["total"])
437
+ for key in ("route", "global_type", "severity", "root", "spatial"):
438
+ assert key in result and torch.isfinite(result[key])
439
+ assert objective.global_type_head.weight.grad is not None
440
+
441
+
442
+ def test_real_encoder_balanced_batch_trains_semantic_tokens_and_strictly_reloads():
443
+ config = v2.GraphConfig(
444
+ latent_channels=16,
445
+ node_dim=32,
446
+ spatial_map_size=(4, 4),
447
+ )
448
+ model = v2.BlindDegradationGraphEncoder(config).train()
449
+ objective = v2.Phase1GraphObjective(node_dim=32)
450
+ clean = torch.rand(4, 3, 16, 16)
451
+ degraded = (clean + 0.1 * torch.rand_like(clean)).clamp(0, 1)
452
+ labels = torch.arange(4)
453
+
454
+ graph_degraded = model.forward_student(degraded)
455
+ graph_clean = v2.forward_clean_bn_safe(model, clean)
456
+ losses = objective(
457
+ graph_degraded, graph_clean, degraded, clean, labels,
458
+ torch.linspace(0.2, 0.8, 4), torch.ones(4), model.clean_root(),
459
+ )
460
+ losses["total"].backward()
461
+
462
+ token_grad = model.token_generator.semantic_tokens.grad
463
+ assert token_grad is not None
464
+ assert torch.isfinite(token_grad).all()
465
+ assert (token_grad.norm(dim=1) > 0).all()
466
+ assert model.token_generator.feat_proj.weight.grad is not None
467
+ assert model.clean_root.embedding.grad is None
468
+ assert torch.equal(
469
+ model.clean_root.embedding,
470
+ torch.zeros_like(model.clean_root.embedding),
471
+ )
472
+ clone = v2.BlindDegradationGraphEncoder(config)
473
+ clone.load_state_dict(model.state_dict(), strict=True)
474
+
475
+
476
+ def test_real_evaluate_train_checkpoint_and_provenance_smoke(tmp_path):
477
+ config = v2.GraphConfig(
478
+ latent_channels=16,
479
+ node_dim=32,
480
+ spatial_map_size=(4, 4),
481
+ )
482
+ model = v2.BlindDegradationGraphEncoder(config)
483
+ objective = v2.Phase1GraphObjective(32)
484
+ batch = {
485
+ "degraded": torch.rand(4, 3, 16, 16),
486
+ "clean": torch.rand(4, 3, 16, 16),
487
+ "label": torch.arange(4),
488
+ "severity": torch.linspace(0.1, 0.9, 4),
489
+ }
490
+ metrics = v2.evaluate(model, [batch], torch.device("cpu"), torch.ones(4))
491
+ assert metrics["sample_count"] == 4
492
+
493
+ optimizer = torch.optim.AdamW(
494
+ list(model.parameters()) + list(objective.parameters()), lr=1e-4
495
+ )
496
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=1)
497
+ scaler = torch.cuda.amp.GradScaler(enabled=False)
498
+ trained = v2.train_one_epoch(
499
+ model, objective, [batch], optimizer, scaler, torch.device("cpu"),
500
+ torch.ones(4), False, 1.0,
501
+ )
502
+ assert torch.isfinite(torch.tensor(trained["total"]))
503
+
504
+ quarantine = tmp_path / "quarantine.json"
505
+ quarantine.write_text("{}", encoding="utf-8")
506
+ args = v2.build_parser().parse_args(
507
+ ["--quarantine-manifest", str(quarantine), "--workers", "0"]
508
+ )
509
+ records = tuple(_record(i, name, dataset=name) for i, name in enumerate(v2.BRANCH_ORDER))
510
+ splits = v2.DataSplits(records, records, records, 3)
511
+ provenance = v2.make_provenance(args, splits)
512
+ run_config = v2._configuration(args, config, v2.LossWeights())
513
+ payload = v2.make_checkpoint(
514
+ model, objective.global_type_head, optimizer, scheduler, scaler,
515
+ 1, 0.5, run_config, provenance, [{"epoch": 0}],
516
+ {name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} for name in v2.BRANCH_ORDER},
517
+ )
518
+ checkpoint = tmp_path / "checkpoint.pt"
519
+ v2._atomic_torch_save(checkpoint, payload)
520
+ loaded = v2._load_encoder_checkpoint(
521
+ checkpoint, model, objective, torch.device("cpu")
522
+ )
523
+ assert loaded["epoch"] == 1
524
+ v2._atomic_write_json(tmp_path / "provenance.json", provenance)
525
+ assert (tmp_path / "provenance.json").is_file()
526
+
527
+
528
+ def test_build_loaders_yields_exactly_balanced_batch(tmp_path):
529
+ records = []
530
+ calibration = {}
531
+ for index, name in enumerate(v2.BRANCH_ORDER):
532
+ degraded = tmp_path / name / "d.png"
533
+ clean = tmp_path / name / "c.png"
534
+ _png(degraded, 30 + index)
535
+ _png(clean, 10)
536
+ records.append(v2.PairRecord(degraded, clean, name, name, str(index), str(index)))
537
+ calibration[name] = {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0}
538
+ splits = v2.DataSplits(tuple(records), tuple(records), (), 0)
539
+ args = v2.build_parser().parse_args(
540
+ [
541
+ "--workers", "0", "--batch-size", "4", "--eval-batch-size", "4",
542
+ "--steps-per-epoch", "1", "--image-size", "8",
543
+ ]
544
+ )
545
+ train_loader, val_loader, _, _ = v2.build_loaders(
546
+ args, splits, calibration, torch.device("cpu"), tmp_path / "cache"
547
+ )
548
+ assert sorted(next(iter(train_loader))["label"].tolist()) == [0, 1, 2, 3]
549
+ assert len(next(iter(val_loader))["label"]) == 4
550
+
551
+
552
+ def test_eval_only_main_writes_config_provenance_and_metrics(monkeypatch, tmp_path):
553
+ checkpoint = tmp_path / "model.pt"
554
+ model = v2.BlindDegradationGraphEncoder(v2.GraphConfig())
555
+ calibration = {
556
+ name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0}
557
+ for name in v2.BRANCH_ORDER
558
+ }
559
+ torch.save(
560
+ {
561
+ "model_state_dict": model.state_dict(),
562
+ "aggregation_version": v2.AGGREGATION_VERSION,
563
+ "branch_order": list(v2.BRANCH_ORDER),
564
+ "severity_calibration": calibration,
565
+ },
566
+ checkpoint,
567
+ )
568
+ quarantine = tmp_path / "quarantine.json"
569
+ quarantine.write_text("{}", encoding="utf-8")
570
+ monkeypatch.setattr(v2, "build_data_splits", lambda args: v2.DataSplits((), (), (), 0))
571
+ monkeypatch.setattr(v2, "_make_eval_loader", lambda *args, **kwargs: [])
572
+ metrics = {
573
+ "accuracy": 0.0, "macro_f1": 0.0, "balanced_accuracy": 0.0,
574
+ "severity_mae": 0.0, "spatial_selected_mae": 0.0,
575
+ }
576
+ monkeypatch.setattr(v2, "evaluate", lambda *args, **kwargs: metrics)
577
+ output = tmp_path / "output"
578
+
579
+ assert v2.main(
580
+ [
581
+ "--eval-only", "--checkpoint", str(checkpoint),
582
+ "--output-dir", str(output), "--device", "cpu", "--workers", "0",
583
+ "--quarantine-manifest", str(quarantine), "--allow-count-mismatch",
584
+ ]
585
+ ) == 0
586
+ assert (output / "config.json").is_file()
587
+ assert (output / "provenance.json").is_file()
588
+ assert (output / "eval_val_metrics.json").is_file()
589
+
590
+
591
+ # ---------------------------------------------------------------------------
592
+ # P1-LL (ll_v3): global low-frequency branch, null/OOD routing, selection
593
+ # ---------------------------------------------------------------------------
594
+
595
+ from src.models.graph_encoder.encoder import ( # noqa: E402
596
+ LLGlobalBranch,
597
+ haar_ll,
598
+ photometric_stats,
599
+ )
600
+
601
+
602
+ def _small_ll_config(**overrides):
603
+ defaults = dict(
604
+ latent_channels=16,
605
+ node_dim=32,
606
+ num_semantic_branches=4,
607
+ num_free_nodes=2,
608
+ use_ll_global=True,
609
+ ll_global_dim=32,
610
+ )
611
+ defaults.update(overrides)
612
+ return v2.GraphConfig(**defaults)
613
+
614
+
615
+ def test_haar_ll_and_photometric_stats_are_finite_and_shaped():
616
+ image = torch.rand(3, 3, 64, 64)
617
+ ll = haar_ll(image)
618
+ assert ll.shape == (3, 3, 32, 32)
619
+ # LL of a constant image is the constant (energy-preserving /2 scaling
620
+ # doubles the mean per level by design of the orthonormal transform).
621
+ stats = photometric_stats(image)
622
+ assert stats.shape == (3, LLGlobalBranch.STATS_DIM)
623
+ assert torch.isfinite(stats).all()
624
+
625
+
626
+ def test_ll_branch_is_deterministic_and_sized():
627
+ torch.manual_seed(0)
628
+ branch = LLGlobalBranch(output_dim=32)
629
+ branch.eval()
630
+ image = torch.rand(2, 3, 64, 64)
631
+ with torch.no_grad():
632
+ first = branch(image)
633
+ second = branch(image)
634
+ assert first.shape == (2, 32)
635
+ assert torch.equal(first, second)
636
+
637
+
638
+ def test_ll_config_gates_state_dict_and_preserves_phase2_contract():
639
+ legacy = v2.BlindDegradationGraphEncoder(
640
+ v2.GraphConfig(latent_channels=16, node_dim=32)
641
+ )
642
+ assert not any("ll_" in name for name in legacy.state_dict())
643
+
644
+ model = v2.BlindDegradationGraphEncoder(_small_ll_config())
645
+ names = model.state_dict().keys()
646
+ assert any(name.startswith("ll_branch.") for name in names)
647
+ assert any(name.startswith("ll_condition.") for name in names)
648
+
649
+ graph = model.forward_student(torch.rand(2, 3, 64, 64))
650
+ assert graph.routing_probs.shape == (2, 6)
651
+ assert graph.severity_coords.shape == (2, 4)
652
+ assert graph.spatial_maps.shape[:2] == (2, 4)
653
+ assert graph.node_tokens.shape == (2, 6, 32)
654
+ assert graph.global_condition.shape == (2, 32)
655
+ v2.assert_phase2_contract(model)
656
+
657
+
658
+ def test_ll_condition_is_zero_initialized_for_v2_aggregation_equivalence():
659
+ model = v2.BlindDegradationGraphEncoder(_small_ll_config())
660
+ assert int(torch.count_nonzero(model.ll_condition.weight)) == 0
661
+ assert int(torch.count_nonzero(model.ll_condition.bias)) == 0
662
+
663
+
664
+ @pytest.mark.parametrize("kind", v2.OOD_KINDS)
665
+ def test_synthesize_ood_is_deterministic_bounded_and_nontrivial(kind):
666
+ clean = torch.rand(2, 3, 64, 64)
667
+ first = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(7))
668
+ second = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(7))
669
+ other = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(8))
670
+ assert torch.equal(first, second)
671
+ assert first.shape == clean.shape
672
+ assert float(first.min()) >= -1e-5 and float(first.max()) <= 1.0 + 1e-5
673
+ assert not torch.equal(first, clean)
674
+ if kind == "snow":
675
+ assert not torch.equal(first, other)
676
+
677
+
678
+ def test_objective_with_ood_routes_clean_and_ood_into_free_slots():
679
+ torch.manual_seed(0)
680
+ config = _small_ll_config()
681
+ model = v2.BlindDegradationGraphEncoder(config)
682
+ objective = v2.Phase1GraphObjective(node_dim=32)
683
+ degraded = torch.rand(4, 3, 64, 64)
684
+ clean = torch.rand(4, 3, 64, 64)
685
+ ood = v2.synthesize_ood(clean, "snow", torch.Generator().manual_seed(3))
686
+ labels = torch.tensor([0, 1, 2, 3])
687
+ severity = torch.rand(4)
688
+ pixel_q95 = torch.ones(4)
689
+
690
+ graph_degraded = model.forward_student(degraded)
691
+ graph_clean = model.forward_student(clean)
692
+ graph_ood = model.forward_student(ood)
693
+ losses = objective(
694
+ graph_degraded, graph_clean, degraded, clean, labels, severity,
695
+ pixel_q95, model.clean_root(), graph_ood=graph_ood,
696
+ )
697
+ for name in ("null_route", "ood_route", "unknown_margin", "total"):
698
+ assert torch.isfinite(losses[name]), name
699
+ assert float(losses["null_route"]) > 0.0
700
+ assert float(losses["ood_route"]) > 0.0
701
+
702
+ losses["total"].backward()
703
+ routing_grads = [
704
+ parameter.grad
705
+ for name, parameter in model.state_predictor.routing_net.named_parameters()
706
+ if parameter.grad is not None
707
+ ]
708
+ assert routing_grads and any(
709
+ float(grad.abs().sum()) > 0 for grad in routing_grads
710
+ )
711
+
712
+
713
+ def test_objective_without_ood_matches_legacy_signature():
714
+ torch.manual_seed(0)
715
+ config = v2.GraphConfig(latent_channels=16, node_dim=32)
716
+ model = v2.BlindDegradationGraphEncoder(config)
717
+ objective = v2.Phase1GraphObjective(node_dim=32)
718
+ degraded = torch.rand(2, 3, 64, 64)
719
+ clean = torch.rand(2, 3, 64, 64)
720
+ losses = objective(
721
+ model.forward_student(degraded), model.forward_student(clean),
722
+ degraded, clean, torch.tensor([0, 1]), torch.rand(2), torch.ones(4),
723
+ model.clean_root(),
724
+ )
725
+ assert float(losses["ood_route"]) == 0.0
726
+ assert float(losses["unknown_margin"]) == 0.0
727
+ assert torch.isfinite(losses["total"])
728
+
729
+
730
+ def test_selection_key_prefers_null_routing_after_f1_and_accepts_legacy():
731
+ base = {
732
+ "macro_f1": 0.9, "severity_mae": 0.1, "spatial_selected_mae": 0.1,
733
+ "severity_spearman": 0.0,
734
+ }
735
+ with_null = dict(base, null_accuracy_clean=1.0, null_accuracy_ood=0.8)
736
+ without_null = dict(base, null_accuracy_clean=0.1, null_accuracy_ood=0.1)
737
+ higher_f1 = dict(without_null, macro_f1=0.95)
738
+ assert v2.selection_key(with_null) > v2.selection_key(without_null)
739
+ assert v2.selection_key(higher_f1) > v2.selection_key(with_null)
740
+ legacy = {
741
+ "macro_f1": 0.9, "severity_mae": 0.2, "spatial_selected_mae": 0.1,
742
+ }
743
+ assert v2.selection_key(legacy) < v2.selection_key(base)
744
+
745
+
746
+ def test_validation_metrics_accept_null_audit_fields():
747
+ metrics = v2.compute_validation_metrics(
748
+ labels=[0, 1], predictions=[0, 1], severity_targets=[0.1, 0.2],
749
+ severity_predictions=[0.1, 0.2], unknown_routing=[0.0, 0.0],
750
+ entropies=[0.1, 0.1], losses=[0.5, 0.5], spatial_mae=[0.1, 0.1],
751
+ inactive_activation=[0.0, 0.0],
752
+ null_accuracy_clean=0.75, null_accuracy_ood=0.5, unknown_norm_gap=0.2,
753
+ )
754
+ assert metrics["null_accuracy_clean"] == 0.75
755
+ assert metrics["null_accuracy_ood"] == 0.5
756
+ assert metrics["unknown_norm_gap"] == 0.2
757
+
758
+
759
+ def test_build_frozen_phase1_reconstructs_ll_architecture_from_checkpoint(tmp_path):
760
+ import train_phase2_graph_resshift_v4 as p2
761
+
762
+ config = _small_ll_config()
763
+ model = v2.BlindDegradationGraphEncoder(config)
764
+ head = torch.nn.Linear(32, 4)
765
+ graph_config_dict = dict(vars(config))
766
+ checkpoint = v2.make_checkpoint(
767
+ model, head, None, None, None, epoch=1, best_score=0.5,
768
+ config={"graph_config": graph_config_dict},
769
+ provenance={}, history=[],
770
+ severity_calibration={
771
+ name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0}
772
+ for name in v2.BRANCH_ORDER
773
+ },
774
+ )
775
+ path = tmp_path / "phase1_ll.pt"
776
+ torch.save(checkpoint, str(path))
777
+ sha = v2.sha256_file(path)
778
+ frozen, metadata = p2.build_frozen_phase1(path, sha, torch.device("cpu"))
779
+ assert frozen.encoder.ll_branch is not None
780
+ assert metadata["sha256"] == sha
781
+ representation = frozen(torch.rand(1, 3, 64, 64))
782
+ assert representation.routing_probs.shape == (1, 6)
783
+
784
+
785
+ def test_pearson_and_spearman_ignore_non_finite_pairs():
786
+ # NaN pairs are dropped; the remaining finite pairs correlate normally.
787
+ two_left = v2._pearson([1.0, float("nan"), 3.0], [1.0, 2.0, 3.0])
788
+ assert abs(two_left - 1.0) < 1e-9
789
+ clean = v2._pearson([1.0, 2.0, 3.0, float("nan")], [1.0, 2.0, 3.0, 5.0])
790
+ assert abs(clean - 1.0) < 1e-9
791
+ # All pairs non-finite -> fewer than two survivors -> safe zero.
792
+ assert v2._pearson([float("nan")] * 3, [1.0, 2.0, 3.0]) == 0.0
793
+ assert math.isfinite(v2._spearman([float("inf")] * 3, [1.0, 2.0, 3.0]))
794
+
795
+
796
+ def test_sanitize_json_replaces_non_finite_and_write_survives(tmp_path):
797
+ payload = {
798
+ "ok": 1.5,
799
+ "bad": float("nan"),
800
+ "nested": [float("inf"), {"x": float("-inf"), "y": 2}],
801
+ }
802
+ sanitized = v2._sanitize_json(payload)
803
+ assert sanitized["bad"] is None
804
+ assert sanitized["nested"][0] is None
805
+ assert sanitized["nested"][1]["x"] is None
806
+ assert sanitized["nested"][1]["y"] == 2
807
+ target = tmp_path / "history.json"
808
+ v2._atomic_write_json(target, payload)
809
+ import json as _json
810
+
811
+ assert _json.loads(target.read_text())["bad"] is None
812
+
813
+
814
+ def test_selection_key_treats_non_finite_metrics_as_worst():
815
+ healthy = {
816
+ "macro_f1": 0.5, "severity_mae": 0.2, "spatial_selected_mae": 0.2,
817
+ }
818
+ poisoned = {
819
+ "macro_f1": float("nan"), "severity_mae": 0.2,
820
+ "spatial_selected_mae": 0.2,
821
+ }
822
+ assert v2.selection_key(healthy) > v2.selection_key(poisoned)
823
+
824
+
825
+ def test_ll_branch_stays_fp32_under_autocast():
826
+ branch = LLGlobalBranch(output_dim=32)
827
+ image = torch.rand(1, 3, 64, 64)
828
+ if torch.cuda.is_available():
829
+ branch = branch.cuda()
830
+ image = image.cuda()
831
+ with torch.cuda.amp.autocast(enabled=True):
832
+ output = branch(image)
833
+ else:
834
+ output = branch(image)
835
+ assert output.dtype == torch.float32
836
+
837
+
838
+ def test_synthesize_noise_is_deterministic_and_bounded() -> None:
839
+ clean = torch.rand(3, 3, 32, 32)
840
+ g1 = torch.Generator().manual_seed(11)
841
+ g2 = torch.Generator().manual_seed(11)
842
+ a = v2.synthesize_noise(clean, g1)
843
+ b = v2.synthesize_noise(clean, g2)
844
+ assert torch.equal(a, b)
845
+ assert float(a.min()) >= 0.0 and float(a.max()) <= 1.0
846
+ assert float((a - clean).abs().mean()) > 1e-3
847
+ bank = [torch.randn(3, 32, 32) * 0.05]
848
+ c = v2.synthesize_noise(clean, torch.Generator().manual_seed(3), bank)
849
+ assert c.shape == clean.shape
850
+
851
+
852
+ def test_apply_noise_positives_relabels_only_selected_non_noise() -> None:
853
+ clean = torch.rand(6, 3, 16, 16)
854
+ degraded = clean.clone()
855
+ labels = torch.tensor([0, v2.NOISE_INDEX, 2, 3, 0, 2])
856
+ severity = torch.zeros(6)
857
+ calibration = {"p05": 0.0, "p95": 0.2}
858
+ new_deg, new_lab, new_sev, mask = v2.apply_noise_positives(
859
+ degraded, clean, labels, severity, 1.0, torch.Generator().manual_seed(5),
860
+ calibration,
861
+ )
862
+ assert bool(mask[1]) is False # real noise sample untouched
863
+ assert torch.equal(new_lab[mask], torch.full((int(mask.sum()),), v2.NOISE_INDEX))
864
+ assert torch.equal(new_deg[~mask], degraded[~mask])
865
+ assert torch.equal(labels, torch.tensor([0, v2.NOISE_INDEX, 2, 3, 0, 2])) # not mutated
866
+ assert float(new_sev[mask].min()) > 0.0 and float(new_sev[mask].max()) <= 1.0
867
+ untouched_deg, untouched_lab, _, zero_mask = v2.apply_noise_positives(
868
+ degraded, clean, labels, severity, 0.0, torch.Generator().manual_seed(5), calibration
869
+ )
870
+ assert untouched_deg is degraded and untouched_lab is labels and not bool(zero_mask.any())
871
+
872
+
873
+ def test_texture_null_weights_rank_textured_images_higher() -> None:
874
+ flat = torch.full((1, 3, 32, 32), 0.5)
875
+ textured = torch.rand(1, 3, 32, 32)
876
+ weights = v2.texture_null_weights(torch.cat([flat, textured], dim=0))
877
+ assert weights.shape == (2,)
878
+ assert float(weights[1]) > float(weights[0])
879
+ assert float(weights.min()) >= 0.5 and float(weights.max()) <= 1.5
880
+
881
+
882
+ def test_objective_accepts_texture_weighted_null() -> None:
883
+ objective = v2.Phase1GraphObjective(node_dim=256, texture_weighted_null=True)
884
+ assert objective.texture_weighted_null is True
885
+
886
+
887
+ def test_sharpen_ood_kind_adds_detail_deterministically() -> None:
888
+ clean = torch.rand(2, 3, 32, 32)
889
+ a = v2.synthesize_ood(clean, "sharpen", torch.Generator().manual_seed(2))
890
+ b = v2.synthesize_ood(clean, "sharpen", torch.Generator().manual_seed(2))
891
+ assert torch.equal(a, b)
892
+ assert a.shape == clean.shape and float(a.min()) >= 0.0 and float(a.max()) <= 1.0
893
+ assert float((a - clean).abs().mean()) > 1e-3
894
+ assert "sharpen" in v2.OOD_KINDS
895
+
896
+
897
+ def test_transplant_only_noise_uses_bank_and_gain() -> None:
898
+ clean = torch.rand(2, 3, 16, 16) * 0.5
899
+ bank = [torch.ones(3, 16, 16) * 0.1]
900
+ out = v2.synthesize_noise(
901
+ clean, torch.Generator().manual_seed(9), bank, synthetic_prob=0.0, gain_max=2.5
902
+ )
903
+ residual = out - clean
904
+ # transplant of a constant residual: per-image constant offset in [0.05, 0.25]
905
+ per_image = residual.flatten(1).mean(dim=1)
906
+ assert float(per_image.min()) >= 0.05 - 1e-6 and float(per_image.max()) <= 0.25 + 1e-6
907
+ spread = residual.flatten(1).std(dim=1)
908
+ assert float(spread.max()) < 1e-5
dataset/phase1_noise_20260906/code/train_graph_encoder_v2.py ADDED
The diff for this file is too large to render. See raw diff
 
dataset/phase1_noise_20260906/code/train_phase1_clean_relative.py ADDED
@@ -0,0 +1,596 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Train seven clean-relative factors without modifying the legacy Phase-1 path.
2
+
3
+ Real pairs provide domain labels, not physical severity labels. Controlled
4
+ operators supply the latter. Every selected real record is consumed once per
5
+ epoch; loss weighting, rather than oversampling, balances domains.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import contextlib
12
+ from dataclasses import asdict, dataclass
13
+ import hashlib
14
+ import json
15
+ import math
16
+ import os
17
+ from pathlib import Path
18
+ import random
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ import time
23
+ from typing import Any
24
+
25
+ import numpy as np
26
+ import torch
27
+ from torch import Tensor
28
+ import torch.nn.functional as F
29
+ from torch.utils.data import DataLoader
30
+
31
+ TYPE_ORDER = ("rain", "noise", "haze", "lowlight", "snow", "blur", "jpeg")
32
+ HELDOUT_PAIRS = (("rain", "jpeg"), ("noise", "haze"), ("snow", "blur"))
33
+ TRAIN_PAIRS = tuple(
34
+ (a, b) for a in TYPE_ORDER for b in TYPE_ORDER
35
+ if a != b and frozenset((a, b)) not in {frozenset(pair) for pair in HELDOUT_PAIRS}
36
+ )
37
+
38
+
39
+ def epoch_indices(size: int, seed: int, epoch: int, start: int = 0) -> list[int]:
40
+ """An independently seeded permutation, resumable by consumed-record cursor."""
41
+ if size < 0 or not 0 <= start <= size:
42
+ raise ValueError("Invalid dataset size or resume cursor")
43
+ generator = torch.Generator().manual_seed(seed + epoch * 1_000_003)
44
+ return torch.randperm(size, generator=generator).tolist()[start:]
45
+
46
+
47
+ def class_weights(labels: Tensor, num_classes: int = 7) -> Tensor:
48
+ counts = torch.bincount(labels.long(), minlength=num_classes).float()
49
+ present = counts > 0
50
+ weights = torch.zeros_like(counts)
51
+ if present.any():
52
+ weights[present] = len(labels) / (present.sum() * counts[present])
53
+ return weights
54
+
55
+
56
+ def capture_rng() -> dict[str, Any]:
57
+ return {
58
+ "python": random.getstate(), "numpy": np.random.get_state(),
59
+ "torch": torch.get_rng_state(),
60
+ "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None,
61
+ }
62
+
63
+
64
+ def restore_rng(state: dict[str, Any]) -> None:
65
+ random.setstate(state["python"])
66
+ np.random.set_state(state["numpy"])
67
+ torch.set_rng_state(state["torch"].cpu())
68
+ if state.get("cuda") is not None and torch.cuda.is_available():
69
+ torch.cuda.set_rng_state_all([item.cpu() for item in state["cuda"]])
70
+
71
+
72
+ def _atomic_write(path: Path, writer) -> None:
73
+ path.parent.mkdir(parents=True, exist_ok=True)
74
+ descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent)
75
+ try:
76
+ with os.fdopen(descriptor, "wb") as handle:
77
+ writer(handle)
78
+ handle.flush()
79
+ os.fsync(handle.fileno())
80
+ os.replace(temporary, path)
81
+ directory = os.open(path.parent, os.O_RDONLY)
82
+ try:
83
+ os.fsync(directory)
84
+ finally:
85
+ os.close(directory)
86
+ finally:
87
+ if os.path.exists(temporary):
88
+ os.unlink(temporary)
89
+
90
+
91
+ def atomic_torch_save(payload: Any, path: str | Path) -> None:
92
+ _atomic_write(Path(path), lambda handle: torch.save(payload, handle))
93
+
94
+
95
+ def atomic_json_save(payload: Any, path: str | Path) -> None:
96
+ encoded = json.dumps(payload, indent=2, allow_nan=False, default=str).encode("utf-8")
97
+ _atomic_write(Path(path), lambda handle: handle.write(encoded))
98
+
99
+
100
+ def append_jsonl(path: Path, payload: Any) -> None:
101
+ with path.open("a", encoding="utf-8") as handle:
102
+ handle.write(json.dumps(payload, allow_nan=False, default=str) + "\n")
103
+ handle.flush()
104
+ os.fsync(handle.fileno())
105
+
106
+
107
+ def safe_optimizer_step(model, optimizer, max_norm: float, scaler=None) -> tuple[bool, float | None]:
108
+ """Reject all nonfinite gradients before mutating optimizer or parameters."""
109
+ if scaler is not None and scaler.is_enabled():
110
+ scaler.unscale_(optimizer)
111
+ parameters = [p for p in model.parameters() if p.grad is not None]
112
+ finite = all(bool(torch.isfinite(p.grad).all()) for p in parameters)
113
+ norm = None
114
+ if finite and parameters:
115
+ measured = torch.nn.utils.clip_grad_norm_(parameters, max_norm)
116
+ finite = bool(torch.isfinite(measured))
117
+ norm = float(measured) if finite else None
118
+ if finite:
119
+ if scaler is not None and scaler.is_enabled():
120
+ scaler.step(optimizer)
121
+ else:
122
+ optimizer.step()
123
+ if scaler is not None and scaler.is_enabled():
124
+ scaler.update()
125
+ if not finite:
126
+ optimizer.zero_grad(set_to_none=True)
127
+ return finite, norm
128
+
129
+
130
+ def file_digest(path: str | Path) -> str:
131
+ digest = hashlib.sha256()
132
+ with Path(path).open("rb") as handle:
133
+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):
134
+ digest.update(chunk)
135
+ return digest.hexdigest()
136
+
137
+
138
+ def source_provenance() -> dict[str, Any]:
139
+ root = Path(__file__).resolve().parent
140
+ files = [Path(__file__), root / "eval_phase1_clean_relative.py", *sorted((root / "src").rglob("*.py"))]
141
+ hashes = {str(path.relative_to(root)): file_digest(path) for path in files if path.is_file()}
142
+ result: dict[str, Any] = {"source_sha256": hashes, "python": sys.version, "torch": torch.__version__}
143
+ for key, command in (("git_head", ["git", "rev-parse", "HEAD"]), ("git_status", ["git", "status", "--porcelain"])):
144
+ completed = subprocess.run(command, cwd=root, capture_output=True, text=True, check=False)
145
+ result[key] = completed.stdout.strip() if completed.returncode == 0 else None
146
+ result["source_digest"] = hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest()
147
+ receipt = root / "DEPLOYMENT.json"
148
+ result["deployment_receipt"] = json.loads(receipt.read_text()) if receipt.is_file() else None
149
+ result["deployment_sha"] = os.environ.get("DEPLOYMENT_SHA")
150
+ return result
151
+
152
+
153
+ def record_labels(dataset) -> Tensor:
154
+ labels = []
155
+ for record in dataset.records:
156
+ name = record.get("type", record.get("degradation"))
157
+ if name not in TYPE_ORDER:
158
+ raise ValueError(f"Unsupported manifest degradation: {name!r}")
159
+ labels.append(TYPE_ORDER.index(name))
160
+ return torch.tensor(labels, dtype=torch.long)
161
+
162
+
163
+ def scene_component_ids(records: list[dict]) -> list[int]:
164
+ """Connect both dataset-scene groups and duplicate clean-image content."""
165
+ parents = list(range(len(records)))
166
+
167
+ def find(index):
168
+ while parents[index] != index:
169
+ parents[index] = parents[parents[index]]
170
+ index = parents[index]
171
+ return index
172
+
173
+ seen = {}
174
+ for index, record in enumerate(records):
175
+ keys = (("group", record["dataset"], record["group"]), ("content", record["clean_content_sha256"]))
176
+ for key in keys:
177
+ if key in seen:
178
+ current, previous = find(index), find(seen[key])
179
+ parents[max(current, previous)] = min(current, previous)
180
+ else:
181
+ seen[key] = index
182
+ return [find(index) for index in range(len(records))]
183
+
184
+
185
+ def selected_indices(labels: Tensor, cap: int | None, seed: int) -> list[int]:
186
+ """Deterministic stratified subset for explicitly capped smoke/quick checks."""
187
+ if cap is None or cap >= len(labels):
188
+ return list(range(len(labels)))
189
+ if cap <= 0:
190
+ raise ValueError("An explicit record cap must be positive")
191
+ rng = random.Random(seed)
192
+ groups = [torch.where(labels == k)[0].tolist() for k in range(len(TYPE_ORDER))]
193
+ for group in groups:
194
+ rng.shuffle(group)
195
+ selected = []
196
+ while len(selected) < cap:
197
+ for group in groups:
198
+ if group and len(selected) < cap:
199
+ selected.append(group.pop())
200
+ return selected
201
+
202
+
203
+ @dataclass
204
+ class LossWeights:
205
+ presence: float = 1.0
206
+ root: float = 1.0
207
+ content: float = 0.1
208
+ variance: float = 0.05
209
+ subspace: float = 0.2
210
+ free: float = 0.02
211
+ distill: float = 0.5
212
+ severity: float = 0.5
213
+ invariance: float = 0.1
214
+ proxy: float = 1.0
215
+ transfer: float = 0.5
216
+ interaction: float = 0.2
217
+ spatial: float = 0.1
218
+ photometric: float = 0.1
219
+
220
+
221
+ def _mean_per_sample(value: Tensor) -> Tensor:
222
+ return value.reshape(len(value), -1).mean(1)
223
+
224
+
225
+ def image_statistics(image: Tensor) -> Tensor:
226
+ """Eight observable image summaries; differences are not physical parameters."""
227
+ gray = image.mean(1, keepdim=True)
228
+ return torch.cat((image.mean((-2, -1)), image.std((-2, -1), unbiased=False),
229
+ (gray[..., 1:] - gray[..., :-1]).abs().mean((-2, -1)),
230
+ (gray[..., 1:, :] - gray[..., :-1, :]).abs().mean((-2, -1))), dim=1)
231
+
232
+
233
+ def residual_statistics(residual: Tensor) -> Tensor:
234
+ """Residual mean/std and native-grid gradient/Laplacian RMS (15 channels)."""
235
+ residual = residual.float()
236
+ dx = residual[..., 1:] - residual[..., :-1]
237
+ dy = residual[..., 1:, :] - residual[..., :-1, :]
238
+ laplace = (4 * residual[..., 1:-1, 1:-1] - residual[..., :-2, 1:-1]
239
+ - residual[..., 2:, 1:-1] - residual[..., 1:-1, :-2] - residual[..., 1:-1, 2:])
240
+ def rms(item):
241
+ return (item.square().mean((-2, -1)) + 1e-8).sqrt()
242
+ return torch.cat((residual.mean((-2, -1)), residual.std((-2, -1), unbiased=False),
243
+ rms(dx), rms(dy), rms(laplace)), dim=1)
244
+
245
+
246
+ def supervised_terms(rep: dict, presence: Tensor, weights: Tensor, severity: Tensor | None = None,
247
+ severity_mask: Tensor | None = None) -> dict[str, Tensor]:
248
+ known = presence.shape[1]
249
+ positive = presence.sum(1).clamp_min(1)
250
+ bce = F.binary_cross_entropy_with_logits(rep["presence_logits"], presence, reduction="none").mean(1)
251
+ amplitudes = rep["amplitudes"][:, :known]
252
+ inactive = ((1 - presence) * amplitudes.square()).mean(1)
253
+ active_error = F.relu(0.25 - amplitudes).square()
254
+ if severity is None:
255
+ severity_loss = bce.new_zeros(())
256
+ else:
257
+ mask = presence if severity_mask is None else severity_mask.to(presence) * presence
258
+ active_error = torch.where(mask.bool(), (amplitudes - severity).square(), active_error)
259
+ severity_loss = ((((rep["severity"] - severity).square() * mask).sum(1) / mask.sum(1).clamp_min(1)) * weights).mean()
260
+ active = (presence * active_error).sum(1) / positive
261
+ free = rep["amplitudes"][:, known:].square().mean(1) if rep["amplitudes"].shape[1] > known else bce * 0
262
+ free = free + rep["residual"].square().mean(1)
263
+ return {
264
+ "presence": (bce * weights).mean(),
265
+ "subspace": ((active + inactive) * weights).mean(),
266
+ "free": (free * weights).mean(), "severity": severity_loss,
267
+ }
268
+
269
+
270
+ def pair_objective(model, pair: dict, clean: Tensor, degraded: Tensor, presence: Tensor,
271
+ weights: Tensor, loss_weights: LossWeights, severity: Tensor | None = None,
272
+ include_anchor: bool = True, severity_mask: Tensor | None = None) -> tuple[Tensor, dict[str, Tensor]]:
273
+ student, teacher, reference = pair["student"], pair["teacher"], pair["clean"]
274
+ terms = supervised_terms(student, presence, weights, severity, severity_mask)
275
+ teacher_terms = supervised_terms(teacher, presence, weights, severity, severity_mask)
276
+ terms = {key: (value + teacher_terms[key]) / 2 for key, value in terms.items()}
277
+ terms["distill"] = ((student["delta"] - teacher["delta"].detach()).square().mean(1) * weights).mean()
278
+ visible_change = F.interpolate((degraded - clean).abs().mean(1, keepdim=True), size=student["spatial"].shape[-2:], mode="area")
279
+ spatial_target = visible_change * presence[:, :, None, None]
280
+ # Domain-indexed observed change, not a claim of physical factor support.
281
+ terms["spatial"] = ((_mean_per_sample((student["spatial"] - spatial_target).square())
282
+ + _mean_per_sample((teacher["spatial"] - spatial_target).square())) * weights).mean() / 2
283
+ photometric_target = image_statistics(degraded) - image_statistics(clean)
284
+ terms["photometric"] = (((student["photometric"] - photometric_target).square().mean(1)
285
+ + (teacher["photometric"] - photometric_target).square().mean(1)) * weights).mean() / 2
286
+ if include_anchor:
287
+ terms["root"] = reference["delta"].square().mean() + F.binary_cross_entropy_with_logits(
288
+ reference["presence_logits"], torch.zeros_like(presence))
289
+ terms["root"] += reference["spatial"].square().mean()
290
+ terms["content"] = F.smooth_l1_loss(student["content"], reference["content"].detach())
291
+ pooled = reference["content"].mean((-2, -1)).float()
292
+ terms["variance"] = F.relu(0.1 - torch.sqrt(pooled.var(0, unbiased=False) + 1e-4)).mean() if len(clean) > 1 else pooled.sum() * 0
293
+ if loss_weights.proxy:
294
+ clean_hat = model.decode(reference["content"], torch.zeros_like(teacher["delta"]), clean.shape[-2:])
295
+ degraded_hat = model.decode(reference["content"], teacher["delta"], clean.shape[-2:])
296
+ terms["proxy"] = (_mean_per_sample((clean_hat - clean).abs()) * weights).mean()
297
+ terms["proxy"] += (functional_error(degraded_hat, degraded, clean, presence.argmax(1)) * weights).mean()
298
+ total = sum(getattr(loss_weights, key) * value for key, value in terms.items())
299
+ return total, terms
300
+
301
+
302
+ def controlled_batch(clean_cpu: Tensor, step: int, seed: int, count: int,
303
+ pairs=TRAIN_PAIRS, heldout: bool = False, scene_ids: list[str] | None = None) -> dict[str, Any]:
304
+ """Matched operators on different content; labels come only from synthesis."""
305
+ from src.data.clean_relative import sample_degradation_parameters, synthesize_composition, synthesize_degradation
306
+
307
+ count = min(count, len(clean_cpu))
308
+ scene_ids = scene_ids if scene_ids is not None else [str(i) for i in range(len(clean_cpu))]
309
+ partners = [next((j for j in range(len(clean_cpu)) if scene_ids[j] != scene_ids[i]), i) for i in range(count)]
310
+ cross_content_available = all(scene_ids[i] != scene_ids[j] for i, j in enumerate(partners))
311
+ collected: dict[str, list] = {key: [] for key in (
312
+ "clean", "other_clean", "single", "other_single", "second", "mixed",
313
+ "presence", "second_presence", "severity", "second_severity", "first_type", "second_type",
314
+ )}
315
+ specs = []
316
+ for i in range(count):
317
+ a, b = pairs[(step * count + i) % len(pairs)]
318
+ sample_seed = seed + step * 10_007 + i * 101
319
+ pa = sample_degradation_parameters(a, sample_seed, heldout=heldout)
320
+ pb = sample_degradation_parameters(b, sample_seed + 1, heldout=heldout)
321
+ x = clean_cpu[i]
322
+ other = clean_cpu[partners[i]]
323
+ ya, _ = synthesize_degradation(x, a, parameters=pa, seed=sample_seed)
324
+ yb, _ = synthesize_degradation(x, b, parameters=pb, seed=sample_seed + 1)
325
+ yother, _ = synthesize_degradation(other, a, parameters=pa, seed=sample_seed)
326
+ mixed, _ = synthesize_composition(x, (a, b), parameters=(pa, pb), seed=sample_seed)
327
+ active, second_active = torch.zeros(7), torch.zeros(7)
328
+ severity, second_severity = torch.zeros(7), torch.zeros(7)
329
+ active[TYPE_ORDER.index(a)] = second_active[TYPE_ORDER.index(b)] = 1
330
+ severity[TYPE_ORDER.index(a)] = float(pa["severity"])
331
+ second_severity[TYPE_ORDER.index(b)] = float(pb["severity"])
332
+ values = (x, other, ya, yother, yb, mixed, active, second_active, severity, second_severity,
333
+ torch.tensor(TYPE_ORDER.index(a)), torch.tensor(TYPE_ORDER.index(b)))
334
+ for key, value in zip(collected, values):
335
+ collected[key].append(value)
336
+ specs.append({"first": a, "second": b, "first_parameters": pa, "second_parameters": pb})
337
+ result = {key: torch.stack(values) for key, values in collected.items()}
338
+ result["specs"] = specs
339
+ result["cross_content_available"] = cross_content_available
340
+ return result
341
+
342
+
343
+ def synthetic_objective(model, data: dict, loss_weights: LossWeights, use_edges: bool) -> tuple[Tensor, dict[str, Tensor]]:
344
+ x = data["clean"]
345
+ single = model.forward_pair(data["single"], x)
346
+ second = model.forward_pair(data["second"], x)
347
+ mixed = model.forward_pair(data["mixed"], x)
348
+ pairs = ((single, data["single"], data["presence"], data["severity"]),
349
+ (second, data["second"], data["second_presence"], data["second_severity"]),
350
+ (mixed, data["mixed"], data["presence"] + data["second_presence"], data["severity"] + data["second_severity"]))
351
+ total = x.sum() * 0
352
+ logs: dict[str, Tensor] = {}
353
+ for pair, degraded, presence, severity in pairs:
354
+ value, terms = pair_objective(model, pair, x, degraded, presence, x.new_ones(len(x)), loss_weights,
355
+ severity=severity, include_anchor=False)
356
+ total = total + value / len(pairs)
357
+ for key, item in terms.items():
358
+ logs[key] = logs.get(key, x.sum() * 0) + item / len(pairs)
359
+ composed = model.compose(single["teacher"]["delta"], second["teacher"]["delta"],
360
+ data["first_type"], data["second_type"], use_edges=use_edges)
361
+ logs["interaction"] = F.mse_loss(composed, mixed["teacher"]["delta"].detach())
362
+ total = total + loss_weights.interaction * logs["interaction"]
363
+ if data["cross_content_available"]:
364
+ other = model.forward_pair(data["other_single"], data["other_clean"])
365
+ logs["invariance"] = F.mse_loss(single["teacher"]["coefficients"][:, :7], other["teacher"]["coefficients"][:, :7])
366
+ total = total + loss_weights.invariance * logs["invariance"]
367
+ if loss_weights.transfer:
368
+ prediction = model.decode(other["clean"]["content"], single["teacher"]["delta"], x.shape[-2:])
369
+ logs["transfer"] = functional_error(prediction, data["other_single"], data["other_clean"], data["first_type"]).mean()
370
+ total = total + loss_weights.transfer * logs["transfer"]
371
+ return total, logs
372
+
373
+
374
+ def functional_error(prediction: Tensor, target: Tensor, clean: Tensor, labels: Tensor) -> Tensor:
375
+ """Pixel error for deterministic operators; residual moments for random ones.
376
+
377
+ Matching moments is deliberately not described as a full likelihood test.
378
+ """
379
+ pixel = _mean_per_sample((prediction - target).abs())
380
+ moments = (residual_statistics(prediction - clean) - residual_statistics(target - clean)).abs().mean(1)
381
+ stochastic = (labels == TYPE_ORDER.index("noise")) | (labels == TYPE_ORDER.index("rain")) | (labels == TYPE_ORDER.index("snow"))
382
+ return torch.where(stochastic, moments, pixel)
383
+
384
+
385
+ def build_parser() -> argparse.ArgumentParser:
386
+ parser = argparse.ArgumentParser(description=__doc__)
387
+ parser.add_argument("--manifest", required=True)
388
+ parser.add_argument("--output-dir", required=True)
389
+ parser.add_argument("--epochs", type=int, default=10)
390
+ parser.add_argument("--batch-size", type=int, default=16)
391
+ parser.add_argument("--patch-size", type=int, default=128)
392
+ parser.add_argument("--num-workers", type=int, default=4)
393
+ parser.add_argument("--threads", type=int, default=4)
394
+ parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
395
+ parser.add_argument("--seed", type=int, default=42)
396
+ parser.add_argument("--lr", type=float, default=2e-4)
397
+ parser.add_argument("--weight-decay", type=float, default=1e-4)
398
+ parser.add_argument("--grad-clip", type=float, default=1.0)
399
+ parser.add_argument("--amp", choices=("none", "bfloat16", "float16"), default="none")
400
+ parser.add_argument("--synthetic-batch-size", type=int, default=4)
401
+ parser.add_argument("--synthetic-every", type=int, default=1)
402
+ parser.add_argument("--save-every", type=int, default=250)
403
+ parser.add_argument("--log-every", type=int, default=25)
404
+ parser.add_argument("--val-every", type=int, default=1)
405
+ parser.add_argument("--quick-val-records", type=int, default=224)
406
+ parser.add_argument("--max-train-records", type=int, help="Explicitly capped smoke run; omitted means ALL train records")
407
+ parser.add_argument("--max-steps", type=int, help="Explicit optimizer-attempt cap for a smoke run")
408
+ parser.add_argument("--resume")
409
+ parser.add_argument("--no-edges", action="store_true", help="Disable ordered-composition correction; evidence attention remains enabled")
410
+ parser.add_argument("--prototype-only", action="store_true", help="Rank-one/type baseline; not capacity-matched")
411
+ parser.add_argument("--no-proxy", action="store_true")
412
+ return parser
413
+
414
+
415
+ def main(argv: list[str] | None = None) -> dict[str, Any]:
416
+ args = build_parser().parse_args(argv)
417
+ for key in ("epochs", "batch_size", "patch_size", "synthetic_batch_size", "synthetic_every", "save_every", "log_every", "val_every", "threads"):
418
+ if getattr(args, key) <= 0:
419
+ raise ValueError(f"--{key.replace('_', '-')} must be positive")
420
+ if args.num_workers < 0 or (args.max_steps is not None and args.max_steps <= 0):
421
+ raise ValueError("Invalid worker count or step cap")
422
+ if args.patch_size < 32 or args.patch_size % 16:
423
+ raise ValueError("Patch size must be >=32 and divisible by16")
424
+ torch.set_num_threads(args.threads)
425
+ random.seed(args.seed)
426
+ np.random.seed(args.seed)
427
+ torch.manual_seed(args.seed)
428
+ if torch.cuda.is_available():
429
+ torch.cuda.manual_seed_all(args.seed)
430
+ device = torch.device(args.device)
431
+ if args.amp != "none" and device.type != "cuda":
432
+ raise ValueError("AMP is supported here only on CUDA/ROCm devices")
433
+ from src.data.clean_relative import PairedDegradationDataset
434
+ from src.models.graph_encoder.clean_relative import CleanRelativeConfig, CleanRelativeGraphEncoder
435
+ from eval_phase1_clean_relative import evaluate_real
436
+
437
+ dataset = PairedDegradationDataset(args.manifest, split="train", crop_size=args.patch_size, seed=args.seed)
438
+ labels = record_labels(dataset)
439
+ scene_components = scene_component_ids(dataset.records)
440
+ selected = selected_indices(labels, args.max_train_records, args.seed)
441
+ if not selected:
442
+ raise ValueError("Training manifest contains no selected records")
443
+ sample_weights = class_weights(labels[selected]).to(device)
444
+ config = CleanRelativeConfig(rank=1 if args.prototype_only else 8)
445
+ model = CleanRelativeGraphEncoder(config).to(device)
446
+ optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay)
447
+ total_steps = args.epochs * math.ceil(len(selected) / args.batch_size)
448
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_steps)
449
+ scaler = torch.amp.GradScaler("cuda", enabled=args.amp == "float16")
450
+ loss_weights = LossWeights(proxy=0 if args.no_proxy else 1, transfer=0 if args.no_proxy else 0.5)
451
+ output = Path(args.output_dir)
452
+ output.mkdir(parents=True, exist_ok=True)
453
+ manifest_sha = file_digest(args.manifest)
454
+ run_config = {
455
+ "arguments": vars(args), "model_config": asdict(config), "loss_weights": asdict(loss_weights),
456
+ "type_order": TYPE_ORDER, "manifest_sha256": manifest_sha, "provenance": source_provenance(),
457
+ "train_records_total": len(dataset), "train_records_selected": len(selected),
458
+ "class_counts": torch.bincount(labels[selected], minlength=7).tolist(),
459
+ "class_loss_weights": sample_weights.cpu().tolist(), "sampling": "epoch permutation without replacement; drop_last=False",
460
+ "scope": "smoke_capped" if args.max_train_records is not None or args.max_steps is not None else "full_manifest",
461
+ "train_compositions": TRAIN_PAIRS, "heldout_compositions": HELDOUT_PAIRS,
462
+ "no_edges_scope": "Only ordered-composition correction; not a complete no-message-passing ablation",
463
+ "semantic_limits": ["Dataset labels do not establish exclusive physical mechanisms", "Severity supervision uses explicit synthetic parameter masks; unknown real severity is not labeled", "Edges model latent nonadditivity, not causal identification", "Proxy stochastic comparisons match residual/HF moments, not full likelihoods", "Paired teacher uses the same linear head: teacher_delta=student_delta-clean_delta; agreement alone is a root constraint", "Spatial targets measure observed domain-indexed appearance change, not physical support"],
464
+ }
465
+ epoch, cursor, global_step, optimizer_steps = 0, 0, 0, 0
466
+ best_score = -float("inf")
467
+ skipped = 0
468
+ if args.resume:
469
+ checkpoint = torch.load(args.resume, map_location="cpu", weights_only=False)
470
+ previous = checkpoint["run_config"]
471
+ if previous["manifest_sha256"] != manifest_sha or previous["model_config"] != asdict(config):
472
+ raise ValueError("Resume requires identical manifest and model configuration")
473
+ for name in ("seed", "batch_size", "patch_size", "max_train_records", "epochs", "lr", "weight_decay", "grad_clip", "quick_val_records", "val_every", "no_edges", "no_proxy", "synthetic_batch_size", "synthetic_every", "amp"):
474
+ if previous["arguments"].get(name) != vars(args).get(name):
475
+ raise ValueError(f"Resume changes training semantics: {name}")
476
+ if previous["provenance"]["source_digest"] != run_config["provenance"]["source_digest"]:
477
+ raise ValueError("Source changed since checkpoint; use a new run rather than silently hot-patching")
478
+ model.load_state_dict(checkpoint["model"])
479
+ optimizer.load_state_dict(checkpoint["optimizer"])
480
+ scheduler.load_state_dict(checkpoint["scheduler"])
481
+ scaler.load_state_dict(checkpoint["scaler"])
482
+ epoch, cursor = checkpoint["epoch"], checkpoint["cursor"]
483
+ global_step, optimizer_steps = checkpoint["global_step"], checkpoint["optimizer_steps"]
484
+ best_score, skipped = checkpoint["best_score"], checkpoint["skipped_steps"]
485
+ restore_rng(checkpoint["rng"])
486
+ atomic_json_save(run_config, output / f"resume_config_step{global_step}.json")
487
+ elif (output / "run_config.json").exists() or (output / "last.pt").exists():
488
+ raise FileExistsError("Output directory already contains a run; use --resume or a new output directory")
489
+ else:
490
+ atomic_json_save(run_config, output / "run_config.json")
491
+
492
+ def save(name="last.pt"):
493
+ atomic_torch_save({
494
+ "schema_version": 1, "model": model.state_dict(), "model_config": asdict(config),
495
+ "optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict(), "scaler": scaler.state_dict(),
496
+ "rng": capture_rng(), "epoch": epoch, "cursor": cursor, "global_step": global_step,
497
+ "optimizer_steps": optimizer_steps, "best_score": best_score, "skipped_steps": skipped,
498
+ "run_config": run_config,
499
+ }, output / name)
500
+
501
+ started = time.monotonic()
502
+ consecutive_bad = 0
503
+ metrics_path = output / "metrics.jsonl"
504
+ while epoch < args.epochs and (args.max_steps is None or global_step < args.max_steps):
505
+ dataset.set_epoch(epoch)
506
+ indices = [selected[i] for i in epoch_indices(len(selected), args.seed, epoch, cursor)]
507
+ loader = DataLoader(dataset, batch_size=args.batch_size, sampler=indices, drop_last=False,
508
+ num_workers=args.num_workers, pin_memory=device.type == "cuda",
509
+ generator=torch.Generator().manual_seed(args.seed + epoch), persistent_workers=False)
510
+ model.train()
511
+ for batch in loader:
512
+ optimizer.zero_grad(set_to_none=True)
513
+ clean_cpu = batch["clean"]
514
+ clean, degraded = clean_cpu.to(device), batch["degraded"].to(device)
515
+ label = batch["label"].to(device)
516
+ presence = batch["presence"].to(device)
517
+ dtype = torch.bfloat16 if args.amp == "bfloat16" else torch.float16
518
+ autocast = torch.autocast(device_type="cuda", dtype=dtype) if args.amp != "none" else contextlib.nullcontext()
519
+ with autocast:
520
+ pair = model.forward_pair(degraded, clean)
521
+ loss, terms = pair_objective(model, pair, clean, degraded, presence, sample_weights[label], loss_weights,
522
+ severity=batch["severity"].to(device), severity_mask=batch["severity_mask"].to(device))
523
+ if global_step % args.synthetic_every == 0:
524
+ scene_ids = [str(scene_components[int(i)]) for i in batch["index"]]
525
+ synthetic = controlled_batch(clean_cpu, global_step, args.seed, args.synthetic_batch_size, scene_ids=scene_ids)
526
+ synthetic = {key: value.to(device) if isinstance(value, Tensor) else value for key, value in synthetic.items()}
527
+ synthetic_loss, synthetic_terms = synthetic_objective(model, synthetic, loss_weights, not args.no_edges)
528
+ loss = loss + synthetic_loss
529
+ terms.update({"synthetic_" + key: value for key, value in synthetic_terms.items()})
530
+ finite_loss = bool(torch.isfinite(loss))
531
+ gradient_norm = None
532
+ if finite_loss:
533
+ scaler.scale(loss).backward()
534
+ accepted, gradient_norm = safe_optimizer_step(model, optimizer, args.grad_clip, scaler)
535
+ else:
536
+ accepted = False
537
+ optimizer.zero_grad(set_to_none=True)
538
+ cursor += len(clean)
539
+ global_step += 1
540
+ if accepted:
541
+ scheduler.step()
542
+ optimizer_steps += 1
543
+ consecutive_bad = 0
544
+ else:
545
+ skipped += 1
546
+ consecutive_bad += 1
547
+ if global_step % args.log_every == 0 or not accepted or global_step == 1:
548
+ row = {"event": "train", "epoch": epoch, "cursor": cursor, "selected_records": len(selected),
549
+ "step": global_step, "optimizer_steps": optimizer_steps, "loss": float(loss.detach()) if finite_loss else None,
550
+ "accepted": accepted, "gradient_norm": gradient_norm, "lr": scheduler.get_last_lr()[0],
551
+ "elapsed_seconds": time.monotonic() - started,
552
+ "cuda_peak_allocated_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else None,
553
+ "terms": {key: float(value.detach()) if torch.isfinite(value) else None for key, value in terms.items()}}
554
+ append_jsonl(metrics_path, row)
555
+ print(json.dumps(row), flush=True)
556
+ if global_step % args.save_every == 0 or consecutive_bad >= 3:
557
+ save()
558
+ if consecutive_bad >= 3:
559
+ raise FloatingPointError("Three consecutive nonfinite optimizer attempts; recoverable checkpoint saved")
560
+ if args.max_steps is not None and global_step >= args.max_steps:
561
+ break
562
+ if cursor == len(selected):
563
+ append_jsonl(metrics_path, {"event": "epoch_coverage", "epoch": epoch, "unique_records": cursor,
564
+ "expected_records": len(selected), "complete": True, "drop_last": False})
565
+ epoch += 1
566
+ cursor = 0
567
+ if epoch % args.val_every == 0:
568
+ rng_before = capture_rng()
569
+ report = evaluate_real(model, args.manifest, "val", device, args.batch_size, args.patch_size,
570
+ args.num_workers, args.quick_val_records, args.seed, functional_enabled=not args.no_proxy)
571
+ restore_rng(rng_before)
572
+ score = report["classification"]["macro_f1"]
573
+ append_jsonl(metrics_path, {"event": "validation", "epoch": epoch, "step": global_step, "report": report})
574
+ if score > best_score:
575
+ best_score = score
576
+ save("best.pt")
577
+ save()
578
+ rng_before = capture_rng()
579
+ report = evaluate_real(model, args.manifest, "val", device, args.batch_size, args.patch_size,
580
+ args.num_workers, None, args.seed, functional_enabled=not args.no_proxy)
581
+ restore_rng(rng_before)
582
+ final = {"status": "completed" if epoch == args.epochs else "smoke_step_cap", "epoch": epoch, "cursor": cursor,
583
+ "global_step": global_step, "optimizer_steps": optimizer_steps, "skipped_steps": skipped,
584
+ "elapsed_seconds": time.monotonic() - started, "full_validation": report}
585
+ atomic_json_save(final, output / "final_validation.json")
586
+ # A capped first epoch may have no quick-validation checkpoint yet.
587
+ if not (output / "best.pt").exists():
588
+ best_score = report["classification"]["macro_f1"]
589
+ save("best.pt")
590
+ save()
591
+ print(json.dumps(final), flush=True)
592
+ return final
593
+
594
+
595
+ if __name__ == "__main__":
596
+ main()
dataset/phase1_noise_20260906/code/train_phase2_gated_resshift_v5.py ADDED
@@ -0,0 +1,1145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train Phase 2 v5 with continuous soft experts and DA-CLIP-style control.
3
+
4
+ The audited v4 data/DDP/AMP/checkpoint runtime is reused without modifying its
5
+ source. This entrypoint installs a scoped v5 backend for the duration of one
6
+ run: a five-way continuous router, zero-initialized expert adapters, learned
7
+ noise/time prompts, and an optional variance-preserving independent Gaussian
8
+ bank. The residual-shift schedule and exact posterior remain unchanged.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import contextlib
15
+ from dataclasses import dataclass
16
+ import hashlib
17
+ import math
18
+ from pathlib import Path
19
+ from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple
20
+
21
+ import torch
22
+ from torch import Tensor, nn
23
+
24
+ import train_phase2_graph_resshift_v4 as v4
25
+ from src.models.restoration.gated_graph_resshift_v5 import (
26
+ EXPERT_KAPPA_VERSION,
27
+ EXPERT_ORDER,
28
+ NOISE_MIXER_VERSION,
29
+ ROUTER_VERSION,
30
+ ExpertKappaSchedule,
31
+ GatedConditionBundleV5,
32
+ GatedGraphConditionerV5,
33
+ GatedGraphResidualShiftUNetV5,
34
+ VariancePreservingNoiseMixer,
35
+ )
36
+ from src.models.restoration.graph_resshift_v4 import (
37
+ BRANCH_ORDER,
38
+ FrozenPhase1,
39
+ ResidualShiftSchedule,
40
+ pad_to_multiple,
41
+ pixel_shuffle2,
42
+ pixel_unshuffle2,
43
+ )
44
+
45
+
46
+ V5_SCHEMA_VERSION = 5
47
+ V4_WARMSTART_MAPPING_VERSION = "shared_keys_strict_v1"
48
+ NOISE_SEED_VERSION = "legacy_shared_plus_per_sample_expert_bank_v2"
49
+
50
+ # Capture the stable backend before the scoped installer replaces names on the
51
+ # imported module. Calling these aliases avoids recursion inside the patch.
52
+ _V4_ARCHITECTURE = v4._architecture
53
+ _V4_DATA_PLAN = v4._data_plan
54
+ _V4_SCHEDULE_CONFIG = v4._schedule_config
55
+ _V4_LOAD_OR_CREATE_SPLITS = v4._load_or_create_splits
56
+ _V4_DETERMINISTIC_TRAINING_PLAN = v4.deterministic_training_plan
57
+ _V4_NOISE_FOR_RECORDS = v4._noise_for_records
58
+
59
+
60
+ @dataclass
61
+ class GatedTrainStepResult:
62
+ """Restoration objective plus routed-noise diagnostics."""
63
+
64
+ loss: Tensor
65
+ reconstruction_loss: Tensor
66
+ router_loss: Tensor
67
+ u0_prediction: Tensor
68
+ u0_target: Tensor
69
+ u_t: Tensor
70
+ mixed_noise: Tensor
71
+ kappa: Optional[Tensor] = None
72
+
73
+
74
+ class Phase2GatedRestorationModule(nn.Module):
75
+ """Trainable v5 module; frozen Phase-1 remains outside this object."""
76
+
77
+ def __init__(
78
+ self,
79
+ conditioner: GatedGraphConditionerV5,
80
+ denoiser: nn.Module,
81
+ schedule: ResidualShiftSchedule,
82
+ noise_mixer: VariancePreservingNoiseMixer,
83
+ condition_mode: str,
84
+ *,
85
+ router_anchor_weight: float = 0.01,
86
+ router_balance_weight: float = 0.01,
87
+ router_correction_weight: float = 0.001,
88
+ expert_kappa: Optional[ExpertKappaSchedule] = None,
89
+ ) -> None:
90
+ super().__init__()
91
+ if condition_mode not in ("full", "null"):
92
+ raise ValueError("condition_mode must be 'full' or 'null'")
93
+ for name, value in (
94
+ ("router_anchor_weight", router_anchor_weight),
95
+ ("router_balance_weight", router_balance_weight),
96
+ ("router_correction_weight", router_correction_weight),
97
+ ):
98
+ if not math.isfinite(value) or value < 0.0:
99
+ raise ValueError("%s must be finite and non-negative" % name)
100
+ self.conditioner = conditioner
101
+ self.denoiser = denoiser
102
+ self.schedule = schedule
103
+ self.noise_mixer = noise_mixer
104
+ self.condition_mode = condition_mode
105
+ self.router_anchor_weight = float(router_anchor_weight)
106
+ self.router_balance_weight = float(router_balance_weight)
107
+ self.router_correction_weight = float(router_correction_weight)
108
+ self.expert_kappa = expert_kappa
109
+
110
+ def build_condition(self, representation: Any) -> GatedConditionBundleV5:
111
+ return self.conditioner(representation, mode=self.condition_mode)
112
+
113
+ def effective_kappa(
114
+ self, condition: GatedConditionBundleV5
115
+ ) -> Optional[Tensor]:
116
+ """Per-sample kappa for the current gate, or None for the global one."""
117
+
118
+ if self.expert_kappa is None:
119
+ return None
120
+ return self.expert_kappa(
121
+ condition.expert_gates, condition.route_active
122
+ )
123
+
124
+ def predict_x0(
125
+ self,
126
+ u_t: Tensor,
127
+ u_y: Tensor,
128
+ timesteps: Tensor,
129
+ condition: GatedConditionBundleV5,
130
+ ) -> Tensor:
131
+ return self.denoiser(u_t, u_y, timesteps, condition)
132
+
133
+ def route_noise(
134
+ self, noise_bank: Tensor, condition: GatedConditionBundleV5
135
+ ) -> Tensor:
136
+ return self.noise_mixer(
137
+ noise_bank,
138
+ condition.expert_gates,
139
+ condition.route_active,
140
+ )
141
+
142
+ def forward(
143
+ self,
144
+ clean: Tensor,
145
+ degraded: Tensor,
146
+ representation: Any,
147
+ timesteps: Tensor,
148
+ noise: Tensor,
149
+ ) -> Tensor:
150
+ # DDP must see the loss through forward, exactly as in v4.
151
+ return self.training_loss(
152
+ clean, degraded, representation, timesteps, noise
153
+ ).loss
154
+
155
+ def training_loss(
156
+ self,
157
+ clean: Tensor,
158
+ degraded: Tensor,
159
+ representation: Any,
160
+ timesteps: Tensor,
161
+ noise_bank: Tensor,
162
+ ) -> GatedTrainStepResult:
163
+ """FP32 x0 MSE plus label-free router regularization."""
164
+
165
+ u0 = pixel_unshuffle2(clean)
166
+ uy = pixel_unshuffle2(degraded)
167
+ condition = self.build_condition(representation)
168
+ # Kappa is read at the CURRENT anneal position, then the counter
169
+ # advances, so the first training microstep is exactly v4-equivalent.
170
+ kappa = self.effective_kappa(condition)
171
+ mixed_noise = self.route_noise(noise_bank, condition)
172
+ if mixed_noise.shape != u0.shape:
173
+ raise ValueError("routed noise must match the diffusion state")
174
+ u_t = self.schedule.q_sample(
175
+ u0, uy, timesteps, noise=mixed_noise, kappa=kappa
176
+ )
177
+ prediction = self.predict_x0(u_t, uy, timesteps, condition)
178
+ reconstruction = (prediction.float() - u0.float()).square().mean()
179
+ router_loss = (
180
+ self.router_anchor_weight * condition.router_anchor_loss.float()
181
+ + self.router_balance_weight * condition.router_balance_loss.float()
182
+ + self.router_correction_weight
183
+ * condition.router_correction_loss.float()
184
+ )
185
+ total = reconstruction + router_loss
186
+ if self.expert_kappa is not None and self.training:
187
+ self.expert_kappa.advance()
188
+ return GatedTrainStepResult(
189
+ loss=total,
190
+ reconstruction_loss=reconstruction,
191
+ router_loss=router_loss,
192
+ u0_prediction=prediction,
193
+ u0_target=u0,
194
+ u_t=u_t,
195
+ mixed_noise=mixed_noise,
196
+ kappa=None if kappa is None else kappa.detach(),
197
+ )
198
+
199
+
200
+ def deterministic_expert_training_plan(
201
+ reference: Tensor,
202
+ timesteps: int,
203
+ seed: int,
204
+ global_microstep: int,
205
+ rank: int = 0,
206
+ sample_seeds: Optional[Sequence[int]] = None,
207
+ num_experts: int = len(EXPERT_ORDER),
208
+ ) -> Tuple[Tensor, Tensor]:
209
+ """Create a legacy shared stream plus independent expert Gaussians.
210
+
211
+ Rank/order invariance requires the per-sample identities emitted by the
212
+ balanced sampler. Without ``sample_seeds`` the fallback deliberately
213
+ retains v4's rank-local behavior.
214
+ """
215
+
216
+ if reference.ndim != 4:
217
+ raise ValueError("reference must be a BCHW diffusion state")
218
+ if timesteps < 1 or num_experts < 1:
219
+ raise ValueError("timesteps and num_experts must be positive")
220
+ batch = reference.shape[0]
221
+ if sample_seeds is not None and len(sample_seeds) != batch:
222
+ raise ValueError("one sample seed is required per image")
223
+
224
+ cpu_reference = torch.empty(
225
+ tuple(reference.shape), device="cpu", dtype=reference.dtype
226
+ )
227
+ legacy_timesteps, legacy_noise = _V4_DETERMINISTIC_TRAINING_PLAN(
228
+ cpu_reference,
229
+ timesteps,
230
+ seed,
231
+ global_microstep,
232
+ rank=rank,
233
+ sample_seeds=sample_seeds,
234
+ )
235
+ banks: List[Tensor] = []
236
+ for index in range(batch):
237
+ sample_identity: Any
238
+ if sample_seeds is None:
239
+ sample_identity = ("rank", int(rank), "index", index)
240
+ else:
241
+ sample_identity = int(sample_seeds[index])
242
+ streams: List[Tensor] = [legacy_noise[index]]
243
+ for expert_index in range(num_experts):
244
+ generator = torch.Generator(device="cpu")
245
+ generator.manual_seed(
246
+ v4._seed_value(
247
+ seed,
248
+ "train-v5",
249
+ global_microstep,
250
+ sample_identity,
251
+ "expert-noise",
252
+ expert_index,
253
+ )
254
+ )
255
+ streams.append(
256
+ torch.randn(
257
+ tuple(reference[index].shape),
258
+ generator=generator,
259
+ dtype=torch.float32,
260
+ )
261
+ )
262
+ banks.append(torch.stack(streams, dim=0))
263
+ bank_tensor = torch.stack(banks, dim=0)
264
+ return legacy_timesteps.to(reference.device), bank_tensor.to(
265
+ device=reference.device, dtype=reference.dtype
266
+ )
267
+
268
+
269
+ def _noise_bank_for_records(
270
+ reference: Tensor,
271
+ record_ids: Optional[Sequence[str]],
272
+ seed: int,
273
+ stage: Any,
274
+ num_experts: int = len(EXPERT_ORDER),
275
+ ) -> Tensor:
276
+ if reference.ndim != 4:
277
+ raise ValueError("reference must be a BCHW diffusion state")
278
+ if record_ids is not None and len(record_ids) != reference.shape[0]:
279
+ raise ValueError("one record id is required per image")
280
+ cpu_reference = torch.empty(
281
+ tuple(reference.shape), device="cpu", dtype=reference.dtype
282
+ )
283
+ shared = _V4_NOISE_FOR_RECORDS(cpu_reference, record_ids, seed, stage)
284
+ samples: List[Tensor] = []
285
+ for index in range(reference.shape[0]):
286
+ identity = index if record_ids is None else str(record_ids[index])
287
+ streams: List[Tensor] = [shared[index]]
288
+ for expert_index in range(num_experts):
289
+ streams.append(
290
+ v4._cpu_random_tensor(
291
+ reference[index].shape,
292
+ v4._seed_value(
293
+ seed,
294
+ "eval-v5",
295
+ identity,
296
+ stage,
297
+ "expert-noise",
298
+ expert_index,
299
+ ),
300
+ reference.dtype,
301
+ )
302
+ )
303
+ samples.append(torch.stack(streams, dim=0))
304
+ return torch.stack(samples, dim=0).to(reference.device)
305
+
306
+
307
+ def _shared_noise_bank_for_records(
308
+ reference: Tensor,
309
+ record_ids: Optional[Sequence[str]],
310
+ seed: int,
311
+ stage: Any,
312
+ num_experts: int = len(EXPERT_ORDER),
313
+ ) -> Tensor:
314
+ """Expose legacy v4 noise as a zero-copy shared-only v5 bank."""
315
+
316
+ shared = _V4_NOISE_FOR_RECORDS(reference, record_ids, seed, stage)
317
+ return shared.unsqueeze(1).expand(
318
+ -1, num_experts + 1, -1, -1, -1
319
+ )
320
+
321
+
322
+ @torch.no_grad()
323
+ def sample_gated_restoration(
324
+ model: nn.Module,
325
+ phase1: FrozenPhase1,
326
+ degraded: Tensor,
327
+ *,
328
+ seed: int,
329
+ record_ids: Optional[Sequence[str]] = None,
330
+ initial_noise_bank: Optional[Tensor] = None,
331
+ amp_enabled: Optional[bool] = None,
332
+ ) -> Tensor:
333
+ """Run the unchanged exact posterior with one fixed soft gate per image."""
334
+
335
+ restorer = v4.unwrap_module(model)
336
+ if not isinstance(restorer, Phase2GatedRestorationModule):
337
+ raise TypeError("model must wrap Phase2GatedRestorationModule")
338
+ use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled)
339
+ with torch.cuda.amp.autocast(enabled=use_amp):
340
+ padded, original_size = pad_to_multiple(degraded, multiple=16)
341
+ representation = phase1(padded)
342
+ # The condition object, including its gate, is built exactly once and
343
+ # reused at every reverse step.
344
+ condition = restorer.build_condition(representation)
345
+ uy = pixel_unshuffle2(padded)
346
+ noise_bank_builder = (
347
+ _shared_noise_bank_for_records
348
+ if restorer.noise_mixer.expert_fraction_value == 0.0
349
+ else _noise_bank_for_records
350
+ )
351
+ expected_shape = (
352
+ uy.shape[0],
353
+ len(EXPERT_ORDER) + 1,
354
+ uy.shape[1],
355
+ uy.shape[2],
356
+ uy.shape[3],
357
+ )
358
+ if initial_noise_bank is None:
359
+ initial_noise_bank = noise_bank_builder(
360
+ uy, record_ids, seed=seed, stage="initial"
361
+ )
362
+ elif tuple(initial_noise_bank.shape) != expected_shape:
363
+ raise ValueError(
364
+ "initial_noise_bank must match [B, shared+experts, C, H, W]"
365
+ )
366
+ else:
367
+ initial_noise_bank = initial_noise_bank.to(
368
+ device=uy.device, dtype=uy.dtype
369
+ )
370
+
371
+ initial_noise = restorer.route_noise(initial_noise_bank, condition)
372
+ eta_terminal = restorer.schedule.eta[-1].to(
373
+ device=uy.device, dtype=uy.dtype
374
+ )
375
+ # One fixed per-sample kappa is used for the initial state and every
376
+ # posterior step, mirroring the fixed soft gate above.
377
+ kappa_override = restorer.effective_kappa(condition)
378
+ kappa = restorer.schedule.kappa_factor(kappa_override, uy)
379
+ u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise
380
+ batch = uy.shape[0]
381
+ for step in restorer.schedule.reverse_timesteps():
382
+ timesteps = torch.full(
383
+ (batch,), step, device=uy.device, dtype=torch.long
384
+ )
385
+ u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition)
386
+ mean, variance = restorer.schedule.posterior_mean_variance(
387
+ u_t, u0_hat, timesteps, kappa=kappa_override
388
+ )
389
+ if step > 1:
390
+ bank = noise_bank_builder(
391
+ u_t, record_ids, seed=seed, stage=step
392
+ )
393
+ routed_noise = restorer.route_noise(bank, condition)
394
+ u_t = mean + torch.sqrt(variance) * routed_noise
395
+ else:
396
+ u_t = mean
397
+ restored = pixel_shuffle2(u_t)
398
+ height, width = original_size
399
+ return restored[..., :height, :width].clamp(0.0, 1.0)
400
+
401
+
402
+ def _file_sha256(path: Path) -> str:
403
+ digest = hashlib.sha256()
404
+ with Path(path).open("rb") as handle:
405
+ while True:
406
+ block = handle.read(1024 * 1024)
407
+ if not block:
408
+ break
409
+ digest.update(block)
410
+ return digest.hexdigest()
411
+
412
+
413
+ def _is_v5_only_key(name: str) -> bool:
414
+ return name.startswith(
415
+ (
416
+ "conditioner.router.",
417
+ "denoiser.noise_type_tokens",
418
+ "denoiser.down_experts.",
419
+ "denoiser.up_experts.",
420
+ "noise_mixer.",
421
+ "expert_kappa.",
422
+ )
423
+ )
424
+
425
+
426
+ def _configure_trainable_paths(
427
+ model: Phase2GatedRestorationModule, *, train_shared_trunk: bool
428
+ ) -> None:
429
+ """Freeze the v4 restoration trunk for the controlled adapter-first arm."""
430
+
431
+ for name, parameter in model.named_parameters():
432
+ parameter.requires_grad_(
433
+ bool(train_shared_trunk) or _is_v5_only_key(name)
434
+ )
435
+
436
+
437
+ def _validate_adapter_only_output_head(
438
+ state: Mapping[str, Any], architecture: Mapping[str, Any], source: str
439
+ ) -> None:
440
+ optimization = architecture.get("optimization")
441
+ if not isinstance(optimization, Mapping):
442
+ raise ValueError("%s is missing v5 optimization provenance" % source)
443
+ shared_trainable = optimization.get("shared_trunk_trainable")
444
+ if not isinstance(shared_trainable, bool):
445
+ raise ValueError("%s has invalid shared-trunk provenance" % source)
446
+ if shared_trainable:
447
+ return
448
+ output_weight = state.get("denoiser.output_residual.weight")
449
+ if (
450
+ not isinstance(output_weight, Tensor)
451
+ or not bool(torch.isfinite(output_weight).all())
452
+ or int(torch.count_nonzero(output_weight).item()) == 0
453
+ ):
454
+ raise ValueError(
455
+ "%s adapter-only state requires a finite nonzero output head"
456
+ % source
457
+ )
458
+
459
+
460
+ def load_v4_warmstart(
461
+ path: Path,
462
+ expected_sha256: str,
463
+ model: Phase2GatedRestorationModule,
464
+ args: argparse.Namespace,
465
+ *,
466
+ weight_source: str,
467
+ expected_train_digest: str,
468
+ expected_val_digest: str,
469
+ ) -> Dict[str, Any]:
470
+ """Strictly materialize all shared v4 weights before exposing v5 state."""
471
+
472
+ actual_sha256 = _file_sha256(path)
473
+ if actual_sha256.lower() != str(expected_sha256).lower():
474
+ raise ValueError(
475
+ "v4 warmstart sha256 mismatch: expected %s, received %s"
476
+ % (expected_sha256, actual_sha256)
477
+ )
478
+ checkpoint = v4._torch_load(path, map_location="cpu")
479
+ if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2:
480
+ raise ValueError("warmstart must be a Phase-2 v4 checkpoint")
481
+ contract = checkpoint.get("contract")
482
+ if not isinstance(contract, Mapping):
483
+ raise ValueError("v4 warmstart is missing its canonical contract")
484
+ mirrored_fields = {
485
+ "condition_mode": "full",
486
+ "phase1_sha256": args.phase1_sha256,
487
+ "train_digest": str(expected_train_digest),
488
+ "val_digest": str(expected_val_digest),
489
+ }
490
+ for field, expected in mirrored_fields.items():
491
+ if checkpoint.get(field) != expected or contract.get(field) != expected:
492
+ raise ValueError("v4 warmstart %s mismatch" % field)
493
+ phase1_metadata = checkpoint.get("phase1_metadata", {})
494
+ if phase1_metadata != contract.get("phase1_metadata"):
495
+ raise ValueError("v4 warmstart Phase-1 metadata mirror mismatch")
496
+ if list(phase1_metadata.get("branch_order", ())) != list(BRANCH_ORDER):
497
+ raise ValueError("v4 warmstart branch_order mismatch")
498
+
499
+ architecture = checkpoint.get("architecture", {})
500
+ expected_architecture = _V4_ARCHITECTURE(args)
501
+ if contract.get("architecture") != architecture:
502
+ raise ValueError("v4 warmstart architecture mirror mismatch")
503
+ for field in ("name", "dims", "cond_dim", "state_channels"):
504
+ if architecture.get(field) != expected_architecture.get(field):
505
+ raise ValueError("v4 warmstart architecture %s mismatch" % field)
506
+ expected_schedule = _V4_SCHEDULE_CONFIG(args)
507
+ if (
508
+ checkpoint.get("schedule_config") != expected_schedule
509
+ or contract.get("schedule") != expected_schedule
510
+ ):
511
+ raise ValueError("v4 warmstart schedule mismatch")
512
+
513
+ if weight_source == "model":
514
+ state = checkpoint.get("model_state_dict")
515
+ elif weight_source == "ema":
516
+ ema_state = checkpoint.get("ema_state_dict")
517
+ state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None
518
+ else:
519
+ raise ValueError("weight_source must be 'model' or 'ema'")
520
+ if not isinstance(state, Mapping):
521
+ raise ValueError("v4 warmstart is missing the selected state")
522
+ if not bool(getattr(args, "train_shared_trunk", False)):
523
+ source_step = checkpoint.get("step")
524
+ if isinstance(source_step, bool) or not isinstance(source_step, int) or source_step <= 0:
525
+ raise ValueError(
526
+ "adapter-only warmstart requires a trained v4 checkpoint"
527
+ )
528
+ output_weight = state.get("denoiser.output_residual.weight")
529
+ if (
530
+ not isinstance(output_weight, Tensor)
531
+ or not bool(torch.isfinite(output_weight).all())
532
+ or int(torch.count_nonzero(output_weight).item()) == 0
533
+ ):
534
+ raise ValueError(
535
+ "adapter-only warmstart requires a finite nonzero v4 output head"
536
+ )
537
+
538
+ target_state = model.state_dict()
539
+ expected_shared = {
540
+ name for name in target_state.keys() if not _is_v5_only_key(name)
541
+ }
542
+ source_keys = set(state.keys())
543
+ if source_keys != expected_shared:
544
+ missing = sorted(expected_shared - source_keys)
545
+ unexpected = sorted(source_keys - expected_shared)
546
+ raise ValueError(
547
+ "v4 warmstart shared key mismatch; missing=%r unexpected=%r"
548
+ % (missing, unexpected)
549
+ )
550
+ for name in sorted(expected_shared):
551
+ value = state[name]
552
+ if not isinstance(value, Tensor) or value.shape != target_state[name].shape:
553
+ raise ValueError("v4 warmstart tensor shape mismatch: %s" % name)
554
+
555
+ result = model.load_state_dict(state, strict=False)
556
+ expected_missing = sorted(
557
+ name for name in target_state.keys() if _is_v5_only_key(name)
558
+ )
559
+ if sorted(result.missing_keys) != expected_missing or result.unexpected_keys:
560
+ raise RuntimeError("v4 warmstart loader violated its exact allowlist")
561
+
562
+ audit = {
563
+ "mapping_version": V4_WARMSTART_MAPPING_VERSION,
564
+ "source_checkpoint_sha256": actual_sha256,
565
+ "source_schema_version": 4,
566
+ "source_step": int(checkpoint.get("step", -1)),
567
+ "source_condition_mode": checkpoint.get("condition_mode"),
568
+ "weight_source": weight_source,
569
+ "source_train_digest": checkpoint.get("train_digest"),
570
+ "source_val_digest": checkpoint.get("val_digest"),
571
+ "materialized_state_hash": v4.model_state_hash(model),
572
+ }
573
+ return audit
574
+
575
+
576
+ def _neutral_warmstart_audit() -> Dict[str, Any]:
577
+ return {
578
+ "mapping_version": V4_WARMSTART_MAPPING_VERSION,
579
+ "source_checkpoint_sha256": None,
580
+ "source_schema_version": None,
581
+ "source_step": None,
582
+ "source_condition_mode": None,
583
+ "weight_source": None,
584
+ "source_train_digest": None,
585
+ "source_val_digest": None,
586
+ "materialized_state_hash": None,
587
+ }
588
+
589
+
590
+ def _stored_warmstart_audit(path: Path) -> Dict[str, Any]:
591
+ checkpoint = v4._torch_load(path, map_location="cpu")
592
+ if checkpoint.get("schema_version") != V5_SCHEMA_VERSION:
593
+ raise ValueError("v5 state source has the wrong schema_version")
594
+ contract = checkpoint.get("contract")
595
+ architecture = contract.get("architecture") if isinstance(contract, Mapping) else None
596
+ warmstart = architecture.get("warmstart") if isinstance(architecture, Mapping) else None
597
+ if not isinstance(warmstart, Mapping):
598
+ raise ValueError("v5 state source is missing warmstart audit")
599
+ return dict(warmstart)
600
+
601
+
602
+ def _parse_expert_kappa_values(value: Optional[str]) -> Tuple[float, ...]:
603
+ """Parse and fail-closed validate five comma-separated expert kappas."""
604
+
605
+ if value is None:
606
+ raise ValueError("--expert-kappa requires --expert-kappa-values")
607
+ parts = [part.strip() for part in str(value).split(",")]
608
+ if len(parts) != len(EXPERT_ORDER):
609
+ raise ValueError(
610
+ "--expert-kappa-values requires %d comma-separated values in "
611
+ "EXPERT_ORDER %r" % (len(EXPERT_ORDER), list(EXPERT_ORDER))
612
+ )
613
+ values = []
614
+ for name, part in zip(EXPERT_ORDER, parts):
615
+ try:
616
+ parsed = float(part)
617
+ except ValueError:
618
+ raise ValueError("expert kappa for %s is not a number" % name)
619
+ if not math.isfinite(parsed) or parsed <= 0.0:
620
+ raise ValueError(
621
+ "expert kappa for %s must be finite and positive" % name
622
+ )
623
+ values.append(parsed)
624
+ return tuple(values)
625
+
626
+
627
+ def _build_expert_kappa(
628
+ args: argparse.Namespace,
629
+ ) -> Optional[ExpertKappaSchedule]:
630
+ if not bool(getattr(args, "expert_kappa", False)):
631
+ return None
632
+ if args.kappa is None:
633
+ raise ValueError("--expert-kappa requires an explicit --kappa")
634
+ return ExpertKappaSchedule(
635
+ kappa_per_expert=_parse_expert_kappa_values(args.expert_kappa_values),
636
+ kappa_global=float(args.kappa),
637
+ anneal_microsteps=(
638
+ int(args.expert_kappa_anneal_steps) * int(args.grad_accum)
639
+ ),
640
+ )
641
+
642
+
643
+ def _build_v5_restorer(
644
+ args: argparse.Namespace, device: torch.device
645
+ ) -> Phase2GatedRestorationModule:
646
+ schedule = ResidualShiftSchedule(
647
+ timesteps=args.timesteps,
648
+ eta_end=args.eta_end,
649
+ min_noise=args.min_noise,
650
+ power=args.power,
651
+ kappa=args.kappa,
652
+ )
653
+ conditioner = GatedGraphConditionerV5(
654
+ cond_dim=args.cond_dim,
655
+ stage_dims=args.dims,
656
+ router_hidden_dim=args.router_hidden_dim,
657
+ router_temperature=args.router_temperature,
658
+ router_max_correction=args.router_max_correction,
659
+ )
660
+ denoiser = GatedGraphResidualShiftUNetV5(
661
+ dims=args.dims,
662
+ cond_dim=args.cond_dim,
663
+ adapter_rank=args.adapter_rank,
664
+ )
665
+ model = Phase2GatedRestorationModule(
666
+ conditioner=conditioner,
667
+ denoiser=denoiser,
668
+ schedule=schedule,
669
+ noise_mixer=VariancePreservingNoiseMixer(
670
+ num_experts=len(EXPERT_ORDER),
671
+ expert_fraction=args.expert_noise_fraction,
672
+ ),
673
+ condition_mode=args.condition,
674
+ router_anchor_weight=args.router_anchor_weight,
675
+ router_balance_weight=args.router_balance_weight,
676
+ router_correction_weight=args.router_correction_weight,
677
+ expert_kappa=_build_expert_kappa(args),
678
+ )
679
+
680
+ if args.resume is not None:
681
+ audit = _stored_warmstart_audit(args.resume)
682
+ elif args.init_checkpoint is not None:
683
+ audit = _stored_warmstart_audit(args.init_checkpoint)
684
+ elif args.warmstart_v4 is not None:
685
+ train_digest = getattr(args, "_v5_train_digest", None)
686
+ val_digest = getattr(args, "_v5_val_digest", None)
687
+ if not isinstance(train_digest, str) or not isinstance(val_digest, str):
688
+ raise RuntimeError("v5 split digests must be resolved before warmstart")
689
+ audit = load_v4_warmstart(
690
+ args.warmstart_v4,
691
+ args.warmstart_v4_sha256,
692
+ model,
693
+ args,
694
+ weight_source=args.warmstart_weight_source,
695
+ expected_train_digest=train_digest,
696
+ expected_val_digest=val_digest,
697
+ )
698
+ else:
699
+ audit = _neutral_warmstart_audit()
700
+ _configure_trainable_paths(
701
+ model, train_shared_trunk=bool(args.train_shared_trunk)
702
+ )
703
+ setattr(args, "_v5_warmstart_audit", audit)
704
+ return model.to(device)
705
+
706
+
707
+ def _v5_architecture(args: argparse.Namespace) -> Dict[str, Any]:
708
+ audit = getattr(args, "_v5_warmstart_audit", None)
709
+ if not isinstance(audit, Mapping):
710
+ raise RuntimeError("v5 warmstart audit must be resolved before architecture")
711
+ return {
712
+ "name": "gated_graph_resshift_v5",
713
+ "version": 5,
714
+ "dims": list(args.dims),
715
+ "cond_dim": int(args.cond_dim),
716
+ "state_channels": 12,
717
+ "pixel_unshuffle_factor": 2,
718
+ "denoiser_input_channels": 36,
719
+ "prediction": "x0",
720
+ "expert_order": list(EXPERT_ORDER),
721
+ "router": {
722
+ "version": ROUTER_VERSION,
723
+ "temperature": float(args.router_temperature),
724
+ "max_correction": float(args.router_max_correction),
725
+ "hidden_dim": int(args.router_hidden_dim),
726
+ "balance_scope": "rank_local_microbatch_v1",
727
+ },
728
+ "adapters": {
729
+ "rank": int(args.adapter_rank),
730
+ "placements": ["down0", "down1", "down2", "down3", "up2", "up1", "up0"],
731
+ "output_initialization": "zero",
732
+ },
733
+ "noise_type_prompt": "zero_initialized_gate_weighted_tokens_v1",
734
+ "optimization": {
735
+ "shared_trunk_trainable": bool(args.train_shared_trunk),
736
+ "new_paths_trainable": True,
737
+ },
738
+ "warmstart": dict(audit),
739
+ }
740
+
741
+
742
+ def _v5_schedule_config(args: argparse.Namespace) -> Dict[str, Any]:
743
+ result = dict(_V4_SCHEDULE_CONFIG(args))
744
+ result["noise_routing"] = {
745
+ "mixer": NOISE_MIXER_VERSION,
746
+ "expert_fraction": float(args.expert_noise_fraction),
747
+ "gate_gradient": "stopped",
748
+ "schedule_modified": False,
749
+ "distribution_semantics": "iid_standard_normal_stochastic_ablation",
750
+ }
751
+ enabled = bool(getattr(args, "expert_kappa", False))
752
+ result["expert_kappa"] = {
753
+ "enabled": enabled,
754
+ "version": EXPERT_KAPPA_VERSION if enabled else None,
755
+ "values": (
756
+ list(_parse_expert_kappa_values(args.expert_kappa_values))
757
+ if enabled
758
+ else None
759
+ ),
760
+ "anneal_steps": (
761
+ int(args.expert_kappa_anneal_steps) if enabled else None
762
+ ),
763
+ "gate_gradient": "stopped",
764
+ "posterior": "exact_per_sample_kappa",
765
+ "modifies_forward_kappa": enabled,
766
+ }
767
+ return result
768
+
769
+
770
+ def _v5_data_plan(
771
+ args: argparse.Namespace,
772
+ world_size: int,
773
+ amp_enabled: Optional[bool] = None,
774
+ ) -> Dict[str, Any]:
775
+ result = dict(_V4_DATA_PLAN(args, world_size, amp_enabled=amp_enabled))
776
+ result["noise_plan"] = NOISE_SEED_VERSION
777
+ result["router_balance_topology"] = {
778
+ "scope": "rank_local_microbatch_v1",
779
+ "world_size": int(world_size),
780
+ "local_batch": int(args.batch_size),
781
+ }
782
+ return result
783
+
784
+
785
+ def save_v5_training_checkpoint(
786
+ path: Path,
787
+ model: nn.Module,
788
+ ema: v4.ExponentialMovingAverage,
789
+ optimizer: torch.optim.Optimizer,
790
+ scheduler: torch.optim.lr_scheduler._LRScheduler,
791
+ scaler: torch.cuda.amp.GradScaler,
792
+ *,
793
+ step: int,
794
+ contract: v4.CheckpointContract,
795
+ history: Sequence[Mapping[str, Any]],
796
+ recovery_marker: Optional[Mapping[str, Any]] = None,
797
+ ) -> None:
798
+ payload: Dict[str, Any] = {
799
+ "schema_version": V5_SCHEMA_VERSION,
800
+ "phase": 2,
801
+ "architecture_version": 5,
802
+ "step": int(step),
803
+ "model_state_dict": v4.unwrap_module(model).state_dict(),
804
+ "ema_state_dict": ema.state_dict(),
805
+ "optimizer_state_dict": optimizer.state_dict(),
806
+ "scheduler_state_dict": scheduler.state_dict(),
807
+ "scaler_state_dict": scaler.state_dict(),
808
+ "rng_state": v4._rng_state(),
809
+ "contract": contract.to_dict(),
810
+ "condition_mode": contract.condition_mode,
811
+ "phase1_sha256": contract.phase1_sha256,
812
+ "phase1_metadata": dict(contract.phase1_metadata),
813
+ "train_digest": contract.train_digest,
814
+ "val_digest": contract.val_digest,
815
+ "schedule_config": dict(contract.schedule),
816
+ "architecture": dict(contract.architecture),
817
+ "data_plan": dict(contract.data_plan),
818
+ "warmstart_audit": dict(contract.architecture.get("warmstart", {})),
819
+ "init_model_hash": contract.init_model_hash,
820
+ "max_steps": contract.max_steps,
821
+ "ema_decay": contract.ema_decay,
822
+ "history": [dict(item) for item in history],
823
+ }
824
+ if recovery_marker is not None:
825
+ payload["recovery"] = dict(recovery_marker)
826
+ v4._atomic_torch_save(payload, Path(path))
827
+
828
+
829
+ def resume_v5_training_checkpoint(
830
+ path: Path,
831
+ model: nn.Module,
832
+ ema: v4.ExponentialMovingAverage,
833
+ optimizer: torch.optim.Optimizer,
834
+ scheduler: torch.optim.lr_scheduler._LRScheduler,
835
+ scaler: torch.cuda.amp.GradScaler,
836
+ contract: v4.CheckpointContract,
837
+ ) -> v4.ResumeState:
838
+ checkpoint = v4._torch_load(path, map_location="cpu")
839
+ if checkpoint.get("schema_version") != V5_SCHEMA_VERSION or checkpoint.get("phase") != 2:
840
+ raise ValueError("not a Phase-2 v5 checkpoint")
841
+ v4._validate_contract(checkpoint.get("contract", {}), contract)
842
+ for field in (
843
+ "condition_mode",
844
+ "phase1_sha256",
845
+ "phase1_metadata",
846
+ "train_digest",
847
+ "val_digest",
848
+ "schedule_config",
849
+ "architecture",
850
+ "data_plan",
851
+ "warmstart_audit",
852
+ "init_model_hash",
853
+ "max_steps",
854
+ "ema_decay",
855
+ ):
856
+ if field == "schedule_config":
857
+ expected = contract.to_dict().get("schedule")
858
+ elif field == "warmstart_audit":
859
+ expected = contract.architecture.get("warmstart", {})
860
+ else:
861
+ expected = contract.to_dict().get(field)
862
+ if checkpoint.get(field) != expected:
863
+ raise ValueError("v5 checkpoint top-level %s mismatch" % field)
864
+ state = checkpoint.get("model_state_dict")
865
+ if not isinstance(state, Mapping):
866
+ raise ValueError("v5 resume checkpoint is missing model state")
867
+ _validate_adapter_only_output_head(
868
+ state, contract.architecture, "v5 resume checkpoint"
869
+ )
870
+ ema_state = checkpoint.get("ema_state_dict")
871
+ ema_shadow = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None
872
+ if not isinstance(ema_shadow, Mapping):
873
+ raise ValueError("v5 resume checkpoint is missing EMA shadow state")
874
+ _validate_adapter_only_output_head(
875
+ ema_shadow, contract.architecture, "v5 resume EMA"
876
+ )
877
+ v4.unwrap_module(model).load_state_dict(state, strict=True)
878
+ ema.load_state_dict(ema_state)
879
+ optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
880
+ scheduler.load_state_dict(checkpoint["scheduler_state_dict"])
881
+ scaler.load_state_dict(checkpoint["scaler_state_dict"])
882
+ v4._restore_rng_state(checkpoint["rng_state"])
883
+ return v4.ResumeState(
884
+ step=int(checkpoint["step"]),
885
+ history=[dict(item) for item in checkpoint.get("history", [])],
886
+ )
887
+
888
+
889
+ def load_shared_initialization_v5(
890
+ path: Path,
891
+ model: nn.Module,
892
+ *,
893
+ target_condition: str,
894
+ expected_architecture: Mapping[str, Any],
895
+ expected_schedule: Mapping[str, Any],
896
+ expected_data_plan: Mapping[str, Any],
897
+ expected_phase1_sha256: str,
898
+ expected_phase1_metadata: Mapping[str, Any],
899
+ expected_train_digest: str,
900
+ expected_val_digest: str,
901
+ expected_max_steps: int,
902
+ expected_ema_decay: float,
903
+ ) -> str:
904
+ checkpoint = v4._torch_load(path, map_location="cpu")
905
+ if checkpoint.get("schema_version") != V5_SCHEMA_VERSION or checkpoint.get("phase") != 2:
906
+ raise ValueError("initialization must be a Phase-2 v5 checkpoint")
907
+ if checkpoint.get("step") != 0:
908
+ raise ValueError("shared initialization checkpoint must be at step zero")
909
+ source_contract = checkpoint.get("contract")
910
+ if not isinstance(source_contract, Mapping):
911
+ raise ValueError("initialization checkpoint is missing its contract")
912
+ expected_fields: Dict[str, Any] = {
913
+ "architecture": dict(expected_architecture),
914
+ "schedule": dict(expected_schedule),
915
+ "data_plan": dict(expected_data_plan),
916
+ "phase1_sha256": str(expected_phase1_sha256),
917
+ "phase1_metadata": dict(expected_phase1_metadata),
918
+ "train_digest": str(expected_train_digest),
919
+ "val_digest": str(expected_val_digest),
920
+ "max_steps": int(expected_max_steps),
921
+ "ema_decay": float(expected_ema_decay),
922
+ }
923
+ for field, expected in expected_fields.items():
924
+ if source_contract.get(field) != expected:
925
+ raise ValueError("shared v5 initialization %s mismatch" % field)
926
+ mirror = "schedule_config" if field == "schedule" else field
927
+ if checkpoint.get(mirror) != expected:
928
+ raise ValueError("shared v5 top-level %s mismatch" % mirror)
929
+ source_condition = source_contract.get("condition_mode")
930
+ if source_condition != target_condition and not (
931
+ source_condition == "null" and target_condition == "full"
932
+ ):
933
+ raise ValueError("shared v5 condition transition is forbidden")
934
+ state = checkpoint.get("model_state_dict")
935
+ if not isinstance(state, Mapping):
936
+ raise ValueError("shared v5 initialization has no model state")
937
+ _validate_adapter_only_output_head(
938
+ state, expected_architecture, "shared v5 initialization"
939
+ )
940
+ target = v4.unwrap_module(model)
941
+ # Schedule buffers are scientific configuration rather than trainable
942
+ # initialization. Verify their bytes before any state mutates the target.
943
+ for name, expected_value in target.schedule.state_dict().items():
944
+ source_value = state.get("schedule." + name)
945
+ if not isinstance(source_value, Tensor) or not torch.equal(
946
+ source_value.detach().cpu(), expected_value.detach().cpu()
947
+ ):
948
+ raise ValueError(
949
+ "shared v5 initialization schedule buffer mismatch: %s" % name
950
+ )
951
+ target.load_state_dict(state, strict=True)
952
+ actual_hash = v4.model_state_hash(target)
953
+ if (
954
+ source_contract.get("init_model_hash") != actual_hash
955
+ or checkpoint.get("init_model_hash") != actual_hash
956
+ ):
957
+ raise ValueError("shared v5 initialization model hash mismatch")
958
+ return actual_hash
959
+
960
+
961
+ def build_parser() -> argparse.ArgumentParser:
962
+ parser = v4.build_parser()
963
+ parser.description = __doc__
964
+ parser.add_argument("--adapter-rank", type=int, default=16)
965
+ parser.add_argument("--router-hidden-dim", type=int, default=256)
966
+ parser.add_argument("--router-temperature", type=float, default=1.0)
967
+ parser.add_argument("--router-max-correction", type=float, default=2.0)
968
+ parser.add_argument("--router-anchor-weight", type=float, default=0.01)
969
+ parser.add_argument("--router-balance-weight", type=float, default=0.01)
970
+ parser.add_argument("--router-correction-weight", type=float, default=0.001)
971
+ parser.add_argument(
972
+ "--expert-noise-fraction",
973
+ type=float,
974
+ default=0.0,
975
+ help="conditional variance fraction from the independent expert bank",
976
+ )
977
+ parser.add_argument(
978
+ "--expert-kappa",
979
+ action="store_true",
980
+ help="scale forward corruption with a gate-weighted per-type kappa",
981
+ )
982
+ parser.add_argument(
983
+ "--expert-kappa-values",
984
+ type=str,
985
+ default=None,
986
+ help="five comma-separated kappas in EXPERT_ORDER "
987
+ "(rain,noise,haze,lowlight,generic)",
988
+ )
989
+ parser.add_argument(
990
+ "--expert-kappa-anneal-steps",
991
+ type=int,
992
+ default=2000,
993
+ help="optimizer steps to anneal from the global kappa to the "
994
+ "gate-weighted per-type kappa (0 disables the anneal)",
995
+ )
996
+ parser.add_argument(
997
+ "--train-shared-trunk",
998
+ action="store_true",
999
+ help="also fine-tune v4 shared weights; default trains only v5 paths",
1000
+ )
1001
+ parser.add_argument("--warmstart-v4", type=Path)
1002
+ parser.add_argument("--warmstart-v4-sha256")
1003
+ parser.add_argument(
1004
+ "--warmstart-weight-source", choices=("ema", "model"), default="ema"
1005
+ )
1006
+ return parser
1007
+
1008
+
1009
+ def validate_v5_runtime_args(args: argparse.Namespace) -> int:
1010
+ stop_step = v4.validate_runtime_args(args)
1011
+ if args.adapter_rank <= 0 or args.router_hidden_dim <= 0:
1012
+ raise ValueError("adapter and router dimensions must be positive")
1013
+ for name in (
1014
+ "router_temperature",
1015
+ "router_max_correction",
1016
+ ):
1017
+ value = float(getattr(args, name))
1018
+ if not math.isfinite(value) or value <= 0.0:
1019
+ raise ValueError("%s must be finite and positive" % name)
1020
+ for name in (
1021
+ "router_anchor_weight",
1022
+ "router_balance_weight",
1023
+ "router_correction_weight",
1024
+ ):
1025
+ value = float(getattr(args, name))
1026
+ if not math.isfinite(value) or value < 0.0:
1027
+ raise ValueError("%s must be finite and non-negative" % name)
1028
+ if not math.isfinite(args.expert_noise_fraction) or not 0.0 <= args.expert_noise_fraction <= 1.0:
1029
+ raise ValueError("--expert-noise-fraction must lie in [0, 1]")
1030
+ if bool(getattr(args, "expert_kappa", False)):
1031
+ _parse_expert_kappa_values(args.expert_kappa_values)
1032
+ if args.kappa is None:
1033
+ raise ValueError("--expert-kappa requires an explicit --kappa")
1034
+ if int(args.expert_kappa_anneal_steps) < 0:
1035
+ raise ValueError(
1036
+ "--expert-kappa-anneal-steps must be non-negative"
1037
+ )
1038
+ elif getattr(args, "expert_kappa_values", None) is not None:
1039
+ raise ValueError(
1040
+ "--expert-kappa-values is only valid together with --expert-kappa"
1041
+ )
1042
+ has_warmstart_path = args.warmstart_v4 is not None
1043
+ has_warmstart_sha = args.warmstart_v4_sha256 is not None
1044
+ if has_warmstart_path != has_warmstart_sha:
1045
+ raise ValueError("v4 warmstart path and sha256 must be supplied together")
1046
+ if (args.resume is not None or args.init_checkpoint is not None) and (
1047
+ has_warmstart_path or has_warmstart_sha
1048
+ ):
1049
+ raise ValueError("v5 resume/init and v4 warmstart are mutually exclusive")
1050
+ if has_warmstart_sha:
1051
+ value = str(args.warmstart_v4_sha256).lower()
1052
+ if len(value) != 64 or any(character not in "0123456789abcdef" for character in value):
1053
+ raise ValueError("v4 warmstart sha256 must be 64 hexadecimal characters")
1054
+ has_state_source = (
1055
+ args.resume is not None
1056
+ or args.init_checkpoint is not None
1057
+ or has_warmstart_path
1058
+ )
1059
+ if (
1060
+ not args.calibrate_kappa
1061
+ and not args.train_shared_trunk
1062
+ and not has_state_source
1063
+ ):
1064
+ raise ValueError(
1065
+ "adapter-only training requires a v4 warmstart or v5 state source"
1066
+ )
1067
+ return stop_step
1068
+
1069
+
1070
+ @contextlib.contextmanager
1071
+ def _installed_v5_backend(args: argparse.Namespace) -> Iterator[None]:
1072
+ """Temporarily route the stable v4 runtime through v5 implementations."""
1073
+
1074
+ def training_plan(
1075
+ reference: Tensor,
1076
+ timesteps: int,
1077
+ seed: int,
1078
+ global_microstep: int,
1079
+ rank: int = 0,
1080
+ sample_seeds: Optional[Sequence[int]] = None,
1081
+ ) -> Tuple[Tensor, Tensor]:
1082
+ if float(args.expert_noise_fraction) == 0.0:
1083
+ timestep_values, shared = _V4_DETERMINISTIC_TRAINING_PLAN(
1084
+ reference,
1085
+ timesteps,
1086
+ seed,
1087
+ global_microstep,
1088
+ rank=rank,
1089
+ sample_seeds=sample_seeds,
1090
+ )
1091
+ shared_bank = shared.unsqueeze(1).expand(
1092
+ -1, len(EXPERT_ORDER) + 1, -1, -1, -1
1093
+ )
1094
+ return timestep_values, shared_bank
1095
+ return deterministic_expert_training_plan(
1096
+ reference,
1097
+ timesteps,
1098
+ seed,
1099
+ global_microstep,
1100
+ rank=rank,
1101
+ sample_seeds=sample_seeds,
1102
+ )
1103
+
1104
+ def load_or_create_splits(runtime_args: argparse.Namespace) -> Any:
1105
+ splits = _V4_LOAD_OR_CREATE_SPLITS(runtime_args)
1106
+ from src.data.phase2_v4 import split_digest
1107
+
1108
+ setattr(runtime_args, "_v5_train_digest", split_digest(splits.train))
1109
+ setattr(runtime_args, "_v5_val_digest", split_digest(splits.val))
1110
+ return splits
1111
+
1112
+ replacements = {
1113
+ "_build_restorer": _build_v5_restorer,
1114
+ "_load_or_create_splits": load_or_create_splits,
1115
+ "_architecture": _v5_architecture,
1116
+ "_schedule_config": _v5_schedule_config,
1117
+ "_data_plan": _v5_data_plan,
1118
+ "deterministic_training_plan": training_plan,
1119
+ "sample_restoration": sample_gated_restoration,
1120
+ "save_training_checkpoint": save_v5_training_checkpoint,
1121
+ "resume_training_checkpoint": resume_v5_training_checkpoint,
1122
+ "load_shared_initialization": load_shared_initialization_v5,
1123
+ }
1124
+ originals = {name: getattr(v4, name) for name in replacements}
1125
+ try:
1126
+ for name, replacement in replacements.items():
1127
+ setattr(v4, name, replacement)
1128
+ yield
1129
+ finally:
1130
+ for name, original in originals.items():
1131
+ setattr(v4, name, original)
1132
+
1133
+
1134
+ def run(args: argparse.Namespace) -> None:
1135
+ validate_v5_runtime_args(args)
1136
+ with _installed_v5_backend(args):
1137
+ v4.run(args)
1138
+
1139
+
1140
+ def main(argv: Optional[Sequence[str]] = None) -> None:
1141
+ run(build_parser().parse_args(argv))
1142
+
1143
+
1144
+ if __name__ == "__main__":
1145
+ main()
dataset/phase1_noise_20260906/code/train_phase2_graph_moe_v6.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Phase 2 v6: graph-MoE restoration on the ll_v3 Phase-1 representation.
3
+
4
+ Reuses the stable v4 runtime through a scoped backend install (the v5
5
+ pattern). Differences from v5:
6
+
7
+ * independent per-node sigmoid activations, strength = a_k * severity_k,
8
+ spatial expert gating, 3x3 experts, top-2 execution (graph_moe_v6.py);
9
+ * per-node kappa from normalized strengths (A7 machinery);
10
+ * the shared trunk FINETUNES (new Phase-1 changes the conditioning
11
+ distribution, so a frozen trunk would be mis-conditioned) — use
12
+ --learning-rate 5e-5;
13
+ * cross-Phase-1 warm start: v4 weights load although the Phase-1 checkpoint
14
+ differs; both SHAs are recorded in the audit;
15
+ * evaluation samples with --eval-sample-steps (default 1, the measured
16
+ strongest mode).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import contextlib
23
+ import hashlib
24
+ import math
25
+ from dataclasses import dataclass
26
+ from pathlib import Path
27
+ from typing import Any, Dict, Iterator, Mapping, Optional, Sequence, Tuple
28
+
29
+ import torch
30
+ from torch import Tensor, nn
31
+
32
+ import train_phase2_graph_resshift_v4 as v4
33
+ from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule
34
+ from src.models.restoration.graph_moe_v6 import (
35
+ MOE_V6_VERSION,
36
+ NUM_EXPERTS,
37
+ MoEConditionBundleV6,
38
+ MoEGraphConditionerV6,
39
+ MoEGraphResidualShiftUNetV6,
40
+ expert_kappa_from_strengths,
41
+ )
42
+ from src.models.restoration.graph_resshift_v4 import (
43
+ FrozenPhase1,
44
+ ResidualShiftSchedule,
45
+ pad_to_multiple,
46
+ pixel_shuffle2,
47
+ pixel_unshuffle2,
48
+ )
49
+
50
+ V6_WARMSTART_MAPPING_VERSION = "cross_phase1_shared_keys_v1"
51
+ DEFAULT_KAPPA_VALUES = "0.09780,0.03836,0.13436,0.41464,0.11608"
52
+
53
+ _V4_ARCHITECTURE = v4._architecture
54
+ _V4_SCHEDULE_CONFIG = v4._schedule_config
55
+ _V4_DATA_PLAN = v4._data_plan
56
+
57
+
58
+ def _is_v6_only_key(name: str) -> bool:
59
+ return name.startswith(
60
+ (
61
+ "conditioner.node_gate.",
62
+ "denoiser.strength_tokens",
63
+ "denoiser.down_experts.",
64
+ "denoiser.up_experts.",
65
+ "expert_kappa.",
66
+ )
67
+ )
68
+
69
+
70
+ @dataclass
71
+ class MoETrainStepResult:
72
+ loss: Tensor
73
+ reconstruction_loss: Tensor
74
+ gate_loss: Tensor
75
+ u0_prediction: Tensor
76
+ u0_target: Tensor
77
+ u_t: Tensor
78
+ kappa: Tensor
79
+
80
+
81
+ class Phase2MoEV6Module(nn.Module):
82
+ """Trainable v6 module; the frozen Phase-1 encoder stays outside."""
83
+
84
+ def __init__(
85
+ self,
86
+ conditioner: MoEGraphConditionerV6,
87
+ denoiser: MoEGraphResidualShiftUNetV6,
88
+ schedule: ResidualShiftSchedule,
89
+ expert_kappa: ExpertKappaSchedule,
90
+ condition_mode: str,
91
+ *,
92
+ gate_anchor_weight: float = 0.05,
93
+ gate_correction_weight: float = 0.001,
94
+ ) -> None:
95
+ super().__init__()
96
+ if condition_mode not in ("full", "null"):
97
+ raise ValueError("condition_mode must be 'full' or 'null'")
98
+ self.conditioner = conditioner
99
+ self.denoiser = denoiser
100
+ self.schedule = schedule
101
+ self.expert_kappa = expert_kappa
102
+ self.condition_mode = condition_mode
103
+ self.gate_anchor_weight = float(gate_anchor_weight)
104
+ self.gate_correction_weight = float(gate_correction_weight)
105
+ self.eval_sample_steps = 1
106
+
107
+ def build_condition(self, representation: Any) -> MoEConditionBundleV6:
108
+ return self.conditioner(representation, mode=self.condition_mode)
109
+
110
+ def predict_x0(
111
+ self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition
112
+ ) -> Tensor:
113
+ return self.denoiser(u_t, u_y, timesteps, condition)
114
+
115
+ def effective_kappa(self, condition: MoEConditionBundleV6) -> Tensor:
116
+ return expert_kappa_from_strengths(
117
+ self.expert_kappa, condition.gate, condition.route_active
118
+ )
119
+
120
+ def forward(
121
+ self,
122
+ clean: Tensor,
123
+ degraded: Tensor,
124
+ representation: Any,
125
+ timesteps: Tensor,
126
+ noise: Optional[Tensor] = None,
127
+ ) -> Tensor:
128
+ return self.training_loss(
129
+ clean, degraded, representation, timesteps, noise=noise
130
+ ).loss
131
+
132
+ def training_loss(
133
+ self,
134
+ clean: Tensor,
135
+ degraded: Tensor,
136
+ representation: Any,
137
+ timesteps: Tensor,
138
+ noise: Optional[Tensor] = None,
139
+ ) -> MoETrainStepResult:
140
+ u0 = pixel_unshuffle2(clean)
141
+ uy = pixel_unshuffle2(degraded)
142
+ condition = self.build_condition(representation)
143
+ kappa = self.effective_kappa(condition)
144
+ u_t = self.schedule.q_sample(u0, uy, timesteps, noise=noise, kappa=kappa)
145
+ prediction = self.predict_x0(u_t, uy, timesteps, condition)
146
+ reconstruction = (prediction.float() - u0.float()).square().mean()
147
+ gate_loss = (
148
+ self.gate_anchor_weight * condition.gate.anchor_loss.float()
149
+ + self.gate_correction_weight
150
+ * condition.gate.correction_loss.float()
151
+ )
152
+ if self.expert_kappa is not None and self.training:
153
+ self.expert_kappa.advance()
154
+ return MoETrainStepResult(
155
+ loss=reconstruction + gate_loss,
156
+ reconstruction_loss=reconstruction,
157
+ gate_loss=gate_loss,
158
+ u0_prediction=prediction,
159
+ u0_target=u0,
160
+ u_t=u_t,
161
+ kappa=kappa.detach(),
162
+ )
163
+
164
+
165
+ @torch.no_grad()
166
+ def sample_moe_restoration(
167
+ model: nn.Module,
168
+ phase1: FrozenPhase1,
169
+ degraded: Tensor,
170
+ *,
171
+ seed: int,
172
+ record_ids: Optional[Sequence[str]] = None,
173
+ initial_noise: Optional[Tensor] = None,
174
+ amp_enabled: Optional[bool] = None,
175
+ ) -> Tensor:
176
+ """One-step x0 by default; the exact posterior chain when configured."""
177
+
178
+ restorer = v4.unwrap_module(model)
179
+ if not isinstance(restorer, Phase2MoEV6Module):
180
+ raise TypeError("model must wrap Phase2MoEV6Module")
181
+ steps = int(getattr(restorer, "eval_sample_steps", 1))
182
+ use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled)
183
+ with torch.cuda.amp.autocast(enabled=use_amp):
184
+ padded, size = pad_to_multiple(degraded, multiple=16)
185
+ representation = phase1(padded)
186
+ condition = restorer.build_condition(representation)
187
+ uy = pixel_unshuffle2(padded)
188
+ if initial_noise is None:
189
+ initial_noise = v4._noise_for_records(
190
+ uy, list(record_ids) if record_ids else None,
191
+ seed=seed, stage="initial",
192
+ )
193
+ kappa_vector = restorer.effective_kappa(condition)
194
+ kappa = restorer.schedule.kappa_factor(kappa_vector, uy)
195
+ eta_terminal = restorer.schedule.eta[-1].to(uy.device, uy.dtype)
196
+ u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise
197
+ batch = uy.shape[0]
198
+ if steps <= 1:
199
+ timesteps = torch.full(
200
+ (batch,), restorer.schedule.timesteps,
201
+ device=uy.device, dtype=torch.long,
202
+ )
203
+ u_t = restorer.predict_x0(u_t, uy, timesteps, condition)
204
+ else:
205
+ for step in restorer.schedule.reverse_timesteps():
206
+ timesteps = torch.full(
207
+ (batch,), step, device=uy.device, dtype=torch.long
208
+ )
209
+ u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition)
210
+ mean, variance = restorer.schedule.posterior_mean_variance(
211
+ u_t, u0_hat, timesteps, kappa=kappa_vector
212
+ )
213
+ if step > 1:
214
+ noise = v4._noise_for_records(
215
+ u_t, list(record_ids) if record_ids else None,
216
+ seed=seed, stage=step,
217
+ )
218
+ u_t = mean + torch.sqrt(variance) * noise
219
+ else:
220
+ u_t = mean
221
+ restored = pixel_shuffle2(u_t)
222
+ height, width = size
223
+ return restored[..., :height, :width].clamp(0.0, 1.0)
224
+
225
+
226
+ def _file_sha256(path: Path) -> str:
227
+ digest = hashlib.sha256()
228
+ with Path(path).open("rb") as handle:
229
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
230
+ digest.update(block)
231
+ return digest.hexdigest()
232
+
233
+
234
+ def load_v4_warmstart_moe(
235
+ path: Path,
236
+ expected_sha256: str,
237
+ model: Phase2MoEV6Module,
238
+ *,
239
+ weight_source: str,
240
+ ) -> Dict[str, Any]:
241
+ """Load shared v4 trunk weights across a deliberate Phase-1 swap.
242
+
243
+ Unlike the v5 loader this does NOT require the Phase-1 SHA to match:
244
+ v6 exists to move to the ll_v3 representation, and the trunk finetunes
245
+ to the new conditioning. Both facts are recorded in the audit.
246
+ """
247
+
248
+ actual = _file_sha256(path)
249
+ if actual.lower() != str(expected_sha256).lower():
250
+ raise ValueError("v4 warmstart sha256 mismatch")
251
+ checkpoint = v4._torch_load(Path(path), map_location="cpu")
252
+ if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2:
253
+ raise ValueError("warmstart must be a Phase-2 v4 checkpoint")
254
+ if checkpoint.get("condition_mode") != "full":
255
+ raise ValueError("v6 warmstart requires a full-condition v4 run")
256
+ if weight_source == "model":
257
+ state = checkpoint.get("model_state_dict")
258
+ elif weight_source == "ema":
259
+ ema_state = checkpoint.get("ema_state_dict")
260
+ state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None
261
+ else:
262
+ raise ValueError("weight_source must be 'model' or 'ema'")
263
+ if not isinstance(state, Mapping):
264
+ raise ValueError("v4 warmstart is missing the selected state")
265
+
266
+ target = model.state_dict()
267
+ expected_shared = {
268
+ name for name in target if not _is_v6_only_key(name)
269
+ }
270
+ source_keys = set(state.keys())
271
+ if source_keys != expected_shared:
272
+ missing = sorted(expected_shared - source_keys)
273
+ unexpected = sorted(source_keys - expected_shared)
274
+ raise ValueError(
275
+ "v4 warmstart shared key mismatch; missing=%r unexpected=%r"
276
+ % (missing[:8], unexpected[:8])
277
+ )
278
+ result = model.load_state_dict(state, strict=False)
279
+ expected_missing = sorted(name for name in target if _is_v6_only_key(name))
280
+ if sorted(result.missing_keys) != expected_missing or result.unexpected_keys:
281
+ raise RuntimeError("v6 warmstart loader violated its allowlist")
282
+ return {
283
+ "mapping_version": V6_WARMSTART_MAPPING_VERSION,
284
+ "source_checkpoint_sha256": actual,
285
+ "source_step": int(checkpoint.get("step", -1)),
286
+ "weight_source": weight_source,
287
+ "source_phase1_sha256": checkpoint.get("phase1_sha256"),
288
+ "cross_phase1": True,
289
+ "materialized_state_hash": v4.model_state_hash(model),
290
+ }
291
+
292
+
293
+ def _parse_kappa_values(value: str) -> Tuple[float, ...]:
294
+ parts = [float(part) for part in str(value).split(",")]
295
+ if len(parts) != NUM_EXPERTS or any(
296
+ not math.isfinite(p) or p <= 0 for p in parts
297
+ ):
298
+ raise ValueError(
299
+ "--expert-kappa-values requires %d positive floats" % NUM_EXPERTS
300
+ )
301
+ return tuple(parts)
302
+
303
+
304
+ def _build_moe_restorer(
305
+ args: argparse.Namespace, device: torch.device
306
+ ) -> Phase2MoEV6Module:
307
+ schedule = ResidualShiftSchedule(
308
+ timesteps=args.timesteps, eta_end=args.eta_end,
309
+ min_noise=args.min_noise, power=args.power, kappa=args.kappa,
310
+ )
311
+ conditioner = MoEGraphConditionerV6(
312
+ cond_dim=args.cond_dim, stage_dims=args.dims,
313
+ gate_hidden_dim=args.gate_hidden_dim,
314
+ gate_max_correction=args.gate_max_correction,
315
+ )
316
+ denoiser = MoEGraphResidualShiftUNetV6(
317
+ dims=args.dims, cond_dim=args.cond_dim, expert_rank=args.expert_rank,
318
+ )
319
+ expert_kappa = ExpertKappaSchedule(
320
+ kappa_per_expert=_parse_kappa_values(args.expert_kappa_values),
321
+ kappa_global=float(args.kappa),
322
+ anneal_microsteps=int(args.expert_kappa_anneal_steps)
323
+ * int(args.grad_accum),
324
+ )
325
+ model = Phase2MoEV6Module(
326
+ conditioner=conditioner, denoiser=denoiser, schedule=schedule,
327
+ expert_kappa=expert_kappa, condition_mode=args.condition,
328
+ gate_anchor_weight=args.gate_anchor_weight,
329
+ gate_correction_weight=args.gate_correction_weight,
330
+ )
331
+ model.eval_sample_steps = int(args.eval_sample_steps)
332
+ if args.resume is None and args.init_checkpoint is None:
333
+ if args.warmstart_v4 is None:
334
+ raise ValueError("v6 requires --warmstart-v4 (or resume/init)")
335
+ audit = load_v4_warmstart_moe(
336
+ args.warmstart_v4, args.warmstart_v4_sha256, model,
337
+ weight_source=args.warmstart_weight_source,
338
+ )
339
+ else:
340
+ # Resume/init must reproduce the stored contract exactly, so the
341
+ # warm-start audit is read back from the checkpoint being resumed.
342
+ source = args.resume if args.resume is not None else args.init_checkpoint
343
+ stored = v4._torch_load(Path(source), map_location="cpu")
344
+ architecture = stored.get("architecture") if isinstance(stored, Mapping) else None
345
+ audit = (
346
+ dict(architecture.get("warmstart", {}))
347
+ if isinstance(architecture, Mapping)
348
+ else {"mapping_version": "resumed_state"}
349
+ )
350
+ del stored
351
+ setattr(args, "_v6_warmstart_audit", audit)
352
+ # Curriculum stage 1: only the v6 control paths learn while the trunk
353
+ # stays at its v4 warm start (run 1 showed that a free trunk under
354
+ # full gating from step 0 collapses lowlight/haze).
355
+ if bool(getattr(args, "freeze_shared_trunk", False)):
356
+ for name, parameter in model.named_parameters():
357
+ parameter.requires_grad_(_is_v6_only_key(name))
358
+ return model.to(device)
359
+
360
+
361
+ def _moe_architecture(args: argparse.Namespace) -> Dict[str, Any]:
362
+ audit = getattr(args, "_v6_warmstart_audit", {})
363
+ return {
364
+ "name": "graph_moe_v6",
365
+ "version": 6,
366
+ "moe": {
367
+ "mechanism": MOE_V6_VERSION,
368
+ "expert_rank": int(args.expert_rank),
369
+ "gate_hidden_dim": int(args.gate_hidden_dim),
370
+ "gate_max_correction": float(args.gate_max_correction),
371
+ "activation": "independent_sigmoid_strength_severity",
372
+ "execution": "top2",
373
+ "spatial_gating": "phase1_maps_blend",
374
+ },
375
+ "dims": list(args.dims),
376
+ "cond_dim": int(args.cond_dim),
377
+ "state_channels": 12,
378
+ "prediction": "x0",
379
+ "eval_sample_steps": int(args.eval_sample_steps),
380
+ "trunk": "v4_warmstart_curriculum",
381
+ "warmstart": dict(audit),
382
+ }
383
+
384
+
385
+ def _moe_schedule_config(args: argparse.Namespace) -> Dict[str, Any]:
386
+ result = dict(_V4_SCHEDULE_CONFIG(args))
387
+ result["expert_kappa"] = {
388
+ "enabled": True,
389
+ "values": list(_parse_kappa_values(args.expert_kappa_values)),
390
+ "anneal_steps": int(args.expert_kappa_anneal_steps),
391
+ "source": "normalized_node_strengths",
392
+ "posterior": "exact_per_sample_kappa",
393
+ }
394
+ return result
395
+
396
+
397
+ def _moe_data_plan(
398
+ args: argparse.Namespace, world_size: int, amp_enabled=None
399
+ ) -> Dict[str, Any]:
400
+ result = dict(_V4_DATA_PLAN(args, world_size, amp_enabled=amp_enabled))
401
+ result["noise_plan"] = "v4_single_stream"
402
+ return result
403
+
404
+
405
+ def build_parser() -> argparse.ArgumentParser:
406
+ parser = v4.build_parser()
407
+ parser.description = __doc__
408
+ parser.add_argument("--expert-rank", type=int, default=16)
409
+ parser.add_argument("--gate-hidden-dim", type=int, default=128)
410
+ parser.add_argument("--gate-max-correction", type=float, default=1.0)
411
+ parser.add_argument("--gate-anchor-weight", type=float, default=0.05)
412
+ parser.add_argument("--gate-correction-weight", type=float, default=0.001)
413
+ parser.add_argument(
414
+ "--expert-kappa-values", type=str, default=DEFAULT_KAPPA_VALUES
415
+ )
416
+ parser.add_argument("--expert-kappa-anneal-steps", type=int, default=1000)
417
+ parser.add_argument("--eval-sample-steps", type=int, default=1)
418
+ parser.add_argument(
419
+ "--freeze-shared-trunk",
420
+ action="store_true",
421
+ help="curriculum stage 1: train only the v6 control paths",
422
+ )
423
+ parser.add_argument("--warmstart-v4", type=Path)
424
+ parser.add_argument("--warmstart-v4-sha256")
425
+ parser.add_argument(
426
+ "--warmstart-weight-source", choices=("ema", "model"), default="ema"
427
+ )
428
+ return parser
429
+
430
+
431
+ @contextlib.contextmanager
432
+ def _installed_v6_backend(args: argparse.Namespace) -> Iterator[None]:
433
+ replacements = {
434
+ "_build_restorer": _build_moe_restorer,
435
+ "_architecture": _moe_architecture,
436
+ "_schedule_config": _moe_schedule_config,
437
+ "_data_plan": _moe_data_plan,
438
+ "sample_restoration": sample_moe_restoration,
439
+ }
440
+ originals = {name: getattr(v4, name) for name in replacements}
441
+ try:
442
+ for name, replacement in replacements.items():
443
+ setattr(v4, name, replacement)
444
+ yield
445
+ finally:
446
+ for name, original in originals.items():
447
+ setattr(v4, name, original)
448
+
449
+
450
+ def run(args: argparse.Namespace) -> None:
451
+ v4.validate_runtime_args(args)
452
+ _parse_kappa_values(args.expert_kappa_values)
453
+ if args.eval_sample_steps < 1:
454
+ raise ValueError("--eval-sample-steps must be >= 1")
455
+ has_path = args.warmstart_v4 is not None
456
+ has_sha = args.warmstart_v4_sha256 is not None
457
+ if has_path != has_sha:
458
+ raise ValueError("warmstart path and sha256 go together")
459
+ with _installed_v6_backend(args):
460
+ v4.run(args)
461
+
462
+
463
+ def main(argv: Optional[Sequence[str]] = None) -> None:
464
+ run(build_parser().parse_args(argv))
465
+
466
+
467
+ if __name__ == "__main__":
468
+ main()
dataset/phase1_noise_20260906/code/train_phase2_graph_resshift_v4.py ADDED
@@ -0,0 +1,2119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Train and evaluate graph-conditioned residual-shift restoration (Phase 2 v4).
3
+
4
+ Phase 1 is an inference-only representation learner. This entrypoint never
5
+ feeds it clean targets, degradation labels, or any other oracle information.
6
+ The ``full`` and ``null`` arms instantiate exactly the same trainable module;
7
+ the latter masks the continuous graph condition after the conditioner so the
8
+ representation-utility gate is parameter matched.
9
+
10
+ The implementation intentionally targets Python 3.9 and PyTorch 1.10 because
11
+ those are the versions installed on the training host.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import argparse
17
+ import contextlib
18
+ import dataclasses
19
+ import hashlib
20
+ import json
21
+ import math
22
+ import os
23
+ import random
24
+ import time
25
+ from dataclasses import dataclass
26
+ from pathlib import Path
27
+ from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple
28
+
29
+ import numpy as np
30
+ import torch
31
+ from torch import Tensor, nn
32
+ import torch.distributed as dist
33
+ import torch.nn.functional as F
34
+ from torch.nn.parallel import DistributedDataParallel
35
+ from torch.utils.data import DataLoader
36
+
37
+ from src.models.restoration.graph_resshift_v4 import (
38
+ BRANCH_ORDER,
39
+ PHASE1_AGGREGATION_VERSION,
40
+ PHASE1_SCHEMA_VERSION,
41
+ FrozenPhase1,
42
+ GraphConditionerV4,
43
+ GraphResidualShiftUNetV4,
44
+ ResidualShiftSchedule,
45
+ load_phase1_checkpoint,
46
+ pad_to_multiple,
47
+ pixel_shuffle2,
48
+ pixel_unshuffle2,
49
+ )
50
+
51
+
52
+ DOMAINS: Tuple[str, ...] = tuple(BRANCH_ORDER)
53
+
54
+
55
+ @dataclass
56
+ class TrainStepResult:
57
+ """The exact x0 objective and useful detached diagnostics."""
58
+
59
+ loss: Tensor
60
+ u0_prediction: Tensor
61
+ u0_target: Tensor
62
+ u_t: Tensor
63
+
64
+
65
+ class Phase2RestorationModule(nn.Module):
66
+ """Trainable Phase-2 module; the frozen Phase-1 encoder is deliberately absent."""
67
+
68
+ def __init__(
69
+ self,
70
+ conditioner: GraphConditionerV4,
71
+ denoiser: GraphResidualShiftUNetV4,
72
+ schedule: ResidualShiftSchedule,
73
+ condition_mode: str,
74
+ ) -> None:
75
+ super().__init__()
76
+ if condition_mode not in ("full", "null"):
77
+ raise ValueError("condition_mode must be 'full' or 'null'")
78
+ self.conditioner = conditioner
79
+ self.denoiser = denoiser
80
+ self.schedule = schedule
81
+ self.condition_mode = condition_mode
82
+
83
+ def build_condition(self, representation: Any) -> Any:
84
+ return self.conditioner(representation, mode=self.condition_mode)
85
+
86
+ def predict_x0(
87
+ self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition: Any
88
+ ) -> Tensor:
89
+ return self.denoiser(u_t, u_y, timesteps, condition)
90
+
91
+ def forward(
92
+ self,
93
+ clean: Tensor,
94
+ degraded: Tensor,
95
+ representation: Any,
96
+ timesteps: Tensor,
97
+ noise: Optional[Tensor] = None,
98
+ ) -> Tensor:
99
+ """DDP-visible training forward.
100
+
101
+ Keeping the objective behind ``forward`` is important: calling a
102
+ method on ``module`` directly would bypass DistributedDataParallel's
103
+ reducer preparation and make ``no_sync`` accumulation incorrect.
104
+ """
105
+
106
+ return self.training_loss(
107
+ clean, degraded, representation, timesteps, noise=noise
108
+ ).loss
109
+
110
+ def training_loss(
111
+ self,
112
+ clean: Tensor,
113
+ degraded: Tensor,
114
+ representation: Any,
115
+ timesteps: Tensor,
116
+ noise: Optional[Tensor] = None,
117
+ ) -> TrainStepResult:
118
+ """Uniform-timestep x0 prediction with one unweighted FP32 MSE."""
119
+
120
+ u0 = pixel_unshuffle2(clean)
121
+ uy = pixel_unshuffle2(degraded)
122
+ u_t = self.schedule.q_sample(u0, uy, timesteps, noise=noise)
123
+ prediction = self.predict_x0(
124
+ u_t, uy, timesteps, self.build_condition(representation)
125
+ )
126
+ # Force the reduction to FP32 even when the U-Net runs under autocast.
127
+ loss = (prediction.float() - u0.float()).square().mean()
128
+ return TrainStepResult(loss, prediction, u0, u_t)
129
+
130
+
131
+ def apply_identity_pairs(
132
+ degraded: Tensor, clean: Tensor, probability: float
133
+ ) -> Tensor:
134
+ """Replace a random subset of degraded inputs with their clean targets.
135
+
136
+ Teaches the fixed point f(x) = x explicitly (the "do nothing" behaviour
137
+ missing from a training distribution that only contains degraded
138
+ inputs). Applied BEFORE the frozen Phase-1 call so the representation
139
+ sees the clean image too.
140
+ """
141
+
142
+ if probability <= 0.0:
143
+ return degraded
144
+ mask = torch.rand(clean.shape[0], device=clean.device) < float(probability)
145
+ if not bool(mask.any()):
146
+ return degraded
147
+ return torch.where(mask.view(-1, 1, 1, 1), clean, degraded)
148
+
149
+
150
+ def identity_pair_mask(batch_size: int, probability: float, device) -> Tensor:
151
+ if probability <= 0.0:
152
+ return torch.zeros(batch_size, dtype=torch.bool, device=device)
153
+ return torch.rand(batch_size, device=device) < float(probability)
154
+
155
+
156
+ def exposure_diverse_identity(
157
+ clean: Tensor,
158
+ full_clean: Optional[Tensor],
159
+ identity: Tensor,
160
+ generator: torch.Generator,
161
+ jitter: float = 0.0,
162
+ extra_crop: Optional[Tensor] = None,
163
+ extra_full: Optional[Tensor] = None,
164
+ extra_prob: float = 0.0,
165
+ ) -> Tuple[Tensor, Optional[Tensor]]:
166
+ """Make identity pairs exposure- and content-diverse (v8).
167
+
168
+ The trunk learned an exposure prior ("dark -> brighten, mid -> pull to
169
+ the training mean") because identity pairs only ever showed the bright
170
+ clean images of the four training domains (scene008 diagnosis: 9 of 12
171
+ lost dB were a global tone shift). For the identity rows this (a)
172
+ optionally swaps the clean image for one from an external clean pool and
173
+ (b) multiplies input AND target by a random global gain exp(U(-j, j)),
174
+ clamped to [0, 1]. Returns the new (clean, full_clean); the caller copies
175
+ the identity rows of clean into degraded afterwards, so the pair stays
176
+ exactly (x, x). Deterministic through ``generator``.
177
+ """
178
+
179
+ if not bool(identity.any()):
180
+ return clean, full_clean
181
+ batch = clean.shape[0]
182
+ new_clean, new_full = clean.clone(), (full_clean.clone() if full_clean is not None else None)
183
+ if extra_crop is not None and extra_prob > 0.0:
184
+ swap = (torch.rand(batch, generator=generator) < float(extra_prob)).to(clean.device) & identity
185
+ if bool(swap.any()):
186
+ source = extra_crop[: batch].to(clean.device, clean.dtype)
187
+ if source.shape[0] < batch:
188
+ repeat = int(math.ceil(batch / source.shape[0]))
189
+ source = source.repeat(repeat, 1, 1, 1)[:batch]
190
+ new_clean = torch.where(swap.view(-1, 1, 1, 1), source, new_clean)
191
+ if new_full is not None:
192
+ full_source = (extra_full if extra_full is not None else extra_crop)[: batch]
193
+ full_source = full_source.to(clean.device, new_full.dtype)
194
+ if full_source.shape[0] < batch:
195
+ repeat = int(math.ceil(batch / full_source.shape[0]))
196
+ full_source = full_source.repeat(repeat, 1, 1, 1)[:batch]
197
+ if full_source.shape[-2:] != new_full.shape[-2:]:
198
+ full_source = F.interpolate(full_source, size=new_full.shape[-2:], mode="area")
199
+ new_full = torch.where(swap.view(-1, 1, 1, 1), full_source, new_full)
200
+ if jitter > 0.0:
201
+ log_gain = (torch.rand(batch, generator=generator) * 2.0 - 1.0) * float(jitter)
202
+ gain = log_gain.exp().to(clean.device, clean.dtype).view(-1, 1, 1, 1)
203
+ gain = torch.where(identity.view(-1, 1, 1, 1), gain, torch.ones_like(gain))
204
+ new_clean = (new_clean * gain).clamp(0.0, 1.0)
205
+ if new_full is not None:
206
+ new_full = (new_full * gain.to(new_full.dtype)).clamp(0.0, 1.0)
207
+ return new_clean, new_full
208
+
209
+
210
+ def synthetic_noise_pairs(
211
+ degraded: Tensor,
212
+ clean: Tensor,
213
+ probability: float,
214
+ generator: torch.Generator,
215
+ full_degraded: Optional[Tensor] = None,
216
+ full_clean: Optional[Tensor] = None,
217
+ ) -> Tuple[Tensor, Optional[Tensor], Tensor]:
218
+ """Clean-image prior for the trunk: turn a random subset of pairs into
219
+ (clean + heteroscedastic Poisson-Gaussian noise, clean).
220
+
221
+ This is what the two-stage refiner had (pretraining on clean + light
222
+ corruption over every clean image) and the unified trunk never got.
223
+ The same noise parameters are applied to the whole-frame view so the
224
+ global context stays consistent with the crop. Deterministic per call
225
+ through ``generator``. Returns (degraded, full_degraded, mask)."""
226
+
227
+ batch = clean.shape[0]
228
+ if probability <= 0.0:
229
+ return degraded, full_degraded, torch.zeros(batch, dtype=torch.bool, device=clean.device)
230
+ draw = torch.rand(batch, generator=generator)
231
+ mask = (draw < float(probability)).to(clean.device)
232
+ if not bool(mask.any()):
233
+ return degraded, full_degraded, mask
234
+ params = torch.rand(batch, 2, generator=generator)
235
+ a = (0.0005 + 0.0195 * params[:, 0]).to(clean.device).view(-1, 1, 1, 1)
236
+ b = (0.0001 + 0.0049 * params[:, 1]).to(clean.device).view(-1, 1, 1, 1)
237
+ eps = torch.randn(clean.shape, generator=generator).to(clean.device)
238
+ noisy = (clean + (a * clean.clamp(0, 1) + b).sqrt() * eps).clamp(0.0, 1.0)
239
+ new_degraded = torch.where(mask.view(-1, 1, 1, 1), noisy.to(degraded.dtype), degraded)
240
+ new_full = full_degraded
241
+ if full_degraded is not None and full_clean is not None:
242
+ eps_full = torch.randn(full_clean.shape, generator=generator).to(clean.device)
243
+ noisy_full = (full_clean + (a * full_clean.clamp(0, 1) + b).sqrt() * eps_full).clamp(0.0, 1.0)
244
+ new_full = torch.where(mask.view(-1, 1, 1, 1), noisy_full.to(full_degraded.dtype), full_degraded)
245
+ return new_degraded, new_full, mask
246
+
247
+
248
+ def extra_clean_files(spec: Any, balance: bool = True) -> List[Path]:
249
+ """Image files of one or more clean pools; ``spec`` is a path or a
250
+ comma-separated list of paths (v10: Snow100K gt + SIDD GT + LOL GT so
251
+ identity pairs cover dark, textured, real-camera clean images).
252
+
253
+ ``balance`` repeats the entries of every smaller root until each root
254
+ has as many entries as the largest one, so a 121-image SIDD pool is
255
+ drawn as often as a 50k-image Snow100K pool (crops are re-randomised per
256
+ entry index, so repeated files still yield different crops).
257
+ """
258
+
259
+ from src.data.folder_crops import list_image_files
260
+
261
+ roots = [part.strip() for part in str(spec).split(",") if part.strip()]
262
+ if not roots:
263
+ raise ValueError("extra clean pool needs at least one folder")
264
+ per_root = [list_image_files(Path(root)) for root in roots]
265
+ if any(not files for files in per_root):
266
+ raise ValueError("extra clean pool is empty: %s" % spec)
267
+ if balance and len(per_root) > 1:
268
+ target = max(len(files) for files in per_root)
269
+ per_root = [
270
+ (files * int(math.ceil(target / len(files))))[:target] for files in per_root
271
+ ]
272
+ files: List[Path] = []
273
+ for group in per_root:
274
+ files.extend(group)
275
+ return files
276
+
277
+
278
+ def unwrap_module(module: nn.Module) -> nn.Module:
279
+ return module.module if isinstance(module, DistributedDataParallel) else module
280
+
281
+
282
+ def _seed_value(seed: int, *parts: Any) -> int:
283
+ payload = "\0".join([str(int(seed))] + [str(part) for part in parts])
284
+ digest = hashlib.sha256(payload.encode("utf-8")).digest()
285
+ # torch.Generator.manual_seed accepts a signed 64-bit-safe positive value.
286
+ return int.from_bytes(digest[:8], "little") % (2 ** 63 - 1)
287
+
288
+
289
+ def _cpu_random_tensor(shape: Sequence[int], seed: int, dtype: torch.dtype) -> Tensor:
290
+ generator = torch.Generator(device="cpu")
291
+ generator.manual_seed(int(seed))
292
+ # CPU float16 normal generation was incomplete in older PyTorch versions.
293
+ return torch.randn(tuple(shape), generator=generator, dtype=torch.float32).to(dtype)
294
+
295
+
296
+ def deterministic_training_plan(
297
+ reference: Tensor,
298
+ timesteps: int,
299
+ seed: int,
300
+ global_microstep: int,
301
+ rank: int = 0,
302
+ sample_seeds: Optional[Sequence[int]] = None,
303
+ ) -> Tuple[Tensor, Tensor]:
304
+ """Return a reproducible t/noise plan independent of global RNG state.
305
+
306
+ ``sample_seeds`` are emitted by the global balanced sampler before its DDP
307
+ shard. Using them makes the union of two local rank plans exactly equal to
308
+ the corresponding single-GPU global micro-batch plan.
309
+ """
310
+
311
+ if timesteps < 1:
312
+ raise ValueError("timesteps must be positive")
313
+ if sample_seeds is not None:
314
+ if len(sample_seeds) != reference.shape[0]:
315
+ raise ValueError("one sample seed is required per training image")
316
+ timestep_values: List[Tensor] = []
317
+ noises: List[Tensor] = []
318
+ for index, sample_seed in enumerate(sample_seeds):
319
+ generator = torch.Generator(device="cpu")
320
+ generator.manual_seed(
321
+ _seed_value(seed, "train", global_microstep, int(sample_seed))
322
+ )
323
+ timestep_values.append(
324
+ torch.randint(1, timesteps + 1, (1,), generator=generator)
325
+ )
326
+ noises.append(
327
+ torch.randn(
328
+ tuple(reference[index].shape),
329
+ generator=generator,
330
+ dtype=torch.float32,
331
+ )
332
+ )
333
+ t = torch.cat(timestep_values, dim=0).long()
334
+ noise = torch.stack(noises, dim=0)
335
+ return t.to(reference.device), noise.to(
336
+ reference.device, dtype=reference.dtype
337
+ )
338
+ plan_seed = _seed_value(seed, "train", global_microstep, rank)
339
+ generator = torch.Generator(device="cpu")
340
+ generator.manual_seed(plan_seed)
341
+ t = torch.randint(
342
+ 1, timesteps + 1, (reference.shape[0],), generator=generator, dtype=torch.long
343
+ )
344
+ noise = torch.randn(tuple(reference.shape), generator=generator, dtype=torch.float32)
345
+ return t.to(reference.device), noise.to(reference.device, dtype=reference.dtype)
346
+
347
+
348
+ def _noise_for_records(
349
+ reference: Tensor,
350
+ record_ids: Optional[Sequence[str]],
351
+ seed: int,
352
+ stage: Any,
353
+ ) -> Tensor:
354
+ if record_ids is None:
355
+ return _cpu_random_tensor(
356
+ reference.shape, _seed_value(seed, "eval", stage), reference.dtype
357
+ ).to(reference.device)
358
+ if len(record_ids) != reference.shape[0]:
359
+ raise ValueError("one record id is required per image")
360
+ samples = []
361
+ for index, record_id in enumerate(record_ids):
362
+ samples.append(
363
+ _cpu_random_tensor(
364
+ reference[index].shape,
365
+ _seed_value(seed, "eval", str(record_id), stage),
366
+ reference.dtype,
367
+ )
368
+ )
369
+ return torch.stack(samples, dim=0).to(reference.device)
370
+
371
+
372
+ @torch.no_grad()
373
+ def sample_restoration(
374
+ model: nn.Module,
375
+ phase1: FrozenPhase1,
376
+ degraded: Tensor,
377
+ *,
378
+ seed: int,
379
+ record_ids: Optional[Sequence[str]] = None,
380
+ initial_noise: Optional[Tensor] = None,
381
+ amp_enabled: Optional[bool] = None,
382
+ ) -> Tensor:
383
+ """Run the exact ``T ... 1`` posterior and extract Phase-1 only once."""
384
+
385
+ restorer = unwrap_module(model)
386
+ if not isinstance(restorer, Phase2RestorationModule):
387
+ raise TypeError("model must wrap Phase2RestorationModule")
388
+ use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled)
389
+ with torch.cuda.amp.autocast(enabled=use_amp):
390
+ padded, original_size = pad_to_multiple(degraded, multiple=16)
391
+ representation = phase1(padded)
392
+ condition = restorer.build_condition(representation)
393
+ uy = pixel_unshuffle2(padded)
394
+ if initial_noise is None:
395
+ initial_noise = _noise_for_records(
396
+ uy, record_ids, seed=seed, stage="initial"
397
+ )
398
+ elif initial_noise.shape != uy.shape:
399
+ raise ValueError("initial_noise must match the padded pixel-unshuffle state")
400
+ else:
401
+ initial_noise = initial_noise.to(device=uy.device, dtype=uy.dtype)
402
+
403
+ eta_terminal = restorer.schedule.eta[-1].to(device=uy.device, dtype=uy.dtype)
404
+ kappa = restorer.schedule.kappa.to(device=uy.device, dtype=uy.dtype)
405
+ u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise
406
+ batch = uy.shape[0]
407
+ for step in restorer.schedule.reverse_timesteps():
408
+ t = torch.full((batch,), step, device=uy.device, dtype=torch.long)
409
+ u0_hat = restorer.predict_x0(u_t, uy, t, condition)
410
+ mean, variance = restorer.schedule.posterior_mean_variance(
411
+ u_t, u0_hat, t
412
+ )
413
+ if step > 1:
414
+ noise = _noise_for_records(u_t, record_ids, seed=seed, stage=step)
415
+ u_t = mean + torch.sqrt(variance) * noise
416
+ else:
417
+ # q(u_0 | u_1, u0_hat) is deterministic; never inject t=1 noise.
418
+ u_t = mean
419
+ restored = pixel_shuffle2(u_t)
420
+ height, width = original_size
421
+ return restored[..., :height, :width].clamp(0.0, 1.0)
422
+
423
+
424
+ def rgb_psnr_per_image(prediction: Tensor, target: Tensor) -> Tensor:
425
+ """Per-image RGB PSNR on [0, 1] values (no batch averaging)."""
426
+
427
+ if prediction.shape != target.shape or prediction.ndim != 4:
428
+ raise ValueError("PSNR inputs must have the same BCHW shape")
429
+ mse = (prediction.float() - target.float()).square().flatten(1).mean(1)
430
+ return -10.0 * torch.log10(mse.clamp_min(torch.finfo(torch.float32).tiny))
431
+
432
+
433
+ def _gaussian_window(
434
+ window_size: int, sigma: float, channels: int, device: torch.device
435
+ ) -> Tensor:
436
+ coordinates = torch.arange(window_size, device=device, dtype=torch.float32)
437
+ coordinates = coordinates - float(window_size - 1) / 2.0
438
+ kernel = torch.exp(-(coordinates.square()) / (2.0 * sigma * sigma))
439
+ kernel = kernel / kernel.sum()
440
+ window = torch.outer(kernel, kernel)
441
+ return window.reshape(1, 1, window_size, window_size).repeat(channels, 1, 1, 1)
442
+
443
+
444
+ def rgb_ssim_per_image(
445
+ prediction: Tensor,
446
+ target: Tensor,
447
+ window_size: int = 11,
448
+ sigma: float = 1.5,
449
+ ) -> Tensor:
450
+ """Windowed Gaussian RGB SSIM, reduced separately for every image."""
451
+
452
+ if prediction.shape != target.shape or prediction.ndim != 4:
453
+ raise ValueError("SSIM inputs must have the same BCHW shape")
454
+ if window_size <= 0 or window_size % 2 == 0:
455
+ raise ValueError("window_size must be a positive odd integer")
456
+ x, y = prediction.float(), target.float()
457
+ channels = x.shape[1]
458
+ window = _gaussian_window(window_size, sigma, channels, x.device)
459
+ padding = window_size // 2
460
+ pad_mode = (
461
+ "reflect"
462
+ if x.shape[-2] > padding and x.shape[-1] > padding
463
+ else "replicate"
464
+ )
465
+ x_pad = F.pad(x, (padding, padding, padding, padding), mode=pad_mode)
466
+ y_pad = F.pad(y, (padding, padding, padding, padding), mode=pad_mode)
467
+ mu_x = F.conv2d(x_pad, window, groups=channels)
468
+ mu_y = F.conv2d(y_pad, window, groups=channels)
469
+ mu_x_sq, mu_y_sq, mu_xy = mu_x.square(), mu_y.square(), mu_x * mu_y
470
+ sigma_x = F.conv2d(x_pad * x_pad, window, groups=channels) - mu_x_sq
471
+ sigma_y = F.conv2d(y_pad * y_pad, window, groups=channels) - mu_y_sq
472
+ sigma_xy = F.conv2d(x_pad * y_pad, window, groups=channels) - mu_xy
473
+ c1, c2 = 0.01 ** 2, 0.03 ** 2
474
+ numerator = (2.0 * mu_xy + c1) * (2.0 * sigma_xy + c2)
475
+ denominator = (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2)
476
+ return (numerator / denominator.clamp_min(1e-12)).flatten(1).mean(1)
477
+
478
+
479
+ class DomainMetricAccumulator:
480
+ """Domain-first metric reduction used for model selection."""
481
+
482
+ def __init__(self, domains: Sequence[str] = DOMAINS) -> None:
483
+ self.domains = tuple(domains)
484
+ self.values: Dict[str, Dict[str, List[float]]] = {
485
+ domain: {"psnr": [], "ssim": []} for domain in self.domains
486
+ }
487
+
488
+ def update(self, domain: str, psnr: float, ssim: float) -> None:
489
+ if domain not in self.values:
490
+ raise ValueError("unknown evaluation domain %r" % domain)
491
+ self.values[domain]["psnr"].append(float(psnr))
492
+ self.values[domain]["ssim"].append(float(ssim))
493
+
494
+ def compute(self) -> Dict[str, Any]:
495
+ missing = [domain for domain in self.domains if not self.values[domain]["psnr"]]
496
+ if missing:
497
+ raise ValueError("evaluation has no images for domains %r" % missing)
498
+ per_domain: Dict[str, Dict[str, Any]] = {}
499
+ for domain in self.domains:
500
+ values = self.values[domain]
501
+ per_domain[domain] = {
502
+ "psnr": float(np.mean(values["psnr"])),
503
+ "ssim": float(np.mean(values["ssim"])),
504
+ "count": len(values["psnr"]),
505
+ }
506
+ macro_psnr = float(np.mean([per_domain[d]["psnr"] for d in self.domains]))
507
+ macro_ssim = float(np.mean([per_domain[d]["ssim"] for d in self.domains]))
508
+ all_psnr = [value for d in self.domains for value in self.values[d]["psnr"]]
509
+ all_ssim = [value for d in self.domains for value in self.values[d]["ssim"]]
510
+ return {
511
+ "per_domain": per_domain,
512
+ "macro_psnr": macro_psnr,
513
+ "macro_ssim": macro_ssim,
514
+ "image_weighted_psnr": float(np.mean(all_psnr)),
515
+ "image_weighted_ssim": float(np.mean(all_ssim)),
516
+ }
517
+
518
+
519
+ @torch.no_grad()
520
+ def evaluate(
521
+ model: nn.Module,
522
+ phase1: FrozenPhase1,
523
+ loader: Iterable[Mapping[str, Any]],
524
+ device: torch.device,
525
+ seed: int,
526
+ amp_enabled: Optional[bool] = None,
527
+ ) -> Dict[str, Any]:
528
+ """Evaluate restoration and the degraded-input baseline in fixed order."""
529
+
530
+ model.eval()
531
+ phase1.eval()
532
+ restored_metrics = DomainMetricAccumulator()
533
+ baseline_metrics = DomainMetricAccumulator()
534
+ for batch in loader:
535
+ degraded = batch["degraded"].to(device, non_blocking=True)
536
+ clean = batch["clean"].to(device, non_blocking=True)
537
+ domains = [str(value) for value in batch["degradation"]]
538
+ record_ids = [str(value) for value in batch["record_id"]]
539
+ extra: Dict[str, Any] = {}
540
+ if "full_degraded" in batch and getattr(sample_restoration, "accepts_full_frame", False):
541
+ extra["full_degraded"] = batch["full_degraded"].to(device, non_blocking=True)
542
+ restored = sample_restoration(
543
+ model,
544
+ phase1,
545
+ degraded,
546
+ seed=seed,
547
+ record_ids=record_ids,
548
+ amp_enabled=amp_enabled,
549
+ **extra,
550
+ )
551
+ psnr = rgb_psnr_per_image(restored, clean).cpu().tolist()
552
+ ssim = rgb_ssim_per_image(restored, clean).cpu().tolist()
553
+ base_psnr = rgb_psnr_per_image(degraded, clean).cpu().tolist()
554
+ base_ssim = rgb_ssim_per_image(degraded, clean).cpu().tolist()
555
+ for index, domain in enumerate(domains):
556
+ restored_metrics.update(domain, psnr[index], ssim[index])
557
+ baseline_metrics.update(domain, base_psnr[index], base_ssim[index])
558
+ return {
559
+ "restored": restored_metrics.compute(),
560
+ "degraded_baseline": baseline_metrics.compute(),
561
+ }
562
+
563
+
564
+ class ExponentialMovingAverage:
565
+ """Device-resident EMA over parameters and persistent buffers."""
566
+
567
+ def __init__(self, module: nn.Module, decay: float = 0.9999) -> None:
568
+ if not 0.0 <= decay < 1.0:
569
+ raise ValueError("EMA decay must satisfy 0 <= decay < 1")
570
+ self.decay = float(decay)
571
+ self.num_updates = 0
572
+ self.shadow = {
573
+ name: value.detach().clone()
574
+ for name, value in unwrap_module(module).state_dict().items()
575
+ }
576
+
577
+ @torch.no_grad()
578
+ def update(self, module: nn.Module) -> None:
579
+ current = unwrap_module(module).state_dict()
580
+ if current.keys() != self.shadow.keys():
581
+ raise ValueError("EMA/model state keys changed")
582
+ self.num_updates += 1
583
+ warmup_decay = float(1 + self.num_updates) / float(10 + self.num_updates)
584
+ effective_decay = min(self.decay, warmup_decay)
585
+ for name, value in current.items():
586
+ source = value.detach()
587
+ if torch.is_floating_point(source):
588
+ self.shadow[name].mul_(effective_decay).add_(
589
+ source, alpha=1.0 - effective_decay
590
+ )
591
+ else:
592
+ self.shadow[name].copy_(source)
593
+
594
+ def state_dict(self) -> Dict[str, Any]:
595
+ return {
596
+ "decay": self.decay,
597
+ "num_updates": self.num_updates,
598
+ "shadow": {name: value.clone() for name, value in self.shadow.items()},
599
+ }
600
+
601
+ def load_state_dict(self, state: Mapping[str, Any]) -> None:
602
+ if float(state["decay"]) != self.decay:
603
+ raise ValueError("EMA decay mismatch")
604
+ update_count = state.get("num_updates")
605
+ if isinstance(update_count, bool) or not isinstance(update_count, int):
606
+ raise ValueError("EMA state is missing a valid update count")
607
+ if update_count < 0:
608
+ raise ValueError("EMA update count cannot be negative")
609
+ self.num_updates = update_count
610
+ shadow = state["shadow"]
611
+ if shadow.keys() != self.shadow.keys():
612
+ raise ValueError("EMA state keys mismatch")
613
+ self.shadow = {
614
+ name: value.to(
615
+ device=self.shadow[name].device, dtype=self.shadow[name].dtype
616
+ ).clone()
617
+ for name, value in shadow.items()
618
+ }
619
+
620
+ @contextlib.contextmanager
621
+ def apply(self, module: nn.Module) -> Iterator[None]:
622
+ target = unwrap_module(module)
623
+ original = {name: value.detach().clone() for name, value in target.state_dict().items()}
624
+ target.load_state_dict(self.shadow, strict=True)
625
+ try:
626
+ yield
627
+ finally:
628
+ target.load_state_dict(original, strict=True)
629
+
630
+
631
+ def make_grad_scaler(enabled: bool) -> torch.cuda.amp.GradScaler:
632
+ return torch.cuda.amp.GradScaler(enabled=bool(enabled))
633
+
634
+
635
+ def scaler_step_or_fail(
636
+ scaler: torch.cuda.amp.GradScaler,
637
+ optimizer: torch.optim.Optimizer,
638
+ ) -> None:
639
+ """Apply one AMP step, failing before any logical cursor can advance.
640
+
641
+ PyTorch signals a skipped optimizer update by reducing the dynamic scale.
642
+ Continuing would desynchronize the sample cursor, LR scheduler, and EMA
643
+ from actual parameter updates, so deterministic v4 runs stop and resume
644
+ from their last atomic checkpoint instead.
645
+ """
646
+
647
+ scale_before = float(scaler.get_scale())
648
+ scaler.step(optimizer)
649
+ scaler.update()
650
+ scale_after = float(scaler.get_scale())
651
+ if scale_after < scale_before:
652
+ optimizer.zero_grad(set_to_none=True)
653
+ raise FloatingPointError(
654
+ "AMP overflow skipped the optimizer update; run stopped before "
655
+ "advancing scheduler, EMA, or logical step"
656
+ )
657
+
658
+
659
+ class RecoverableAmpOverflow(FloatingPointError):
660
+ """AMP gradient overflow with an atomic unchanged-step resume checkpoint."""
661
+
662
+
663
+ def collective_device() -> torch.device:
664
+ """Device the NCCL collectives must run on for this process."""
665
+
666
+ if torch.cuda.is_available():
667
+ return torch.device("cuda", torch.cuda.current_device())
668
+ return torch.device("cpu")
669
+
670
+
671
+ def has_any_gradient(model: nn.Module) -> bool:
672
+ """False when a step produced no gradient at all (every micro-batch was
673
+ dropped), in which case there is nothing to clip, reduce or apply."""
674
+
675
+ return any(p.grad is not None for p in unwrap_module(model).parameters())
676
+
677
+
678
+ def is_globally_finite_scalar(value: Tensor) -> bool:
679
+ """Synchronize a scalar finite/non-finite decision across all DDP ranks."""
680
+
681
+ detached = value.detach()
682
+ if detached.numel() != 1:
683
+ raise ValueError("finite check requires a scalar tensor")
684
+ finite = torch.isfinite(detached).all().to(dtype=torch.int32)
685
+ if dist.is_available() and dist.is_initialized():
686
+ # clip_grad_norm_ returns a CPU scalar when no parameter carries a
687
+ # gradient; NCCL rejects that with "Tensors must be CUDA and dense".
688
+ finite = finite.to(collective_device())
689
+ dist.all_reduce(finite, op=dist.ReduceOp.MIN)
690
+ return bool(finite.item())
691
+
692
+
693
+ def require_finite_tensor(value: Tensor, name: str) -> float:
694
+ """Return a scalar diagnostic or fail every DDP rank before state advances."""
695
+
696
+ if not is_globally_finite_scalar(value):
697
+ raise FloatingPointError("non-finite %s" % name)
698
+ return float(value.detach().float().item())
699
+
700
+
701
+ def nonfinite_loss_within_budget(
702
+ *, consecutive: int, total: int, max_consecutive: int = 5, max_total: int = 100
703
+ ) -> bool:
704
+ """Isolated fp16 spikes are tolerable; a persistent NaN is not."""
705
+
706
+ return int(consecutive) < int(max_consecutive) and int(total) <= int(max_total)
707
+
708
+
709
+ # The encoder half of the Uformer denoiser: everything that consumes the
710
+ # input image on the way down. Freezing it for the first steps of a run lets
711
+ # the decoder, the conditioning path and the heads re-adapt to a NEW Phase-1
712
+ # conditioning without disturbing generic features (the v6.1 lesson: opening
713
+ # the whole trunk from step 0 reproduces cross-domain interference).
714
+ ENCODER_PARAMETER_TOKENS: Tuple[str, ...] = (
715
+ "input_projection", "down_blocks", "down_attentions", "downsamples", "down_experts",
716
+ )
717
+
718
+
719
+ def is_encoder_parameter(name: str) -> bool:
720
+ return any(token in name.split(".") for token in ENCODER_PARAMETER_TOKENS)
721
+
722
+
723
+ def mask_encoder_gradients(model: nn.Module) -> int:
724
+ """Drop encoder gradients before the optimizer sees them.
725
+
726
+ Preferred over toggling ``requires_grad`` because DistributedDataParallel
727
+ fixes its reduction buckets at construction time; masking keeps the
728
+ backward graph identical and simply discards the reduced gradients.
729
+ """
730
+
731
+ masked = 0
732
+ for name, parameter in unwrap_module(model).named_parameters():
733
+ if parameter.grad is not None and is_encoder_parameter(name):
734
+ parameter.grad = None
735
+ masked += 1
736
+ return masked
737
+
738
+
739
+ class EarlyStopper:
740
+ """Stop when ``patience`` consecutive evaluations bring no real gain."""
741
+
742
+ def __init__(self, patience: int, min_delta: float = 0.02) -> None:
743
+ self.patience = int(patience)
744
+ self.min_delta = float(min_delta)
745
+ self.best = -math.inf
746
+ self.strikes = 0
747
+
748
+ def update(self, score: float) -> bool:
749
+ if self.patience <= 0:
750
+ return False
751
+ value = float(score)
752
+ if value > self.best + self.min_delta:
753
+ self.best = value
754
+ self.strikes = 0
755
+ return False
756
+ self.best = max(self.best, value)
757
+ self.strikes += 1
758
+ return self.strikes >= self.patience
759
+
760
+ def state_dict(self) -> Dict[str, Any]:
761
+ return {"best": float(self.best), "strikes": int(self.strikes)}
762
+
763
+ def load_state_dict(self, state: Mapping[str, Any]) -> None:
764
+ """Restore best/strikes across an overflow resume (otherwise a resumed
765
+ run silently restarts its patience budget)."""
766
+
767
+ self.best = float(state.get("best", -math.inf))
768
+ self.strikes = int(state.get("strikes", 0))
769
+
770
+
771
+ def loss_overflow_action(loss: Tensor, *, amp_enabled: bool) -> str:
772
+ """Decide what a (possibly non-finite) forward loss means.
773
+
774
+ A NaN/Inf produced inside ``autocast`` is an fp16 range failure in the
775
+ forward pass. The AMP loss scale only multiplies the backward pass, so
776
+ backing it off and replaying the same batch reproduces the same NaN;
777
+ the batch is dropped instead (``skip``) and the step proceeds with the
778
+ remaining micro-batches. In fp32 a non-finite loss is a real defect and
779
+ stays fatal.
780
+ """
781
+
782
+ if is_globally_finite_scalar(loss):
783
+ return "ok"
784
+ return "skip" if amp_enabled else "fail"
785
+
786
+
787
+ def model_state_hash(module: nn.Module) -> str:
788
+ digest = hashlib.sha256()
789
+ for name, value in sorted(unwrap_module(module).state_dict().items()):
790
+ tensor = value.detach().cpu().contiguous()
791
+ digest.update(name.encode("utf-8"))
792
+ digest.update(str(tuple(tensor.shape)).encode("ascii"))
793
+ digest.update(str(tensor.dtype).encode("ascii"))
794
+ if tensor.dtype == torch.bfloat16:
795
+ tensor = tensor.float()
796
+ digest.update(tensor.numpy().tobytes())
797
+ return digest.hexdigest()
798
+
799
+
800
+ def _file_sha256(path: Path) -> str:
801
+ digest = hashlib.sha256()
802
+ with Path(path).open("rb") as handle:
803
+ while True:
804
+ block = handle.read(1024 * 1024)
805
+ if not block:
806
+ break
807
+ digest.update(block)
808
+ return digest.hexdigest()
809
+
810
+
811
+ def validate_phase1_artifact_header(
812
+ path: Path, expected_sha256: str
813
+ ) -> Mapping[str, Any]:
814
+ """Pin calibration provenance without instantiating the unused encoder."""
815
+
816
+ actual_sha256 = _file_sha256(path)
817
+ if actual_sha256.lower() != str(expected_sha256).lower():
818
+ raise ValueError(
819
+ "Phase-1 sha256 mismatch: expected %s, received %s"
820
+ % (expected_sha256, actual_sha256)
821
+ )
822
+ checkpoint = _torch_load(path, map_location="cpu")
823
+ expected = {
824
+ "schema_version": PHASE1_SCHEMA_VERSION,
825
+ "phase": 1,
826
+ "aggregation_version": PHASE1_AGGREGATION_VERSION,
827
+ "branch_order": list(BRANCH_ORDER),
828
+ }
829
+ for field, value in expected.items():
830
+ actual = checkpoint.get(field)
831
+ if field == "branch_order" and actual is not None:
832
+ actual = list(actual)
833
+ if actual != value:
834
+ raise ValueError(
835
+ "Phase-1 %s mismatch: expected %r, received %r"
836
+ % (field, value, actual)
837
+ )
838
+ return checkpoint
839
+
840
+
841
+ @dataclass(frozen=True)
842
+ class CheckpointContract:
843
+ condition_mode: str
844
+ phase1_sha256: str
845
+ phase1_metadata: Mapping[str, Any]
846
+ train_digest: str
847
+ val_digest: str
848
+ schedule: Mapping[str, Any]
849
+ architecture: Mapping[str, Any]
850
+ data_plan: Mapping[str, Any]
851
+ init_model_hash: str
852
+ max_steps: int
853
+ ema_decay: float
854
+
855
+ def to_dict(self) -> Dict[str, Any]:
856
+ return dataclasses.asdict(self)
857
+
858
+
859
+ @dataclass
860
+ class ResumeState:
861
+ step: int
862
+ history: List[Dict[str, Any]]
863
+ early_stop: Optional[Dict[str, Any]] = None
864
+
865
+
866
+ def _rng_state() -> Dict[str, Any]:
867
+ state: Dict[str, Any] = {
868
+ "python": random.getstate(),
869
+ "numpy": np.random.get_state(),
870
+ "torch": torch.get_rng_state(),
871
+ }
872
+ if torch.cuda.is_available():
873
+ state["cuda"] = torch.cuda.get_rng_state_all()
874
+ return state
875
+
876
+
877
+ def _restore_rng_state(state: Mapping[str, Any]) -> None:
878
+ random.setstate(state["python"])
879
+ np.random.set_state(state["numpy"])
880
+ torch.set_rng_state(state["torch"])
881
+ if torch.cuda.is_available() and "cuda" in state:
882
+ device_index = torch.cuda.current_device()
883
+ cuda_states = state["cuda"]
884
+ # In torchrun every process may see every GPU. Restoring all devices
885
+ # from every rank would create a cross-process race; each rank owns and
886
+ # restores only its active device. A single-visible-GPU gate checkpoint
887
+ # has one saved stream; it is the portable source stream for every rank.
888
+ source_index = device_index if device_index < len(cuda_states) else 0
889
+ torch.cuda.set_rng_state(cuda_states[source_index], device=device_index)
890
+
891
+
892
+ def _atomic_torch_save(payload: Any, path: Path) -> None:
893
+ path.parent.mkdir(parents=True, exist_ok=True)
894
+ temporary = path.with_name(".%s.%d.tmp" % (path.name, os.getpid()))
895
+ try:
896
+ torch.save(payload, str(temporary))
897
+ os.replace(str(temporary), str(path))
898
+ finally:
899
+ if temporary.exists():
900
+ temporary.unlink()
901
+
902
+
903
+ def _torch_load(path: Path, map_location: Any = "cpu") -> Any:
904
+ try:
905
+ return torch.load(str(path), map_location=map_location, weights_only=False)
906
+ except TypeError:
907
+ return torch.load(str(path), map_location=map_location)
908
+
909
+
910
+ def save_training_checkpoint(
911
+ path: Path,
912
+ model: nn.Module,
913
+ ema: ExponentialMovingAverage,
914
+ optimizer: torch.optim.Optimizer,
915
+ scheduler: torch.optim.lr_scheduler._LRScheduler,
916
+ scaler: torch.cuda.amp.GradScaler,
917
+ *,
918
+ step: int,
919
+ contract: CheckpointContract,
920
+ history: Sequence[Mapping[str, Any]],
921
+ recovery_marker: Optional[Mapping[str, Any]] = None,
922
+ early_stop: Optional[Mapping[str, Any]] = None,
923
+ ) -> None:
924
+ payload = {
925
+ "schema_version": 4,
926
+ "phase": 2,
927
+ "step": int(step),
928
+ "model_state_dict": unwrap_module(model).state_dict(),
929
+ "ema_state_dict": ema.state_dict(),
930
+ "optimizer_state_dict": optimizer.state_dict(),
931
+ "scheduler_state_dict": scheduler.state_dict(),
932
+ "scaler_state_dict": scaler.state_dict(),
933
+ "rng_state": _rng_state(),
934
+ "early_stop": dict(early_stop) if early_stop is not None else None,
935
+ "contract": contract.to_dict(),
936
+ "condition_mode": contract.condition_mode,
937
+ "phase1_sha256": contract.phase1_sha256,
938
+ "phase1_metadata": dict(contract.phase1_metadata),
939
+ "train_digest": contract.train_digest,
940
+ "val_digest": contract.val_digest,
941
+ "schedule_config": dict(contract.schedule),
942
+ "architecture": dict(contract.architecture),
943
+ "init_model_hash": contract.init_model_hash,
944
+ "max_steps": contract.max_steps,
945
+ "ema_decay": contract.ema_decay,
946
+ "history": [dict(item) for item in history],
947
+ }
948
+ if recovery_marker is not None:
949
+ payload["recovery"] = dict(recovery_marker)
950
+ _atomic_torch_save(payload, Path(path))
951
+
952
+
953
+ def recover_amp_gradient_overflow(
954
+ path: Path,
955
+ model: nn.Module,
956
+ ema: ExponentialMovingAverage,
957
+ optimizer: torch.optim.Optimizer,
958
+ scheduler: torch.optim.lr_scheduler._LRScheduler,
959
+ scaler: torch.cuda.amp.GradScaler,
960
+ *,
961
+ step: int,
962
+ contract: CheckpointContract,
963
+ history: Sequence[Mapping[str, Any]],
964
+ rank: int,
965
+ distributed: bool,
966
+ observed_grad_norm: float,
967
+ reason: str = "nonfinite_gradient_norm",
968
+ early_stop: Optional[Mapping[str, Any]] = None,
969
+ ) -> None:
970
+ """Back off AMP exactly once, checkpoint unchanged state, then stop.
971
+
972
+ This function is entered only after a globally synchronized non-finite
973
+ gradient decision. ``GradScaler.update(new_scale=...)`` both applies the
974
+ explicit backoff and resets its per-optimizer UNSCALED stage. The growth
975
+ tracker is reset separately because the public update API intentionally
976
+ preserves it when a caller supplies a scale.
977
+ """
978
+
979
+ scale_before = float(scaler.get_scale())
980
+ scale_after = scale_before * float(scaler.get_backoff_factor())
981
+ if not math.isfinite(scale_after) or scale_after <= 0.0:
982
+ raise FloatingPointError("AMP scaler produced an invalid recovery scale")
983
+ scaler.update(new_scale=scale_after)
984
+ growth_tracker = getattr(scaler, "_growth_tracker", None)
985
+ if not isinstance(growth_tracker, Tensor):
986
+ raise RuntimeError("AMP scaler growth tracker is unavailable for recovery")
987
+ growth_tracker.zero_()
988
+ optimizer.zero_grad(set_to_none=True)
989
+
990
+ marker = {
991
+ "schema_version": 1,
992
+ "reason": str(reason),
993
+ "step": int(step),
994
+ "observed_grad_norm": repr(float(observed_grad_norm)),
995
+ "scale_before": scale_before,
996
+ "scale_after": scale_after,
997
+ "growth_tracker_reset": 0,
998
+ "optimizer_step_applied": False,
999
+ "replay_logical_step": int(step),
1000
+ }
1001
+ save_error: Optional[Exception] = None
1002
+ if rank == 0:
1003
+ try:
1004
+ save_training_checkpoint(
1005
+ path,
1006
+ model,
1007
+ ema,
1008
+ optimizer,
1009
+ scheduler,
1010
+ scaler,
1011
+ step=step,
1012
+ contract=contract,
1013
+ history=history,
1014
+ recovery_marker=marker,
1015
+ early_stop=early_stop,
1016
+ )
1017
+ except Exception as error: # synchronize filesystem failures across DDP
1018
+ save_error = error
1019
+ save_succeeded = save_error is None
1020
+ if distributed:
1021
+ parameter = next(unwrap_module(model).parameters(), None)
1022
+ flag_device = parameter.device if parameter is not None else torch.device("cpu")
1023
+ save_flag = torch.tensor(
1024
+ 1 if save_succeeded else 0,
1025
+ dtype=torch.int32,
1026
+ device=flag_device,
1027
+ )
1028
+ # Every rank participates even when rank zero's atomic write failed,
1029
+ # avoiding peers hanging forever in the subsequent success barrier.
1030
+ dist.broadcast(save_flag, src=0)
1031
+ save_succeeded = bool(save_flag.item())
1032
+ if not save_succeeded:
1033
+ detail = ": %s" % save_error if save_error is not None else ""
1034
+ raise RecoverableAmpOverflow(
1035
+ "AMP overflow recovery checkpoint save failed on rank 0 at %s%s; "
1036
+ "logical step %d was not advanced"
1037
+ % (path, detail, step)
1038
+ ) from save_error
1039
+ if distributed:
1040
+ dist.barrier()
1041
+ raise RecoverableAmpOverflow(
1042
+ "%s at logical step %d; scaler backed off "
1043
+ "from %g to %g and recovery checkpoint saved at %s; resume from it "
1044
+ "to replay the unchanged step"
1045
+ % (
1046
+ "non-finite AMP gradient norm"
1047
+ if reason == "nonfinite_gradient_norm"
1048
+ else "non-finite AMP forward loss",
1049
+ step, scale_before, scale_after, path,
1050
+ )
1051
+ )
1052
+
1053
+
1054
+ def _contract_mismatches(actual: Any, expected: Any, path: str, added: List[str]) -> List[str]:
1055
+ """Recursive comparison; a key that exists in ``expected`` (the running
1056
+ code) but not in the stored ``actual`` is a field ADDED to the
1057
+ architecture/schedule record after the checkpoint was written (recorded
1058
+ in ``added``, tolerated); any other difference is a mismatch."""
1059
+
1060
+ if isinstance(expected, Mapping) and isinstance(actual, Mapping):
1061
+ problems: List[str] = []
1062
+ for key in sorted(set(expected) | set(actual)):
1063
+ child = "%s.%s" % (path, key) if path else str(key)
1064
+ if key not in actual:
1065
+ added.append(child)
1066
+ continue
1067
+ if key not in expected:
1068
+ problems.append("%s removed" % child)
1069
+ continue
1070
+ problems.extend(_contract_mismatches(actual[key], expected[key], child, added))
1071
+ return problems
1072
+ if actual != expected:
1073
+ return ["%s: expected %r, received %r" % (path, expected, actual)]
1074
+ return []
1075
+
1076
+
1077
+ def _validate_contract(actual: Mapping[str, Any], expected: CheckpointContract) -> None:
1078
+ expected_fields = expected.to_dict()
1079
+ for name, expected_value in expected_fields.items():
1080
+ actual_value = actual.get(name)
1081
+ if actual_value == expected_value:
1082
+ continue
1083
+ added: List[str] = []
1084
+ problems = _contract_mismatches(actual_value, expected_value, name, added)
1085
+ if problems:
1086
+ raise ValueError(
1087
+ "checkpoint contract %s mismatch: %s" % (name, "; ".join(problems[:6]))
1088
+ )
1089
+ if added:
1090
+ print(
1091
+ "[resume] contract %s: tolerating %d field(s) added after the checkpoint: %s"
1092
+ % (name, len(added), ", ".join(added[:8])),
1093
+ flush=True,
1094
+ )
1095
+
1096
+
1097
+ def resume_training_checkpoint(
1098
+ path: Path,
1099
+ model: nn.Module,
1100
+ ema: ExponentialMovingAverage,
1101
+ optimizer: torch.optim.Optimizer,
1102
+ scheduler: torch.optim.lr_scheduler._LRScheduler,
1103
+ scaler: torch.cuda.amp.GradScaler,
1104
+ contract: CheckpointContract,
1105
+ ) -> ResumeState:
1106
+ checkpoint = _torch_load(Path(path), map_location="cpu")
1107
+ if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2:
1108
+ raise ValueError("not a Phase-2 v4 checkpoint")
1109
+ _validate_contract(checkpoint.get("contract", {}), contract)
1110
+ unwrap_module(model).load_state_dict(checkpoint["model_state_dict"], strict=True)
1111
+ ema.load_state_dict(checkpoint["ema_state_dict"])
1112
+ optimizer.load_state_dict(checkpoint["optimizer_state_dict"])
1113
+ scheduler.load_state_dict(checkpoint["scheduler_state_dict"])
1114
+ scaler.load_state_dict(checkpoint["scaler_state_dict"])
1115
+ _restore_rng_state(checkpoint["rng_state"])
1116
+ stored_early_stop = checkpoint.get("early_stop")
1117
+ return ResumeState(
1118
+ step=int(checkpoint["step"]),
1119
+ history=[dict(item) for item in checkpoint.get("history", [])],
1120
+ early_stop=dict(stored_early_stop) if isinstance(stored_early_stop, Mapping) else None,
1121
+ )
1122
+
1123
+
1124
+ def load_shared_initialization(
1125
+ path: Path,
1126
+ model: nn.Module,
1127
+ *,
1128
+ target_condition: str,
1129
+ expected_architecture: Mapping[str, Any],
1130
+ expected_schedule: Mapping[str, Any],
1131
+ expected_data_plan: Mapping[str, Any],
1132
+ expected_phase1_sha256: str,
1133
+ expected_phase1_metadata: Mapping[str, Any],
1134
+ expected_train_digest: str,
1135
+ expected_val_digest: str,
1136
+ expected_max_steps: int,
1137
+ expected_ema_decay: float,
1138
+ ) -> str:
1139
+ """Load a provenance-checked step-zero D0 initialization for the D5 gate."""
1140
+
1141
+ checkpoint = _torch_load(Path(path), map_location="cpu")
1142
+ if not isinstance(checkpoint, Mapping):
1143
+ raise ValueError("initialization checkpoint must be a mapping")
1144
+ if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2:
1145
+ raise ValueError("initialization must be a Phase-2 v4 checkpoint")
1146
+ source_step = checkpoint.get("step")
1147
+ if isinstance(source_step, bool) or source_step != 0:
1148
+ raise ValueError("shared initialization checkpoint must be at step zero")
1149
+ source_contract = checkpoint.get("contract")
1150
+ if not isinstance(source_contract, Mapping):
1151
+ raise ValueError("initialization checkpoint is missing its contract")
1152
+ for field, expected in (
1153
+ ("architecture", dict(expected_architecture)),
1154
+ ("schedule", dict(expected_schedule)),
1155
+ ("data_plan", dict(expected_data_plan)),
1156
+ ):
1157
+ if source_contract.get(field) != expected:
1158
+ raise ValueError("shared initialization %s mismatch" % field)
1159
+ expected_provenance: Dict[str, Any] = {
1160
+ "phase1_sha256": str(expected_phase1_sha256),
1161
+ "phase1_metadata": dict(expected_phase1_metadata),
1162
+ "train_digest": str(expected_train_digest),
1163
+ "val_digest": str(expected_val_digest),
1164
+ "max_steps": int(expected_max_steps),
1165
+ "ema_decay": float(expected_ema_decay),
1166
+ }
1167
+ # Validate both the canonical contract and its top-level audit mirrors.
1168
+ # Requiring both prevents a partially edited checkpoint from becoming the
1169
+ # shared D0/D5 initialization source.
1170
+ for field, expected in expected_provenance.items():
1171
+ if source_contract.get(field) != expected:
1172
+ raise ValueError(
1173
+ "shared initialization contract %s mismatch" % field
1174
+ )
1175
+ if checkpoint.get(field) != expected:
1176
+ raise ValueError(
1177
+ "shared initialization top-level %s mismatch" % field
1178
+ )
1179
+ source_condition = source_contract.get("condition_mode")
1180
+ if source_condition != target_condition and not (
1181
+ source_condition == "null" and target_condition == "full"
1182
+ ):
1183
+ raise ValueError(
1184
+ "shared initialization condition transition %r -> %r is forbidden"
1185
+ % (source_condition, target_condition)
1186
+ )
1187
+ state = checkpoint.get("model_state_dict")
1188
+ if not isinstance(state, Mapping):
1189
+ raise ValueError("initialization checkpoint has no model state")
1190
+
1191
+ target = unwrap_module(model)
1192
+ # Schedule buffers are immutable scientific configuration, not trainable
1193
+ # initialization. Compare them before loading so a mislabeled checkpoint
1194
+ # cannot overwrite the CLI-built schedule while recording a different one.
1195
+ for name, expected_value in target.schedule.state_dict().items():
1196
+ source_value = state.get("schedule." + name)
1197
+ if not isinstance(source_value, Tensor) or not torch.equal(
1198
+ source_value.detach().cpu(), expected_value.detach().cpu()
1199
+ ):
1200
+ raise ValueError("shared initialization schedule buffer mismatch: %s" % name)
1201
+ target.load_state_dict(state, strict=True)
1202
+ actual_hash = model_state_hash(target)
1203
+ recorded_hash = source_contract.get("init_model_hash")
1204
+ if recorded_hash != actual_hash or checkpoint.get("init_model_hash") != actual_hash:
1205
+ raise ValueError("shared initialization model hash mismatch")
1206
+ return actual_hash
1207
+
1208
+
1209
+ class BoundedCheckpointManager:
1210
+ """Only init/last/best/recovery plus at most three milestone files."""
1211
+
1212
+ def __init__(self, output_dir: Path, max_milestones: int = 3) -> None:
1213
+ if max_milestones < 0 or max_milestones > 3:
1214
+ raise ValueError("max_milestones must be between zero and three")
1215
+ self.output_dir = Path(output_dir)
1216
+ self.max_milestones = int(max_milestones)
1217
+
1218
+ def path_for(self, kind: str, step: Optional[int] = None) -> Path:
1219
+ if kind in ("init", "last", "best", "overflow_recovery"):
1220
+ return self.output_dir / (kind + ".pt")
1221
+ if kind == "milestone" and step is not None:
1222
+ return self.output_dir / ("milestone_%08d.pt" % int(step))
1223
+ raise ValueError("unsupported checkpoint kind")
1224
+
1225
+ def prune_milestones(self) -> None:
1226
+ files = sorted(self.output_dir.glob("milestone_*.pt"))
1227
+ for obsolete in files[: max(0, len(files) - self.max_milestones)]:
1228
+ obsolete.unlink()
1229
+
1230
+
1231
+ def build_lr_scheduler(
1232
+ optimizer: torch.optim.Optimizer,
1233
+ max_steps: int,
1234
+ warmup_steps: int = 500,
1235
+ min_lr: float = 1e-6,
1236
+ base_lr: float = 1e-4,
1237
+ ) -> torch.optim.lr_scheduler.LambdaLR:
1238
+ if max_steps <= warmup_steps:
1239
+ raise ValueError("max_steps must exceed warmup_steps")
1240
+ minimum_ratio = float(min_lr) / float(base_lr)
1241
+
1242
+ def multiplier(step: int) -> float:
1243
+ if step < warmup_steps:
1244
+ return max(float(step + 1) / float(warmup_steps), 1.0 / warmup_steps)
1245
+ progress = min(1.0, float(step - warmup_steps) / float(max_steps - warmup_steps))
1246
+ cosine = 0.5 * (1.0 + math.cos(math.pi * progress))
1247
+ return minimum_ratio + (1.0 - minimum_ratio) * cosine
1248
+
1249
+ return torch.optim.lr_scheduler.LambdaLR(optimizer, multiplier)
1250
+
1251
+
1252
+ def _atomic_json_dump(payload: Any, path: Path) -> None:
1253
+ path.parent.mkdir(parents=True, exist_ok=True)
1254
+ temporary = path.with_name(".%s.%d.tmp" % (path.name, os.getpid()))
1255
+ try:
1256
+ with temporary.open("w", encoding="utf-8") as handle:
1257
+ json.dump(payload, handle, indent=2, sort_keys=True)
1258
+ handle.write("\n")
1259
+ os.replace(str(temporary), str(path))
1260
+ finally:
1261
+ if temporary.exists():
1262
+ temporary.unlink()
1263
+
1264
+
1265
+ def _append_jsonl(payload: Mapping[str, Any], path: Path) -> None:
1266
+ path.parent.mkdir(parents=True, exist_ok=True)
1267
+ with path.open("a", encoding="utf-8") as handle:
1268
+ handle.write(json.dumps(dict(payload), sort_keys=True) + "\n")
1269
+
1270
+
1271
+ @torch.no_grad()
1272
+ def calibrate_kappa(
1273
+ loader: Iterable[Mapping[str, Any]],
1274
+ output_path: Path,
1275
+ max_images: int = 4096,
1276
+ ) -> Dict[str, Any]:
1277
+ """Train-only residual RMS audit; recommendation is the macro domain median."""
1278
+
1279
+ values: Dict[str, List[float]] = {domain: [] for domain in DOMAINS}
1280
+ seen = 0
1281
+ for batch in loader:
1282
+ clean = batch["clean"]
1283
+ degraded = batch["degraded"]
1284
+ domains = [str(value) for value in batch["degradation"]]
1285
+ u0, uy = pixel_unshuffle2(clean), pixel_unshuffle2(degraded)
1286
+ rms = (uy.float() - u0.float()).square().flatten(1).mean(1).sqrt().tolist()
1287
+ for domain, value in zip(domains, rms):
1288
+ values[domain].append(float(value))
1289
+ seen += 1
1290
+ if seen >= max_images:
1291
+ break
1292
+ if seen >= max_images:
1293
+ break
1294
+ missing = [domain for domain in DOMAINS if not values[domain]]
1295
+ if missing:
1296
+ raise ValueError("kappa calibration has no training samples for %r" % missing)
1297
+ medians = {domain: float(np.median(values[domain])) for domain in DOMAINS}
1298
+ payload = {
1299
+ "schema_version": 1,
1300
+ "source": "training_split_only",
1301
+ "num_images": seen,
1302
+ "per_domain_residual_rms_median": medians,
1303
+ "recommended_kappa": float(np.median(list(medians.values()))),
1304
+ }
1305
+ _atomic_json_dump(payload, Path(output_path))
1306
+ return payload
1307
+
1308
+
1309
+ def _parse_int_csv(value: str) -> Tuple[int, ...]:
1310
+ if not value.strip():
1311
+ return ()
1312
+ result = tuple(sorted(set(int(item.strip()) for item in value.split(","))))
1313
+ if any(item < 0 for item in result):
1314
+ raise argparse.ArgumentTypeError("steps must be non-negative")
1315
+ return result
1316
+
1317
+
1318
+ def _parse_dims(value: str) -> Tuple[int, int, int, int]:
1319
+ result = tuple(int(item.strip()) for item in value.split(","))
1320
+ if len(result) != 4 or any(item <= 0 for item in result):
1321
+ raise argparse.ArgumentTypeError("dims must be four positive comma-separated integers")
1322
+ return result # type: ignore[return-value]
1323
+
1324
+
1325
+ def build_parser() -> argparse.ArgumentParser:
1326
+ parser = argparse.ArgumentParser(description=__doc__)
1327
+ parser.add_argument("--condition", choices=("full", "null"), default="full")
1328
+ parser.add_argument("--phase1-checkpoint", type=Path, required=True)
1329
+ parser.add_argument("--phase1-sha256", required=True)
1330
+ parser.add_argument("--manifest", type=Path, required=True)
1331
+ parser.add_argument("--create-manifest", action="store_true")
1332
+ parser.add_argument("--data-root", type=Path, default=Path(os.environ.get("SCDC_DATA_ROOT", "/home/admin_mcn/data")))
1333
+ parser.add_argument("--rain13k-root", type=Path)
1334
+ parser.add_argument("--quarantine-manifest", type=Path)
1335
+ parser.add_argument("--output-dir", type=Path, required=True)
1336
+ parser.add_argument("--batch-size", type=int, default=8)
1337
+ parser.add_argument("--eval-batch-size", type=int, default=4)
1338
+ parser.add_argument("--grad-accum", type=int, default=2)
1339
+ parser.add_argument("--max-steps", type=int, default=40_000)
1340
+ parser.add_argument("--run-until-step", type=int, default=None)
1341
+ parser.add_argument(
1342
+ "--eval-steps",
1343
+ type=_parse_int_csv,
1344
+ default=(0, 500, 1000, 2000, 5000, 10000, 20000, 40000),
1345
+ )
1346
+ parser.add_argument("--milestone-steps", type=_parse_int_csv, default=())
1347
+ parser.add_argument("--workers", type=int, default=8)
1348
+ parser.add_argument(
1349
+ "--extra-clean-workers", type=int, default=2,
1350
+ help="DataLoader workers for the extra clean pool (12 MP SIDD PNGs decode slowly; "
1351
+ "2 workers capped the MI325X run at ~20%% GPU use)",
1352
+ )
1353
+ parser.add_argument("--crop-size", type=int, default=256)
1354
+ parser.add_argument("--dims", type=_parse_dims, default=(64, 128, 192, 256))
1355
+ parser.add_argument("--cond-dim", type=int, default=256)
1356
+ parser.add_argument("--timesteps", type=int, default=8)
1357
+ parser.add_argument("--eta-end", type=float, default=0.99)
1358
+ parser.add_argument("--min-noise", type=float, default=0.2)
1359
+ parser.add_argument("--power", type=float, default=0.3)
1360
+ parser.add_argument("--kappa", type=float, default=None)
1361
+ parser.add_argument("--seed", type=int, default=42)
1362
+ parser.add_argument("--eval-seed", type=int, default=20260830)
1363
+ parser.add_argument("--device", default="cuda")
1364
+ parser.add_argument("--ddp", action="store_true")
1365
+ parser.add_argument(
1366
+ "--freeze-encoder-steps", type=int, default=0,
1367
+ help="train only the decoder/conditioning/heads for the first N steps "
1368
+ "(encoder gradients are dropped); 0 = train everything from step 0",
1369
+ )
1370
+ parser.add_argument(
1371
+ "--early-stop-patience", type=int, default=0,
1372
+ help="stop after N consecutive evaluations without a real macro-PSNR gain (0 = off)",
1373
+ )
1374
+ parser.add_argument("--early-stop-min-delta", type=float, default=0.02)
1375
+ parser.add_argument(
1376
+ "--identity-pair-prob", type=float, default=0.0,
1377
+ help="per-sample probability of feeding the clean target as input",
1378
+ )
1379
+ parser.add_argument(
1380
+ "--noise-pair-prob", type=float, default=0.0,
1381
+ help="per-sample probability of a synthetic (clean+noise, clean) pair",
1382
+ )
1383
+ parser.add_argument(
1384
+ "--global-context", action="store_true",
1385
+ help="run Phase-1 on the whole frame too and inject it (v7 backends)",
1386
+ )
1387
+ parser.add_argument(
1388
+ "--ddp-find-unused", action="store_true",
1389
+ help="required for MoE backends under DDP (data-dependent expert use)",
1390
+ )
1391
+ parser.add_argument("--no-amp", action="store_true")
1392
+ parser.add_argument("--resume", type=Path)
1393
+ parser.add_argument("--init-checkpoint", type=Path)
1394
+ parser.add_argument("--ema-decay", type=float, default=0.9999)
1395
+ parser.add_argument("--learning-rate", type=float, default=1e-4)
1396
+ parser.add_argument("--calibrate-kappa", action="store_true")
1397
+ parser.add_argument("--calibration-images", type=int, default=4096)
1398
+ return parser
1399
+
1400
+
1401
+ def _distributed_context(args: argparse.Namespace) -> Tuple[int, int, int, torch.device]:
1402
+ if args.ddp:
1403
+ if not torch.cuda.is_available():
1404
+ raise RuntimeError("DDP/NCCL requires CUDA")
1405
+ if not dist.is_initialized():
1406
+ dist.init_process_group(backend="nccl", init_method="env://")
1407
+ rank, world_size = dist.get_rank(), dist.get_world_size()
1408
+ local_rank = int(os.environ.get("LOCAL_RANK", "0"))
1409
+ torch.cuda.set_device(local_rank)
1410
+ return rank, world_size, local_rank, torch.device("cuda", local_rank)
1411
+ device = torch.device(args.device)
1412
+ if device.type == "cuda" and not torch.cuda.is_available():
1413
+ raise RuntimeError("CUDA was requested but is unavailable")
1414
+ if device.type == "cuda":
1415
+ device_index = 0 if device.index is None else int(device.index)
1416
+ torch.cuda.set_device(device_index)
1417
+ device = torch.device("cuda", device_index)
1418
+ return 0, 1, 0, device
1419
+
1420
+
1421
+ def _seed_everything(seed: int, rank: int) -> None:
1422
+ value = int(seed) + int(rank) * 1000003
1423
+ random.seed(value)
1424
+ np.random.seed(value % (2 ** 32))
1425
+ torch.manual_seed(value)
1426
+ if torch.cuda.is_available():
1427
+ torch.cuda.manual_seed_all(value)
1428
+
1429
+
1430
+ def build_frozen_phase1(
1431
+ checkpoint_path: Path, expected_sha256: str, device: torch.device
1432
+ ) -> Tuple[FrozenPhase1, Dict[str, Any]]:
1433
+ # Kept lazy so unit tests can run in checkouts that only contain Phase 2.
1434
+ import inspect
1435
+
1436
+ from src.models.graph_encoder import BlindDegradationGraphEncoder, GraphConfig
1437
+
1438
+ # The encoder architecture is governed by the checkpoint's stored
1439
+ # graph_config (e.g. the ll_v3 global branch); unknown or missing keys
1440
+ # fall back to the legacy defaults so v2 checkpoints load unchanged.
1441
+ peek = _torch_load(Path(checkpoint_path), map_location="cpu")
1442
+ stored: Dict[str, Any] = {}
1443
+ config_block = peek.get("config") if isinstance(peek, Mapping) else None
1444
+ if isinstance(config_block, Mapping):
1445
+ graph_block = config_block.get("graph_config")
1446
+ if isinstance(graph_block, Mapping):
1447
+ stored = dict(graph_block)
1448
+ allowed = set(inspect.signature(GraphConfig.__init__).parameters) - {"self"}
1449
+ kwargs = {key: value for key, value in stored.items() if key in allowed}
1450
+ if "spatial_map_size" in kwargs:
1451
+ kwargs["spatial_map_size"] = tuple(kwargs["spatial_map_size"])
1452
+ del peek
1453
+
1454
+ encoder = BlindDegradationGraphEncoder(GraphConfig(**kwargs))
1455
+ metadata = load_phase1_checkpoint(
1456
+ checkpoint_path, encoder, expected_sha256=expected_sha256, map_location="cpu"
1457
+ )
1458
+ frozen = FrozenPhase1(encoder).to(device)
1459
+ frozen.eval()
1460
+ return frozen, metadata
1461
+
1462
+
1463
+ def _load_or_create_splits(args: argparse.Namespace) -> Any:
1464
+ from src.data.phase2_v4 import (
1465
+ build_train_val_splits,
1466
+ load_train_val_manifest,
1467
+ save_train_val_manifest,
1468
+ )
1469
+
1470
+ if args.create_manifest:
1471
+ if args.rain13k_root is None or args.quarantine_manifest is None:
1472
+ raise ValueError("creating a manifest requires rain and quarantine paths")
1473
+ splits = build_train_val_splits(
1474
+ args.data_root, args.rain13k_root, args.quarantine_manifest
1475
+ )
1476
+ save_train_val_manifest(args.manifest, splits)
1477
+ return splits
1478
+ if not args.manifest.is_file():
1479
+ raise FileNotFoundError("manifest does not exist: %s" % args.manifest)
1480
+ return load_train_val_manifest(args.manifest)
1481
+
1482
+
1483
+ def _make_loaders(
1484
+ args: argparse.Namespace,
1485
+ splits: Any,
1486
+ start_microstep: int,
1487
+ rank: int,
1488
+ world_size: int,
1489
+ ) -> Tuple[DataLoader, DataLoader]:
1490
+ from src.data.phase2_v4 import (
1491
+ DeterministicBalancedBatchSampler,
1492
+ Phase2PairDataset,
1493
+ )
1494
+
1495
+ train_dataset = Phase2PairDataset(
1496
+ splits.train, crop_size=args.crop_size, training=True, upscale_small=True
1497
+ )
1498
+ val_dataset = Phase2PairDataset(
1499
+ splits.val, crop_size=args.crop_size, training=False, upscale_small=True
1500
+ )
1501
+ stop_step = args.run_until_step if args.run_until_step is not None else args.max_steps
1502
+ total_microsteps = stop_step * args.grad_accum
1503
+ if start_microstep > total_microsteps:
1504
+ raise ValueError("resume step is beyond --run-until-step")
1505
+ sampler = DeterministicBalancedBatchSampler(
1506
+ [record.label for record in splits.train],
1507
+ batch_size=args.batch_size,
1508
+ steps=max(1, total_microsteps),
1509
+ seed=args.seed,
1510
+ start_microstep=start_microstep,
1511
+ rank=rank,
1512
+ world_size=world_size,
1513
+ )
1514
+ loader_kwargs: Dict[str, Any] = {
1515
+ "num_workers": args.workers,
1516
+ "pin_memory": True,
1517
+ }
1518
+ if args.workers > 0:
1519
+ loader_kwargs["persistent_workers"] = True
1520
+ loader_kwargs["prefetch_factor"] = 2
1521
+ train_loader = DataLoader(train_dataset, batch_sampler=sampler, **loader_kwargs)
1522
+ val_loader = DataLoader(
1523
+ val_dataset,
1524
+ batch_size=args.eval_batch_size,
1525
+ shuffle=False,
1526
+ drop_last=False,
1527
+ **loader_kwargs,
1528
+ )
1529
+ return train_loader, val_loader
1530
+
1531
+
1532
+ def _architecture(args: argparse.Namespace) -> Dict[str, Any]:
1533
+ return {
1534
+ "name": "graph_resshift_v4",
1535
+ "dims": list(args.dims),
1536
+ "cond_dim": args.cond_dim,
1537
+ "state_channels": 12,
1538
+ "pixel_unshuffle_factor": 2,
1539
+ "denoiser_input_channels": 36,
1540
+ "prediction": "x0",
1541
+ }
1542
+
1543
+
1544
+ def _data_plan(
1545
+ args: argparse.Namespace,
1546
+ world_size: int,
1547
+ amp_enabled: Optional[bool] = None,
1548
+ ) -> Dict[str, Any]:
1549
+ global_micro_batch = int(args.batch_size) * int(world_size)
1550
+ if amp_enabled is None:
1551
+ amp_enabled = not bool(getattr(args, "no_amp", False))
1552
+ return {
1553
+ "schema_version": 1,
1554
+ "sampler": "deterministic_balanced_global_shard_v1",
1555
+ "noise_plan": "per_sample_seed_v1",
1556
+ "seed": int(args.seed),
1557
+ "eval_seed": int(args.eval_seed),
1558
+ "crop_size": int(args.crop_size),
1559
+ "global_micro_batch": global_micro_batch,
1560
+ "grad_accum": int(args.grad_accum),
1561
+ "effective_batch": global_micro_batch * int(args.grad_accum),
1562
+ "precision": "amp_fp16" if amp_enabled else "fp32",
1563
+ }
1564
+
1565
+
1566
+ def _schedule_config(args: argparse.Namespace) -> Dict[str, Any]:
1567
+ return {
1568
+ "timesteps": args.timesteps,
1569
+ "eta_end": args.eta_end,
1570
+ "min_noise": args.min_noise,
1571
+ "power": args.power,
1572
+ "kappa": args.kappa,
1573
+ }
1574
+
1575
+
1576
+ def _build_restorer(args: argparse.Namespace, device: torch.device) -> Phase2RestorationModule:
1577
+ schedule = ResidualShiftSchedule(
1578
+ timesteps=args.timesteps,
1579
+ eta_end=args.eta_end,
1580
+ min_noise=args.min_noise,
1581
+ power=args.power,
1582
+ kappa=args.kappa,
1583
+ )
1584
+ conditioner = GraphConditionerV4(cond_dim=args.cond_dim, stage_dims=args.dims)
1585
+ denoiser = GraphResidualShiftUNetV4(dims=args.dims, cond_dim=args.cond_dim)
1586
+ return Phase2RestorationModule(
1587
+ conditioner, denoiser, schedule, args.condition
1588
+ ).to(device)
1589
+
1590
+
1591
+ def _write_run_config(args: argparse.Namespace, path: Path) -> None:
1592
+ payload = vars(args).copy()
1593
+ for name, value in list(payload.items()):
1594
+ if isinstance(value, Path):
1595
+ payload[name] = str(value)
1596
+ elif isinstance(value, tuple):
1597
+ payload[name] = list(value)
1598
+ _atomic_json_dump(payload, path)
1599
+
1600
+
1601
+ def _prepare_output_directory(
1602
+ args: argparse.Namespace,
1603
+ rank: int,
1604
+ resume_step: Optional[int] = None,
1605
+ ) -> None:
1606
+ """Protect run provenance and write config only after contract validation."""
1607
+
1608
+ output_dir = Path(args.output_dir)
1609
+ if args.resume is None:
1610
+ nonempty = output_dir.exists() and any(output_dir.iterdir())
1611
+ if nonempty:
1612
+ raise FileExistsError(
1613
+ "fresh output directory is not empty: %s" % output_dir
1614
+ )
1615
+ output_dir.mkdir(parents=True, exist_ok=True)
1616
+ if args.ddp:
1617
+ dist.barrier()
1618
+ if rank == 0:
1619
+ if args.resume is None:
1620
+ destination = output_dir / "run_config.json"
1621
+ else:
1622
+ destination = output_dir / (
1623
+ "resume_config_step_%08d_%d.json"
1624
+ % (int(resume_step or 0), time.time_ns())
1625
+ )
1626
+ _write_run_config(args, destination)
1627
+ if args.ddp:
1628
+ dist.barrier()
1629
+
1630
+
1631
+ def validate_runtime_args(args: argparse.Namespace) -> int:
1632
+ """Fail on invalid CLI combinations before touching CUDA or run outputs."""
1633
+
1634
+ if args.kappa is None and not args.calibrate_kappa:
1635
+ raise ValueError("training requires an explicit frozen --kappa")
1636
+ if args.kappa is not None and (
1637
+ not math.isfinite(args.kappa) or args.kappa < 0.0
1638
+ ):
1639
+ raise ValueError("--kappa must be finite and non-negative")
1640
+ if not math.isfinite(args.power) or args.power <= 0.0:
1641
+ raise ValueError("--power must be finite and positive")
1642
+ if not math.isfinite(args.ema_decay) or not 0.0 <= args.ema_decay < 1.0:
1643
+ raise ValueError("--ema-decay must be finite and lie in [0, 1)")
1644
+ if args.max_steps <= 500:
1645
+ raise ValueError("--max-steps must exceed the 500-step warmup")
1646
+ stop_step = args.run_until_step if args.run_until_step is not None else args.max_steps
1647
+ if stop_step < 0 or stop_step > args.max_steps:
1648
+ raise ValueError("--run-until-step must lie in [0, max_steps]")
1649
+ if args.batch_size <= 0 or args.batch_size % 4:
1650
+ raise ValueError("--batch-size must be positive and divisible by four")
1651
+ if args.grad_accum <= 0:
1652
+ raise ValueError("--grad-accum must be positive")
1653
+ if args.resume is not None and args.init_checkpoint is not None:
1654
+ raise ValueError("--resume and --init-checkpoint are mutually exclusive")
1655
+ if args.calibrate_kappa and (
1656
+ args.resume is not None or args.init_checkpoint is not None
1657
+ ):
1658
+ raise ValueError("kappa calibration cannot resume or load model initialization")
1659
+ if args.crop_size <= 0 or args.crop_size % 2:
1660
+ raise ValueError("--crop-size must be a positive even integer")
1661
+ if args.eval_batch_size <= 0:
1662
+ raise ValueError("--eval-batch-size must be positive")
1663
+ if args.workers < 0:
1664
+ raise ValueError("--workers must be non-negative")
1665
+ return int(stop_step)
1666
+
1667
+
1668
+ def run(args: argparse.Namespace) -> None:
1669
+ stop_step = validate_runtime_args(args)
1670
+
1671
+ rank, world_size, local_rank, device = _distributed_context(args)
1672
+ _seed_everything(args.seed, rank)
1673
+ output_dir = args.output_dir
1674
+ amp_enabled = device.type == "cuda" and not args.no_amp
1675
+
1676
+ splits = _load_or_create_splits(args)
1677
+ from src.data.phase2_v4 import (
1678
+ split_digest,
1679
+ validate_clean_file_integrity,
1680
+ validate_splits_against_checkpoint,
1681
+ )
1682
+
1683
+ # Calibration and training are both pinned to the exact Phase-1 support
1684
+ # provenance; no optimization mode may silently use a different split.
1685
+ phase1_checkpoint = validate_phase1_artifact_header(
1686
+ args.phase1_checkpoint, args.phase1_sha256
1687
+ )
1688
+ validate_splits_against_checkpoint(splits, phase1_checkpoint)
1689
+ # Only canonical, provenance-validated paths may be read. Hashing before
1690
+ # the split contract check could touch an arbitrary path from a tampered
1691
+ # manifest (including data reserved outside the training/validation set).
1692
+ validate_clean_file_integrity(splits)
1693
+ if args.calibrate_kappa:
1694
+ _prepare_output_directory(args, rank)
1695
+ # Calibration is train-only and exactly domain balanced. A sequential
1696
+ # traversal would exhaust the Rain13K prefix before seeing the smaller
1697
+ # SIDD/LOLv2 domains when a sample cap is used.
1698
+ from src.data.phase2_v4 import (
1699
+ DeterministicBalancedBatchSampler,
1700
+ Phase2PairDataset,
1701
+ )
1702
+
1703
+ calibration_dataset = Phase2PairDataset(
1704
+ splits.train, crop_size=args.crop_size, training=True, upscale_small=True
1705
+ )
1706
+ if args.calibration_images < 4:
1707
+ raise ValueError("--calibration-images must be at least four")
1708
+ calibration_batch = max(4, (args.eval_batch_size // 4) * 4)
1709
+ calibration_steps = int(
1710
+ math.ceil(float(args.calibration_images) / float(calibration_batch))
1711
+ )
1712
+ calibration_sampler = DeterministicBalancedBatchSampler(
1713
+ [record.label for record in splits.train],
1714
+ batch_size=calibration_batch,
1715
+ steps=calibration_steps,
1716
+ seed=args.seed,
1717
+ )
1718
+ calibration_loader = DataLoader(
1719
+ calibration_dataset,
1720
+ batch_sampler=calibration_sampler,
1721
+ num_workers=args.workers,
1722
+ pin_memory=True,
1723
+ )
1724
+ if rank == 0:
1725
+ result = calibrate_kappa(
1726
+ calibration_loader,
1727
+ output_dir / "kappa_calibration.json",
1728
+ max_images=args.calibration_images,
1729
+ )
1730
+ print(json.dumps(result, sort_keys=True))
1731
+ if args.ddp:
1732
+ dist.barrier()
1733
+ dist.destroy_process_group()
1734
+ return
1735
+
1736
+ phase1, phase1_metadata = build_frozen_phase1(
1737
+ args.phase1_checkpoint, args.phase1_sha256, device
1738
+ )
1739
+ train_digest_value = split_digest(splits.train)
1740
+ val_digest_value = split_digest(splits.val)
1741
+
1742
+ model = _build_restorer(args, device)
1743
+ architecture_config = _architecture(args)
1744
+ schedule_config = _schedule_config(args)
1745
+ data_plan = _data_plan(args, world_size, amp_enabled=amp_enabled)
1746
+ if args.resume is not None:
1747
+ resume_header = _torch_load(args.resume, map_location="cpu")
1748
+ stored_contract = resume_header.get("contract", {})
1749
+ if "init_model_hash" not in stored_contract:
1750
+ raise ValueError("resume checkpoint is missing init_model_hash")
1751
+ # A DDP rank intentionally has a different pre-broadcast RNG stream;
1752
+ # preserve and validate the immutable initialization provenance stored
1753
+ # by the single-GPU source run rather than hashing throwaway weights.
1754
+ init_hash = str(stored_contract["init_model_hash"])
1755
+ elif args.init_checkpoint is not None:
1756
+ init_hash = load_shared_initialization(
1757
+ args.init_checkpoint,
1758
+ model,
1759
+ target_condition=args.condition,
1760
+ expected_architecture=architecture_config,
1761
+ expected_schedule=schedule_config,
1762
+ expected_data_plan=data_plan,
1763
+ expected_phase1_sha256=phase1_metadata["sha256"],
1764
+ expected_phase1_metadata=phase1_metadata,
1765
+ expected_train_digest=train_digest_value,
1766
+ expected_val_digest=val_digest_value,
1767
+ expected_max_steps=args.max_steps,
1768
+ expected_ema_decay=args.ema_decay,
1769
+ )
1770
+ else:
1771
+ init_hash = model_state_hash(model)
1772
+ base_lr = float(getattr(args, "learning_rate", 1e-4))
1773
+ optimizer = torch.optim.AdamW(
1774
+ model.parameters(), lr=base_lr, betas=(0.9, 0.99), weight_decay=1e-4
1775
+ )
1776
+ scheduler = build_lr_scheduler(
1777
+ optimizer, max_steps=args.max_steps, base_lr=base_lr
1778
+ )
1779
+ scaler = make_grad_scaler(amp_enabled)
1780
+ ema = ExponentialMovingAverage(model, decay=args.ema_decay)
1781
+ contract = CheckpointContract(
1782
+ condition_mode=args.condition,
1783
+ phase1_sha256=phase1_metadata["sha256"],
1784
+ phase1_metadata=phase1_metadata,
1785
+ train_digest=train_digest_value,
1786
+ val_digest=val_digest_value,
1787
+ schedule=schedule_config,
1788
+ architecture=architecture_config,
1789
+ data_plan=data_plan,
1790
+ init_model_hash=init_hash,
1791
+ max_steps=args.max_steps,
1792
+ ema_decay=args.ema_decay,
1793
+ )
1794
+ history: List[Dict[str, Any]] = []
1795
+ step = 0
1796
+ resumed_early_stop: Optional[Dict[str, Any]] = None
1797
+ if args.resume is not None:
1798
+ resumed = resume_training_checkpoint(
1799
+ args.resume, model, ema, optimizer, scheduler, scaler, contract
1800
+ )
1801
+ step, history = resumed.step, resumed.history
1802
+ resumed_early_stop = resumed.early_stop
1803
+ _prepare_output_directory(args, rank, resume_step=step)
1804
+ elif rank == 0:
1805
+ _prepare_output_directory(args, rank)
1806
+ manager = BoundedCheckpointManager(output_dir)
1807
+ save_training_checkpoint(
1808
+ manager.path_for("init"), model, ema, optimizer, scheduler, scaler,
1809
+ step=0, contract=contract, history=history,
1810
+ )
1811
+ else:
1812
+ _prepare_output_directory(args, rank)
1813
+
1814
+ # Phase 1 is outside DistributedDataParallel and outside the optimizer.
1815
+ phase1_parameter_ids = {id(parameter) for parameter in phase1.parameters()}
1816
+ optimizer_parameter_ids = {
1817
+ id(parameter) for group in optimizer.param_groups for parameter in group["params"]
1818
+ }
1819
+ if phase1_parameter_ids & optimizer_parameter_ids:
1820
+ raise RuntimeError("Phase-1 parameters leaked into the Phase-2 optimizer")
1821
+
1822
+ if args.ddp:
1823
+ model = DistributedDataParallel(
1824
+ model,
1825
+ device_ids=[local_rank],
1826
+ output_device=local_rank,
1827
+ broadcast_buffers=False,
1828
+ # MoE backends (v5+) hard-skip unselected experts per batch, so
1829
+ # parameter usage is data-dependent and differs across ranks;
1830
+ # without unused-parameter tracking the reducer deadlocks on the
1831
+ # first batch whose expert set diverges.
1832
+ find_unused_parameters=bool(
1833
+ getattr(args, "ddp_find_unused", False)
1834
+ ),
1835
+ )
1836
+ start_microstep = step * args.grad_accum
1837
+ train_loader, val_loader = _make_loaders(
1838
+ args, splits, start_microstep, rank, world_size
1839
+ )
1840
+ eval_steps = set(args.eval_steps)
1841
+ milestone_steps = set(args.milestone_steps)
1842
+ manager = BoundedCheckpointManager(output_dir)
1843
+ best_score = max(
1844
+ [float(item.get("macro_psnr", -float("inf"))) for item in history]
1845
+ or [-float("inf")]
1846
+ )
1847
+
1848
+ early_stopper = EarlyStopper(
1849
+ int(getattr(args, "early_stop_patience", 0)),
1850
+ float(getattr(args, "early_stop_min_delta", 0.02)),
1851
+ )
1852
+ if resumed_early_stop:
1853
+ early_stopper.load_state_dict(resumed_early_stop)
1854
+ if rank == 0:
1855
+ print("[resume] early-stop state restored: %r" % (resumed_early_stop,), flush=True)
1856
+ freeze_encoder_steps = int(getattr(args, "freeze_encoder_steps", 0))
1857
+
1858
+ def do_evaluation(current_step: int) -> bool:
1859
+ """Evaluate on rank zero; return whether training should stop."""
1860
+ nonlocal best_score
1861
+ stop_flag = 0
1862
+ if args.ddp:
1863
+ dist.barrier()
1864
+ # Rank zero evaluates a complete, fixed-order validation set.
1865
+ if rank == 0:
1866
+ with ema.apply(model):
1867
+ metrics = evaluate(
1868
+ model,
1869
+ phase1,
1870
+ val_loader,
1871
+ device,
1872
+ args.eval_seed,
1873
+ amp_enabled=amp_enabled,
1874
+ )
1875
+ event = {
1876
+ "event": "evaluation",
1877
+ "step": current_step,
1878
+ "condition": args.condition,
1879
+ "macro_psnr": metrics["restored"]["macro_psnr"],
1880
+ "macro_ssim": metrics["restored"]["macro_ssim"],
1881
+ "metrics": metrics,
1882
+ "time": time.time(),
1883
+ }
1884
+ history.append(event)
1885
+ _append_jsonl(event, output_dir / "metrics.jsonl")
1886
+ _atomic_json_dump(history, output_dir / "history.json")
1887
+ print(json.dumps(event, sort_keys=True), flush=True)
1888
+ if event["macro_psnr"] > best_score:
1889
+ best_score = float(event["macro_psnr"])
1890
+ save_training_checkpoint(
1891
+ manager.path_for("best"), model, ema, optimizer, scheduler, scaler,
1892
+ step=current_step, contract=contract, history=history,
1893
+ early_stop=early_stopper.state_dict(),
1894
+ )
1895
+ if args.ddp:
1896
+ dist.barrier()
1897
+
1898
+ stop_requested = False
1899
+ if step == 0 and 0 in eval_steps:
1900
+ stop_requested = do_evaluation(0)
1901
+ model.train()
1902
+ phase1.eval()
1903
+ optimizer.zero_grad(set_to_none=True)
1904
+ loader_iterator = iter(train_loader)
1905
+ extra_clean_iter = None
1906
+ if getattr(args, "extra_clean_root", None):
1907
+ from src.data.folder_crops import FolderCropDataset, infinite_batches
1908
+
1909
+ extra_files = extra_clean_files(args.extra_clean_root)
1910
+ extra_clean_iter = infinite_batches(DataLoader(
1911
+ FolderCropDataset(
1912
+ extra_files, size=int(args.crop_size),
1913
+ seed=int(args.seed) * 31 + int(rank), return_full=True,
1914
+ ),
1915
+ batch_size=int(args.batch_size), shuffle=True, drop_last=True,
1916
+ num_workers=int(getattr(args, "extra_clean_workers", 2)), pin_memory=device.type == "cuda",
1917
+ ))
1918
+ if rank == 0:
1919
+ print("extra clean pool for identity pairs: %d files" % len(extra_files), flush=True)
1920
+ nonfinite_forward_total = 0
1921
+ while step < stop_step:
1922
+ accumulated_loss = 0.0
1923
+ nonfinite_forward_consecutive = 0
1924
+ for accumulation_index in range(args.grad_accum):
1925
+ batch = next(loader_iterator)
1926
+ degraded = batch["degraded"].to(device, non_blocking=True)
1927
+ clean = batch["clean"].to(device, non_blocking=True)
1928
+ use_full = (
1929
+ bool(getattr(args, "global_context", False))
1930
+ or bool(getattr(args, "exposure_pregain", False))
1931
+ ) and "full_degraded" in batch
1932
+ full_degraded = batch["full_degraded"].to(device, non_blocking=True) if use_full else None
1933
+ full_clean = batch["full_clean"].to(device, non_blocking=True) if use_full else None
1934
+ aug_generator = torch.Generator()
1935
+ aug_generator.manual_seed(
1936
+ (int(args.seed) * 7919 + int(step) * 104729 + int(accumulation_index) * 31 + int(rank)) % (2 ** 63 - 1)
1937
+ )
1938
+ degraded, full_degraded, _ = synthetic_noise_pairs(
1939
+ degraded, clean, float(getattr(args, "noise_pair_prob", 0.0)),
1940
+ aug_generator, full_degraded, full_clean,
1941
+ )
1942
+ identity = identity_pair_mask(
1943
+ clean.shape[0], float(getattr(args, "identity_pair_prob", 0.0)), device
1944
+ )
1945
+ if bool(identity.any()):
1946
+ extra_crop = extra_full = None
1947
+ if extra_clean_iter is not None:
1948
+ extra_batch = next(extra_clean_iter)
1949
+ extra_crop = extra_batch["crop"].to(device, non_blocking=True)
1950
+ extra_full = extra_batch["full"].to(device, non_blocking=True)
1951
+ clean, full_clean = exposure_diverse_identity(
1952
+ clean, full_clean, identity, aug_generator,
1953
+ jitter=float(getattr(args, "identity_exposure_jitter", 0.0)),
1954
+ extra_crop=extra_crop, extra_full=extra_full,
1955
+ extra_prob=float(getattr(args, "extra_clean_prob", 0.0)),
1956
+ )
1957
+ degraded = torch.where(identity.view(-1, 1, 1, 1), clean, degraded)
1958
+ if full_degraded is not None:
1959
+ full_degraded = torch.where(identity.view(-1, 1, 1, 1), full_clean, full_degraded)
1960
+ # Representation call is intentionally performed even for D0/null.
1961
+ with torch.cuda.amp.autocast(enabled=amp_enabled):
1962
+ representation = phase1(degraded)
1963
+ if full_degraded is not None:
1964
+ representation.full_frame = phase1(full_degraded)
1965
+ # Raw whole frame for image-statistics consumers (v10 pre-gain).
1966
+ representation.full_image = full_degraded
1967
+ u0_reference = pixel_unshuffle2(clean)
1968
+ global_microstep = step * args.grad_accum + accumulation_index
1969
+ sample_seed_values = batch["sample_seed"]
1970
+ if isinstance(sample_seed_values, Tensor):
1971
+ sample_seed_values = sample_seed_values.tolist()
1972
+ timesteps, noise = deterministic_training_plan(
1973
+ u0_reference,
1974
+ args.timesteps,
1975
+ args.seed,
1976
+ global_microstep,
1977
+ rank=rank,
1978
+ sample_seeds=sample_seed_values,
1979
+ )
1980
+ should_sync = accumulation_index == args.grad_accum - 1
1981
+ sync_context = (
1982
+ contextlib.nullcontext()
1983
+ if should_sync or not isinstance(model, DistributedDataParallel)
1984
+ else model.no_sync()
1985
+ )
1986
+ with sync_context:
1987
+ with torch.cuda.amp.autocast(enabled=amp_enabled):
1988
+ loss = model(
1989
+ clean, degraded, representation, timesteps, noise
1990
+ )
1991
+ action = loss_overflow_action(loss, amp_enabled=amp_enabled)
1992
+ if action == "fail":
1993
+ raise FloatingPointError("non-finite training loss")
1994
+ skipped = action == "skip"
1995
+ if not skipped:
1996
+ loss_value = float(loss.detach().float().item())
1997
+ scaled_loss = loss / float(args.grad_accum)
1998
+ if skipped:
1999
+ # fp16 range failure on this micro-batch: drop it (no
2000
+ # backward, no loss contribution) and keep the step.
2001
+ nonfinite_forward_consecutive += 1
2002
+ nonfinite_forward_total += 1
2003
+ if not nonfinite_loss_within_budget(
2004
+ consecutive=nonfinite_forward_consecutive,
2005
+ total=nonfinite_forward_total,
2006
+ ):
2007
+ raise FloatingPointError(
2008
+ "non-finite training loss on %d consecutive micro-batches "
2009
+ "(%d total) at logical step %d"
2010
+ % (nonfinite_forward_consecutive, nonfinite_forward_total, step)
2011
+ )
2012
+ # Free the retained graph: without the backward that would
2013
+ # normally consume it, these activations would still be
2014
+ # alive during the next forward and blow the memory budget.
2015
+ del loss
2016
+ continue
2017
+ nonfinite_forward_consecutive = 0
2018
+ scaler.scale(scaled_loss).backward()
2019
+ accumulated_loss += loss_value
2020
+ # Drop the frozen half BEFORE unscaling: an fp16 overflow inside the
2021
+ # frozen encoder would otherwise set the scaler's found_inf, be hidden
2022
+ # from the grad-norm check by the mask, and make the scaler refuse the
2023
+ # step (observed at step ~2350 of the first 15k run).
2024
+ if freeze_encoder_steps > 0 and step < freeze_encoder_steps:
2025
+ masked_encoder_grads = mask_encoder_gradients(model)
2026
+ else:
2027
+ masked_encoder_grads = 0
2028
+ if not has_any_gradient(model):
2029
+ # Every micro-batch of this step overflowed in fp16 and was
2030
+ # dropped. There is no update to apply: clear the state, advance
2031
+ # the cursor and move on rather than reducing an empty gradient.
2032
+ optimizer.zero_grad(set_to_none=True)
2033
+ step += 1
2034
+ if rank == 0:
2035
+ _append_jsonl(
2036
+ {"event": "skipped_step", "step": step,
2037
+ "reason": "all micro-batches non-finite", "time": time.time()},
2038
+ output_dir / "metrics.jsonl",
2039
+ )
2040
+ continue
2041
+ scaler.unscale_(optimizer)
2042
+ grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
2043
+ if not is_globally_finite_scalar(grad_norm):
2044
+ if not amp_enabled:
2045
+ raise FloatingPointError("non-finite gradient norm")
2046
+ recover_amp_gradient_overflow(
2047
+ manager.path_for("overflow_recovery"),
2048
+ model,
2049
+ ema,
2050
+ optimizer,
2051
+ scheduler,
2052
+ scaler,
2053
+ step=step,
2054
+ contract=contract,
2055
+ history=history,
2056
+ rank=rank,
2057
+ distributed=args.ddp,
2058
+ observed_grad_norm=float(grad_norm.detach().float().item()),
2059
+ early_stop=early_stopper.state_dict(),
2060
+ )
2061
+ grad_norm_value = float(grad_norm.detach().float().item())
2062
+ scaler_step_or_fail(scaler, optimizer)
2063
+ optimizer.zero_grad(set_to_none=True)
2064
+ scheduler.step()
2065
+ ema.update(model)
2066
+ step += 1
2067
+
2068
+ if rank == 0 and (step == 1 or step % 25 == 0):
2069
+ event = {
2070
+ "event": "train",
2071
+ "step": step,
2072
+ "loss": accumulated_loss / args.grad_accum,
2073
+ "lr": optimizer.param_groups[0]["lr"],
2074
+ "grad_norm": grad_norm_value,
2075
+ "condition": args.condition,
2076
+ "time": time.time(),
2077
+ }
2078
+ _append_jsonl(event, output_dir / "metrics.jsonl")
2079
+ print(json.dumps(event, sort_keys=True), flush=True)
2080
+ if step in eval_steps:
2081
+ stop_requested = do_evaluation(step)
2082
+ model.train()
2083
+ phase1.eval()
2084
+ if rank == 0 and step in milestone_steps:
2085
+ save_training_checkpoint(
2086
+ manager.path_for("milestone", step), model, ema, optimizer,
2087
+ scheduler, scaler, step=step, contract=contract, history=history,
2088
+ early_stop=early_stopper.state_dict(),
2089
+ )
2090
+ manager.prune_milestones()
2091
+ if rank == 0 and (step % 250 == 0 or step == stop_step):
2092
+ save_training_checkpoint(
2093
+ manager.path_for("last"), model, ema, optimizer, scheduler, scaler,
2094
+ step=step, contract=contract, history=history,
2095
+ early_stop=early_stopper.state_dict(),
2096
+ )
2097
+ if stop_requested:
2098
+ # Every rank leaves together: the flag was broadcast inside
2099
+ # do_evaluation, so no rank is left waiting at the next barrier.
2100
+ if rank == 0:
2101
+ save_training_checkpoint(
2102
+ manager.path_for("last"), model, ema, optimizer, scheduler, scaler,
2103
+ step=step, contract=contract, history=history,
2104
+ early_stop=early_stopper.state_dict(),
2105
+ )
2106
+ print("[early-stop] training ended at step %d" % step, flush=True)
2107
+ break
2108
+
2109
+ if args.ddp:
2110
+ dist.barrier()
2111
+ dist.destroy_process_group()
2112
+
2113
+
2114
+ def main(argv: Optional[Sequence[str]] = None) -> None:
2115
+ run(build_parser().parse_args(argv))
2116
+
2117
+
2118
+ if __name__ == "__main__":
2119
+ main()
dataset/phase1_noise_20260906/code/train_phase2_unified_v7.py ADDED
@@ -0,0 +1,1354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Phase 2 v7: unified two-step ResShift — one network, no external refiner.
3
+
4
+ The gen-2 pipeline (v6.1 one-step + refiner) is re-expressed as an honest
5
+ two-step diffusion over the SAME weights:
6
+
7
+ coarse t=2: u_2 = u_y-anchored marginal -> x0-MSE (content)
8
+ fine t=1: u_1 built from the model's OWN detached prediction via the
9
+ exact posterior -> image-space L1 + VGG (appearance)
10
+
11
+ Chain-aware fine-step construction removes the exposure bias that made the
12
+ old 8-step chain destructive; timestep conditioning (AdaGN) lets one network
13
+ host both behaviours. Warm start: full v6.1 weights minus the schedule
14
+ buffers (T changes 8 -> 2).
15
+
16
+ The VGG perceptual criterion is attached via ``object.__setattr__`` so it
17
+ never enters ``state_dict``/EMA/optimizer.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import contextlib
24
+ import hashlib
25
+ from pathlib import Path
26
+ from typing import Any, Dict, Iterator, Mapping, Optional, Sequence, Tuple
27
+
28
+ import torch
29
+ from torch import Tensor, nn
30
+ import torch.nn.functional as F
31
+
32
+ import train_phase2_graph_resshift_v4 as v4
33
+ import train_phase2_graph_moe_v6 as v6
34
+ from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule
35
+ from src.models.restoration.graph_moe_v6 import (
36
+ MoEGraphConditionerV6,
37
+ MoEGraphResidualShiftUNetV6,
38
+ )
39
+ from src.models.restoration.graph_resshift_v4 import (
40
+ ResidualShiftSchedule,
41
+ pixel_shuffle2,
42
+ pixel_unshuffle2,
43
+ )
44
+ from src.models.restoration.refiner_decoder import RefinerBlock
45
+ from src.models.restoration.uformer_moe_v7 import UformerMoEUNetV7
46
+
47
+ V7_VERSION = "unified_two_step_resshift_v1"
48
+ V7_WARMSTART_MAPPING_VERSION = "v6_full_state_minus_schedule_v1"
49
+
50
+ # Phase-1's readout dimension; the output FiLM conditions on the raw
51
+ # representation vector, which is fixed by the frozen encoder architecture.
52
+ GLOBAL_CONDITION_DIM = 256
53
+
54
+ # Image-head submodules absent from a warm-start source are left at their
55
+ # zero-initialized state instead of failing the strict key check.
56
+ _V7_FRESH_HEAD_PREFIXES = (
57
+ "full_res_tail.", "output_film.", "denoiser.pyramid_heads.",
58
+ "null_context", "null_global", "ctx_full_proj", "global_full_proj",
59
+ "photometric_head.", "exposure_pregain.", "colour_head.",
60
+ "denoiser.down_globals.", "denoiser.up_globals.",
61
+ )
62
+ # Phase-1 v5 PhotometricBranch state width (zeros when the encoder lacks it).
63
+ PHOTOMETRIC_STATE_DIM = 128
64
+ _DEFAULT_PYRAMID_WEIGHTS = (0.1, 0.2, 0.3)
65
+
66
+
67
+ def _replace_bundle(bundle: Any, **changes: Any) -> Any:
68
+ import copy
69
+ import dataclasses
70
+
71
+ if dataclasses.is_dataclass(bundle):
72
+ return dataclasses.replace(bundle, **changes)
73
+ clone = copy.copy(bundle)
74
+ for name, value in changes.items():
75
+ setattr(clone, name, value)
76
+ return clone
77
+
78
+
79
+ class FullResTail(nn.Module):
80
+ """Shallow NAFNet-lite residual head at FULL image resolution.
81
+
82
+ The diffusion trunk works entirely on the pixel-unshuffled half-res
83
+ state; this tail is the only place the network sees real pixels, so it
84
+ carries the fine-detail share (residual noise, sharpness) of the fine
85
+ objective. Input is (restored ‖ degraded); the output conv is
86
+ zero-initialized so the head is an exact identity at warm start.
87
+ """
88
+
89
+ def __init__(self, blocks: int = 3, width: int = 48) -> None:
90
+ super().__init__()
91
+ if blocks < 1:
92
+ raise ValueError("FullResTail requires at least one block")
93
+ self.entry = nn.Conv2d(6, width, 3, padding=1)
94
+ self.body = nn.Sequential(
95
+ *[RefinerBlock(width) for _ in range(int(blocks))]
96
+ )
97
+ self.out = nn.Conv2d(width, 3, 3, padding=1)
98
+ nn.init.zeros_(self.out.weight)
99
+ nn.init.zeros_(self.out.bias)
100
+
101
+ def forward(self, stacked: Tensor) -> Tensor:
102
+ return self.out(self.body(self.entry(stacked)))
103
+
104
+ # BT.601 chroma rows (U, V). The luminance row is deliberately absent: the
105
+ # chroma objective must stay orthogonal to the L1/VGG terms that already
106
+ # constrain brightness, so only hue/saturation errors are re-weighted. Both
107
+ # rows must sum to exactly zero so a pure gray offset projects to zero chroma
108
+ # (the textbook U row is off by 1e-5 from rounding; the R coefficient below
109
+ # absorbs it).
110
+ _UV_FROM_RGB = (
111
+ (-0.14714, -0.28886, 0.436),
112
+ (0.615, -0.51499, -0.10001),
113
+ )
114
+
115
+
116
+ def rgb_to_uv(image: Tensor) -> Tensor:
117
+ """Project an RGB batch [B,3,H,W] onto its BT.601 U/V chroma planes."""
118
+
119
+ if image.dim() != 4 or image.shape[1] != 3:
120
+ raise ValueError("rgb_to_uv expects a [B,3,H,W] batch")
121
+ weight = image.new_tensor(_UV_FROM_RGB)
122
+ return torch.einsum("bchw,oc->bohw", image, weight)
123
+
124
+
125
+ # BT.601 luma row; sums to exactly 1 so a uniform gray image maps to its own
126
+ # gray level.
127
+ _Y_FROM_RGB = (0.299, 0.587, 0.114)
128
+
129
+ # The luma objective compares tone at this pooled resolution: coarse enough
130
+ # to be orthogonal to the pixel L1 (which already constrains detail), fine
131
+ # enough to catch regionally varying exposure errors, not just the mean.
132
+ _LUMA_POOL_GRID = 8
133
+
134
+
135
+ def rgb_to_luma(image: Tensor) -> Tensor:
136
+ """Project an RGB batch [B,3,H,W] onto its BT.601 luma plane [B,1,H,W]."""
137
+
138
+ if image.dim() != 4 or image.shape[1] != 3:
139
+ raise ValueError("rgb_to_luma expects a [B,3,H,W] batch")
140
+ weight = image.new_tensor(_Y_FROM_RGB).view(1, 3, 1, 1)
141
+ return (image * weight).sum(dim=1, keepdim=True)
142
+
143
+
144
+ def pooled_luma(image: Tensor, grid: int = _LUMA_POOL_GRID) -> Tensor:
145
+ """Coarse tone map: BT.601 luma average-pooled onto a grid×grid layout."""
146
+
147
+ return F.adaptive_avg_pool2d(rgb_to_luma(image), (grid, grid))
148
+
149
+ _V4_SCHEDULE_CONFIG = v4._schedule_config
150
+ _V4_DATA_PLAN = v4._data_plan
151
+
152
+
153
+ class GlobalPhotometricHead(nn.Module):
154
+ """Per-image global exposure controllable (v8).
155
+
156
+ Measured on run A (probe_global_knob.py): a per-image global affine
157
+ ``a*x + b`` on the output is worth +7.2 dB oracle / ~+3 dB predictable on
158
+ lowlight, +6 / +2 on nearly-clean scene008, +1.4 / +1.2 on haze, and it
159
+ removes the systematic over-exposure of lowlight (oracle gain 0.82). The
160
+ colour (HV-plane) knob was worth only +0.5-0.9 dB, so the head predicts
161
+ intensity only. Inputs: Phase-1 global_condition + photometric_state of
162
+ the crop and, when available, of the whole frame. Zero-initialised
163
+ (exact identity), tanh-bounded (shrinkage: the pooled linear predictor
164
+ destroyed noise by -6.8 dB without it), ``dose`` scales the deltas at
165
+ inference and per-sample dropout keeps the identity path trained.
166
+ """
167
+
168
+ def __init__(self, hidden: int = 128, max_log_gain: float = 0.7, max_bias: float = 0.2) -> None:
169
+ super().__init__()
170
+ in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM)
171
+ self.net = nn.Sequential(
172
+ nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 2)
173
+ )
174
+ nn.init.zeros_(self.net[-1].weight)
175
+ nn.init.zeros_(self.net[-1].bias)
176
+ self.max_log_gain = float(max_log_gain)
177
+ self.max_bias = float(max_bias)
178
+
179
+ @staticmethod
180
+ def _vector(representation: Any) -> Tensor:
181
+ global_condition = representation.global_condition.float()
182
+ state = getattr(representation, "photometric_state", None)
183
+ if state is None:
184
+ state = global_condition.new_zeros(global_condition.shape[0], PHOTOMETRIC_STATE_DIM)
185
+ return torch.cat((global_condition, state.float()), dim=1)
186
+
187
+ def coefficients(self, representation: Any) -> Tuple[Tensor, Tensor]:
188
+ """(log_gain, bias), each [B], already bounded."""
189
+ crop = self._vector(representation)
190
+ full = getattr(representation, "full_frame", None)
191
+ full_vector = self._vector(full) if full is not None else torch.zeros_like(crop)
192
+ raw = self.net(torch.cat((crop, full_vector), dim=1))
193
+ return self.max_log_gain * torch.tanh(raw[:, 0]), self.max_bias * torch.tanh(raw[:, 1])
194
+
195
+ def forward(
196
+ self,
197
+ image: Tensor,
198
+ representation: Any,
199
+ dose: float = 1.0,
200
+ drop_mask: Optional[Tensor] = None,
201
+ ) -> Tensor:
202
+ with torch.cuda.amp.autocast(enabled=False):
203
+ log_gain, bias = self.coefficients(representation)
204
+ if drop_mask is not None:
205
+ keep = (~drop_mask.to(torch.bool)).to(log_gain.dtype)
206
+ log_gain, bias = log_gain * keep, bias * keep
207
+ gain = (float(dose) * log_gain).exp().view(-1, 1, 1, 1)
208
+ bias = (float(dose) * bias).view(-1, 1, 1, 1)
209
+ return image.float() * gain + bias
210
+
211
+
212
+ # Whole-image exposure descriptors fed to the pre-gain (per image).
213
+ PREGAIN_STATS_DIM = 8
214
+
215
+
216
+ def luma_statistics(image: Tensor) -> Tensor:
217
+ """[B, 8]: mean luma, log mean luma, luma p05/p50/p95, mean R/G/B."""
218
+
219
+ if image.dim() != 4 or image.shape[1] != 3:
220
+ raise ValueError("luma_statistics expects a [B,3,H,W] batch")
221
+ x = image.float().clamp(0.0, 1.0)
222
+ luma = rgb_to_luma(x).flatten(1)
223
+ mean = luma.mean(dim=1, keepdim=True)
224
+ probes = torch.tensor([0.05, 0.5, 0.95], device=luma.device, dtype=luma.dtype)
225
+ quantiles = torch.quantile(luma, probes, dim=1).transpose(0, 1)
226
+ channel_means = x.mean(dim=(2, 3))
227
+ return torch.cat((mean, (mean + 1e-3).log(), quantiles, channel_means), dim=1)
228
+
229
+
230
+ class ExposurePreGain(nn.Module):
231
+ """Retinex-style per-image INPUT gain (v10).
232
+
233
+ The v8 photometric head rescales the OUTPUT; the trunk still has to do
234
+ the x5-x10 brightening of a low-light input through a residual on u_y,
235
+ which is where the exposure overshoot and chroma loss come from. Every
236
+ published LOL method first estimates a global/illumination gain and
237
+ lets the restorer work in a normalised regime (Retinexformer's
238
+ illumination estimator). This module predicts one bounded log-gain per
239
+ image from the Phase-1 vectors of crop and whole frame (routing decides
240
+ "low-light" vs "dark but clean") plus raw luma statistics of both, and
241
+ multiplies the degraded image BEFORE pixel-unshuffle, so the residual
242
+ anchor u_y, the diffusion state and the full-res tail all see the gained
243
+ image. Zero-initialised (gain 1 -> bitwise identity), tanh-bounded,
244
+ ``dose`` scales the log-gain and per-sample dropout keeps gain-1 trained.
245
+ """
246
+
247
+ def __init__(self, hidden: int = 128, max_log_gain: float = 1.6) -> None:
248
+ super().__init__()
249
+ in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM) + 2 * PREGAIN_STATS_DIM
250
+ self.net = nn.Sequential(
251
+ nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 1)
252
+ )
253
+ nn.init.zeros_(self.net[-1].weight)
254
+ nn.init.zeros_(self.net[-1].bias)
255
+ self.max_log_gain = float(max_log_gain)
256
+
257
+ def log_gain(self, image: Tensor, representation: Any) -> Tensor:
258
+ crop_vector = GlobalPhotometricHead._vector(representation)
259
+ full = getattr(representation, "full_frame", None)
260
+ full_vector = (
261
+ GlobalPhotometricHead._vector(full) if full is not None else torch.zeros_like(crop_vector)
262
+ )
263
+ crop_stats = luma_statistics(image)
264
+ full_image = getattr(representation, "full_image", None)
265
+ full_stats = luma_statistics(full_image) if full_image is not None else crop_stats
266
+ raw = self.net(torch.cat((crop_vector, full_vector, crop_stats, full_stats), dim=1))
267
+ return self.max_log_gain * torch.tanh(raw[:, 0])
268
+
269
+ def forward(
270
+ self,
271
+ image: Tensor,
272
+ representation: Any,
273
+ dose: float = 1.0,
274
+ drop_mask: Optional[Tensor] = None,
275
+ ) -> Tuple[Tensor, Tensor]:
276
+ """(gained image in fp32, log-gain [B])."""
277
+
278
+ with torch.cuda.amp.autocast(enabled=False):
279
+ log_gain = self.log_gain(image, representation)
280
+ if drop_mask is not None:
281
+ keep = (~drop_mask.to(torch.bool)).to(log_gain.dtype)
282
+ log_gain = log_gain * keep
283
+ gain = (float(dose) * log_gain).exp().view(-1, 1, 1, 1)
284
+ return image.float() * gain, log_gain
285
+
286
+
287
+ def pregain_target(clean: Tensor, degraded: Tensor, max_log_gain: float, eps: float = 1e-3) -> Tensor:
288
+ """Supervised target for the pre-gain: the log ratio of mean luma
289
+ clean/degraded per image, clamped to the head's bound. Identity and
290
+ noise pairs -> 0, low-light pairs -> the exposure lift, hazy pairs -> a
291
+ mild negative value (the clean scene is darker than its airlight). Gives
292
+ the gain a direct learning signal; measured on v10 (end-to-end only) the
293
+ gain had barely moved off 1.0 after 4k steps."""
294
+
295
+ ratio = (rgb_to_luma(clean.float()).mean(dim=(1, 2, 3)) + eps) / (
296
+ rgb_to_luma(degraded.float()).mean(dim=(1, 2, 3)) + eps
297
+ )
298
+ # Lift only (gain >= 1): a hazy input's clean scene is darker than its
299
+ # airlight, so an unclamped target darkened every hazy input by ~x0.7 and
300
+ # the trunk had to re-learn dehazing on inputs it never saw (v11 stage A,
301
+ # haze val 32.0 -> 30.4 in 2k steps). Darkening is trivial for the trunk;
302
+ # the Retinex-style pre-gain only needs to normalise under-exposure.
303
+ return ratio.log().clamp(0.0, float(max_log_gain))
304
+
305
+
306
+ class GlobalColourHead(nn.Module):
307
+ """Per-image global colour transform on the OUTPUT (v12): y = M x + b with
308
+ M = diag(exp(d)) (I + O), d/O/b tanh-bounded, zero-initialised (identity).
309
+
310
+ Measured on v11a outputs (LOLv2-real, whole image, oracle fit per image):
311
+ raw 19.3 -> intensity affine 27.5 -> 3x3 matrix + bias 29.3 dB, i.e. most
312
+ of the remaining low-light error is a global per-image colour/tone map
313
+ (gain, white balance, cast), which the intensity-only photometric head
314
+ cannot express. Predicted from the same inputs as the photometric head
315
+ (Phase-1 crop + whole-frame vectors and luma statistics); trained with
316
+ a supervised target (least-squares fit of the transform from the
317
+ detached output to the clean image) so it learns immediately, like the
318
+ pre-gain.
319
+ """
320
+
321
+ def __init__(self, hidden: int = 128, max_log_diag: float = 1.0, max_offdiag: float = 0.5,
322
+ max_bias: float = 0.25) -> None:
323
+ super().__init__()
324
+ in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM) + 2 * PREGAIN_STATS_DIM
325
+ self.net = nn.Sequential(nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 12))
326
+ nn.init.zeros_(self.net[-1].weight)
327
+ nn.init.zeros_(self.net[-1].bias)
328
+ self.max_log_diag = float(max_log_diag)
329
+ self.max_offdiag = float(max_offdiag)
330
+ self.max_bias = float(max_bias)
331
+
332
+ def coefficients(self, image: Tensor, representation: Any) -> Tuple[Tensor, Tensor]:
333
+ """(M [B,3,3], b [B,3]) — bounded; identity at initialisation."""
334
+ crop_vector = GlobalPhotometricHead._vector(representation)
335
+ full = getattr(representation, "full_frame", None)
336
+ full_vector = GlobalPhotometricHead._vector(full) if full is not None else torch.zeros_like(crop_vector)
337
+ crop_stats = luma_statistics(image)
338
+ full_image = getattr(representation, "full_image", None)
339
+ full_stats = luma_statistics(full_image) if full_image is not None else crop_stats
340
+ raw = self.net(torch.cat((crop_vector, full_vector, crop_stats, full_stats), dim=1))
341
+ log_diag = self.max_log_diag * torch.tanh(raw[:, 0:3])
342
+ off = self.max_offdiag * torch.tanh(raw[:, 3:9]).view(-1, 3, 2)
343
+ bias = self.max_bias * torch.tanh(raw[:, 9:12])
344
+ eye = torch.eye(3, device=raw.device, dtype=raw.dtype).unsqueeze(0)
345
+ # off-diagonal slots: row i gets the two entries j != i
346
+ offdiag = raw.new_zeros(raw.shape[0], 3, 3)
347
+ idx = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)]
348
+ flat = off.reshape(-1, 6)
349
+ for k, (i, j) in enumerate(idx):
350
+ offdiag[:, i, j] = flat[:, k]
351
+ matrix = torch.diag_embed(log_diag.exp()) @ (eye + offdiag)
352
+ return matrix, bias
353
+
354
+ def forward(self, image: Tensor, representation: Any, dose: float = 1.0,
355
+ drop_mask: Optional[Tensor] = None) -> Tensor:
356
+ with torch.cuda.amp.autocast(enabled=False):
357
+ matrix, bias = self.coefficients(image, representation)
358
+ if drop_mask is not None:
359
+ keep = (~drop_mask.to(torch.bool)).to(matrix.dtype).view(-1, 1, 1)
360
+ eye = torch.eye(3, device=matrix.device, dtype=matrix.dtype).unsqueeze(0)
361
+ matrix = keep * matrix + (1 - keep) * eye
362
+ bias = bias * keep.view(-1, 1)
363
+ if float(dose) != 1.0:
364
+ eye = torch.eye(3, device=matrix.device, dtype=matrix.dtype).unsqueeze(0)
365
+ matrix = eye + float(dose) * (matrix - eye)
366
+ bias = float(dose) * bias
367
+ x = image.float()
368
+ out = torch.einsum("bij,bjhw->bihw", matrix, x) + bias.view(-1, 3, 1, 1)
369
+ return out
370
+
371
+
372
+ def colour_target(output: Tensor, clean: Tensor, samples: int = 4096, seed: int = 0) -> Tuple[Tensor, Tensor]:
373
+ """Per-image least-squares fit of clean ~ M output + b on a pixel sample:
374
+ the supervised target of ``GlobalColourHead`` (returns M [B,3,3], b [B,3])."""
375
+
376
+ batch, _, height, width = output.shape
377
+ n = height * width
378
+ gen = torch.Generator(device="cpu").manual_seed(int(seed))
379
+ index = torch.randperm(n, generator=gen)[: min(int(samples), n)].to(output.device)
380
+ x = output.detach().float().flatten(2)[:, :, index].transpose(1, 2) # [B,S,3]
381
+ y = clean.detach().float().flatten(2)[:, :, index].transpose(1, 2)
382
+ ones = torch.ones(batch, x.shape[1], 1, device=x.device, dtype=x.dtype)
383
+ xa = torch.cat((x, ones), dim=2) # [B,S,4]
384
+ # ridge-regularised normal equations (robust to flat/saturated images)
385
+ gram = xa.transpose(1, 2) @ xa + 1e-3 * torch.eye(4, device=x.device, dtype=x.dtype)
386
+ sol = torch.linalg.solve(gram, xa.transpose(1, 2) @ y) # [B,4,3]: y = xa @ sol
387
+ matrix = sol[:, :3, :].transpose(1, 2) # [B,3,3]: y_i = sum_j M_ij x_j
388
+ bias = sol[:, 3, :]
389
+ return matrix, bias
390
+
391
+
392
+ class Phase2UnifiedV7Module(v6.Phase2MoEV6Module):
393
+ """v6 graph-MoE module trained with the composite two-step objective."""
394
+
395
+ def __init__(
396
+ self,
397
+ *args,
398
+ fine_l1_weight: float = 1.0,
399
+ fine_vgg_weight: float = 0.1,
400
+ fine_chroma_weight: float = 0.0,
401
+ fine_luma_weight: float = 0.0,
402
+ tail_blocks: int = 0,
403
+ tail_width: int = 48,
404
+ use_output_film: bool = False,
405
+ cond_dropout_prob: float = 0.0,
406
+ pyramid_loss_weights: Sequence[float] = _DEFAULT_PYRAMID_WEIGHTS,
407
+ global_context: bool = False,
408
+ photometric_head: bool = False,
409
+ photometric_dropout: float = 0.0,
410
+ fine_chroma_space: str = "uv",
411
+ exposure_pregain: bool = False,
412
+ pregain_dropout: float = 0.0,
413
+ pregain_max_log_gain: float = 1.6,
414
+ pregain_target_weight: float = 0.0,
415
+ colour_head: bool = False,
416
+ colour_dropout: float = 0.0,
417
+ colour_target_weight: float = 0.0,
418
+ **kwargs,
419
+ ) -> None:
420
+ super().__init__(*args, **kwargs)
421
+ if fine_chroma_space not in ("uv", "hv"):
422
+ raise ValueError("fine_chroma_space must be 'uv' or 'hv'")
423
+ self.fine_chroma_space = str(fine_chroma_space)
424
+ self.photometric_head = GlobalPhotometricHead() if photometric_head else None
425
+ self.photometric_dropout = float(photometric_dropout)
426
+ self.exposure_pregain = (
427
+ ExposurePreGain(max_log_gain=float(pregain_max_log_gain)) if exposure_pregain else None
428
+ )
429
+ self.pregain_dropout = float(pregain_dropout)
430
+ self.pregain_target_weight = float(pregain_target_weight)
431
+ self.colour_head = GlobalColourHead() if colour_head else None
432
+ self.colour_dropout = float(colour_dropout)
433
+ self.colour_target_weight = float(colour_target_weight)
434
+ # Whole-frame context (Phase-1 on the full image) enters through the
435
+ # two live paths — added to the crop's context tokens and to the
436
+ # adaLN global vector — behind zero-init projections (identity at
437
+ # warm start).
438
+ if global_context:
439
+ cdim = int(self.conditioner.cond_dim)
440
+ self.ctx_full_proj = nn.Linear(cdim, cdim)
441
+ self.global_full_proj = nn.Linear(cdim, cdim)
442
+ for module in (self.ctx_full_proj, self.global_full_proj):
443
+ nn.init.zeros_(module.weight)
444
+ nn.init.zeros_(module.bias)
445
+ else:
446
+ self.ctx_full_proj = None
447
+ self.global_full_proj = None
448
+ self.cond_dropout_prob = float(cond_dropout_prob)
449
+ self.pyramid_loss_weights = tuple(float(w) for w in pyramid_loss_weights)
450
+ # Learned null condition (DGF): replaces the two live injection paths
451
+ # (cross-attention context, adaLN global vector). Zero-initialized so
452
+ # the untrained null branch coincides with the measured ablation.
453
+ if self.cond_dropout_prob > 0.0:
454
+ tokens = int(self.conditioner.num_nodes) + 2
455
+ cond_dim = int(self.conditioner.cond_dim)
456
+ self.null_context = nn.Parameter(torch.zeros(1, tokens, cond_dim))
457
+ self.null_global = nn.Parameter(torch.zeros(1, cond_dim))
458
+ else:
459
+ self.null_context = None
460
+ self.null_global = None
461
+ self.fine_l1_weight = float(fine_l1_weight)
462
+ self.fine_vgg_weight = float(fine_vgg_weight)
463
+ self.fine_chroma_weight = float(fine_chroma_weight)
464
+ self.fine_luma_weight = float(fine_luma_weight)
465
+ self.full_res_tail = (
466
+ FullResTail(blocks=int(tail_blocks), width=int(tail_width))
467
+ if int(tail_blocks) > 0
468
+ else None
469
+ )
470
+ if use_output_film:
471
+ self.output_film = nn.Linear(GLOBAL_CONDITION_DIM, 6)
472
+ nn.init.zeros_(self.output_film.weight)
473
+ nn.init.zeros_(self.output_film.bias)
474
+ else:
475
+ self.output_film = None
476
+ self.eval_sample_steps = int(self.schedule.timesteps)
477
+ # Deliberately hidden from nn.Module bookkeeping: the criterion is
478
+ # part of the objective, not of the model state.
479
+ object.__setattr__(self, "_perceptual", None)
480
+
481
+ def build_condition(self, representation: Any):
482
+ bundle = super().build_condition(representation)
483
+ full = getattr(representation, "full_frame", None)
484
+ if self.ctx_full_proj is None or full is None:
485
+ return bundle
486
+ full_bundle = self.conditioner(full, mode=self.condition_mode)
487
+ return _replace_bundle(
488
+ bundle,
489
+ context=bundle.context + self.ctx_full_proj(full_bundle.context.to(bundle.context.dtype)),
490
+ global_vector=bundle.global_vector
491
+ + self.global_full_proj(full_bundle.global_vector.to(bundle.global_vector.dtype)),
492
+ )
493
+
494
+ def null_condition(self, condition: Any, mask: Optional[Tensor] = None) -> Any:
495
+ """Swap the live injection paths for the learned null tokens.
496
+
497
+ ``mask`` [B] selects rows to null (per-sample conditioning dropout);
498
+ ``None`` nulls the whole batch (unconditional branch at inference).
499
+ """
500
+
501
+ if self.null_context is None:
502
+ raise RuntimeError("model was built without null-condition tokens")
503
+ context = condition.context
504
+ global_vector = condition.global_vector
505
+ null_context = self.null_context.to(context.dtype).expand_as(context)
506
+ null_global = self.null_global.to(global_vector.dtype).expand_as(global_vector)
507
+ if mask is None:
508
+ new_context, new_global = null_context, null_global
509
+ else:
510
+ row = mask.view(-1, 1, 1).to(torch.bool)
511
+ new_context = torch.where(row, null_context, context)
512
+ new_global = torch.where(row.view(-1, 1), null_global, global_vector)
513
+ return _replace_bundle(
514
+ condition, context=new_context, global_vector=new_global
515
+ )
516
+
517
+ def predict_x0_pyramid(
518
+ self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition: Any
519
+ ):
520
+ """x0 prediction plus the coarse-to-fine band estimates (if any)."""
521
+
522
+ if getattr(self.denoiser, "pyramid_heads", None) is None:
523
+ return self.predict_x0(u_t, u_y, timesteps, condition), []
524
+ return self.denoiser(u_t, u_y, timesteps, condition, return_pyramid=True)
525
+
526
+ def apply_pregain(
527
+ self,
528
+ degraded: Tensor,
529
+ representation: Any,
530
+ dose: float = 1.0,
531
+ drop_mask: Optional[Tensor] = None,
532
+ ) -> Tensor:
533
+ """Input-side exposure gain (v10); the input itself when disabled."""
534
+
535
+ if self.exposure_pregain is None:
536
+ return degraded
537
+ gained, _ = self.exposure_pregain(degraded, representation, dose=dose, drop_mask=drop_mask)
538
+ return gained.to(degraded.dtype)
539
+
540
+ def apply_image_head(
541
+ self,
542
+ image: Tensor,
543
+ degraded: Tensor,
544
+ representation: Any,
545
+ photometric_dose: float = 1.0,
546
+ photometric_drop: Optional[Tensor] = None,
547
+ colour_dose: float = 1.0,
548
+ colour_drop: Optional[Tensor] = None,
549
+ ) -> Tensor:
550
+ """Full-res tail + global FiLM + global exposure controllable (+ v12
551
+ global colour transform); exact identity at initialization."""
552
+
553
+ if self.full_res_tail is not None:
554
+ # fp32: the NAFNet SimpleGate products overflow fp16 once the
555
+ # pre-gain lifts a low-light input (x3.4 -> |activation| ~400 ->
556
+ # 400^2 > 65504; LOLv2 whole-image restoration went NaN on the
557
+ # MI325X run). The tail is 0.2M parameters; the cost is small.
558
+ with torch.cuda.amp.autocast(enabled=False):
559
+ image = image.float() + self.full_res_tail(
560
+ torch.cat((image.float(), degraded.float()), dim=1)
561
+ )
562
+ if self.output_film is not None:
563
+ with torch.cuda.amp.autocast(enabled=False):
564
+ parameters = self.output_film(
565
+ representation.global_condition.float()
566
+ )
567
+ scale, shift = parameters.view(-1, 2, 3, 1, 1).unbind(dim=1)
568
+ image = image * (1.0 + scale) + shift
569
+ if self.photometric_head is not None:
570
+ image = self.photometric_head(
571
+ image, representation, dose=photometric_dose, drop_mask=photometric_drop
572
+ ).to(image.dtype)
573
+ if self.colour_head is not None:
574
+ image = self.colour_head(
575
+ image, representation, dose=colour_dose, drop_mask=colour_drop
576
+ ).to(image.dtype)
577
+ return image
578
+
579
+ def chroma_planes(self, image: Tensor) -> Tensor:
580
+ """Chroma planes for the fine chroma loss: BT.601 UV, or the HVI HV
581
+ plane whose intensity collapse down-weights chroma in dark pixels."""
582
+ if self.fine_chroma_space == "hv":
583
+ from src.models.graph_encoder.hvi import rgb_to_hvi
584
+
585
+ return rgb_to_hvi(image.float().clamp(0.0, 1.0), 0.2)[:, :2]
586
+ return rgb_to_uv(image)
587
+
588
+ def _perceptual_loss(self, prediction: Tensor, target: Tensor) -> Tensor:
589
+ if self.fine_vgg_weight == 0.0:
590
+ return prediction.new_zeros(())
591
+ if self._perceptual is None:
592
+ from src.models.restoration.refiner_decoder import VGGPerceptualLoss
593
+
594
+ module = VGGPerceptualLoss().to(prediction.device)
595
+ object.__setattr__(self, "_perceptual", module)
596
+ with torch.cuda.amp.autocast(enabled=False):
597
+ return self._perceptual(
598
+ prediction.float().clamp(0.0, 1.0), target.float()
599
+ )
600
+
601
+ def training_loss(
602
+ self,
603
+ clean: Tensor,
604
+ degraded: Tensor,
605
+ representation: Any,
606
+ timesteps: Tensor,
607
+ noise: Optional[Tensor] = None,
608
+ ) -> v6.MoETrainStepResult:
609
+ """Composite objective; the runtime-sampled ``timesteps`` is ignored
610
+ because every microstep trains both chain positions."""
611
+
612
+ del timesteps
613
+ pregain_drop = None
614
+ pregain_loss = clean.new_zeros(())
615
+ if self.exposure_pregain is not None and self.training and self.pregain_dropout > 0.0:
616
+ pregain_drop = torch.rand(clean.shape[0], device=clean.device) < self.pregain_dropout
617
+ if self.exposure_pregain is not None and self.pregain_target_weight > 0.0:
618
+ # Direct supervision of the (unmasked) log-gain; the target is
619
+ # computed from the ORIGINAL degraded image before gaining.
620
+ with torch.cuda.amp.autocast(enabled=False):
621
+ raw_log_gain = self.exposure_pregain.log_gain(degraded, representation)
622
+ target = pregain_target(clean, degraded, self.exposure_pregain.max_log_gain)
623
+ pregain_loss = self.pregain_target_weight * (raw_log_gain - target).square().mean()
624
+ degraded = self.apply_pregain(degraded, representation, drop_mask=pregain_drop)
625
+ u0 = pixel_unshuffle2(clean)
626
+ uy = pixel_unshuffle2(degraded)
627
+ if noise is None:
628
+ noise = torch.randn_like(u0)
629
+ condition = self.build_condition(representation)
630
+ if self.training and self.cond_dropout_prob > 0.0:
631
+ drop = torch.rand(u0.shape[0], device=u0.device) < self.cond_dropout_prob
632
+ # Always route through the null tokens (a row-wise where), even
633
+ # when no row is dropped: the result is bitwise the conditioned
634
+ # bundle, but the null parameters stay in the autograd graph on
635
+ # every micro-batch, which DDP + no_sync accumulation requires.
636
+ condition = self.null_condition(condition, drop)
637
+ kappa = self.effective_kappa(condition)
638
+ terminal = self.schedule.timesteps
639
+ t_coarse = torch.full(
640
+ (u0.shape[0],), terminal, device=u0.device, dtype=torch.long
641
+ )
642
+ u_t = self.schedule.q_sample(u0, uy, t_coarse, noise=noise, kappa=kappa)
643
+ coarse_prediction, pyramid = self.predict_x0_pyramid(
644
+ u_t, uy, t_coarse, condition
645
+ )
646
+ coarse_loss = (coarse_prediction.float() - u0.float()).square().mean()
647
+ # Deep supervision of the coarse-to-fine bands: each decoder scale is
648
+ # asked for the area-downsampled clean state (MSE only; perceptual
649
+ # terms stay at full resolution).
650
+ pyramid_loss = coarse_prediction.new_zeros(())
651
+ for weight, estimate in zip(self.pyramid_loss_weights, pyramid):
652
+ target = F.interpolate(
653
+ u0.float(), size=estimate.shape[-2:], mode="area"
654
+ )
655
+ pyramid_loss = pyramid_loss + weight * (
656
+ estimate.float() - target
657
+ ).square().mean()
658
+
659
+ # Fine step is built from the model's OWN detached estimate — the
660
+ # network learns to polish its actual chain state, not a
661
+ # teacher-forced one. The mirrored noise keeps the plan replayable.
662
+ mean, variance = self.schedule.posterior_mean_variance(
663
+ u_t, coarse_prediction.detach(), t_coarse, kappa=kappa
664
+ )
665
+ fine_noise = torch.flip(noise, dims=(-1,))
666
+ u_fine = mean + torch.sqrt(variance) * fine_noise
667
+ t_fine = torch.full(
668
+ (u0.shape[0],), 1, device=u0.device, dtype=torch.long
669
+ )
670
+ fine_prediction = self.predict_x0(u_fine, uy, t_fine, condition)
671
+ fine_image = pixel_shuffle2(fine_prediction.float())
672
+ photometric_drop = None
673
+ if self.photometric_head is not None and self.training and self.photometric_dropout > 0.0:
674
+ photometric_drop = torch.rand(u0.shape[0], device=u0.device) < self.photometric_dropout
675
+ colour_drop = None
676
+ if self.colour_head is not None and self.training and self.colour_dropout > 0.0:
677
+ colour_drop = torch.rand(u0.shape[0], device=u0.device) < self.colour_dropout
678
+ colour_loss = fine_image.new_zeros(())
679
+ if self.colour_head is not None and self.colour_target_weight > 0.0:
680
+ # Supervised target: the least-squares global map from the image
681
+ # BEFORE the colour head (tail + photometric head applied) to the
682
+ # clean image; the head must learn to predict it.
683
+ with torch.cuda.amp.autocast(enabled=False), torch.no_grad():
684
+ # target and the head's image statistics need no gradient;
685
+ # keeping this pass out of autograd avoids a second full-res
686
+ # tail activation set (OOM at batch 32 on MI325X otherwise)
687
+ before = self.apply_image_head(
688
+ fine_image.detach(), degraded.float(), representation,
689
+ photometric_drop=photometric_drop, colour_dose=0.0,
690
+ )
691
+ target_m, target_b = colour_target(before, clean.float())
692
+ target_m = target_m.clamp(-3.0, 3.0)
693
+ target_b = target_b.clamp(-self.colour_head.max_bias, self.colour_head.max_bias)
694
+ pred_m, pred_b = self.colour_head.coefficients(before, representation)
695
+ colour_loss = self.colour_target_weight * (
696
+ (pred_m - target_m).square().sum(dim=(1, 2)).mean()
697
+ + (pred_b - target_b).square().sum(dim=1).mean()
698
+ )
699
+ fine_image = self.apply_image_head(
700
+ fine_image, degraded.float(), representation,
701
+ photometric_drop=photometric_drop, colour_drop=colour_drop,
702
+ )
703
+ fine_l1 = F.l1_loss(fine_image, clean.float())
704
+ fine_vgg = self._perceptual_loss(fine_image, clean)
705
+ if self.fine_chroma_weight != 0.0:
706
+ fine_chroma = F.l1_loss(
707
+ self.chroma_planes(fine_image), self.chroma_planes(clean.float())
708
+ )
709
+ else:
710
+ fine_chroma = fine_image.new_zeros(())
711
+ if self.fine_luma_weight != 0.0:
712
+ fine_luma = F.l1_loss(
713
+ pooled_luma(fine_image), pooled_luma(clean.float())
714
+ )
715
+ else:
716
+ fine_luma = fine_image.new_zeros(())
717
+ fine_loss = (
718
+ self.fine_l1_weight * fine_l1
719
+ + self.fine_vgg_weight * fine_vgg
720
+ + self.fine_chroma_weight * fine_chroma
721
+ + self.fine_luma_weight * fine_luma
722
+ )
723
+
724
+ gate_loss = (
725
+ self.gate_anchor_weight * condition.gate.anchor_loss.float()
726
+ + self.gate_correction_weight
727
+ * condition.gate.correction_loss.float()
728
+ )
729
+ if self.expert_kappa is not None and self.training:
730
+ self.expert_kappa.advance()
731
+ return v6.MoETrainStepResult(
732
+ loss=coarse_loss + pyramid_loss + fine_loss + gate_loss + pregain_loss + colour_loss,
733
+ reconstruction_loss=coarse_loss,
734
+ gate_loss=fine_loss,
735
+ u0_prediction=fine_prediction,
736
+ u0_target=u0,
737
+ u_t=u_t,
738
+ kappa=kappa.detach(),
739
+ )
740
+
741
+
742
+ def _file_sha256(path: Path) -> str:
743
+ digest = hashlib.sha256()
744
+ with Path(path).open("rb") as handle:
745
+ for block in iter(lambda: handle.read(1024 * 1024), b""):
746
+ digest.update(block)
747
+ return digest.hexdigest()
748
+
749
+
750
+ _BLOCK_KEY = __import__("re").compile(r"^denoiser\.(down_blocks|up_blocks)\.(\d+)\.(\d+)\.")
751
+
752
+
753
+ def _is_appended_block_key(name: str, donor: Mapping[str, Any]) -> bool:
754
+ """v11: a LeWin block whose index is beyond every block the donor has in
755
+ the same stage (appended, zero-init, identity) may be missing from the
756
+ donor; an index the donor DOES have must be present."""
757
+
758
+ match = _BLOCK_KEY.match(name)
759
+ if match is None:
760
+ return False
761
+ path, stage, index = match.group(1), match.group(2), int(match.group(3))
762
+ prefix = "denoiser.%s.%s." % (path, stage)
763
+ donor_indices = {
764
+ int(key[len(prefix):].split(".")[0])
765
+ for key in donor
766
+ if key.startswith(prefix) and key[len(prefix):].split(".")[0].isdigit()
767
+ }
768
+ return bool(donor_indices) and index > max(donor_indices)
769
+
770
+
771
+ def load_v6_warmstart(
772
+ path: Path,
773
+ expected_sha256: str,
774
+ model: Phase2UnifiedV7Module,
775
+ *,
776
+ weight_source: str = "ema",
777
+ ) -> Dict[str, Any]:
778
+ """Load the full v6.1 state except the (reshaped) schedule buffers."""
779
+
780
+ actual = _file_sha256(path)
781
+ if actual.lower() != str(expected_sha256).lower():
782
+ raise ValueError("v6 warmstart sha256 mismatch")
783
+ checkpoint = v4._torch_load(Path(path), map_location="cpu")
784
+ if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2:
785
+ raise ValueError("warmstart must be a Phase-2 checkpoint")
786
+ if weight_source == "model":
787
+ state = checkpoint.get("model_state_dict")
788
+ elif weight_source == "ema":
789
+ ema_state = checkpoint.get("ema_state_dict")
790
+ state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None
791
+ else:
792
+ raise ValueError("weight_source must be 'model' or 'ema'")
793
+ if not isinstance(state, Mapping):
794
+ raise ValueError("v6 warmstart is missing the selected state")
795
+
796
+ filtered = {
797
+ name: value
798
+ for name, value in state.items()
799
+ if not name.startswith("schedule.")
800
+ }
801
+ target = model.state_dict()
802
+ # Image-head submodules added AFTER the source run keep their fresh
803
+ # zero-initialized state (they are exact identities), so their absence
804
+ # from the source is tolerated — nothing else is.
805
+ import re as _re
806
+
807
+ fresh_head_keys = sorted(
808
+ name
809
+ for name in target
810
+ if name not in filtered
811
+ and (
812
+ name.startswith(_V7_FRESH_HEAD_PREFIXES)
813
+ or _re.match(r"^full_res_tail\.body\.\d+\.", name) is not None
814
+ or _is_appended_block_key(name, filtered)
815
+ )
816
+ )
817
+ expected = {
818
+ n
819
+ for n in target
820
+ if not n.startswith("schedule.") and n not in set(fresh_head_keys)
821
+ }
822
+ # Optional image-head modules the TARGET was built without (an ablation
823
+ # that drops the photometric head / pre-gain / colour head) may be present
824
+ # in the donor: their weights are dropped, everything else must match.
825
+ dropped_head_keys = sorted(
826
+ name for name in filtered
827
+ if name not in expected and name.startswith(_V7_FRESH_HEAD_PREFIXES)
828
+ )
829
+ if dropped_head_keys:
830
+ filtered = {k: v for k, v in filtered.items() if k not in set(dropped_head_keys)}
831
+ print("[warmstart] dropping %d donor keys of heads absent from the target: %s"
832
+ % (len(dropped_head_keys), ", ".join(sorted({k.split(".")[0] for k in dropped_head_keys}))),
833
+ flush=True)
834
+ if set(filtered.keys()) != expected:
835
+ missing = sorted(expected - set(filtered))
836
+ unexpected = sorted(set(filtered) - expected)
837
+ raise ValueError(
838
+ "v6 warmstart key mismatch; missing=%r unexpected=%r"
839
+ % (missing[:6], unexpected[:6])
840
+ )
841
+ result = model.load_state_dict(filtered, strict=False)
842
+ allowed_missing = set(fresh_head_keys)
843
+ if result.unexpected_keys or any(
844
+ not name.startswith("schedule.") and name not in allowed_missing
845
+ for name in result.missing_keys
846
+ ):
847
+ raise RuntimeError("v7 warmstart loader violated its allowlist")
848
+ return {
849
+ "mapping_version": V7_WARMSTART_MAPPING_VERSION,
850
+ "source_checkpoint_sha256": actual,
851
+ "source_step": int(checkpoint.get("step", -1)),
852
+ "weight_source": weight_source,
853
+ "schedule_reinitialized": True,
854
+ "fresh_head_keys": len(fresh_head_keys),
855
+ "dropped_head_keys": len(dropped_head_keys),
856
+ "materialized_state_hash": v4.model_state_hash(model),
857
+ }
858
+
859
+
860
+ def sample_unified_restoration(
861
+ model: nn.Module,
862
+ phase1: "v4.FrozenPhase1",
863
+ degraded: Tensor,
864
+ *,
865
+ seed: int,
866
+ record_ids: Optional[Sequence[str]] = None,
867
+ initial_noise: Optional[Tensor] = None,
868
+ amp_enabled: Optional[bool] = None,
869
+ dose: Optional[float] = None,
870
+ full_degraded: Optional[Tensor] = None,
871
+ photometric_dose: Optional[float] = None,
872
+ pregain_dose: Optional[float] = None,
873
+ colour_dose: Optional[float] = None,
874
+ ) -> Tensor:
875
+ """v6 exact-posterior sampling plus the v7 image head.
876
+
877
+ ``dose`` (DGF) interpolates the coarse-step x0 prediction between the
878
+ learned null branch and the conditioned branch:
879
+ x0 = x0(null) + dose * (x0(c) - x0(null)); the fine step always runs
880
+ fully conditioned. ``None`` (or 1.0) is the plain conditioned sampler.
881
+
882
+ Mirrors ``v6.sample_moe_restoration`` step for step; the only addition is
883
+ ``apply_image_head`` on the shuffled image BEFORE crop/clamp, matching
884
+ the training-time order. Bitwise-identical to the v6 sampler when the
885
+ head is disabled (it is an exact identity then).
886
+ """
887
+
888
+ restorer = v4.unwrap_module(model)
889
+ if not isinstance(restorer, Phase2UnifiedV7Module):
890
+ raise TypeError("model must wrap Phase2UnifiedV7Module")
891
+ steps = int(getattr(restorer, "eval_sample_steps", 1))
892
+ use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled)
893
+ with torch.cuda.amp.autocast(enabled=use_amp):
894
+ padded, size = v4.pad_to_multiple(degraded, multiple=16)
895
+ representation = phase1(padded)
896
+ if full_degraded is not None and getattr(restorer, "ctx_full_proj", None) is not None:
897
+ representation.full_frame = phase1(full_degraded.to(degraded.device))
898
+ if full_degraded is not None:
899
+ representation.full_image = full_degraded.to(degraded.device)
900
+ # v10 input-side exposure gain (identity when the module is absent).
901
+ padded = restorer.apply_pregain(
902
+ padded, representation,
903
+ dose=1.0 if pregain_dose is None else float(pregain_dose),
904
+ )
905
+ condition = restorer.build_condition(representation)
906
+ if float(getattr(restorer, "cond_dropout_prob", 0.0)) >= 1.0:
907
+ # A model trained with p = 1 never saw a real condition: sample
908
+ # it fully unconditionally (both steps); ``dose`` is meaningless.
909
+ condition = restorer.null_condition(condition)
910
+ dose = None
911
+ uy = pixel_unshuffle2(padded)
912
+ if initial_noise is None:
913
+ initial_noise = v4._noise_for_records(
914
+ uy, list(record_ids) if record_ids else None,
915
+ seed=seed, stage="initial",
916
+ )
917
+ kappa_vector = restorer.effective_kappa(condition)
918
+ kappa = restorer.schedule.kappa_factor(kappa_vector, uy)
919
+ eta_terminal = restorer.schedule.eta[-1].to(uy.device, uy.dtype)
920
+ u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise
921
+ batch = uy.shape[0]
922
+ if steps <= 1:
923
+ timesteps = torch.full(
924
+ (batch,), restorer.schedule.timesteps,
925
+ device=uy.device, dtype=torch.long,
926
+ )
927
+ u_t = restorer.predict_x0(u_t, uy, timesteps, condition)
928
+ else:
929
+ null_bundle = None
930
+ if dose is not None and float(dose) != 1.0:
931
+ null_bundle = restorer.null_condition(condition)
932
+ for step in restorer.schedule.reverse_timesteps():
933
+ timesteps = torch.full(
934
+ (batch,), step, device=uy.device, dtype=torch.long
935
+ )
936
+ u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition)
937
+ if null_bundle is not None and step == restorer.schedule.timesteps:
938
+ u0_null = restorer.predict_x0(u_t, uy, timesteps, null_bundle)
939
+ u0_hat = u0_null + float(dose) * (u0_hat - u0_null)
940
+ mean, variance = restorer.schedule.posterior_mean_variance(
941
+ u_t, u0_hat, timesteps, kappa=kappa_vector
942
+ )
943
+ if step > 1:
944
+ noise = v4._noise_for_records(
945
+ u_t, list(record_ids) if record_ids else None,
946
+ seed=seed, stage=step,
947
+ )
948
+ u_t = mean + torch.sqrt(variance) * noise
949
+ else:
950
+ u_t = mean
951
+ restored = pixel_shuffle2(u_t)
952
+ restored = restorer.apply_image_head(
953
+ restored, padded.to(restored.dtype), representation,
954
+ photometric_dose=1.0 if photometric_dose is None else float(photometric_dose),
955
+ colour_dose=1.0 if colour_dose is None else float(colour_dose),
956
+ )
957
+ height, width = size
958
+ return restored[..., :height, :width].clamp(0.0, 1.0)
959
+
960
+
961
+ sample_unified_restoration.accepts_full_frame = True
962
+
963
+
964
+ BASE_BLOCKS_PER_STAGE = 2
965
+
966
+
967
+ def _parse_extra_blocks(value: Any) -> Sequence[int]:
968
+ """Extra LeWin blocks appended per stage (v11), "" -> (0, 0, 0, 0)."""
969
+
970
+ if value is None or (isinstance(value, str) and not value.strip()):
971
+ return (0, 0, 0, 0)
972
+ parts = (
973
+ tuple(int(v) for v in value.split(",") if v.strip())
974
+ if isinstance(value, str) else tuple(int(v) for v in value)
975
+ )
976
+ if len(parts) != 4 or any(v < 0 for v in parts):
977
+ raise ValueError("extra blocks per stage must be four non-negative ints")
978
+ return parts
979
+
980
+
981
+ def blocks_per_stage(args: argparse.Namespace) -> Sequence[int]:
982
+ extra = _parse_extra_blocks(getattr(args, "extra_blocks_per_stage", ""))
983
+ return tuple(BASE_BLOCKS_PER_STAGE + int(e) for e in extra)
984
+
985
+
986
+ def _parse_scales(value: Any) -> Sequence[int]:
987
+ """Stage indices for the v10 global-attention blocks ("" -> none)."""
988
+
989
+ if value is None:
990
+ return ()
991
+ if isinstance(value, str):
992
+ return tuple(int(v) for v in value.split(",") if v.strip())
993
+ return tuple(int(v) for v in value)
994
+
995
+
996
+ def _parse_weights(value: Any) -> Sequence[float]:
997
+ if value is None:
998
+ return _DEFAULT_PYRAMID_WEIGHTS
999
+ if isinstance(value, str):
1000
+ return tuple(float(v) for v in value.split(",") if v.strip())
1001
+ return tuple(float(v) for v in value)
1002
+
1003
+
1004
+ def _build_v7_restorer(
1005
+ args: argparse.Namespace, device: torch.device
1006
+ ) -> Phase2UnifiedV7Module:
1007
+ schedule = ResidualShiftSchedule(
1008
+ timesteps=args.timesteps, eta_end=args.eta_end,
1009
+ min_noise=args.min_noise, power=args.power, kappa=args.kappa,
1010
+ )
1011
+ model = Phase2UnifiedV7Module(
1012
+ conditioner=MoEGraphConditionerV6(
1013
+ cond_dim=args.cond_dim, stage_dims=args.dims,
1014
+ gate_hidden_dim=args.gate_hidden_dim,
1015
+ gate_max_correction=args.gate_max_correction,
1016
+ ),
1017
+ denoiser=(
1018
+ UformerMoEUNetV7(
1019
+ dims=args.dims, cond_dim=args.cond_dim,
1020
+ expert_rank=args.expert_rank,
1021
+ pyramid_heads=bool(getattr(args, "pyramid_heads", False)),
1022
+ global_attention_scales=_parse_scales(
1023
+ getattr(args, "global_attention_scales", "")
1024
+ ),
1025
+ blocks_per_stage=blocks_per_stage(args),
1026
+ grad_checkpoint=bool(getattr(args, "grad_checkpoint", False)),
1027
+ )
1028
+ if args.backbone == "uformer"
1029
+ else MoEGraphResidualShiftUNetV6(
1030
+ dims=args.dims, cond_dim=args.cond_dim,
1031
+ expert_rank=args.expert_rank,
1032
+ )
1033
+ ),
1034
+ schedule=schedule,
1035
+ expert_kappa=ExpertKappaSchedule(
1036
+ kappa_per_expert=v6._parse_kappa_values(args.expert_kappa_values),
1037
+ kappa_global=float(args.kappa),
1038
+ anneal_microsteps=0,
1039
+ ),
1040
+ condition_mode=args.condition,
1041
+ gate_anchor_weight=args.gate_anchor_weight,
1042
+ gate_correction_weight=args.gate_correction_weight,
1043
+ fine_l1_weight=args.fine_l1_weight,
1044
+ fine_vgg_weight=args.fine_vgg_weight,
1045
+ fine_chroma_weight=float(getattr(args, "fine_chroma_weight", 0.0)),
1046
+ fine_luma_weight=float(getattr(args, "fine_luma_weight", 0.0)),
1047
+ tail_blocks=int(getattr(args, "full_res_tail_blocks", 0)),
1048
+ tail_width=int(getattr(args, "full_res_tail_width", 48)),
1049
+ use_output_film=bool(getattr(args, "output_film", False)),
1050
+ global_context=bool(getattr(args, "global_context", False)),
1051
+ cond_dropout_prob=float(getattr(args, "cond_dropout_prob", 0.0)),
1052
+ pyramid_loss_weights=_parse_weights(
1053
+ getattr(args, "pyramid_loss_weights", None)
1054
+ ),
1055
+ photometric_head=bool(getattr(args, "photometric_head", False)),
1056
+ photometric_dropout=float(getattr(args, "photometric_dropout", 0.0)),
1057
+ fine_chroma_space=str(getattr(args, "fine_chroma_space", "uv")),
1058
+ exposure_pregain=bool(getattr(args, "exposure_pregain", False)),
1059
+ pregain_dropout=float(getattr(args, "pregain_dropout", 0.0)),
1060
+ pregain_max_log_gain=float(getattr(args, "pregain_max_log_gain", 1.6)),
1061
+ pregain_target_weight=float(getattr(args, "pregain_target_weight", 0.0)),
1062
+ colour_head=bool(getattr(args, "colour_head", False)),
1063
+ colour_dropout=float(getattr(args, "colour_dropout", 0.0)),
1064
+ colour_target_weight=float(getattr(args, "colour_target_weight", 0.0)),
1065
+ )
1066
+ if args.resume is None and args.init_checkpoint is None:
1067
+ if args.warmstart_v6 is not None:
1068
+ audit = load_v6_warmstart(
1069
+ args.warmstart_v6, args.warmstart_v6_sha256, model,
1070
+ weight_source=args.warmstart_weight_source,
1071
+ )
1072
+ elif bool(getattr(args, "allow_scratch", False)):
1073
+ audit = {"mapping_version": "from_scratch"}
1074
+ else:
1075
+ raise ValueError(
1076
+ "v7 requires --warmstart-v6, resume/init, or --allow-scratch"
1077
+ )
1078
+ else:
1079
+ source = args.resume if args.resume is not None else args.init_checkpoint
1080
+ stored = v4._torch_load(Path(source), map_location="cpu")
1081
+ architecture = stored.get("architecture") if isinstance(stored, Mapping) else None
1082
+ audit = (
1083
+ dict(architecture.get("warmstart", {}))
1084
+ if isinstance(architecture, Mapping)
1085
+ else {"mapping_version": "resumed_state"}
1086
+ )
1087
+ del stored
1088
+ setattr(args, "_v7_warmstart_audit", audit)
1089
+ if bool(getattr(args, "freeze_shared_trunk", False)):
1090
+ for name, parameter in model.named_parameters():
1091
+ parameter.requires_grad_(v6._is_v6_only_key(name))
1092
+ return model.to(device)
1093
+
1094
+
1095
+ def _v7_architecture(args: argparse.Namespace) -> Dict[str, Any]:
1096
+ audit = getattr(args, "_v7_warmstart_audit", {})
1097
+ return {
1098
+ "name": "unified_two_step_resshift_v7",
1099
+ "version": 7,
1100
+ "mechanism": V7_VERSION,
1101
+ "backbone": str(getattr(args, "backbone", "conv")),
1102
+ "moe": {
1103
+ "expert_rank": int(args.expert_rank),
1104
+ "gate_hidden_dim": int(args.gate_hidden_dim),
1105
+ "gate_max_correction": float(args.gate_max_correction),
1106
+ },
1107
+ "objective": {
1108
+ "coarse": "x0_mse_fp32",
1109
+ "fine": "chain_aware_l1_vgg",
1110
+ "fine_l1_weight": float(args.fine_l1_weight),
1111
+ "fine_vgg_weight": float(args.fine_vgg_weight),
1112
+ "fine_chroma_weight": float(
1113
+ getattr(args, "fine_chroma_weight", 0.0)
1114
+ ),
1115
+ "fine_chroma_space": (
1116
+ "hvi_hv_k0.2" if str(getattr(args, "fine_chroma_space", "uv")) == "hv"
1117
+ else "yuv_bt601_uv"
1118
+ ),
1119
+ "fine_luma_weight": float(getattr(args, "fine_luma_weight", 0.0)),
1120
+ "fine_luma_space": "yuv_bt601_y_pool%d" % _LUMA_POOL_GRID,
1121
+ "fine_noise": "mirrored_coarse_noise",
1122
+ },
1123
+ "coarse_to_fine": {
1124
+ "pyramid_heads": bool(getattr(args, "pyramid_heads", False)),
1125
+ "pyramid_loss_weights": list(
1126
+ _parse_weights(getattr(args, "pyramid_loss_weights", None))
1127
+ ),
1128
+ },
1129
+ "dose": {
1130
+ "cond_dropout_prob": float(getattr(args, "cond_dropout_prob", 0.0)),
1131
+ "null_paths": ["context", "global_vector"],
1132
+ "identity_pair_prob": float(getattr(args, "identity_pair_prob", 0.0)),
1133
+ },
1134
+ "global_context": bool(getattr(args, "global_context", False)),
1135
+ "exposure_pregain": {
1136
+ "enabled": bool(getattr(args, "exposure_pregain", False)),
1137
+ "dropout": float(getattr(args, "pregain_dropout", 0.0)),
1138
+ "max_log_gain": float(getattr(args, "pregain_max_log_gain", 1.6)),
1139
+ "target_weight": float(getattr(args, "pregain_target_weight", 0.0)),
1140
+ "target": "clamped_log_mean_luma_ratio_clean_over_degraded",
1141
+ "inputs": ["global_condition", "photometric_state", "full_frame.*",
1142
+ "luma_statistics(crop)", "luma_statistics(full_image)"],
1143
+ "placement": "input_before_pixel_unshuffle",
1144
+ },
1145
+ "global_attention_scales": list(
1146
+ _parse_scales(getattr(args, "global_attention_scales", ""))
1147
+ ),
1148
+ "colour_head": {
1149
+ "enabled": bool(getattr(args, "colour_head", False)),
1150
+ "dropout": float(getattr(args, "colour_dropout", 0.0)),
1151
+ "target_weight": float(getattr(args, "colour_target_weight", 0.0)),
1152
+ "form": "diag(exp(d))(I+O)x+b, bounded, output side after the photometric head",
1153
+ },
1154
+ "blocks_per_stage": list(blocks_per_stage(args)),
1155
+ "grad_checkpoint": bool(getattr(args, "grad_checkpoint", False)),
1156
+ "data_aug": {
1157
+ "identity_pair_prob": float(getattr(args, "identity_pair_prob", 0.0)),
1158
+ "noise_pair_prob": float(getattr(args, "noise_pair_prob", 0.0)),
1159
+ "identity_exposure_jitter": float(getattr(args, "identity_exposure_jitter", 0.0)),
1160
+ "extra_clean_root": (
1161
+ str(getattr(args, "extra_clean_root", None))
1162
+ if getattr(args, "extra_clean_root", None) else None
1163
+ ),
1164
+ "extra_clean_prob": float(getattr(args, "extra_clean_prob", 0.0)),
1165
+ },
1166
+ "image_head": {
1167
+ "full_res_tail_blocks": int(
1168
+ getattr(args, "full_res_tail_blocks", 0)
1169
+ ),
1170
+ "full_res_tail_width": int(
1171
+ getattr(args, "full_res_tail_width", 48)
1172
+ ),
1173
+ "output_film": bool(getattr(args, "output_film", False)),
1174
+ "photometric_head": bool(getattr(args, "photometric_head", False)),
1175
+ "photometric_dropout": float(getattr(args, "photometric_dropout", 0.0)),
1176
+ "photometric_bounds": {"max_log_gain": 0.7, "max_bias": 0.2},
1177
+ "photometric_inputs": ["global_condition", "photometric_state", "full_frame.*"],
1178
+ },
1179
+ "dims": list(args.dims),
1180
+ "cond_dim": int(args.cond_dim),
1181
+ "state_channels": 12,
1182
+ "prediction": "x0",
1183
+ "eval_sample_steps": int(args.timesteps),
1184
+ "warmstart": dict(audit),
1185
+ }
1186
+
1187
+
1188
+ def _v7_schedule_config(args: argparse.Namespace) -> Dict[str, Any]:
1189
+ result = dict(_V4_SCHEDULE_CONFIG(args))
1190
+ result["expert_kappa"] = {
1191
+ "enabled": True,
1192
+ "values": list(v6._parse_kappa_values(args.expert_kappa_values)),
1193
+ "anneal_steps": 0,
1194
+ "source": "normalized_node_strengths",
1195
+ "posterior": "exact_per_sample_kappa",
1196
+ }
1197
+ result["unified_two_step"] = True
1198
+ return result
1199
+
1200
+
1201
+ def build_parser() -> argparse.ArgumentParser:
1202
+ parser = v6.build_parser()
1203
+ parser.description = __doc__
1204
+ parser.add_argument("--fine-l1-weight", type=float, default=1.0)
1205
+ parser.add_argument("--fine-vgg-weight", type=float, default=0.1)
1206
+ parser.add_argument(
1207
+ "--fine-chroma-weight", type=float, default=0.0,
1208
+ help="L1 weight on BT.601 U/V chroma planes of the fine prediction",
1209
+ )
1210
+ parser.add_argument(
1211
+ "--fine-luma-weight", type=float, default=0.0,
1212
+ help="L1 weight on the 8x8-pooled BT.601 luma of the fine prediction",
1213
+ )
1214
+ parser.add_argument(
1215
+ "--full-res-tail-blocks", type=int, default=0,
1216
+ help="NAFNet-lite blocks in the full-resolution image head (0 = off)",
1217
+ )
1218
+ parser.add_argument("--full-res-tail-width", type=int, default=48)
1219
+ parser.add_argument(
1220
+ "--output-film", action="store_true",
1221
+ help="global-condition FiLM (per-channel affine) on the output image",
1222
+ )
1223
+ parser.add_argument(
1224
+ "--pyramid-heads", action="store_true",
1225
+ help="coarse-to-fine Laplacian band heads at 16/32/64 px (uformer)",
1226
+ )
1227
+ parser.add_argument(
1228
+ "--pyramid-loss-weights", default="0.1,0.2,0.3",
1229
+ help="deep-supervision MSE weights for the 16/32/64 px bands",
1230
+ )
1231
+ parser.add_argument(
1232
+ "--cond-dropout-prob", type=float, default=0.0,
1233
+ help="per-sample probability of swapping context/global_vector for "
1234
+ "the learned null tokens (DGF)",
1235
+ )
1236
+ parser.add_argument(
1237
+ "--photometric-head", action="store_true",
1238
+ help="global exposure controllable (log-gain, bias) on the output, "
1239
+ "predicted from Phase-1 global_condition + photometric_state",
1240
+ )
1241
+ parser.add_argument(
1242
+ "--photometric-dropout", type=float, default=0.0,
1243
+ help="per-sample probability of zeroing the photometric head (identity path)",
1244
+ )
1245
+ parser.add_argument(
1246
+ "--fine-chroma-space", choices=("uv", "hv"), default="uv",
1247
+ help="chroma planes for --fine-chroma-weight: BT.601 UV or HVI HV (k=0.2)",
1248
+ )
1249
+ parser.add_argument(
1250
+ "--identity-exposure-jitter", type=float, default=0.0,
1251
+ help="identity pairs get a random global gain exp(U(-j, j)) applied to input AND target",
1252
+ )
1253
+ parser.add_argument(
1254
+ "--extra-clean-root", default=None,
1255
+ help="folder of extra clean images used for identity pairs (e.g. Snow100K gt)",
1256
+ )
1257
+ parser.add_argument(
1258
+ "--extra-clean-prob", type=float, default=0.5,
1259
+ help="probability that an identity pair is drawn from --extra-clean-root",
1260
+ )
1261
+ parser.add_argument(
1262
+ "--exposure-pregain", action="store_true",
1263
+ help="v10: per-image input gain (Retinex-style) predicted from Phase-1 "
1264
+ "vectors + whole-frame luma statistics, applied before the trunk",
1265
+ )
1266
+ parser.add_argument(
1267
+ "--pregain-dropout", type=float, default=0.0,
1268
+ help="per-sample probability of forcing the pre-gain to 1 (identity path)",
1269
+ )
1270
+ parser.add_argument(
1271
+ "--pregain-max-log-gain", type=float, default=1.6,
1272
+ help="tanh bound of the pre-gain log-gain (1.6 = x0.2 .. x5)",
1273
+ )
1274
+ parser.add_argument(
1275
+ "--pregain-target-weight", type=float, default=0.0,
1276
+ help="v11: weight of the supervised pre-gain loss (log-gain vs clamped log "
1277
+ "luma ratio clean/degraded); 0 = end-to-end only",
1278
+ )
1279
+ parser.add_argument(
1280
+ "--colour-head", action="store_true",
1281
+ help="v12: per-image global colour transform (3x3 + bias) on the output, "
1282
+ "predicted from Phase-1 vectors + whole-frame luma statistics",
1283
+ )
1284
+ parser.add_argument("--colour-dropout", type=float, default=0.0,
1285
+ help="per-sample probability of forcing the colour head to identity")
1286
+ parser.add_argument("--colour-target-weight", type=float, default=0.0,
1287
+ help="weight of the supervised colour-head loss (least-squares target per image)")
1288
+ parser.add_argument(
1289
+ "--global-attention-scales", default="",
1290
+ help="v10: comma-separated stage indices (0..3) that get a zero-init "
1291
+ "whole-map self-attention block after the LeWin blocks, e.g. 2,3",
1292
+ )
1293
+ parser.add_argument(
1294
+ "--extra-blocks-per-stage", default="",
1295
+ help="v11: LeWin blocks appended per stage beyond the base 2, e.g. 0,2,4,4 "
1296
+ "(zero-init adaLN -> identity at warm start; down and up paths)",
1297
+ )
1298
+ parser.add_argument(
1299
+ "--grad-checkpoint", action="store_true",
1300
+ help="v11: recompute transformer blocks in backward (single-process runs only "
1301
+ "with torch 1.10 reentrant checkpoint + DDP find_unused)",
1302
+ )
1303
+ parser.add_argument("--warmstart-v6", type=Path)
1304
+ parser.add_argument("--warmstart-v6-sha256")
1305
+ parser.add_argument(
1306
+ "--backbone", choices=("conv", "uformer"), default="conv"
1307
+ )
1308
+ parser.add_argument(
1309
+ "--allow-scratch", action="store_true",
1310
+ help="permit training without a warm start (uformer backbone)",
1311
+ )
1312
+ return parser
1313
+
1314
+
1315
+ @contextlib.contextmanager
1316
+ def _installed_v7_backend(args: argparse.Namespace) -> Iterator[None]:
1317
+ replacements = {
1318
+ "_build_restorer": _build_v7_restorer,
1319
+ "_architecture": _v7_architecture,
1320
+ "_schedule_config": _v7_schedule_config,
1321
+ "_data_plan": v6._moe_data_plan,
1322
+ "sample_restoration": sample_unified_restoration,
1323
+ }
1324
+ originals = {name: getattr(v4, name) for name in replacements}
1325
+ try:
1326
+ for name, replacement in replacements.items():
1327
+ setattr(v4, name, replacement)
1328
+ yield
1329
+ finally:
1330
+ for name, original in originals.items():
1331
+ setattr(v4, name, original)
1332
+
1333
+
1334
+ def run(args: argparse.Namespace) -> None:
1335
+ v4.validate_runtime_args(args)
1336
+ if int(args.timesteps) != 2:
1337
+ raise ValueError("v7 is a two-step process; pass --timesteps 2")
1338
+ for name in ("fine_l1_weight", "fine_vgg_weight"):
1339
+ if float(getattr(args, name)) < 0:
1340
+ raise ValueError("%s must be non-negative" % name)
1341
+ has_path = args.warmstart_v6 is not None
1342
+ has_sha = args.warmstart_v6_sha256 is not None
1343
+ if has_path != has_sha:
1344
+ raise ValueError("warmstart path and sha256 go together")
1345
+ with _installed_v7_backend(args):
1346
+ v4.run(args)
1347
+
1348
+
1349
+ def main(argv: Optional[Sequence[str]] = None) -> None:
1350
+ run(build_parser().parse_args(argv))
1351
+
1352
+
1353
+ if __name__ == "__main__":
1354
+ main()