diff --git a/dataset/phase1_noise_20260906/code/diagnose_phase1_routing.py b/dataset/phase1_noise_20260906/code/diagnose_phase1_routing.py new file mode 100644 index 0000000000000000000000000000000000000000..cc3c21862b11950febd4c140fff93d4d7c37795f --- /dev/null +++ b/dataset/phase1_noise_20260906/code/diagnose_phase1_routing.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Routing / severity diagnosis of a Phase-1 checkpoint on the cases that +exposed the noise-concept drift: SIDD val noisy inputs and their clean GT, +scene008 (locked, nearly clean, dark textured), and lowlight inputs. +Prints mean routing per node and mean severity per branch for each group.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest + +NODES = ("rain", "noise", "haze", "lowlight", "free1", "free2") + + +def _summary(phase1, batch: torch.Tensor) -> dict: + with torch.no_grad(): + rep = phase1(batch) + routing = rep.routing_probs.mean(0).tolist() + severity = rep.severity_coords.mean(0).tolist() + argmax = rep.routing_probs.argmax(1) + return { + "routing": {n: round(v, 3) for n, v in zip(NODES, routing)}, + "severity": {n: round(v, 3) for n, v in zip(NODES[:4], severity)}, + "argmax_share": {n: round(float((argmax == i).float().mean()), 2) for i, n in enumerate(NODES)}, + "mean_luma": round(float(batch.mean()), 3), + "n": int(batch.shape[0]), + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + parser.add_argument("--output", type=Path, default=None) + args = parser.parse_args() + device = torch.device("cuda") + import hashlib + sha = hashlib.sha256(args.checkpoint.read_bytes()).hexdigest() + phase1, _ = v4.build_frozen_phase1(args.checkpoint, sha, device) + + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + noise_locked = [r for r in splits.locked_test if r.degradation == "noise"] + ds = ext.PairCropDataset(noise_locked) + s8_deg = torch.stack([ds[i]["degraded"] for i in range(len(noise_locked))]).to(device) + s8_cln = torch.stack([ds[i]["clean"] for i in range(len(noise_locked))]).to(device) + + vs = load_train_val_manifest(args.manifest) + vd = Phase2PairDataset(vs.val, crop_size=256, training=False, upscale_small=True) + groups = {} + for domain in ("noise", "lowlight", "rain", "haze"): + idx = [i for i, r in enumerate(vs.val) if r.degradation == domain][:20] + groups["val_%s_input" % domain] = torch.stack([vd[i]["degraded"] for i in idx]).to(device) + groups["val_%s_clean" % domain] = torch.stack([vd[i]["clean"] for i in idx]).to(device) + groups["scene008_input"] = s8_deg + groups["scene008_clean"] = s8_cln + + report = {"checkpoint": str(args.checkpoint), "sha256": sha} + for name, batch in groups.items(): + report[name] = _summary(phase1, batch) + r = report[name] + print("%-22s route %-58s sev %s" % (name, json.dumps(r["routing"]), json.dumps(r["severity"]))) + if args.output: + args.output.write_text(json.dumps(report, indent=2)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/download_all_datasets.sh b/dataset/phase1_noise_20260906/code/download_all_datasets.sh new file mode 100644 index 0000000000000000000000000000000000000000..799357207fc0ced23dffb6fdd60fecf7bb7228b8 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/download_all_datasets.sh @@ -0,0 +1,118 @@ +#!/bin/bash +# Download all 5 datasets locally then upload to server +# Run this on your LOCAL machine (with internet access) + +set -e + +LOCAL_DIR="/Users/nguyenbinhan/Downloads/datasets" +SERVER="3090" +REMOTE_DIR="/home/admin_mcn/data" + +mkdir -p "$LOCAL_DIR" + +echo "==============================================" +echo "Downloading SCDC Datasets" +echo "==============================================" + +# 1. Rain200H +echo "" +echo "[1/5] Downloading Rain200H..." +cd "$LOCAL_DIR" +if [ ! -d "Rain200H" ]; then + 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" + if [ -f Rain200H.zip ] && [ $(stat -f%z Rain200H.zip 2>/dev/null || stat -c%s Rain200H.zip 2>/dev/null) -gt 1000000 ]; then + unzip -q Rain200H.zip -d Rain200H + rm Rain200H.zip + echo " Rain200H downloaded!" + else + echo " Download failed. Please manually download from:" + echo " https://drive.google.com/file/d/1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF/view" + mkdir -p Rain200H + fi +else + echo " Rain200H already exists" +fi + +# 2. LOLv2 +echo "" +echo "[2/5] Downloading LOLv2..." +cd "$LOCAL_DIR" +if [ ! -d "LOLv2" ]; then + echo " Please download LOLv2 manually from: https://daooshee.github.io/FOVDFE/" + echo " Expected structure: LOLv2/LOLv2/Real_captured/" + mkdir -p LOLv2/LOLv2/Real_captured +fi + +# 3. RESIDE (OTS) +echo "" +echo "[3/5] Downloading RESIDE..." +cd "$LOCAL_DIR" +if [ ! -d "RESIDE" ]; then + echo " Please download RESIDE manually from: https://github.com/x懦yzzz/RESIDE" + echo " Expected structure: RESIDE/OTS/OTS/" + mkdir -p RESIDE/OTS/OTS +fi + +# 4. GOPRO +echo "" +echo "[4/5] Downloading GOPRO..." +cd "$LOCAL_DIR" +if [ ! -d "GOPRO" ]; then + echo " Please download GOPRO manually from: https://github.com/SeungjunNah/DeepDeblur" + echo " Expected structure: GOPRO/train/blur/, GOPRO/train/sharp/" + mkdir -p GOPRO/train/blur GOPRO/train/sharp GOPRO/test/blur GOPRO/test/sharp +fi + +# 5. SIDD +echo "" +echo "[5/5] Downloading SIDD..." +cd "$LOCAL_DIR" +if [ ! -d "SIDD" ]; then + echo " SIDD requires registration at: https://sid.epfl.ch/" + echo " Please download manually after registration." + mkdir -p SIDD/SIDD_Benchmark +fi + +echo "" +echo "==============================================" +echo "Upload to Server" +echo "==============================================" + +echo "" +echo "Uploading Rain200H..." +if [ -d "$LOCAL_DIR/Rain200H" ]; then + if [ -d "$LOCAL_DIR/Rain200H/train_c" ] || [ -d "$LOCAL_DIR/Rain200H/rainy_image_extractions" ]; then + tar -czvf /tmp/rain200h.tar.gz -C "$LOCAL_DIR" Rain200H 2>/dev/null + scp /tmp/rain200h.tar.gz $SERVER:$REMOTE_DIR/ + ssh $SERVER "cd $REMOTE_DIR && tar -xzvf rain200h.tar.gz && rm rain200h.tar.gz" + rm /tmp/rain200h.tar.gz + echo " Rain200H uploaded!" + else + echo " Rain200H folder exists but structure is unexpected" + ls "$LOCAL_DIR/Rain200H/" + fi +else + echo " Rain200H not found locally" +fi + +echo "" +echo "==============================================" +echo "Summary" +echo "==============================================" +echo "" +echo "Datasets at $LOCAL_DIR:" +for dir in Rain200H LOLv2 RESIDE GOPRO SIDD; do + if [ -d "$LOCAL_DIR/$dir" ]; then + count=$(find "$LOCAL_DIR/$dir" -type f \( -name "*.png" -o -name "*.jpg" \) 2>/dev/null | wc -l) + echo " OK $dir ($count images)" + else + echo " MISSING $dir (not downloaded)" + fi +done + +echo "" +echo "Datasets on server $SERVER:" +ssh $SERVER "ls -la $REMOTE_DIR/ 2>/dev/null || echo 'Remote dir not found'" + +echo "" +echo "Done!" diff --git a/dataset/phase1_noise_20260906/code/download_rain200h.sh b/dataset/phase1_noise_20260906/code/download_rain200h.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e099496543422f2ceb29105d75737ccabf875c8 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/download_rain200h.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# Download Rain200H dataset for deraining +# Link: https://drive.google.com/file/d/1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF/view + +set -e + +DATA_ROOT="/home/admin_mcn/data" +RAIN_DIR="$DATA_ROOT/Rain200H" +mkdir -p "$RAIN_DIR" + +echo "==============================================" +echo "Downloading Rain200H Dataset" +echo "==============================================" + +# Method 1: Using gdown (if available) +if command -v gdown &> /dev/null; then + echo "Using gdown..." + cd "$DATA_ROOT" + gdown 1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF -O Rain200H.zip + unzip -q Rain200H.zip -d Rain200H + rm Rain200H.zip +# Method 2: Using wget/curl with direct link +else + echo "Installing gdown..." + pip3 install gdown + + echo "Downloading from Google Drive..." + cd "$DATA_ROOT" + gdown 1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF -O Rain200H.zip + + echo "Extracting..." + unzip -q Rain200H.zip -d Rain200H + rm Rain200H.zip +fi + +echo "Checking structure..." +ls -la "$RAIN_DIR/" + +# Verify dataset structure +if [ -d "$RAIN_DIR/train_c" ] || [ -d "$RAIN_DIR/Rain200H/train_c" ]; then + echo "" + echo "==============================================" + echo "Rain200H Dataset Ready!" + echo "==============================================" + echo "Structure:" + find "$RAIN_DIR" -type d | head -10 + echo "" + echo "Sample counts:" + if [ -d "$RAIN_DIR/train_c" ]; then + echo " Train clean: $(ls "$RAIN_DIR/train_c/" 2>/dev/null | wc -l) images" + elif [ -d "$RAIN_DIR/Rain200H/train_c" ]; then + echo " Train clean: $(ls "$RAIN_DIR/Rain200H/train_c/" 2>/dev/null | wc -l) images" + fi +else + echo "" + echo "WARNING: Dataset structure not as expected." + echo "Please check $RAIN_DIR manually." +fi + +echo "" +echo "Done!" diff --git a/dataset/phase1_noise_20260906/code/eval_full_frame.py b/dataset/phase1_noise_20260906/code/eval_full_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..bc728ad86963304605099569bc7fc10662eace93 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/eval_full_frame.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python3 +"""Native-resolution, full-image evaluation of a v7-family checkpoint. + +Why a second protocol: ``eval_pipeline_external.py`` measures 256 center +crops taken AFTER ``_resize_center_crop`` (short side -> 256), i.e. every +external image is downscaled first (Test1200 384 -> 256 = 0.67x, RESIDE +0.62x, SIDD scene008 ~12x). Downscaling averages real noise away (scene008 +input reads 39 dB "nearly clean") and moves every set to a scale the trunk +never trained on (Phase-2 trains on NATIVE 256 crops). Published numbers are +full images at native resolution, so this evaluator restores the whole +image at native scale with overlapping 256 tiles (the training crop size), +Phase-1 per tile plus the aspect-squashed whole frame for global-context +models, optional x8 dihedral test-time augmentation, and reports RGB and +Y-channel PSNR/SSIM (deraining papers report Y) plus LPIPS. + +Groups: rain_locked (Test100+Test1200, 384x384), noise_locked_scene008 (SIDD +scene 008 at native 12 MP), haze_heldout (300 RESIDE), lowlight_lolv2_test +(the 100 LOLv2-real test images = the lowlight val split, directly +comparable to published LOLv2-real numbers). +""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import Callable, Dict, List, Optional, Sequence, Tuple + +import torch +from torch import Tensor +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 + +RestoreFn = Callable[[Tensor, Sequence[str], Optional[Tensor]], Tensor] + +_LANCZOS = getattr(getattr(__import__("PIL.Image", fromlist=["Image"]), "Resampling", None), "LANCZOS", None) + + +# ---- dihedral test-time augmentation -------------------------------------- # +def dihedral_transform(image: Tensor, index: int) -> Tensor: + """Apply one of the 8 square symmetries (index 0 = identity). + + index = 4 * flip + rotation, rotation in {0,1,2,3} quarter turns + counter-clockwise, flip = horizontal mirror applied FIRST. + """ + + if not 0 <= int(index) < 8: + raise ValueError("dihedral index must be in [0, 8)") + out = image + if index >= 4: + out = torch.flip(out, dims=(-1,)) + return torch.rot90(out, k=int(index) % 4, dims=(-2, -1)) + + +def dihedral_inverse(image: Tensor, index: int) -> Tensor: + """Undo ``dihedral_transform(_, index)``.""" + + if not 0 <= int(index) < 8: + raise ValueError("dihedral index must be in [0, 8)") + out = torch.rot90(image, k=-(int(index) % 4), dims=(-2, -1)) + if index >= 4: + out = torch.flip(out, dims=(-1,)) + return out + + +# ---- tiling --------------------------------------------------------------- # +def tile_boxes(height: int, width: int, tile: int, overlap: int) -> List[Tuple[int, int]]: + """Top-left corners of ``tile``-sized boxes covering an image of at least + ``tile`` in both dimensions; the last row/column is flush with the edge.""" + + if tile <= 0 or overlap < 0 or overlap >= tile: + raise ValueError("need 0 <= overlap < tile") + if height < tile or width < tile: + raise ValueError("image must be at least one tile in both dimensions") + stride = tile - overlap + + def starts(length: int) -> List[int]: + positions = list(range(0, max(length - tile, 0) + 1, stride)) + if positions[-1] != length - tile: + positions.append(length - tile) + return positions + + return [(top, left) for top in starts(height) for left in starts(width)] + + +def blend_weights(tile: int, overlap: int, device=None, dtype=torch.float32) -> Tensor: + """[1,1,tile,tile] raised-cosine ramp over ``overlap`` pixels on every + edge, 1 in the interior; complementary ramps of adjacent tiles sum to 1.""" + + ramp = torch.ones(tile, device=device, dtype=dtype) + if overlap > 0: + positions = (torch.arange(overlap, device=device, dtype=dtype) + 0.5) / float(overlap) + edge = 0.5 - 0.5 * torch.cos(math.pi * positions) + ramp[:overlap] = edge + ramp[tile - overlap:] = torch.flip(edge, dims=(0,)) + return (ramp.view(-1, 1) * ramp.view(1, -1)).view(1, 1, tile, tile) + + +def _pad_to_tile(image: Tensor, tile: int) -> Tuple[Tensor, Tuple[int, int]]: + height, width = int(image.shape[-2]), int(image.shape[-1]) + pad_h, pad_w = max(tile - height, 0), max(tile - width, 0) + if pad_h == 0 and pad_w == 0: + return image, (height, width) + mode = "reflect" if pad_h < height and pad_w < width else "replicate" + return F.pad(image, (0, pad_w, 0, pad_h), mode=mode), (height, width) + + +@torch.no_grad() +def restore_tiled( + restore: RestoreFn, + image: Tensor, + record_id: str, + *, + tile: int = 256, + overlap: int = 64, + tile_batch: int = 8, + full_frame: Optional[Tensor] = None, +) -> Tensor: + """Restore one [1,3,H,W] image with overlapping tiles. + + ``restore(tiles [N,3,tile,tile], record_ids, full_frame [N,3,s,s] | None)`` + returns the restored tiles. Every tile gets a distinct record id so the + record-keyed sampler noise stays deterministic per tile. + """ + + if image.ndim != 4 or image.shape[0] != 1: + raise ValueError("restore_tiled expects a single [1,3,H,W] image") + padded, (height, width) = _pad_to_tile(image, tile) + boxes = tile_boxes(int(padded.shape[-2]), int(padded.shape[-1]), tile, overlap) + weights = blend_weights(tile, overlap, device=padded.device, dtype=torch.float32) + canvas = torch.zeros(1, padded.shape[1], padded.shape[-2], padded.shape[-1], + device=padded.device, dtype=torch.float32) + total = torch.zeros(1, 1, padded.shape[-2], padded.shape[-1], + device=padded.device, dtype=torch.float32) + for start in range(0, len(boxes), max(int(tile_batch), 1)): + chunk = boxes[start:start + max(int(tile_batch), 1)] + tiles = torch.cat([padded[..., t:t + tile, l:l + tile] for t, l in chunk], dim=0) + ids = ["%s|tile%d" % (record_id, start + k) for k in range(len(chunk))] + full = None if full_frame is None else full_frame.expand(len(chunk), -1, -1, -1) + restored = restore(tiles, ids, full).float() + if restored.shape != tiles.shape: + raise ValueError("restore must return tiles of the input shape") + for k, (t, l) in enumerate(chunk): + canvas[..., t:t + tile, l:l + tile] += restored[k:k + 1] * weights + total[..., t:t + tile, l:l + tile] += weights + return (canvas / total)[..., :height, :width] + + +# Every scale of the trunk must stay divisible by the 8x8 window: image/2 +# (pixel-unshuffle) then three /2 stages -> the image must be a multiple of +# 2 * 8 * 8 = 128 for the relative-position bias to apply at all four scales. +WHOLE_IMAGE_MULTIPLE = 128 + + +@torch.no_grad() +def restore_whole( + restore: RestoreFn, + image: Tensor, + record_id: str, + *, + multiple: int = WHOLE_IMAGE_MULTIPLE, + full_frame: Optional[Tensor] = None, +) -> Tensor: + """Restore one [1,3,H,W] image in a single pass (no tiles): reflect-pad + to a multiple of ``multiple`` so the window attention keeps its native + 8x8 windows at every scale, then crop back. Removes the per-tile + conditioning/exposure inconsistency of tiled inference.""" + + if image.ndim != 4 or image.shape[0] != 1: + raise ValueError("restore_whole expects a single [1,3,H,W] image") + height, width = int(image.shape[-2]), int(image.shape[-1]) + pad_h, pad_w = (-height) % multiple, (-width) % multiple + padded = image + if pad_h or pad_w: + mode = "reflect" if pad_h < height and pad_w < width else "replicate" + padded = F.pad(image, (0, pad_w, 0, pad_h), mode=mode) + restored = restore(padded, ["%s|whole" % record_id], full_frame).float() + if restored.shape != padded.shape: + raise ValueError("restore must return an image of the input shape") + return restored[..., :height, :width] + + +# TTA sets. x2 = identity + horizontal mirror only: rotations and the +# vertical flip change the orientation of rain streaks and put the sky at the +# bottom, which the model never saw (measured on v9a15k, tiled: x8 costs +# -2.4 dB on Test1200 and -1.0 dB on haze while helping isotropic noise). +TTA_TRANSFORMS = {1: (0,), 2: (0, 4), 8: tuple(range(8))} + + +@torch.no_grad() +def restore_full_frame( + restore: RestoreFn, + image: Tensor, + record_id: str, + *, + tta: int = 1, + full_frame: Optional[Tensor] = None, + whole_max_pixels: int = 0, + **tiling, +) -> Tensor: + """Restoration averaged over ``tta`` dihedral transforms (1 or 8). + + Images with at most ``whole_max_pixels`` pixels are restored in one pass + (``restore_whole``); larger ones (or all, when 0) with overlapping tiles. + """ + + if int(tta) not in TTA_TRANSFORMS: + raise ValueError("tta must be 1, 2 or 8") + pixels = int(image.shape[-2]) * int(image.shape[-1]) + whole = int(whole_max_pixels) > 0 and pixels <= int(whole_max_pixels) + outputs = [] + for index in TTA_TRANSFORMS[int(tta)]: + transformed = dihedral_transform(image, index) + full = None if full_frame is None else dihedral_transform(full_frame, index) + tag = "%s|d%d" % (record_id, index) + if whole: + restored = restore_whole(restore, transformed, tag, full_frame=full) + else: + restored = restore_tiled(restore, transformed, tag, full_frame=full, **tiling) + outputs.append(dihedral_inverse(restored, index)) + return torch.stack(outputs, dim=0).mean(dim=0).clamp(0.0, 1.0) + + +# ---- metrics -------------------------------------------------------------- # +def rgb_to_y601(image: Tensor) -> Tensor: + """BT.601 luma of an RGB [B,3,H,W] batch in [0,1] -> Y in [16,235]/255.""" + + if image.ndim != 4 or image.shape[1] != 3: + raise ValueError("rgb_to_y601 expects [B,3,H,W]") + r, g, b = image[:, 0:1].float(), image[:, 1:2].float(), image[:, 2:3].float() + return (16.0 + 65.481 * r + 128.553 * g + 24.966 * b) / 255.0 + + +def psnr_y_per_image(prediction: Tensor, target: Tensor) -> Tensor: + return v4.rgb_psnr_per_image(rgb_to_y601(prediction), rgb_to_y601(target)) + + +def ssim_y_per_image(prediction: Tensor, target: Tensor) -> Tensor: + return v4.rgb_ssim_per_image(rgb_to_y601(prediction), rgb_to_y601(target)) + + +def lpips_center(lpips_fn, prediction: Tensor, target: Tensor, max_side: int = 1024) -> Tensor: + """LPIPS on the full image, or on a central ``max_side`` window for very + large images (the AlexNet features of a 12 MP frame do not fit).""" + + height, width = prediction.shape[-2:] + if height > max_side or width > max_side: + top, left = max((height - max_side) // 2, 0), max((width - max_side) // 2, 0) + prediction = prediction[..., top:top + max_side, left:left + max_side] + target = target[..., top:top + max_side, left:left + max_side] + return lpips_fn(prediction * 2 - 1, target * 2 - 1).flatten() + + +# ---- data ----------------------------------------------------------------- # +class FullFrameDataset(Dataset): + """Native pairs (upscaled only when smaller than ``crop`` on the short + side, exactly Phase2PairDataset's rule) plus the aspect-squashed whole + frame used by global-context models.""" + + def __init__(self, records: Sequence, crop: int = 256) -> None: + self.records = list(records) + self.crop = int(crop) + + def __len__(self) -> int: + return len(self.records) + + def __getitem__(self, index: int): + record = self.records[index] + degraded, clean = p1._native_open_pair(record, self.crop) + full = degraded.resize((self.crop, self.crop), _LANCZOS) + return { + "degraded": p1._pil_to_tensor(degraded), + "clean": p1._pil_to_tensor(clean), + "full_degraded": p1._pil_to_tensor(full), + "record_id": record.record_id, + } + + +def external_groups(haze_count: int = 300) -> Dict[str, list]: + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rain = [r for r in splits.locked_test if r.degradation == "rain"] + noise = [r for r in splits.locked_test if r.degradation == "noise"] + lowlight = [r for r in splits.val if r.degradation == "lowlight"] + reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE") + used = { + r.split_group for r in list(splits.train) + list(splits.val) + if r.degradation == "haze" + } + haze = [r for r in reside[5000:] if r.split_group not in used][:haze_count] + return { + "rain_locked": rain, + "noise_locked_scene008": noise, + "haze_heldout": haze, + "lowlight_lolv2_test": lowlight, + } + + +def _mean(values: List[float]) -> float: + return float(sum(values) / len(values)) if values else float("nan") + + +@torch.no_grad() +def evaluate_group_full_frame( + restore: RestoreFn, + records: Sequence, + name: str, + device: torch.device, + lpips_fn=None, + *, + tta: int = 1, + tile: int = 256, + overlap: int = 64, + tile_batch: int = 8, + use_full_frame: bool = True, + workers: int = 2, + whole_max_pixels: int = 0, +) -> Dict[str, object]: + loader = DataLoader(FullFrameDataset(records, crop=tile), batch_size=1, + shuffle=False, num_workers=workers) + keys = ("psnr", "ssim", "psnr_y", "ssim_y", "lpips") + acc = {kind: {k: [] for k in keys} for kind in ("restored", "degraded")} + sizes = [] + for batch in loader: + degraded = batch["degraded"].to(device) + clean = batch["clean"].to(device) + full = batch["full_degraded"].to(device) if use_full_frame else None + record_id = str(batch["record_id"][0]) + restored = restore_full_frame( + restore, degraded, record_id, tta=tta, full_frame=full, + tile=tile, overlap=overlap, tile_batch=tile_batch, + whole_max_pixels=whole_max_pixels, + ) + sizes.append([int(degraded.shape[-2]), int(degraded.shape[-1])]) + for kind, image in (("restored", restored), ("degraded", degraded)): + slot = acc[kind] + slot["psnr"] += v4.rgb_psnr_per_image(image, clean).cpu().tolist() + slot["ssim"] += v4.rgb_ssim_per_image(image, clean).cpu().tolist() + slot["psnr_y"] += psnr_y_per_image(image, clean).cpu().tolist() + slot["ssim_y"] += ssim_y_per_image(image, clean).cpu().tolist() + if lpips_fn is not None: + slot["lpips"] += lpips_center(lpips_fn, image, clean).cpu().tolist() + report = { + "n": len(records), + "protocol": {"tile": tile, "overlap": overlap, "tta": int(tta), "native": True, + "full_frame_context": bool(use_full_frame), + "whole_max_pixels": int(whole_max_pixels)}, + "sizes_hw": sizes[:3], + } + for kind, slot in acc.items(): + report[kind] = {k: _mean(v) for k, v in slot.items() if v} + print(name, json.dumps(report, sort_keys=True), flush=True) + return report + + +def main(argv: Optional[Sequence[str]] = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--groups", default="rain_locked,noise_locked_scene008,haze_heldout,lowlight_lolv2_test") + parser.add_argument("--tta", type=int, default=1, choices=(1, 2, 8), + help="1 = none, 2 = + horizontal mirror (orientation-safe), 8 = full dihedral") + parser.add_argument("--tile", type=int, default=256) + parser.add_argument("--overlap", type=int, default=64) + parser.add_argument("--tile-batch", type=int, default=8) + parser.add_argument("--haze-count", type=int, default=300) + parser.add_argument("--dose", type=float, default=None) + parser.add_argument("--photometric-dose", type=float, default=None) + parser.add_argument( + "--whole-max-pixels", type=int, default=0, + help="restore images up to this many pixels in ONE pass (pad to x128) " + "instead of tiles; 0 = always tile. 1.2e6 covers LOL/RESIDE/Test1200.", + ) + parser.add_argument("--pregain-dose", type=float, default=None, + help="scale of the v10 input pre-gain log-gain (None = 1.0; 0 = off)") + parser.add_argument("--colour-dose", type=float, default=None, + help="scale of the v12 global colour head (None = 1.0; 0 = off)") + parser.add_argument("--checkpoint", default="best.pt", + help="file inside --run-dir to evaluate (best.pt, last.pt, milestone_%08d.pt)") + parser.add_argument("--no-lpips", action="store_true") + parser.add_argument("--limit", type=int, default=0, help="debug: first N records per group") + args = parser.parse_args(argv) + + from eval_v7_external import V7Pipeline + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + pipeline = V7Pipeline(args.run_dir, device, dose=args.dose, photometric_dose=args.photometric_dose, + checkpoint=args.checkpoint, pregain_dose=args.pregain_dose, + colour_dose=args.colour_dose) + seed = int(pipeline.args.eval_seed) + + def restore(tiles: Tensor, ids: Sequence[str], full: Optional[Tensor]) -> Tensor: + return pipeline.restore(tiles, record_ids=list(ids), seed=seed, full_degraded=full)["restored"] + + lpips_fn = None + if not args.no_lpips: + import lpips + + lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device) + groups = external_groups(args.haze_count) + report = {"run_dir": str(args.run_dir), "dose": args.dose, + "photometric_dose": args.photometric_dose, "tta": int(args.tta), + "whole_max_pixels": int(args.whole_max_pixels), + "checkpoint": pipeline.checkpoint_name, "checkpoint_step": pipeline.checkpoint_step, + "pregain_dose": args.pregain_dose} + for name in [g.strip() for g in args.groups.split(",") if g.strip()]: + records = groups[name] + if args.limit > 0: + records = records[: args.limit] + report[name] = evaluate_group_full_frame( + restore, records, name, device, lpips_fn, + tta=args.tta, tile=args.tile, overlap=args.overlap, tile_batch=args.tile_batch, + whole_max_pixels=args.whole_max_pixels, + ) + args.output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE", args.output, flush=True) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/eval_gen2_external.py b/dataset/phase1_noise_20260906/code/eval_gen2_external.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1d592958d89627867edf68ecf1bec7bedfa96d --- /dev/null +++ b/dataset/phase1_noise_20260906/code/eval_gen2_external.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Official + external evaluation of the gen-2 pipeline (v6.1 + refiner).""" +import json +from pathlib import Path + +import torch + +import train_refiner_a as tr +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +from src.models.restoration.refiner_decoder import RefinerDecoder +import train_phase2_graph_resshift_v4 as v4 + + +class Gen2Pipeline: + def __init__(self, device): + self.device = device + self.regressor, self.phase1, self.args = tr.load_frozen_regressor( + device, kind="v6", run_dir=Path("outputs/phase2_moe_v6/v61_seed42") + ) + state = torch.load("outputs/refiner_v6_v1/refiner_best.pt", map_location="cpu") + refiner = RefinerDecoder() + refiner.load_state_dict(state["refiner_state_dict"], strict=True) + self.refiner = refiner.to(device).eval() + print("refiner best step:", state["step"], "macro:", round(state["macro_refined_psnr"], 3)) + + @torch.no_grad() + def restore(self, degraded, record_ids=None, seed=20260830): + degraded = degraded.to(self.device) + x0 = tr.one_step_x0(self.regressor, self.phase1, degraded, + [str(r) for r in record_ids], seed, "initial") + px, size = v4.pad_to_multiple(x0, multiple=4) + py, _ = v4.pad_to_multiple(degraded, multiple=4) + out = self.refiner(px, py) + h, w = size + return {"x0_hat": x0, "restored": out[..., :h, :w]} + + +def main(): + import lpips + device = torch.device("cuda") + pipeline = Gen2Pipeline(device) + lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device) + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rain = [r for r in splits.locked_test if r.degradation == "rain"] + noise = [r for r in splits.locked_test if r.degradation == "noise"] + reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE") + used = {r.split_group for r in list(splits.train) + list(splits.val) if r.degradation == "haze"} + haze = [r for r in reside[5000:] if r.split_group not in used][:300] + report = { + "rain_locked": ext.evaluate_group(pipeline, rain, "rain_locked", lpips_fn), + "noise_locked_scene008": ext.evaluate_group(pipeline, noise, "noise_locked", lpips_fn), + "haze_heldout": ext.evaluate_group(pipeline, haze, "haze_heldout", lpips_fn), + } + Path("outputs/gen2_external_v1.json").write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE outputs/gen2_external_v1.json") + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/eval_phase1_clean_relative.py b/dataset/phase1_noise_20260906/code/eval_phase1_clean_relative.py new file mode 100644 index 0000000000000000000000000000000000000000..e656afd99562d55a2fbe191f5f8fcbb47c5a668b --- /dev/null +++ b/dataset/phase1_noise_20260906/code/eval_phase1_clean_relative.py @@ -0,0 +1,475 @@ +"""Auditable real/synthetic evaluation for seven clean-relative factors. + +Test is an explicitly requested evaluation split, never a training selector. +Missing targets, collapsed targets, and unimplemented claims remain explicit. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch import Tensor +import torch.nn.functional as F +from torch.utils.data import DataLoader + +from train_phase1_clean_relative import ( + TYPE_ORDER, HELDOUT_PAIRS, TRAIN_PAIRS, atomic_json_save, file_digest, + functional_error, record_labels, residual_statistics, scene_component_ids, selected_indices, +) + + +def average_precision(targets, scores) -> float | None: + """Threshold-grouped AP: ties cannot gain an arbitrary ranking advantage.""" + labels = np.asarray(targets, dtype=np.int64) + values = np.asarray(scores, dtype=np.float64) + positives = int(labels.sum()) + if positives == 0: + return None + if len(labels) != len(values) or not np.isfinite(values).all(): + raise ValueError("Invalid average-precision inputs") + order = np.argsort(-values, kind="stable") + labels, values = labels[order], values[order] + cumulative = np.cumsum(labels) + ends = np.r_[np.flatnonzero(values[:-1] != values[1:]), len(values) - 1] + true_positive = cumulative[ends] + recalls = true_positive / positives + precisions = true_positive / (ends + 1) + return float(np.sum(np.diff(np.r_[0.0, recalls]) * precisions)) + + +def classification_report(labels: Tensor, logits: Tensor) -> dict[str, Any]: + labels, logits = labels.cpu(), logits.detach().float().cpu() + if len(labels) == 0: + raise ValueError("No records to evaluate") + probabilities = logits.sigmoid() + predicted = logits.argmax(1) + confusion = torch.bincount(labels * 7 + predicted, minlength=49).reshape(7, 7) + domains = {} + f1s, aps, supported_f1s = [], [], [] + for i, name in enumerate(TYPE_ORDER): + tp = int(confusion[i, i]) + support, predicted_count = int(confusion[i].sum()), int(confusion[:, i].sum()) + precision = tp / predicted_count if predicted_count else 0.0 + recall = tp / support if support else 0.0 + f1 = 2 * tp / (support + predicted_count) if support + predicted_count else 0.0 + ap = average_precision((labels == i).numpy(), probabilities[:, i].numpy()) + domains[name] = {"support": support, "precision": precision, "recall": recall, "f1": f1, "average_precision": ap} + f1s.append(f1) + if support: + supported_f1s.append(f1) + if ap is not None: + aps.append(ap) + return {"type_order": TYPE_ORDER, "records": len(labels), "confusion": confusion.tolist(), "per_domain": domains, + "accuracy": float((predicted == labels).float().mean()), "macro_f1": float(np.mean(f1s)), + "macro_f1_supported": float(np.mean(supported_f1s)), "supported_classes": len(supported_f1s), + "macro_average_precision_supported": float(np.mean(aps)) if aps else None, + "interpretation": "Single manifest-domain argmax; probabilities remain independent presence scores"} + + +def regression_report(targets, predictions) -> dict[str, Any]: + target, prediction = np.asarray(targets, dtype=float), np.asarray(predictions, dtype=float) + if not target.size: + return {"count": 0, "mae": None, "r2": None, "pearson": None, "target_variance": None} + variance = float(np.var(target)) + residual = float(np.sum((target - prediction) ** 2)) + total = float(np.sum((target - np.mean(target)) ** 2)) + 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 + return {"count": int(target.size), "mae": float(np.mean(np.abs(target - prediction))), + "r2": 1 - residual / total if total > 1e-12 else None, "pearson": correlation, + "target_variance": variance} + + +def binary_auc(known_scores, unknown_scores) -> float | None: + """Mann–Whitney AUC, including half credit for ties.""" + known, unknown = np.asarray(known_scores), np.asarray(unknown_scores) + if not len(known) or not len(unknown): + return None + return float(np.mean(unknown[:, None] > known[None, :]) + 0.5 * np.mean(unknown[:, None] == known[None, :])) + + +def _loader(manifest, split, patch_size, batch_size, workers, cap, seed): + from src.data.clean_relative import PairedDegradationDataset + + dataset = PairedDegradationDataset(manifest, split=split, crop_size=patch_size, seed=seed) + labels = record_labels(dataset) + selected = selected_indices(labels, cap, seed) + if not selected: + raise ValueError(f"Manifest split {split!r} is empty") + loader = DataLoader(dataset, batch_size=batch_size, sampler=selected, drop_last=False, num_workers=workers, + generator=torch.Generator().manual_seed(seed), persistent_workers=False) + return dataset, selected, loader + + +@torch.inference_mode() +def evaluate_real(model, manifest: str, split: str, device, batch_size: int = 16, patch_size: int = 128, + workers: int = 0, max_records: int | None = None, seed: int = 42, + functional_enabled: bool = True) -> dict[str, Any]: + dataset, selected, loader = _loader(manifest, split, patch_size, batch_size, workers, max_records, seed) + previous_mode = model.training + model.eval() + labels, logits, clean_probabilities, clean_norms, deltas = [], [], [], [], [] + paired_content, shuffled_content = [], [] + clean_proxy_l1, clean_proxy_psnr = [], [] + physical = {name: {"target": [], "prediction": []} for name in TYPE_ORDER} + try: + for batch in loader: + pair = model.forward_pair(batch["degraded"].to(device), batch["clean"].to(device)) + student, clean = pair["student"], pair["clean"] + if functional_enabled: + target_clean = batch["clean"].to(device) + origin = model.decode(clean["content"], torch.zeros_like(clean["delta"]), target_clean.shape[-2:]) + error = origin - target_clean + clean_proxy_l1.extend(error.abs().flatten(1).mean(1).cpu().tolist()) + clean_proxy_psnr.extend((-10 * error.square().flatten(1).mean(1).clamp_min(1e-12).log10()).cpu().tolist()) + labels.append(batch["label"]) + logits.append(student["presence_logits"].float().cpu()) + clean_probabilities.append(clean["presence_logits"].sigmoid().float().cpu()) + clean_norms.append(clean["delta"].norm(dim=1).float().cpu()) + deltas.append(student["delta"].float().cpu()) + for k, name in enumerate(TYPE_ORDER): + mask = batch["severity_mask"][:, k] + physical[name]["target"].extend(batch["severity"][mask, k].tolist()) + physical[name]["prediction"].extend(student["severity"].cpu()[mask, k].tolist()) + paired_content.append((student["content"] - clean["content"]).square().flatten(1).mean(1).cpu()) + if len(batch["clean"]) > 1: + shuffled_content.append((student["content"] - clean["content"].roll(1, 0)).square().flatten(1).mean(1).cpu()) + finally: + model.train(previous_mode) + probabilities, norms, delta = torch.cat(clean_probabilities), torch.cat(clean_norms), torch.cat(deltas) + report = { + "split": split, "records_total": len(dataset), "records_evaluated": len(selected), + "scope": "all_records" if len(selected) == len(dataset) else "explicitly_capped", + "image_protocol": f"One deterministic paired {patch_size}x{patch_size} native crop per record; not full-image restoration", + "classification": classification_report(torch.cat(labels), torch.cat(logits)), + "clean": {"any_false_positive_rate_at_0_5": float((probabilities > 0.5).any(1).float().mean()), + "per_factor_false_positive_rate_at_0_5": dict(zip(TYPE_ORDER, (probabilities > 0.5).float().mean(0).tolist())), + "delta_norm_mean": float(norms.mean()), "delta_norm_p95": float(torch.quantile(norms, 0.95)), "delta_norm_max": float(norms.max())}, + "clean_origin_proxy": {"status": "measured" if functional_enabled else "unsupported_without_trained_proxy", + "rgb_l1": _mean(clean_proxy_l1), "psnr_mean_db": _mean(clean_proxy_psnr), + "definition": "G(content(clean), zero_delta) against clean; peak=1, MSE floor=1e-12, outputs not clamped"}, + "representation": {"mean_coordinate_variance": float(delta.var(0, unbiased=False).mean()), "mean_norm": float(delta.norm(dim=1).mean())}, + "paired_content": {"matched_feature_mse": float(torch.cat(paired_content).mean()), + "within_batch_shuffled_feature_mse": float(torch.cat(shuffled_content).mean()) if shuffled_content else None, + "interpretation": "Paired-feature consistency diagnostic; not an independence test"}, + "manifest_physical_severity": { + name: {"status": "measured_from_explicit_parameter_mask" if item["target"] else "unsupported_without_physical_targets", + **regression_report(item["target"], item["prediction"])} for name, item in physical.items()}, + "severity_interpretation": "Only supplied synthetic parameter masks are scored, e.g. generated JPEG; real domain names are not physical severity measurements", + } + return report + + +def _content_probe(baseline, descriptor, content, group_ids) -> dict[str, Any]: + """Does a global code predict observable scene information beyond type/dose?""" + groups = np.asarray(group_ids) + unique = np.unique(groups) + if len(unique) < 4: + return {"status": "insufficient_data", "reason": "Need at least four distinct source scenes for a disjoint probe split"} + train = np.isin(groups, unique[:len(unique) // 2]) + test = ~train + target = np.asarray(content, dtype=np.float64) + + def fit_error(features): + features = np.asarray(features, dtype=np.float64) + center, scale = features[train].mean(0), features[train].std(0).clip(1e-4) + normalized = (features - center) / scale + normalized = np.column_stack((np.ones(len(normalized)), normalized)) + penalty = np.eye(normalized.shape[1]) + penalty[0, 0] = 0 + coefficients = np.linalg.solve(normalized[train].T @ normalized[train] + penalty, normalized[train].T @ target[train]) + return float(np.mean((normalized[test] @ coefficients - target[test]) ** 2)) + + base = np.asarray(baseline) + base_error = fit_error(base) + augmented_error = fit_error(np.concatenate((base, np.asarray(descriptor)), axis=1)) + variance = float(target[test].var(0).mean()) + return {"status": "measured", "train_scenes": int(len(unique) // 2), "test_scenes": int(len(unique) - len(unique) // 2), + "baseline": "Ridge regression from type one-hot plus type-by-normalized-physical-severity", + "target": "Clean 4x4 RGB thumbnail, fixed observable rather than learned teacher target", + "baseline_mse": base_error, "baseline_plus_delta_mse": augmented_error, + "heldout_target_variance": variance, + "baseline_r2": 1 - base_error / variance if variance > 1e-12 else None, + "baseline_plus_delta_r2": 1 - augmented_error / variance if variance > 1e-12 else None, + "relative_improvement": (base_error - augmented_error) / base_error if base_error > 1e-12 else None, + "interpretation": "Positive held-out improvement is evidence of this specific content-prediction channel; not a proof of independence or universally undesirable content dependence"} + + +def physical_parameter_probe(rows: list[dict], kind: str) -> dict[str, Any]: + """Test within-factor information beyond dose, against fixed physical targets.""" + groups = [row["scene"] for row in rows] + if len(set(groups)) < 8: + return {"status": "insufficient_data", "reason": "Need at least eight distinct source scenes for this physical-parameter probe"} + if kind not in ("rain", "blur", "haze"): + return {"status": "unsupported", "reason": "No independently varied non-dose physical target in this synthetic operator"} + if kind == "haze": + target = [row["parameters"]["airlight"] for row in rows] + target_name = "airlight RGB" + else: + angles = np.deg2rad([row["parameters"]["angle"] for row in rows]) + target = np.column_stack((np.sin(2 * angles), np.cos(2 * angles))) + target_name = "sin(2*orientation), cos(2*orientation), respecting 180-degree line symmetry" + report = _content_probe([[row["parameters"]["severity"]] for row in rows], + [row["coefficients"] for row in rows], target, groups) + report["baseline"] = "Within-type normalized physical severity (type is constant); fixed ridge alpha=1" + report["target"] = target_name + report["interpretation"] = "Held-out-scene recovery of independently varied physical parameters from the active factor coordinates beyond a severity-only baseline" + report["factor_rank"] = len(rows[0]["coefficients"]) + report["baseline_plus_factor_coefficients_mse"] = report.pop("baseline_plus_delta_mse") + report["baseline_plus_factor_coefficients_r2"] = report.pop("baseline_plus_delta_r2") + return report + + +def _mean(values): + return float(np.mean(values)) if values else None + + +def _scene_indices(dataset, count: int, seed: int) -> list[int]: + """Select distinct manifest scene groups, not many variants of one image.""" + by_scene = {} + for i, scene in enumerate(scene_component_ids(dataset.records)): + by_scene.setdefault(scene, i) + order = np.random.default_rng(seed).permutation(len(by_scene))[:count] + values = list(by_scene.values()) + return [values[int(i)] for i in order] + + +@torch.inference_mode() +def evaluate_controlled(model, manifest: str, split: str, device, batch_size=8, patch_size=128, + scenes=28, seed=42, use_edges=True, functional_enabled=True) -> dict[str, Any]: + from src.data.clean_relative import PairedDegradationDataset, sample_degradation_parameters, synthesize_composition, synthesize_degradation + + dataset = PairedDegradationDataset(manifest, split=split, crop_size=patch_size, seed=seed) + indices = _scene_indices(dataset, scenes, seed) + if not indices: + return {"status": "unsupported", "reason": "No source scenes"} + model.eval() + severity = {name: {"target": [], "prediction": [], "parameters": []} for name in TYPE_ORDER} + transfer = {name: [] for name in TYPE_ORDER} + transfer_controls = {name: {mode: [] for mode in ("blind", "zero", "shuffled_paired")} for name in TYPE_ORDER} + physical_rows = {name: [] for name in TYPE_ORDER} + drop = {name: [] for name in TYPE_ORDER} + drop_baseline = {name: [] for name in TYPE_ORDER} + mixed_result = {"heldout_pairs": [], "seen_pairs_both_orders_new_scenes": []} + hf_statistics = {name: [] for name in TYPE_ORDER} + known_uncertainty, unknown_uncertainty = [], [] + probe_baseline, probe_descriptor, probe_content, probe_groups = [], [], [], [] + single_targets, single_logits, mixed_targets, mixed_logits = [], [], [], [] + swap_differences = [] + for start in range(0, len(indices), batch_size): + current = indices[start:start + batch_size] + x_cpu = torch.stack([dataset[i]["clean"] for i in current]) + x = x_cpu.to(device) + clean_rep = model(x) + # Roll against all selected scenes, so the final batch of one still has distinct content. + other_indices = [indices[(start + i + 1) % len(indices)] for i in range(len(current))] + other_cpu = torch.stack([dataset[i]["clean"] for i in other_indices]) + other = other_cpu.to(device) + other_clean_rep = model(other) + for k, name in enumerate(TYPE_ORDER): + ys, transferred_targets, targets, params = [], [], [], [] + for j in range(len(current)): + sample_seed = seed + current[j] * 1009 + k * 29 + param = sample_degradation_parameters(name, sample_seed, heldout=True) + y, _ = synthesize_degradation(x_cpu[j], name, parameters=param, seed=sample_seed) + target, _ = synthesize_degradation(other_cpu[j], name, parameters=param, seed=sample_seed) + ys.append(y) + transferred_targets.append(target) + targets.append(float(param["severity"])) + params.append(param) + y, other_y = torch.stack(ys).to(device), torch.stack(transferred_targets).to(device) + pair = model.forward_pair(y, x) + rep = pair["student"] + severity[name]["target"].extend(targets) + severity[name]["prediction"].extend(rep["severity"][:, k].cpu().tolist()) + severity[name]["parameters"].extend(params) + for j, param in enumerate(params): + physical_rows[name].append({"scene": current[j], "parameters": param, + "coefficients": rep["coefficients"][j, k].cpu().tolist()}) + single_targets.extend([k] * len(current)) + single_logits.append(rep["presence_logits"].cpu()) + known_uncertainty.extend((1 - rep["presence_logits"].sigmoid().max(1).values).cpu().tolist()) + if len(indices) > 1: + if functional_enabled: + transferred = model.decode(other_clean_rep["content"], pair["teacher"]["delta"], x.shape[-2:]) + transfer[name].extend(functional_error(transferred, other_y, other, torch.full((len(x),), k, device=device)).cpu().tolist()) + hf_error = (residual_statistics(transferred - other)[:, 6:] - residual_statistics(other_y - other)[:, 6:]).abs().mean(1) + hf_statistics[name].extend(hf_error.cpu().tolist()) + control_codes = {"blind": rep["delta"], "zero": torch.zeros_like(rep["delta"])} + if len(x) > 1: + control_codes["shuffled_paired"] = pair["teacher"]["delta"].roll(1, 0) + for mode, code in control_codes.items(): + control = model.decode(other_clean_rep["content"], code, x.shape[-2:]) + errors = functional_error(control, other_y, other, torch.full((len(x),), k, device=device)).cpu().tolist() + if mode == "shuffled_paired": + errors = [value for j, value in enumerate(errors) if params[j] != params[(j - 1) % len(x)]] + transfer_controls[name][mode].extend(errors) + other_teacher = model.encode_pair(other_y, other) + swap_differences.extend((pair["teacher"]["coefficients"][:, :7] - other_teacher["coefficients"][:, :7]).square().flatten(1).mean(1).cpu().tolist()) + if functional_enabled: + dropped_delta = model.drop_factor(pair["teacher"]["delta"], k) + dropped = model.decode(clean_rep["content"], dropped_delta, x.shape[-2:]) + untouched = model.decode(clean_rep["content"], pair["teacher"]["delta"], x.shape[-2:]) + drop[name].extend((dropped - x).abs().flatten(1).mean(1).cpu().tolist()) + drop_baseline[name].extend((untouched - x).abs().flatten(1).mean(1).cpu().tolist()) + one_hot = np.eye(7)[k] + content = F.adaptive_avg_pool2d(x, (4, 4)).flatten(1).cpu().tolist() + for j, target in enumerate(targets): + probe_baseline.append(np.r_[one_hot, one_hot * target]) + probe_descriptor.append(rep["delta"][j].cpu().numpy()) + probe_content.append(content[j]) + probe_groups.append(current[j]) + for regime, candidate_pairs in (("heldout_pairs", HELDOUT_PAIRS), ("seen_pairs_both_orders_new_scenes", TRAIN_PAIRS[:3])): + for a, b in candidate_pairs: + ya, yb, yab, yba = [], [], [], [] + for j, index in enumerate(current): + sample_seed = seed + index * 1009 + TYPE_ORDER.index(a) * 29 + pa = sample_degradation_parameters(a, sample_seed, heldout=False) + pb = sample_degradation_parameters(b, sample_seed + 1, heldout=False) + ya.append(synthesize_degradation(x_cpu[j], a, parameters=pa, seed=sample_seed)[0]) + yb.append(synthesize_degradation(x_cpu[j], b, parameters=pb, seed=sample_seed + 1)[0]) + yab.append(synthesize_composition(x_cpu[j], (a, b), parameters=(pa, pb), seed=sample_seed)[0]) + yba.append(synthesize_composition(x_cpu[j], (b, a), parameters=(pb, pa), seed=sample_seed)[0]) + first = model.encode_pair(torch.stack(ya).to(device), x) + second = model.encode_pair(torch.stack(yb).to(device), x) + ab = model.encode_pair(torch.stack(yab).to(device), x) + ba_pair = model.forward_pair(torch.stack(yba).to(device), x) + ba = ba_pair["teacher"] + composed = model.compose(first["delta"], second["delta"], TYPE_ORDER.index(a), TYPE_ORDER.index(b), use_edges=use_edges) + reverse = model.compose(second["delta"], first["delta"], TYPE_ORDER.index(b), TYPE_ORDER.index(a), use_edges=use_edges) + additive = first["delta"] + second["delta"] + raw_target = (ab["delta"] - ba["delta"]) + result = {"pair": [a, b], "count": len(current), + "forward_latent_mse": float(F.mse_loss(composed, ab["delta"])), + "forward_additive_latent_mse": float(F.mse_loss(additive, ab["delta"])), + "reverse_latent_mse": float(F.mse_loss(reverse, ba["delta"])), + "reverse_additive_latent_mse": float(F.mse_loss(additive, ba["delta"])), + "order_difference_mse": float(F.mse_loss(composed - reverse, raw_target)), + "order_target_mean_square": float(raw_target.square().mean())} + if functional_enabled: + stochastic = a in ("rain", "noise", "snow") or b in ("rain", "noise", "snow") + error_labels = torch.full((len(x),), 1 if stochastic else TYPE_ORDER.index(a), device=device) + for direction, code, observed in (("forward", composed, torch.stack(yab).to(device)), + ("reverse", reverse, torch.stack(yba).to(device))): + decoded = model.decode(clean_rep["content"], code, x.shape[-2:]) + additive_decoded = model.decode(clean_rep["content"], additive, x.shape[-2:]) + result[direction + "_functional_error"] = float(functional_error(decoded, observed, x, error_labels).mean()) + result[direction + "_additive_functional_error"] = float(functional_error(additive_decoded, observed, x, error_labels).mean()) + result[direction + "_pixel_l1"] = float((decoded - observed).abs().mean()) + result[direction + "_additive_pixel_l1"] = float((additive_decoded - observed).abs().mean()) + result[direction + "_residual_hf_l1"] = float((residual_statistics(decoded - x)[:, 6:] - residual_statistics(observed - x)[:, 6:]).abs().mean()) + # Counterfactual removal targets are remaining operators applied to clean. + for removed, remaining, remaining_image in ((a, b, torch.stack(yb).to(device)), (b, a, torch.stack(ya).to(device))): + labels_remaining = torch.full((len(x),), TYPE_ORDER.index(remaining), device=device) + for mode, code in (("paired", ba["delta"]), ("blind", ba_pair["student"]["delta"])): + dropped = model.decode(clean_rep["content"], model.drop_factor(code, TYPE_ORDER.index(removed)), x.shape[-2:]) + untouched = model.decode(clean_rep["content"], code, x.shape[-2:]) + prefix = f"reverse_drop_{removed}_retain_{remaining}_{mode}" + result[prefix + "_error"] = float(functional_error(dropped, remaining_image, x, labels_remaining).mean()) + result[prefix + "_before_drop_error"] = float(functional_error(untouched, remaining_image, x, labels_remaining).mean()) + else: + result["external_functional_status"] = "unsupported_without_trained_proxy" + mixed_result[regime].append(result) + target = torch.zeros(len(x), 7) + target[:, TYPE_ORDER.index(a)] = target[:, TYPE_ORDER.index(b)] = 1 + mixed_targets.append(target) + mixed_logits.append(ba_pair["student"]["presence_logits"].cpu()) + # Explicit unseen operator probe; not seven-family leave-one-out training. + occluded = x.clone() + h, w = x.shape[-2:] + occluded[:, :, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.5 + unknown = model(occluded) + unknown_uncertainty.extend((1 - unknown["presence_logits"].sigmoid().max(1).values).cpu().tolist()) + target = torch.cat(mixed_targets) + probability = torch.cat(mixed_logits).sigmoid() + binary = probability > 0.5 + mixed_ap = {name: average_precision(target[:, k].numpy(), probability[:, k].numpy()) for k, name in enumerate(TYPE_ORDER)} + return { + "status": "measured", "source_split": split, "distinct_source_scenes": len(indices), "requested_scenes": scenes, + "severity_regime": "Held-out normalized physical severity range supplied by synthetic operators", + "single_classification": classification_report(torch.tensor(single_targets), torch.cat(single_logits)), + "severity": {name: {**regression_report(item["target"], item["prediction"]), "physical_parameter_examples": item["parameters"][:3], + "target_definition": "Normalized generating parameter; never inferred from real domain labels"} for name, item in severity.items()}, + "within_factor_parameter_probes": {name: physical_parameter_probe(rows, name) for name, rows in physical_rows.items()}, + "cross_content_transfer": {"status": "measured" if functional_enabled and len(indices) > 1 else "unsupported_without_trained_proxy_and_distinct_content", + "per_domain_error": {name: _mean(values) for name, values in transfer.items()}, + "paired_teacher_error": {name: _mean(values) for name, values in transfer.items()}, + "controls": {name: {mode: {"count": len(values), "error": _mean(values)} for mode, values in modes.items()} for name, modes in transfer_controls.items()}, + "shuffled_baseline": "Same factor but mismatched generating parameters within batch; skipped if no distinct donor is available", + "native_hf_residual_statistics_l1": {name: _mean(values) for name, values in hf_statistics.items()}, + "matched_parameter_coefficient_mse": _mean(swap_differences), + "metric": "RGB L1 for deterministic types; residual mean/std and gradient/Laplacian RMS L1 for rain/noise/snow", + "limitation": "Deterministic proxy cannot generate a full conditional noise distribution"}, + "factor_drop": {name: {"clean_l1_after_drop": _mean(drop[name]), "clean_l1_before_drop": _mean(drop_baseline[name])} for name in TYPE_ORDER}, + "factor_drop_interpretation": "Controlled decoder intervention test; not a real-world causal identification claim", + "mixed": {"per_batch_results": mixed_result, "exact_presence_match_at_0_5": float((binary == target.bool()).all(1).float().mean()), + "per_factor_average_precision": mixed_ap, + "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", + "external_functional_targets": "Actual synthesized forward/reverse images; mixed-node removal targets the remaining operator on clean; additive and before-drop baselines included", + "target_definition": "Latent composition targets are jointly learned; errors measure agreement, not physical identifiability", + "basis_reference_noncollapse": "Consult real representation variance and order_target_mean_square alongside latent errors"}, + "content_probe": _content_probe(probe_baseline, probe_descriptor, probe_content, probe_groups), + "unseen_operator_probe": {"operator": "central gray occlusion", "score": "1 - maximum known presence probability", + "auc": binary_auc(known_uncertainty, unknown_uncertainty), + "known_count": len(known_uncertainty), "unknown_count": len(unknown_uncertainty), + "limitation": "One controlled unseen-operator probe, not calibrated open-set recognition"}, + "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"}, + } + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--manifest", required=True) + parser.add_argument("--split", choices=("val", "test"), default="val") + parser.add_argument("--output") + parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--patch-size", type=int, default=128) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--max-records", type=int, help="Explicit cap; omitted evaluates all real split records") + parser.add_argument("--synthetic-scenes", type=int, default=28) + parser.add_argument("--skip-controlled", action="store_true") + parser.add_argument("--no-edges", action="store_true", help="Inference ablation, separately labeled from retraining without edges") + return parser + + +def main(argv: list[str] | None = None) -> dict[str, Any]: + args = build_parser().parse_args(argv) + if min(args.batch_size, args.patch_size, args.threads, args.synthetic_scenes) <= 0 or args.num_workers < 0: + raise ValueError("Invalid batch, crop, thread, synthetic scene, or worker count") + torch.set_num_threads(args.threads) + from src.models.graph_encoder.clean_relative import CleanRelativeConfig, CleanRelativeGraphEncoder + + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + config = CleanRelativeConfig(**checkpoint["model_config"]) + device = torch.device(args.device) + model = CleanRelativeGraphEncoder(config).to(device) + model.load_state_dict(checkpoint["model"]) + report = {"checkpoint": str(Path(args.checkpoint).resolve()), "checkpoint_sha256": file_digest(args.checkpoint), + "checkpoint_step": checkpoint["global_step"], "training_scope": checkpoint["run_config"]["scope"], + "manifest_sha256": file_digest(args.manifest), "arguments": vars(args), + "real": evaluate_real(model, args.manifest, args.split, device, args.batch_size, args.patch_size, + args.num_workers, args.max_records, args.seed, + functional_enabled=not checkpoint["run_config"]["arguments"].get("no_proxy", False))} + if not args.skip_controlled: + report["controlled"] = evaluate_controlled(model, args.manifest, args.split, device, min(args.batch_size, 8), + args.patch_size, args.synthetic_scenes, args.seed, + use_edges=not args.no_edges and not checkpoint["run_config"]["arguments"]["no_edges"], + functional_enabled=not checkpoint["run_config"]["arguments"].get("no_proxy", False)) + else: + report["controlled"] = {"status": "explicitly_skipped"} + output = Path(args.output) if args.output else Path(args.checkpoint).parent / f"evaluation_{args.split}_{Path(args.checkpoint).stem}.json" + atomic_json_save(report, output) + print(json.dumps({"output": str(output), "real": report["real"]}), flush=True) + return report + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/eval_pipeline_external.py b/dataset/phase1_noise_20260906/code/eval_pipeline_external.py new file mode 100644 index 0000000000000000000000000000000000000000..bad48e762c3caff563a4b8fcf88330ff3416254c --- /dev/null +++ b/dataset/phase1_noise_20260906/code/eval_pipeline_external.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Held-out evaluation of pipeline A on data Phase 2 never touched. + +Sources: + rain_locked Rain13K Test100+Test1200 (Phase-1 locked test, 1.200 pairs) + noise_locked SIDD scene 008 (locked, 20 pairs) + haze_heldout RESIDE hazy images beyond the first-5000 training window, + filtered so no clean source overlaps train/val groups. + +Center-crop 256 protocol, record-keyed noise, PSNR/SSIM/LPIPS for both the +one-step regression and the refined output. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Sequence + +import torch +from torch.utils.data import DataLoader, Dataset + +import infer_scdc_pipeline as pipe +import train_phase2_graph_resshift_v4 as v4 +import train_graph_encoder_v2 as p1 + + +class PairCropDataset(Dataset): + def __init__(self, records: Sequence, size: int = 256) -> None: + self.records = list(records) + self.size = size + + def __len__(self) -> int: + return len(self.records) + + def __getitem__(self, index: int): + record = self.records[index] + degraded, clean = p1.load_pair_uint8(record, self.size) + # Whole-frame view (aspect-squashed) for global-context models. + full = p1._open_rgb(record.degraded).resize((self.size, self.size)) + return { + "degraded": p1._pil_to_tensor(degraded), + "clean": p1._pil_to_tensor(clean), + "full_degraded": p1._pil_to_tensor(full), + "record_id": record.record_id, + } + + +def evaluate_group( + pipeline: "pipe.SCDCPipeline", records: Sequence, name: str, lpips_fn +) -> Dict[str, object]: + loader = DataLoader( + PairCropDataset(records), batch_size=8, shuffle=False, num_workers=4 + ) + acc: Dict[str, Dict[str, List[float]]] = {} + with torch.no_grad(): + for batch in loader: + clean = batch["clean"].to(pipeline.device) + extra = {} + if "full_degraded" in batch and getattr(pipeline, "accepts_full_frame", False): + extra["full_degraded"] = batch["full_degraded"] + result = pipeline.restore( + batch["degraded"], + record_ids=[str(v) for v in batch["record_id"]], + seed=int(pipeline.args.eval_seed), + **extra, + ) + for kind in ("x0_hat", "restored"): + slot = acc.setdefault( + kind, {"psnr": [], "ssim": [], "lpips": []} + ) + slot["psnr"] += v4.rgb_psnr_per_image( + result[kind], clean + ).cpu().tolist() + slot["ssim"] += v4.rgb_ssim_per_image( + result[kind], clean + ).cpu().tolist() + slot["lpips"] += lpips_fn( + result[kind] * 2 - 1, clean * 2 - 1 + ).flatten().cpu().tolist() + report = {"n": len(records)} + for kind, values in acc.items(): + report[kind] = { + metric: sum(items) / len(items) for metric, items in values.items() + } + print(name, json.dumps(report, sort_keys=True), flush=True) + return report + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--refiner", type=Path, + default=Path("outputs/refiner_a_v1/refiner_best.pt"), + ) + parser.add_argument( + "--output", type=Path, + default=Path("outputs/pipeline_eval_external_v1.json"), + ) + parser.add_argument("--haze-count", type=int, default=300) + args = parser.parse_args() + + device = torch.device("cuda") + pipeline = pipe.SCDCPipeline(args.refiner, device, sample_steps=1) + + import lpips + + lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device) + + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rain_locked = [r for r in splits.locked_test if r.degradation == "rain"] + noise_locked = [r for r in splits.locked_test if r.degradation == "noise"] + + # Held-out RESIDE: everything past the training window, minus any record + # whose clean source group appears in train or val. + reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE") + used_groups = { + r.split_group for r in list(splits.train) + list(splits.val) + if r.degradation == "haze" + } + haze_heldout = [ + r for r in reside[5000:] if r.split_group not in used_groups + ][: args.haze_count] + + report = { + "rain_locked_test100_1200": evaluate_group( + pipeline, rain_locked, "rain_locked", lpips_fn + ), + "noise_locked_sidd_scene008": evaluate_group( + pipeline, noise_locked, "noise_locked", lpips_fn + ), + "haze_heldout_reside": evaluate_group( + pipeline, haze_heldout, "haze_heldout", lpips_fn + ), + } + args.output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE", args.output, flush=True) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/eval_v7_external.py b/dataset/phase1_noise_20260906/code/eval_v7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..87272076003c60e66ae14198f9e557fb3c647152 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/eval_v7_external.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""External held-out evaluation of a pure v7 checkpoint (no refiner). + +Reuses the gen-2 external protocol verbatim (same locked rain/noise sets, +same RESIDE held-out selection, same crops/metrics via +``eval_pipeline_external.evaluate_group``) so numbers are directly +comparable with ``outputs/gen2_external_v1.json``. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_moe_v6 as v6 +import train_phase2_graph_resshift_v4 as v4 +from visualize_v7_uformer import _load_run_args + + +class V7Pipeline: + def __init__( + self, run_dir: Path, device: torch.device, dose: float = None, + photometric_dose: float = None, checkpoint: str = "best.pt", + pregain_dose: float = None, colour_dose: float = None, + ) -> None: + import train_phase2_unified_v7 as v7 + + self.device = device + self.dose = dose + self.pregain_dose = pregain_dose + self.colour_dose = colour_dose + self.photometric_dose = photometric_dose + self.args = _load_run_args(run_dir) + # Any checkpoint of the run (best.pt, last.pt, milestone_%08d.pt): the + # val-macro selector behind best.pt is known to be a poor proxy for + # the external sets, so milestones/last are evaluated too. + self.checkpoint_name = str(checkpoint) + checkpoint = v4._torch_load(run_dir / self.checkpoint_name, map_location="cpu") + self.model = v7._build_v7_restorer(self.args, device) + self.model.load_state_dict( + checkpoint["ema_state_dict"]["shadow"], strict=True + ) + self.model.eval() + self.phase1, _ = v4.build_frozen_phase1( + self.args.phase1_checkpoint, self.args.phase1_sha256, device + ) + self.checkpoint_step = int(checkpoint["step"]) + print("v7 checkpoint %s step: %d" % (self.checkpoint_name, self.checkpoint_step)) + + accepts_full_frame = True + + @torch.no_grad() + def restore(self, degraded, record_ids=None, seed=20260830, full_degraded=None): + import train_phase2_unified_v7 as v7 + + degraded = degraded.to(self.device) + restored = v7.sample_unified_restoration( + self.model, self.phase1, degraded, + seed=int(seed), record_ids=[str(r) for r in record_ids], + dose=self.dose, + pregain_dose=self.pregain_dose, + colour_dose=self.colour_dose, + full_degraded=None if full_degraded is None else full_degraded.to(self.device), + photometric_dose=self.photometric_dose, + ) + # No refiner stage: the diffusion output IS the pipeline output. + return {"x0_hat": restored, "restored": restored} + + +def degraded_baseline(records, device) -> dict: + from torch.utils.data import DataLoader + + loader = DataLoader( + ext.PairCropDataset(records), batch_size=16, shuffle=False, num_workers=4 + ) + psnr, ssim = [], [] + for batch in loader: + clean = batch["clean"].to(device) + degraded = batch["degraded"].to(device) + psnr += v4.rgb_psnr_per_image(degraded, clean).cpu().tolist() + ssim += v4.rgb_ssim_per_image(degraded, clean).cpu().tolist() + return { + "psnr": sum(psnr) / len(psnr), + "ssim": sum(ssim) / len(ssim), + } + + +def main() -> None: + import lpips + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--run-dir", type=Path, + default=Path("outputs/phase2_v7/uformer_luma8k_seed42"), + ) + parser.add_argument( + "--output", type=Path, default=Path("outputs/v7_external_v1.json") + ) + parser.add_argument( + "--dose", type=float, default=None, + help="DGF guidance dose at the coarse step (None = plain conditioned)", + ) + parser.add_argument( + "--photometric-dose", type=float, default=None, + help="scale of the v8 global exposure head deltas (None = 1.0; 0 = off)", + ) + parser.add_argument("--checkpoint", default="best.pt", help="file inside --run-dir to evaluate") + args = parser.parse_args() + + device = torch.device("cuda") + pipeline = V7Pipeline(args.run_dir, device, dose=args.dose, photometric_dose=args.photometric_dose, + checkpoint=args.checkpoint) + lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device) + + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rain = [r for r in splits.locked_test if r.degradation == "rain"] + noise = [r for r in splits.locked_test if r.degradation == "noise"] + reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE") + used = { + r.split_group + for r in list(splits.train) + list(splits.val) + if r.degradation == "haze" + } + haze = [r for r in reside[5000:] if r.split_group not in used][:300] + + report = {"run_dir": str(args.run_dir), "dose": args.dose, "photometric_dose": args.photometric_dose, + "checkpoint": pipeline.checkpoint_name, "checkpoint_step": pipeline.checkpoint_step} + for name, records in ( + ("rain_locked", rain), + ("noise_locked_scene008", noise), + ("haze_heldout", haze), + ): + group = ext.evaluate_group(pipeline, records, name, lpips_fn) + group["degraded_baseline"] = degraded_baseline(records, device) + report[name] = group + args.output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/gate_phase1.sh b/dataset/phase1_noise_20260906/code/gate_phase1.sh new file mode 100644 index 0000000000000000000000000000000000000000..c786cb281cd0f28f1982e5c59c345243eaf2cc37 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/gate_phase1.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -u; cd /home/admin_mcn/scdc_ban; PY=/home/admin_mcn/anaconda3/bin/python +gate_for() { # $1 = run name ; writes outputs/$1_gate.json ; prints pass/score + local name=$1 ckpt=outputs/$1/graph_encoder_best.pt + CUDA_VISIBLE_DEVICES=0 $PY visualize_phase1_graph.py --checkpoint $ckpt --output-dir outputs/phase1_vis/$name > outputs/phase1_vis_$name.log 2>&1 + CAND=$name CUDA_VISIBLE_DEVICES=0 $PY - <<'PYEOF' > outputs/${name}_gate.log 2>&1 +import glob, hashlib, json, math, os, torch, numpy as np +from pathlib import Path +from PIL import Image +import train_phase2_graph_resshift_v4 as v4 +from visualize_phase1_graph import encode, NODES +name = os.environ["CAND"] +files = sorted(glob.glob("/home/admin_mcn/data/Snow100K/realistic/**/*.jpg", recursive=True)) +def load(f): + im = Image.open(f).convert("RGB"); w, h = im.size; s = 256 / min(w, h) + if s > 1: im = im.resize((max(256, math.ceil(w * s)), max(256, math.ceil(h * s))), Image.LANCZOS); w, h = im.size + l, t = (w - 256) // 2, (h - 256) // 2 + return torch.from_numpy(np.asarray(im.crop((l, t, l + 256, t + 256)), dtype=np.float32) / 255.).permute(2, 0, 1) +imgs = torch.stack([load(f) for f in files]) +ck = Path("outputs/%s/graph_encoder_best.pt" % name) +p1, _ = v4.build_frozen_phase1(ck, hashlib.sha256(ck.read_bytes()).hexdigest(), torch.device("cuda")) +enc = encode(p1, imgs.cuda()) +route = dict(zip(NODES, enc["routing"].mean(0).tolist())) +summary = json.load(open("outputs/phase1_vis/%s/summary.json" % name)) +conf = summary["confusion"] +row = lambda prefix: next(v for k, v in conf.items() if k.startswith(prefix)) +hist = json.load(open("outputs/%s/history.json" % name)) +best_f1 = max(e["val"].get("macro_f1", 0.0) for e in hist if "val" in e) +gates = { + "snow_real_free": (route["free1"] + route["free2"], 0.70, ">="), + # not worse than ll_v3 (0.46 haze->rain on the same val); the +0.3 dB + # claim for v8 does not depend on Phase-1 routing improving, only on it + # not regressing and on photometric_state existing. + "haze_to_rain_max": (row("Haze input")["rain"], 0.46, "<="), + "rain_to_rain_min": (row("Rain input")["rain"], 0.55, ">="), + "lowlight_to_lowlight_min": (row("Low-light input")["lowlight"], 0.85, ">="), +} +passed = {k: (v[0] >= v[1] if v[2] == ">=" else v[0] <= v[1]) for k, v in gates.items()} +report = {"candidate": name, "sha256": hashlib.sha256(ck.read_bytes()).hexdigest(), "snow_real_routing": route, + "gates": {k: {"value": v[0], "threshold": v[1], "pass": passed[k]} for k, v in gates.items()}, + "n_pass": int(sum(passed.values())), "pass": bool(all(passed.values())), "best_val_macro_f1": best_f1, + "noise_recall": row("Noise input")["noise"]} +Path("outputs/%s_gate.json" % name).write_text(json.dumps(report, indent=2)) +print(json.dumps(report)) +PYEOF + $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']))" +} +gate_for $1 diff --git a/dataset/phase1_noise_20260906/code/hf_bundle_upload.py b/dataset/phase1_noise_20260906/code/hf_bundle_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f668e93a25d0506d206e05209a6580f44c430e --- /dev/null +++ b/dataset/phase1_noise_20260906/code/hf_bundle_upload.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Bundle exactly the data this project trains/evaluates on and upload it to +a Hugging Face dataset repo. + +Contents (all paths inside the tars are relative to two roots, recorded in +manifests/path_roots.json so the absolute paths in the manifests can be +rewritten on another machine): + Rain13K.tar every Rain13K file referenced by the Phase-1 splits + (train / val / locked test) and the Phase-2 manifest + RESIDE_used.tar the RESIDE hazy/clear files used in training/val plus + the 300 held-out evaluation scenes + LOLv2.tar LOLv2-real (train + test), as extracted + SIDD_Small.tar SIDD Small sRGB (all 160 scenes; 121 train / 19 val / + 20 locked scene 008) + Snow100K_gt.tar, Snow100K_synthetic.tar the clean pool and the real-OOD + pool used by Phase-1 v5 / Phase-2 identity pairs + manifests/ Phase-2 train/val manifest, quarantine list, file lists + per split, path roots, README +Token: HF_TOKEN environment variable only (never written to disk here). +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +HOME = Path("/home/admin_mcn") +ROOTS = { # absolute prefix -> archive prefix + str(HOME / "data") + "/": "data/", + str(HOME / ".cache" / "kagglehub") + "/": "kagglehub/", +} +REPO = "Anbinh93/image_restoration" + + +def relative(path: str) -> str: + for prefix, target in ROOTS.items(): + if path.startswith(prefix): + return target + path[len(prefix):] + raise ValueError("file outside the known roots: %s" % path) + + +def collect() -> dict: + sys.path.insert(0, str(HOME / "scdc_ban")) + import train_graph_encoder_v2 as p1 + import eval_full_frame as ff + + groups = ff.external_groups(300) + args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(args) + manifest = json.load(open(HOME / "scdc_ban/outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + lists: dict = {} + + def add(name, records): + files = set() + for r in records: + files.add(str(r.degraded)); files.add(str(r.clean)) + lists[name] = sorted(files) + + add("phase1_train", splits.train); add("phase1_val", splits.val); add("phase1_locked_test", splits.locked_test) + add("haze_heldout_300", groups["haze_heldout"]) + m = set() + for key in ("train", "val"): + for r in manifest[key]: + for f in ("degraded", "clean"): + if f in r: + m.add(str(r[f])) + lists["phase2_manifest"] = sorted(m) + return lists + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--staging", type=Path, default=HOME / "hf_staging/image_restoration") + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--skip-tar", action="store_true", help="tars already built; only upload") + args = parser.parse_args() + staging = args.staging + (staging / "manifests").mkdir(parents=True, exist_ok=True) + + lists = collect() + every = set() + for files in lists.values(): + every.update(files) + by_dataset = {"Rain13K": [], "RESIDE_used": [], "LOLv2": [], "SIDD_Small": []} + for f in sorted(every): + if "kagglehub" in f or "rain13k" in f.lower(): + by_dataset["Rain13K"].append(f) + elif "/RESIDE/" in f: + by_dataset["RESIDE_used"].append(f) + elif "/LOLv2/" in f: + by_dataset["LOLv2"].append(f) + elif "/SIDD/" in f: + by_dataset["SIDD_Small"].append(f) + else: + raise SystemExit("unclassified file: %s" % f) + # whole folders for the pools and the small datasets (LOLv2 / SIDD complete) + folders = { + "LOLv2": str(HOME / "data/LOLv2/lolv2_hf"), + "SIDD_Small": str(HOME / "data/SIDD/SIDD_Small_sRGB_Only"), + "Snow100K_gt": str(HOME / "data/Snow100K/train/all/gt"), + "Snow100K_synthetic": str(HOME / "data/Snow100K/train/all/synthetic"), + } + summary = {} + for name, files in by_dataset.items(): + size = sum(os.path.getsize(f) for f in files if os.path.exists(f)) + summary[name] = {"files": len(files), "bytes": size} + for name, folder in folders.items(): + total = sum(p.stat().st_size for p in Path(folder).rglob("*") if p.is_file()) + summary[name + "(folder)"] = {"bytes": total} + print("SUMMARY", json.dumps(summary), flush=True) + for name, files in lists.items(): + (staging / "manifests" / ("%s_files.txt" % name)).write_text("\n".join(relative(f) for f in files) + "\n") + (staging / "manifests" / "path_roots.json").write_text(json.dumps(ROOTS, indent=2)) + for src in (HOME / "scdc_ban/outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json", + HOME / "scdc_ban/src/data/rain13k_quarantine_v1.json"): + if src.exists(): + (staging / "manifests" / src.name).write_text(src.read_text()) + (staging / "README.md").write_text(README) + if args.dry_run: + return + + def tar(name: str, entries: list, listfile: bool) -> None: + out = staging / ("%s.tar" % name) + if out.exists() and args.skip_tar: + return + cmd = ["tar", "-cf", str(out), "-C", str(HOME), + "--transform", "s|^\\.cache/kagglehub/|kagglehub/|"] + if listfile: + lst = staging / "manifests" / ("_%s.lst" % name) + lst.write_text("\n".join(os.path.relpath(f, HOME) for f in entries) + "\n") + cmd += ["-T", str(lst)] + else: + cmd += [os.path.relpath(entries[0], HOME)] + t0 = time.time() + subprocess.run(cmd, check=True) + print("TAR %s %.2f GB in %.0fs" % (name, out.stat().st_size / 2**30, time.time() - t0), flush=True) + + tar("Rain13K", by_dataset["Rain13K"], True) + tar("RESIDE_used", by_dataset["RESIDE_used"], True) + for name, folder in folders.items(): + tar(name, [folder], False) + for lst in (staging / "manifests").glob("_*.lst"): + lst.unlink() + + from huggingface_hub import HfApi + + token = os.environ.get("HF_TOKEN") + if not token: + raise SystemExit("HF_TOKEN is not set") + api = HfApi(token=token) + api.create_repo(REPO, repo_type="dataset", exist_ok=True) + t0 = time.time() + api.upload_large_folder(repo_id=REPO, repo_type="dataset", folder_path=str(staging), + num_workers=4, print_report_every=60) + print("UPLOAD done in %.0f min -> https://huggingface.co/datasets/%s" % ((time.time() - t0) / 60, REPO), flush=True) + + +README = """--- +license: other +task_categories: [image-to-image] +tags: [image-restoration, deraining, dehazing, denoising, low-light] +--- +# SCDC image restoration data bundle + +Exactly the files used by the SCDC project (blind degradation graph encoder + +unified two-step ResShift restorer): https://github.com/anbinh93/SCDC + +| Archive | Content | +|---|---| +| `Rain13K.tar` | Rain13K pairs referenced by the Phase-1 splits (train / val / locked Test100+Test1200) and the Phase-2 manifest | +| `RESIDE_used.tar` | RESIDE hazy/clear files used for training/validation plus the 300 held-out evaluation scenes | +| `LOLv2.tar` | LOLv2-real, train (689) + test (100) | +| `SIDD_Small.tar` | SIDD Small sRGB, all 160 scenes (121 train / 19 val / 20 locked = scene 008) | +| `Snow100K_gt.tar`, `Snow100K_synthetic.tar` | Snow100K training gt (clean pool) and synthetic snow (real-unknown pool) | +| `manifests/` | `train_val_manifest_v1.json` (Phase-2 train/val, sha digests), `rain13k_quarantine_v1.json`, per-split file lists, `path_roots.json` | + +Paths inside the archives are relative to two roots (see `manifests/path_roots.json`): +`/home/admin_mcn/data/` -> `data/` and `/home/admin_mcn/.cache/kagglehub/` -> `kagglehub/`. +To reuse the manifests on another machine, extract everything under one directory +and rewrite the two absolute prefixes in the JSON files to that directory. + +All datasets belong to their original authors and keep their original licenses +(research use): Rain13K (Jiang et al. / MPRNet compilation), RESIDE (Li et al.), +LOLv2 (Yang et al.), SIDD (Abdelhamed et al.), Snow100K (Liu et al.). +""" + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/infer_scdc_pipeline.py b/dataset/phase1_noise_20260906/code/infer_scdc_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..97cfdece9e614990d8a623bf06c069088cc1149b --- /dev/null +++ b/dataset/phase1_noise_20260906/code/infer_scdc_pipeline.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +"""Complete SCDC inference pipeline (option A, two-stage). + + degraded -> frozen Phase-1 -> diffusion U-Net (1-step x0 by default, + optional k-step chain) -> refiner decoder -> restored image + +Usage: + # per-domain evaluation on the locked val split + python infer_scdc_pipeline.py --refiner outputs/refiner_a_v1/refiner_best.pt --eval + + # restore arbitrary images from a directory + python infer_scdc_pipeline.py --refiner ... --images in_dir --output out_dir +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, Optional, Sequence + +import torch +from torch import Tensor +from torch.utils.data import DataLoader + +import train_phase2_graph_resshift_v4 as v4 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from src.models.restoration.refiner_decoder import RefinerDecoder + +V4_RUN = Path("outputs/phase2_graph_resshift_v4/gate_d5_seed42") + + +class SCDCPipeline: + """Frozen Phase-1 + frozen one-step regressor + refiner decoder.""" + + def __init__( + self, + refiner_checkpoint: Optional[Path], + device: torch.device, + sample_steps: int = 1, + ) -> None: + if sample_steps < 1: + raise ValueError("sample_steps must be >= 1") + self.device = device + self.sample_steps = int(sample_steps) + cfg = json.loads((V4_RUN / "run_config.json").read_text()) + args = argparse.Namespace(**cfg) + for key in ("manifest", "data_root", "phase1_checkpoint"): + setattr(args, key, Path(str(getattr(args, key)))) + self.args = args + self.regressor = v4._build_restorer(args, device) + checkpoint = v4._torch_load(V4_RUN / "best.pt") + self.regressor.load_state_dict( + checkpoint["ema_state_dict"]["shadow"], strict=True + ) + self.regressor.eval() + for parameter in self.regressor.parameters(): + parameter.requires_grad_(False) + self.phase1, _ = v4.build_frozen_phase1( + args.phase1_checkpoint, args.phase1_sha256, device + ) + self.refiner: Optional[RefinerDecoder] = None + if refiner_checkpoint is not None: + state = torch.load(str(refiner_checkpoint), map_location="cpu") + refiner = RefinerDecoder() + refiner.load_state_dict(state["refiner_state_dict"], strict=True) + self.refiner = refiner.to(device).eval() + + @torch.no_grad() + def regress_x0( + self, degraded: Tensor, record_ids: Optional[Sequence[str]], seed: int + ) -> Tensor: + if self.sample_steps > 1: + return v4.sample_restoration( + self.regressor, self.phase1, degraded, + seed=seed, record_ids=list(record_ids) if record_ids else None, + ) + padded, size = v4.pad_to_multiple(degraded, multiple=16) + representation = self.phase1(padded) + condition = self.regressor.build_condition(representation) + uy = v4.pixel_unshuffle2(padded) + noise = v4._noise_for_records( + uy, list(record_ids) if record_ids else None, seed=seed, stage="initial" + ) + eta_terminal = self.regressor.schedule.eta[-1].to(uy.device, uy.dtype) + kappa = self.regressor.schedule.kappa.to(uy.device, uy.dtype) + u_terminal = uy + kappa * torch.sqrt(eta_terminal) * noise + timesteps = torch.full( + (uy.shape[0],), self.regressor.schedule.timesteps, + device=uy.device, dtype=torch.long, + ) + u0_hat = self.regressor.predict_x0(u_terminal, uy, timesteps, condition) + out = v4.pixel_shuffle2(u0_hat) + height, width = size + return out[..., :height, :width].clamp(0.0, 1.0) + + @torch.no_grad() + def restore( + self, + degraded: Tensor, + record_ids: Optional[Sequence[str]] = None, + seed: int = 20260830, + ) -> Dict[str, Tensor]: + degraded = degraded.to(self.device) + x0_hat = self.regress_x0(degraded, record_ids, seed) + if self.refiner is None: + return {"x0_hat": x0_hat, "restored": x0_hat} + padded_x0, size = v4.pad_to_multiple(x0_hat, multiple=4) + padded_y, _ = v4.pad_to_multiple(degraded, multiple=4) + refined = self.refiner(padded_x0, padded_y) + height, width = size + return {"x0_hat": x0_hat, "restored": refined[..., :height, :width]} + + +def run_eval(pipeline: SCDCPipeline, output: Path) -> None: + splits = load_train_val_manifest(pipeline.args.manifest) + loader = DataLoader( + Phase2PairDataset(splits.val, crop_size=256, training=False, + upscale_small=True), + batch_size=8, shuffle=False, num_workers=4, + ) + acc: Dict[str, Dict[str, list]] = {} + for batch in loader: + clean = batch["clean"].to(pipeline.device) + result = pipeline.restore( + batch["degraded"], + record_ids=[str(v) for v in batch["record_id"]], + seed=int(pipeline.args.eval_seed), + ) + for name in ("x0_hat", "restored"): + psnr = v4.rgb_psnr_per_image(result[name], clean).cpu().tolist() + ssim = v4.rgb_ssim_per_image(result[name], clean).cpu().tolist() + for domain, p, s in zip( + [str(v) for v in batch["degradation"]], psnr, ssim + ): + slot = acc.setdefault(name, {}).setdefault( + domain, {"psnr": [], "ssim": []} + ) + slot["psnr"].append(p) + slot["ssim"].append(s) + report: Dict[str, object] = {"sample_steps": pipeline.sample_steps} + for name, domains in acc.items(): + block = {} + for domain, values in sorted(domains.items()): + block[domain] = { + "psnr": sum(values["psnr"]) / len(values["psnr"]), + "ssim": sum(values["ssim"]) / len(values["ssim"]), + "count": len(values["psnr"]), + } + block["macro_psnr"] = sum(v["psnr"] for v in block.values()) / len(block) + block["macro_ssim"] = sum( + v["ssim"] for v in block.values() if isinstance(v, dict) + ) / len([v for v in block.values() if isinstance(v, dict)]) + report[name] = block + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print(json.dumps(report, indent=2, sort_keys=True)) + + +def run_images(pipeline: SCDCPipeline, images: Path, output: Path) -> None: + from PIL import Image + import numpy as np + + output.mkdir(parents=True, exist_ok=True) + paths = sorted( + p for p in images.iterdir() + if p.suffix.lower() in (".png", ".jpg", ".jpeg", ".bmp") + ) + for path in paths: + array = np.asarray( + Image.open(path).convert("RGB"), dtype=np.float32 + ) / 255.0 + tensor = torch.from_numpy(array).permute(2, 0, 1).unsqueeze(0) + restored = pipeline.restore(tensor)["restored"][0] + out = (restored.clamp(0, 1).cpu().permute(1, 2, 0).numpy() * 255).astype( + "uint8" + ) + Image.fromarray(out).save(output / path.name) + print("restored", path.name, flush=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--refiner", type=Path, default=None) + parser.add_argument("--sample-steps", type=int, default=1) + parser.add_argument("--eval", action="store_true") + parser.add_argument("--images", type=Path, default=None) + parser.add_argument("--output", type=Path, + default=Path("outputs/pipeline_eval.json")) + args = parser.parse_args() + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + pipeline = SCDCPipeline(args.refiner, device, sample_steps=args.sample_steps) + if args.eval: + run_eval(pipeline, args.output) + if args.images is not None: + run_images(pipeline, args.images, args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/make_final_charts.py b/dataset/phase1_noise_20260906/code/make_final_charts.py new file mode 100644 index 0000000000000000000000000000000000000000..3c7c77de6d2c8493ffd117d5fdb05e99f1c3143d --- /dev/null +++ b/dataset/phase1_noise_20260906/code/make_final_charts.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Static slide charts for the SCDC final report (matplotlib, light surface). + +Palette: validated categorical slots (blue, orange, aqua, yellow) in fixed +order; text in ink tokens; thin marks; recessive grid; no dual axes. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +SURFACE = "#fcfcfb" +INK = "#0b0b0b" +INK2 = "#52514e" +GRID = "#e6e5e1" +C = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"] # fixed categorical order +NEUTRAL = "#b9b8b3" + + +def _style(ax, title, xlabel=""): + ax.set_facecolor(SURFACE) + for side in ("top", "right", "left"): + ax.spines[side].set_visible(False) + ax.spines["bottom"].set_color(GRID) + ax.tick_params(colors=INK2, length=0) + ax.grid(axis="x", color=GRID, linewidth=0.8) + ax.set_axisbelow(True) + ax.set_title(title, loc="left", color=INK, fontsize=12, fontweight="semibold") + if xlabel: + ax.set_xlabel(xlabel, color=INK2) + + +def chart_progression(out: Path) -> None: + rows = [ + ("v4 ResShift 1-step (conv, 8-step train)", 22.68, 0.662, NEUTRAL), + ("v7 unified 2-step (conv, warm-start)", 23.41, 0.703, NEUTRAL), + ("v7 Uformer, from scratch 8k", 25.26, 0.777, C[0]), + ("+ chroma loss, warm-restart 16k", 26.44, 0.808, C[0]), + ("+ luma loss, 8k", 26.59, 0.811, C[0]), + ("+ full-res head + FiLM, 8k", 27.43, 0.846, C[0]), + ("+ DGF (null tokens, identity, pyramid), 8k", 27.50, 0.850, C[0]), + ("ref: Pipeline A (2 networks)", 26.76, 0.863, C[1]), + ("ref: gen-2 (2 networks)", 27.55, 0.874, C[1]), + ] + fig, ax = plt.subplots(figsize=(10, 5.2), facecolor=SURFACE) + names = [r[0] for r in rows][::-1] + vals = [r[1] for r in rows][::-1] + cols = [r[3] for r in rows][::-1] + ssim = [r[2] for r in rows][::-1] + import numpy as np + pos = np.arange(len(names)) + bars = ax.barh(pos, vals, color=cols, height=0.62, align="center") + ax.set_yticks(pos) + ax.set_yticklabels(names, color=INK, fontsize=9) + for y, v, s in zip(pos, vals, ssim): + ax.text(v + 0.06, y, "%.2f dB · SSIM %.3f" % (v, s), + va="center", ha="left", color=INK, fontsize=9) + ax.set_xlim(22, 28.6) + _style(ax, "Internal validation: macro PSNR by version\n(one network in blue, two-network references in orange)", "PSNR (dB)") + fig.tight_layout() + fig.savefig(str(out), dpi=160, facecolor=SURFACE) + plt.close(fig) + + +def chart_external(out: Path) -> None: + sets = ["Rain (locked, 1200)", "Haze (held-out, 300)", "Noise scene008 (20)"] + series = [ + ("Degraded input", [22.56, 18.17, 39.02], NEUTRAL), + ("gen-2, two networks", [26.71, 31.18, 22.35], C[1]), + ("head8k, one network", [28.02, 31.71, 27.09], C[0]), + ("DGF (w=1), one network", [27.88, 31.87, 26.50], C[2]), + ] + fig, ax = plt.subplots(figsize=(10, 4.6), facecolor=SURFACE) + import numpy as np + x = np.arange(len(sets)) + w = 0.19 + for i, (label, vals, col) in enumerate(series): + bars = ax.bar(x + (i - 1.5) * w, vals, width=w - 0.02, color=col, label=label) + for b, v in zip(bars, vals): + ax.text(b.get_x() + b.get_width() / 2, v + 0.4, "%.1f" % v, ha="center", va="bottom", color=INK, fontsize=8) + ax.set_xticks(x) + ax.set_xticklabels(sets, color=INK) + ax.set_ylim(15, 42) + ax.grid(axis="y", color=GRID, linewidth=0.8) + ax.grid(False, axis="x") + _style(ax, "External held-out PSNR\n(one network beats the two-network pipeline out of distribution)", "") + ax.set_ylabel("PSNR (dB)", color=INK2) + ax.legend(frameon=False, ncol=2, loc="upper center", fontsize=9) + fig.tight_layout() + fig.savefig(str(out), dpi=160, facecolor=SURFACE) + plt.close(fig) + + +def chart_probe(out: Path) -> None: + rows = [ + ("context (cross-attention tokens)", -3.68), + ("global_vector (adaLN)", -3.45), + ("unknown_residual (field)", -0.74), + ("global_condition (field)", -0.24), + ("node_tokens (field)", -0.16), + ("MoE gate + per-type κ (uniform)", -0.085), + ("routing_probs (field)", -0.05), + ("severity_coords (field)", -0.03), + ("spatial maps 16×16 (inject)", -0.01), + ("content latent 64 px (inject)", 0.00), + ] + fig, ax = plt.subplots(figsize=(10, 4.8), facecolor=SURFACE) + names = [r[0] for r in rows][::-1] + vals = [r[1] for r in rows][::-1] + cols = [C[0] if v < -1 else (C[3] if v < -0.1 else NEUTRAL) for v in vals] + import numpy as np + pos = np.arange(len(names)) + ax.barh(pos, vals, color=cols, height=0.62, align="center") + ax.set_yticks(pos) + ax.set_yticklabels(names, color=INK, fontsize=9) + for y, v in zip(pos, vals): + if v < -0.3: + ax.text(v - 0.05, y, "%+.2f dB" % v, va="center", ha="right", color=INK, fontsize=9) + else: + ax.text(0.06, y, "%+.2f dB" % v, va="center", ha="left", color=INK, fontsize=9) + ax.set_xlim(-4.2, 0.6) + _style(ax, "Inference-time ablation (head8k)\nmacro PSNR change when one Phase-1 tap is removed", "Δ macro PSNR (dB)") + fig.tight_layout() + fig.savefig(str(out), dpi=160, facecolor=SURFACE) + plt.close(fig) + + +def chart_control(out: Path, control: dict, conditioned: dict) -> None: + steps = sorted(set(control) & set(conditioned)) + fig, ax = plt.subplots(figsize=(10, 4.4), facecolor=SURFACE) + 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)") + 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)") + for s in (steps[-1],): + ax.text(s - 120, conditioned[s] + 0.12, "%.2f" % conditioned[s], color=INK, fontsize=9, ha="right") + ax.text(s - 120, control[s] - 0.3, "%.2f" % control[s], color=INK, fontsize=9, ha="right") + ax.set_xlabel("fine-tune step", color=INK2) + ax.set_ylabel("macro PSNR (dB)", color=INK2) + ax.grid(axis="y", color=GRID, linewidth=0.8) + ax.grid(False, axis="x") + _style(ax, "Does the trunk need Phase-1?\n(same recipe and warm start; conditioning on vs. off)", "") + ax.legend(frameon=False, loc="lower right", fontsize=9) + fig.tight_layout() + fig.savefig(str(out), dpi=160, facecolor=SURFACE) + plt.close(fig) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out-dir", type=Path, default=Path("outputs/final_charts")) + parser.add_argument("--control-metrics", type=Path, default=None) + parser.add_argument("--conditioned-metrics", type=Path, default=None) + args = parser.parse_args() + args.out_dir.mkdir(parents=True, exist_ok=True) + chart_progression(args.out_dir / "01_version_progression.png") + chart_external(args.out_dir / "02_external.png") + chart_probe(args.out_dir / "03_tap_probe.png") + if args.control_metrics and args.conditioned_metrics: + def evals(path): + out = {} + for line in open(path): + r = json.loads(line) + if r.get("event") == "evaluation": + out[int(r["step"])] = float(r["macro_psnr"]) + return out + chart_control(args.out_dir / "04_phase1_control.png", evals(args.control_metrics), evals(args.conditioned_metrics)) + print("charts written to", args.out_dir) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/probe_color_space.py b/dataset/phase1_noise_20260906/code/probe_color_space.py new file mode 100644 index 0000000000000000000000000000000000000000..1c6ecb21d50e859a481a9f4190100b9d660d519f --- /dev/null +++ b/dataset/phase1_noise_20260906/code/probe_color_space.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Does an HVI colour state buy Phase-1 / Phase-2 anything? Three measurements, +no training required. + +H1 Representation: per-image colour features in HVI (hvi_colour_stats) vs the + current photometric stats (RGB/luma) vs YUV chroma stats — 5-fold linear + probe for {rain, noise, haze, lowlight, clean, real snow}; also a + colour-only variant (chroma features alone) to isolate the colour space. +H2 Error anatomy of the current Phase-2 (run A): how much of the remaining + squared error sits in the HV (colour) plane vs the I plane, per domain. +H3 Controllability ceiling: per-image GLOBAL fits on the output — I affine + (exposure knob), HV affine (colour knob: 2x2 matrix + bias), both — and + the PSNR each recovers. An upper bound on what a per-image colour + conditioning could deliver. +""" + +from __future__ import annotations + +import argparse +import glob +import json +import math +from pathlib import Path +from typing import Dict, List, Sequence, Tuple + +import numpy as np +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_unified_v7 as v7 +from eval_v7_external import V7Pipeline +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from src.models.graph_encoder.encoder import photometric_stats +from src.models.graph_encoder.hvi import ( + HVI_STAT_NAMES, hvi_colour_stats, hvi_to_rgb, rgb_to_hvi, +) + +DOMAINS = ("rain", "noise", "haze", "lowlight") +CLASSES = ("rain", "noise", "haze", "lowlight", "clean", "snow_real") +_EPS = 1e-8 + + +# --------------------------------------------------------------------------- # +# feature sets +# --------------------------------------------------------------------------- # +def _hh1_mad(plane: torch.Tensor) -> torch.Tensor: + x = plane[:, None] + hh = (x[..., 0::2, 0::2] - x[..., 0::2, 1::2] - x[..., 1::2, 0::2] + x[..., 1::2, 1::2]) / 2.0 + return hh.abs().flatten(1).median(dim=1).values / 0.6745 + + +def yuv_stats(rgb: torch.Tensor) -> torch.Tensor: + uv = v7.rgb_to_uv(rgb) + y = v7.rgb_to_luma(rgb)[:, 0] + radius = uv.norm(dim=1).flatten(1) + yf = y.flatten(1) + return torch.stack(( + uv[:, 0].flatten(1).mean(1), uv[:, 1].flatten(1).mean(1), + radius.mean(1), radius.std(1), radius.quantile(0.95, dim=1), + _hh1_mad(uv[:, 0]), _hh1_mad(uv[:, 1]), + yf.mean(1), yf.std(1), yf.quantile(0.05, dim=1), yf.quantile(0.95, dim=1), + ), dim=1) + + +FEATURE_SETS = { + "rgb_photometric14": lambda x, k: photometric_stats(x), + "yuv11": lambda x, k: yuv_stats(x), + "hvi13": lambda x, k: hvi_colour_stats(x, k), + # colour-only slices (no luminance information at all) + "rgb_colour3": lambda x, k: photometric_stats(x)[:, 6:9], + "yuv_colour7": lambda x, k: yuv_stats(x)[:, :7], + "hvi_colour7": lambda x, k: hvi_colour_stats(x, k)[:, :7], +} + + +@torch.no_grad() +def features_for(images: torch.Tensor, k: float, batch: int = 32) -> Dict[str, np.ndarray]: + out: Dict[str, List[torch.Tensor]] = {n: [] for n in FEATURE_SETS} + for start in range(0, images.shape[0], batch): + chunk = images[start:start + batch].float() + for name, fn in FEATURE_SETS.items(): + out[name].append(fn(chunk, k).float().cpu()) + return {n: torch.cat(v).numpy() for n, v in out.items()} + + +# --------------------------------------------------------------------------- # +# linear probe (torch multinomial logistic regression, 5-fold stratified) +# --------------------------------------------------------------------------- # +def _fit_logreg(x: torch.Tensor, y: torch.Tensor, n_classes: int, l2: float = 1e-3) -> torch.nn.Linear: + model = torch.nn.Linear(x.shape[1], n_classes) + opt = torch.optim.LBFGS(model.parameters(), lr=0.5, max_iter=300, line_search_fn="strong_wolfe") + counts = torch.bincount(y, minlength=n_classes).float().clamp_min(1) + weight = counts.sum() / (n_classes * counts) # class-balanced CE + + def closure(): + opt.zero_grad() + loss = torch.nn.functional.cross_entropy(model(x), y, weight=weight) + loss = loss + l2 * model.weight.square().sum() + loss.backward() + return loss + + opt.step(closure) + return model + + +def linear_probe(features: np.ndarray, labels: np.ndarray, n_classes: int, folds: int = 5, seed: int = 0) -> Dict[str, object]: + rng = np.random.RandomState(seed) + fold_of = np.zeros(len(labels), dtype=int) + for c in range(n_classes): + idx = np.where(labels == c)[0] + rng.shuffle(idx) + for f, chunk in enumerate(np.array_split(idx, folds)): + fold_of[chunk] = f + confusion = np.zeros((n_classes, n_classes), dtype=np.int64) + for f in range(folds): + tr, te = fold_of != f, fold_of == f + mu, sd = features[tr].mean(0), features[tr].std(0) + 1e-6 + xtr = torch.tensor((features[tr] - mu) / sd, dtype=torch.float32) + xte = torch.tensor((features[te] - mu) / sd, dtype=torch.float32) + model = _fit_logreg(xtr, torch.tensor(labels[tr]), n_classes) + with torch.no_grad(): + pred = model(xte).argmax(1).numpy() + for t, p in zip(labels[te], pred): + confusion[t, p] += 1 + recall = confusion.diagonal() / confusion.sum(1).clip(min=1) + return { + "balanced_accuracy": float(recall.mean()), + "per_class_recall": {CLASSES[i]: float(recall[i]) for i in range(n_classes)}, + "confusion": confusion.tolist(), + } + + +# --------------------------------------------------------------------------- # +# H2 / H3 on Phase-2 outputs +# --------------------------------------------------------------------------- # +def _lstsq(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """Least squares a @ x = b (a [N,p], b [N,q]) via normal equations.""" + ata = a.T @ a + 1e-6 * torch.eye(a.shape[1], device=a.device, dtype=a.dtype) + return torch.linalg.solve(ata, a.T @ b) + + +def _psnr(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + return v4.rgb_psnr_per_image(x.clamp(0, 1), y) + + +@torch.no_grad() +def error_anatomy(restored: torch.Tensor, clean: torch.Tensor, k: float) -> Dict[str, torch.Tensor]: + hvi_r, hvi_c = rgb_to_hvi(restored, k), rgb_to_hvi(clean, k) + err = (hvi_r - hvi_c).square().flatten(2).mean(2) # [B,3] + uv_err = (v7.rgb_to_uv(restored) - v7.rgb_to_uv(clean)).square().flatten(2).mean(2).sum(1) + y_err = (v7.rgb_to_luma(restored) - v7.rgb_to_luma(clean)).square().flatten(1).mean(1) + n = restored.shape[0] + i_fit, hv_fit, both = [], [], [] + for i in range(n): + r, c = hvi_r[i].double(), hvi_c[i].double() + ones = torch.ones_like(r[2].flatten()) + # intensity affine + a_i = torch.stack((r[2].flatten(), ones), 1) + coef = _lstsq(a_i, c[2].flatten()[:, None]) + i_new = (a_i @ coef).reshape(r[2].shape).clamp(0, 1) + # HV affine (2x2 + bias) + a_hv = torch.stack((r[0].flatten(), r[1].flatten(), ones), 1) + coef_hv = _lstsq(a_hv, torch.stack((c[0].flatten(), c[1].flatten()), 1)) + hv_new = (a_hv @ coef_hv).T.reshape(2, *r[0].shape) + i_fit.append(torch.stack((r[0], r[1], i_new)).float()) + hv_fit.append(torch.stack((hv_new[0].float(), hv_new[1].float(), r[2].float()))) + both.append(torch.stack((hv_new[0].float(), hv_new[1].float(), i_new.float()))) + to_rgb = lambda lst: hvi_to_rgb(torch.stack(lst), k) + return { + "mse_H": err[:, 0], "mse_V": err[:, 1], "mse_I": err[:, 2], + "mse_UV": uv_err, "mse_Y": y_err, + "psnr_raw": _psnr(restored, clean), + "psnr_I_affine": _psnr(to_rgb(i_fit), clean), + "psnr_HV_affine": _psnr(to_rgb(hv_fit), clean), + "psnr_both": _psnr(to_rgb(both), clean), + "psnr_hvi_roundtrip": _psnr(hvi_to_rgb(hvi_r, k), clean), + } + + +# --------------------------------------------------------------------------- # +def _load_dir_images(pattern: str, size: int = 256) -> torch.Tensor: + from PIL import Image + files = sorted(glob.glob(pattern, recursive=True)) + out = [] + for f in files: + im = Image.open(f).convert("RGB") + w, h = im.size + s = size / min(w, h) + if s > 1: + im = im.resize((max(size, math.ceil(w * s)), max(size, math.ceil(h * s))), Image.LANCZOS) + w, h = im.size + l, t = (w - size) // 2, (h - size) // 2 + im = im.crop((l, t, l + size, t + size)) + out.append(torch.from_numpy(np.asarray(im, dtype=np.float32) / 255.0).permute(2, 0, 1)) + return torch.stack(out) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, default=Path("outputs/phase2_v7/uformer_p5_8k_seed42")) + parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + parser.add_argument("--snow-glob", default="/home/admin_mcn/data/Snow100K/realistic/**/*.jpg") + parser.add_argument("--output", type=Path, default=Path("outputs/color_space_probe.json")) + parser.add_argument("--k", type=float, default=0.2) + parser.add_argument("--device", default="cuda") + args = parser.parse_args() + device = torch.device(args.device) + + splits = load_train_val_manifest(args.manifest) + dataset = Phase2PairDataset(splits.val, crop_size=256, training=False, upscale_small=True) + groups: Dict[str, torch.Tensor] = {} + pairs: Dict[str, Tuple[torch.Tensor, torch.Tensor, List[str], torch.Tensor]] = {} + for d in DOMAINS: + idx = [i for i, r in enumerate(splits.val) if r.degradation == d] + items = [dataset[i] for i in idx] + deg = torch.stack([it["degraded"] for it in items]) + cln = torch.stack([it["clean"] for it in items]) + full = torch.stack([it["full_degraded"] for it in items]) + groups[d] = deg + groups["clean_" + d] = cln + pairs[d] = (deg, cln, [it["record_id"] for it in items], full) + p1_args = p1.build_parser().parse_args([]) + ext_splits = p1.build_data_splits(p1_args) + s8 = [r for r in ext_splits.locked_test if r.degradation == "noise"] + ds8 = ext.PairCropDataset(s8) + it8 = [ds8[i] for i in range(len(s8))] + groups["scene008_input"] = torch.stack([it["degraded"] for it in it8]) + groups["scene008_clean"] = torch.stack([it["clean"] for it in it8]) + pairs["scene008"] = (groups["scene008_input"], groups["scene008_clean"], + [it["record_id"] for it in it8], torch.stack([it["full_degraded"] for it in it8])) + groups["snow_real"] = _load_dir_images(args.snow_glob) + print("groups:", {k: int(v.shape[0]) for k, v in groups.items()}) + + # ---- H1 ------------------------------------------------------------- # + feats_by_group = {g: features_for(x.to(device), args.k) for g, x in groups.items()} + label_of = {d: i for i, d in enumerate(DOMAINS)} + rows, labels = {n: [] for n in FEATURE_SETS}, [] + for g, feats in feats_by_group.items(): + if g in label_of: + lab = label_of[g] + elif g.startswith("clean_") or g.startswith("scene008"): + lab = CLASSES.index("clean") + else: + lab = CLASSES.index("snow_real") + n = next(iter(feats.values())).shape[0] + labels.extend([lab] * n) + for name in FEATURE_SETS: + rows[name].append(feats[name]) + labels = np.array(labels) + h1 = {} + for name in FEATURE_SETS: + h1[name] = linear_probe(np.concatenate(rows[name]), labels, len(CLASSES)) + print("H1 %-20s bal.acc %.3f recall %s" % ( + name, h1[name]["balanced_accuracy"], + " ".join("%s=%.2f" % (c[:5], v) for c, v in h1[name]["per_class_recall"].items()))) + union = np.concatenate([np.concatenate(rows[n]) for n in ("rgb_photometric14", "hvi13")], axis=1) + h1["rgb14+hvi13"] = linear_probe(union, labels, len(CLASSES)) + print("H1 %-20s bal.acc %.3f" % ("rgb14+hvi13", h1["rgb14+hvi13"]["balanced_accuracy"])) + # group-mean HVI stats (for the report) + h1["group_mean_hvi"] = {g: dict(zip(HVI_STAT_NAMES, np.round(f["hvi13"].mean(0), 4).tolist())) + for g, f in feats_by_group.items()} + + # ---- H2 / H3 -------------------------------------------------------- # + pipe = V7Pipeline(args.run_dir, device) + h23 = {} + for name, (deg, cln, ids, full) in pairs.items(): + acc: Dict[str, List[torch.Tensor]] = {} + for start in range(0, deg.shape[0], 8): + sl = slice(start, start + 8) + restored = pipe.restore(deg[sl].to(device), record_ids=ids[sl], + full_degraded=full[sl].to(device))["restored"].float().clamp(0, 1) + for key, val in error_anatomy(restored, cln[sl].to(device), args.k).items(): + acc.setdefault(key, []).append(val.cpu()) + means = {k: float(torch.cat(v).mean()) for k, v in acc.items()} + hv = means["mse_H"] + means["mse_V"] + means["share_HV_of_HVI"] = hv / (hv + means["mse_I"] + _EPS) + means["share_UV_of_YUV"] = means["mse_UV"] / (means["mse_UV"] + means["mse_Y"] + _EPS) + means["n"] = int(deg.shape[0]) + h23[name] = means + 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" % ( + name, means["n"], means["psnr_raw"], means["psnr_I_affine"], means["psnr_HV_affine"], + means["psnr_both"], means["share_HV_of_HVI"], means["share_UV_of_YUV"], means["psnr_hvi_roundtrip"])) + + args.output.write_text(json.dumps({"run_dir": str(args.run_dir), "k": args.k, "H1": h1, "H2H3": h23}, indent=2)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/probe_phase1_scale.py b/dataset/phase1_noise_20260906/code/probe_phase1_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..68469086901583c0b73e876554320c4579b49def --- /dev/null +++ b/dataset/phase1_noise_20260906/code/probe_phase1_scale.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Does Phase-1's resize-centre-crop policy hide the degradation it must detect? + +The Phase-1 trainer (``train_graph_encoder_v2.PairDataset``) resizes every pair +so the short side is 256 and takes ONE centre crop. SIDD frames are ~4000x3000, +so the noise class is seen at ~12x downsampling (sensor noise averaged away); +Rain13K (384), LOL (600x400) and RESIDE (~550x413) are seen at ~1.5x. Phase-2 +and the Phase-1 dashboard consume native-resolution 256 crops instead. + +This probe routes the SAME validation pairs through one or more Phase-1 +checkpoints under three policies and reports the routing per domain (and per +ISO for SIDD): + + A trainer policy resize short side -> 256, centre crop + B native centre Phase-2 policy (upscale only if smaller than 256) + C native random K random native crops per pair (mean over crops) + +It also routes the Snow100K ``gt`` clean pool stratified by a dark-channel +haze proxy, with RESIDE hazy / clear and Rain13K / LOL clean crops as +reference distributions, to test whether the pool carries haze-like cues. +""" + +from __future__ import annotations + +import argparse +import json +import random +from collections import defaultdict +from pathlib import Path +from typing import Dict, List, Sequence, Tuple + +import torch +import torch.nn.functional as F +from PIL import Image + +import train_graph_encoder_v2 as v2 +import train_phase2_graph_resshift_v4 as v4 +from src.data.folder_crops import list_image_files + +NODES = ("rain", "noise", "haze", "lowlight", "free1", "free2") +DOMAIN_INDEX = {"rain": 0, "noise": 1, "haze": 2, "lowlight": 3} + + +def native_centre_crop(image: Image.Image, size: int) -> Image.Image: + width, height = image.size + if min(width, height) < size: + scale = float(size) / min(width, height) + image = image.resize( + (max(size, int(round(width * scale))), max(size, int(round(height * scale)))), + v2._LANCZOS, + ) + width, height = image.size + left, top = (width - size) // 2, (height - size) // 2 + return image.crop((left, top, left + size, top + size)) + + +def native_random_crops(image: Image.Image, size: int, count: int, seed: int) -> List[Image.Image]: + width, height = image.size + if min(width, height) < size: + return [native_centre_crop(image, size)] * count + rng = random.Random(seed) + crops = [] + for _ in range(count): + left = rng.randrange(width - size + 1) + top = rng.randrange(height - size + 1) + crops.append(image.crop((left, top, left + size, top + size))) + return crops + + +def sidd_iso(source_id: str) -> str: + parts = Path(source_id).name.split("_") + return parts[3] if len(parts) > 3 else "?" + + +def dark_channel_mean(images: torch.Tensor, patch: int = 15) -> torch.Tensor: + """Mean of the dark channel (He et al.): low for clear scenes, high for haze.""" + minimum = images.amin(dim=1, keepdim=True) + dark = -F.max_pool2d(-minimum, patch, stride=1, padding=patch // 2) + return dark.mean(dim=(1, 2, 3)) + + +def luma_contrast(images: torch.Tensor) -> torch.Tensor: + luma = 0.299 * images[:, 0] + 0.587 * images[:, 1] + 0.114 * images[:, 2] + return luma.flatten(1).std(dim=1) + + +@torch.no_grad() +def route(phase1, images: torch.Tensor, device: torch.device, batch: int = 16) -> torch.Tensor: + probs = [] + for start in range(0, images.shape[0], batch): + rep = phase1(images[start:start + batch].to(device)) + probs.append(rep.routing_probs.float().cpu()) + return torch.cat(probs) + + +def distribution(probs: torch.Tensor) -> Dict[str, float]: + argmax = probs.argmax(dim=1) + return {node: round(float((argmax == i).float().mean()), 3) for i, node in enumerate(NODES)} + + +def quantiles(values: torch.Tensor) -> Dict[str, float]: + qs = torch.tensor([0.1, 0.25, 0.5, 0.75, 0.9]) + return {"q%d" % int(q * 100): round(float(v), 4) for q, v in zip(qs, torch.quantile(values, qs))} + + +def run(argv: Sequence[str] | None = None) -> Dict[str, object]: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", action="append", required=True, + help="tag=path, repeatable") + parser.add_argument("--k-random", type=int, default=4) + parser.add_argument("--pool-root", default="/home/admin_mcn/data/Snow100K/train/all/gt") + parser.add_argument("--pool-count", type=int, default=512) + parser.add_argument("--image-size", type=int, default=256) + parser.add_argument("--output", type=Path, default=Path("outputs/phase1_scale_probe.json")) + parser.add_argument("--device", default="cuda") + args = parser.parse_args(argv) + device = torch.device(args.device) + size = args.image_size + + splits = v2.build_data_splits(v2.build_parser().parse_args([])) + records = list(splits.val) + print("val records: %d" % len(records), flush=True) + + # ---- load crops once ------------------------------------------------- # + per_policy: Dict[str, List[torch.Tensor]] = {"A": [], "B": [], "C": []} + meta: List[Tuple[str, str, str]] = [] # (domain, dataset, source_id) + clean_native: Dict[str, List[torch.Tensor]] = defaultdict(list) + hazy_native: List[torch.Tensor] = [] + for index, record in enumerate(records): + degraded = v2._open_rgb(record.degraded) + clean = v2._open_rgb(record.clean) + per_policy["A"].append(v2._pil_to_tensor(v2._resize_center_crop(degraded, size))) + per_policy["B"].append(v2._pil_to_tensor(native_centre_crop(degraded, size))) + crops = native_random_crops(degraded, size, args.k_random, seed=1000 + index) + per_policy["C"].append(torch.stack([v2._pil_to_tensor(c) for c in crops])) + meta.append((record.degradation, record.dataset, record.source_id)) + clean_native[record.degradation].append(v2._pil_to_tensor(native_centre_crop(clean, size))) + if record.degradation == "haze": + hazy_native.append(per_policy["B"][-1]) + if index % 50 == 0: + print("loaded %d/%d" % (index, len(records)), flush=True) + images_a = torch.stack(per_policy["A"]) + images_b = torch.stack(per_policy["B"]) + images_c = torch.stack(per_policy["C"]) # [N, K, 3, H, W] + + # ---- clean pool + haze proxy ---------------------------------------- # + pool_files = list_image_files(Path(args.pool_root)) + rng = random.Random(20260903) + pool_files = rng.sample(pool_files, min(args.pool_count, len(pool_files))) + pool = torch.stack([ + v2._pil_to_tensor(native_centre_crop(v2._open_rgb(path), size)) for path in pool_files + ]) + dcp_pool = dark_channel_mean(pool) + contrast_pool = luma_contrast(pool) + reference = { + "snow100k_gt_pool": {"dcp": quantiles(dcp_pool), "contrast": quantiles(contrast_pool)}, + "reside_hazy_val": {"dcp": quantiles(dark_channel_mean(torch.stack(hazy_native)))}, + } + for domain, crops in clean_native.items(): + stacked = torch.stack(crops) + reference["%s_clean_gt_val" % domain] = { + "dcp": quantiles(dark_channel_mean(stacked)), + "contrast": quantiles(luma_contrast(stacked)), + } + thresholds = torch.quantile(dcp_pool, torch.tensor([0.25, 0.5, 0.75])) + pool_quartile = torch.bucketize(dcp_pool, thresholds) + + # ---- route through each checkpoint ---------------------------------- # + results: Dict[str, object] = {"reference_dcp": reference, "checkpoints": {}} + for spec in args.checkpoint: + tag, path = spec.split("=", 1) + sha = v2.sha256_file(Path(path)) + phase1, _ = v4.build_frozen_phase1(Path(path), sha, device) + probs = { + "A": route(phase1, images_a, device), + "B": route(phase1, images_b, device), + "C": route(phase1, images_c.flatten(0, 1), device).view(len(records), args.k_random, -1).mean(dim=1), + } + report: Dict[str, object] = {"sha256": sha[:16], "domains": {}, "sidd_by_iso": {}, "pool": {}} + for domain, di in DOMAIN_INDEX.items(): + rows = [i for i, m in enumerate(meta) if m[0] == domain] + entry = {} + for policy, p in probs.items(): + sub = p[rows] + entry[policy] = { + "argmax": distribution(sub), + "own_prob_mean": round(float(sub[:, di].mean()), 3), + "free_prob_mean": round(float(sub[:, 4:].sum(dim=1).mean()), 3), + } + entry["agreement_A_B"] = round(float((probs["A"][rows].argmax(1) == probs["B"][rows].argmax(1)).float().mean()), 3) + report["domains"][domain] = entry + noise_rows = [i for i, m in enumerate(meta) if m[0] == "noise"] + by_iso: Dict[str, List[int]] = defaultdict(list) + for i in noise_rows: + by_iso[sidd_iso(meta[i][2])].append(i) + for iso, rows in sorted(by_iso.items()): + report["sidd_by_iso"][iso] = { + "n": len(rows), + **{policy: {"noise_prob": round(float(p[rows][:, 1].mean()), 3), + "argmax": distribution(p[rows])} for policy, p in probs.items()}, + } + pool_probs = route(phase1, pool, device) + report["pool"]["all"] = distribution(pool_probs) + for q in range(4): + rows = (pool_quartile == q).nonzero(as_tuple=True)[0] + report["pool"]["dcp_quartile_%d" % (q + 1)] = { + "n": int(rows.numel()), + "dcp_mean": round(float(dcp_pool[rows].mean()), 4), + "argmax": distribution(pool_probs[rows]), + "haze_prob_mean": round(float(pool_probs[rows][:, 2].mean()), 3), + } + results["checkpoints"][tag] = report + + print("=== %s (%s)" % (tag, sha[:12])) + for domain, entry in report["domains"].items(): + print(" %-8s A own=%.2f free=%.2f | B own=%.2f free=%.2f | C own=%.2f free=%.2f | agree(A,B)=%.2f" % ( + domain, entry["A"]["own_prob_mean"], entry["A"]["free_prob_mean"], + entry["B"]["own_prob_mean"], entry["B"]["free_prob_mean"], + entry["C"]["own_prob_mean"], entry["C"]["free_prob_mean"], entry["agreement_A_B"])) + print(" A argmax %s" % entry["A"]["argmax"]) + print(" B argmax %s" % entry["B"]["argmax"]) + for iso, entry in report["sidd_by_iso"].items(): + print(" SIDD ISO %s n=%d noise_prob A=%.2f B=%.2f C=%.2f B argmax %s" % ( + iso, entry["n"], entry["A"]["noise_prob"], entry["B"]["noise_prob"], entry["C"]["noise_prob"], entry["B"]["argmax"])) + print(" pool all: %s" % report["pool"]["all"]) + for q in range(4): + e = report["pool"]["dcp_quartile_%d" % (q + 1)] + print(" pool DCP q%d (mean %.3f): haze_prob %.2f argmax %s" % (q + 1, e["dcp_mean"], e["haze_prob_mean"], e["argmax"])) + del phase1 + torch.cuda.empty_cache() + + print("reference DCP: %s" % json.dumps(reference, indent=None)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(results, indent=2)) + print("saved %s" % args.output) + return results + + +if __name__ == "__main__": + run() diff --git a/dataset/phase1_noise_20260906/code/probe_pregain.py b/dataset/phase1_noise_20260906/code/probe_pregain.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a1531a1f06a61afc91321982fd9c7fbcb4749e --- /dev/null +++ b/dataset/phase1_noise_20260906/code/probe_pregain.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Print the v10 input pre-gain the model predicts per external group +(mean / min / max log-gain and gain), using the same Phase-1 crop + whole +frame inputs the sampler uses. Diagnoses e.g. a gain > 1 on bright hazy +images (clipping) vs the intended gain on low-light inputs.""" + +import argparse +import json +from pathlib import Path + +import torch + +import eval_full_frame as ff +import train_phase2_graph_resshift_v4 as v4 +from eval_v7_external import V7Pipeline + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--checkpoint", default="best.pt") + parser.add_argument("--groups", default="lowlight_lolv2_test,haze_heldout,rain_locked,noise_locked_scene008") + parser.add_argument("--limit", type=int, default=40) + parser.add_argument("--output", type=Path, default=None) + args = parser.parse_args() + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + pipeline = V7Pipeline(args.run_dir, device, checkpoint=args.checkpoint) + restorer = v4.unwrap_module(pipeline.model) + if getattr(restorer, "exposure_pregain", None) is None: + raise SystemExit("this run has no exposure pre-gain") + groups = ff.external_groups() + report = {} + for name in [g.strip() for g in args.groups.split(",") if g.strip()]: + dataset = ff.FullFrameDataset(groups[name][: args.limit]) + gains = [] + with torch.no_grad(): + for index in range(len(dataset)): + item = dataset[index] + degraded = item["degraded"].unsqueeze(0).to(device) + full = item["full_degraded"].unsqueeze(0).to(device) + # centre 256 crop as a Phase-1 tile, like the sampler's tiles + h, w = degraded.shape[-2:] + top, left = max((h - 256) // 2, 0), max((w - 256) // 2, 0) + crop = degraded[..., top:top + 256, left:left + 256] + rep = pipeline.phase1(crop) + if getattr(restorer, "ctx_full_proj", None) is not None: + rep.full_frame = pipeline.phase1(full) + rep.full_image = full + log_gain = restorer.exposure_pregain.log_gain(crop, rep) + gains.append(float(log_gain[0])) + t = torch.tensor(gains) + report[name] = {"n": len(gains), "log_gain_mean": float(t.mean()), "log_gain_min": float(t.min()), + "log_gain_max": float(t.max()), "gain_mean": float(t.exp().mean()), + "frac_gain_gt_1.05": float((t > 0.05).float().mean())} + print(name, json.dumps(report[name]), flush=True) + if args.output: + args.output.write_text(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/probe_scene008_tone.py b/dataset/phase1_noise_20260906/code/probe_scene008_tone.py new file mode 100644 index 0000000000000000000000000000000000000000..08a469b49eac5fb9624a4fec62ca77713affcef1 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/probe_scene008_tone.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Is the scene008 (nearly clean, dark textured) failure a global tone shift? + +For every locked scene008 record: mean luma of input / restored / GT, per-channel +mean shift restored-GT, PSNR of the raw output, and PSNR after a single global +affine correction (gain+bias fitted on luma against GT). If the corrected PSNR +recovers most of the gap, the model is applying an exposure lift, not +destroying texture. Also reports the val degraded baselines per domain so +in-distribution gains can be read against the input quality. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from eval_v7_external import V7Pipeline +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from visualize_v7_uformer import _load_run_args + +LUMA = (0.299, 0.587, 0.114) + + +def luma(x: torch.Tensor) -> torch.Tensor: + return sum(x[:, c] * w for c, w in enumerate(LUMA)) + + +def affine_match(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """Per-image global gain+bias on all channels fitted by least squares on luma.""" + out = [] + for p, t in zip(pred, target): + lp, lt = luma(p[None])[0].flatten(), luma(t[None])[0].flatten() + var = lp.var() + gain = ((lp - lp.mean()) * (lt - lt.mean())).mean() / var if var > 1e-8 else 1.0 + bias = lt.mean() - gain * lp.mean() + out.append((p * gain + bias).clamp(0, 1)) + return torch.stack(out) + + +def scene008(pipe: V7Pipeline, device, dose) -> dict: + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + records = [r for r in splits.locked_test if r.degradation == "noise"] + dataset = ext.PairCropDataset(records) + rows = [] + pipe.dose = dose + for start in range(0, len(records), 8): + items = [dataset[i] for i in range(start, min(start + 8, len(records)))] + degraded = torch.stack([it["degraded"] for it in items]).to(device) + clean = torch.stack([it["clean"] for it in items]).to(device) + ids = [it["record_id"] for it in items] + # Whole-frame view must reach the pipeline, otherwise a --global-context + # model silently runs without its full-frame branch (not deployment). + full = (torch.stack([it["full_degraded"] for it in items]).to(device) + if "full_degraded" in items[0] else None) + with torch.no_grad(): + restored = pipe.restore( + degraded, record_ids=ids, full_degraded=full + )["restored"].float().clamp(0, 1) + matched = affine_match(restored, clean) + for i, rid in enumerate(ids): + rows.append({ + "record_id": rid, + "luma_input": float(luma(degraded[i:i+1]).mean()), + "luma_restored": float(luma(restored[i:i+1]).mean()), + "luma_gt": float(luma(clean[i:i+1]).mean()), + "rgb_shift": [float((restored[i, c] - clean[i, c]).mean()) for c in range(3)], + "psnr_input": float(v4.rgb_psnr_per_image(degraded[i:i+1], clean[i:i+1])[0]), + "psnr_restored": float(v4.rgb_psnr_per_image(restored[i:i+1], clean[i:i+1])[0]), + "psnr_affine_matched": float(v4.rgb_psnr_per_image(matched[i:i+1], clean[i:i+1])[0]), + "ssim_restored": float(v4.rgb_ssim_per_image(restored[i:i+1], clean[i:i+1])[0]), + "ssim_affine_matched": float(v4.rgb_ssim_per_image(matched[i:i+1], clean[i:i+1])[0]), + }) + mean = lambda k: sum(r[k] for r in rows) / len(rows) + return { + "n": len(rows), "dose": dose, "rows": rows, + "mean": {k: mean(k) for k in ("luma_input", "luma_restored", "luma_gt", "psnr_input", + "psnr_restored", "psnr_affine_matched", + "ssim_restored", "ssim_affine_matched")}, + } + + +def val_baselines(run_args, device) -> dict: + splits = load_train_val_manifest(run_args.manifest) + dataset = Phase2PairDataset(splits.val, crop_size=run_args.crop_size, training=False) + acc = {} + for index, record in enumerate(splits.val): + item = dataset[index] + d, c = item["degraded"][None].to(device), item["clean"][None].to(device) + entry = acc.setdefault(record.degradation, {"psnr": [], "ssim": []}) + entry["psnr"].append(float(v4.rgb_psnr_per_image(d, c)[0])) + entry["ssim"].append(float(v4.rgb_ssim_per_image(d, c)[0])) + return {k: {"n": len(v["psnr"]), "psnr": sum(v["psnr"]) / len(v["psnr"]), + "ssim": sum(v["ssim"]) / len(v["ssim"])} for k, v in acc.items()} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--skip-val-baseline", action="store_true") + args = parser.parse_args() + device = torch.device("cuda") + pipe = V7Pipeline(args.run_dir, device) + report = { + "run_dir": str(args.run_dir), + "scene008_dose1": scene008(pipe, device, None), + "scene008_dose0": scene008(pipe, device, 0.0), + "val_degraded_baseline": ( + None if args.skip_val_baseline + else val_baselines(_load_run_args(args.run_dir), device) + ), + } + args.output.write_text(json.dumps(report, indent=2)) + for key in ("scene008_dose1", "scene008_dose0"): + m = report[key]["mean"] + print(key, " ".join("%s=%.3f" % (k, v) for k, v in m.items())) + print("val_degraded_baseline", json.dumps(report["val_degraded_baseline"])) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/probe_v11_memory.py b/dataset/phase1_noise_20260906/code/probe_v11_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbf14b55cf3789bc86513440c5f63828ee0837e --- /dev/null +++ b/dataset/phase1_noise_20260906/code/probe_v11_memory.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Peak-memory / throughput probe for a v7-family training configuration. + +Builds the restorer exactly as the trainer would (same parser + builder), +runs ``--steps`` training micro-steps on synthetic batches at the given crop +and batch size with AMP, and prints peak allocated memory and step time so a +launcher can pick the batch size for each progressive-resolution stage +(v11) before committing both GPUs. Phase-1 is replaced by a synthetic +representation of the right shapes (its footprint is small and frozen). + +Usage: probe_v11_memory.py --crop 384 --batch 4 [--grad-checkpoint] -- +""" + +from __future__ import annotations + +import argparse +import json +import sys +import time +from types import SimpleNamespace + +import torch + +import train_phase2_unified_v7 as v7 + + +def synthetic_representation(batch: int, crop: int, device) -> SimpleNamespace: + latent = crop // 4 + rep = SimpleNamespace( + content_latent=torch.randn(batch, 128, latent, latent, device=device), + node_tokens=torch.randn(batch, 6, 256, device=device), + routing_probs=torch.softmax(torch.randn(batch, 6, device=device), dim=-1), + severity_coords=torch.rand(batch, 4, device=device), + spatial_maps=torch.rand(batch, 4, 16, 16, device=device), + unknown_residual=torch.randn(batch, 256, device=device), + global_condition=torch.randn(batch, 256, device=device), + photometric_state=torch.randn(batch, v7.PHOTOMETRIC_STATE_DIM, device=device), + ) + full = SimpleNamespace(**{k: (v.clone() if isinstance(v, torch.Tensor) else v) for k, v in vars(rep).items()}) + rep.full_frame = full + rep.full_image = torch.rand(batch, 3, 256, 256, device=device) + return rep + + +def main(argv=None) -> None: + argv = list(sys.argv[1:] if argv is None else argv) + if "--" not in argv: + raise SystemExit("usage: probe_v11_memory.py --crop N --batch N [--steps N] -- ") + split = argv.index("--") + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--crop", type=int, required=True) + parser.add_argument("--batch", type=int, required=True) + parser.add_argument("--steps", type=int, default=3) + parser.add_argument("--output", default=None) + probe = parser.parse_args(argv[:split]) + args = v7.build_parser().parse_args(argv[split + 1:] + ["--allow-scratch"]) + device = torch.device("cuda") + model = v7._build_v7_restorer(args, device) + model.train() + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5) + scaler = torch.cuda.amp.GradScaler() + torch.cuda.reset_peak_memory_stats(device) + timings = [] + for step in range(int(probe.steps)): + clean = torch.rand(probe.batch, 3, probe.crop, probe.crop, device=device) + degraded = torch.rand(probe.batch, 3, probe.crop, probe.crop, device=device) + rep = synthetic_representation(probe.batch, probe.crop, device) + timesteps = torch.full((probe.batch,), 2, device=device, dtype=torch.long) + torch.cuda.synchronize() + start = time.time() + with torch.cuda.amp.autocast(enabled=True): + result = model.training_loss(clean, degraded, rep, timesteps) + scaler.scale(result.loss).backward() + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + scaler.step(optimizer) + scaler.update() + optimizer.zero_grad(set_to_none=True) + torch.cuda.synchronize() + timings.append(time.time() - start) + peak = torch.cuda.max_memory_allocated(device) / 2 ** 30 + params = sum(p.numel() for p in model.parameters()) / 1e6 + report = { + "crop": probe.crop, "batch": probe.batch, "params_M": round(params, 2), + "peak_gib": round(peak, 2), "step_s": round(sum(timings[1:]) / max(len(timings) - 1, 1), 3), + "grad_checkpoint": bool(getattr(args, "grad_checkpoint", False)), + "blocks_per_stage": list(v7.blocks_per_stage(args)), + } + print("PROBE " + json.dumps(report), flush=True) + if probe.output: + with open(probe.output, "w") as handle: + json.dump(report, handle) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/quick_eval_every.sh b/dataset/phase1_noise_20260906/code/quick_eval_every.sh new file mode 100644 index 0000000000000000000000000000000000000000..e7e77e43d279450def7eb41b36d14003905a0247 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/quick_eval_every.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Quick external check of a running stage every N steps (user request): +# when the train log passes each target step, snapshot last.pt and run the +# whole-image full-frame evaluator on LOLv2 / haze / Test1200 (no LPIPS, no +# 12 MP scene008) on the given GPU, sharing it with training. +# Usage: quick_eval_every.sh +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +RUN=$1; GPU=$2; TARGETS=${3//,/ } +RUN_DIR=outputs/phase2_v7/$RUN +LOG=outputs/phase2_v7/${RUN}_train.log +log() { echo "[quick $(date +%H:%M:%S)] $*"; } +current_step() { grep "\"event\": \"train\"" "$LOG" 2>/dev/null | tail -n 1 | grep -o "\"step\": [0-9]*" | grep -o "[0-9]*"; } +for target in $TARGETS; do + while true; do + s=$(current_step); s=${s:-0} + if [ "$s" -ge "$target" ]; then break; fi + 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 + sleep 120 + done + sleep 60 # let last.pt (written every 250 steps) settle + snap=$RUN_DIR/snapshot_${target}.pt + cp "$RUN_DIR/last.pt" "$snap" + step=$($PY -c "import torch; print(torch.load('$snap', map_location='cpu')['step'])") + log "snapshot for target $target = last.pt at step $step" + CUDA_VISIBLE_DEVICES=$GPU $PY -u eval_full_frame.py --run-dir "$RUN_DIR" --checkpoint "snapshot_${target}.pt" \ + --groups lowlight_lolv2_test,haze_heldout,rain_locked --whole-max-pixels 1200000 --tta 1 --no-lpips \ + --output outputs/quick_${RUN}_${target}.json >> outputs/phase2_v7/quick_eval_${RUN}.log 2>&1 \ + && log "wrote outputs/quick_${RUN}_${target}.json" || log "eval FAILED at $target" +done +log "done" diff --git a/dataset/phase1_noise_20260906/code/run_ablation_C_only.sh b/dataset/phase1_noise_20260906/code/run_ablation_C_only.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d7832747d6230153d9d0284b998a1597667b7b6 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_ablation_C_only.sh @@ -0,0 +1,73 @@ +#!/bin/bash +# Photometric ablation on the MI325X host (user request 2026-09-05): +# A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5 +# B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run) +# C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6 +# All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then +# whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt. +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +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/ +export OMP_NUM_THREADS=8 +export PYTORCH_ALLOC_CONF=expandable_segments:True +# Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A). +free_gpus() { + rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \ + | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' ' +} +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +STEPS=${STEPS:-5000} +EVLOG=outputs/phase2_v7/ablation_photometric_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[abl $(date +%H:%M:%S)] $*"; } + +BASE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \ + --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \ + --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \ + --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \ + --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02" +PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02" +COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05" + +launch() { # name gpu extra + local name=$1 gpu=$2 extra=$3 + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \ + >> outputs/phase2_v7/${name}_train.log 2>&1 & + log "launched $name on GPU$gpu pid $!" +} +wait_done() { # name + local name=$1 run_dir=outputs/phase2_v7/$1 + while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done + if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi +} +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } + +# C_colour only, on a given GPU (GPU 6 is contested by another tenant on this host) +GC=${GC:-5} +rm -rf outputs/phase2_v7/abl_C_colour +launch abl_C_colour "$GC" "$PHOTO $COLOUR" +wait_done abl_C_colour +log "C_colour finished" diff --git a/dataset/phase1_noise_20260906/code/run_ablation_C_then_eval.sh b/dataset/phase1_noise_20260906/code/run_ablation_C_then_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..cacf91fdedd0d2a2aa86aaf538ea1332130bd97a --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_ablation_C_then_eval.sh @@ -0,0 +1,88 @@ +#!/bin/bash +# Photometric ablation on the MI325X host (user request 2026-09-05): +# A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5 +# B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run) +# C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6 +# All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then +# whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt. +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +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/ +export OMP_NUM_THREADS=8 +export PYTORCH_ALLOC_CONF=expandable_segments:True +# Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A). +free_gpus() { + rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \ + | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' ' +} +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +STEPS=${STEPS:-5000} +EVLOG=outputs/phase2_v7/ablation_photometric_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[abl $(date +%H:%M:%S)] $*"; } + +BASE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \ + --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \ + --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \ + --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \ + --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02" +PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02" +COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05" + +launch() { # name gpu extra + local name=$1 gpu=$2 extra=$3 + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \ + >> outputs/phase2_v7/${name}_train.log 2>&1 & + log "launched $name on GPU$gpu pid $!" +} +wait_done() { # name + local name=$1 run_dir=outputs/phase2_v7/$1 + while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done + if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi +} +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } + +# C_colour (relaunch after an external kill) + its evals + the comparison table. +GC=${GC:-5} +while pgrep -f "[e]val_full_frame.py" >/dev/null; do sleep 30; done # let the A/B evals finish first +rm -rf outputs/phase2_v7/abl_C_colour +launch abl_C_colour "$GC" "$PHOTO $COLOUR" +wait_done abl_C_colour +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 +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 +$PY - <<'PYEOF' +import json, os +rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"), + ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")] +print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008") +for name, p in rows: + if not os.path.exists(p): print(name, "missing"); continue + r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f] + print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % ( + name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"), + g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips"))) +PYEOF +log "ablation finished" diff --git a/dataset/phase1_noise_20260906/code/run_ablation_photometric.sh b/dataset/phase1_noise_20260906/code/run_ablation_photometric.sh new file mode 100644 index 0000000000000000000000000000000000000000..29b396406e090fa5b5beaeaf177a4013e82ff57c --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_ablation_photometric.sh @@ -0,0 +1,94 @@ +#!/bin/bash +# Photometric ablation on the MI325X host (user request 2026-09-05): +# A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5 +# B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run) +# C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6 +# All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then +# whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt. +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +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/ +export OMP_NUM_THREADS=8 +export PYTORCH_ALLOC_CONF=expandable_segments:True +# Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A). +free_gpus() { + rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \ + | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' ' +} +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +STEPS=${STEPS:-5000} +EVLOG=outputs/phase2_v7/ablation_photometric_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[abl $(date +%H:%M:%S)] $*"; } + +BASE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \ + --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \ + --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \ + --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \ + --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02" +PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02" +COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05" + +launch() { # name gpu extra + local name=$1 gpu=$2 extra=$3 + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \ + >> outputs/phase2_v7/${name}_train.log 2>&1 & + log "launched $name on GPU$gpu pid $!" +} +wait_done() { # name + local name=$1 run_dir=outputs/phase2_v7/$1 + while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done + if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi +} +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } + +read -r GA GC _ <<< "$(free_gpus)" +[ -n "${GA:-}" ] && [ -n "${GC:-}" ] || { log "need two free GPUs, found: '$(free_gpus)'"; exit 1; } +log "using GPUs $GA (A_nophoto) and $GC (C_colour)" +launch abl_A_nophoto "$GA" "" +launch abl_C_colour "$GC" "$PHOTO $COLOUR" +wait_done abl_A_nophoto; wait_done abl_C_colour +# B = the stage-A run at the same step count +B_CKPT=outputs/phase2_v7/uformer_v11a_256_x/milestone_00005000.pt +[ -f $B_CKPT ] || log "WARNING: $B_CKPT missing" +( 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 + 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 ) & +( 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 + 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 ) & +wait +$PY - <<'PYEOF' +import json, os +rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"), + ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")] +print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008") +for name, p in rows: + if not os.path.exists(p): print(name, "missing"); continue + r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f] + print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % ( + name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"), + g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips"))) +PYEOF +log "ablation finished" diff --git a/dataset/phase1_noise_20260906/code/run_ablation_seq.sh b/dataset/phase1_noise_20260906/code/run_ablation_seq.sh new file mode 100644 index 0000000000000000000000000000000000000000..b74c0b9d9ac9c3ab2823cf31441b0379eb5c7297 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_ablation_seq.sh @@ -0,0 +1,96 @@ +#!/bin/bash +# Photometric ablation on the MI325X host (user request 2026-09-05): +# A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5 +# B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run) +# C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6 +# All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then +# whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt. +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +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/ +export OMP_NUM_THREADS=8 +export PYTORCH_ALLOC_CONF=expandable_segments:True +# Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A). +free_gpus() { + rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \ + | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' ' +} +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +STEPS=${STEPS:-5000} +EVLOG=outputs/phase2_v7/ablation_photometric_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[abl $(date +%H:%M:%S)] $*"; } + +BASE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \ + --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \ + --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \ + --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \ + --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02" +PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02" +COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05" + +launch() { # name gpu extra + local name=$1 gpu=$2 extra=$3 + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \ + >> outputs/phase2_v7/${name}_train.log 2>&1 & + log "launched $name on GPU$gpu pid $!" +} +wait_done() { # name + local name=$1 run_dir=outputs/phase2_v7/$1 + while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done + if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi +} +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } + +# Sequential variant for a contested host: A (already running or launched) then C on ONE device. +GA=${GA:-5}; GC=${GC:-5} +running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir outputs/phase2_v7/$1" >/dev/null; } +if ! running abl_A_nophoto && ! grep -q "\"step\": $STEPS" outputs/phase2_v7/abl_A_nophoto/metrics.jsonl 2>/dev/null; then + rm -rf outputs/phase2_v7/abl_A_nophoto; launch abl_A_nophoto "$GA" "" +fi +wait_done abl_A_nophoto +rm -rf outputs/phase2_v7/abl_C_colour +launch abl_C_colour "$GC" "$PHOTO $COLOUR" +wait_done abl_C_colour +B_CKPT=outputs/phase2_v7/uformer_v11a_256_x/milestone_00005000.pt +[ -f $B_CKPT ] || log "WARNING: $B_CKPT missing" +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 +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 +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 +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 +$PY - <<'PYEOF' +import json, os +rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"), + ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")] +print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008") +for name, p in rows: + if not os.path.exists(p): print(name, "missing"); continue + r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f] + print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % ( + name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"), + g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips"))) +PYEOF +log "ablation finished" diff --git a/dataset/phase1_noise_20260906/code/run_phase1_v5c.sh b/dataset/phase1_noise_20260906/code/run_phase1_v5c.sh new file mode 100644 index 0000000000000000000000000000000000000000..114669878a6b3eec9943fcd35f74843cb614aab8 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_phase1_v5c.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# Phase-1 v5c pair (2026-09-03): the v5b recipe under the NATIVE crop policy +# (Phase-2 parity; SIDD seen at native resolution instead of ~12x downsampled). +# GPU0 phase1_v5c native + SupCon on known+paired-clean only (embed-members known_clean) +# GPU1 phase1_v5c_ab native + v5b SupCon membership (all) -> isolates the crop policy +# Both share one native SIDD cache; the second run starts only after the first +# has finished prebuilding it (severity_calibration.json appears after prebuild). +# Usage: bash run_phase1_v5c.sh (launch both) +# ONLY=v5c bash run_phase1_v5c.sh (launch one: v5c | v5c_ab) +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CACHE=outputs/phase1_cache/sidd_native_256 +DATA=/home/admin_mcn/data +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 8 --no-amp --seed 42 \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 \ + --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE" + +launch() { # $1 = run name, $2 = gpu, $3 = embed members + local name=$1 gpu=$2 members=$3 + mkdir -p outputs/$name + CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON \ + --embed-members $members --output-dir outputs/$name \ + > outputs/${name}_train.log 2>&1 < /dev/null & + echo "[v5c] launched $name on GPU$gpu (embed-members=$members) pid $!" +} + +wait_for_cache() { # wait until the first run wrote its calibration (cache prebuilt) + local name=$1 + for _ in $(seq 1 240); do + if [ -f outputs/$name/severity_calibration.json ]; then return 0; fi + if grep -q Traceback outputs/${name}_train.log 2>/dev/null; then echo "[v5c] $name crashed before cache"; return 1; fi + sleep 15 + done + echo "[v5c] timed out waiting for $name cache"; return 1 +} + +ONLY=${ONLY:-both} +case "$ONLY" in + v5c) launch phase1_v5c 0 known_clean ;; + v5c_ab) launch phase1_v5c_ab 1 all ;; + both) + launch phase1_v5c 0 known_clean + wait_for_cache phase1_v5c && launch phase1_v5c_ab 1 all + ;; + *) echo "ONLY must be v5c | v5c_ab | both"; exit 2 ;; +esac diff --git a/dataset/phase1_noise_20260906/code/run_phase1_v5d.sh b/dataset/phase1_noise_20260906/code/run_phase1_v5d.sh new file mode 100644 index 0000000000000000000000000000000000000000..7b1fbed613de934bf15913d16fe056606436f85a --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_phase1_v5d.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Phase-1 v5d pair (2026-09-03): v5c_ab recipe (native crops, v5b losses, +# SupCon members = all) + weight EMA (0.999) for evaluation/selection and the +# balanced selection key (0.5*F1 + 0.5*mean null terms), two seeds. +# GPU0 phase1_v5d seed 42 +# GPU1 phase1_v5d_s43 seed 43 +# Shares the native SIDD cache built by v5c; severity calibration is copied +# from phase1_v5c (same records, same policy -> same fingerprint). +# Usage: bash run_phase1_v5d.sh (both) +# ONLY=v5d|v5d_s43 bash run_phase1_v5d.sh +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CACHE=outputs/phase1_cache/sidd_native_256 +DATA=/home/admin_mcn/data +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 8 --no-amp \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \ + --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \ + --ema-decay 0.999 --selection balanced" + +launch() { # $1 = run name, $2 = gpu, $3 = seed + local name=$1 gpu=$2 seed=$3 + mkdir -p outputs/$name + [ -f outputs/$name/severity_calibration.json ] || cp outputs/phase1_v5c/severity_calibration.json outputs/$name/ 2>/dev/null + CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON \ + --seed $seed --output-dir outputs/$name \ + > outputs/${name}_train.log 2>&1 < /dev/null & + echo "[v5d] launched $name on GPU$gpu (seed $seed) pid $!" +} + +ONLY=${ONLY:-both} +case "$ONLY" in + v5d) launch phase1_v5d 0 42 ;; + v5d_s43) launch phase1_v5d_s43 1 43 ;; + both) launch phase1_v5d 0 42; sleep 20; launch phase1_v5d_s43 1 43 ;; + *) echo "ONLY must be v5d | v5d_s43 | both"; exit 2 ;; +esac diff --git a/dataset/phase1_noise_20260906/code/run_phase1_v5e.sh b/dataset/phase1_noise_20260906/code/run_phase1_v5e.sh new file mode 100644 index 0000000000000000000000000000000000000000..501de37ec8659b9e88089f2a0516888548bfaa23 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_phase1_v5e.sh @@ -0,0 +1,57 @@ +#!/bin/bash +# Phase-1 v5e pair (2026-09-04): v5c_ab recipe (native crops, v5b losses, +# SupCon all, raw-weight eval, F1 selection) + residual-aware training crops +# and a crop-level severity floor. +# GPU0 phase1_v5e --crop-select residual --crop-candidates 4 --severity-floor 0.05 +# GPU1 phase1_v5e_ab --crop-select residual --crop-candidates 4 (no floor -> isolates the floor) +# Each launch can wait for a previous run's "Training complete" (WAIT0 / WAIT1 = +# path of that run's train log) so it starts as soon as the GPU frees up. +# Usage: WAIT0=outputs/phase1_v5d_train.log WAIT1=outputs/phase1_v5d_s43_train.log bash run_phase1_v5e.sh +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CACHE=outputs/phase1_cache/sidd_native_256 +DATA=/home/admin_mcn/data +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 8 --no-amp --seed 42 \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \ + --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \ + --crop-select residual --crop-candidates 4" + +wait_log() { # $1 = train log to wait for ("" = no wait) + [ -z "$1" ] && return 0 + while ! grep -q "Training complete" "$1" 2>/dev/null; do + if grep -q Traceback "$1" 2>/dev/null && ! pgrep -f "[t]rain_graph_encoder_v2.py.*$(basename ${1%_train.log})" >/dev/null; then + echo "[v5e] $1 crashed; launching anyway"; return 0 + fi + sleep 120 + done + sleep 30 +} + +launch() { # $1 = run name, $2 = gpu, $3 = extra flags + local name=$1 gpu=$2 extra=$3 + mkdir -p outputs/$name + [ -f outputs/$name/severity_calibration.json ] || cp outputs/phase1_v5c/severity_calibration.json outputs/$name/ 2>/dev/null + CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON $extra \ + --output-dir outputs/$name > outputs/${name}_train.log 2>&1 < /dev/null & + echo "[v5e] $(date +%H:%M) launched $name on GPU$gpu ($extra) pid $!" +} + +ONLY=${ONLY:-both} +WAIT0=${WAIT0:-}; WAIT1=${WAIT1:-} +case "$ONLY" in + v5e) wait_log "$WAIT0"; launch phase1_v5e 0 "--severity-floor 0.05" ;; + v5e_ab) wait_log "$WAIT1"; launch phase1_v5e_ab 1 "--severity-floor 0.0" ;; + both) + ( wait_log "$WAIT0"; launch phase1_v5e 0 "--severity-floor 0.05" ) & + ( wait_log "$WAIT1"; launch phase1_v5e_ab 1 "--severity-floor 0.0" ) & + wait + ;; + *) echo "ONLY must be v5e | v5e_ab | both"; exit 2 ;; +esac diff --git a/dataset/phase1_noise_20260906/code/run_uformer_dgf8k.sh b/dataset/phase1_noise_20260906/code/run_uformer_dgf8k.sh new file mode 100644 index 0000000000000000000000000000000000000000..f07a0f8e9e35268261bc7e8bb5e81be79478af7b --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_dgf8k.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_dgf8k_seed42 +LOG=outputs/phase2_v7/uformer_dgf8k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_head8k_seed42/best.pt +WARMSTART_SHA=0168e543c6025514e7b98ef7ddd9e191de2bdcaca9072e0a796fadcf503cbc9c + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_dgf8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.10 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_head8k.sh b/dataset/phase1_noise_20260906/code/run_uformer_head8k.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee858db19602fd2b582c8e6ad15c841b3c1d9865 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_head8k.sh @@ -0,0 +1,85 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_head8k_seed42 +LOG=outputs/phase2_v7/uformer_head8k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_luma8k_seed42/best.pt +WARMSTART_SHA=42c11eda0df3d4c3645a7013a831a5e965915d252895c2de58b5048d286e7817 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_head8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_luma8k.sh b/dataset/phase1_noise_20260906/code/run_uformer_luma8k.sh new file mode 100644 index 0000000000000000000000000000000000000000..25820b8a239403cff0abb7959acf624d50b35c84 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_luma8k.sh @@ -0,0 +1,84 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_luma8k_seed42 +LOG=outputs/phase2_v7/uformer_luma8k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer16k_seed42/best.pt +WARMSTART_SHA=809241a2a2e11c1d5e87b292827a97a2d71aa86a7684996caf903bf870532c43 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_luma8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_nophase1.sh b/dataset/phase1_noise_20260906/code/run_uformer_nophase1.sh new file mode 100644 index 0000000000000000000000000000000000000000..b69b9ce6764752ab54881c1231a784f3e84aa0dc --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_nophase1.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_nophase1_8k_seed42 +LOG=outputs/phase2_v7/uformer_nophase1_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_head8k_seed42/best.pt +WARMSTART_SHA=0168e543c6025514e7b98ef7ddd9e191de2bdcaca9072e0a796fadcf503cbc9c + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_nophase1_8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=0 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 1.0 --identity-pair-prob 0.10 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_p45.sh b/dataset/phase1_noise_20260906/code/run_uformer_p45.sh new file mode 100644 index 0000000000000000000000000000000000000000..a4220dfefc17f16b5e74f0d9cb5f073ef6136ac4 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_p45.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_p45_8k_seed42 +LOG=outputs/phase2_v7/uformer_p45_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_dgf8k_seed42/best.pt +WARMSTART_SHA=f92dc6d37ffe4e8a55ce723a1acf51042bf9821b98eefeaebb8ba140b7ce0f97 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_p45_8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=1 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.10 --noise-pair-prob 0.20 --global-context \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_p5.sh b/dataset/phase1_noise_20260906/code/run_uformer_p5.sh new file mode 100644 index 0000000000000000000000000000000000000000..c89b274eb6da857e97f5cfb48c0929dd126e80b9 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_p5.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_p5_8k_seed42 +LOG=outputs/phase2_v7/uformer_p5_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_dgf8k_seed42/best.pt +WARMSTART_SHA=f92dc6d37ffe4e8a55ce723a1acf51042bf9821b98eefeaebb8ba140b7ce0f97 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_p5_8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=0 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.10 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_v10.sh b/dataset/phase1_noise_20260906/code/run_uformer_v10.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c14f3d6dc7eebd163999a9dbfc38032f560260a --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_v10.sh @@ -0,0 +1,137 @@ +#!/bin/bash +# v10 chain (2026-09-04): runs AFTER uformer_v9a15k_seed42 finishes. +# 1. wait until the 15k trainer is gone (eval@15000, early stop, or death) +# 2. GPU0 evals of v9a15k best.pt: locked crop protocol (comparable to A/B/v9a-4k), +# native full-frame protocol (eval_full_frame.py) for v9a15k, A, v9a-4k, B, +# scene008 tone probe, then full-frame x8 TTA for v9a15k +# 3. GPU1 v10 = A recipe on Phase-1 v5f, warm-start v9a15k best (EMA) +# + whole-frame context + photometric head + exposure-diverse identity +# pairs from SIDD-train-GT / LOL-train-GT / Snow100K-gt (balanced) +# + v10 input pre-gain (Retinex-style) + global attention at stages 2,3 +# 4. GPU0 v10_ab = v10 minus pre-gain and global attention (isolates the two new blocks), +# launched when the evals are done +# Each run has its own AMP-overflow supervisor (resume from overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +SRC_NAME=uformer_v9a15k_seed42 +SRC_RUN=outputs/phase2_v7/$SRC_NAME +SRC_LOG=outputs/phase2_v7/uformer_v9a15k_train.log +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt +STEPS=${STEPS:-8000} +MAX_RESTARTS=20 +export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 + +log() { echo "[v10 $(date +%H:%M:%S)] $*"; } +src_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$SRC_NAME" >/dev/null; } +src_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": 15000\|\"step\": 15000.*\"event\": \"evaluation\"" "$SRC_RUN/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$SRC_LOG" 2>/dev/null +} + +# ---- 1. wait for the source run ------------------------------------------ # +quiet=0 +while true; do + if src_complete && ! src_running; then log "source run complete"; break; fi + if ! src_running; then + quiet=$((quiet + 1)) + if [ "$quiet" -ge 6 ]; then log "source trainer absent for 6 polls without completion; proceeding with its best.pt"; break; fi + else + quiet=0 + fi + sleep 60 +done +sleep 30 +WARM=$SRC_RUN/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +log "warm start $WARM sha=$WARM_SHA phase1=$PHASE1 sha=$PHASE1_SHA" + +# ---- shared recipe ---------------------------------------------------------- # +COMMON="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \ + --learning-rate 3e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,500,1000,2000,3000,4000,5000,6000,7000,8000 --milestone-steps 4000,8000 \ + --freeze-encoder-steps 1000 --early-stop-patience 4 --early-stop-min-delta 0.02 \ + --seed 42 --eval-seed 20260830 \ + --global-context --photometric-head --photometric-dropout 0.1 \ + --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6" +V10_EXTRA="--exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --global-attention-scales 2,3" + +launch() { # $1 name $2 gpu $3 fresh|resume $4 extra flags + local name=$1 gpu=$2 mode=$3 extra=$4 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log + local source + if [ "$mode" = "fresh" ]; then + source="--warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema" + else + source="--resume $run_dir/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $COMMON $extra $source \ + --output-dir "$run_dir" >> "$log" 2>&1 & + log "launched $name on GPU$gpu ($mode) pid $!" +} + +supervise() { # $1 name $2 gpu $3 extra flags + local name=$1 gpu=$2 extra=$3 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log + running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; } + complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $STEPS\|\"step\": $STEPS.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null + } + overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; } + local restarts=0 seen + seen=$(overflows) + if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$name" "$gpu" resume "$extra"; else launch "$name" "$gpu" fresh "$extra"; fi + sleep 180 + while true; do + if complete; then log "$name complete (eval @$STEPS or early stop)"; return 0; fi + if ! running; then + local current; current=$(overflows) + if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then + restarts=$((restarts + 1)); seen=$current + log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch "$name" "$gpu" resume "$extra"; sleep 180 + else + log "$name process died WITHOUT a new overflow (or budget exhausted); giving up"; return 1 + fi + fi + sleep 45 + done +} + +# ---- 3. v10 on GPU1 (starts immediately) ----------------------------------- # +( supervise uformer_v10_8k_seed42 1 "$V10_EXTRA" ) & +V10_PID=$! + +# ---- 2. evals of the source run on GPU0 ------------------------------------ # +run_eval() { log "eval: $*"; CUDA_VISIBLE_DEVICES=0 $PY -u "$@" >> outputs/phase2_v7/uformer_v10_evals.log 2>&1 || log "eval FAILED: $*"; } +run_eval eval_v7_external.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_external_v1.json +run_eval eval_full_frame.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_fullframe_v1.json --tta 1 +run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_p5_8k_seed42 --output outputs/v7_p5_fullframe_v1.json --tta 1 +run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_v9a_8k_seed42 --output outputs/v7_v9a4k_fullframe_v1.json --tta 1 +run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_p45_8k_seed42 --output outputs/v7_p45_fullframe_v1.json --tta 1 +run_eval probe_scene008_tone.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_scene008_tone.json --skip-val-baseline +run_eval eval_full_frame.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_fullframe_tta8_v1.json --tta 8 +log "evals done" + +# ---- 4. ablation on GPU0 ---------------------------------------------------- # +( supervise uformer_v10ab_8k_seed42 0 "" ) & +AB_PID=$! +wait $V10_PID; log "v10 supervisor exited ($?)" +wait $AB_PID; log "v10_ab supervisor exited ($?)" +log "chain finished" diff --git a/dataset/phase1_noise_20260906/code/run_uformer_v10ab_resume.sh b/dataset/phase1_noise_20260906/code/run_uformer_v10ab_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..b1b85e9973505853dc6764c8c21a8b9964c5154e --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_v10ab_resume.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# Resume uformer_v10ab_8k_seed42 from its overflow_recovery.pt after the +# 08:12 resume died on a contract mismatch (code synced mid-run added +# architecture keys; the runtime now tolerates added keys). Same recipe as +# run_uformer_v10.sh (v10_ab = COMMON without the v10 extras), GPU0, with the +# same overflow supervisor. +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +NAME=uformer_v10ab_8k_seed42 +RUN_DIR=outputs/phase2_v7/$NAME +LOG=outputs/phase2_v7/${NAME}_train.log +STEPS=8000 +GPU=${GPU:-0} +MAX_RESTARTS=20 +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt +export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 +log() { echo "[v10ab-resume $(date +%H:%M:%S)] $*"; } + +COMMON="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \ + --learning-rate 3e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,500,1000,2000,3000,4000,5000,6000,7000,8000 --milestone-steps 4000,8000 \ + --freeze-encoder-steps 1000 --early-stop-patience 4 --early-stop-min-delta 0.02 \ + --seed 42 --eval-seed 20260830 \ + --global-context --photometric-head --photometric-dropout 0.1 \ + --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6" + +running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $RUN_DIR" >/dev/null; } +complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $STEPS\|\"step\": $STEPS.*\"event\": \"evaluation\"" "$RUN_DIR/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$LOG" 2>/dev/null +} +overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null | head -n 1); echo "${n:-0}"; } +launch() { + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$GPU nohup $PY -u train_phase2_unified_v7.py $COMMON \ + --resume $RUN_DIR/overflow_recovery.pt --output-dir "$RUN_DIR" >> "$LOG" 2>&1 & + log "launched resume on GPU$GPU pid $!" +} + +[ -f "$RUN_DIR/overflow_recovery.pt" ] || { log "no overflow_recovery.pt; nothing to resume"; exit 1; } +if running; then log "already running"; exit 0; fi +restarts=0; seen=$(overflows) +launch; sleep 180 +while true; do + if complete; then log "complete"; break; fi + if ! running; then + current=$(overflows) + if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ]; then + restarts=$((restarts + 1)); seen=$current + log "relaunch #$restarts from overflow_recovery.pt (overflows=$current)"; launch; sleep 180 + else + log "died WITHOUT a new overflow; giving up"; break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_v11.sh b/dataset/phase1_noise_20260906/code/run_uformer_v11.sh new file mode 100644 index 0000000000000000000000000000000000000000..7aa20989b64d55817293af76a5a754a424218b1f --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_v11.sh @@ -0,0 +1,221 @@ +#!/bin/bash +# v11 chain (2026-09-05): capacity + budget + progressive resolution, both GPUs (DDP). +# 0. wait until the v10 chain is finished (no v10 supervisor, no trainer processes) +# 1. native full-frame + crop evals of v10 and v10_ab (GPU0 / GPU1 in parallel), then +# pick the warm start among {v10, v10_ab, v9a15k} by the mean of the four +# full-frame group PSNRs (lowlight LOLv2, rain Test1200 Y-channel, haze, scene008) +# 2. memory probe (GPU0) to pick per-stage batch sizes +# 3. stage A crop 256, 24k steps, DDP x2, LR 5e-5 +# stage B crop 320, 8k steps, DDP x2, LR 3e-5, warm-start best of A +# stage C crop 384, 8k steps, DDP x2 (or 1 GPU + grad checkpoint if the probe says so), LR 2e-5 +# recipe = v10 (pre-gain, global attention 2,3, whole-frame context, photometric head, +# exposure-diverse identity pools) + --extra-blocks-per-stage 0,2,4,4 (13.4M -> ~28.8M) +# 4. full-frame evals after every stage (TTA 1), TTA 8 after stage C +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt +MAX_RESTARTS=20 +MEM_BUDGET_GIB=${MEM_BUDGET_GIB:-19.5} +export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 +EVLOG=outputs/phase2_v7/uformer_v11_evals.log + +log() { echo "[v11 $(date +%H:%M:%S)] $*"; } +trainers_running() { pgrep -f "[t]rain_phase2_unified_v7.py" >/dev/null; } +v10_chain_running() { pgrep -f "[r]un_uformer_v10.sh" >/dev/null; } + +# ---- 0. wait for the GPUs ------------------------------------------------- # +while v10_chain_running || trainers_running; do sleep 120; done +log "GPUs free" +sleep 30 + +# ---- 1. evals of the v10 pair + warm-start selection ---------------------- # +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } +# WARM_OVERRIDE= skips the evaluation sweep and the +# selection (user request 2026-09-05: start DDP training right away). +if [ -n "${WARM_OVERRIDE:-}" ]; then + WARM=$WARM_OVERRIDE + WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) + log "warm start OVERRIDE: $WARM sha=$WARM_SHA (evaluation sweep skipped)" +fi +if [ -z "${WARM_OVERRIDE:-}" ]; then +# Whole-image single pass for images <= 1.2 MP (LOL / RESIDE / Test1200); the +# 12 MP SIDD frames stay tiled. Tiling costs -2.1 dB on LOLv2 (per-tile +# exposure inconsistency), so every full-frame number below uses this mode. +WHOLE="--whole-max-pixels 1200000" +# best.pt is picked by val macro, which is a poor proxy for the external +# sets, so every candidate run is evaluated at best / milestone / last and +# the warm start is the best (run, checkpoint) pair on the full-frame score. +ckpt_tag() { echo "$1" | sed 's/\.pt$//; s/milestone_0*/m/'; } +eval_run_checkpoints() { # $1 gpu $2 run $3 tag $4.. checkpoints + local gpu=$1 run=$2 tag=$3; shift 3 + run_eval "$gpu" eval_v7_external.py --run-dir outputs/phase2_v7/$run --output outputs/v7_${tag}_external_v1.json + for ck in "$@"; do + [ -f outputs/phase2_v7/$run/$ck ] || { log "skip missing $run/$ck"; continue; } + run_eval "$gpu" eval_full_frame.py --run-dir outputs/phase2_v7/$run --checkpoint "$ck" \ + --output outputs/v7_${tag}_$(ckpt_tag "$ck")_fullframe_whole_v1.json --tta 1 $WHOLE + done +} +( eval_run_checkpoints 0 uformer_v10_8k_seed42 v10 best.pt milestone_00004000.pt last.pt + eval_run_checkpoints 0 uformer_v9a15k_seed42 v9a15k best.pt milestone_00008000.pt last.pt ) & +( eval_run_checkpoints 1 uformer_v10ab_8k_seed42 v10ab best.pt milestone_00004000.pt last.pt ) & +wait +SELECTION=$($PY - <<'PYEOF' +import glob, json, os, re, sys +runs = {"v10": "uformer_v10_8k_seed42", "v10ab": "uformer_v10ab_8k_seed42", "v9a15k": "uformer_v9a15k_seed42"} +def score(path): + r = json.load(open(path)) + try: + return (r["lowlight_lolv2_test"]["restored"]["psnr"] + r["rain_locked"]["restored"]["psnr_y"] + + r["haze_heldout"]["restored"]["psnr"] + r["noise_locked_scene008"]["restored"]["psnr"]) / 4.0, r.get("checkpoint", "best.pt") + except KeyError: + return None, None +scores = {} +for tag, run in runs.items(): + for path in glob.glob("outputs/v7_%s_*_fullframe_whole_v1.json" % tag): + value, ck = score(path) + if value is not None and ck and os.path.exists("outputs/phase2_v7/%s/%s" % (run, ck)): + scores[(run, ck)] = value +if not scores: + print("uformer_v9a15k_seed42 best.pt") +else: + (run, ck) = max(scores, key=scores.get) + print(run, ck) +sys.stderr.write("warm-start scores: %s\n" % json.dumps({"%s/%s" % k: round(v, 3) for k, v in sorted(scores.items())})) +PYEOF +) +read -r SOURCE SOURCE_CKPT <<< "$SELECTION" +log "warm start selected: $SOURCE/$SOURCE_CKPT" +WARM=outputs/phase2_v7/$SOURCE/$SOURCE_CKPT +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +fi + +# ---- shared recipe -------------------------------------------------------- # +RECIPE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 4 --seed 42 --eval-seed 20260830 \ + --global-context --photometric-head --photometric-dropout 0.1 \ + --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4" + +# ---- 2. memory probe ------------------------------------------------------ # +probe() { # $1 crop $2 batch $3 extra -> peak GiB or 99 on failure + 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") + echo "$out" >> $EVLOG + 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)" +} +fits() { $PY -c "import sys; sys.exit(0 if float('$1') <= float('$MEM_BUDGET_GIB') else 1)"; } +pick_batch() { # $1 crop -> "batch accum" for DDP x2 with effective batch 16 (stdout = result only) + local crop=$1 peak + for cfg in "8 1" "4 2" "2 4"; do + set -- $cfg + peak=$(probe "$crop" "$1" "") + log "probe crop=$crop batch=$1 -> peak ${peak} GiB" >&2 + if fits "$peak"; then echo "$1 $2"; return 0; fi + done + echo "0 0" +} + +# ---- supervisor ----------------------------------------------------------- # +launch() { # name gpus mode(fresh|resume) crop batch accum steps lr evalsteps milestones extra warm + 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} + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log source + if [ "$mode" = "fresh" ]; then + source="--warmstart-v6 $warm --warmstart-v6-sha256 $(sha256sum $warm | cut -d' ' -f1) --warmstart-weight-source ema" + else + source="--resume $run_dir/overflow_recovery.pt" + fi + local common="$RECIPE $extra $source --output-dir $run_dir --crop-size $crop \ + --batch-size $batch --grad-accum $accum --eval-batch-size 4 \ + --learning-rate $lr --max-steps $steps --run-until-step $steps \ + --eval-steps $evals --milestone-steps $miles \ + --freeze-encoder-steps 1000 --early-stop-patience ${PATIENCE:-0} --early-stop-min-delta 0.02" + # shellcheck disable=SC2086 + if [ "$gpus" = "0,1" ]; then + CUDA_VISIBLE_DEVICES=0,1 nohup $PY -m torch.distributed.run --nproc_per_node=2 --master_port=29531 \ + train_phase2_unified_v7.py --ddp --ddp-find-unused $common >> "$log" 2>&1 & + else + CUDA_VISIBLE_DEVICES=$gpus nohup $PY -u train_phase2_unified_v7.py $common >> "$log" 2>&1 & + fi + log "launched $name on GPU$gpus ($mode, crop $crop, batch ${batch}x${accum}, $steps steps) pid $!" +} + +supervise() { # same args as launch (mode ignored) + local name=$1 gpus=$2 steps=$7 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log + running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; } + complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $steps\|\"step\": $steps.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null + } + overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; } + local restarts=0 seen; seen=$(overflows) + if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$1" "$2" resume "${@:4}"; else launch "$1" "$2" fresh "${@:4}"; fi + sleep 240 + while true; do + if complete; then log "$name complete"; return 0; fi + if ! running; then + local current; current=$(overflows) + if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then + restarts=$((restarts + 1)); seen=$current + log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch "$1" "$2" resume "${@:4}"; sleep 240 + else + log "$name died WITHOUT a new overflow (or budget exhausted); stopping the chain"; return 1 + fi + fi + sleep 60 + done +} + +stage_evals() { # $1 run name $2 tag $3 tta + run_eval 0 eval_v7_external.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_external_v1.json + 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 + 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 + if [ "$3" = "8" ]; then + # orientation-safe x2 (mirror) for every group; the full dihedral x8 only + # for isotropic noise (x8 costs -2.4 dB on rain / -1.0 dB on haze) + 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 + 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 + run_eval 1 probe_scene008_tone.py --run-dir outputs/phase2_v7/$1 --output outputs/v7_${2}_scene008_tone.json --skip-val-baseline + fi +} + +# ---- 3. stages ------------------------------------------------------------ # +A=uformer_v11a_256_seed42; B=uformer_v11b_320_seed42; C=uformer_v11c_384_seed42 + +read -r BA AA <<< "$(pick_batch 256)" +[ "$BA" = "0" ] && { log "no batch fits at 256; aborting"; exit 1; } +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 +stage_evals $A v11a 1 + +read -r BB AB <<< "$(pick_batch 320)" +[ "$BB" = "0" ] && { log "no batch fits at 320; aborting"; exit 1; } +# Stages warm-start from the END of the previous stage (last.pt = cosine +# schedule fully annealed): best.pt is picked by val macro, which does not +# track the external sets and can stay at the step-0 checkpoint. +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 +stage_evals $B v11b 1 + +read -r BC AC <<< "$(pick_batch 384)" +if [ "$BC" = "0" ]; then + log "384 does not fit without checkpointing on 2 ranks; running stage C on ONE GPU with --grad-checkpoint (batch 4 x accum 4)" + 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 +else + 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 +fi +stage_evals $C v11c 8 +log "chain finished" diff --git a/dataset/phase1_noise_20260906/code/run_uformer_v11_mi325x.sh b/dataset/phase1_noise_20260906/code/run_uformer_v11_mi325x.sh new file mode 100644 index 0000000000000000000000000000000000000000..2137ee21d595e3e7523d54327df0b91aa6f4614f --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_v11_mi325x.sh @@ -0,0 +1,120 @@ +#!/bin/bash +# v11 on the MI325X host (kim.long-mi325x8), ONE GPU (default 7), no DDP. +# Same recipe as run_uformer_v11.sh; the 256 GB card takes the whole +# effective batch in one micro-batch, so batch/LR/steps are re-scaled: +# stage A crop 256 BATCH_A (probe: 2.6 GiB/sample) LR_A STEPS_A +# stage B crop 320 BATCH_B LR_B STEPS_B warm-start A/last.pt +# stage C crop 384 BATCH_C LR_C STEPS_C warm-start B/last.pt +# Data roots come from the HF bundle (SCDC_DATA_ROOT / SCDC_RAIN13K_ROOT). +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +# map this host's roots back to the canonical ones for the audited split digests +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/ +GPU=${GPU:-7} +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +TAG=${TAG:-x} # run-name suffix: x = v11 on MI325X, v12 = Phase-1 v6 +WARM=${WARM:-outputs/phase2_v7/uformer_v10_8k_seed42/best.pt} +# identity-pair clean pools: TRAIN-split SIDD/LOL GTs only (built by make_clean_pools.py), plus Snow100K gt +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +# Probe on GPU 7 (30M params, crop 256): batch 16 -> 42 GiB 0.42 s (38 img/s), +# batch 32 -> 84 GiB 0.67 s (48 img/s), batch 64 -> 167 GiB 1.56 s (41 img/s), +# batch 96 OOM. Compute saturates at 32, so 32 gives the most images/s AND the +# most optimizer steps per hour; LR scaled by sqrt(32/16) from the 5e-5 recipe. +BATCH_A=${BATCH_A:-32}; LR_A=${LR_A:-7e-5}; STEPS_A=${STEPS_A:-20000} +BATCH_B=${BATCH_B:-20}; LR_B=${LR_B:-5e-5}; STEPS_B=${STEPS_B:-6000} +BATCH_C=${BATCH_C:-14}; LR_C=${LR_C:-3e-5}; STEPS_C=${STEPS_C:-6000} +WORKERS=${WORKERS:-32} +EXTRA_WORKERS=${EXTRA_WORKERS:-12} +export OMP_NUM_THREADS=${OMP_NUM_THREADS:-8} +MAX_RESTARTS=20 +EVLOG=outputs/phase2_v7/uformer_v11_${TAG}_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[v11x $(date +%H:%M:%S)] $*"; } + +RECIPE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers $WORKERS --extra-clean-workers $EXTRA_WORKERS --seed 42 --eval-seed 20260830 \ + --global-context --photometric-head --photometric-dropout 0.1 \ + --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4" + +launch() { # name mode(fresh|resume) crop batch steps lr evalsteps milestones warm + local name=$1 mode=$2 crop=$3 batch=$4 steps=$5 lr=$6 evals=$7 miles=$8 warm=$9 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log source + if [ "$mode" = "fresh" ]; then + source="--warmstart-v6 $warm --warmstart-v6-sha256 $(sha256sum $warm | cut -d' ' -f1) --warmstart-weight-source ema" + else + source="--resume $run_dir/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$GPU nohup $PY -u train_phase2_unified_v7.py $RECIPE $source --output-dir $run_dir \ + --crop-size $crop --batch-size $batch --grad-accum 1 --eval-batch-size 16 \ + --learning-rate $lr --max-steps $steps --run-until-step $steps \ + --eval-steps $evals --milestone-steps $miles \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02 >> "$log" 2>&1 & + log "launched $name on GPU$GPU ($mode, crop $crop, batch $batch, $steps steps, lr $lr) pid $!" +} + +supervise() { # same args as launch minus mode: name crop batch steps lr evals miles warm + local name=$1 steps=$4 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log + running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; } + complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $steps\|\"step\": $steps.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null + } + overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; } + local restarts=0 seen; seen=$(overflows) + if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$1" resume "${@:2}"; else launch "$1" fresh "${@:2}"; fi + sleep 240 + while true; do + if complete; then log "$name complete"; return 0; fi + if ! running; then + local current; current=$(overflows) + if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then + restarts=$((restarts + 1)); seen=$current + log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch "$1" resume "${@:2}"; sleep 240 + else + log "$name died WITHOUT a new overflow (or budget exhausted); stopping the chain"; return 1 + fi + fi + sleep 60 + done +} + +run_eval() { log "eval: $*"; CUDA_VISIBLE_DEVICES=$GPU $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } +stage_evals() { # run tag tta + run_eval eval_v7_external.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_external_v1.json + 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 + 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 + if [ "$3" = "8" ]; then + 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 + 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 + fi +} + +A=uformer_v11a_256_$TAG; B=uformer_v11b_320_$TAG; C=uformer_v11c_384_$TAG +log "warm start $WARM sha=$(sha256sum $WARM | cut -d' ' -f1) phase1 sha=$PHASE1_SHA GPU=$GPU" +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 +stage_evals $A v11a$TAG 1 +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 +stage_evals $B v11b$TAG 1 +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 +stage_evals $C v11c$TAG 8 +log "chain finished" diff --git a/dataset/phase1_noise_20260906/code/run_uformer_v8a.sh b/dataset/phase1_noise_20260906/code/run_uformer_v8a.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec8a6f2b1957505f839040be06b50012a7d96386 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_v8a.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# v8a: Phase-2 on Phase-1 v5 — A recipe (clean prior + tail 6) + whole-frame +# context (B) + global exposure controllable head + exposure-diverse identity +# pairs (Snow100K gt pool); chroma loss space = uv. Warm-start from A best. +# Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v8a_8k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v8a_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt +WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1) +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=0 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \ + --photometric-head --photometric-dropout 0.15 \ + --identity-exposure-jitter 0.9 \ + --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_v8b.sh b/dataset/phase1_noise_20260906/code/run_uformer_v8b.sh new file mode 100644 index 0000000000000000000000000000000000000000..585f1192944af2c249f656370aea5d677cf9493d --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_v8b.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# v8b: Phase-2 on Phase-1 v5 — A recipe (clean prior + tail 6) + whole-frame +# context (B) + global exposure controllable head + exposure-diverse identity +# pairs (Snow100K gt pool); chroma loss space = hv. Warm-start from A best. +# Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v8b_8k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v8b_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt +WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1) +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=1 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-chroma-space hv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \ + --photometric-head --photometric-dropout 0.15 \ + --identity-exposure-jitter 0.9 \ + --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_v8c.sh b/dataset/phase1_noise_20260906/code/run_uformer_v8c.sh new file mode 100644 index 0000000000000000000000000000000000000000..43aa51afdb3fc7e549c43c45c8f33c5efb8c0925 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_v8c.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# v8c: identical recipe to v8a (uv chroma) but conditioned on Phase-1 v5b +# (HVI photometric branch, real-snow OOD). Isolates the Phase-1 choice vs v8a +# (ll_v3). Warm-start from A best (trunk was trained under ll_v3 conditioning). +# Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v8c_8k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v8c_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt +WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1) +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5b/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=1 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \ + --photometric-head --photometric-dropout 0.15 \ + --identity-exposure-jitter 0.9 \ + --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_uformer_v9b.sh b/dataset/phase1_noise_20260906/code/run_uformer_v9b.sh new file mode 100644 index 0000000000000000000000000000000000000000..b8b5a722ebab86642ad32b0a68852d871a590b0e --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_uformer_v9b.sh @@ -0,0 +1,103 @@ +#!/bin/bash +# v9b: Phase-2 on Phase-1 v5f — A recipe + whole-frame context (B) + global +# exposure controllable head + exposure-diverse identity pairs (Snow100K gt); +# chroma loss space = uv. Warm-start from A best. Pairs with v9a (plain A +# recipe on the same Phase-1) to separate 'better Phase-1' from 'v8 features'. +# Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v9b_8k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v9b_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt +WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1) +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + # The whole-frame context path peaks at ~22 GB of the 24 GB card with + # batch 8, which OOMs as soon as a resume adds the optimizer moments up + # front. Half the micro-batch, twice the accumulation: same effective + # batch 16, ~11 GB peak. + CUDA_VISIBLE_DEVICES=1 PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \ + --photometric-head --photometric-dropout 0.15 \ + --identity-exposure-jitter 0.9 \ + --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { local n; n=$(grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null | head -n 1); echo "${n:-0}"; } + +restarts=0 +seen_overflows=$(overflow_count) +if [ -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] resuming from an existing overflow_recovery.pt phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows in log: $seen_overflows)" + launch resume +else + echo "[supervisor] fresh launch phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows in log: $seen_overflows)" + launch fresh +fi +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/run_v12_mi325x.sh b/dataset/phase1_noise_20260906/code/run_v12_mi325x.sh new file mode 100644 index 0000000000000000000000000000000000000000..6d9a239c0d4e0efded1d7bc642182f602d85e818 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_v12_mi325x.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# v12 on the MI325X host, ONE GPU (default 5): +# stage 0 Phase-1 v6 = v5f recipe + oriented Haar bands (rain vs snow/noise) +# + root weight 1.0 (clean images collapse to the root in global space) +# + OOD global margin 0.25 (snow away from known-type centroids) +# stage 1+ Phase-2 v11 recipe chained on Phase-1 v6 (run_uformer_v11_mi325x.sh, TAG=v12) +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +GPU=${GPU:-5} +NAME=phase1_v6 +CACHE=outputs/phase1_cache/sidd_native_256 +log() { echo "[v12 $(date +%H:%M:%S)] $*"; } + +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 12 --no-amp --seed 42 \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \ + --ood-real-root $SCDC_DATA_ROOT/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $SCDC_DATA_ROOT/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \ + --crop-select random --severity-floor 0.05 \ + --ll-oriented-bands --root-weight 1.0 --ood-global-margin-weight 0.25" + +mkdir -p outputs/$NAME +[ -f outputs/$NAME/severity_calibration.json ] || cp outputs/phase1_v5f/severity_calibration.json outputs/$NAME/ 2>/dev/null +if ! grep -q "Training complete" outputs/${NAME}_train.log 2>/dev/null; then + log "stage 0: Phase-1 v6 on GPU$GPU" + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$GPU $PY -u train_graph_encoder_v2.py $COMMON --output-dir outputs/$NAME > outputs/${NAME}_train.log 2>&1 + grep -q "Training complete" outputs/${NAME}_train.log || { log "Phase-1 v6 did not finish; see outputs/${NAME}_train.log"; exit 1; } +fi +log "Phase-1 v6 done: $(grep -o 'best.*' outputs/${NAME}_train.log | tail -n 1 | cut -c1-120)" +[ -f outputs/$NAME/graph_encoder_best.pt ] || { log "no graph_encoder_best.pt"; exit 1; } +log "stage 1+: Phase-2 v12 chain on GPU$GPU" +PHASE1_CKPT=outputs/$NAME/graph_encoder_best.pt TAG=v12 GPU=$GPU bash run_uformer_v11_mi325x.sh diff --git a/dataset/phase1_noise_20260906/code/run_v8_after_v5.sh b/dataset/phase1_noise_20260906/code/run_v8_after_v5.sh new file mode 100644 index 0000000000000000000000000000000000000000..9357388d3a9ab6882716c8c2bffdb1fc24f9121a --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_v8_after_v5.sh @@ -0,0 +1,91 @@ +#!/bin/bash +# Chain: wait for the Phase-1 v5 candidates to finish, run the sanity +# dashboard + real-snow gate on each, pick the best passing candidate, then +# launch the two Phase-2 v8 supervisors (v8a GPU0 = UV chroma, v8b GPU1 = HV +# chroma) on it. Stops before spending 2x8h GPU when no candidate passes. +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CANDIDATES=${CANDIDATES:-"phase1_v5 phase1_v5b"} + +wait_for() { # $1 = run name + local dir=outputs/$1 log=outputs/$1_train.log + while true; do + if [ -f "$dir/locked_test_metrics.json" ] && grep -q "Training complete" "$log" 2>/dev/null; then return 0; fi + if grep -q "Traceback" "$log" 2>/dev/null && ! pgrep -f "[t]rain_graph_encoder_v2.py.*$1" >/dev/null; then + local age=$(( $(date +%s) - $(stat -c %Y "$log") )) + if [ "$age" -gt 120 ]; then echo "[chain] $1 crashed (log idle ${age}s)"; return 1; fi + fi + sleep 120 + done +} + +gate_for() { # $1 = run name ; writes outputs/$1_gate.json ; prints pass/score + local name=$1 ckpt=outputs/$1/graph_encoder_best.pt + CUDA_VISIBLE_DEVICES=0 $PY visualize_phase1_graph.py --checkpoint $ckpt --output-dir outputs/phase1_vis/$name > outputs/phase1_vis_$name.log 2>&1 + CAND=$name CUDA_VISIBLE_DEVICES=0 $PY - <<'PYEOF' > outputs/${name}_gate.log 2>&1 +import glob, hashlib, json, math, os, torch, numpy as np +from pathlib import Path +from PIL import Image +import train_phase2_graph_resshift_v4 as v4 +from visualize_phase1_graph import encode, NODES +name = os.environ["CAND"] +files = sorted(glob.glob("/home/admin_mcn/data/Snow100K/realistic/**/*.jpg", recursive=True)) +def load(f): + im = Image.open(f).convert("RGB"); w, h = im.size; s = 256 / min(w, h) + if s > 1: im = im.resize((max(256, math.ceil(w * s)), max(256, math.ceil(h * s))), Image.LANCZOS); w, h = im.size + l, t = (w - 256) // 2, (h - 256) // 2 + return torch.from_numpy(np.asarray(im.crop((l, t, l + 256, t + 256)), dtype=np.float32) / 255.).permute(2, 0, 1) +imgs = torch.stack([load(f) for f in files]) +ck = Path("outputs/%s/graph_encoder_best.pt" % name) +p1, _ = v4.build_frozen_phase1(ck, hashlib.sha256(ck.read_bytes()).hexdigest(), torch.device("cuda")) +enc = encode(p1, imgs.cuda()) +route = dict(zip(NODES, enc["routing"].mean(0).tolist())) +summary = json.load(open("outputs/phase1_vis/%s/summary.json" % name)) +conf = summary["confusion"] +row = lambda prefix: next(v for k, v in conf.items() if k.startswith(prefix)) +hist = json.load(open("outputs/%s/history.json" % name)) +best_f1 = max(e["val"].get("macro_f1", 0.0) for e in hist if "val" in e) +gates = { + "snow_real_free": (route["free1"] + route["free2"], 0.70, ">="), + # not worse than ll_v3 (0.46 haze->rain on the same val); the +0.3 dB + # claim for v8 does not depend on Phase-1 routing improving, only on it + # not regressing and on photometric_state existing. + "haze_to_rain_max": (row("Haze input")["rain"], 0.46, "<="), + "rain_to_rain_min": (row("Rain input")["rain"], 0.55, ">="), + "lowlight_to_lowlight_min": (row("Low-light input")["lowlight"], 0.85, ">="), +} +passed = {k: (v[0] >= v[1] if v[2] == ">=" else v[0] <= v[1]) for k, v in gates.items()} +report = {"candidate": name, "sha256": hashlib.sha256(ck.read_bytes()).hexdigest(), "snow_real_routing": route, + "gates": {k: {"value": v[0], "threshold": v[1], "pass": passed[k]} for k, v in gates.items()}, + "n_pass": int(sum(passed.values())), "pass": bool(all(passed.values())), "best_val_macro_f1": best_f1, + "noise_recall": row("Noise input")["noise"]} +Path("outputs/%s_gate.json" % name).write_text(json.dumps(report, indent=2)) +print(json.dumps(report)) +PYEOF + $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']))" +} + +best_name=""; best_key="" +for cand in $CANDIDATES; do + echo "[chain] waiting for $cand" + if ! wait_for $cand; then continue; fi + sleep 20 + echo "[chain] $cand done: $(sha256sum outputs/$cand/graph_encoder_best.pt | cut -c1-16); dashboard + gate" + read -r pass npass f1 <<< "$(gate_for $cand)" + echo "[chain] $cand gate pass=$pass n_pass=$npass best_val_f1=$f1 (outputs/${cand}_gate.json)" + key=$(printf "%d.%d.%s" "$pass" "$npass" "$f1") + if [ -z "$best_name" ] || [ "$(printf '%s\n%s\n' "$best_key" "$key" | sort -t. -k1,1n -k2,2n -k3,3n | tail -1)" = "$key" ]; then + best_name=$cand; best_key=$key + fi +done +if [ -z "$best_name" ]; then echo "[chain] no candidate finished; aborting"; exit 1; fi +if [ "${best_key%%.*}" != "1" ]; then + echo "[chain] GATE FAIL for every candidate (best=$best_name key=$best_key); NOT launching v8"; exit 2 +fi +export PHASE1_CKPT=outputs/$best_name/graph_encoder_best.pt +echo "[chain] GATE PASS -> $best_name ($PHASE1_CKPT); launching v8a (GPU0) and v8b (GPU1)" +nohup bash run_uformer_v8a.sh > outputs/phase2_v7/uformer_v8a_supervisor.log 2>&1 < /dev/null & +sleep 120 +nohup bash run_uformer_v8b.sh > outputs/phase2_v7/uformer_v8b_supervisor.log 2>&1 < /dev/null & +echo "[chain] both supervisors launched" diff --git a/dataset/phase1_noise_20260906/code/run_v8_postrun.sh b/dataset/phase1_noise_20260906/code/run_v8_postrun.sh new file mode 100644 index 0000000000000000000000000000000000000000..d5586ecb6827e591146e678472440fcdad569388 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/run_v8_postrun.sh @@ -0,0 +1,35 @@ +#!/bin/bash +# After both v8 supervisors finish: per-run external eval, global-knob probe +# (how much of the oracle exposure gain the head captured), scene008 tone +# probe, qualitative grids; then the Phase-2 dose sweep for the head. +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +done_run() { grep -q "run complete" "outputs/phase2_v7/uformer_$1_supervisor.log" 2>/dev/null; } +dead_run() { grep -qE "not restarting|exhausted|no recovery" "outputs/phase2_v7/uformer_$1_supervisor.log" 2>/dev/null; } +A_TAG=${A_TAG:-v8a}; B_TAG=${B_TAG:-v8b} +echo "[postrun] waiting for $A_TAG and $B_TAG supervisors" +while true; do + a_ok=0; b_ok=0 + if done_run $A_TAG || dead_run $A_TAG; then a_ok=1; fi + if done_run $B_TAG || dead_run $B_TAG; then b_ok=1; fi + if [ "$a_ok" = 1 ] && [ "$b_ok" = 1 ]; then break; fi + sleep 300 +done +sleep 60 +pkill -f "[t]rain_phase2_unified_v7.py.*uformer_v8" 2>/dev/null; sleep 20 +for pair in "$A_TAG 0" "$B_TAG 1"; do + set -- $pair; TAG=$1; GPU=$2; R=outputs/phase2_v7/uformer_${TAG}_8k_seed42 + if [ ! -f "$R/best.pt" ]; then echo "[postrun] $TAG has no best.pt; skipping"; continue; fi + ( + CUDA_VISIBLE_DEVICES=$GPU $PY eval_v7_external.py --run-dir $R --output outputs/v7_${TAG}_external_v1.json + CUDA_VISIBLE_DEVICES=$GPU $PY eval_v7_external.py --run-dir $R --output outputs/v7_${TAG}_external_pdose0.json --photometric-dose 0 + CUDA_VISIBLE_DEVICES=$GPU $PY probe_global_knob.py --run-dir $R --output outputs/global_knob_probe_${TAG}.json + CUDA_VISIBLE_DEVICES=$GPU $PY probe_scene008_tone.py --run-dir $R --output outputs/v7_${TAG}_scene008_tone.json --skip-val-baseline + CUDA_VISIBLE_DEVICES=$GPU $PY visualize_v7_uformer.py --run-dir $R --per-domain 3 + CUDA_VISIBLE_DEVICES=$GPU $PY visualize_scene008.py --run-dir $R --output $R/vis/scene008.png --count 3 + echo "[postrun] $TAG done" + ) > outputs/phase2_v7/${TAG}_postrun.log 2>&1 & +done +wait +echo "POSTRUN-ALL-DONE" diff --git a/dataset/phase1_noise_20260906/code/supervise_uformer16k.sh b/dataset/phase1_noise_20260906/code/supervise_uformer16k.sh new file mode 100644 index 0000000000000000000000000000000000000000..e73d0f286f3ccd72f6278d544df12c0c51b4f058 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/supervise_uformer16k.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# Auto-resume supervisor for outputs/phase2_v7/uformer16k_seed42. +# Relaunches training from overflow_recovery.pt after each designed +# RecoverableAmpOverflow exit; stops on completion (step 16000 evaluated), +# on any non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer16k_seed42 +LOG=outputs/phase2_v7/uformer16k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +restarts=0 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer16k_seed42" >/dev/null; } +is_complete() { grep -q '"event": "evaluation".*"step": 16000\|"step": 16000.*"event": "evaluation"' "$RUN_DIR/metrics.jsonl" 2>/dev/null; } + +launch() { + nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused --backbone uformer --timesteps 2 \ + --resume "$RUN_DIR/overflow_recovery.pt" \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-vgg-weight 0.1 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 5e-5 --max-steps 16000 --run-until-step 16000 \ + --eval-steps 0,1000,2000,3000,4000,6000,8000,10000,12000,14000,16000 \ + --milestone-steps 4000,8000,12000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +seen_overflows=$(overflow_count) +echo "[supervisor] start; overflows so far: $seen_overflows" + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @16000 present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ] || [ "$restarts" -eq 0 ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] no recovery checkpoint; refusing to relaunch" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/code/test_train_graph_encoder_v2.py b/dataset/phase1_noise_20260906/code/test_train_graph_encoder_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d97a83d38898b616f066d0acbbcc712c806dcd68 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/test_train_graph_encoder_v2.py @@ -0,0 +1,908 @@ +from pathlib import Path +from types import SimpleNamespace + +import math + +import pytest +import torch +import torch.nn as nn + +import train_graph_encoder_v2 as v2 +from src.models.graph_encoder.representation import aggregate_graph_condition + + +def _record(index, degradation="haze", group=None, dataset="RESIDE"): + source = str(index) + return v2.PairRecord( + degraded=Path("/deg") / (source + ".png"), + clean=Path("/clean") / (source + ".png"), + degradation=degradation, + dataset=dataset, + source_id=source, + split_group=group or source, + ) + + +def _png(path, value=0): + path.parent.mkdir(parents=True, exist_ok=True) + v2.Image.new("RGB", (12, 8), color=(value, value, value)).save(path) + + +def test_real_branch_order_preserves_deployed_positional_semantics(): + assert v2.BRANCH_ORDER == ("rain", "noise", "haze", "lowlight") + assert v2.BRANCH_TO_INDEX == { + "rain": 0, + "noise": 1, + "haze": 2, + "lowlight": 3, + } + + +def test_reside_first_5000_has_source_isolated_first_100_validation(): + records = [] + records.extend(_record(i, group="val-a") for i in range(95)) + records.extend(_record(i + 95, group="val-leak") for i in range(5)) + records.extend(_record(i + 100, group="val-leak") for i in range(5)) + records.extend(_record(i + 105) for i in range(4895)) + + train, val = v2.split_reside_records(records, limit=5000, val_count=100) + + assert len(val) == 100 + assert len(train) == 4895 + assert {r.split_group for r in train}.isdisjoint( + {r.split_group for r in val} + ) + + +def test_sidd_split_is_scene_disjoint_with_audited_live_counts(): + scene_counts = { + "001": 28, "002": 15, "003": 15, "004": 15, "005": 19, + "006": 19, "007": 20, "008": 20, "009": 6, "010": 3, + } + records = [] + index = 0 + for scene, count in scene_counts.items(): + for _ in range(count): + records.append(_record(index, "noise", scene, "SIDD")) + index += 1 + + train, val, locked = v2.split_sidd_records(records) + + assert (len(train), len(val), len(locked)) == (121, 19, 20) + groups = [{r.split_group for r in split} for split in (train, val, locked)] + assert groups[0].isdisjoint(groups[1]) + assert groups[0].isdisjoint(groups[2]) + assert groups[1].isdisjoint(groups[2]) + assert groups[1] == {"006"} + assert groups[2] == {"008"} + + +def test_sidd_scene_number_is_second_folder_token(): + assert v2.sidd_scene_number("0192_009_IP_00100_00200_3200_N") == "009" + with pytest.raises(ValueError, match="SIDD source directory"): + v2.sidd_scene_number("malformed") + + +def test_live_layout_discovery_and_source_leakage_guard(tmp_path): + lol = tmp_path / "lol" + _png(lol / "Train/Input/00001.png", 10) + _png(lol / "Train/GT/00001.png", 20) + assert len(v2.discover_lol_records(lol, "Train")) == 1 + + reside = tmp_path / "reside" + _png(reside / "clear/0001.jpg", 20) + _png(reside / "hazy/0001_0.8_0.1.jpg", 10) + assert v2.discover_reside_records(reside)[0].split_group == "0001" + + sidd = tmp_path / "sidd" + for scene in range(1, 11): + source = sidd / ("%04d_%03d_IP_00100_00200_3200_N" % (scene, scene)) + _png(source / "NOISY_SRGB_010.PNG", 10) + _png(source / "GT_SRGB_010.PNG", 20) + sidd_records = v2.discover_sidd_records(sidd) + parts = v2.split_sidd_records(sidd_records) + assert [len(part) for part in parts] == [8, 1, 1] + + shared = _record(0, group="same") + splits = v2.DataSplits((shared,), (shared,), (), 0) + with pytest.raises(ValueError, match="source leakage"): + v2.assert_split_isolation(splits) + + shared_clean = tmp_path / "shared-clean.png" + _png(shared_clean, 77) + train = v2.PairRecord( + shared_clean, shared_clean, "rain", "Rain13K", "a", "rain-a" + ) + val = v2.PairRecord( + shared_clean, shared_clean, "lowlight", "LOLv2", "b", "lol-b" + ) + with pytest.raises(ValueError, match="clean-content leakage"): + v2.assert_split_isolation(v2.DataSplits((train,), (val,), (), 0)) + + +def test_rain_adapter_uses_quarantine_and_only_test100_test1200(monkeypatch, tmp_path): + pairs = [] + for index in range(3): + degraded = tmp_path / ("d%d.png" % index) + clean = tmp_path / ("c%d.png" % index) + _png(degraded, index) + _png(clean, index + 1) + pairs.append((degraded, clean)) + captured = {} + + def fake_loader(root, **kwargs): + captured.update(kwargs) + return SimpleNamespace( + train_pairs=(pairs[0],), + official_test_pairs={"Test100": (pairs[1],), "Test1200": (pairs[2],)}, + quarantined_train_pair_count=1155, + ) + + monkeypatch.setattr(v2, "load_rain13k_resized", fake_loader) + train, val, locked, count = v2.build_rain_records(tmp_path, tmp_path / "q.json") + assert (len(train), len(val), len(locked), count) == (1, 1, 1, 1155) + assert captured["max_train_pairs"] == 0 + assert captured["quarantine_manifest"] == tmp_path / "q.json" + + +def test_build_data_splits_composes_domains_and_checks_counts(monkeypatch, tmp_path): + rain = _record(1, "rain", "r1", "Rain13K") + low_train = _record(2, "lowlight", "l1", "LOLv2") + low_val = _record(3, "lowlight", "l2", "LOLv2") + haze_train = _record(4, "haze", "h1", "RESIDE") + haze_val = _record(5, "haze", "h2", "RESIDE") + noise_train = _record(6, "noise", "n1", "SIDD") + noise_val = _record(7, "noise", "n2", "SIDD") + noise_test = _record(8, "noise", "n3", "SIDD") + monkeypatch.setattr(v2, "build_rain_records", lambda *args: ([rain], [rain], [rain], 1)) + monkeypatch.setattr( + v2, "discover_lol_records", + lambda root, split: [low_train] if split == "Train" else [low_val], + ) + monkeypatch.setattr(v2, "discover_reside_records", lambda root: [haze_train, haze_val]) + monkeypatch.setattr(v2, "split_reside_records", lambda *args: ([haze_train], [haze_val])) + monkeypatch.setattr(v2, "discover_sidd_records", lambda root: [noise_train, noise_val, noise_test]) + monkeypatch.setattr( + v2, "split_sidd_records", lambda records: ([noise_train], [noise_val], [noise_test]) + ) + monkeypatch.setattr(v2, "assert_split_isolation", lambda splits: None) + args = v2.build_parser().parse_args( + ["--data-root", str(tmp_path), "--allow-count-mismatch"] + ) + splits = v2.build_data_splits(args) + assert (len(splits.train), len(splits.val), len(splits.locked_test)) == (4, 4, 2) + + +def test_sidd_cache_is_main_process_only_and_calibration_is_persisted(tmp_path): + records = [] + for index, degradation in enumerate(v2.BRANCH_ORDER): + degraded = tmp_path / degradation / "degraded.png" + clean = tmp_path / degradation / "clean.png" + _png(degraded, 40 + index * 10) + _png(clean, 10) + records.append( + v2.PairRecord( + degraded, clean, degradation, + "SIDD" if degradation == "noise" else degradation, + str(index), str(index), + ) + ) + cache = tmp_path / "cache" + calibration = { + name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + for name in v2.BRANCH_ORDER + } + dataset = v2.PairDataset(records, 8, calibration, cache) + dataset.prepare_cache() + assert len(list(cache.glob("*.png"))) == 2 + sample = dataset[1] + assert sample["degraded"].shape == (3, 8, 8) + assert 0 <= sample["severity"] <= 1 + + output = tmp_path / "calibration.json" + fitted = v2.fit_training_calibration(records, 8, output, cache) + first_fingerprint = v2.json.loads(output.read_text(encoding="utf-8"))["fingerprint"] + assert set(fitted) == set(v2.BRANCH_ORDER) + assert all(values["pixel_q95"] > 0 for values in fitted.values()) + assert v2.fit_training_calibration(records, 8, output, cache) == fitted + + sidd_record = records[1] + old_paths = dataset._cache_paths(sidd_record) + old_mtime = sidd_record.degraded.stat().st_mtime_ns + _png(sidd_record.degraded, 222) + v2.os.utime( + sidd_record.degraded, + ns=(old_mtime + 1_000_000_000, old_mtime + 1_000_000_000), + ) + new_paths = dataset._cache_paths(sidd_record) + assert new_paths != old_paths + dataset.prepare_cache() + assert all(path.is_file() for path in new_paths) + v2.fit_training_calibration(records, 8, output, cache) + second_fingerprint = v2.json.loads(output.read_text(encoding="utf-8"))["fingerprint"] + assert second_fingerprint != first_fingerprint + + +def test_balanced_batch_sampler_is_exact_and_seeded_with_replacement(): + labels = [0, 0, 0, 1, 2, 3] + sampler_a = v2.BalancedBatchSampler(labels, batch_size=8, steps=3, seed=17) + sampler_b = v2.BalancedBatchSampler(labels, batch_size=8, steps=3, seed=17) + + batches_a = list(sampler_a) + assert batches_a == list(sampler_b) + assert len(batches_a) == 3 + for batch in batches_a: + assert [labels[i] for i in batch].count(0) == 2 + assert [labels[i] for i in batch].count(1) == 2 + assert [labels[i] for i in batch].count(2) == 2 + assert [labels[i] for i in batch].count(3) == 2 + with pytest.raises(ValueError, match="divisible"): + v2.BalancedBatchSampler(labels, batch_size=6, steps=1, seed=17) + + +def test_severity_proxy_is_deterministic_and_bounded(): + clean = torch.zeros(3, 4, 4) + degraded = torch.full((3, 4, 4), 0.25) + first = v2.residual_mae_severity(degraded, clean, 0.1, 0.4) + second = v2.residual_mae_severity(degraded, clean, 0.1, 0.4) + assert first.item() == pytest.approx(0.5) + assert torch.equal(first, second) + with pytest.raises(ValueError, match="p95"): + v2.residual_mae_severity(degraded, clean, 0.4, 0.4) + + +def test_spatial_supervision_rewards_selected_branch_and_suppresses_inactive(): + clean = torch.zeros(2, 3, 8, 8) + degraded = torch.ones(2, 3, 8, 8) + labels = torch.tensor([0, 2]) + q95 = torch.ones(4) + good = torch.zeros(2, 4, 2, 2) + good[0, 0] = 1 + good[1, 2] = 1 + bad = 1 - good + + good_loss, good_metrics = v2.spatial_supervision_loss( + good, degraded, clean, labels, q95 + ) + bad_loss, _ = v2.spatial_supervision_loss( + bad, degraded, clean, labels, q95 + ) + + assert good_loss < bad_loss + assert good_metrics["spatial_selected_mae"] == pytest.approx(0.0) + assert good_metrics["spatial_inactive_activation"] == pytest.approx(0.0) + + +def test_clean_forward_keeps_bn_statistics_frozen_but_allows_gradients(): + class TinyGraph(nn.Module): + def __init__(self): + super().__init__() + self.bn = nn.BatchNorm2d(3) + + def forward_student(self, image): + return self.bn(image) + + model = TinyGraph().train() + before = model.bn.running_mean.clone() + clean = torch.randn(2, 3, 4, 4, requires_grad=True) + + result = v2.forward_clean_bn_safe(model, clean) + result.sum().backward() + + assert torch.equal(model.bn.running_mean, before) + assert clean.grad is not None + assert model.training and model.bn.training + + +def test_free_tokens_are_scaled_by_absolute_posterior_mass(): + class ZeroBranch: + def get_branch_embedding(self, severity): + return torch.zeros(severity.shape[0], 1) + + tokens = torch.tensor([[[0.0], [10.0], [20.0]]]) + routing = torch.tensor([[1.0, 0.0, 0.0]]) + result = aggregate_graph_condition( + tokens, routing, torch.zeros(1, 1), [ZeroBranch()] + ) + assert torch.equal(result, torch.zeros_like(result)) + + +def test_semantic_token_affects_condition_only_when_its_route_is_active(): + class ZeroBranch: + def get_branch_embedding(self, severity): + return torch.zeros(severity.shape[0], 1) + + base = torch.tensor([[[1.0], [0.0], [0.0]]]) + changed = torch.tensor([[[3.0], [0.0], [0.0]]]) + active = torch.tensor([[1.0, 0.0, 0.0]]) + inactive = torch.tensor([[0.0, 0.5, 0.5]]) + args = (torch.zeros(1, 1), [ZeroBranch()]) + + assert not torch.equal( + aggregate_graph_condition(base, active, *args), + aggregate_graph_condition(changed, active, *args), + ) + assert torch.equal( + aggregate_graph_condition(base, inactive, *args), + aggregate_graph_condition(changed, inactive, *args), + ) + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_aggregation_preserves_amp_dtype(dtype): + class ZeroBranch: + def get_branch_embedding(self, severity): + return severity.new_zeros((severity.shape[0], 2)) + + result = aggregate_graph_condition( + torch.ones(1, 3, 2, dtype=dtype), + torch.tensor([[1.0, 0.0, 0.0]], dtype=dtype), + torch.zeros(1, 1, dtype=dtype), + [ZeroBranch()], + ) + assert result.dtype == dtype + + +def test_validation_metrics_include_per_class_and_safe_constant_correlation(): + metrics = v2.compute_validation_metrics( + labels=[0, 0, 1, 1], + predictions=[0, 4, 1, 5], + severity_targets=[0.5, 0.5, 0.2, 0.8], + severity_predictions=[0.5, 0.5, 0.3, 0.7], + unknown_routing=[0.1, 0.2, 0.3, 0.4], + entropies=[0.2, 0.2, 0.4, 0.4], + losses=[1.0, 1.0, 2.0, 2.0], + spatial_mae=[0.1, 0.1, 0.2, 0.2], + inactive_activation=[0.0, 0.0, 0.1, 0.1], + ) + assert metrics["accuracy"] == 0.5 + assert metrics["macro_f1"] < 1.0 + assert metrics["balanced_accuracy"] == 0.5 + assert len(metrics["confusion_matrix"]) == 4 + assert all(len(row) == 6 for row in metrics["confusion_matrix"]) + assert metrics["per_class"]["rain"]["severity_spearman"] == 0.0 + assert "spatial_selected_mae" in metrics["per_class"]["noise"] + + +def test_checkpoint_keeps_phase2_schema_and_trainer_state_separate(tmp_path): + model = nn.Linear(2, 2) + head = nn.Linear(2, 4) + payload = v2.make_checkpoint( + model=model, + aux_classifier=head, + optimizer=None, + scheduler=None, + scaler=None, + epoch=0, + best_score=0.2, + config={"branch_order": list(v2.BRANCH_ORDER)}, + provenance={"counts": {"train": 1}}, + history=[{"epoch": 0}], + severity_calibration={"rain": {"p05": 0.1, "p95": 0.5}}, + ) + assert payload["model_state_dict"].keys() == model.state_dict().keys() + assert "global_type_head" in payload["trainer_state"] + assert payload["branch_order"] == list(v2.BRANCH_ORDER) + + +def test_checkpoint_loader_rejects_legacy_aggregation_or_branch_semantics(tmp_path): + model = nn.Linear(2, 2) + checkpoint_path = tmp_path / "legacy.pt" + torch.save( + { + "model_state_dict": model.state_dict(), + "aggregation_version": 1, + "branch_order": ["blur", "noise", "jpeg", "lowlight"], + }, + checkpoint_path, + ) + with pytest.raises(ValueError, match="aggregation_version"): + v2._load_encoder_checkpoint(checkpoint_path, model, None, torch.device("cpu")) + + +def test_cli_requires_explicit_final_test_and_has_output_path(): + args = v2.build_parser().parse_args([]) + assert args.output_dir + assert args.run_final_test is False + + +def test_checkpoint_selection_is_lexicographic_by_macro_f1(): + better_f1 = {"macro_f1": 0.81, "severity_mae": 0.9, "spatial_selected_mae": 0.9} + better_aux = {"macro_f1": 0.80, "severity_mae": 0.0, "spatial_selected_mae": 0.0} + assert v2.selection_key(better_f1) > v2.selection_key(better_aux) + + +def test_supervised_objective_is_finite_and_backpropagates_all_core_losses(): + def graph(batch=2, dim=4): + return SimpleNamespace( + routing_probs=torch.softmax(torch.randn(batch, 6, requires_grad=True), -1), + severity_coords=torch.sigmoid(torch.randn(batch, 4, requires_grad=True)), + global_condition=torch.randn(batch, dim, requires_grad=True), + content_latent=torch.randn(batch, dim, 2, 2, requires_grad=True), + spatial_maps=torch.sigmoid(torch.randn(batch, 4, 2, 2, requires_grad=True)), + unknown_residual=torch.randn(batch, dim, requires_grad=True), + ) + + objective = v2.Phase1GraphObjective(node_dim=4) + degraded = torch.ones(2, 3, 8, 8) + clean = torch.zeros_like(degraded) + labels = torch.tensor([0, 2]) + result = objective( + graph(), graph(), degraded, clean, labels, + torch.tensor([0.3, 0.7]), torch.ones(4), torch.zeros(1, 4), + ) + result["total"].backward() + + assert torch.isfinite(result["total"]) + for key in ("route", "global_type", "severity", "root", "spatial"): + assert key in result and torch.isfinite(result[key]) + assert objective.global_type_head.weight.grad is not None + + +def test_real_encoder_balanced_batch_trains_semantic_tokens_and_strictly_reloads(): + config = v2.GraphConfig( + latent_channels=16, + node_dim=32, + spatial_map_size=(4, 4), + ) + model = v2.BlindDegradationGraphEncoder(config).train() + objective = v2.Phase1GraphObjective(node_dim=32) + clean = torch.rand(4, 3, 16, 16) + degraded = (clean + 0.1 * torch.rand_like(clean)).clamp(0, 1) + labels = torch.arange(4) + + graph_degraded = model.forward_student(degraded) + graph_clean = v2.forward_clean_bn_safe(model, clean) + losses = objective( + graph_degraded, graph_clean, degraded, clean, labels, + torch.linspace(0.2, 0.8, 4), torch.ones(4), model.clean_root(), + ) + losses["total"].backward() + + token_grad = model.token_generator.semantic_tokens.grad + assert token_grad is not None + assert torch.isfinite(token_grad).all() + assert (token_grad.norm(dim=1) > 0).all() + assert model.token_generator.feat_proj.weight.grad is not None + assert model.clean_root.embedding.grad is None + assert torch.equal( + model.clean_root.embedding, + torch.zeros_like(model.clean_root.embedding), + ) + clone = v2.BlindDegradationGraphEncoder(config) + clone.load_state_dict(model.state_dict(), strict=True) + + +def test_real_evaluate_train_checkpoint_and_provenance_smoke(tmp_path): + config = v2.GraphConfig( + latent_channels=16, + node_dim=32, + spatial_map_size=(4, 4), + ) + model = v2.BlindDegradationGraphEncoder(config) + objective = v2.Phase1GraphObjective(32) + batch = { + "degraded": torch.rand(4, 3, 16, 16), + "clean": torch.rand(4, 3, 16, 16), + "label": torch.arange(4), + "severity": torch.linspace(0.1, 0.9, 4), + } + metrics = v2.evaluate(model, [batch], torch.device("cpu"), torch.ones(4)) + assert metrics["sample_count"] == 4 + + optimizer = torch.optim.AdamW( + list(model.parameters()) + list(objective.parameters()), lr=1e-4 + ) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=1) + scaler = torch.cuda.amp.GradScaler(enabled=False) + trained = v2.train_one_epoch( + model, objective, [batch], optimizer, scaler, torch.device("cpu"), + torch.ones(4), False, 1.0, + ) + assert torch.isfinite(torch.tensor(trained["total"])) + + quarantine = tmp_path / "quarantine.json" + quarantine.write_text("{}", encoding="utf-8") + args = v2.build_parser().parse_args( + ["--quarantine-manifest", str(quarantine), "--workers", "0"] + ) + records = tuple(_record(i, name, dataset=name) for i, name in enumerate(v2.BRANCH_ORDER)) + splits = v2.DataSplits(records, records, records, 3) + provenance = v2.make_provenance(args, splits) + run_config = v2._configuration(args, config, v2.LossWeights()) + payload = v2.make_checkpoint( + model, objective.global_type_head, optimizer, scheduler, scaler, + 1, 0.5, run_config, provenance, [{"epoch": 0}], + {name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} for name in v2.BRANCH_ORDER}, + ) + checkpoint = tmp_path / "checkpoint.pt" + v2._atomic_torch_save(checkpoint, payload) + loaded = v2._load_encoder_checkpoint( + checkpoint, model, objective, torch.device("cpu") + ) + assert loaded["epoch"] == 1 + v2._atomic_write_json(tmp_path / "provenance.json", provenance) + assert (tmp_path / "provenance.json").is_file() + + +def test_build_loaders_yields_exactly_balanced_batch(tmp_path): + records = [] + calibration = {} + for index, name in enumerate(v2.BRANCH_ORDER): + degraded = tmp_path / name / "d.png" + clean = tmp_path / name / "c.png" + _png(degraded, 30 + index) + _png(clean, 10) + records.append(v2.PairRecord(degraded, clean, name, name, str(index), str(index))) + calibration[name] = {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + splits = v2.DataSplits(tuple(records), tuple(records), (), 0) + args = v2.build_parser().parse_args( + [ + "--workers", "0", "--batch-size", "4", "--eval-batch-size", "4", + "--steps-per-epoch", "1", "--image-size", "8", + ] + ) + train_loader, val_loader, _, _ = v2.build_loaders( + args, splits, calibration, torch.device("cpu"), tmp_path / "cache" + ) + assert sorted(next(iter(train_loader))["label"].tolist()) == [0, 1, 2, 3] + assert len(next(iter(val_loader))["label"]) == 4 + + +def test_eval_only_main_writes_config_provenance_and_metrics(monkeypatch, tmp_path): + checkpoint = tmp_path / "model.pt" + model = v2.BlindDegradationGraphEncoder(v2.GraphConfig()) + calibration = { + name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + for name in v2.BRANCH_ORDER + } + torch.save( + { + "model_state_dict": model.state_dict(), + "aggregation_version": v2.AGGREGATION_VERSION, + "branch_order": list(v2.BRANCH_ORDER), + "severity_calibration": calibration, + }, + checkpoint, + ) + quarantine = tmp_path / "quarantine.json" + quarantine.write_text("{}", encoding="utf-8") + monkeypatch.setattr(v2, "build_data_splits", lambda args: v2.DataSplits((), (), (), 0)) + monkeypatch.setattr(v2, "_make_eval_loader", lambda *args, **kwargs: []) + metrics = { + "accuracy": 0.0, "macro_f1": 0.0, "balanced_accuracy": 0.0, + "severity_mae": 0.0, "spatial_selected_mae": 0.0, + } + monkeypatch.setattr(v2, "evaluate", lambda *args, **kwargs: metrics) + output = tmp_path / "output" + + assert v2.main( + [ + "--eval-only", "--checkpoint", str(checkpoint), + "--output-dir", str(output), "--device", "cpu", "--workers", "0", + "--quarantine-manifest", str(quarantine), "--allow-count-mismatch", + ] + ) == 0 + assert (output / "config.json").is_file() + assert (output / "provenance.json").is_file() + assert (output / "eval_val_metrics.json").is_file() + + +# --------------------------------------------------------------------------- +# P1-LL (ll_v3): global low-frequency branch, null/OOD routing, selection +# --------------------------------------------------------------------------- + +from src.models.graph_encoder.encoder import ( # noqa: E402 + LLGlobalBranch, + haar_ll, + photometric_stats, +) + + +def _small_ll_config(**overrides): + defaults = dict( + latent_channels=16, + node_dim=32, + num_semantic_branches=4, + num_free_nodes=2, + use_ll_global=True, + ll_global_dim=32, + ) + defaults.update(overrides) + return v2.GraphConfig(**defaults) + + +def test_haar_ll_and_photometric_stats_are_finite_and_shaped(): + image = torch.rand(3, 3, 64, 64) + ll = haar_ll(image) + assert ll.shape == (3, 3, 32, 32) + # LL of a constant image is the constant (energy-preserving /2 scaling + # doubles the mean per level by design of the orthonormal transform). + stats = photometric_stats(image) + assert stats.shape == (3, LLGlobalBranch.STATS_DIM) + assert torch.isfinite(stats).all() + + +def test_ll_branch_is_deterministic_and_sized(): + torch.manual_seed(0) + branch = LLGlobalBranch(output_dim=32) + branch.eval() + image = torch.rand(2, 3, 64, 64) + with torch.no_grad(): + first = branch(image) + second = branch(image) + assert first.shape == (2, 32) + assert torch.equal(first, second) + + +def test_ll_config_gates_state_dict_and_preserves_phase2_contract(): + legacy = v2.BlindDegradationGraphEncoder( + v2.GraphConfig(latent_channels=16, node_dim=32) + ) + assert not any("ll_" in name for name in legacy.state_dict()) + + model = v2.BlindDegradationGraphEncoder(_small_ll_config()) + names = model.state_dict().keys() + assert any(name.startswith("ll_branch.") for name in names) + assert any(name.startswith("ll_condition.") for name in names) + + graph = model.forward_student(torch.rand(2, 3, 64, 64)) + assert graph.routing_probs.shape == (2, 6) + assert graph.severity_coords.shape == (2, 4) + assert graph.spatial_maps.shape[:2] == (2, 4) + assert graph.node_tokens.shape == (2, 6, 32) + assert graph.global_condition.shape == (2, 32) + v2.assert_phase2_contract(model) + + +def test_ll_condition_is_zero_initialized_for_v2_aggregation_equivalence(): + model = v2.BlindDegradationGraphEncoder(_small_ll_config()) + assert int(torch.count_nonzero(model.ll_condition.weight)) == 0 + assert int(torch.count_nonzero(model.ll_condition.bias)) == 0 + + +@pytest.mark.parametrize("kind", v2.OOD_KINDS) +def test_synthesize_ood_is_deterministic_bounded_and_nontrivial(kind): + clean = torch.rand(2, 3, 64, 64) + first = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(7)) + second = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(7)) + other = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(8)) + assert torch.equal(first, second) + assert first.shape == clean.shape + assert float(first.min()) >= -1e-5 and float(first.max()) <= 1.0 + 1e-5 + assert not torch.equal(first, clean) + if kind == "snow": + assert not torch.equal(first, other) + + +def test_objective_with_ood_routes_clean_and_ood_into_free_slots(): + torch.manual_seed(0) + config = _small_ll_config() + model = v2.BlindDegradationGraphEncoder(config) + objective = v2.Phase1GraphObjective(node_dim=32) + degraded = torch.rand(4, 3, 64, 64) + clean = torch.rand(4, 3, 64, 64) + ood = v2.synthesize_ood(clean, "snow", torch.Generator().manual_seed(3)) + labels = torch.tensor([0, 1, 2, 3]) + severity = torch.rand(4) + pixel_q95 = torch.ones(4) + + graph_degraded = model.forward_student(degraded) + graph_clean = model.forward_student(clean) + graph_ood = model.forward_student(ood) + losses = objective( + graph_degraded, graph_clean, degraded, clean, labels, severity, + pixel_q95, model.clean_root(), graph_ood=graph_ood, + ) + for name in ("null_route", "ood_route", "unknown_margin", "total"): + assert torch.isfinite(losses[name]), name + assert float(losses["null_route"]) > 0.0 + assert float(losses["ood_route"]) > 0.0 + + losses["total"].backward() + routing_grads = [ + parameter.grad + for name, parameter in model.state_predictor.routing_net.named_parameters() + if parameter.grad is not None + ] + assert routing_grads and any( + float(grad.abs().sum()) > 0 for grad in routing_grads + ) + + +def test_objective_without_ood_matches_legacy_signature(): + torch.manual_seed(0) + config = v2.GraphConfig(latent_channels=16, node_dim=32) + model = v2.BlindDegradationGraphEncoder(config) + objective = v2.Phase1GraphObjective(node_dim=32) + degraded = torch.rand(2, 3, 64, 64) + clean = torch.rand(2, 3, 64, 64) + losses = objective( + model.forward_student(degraded), model.forward_student(clean), + degraded, clean, torch.tensor([0, 1]), torch.rand(2), torch.ones(4), + model.clean_root(), + ) + assert float(losses["ood_route"]) == 0.0 + assert float(losses["unknown_margin"]) == 0.0 + assert torch.isfinite(losses["total"]) + + +def test_selection_key_prefers_null_routing_after_f1_and_accepts_legacy(): + base = { + "macro_f1": 0.9, "severity_mae": 0.1, "spatial_selected_mae": 0.1, + "severity_spearman": 0.0, + } + with_null = dict(base, null_accuracy_clean=1.0, null_accuracy_ood=0.8) + without_null = dict(base, null_accuracy_clean=0.1, null_accuracy_ood=0.1) + higher_f1 = dict(without_null, macro_f1=0.95) + assert v2.selection_key(with_null) > v2.selection_key(without_null) + assert v2.selection_key(higher_f1) > v2.selection_key(with_null) + legacy = { + "macro_f1": 0.9, "severity_mae": 0.2, "spatial_selected_mae": 0.1, + } + assert v2.selection_key(legacy) < v2.selection_key(base) + + +def test_validation_metrics_accept_null_audit_fields(): + metrics = v2.compute_validation_metrics( + labels=[0, 1], predictions=[0, 1], severity_targets=[0.1, 0.2], + severity_predictions=[0.1, 0.2], unknown_routing=[0.0, 0.0], + entropies=[0.1, 0.1], losses=[0.5, 0.5], spatial_mae=[0.1, 0.1], + inactive_activation=[0.0, 0.0], + null_accuracy_clean=0.75, null_accuracy_ood=0.5, unknown_norm_gap=0.2, + ) + assert metrics["null_accuracy_clean"] == 0.75 + assert metrics["null_accuracy_ood"] == 0.5 + assert metrics["unknown_norm_gap"] == 0.2 + + +def test_build_frozen_phase1_reconstructs_ll_architecture_from_checkpoint(tmp_path): + import train_phase2_graph_resshift_v4 as p2 + + config = _small_ll_config() + model = v2.BlindDegradationGraphEncoder(config) + head = torch.nn.Linear(32, 4) + graph_config_dict = dict(vars(config)) + checkpoint = v2.make_checkpoint( + model, head, None, None, None, epoch=1, best_score=0.5, + config={"graph_config": graph_config_dict}, + provenance={}, history=[], + severity_calibration={ + name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + for name in v2.BRANCH_ORDER + }, + ) + path = tmp_path / "phase1_ll.pt" + torch.save(checkpoint, str(path)) + sha = v2.sha256_file(path) + frozen, metadata = p2.build_frozen_phase1(path, sha, torch.device("cpu")) + assert frozen.encoder.ll_branch is not None + assert metadata["sha256"] == sha + representation = frozen(torch.rand(1, 3, 64, 64)) + assert representation.routing_probs.shape == (1, 6) + + +def test_pearson_and_spearman_ignore_non_finite_pairs(): + # NaN pairs are dropped; the remaining finite pairs correlate normally. + two_left = v2._pearson([1.0, float("nan"), 3.0], [1.0, 2.0, 3.0]) + assert abs(two_left - 1.0) < 1e-9 + clean = v2._pearson([1.0, 2.0, 3.0, float("nan")], [1.0, 2.0, 3.0, 5.0]) + assert abs(clean - 1.0) < 1e-9 + # All pairs non-finite -> fewer than two survivors -> safe zero. + assert v2._pearson([float("nan")] * 3, [1.0, 2.0, 3.0]) == 0.0 + assert math.isfinite(v2._spearman([float("inf")] * 3, [1.0, 2.0, 3.0])) + + +def test_sanitize_json_replaces_non_finite_and_write_survives(tmp_path): + payload = { + "ok": 1.5, + "bad": float("nan"), + "nested": [float("inf"), {"x": float("-inf"), "y": 2}], + } + sanitized = v2._sanitize_json(payload) + assert sanitized["bad"] is None + assert sanitized["nested"][0] is None + assert sanitized["nested"][1]["x"] is None + assert sanitized["nested"][1]["y"] == 2 + target = tmp_path / "history.json" + v2._atomic_write_json(target, payload) + import json as _json + + assert _json.loads(target.read_text())["bad"] is None + + +def test_selection_key_treats_non_finite_metrics_as_worst(): + healthy = { + "macro_f1": 0.5, "severity_mae": 0.2, "spatial_selected_mae": 0.2, + } + poisoned = { + "macro_f1": float("nan"), "severity_mae": 0.2, + "spatial_selected_mae": 0.2, + } + assert v2.selection_key(healthy) > v2.selection_key(poisoned) + + +def test_ll_branch_stays_fp32_under_autocast(): + branch = LLGlobalBranch(output_dim=32) + image = torch.rand(1, 3, 64, 64) + if torch.cuda.is_available(): + branch = branch.cuda() + image = image.cuda() + with torch.cuda.amp.autocast(enabled=True): + output = branch(image) + else: + output = branch(image) + assert output.dtype == torch.float32 + + +def test_synthesize_noise_is_deterministic_and_bounded() -> None: + clean = torch.rand(3, 3, 32, 32) + g1 = torch.Generator().manual_seed(11) + g2 = torch.Generator().manual_seed(11) + a = v2.synthesize_noise(clean, g1) + b = v2.synthesize_noise(clean, g2) + assert torch.equal(a, b) + assert float(a.min()) >= 0.0 and float(a.max()) <= 1.0 + assert float((a - clean).abs().mean()) > 1e-3 + bank = [torch.randn(3, 32, 32) * 0.05] + c = v2.synthesize_noise(clean, torch.Generator().manual_seed(3), bank) + assert c.shape == clean.shape + + +def test_apply_noise_positives_relabels_only_selected_non_noise() -> None: + clean = torch.rand(6, 3, 16, 16) + degraded = clean.clone() + labels = torch.tensor([0, v2.NOISE_INDEX, 2, 3, 0, 2]) + severity = torch.zeros(6) + calibration = {"p05": 0.0, "p95": 0.2} + new_deg, new_lab, new_sev, mask = v2.apply_noise_positives( + degraded, clean, labels, severity, 1.0, torch.Generator().manual_seed(5), + calibration, + ) + assert bool(mask[1]) is False # real noise sample untouched + assert torch.equal(new_lab[mask], torch.full((int(mask.sum()),), v2.NOISE_INDEX)) + assert torch.equal(new_deg[~mask], degraded[~mask]) + assert torch.equal(labels, torch.tensor([0, v2.NOISE_INDEX, 2, 3, 0, 2])) # not mutated + assert float(new_sev[mask].min()) > 0.0 and float(new_sev[mask].max()) <= 1.0 + untouched_deg, untouched_lab, _, zero_mask = v2.apply_noise_positives( + degraded, clean, labels, severity, 0.0, torch.Generator().manual_seed(5), calibration + ) + assert untouched_deg is degraded and untouched_lab is labels and not bool(zero_mask.any()) + + +def test_texture_null_weights_rank_textured_images_higher() -> None: + flat = torch.full((1, 3, 32, 32), 0.5) + textured = torch.rand(1, 3, 32, 32) + weights = v2.texture_null_weights(torch.cat([flat, textured], dim=0)) + assert weights.shape == (2,) + assert float(weights[1]) > float(weights[0]) + assert float(weights.min()) >= 0.5 and float(weights.max()) <= 1.5 + + +def test_objective_accepts_texture_weighted_null() -> None: + objective = v2.Phase1GraphObjective(node_dim=256, texture_weighted_null=True) + assert objective.texture_weighted_null is True + + +def test_sharpen_ood_kind_adds_detail_deterministically() -> None: + clean = torch.rand(2, 3, 32, 32) + a = v2.synthesize_ood(clean, "sharpen", torch.Generator().manual_seed(2)) + b = v2.synthesize_ood(clean, "sharpen", torch.Generator().manual_seed(2)) + assert torch.equal(a, b) + assert a.shape == clean.shape and float(a.min()) >= 0.0 and float(a.max()) <= 1.0 + assert float((a - clean).abs().mean()) > 1e-3 + assert "sharpen" in v2.OOD_KINDS + + +def test_transplant_only_noise_uses_bank_and_gain() -> None: + clean = torch.rand(2, 3, 16, 16) * 0.5 + bank = [torch.ones(3, 16, 16) * 0.1] + out = v2.synthesize_noise( + clean, torch.Generator().manual_seed(9), bank, synthetic_prob=0.0, gain_max=2.5 + ) + residual = out - clean + # transplant of a constant residual: per-image constant offset in [0.05, 0.25] + per_image = residual.flatten(1).mean(dim=1) + assert float(per_image.min()) >= 0.05 - 1e-6 and float(per_image.max()) <= 0.25 + 1e-6 + spread = residual.flatten(1).std(dim=1) + assert float(spread.max()) < 1e-5 diff --git a/dataset/phase1_noise_20260906/code/train_graph_encoder_v2.py b/dataset/phase1_noise_20260906/code/train_graph_encoder_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..2e755bf09f1436bfac0aae6f524b26d12a2cecff --- /dev/null +++ b/dataset/phase1_noise_20260906/code/train_graph_encoder_v2.py @@ -0,0 +1,2640 @@ +#!/usr/bin/env python3 +"""Leakage-safe Phase-1 graph encoder training and evaluation. + +The deployed graph encoder keeps its original positional semantics: +``blur, noise, jpeg, lowlight`` become the real paired domains +``rain, noise, haze, lowlight``. This module never uses the legacy +``CombinedGraphLoss`` or its degraded-as-teacher path. +""" + +from __future__ import annotations + +import argparse +import copy +import dataclasses +import hashlib +import json +import math +import os +import random +import sys +import time +from contextlib import contextmanager +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from PIL import Image +from torch.utils.data import DataLoader, Dataset, Sampler + +PROJECT_ROOT = Path(__file__).resolve().parent +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from src.data.rain13k_resized import load_rain13k_resized # noqa: E402 +from src.models.graph_encoder.hvi import rgb_to_hvi # noqa: E402 +from src.models.graph_encoder import ( # noqa: E402 + BlindDegradationGraphEncoder, + GraphConfig, +) + + +BRANCH_ORDER: Tuple[str, ...] = ("rain", "noise", "haze", "lowlight") +BRANCH_TO_INDEX: Dict[str, int] = { + name: index for index, name in enumerate(BRANCH_ORDER) +} +NUM_KNOWN = len(BRANCH_ORDER) +NUM_GRAPH_ROUTES = 6 +AGGREGATION_VERSION = 2 +CACHE_VERSION = 1 +# v5c crop policies. "resize" (legacy, ll_v3/v5): shorter side -> image_size, +# centre crop — SIDD ~4000x3000 frames are downsampled ~12x, which averages +# the sensor noise away. "native" (Phase-2 parity): random native-resolution +# crops for training, centre crop for evaluation; SIDD crops come from a +# prebuilt native cache (sidd_native_crops per training pair, 1 for eval). +CROP_POLICIES: Tuple[str, ...] = ("resize", "native") +NATIVE_CACHE_TAG = b"SCDC_PHASE1_SIDD_NATIVE_CACHE_V1\0" +EMBED_MEMBERS: Tuple[str, ...] = ("all", "known_clean") +# v5e: training-crop selection. "random" = one native crop per draw; +# "residual" = draw crop_candidates crops and keep the one with the largest +# paired residual, so a sparse-rain / light-haze crop actually contains the +# degradation it is labelled with (34% of native Rain13K crops had severity +# < 0.05 under "random"). +CROP_SELECT: Tuple[str, ...] = ("random", "residual") +AUDITED_COUNTS = {"train": 18261, "val": 317, "locked_test": 1220} + +DEFAULT_DATA_ROOT = Path(os.environ.get("SCDC_DATA_ROOT", "/home/admin_mcn/data")) +DEFAULT_RAIN_ROOT = Path(os.environ.get( + "SCDC_RAIN13K_ROOT", + "/home/admin_mcn/.cache/kagglehub/datasets/hngphchi/rain13k-resized/versions/1", +)) +DEFAULT_OUTPUT_DIR = Path( + "/home/admin_mcn/scdc_ban/outputs/graph_encoder_v2" +) +DEFAULT_QUARANTINE = PROJECT_ROOT / "src/data/rain13k_quarantine_v1.json" + +try: + _LANCZOS = Image.Resampling.LANCZOS +except AttributeError: # Pillow < 9 + _LANCZOS = Image.LANCZOS + + +@dataclass(frozen=True) +class PairRecord: + degraded: Path + clean: Path + degradation: str + dataset: str + source_id: str + split_group: str + clean_content_sha256: Optional[str] = None + + @property + def label(self) -> int: + return BRANCH_TO_INDEX[self.degradation] + + @property + def record_id(self) -> str: + payload = "\0".join( + ( + self.dataset, + self.source_id, + str(self.degraded), + str(self.clean), + self.clean_content_sha256 or "", + ) + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +@dataclass(frozen=True) +class DataSplits: + train: Tuple[PairRecord, ...] + val: Tuple[PairRecord, ...] + locked_test: Tuple[PairRecord, ...] + quarantine_count: int + + +def set_seed(seed: int) -> None: + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + + +def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + while True: + chunk = handle.read(chunk_size) + if not chunk: + break + digest.update(chunk) + return digest.hexdigest() + + +def _image_files(directory: Path) -> List[Path]: + extensions = {".png", ".jpg", ".jpeg"} + return sorted( + path + for path in directory.iterdir() + if path.is_file() and path.suffix.lower() in extensions + ) + + +def _require_pair_directories(input_dir: Path, target_dir: Path, label: str) -> None: + for directory in (input_dir, target_dir): + if not directory.is_dir(): + raise FileNotFoundError("%s missing directory: %s" % (label, directory)) + + +def _content_group(path: Path) -> str: + return sha256_file(path) + + +def build_rain_records( + rain_root: Path, quarantine_manifest: Path +) -> Tuple[List[PairRecord], List[PairRecord], List[PairRecord], int]: + splits = load_rain13k_resized( + rain_root, + max_train_pairs=0, + seed=42, + quarantine_manifest=quarantine_manifest, + ) + + def convert(pairs: Iterable[Tuple[Path, Path]], origin: str) -> List[PairRecord]: + records = [] + for degraded, clean in pairs: + content_hash = _content_group(clean) + records.append( + PairRecord( + degraded=degraded, + clean=clean, + degradation="rain", + dataset="Rain13K", + source_id="%s:%s" % (origin, degraded.name), + split_group=content_hash, + clean_content_sha256=content_hash, + ) + ) + return records + + train = convert(splits.train_pairs, "train_resized") + val = convert(splits.official_test_pairs["Test100"], "Test100") + locked = convert(splits.official_test_pairs["Test1200"], "Test1200") + return train, val, locked, splits.quarantined_train_pair_count + + +def discover_lol_records(root: Path, split: str) -> List[PairRecord]: + input_dir = root / split / "Input" + target_dir = root / split / "GT" + _require_pair_directories(input_dir, target_dir, "LOLv2 %s" % split) + records = [] + for degraded in _image_files(input_dir): + clean = target_dir / degraded.name + if not clean.is_file(): + raise ValueError("LOLv2 %s missing GT for %s" % (split, degraded.name)) + content_hash = _content_group(clean) + records.append( + PairRecord( + degraded=degraded, + clean=clean, + degradation="lowlight", + dataset="LOLv2", + source_id=degraded.stem, + split_group=content_hash, + clean_content_sha256=content_hash, + ) + ) + if not records: + raise ValueError("LOLv2 %s contains no paired images" % split) + return records + + +def discover_reside_records(root: Path) -> List[PairRecord]: + hazy_dir = root / "hazy" + clear_dir = root / "clear" + _require_pair_directories(hazy_dir, clear_dir, "RESIDE") + clear_by_source = {path.stem: path for path in _image_files(clear_dir)} + clean_hash_by_source: Dict[str, str] = {} + records = [] + for degraded in _image_files(hazy_dir): + source = degraded.stem.split("_")[0] + clean = clear_by_source.get(source) + if clean is None: + continue + if source not in clean_hash_by_source: + clean_hash_by_source[source] = _content_group(clean) + records.append( + PairRecord( + degraded=degraded, + clean=clean, + degradation="haze", + dataset="RESIDE", + source_id=degraded.stem, + split_group=source, + clean_content_sha256=clean_hash_by_source[source], + ) + ) + if not records: + raise ValueError("RESIDE contains no paired images") + return records + + +def split_reside_records( + records: Sequence[PairRecord], limit: int = 5000, val_count: int = 100 +) -> Tuple[List[PairRecord], List[PairRecord]]: + if limit <= 0 or val_count <= 0 or val_count >= limit: + raise ValueError("RESIDE requires 0 < val_count < limit") + limited = list(records[:limit]) + if len(limited) < limit: + raise ValueError( + "RESIDE audited contract requires %d pairs, found %d" + % (limit, len(limited)) + ) + val = limited[:val_count] + val_groups = {record.split_group for record in val} + train = [ + record for record in limited[val_count:] + if record.split_group not in val_groups + ] + return train, val + + +def sidd_scene_number(source_id: str) -> str: + parts = source_id.split("_") + if len(parts) < 3 or len(parts[1]) != 3 or not parts[1].isdigit(): + raise ValueError("Malformed SIDD source directory: %s" % source_id) + return parts[1] + + +def discover_sidd_records(root: Path) -> List[PairRecord]: + if not root.is_dir(): + raise FileNotFoundError("SIDD Data directory does not exist: %s" % root) + records = [] + for source_dir in sorted(path for path in root.iterdir() if path.is_dir()): + noisy = sorted(source_dir.glob("NOISY_SRGB_*")) + clean = sorted(source_dir.glob("GT_SRGB_*")) + if len(noisy) != 1 or len(clean) != 1: + raise ValueError( + "SIDD source %s must contain one NOISY/GT pair" % source_dir.name + ) + records.append( + PairRecord( + degraded=noisy[0], + clean=clean[0], + degradation="noise", + dataset="SIDD", + source_id=source_dir.name, + split_group=sidd_scene_number(source_dir.name), + clean_content_sha256=_content_group(clean[0]), + ) + ) + if not records: + raise ValueError("SIDD contains no paired source directories") + return records + + +def split_sidd_records( + records: Sequence[PairRecord], +) -> Tuple[List[PairRecord], List[PairRecord], List[PairRecord]]: + by_scene: Dict[str, List[PairRecord]] = {} + for record in records: + by_scene.setdefault(record.split_group, []).append(record) + if len(by_scene) != 10: + raise ValueError( + "SIDD audited scene split requires 10 scenes, found %d" % len(by_scene) + ) + ordered_scenes = sorted( + by_scene, + key=lambda scene: (hashlib.sha256(scene.encode("utf-8")).digest(), scene), + ) + scene_partitions = (ordered_scenes[:8], ordered_scenes[8:9], ordered_scenes[9:]) + partitions = [] + for scenes in scene_partitions: + partitions.append( + [record for scene in scenes for record in by_scene[scene]] + ) + return partitions[0], partitions[1], partitions[2] + + +def assert_split_isolation(splits: DataSplits) -> None: + keys = [] + for records in (splits.train, splits.val, splits.locked_test): + keys.append({(record.dataset, record.split_group) for record in records}) + labels = ("train", "val", "locked_test") + for left in range(3): + for right in range(left + 1, 3): + overlap = keys[left] & keys[right] + if overlap: + preview = sorted(overlap)[:5] + raise ValueError( + "source leakage between %s and %s: %r" + % (labels[left], labels[right], preview) + ) + + # Dataset-scoped source IDs cannot detect the same clean image copied into + # a different corpus. Enforce dataset-agnostic exact content isolation too. + content_keys = [] + for records in (splits.train, splits.val, splits.locked_test): + identities = set() + for record in records: + identity = record.clean_content_sha256 + if identity is None: + if record.clean.is_file(): + identity = sha256_file(record.clean) + else: + identity = "unresolved:%s:%s" % ( + record.dataset, record.split_group + ) + identities.add(identity) + content_keys.append(identities) + for left in range(3): + for right in range(left + 1, 3): + overlap = content_keys[left] & content_keys[right] + if overlap: + raise ValueError( + "clean-content leakage between %s and %s: %r" + % (labels[left], labels[right], sorted(overlap)[:5]) + ) + + +def build_data_splits(args: argparse.Namespace) -> DataSplits: + rain_train, rain_val, rain_test, quarantine_count = build_rain_records( + Path(args.rain13k_root), Path(args.quarantine_manifest) + ) + lol_root = Path(args.data_root) / "LOLv2/lolv2_hf" + lol_train = discover_lol_records(lol_root, "Train") + lol_val = discover_lol_records(lol_root, "Test") + reside_all = discover_reside_records(Path(args.data_root) / "RESIDE") + reside_train, reside_val = split_reside_records( + reside_all, args.reside_limit, args.reside_val_count + ) + sidd_all = discover_sidd_records( + Path(args.data_root) / "SIDD/SIDD_Small_sRGB_Only/Data" + ) + sidd_train, sidd_val, sidd_test = split_sidd_records(sidd_all) + splits = DataSplits( + train=tuple(rain_train + lol_train + reside_train + sidd_train), + val=tuple(rain_val + lol_val + reside_val + sidd_val), + locked_test=tuple(rain_test + sidd_test), + quarantine_count=quarantine_count, + ) + assert_split_isolation(splits) + counts = { + "train": len(splits.train), + "val": len(splits.val), + "locked_test": len(splits.locked_test), + } + if not args.allow_count_mismatch and counts != AUDITED_COUNTS: + raise ValueError( + "live-data counts differ from audited contract: expected %r, got %r" + % (AUDITED_COUNTS, counts) + ) + return splits + + +class BalancedBatchSampler(Sampler[List[int]]): + """Exact per-batch class balance via inverse-frequency replacement.""" + + def __init__( + self, + labels: Sequence[int], + batch_size: int, + steps: int, + seed: int, + epoch: int = 0, + yield_seeds: bool = False, + ) -> None: + if batch_size <= 0 or batch_size % NUM_KNOWN: + raise ValueError("batch_size must be positive and divisible by 4") + if steps <= 0: + raise ValueError("steps must be positive") + self.by_class = [] + for class_index in range(NUM_KNOWN): + indices = [i for i, label in enumerate(labels) if label == class_index] + if not indices: + raise ValueError("balanced sampler has an empty class") + self.by_class.append(indices) + self.batch_size = batch_size + self.per_class = batch_size // NUM_KNOWN + self.steps = steps + self.seed = seed + self.epoch = epoch + # v5c: emit (record_index, sample_seed) so a native-crop dataset can + # draw a fresh, replayable crop per draw (Phase2PairDataset protocol). + # A separate generator keeps the record draws identical to yield_seeds=False. + self.yield_seeds = bool(yield_seeds) + + def __len__(self) -> int: + return self.steps + + def __iter__(self) -> Iterator[List[object]]: + generator = torch.Generator() + generator.manual_seed(self.seed + self.epoch * 1000003) + seed_generator = torch.Generator() + seed_generator.manual_seed(self.seed * 7 + self.epoch * 1000003 + 17) + for _ in range(self.steps): + batch = [] + for indices in self.by_class: + draws = torch.randint( + len(indices), (self.per_class,), generator=generator + ).tolist() + batch.extend(indices[position] for position in draws) + permutation = torch.randperm(len(batch), generator=generator).tolist() + ordered = [batch[position] for position in permutation] + if not self.yield_seeds: + yield ordered + continue + seeds = torch.randint(0, 2 ** 31 - 1, (len(ordered),), generator=seed_generator).tolist() + yield [(index, int(seed)) for index, seed in zip(ordered, seeds)] + + +def _open_rgb(path: Path) -> Image.Image: + try: + with Image.open(path) as image: + return image.convert("RGB").copy() + except Exception as exc: + raise RuntimeError("Failed to decode image %s: %s" % (path, exc)) from exc + + +def _resize_center_crop(image: Image.Image, size: int) -> Image.Image: + width, height = image.size + if width <= 0 or height <= 0: + raise ValueError("image has invalid dimensions: %r" % (image.size,)) + scale = float(size) / min(width, height) + resized = image.resize( + (max(size, int(round(width * scale))), max(size, int(round(height * scale)))), + _LANCZOS, + ) + left = (resized.width - size) // 2 + top = (resized.height - size) // 2 + return resized.crop((left, top, left + size, top + size)) + + +def load_pair_uint8(record: PairRecord, size: int) -> Tuple[Image.Image, Image.Image]: + degraded = _resize_center_crop(_open_rgb(record.degraded), size) + clean = _resize_center_crop(_open_rgb(record.clean), size) + return degraded, clean + + +def _pil_to_tensor(image: Image.Image) -> torch.Tensor: + array = np.asarray(image, dtype=np.uint8).copy() + return torch.from_numpy(array).permute(2, 0, 1).float().div_(255.0) + + +# ---- v5c native-resolution crop policy (Phase-2 parity) ------------------- # +def _native_open_pair(record: PairRecord, size: int) -> Tuple[Image.Image, Image.Image]: + """Open a pair at native resolution; upscale only when smaller than ``size`` + (exactly Phase2PairDataset's rule), never downscale.""" + degraded, clean = _open_rgb(record.degraded), _open_rgb(record.clean) + if degraded.size != clean.size: + raise ValueError( + "paired images must share a native size: %s is %r vs %r" + % (record.source_id, degraded.size, clean.size) + ) + width, height = degraded.size + if min(width, height) < size: + scale = float(size) / min(width, height) + resized = ( + max(size, int(math.ceil(width * scale))), + max(size, int(math.ceil(height * scale))), + ) + degraded = degraded.resize(resized, _LANCZOS) + clean = clean.resize(resized, _LANCZOS) + return degraded, clean + + +def _crop_box( + width: int, height: int, size: int, rng: Optional[random.Random] +) -> Tuple[int, int, int, int]: + if rng is None: + left, top = (width - size) // 2, (height - size) // 2 + else: + left = rng.randrange(width - size + 1) + top = rng.randrange(height - size + 1) + return (left, top, left + size, top + size) + + +def _sample_rng(record: PairRecord, sample_seed: int) -> random.Random: + digest = hashlib.sha256(("%s:%d" % (record.record_id, int(sample_seed))).encode("ascii")) + return random.Random(int(digest.hexdigest()[:16], 16)) + + +def _sidd_native_boxes( + record: PairRecord, width: int, height: int, size: int, count: int, training: bool +) -> List[Tuple[int, int, int, int]]: + """Deterministic native crop boxes for one SIDD pair: ``count`` random + boxes for training (seeded by the record id), the centre box for eval.""" + if not training: + return [_crop_box(width, height, size, None)] + digest = hashlib.sha256(("native-cache:%s" % record.record_id).encode("ascii")) + rng = random.Random(int(digest.hexdigest()[:16], 16)) + return [_crop_box(width, height, size, rng) for _ in range(count)] + + +def _select_pair_by_residual( + pairs: Sequence[Tuple[torch.Tensor, torch.Tensor]] +) -> Tuple[torch.Tensor, torch.Tensor]: + """Keep the candidate crop with the largest paired absolute residual.""" + if len(pairs) == 1: + return pairs[0] + scores = [float((degraded - clean).abs().mean()) for degraded, clean in pairs] + return pairs[max(range(len(pairs)), key=scores.__getitem__)] + + +def _native_cache_paths( + cache_dir: Path, record: PairRecord, image_size: int, crop_index: int +) -> Tuple[Path, Path]: + digest = hashlib.sha256(NATIVE_CACHE_TAG) + digest.update(record.record_id.encode("ascii")) + digest.update(str(image_size).encode("ascii")) + for source_path in (record.degraded, record.clean): + stat = source_path.stat() + contract = "%d:%d:%d:%d" % ( + stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns, getattr(stat, "st_ino", 0) + ) + digest.update(contract.encode("ascii")) + digest.update(b"\0") + stem = "%s_n%d_c%02d_v%d" % (digest.hexdigest(), image_size, int(crop_index), CACHE_VERSION) + return cache_dir / (stem + "_deg.png"), cache_dir / (stem + "_clean.png") + + +def _atomic_image_save(image: Image.Image, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name( + ".%s.%d.%d.tmp" % (path.name, os.getpid(), time.time_ns()) + ) + try: + image.save(str(temporary), format="PNG") + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +class PairDataset(Dataset): + def __init__( + self, + records: Sequence[PairRecord], + image_size: int, + severity_calibration: Mapping[str, Mapping[str, float]], + cache_dir: Optional[Path] = None, + crop_policy: str = "resize", + training: bool = False, + sidd_native_crops: int = 32, + crop_select: str = "random", + crop_candidates: int = 4, + ) -> None: + if crop_policy not in CROP_POLICIES: + raise ValueError("crop_policy must be one of %r, got %r" % (CROP_POLICIES, crop_policy)) + if int(sidd_native_crops) < 1: + raise ValueError("sidd_native_crops must be >= 1") + if crop_select not in CROP_SELECT: + raise ValueError("crop_select must be one of %r, got %r" % (CROP_SELECT, crop_select)) + if int(crop_candidates) < 1: + raise ValueError("crop_candidates must be >= 1") + self.crop_select = str(crop_select) + self.crop_candidates = int(crop_candidates) + self.records = tuple(records) + self.image_size = image_size + self.severity_calibration = severity_calibration + self.cache_dir = cache_dir + self.crop_policy = str(crop_policy) + self.training = bool(training) + self.sidd_native_crops = int(sidd_native_crops) + + def __len__(self) -> int: + return len(self.records) + + @property + def native(self) -> bool: + return self.crop_policy == "native" + + def _sidd_crop_count(self) -> int: + return self.sidd_native_crops if self.training else 1 + + def _cache_paths(self, record: PairRecord) -> Tuple[Path, Path]: + assert self.cache_dir is not None + return _cache_paths(self.cache_dir, record, self.image_size) + + def _native_cache_paths(self, record: PairRecord, crop_index: int) -> Tuple[Path, Path]: + assert self.cache_dir is not None + return _native_cache_paths(self.cache_dir, record, self.image_size, crop_index) + + def prepare_cache(self) -> None: + if self.cache_dir is None: + return + self.cache_dir.mkdir(parents=True, exist_ok=True) + for record in self.records: + if record.dataset != "SIDD": + continue + if not self.native: + degraded_path, clean_path = self._cache_paths(record) + if degraded_path.is_file() and clean_path.is_file(): + continue + degraded, clean = load_pair_uint8(record, self.image_size) + _atomic_image_save(degraded, degraded_path) + _atomic_image_save(clean, clean_path) + continue + paths = [self._native_cache_paths(record, k) for k in range(self._sidd_crop_count())] + if all(d.is_file() and c.is_file() for d, c in paths): + continue + degraded, clean = _native_open_pair(record, self.image_size) + boxes = _sidd_native_boxes( + record, degraded.width, degraded.height, self.image_size, + self._sidd_crop_count(), self.training, + ) + for (degraded_path, clean_path), box in zip(paths, boxes): + _atomic_image_save(degraded.crop(box), degraded_path) + _atomic_image_save(clean.crop(box), clean_path) + + def _load( + self, record: PairRecord, rng: Optional[random.Random] = None + ) -> Tuple[torch.Tensor, torch.Tensor]: + if not self.native: + if self.cache_dir is None or record.dataset != "SIDD": + degraded, clean = load_pair_uint8(record, self.image_size) + else: + degraded_path, clean_path = self._cache_paths(record) + if not degraded_path.is_file() or not clean_path.is_file(): + raise RuntimeError( + "SIDD cache was not prebuilt in the main process: %s" % self.cache_dir + ) + degraded, clean = _open_rgb(degraded_path), _open_rgb(clean_path) + return _pil_to_tensor(degraded), _pil_to_tensor(clean) + candidates = ( + self.crop_candidates if (rng is not None and self.crop_select == "residual") else 1 + ) + if record.dataset == "SIDD" and self.cache_dir is not None: + pairs = [] + for _ in range(candidates): + crop_index = rng.randrange(self._sidd_crop_count()) if rng is not None else 0 + degraded_path, clean_path = self._native_cache_paths(record, crop_index) + if not degraded_path.is_file() or not clean_path.is_file(): + raise RuntimeError( + "SIDD native cache was not prebuilt in the main process: %s" % self.cache_dir + ) + pairs.append((_pil_to_tensor(_open_rgb(degraded_path)), _pil_to_tensor(_open_rgb(clean_path)))) + return _select_pair_by_residual(pairs) + degraded, clean = _native_open_pair(record, self.image_size) + pairs = [] + for _ in range(candidates): + box = _crop_box(degraded.width, degraded.height, self.image_size, rng) + pairs.append((_pil_to_tensor(degraded.crop(box)), _pil_to_tensor(clean.crop(box)))) + return _select_pair_by_residual(pairs) + + def __getitem__(self, item: object) -> Dict[str, object]: + # Native training draws come as (record_index, sample_seed) from the + # balanced sampler; a bare index always yields the deterministic + # centre crop (evaluation, calibration, legacy callers). + if isinstance(item, (tuple, list)): + if len(item) != 2: + raise TypeError("sampled items must be (record_index, sample_seed)") + index, sample_seed = int(item[0]), int(item[1]) + else: + index, sample_seed = int(item), None + record = self.records[index] + rng = ( + _sample_rng(record, sample_seed) + if (self.native and self.training and sample_seed is not None) else None + ) + degraded, clean = self._load(record, rng) + calibration = self.severity_calibration[record.degradation] + severity = residual_mae_severity( + degraded, clean, calibration["p05"], calibration["p95"] + ) + return { + "degraded": degraded, + "clean": clean, + "label": record.label, + "severity": severity, + "degradation": record.degradation, + "source_id": record.source_id, + } + + +def residual_mae_severity( + degraded: torch.Tensor, clean: torch.Tensor, p05: float, p95: float +) -> torch.Tensor: + if p95 <= p05: + raise ValueError("severity p95 must be greater than p05") + raw = (degraded - clean).abs().mean() + return ((raw - float(p05)) / float(p95 - p05)).clamp(0.0, 1.0) + + +def _cache_paths(cache_dir: Path, record: PairRecord, image_size: int) -> Tuple[Path, Path]: + digest = hashlib.sha256(b"SCDC_PHASE1_SIDD_CACHE_V1\0") + digest.update(record.record_id.encode("ascii")) + digest.update(str(image_size).encode("ascii")) + for source_path in (record.degraded, record.clean): + stat = source_path.stat() + contract = "%d:%d:%d:%d" % ( + stat.st_size, + stat.st_mtime_ns, + stat.st_ctime_ns, + getattr(stat, "st_ino", 0), + ) + digest.update(contract.encode("ascii")) + digest.update(b"\0") + stem = "%s_s%d_v%d" % (digest.hexdigest(), image_size, CACHE_VERSION) + return cache_dir / (stem + "_deg.png"), cache_dir / (stem + "_clean.png") + + +def _load_record_tensors( + record: PairRecord, + image_size: int, + sidd_cache_dir: Optional[Path], + crop_policy: str = "resize", +) -> Tuple[torch.Tensor, torch.Tensor]: + if record.dataset == "SIDD" and sidd_cache_dir is not None: + if crop_policy == "native": + # Crop 0 of the training cache (a seeded random native crop). + degraded_path, clean_path = _native_cache_paths(sidd_cache_dir, record, image_size, 0) + else: + degraded_path, clean_path = _cache_paths(sidd_cache_dir, record, image_size) + if not degraded_path.is_file() or not clean_path.is_file(): + raise RuntimeError("SIDD cache missing during calibration: %s" % degraded_path) + return _pil_to_tensor(_open_rgb(degraded_path)), _pil_to_tensor(_open_rgb(clean_path)) + if crop_policy == "native": + degraded, clean = _native_open_pair(record, image_size) + box = _crop_box(degraded.width, degraded.height, image_size, None) + return _pil_to_tensor(degraded.crop(box)), _pil_to_tensor(clean.crop(box)) + degraded, clean = load_pair_uint8(record, image_size) + return _pil_to_tensor(degraded), _pil_to_tensor(clean) + + +def _records_fingerprint( + records: Sequence[PairRecord], image_size: int, crop_policy: str = "resize" +) -> str: + digest = hashlib.sha256(b"SCDC_PHASE1_CALIBRATION_V1\0") + if crop_policy != "resize": + # Legacy digests (resize policy) stay byte-identical so ll_v3/v5 + # calibration caches remain valid. + digest.update(("crop_policy=%s\0" % crop_policy).encode("ascii")) + digest.update(str(image_size).encode("ascii")) + for record in records: + digest.update(record.record_id.encode("ascii")) + for source_path in (record.degraded, record.clean): + stat = source_path.stat() + digest.update( + ("%d:%d:%d:%d" % ( + stat.st_size, + stat.st_mtime_ns, + stat.st_ctime_ns, + getattr(stat, "st_ino", 0), + )).encode("ascii") + ) + digest.update(b"\0") + digest.update(b"\n") + return digest.hexdigest() + + +def _histogram_quantile(counts: np.ndarray, quantile: float) -> float: + total = int(counts.sum()) + if total <= 0: + return 1.0 + threshold = max(1, int(math.ceil(total * quantile))) + index = int(np.searchsorted(np.cumsum(counts), threshold, side="left")) + return min(1.0, max(1.0 / len(counts), float(index + 1) / len(counts))) + + +def fit_training_calibration( + records: Sequence[PairRecord], + image_size: int, + output_path: Path, + sidd_cache_dir: Optional[Path], + crop_policy: str = "resize", +) -> Dict[str, Dict[str, float]]: + """Fit train-only scalar p05/p95 and pixel q95, with a persistent cache.""" + fingerprint = _records_fingerprint(records, image_size, crop_policy) + if output_path.is_file(): + payload = json.loads(output_path.read_text(encoding="utf-8")) + if payload.get("fingerprint") == fingerprint: + return payload["domains"] + + maes: Dict[str, List[float]] = {name: [] for name in BRANCH_ORDER} + histograms = { + name: np.zeros(4096, dtype=np.int64) for name in BRANCH_ORDER + } + for record in records: + degraded, clean = _load_record_tensors(record, image_size, sidd_cache_dir, crop_policy) + residual = (degraded - clean).abs().mean(dim=0) + maes[record.degradation].append(float(residual.mean().item())) + histogram, _ = np.histogram( + residual.numpy(), bins=4096, range=(0.0, 1.0) + ) + histograms[record.degradation] += histogram + + domains: Dict[str, Dict[str, float]] = {} + for name in BRANCH_ORDER: + if not maes[name]: + raise ValueError("calibration has no training records for %s" % name) + p05, p95 = np.percentile(np.asarray(maes[name]), [5.0, 95.0]).tolist() + if p95 <= p05: + p95 = p05 + 1e-6 + domains[name] = { + "p05": float(p05), + "p95": float(p95), + "pixel_q95": _histogram_quantile(histograms[name], 0.95), + "sample_count": float(len(maes[name])), + } + _atomic_write_json( + output_path, + { + "version": 1, + "definition": ( + "paired native-resolution centre-crop RGB absolute residual" + if crop_policy == "native" + else "paired center-crop RGB absolute residual" + ), + "crop_policy": crop_policy, + "fit_split": "train_only", + "fingerprint": fingerprint, + "domains": domains, + }, + ) + return domains + + +@contextmanager +def _batch_norm_eval(model: nn.Module) -> Iterator[None]: + batch_norms = [ + module + for module in model.modules() + if isinstance(module, nn.modules.batchnorm._BatchNorm) + ] + states = [module.training for module in batch_norms] + try: + for module in batch_norms: + module.eval() + yield + finally: + for module, state in zip(batch_norms, states): + module.train(state) + + +def forward_clean_bn_safe(model: nn.Module, clean: torch.Tensor): + """Clean paired pass with gradients, without changing degraded BN statistics.""" + with _batch_norm_eval(model): + return model.forward_student(clean) + + +def spatial_supervision_loss( + spatial_maps: torch.Tensor, + degraded: torch.Tensor, + clean: torch.Tensor, + labels: torch.Tensor, + pixel_q95: torch.Tensor, +) -> Tuple[torch.Tensor, Dict[str, float]]: + if spatial_maps.ndim != 4 or spatial_maps.shape[1] != NUM_KNOWN: + raise ValueError("spatial_maps must be [B,4,H,W]") + residual = (degraded - clean).abs().mean(dim=1, keepdim=True) + target = F.adaptive_avg_pool2d(residual, spatial_maps.shape[-2:]) + scales = pixel_q95.to(spatial_maps.device).index_select(0, labels) + target = (target / scales.view(-1, 1, 1, 1).clamp_min(1e-6)).clamp(0, 1) + rows = torch.arange(labels.shape[0], device=labels.device) + selected = spatial_maps[rows, labels].unsqueeze(1) + selected_loss = F.smooth_l1_loss(selected, target) + selected_mae = (selected - target).abs().mean() + active_mask = F.one_hot(labels, NUM_KNOWN).to(spatial_maps.dtype) + inactive_mask = 1.0 - active_mask.view(-1, NUM_KNOWN, 1, 1) + inactive_square = (spatial_maps.square() * inactive_mask).sum() / ( + inactive_mask.sum() * spatial_maps.shape[-2] * spatial_maps.shape[-1] + ).clamp_min(1.0) + inactive_activation = (spatial_maps * inactive_mask).sum() / ( + inactive_mask.sum() * spatial_maps.shape[-2] * spatial_maps.shape[-1] + ).clamp_min(1.0) + loss = selected_loss + 0.25 * inactive_square + return loss, { + "spatial_selected_mae": float(selected_mae.detach().item()), + "spatial_inactive_activation": float(inactive_activation.detach().item()), + } + + +OOD_KINDS = ("snow", "blur", "pixelate", "sharpen") + + +def synthesize_ood( + clean: torch.Tensor, kind: str, generator: torch.Generator +) -> torch.Tensor: + """Deterministic synthetic OOD degradations disjoint from the four knowns. + + snow = blob occluders, blur = PSF loss, pixelate = compression-like. + Parameters are drawn from the CPU generator so plans replay exactly. + """ + if clean.ndim != 4 or clean.shape[1] != 3: + raise ValueError("clean must be a [B,3,H,W] tensor") + if kind == "snow": + batch, _, height, width = clean.shape + flakes = 96 + yy, xx = torch.meshgrid( + torch.arange(height, dtype=torch.float32), + torch.arange(width, dtype=torch.float32), + ) + yy = yy.to(clean.device) + xx = xx.to(clean.device) + result = [] + for index in range(batch): + params = torch.rand(flakes, 6, generator=generator) + cx = (params[:, 0] * (width - 1)).to(clean.device) + cy = (params[:, 1] * (height - 1)).to(clean.device) + radius = (1.0 + params[:, 2] * 4.0).to(clean.device) + # Near-circular flakes only: elongated blobs are statistically + # rain streaks and teach the router to dump real rain into the + # free slots (measured: rain argmax 97->61 with elong up to 3x). + elong = (1.0 + params[:, 3] * 0.5).to(clean.device) + opacity = (0.55 + params[:, 4] * 0.4).to(clean.device) + du = xx.unsqueeze(0) - cx.view(-1, 1, 1) + dv = yy.unsqueeze(0) - cy.view(-1, 1, 1) + blob = torch.exp( + -( + du.square() / (2.0 * (radius * elong).view(-1, 1, 1).square()) + + dv.square() / (2.0 * radius.view(-1, 1, 1).square()) + ) + ) + alpha = (opacity.view(-1, 1, 1) * blob).sum(dim=0).clamp(0, 1) + result.append(clean[index] * (1 - alpha) + alpha) + return torch.stack(result, dim=0) + if kind == "blur": + sigma = 1.5 + float(torch.rand(1, generator=generator)) * 2.0 + size = int(2 * round(3 * sigma) + 1) + offsets = torch.arange(size, dtype=torch.float32) - size // 2 + kernel = torch.exp(-offsets.square() / (2 * sigma * sigma)) + kernel = (kernel / kernel.sum()).to(clean.device) + pad = size // 2 + row = kernel.view(1, 1, 1, size).expand(3, 1, 1, size) + col = kernel.view(1, 1, size, 1).expand(3, 1, size, 1) + blurred = F.conv2d( + F.pad(clean, (pad, pad, 0, 0), mode="reflect"), row, groups=3 + ) + return F.conv2d( + F.pad(blurred, (0, 0, pad, pad), mode="reflect"), col, groups=3 + ) + if kind == "pixelate": + factor = 4 * (1 + int(torch.randint(0, 2, (1,), generator=generator))) + down = F.avg_pool2d(clean, factor) + return F.interpolate(down, size=clean.shape[-2:], mode="nearest") + if kind == "sharpen": + # Unsharp masking: MORE fine detail, no degradation. A hard negative + # for the noise concept (fine structured detail must route to null). + amount = 0.8 + 1.2 * float(torch.rand(1, generator=generator)) + kernel = torch.tensor( + [[1.0, 2.0, 1.0], [2.0, 4.0, 2.0], [1.0, 2.0, 1.0]], device=clean.device + ) / 16.0 + blurred = F.conv2d( + F.pad(clean, (1, 1, 1, 1), mode="reflect"), + kernel.view(1, 1, 3, 3).expand(3, 1, 3, 3), groups=3, + ) + return (clean + amount * (clean - blurred)).clamp(0.0, 1.0) + raise ValueError("unknown OOD kind %r" % kind) + + +NOISE_INDEX = BRANCH_ORDER.index("noise") + + +def synthesize_noise( + clean: torch.Tensor, + generator: torch.Generator, + residual_bank: Optional[Sequence[torch.Tensor]] = None, + synthetic_prob: float = 0.5, + gain_max: float = 1.4, +) -> torch.Tensor: + """Realistic noise positives on ANY clean image (deterministic). + + Two modes drawn per image: (a) heteroscedastic Poisson-Gaussian noise in + sRGB (sigma^2 = a*x + b), optionally 3x3-correlated to mimic demosaicing; + (b) transplant of a real SIDD residual (noisy - clean) from ``residual_bank`` + with a random flip. Purpose: the noise concept must be learned from noise + statistics on thousands of scenes, not memorised from 8 SIDD scenes. + """ + if clean.ndim != 4 or clean.shape[1] != 3: + raise ValueError("clean must be a [B,3,H,W] tensor") + batch = clean.shape[0] + outputs = [] + for index in range(batch): + image = clean[index] + use_bank = ( + residual_bank is not None and len(residual_bank) > 0 + and float(torch.rand(1, generator=generator)) >= float(synthetic_prob) + ) + if use_bank: + pick = int(torch.randint(0, len(residual_bank), (1,), generator=generator)) + residual = residual_bank[pick].to(image.device, image.dtype) + if residual.shape[-2:] != image.shape[-2:]: + residual = F.interpolate( + residual.unsqueeze(0), size=image.shape[-2:], mode="bilinear", + align_corners=False, + )[0] + flips = torch.rand(2, generator=generator) + if float(flips[0]) < 0.5: + residual = residual.flip(-1) + if float(flips[1]) < 0.5: + residual = residual.flip(-2) + gain = 0.5 + (float(gain_max) - 0.5) * float(torch.rand(1, generator=generator)) + noisy = image + gain * residual + else: + params = torch.rand(4, generator=generator) + a = 0.002 + 0.028 * float(params[0]) + b = 0.0002 + 0.006 * float(params[1]) + sigma = (a * image.clamp(0.0, 1.0) + b).sqrt() + noise = torch.randn(image.shape, generator=generator).to(image.device) + if float(params[2]) < 0.5: + kernel = torch.tensor( + [[1.0, 2.0, 1.0], [2.0, 4.0, 2.0], [1.0, 2.0, 1.0]], + device=image.device, + ) / 16.0 + noise = F.conv2d( + F.pad(noise.unsqueeze(0), (1, 1, 1, 1), mode="reflect"), + kernel.view(1, 1, 3, 3).expand(3, 1, 3, 3), groups=3, + )[0] * 1.6 # restore variance lost to the blur + noisy = image + sigma * noise + outputs.append(noisy.clamp(0.0, 1.0)) + return torch.stack(outputs, dim=0) + + +def apply_noise_positives( + degraded: torch.Tensor, + clean: torch.Tensor, + labels: torch.Tensor, + severity: torch.Tensor, + probability: float, + generator: torch.Generator, + noise_calibration: Mapping[str, float], + residual_bank: Optional[Sequence[torch.Tensor]] = None, + synthetic_prob: float = 0.5, + gain_max: float = 1.4, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Turn a random subset of NON-noise pairs into noise pairs. + + Returns new (degraded, labels, severity, mask) tensors; the originals are + not mutated. Severity targets use the same residual-MAE rule and the + noise-domain calibration as real SIDD pairs. + """ + if probability <= 0.0: + return degraded, labels, severity, torch.zeros_like(labels, dtype=torch.bool) + draw = torch.rand(labels.shape[0], generator=generator).to(labels.device) + mask = (draw < float(probability)) & (labels != NOISE_INDEX) + if not bool(mask.any()): + return degraded, labels, severity, mask + noisy = synthesize_noise( + clean, generator, residual_bank, synthetic_prob=synthetic_prob, gain_max=gain_max + ) + new_degraded = torch.where(mask.view(-1, 1, 1, 1), noisy, degraded) + new_labels = torch.where(mask, torch.full_like(labels, NOISE_INDEX), labels) + p05, p95 = float(noise_calibration["p05"]), float(noise_calibration["p95"]) + per_image = torch.stack([ + residual_mae_severity(noisy[i], clean[i], p05, p95) for i in range(labels.shape[0]) + ]).to(severity.dtype) + new_severity = torch.where(mask, per_image, severity) + return new_degraded, new_labels, new_severity, mask + + +def ood_global_margin_loss( + known_global: torch.Tensor, + known_labels: torch.Tensor, + ood_global: torch.Tensor, + margin: float = 0.5, +) -> torch.Tensor: + """v6: every real-OOD global vector must stay at least ``margin`` (in + L2-normalised space, so 0..2) away from the nearest KNOWN-type batch + centroid. Hinge only: nothing pulls OOD samples together or towards a + slot, so the free nodes keep their own geometry. Zero when the batch + has no OOD rows or no known rows.""" + + if ood_global.shape[0] == 0 or known_global.shape[0] == 0: + return known_global.new_tensor(0.0) + known = F.normalize(known_global.float(), dim=1) + ood = F.normalize(ood_global.float(), dim=1) + centroids = [] + for label in torch.unique(known_labels): + centroids.append(F.normalize(known[known_labels == label].mean(dim=0, keepdim=True), dim=1)) + centroids = torch.cat(centroids, dim=0) # [K', D] + distance = torch.cdist(ood, centroids) # [N, K'] + nearest = distance.min(dim=1).values + return F.relu(float(margin) - nearest).mean() + + +def texture_null_weights(clean: torch.Tensor) -> torch.Tensor: + """Per-image weights in [0.5, 1.5] rising with high-frequency texture. + + Clean images with strong structured high frequencies are the hardest + negatives for the noise concept (texture is not noise); they get the + strongest pull into the null slots. + """ + luma = (0.299 * clean[:, 0] + 0.587 * clean[:, 1] + 0.114 * clean[:, 2]).unsqueeze(1) + kernel = torch.tensor( + [[0.0, 1.0, 0.0], [1.0, -4.0, 1.0], [0.0, 1.0, 0.0]], device=clean.device, + dtype=luma.dtype, + ).view(1, 1, 3, 3) + response = F.conv2d(luma, kernel, padding=1) + variance = response.flatten(1).var(dim=1) + if variance.numel() < 2: + return torch.ones_like(variance) + ranks = variance.argsort().argsort().to(variance.dtype) + return 0.5 + ranks / max(1.0, float(variance.numel() - 1)) + + +class WeightEMA: + """Exponential moving average of the encoder weights (v5d). + + The shadow module is what gets evaluated, selected and written to + ``model_state_dict`` (Phase-2 consumes it). Floating-point buffers (the + BatchNorm running statistics of ``feature_extractor``) are averaged with + the same decay as the weights, exactly like timm's ModelEma: copying the + live statistics next to averaged conv weights collapsed routing (every + input -> rain) because BatchNorm makes the network sensitive to the + weight/statistic mismatch. Integer buffers (``num_batches_tracked``) are + copied. ``warmup`` uses ``min(decay, (1 + n) / (10 + n))`` so early + shadows are not dominated by the random initialisation. + """ + + def __init__(self, model: nn.Module, decay: float, warmup: bool = True) -> None: + if not 0.0 < float(decay) < 1.0: + raise ValueError("ema decay must be in (0, 1), got %r" % decay) + self.decay = float(decay) + self.warmup = bool(warmup) + self.updates = 0 + self.module = copy.deepcopy(model).eval() + for parameter in self.module.parameters(): + parameter.requires_grad_(False) + + def effective_decay(self, updates: int) -> float: + if not self.warmup: + return self.decay + return min(self.decay, (1.0 + updates) / (10.0 + updates)) + + @torch.no_grad() + def update(self, model: nn.Module) -> None: + self.updates += 1 + decay = self.effective_decay(self.updates) + live = dict(model.named_parameters()) + for name, shadow in self.module.named_parameters(): + shadow.mul_(decay).add_(live[name].detach().to(shadow.dtype), alpha=1.0 - decay) + live_buffers = dict(model.named_buffers()) + for name, shadow in self.module.named_buffers(): + if shadow.dtype.is_floating_point: + shadow.mul_(decay).add_(live_buffers[name].detach().to(shadow.dtype), alpha=1.0 - decay) + else: + shadow.copy_(live_buffers[name]) + + +@dataclass(frozen=True) +class LossWeights: + route: float = 1.0 + global_type: float = 0.5 + severity: float = 1.0 + root: float = 0.2 + content: float = 0.2 + # v3.1 rebalance: the free-slot attractor absorbed known-domain mass + # (rain 97->61); keep the null/OOD pull but halve it and raise the + # known-sample free-mass suppression. + unknown: float = 0.25 + spatial: float = 0.1 + null_route: float = 0.15 + ood_route: float = 0.15 + unknown_margin: float = 0.1 + # v5: metric separation on the readout embedding, supervised photometric + # shift (HVI global affine degraded->clean), and the null pull on an + # extra clean pool (Snow100K gt) that is not paired with any degradation. + embed: float = 0.0 + photometric: float = 0.0 + extra_null: float = 0.0 + # v6: margin between real-OOD global vectors and the known-type batch + # centroids (t-SNE showed snow and rain sharing one cloud in + # global_condition even though routing sends snow to the free slots). + ood_global_margin: float = 0.0 + + +CLEAN_CLASS = NUM_KNOWN +UNKNOWN_CLASS = NUM_KNOWN + 1 + + +def supervised_contrastive_loss( + embeddings: torch.Tensor, + labels: torch.Tensor, + temperature: float = 0.1, + unknown_label: Optional[int] = None, +) -> torch.Tensor: + """Supervised contrastive loss (Khosla et al.) on L2-normalised embeddings. + + Samples with ``unknown_label`` act only as negatives: they are pushed away + from every known class and from clean, but never pulled together (unknown + degradations are not one cluster). + """ + z = F.normalize(embeddings.float(), dim=1) + n = z.shape[0] + if n < 2: + return z.new_tensor(0.0) + logits = z @ z.T / float(temperature) + eye = torch.eye(n, dtype=torch.bool, device=z.device) + logits = logits.masked_fill(eye, -1e4) + log_prob = logits - torch.logsumexp(logits, dim=1, keepdim=True) + same = labels.view(-1, 1) == labels.view(1, -1) + positives = same & ~eye + if unknown_label is not None: + positives = positives & (labels.view(-1, 1) != int(unknown_label)) + counts = positives.sum(dim=1) + valid = counts > 0 + if not bool(valid.any()): + return z.new_tensor(0.0) + per_anchor = -(log_prob * positives.to(log_prob.dtype)).sum(dim=1)[valid] / counts[valid].to(log_prob.dtype) + return per_anchor.mean() + + +@torch.no_grad() +def photometric_shift_targets( + degraded: torch.Tensor, clean: torch.Tensor, k: float = 0.2 +) -> torch.Tensor: + """Per-image global affine degraded->clean in HVI, as an 8-vector: + (log gain_I, bias_I, M11-1, M21, M12, M22-1, t1, t2) where + [h', v'] = [h, v] @ M + t on the HV plane. Identity maps to zeros.""" + k_value = float(k.detach()) if torch.is_tensor(k) else float(k) + hd = rgb_to_hvi(degraded.float().clamp(0, 1), k_value) + hc = rgb_to_hvi(clean.float().clamp(0, 1), k_value) + x, y = hd[:, 2].flatten(1), hc[:, 2].flatten(1) + xm, ym = x.mean(1, keepdim=True), y.mean(1, keepdim=True) + var = ((x - xm) ** 2).mean(1) + cov = ((x - xm) * (y - ym)).mean(1) + gain = (cov / (var + 1e-6)).clamp(0.05, 20.0) + bias = ym.squeeze(1) - gain * xm.squeeze(1) + ones = torch.ones_like(x) + a_mat = torch.stack((hd[:, 0].flatten(1), hd[:, 1].flatten(1), ones), dim=2) # [B,N,3] + y_mat = torch.stack((hc[:, 0].flatten(1), hc[:, 1].flatten(1)), dim=2) # [B,N,2] + ata = a_mat.transpose(1, 2) @ a_mat + 1e-4 * torch.eye(3, device=x.device).unsqueeze(0) + aty = a_mat.transpose(1, 2) @ y_mat + # Batched tiny solves go through cuSOLVER in torch 1.10 and intermittently + # raise "CUDA error: misaligned address" (killed phase1_v5 at epoch 8). + # B x 3 x 3 in float64 on the CPU is exact and costs nothing. + try: + m = torch.linalg.solve(ata.double().cpu(), aty.double().cpu()).to(x.device, x.dtype) # [B,3,2] + except RuntimeError: + m = torch.tensor([[1.0, 0.0], [0.0, 1.0], [0.0, 0.0]], device=x.device, dtype=x.dtype) + m = m.unsqueeze(0).expand(x.shape[0], -1, -1).clone() + target = torch.stack(( + gain.log(), bias, + m[:, 0, 0] - 1.0, m[:, 1, 0], m[:, 0, 1], m[:, 1, 1] - 1.0, m[:, 2, 0], m[:, 2, 1], + ), dim=1) + return target.clamp(-3.0, 3.0) + + +# Real-OOD / extra-clean pools live in src.data.folder_crops (shared with +# the Phase-2 runtime); the names are re-exported for the trainer's callers. +from src.data.folder_crops import ( # noqa: E402 + FolderCropDataset, infinite_batches as _infinite_batches, list_image_files, +) + + +class Phase1GraphObjective(nn.Module): + """Paired supervised objective; contains only the trainer-side type head.""" + + def __init__( + self, + node_dim: int = 256, + weights: Optional[LossWeights] = None, + texture_weighted_null: bool = False, + readout_dim: int = 0, + embed_temperature: float = 0.1, + embed_dim: int = 128, + embed_members: str = "all", + severity_floor: float = 0.0, + ood_global_margin: float = 0.5, + ): + super().__init__() + if float(severity_floor) < 0.0: + raise ValueError("severity_floor must be >= 0") + # v5e: pairs whose crop-level severity is below the floor carry no + # visible degradation; they are supervised as clean (free slots, + # zero severity) instead of forcing a hard type route. + self.severity_floor = float(severity_floor) + self.ood_global_margin = float(ood_global_margin) + if embed_members not in EMBED_MEMBERS: + raise ValueError("embed_members must be one of %r, got %r" % (EMBED_MEMBERS, embed_members)) + self.global_type_head = nn.Linear(node_dim, NUM_KNOWN) + self.weights = weights or LossWeights() + self.texture_weighted_null = bool(texture_weighted_null) + self.embed_temperature = float(embed_temperature) + # v5c: "known_clean" keeps the extra clean pool and the OOD batch out of + # the contrastive term (v5/v5b: clean+pool were 64 of 128 samples and + # unknown-as-negative pushed real snow/light rain into the free slot). + self.embed_members = str(embed_members) + self.embed_projector = ( + nn.Sequential(nn.Linear(readout_dim, embed_dim), nn.SiLU(), nn.Linear(embed_dim, embed_dim)) + if self.weights.embed > 0.0 and readout_dim > 0 else None + ) + + def forward( + self, + graph_degraded, + graph_clean, + degraded: torch.Tensor, + clean: torch.Tensor, + labels: torch.Tensor, + severity_targets: torch.Tensor, + pixel_q95: torch.Tensor, + clean_root: torch.Tensor, + graph_ood=None, + graph_extra_clean=None, + photometric_k: float = 0.2, + ) -> Dict[str, torch.Tensor]: + rows = torch.arange(labels.shape[0], device=labels.device) + floored = ( + severity_targets < self.severity_floor + if self.severity_floor > 0.0 + else torch.zeros_like(labels, dtype=torch.bool) + ) + kept = ~floored + kept_rows = rows[kept] + kept_labels = labels[kept] + any_kept = bool(kept.any()) + zero = graph_degraded.routing_probs.new_tensor(0.0) + if any_kept: + selected_probability = graph_degraded.routing_probs[kept_rows, kept_labels] + route = -selected_probability.clamp_min(1e-8).log().mean() + global_type = F.cross_entropy( + self.global_type_head(graph_degraded.global_condition[kept_rows]), kept_labels + ) + selected_severity = graph_degraded.severity_coords[kept_rows, kept_labels] + severity_selected = F.smooth_l1_loss(selected_severity, severity_targets[kept_rows]) + severity_mask = 1.0 - F.one_hot(kept_labels, NUM_KNOWN).to( + graph_degraded.severity_coords.dtype + ) + severity_inactive = ( + graph_degraded.severity_coords[kept_rows].square() * severity_mask + ).sum() / severity_mask.sum().clamp_min(1.0) + else: + route, global_type, severity_selected, severity_inactive = zero, zero, zero, zero + if bool(floored.any()): + # No visible degradation in the crop: every severity coordinate is 0. + severity_inactive = severity_inactive + graph_degraded.severity_coords[floored].square().mean() + severity = severity_selected + 0.1 * severity_inactive + + # The clean root is the fixed graph origin for this supervised v2 run. + # Detaching prevents the target from chasing the clean representation. + anchor = clean_root.detach().to( + graph_clean.global_condition.device + ).expand_as( + graph_clean.global_condition + ) + root = ( + F.smooth_l1_loss(graph_clean.global_condition, anchor) + + graph_clean.severity_coords.square().mean() + + graph_clean.spatial_maps.square().mean() + + graph_clean.unknown_residual.square().mean() + ) + content = F.smooth_l1_loss( + graph_degraded.content_latent, graph_clean.content_latent + ) + if any_kept: + unknown = ( + graph_degraded.routing_probs[kept_rows, NUM_KNOWN:].sum(dim=1).mean() + + 0.1 * graph_degraded.unknown_residual[kept_rows].square().mean() + ) + spatial, spatial_metrics = spatial_supervision_loss( + graph_degraded.spatial_maps[kept_rows], + degraded[kept_rows], + clean[kept_rows], + kept_labels, + pixel_q95, + ) + else: + unknown = zero + spatial = zero + spatial_metrics = {"spatial_selected_mae": 0.0, "spatial_inactive_activation": 0.0} + if bool(floored.any()): + floor_null = ( + -graph_degraded.routing_probs[floored, NUM_KNOWN:].sum(dim=1).clamp_min(1e-8).log().mean() + ) + else: + floor_null = zero + floor_fraction = float(floored.float().mean()) if labels.numel() else 0.0 + + # Free slots are the null/other detector: clean and synthetic-OOD + # inputs must route into them, otherwise the suppression term above + # kills the unseen-degradation mechanism entirely. + null_terms = -graph_clean.routing_probs[:, NUM_KNOWN:].sum(dim=1).clamp_min(1e-8).log() + if self.texture_weighted_null: + null_weights = texture_null_weights(clean.float()).to(null_terms.dtype) + null_route = (null_terms * null_weights).sum() / null_weights.sum() + else: + null_route = null_terms.mean() + if graph_ood is not None: + ood_route = ( + -graph_ood.routing_probs[:, NUM_KNOWN:] + .sum(dim=1) + .clamp_min(1e-8) + .log() + .mean() + ) + scale = math.sqrt(graph_degraded.unknown_residual.shape[1]) + known_norm = graph_degraded.unknown_residual.float().norm(dim=1) / scale + ood_norm = graph_ood.unknown_residual.float().norm(dim=1) / scale + unknown_margin = F.relu( + 0.1 + known_norm.mean() - ood_norm.mean() + ) + ood_route = ood_route + 0.1 * graph_ood.severity_coords.square().mean() + else: + ood_route = route.new_tensor(0.0) + unknown_margin = route.new_tensor(0.0) + ood_global = route.new_tensor(0.0) + if graph_ood is not None and self.weights.ood_global_margin > 0.0 and any_kept: + ood_global = ood_global_margin_loss( + graph_degraded.global_condition[kept_rows], kept_labels, + graph_ood.global_condition, margin=self.ood_global_margin, + ) + + # ---- v5 terms --------------------------------------------------- # + embed = route.new_tensor(0.0) + if self.embed_projector is not None and getattr(graph_degraded, "readout", None) is not None: + feats = [graph_degraded.readout, graph_clean.readout] + degraded_labels = torch.where(floored, torch.full_like(labels, CLEAN_CLASS), labels) + labs = [degraded_labels, torch.full_like(labels, CLEAN_CLASS)] + include_pools = self.embed_members == "all" + if include_pools and graph_extra_clean is not None: + feats.append(graph_extra_clean.readout) + labs.append(torch.full((graph_extra_clean.readout.shape[0],), CLEAN_CLASS, dtype=labels.dtype, device=labels.device)) + if include_pools and graph_ood is not None: + feats.append(graph_ood.readout) + labs.append(torch.full((graph_ood.readout.shape[0],), UNKNOWN_CLASS, dtype=labels.dtype, device=labels.device)) + z = self.embed_projector(torch.cat(feats, dim=0).float()) + embed = supervised_contrastive_loss( + z, torch.cat(labs, dim=0), self.embed_temperature, unknown_label=UNKNOWN_CLASS + ) + photometric = route.new_tensor(0.0) + if self.weights.photometric > 0.0 and getattr(graph_degraded, "photometric_shift", None) is not None: + targets = photometric_shift_targets(degraded, clean, photometric_k) + terms = [F.smooth_l1_loss(graph_degraded.photometric_shift.float(), targets)] + terms.append(graph_clean.photometric_shift.float().abs().mean()) + if graph_extra_clean is not None and graph_extra_clean.photometric_shift is not None: + terms.append(graph_extra_clean.photometric_shift.float().abs().mean()) + photometric = sum(terms) / len(terms) + extra_null = route.new_tensor(0.0) + if graph_extra_clean is not None: + extra_null = ( + -graph_extra_clean.routing_probs[:, NUM_KNOWN:].sum(dim=1).clamp_min(1e-8).log().mean() + + graph_extra_clean.severity_coords.square().mean() + + 0.1 * graph_extra_clean.unknown_residual.square().mean() + ) + + weighted = { + "route": route * self.weights.route, + "global_type": global_type * self.weights.global_type, + "severity": severity * self.weights.severity, + "root": root * self.weights.root, + "content": content * self.weights.content, + "unknown": unknown * self.weights.unknown, + "spatial": spatial * self.weights.spatial, + "null_route": null_route * self.weights.null_route, + "ood_route": ood_route * self.weights.ood_route, + "unknown_margin": unknown_margin * self.weights.unknown_margin, + "embed": embed * self.weights.embed, + "photometric": photometric * self.weights.photometric, + "extra_null": extra_null * self.weights.extra_null, + "floor_null": floor_null * self.weights.null_route, + "ood_global": ood_global * self.weights.ood_global_margin, + } + total = sum(weighted.values()) + result = dict(weighted) + result["total"] = total + result["floor_fraction"] = total.new_tensor(floor_fraction) + result["spatial_selected_mae"] = total.new_tensor( + spatial_metrics["spatial_selected_mae"] + ) + result["spatial_inactive_activation"] = total.new_tensor( + spatial_metrics["spatial_inactive_activation"] + ) + return result + + +def _mean(values: Sequence[float]) -> float: + return float(sum(values) / len(values)) if values else 0.0 + + +def _average_ranks(values: Sequence[float]) -> List[float]: + order = sorted(range(len(values)), key=lambda index: (values[index], index)) + ranks = [0.0] * len(values) + position = 0 + while position < len(order): + end = position + 1 + while end < len(order) and values[order[end]] == values[order[position]]: + end += 1 + average = (position + 1 + end) / 2.0 + for ranked_index in order[position:end]: + ranks[ranked_index] = average + position = end + return ranks + + +def _pearson(left: Sequence[float], right: Sequence[float]) -> float: + if len(left) != len(right): + return 0.0 + finite_pairs = [ + (a, b) + for a, b in zip(left, right) + if math.isfinite(a) and math.isfinite(b) + ] + if len(finite_pairs) < 2: + return 0.0 + left = [a for a, _ in finite_pairs] + right = [b for _, b in finite_pairs] + left_mean, right_mean = _mean(left), _mean(right) + centered_left = [value - left_mean for value in left] + centered_right = [value - right_mean for value in right] + denominator = math.sqrt( + sum(value * value for value in centered_left) + * sum(value * value for value in centered_right) + ) + if denominator <= 1e-12: + return 0.0 + return float( + sum(a * b for a, b in zip(centered_left, centered_right)) / denominator + ) + + +def _spearman(left: Sequence[float], right: Sequence[float]) -> float: + return _pearson(_average_ranks(left), _average_ranks(right)) + + +def compute_validation_metrics( + labels: Sequence[int], + predictions: Sequence[int], + severity_targets: Sequence[float], + severity_predictions: Sequence[float], + unknown_routing: Sequence[float], + entropies: Sequence[float], + losses: Sequence[float], + spatial_mae: Sequence[float], + inactive_activation: Sequence[float], + clean_root_error: Optional[Sequence[float]] = None, + null_accuracy_clean: Optional[float] = None, + null_accuracy_ood: Optional[float] = None, + unknown_norm_gap: Optional[float] = None, +) -> Dict[str, object]: + lengths = { + len(labels), len(predictions), len(severity_targets), + len(severity_predictions), len(unknown_routing), len(entropies), + len(losses), len(spatial_mae), len(inactive_activation), + } + if len(lengths) != 1 or not labels: + raise ValueError("validation metric arrays must be aligned and non-empty") + if clean_root_error is None: + clean_root_error = [0.0] * len(labels) + if len(clean_root_error) != len(labels): + raise ValueError("clean_root_error must align with labels") + + confusion = [[0 for _ in range(NUM_GRAPH_ROUTES)] for _ in range(NUM_KNOWN)] + for truth, prediction in zip(labels, predictions): + if truth < 0 or truth >= NUM_KNOWN: + raise ValueError("truth label outside known classes") + if prediction < 0 or prediction >= NUM_GRAPH_ROUTES: + raise ValueError("prediction outside six graph routes") + confusion[truth][prediction] += 1 + + per_class: Dict[str, Dict[str, float]] = {} + f1_values, recalls = [], [] + for class_index, class_name in enumerate(BRANCH_ORDER): + indices = [i for i, label in enumerate(labels) if label == class_index] + support = len(indices) + true_positive = confusion[class_index][class_index] + false_negative = support - true_positive + false_positive = sum( + confusion[row][class_index] + for row in range(NUM_KNOWN) + if row != class_index + ) + precision = true_positive / max(1, true_positive + false_positive) + recall = true_positive / max(1, true_positive + false_negative) + f1 = 0.0 if precision + recall == 0 else 2 * precision * recall / (precision + recall) + if support > 0: + f1_values.append(f1) + recalls.append(recall) + targets = [severity_targets[i] for i in indices] + estimates = [severity_predictions[i] for i in indices] + per_class[class_name] = { + "support": float(support), + "accuracy": float(recall), + "precision": float(precision), + "f1": float(f1), + "severity_mae": _mean( + [abs(a - b) for a, b in zip(targets, estimates)] + ), + "severity_spearman": _spearman(targets, estimates), + "unknown_routing": _mean([unknown_routing[i] for i in indices]), + "routing_entropy": _mean([entropies[i] for i in indices]), + "loss": _mean([losses[i] for i in indices]), + "spatial_selected_mae": _mean([spatial_mae[i] for i in indices]), + "spatial_inactive_activation": _mean( + [inactive_activation[i] for i in indices] + ), + "clean_root_error": _mean([clean_root_error[i] for i in indices]), + } + + return { + "sample_count": len(labels), + "accuracy": sum(int(a == b) for a, b in zip(labels, predictions)) / len(labels), + "macro_f1": _mean(f1_values), + "balanced_accuracy": _mean(recalls), + "severity_mae": _mean( + [abs(a - b) for a, b in zip(severity_targets, severity_predictions)] + ), + "severity_spearman": _spearman(severity_targets, severity_predictions), + "unknown_routing": _mean(unknown_routing), + "unknown_prediction_rate": sum( + int(prediction >= NUM_KNOWN) for prediction in predictions + ) / len(predictions), + "routing_entropy": _mean(entropies), + "loss": _mean(losses), + "spatial_selected_mae": _mean(spatial_mae), + "spatial_inactive_activation": _mean(inactive_activation), + "clean_root_error": _mean(clean_root_error), + "null_accuracy_clean": ( + float(null_accuracy_clean) if null_accuracy_clean is not None else 0.0 + ), + "null_accuracy_ood": ( + float(null_accuracy_ood) if null_accuracy_ood is not None else 0.0 + ), + "unknown_norm_gap": ( + float(unknown_norm_gap) if unknown_norm_gap is not None else 0.0 + ), + "confusion_matrix": confusion, + "per_class": per_class, + } + + +def _per_sample_eval_values( + graph_degraded, + graph_clean, + degraded: torch.Tensor, + clean: torch.Tensor, + labels: torch.Tensor, + severity: torch.Tensor, + pixel_q95: torch.Tensor, + clean_root: torch.Tensor, +) -> Dict[str, torch.Tensor]: + rows = torch.arange(labels.shape[0], device=labels.device) + selected_severity = graph_degraded.severity_coords[rows, labels] + residual = (degraded - clean).abs().mean(dim=1, keepdim=True) + target_map = F.adaptive_avg_pool2d(residual, graph_degraded.spatial_maps.shape[-2:]) + scales = pixel_q95.index_select(0, labels).view(-1, 1, 1, 1).clamp_min(1e-6) + target_map = (target_map / scales).clamp(0, 1) + selected_map = graph_degraded.spatial_maps[rows, labels].unsqueeze(1) + active = F.one_hot(labels, NUM_KNOWN).to(degraded.dtype).view(-1, NUM_KNOWN, 1, 1) + inactive = (graph_degraded.spatial_maps * (1 - active)).sum(dim=(1, 2, 3)) / ( + (NUM_KNOWN - 1) * graph_degraded.spatial_maps.shape[-2] * graph_degraded.spatial_maps.shape[-1] + ) + root = clean_root.to(degraded.device).expand_as(graph_clean.global_condition) + root_error = ( + (graph_clean.global_condition - root).abs().mean(dim=1) + + graph_clean.severity_coords.abs().mean(dim=1) + + graph_clean.spatial_maps.abs().mean(dim=(1, 2, 3)) + + graph_clean.unknown_residual.abs().mean(dim=1) + ) + route_loss = -graph_degraded.routing_probs[rows, labels].clamp_min(1e-8).log() + spatial_mae = (selected_map - target_map).abs().mean(dim=(1, 2, 3)) + sample_loss = route_loss + (selected_severity - severity).abs() + 0.1 * spatial_mae + 0.2 * root_error + entropy = -( + graph_degraded.routing_probs + * graph_degraded.routing_probs.clamp_min(1e-8).log() + ).sum(dim=1) + return { + "predictions": graph_degraded.routing_probs.argmax(dim=1), + "severity_predictions": selected_severity, + "unknown_routing": graph_degraded.routing_probs[:, NUM_KNOWN:].sum(dim=1), + "entropy": entropy, + "loss": sample_loss, + "spatial_mae": spatial_mae, + "inactive_activation": inactive, + "clean_root_error": root_error, + } + + +def _sanitize_json(payload: object) -> object: + """Replace non-finite floats with None so logging can never abort a run.""" + if isinstance(payload, float): + return payload if math.isfinite(payload) else None + if isinstance(payload, dict): + return {key: _sanitize_json(value) for key, value in payload.items()} + if isinstance(payload, (list, tuple)): + return [_sanitize_json(value) for value in payload] + return payload + + +def _atomic_write_json(path: Path, payload: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name( + ".%s.%d.%d.tmp" % (path.name, os.getpid(), time.time_ns()) + ) + try: + temporary.write_text( + json.dumps( + _sanitize_json(payload), indent=2, sort_keys=True, allow_nan=False + ), + encoding="utf-8", + ) + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +def _atomic_torch_save(path: Path, payload: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name( + ".%s.%d.%d.tmp" % (path.name, os.getpid(), time.time_ns()) + ) + try: + torch.save(payload, str(temporary)) + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +def make_checkpoint( + model: nn.Module, + aux_classifier: nn.Module, + optimizer, + scheduler, + scaler, + epoch: int, + best_score: float, + config: Mapping[str, object], + provenance: Mapping[str, object], + history: Sequence[Mapping[str, object]], + severity_calibration: Mapping[str, Mapping[str, float]], + raw_model: Optional[nn.Module] = None, +) -> Dict[str, object]: + trainer_state: Dict[str, object] = { + "global_type_head": aux_classifier.state_dict(), + } + if raw_model is not None: + # v5d: ``model`` is the EMA shadow (what Phase-2 loads); keep the live + # weights trainer-side so a resume does not restart from the average. + trainer_state["raw_model_state_dict"] = raw_model.state_dict() + if optimizer is not None: + trainer_state["optimizer"] = optimizer.state_dict() + if scheduler is not None: + trainer_state["scheduler"] = scheduler.state_dict() + if scaler is not None: + trainer_state["grad_scaler"] = scaler.state_dict() + return { + "schema_version": 2, + "phase": 1, + "epoch": int(epoch), + "best_score": float(best_score), + # Phase 2 consumes this exact key with strict state loading. + "model_state_dict": model.state_dict(), + "trainer_state": trainer_state, + "branch_order": list(BRANCH_ORDER), + "aggregation_version": AGGREGATION_VERSION, + "config": dict(config), + "provenance": dict(provenance), + "history": list(history), + "severity_calibration": dict(severity_calibration), + } + + +def _record_counts(records: Sequence[PairRecord]) -> Dict[str, object]: + by_class = {name: 0 for name in BRANCH_ORDER} + by_dataset: Dict[str, int] = {} + unique_groups: Dict[str, set] = {} + for record in records: + by_class[record.degradation] += 1 + by_dataset[record.dataset] = by_dataset.get(record.dataset, 0) + 1 + unique_groups.setdefault(record.dataset, set()).add(record.split_group) + return { + "pairs": len(records), + "by_class": by_class, + "by_dataset": by_dataset, + "unique_groups_by_dataset": { + name: len(groups) for name, groups in sorted(unique_groups.items()) + }, + } + + +def _split_digest(records: Sequence[PairRecord]) -> str: + digest = hashlib.sha256(b"SCDC_PHASE1_SPLIT_V2\0") + for record in records: + digest.update(record.record_id.encode("ascii")) + digest.update(b"\n") + return digest.hexdigest() + + +def make_provenance(args: argparse.Namespace, splits: DataSplits) -> Dict[str, object]: + return { + "schema_version": 2, + "branch_order": list(BRANCH_ORDER), + "deployed_positional_mapping": { + "blur": "rain", "noise": "noise", "jpeg": "haze", "lowlight": "lowlight" + }, + "aggregation_version": AGGREGATION_VERSION, + "rain_quarantine_manifest": str(Path(args.quarantine_manifest).resolve()), + "rain_quarantine_sha256": sha256_file(Path(args.quarantine_manifest)), + "quarantined_rain_train_pairs": splits.quarantine_count, + "split_policy": { + "Rain13K": "quarantined train; Test100 val; Test1200 locked test", + "LOLv2": "Train only train; Test only val", + "RESIDE": "sorted first5000; first100 val; exclude every val source from train", + "SIDD": "scene_number grouped; SHA256 scene order; first8/next1/last1 scenes", + }, + "locked_test_policy": "never decoded until best selection and --run-final-test", + "counts": { + "train": _record_counts(splits.train), + "val": _record_counts(splits.val), + "locked_test": _record_counts(splits.locked_test), + }, + "split_digests": { + "train": _split_digest(splits.train), + "val": _split_digest(splits.val), + "locked_test": _split_digest(splits.locked_test), + }, + "crop_policy": str(getattr(args, "crop_policy", "resize")), + "sidd_cache": { + "version": CACHE_VERSION, + "format": ( + "paired RGB uint8 PNG native-resolution crops (%d random per train pair, centre for eval)" + % int(getattr(args, "sidd_native_crops", 32)) + if str(getattr(args, "crop_policy", "resize")) == "native" + else "paired RGB uint8 PNG after shorter-side resize + center crop" + ), + "prebuild": "main process, train and val only before optimization", + }, + "severity": { + "proxy": "paired RGB residual MAE", + "normalization": "per-domain train-only p05/p95", + "spatial_scale": "per-domain train-only residual-pixel q95", + }, + } + + +def _worker_seed(worker_id: int) -> None: + seed = torch.initial_seed() % (2 ** 32) + random.seed(seed) + np.random.seed(seed) + + +def _loader_kwargs(args: argparse.Namespace, device: torch.device) -> Dict[str, object]: + kwargs: Dict[str, object] = { + "num_workers": args.workers, + "pin_memory": device.type == "cuda", + "worker_init_fn": _worker_seed, + } + if args.workers > 0: + kwargs["persistent_workers"] = True + kwargs["prefetch_factor"] = args.prefetch_factor + return kwargs + + +def build_loaders( + args: argparse.Namespace, + splits: DataSplits, + calibration: Mapping[str, Mapping[str, float]], + device: torch.device, + cache_root: Path, +) -> Tuple[DataLoader, DataLoader, PairDataset, PairDataset]: + crop_policy = str(getattr(args, "crop_policy", "resize")) + sidd_native_crops = int(getattr(args, "sidd_native_crops", 32)) + train_dataset = PairDataset( + splits.train, args.image_size, calibration, cache_root / "train", + crop_policy=crop_policy, training=True, sidd_native_crops=sidd_native_crops, + crop_select=str(getattr(args, "crop_select", "random")), + crop_candidates=int(getattr(args, "crop_candidates", 4)), + ) + val_dataset = PairDataset( + splits.val, args.image_size, calibration, cache_root / "val", + crop_policy=crop_policy, training=False, sidd_native_crops=sidd_native_crops, + ) + # Build once in the main process; workers never touch 6.6GB raw SIDD pairs. + train_dataset.prepare_cache() + val_dataset.prepare_cache() + steps = args.steps_per_epoch or int(math.ceil(len(train_dataset) / args.batch_size)) + batch_sampler = BalancedBatchSampler( + [record.label for record in splits.train], + batch_size=args.batch_size, + steps=steps, + seed=args.seed, + yield_seeds=(crop_policy == "native"), + ) + kwargs = _loader_kwargs(args, device) + train_loader = DataLoader(train_dataset, batch_sampler=batch_sampler, **kwargs) + val_loader = DataLoader( + val_dataset, + batch_size=args.eval_batch_size, + shuffle=False, + drop_last=False, + **kwargs + ) + return train_loader, val_loader, train_dataset, val_dataset + + +@torch.no_grad() +def evaluate( + model: BlindDegradationGraphEncoder, + loader: DataLoader, + device: torch.device, + pixel_q95: torch.Tensor, + real_ood_loader: Optional[DataLoader] = None, +) -> Dict[str, object]: + model.eval() + collected: Dict[str, List[float]] = { + "labels": [], "predictions": [], "severity_targets": [], + "severity_predictions": [], "unknown_routing": [], "entropies": [], + "losses": [], "spatial_mae": [], "inactive_activation": [], + "clean_root_error": [], + } + for batch in loader: + degraded = batch["degraded"].to(device, non_blocking=True) + clean = batch["clean"].to(device, non_blocking=True) + labels = batch["label"].to(device, non_blocking=True).long() + severity = batch["severity"].to(device, non_blocking=True).float() + graph_degraded = model.forward_student(degraded) + graph_clean = forward_clean_bn_safe(model, clean) + values = _per_sample_eval_values( + graph_degraded, graph_clean, degraded, clean, labels, severity, + pixel_q95.to(device), model.clean_root(), + ) + collected["labels"].extend(labels.cpu().tolist()) + collected["severity_targets"].extend(severity.cpu().tolist()) + mapping = { + "predictions": "predictions", + "severity_predictions": "severity_predictions", + "unknown_routing": "unknown_routing", + "entropy": "entropies", + "loss": "losses", + "spatial_mae": "spatial_mae", + "inactive_activation": "inactive_activation", + "clean_root_error": "clean_root_error", + } + for source, target in mapping.items(): + collected[target].extend(values[source].detach().cpu().tolist()) + + # Null/OOD routing audit: clean inputs and deterministic synthetic OOD + # must land in the free slots, and OOD unknown-residual norms must sit + # above the in-domain norms for novelty scoring to have the right sign. + null_hits, ood_hits, null_total = 0, 0, 0 + known_norms: List[float] = [] + ood_norms: List[float] = [] + ood_generator = torch.Generator() + ood_generator.manual_seed(20260831) + for batch_index, batch in enumerate(loader): + clean = batch["clean"].to(device, non_blocking=True) + degraded = batch["degraded"].to(device, non_blocking=True) + kind = OOD_KINDS[batch_index % len(OOD_KINDS)] + ood = synthesize_ood(clean, kind, ood_generator) + graph_clean = model.forward_student(clean) + graph_ood = model.forward_student(ood) + graph_known = model.forward_student(degraded) + null_hits += int( + (graph_clean.routing_probs.argmax(dim=1) >= NUM_KNOWN).sum() + ) + ood_hits += int( + (graph_ood.routing_probs.argmax(dim=1) >= NUM_KNOWN).sum() + ) + null_total += clean.shape[0] + scale = math.sqrt(graph_known.unknown_residual.shape[1]) + known_norms.extend( + (graph_known.unknown_residual.norm(dim=1) / scale).cpu().tolist() + ) + ood_norms.extend( + (graph_ood.unknown_residual.norm(dim=1) / scale).cpu().tolist() + ) + metrics = compute_validation_metrics( + **collected, + null_accuracy_clean=null_hits / max(1, null_total), + null_accuracy_ood=ood_hits / max(1, null_total), + unknown_norm_gap=_mean(ood_norms) - _mean(known_norms), + ) + if real_ood_loader is not None: + # Held-out REAL unknown degradation (Snow100K synthetic snow): the + # synthetic-blob OOD score above did not transfer to it (ll_v3: 0.50). + real_hits, real_total, real_norms = 0, 0, [] + for images in real_ood_loader: + graph_real = model.forward_student(images.to(device, non_blocking=True)) + real_hits += int((graph_real.routing_probs.argmax(dim=1) >= NUM_KNOWN).sum()) + real_total += images.shape[0] + scale = math.sqrt(graph_real.unknown_residual.shape[1]) + real_norms.extend((graph_real.unknown_residual.norm(dim=1) / scale).cpu().tolist()) + metrics = dict(metrics) + metrics["null_accuracy_ood_real"] = real_hits / max(1, real_total) + metrics["unknown_norm_gap_real"] = _mean(real_norms) - _mean(known_norms) + return metrics + + +SELECTION_MODES: Tuple[str, ...] = ("f1", "balanced") + + +def selection_key( + metrics: Mapping[str, object], mode: str = "f1" +) -> Tuple[float, float, float, float, float]: + """Lexicographic selection: F1 first, then null/OOD routing, then + severity Spearman; MAE terms break exact ties. Missing keys default to + zero so legacy metric dictionaries keep their original ordering. + + ``mode="balanced"`` (v5d) puts ``0.5 * F1 + 0.5 * null_mean`` first so a + checkpoint cannot win on routing alone while failing null detection.""" + if mode not in SELECTION_MODES: + raise ValueError("selection mode must be one of %r, got %r" % (SELECTION_MODES, mode)) + + def _finite(value: object, fallback: float) -> float: + number = float(value) + return number if math.isfinite(number) else fallback + + null_terms = [ + _finite(metrics.get("null_accuracy_clean", 0.0), 0.0), + _finite(metrics.get("null_accuracy_ood", 0.0), 0.0), + ] + if "null_accuracy_ood_real" in metrics: + null_terms.append(_finite(metrics.get("null_accuracy_ood_real", 0.0), 0.0)) + null_mean = sum(null_terms) / len(null_terms) + f1 = _finite(metrics["macro_f1"], float("-inf")) + primary = f1 if mode == "f1" else (0.5 * f1 + 0.5 * null_mean if math.isfinite(f1) else f1) + return ( + primary, + null_mean, + _finite(metrics.get("severity_spearman", 0.0), float("-inf")), + -_finite(metrics["severity_mae"], float("inf")), + -_finite(metrics["spatial_selected_mae"], float("inf")), + ) + + +def train_one_epoch( + model: BlindDegradationGraphEncoder, + objective: Phase1GraphObjective, + loader: DataLoader, + optimizer: torch.optim.Optimizer, + scaler: torch.cuda.amp.GradScaler, + device: torch.device, + pixel_q95: torch.Tensor, + amp_enabled: bool, + max_grad_norm: float, + seed: int = 0, + epoch: int = 0, + noise_aug_prob: float = 0.0, + noise_calibration: Optional[Mapping[str, float]] = None, + residual_bank: Optional[List[torch.Tensor]] = None, + noise_aug_synthetic_prob: float = 0.5, + noise_aug_gain_max: float = 1.4, + real_ood_iter: Optional[Iterator[torch.Tensor]] = None, + real_ood_prob: float = 0.0, + extra_clean_iter: Optional[Iterator[torch.Tensor]] = None, + ema: Optional[WeightEMA] = None, +) -> Dict[str, float]: + model.train() + objective.train() + photometric_k = ( + model.photometric_branch.k.detach() if getattr(model, "photometric_branch", None) is not None else 0.2 + ) + synthetic_kinds = OOD_KINDS if real_ood_iter is None else tuple(k for k in OOD_KINDS if k != "snow") + totals: Dict[str, float] = {} + batches = 0 + for batch_index, batch in enumerate(loader): + degraded = batch["degraded"].to(device, non_blocking=True) + clean = batch["clean"].to(device, non_blocking=True) + labels = batch["label"].to(device, non_blocking=True).long() + severity = batch["severity"].to(device, non_blocking=True).float() + ood_generator = torch.Generator() + ood_generator.manual_seed( + (int(seed) * 1000003 + int(epoch) * 1009 + batch_index) % (2 ** 63 - 1) + ) + if noise_aug_prob > 0.0 and noise_calibration is not None: + # Keep a rolling bank of REAL SIDD residuals for transplanting. + if residual_bank is not None: + real = (labels == NOISE_INDEX).nonzero(as_tuple=True)[0] + for row in real.tolist()[:4]: + residual_bank.append((degraded[row] - clean[row]).detach()) + if len(residual_bank) > 64: + residual_bank.pop(0) + degraded, labels, severity, aug_mask = apply_noise_positives( + degraded, clean, labels, severity, noise_aug_prob, + ood_generator, noise_calibration, residual_bank, + synthetic_prob=noise_aug_synthetic_prob, gain_max=noise_aug_gain_max, + ) + totals["noise_aug_samples"] = totals.get("noise_aug_samples", 0.0) + float(aug_mask.sum()) + use_real_ood = ( + real_ood_iter is not None + and float(torch.rand(1, generator=ood_generator)) < float(real_ood_prob) + ) + if use_real_ood: + ood = next(real_ood_iter).to(device, non_blocking=True) + totals["ood_real_batches"] = totals.get("ood_real_batches", 0.0) + 1.0 + else: + ood_kind = synthetic_kinds[batch_index % len(synthetic_kinds)] + ood = synthesize_ood(clean, ood_kind, ood_generator) + extra_clean = ( + next(extra_clean_iter).to(device, non_blocking=True) + if extra_clean_iter is not None else None + ) + optimizer.zero_grad(set_to_none=True) + with torch.cuda.amp.autocast(enabled=amp_enabled): + graph_degraded = model.forward_student(degraded) + graph_clean = forward_clean_bn_safe(model, clean) + graph_ood = forward_clean_bn_safe(model, ood) + graph_extra = ( + forward_clean_bn_safe(model, extra_clean) if extra_clean is not None else None + ) + losses = objective( + graph_degraded, graph_clean, degraded, clean, labels, severity, + pixel_q95.to(device), model.clean_root(), + graph_ood=graph_ood, graph_extra_clean=graph_extra, + photometric_k=photometric_k, + ) + # A single non-finite batch must neither reach the optimizer nor + # poison the epoch metrics (a NaN in history.json aborts the run). + if not bool(torch.isfinite(losses["total"].detach())): + totals["nonfinite_batches"] = totals.get("nonfinite_batches", 0.0) + 1.0 + optimizer.zero_grad(set_to_none=True) + continue + scaler.scale(losses["total"]).backward() + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_( + list(model.parameters()) + list(objective.parameters()), max_grad_norm + ) + scaler.step(optimizer) + scaler.update() + if ema is not None: + ema.update(model) + batches += 1 + for name, value in losses.items(): + totals[name] = totals.get(name, 0.0) + float(value.detach().item()) + averaged = { + name: value / max(1, batches) + for name, value in totals.items() + if name != "nonfinite_batches" + } + averaged["nonfinite_batches"] = totals.get("nonfinite_batches", 0.0) + if getattr(model, "photometric_branch", None) is not None: + averaged["photometric_k"] = float(model.photometric_branch.k.detach()) + return averaged + + +def assert_phase2_contract(model: BlindDegradationGraphEncoder) -> None: + clone = BlindDegradationGraphEncoder(model.config) + clone.load_state_dict(model.state_dict(), strict=True) + if clone.state_predictor.num_total != NUM_GRAPH_ROUTES: + raise RuntimeError("Phase2 contract requires six graph routes") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Leakage-safe Phase-1 graph encoder trainer/evaluator" + ) + parser.add_argument("--data-root", default=str(DEFAULT_DATA_ROOT)) + parser.add_argument("--rain13k-root", default=str(DEFAULT_RAIN_ROOT)) + parser.add_argument("--quarantine-manifest", default=str(DEFAULT_QUARANTINE)) + parser.add_argument("--output-dir", default=str(DEFAULT_OUTPUT_DIR)) + parser.add_argument("--cache-root", default=None) + parser.add_argument("--epochs", type=int, default=50) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--eval-batch-size", type=int, default=16) + parser.add_argument("--steps-per-epoch", type=int, default=500) + parser.add_argument("--learning-rate", type=float, default=1e-4) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--max-grad-norm", type=float, default=1.0) + parser.add_argument("--image-size", type=int, default=256) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument("--prefetch-factor", type=int, default=2) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--device", default="cuda") + parser.add_argument("--no-amp", action="store_true") + parser.add_argument( + "--noise-aug-prob", type=float, default=0.0, + help="per-sample probability of turning a non-noise pair into a " + "synthetic/transplanted noise pair (noise-concept diversification)", + ) + parser.add_argument( + "--noise-aug-synthetic-prob", type=float, default=0.5, + help="share of noise positives drawn from the Poisson-Gaussian model " + "(the rest transplant real SIDD residuals); 0 = transplant only", + ) + parser.add_argument( + "--noise-aug-gain-max", type=float, default=1.4, + help="upper bound of the residual-transplant gain (lower bound 0.5)", + ) + parser.add_argument( + "--texture-null", action="store_true", + help="weight the clean->null routing loss by high-frequency texture", + ) + parser.add_argument("--reside-limit", type=int, default=5000) + parser.add_argument("--reside-val-count", type=int, default=100) + parser.add_argument("--allow-count-mismatch", action="store_true") + parser.add_argument("--run-final-test", action="store_true") + parser.add_argument("--eval-only", action="store_true") + parser.add_argument("--checkpoint", default=None) + # ---- v5: photometric branch, metric separation, real unknowns -------- # + parser.add_argument("--photometric", action="store_true", + help="add the HVI PhotometricBranch (colour/exposure state + shift head)") + parser.add_argument("--photometric-dim", type=int, default=128) + parser.add_argument("--embed-weight", type=float, default=0.0, + help="supervised-contrastive weight on the readout embedding (0 = off)") + parser.add_argument("--embed-temperature", type=float, default=0.1) + parser.add_argument("--photometric-weight", type=float, default=0.0, + help="weight of the supervised photometric-shift head (0 = off)") + parser.add_argument("--ood-real-root", default=None, + help="folder of REAL unknown-degradation images (e.g. Snow100K synthetic) used as OOD") + parser.add_argument("--ood-real-prob", type=float, default=0.5, + help="probability that a step's OOD batch is drawn from --ood-real-root") + parser.add_argument("--ood-real-val-count", type=int, default=512, + help="last N files of --ood-real-root (sorted) held out for null_accuracy_ood_real") + parser.add_argument("--extra-clean-root", default=None, + help="folder of extra clean images (e.g. Snow100K gt) for the null objective") + parser.add_argument("--extra-null-weight", type=float, default=0.15) + # ---- v5c: native-resolution crops (Phase-2 parity), SupCon membership -- # + parser.add_argument("--crop-policy", choices=CROP_POLICIES, default="resize", + help="resize = legacy shorter-side resize + centre crop (SIDD ~12x " + "downsampled); native = random native crops for training, " + "centre crop for eval, exactly like Phase-2") + parser.add_argument("--sidd-native-crops", type=int, default=32, + help="native 256 crops cached per SIDD training pair (eval: 1 centre crop)") + parser.add_argument("--embed-members", choices=EMBED_MEMBERS, default="all", + help="all = SupCon over degraded+clean+extra clean pool+OOD (v5); " + "known_clean = degraded + paired clean only") + # ---- v5d: EMA weights for eval/selection, balanced checkpoint selection # + parser.add_argument("--ema-decay", type=float, default=0.0, + help="EMA decay for the evaluated/selected weights (0 = off; v5d 0.999)") + parser.add_argument("--selection", choices=SELECTION_MODES, default="f1", + help="f1 = macro-F1 first (legacy); balanced = 0.5*F1 + 0.5*mean(null terms)") + # ---- v5e: residual-aware training crops, severity floor ---------------- # + parser.add_argument("--crop-select", choices=CROP_SELECT, default="random", + help="residual = keep the max-residual crop of --crop-candidates native crops (train only)") + parser.add_argument("--crop-candidates", type=int, default=4) + parser.add_argument("--ll-oriented-bands", action="store_true", + help="v6: add LH1/HL1 log-MAD + anisotropy to the LL global branch stats (rain vs snow/noise)") + parser.add_argument("--root-weight", type=float, default=None, + help="v6: override LossWeights.root (clean global_condition -> clean root); default 0.2") + parser.add_argument("--ood-global-margin-weight", type=float, default=0.0, + help="v6: weight of the hinge keeping real-OOD global vectors >= margin from known-type centroids") + parser.add_argument("--ood-global-margin", type=float, default=0.5, + help="v6: the margin (L2-normalised space, 0..2)") + parser.add_argument("--severity-floor", type=float, default=0.0, + help="training pairs with crop severity below this are supervised as clean (0 = off)") + return parser + + +def _configuration( + args: argparse.Namespace, graph_config: GraphConfig, weights: LossWeights +) -> Dict[str, object]: + return { + "cli": { + key: str(value) if isinstance(value, Path) else value + for key, value in vars(args).items() + }, + "graph_config": dict(vars(graph_config)), + "loss_weights": asdict(weights), + "branch_order": list(BRANCH_ORDER), + "aggregation_version": AGGREGATION_VERSION, + "phase1_arch": ( + "ll_v3" if getattr(graph_config, "use_ll_global", False) else "v2" + ), + } + + +def _pixel_q95_tensor( + calibration: Mapping[str, Mapping[str, float]] +) -> torch.Tensor: + return torch.tensor( + [float(calibration[name]["pixel_q95"]) for name in BRANCH_ORDER], + dtype=torch.float32, + ) + + +def _make_eval_loader( + args: argparse.Namespace, + records: Sequence[PairRecord], + calibration: Mapping[str, Mapping[str, float]], + device: torch.device, + cache_dir: Path, + prebuild_cache: bool, +) -> DataLoader: + dataset = PairDataset( + records, args.image_size, calibration, cache_dir, + crop_policy=str(getattr(args, "crop_policy", "resize")), training=False, + sidd_native_crops=int(getattr(args, "sidd_native_crops", 32)), + ) + if prebuild_cache: + dataset.prepare_cache() + return DataLoader( + dataset, + batch_size=args.eval_batch_size, + shuffle=False, + drop_last=False, + **_loader_kwargs(args, device) + ) + + +def _load_encoder_checkpoint( + checkpoint_path: Path, + model: BlindDegradationGraphEncoder, + objective: Optional[Phase1GraphObjective], + device: torch.device, +) -> Dict[str, object]: + checkpoint = torch.load(str(checkpoint_path), map_location=device) + if "model_state_dict" not in checkpoint: + raise ValueError("checkpoint lacks Phase2-compatible model_state_dict") + if checkpoint.get("aggregation_version") != AGGREGATION_VERSION: + raise ValueError( + "checkpoint aggregation_version must be %d, got %r" + % (AGGREGATION_VERSION, checkpoint.get("aggregation_version")) + ) + if tuple(checkpoint.get("branch_order", ())) != BRANCH_ORDER: + raise ValueError( + "checkpoint branch_order must be %r, got %r" + % (BRANCH_ORDER, checkpoint.get("branch_order")) + ) + model.load_state_dict(checkpoint["model_state_dict"], strict=True) + if objective is not None: + trainer_state = checkpoint.get("trainer_state", {}) + if "global_type_head" in trainer_state: + objective.global_type_head.load_state_dict( + trainer_state["global_type_head"], strict=True + ) + return checkpoint + + +def _run_locked_test( + args: argparse.Namespace, + model: BlindDegradationGraphEncoder, + splits: DataSplits, + calibration: Mapping[str, Mapping[str, float]], + device: torch.device, + cache_root: Path, + output_dir: Path, +) -> Dict[str, object]: + # This is the first point at which locked SIDD scene008 / Rain Test1200 decode. + loader = _make_eval_loader( + args, + splits.locked_test, + calibration, + device, + cache_root / "locked_test", + prebuild_cache=True, + ) + metrics = evaluate(model, loader, device, _pixel_q95_tensor(calibration)) + _atomic_write_json(output_dir / "locked_test_metrics.json", metrics) + return metrics + + +def main(argv: Optional[Sequence[str]] = None) -> int: + args = build_parser().parse_args(argv) + if args.epochs < 0: + raise ValueError("epochs must be non-negative") + if args.image_size <= 0: + raise ValueError("image-size must be positive") + if args.eval_only and not args.checkpoint: + raise ValueError("--eval-only requires --checkpoint") + + set_seed(args.seed) + output_dir = Path(args.output_dir).expanduser().resolve() + output_dir.mkdir(parents=True, exist_ok=True) + cache_root = ( + Path(args.cache_root).expanduser().resolve() + if args.cache_root else output_dir / ("cache/sidd_%d" % args.image_size) + ) + requested_device = torch.device(args.device) + if requested_device.type == "cuda" and not torch.cuda.is_available(): + print("CUDA unavailable; falling back to CPU", flush=True) + device = torch.device("cpu") + else: + device = requested_device + + print("Discovering and auditing data splits...", flush=True) + splits = build_data_splits(args) + provenance = make_provenance(args, splits) + _atomic_write_json(output_dir / "provenance.json", provenance) + + graph_config = GraphConfig( + use_ll_global=True, + use_photometric=bool(getattr(args, "photometric", False)), + photometric_dim=int(getattr(args, "photometric_dim", 128)), + ll_oriented_bands=bool(getattr(args, "ll_oriented_bands", False)), + ) + weights = LossWeights( + embed=float(getattr(args, "embed_weight", 0.0)), + photometric=float(getattr(args, "photometric_weight", 0.0)), + extra_null=float(getattr(args, "extra_null_weight", 0.15)) if getattr(args, "extra_clean_root", None) else 0.0, + ood_global_margin=float(getattr(args, "ood_global_margin_weight", 0.0)), + ) + if getattr(args, "root_weight", None) is not None: + weights = dataclasses.replace(weights, root=float(args.root_weight)) + config = _configuration(args, graph_config, weights) + _atomic_write_json(output_dir / "config.json", config) + model = BlindDegradationGraphEncoder(graph_config).to(device) + objective = Phase1GraphObjective( + graph_config.node_dim, weights, + texture_weighted_null=bool(getattr(args, "texture_null", False)), + readout_dim=int(getattr(model, "readout_dim", 0)), + embed_temperature=float(getattr(args, "embed_temperature", 0.1)), + embed_members=str(getattr(args, "embed_members", "all")), + severity_floor=float(getattr(args, "severity_floor", 0.0)), + ood_global_margin=float(getattr(args, "ood_global_margin", 0.5)), + ).to(device) + assert_phase2_contract(model) + crop_policy = str(getattr(args, "crop_policy", "resize")) + sidd_native_crops = int(getattr(args, "sidd_native_crops", 32)) + + if args.eval_only: + # The evaluated architecture is governed by the checkpoint's stored + # graph_config (legacy v2 checkpoints lack the ll_v3 branch), so the + # model must be rebuilt from it rather than the training default. + import inspect + + peek = torch.load(str(Path(args.checkpoint)), map_location="cpu") + stored_config: Dict[str, object] = {} + config_block = peek.get("config") if isinstance(peek, dict) else None + if isinstance(config_block, dict): + stored_config = dict(config_block.get("graph_config") or {}) + del peek + allowed = set( + inspect.signature(GraphConfig.__init__).parameters + ) - {"self"} + config_kwargs = { + key: value for key, value in stored_config.items() if key in allowed + } + if "spatial_map_size" in config_kwargs: + config_kwargs["spatial_map_size"] = tuple( + config_kwargs["spatial_map_size"] + ) + graph_config = GraphConfig(**config_kwargs) + model = BlindDegradationGraphEncoder(graph_config).to(device) + objective = Phase1GraphObjective( + graph_config.node_dim, weights, + texture_weighted_null=bool(getattr(args, "texture_null", False)), + ).to(device) + checkpoint = _load_encoder_checkpoint( + Path(args.checkpoint), model, objective, device + ) + calibration = checkpoint.get("severity_calibration") + if not calibration: + raise ValueError("checkpoint lacks train-only severity calibration") + val_loader = _make_eval_loader( + args, splits.val, calibration, device, cache_root / "val", True + ) + val_metrics = evaluate( + model, val_loader, device, _pixel_q95_tensor(calibration) + ) + _atomic_write_json(output_dir / "eval_val_metrics.json", val_metrics) + print(json.dumps({"val": val_metrics}, sort_keys=True), flush=True) + if args.run_final_test: + locked_metrics = _run_locked_test( + args, model, splits, calibration, device, cache_root, output_dir + ) + print(json.dumps({"locked_test": locked_metrics}, sort_keys=True), flush=True) + return 0 + + # Prebuild only train+val SIDD caches; locked test stays completely untouched. + dummy_calibration = { + name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + for name in BRANCH_ORDER + } + PairDataset( + splits.train, args.image_size, dummy_calibration, cache_root / "train", + crop_policy=crop_policy, training=True, sidd_native_crops=sidd_native_crops, + ).prepare_cache() + PairDataset( + splits.val, args.image_size, dummy_calibration, cache_root / "val", + crop_policy=crop_policy, training=False, sidd_native_crops=sidd_native_crops, + ).prepare_cache() + calibration = fit_training_calibration( + splits.train, + args.image_size, + output_dir / "severity_calibration.json", + cache_root / "train", + crop_policy=crop_policy, + ) + pixel_q95 = _pixel_q95_tensor(calibration) + train_loader, val_loader, _, _ = build_loaders( + args, splits, calibration, device, cache_root + ) + # v5d: evaluate/select/save the EMA shadow; the live model keeps training. + ema_decay = float(getattr(args, "ema_decay", 0.0)) + ema = WeightEMA(model, ema_decay) if ema_decay > 0.0 else None + eval_model = ema.module if ema is not None else model + raw_model = model if ema is not None else None + selection = str(getattr(args, "selection", "f1")) + real_ood_iter, real_ood_val_loader, extra_clean_iter = None, None, None + pool_workers = max(0, min(4, int(args.workers))) + held_out_names: set = set() + if getattr(args, "ood_real_root", None): + real_files = list_image_files(Path(args.ood_real_root)) + val_count = max(0, min(int(args.ood_real_val_count), len(real_files) // 4)) + real_val = real_files[len(real_files) - val_count:] if val_count else [] + real_train = real_files[: len(real_files) - val_count] + held_out_names = {p.name for p in real_val} + real_ood_iter = _infinite_batches(DataLoader( + FolderCropDataset(real_train, args.image_size, seed=args.seed), + batch_size=args.batch_size, shuffle=True, drop_last=True, + num_workers=pool_workers, pin_memory=device.type == "cuda", + )) + if real_val: + real_ood_val_loader = DataLoader( + FolderCropDataset(real_val, args.image_size, seed=args.seed, deterministic=True), + batch_size=args.eval_batch_size, shuffle=False, + num_workers=min(2, pool_workers), pin_memory=device.type == "cuda", + ) + print("real OOD pool: %d train / %d held-out files" % (len(real_train), len(real_val)), flush=True) + if getattr(args, "extra_clean_root", None): + extra_files = [p for p in list_image_files(Path(args.extra_clean_root)) if p.name not in held_out_names] + extra_clean_iter = _infinite_batches(DataLoader( + FolderCropDataset(extra_files, args.image_size, seed=args.seed + 1), + batch_size=args.batch_size, shuffle=True, drop_last=True, + num_workers=pool_workers, pin_memory=device.type == "cuda", + )) + print("extra clean pool: %d files" % len(extra_files), flush=True) + + parameters = list(model.parameters()) + list(objective.parameters()) + optimizer = torch.optim.AdamW( + parameters, lr=args.learning_rate, weight_decay=args.weight_decay + ) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=max(1, args.epochs) + ) + amp_enabled = device.type == "cuda" and not args.no_amp + scaler = torch.cuda.amp.GradScaler(enabled=amp_enabled) + history: List[Mapping[str, object]] = [] + + # Mandatory epoch-0 random-initialization baseline, before any optimizer step. + baseline = evaluate(eval_model, val_loader, device, pixel_q95, real_ood_loader=real_ood_val_loader) + history.append({"epoch": 0, "phase": "baseline", "val": baseline}) + best_key = selection_key(baseline, selection) + best_epoch = 0 + best_path = output_dir / "graph_encoder_best.pt" + baseline_checkpoint = make_checkpoint( + eval_model, objective.global_type_head, optimizer, scheduler, scaler, + epoch=0, best_score=float(baseline["macro_f1"]), config=config, + provenance=provenance, history=history, + severity_calibration=calibration, raw_model=raw_model, + ) + _atomic_torch_save(best_path, baseline_checkpoint) + _atomic_write_json(output_dir / "history.json", history) + print(json.dumps({"epoch": 0, "val": baseline}, sort_keys=True), flush=True) + + residual_bank: List[torch.Tensor] = [] + for epoch in range(1, args.epochs + 1): + train_loader.batch_sampler.epoch = epoch + train_metrics = train_one_epoch( + model, objective, train_loader, optimizer, scaler, device, + pixel_q95, amp_enabled, args.max_grad_norm, + seed=args.seed, epoch=epoch, + noise_aug_prob=float(getattr(args, "noise_aug_prob", 0.0)), + noise_calibration=calibration.get("noise") if isinstance(calibration, Mapping) else None, + residual_bank=residual_bank, + noise_aug_synthetic_prob=float(getattr(args, "noise_aug_synthetic_prob", 0.5)), + noise_aug_gain_max=float(getattr(args, "noise_aug_gain_max", 1.4)), + real_ood_iter=real_ood_iter, + real_ood_prob=float(getattr(args, "ood_real_prob", 0.5)), + extra_clean_iter=extra_clean_iter, + ema=ema, + ) + scheduler.step() + val_metrics = evaluate(eval_model, val_loader, device, pixel_q95, real_ood_loader=real_ood_val_loader) + key = selection_key(val_metrics, selection) + history.append( + {"epoch": epoch, "phase": "train", "train": train_metrics, "val": val_metrics} + ) + if key > best_key: + best_key = key + best_epoch = epoch + _atomic_torch_save( + best_path, + make_checkpoint( + eval_model, objective.global_type_head, optimizer, scheduler, scaler, + epoch=epoch, best_score=float(val_metrics["macro_f1"]), + config=config, provenance=provenance, history=history, + severity_calibration=calibration, raw_model=raw_model, + ), + ) + _atomic_torch_save( + output_dir / "graph_encoder_last.pt", + make_checkpoint( + eval_model, objective.global_type_head, optimizer, scheduler, scaler, + epoch=epoch, best_score=float(best_key[0]), config=config, + provenance=provenance, history=history, + severity_calibration=calibration, raw_model=raw_model, + ), + ) + _atomic_write_json(output_dir / "history.json", history) + print( + json.dumps( + {"epoch": epoch, "best_epoch": best_epoch, "train": train_metrics, "val": val_metrics}, + sort_keys=True, + ), + flush=True, + ) + + # Final evaluation always reloads the selected checkpoint, never the last model. + _load_encoder_checkpoint(best_path, model, objective, device) + if args.run_final_test: + locked_metrics = _run_locked_test( + args, model, splits, calibration, device, cache_root, output_dir + ) + print(json.dumps({"locked_test": locked_metrics}, sort_keys=True), flush=True) + print("Training complete; best epoch %d" % best_epoch, flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dataset/phase1_noise_20260906/code/train_phase1_clean_relative.py b/dataset/phase1_noise_20260906/code/train_phase1_clean_relative.py new file mode 100644 index 0000000000000000000000000000000000000000..02b4a516bc49fa6e87d25041a612286add3a444d --- /dev/null +++ b/dataset/phase1_noise_20260906/code/train_phase1_clean_relative.py @@ -0,0 +1,596 @@ +"""Train seven clean-relative factors without modifying the legacy Phase-1 path. + +Real pairs provide domain labels, not physical severity labels. Controlled +operators supply the latter. Every selected real record is consumed once per +epoch; loss weighting, rather than oversampling, balances domains. +""" + +from __future__ import annotations + +import argparse +import contextlib +from dataclasses import asdict, dataclass +import hashlib +import json +import math +import os +from pathlib import Path +import random +import subprocess +import sys +import tempfile +import time +from typing import Any + +import numpy as np +import torch +from torch import Tensor +import torch.nn.functional as F +from torch.utils.data import DataLoader + +TYPE_ORDER = ("rain", "noise", "haze", "lowlight", "snow", "blur", "jpeg") +HELDOUT_PAIRS = (("rain", "jpeg"), ("noise", "haze"), ("snow", "blur")) +TRAIN_PAIRS = tuple( + (a, b) for a in TYPE_ORDER for b in TYPE_ORDER + if a != b and frozenset((a, b)) not in {frozenset(pair) for pair in HELDOUT_PAIRS} +) + + +def epoch_indices(size: int, seed: int, epoch: int, start: int = 0) -> list[int]: + """An independently seeded permutation, resumable by consumed-record cursor.""" + if size < 0 or not 0 <= start <= size: + raise ValueError("Invalid dataset size or resume cursor") + generator = torch.Generator().manual_seed(seed + epoch * 1_000_003) + return torch.randperm(size, generator=generator).tolist()[start:] + + +def class_weights(labels: Tensor, num_classes: int = 7) -> Tensor: + counts = torch.bincount(labels.long(), minlength=num_classes).float() + present = counts > 0 + weights = torch.zeros_like(counts) + if present.any(): + weights[present] = len(labels) / (present.sum() * counts[present]) + return weights + + +def capture_rng() -> dict[str, Any]: + return { + "python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), + "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None, + } + + +def restore_rng(state: dict[str, Any]) -> None: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"].cpu()) + if state.get("cuda") is not None and torch.cuda.is_available(): + torch.cuda.set_rng_state_all([item.cpu() for item in state["cuda"]]) + + +def _atomic_write(path: Path, writer) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(descriptor, "wb") as handle: + writer(handle) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def atomic_torch_save(payload: Any, path: str | Path) -> None: + _atomic_write(Path(path), lambda handle: torch.save(payload, handle)) + + +def atomic_json_save(payload: Any, path: str | Path) -> None: + encoded = json.dumps(payload, indent=2, allow_nan=False, default=str).encode("utf-8") + _atomic_write(Path(path), lambda handle: handle.write(encoded)) + + +def append_jsonl(path: Path, payload: Any) -> None: + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload, allow_nan=False, default=str) + "\n") + handle.flush() + os.fsync(handle.fileno()) + + +def safe_optimizer_step(model, optimizer, max_norm: float, scaler=None) -> tuple[bool, float | None]: + """Reject all nonfinite gradients before mutating optimizer or parameters.""" + if scaler is not None and scaler.is_enabled(): + scaler.unscale_(optimizer) + parameters = [p for p in model.parameters() if p.grad is not None] + finite = all(bool(torch.isfinite(p.grad).all()) for p in parameters) + norm = None + if finite and parameters: + measured = torch.nn.utils.clip_grad_norm_(parameters, max_norm) + finite = bool(torch.isfinite(measured)) + norm = float(measured) if finite else None + if finite: + if scaler is not None and scaler.is_enabled(): + scaler.step(optimizer) + else: + optimizer.step() + if scaler is not None and scaler.is_enabled(): + scaler.update() + if not finite: + optimizer.zero_grad(set_to_none=True) + return finite, norm + + +def file_digest(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def source_provenance() -> dict[str, Any]: + root = Path(__file__).resolve().parent + files = [Path(__file__), root / "eval_phase1_clean_relative.py", *sorted((root / "src").rglob("*.py"))] + hashes = {str(path.relative_to(root)): file_digest(path) for path in files if path.is_file()} + result: dict[str, Any] = {"source_sha256": hashes, "python": sys.version, "torch": torch.__version__} + for key, command in (("git_head", ["git", "rev-parse", "HEAD"]), ("git_status", ["git", "status", "--porcelain"])): + completed = subprocess.run(command, cwd=root, capture_output=True, text=True, check=False) + result[key] = completed.stdout.strip() if completed.returncode == 0 else None + result["source_digest"] = hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest() + receipt = root / "DEPLOYMENT.json" + result["deployment_receipt"] = json.loads(receipt.read_text()) if receipt.is_file() else None + result["deployment_sha"] = os.environ.get("DEPLOYMENT_SHA") + return result + + +def record_labels(dataset) -> Tensor: + labels = [] + for record in dataset.records: + name = record.get("type", record.get("degradation")) + if name not in TYPE_ORDER: + raise ValueError(f"Unsupported manifest degradation: {name!r}") + labels.append(TYPE_ORDER.index(name)) + return torch.tensor(labels, dtype=torch.long) + + +def scene_component_ids(records: list[dict]) -> list[int]: + """Connect both dataset-scene groups and duplicate clean-image content.""" + parents = list(range(len(records))) + + def find(index): + while parents[index] != index: + parents[index] = parents[parents[index]] + index = parents[index] + return index + + seen = {} + for index, record in enumerate(records): + keys = (("group", record["dataset"], record["group"]), ("content", record["clean_content_sha256"])) + for key in keys: + if key in seen: + current, previous = find(index), find(seen[key]) + parents[max(current, previous)] = min(current, previous) + else: + seen[key] = index + return [find(index) for index in range(len(records))] + + +def selected_indices(labels: Tensor, cap: int | None, seed: int) -> list[int]: + """Deterministic stratified subset for explicitly capped smoke/quick checks.""" + if cap is None or cap >= len(labels): + return list(range(len(labels))) + if cap <= 0: + raise ValueError("An explicit record cap must be positive") + rng = random.Random(seed) + groups = [torch.where(labels == k)[0].tolist() for k in range(len(TYPE_ORDER))] + for group in groups: + rng.shuffle(group) + selected = [] + while len(selected) < cap: + for group in groups: + if group and len(selected) < cap: + selected.append(group.pop()) + return selected + + +@dataclass +class LossWeights: + presence: float = 1.0 + root: float = 1.0 + content: float = 0.1 + variance: float = 0.05 + subspace: float = 0.2 + free: float = 0.02 + distill: float = 0.5 + severity: float = 0.5 + invariance: float = 0.1 + proxy: float = 1.0 + transfer: float = 0.5 + interaction: float = 0.2 + spatial: float = 0.1 + photometric: float = 0.1 + + +def _mean_per_sample(value: Tensor) -> Tensor: + return value.reshape(len(value), -1).mean(1) + + +def image_statistics(image: Tensor) -> Tensor: + """Eight observable image summaries; differences are not physical parameters.""" + gray = image.mean(1, keepdim=True) + return torch.cat((image.mean((-2, -1)), image.std((-2, -1), unbiased=False), + (gray[..., 1:] - gray[..., :-1]).abs().mean((-2, -1)), + (gray[..., 1:, :] - gray[..., :-1, :]).abs().mean((-2, -1))), dim=1) + + +def residual_statistics(residual: Tensor) -> Tensor: + """Residual mean/std and native-grid gradient/Laplacian RMS (15 channels).""" + residual = residual.float() + dx = residual[..., 1:] - residual[..., :-1] + dy = residual[..., 1:, :] - residual[..., :-1, :] + laplace = (4 * residual[..., 1:-1, 1:-1] - residual[..., :-2, 1:-1] + - residual[..., 2:, 1:-1] - residual[..., 1:-1, :-2] - residual[..., 1:-1, 2:]) + def rms(item): + return (item.square().mean((-2, -1)) + 1e-8).sqrt() + return torch.cat((residual.mean((-2, -1)), residual.std((-2, -1), unbiased=False), + rms(dx), rms(dy), rms(laplace)), dim=1) + + +def supervised_terms(rep: dict, presence: Tensor, weights: Tensor, severity: Tensor | None = None, + severity_mask: Tensor | None = None) -> dict[str, Tensor]: + known = presence.shape[1] + positive = presence.sum(1).clamp_min(1) + bce = F.binary_cross_entropy_with_logits(rep["presence_logits"], presence, reduction="none").mean(1) + amplitudes = rep["amplitudes"][:, :known] + inactive = ((1 - presence) * amplitudes.square()).mean(1) + active_error = F.relu(0.25 - amplitudes).square() + if severity is None: + severity_loss = bce.new_zeros(()) + else: + mask = presence if severity_mask is None else severity_mask.to(presence) * presence + active_error = torch.where(mask.bool(), (amplitudes - severity).square(), active_error) + severity_loss = ((((rep["severity"] - severity).square() * mask).sum(1) / mask.sum(1).clamp_min(1)) * weights).mean() + active = (presence * active_error).sum(1) / positive + free = rep["amplitudes"][:, known:].square().mean(1) if rep["amplitudes"].shape[1] > known else bce * 0 + free = free + rep["residual"].square().mean(1) + return { + "presence": (bce * weights).mean(), + "subspace": ((active + inactive) * weights).mean(), + "free": (free * weights).mean(), "severity": severity_loss, + } + + +def pair_objective(model, pair: dict, clean: Tensor, degraded: Tensor, presence: Tensor, + weights: Tensor, loss_weights: LossWeights, severity: Tensor | None = None, + include_anchor: bool = True, severity_mask: Tensor | None = None) -> tuple[Tensor, dict[str, Tensor]]: + student, teacher, reference = pair["student"], pair["teacher"], pair["clean"] + terms = supervised_terms(student, presence, weights, severity, severity_mask) + teacher_terms = supervised_terms(teacher, presence, weights, severity, severity_mask) + terms = {key: (value + teacher_terms[key]) / 2 for key, value in terms.items()} + terms["distill"] = ((student["delta"] - teacher["delta"].detach()).square().mean(1) * weights).mean() + visible_change = F.interpolate((degraded - clean).abs().mean(1, keepdim=True), size=student["spatial"].shape[-2:], mode="area") + spatial_target = visible_change * presence[:, :, None, None] + # Domain-indexed observed change, not a claim of physical factor support. + terms["spatial"] = ((_mean_per_sample((student["spatial"] - spatial_target).square()) + + _mean_per_sample((teacher["spatial"] - spatial_target).square())) * weights).mean() / 2 + photometric_target = image_statistics(degraded) - image_statistics(clean) + terms["photometric"] = (((student["photometric"] - photometric_target).square().mean(1) + + (teacher["photometric"] - photometric_target).square().mean(1)) * weights).mean() / 2 + if include_anchor: + terms["root"] = reference["delta"].square().mean() + F.binary_cross_entropy_with_logits( + reference["presence_logits"], torch.zeros_like(presence)) + terms["root"] += reference["spatial"].square().mean() + terms["content"] = F.smooth_l1_loss(student["content"], reference["content"].detach()) + pooled = reference["content"].mean((-2, -1)).float() + terms["variance"] = F.relu(0.1 - torch.sqrt(pooled.var(0, unbiased=False) + 1e-4)).mean() if len(clean) > 1 else pooled.sum() * 0 + if loss_weights.proxy: + clean_hat = model.decode(reference["content"], torch.zeros_like(teacher["delta"]), clean.shape[-2:]) + degraded_hat = model.decode(reference["content"], teacher["delta"], clean.shape[-2:]) + terms["proxy"] = (_mean_per_sample((clean_hat - clean).abs()) * weights).mean() + terms["proxy"] += (functional_error(degraded_hat, degraded, clean, presence.argmax(1)) * weights).mean() + total = sum(getattr(loss_weights, key) * value for key, value in terms.items()) + return total, terms + + +def controlled_batch(clean_cpu: Tensor, step: int, seed: int, count: int, + pairs=TRAIN_PAIRS, heldout: bool = False, scene_ids: list[str] | None = None) -> dict[str, Any]: + """Matched operators on different content; labels come only from synthesis.""" + from src.data.clean_relative import sample_degradation_parameters, synthesize_composition, synthesize_degradation + + count = min(count, len(clean_cpu)) + scene_ids = scene_ids if scene_ids is not None else [str(i) for i in range(len(clean_cpu))] + partners = [next((j for j in range(len(clean_cpu)) if scene_ids[j] != scene_ids[i]), i) for i in range(count)] + cross_content_available = all(scene_ids[i] != scene_ids[j] for i, j in enumerate(partners)) + collected: dict[str, list] = {key: [] for key in ( + "clean", "other_clean", "single", "other_single", "second", "mixed", + "presence", "second_presence", "severity", "second_severity", "first_type", "second_type", + )} + specs = [] + for i in range(count): + a, b = pairs[(step * count + i) % len(pairs)] + sample_seed = seed + step * 10_007 + i * 101 + pa = sample_degradation_parameters(a, sample_seed, heldout=heldout) + pb = sample_degradation_parameters(b, sample_seed + 1, heldout=heldout) + x = clean_cpu[i] + other = clean_cpu[partners[i]] + ya, _ = synthesize_degradation(x, a, parameters=pa, seed=sample_seed) + yb, _ = synthesize_degradation(x, b, parameters=pb, seed=sample_seed + 1) + yother, _ = synthesize_degradation(other, a, parameters=pa, seed=sample_seed) + mixed, _ = synthesize_composition(x, (a, b), parameters=(pa, pb), seed=sample_seed) + active, second_active = torch.zeros(7), torch.zeros(7) + severity, second_severity = torch.zeros(7), torch.zeros(7) + active[TYPE_ORDER.index(a)] = second_active[TYPE_ORDER.index(b)] = 1 + severity[TYPE_ORDER.index(a)] = float(pa["severity"]) + second_severity[TYPE_ORDER.index(b)] = float(pb["severity"]) + values = (x, other, ya, yother, yb, mixed, active, second_active, severity, second_severity, + torch.tensor(TYPE_ORDER.index(a)), torch.tensor(TYPE_ORDER.index(b))) + for key, value in zip(collected, values): + collected[key].append(value) + specs.append({"first": a, "second": b, "first_parameters": pa, "second_parameters": pb}) + result = {key: torch.stack(values) for key, values in collected.items()} + result["specs"] = specs + result["cross_content_available"] = cross_content_available + return result + + +def synthetic_objective(model, data: dict, loss_weights: LossWeights, use_edges: bool) -> tuple[Tensor, dict[str, Tensor]]: + x = data["clean"] + single = model.forward_pair(data["single"], x) + second = model.forward_pair(data["second"], x) + mixed = model.forward_pair(data["mixed"], x) + pairs = ((single, data["single"], data["presence"], data["severity"]), + (second, data["second"], data["second_presence"], data["second_severity"]), + (mixed, data["mixed"], data["presence"] + data["second_presence"], data["severity"] + data["second_severity"])) + total = x.sum() * 0 + logs: dict[str, Tensor] = {} + for pair, degraded, presence, severity in pairs: + value, terms = pair_objective(model, pair, x, degraded, presence, x.new_ones(len(x)), loss_weights, + severity=severity, include_anchor=False) + total = total + value / len(pairs) + for key, item in terms.items(): + logs[key] = logs.get(key, x.sum() * 0) + item / len(pairs) + composed = model.compose(single["teacher"]["delta"], second["teacher"]["delta"], + data["first_type"], data["second_type"], use_edges=use_edges) + logs["interaction"] = F.mse_loss(composed, mixed["teacher"]["delta"].detach()) + total = total + loss_weights.interaction * logs["interaction"] + if data["cross_content_available"]: + other = model.forward_pair(data["other_single"], data["other_clean"]) + logs["invariance"] = F.mse_loss(single["teacher"]["coefficients"][:, :7], other["teacher"]["coefficients"][:, :7]) + total = total + loss_weights.invariance * logs["invariance"] + if loss_weights.transfer: + prediction = model.decode(other["clean"]["content"], single["teacher"]["delta"], x.shape[-2:]) + logs["transfer"] = functional_error(prediction, data["other_single"], data["other_clean"], data["first_type"]).mean() + total = total + loss_weights.transfer * logs["transfer"] + return total, logs + + +def functional_error(prediction: Tensor, target: Tensor, clean: Tensor, labels: Tensor) -> Tensor: + """Pixel error for deterministic operators; residual moments for random ones. + + Matching moments is deliberately not described as a full likelihood test. + """ + pixel = _mean_per_sample((prediction - target).abs()) + moments = (residual_statistics(prediction - clean) - residual_statistics(target - clean)).abs().mean(1) + stochastic = (labels == TYPE_ORDER.index("noise")) | (labels == TYPE_ORDER.index("rain")) | (labels == TYPE_ORDER.index("snow")) + return torch.where(stochastic, moments, pixel) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--epochs", type=int, default=10) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--patch-size", type=int, default=128) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--lr", type=float, default=2e-4) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--grad-clip", type=float, default=1.0) + parser.add_argument("--amp", choices=("none", "bfloat16", "float16"), default="none") + parser.add_argument("--synthetic-batch-size", type=int, default=4) + parser.add_argument("--synthetic-every", type=int, default=1) + parser.add_argument("--save-every", type=int, default=250) + parser.add_argument("--log-every", type=int, default=25) + parser.add_argument("--val-every", type=int, default=1) + parser.add_argument("--quick-val-records", type=int, default=224) + parser.add_argument("--max-train-records", type=int, help="Explicitly capped smoke run; omitted means ALL train records") + parser.add_argument("--max-steps", type=int, help="Explicit optimizer-attempt cap for a smoke run") + parser.add_argument("--resume") + parser.add_argument("--no-edges", action="store_true", help="Disable ordered-composition correction; evidence attention remains enabled") + parser.add_argument("--prototype-only", action="store_true", help="Rank-one/type baseline; not capacity-matched") + parser.add_argument("--no-proxy", action="store_true") + return parser + + +def main(argv: list[str] | None = None) -> dict[str, Any]: + args = build_parser().parse_args(argv) + for key in ("epochs", "batch_size", "patch_size", "synthetic_batch_size", "synthetic_every", "save_every", "log_every", "val_every", "threads"): + if getattr(args, key) <= 0: + raise ValueError(f"--{key.replace('_', '-')} must be positive") + if args.num_workers < 0 or (args.max_steps is not None and args.max_steps <= 0): + raise ValueError("Invalid worker count or step cap") + if args.patch_size < 32 or args.patch_size % 16: + raise ValueError("Patch size must be >=32 and divisible by16") + torch.set_num_threads(args.threads) + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(args.seed) + device = torch.device(args.device) + if args.amp != "none" and device.type != "cuda": + raise ValueError("AMP is supported here only on CUDA/ROCm devices") + from src.data.clean_relative import PairedDegradationDataset + from src.models.graph_encoder.clean_relative import CleanRelativeConfig, CleanRelativeGraphEncoder + from eval_phase1_clean_relative import evaluate_real + + dataset = PairedDegradationDataset(args.manifest, split="train", crop_size=args.patch_size, seed=args.seed) + labels = record_labels(dataset) + scene_components = scene_component_ids(dataset.records) + selected = selected_indices(labels, args.max_train_records, args.seed) + if not selected: + raise ValueError("Training manifest contains no selected records") + sample_weights = class_weights(labels[selected]).to(device) + config = CleanRelativeConfig(rank=1 if args.prototype_only else 8) + model = CleanRelativeGraphEncoder(config).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) + total_steps = args.epochs * math.ceil(len(selected) / args.batch_size) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_steps) + scaler = torch.amp.GradScaler("cuda", enabled=args.amp == "float16") + loss_weights = LossWeights(proxy=0 if args.no_proxy else 1, transfer=0 if args.no_proxy else 0.5) + output = Path(args.output_dir) + output.mkdir(parents=True, exist_ok=True) + manifest_sha = file_digest(args.manifest) + run_config = { + "arguments": vars(args), "model_config": asdict(config), "loss_weights": asdict(loss_weights), + "type_order": TYPE_ORDER, "manifest_sha256": manifest_sha, "provenance": source_provenance(), + "train_records_total": len(dataset), "train_records_selected": len(selected), + "class_counts": torch.bincount(labels[selected], minlength=7).tolist(), + "class_loss_weights": sample_weights.cpu().tolist(), "sampling": "epoch permutation without replacement; drop_last=False", + "scope": "smoke_capped" if args.max_train_records is not None or args.max_steps is not None else "full_manifest", + "train_compositions": TRAIN_PAIRS, "heldout_compositions": HELDOUT_PAIRS, + "no_edges_scope": "Only ordered-composition correction; not a complete no-message-passing ablation", + "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"], + } + epoch, cursor, global_step, optimizer_steps = 0, 0, 0, 0 + best_score = -float("inf") + skipped = 0 + if args.resume: + checkpoint = torch.load(args.resume, map_location="cpu", weights_only=False) + previous = checkpoint["run_config"] + if previous["manifest_sha256"] != manifest_sha or previous["model_config"] != asdict(config): + raise ValueError("Resume requires identical manifest and model configuration") + 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"): + if previous["arguments"].get(name) != vars(args).get(name): + raise ValueError(f"Resume changes training semantics: {name}") + if previous["provenance"]["source_digest"] != run_config["provenance"]["source_digest"]: + raise ValueError("Source changed since checkpoint; use a new run rather than silently hot-patching") + model.load_state_dict(checkpoint["model"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + scheduler.load_state_dict(checkpoint["scheduler"]) + scaler.load_state_dict(checkpoint["scaler"]) + epoch, cursor = checkpoint["epoch"], checkpoint["cursor"] + global_step, optimizer_steps = checkpoint["global_step"], checkpoint["optimizer_steps"] + best_score, skipped = checkpoint["best_score"], checkpoint["skipped_steps"] + restore_rng(checkpoint["rng"]) + atomic_json_save(run_config, output / f"resume_config_step{global_step}.json") + elif (output / "run_config.json").exists() or (output / "last.pt").exists(): + raise FileExistsError("Output directory already contains a run; use --resume or a new output directory") + else: + atomic_json_save(run_config, output / "run_config.json") + + def save(name="last.pt"): + atomic_torch_save({ + "schema_version": 1, "model": model.state_dict(), "model_config": asdict(config), + "optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict(), "scaler": scaler.state_dict(), + "rng": capture_rng(), "epoch": epoch, "cursor": cursor, "global_step": global_step, + "optimizer_steps": optimizer_steps, "best_score": best_score, "skipped_steps": skipped, + "run_config": run_config, + }, output / name) + + started = time.monotonic() + consecutive_bad = 0 + metrics_path = output / "metrics.jsonl" + while epoch < args.epochs and (args.max_steps is None or global_step < args.max_steps): + dataset.set_epoch(epoch) + indices = [selected[i] for i in epoch_indices(len(selected), args.seed, epoch, cursor)] + loader = DataLoader(dataset, batch_size=args.batch_size, sampler=indices, drop_last=False, + num_workers=args.num_workers, pin_memory=device.type == "cuda", + generator=torch.Generator().manual_seed(args.seed + epoch), persistent_workers=False) + model.train() + for batch in loader: + optimizer.zero_grad(set_to_none=True) + clean_cpu = batch["clean"] + clean, degraded = clean_cpu.to(device), batch["degraded"].to(device) + label = batch["label"].to(device) + presence = batch["presence"].to(device) + dtype = torch.bfloat16 if args.amp == "bfloat16" else torch.float16 + autocast = torch.autocast(device_type="cuda", dtype=dtype) if args.amp != "none" else contextlib.nullcontext() + with autocast: + pair = model.forward_pair(degraded, clean) + loss, terms = pair_objective(model, pair, clean, degraded, presence, sample_weights[label], loss_weights, + severity=batch["severity"].to(device), severity_mask=batch["severity_mask"].to(device)) + if global_step % args.synthetic_every == 0: + scene_ids = [str(scene_components[int(i)]) for i in batch["index"]] + synthetic = controlled_batch(clean_cpu, global_step, args.seed, args.synthetic_batch_size, scene_ids=scene_ids) + synthetic = {key: value.to(device) if isinstance(value, Tensor) else value for key, value in synthetic.items()} + synthetic_loss, synthetic_terms = synthetic_objective(model, synthetic, loss_weights, not args.no_edges) + loss = loss + synthetic_loss + terms.update({"synthetic_" + key: value for key, value in synthetic_terms.items()}) + finite_loss = bool(torch.isfinite(loss)) + gradient_norm = None + if finite_loss: + scaler.scale(loss).backward() + accepted, gradient_norm = safe_optimizer_step(model, optimizer, args.grad_clip, scaler) + else: + accepted = False + optimizer.zero_grad(set_to_none=True) + cursor += len(clean) + global_step += 1 + if accepted: + scheduler.step() + optimizer_steps += 1 + consecutive_bad = 0 + else: + skipped += 1 + consecutive_bad += 1 + if global_step % args.log_every == 0 or not accepted or global_step == 1: + row = {"event": "train", "epoch": epoch, "cursor": cursor, "selected_records": len(selected), + "step": global_step, "optimizer_steps": optimizer_steps, "loss": float(loss.detach()) if finite_loss else None, + "accepted": accepted, "gradient_norm": gradient_norm, "lr": scheduler.get_last_lr()[0], + "elapsed_seconds": time.monotonic() - started, + "cuda_peak_allocated_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else None, + "terms": {key: float(value.detach()) if torch.isfinite(value) else None for key, value in terms.items()}} + append_jsonl(metrics_path, row) + print(json.dumps(row), flush=True) + if global_step % args.save_every == 0 or consecutive_bad >= 3: + save() + if consecutive_bad >= 3: + raise FloatingPointError("Three consecutive nonfinite optimizer attempts; recoverable checkpoint saved") + if args.max_steps is not None and global_step >= args.max_steps: + break + if cursor == len(selected): + append_jsonl(metrics_path, {"event": "epoch_coverage", "epoch": epoch, "unique_records": cursor, + "expected_records": len(selected), "complete": True, "drop_last": False}) + epoch += 1 + cursor = 0 + if epoch % args.val_every == 0: + rng_before = capture_rng() + report = evaluate_real(model, args.manifest, "val", device, args.batch_size, args.patch_size, + args.num_workers, args.quick_val_records, args.seed, functional_enabled=not args.no_proxy) + restore_rng(rng_before) + score = report["classification"]["macro_f1"] + append_jsonl(metrics_path, {"event": "validation", "epoch": epoch, "step": global_step, "report": report}) + if score > best_score: + best_score = score + save("best.pt") + save() + rng_before = capture_rng() + report = evaluate_real(model, args.manifest, "val", device, args.batch_size, args.patch_size, + args.num_workers, None, args.seed, functional_enabled=not args.no_proxy) + restore_rng(rng_before) + final = {"status": "completed" if epoch == args.epochs else "smoke_step_cap", "epoch": epoch, "cursor": cursor, + "global_step": global_step, "optimizer_steps": optimizer_steps, "skipped_steps": skipped, + "elapsed_seconds": time.monotonic() - started, "full_validation": report} + atomic_json_save(final, output / "final_validation.json") + # A capped first epoch may have no quick-validation checkpoint yet. + if not (output / "best.pt").exists(): + best_score = report["classification"]["macro_f1"] + save("best.pt") + save() + print(json.dumps(final), flush=True) + return final + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/train_phase2_gated_resshift_v5.py b/dataset/phase1_noise_20260906/code/train_phase2_gated_resshift_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..98cb2cb018205833c1f9ce52f71d2fa3eabe2011 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/train_phase2_gated_resshift_v5.py @@ -0,0 +1,1145 @@ +#!/usr/bin/env python3 +"""Train Phase 2 v5 with continuous soft experts and DA-CLIP-style control. + +The audited v4 data/DDP/AMP/checkpoint runtime is reused without modifying its +source. This entrypoint installs a scoped v5 backend for the duration of one +run: a five-way continuous router, zero-initialized expert adapters, learned +noise/time prompts, and an optional variance-preserving independent Gaussian +bank. The residual-shift schedule and exact posterior remain unchanged. +""" + +from __future__ import annotations + +import argparse +import contextlib +from dataclasses import dataclass +import hashlib +import math +from pathlib import Path +from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn + +import train_phase2_graph_resshift_v4 as v4 +from src.models.restoration.gated_graph_resshift_v5 import ( + EXPERT_KAPPA_VERSION, + EXPERT_ORDER, + NOISE_MIXER_VERSION, + ROUTER_VERSION, + ExpertKappaSchedule, + GatedConditionBundleV5, + GatedGraphConditionerV5, + GatedGraphResidualShiftUNetV5, + VariancePreservingNoiseMixer, +) +from src.models.restoration.graph_resshift_v4 import ( + BRANCH_ORDER, + FrozenPhase1, + ResidualShiftSchedule, + pad_to_multiple, + pixel_shuffle2, + pixel_unshuffle2, +) + + +V5_SCHEMA_VERSION = 5 +V4_WARMSTART_MAPPING_VERSION = "shared_keys_strict_v1" +NOISE_SEED_VERSION = "legacy_shared_plus_per_sample_expert_bank_v2" + +# Capture the stable backend before the scoped installer replaces names on the +# imported module. Calling these aliases avoids recursion inside the patch. +_V4_ARCHITECTURE = v4._architecture +_V4_DATA_PLAN = v4._data_plan +_V4_SCHEDULE_CONFIG = v4._schedule_config +_V4_LOAD_OR_CREATE_SPLITS = v4._load_or_create_splits +_V4_DETERMINISTIC_TRAINING_PLAN = v4.deterministic_training_plan +_V4_NOISE_FOR_RECORDS = v4._noise_for_records + + +@dataclass +class GatedTrainStepResult: + """Restoration objective plus routed-noise diagnostics.""" + + loss: Tensor + reconstruction_loss: Tensor + router_loss: Tensor + u0_prediction: Tensor + u0_target: Tensor + u_t: Tensor + mixed_noise: Tensor + kappa: Optional[Tensor] = None + + +class Phase2GatedRestorationModule(nn.Module): + """Trainable v5 module; frozen Phase-1 remains outside this object.""" + + def __init__( + self, + conditioner: GatedGraphConditionerV5, + denoiser: nn.Module, + schedule: ResidualShiftSchedule, + noise_mixer: VariancePreservingNoiseMixer, + condition_mode: str, + *, + router_anchor_weight: float = 0.01, + router_balance_weight: float = 0.01, + router_correction_weight: float = 0.001, + expert_kappa: Optional[ExpertKappaSchedule] = None, + ) -> None: + super().__init__() + if condition_mode not in ("full", "null"): + raise ValueError("condition_mode must be 'full' or 'null'") + for name, value in ( + ("router_anchor_weight", router_anchor_weight), + ("router_balance_weight", router_balance_weight), + ("router_correction_weight", router_correction_weight), + ): + if not math.isfinite(value) or value < 0.0: + raise ValueError("%s must be finite and non-negative" % name) + self.conditioner = conditioner + self.denoiser = denoiser + self.schedule = schedule + self.noise_mixer = noise_mixer + self.condition_mode = condition_mode + self.router_anchor_weight = float(router_anchor_weight) + self.router_balance_weight = float(router_balance_weight) + self.router_correction_weight = float(router_correction_weight) + self.expert_kappa = expert_kappa + + def build_condition(self, representation: Any) -> GatedConditionBundleV5: + return self.conditioner(representation, mode=self.condition_mode) + + def effective_kappa( + self, condition: GatedConditionBundleV5 + ) -> Optional[Tensor]: + """Per-sample kappa for the current gate, or None for the global one.""" + + if self.expert_kappa is None: + return None + return self.expert_kappa( + condition.expert_gates, condition.route_active + ) + + def predict_x0( + self, + u_t: Tensor, + u_y: Tensor, + timesteps: Tensor, + condition: GatedConditionBundleV5, + ) -> Tensor: + return self.denoiser(u_t, u_y, timesteps, condition) + + def route_noise( + self, noise_bank: Tensor, condition: GatedConditionBundleV5 + ) -> Tensor: + return self.noise_mixer( + noise_bank, + condition.expert_gates, + condition.route_active, + ) + + def forward( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Tensor, + ) -> Tensor: + # DDP must see the loss through forward, exactly as in v4. + return self.training_loss( + clean, degraded, representation, timesteps, noise + ).loss + + def training_loss( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise_bank: Tensor, + ) -> GatedTrainStepResult: + """FP32 x0 MSE plus label-free router regularization.""" + + u0 = pixel_unshuffle2(clean) + uy = pixel_unshuffle2(degraded) + condition = self.build_condition(representation) + # Kappa is read at the CURRENT anneal position, then the counter + # advances, so the first training microstep is exactly v4-equivalent. + kappa = self.effective_kappa(condition) + mixed_noise = self.route_noise(noise_bank, condition) + if mixed_noise.shape != u0.shape: + raise ValueError("routed noise must match the diffusion state") + u_t = self.schedule.q_sample( + u0, uy, timesteps, noise=mixed_noise, kappa=kappa + ) + prediction = self.predict_x0(u_t, uy, timesteps, condition) + reconstruction = (prediction.float() - u0.float()).square().mean() + router_loss = ( + self.router_anchor_weight * condition.router_anchor_loss.float() + + self.router_balance_weight * condition.router_balance_loss.float() + + self.router_correction_weight + * condition.router_correction_loss.float() + ) + total = reconstruction + router_loss + if self.expert_kappa is not None and self.training: + self.expert_kappa.advance() + return GatedTrainStepResult( + loss=total, + reconstruction_loss=reconstruction, + router_loss=router_loss, + u0_prediction=prediction, + u0_target=u0, + u_t=u_t, + mixed_noise=mixed_noise, + kappa=None if kappa is None else kappa.detach(), + ) + + +def deterministic_expert_training_plan( + reference: Tensor, + timesteps: int, + seed: int, + global_microstep: int, + rank: int = 0, + sample_seeds: Optional[Sequence[int]] = None, + num_experts: int = len(EXPERT_ORDER), +) -> Tuple[Tensor, Tensor]: + """Create a legacy shared stream plus independent expert Gaussians. + + Rank/order invariance requires the per-sample identities emitted by the + balanced sampler. Without ``sample_seeds`` the fallback deliberately + retains v4's rank-local behavior. + """ + + if reference.ndim != 4: + raise ValueError("reference must be a BCHW diffusion state") + if timesteps < 1 or num_experts < 1: + raise ValueError("timesteps and num_experts must be positive") + batch = reference.shape[0] + if sample_seeds is not None and len(sample_seeds) != batch: + raise ValueError("one sample seed is required per image") + + cpu_reference = torch.empty( + tuple(reference.shape), device="cpu", dtype=reference.dtype + ) + legacy_timesteps, legacy_noise = _V4_DETERMINISTIC_TRAINING_PLAN( + cpu_reference, + timesteps, + seed, + global_microstep, + rank=rank, + sample_seeds=sample_seeds, + ) + banks: List[Tensor] = [] + for index in range(batch): + sample_identity: Any + if sample_seeds is None: + sample_identity = ("rank", int(rank), "index", index) + else: + sample_identity = int(sample_seeds[index]) + streams: List[Tensor] = [legacy_noise[index]] + for expert_index in range(num_experts): + generator = torch.Generator(device="cpu") + generator.manual_seed( + v4._seed_value( + seed, + "train-v5", + global_microstep, + sample_identity, + "expert-noise", + expert_index, + ) + ) + streams.append( + torch.randn( + tuple(reference[index].shape), + generator=generator, + dtype=torch.float32, + ) + ) + banks.append(torch.stack(streams, dim=0)) + bank_tensor = torch.stack(banks, dim=0) + return legacy_timesteps.to(reference.device), bank_tensor.to( + device=reference.device, dtype=reference.dtype + ) + + +def _noise_bank_for_records( + reference: Tensor, + record_ids: Optional[Sequence[str]], + seed: int, + stage: Any, + num_experts: int = len(EXPERT_ORDER), +) -> Tensor: + if reference.ndim != 4: + raise ValueError("reference must be a BCHW diffusion state") + if record_ids is not None and len(record_ids) != reference.shape[0]: + raise ValueError("one record id is required per image") + cpu_reference = torch.empty( + tuple(reference.shape), device="cpu", dtype=reference.dtype + ) + shared = _V4_NOISE_FOR_RECORDS(cpu_reference, record_ids, seed, stage) + samples: List[Tensor] = [] + for index in range(reference.shape[0]): + identity = index if record_ids is None else str(record_ids[index]) + streams: List[Tensor] = [shared[index]] + for expert_index in range(num_experts): + streams.append( + v4._cpu_random_tensor( + reference[index].shape, + v4._seed_value( + seed, + "eval-v5", + identity, + stage, + "expert-noise", + expert_index, + ), + reference.dtype, + ) + ) + samples.append(torch.stack(streams, dim=0)) + return torch.stack(samples, dim=0).to(reference.device) + + +def _shared_noise_bank_for_records( + reference: Tensor, + record_ids: Optional[Sequence[str]], + seed: int, + stage: Any, + num_experts: int = len(EXPERT_ORDER), +) -> Tensor: + """Expose legacy v4 noise as a zero-copy shared-only v5 bank.""" + + shared = _V4_NOISE_FOR_RECORDS(reference, record_ids, seed, stage) + return shared.unsqueeze(1).expand( + -1, num_experts + 1, -1, -1, -1 + ) + + +@torch.no_grad() +def sample_gated_restoration( + model: nn.Module, + phase1: FrozenPhase1, + degraded: Tensor, + *, + seed: int, + record_ids: Optional[Sequence[str]] = None, + initial_noise_bank: Optional[Tensor] = None, + amp_enabled: Optional[bool] = None, +) -> Tensor: + """Run the unchanged exact posterior with one fixed soft gate per image.""" + + restorer = v4.unwrap_module(model) + if not isinstance(restorer, Phase2GatedRestorationModule): + raise TypeError("model must wrap Phase2GatedRestorationModule") + use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled) + with torch.cuda.amp.autocast(enabled=use_amp): + padded, original_size = pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + # The condition object, including its gate, is built exactly once and + # reused at every reverse step. + condition = restorer.build_condition(representation) + uy = pixel_unshuffle2(padded) + noise_bank_builder = ( + _shared_noise_bank_for_records + if restorer.noise_mixer.expert_fraction_value == 0.0 + else _noise_bank_for_records + ) + expected_shape = ( + uy.shape[0], + len(EXPERT_ORDER) + 1, + uy.shape[1], + uy.shape[2], + uy.shape[3], + ) + if initial_noise_bank is None: + initial_noise_bank = noise_bank_builder( + uy, record_ids, seed=seed, stage="initial" + ) + elif tuple(initial_noise_bank.shape) != expected_shape: + raise ValueError( + "initial_noise_bank must match [B, shared+experts, C, H, W]" + ) + else: + initial_noise_bank = initial_noise_bank.to( + device=uy.device, dtype=uy.dtype + ) + + initial_noise = restorer.route_noise(initial_noise_bank, condition) + eta_terminal = restorer.schedule.eta[-1].to( + device=uy.device, dtype=uy.dtype + ) + # One fixed per-sample kappa is used for the initial state and every + # posterior step, mirroring the fixed soft gate above. + kappa_override = restorer.effective_kappa(condition) + kappa = restorer.schedule.kappa_factor(kappa_override, uy) + u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise + batch = uy.shape[0] + for step in restorer.schedule.reverse_timesteps(): + timesteps = torch.full( + (batch,), step, device=uy.device, dtype=torch.long + ) + u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition) + mean, variance = restorer.schedule.posterior_mean_variance( + u_t, u0_hat, timesteps, kappa=kappa_override + ) + if step > 1: + bank = noise_bank_builder( + u_t, record_ids, seed=seed, stage=step + ) + routed_noise = restorer.route_noise(bank, condition) + u_t = mean + torch.sqrt(variance) * routed_noise + else: + u_t = mean + restored = pixel_shuffle2(u_t) + height, width = original_size + return restored[..., :height, :width].clamp(0.0, 1.0) + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + while True: + block = handle.read(1024 * 1024) + if not block: + break + digest.update(block) + return digest.hexdigest() + + +def _is_v5_only_key(name: str) -> bool: + return name.startswith( + ( + "conditioner.router.", + "denoiser.noise_type_tokens", + "denoiser.down_experts.", + "denoiser.up_experts.", + "noise_mixer.", + "expert_kappa.", + ) + ) + + +def _configure_trainable_paths( + model: Phase2GatedRestorationModule, *, train_shared_trunk: bool +) -> None: + """Freeze the v4 restoration trunk for the controlled adapter-first arm.""" + + for name, parameter in model.named_parameters(): + parameter.requires_grad_( + bool(train_shared_trunk) or _is_v5_only_key(name) + ) + + +def _validate_adapter_only_output_head( + state: Mapping[str, Any], architecture: Mapping[str, Any], source: str +) -> None: + optimization = architecture.get("optimization") + if not isinstance(optimization, Mapping): + raise ValueError("%s is missing v5 optimization provenance" % source) + shared_trainable = optimization.get("shared_trunk_trainable") + if not isinstance(shared_trainable, bool): + raise ValueError("%s has invalid shared-trunk provenance" % source) + if shared_trainable: + return + output_weight = state.get("denoiser.output_residual.weight") + if ( + not isinstance(output_weight, Tensor) + or not bool(torch.isfinite(output_weight).all()) + or int(torch.count_nonzero(output_weight).item()) == 0 + ): + raise ValueError( + "%s adapter-only state requires a finite nonzero output head" + % source + ) + + +def load_v4_warmstart( + path: Path, + expected_sha256: str, + model: Phase2GatedRestorationModule, + args: argparse.Namespace, + *, + weight_source: str, + expected_train_digest: str, + expected_val_digest: str, +) -> Dict[str, Any]: + """Strictly materialize all shared v4 weights before exposing v5 state.""" + + actual_sha256 = _file_sha256(path) + if actual_sha256.lower() != str(expected_sha256).lower(): + raise ValueError( + "v4 warmstart sha256 mismatch: expected %s, received %s" + % (expected_sha256, actual_sha256) + ) + checkpoint = v4._torch_load(path, map_location="cpu") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("warmstart must be a Phase-2 v4 checkpoint") + contract = checkpoint.get("contract") + if not isinstance(contract, Mapping): + raise ValueError("v4 warmstart is missing its canonical contract") + mirrored_fields = { + "condition_mode": "full", + "phase1_sha256": args.phase1_sha256, + "train_digest": str(expected_train_digest), + "val_digest": str(expected_val_digest), + } + for field, expected in mirrored_fields.items(): + if checkpoint.get(field) != expected or contract.get(field) != expected: + raise ValueError("v4 warmstart %s mismatch" % field) + phase1_metadata = checkpoint.get("phase1_metadata", {}) + if phase1_metadata != contract.get("phase1_metadata"): + raise ValueError("v4 warmstart Phase-1 metadata mirror mismatch") + if list(phase1_metadata.get("branch_order", ())) != list(BRANCH_ORDER): + raise ValueError("v4 warmstart branch_order mismatch") + + architecture = checkpoint.get("architecture", {}) + expected_architecture = _V4_ARCHITECTURE(args) + if contract.get("architecture") != architecture: + raise ValueError("v4 warmstart architecture mirror mismatch") + for field in ("name", "dims", "cond_dim", "state_channels"): + if architecture.get(field) != expected_architecture.get(field): + raise ValueError("v4 warmstart architecture %s mismatch" % field) + expected_schedule = _V4_SCHEDULE_CONFIG(args) + if ( + checkpoint.get("schedule_config") != expected_schedule + or contract.get("schedule") != expected_schedule + ): + raise ValueError("v4 warmstart schedule mismatch") + + if weight_source == "model": + state = checkpoint.get("model_state_dict") + elif weight_source == "ema": + ema_state = checkpoint.get("ema_state_dict") + state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None + else: + raise ValueError("weight_source must be 'model' or 'ema'") + if not isinstance(state, Mapping): + raise ValueError("v4 warmstart is missing the selected state") + if not bool(getattr(args, "train_shared_trunk", False)): + source_step = checkpoint.get("step") + if isinstance(source_step, bool) or not isinstance(source_step, int) or source_step <= 0: + raise ValueError( + "adapter-only warmstart requires a trained v4 checkpoint" + ) + output_weight = state.get("denoiser.output_residual.weight") + if ( + not isinstance(output_weight, Tensor) + or not bool(torch.isfinite(output_weight).all()) + or int(torch.count_nonzero(output_weight).item()) == 0 + ): + raise ValueError( + "adapter-only warmstart requires a finite nonzero v4 output head" + ) + + target_state = model.state_dict() + expected_shared = { + name for name in target_state.keys() if not _is_v5_only_key(name) + } + source_keys = set(state.keys()) + if source_keys != expected_shared: + missing = sorted(expected_shared - source_keys) + unexpected = sorted(source_keys - expected_shared) + raise ValueError( + "v4 warmstart shared key mismatch; missing=%r unexpected=%r" + % (missing, unexpected) + ) + for name in sorted(expected_shared): + value = state[name] + if not isinstance(value, Tensor) or value.shape != target_state[name].shape: + raise ValueError("v4 warmstart tensor shape mismatch: %s" % name) + + result = model.load_state_dict(state, strict=False) + expected_missing = sorted( + name for name in target_state.keys() if _is_v5_only_key(name) + ) + if sorted(result.missing_keys) != expected_missing or result.unexpected_keys: + raise RuntimeError("v4 warmstart loader violated its exact allowlist") + + audit = { + "mapping_version": V4_WARMSTART_MAPPING_VERSION, + "source_checkpoint_sha256": actual_sha256, + "source_schema_version": 4, + "source_step": int(checkpoint.get("step", -1)), + "source_condition_mode": checkpoint.get("condition_mode"), + "weight_source": weight_source, + "source_train_digest": checkpoint.get("train_digest"), + "source_val_digest": checkpoint.get("val_digest"), + "materialized_state_hash": v4.model_state_hash(model), + } + return audit + + +def _neutral_warmstart_audit() -> Dict[str, Any]: + return { + "mapping_version": V4_WARMSTART_MAPPING_VERSION, + "source_checkpoint_sha256": None, + "source_schema_version": None, + "source_step": None, + "source_condition_mode": None, + "weight_source": None, + "source_train_digest": None, + "source_val_digest": None, + "materialized_state_hash": None, + } + + +def _stored_warmstart_audit(path: Path) -> Dict[str, Any]: + checkpoint = v4._torch_load(path, map_location="cpu") + if checkpoint.get("schema_version") != V5_SCHEMA_VERSION: + raise ValueError("v5 state source has the wrong schema_version") + contract = checkpoint.get("contract") + architecture = contract.get("architecture") if isinstance(contract, Mapping) else None + warmstart = architecture.get("warmstart") if isinstance(architecture, Mapping) else None + if not isinstance(warmstart, Mapping): + raise ValueError("v5 state source is missing warmstart audit") + return dict(warmstart) + + +def _parse_expert_kappa_values(value: Optional[str]) -> Tuple[float, ...]: + """Parse and fail-closed validate five comma-separated expert kappas.""" + + if value is None: + raise ValueError("--expert-kappa requires --expert-kappa-values") + parts = [part.strip() for part in str(value).split(",")] + if len(parts) != len(EXPERT_ORDER): + raise ValueError( + "--expert-kappa-values requires %d comma-separated values in " + "EXPERT_ORDER %r" % (len(EXPERT_ORDER), list(EXPERT_ORDER)) + ) + values = [] + for name, part in zip(EXPERT_ORDER, parts): + try: + parsed = float(part) + except ValueError: + raise ValueError("expert kappa for %s is not a number" % name) + if not math.isfinite(parsed) or parsed <= 0.0: + raise ValueError( + "expert kappa for %s must be finite and positive" % name + ) + values.append(parsed) + return tuple(values) + + +def _build_expert_kappa( + args: argparse.Namespace, +) -> Optional[ExpertKappaSchedule]: + if not bool(getattr(args, "expert_kappa", False)): + return None + if args.kappa is None: + raise ValueError("--expert-kappa requires an explicit --kappa") + return ExpertKappaSchedule( + kappa_per_expert=_parse_expert_kappa_values(args.expert_kappa_values), + kappa_global=float(args.kappa), + anneal_microsteps=( + int(args.expert_kappa_anneal_steps) * int(args.grad_accum) + ), + ) + + +def _build_v5_restorer( + args: argparse.Namespace, device: torch.device +) -> Phase2GatedRestorationModule: + schedule = ResidualShiftSchedule( + timesteps=args.timesteps, + eta_end=args.eta_end, + min_noise=args.min_noise, + power=args.power, + kappa=args.kappa, + ) + conditioner = GatedGraphConditionerV5( + cond_dim=args.cond_dim, + stage_dims=args.dims, + router_hidden_dim=args.router_hidden_dim, + router_temperature=args.router_temperature, + router_max_correction=args.router_max_correction, + ) + denoiser = GatedGraphResidualShiftUNetV5( + dims=args.dims, + cond_dim=args.cond_dim, + adapter_rank=args.adapter_rank, + ) + model = Phase2GatedRestorationModule( + conditioner=conditioner, + denoiser=denoiser, + schedule=schedule, + noise_mixer=VariancePreservingNoiseMixer( + num_experts=len(EXPERT_ORDER), + expert_fraction=args.expert_noise_fraction, + ), + condition_mode=args.condition, + router_anchor_weight=args.router_anchor_weight, + router_balance_weight=args.router_balance_weight, + router_correction_weight=args.router_correction_weight, + expert_kappa=_build_expert_kappa(args), + ) + + if args.resume is not None: + audit = _stored_warmstart_audit(args.resume) + elif args.init_checkpoint is not None: + audit = _stored_warmstart_audit(args.init_checkpoint) + elif args.warmstart_v4 is not None: + train_digest = getattr(args, "_v5_train_digest", None) + val_digest = getattr(args, "_v5_val_digest", None) + if not isinstance(train_digest, str) or not isinstance(val_digest, str): + raise RuntimeError("v5 split digests must be resolved before warmstart") + audit = load_v4_warmstart( + args.warmstart_v4, + args.warmstart_v4_sha256, + model, + args, + weight_source=args.warmstart_weight_source, + expected_train_digest=train_digest, + expected_val_digest=val_digest, + ) + else: + audit = _neutral_warmstart_audit() + _configure_trainable_paths( + model, train_shared_trunk=bool(args.train_shared_trunk) + ) + setattr(args, "_v5_warmstart_audit", audit) + return model.to(device) + + +def _v5_architecture(args: argparse.Namespace) -> Dict[str, Any]: + audit = getattr(args, "_v5_warmstart_audit", None) + if not isinstance(audit, Mapping): + raise RuntimeError("v5 warmstart audit must be resolved before architecture") + return { + "name": "gated_graph_resshift_v5", + "version": 5, + "dims": list(args.dims), + "cond_dim": int(args.cond_dim), + "state_channels": 12, + "pixel_unshuffle_factor": 2, + "denoiser_input_channels": 36, + "prediction": "x0", + "expert_order": list(EXPERT_ORDER), + "router": { + "version": ROUTER_VERSION, + "temperature": float(args.router_temperature), + "max_correction": float(args.router_max_correction), + "hidden_dim": int(args.router_hidden_dim), + "balance_scope": "rank_local_microbatch_v1", + }, + "adapters": { + "rank": int(args.adapter_rank), + "placements": ["down0", "down1", "down2", "down3", "up2", "up1", "up0"], + "output_initialization": "zero", + }, + "noise_type_prompt": "zero_initialized_gate_weighted_tokens_v1", + "optimization": { + "shared_trunk_trainable": bool(args.train_shared_trunk), + "new_paths_trainable": True, + }, + "warmstart": dict(audit), + } + + +def _v5_schedule_config(args: argparse.Namespace) -> Dict[str, Any]: + result = dict(_V4_SCHEDULE_CONFIG(args)) + result["noise_routing"] = { + "mixer": NOISE_MIXER_VERSION, + "expert_fraction": float(args.expert_noise_fraction), + "gate_gradient": "stopped", + "schedule_modified": False, + "distribution_semantics": "iid_standard_normal_stochastic_ablation", + } + enabled = bool(getattr(args, "expert_kappa", False)) + result["expert_kappa"] = { + "enabled": enabled, + "version": EXPERT_KAPPA_VERSION if enabled else None, + "values": ( + list(_parse_expert_kappa_values(args.expert_kappa_values)) + if enabled + else None + ), + "anneal_steps": ( + int(args.expert_kappa_anneal_steps) if enabled else None + ), + "gate_gradient": "stopped", + "posterior": "exact_per_sample_kappa", + "modifies_forward_kappa": enabled, + } + return result + + +def _v5_data_plan( + args: argparse.Namespace, + world_size: int, + amp_enabled: Optional[bool] = None, +) -> Dict[str, Any]: + result = dict(_V4_DATA_PLAN(args, world_size, amp_enabled=amp_enabled)) + result["noise_plan"] = NOISE_SEED_VERSION + result["router_balance_topology"] = { + "scope": "rank_local_microbatch_v1", + "world_size": int(world_size), + "local_batch": int(args.batch_size), + } + return result + + +def save_v5_training_checkpoint( + path: Path, + model: nn.Module, + ema: v4.ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + *, + step: int, + contract: v4.CheckpointContract, + history: Sequence[Mapping[str, Any]], + recovery_marker: Optional[Mapping[str, Any]] = None, +) -> None: + payload: Dict[str, Any] = { + "schema_version": V5_SCHEMA_VERSION, + "phase": 2, + "architecture_version": 5, + "step": int(step), + "model_state_dict": v4.unwrap_module(model).state_dict(), + "ema_state_dict": ema.state_dict(), + "optimizer_state_dict": optimizer.state_dict(), + "scheduler_state_dict": scheduler.state_dict(), + "scaler_state_dict": scaler.state_dict(), + "rng_state": v4._rng_state(), + "contract": contract.to_dict(), + "condition_mode": contract.condition_mode, + "phase1_sha256": contract.phase1_sha256, + "phase1_metadata": dict(contract.phase1_metadata), + "train_digest": contract.train_digest, + "val_digest": contract.val_digest, + "schedule_config": dict(contract.schedule), + "architecture": dict(contract.architecture), + "data_plan": dict(contract.data_plan), + "warmstart_audit": dict(contract.architecture.get("warmstart", {})), + "init_model_hash": contract.init_model_hash, + "max_steps": contract.max_steps, + "ema_decay": contract.ema_decay, + "history": [dict(item) for item in history], + } + if recovery_marker is not None: + payload["recovery"] = dict(recovery_marker) + v4._atomic_torch_save(payload, Path(path)) + + +def resume_v5_training_checkpoint( + path: Path, + model: nn.Module, + ema: v4.ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + contract: v4.CheckpointContract, +) -> v4.ResumeState: + checkpoint = v4._torch_load(path, map_location="cpu") + if checkpoint.get("schema_version") != V5_SCHEMA_VERSION or checkpoint.get("phase") != 2: + raise ValueError("not a Phase-2 v5 checkpoint") + v4._validate_contract(checkpoint.get("contract", {}), contract) + for field in ( + "condition_mode", + "phase1_sha256", + "phase1_metadata", + "train_digest", + "val_digest", + "schedule_config", + "architecture", + "data_plan", + "warmstart_audit", + "init_model_hash", + "max_steps", + "ema_decay", + ): + if field == "schedule_config": + expected = contract.to_dict().get("schedule") + elif field == "warmstart_audit": + expected = contract.architecture.get("warmstart", {}) + else: + expected = contract.to_dict().get(field) + if checkpoint.get(field) != expected: + raise ValueError("v5 checkpoint top-level %s mismatch" % field) + state = checkpoint.get("model_state_dict") + if not isinstance(state, Mapping): + raise ValueError("v5 resume checkpoint is missing model state") + _validate_adapter_only_output_head( + state, contract.architecture, "v5 resume checkpoint" + ) + ema_state = checkpoint.get("ema_state_dict") + ema_shadow = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None + if not isinstance(ema_shadow, Mapping): + raise ValueError("v5 resume checkpoint is missing EMA shadow state") + _validate_adapter_only_output_head( + ema_shadow, contract.architecture, "v5 resume EMA" + ) + v4.unwrap_module(model).load_state_dict(state, strict=True) + ema.load_state_dict(ema_state) + optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) + scheduler.load_state_dict(checkpoint["scheduler_state_dict"]) + scaler.load_state_dict(checkpoint["scaler_state_dict"]) + v4._restore_rng_state(checkpoint["rng_state"]) + return v4.ResumeState( + step=int(checkpoint["step"]), + history=[dict(item) for item in checkpoint.get("history", [])], + ) + + +def load_shared_initialization_v5( + path: Path, + model: nn.Module, + *, + target_condition: str, + expected_architecture: Mapping[str, Any], + expected_schedule: Mapping[str, Any], + expected_data_plan: Mapping[str, Any], + expected_phase1_sha256: str, + expected_phase1_metadata: Mapping[str, Any], + expected_train_digest: str, + expected_val_digest: str, + expected_max_steps: int, + expected_ema_decay: float, +) -> str: + checkpoint = v4._torch_load(path, map_location="cpu") + if checkpoint.get("schema_version") != V5_SCHEMA_VERSION or checkpoint.get("phase") != 2: + raise ValueError("initialization must be a Phase-2 v5 checkpoint") + if checkpoint.get("step") != 0: + raise ValueError("shared initialization checkpoint must be at step zero") + source_contract = checkpoint.get("contract") + if not isinstance(source_contract, Mapping): + raise ValueError("initialization checkpoint is missing its contract") + expected_fields: Dict[str, Any] = { + "architecture": dict(expected_architecture), + "schedule": dict(expected_schedule), + "data_plan": dict(expected_data_plan), + "phase1_sha256": str(expected_phase1_sha256), + "phase1_metadata": dict(expected_phase1_metadata), + "train_digest": str(expected_train_digest), + "val_digest": str(expected_val_digest), + "max_steps": int(expected_max_steps), + "ema_decay": float(expected_ema_decay), + } + for field, expected in expected_fields.items(): + if source_contract.get(field) != expected: + raise ValueError("shared v5 initialization %s mismatch" % field) + mirror = "schedule_config" if field == "schedule" else field + if checkpoint.get(mirror) != expected: + raise ValueError("shared v5 top-level %s mismatch" % mirror) + source_condition = source_contract.get("condition_mode") + if source_condition != target_condition and not ( + source_condition == "null" and target_condition == "full" + ): + raise ValueError("shared v5 condition transition is forbidden") + state = checkpoint.get("model_state_dict") + if not isinstance(state, Mapping): + raise ValueError("shared v5 initialization has no model state") + _validate_adapter_only_output_head( + state, expected_architecture, "shared v5 initialization" + ) + target = v4.unwrap_module(model) + # Schedule buffers are scientific configuration rather than trainable + # initialization. Verify their bytes before any state mutates the target. + for name, expected_value in target.schedule.state_dict().items(): + source_value = state.get("schedule." + name) + if not isinstance(source_value, Tensor) or not torch.equal( + source_value.detach().cpu(), expected_value.detach().cpu() + ): + raise ValueError( + "shared v5 initialization schedule buffer mismatch: %s" % name + ) + target.load_state_dict(state, strict=True) + actual_hash = v4.model_state_hash(target) + if ( + source_contract.get("init_model_hash") != actual_hash + or checkpoint.get("init_model_hash") != actual_hash + ): + raise ValueError("shared v5 initialization model hash mismatch") + return actual_hash + + +def build_parser() -> argparse.ArgumentParser: + parser = v4.build_parser() + parser.description = __doc__ + parser.add_argument("--adapter-rank", type=int, default=16) + parser.add_argument("--router-hidden-dim", type=int, default=256) + parser.add_argument("--router-temperature", type=float, default=1.0) + parser.add_argument("--router-max-correction", type=float, default=2.0) + parser.add_argument("--router-anchor-weight", type=float, default=0.01) + parser.add_argument("--router-balance-weight", type=float, default=0.01) + parser.add_argument("--router-correction-weight", type=float, default=0.001) + parser.add_argument( + "--expert-noise-fraction", + type=float, + default=0.0, + help="conditional variance fraction from the independent expert bank", + ) + parser.add_argument( + "--expert-kappa", + action="store_true", + help="scale forward corruption with a gate-weighted per-type kappa", + ) + parser.add_argument( + "--expert-kappa-values", + type=str, + default=None, + help="five comma-separated kappas in EXPERT_ORDER " + "(rain,noise,haze,lowlight,generic)", + ) + parser.add_argument( + "--expert-kappa-anneal-steps", + type=int, + default=2000, + help="optimizer steps to anneal from the global kappa to the " + "gate-weighted per-type kappa (0 disables the anneal)", + ) + parser.add_argument( + "--train-shared-trunk", + action="store_true", + help="also fine-tune v4 shared weights; default trains only v5 paths", + ) + parser.add_argument("--warmstart-v4", type=Path) + parser.add_argument("--warmstart-v4-sha256") + parser.add_argument( + "--warmstart-weight-source", choices=("ema", "model"), default="ema" + ) + return parser + + +def validate_v5_runtime_args(args: argparse.Namespace) -> int: + stop_step = v4.validate_runtime_args(args) + if args.adapter_rank <= 0 or args.router_hidden_dim <= 0: + raise ValueError("adapter and router dimensions must be positive") + for name in ( + "router_temperature", + "router_max_correction", + ): + value = float(getattr(args, name)) + if not math.isfinite(value) or value <= 0.0: + raise ValueError("%s must be finite and positive" % name) + for name in ( + "router_anchor_weight", + "router_balance_weight", + "router_correction_weight", + ): + value = float(getattr(args, name)) + if not math.isfinite(value) or value < 0.0: + raise ValueError("%s must be finite and non-negative" % name) + if not math.isfinite(args.expert_noise_fraction) or not 0.0 <= args.expert_noise_fraction <= 1.0: + raise ValueError("--expert-noise-fraction must lie in [0, 1]") + if bool(getattr(args, "expert_kappa", False)): + _parse_expert_kappa_values(args.expert_kappa_values) + if args.kappa is None: + raise ValueError("--expert-kappa requires an explicit --kappa") + if int(args.expert_kappa_anneal_steps) < 0: + raise ValueError( + "--expert-kappa-anneal-steps must be non-negative" + ) + elif getattr(args, "expert_kappa_values", None) is not None: + raise ValueError( + "--expert-kappa-values is only valid together with --expert-kappa" + ) + has_warmstart_path = args.warmstart_v4 is not None + has_warmstart_sha = args.warmstart_v4_sha256 is not None + if has_warmstart_path != has_warmstart_sha: + raise ValueError("v4 warmstart path and sha256 must be supplied together") + if (args.resume is not None or args.init_checkpoint is not None) and ( + has_warmstart_path or has_warmstart_sha + ): + raise ValueError("v5 resume/init and v4 warmstart are mutually exclusive") + if has_warmstart_sha: + value = str(args.warmstart_v4_sha256).lower() + if len(value) != 64 or any(character not in "0123456789abcdef" for character in value): + raise ValueError("v4 warmstart sha256 must be 64 hexadecimal characters") + has_state_source = ( + args.resume is not None + or args.init_checkpoint is not None + or has_warmstart_path + ) + if ( + not args.calibrate_kappa + and not args.train_shared_trunk + and not has_state_source + ): + raise ValueError( + "adapter-only training requires a v4 warmstart or v5 state source" + ) + return stop_step + + +@contextlib.contextmanager +def _installed_v5_backend(args: argparse.Namespace) -> Iterator[None]: + """Temporarily route the stable v4 runtime through v5 implementations.""" + + def training_plan( + reference: Tensor, + timesteps: int, + seed: int, + global_microstep: int, + rank: int = 0, + sample_seeds: Optional[Sequence[int]] = None, + ) -> Tuple[Tensor, Tensor]: + if float(args.expert_noise_fraction) == 0.0: + timestep_values, shared = _V4_DETERMINISTIC_TRAINING_PLAN( + reference, + timesteps, + seed, + global_microstep, + rank=rank, + sample_seeds=sample_seeds, + ) + shared_bank = shared.unsqueeze(1).expand( + -1, len(EXPERT_ORDER) + 1, -1, -1, -1 + ) + return timestep_values, shared_bank + return deterministic_expert_training_plan( + reference, + timesteps, + seed, + global_microstep, + rank=rank, + sample_seeds=sample_seeds, + ) + + def load_or_create_splits(runtime_args: argparse.Namespace) -> Any: + splits = _V4_LOAD_OR_CREATE_SPLITS(runtime_args) + from src.data.phase2_v4 import split_digest + + setattr(runtime_args, "_v5_train_digest", split_digest(splits.train)) + setattr(runtime_args, "_v5_val_digest", split_digest(splits.val)) + return splits + + replacements = { + "_build_restorer": _build_v5_restorer, + "_load_or_create_splits": load_or_create_splits, + "_architecture": _v5_architecture, + "_schedule_config": _v5_schedule_config, + "_data_plan": _v5_data_plan, + "deterministic_training_plan": training_plan, + "sample_restoration": sample_gated_restoration, + "save_training_checkpoint": save_v5_training_checkpoint, + "resume_training_checkpoint": resume_v5_training_checkpoint, + "load_shared_initialization": load_shared_initialization_v5, + } + originals = {name: getattr(v4, name) for name in replacements} + try: + for name, replacement in replacements.items(): + setattr(v4, name, replacement) + yield + finally: + for name, original in originals.items(): + setattr(v4, name, original) + + +def run(args: argparse.Namespace) -> None: + validate_v5_runtime_args(args) + with _installed_v5_backend(args): + v4.run(args) + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(build_parser().parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/train_phase2_graph_moe_v6.py b/dataset/phase1_noise_20260906/code/train_phase2_graph_moe_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed9eb82197e4ff3421b0e089740005a937b8f7f --- /dev/null +++ b/dataset/phase1_noise_20260906/code/train_phase2_graph_moe_v6.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +"""Phase 2 v6: graph-MoE restoration on the ll_v3 Phase-1 representation. + +Reuses the stable v4 runtime through a scoped backend install (the v5 +pattern). Differences from v5: + +* independent per-node sigmoid activations, strength = a_k * severity_k, + spatial expert gating, 3x3 experts, top-2 execution (graph_moe_v6.py); +* per-node kappa from normalized strengths (A7 machinery); +* the shared trunk FINETUNES (new Phase-1 changes the conditioning + distribution, so a frozen trunk would be mis-conditioned) — use + --learning-rate 5e-5; +* cross-Phase-1 warm start: v4 weights load although the Phase-1 checkpoint + differs; both SHAs are recorded in the audit; +* evaluation samples with --eval-sample-steps (default 1, the measured + strongest mode). +""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +import math +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterator, Mapping, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn + +import train_phase2_graph_resshift_v4 as v4 +from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule +from src.models.restoration.graph_moe_v6 import ( + MOE_V6_VERSION, + NUM_EXPERTS, + MoEConditionBundleV6, + MoEGraphConditionerV6, + MoEGraphResidualShiftUNetV6, + expert_kappa_from_strengths, +) +from src.models.restoration.graph_resshift_v4 import ( + FrozenPhase1, + ResidualShiftSchedule, + pad_to_multiple, + pixel_shuffle2, + pixel_unshuffle2, +) + +V6_WARMSTART_MAPPING_VERSION = "cross_phase1_shared_keys_v1" +DEFAULT_KAPPA_VALUES = "0.09780,0.03836,0.13436,0.41464,0.11608" + +_V4_ARCHITECTURE = v4._architecture +_V4_SCHEDULE_CONFIG = v4._schedule_config +_V4_DATA_PLAN = v4._data_plan + + +def _is_v6_only_key(name: str) -> bool: + return name.startswith( + ( + "conditioner.node_gate.", + "denoiser.strength_tokens", + "denoiser.down_experts.", + "denoiser.up_experts.", + "expert_kappa.", + ) + ) + + +@dataclass +class MoETrainStepResult: + loss: Tensor + reconstruction_loss: Tensor + gate_loss: Tensor + u0_prediction: Tensor + u0_target: Tensor + u_t: Tensor + kappa: Tensor + + +class Phase2MoEV6Module(nn.Module): + """Trainable v6 module; the frozen Phase-1 encoder stays outside.""" + + def __init__( + self, + conditioner: MoEGraphConditionerV6, + denoiser: MoEGraphResidualShiftUNetV6, + schedule: ResidualShiftSchedule, + expert_kappa: ExpertKappaSchedule, + condition_mode: str, + *, + gate_anchor_weight: float = 0.05, + gate_correction_weight: float = 0.001, + ) -> None: + super().__init__() + if condition_mode not in ("full", "null"): + raise ValueError("condition_mode must be 'full' or 'null'") + self.conditioner = conditioner + self.denoiser = denoiser + self.schedule = schedule + self.expert_kappa = expert_kappa + self.condition_mode = condition_mode + self.gate_anchor_weight = float(gate_anchor_weight) + self.gate_correction_weight = float(gate_correction_weight) + self.eval_sample_steps = 1 + + def build_condition(self, representation: Any) -> MoEConditionBundleV6: + return self.conditioner(representation, mode=self.condition_mode) + + def predict_x0( + self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition + ) -> Tensor: + return self.denoiser(u_t, u_y, timesteps, condition) + + def effective_kappa(self, condition: MoEConditionBundleV6) -> Tensor: + return expert_kappa_from_strengths( + self.expert_kappa, condition.gate, condition.route_active + ) + + def forward( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> Tensor: + return self.training_loss( + clean, degraded, representation, timesteps, noise=noise + ).loss + + def training_loss( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> MoETrainStepResult: + u0 = pixel_unshuffle2(clean) + uy = pixel_unshuffle2(degraded) + condition = self.build_condition(representation) + kappa = self.effective_kappa(condition) + u_t = self.schedule.q_sample(u0, uy, timesteps, noise=noise, kappa=kappa) + prediction = self.predict_x0(u_t, uy, timesteps, condition) + reconstruction = (prediction.float() - u0.float()).square().mean() + gate_loss = ( + self.gate_anchor_weight * condition.gate.anchor_loss.float() + + self.gate_correction_weight + * condition.gate.correction_loss.float() + ) + if self.expert_kappa is not None and self.training: + self.expert_kappa.advance() + return MoETrainStepResult( + loss=reconstruction + gate_loss, + reconstruction_loss=reconstruction, + gate_loss=gate_loss, + u0_prediction=prediction, + u0_target=u0, + u_t=u_t, + kappa=kappa.detach(), + ) + + +@torch.no_grad() +def sample_moe_restoration( + model: nn.Module, + phase1: FrozenPhase1, + degraded: Tensor, + *, + seed: int, + record_ids: Optional[Sequence[str]] = None, + initial_noise: Optional[Tensor] = None, + amp_enabled: Optional[bool] = None, +) -> Tensor: + """One-step x0 by default; the exact posterior chain when configured.""" + + restorer = v4.unwrap_module(model) + if not isinstance(restorer, Phase2MoEV6Module): + raise TypeError("model must wrap Phase2MoEV6Module") + steps = int(getattr(restorer, "eval_sample_steps", 1)) + use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled) + with torch.cuda.amp.autocast(enabled=use_amp): + padded, size = pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + condition = restorer.build_condition(representation) + uy = pixel_unshuffle2(padded) + if initial_noise is None: + initial_noise = v4._noise_for_records( + uy, list(record_ids) if record_ids else None, + seed=seed, stage="initial", + ) + kappa_vector = restorer.effective_kappa(condition) + kappa = restorer.schedule.kappa_factor(kappa_vector, uy) + eta_terminal = restorer.schedule.eta[-1].to(uy.device, uy.dtype) + u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise + batch = uy.shape[0] + if steps <= 1: + timesteps = torch.full( + (batch,), restorer.schedule.timesteps, + device=uy.device, dtype=torch.long, + ) + u_t = restorer.predict_x0(u_t, uy, timesteps, condition) + else: + for step in restorer.schedule.reverse_timesteps(): + timesteps = torch.full( + (batch,), step, device=uy.device, dtype=torch.long + ) + u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition) + mean, variance = restorer.schedule.posterior_mean_variance( + u_t, u0_hat, timesteps, kappa=kappa_vector + ) + if step > 1: + noise = v4._noise_for_records( + u_t, list(record_ids) if record_ids else None, + seed=seed, stage=step, + ) + u_t = mean + torch.sqrt(variance) * noise + else: + u_t = mean + restored = pixel_shuffle2(u_t) + height, width = size + return restored[..., :height, :width].clamp(0.0, 1.0) + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_v4_warmstart_moe( + path: Path, + expected_sha256: str, + model: Phase2MoEV6Module, + *, + weight_source: str, +) -> Dict[str, Any]: + """Load shared v4 trunk weights across a deliberate Phase-1 swap. + + Unlike the v5 loader this does NOT require the Phase-1 SHA to match: + v6 exists to move to the ll_v3 representation, and the trunk finetunes + to the new conditioning. Both facts are recorded in the audit. + """ + + actual = _file_sha256(path) + if actual.lower() != str(expected_sha256).lower(): + raise ValueError("v4 warmstart sha256 mismatch") + checkpoint = v4._torch_load(Path(path), map_location="cpu") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("warmstart must be a Phase-2 v4 checkpoint") + if checkpoint.get("condition_mode") != "full": + raise ValueError("v6 warmstart requires a full-condition v4 run") + if weight_source == "model": + state = checkpoint.get("model_state_dict") + elif weight_source == "ema": + ema_state = checkpoint.get("ema_state_dict") + state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None + else: + raise ValueError("weight_source must be 'model' or 'ema'") + if not isinstance(state, Mapping): + raise ValueError("v4 warmstart is missing the selected state") + + target = model.state_dict() + expected_shared = { + name for name in target if not _is_v6_only_key(name) + } + source_keys = set(state.keys()) + if source_keys != expected_shared: + missing = sorted(expected_shared - source_keys) + unexpected = sorted(source_keys - expected_shared) + raise ValueError( + "v4 warmstart shared key mismatch; missing=%r unexpected=%r" + % (missing[:8], unexpected[:8]) + ) + result = model.load_state_dict(state, strict=False) + expected_missing = sorted(name for name in target if _is_v6_only_key(name)) + if sorted(result.missing_keys) != expected_missing or result.unexpected_keys: + raise RuntimeError("v6 warmstart loader violated its allowlist") + return { + "mapping_version": V6_WARMSTART_MAPPING_VERSION, + "source_checkpoint_sha256": actual, + "source_step": int(checkpoint.get("step", -1)), + "weight_source": weight_source, + "source_phase1_sha256": checkpoint.get("phase1_sha256"), + "cross_phase1": True, + "materialized_state_hash": v4.model_state_hash(model), + } + + +def _parse_kappa_values(value: str) -> Tuple[float, ...]: + parts = [float(part) for part in str(value).split(",")] + if len(parts) != NUM_EXPERTS or any( + not math.isfinite(p) or p <= 0 for p in parts + ): + raise ValueError( + "--expert-kappa-values requires %d positive floats" % NUM_EXPERTS + ) + return tuple(parts) + + +def _build_moe_restorer( + args: argparse.Namespace, device: torch.device +) -> Phase2MoEV6Module: + schedule = ResidualShiftSchedule( + timesteps=args.timesteps, eta_end=args.eta_end, + min_noise=args.min_noise, power=args.power, kappa=args.kappa, + ) + conditioner = MoEGraphConditionerV6( + cond_dim=args.cond_dim, stage_dims=args.dims, + gate_hidden_dim=args.gate_hidden_dim, + gate_max_correction=args.gate_max_correction, + ) + denoiser = MoEGraphResidualShiftUNetV6( + dims=args.dims, cond_dim=args.cond_dim, expert_rank=args.expert_rank, + ) + expert_kappa = ExpertKappaSchedule( + kappa_per_expert=_parse_kappa_values(args.expert_kappa_values), + kappa_global=float(args.kappa), + anneal_microsteps=int(args.expert_kappa_anneal_steps) + * int(args.grad_accum), + ) + model = Phase2MoEV6Module( + conditioner=conditioner, denoiser=denoiser, schedule=schedule, + expert_kappa=expert_kappa, condition_mode=args.condition, + gate_anchor_weight=args.gate_anchor_weight, + gate_correction_weight=args.gate_correction_weight, + ) + model.eval_sample_steps = int(args.eval_sample_steps) + if args.resume is None and args.init_checkpoint is None: + if args.warmstart_v4 is None: + raise ValueError("v6 requires --warmstart-v4 (or resume/init)") + audit = load_v4_warmstart_moe( + args.warmstart_v4, args.warmstart_v4_sha256, model, + weight_source=args.warmstart_weight_source, + ) + else: + # Resume/init must reproduce the stored contract exactly, so the + # warm-start audit is read back from the checkpoint being resumed. + source = args.resume if args.resume is not None else args.init_checkpoint + stored = v4._torch_load(Path(source), map_location="cpu") + architecture = stored.get("architecture") if isinstance(stored, Mapping) else None + audit = ( + dict(architecture.get("warmstart", {})) + if isinstance(architecture, Mapping) + else {"mapping_version": "resumed_state"} + ) + del stored + setattr(args, "_v6_warmstart_audit", audit) + # Curriculum stage 1: only the v6 control paths learn while the trunk + # stays at its v4 warm start (run 1 showed that a free trunk under + # full gating from step 0 collapses lowlight/haze). + if bool(getattr(args, "freeze_shared_trunk", False)): + for name, parameter in model.named_parameters(): + parameter.requires_grad_(_is_v6_only_key(name)) + return model.to(device) + + +def _moe_architecture(args: argparse.Namespace) -> Dict[str, Any]: + audit = getattr(args, "_v6_warmstart_audit", {}) + return { + "name": "graph_moe_v6", + "version": 6, + "moe": { + "mechanism": MOE_V6_VERSION, + "expert_rank": int(args.expert_rank), + "gate_hidden_dim": int(args.gate_hidden_dim), + "gate_max_correction": float(args.gate_max_correction), + "activation": "independent_sigmoid_strength_severity", + "execution": "top2", + "spatial_gating": "phase1_maps_blend", + }, + "dims": list(args.dims), + "cond_dim": int(args.cond_dim), + "state_channels": 12, + "prediction": "x0", + "eval_sample_steps": int(args.eval_sample_steps), + "trunk": "v4_warmstart_curriculum", + "warmstart": dict(audit), + } + + +def _moe_schedule_config(args: argparse.Namespace) -> Dict[str, Any]: + result = dict(_V4_SCHEDULE_CONFIG(args)) + result["expert_kappa"] = { + "enabled": True, + "values": list(_parse_kappa_values(args.expert_kappa_values)), + "anneal_steps": int(args.expert_kappa_anneal_steps), + "source": "normalized_node_strengths", + "posterior": "exact_per_sample_kappa", + } + return result + + +def _moe_data_plan( + args: argparse.Namespace, world_size: int, amp_enabled=None +) -> Dict[str, Any]: + result = dict(_V4_DATA_PLAN(args, world_size, amp_enabled=amp_enabled)) + result["noise_plan"] = "v4_single_stream" + return result + + +def build_parser() -> argparse.ArgumentParser: + parser = v4.build_parser() + parser.description = __doc__ + parser.add_argument("--expert-rank", type=int, default=16) + parser.add_argument("--gate-hidden-dim", type=int, default=128) + parser.add_argument("--gate-max-correction", type=float, default=1.0) + parser.add_argument("--gate-anchor-weight", type=float, default=0.05) + parser.add_argument("--gate-correction-weight", type=float, default=0.001) + parser.add_argument( + "--expert-kappa-values", type=str, default=DEFAULT_KAPPA_VALUES + ) + parser.add_argument("--expert-kappa-anneal-steps", type=int, default=1000) + parser.add_argument("--eval-sample-steps", type=int, default=1) + parser.add_argument( + "--freeze-shared-trunk", + action="store_true", + help="curriculum stage 1: train only the v6 control paths", + ) + parser.add_argument("--warmstart-v4", type=Path) + parser.add_argument("--warmstart-v4-sha256") + parser.add_argument( + "--warmstart-weight-source", choices=("ema", "model"), default="ema" + ) + return parser + + +@contextlib.contextmanager +def _installed_v6_backend(args: argparse.Namespace) -> Iterator[None]: + replacements = { + "_build_restorer": _build_moe_restorer, + "_architecture": _moe_architecture, + "_schedule_config": _moe_schedule_config, + "_data_plan": _moe_data_plan, + "sample_restoration": sample_moe_restoration, + } + originals = {name: getattr(v4, name) for name in replacements} + try: + for name, replacement in replacements.items(): + setattr(v4, name, replacement) + yield + finally: + for name, original in originals.items(): + setattr(v4, name, original) + + +def run(args: argparse.Namespace) -> None: + v4.validate_runtime_args(args) + _parse_kappa_values(args.expert_kappa_values) + if args.eval_sample_steps < 1: + raise ValueError("--eval-sample-steps must be >= 1") + has_path = args.warmstart_v4 is not None + has_sha = args.warmstart_v4_sha256 is not None + if has_path != has_sha: + raise ValueError("warmstart path and sha256 go together") + with _installed_v6_backend(args): + v4.run(args) + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(build_parser().parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/train_phase2_graph_resshift_v4.py b/dataset/phase1_noise_20260906/code/train_phase2_graph_resshift_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..eb1135beebd7543b81e41936165198f0882d37b0 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/train_phase2_graph_resshift_v4.py @@ -0,0 +1,2119 @@ +#!/usr/bin/env python3 +"""Train and evaluate graph-conditioned residual-shift restoration (Phase 2 v4). + +Phase 1 is an inference-only representation learner. This entrypoint never +feeds it clean targets, degradation labels, or any other oracle information. +The ``full`` and ``null`` arms instantiate exactly the same trainable module; +the latter masks the continuous graph condition after the conditioner so the +representation-utility gate is parameter matched. + +The implementation intentionally targets Python 3.9 and PyTorch 1.10 because +those are the versions installed on the training host. +""" + +from __future__ import annotations + +import argparse +import contextlib +import dataclasses +import hashlib +import json +import math +import os +import random +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple + +import numpy as np +import torch +from torch import Tensor, nn +import torch.distributed as dist +import torch.nn.functional as F +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from src.models.restoration.graph_resshift_v4 import ( + BRANCH_ORDER, + PHASE1_AGGREGATION_VERSION, + PHASE1_SCHEMA_VERSION, + FrozenPhase1, + GraphConditionerV4, + GraphResidualShiftUNetV4, + ResidualShiftSchedule, + load_phase1_checkpoint, + pad_to_multiple, + pixel_shuffle2, + pixel_unshuffle2, +) + + +DOMAINS: Tuple[str, ...] = tuple(BRANCH_ORDER) + + +@dataclass +class TrainStepResult: + """The exact x0 objective and useful detached diagnostics.""" + + loss: Tensor + u0_prediction: Tensor + u0_target: Tensor + u_t: Tensor + + +class Phase2RestorationModule(nn.Module): + """Trainable Phase-2 module; the frozen Phase-1 encoder is deliberately absent.""" + + def __init__( + self, + conditioner: GraphConditionerV4, + denoiser: GraphResidualShiftUNetV4, + schedule: ResidualShiftSchedule, + condition_mode: str, + ) -> None: + super().__init__() + if condition_mode not in ("full", "null"): + raise ValueError("condition_mode must be 'full' or 'null'") + self.conditioner = conditioner + self.denoiser = denoiser + self.schedule = schedule + self.condition_mode = condition_mode + + def build_condition(self, representation: Any) -> Any: + return self.conditioner(representation, mode=self.condition_mode) + + def predict_x0( + self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition: Any + ) -> Tensor: + return self.denoiser(u_t, u_y, timesteps, condition) + + def forward( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> Tensor: + """DDP-visible training forward. + + Keeping the objective behind ``forward`` is important: calling a + method on ``module`` directly would bypass DistributedDataParallel's + reducer preparation and make ``no_sync`` accumulation incorrect. + """ + + return self.training_loss( + clean, degraded, representation, timesteps, noise=noise + ).loss + + def training_loss( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> TrainStepResult: + """Uniform-timestep x0 prediction with one unweighted FP32 MSE.""" + + u0 = pixel_unshuffle2(clean) + uy = pixel_unshuffle2(degraded) + u_t = self.schedule.q_sample(u0, uy, timesteps, noise=noise) + prediction = self.predict_x0( + u_t, uy, timesteps, self.build_condition(representation) + ) + # Force the reduction to FP32 even when the U-Net runs under autocast. + loss = (prediction.float() - u0.float()).square().mean() + return TrainStepResult(loss, prediction, u0, u_t) + + +def apply_identity_pairs( + degraded: Tensor, clean: Tensor, probability: float +) -> Tensor: + """Replace a random subset of degraded inputs with their clean targets. + + Teaches the fixed point f(x) = x explicitly (the "do nothing" behaviour + missing from a training distribution that only contains degraded + inputs). Applied BEFORE the frozen Phase-1 call so the representation + sees the clean image too. + """ + + if probability <= 0.0: + return degraded + mask = torch.rand(clean.shape[0], device=clean.device) < float(probability) + if not bool(mask.any()): + return degraded + return torch.where(mask.view(-1, 1, 1, 1), clean, degraded) + + +def identity_pair_mask(batch_size: int, probability: float, device) -> Tensor: + if probability <= 0.0: + return torch.zeros(batch_size, dtype=torch.bool, device=device) + return torch.rand(batch_size, device=device) < float(probability) + + +def exposure_diverse_identity( + clean: Tensor, + full_clean: Optional[Tensor], + identity: Tensor, + generator: torch.Generator, + jitter: float = 0.0, + extra_crop: Optional[Tensor] = None, + extra_full: Optional[Tensor] = None, + extra_prob: float = 0.0, +) -> Tuple[Tensor, Optional[Tensor]]: + """Make identity pairs exposure- and content-diverse (v8). + + The trunk learned an exposure prior ("dark -> brighten, mid -> pull to + the training mean") because identity pairs only ever showed the bright + clean images of the four training domains (scene008 diagnosis: 9 of 12 + lost dB were a global tone shift). For the identity rows this (a) + optionally swaps the clean image for one from an external clean pool and + (b) multiplies input AND target by a random global gain exp(U(-j, j)), + clamped to [0, 1]. Returns the new (clean, full_clean); the caller copies + the identity rows of clean into degraded afterwards, so the pair stays + exactly (x, x). Deterministic through ``generator``. + """ + + if not bool(identity.any()): + return clean, full_clean + batch = clean.shape[0] + new_clean, new_full = clean.clone(), (full_clean.clone() if full_clean is not None else None) + if extra_crop is not None and extra_prob > 0.0: + swap = (torch.rand(batch, generator=generator) < float(extra_prob)).to(clean.device) & identity + if bool(swap.any()): + source = extra_crop[: batch].to(clean.device, clean.dtype) + if source.shape[0] < batch: + repeat = int(math.ceil(batch / source.shape[0])) + source = source.repeat(repeat, 1, 1, 1)[:batch] + new_clean = torch.where(swap.view(-1, 1, 1, 1), source, new_clean) + if new_full is not None: + full_source = (extra_full if extra_full is not None else extra_crop)[: batch] + full_source = full_source.to(clean.device, new_full.dtype) + if full_source.shape[0] < batch: + repeat = int(math.ceil(batch / full_source.shape[0])) + full_source = full_source.repeat(repeat, 1, 1, 1)[:batch] + if full_source.shape[-2:] != new_full.shape[-2:]: + full_source = F.interpolate(full_source, size=new_full.shape[-2:], mode="area") + new_full = torch.where(swap.view(-1, 1, 1, 1), full_source, new_full) + if jitter > 0.0: + log_gain = (torch.rand(batch, generator=generator) * 2.0 - 1.0) * float(jitter) + gain = log_gain.exp().to(clean.device, clean.dtype).view(-1, 1, 1, 1) + gain = torch.where(identity.view(-1, 1, 1, 1), gain, torch.ones_like(gain)) + new_clean = (new_clean * gain).clamp(0.0, 1.0) + if new_full is not None: + new_full = (new_full * gain.to(new_full.dtype)).clamp(0.0, 1.0) + return new_clean, new_full + + +def synthetic_noise_pairs( + degraded: Tensor, + clean: Tensor, + probability: float, + generator: torch.Generator, + full_degraded: Optional[Tensor] = None, + full_clean: Optional[Tensor] = None, +) -> Tuple[Tensor, Optional[Tensor], Tensor]: + """Clean-image prior for the trunk: turn a random subset of pairs into + (clean + heteroscedastic Poisson-Gaussian noise, clean). + + This is what the two-stage refiner had (pretraining on clean + light + corruption over every clean image) and the unified trunk never got. + The same noise parameters are applied to the whole-frame view so the + global context stays consistent with the crop. Deterministic per call + through ``generator``. Returns (degraded, full_degraded, mask).""" + + batch = clean.shape[0] + if probability <= 0.0: + return degraded, full_degraded, torch.zeros(batch, dtype=torch.bool, device=clean.device) + draw = torch.rand(batch, generator=generator) + mask = (draw < float(probability)).to(clean.device) + if not bool(mask.any()): + return degraded, full_degraded, mask + params = torch.rand(batch, 2, generator=generator) + a = (0.0005 + 0.0195 * params[:, 0]).to(clean.device).view(-1, 1, 1, 1) + b = (0.0001 + 0.0049 * params[:, 1]).to(clean.device).view(-1, 1, 1, 1) + eps = torch.randn(clean.shape, generator=generator).to(clean.device) + noisy = (clean + (a * clean.clamp(0, 1) + b).sqrt() * eps).clamp(0.0, 1.0) + new_degraded = torch.where(mask.view(-1, 1, 1, 1), noisy.to(degraded.dtype), degraded) + new_full = full_degraded + if full_degraded is not None and full_clean is not None: + eps_full = torch.randn(full_clean.shape, generator=generator).to(clean.device) + noisy_full = (full_clean + (a * full_clean.clamp(0, 1) + b).sqrt() * eps_full).clamp(0.0, 1.0) + new_full = torch.where(mask.view(-1, 1, 1, 1), noisy_full.to(full_degraded.dtype), full_degraded) + return new_degraded, new_full, mask + + +def extra_clean_files(spec: Any, balance: bool = True) -> List[Path]: + """Image files of one or more clean pools; ``spec`` is a path or a + comma-separated list of paths (v10: Snow100K gt + SIDD GT + LOL GT so + identity pairs cover dark, textured, real-camera clean images). + + ``balance`` repeats the entries of every smaller root until each root + has as many entries as the largest one, so a 121-image SIDD pool is + drawn as often as a 50k-image Snow100K pool (crops are re-randomised per + entry index, so repeated files still yield different crops). + """ + + from src.data.folder_crops import list_image_files + + roots = [part.strip() for part in str(spec).split(",") if part.strip()] + if not roots: + raise ValueError("extra clean pool needs at least one folder") + per_root = [list_image_files(Path(root)) for root in roots] + if any(not files for files in per_root): + raise ValueError("extra clean pool is empty: %s" % spec) + if balance and len(per_root) > 1: + target = max(len(files) for files in per_root) + per_root = [ + (files * int(math.ceil(target / len(files))))[:target] for files in per_root + ] + files: List[Path] = [] + for group in per_root: + files.extend(group) + return files + + +def unwrap_module(module: nn.Module) -> nn.Module: + return module.module if isinstance(module, DistributedDataParallel) else module + + +def _seed_value(seed: int, *parts: Any) -> int: + payload = "\0".join([str(int(seed))] + [str(part) for part in parts]) + digest = hashlib.sha256(payload.encode("utf-8")).digest() + # torch.Generator.manual_seed accepts a signed 64-bit-safe positive value. + return int.from_bytes(digest[:8], "little") % (2 ** 63 - 1) + + +def _cpu_random_tensor(shape: Sequence[int], seed: int, dtype: torch.dtype) -> Tensor: + generator = torch.Generator(device="cpu") + generator.manual_seed(int(seed)) + # CPU float16 normal generation was incomplete in older PyTorch versions. + return torch.randn(tuple(shape), generator=generator, dtype=torch.float32).to(dtype) + + +def deterministic_training_plan( + reference: Tensor, + timesteps: int, + seed: int, + global_microstep: int, + rank: int = 0, + sample_seeds: Optional[Sequence[int]] = None, +) -> Tuple[Tensor, Tensor]: + """Return a reproducible t/noise plan independent of global RNG state. + + ``sample_seeds`` are emitted by the global balanced sampler before its DDP + shard. Using them makes the union of two local rank plans exactly equal to + the corresponding single-GPU global micro-batch plan. + """ + + if timesteps < 1: + raise ValueError("timesteps must be positive") + if sample_seeds is not None: + if len(sample_seeds) != reference.shape[0]: + raise ValueError("one sample seed is required per training image") + timestep_values: List[Tensor] = [] + noises: List[Tensor] = [] + for index, sample_seed in enumerate(sample_seeds): + generator = torch.Generator(device="cpu") + generator.manual_seed( + _seed_value(seed, "train", global_microstep, int(sample_seed)) + ) + timestep_values.append( + torch.randint(1, timesteps + 1, (1,), generator=generator) + ) + noises.append( + torch.randn( + tuple(reference[index].shape), + generator=generator, + dtype=torch.float32, + ) + ) + t = torch.cat(timestep_values, dim=0).long() + noise = torch.stack(noises, dim=0) + return t.to(reference.device), noise.to( + reference.device, dtype=reference.dtype + ) + plan_seed = _seed_value(seed, "train", global_microstep, rank) + generator = torch.Generator(device="cpu") + generator.manual_seed(plan_seed) + t = torch.randint( + 1, timesteps + 1, (reference.shape[0],), generator=generator, dtype=torch.long + ) + noise = torch.randn(tuple(reference.shape), generator=generator, dtype=torch.float32) + return t.to(reference.device), noise.to(reference.device, dtype=reference.dtype) + + +def _noise_for_records( + reference: Tensor, + record_ids: Optional[Sequence[str]], + seed: int, + stage: Any, +) -> Tensor: + if record_ids is None: + return _cpu_random_tensor( + reference.shape, _seed_value(seed, "eval", stage), reference.dtype + ).to(reference.device) + if len(record_ids) != reference.shape[0]: + raise ValueError("one record id is required per image") + samples = [] + for index, record_id in enumerate(record_ids): + samples.append( + _cpu_random_tensor( + reference[index].shape, + _seed_value(seed, "eval", str(record_id), stage), + reference.dtype, + ) + ) + return torch.stack(samples, dim=0).to(reference.device) + + +@torch.no_grad() +def sample_restoration( + model: nn.Module, + phase1: FrozenPhase1, + degraded: Tensor, + *, + seed: int, + record_ids: Optional[Sequence[str]] = None, + initial_noise: Optional[Tensor] = None, + amp_enabled: Optional[bool] = None, +) -> Tensor: + """Run the exact ``T ... 1`` posterior and extract Phase-1 only once.""" + + restorer = unwrap_module(model) + if not isinstance(restorer, Phase2RestorationModule): + raise TypeError("model must wrap Phase2RestorationModule") + use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled) + with torch.cuda.amp.autocast(enabled=use_amp): + padded, original_size = pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + condition = restorer.build_condition(representation) + uy = pixel_unshuffle2(padded) + if initial_noise is None: + initial_noise = _noise_for_records( + uy, record_ids, seed=seed, stage="initial" + ) + elif initial_noise.shape != uy.shape: + raise ValueError("initial_noise must match the padded pixel-unshuffle state") + else: + initial_noise = initial_noise.to(device=uy.device, dtype=uy.dtype) + + eta_terminal = restorer.schedule.eta[-1].to(device=uy.device, dtype=uy.dtype) + kappa = restorer.schedule.kappa.to(device=uy.device, dtype=uy.dtype) + u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise + batch = uy.shape[0] + for step in restorer.schedule.reverse_timesteps(): + t = torch.full((batch,), step, device=uy.device, dtype=torch.long) + u0_hat = restorer.predict_x0(u_t, uy, t, condition) + mean, variance = restorer.schedule.posterior_mean_variance( + u_t, u0_hat, t + ) + if step > 1: + noise = _noise_for_records(u_t, record_ids, seed=seed, stage=step) + u_t = mean + torch.sqrt(variance) * noise + else: + # q(u_0 | u_1, u0_hat) is deterministic; never inject t=1 noise. + u_t = mean + restored = pixel_shuffle2(u_t) + height, width = original_size + return restored[..., :height, :width].clamp(0.0, 1.0) + + +def rgb_psnr_per_image(prediction: Tensor, target: Tensor) -> Tensor: + """Per-image RGB PSNR on [0, 1] values (no batch averaging).""" + + if prediction.shape != target.shape or prediction.ndim != 4: + raise ValueError("PSNR inputs must have the same BCHW shape") + mse = (prediction.float() - target.float()).square().flatten(1).mean(1) + return -10.0 * torch.log10(mse.clamp_min(torch.finfo(torch.float32).tiny)) + + +def _gaussian_window( + window_size: int, sigma: float, channels: int, device: torch.device +) -> Tensor: + coordinates = torch.arange(window_size, device=device, dtype=torch.float32) + coordinates = coordinates - float(window_size - 1) / 2.0 + kernel = torch.exp(-(coordinates.square()) / (2.0 * sigma * sigma)) + kernel = kernel / kernel.sum() + window = torch.outer(kernel, kernel) + return window.reshape(1, 1, window_size, window_size).repeat(channels, 1, 1, 1) + + +def rgb_ssim_per_image( + prediction: Tensor, + target: Tensor, + window_size: int = 11, + sigma: float = 1.5, +) -> Tensor: + """Windowed Gaussian RGB SSIM, reduced separately for every image.""" + + if prediction.shape != target.shape or prediction.ndim != 4: + raise ValueError("SSIM inputs must have the same BCHW shape") + if window_size <= 0 or window_size % 2 == 0: + raise ValueError("window_size must be a positive odd integer") + x, y = prediction.float(), target.float() + channels = x.shape[1] + window = _gaussian_window(window_size, sigma, channels, x.device) + padding = window_size // 2 + pad_mode = ( + "reflect" + if x.shape[-2] > padding and x.shape[-1] > padding + else "replicate" + ) + x_pad = F.pad(x, (padding, padding, padding, padding), mode=pad_mode) + y_pad = F.pad(y, (padding, padding, padding, padding), mode=pad_mode) + mu_x = F.conv2d(x_pad, window, groups=channels) + mu_y = F.conv2d(y_pad, window, groups=channels) + mu_x_sq, mu_y_sq, mu_xy = mu_x.square(), mu_y.square(), mu_x * mu_y + sigma_x = F.conv2d(x_pad * x_pad, window, groups=channels) - mu_x_sq + sigma_y = F.conv2d(y_pad * y_pad, window, groups=channels) - mu_y_sq + sigma_xy = F.conv2d(x_pad * y_pad, window, groups=channels) - mu_xy + c1, c2 = 0.01 ** 2, 0.03 ** 2 + numerator = (2.0 * mu_xy + c1) * (2.0 * sigma_xy + c2) + denominator = (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + return (numerator / denominator.clamp_min(1e-12)).flatten(1).mean(1) + + +class DomainMetricAccumulator: + """Domain-first metric reduction used for model selection.""" + + def __init__(self, domains: Sequence[str] = DOMAINS) -> None: + self.domains = tuple(domains) + self.values: Dict[str, Dict[str, List[float]]] = { + domain: {"psnr": [], "ssim": []} for domain in self.domains + } + + def update(self, domain: str, psnr: float, ssim: float) -> None: + if domain not in self.values: + raise ValueError("unknown evaluation domain %r" % domain) + self.values[domain]["psnr"].append(float(psnr)) + self.values[domain]["ssim"].append(float(ssim)) + + def compute(self) -> Dict[str, Any]: + missing = [domain for domain in self.domains if not self.values[domain]["psnr"]] + if missing: + raise ValueError("evaluation has no images for domains %r" % missing) + per_domain: Dict[str, Dict[str, Any]] = {} + for domain in self.domains: + values = self.values[domain] + per_domain[domain] = { + "psnr": float(np.mean(values["psnr"])), + "ssim": float(np.mean(values["ssim"])), + "count": len(values["psnr"]), + } + macro_psnr = float(np.mean([per_domain[d]["psnr"] for d in self.domains])) + macro_ssim = float(np.mean([per_domain[d]["ssim"] for d in self.domains])) + all_psnr = [value for d in self.domains for value in self.values[d]["psnr"]] + all_ssim = [value for d in self.domains for value in self.values[d]["ssim"]] + return { + "per_domain": per_domain, + "macro_psnr": macro_psnr, + "macro_ssim": macro_ssim, + "image_weighted_psnr": float(np.mean(all_psnr)), + "image_weighted_ssim": float(np.mean(all_ssim)), + } + + +@torch.no_grad() +def evaluate( + model: nn.Module, + phase1: FrozenPhase1, + loader: Iterable[Mapping[str, Any]], + device: torch.device, + seed: int, + amp_enabled: Optional[bool] = None, +) -> Dict[str, Any]: + """Evaluate restoration and the degraded-input baseline in fixed order.""" + + model.eval() + phase1.eval() + restored_metrics = DomainMetricAccumulator() + baseline_metrics = DomainMetricAccumulator() + for batch in loader: + degraded = batch["degraded"].to(device, non_blocking=True) + clean = batch["clean"].to(device, non_blocking=True) + domains = [str(value) for value in batch["degradation"]] + record_ids = [str(value) for value in batch["record_id"]] + extra: Dict[str, Any] = {} + if "full_degraded" in batch and getattr(sample_restoration, "accepts_full_frame", False): + extra["full_degraded"] = batch["full_degraded"].to(device, non_blocking=True) + restored = sample_restoration( + model, + phase1, + degraded, + seed=seed, + record_ids=record_ids, + amp_enabled=amp_enabled, + **extra, + ) + psnr = rgb_psnr_per_image(restored, clean).cpu().tolist() + ssim = rgb_ssim_per_image(restored, clean).cpu().tolist() + base_psnr = rgb_psnr_per_image(degraded, clean).cpu().tolist() + base_ssim = rgb_ssim_per_image(degraded, clean).cpu().tolist() + for index, domain in enumerate(domains): + restored_metrics.update(domain, psnr[index], ssim[index]) + baseline_metrics.update(domain, base_psnr[index], base_ssim[index]) + return { + "restored": restored_metrics.compute(), + "degraded_baseline": baseline_metrics.compute(), + } + + +class ExponentialMovingAverage: + """Device-resident EMA over parameters and persistent buffers.""" + + def __init__(self, module: nn.Module, decay: float = 0.9999) -> None: + if not 0.0 <= decay < 1.0: + raise ValueError("EMA decay must satisfy 0 <= decay < 1") + self.decay = float(decay) + self.num_updates = 0 + self.shadow = { + name: value.detach().clone() + for name, value in unwrap_module(module).state_dict().items() + } + + @torch.no_grad() + def update(self, module: nn.Module) -> None: + current = unwrap_module(module).state_dict() + if current.keys() != self.shadow.keys(): + raise ValueError("EMA/model state keys changed") + self.num_updates += 1 + warmup_decay = float(1 + self.num_updates) / float(10 + self.num_updates) + effective_decay = min(self.decay, warmup_decay) + for name, value in current.items(): + source = value.detach() + if torch.is_floating_point(source): + self.shadow[name].mul_(effective_decay).add_( + source, alpha=1.0 - effective_decay + ) + else: + self.shadow[name].copy_(source) + + def state_dict(self) -> Dict[str, Any]: + return { + "decay": self.decay, + "num_updates": self.num_updates, + "shadow": {name: value.clone() for name, value in self.shadow.items()}, + } + + def load_state_dict(self, state: Mapping[str, Any]) -> None: + if float(state["decay"]) != self.decay: + raise ValueError("EMA decay mismatch") + update_count = state.get("num_updates") + if isinstance(update_count, bool) or not isinstance(update_count, int): + raise ValueError("EMA state is missing a valid update count") + if update_count < 0: + raise ValueError("EMA update count cannot be negative") + self.num_updates = update_count + shadow = state["shadow"] + if shadow.keys() != self.shadow.keys(): + raise ValueError("EMA state keys mismatch") + self.shadow = { + name: value.to( + device=self.shadow[name].device, dtype=self.shadow[name].dtype + ).clone() + for name, value in shadow.items() + } + + @contextlib.contextmanager + def apply(self, module: nn.Module) -> Iterator[None]: + target = unwrap_module(module) + original = {name: value.detach().clone() for name, value in target.state_dict().items()} + target.load_state_dict(self.shadow, strict=True) + try: + yield + finally: + target.load_state_dict(original, strict=True) + + +def make_grad_scaler(enabled: bool) -> torch.cuda.amp.GradScaler: + return torch.cuda.amp.GradScaler(enabled=bool(enabled)) + + +def scaler_step_or_fail( + scaler: torch.cuda.amp.GradScaler, + optimizer: torch.optim.Optimizer, +) -> None: + """Apply one AMP step, failing before any logical cursor can advance. + + PyTorch signals a skipped optimizer update by reducing the dynamic scale. + Continuing would desynchronize the sample cursor, LR scheduler, and EMA + from actual parameter updates, so deterministic v4 runs stop and resume + from their last atomic checkpoint instead. + """ + + scale_before = float(scaler.get_scale()) + scaler.step(optimizer) + scaler.update() + scale_after = float(scaler.get_scale()) + if scale_after < scale_before: + optimizer.zero_grad(set_to_none=True) + raise FloatingPointError( + "AMP overflow skipped the optimizer update; run stopped before " + "advancing scheduler, EMA, or logical step" + ) + + +class RecoverableAmpOverflow(FloatingPointError): + """AMP gradient overflow with an atomic unchanged-step resume checkpoint.""" + + +def collective_device() -> torch.device: + """Device the NCCL collectives must run on for this process.""" + + if torch.cuda.is_available(): + return torch.device("cuda", torch.cuda.current_device()) + return torch.device("cpu") + + +def has_any_gradient(model: nn.Module) -> bool: + """False when a step produced no gradient at all (every micro-batch was + dropped), in which case there is nothing to clip, reduce or apply.""" + + return any(p.grad is not None for p in unwrap_module(model).parameters()) + + +def is_globally_finite_scalar(value: Tensor) -> bool: + """Synchronize a scalar finite/non-finite decision across all DDP ranks.""" + + detached = value.detach() + if detached.numel() != 1: + raise ValueError("finite check requires a scalar tensor") + finite = torch.isfinite(detached).all().to(dtype=torch.int32) + if dist.is_available() and dist.is_initialized(): + # clip_grad_norm_ returns a CPU scalar when no parameter carries a + # gradient; NCCL rejects that with "Tensors must be CUDA and dense". + finite = finite.to(collective_device()) + dist.all_reduce(finite, op=dist.ReduceOp.MIN) + return bool(finite.item()) + + +def require_finite_tensor(value: Tensor, name: str) -> float: + """Return a scalar diagnostic or fail every DDP rank before state advances.""" + + if not is_globally_finite_scalar(value): + raise FloatingPointError("non-finite %s" % name) + return float(value.detach().float().item()) + + +def nonfinite_loss_within_budget( + *, consecutive: int, total: int, max_consecutive: int = 5, max_total: int = 100 +) -> bool: + """Isolated fp16 spikes are tolerable; a persistent NaN is not.""" + + return int(consecutive) < int(max_consecutive) and int(total) <= int(max_total) + + +# The encoder half of the Uformer denoiser: everything that consumes the +# input image on the way down. Freezing it for the first steps of a run lets +# the decoder, the conditioning path and the heads re-adapt to a NEW Phase-1 +# conditioning without disturbing generic features (the v6.1 lesson: opening +# the whole trunk from step 0 reproduces cross-domain interference). +ENCODER_PARAMETER_TOKENS: Tuple[str, ...] = ( + "input_projection", "down_blocks", "down_attentions", "downsamples", "down_experts", +) + + +def is_encoder_parameter(name: str) -> bool: + return any(token in name.split(".") for token in ENCODER_PARAMETER_TOKENS) + + +def mask_encoder_gradients(model: nn.Module) -> int: + """Drop encoder gradients before the optimizer sees them. + + Preferred over toggling ``requires_grad`` because DistributedDataParallel + fixes its reduction buckets at construction time; masking keeps the + backward graph identical and simply discards the reduced gradients. + """ + + masked = 0 + for name, parameter in unwrap_module(model).named_parameters(): + if parameter.grad is not None and is_encoder_parameter(name): + parameter.grad = None + masked += 1 + return masked + + +class EarlyStopper: + """Stop when ``patience`` consecutive evaluations bring no real gain.""" + + def __init__(self, patience: int, min_delta: float = 0.02) -> None: + self.patience = int(patience) + self.min_delta = float(min_delta) + self.best = -math.inf + self.strikes = 0 + + def update(self, score: float) -> bool: + if self.patience <= 0: + return False + value = float(score) + if value > self.best + self.min_delta: + self.best = value + self.strikes = 0 + return False + self.best = max(self.best, value) + self.strikes += 1 + return self.strikes >= self.patience + + def state_dict(self) -> Dict[str, Any]: + return {"best": float(self.best), "strikes": int(self.strikes)} + + def load_state_dict(self, state: Mapping[str, Any]) -> None: + """Restore best/strikes across an overflow resume (otherwise a resumed + run silently restarts its patience budget).""" + + self.best = float(state.get("best", -math.inf)) + self.strikes = int(state.get("strikes", 0)) + + +def loss_overflow_action(loss: Tensor, *, amp_enabled: bool) -> str: + """Decide what a (possibly non-finite) forward loss means. + + A NaN/Inf produced inside ``autocast`` is an fp16 range failure in the + forward pass. The AMP loss scale only multiplies the backward pass, so + backing it off and replaying the same batch reproduces the same NaN; + the batch is dropped instead (``skip``) and the step proceeds with the + remaining micro-batches. In fp32 a non-finite loss is a real defect and + stays fatal. + """ + + if is_globally_finite_scalar(loss): + return "ok" + return "skip" if amp_enabled else "fail" + + +def model_state_hash(module: nn.Module) -> str: + digest = hashlib.sha256() + for name, value in sorted(unwrap_module(module).state_dict().items()): + tensor = value.detach().cpu().contiguous() + digest.update(name.encode("utf-8")) + digest.update(str(tuple(tensor.shape)).encode("ascii")) + digest.update(str(tensor.dtype).encode("ascii")) + if tensor.dtype == torch.bfloat16: + tensor = tensor.float() + digest.update(tensor.numpy().tobytes()) + return digest.hexdigest() + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + while True: + block = handle.read(1024 * 1024) + if not block: + break + digest.update(block) + return digest.hexdigest() + + +def validate_phase1_artifact_header( + path: Path, expected_sha256: str +) -> Mapping[str, Any]: + """Pin calibration provenance without instantiating the unused encoder.""" + + actual_sha256 = _file_sha256(path) + if actual_sha256.lower() != str(expected_sha256).lower(): + raise ValueError( + "Phase-1 sha256 mismatch: expected %s, received %s" + % (expected_sha256, actual_sha256) + ) + checkpoint = _torch_load(path, map_location="cpu") + expected = { + "schema_version": PHASE1_SCHEMA_VERSION, + "phase": 1, + "aggregation_version": PHASE1_AGGREGATION_VERSION, + "branch_order": list(BRANCH_ORDER), + } + for field, value in expected.items(): + actual = checkpoint.get(field) + if field == "branch_order" and actual is not None: + actual = list(actual) + if actual != value: + raise ValueError( + "Phase-1 %s mismatch: expected %r, received %r" + % (field, value, actual) + ) + return checkpoint + + +@dataclass(frozen=True) +class CheckpointContract: + condition_mode: str + phase1_sha256: str + phase1_metadata: Mapping[str, Any] + train_digest: str + val_digest: str + schedule: Mapping[str, Any] + architecture: Mapping[str, Any] + data_plan: Mapping[str, Any] + init_model_hash: str + max_steps: int + ema_decay: float + + def to_dict(self) -> Dict[str, Any]: + return dataclasses.asdict(self) + + +@dataclass +class ResumeState: + step: int + history: List[Dict[str, Any]] + early_stop: Optional[Dict[str, Any]] = None + + +def _rng_state() -> Dict[str, Any]: + state: Dict[str, Any] = { + "python": random.getstate(), + "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), + } + if torch.cuda.is_available(): + state["cuda"] = torch.cuda.get_rng_state_all() + return state + + +def _restore_rng_state(state: Mapping[str, Any]) -> None: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + if torch.cuda.is_available() and "cuda" in state: + device_index = torch.cuda.current_device() + cuda_states = state["cuda"] + # In torchrun every process may see every GPU. Restoring all devices + # from every rank would create a cross-process race; each rank owns and + # restores only its active device. A single-visible-GPU gate checkpoint + # has one saved stream; it is the portable source stream for every rank. + source_index = device_index if device_index < len(cuda_states) else 0 + torch.cuda.set_rng_state(cuda_states[source_index], device=device_index) + + +def _atomic_torch_save(payload: Any, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(".%s.%d.tmp" % (path.name, os.getpid())) + try: + torch.save(payload, str(temporary)) + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +def _torch_load(path: Path, map_location: Any = "cpu") -> Any: + try: + return torch.load(str(path), map_location=map_location, weights_only=False) + except TypeError: + return torch.load(str(path), map_location=map_location) + + +def save_training_checkpoint( + path: Path, + model: nn.Module, + ema: ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + *, + step: int, + contract: CheckpointContract, + history: Sequence[Mapping[str, Any]], + recovery_marker: Optional[Mapping[str, Any]] = None, + early_stop: Optional[Mapping[str, Any]] = None, +) -> None: + payload = { + "schema_version": 4, + "phase": 2, + "step": int(step), + "model_state_dict": unwrap_module(model).state_dict(), + "ema_state_dict": ema.state_dict(), + "optimizer_state_dict": optimizer.state_dict(), + "scheduler_state_dict": scheduler.state_dict(), + "scaler_state_dict": scaler.state_dict(), + "rng_state": _rng_state(), + "early_stop": dict(early_stop) if early_stop is not None else None, + "contract": contract.to_dict(), + "condition_mode": contract.condition_mode, + "phase1_sha256": contract.phase1_sha256, + "phase1_metadata": dict(contract.phase1_metadata), + "train_digest": contract.train_digest, + "val_digest": contract.val_digest, + "schedule_config": dict(contract.schedule), + "architecture": dict(contract.architecture), + "init_model_hash": contract.init_model_hash, + "max_steps": contract.max_steps, + "ema_decay": contract.ema_decay, + "history": [dict(item) for item in history], + } + if recovery_marker is not None: + payload["recovery"] = dict(recovery_marker) + _atomic_torch_save(payload, Path(path)) + + +def recover_amp_gradient_overflow( + path: Path, + model: nn.Module, + ema: ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + *, + step: int, + contract: CheckpointContract, + history: Sequence[Mapping[str, Any]], + rank: int, + distributed: bool, + observed_grad_norm: float, + reason: str = "nonfinite_gradient_norm", + early_stop: Optional[Mapping[str, Any]] = None, +) -> None: + """Back off AMP exactly once, checkpoint unchanged state, then stop. + + This function is entered only after a globally synchronized non-finite + gradient decision. ``GradScaler.update(new_scale=...)`` both applies the + explicit backoff and resets its per-optimizer UNSCALED stage. The growth + tracker is reset separately because the public update API intentionally + preserves it when a caller supplies a scale. + """ + + scale_before = float(scaler.get_scale()) + scale_after = scale_before * float(scaler.get_backoff_factor()) + if not math.isfinite(scale_after) or scale_after <= 0.0: + raise FloatingPointError("AMP scaler produced an invalid recovery scale") + scaler.update(new_scale=scale_after) + growth_tracker = getattr(scaler, "_growth_tracker", None) + if not isinstance(growth_tracker, Tensor): + raise RuntimeError("AMP scaler growth tracker is unavailable for recovery") + growth_tracker.zero_() + optimizer.zero_grad(set_to_none=True) + + marker = { + "schema_version": 1, + "reason": str(reason), + "step": int(step), + "observed_grad_norm": repr(float(observed_grad_norm)), + "scale_before": scale_before, + "scale_after": scale_after, + "growth_tracker_reset": 0, + "optimizer_step_applied": False, + "replay_logical_step": int(step), + } + save_error: Optional[Exception] = None + if rank == 0: + try: + save_training_checkpoint( + path, + model, + ema, + optimizer, + scheduler, + scaler, + step=step, + contract=contract, + history=history, + recovery_marker=marker, + early_stop=early_stop, + ) + except Exception as error: # synchronize filesystem failures across DDP + save_error = error + save_succeeded = save_error is None + if distributed: + parameter = next(unwrap_module(model).parameters(), None) + flag_device = parameter.device if parameter is not None else torch.device("cpu") + save_flag = torch.tensor( + 1 if save_succeeded else 0, + dtype=torch.int32, + device=flag_device, + ) + # Every rank participates even when rank zero's atomic write failed, + # avoiding peers hanging forever in the subsequent success barrier. + dist.broadcast(save_flag, src=0) + save_succeeded = bool(save_flag.item()) + if not save_succeeded: + detail = ": %s" % save_error if save_error is not None else "" + raise RecoverableAmpOverflow( + "AMP overflow recovery checkpoint save failed on rank 0 at %s%s; " + "logical step %d was not advanced" + % (path, detail, step) + ) from save_error + if distributed: + dist.barrier() + raise RecoverableAmpOverflow( + "%s at logical step %d; scaler backed off " + "from %g to %g and recovery checkpoint saved at %s; resume from it " + "to replay the unchanged step" + % ( + "non-finite AMP gradient norm" + if reason == "nonfinite_gradient_norm" + else "non-finite AMP forward loss", + step, scale_before, scale_after, path, + ) + ) + + +def _contract_mismatches(actual: Any, expected: Any, path: str, added: List[str]) -> List[str]: + """Recursive comparison; a key that exists in ``expected`` (the running + code) but not in the stored ``actual`` is a field ADDED to the + architecture/schedule record after the checkpoint was written (recorded + in ``added``, tolerated); any other difference is a mismatch.""" + + if isinstance(expected, Mapping) and isinstance(actual, Mapping): + problems: List[str] = [] + for key in sorted(set(expected) | set(actual)): + child = "%s.%s" % (path, key) if path else str(key) + if key not in actual: + added.append(child) + continue + if key not in expected: + problems.append("%s removed" % child) + continue + problems.extend(_contract_mismatches(actual[key], expected[key], child, added)) + return problems + if actual != expected: + return ["%s: expected %r, received %r" % (path, expected, actual)] + return [] + + +def _validate_contract(actual: Mapping[str, Any], expected: CheckpointContract) -> None: + expected_fields = expected.to_dict() + for name, expected_value in expected_fields.items(): + actual_value = actual.get(name) + if actual_value == expected_value: + continue + added: List[str] = [] + problems = _contract_mismatches(actual_value, expected_value, name, added) + if problems: + raise ValueError( + "checkpoint contract %s mismatch: %s" % (name, "; ".join(problems[:6])) + ) + if added: + print( + "[resume] contract %s: tolerating %d field(s) added after the checkpoint: %s" + % (name, len(added), ", ".join(added[:8])), + flush=True, + ) + + +def resume_training_checkpoint( + path: Path, + model: nn.Module, + ema: ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + contract: CheckpointContract, +) -> ResumeState: + checkpoint = _torch_load(Path(path), map_location="cpu") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("not a Phase-2 v4 checkpoint") + _validate_contract(checkpoint.get("contract", {}), contract) + unwrap_module(model).load_state_dict(checkpoint["model_state_dict"], strict=True) + ema.load_state_dict(checkpoint["ema_state_dict"]) + optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) + scheduler.load_state_dict(checkpoint["scheduler_state_dict"]) + scaler.load_state_dict(checkpoint["scaler_state_dict"]) + _restore_rng_state(checkpoint["rng_state"]) + stored_early_stop = checkpoint.get("early_stop") + return ResumeState( + step=int(checkpoint["step"]), + history=[dict(item) for item in checkpoint.get("history", [])], + early_stop=dict(stored_early_stop) if isinstance(stored_early_stop, Mapping) else None, + ) + + +def load_shared_initialization( + path: Path, + model: nn.Module, + *, + target_condition: str, + expected_architecture: Mapping[str, Any], + expected_schedule: Mapping[str, Any], + expected_data_plan: Mapping[str, Any], + expected_phase1_sha256: str, + expected_phase1_metadata: Mapping[str, Any], + expected_train_digest: str, + expected_val_digest: str, + expected_max_steps: int, + expected_ema_decay: float, +) -> str: + """Load a provenance-checked step-zero D0 initialization for the D5 gate.""" + + checkpoint = _torch_load(Path(path), map_location="cpu") + if not isinstance(checkpoint, Mapping): + raise ValueError("initialization checkpoint must be a mapping") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("initialization must be a Phase-2 v4 checkpoint") + source_step = checkpoint.get("step") + if isinstance(source_step, bool) or source_step != 0: + raise ValueError("shared initialization checkpoint must be at step zero") + source_contract = checkpoint.get("contract") + if not isinstance(source_contract, Mapping): + raise ValueError("initialization checkpoint is missing its contract") + for field, expected in ( + ("architecture", dict(expected_architecture)), + ("schedule", dict(expected_schedule)), + ("data_plan", dict(expected_data_plan)), + ): + if source_contract.get(field) != expected: + raise ValueError("shared initialization %s mismatch" % field) + expected_provenance: Dict[str, Any] = { + "phase1_sha256": str(expected_phase1_sha256), + "phase1_metadata": dict(expected_phase1_metadata), + "train_digest": str(expected_train_digest), + "val_digest": str(expected_val_digest), + "max_steps": int(expected_max_steps), + "ema_decay": float(expected_ema_decay), + } + # Validate both the canonical contract and its top-level audit mirrors. + # Requiring both prevents a partially edited checkpoint from becoming the + # shared D0/D5 initialization source. + for field, expected in expected_provenance.items(): + if source_contract.get(field) != expected: + raise ValueError( + "shared initialization contract %s mismatch" % field + ) + if checkpoint.get(field) != expected: + raise ValueError( + "shared initialization top-level %s mismatch" % field + ) + source_condition = source_contract.get("condition_mode") + if source_condition != target_condition and not ( + source_condition == "null" and target_condition == "full" + ): + raise ValueError( + "shared initialization condition transition %r -> %r is forbidden" + % (source_condition, target_condition) + ) + state = checkpoint.get("model_state_dict") + if not isinstance(state, Mapping): + raise ValueError("initialization checkpoint has no model state") + + target = unwrap_module(model) + # Schedule buffers are immutable scientific configuration, not trainable + # initialization. Compare them before loading so a mislabeled checkpoint + # cannot overwrite the CLI-built schedule while recording a different one. + for name, expected_value in target.schedule.state_dict().items(): + source_value = state.get("schedule." + name) + if not isinstance(source_value, Tensor) or not torch.equal( + source_value.detach().cpu(), expected_value.detach().cpu() + ): + raise ValueError("shared initialization schedule buffer mismatch: %s" % name) + target.load_state_dict(state, strict=True) + actual_hash = model_state_hash(target) + recorded_hash = source_contract.get("init_model_hash") + if recorded_hash != actual_hash or checkpoint.get("init_model_hash") != actual_hash: + raise ValueError("shared initialization model hash mismatch") + return actual_hash + + +class BoundedCheckpointManager: + """Only init/last/best/recovery plus at most three milestone files.""" + + def __init__(self, output_dir: Path, max_milestones: int = 3) -> None: + if max_milestones < 0 or max_milestones > 3: + raise ValueError("max_milestones must be between zero and three") + self.output_dir = Path(output_dir) + self.max_milestones = int(max_milestones) + + def path_for(self, kind: str, step: Optional[int] = None) -> Path: + if kind in ("init", "last", "best", "overflow_recovery"): + return self.output_dir / (kind + ".pt") + if kind == "milestone" and step is not None: + return self.output_dir / ("milestone_%08d.pt" % int(step)) + raise ValueError("unsupported checkpoint kind") + + def prune_milestones(self) -> None: + files = sorted(self.output_dir.glob("milestone_*.pt")) + for obsolete in files[: max(0, len(files) - self.max_milestones)]: + obsolete.unlink() + + +def build_lr_scheduler( + optimizer: torch.optim.Optimizer, + max_steps: int, + warmup_steps: int = 500, + min_lr: float = 1e-6, + base_lr: float = 1e-4, +) -> torch.optim.lr_scheduler.LambdaLR: + if max_steps <= warmup_steps: + raise ValueError("max_steps must exceed warmup_steps") + minimum_ratio = float(min_lr) / float(base_lr) + + def multiplier(step: int) -> float: + if step < warmup_steps: + return max(float(step + 1) / float(warmup_steps), 1.0 / warmup_steps) + progress = min(1.0, float(step - warmup_steps) / float(max_steps - warmup_steps)) + cosine = 0.5 * (1.0 + math.cos(math.pi * progress)) + return minimum_ratio + (1.0 - minimum_ratio) * cosine + + return torch.optim.lr_scheduler.LambdaLR(optimizer, multiplier) + + +def _atomic_json_dump(payload: Any, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(".%s.%d.tmp" % (path.name, os.getpid())) + try: + with temporary.open("w", encoding="utf-8") as handle: + json.dump(payload, handle, indent=2, sort_keys=True) + handle.write("\n") + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +def _append_jsonl(payload: Mapping[str, Any], path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(dict(payload), sort_keys=True) + "\n") + + +@torch.no_grad() +def calibrate_kappa( + loader: Iterable[Mapping[str, Any]], + output_path: Path, + max_images: int = 4096, +) -> Dict[str, Any]: + """Train-only residual RMS audit; recommendation is the macro domain median.""" + + values: Dict[str, List[float]] = {domain: [] for domain in DOMAINS} + seen = 0 + for batch in loader: + clean = batch["clean"] + degraded = batch["degraded"] + domains = [str(value) for value in batch["degradation"]] + u0, uy = pixel_unshuffle2(clean), pixel_unshuffle2(degraded) + rms = (uy.float() - u0.float()).square().flatten(1).mean(1).sqrt().tolist() + for domain, value in zip(domains, rms): + values[domain].append(float(value)) + seen += 1 + if seen >= max_images: + break + if seen >= max_images: + break + missing = [domain for domain in DOMAINS if not values[domain]] + if missing: + raise ValueError("kappa calibration has no training samples for %r" % missing) + medians = {domain: float(np.median(values[domain])) for domain in DOMAINS} + payload = { + "schema_version": 1, + "source": "training_split_only", + "num_images": seen, + "per_domain_residual_rms_median": medians, + "recommended_kappa": float(np.median(list(medians.values()))), + } + _atomic_json_dump(payload, Path(output_path)) + return payload + + +def _parse_int_csv(value: str) -> Tuple[int, ...]: + if not value.strip(): + return () + result = tuple(sorted(set(int(item.strip()) for item in value.split(",")))) + if any(item < 0 for item in result): + raise argparse.ArgumentTypeError("steps must be non-negative") + return result + + +def _parse_dims(value: str) -> Tuple[int, int, int, int]: + result = tuple(int(item.strip()) for item in value.split(",")) + if len(result) != 4 or any(item <= 0 for item in result): + raise argparse.ArgumentTypeError("dims must be four positive comma-separated integers") + return result # type: ignore[return-value] + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--condition", choices=("full", "null"), default="full") + parser.add_argument("--phase1-checkpoint", type=Path, required=True) + parser.add_argument("--phase1-sha256", required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--create-manifest", action="store_true") + parser.add_argument("--data-root", type=Path, default=Path(os.environ.get("SCDC_DATA_ROOT", "/home/admin_mcn/data"))) + parser.add_argument("--rain13k-root", type=Path) + parser.add_argument("--quarantine-manifest", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--batch-size", type=int, default=8) + parser.add_argument("--eval-batch-size", type=int, default=4) + parser.add_argument("--grad-accum", type=int, default=2) + parser.add_argument("--max-steps", type=int, default=40_000) + parser.add_argument("--run-until-step", type=int, default=None) + parser.add_argument( + "--eval-steps", + type=_parse_int_csv, + default=(0, 500, 1000, 2000, 5000, 10000, 20000, 40000), + ) + parser.add_argument("--milestone-steps", type=_parse_int_csv, default=()) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument( + "--extra-clean-workers", type=int, default=2, + help="DataLoader workers for the extra clean pool (12 MP SIDD PNGs decode slowly; " + "2 workers capped the MI325X run at ~20%% GPU use)", + ) + parser.add_argument("--crop-size", type=int, default=256) + parser.add_argument("--dims", type=_parse_dims, default=(64, 128, 192, 256)) + parser.add_argument("--cond-dim", type=int, default=256) + parser.add_argument("--timesteps", type=int, default=8) + parser.add_argument("--eta-end", type=float, default=0.99) + parser.add_argument("--min-noise", type=float, default=0.2) + parser.add_argument("--power", type=float, default=0.3) + parser.add_argument("--kappa", type=float, default=None) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--eval-seed", type=int, default=20260830) + parser.add_argument("--device", default="cuda") + parser.add_argument("--ddp", action="store_true") + parser.add_argument( + "--freeze-encoder-steps", type=int, default=0, + help="train only the decoder/conditioning/heads for the first N steps " + "(encoder gradients are dropped); 0 = train everything from step 0", + ) + parser.add_argument( + "--early-stop-patience", type=int, default=0, + help="stop after N consecutive evaluations without a real macro-PSNR gain (0 = off)", + ) + parser.add_argument("--early-stop-min-delta", type=float, default=0.02) + parser.add_argument( + "--identity-pair-prob", type=float, default=0.0, + help="per-sample probability of feeding the clean target as input", + ) + parser.add_argument( + "--noise-pair-prob", type=float, default=0.0, + help="per-sample probability of a synthetic (clean+noise, clean) pair", + ) + parser.add_argument( + "--global-context", action="store_true", + help="run Phase-1 on the whole frame too and inject it (v7 backends)", + ) + parser.add_argument( + "--ddp-find-unused", action="store_true", + help="required for MoE backends under DDP (data-dependent expert use)", + ) + parser.add_argument("--no-amp", action="store_true") + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--ema-decay", type=float, default=0.9999) + parser.add_argument("--learning-rate", type=float, default=1e-4) + parser.add_argument("--calibrate-kappa", action="store_true") + parser.add_argument("--calibration-images", type=int, default=4096) + return parser + + +def _distributed_context(args: argparse.Namespace) -> Tuple[int, int, int, torch.device]: + if args.ddp: + if not torch.cuda.is_available(): + raise RuntimeError("DDP/NCCL requires CUDA") + if not dist.is_initialized(): + dist.init_process_group(backend="nccl", init_method="env://") + rank, world_size = dist.get_rank(), dist.get_world_size() + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + torch.cuda.set_device(local_rank) + return rank, world_size, local_rank, torch.device("cuda", local_rank) + device = torch.device(args.device) + if device.type == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("CUDA was requested but is unavailable") + if device.type == "cuda": + device_index = 0 if device.index is None else int(device.index) + torch.cuda.set_device(device_index) + device = torch.device("cuda", device_index) + return 0, 1, 0, device + + +def _seed_everything(seed: int, rank: int) -> None: + value = int(seed) + int(rank) * 1000003 + random.seed(value) + np.random.seed(value % (2 ** 32)) + torch.manual_seed(value) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(value) + + +def build_frozen_phase1( + checkpoint_path: Path, expected_sha256: str, device: torch.device +) -> Tuple[FrozenPhase1, Dict[str, Any]]: + # Kept lazy so unit tests can run in checkouts that only contain Phase 2. + import inspect + + from src.models.graph_encoder import BlindDegradationGraphEncoder, GraphConfig + + # The encoder architecture is governed by the checkpoint's stored + # graph_config (e.g. the ll_v3 global branch); unknown or missing keys + # fall back to the legacy defaults so v2 checkpoints load unchanged. + peek = _torch_load(Path(checkpoint_path), map_location="cpu") + stored: Dict[str, Any] = {} + config_block = peek.get("config") if isinstance(peek, Mapping) else None + if isinstance(config_block, Mapping): + graph_block = config_block.get("graph_config") + if isinstance(graph_block, Mapping): + stored = dict(graph_block) + allowed = set(inspect.signature(GraphConfig.__init__).parameters) - {"self"} + kwargs = {key: value for key, value in stored.items() if key in allowed} + if "spatial_map_size" in kwargs: + kwargs["spatial_map_size"] = tuple(kwargs["spatial_map_size"]) + del peek + + encoder = BlindDegradationGraphEncoder(GraphConfig(**kwargs)) + metadata = load_phase1_checkpoint( + checkpoint_path, encoder, expected_sha256=expected_sha256, map_location="cpu" + ) + frozen = FrozenPhase1(encoder).to(device) + frozen.eval() + return frozen, metadata + + +def _load_or_create_splits(args: argparse.Namespace) -> Any: + from src.data.phase2_v4 import ( + build_train_val_splits, + load_train_val_manifest, + save_train_val_manifest, + ) + + if args.create_manifest: + if args.rain13k_root is None or args.quarantine_manifest is None: + raise ValueError("creating a manifest requires rain and quarantine paths") + splits = build_train_val_splits( + args.data_root, args.rain13k_root, args.quarantine_manifest + ) + save_train_val_manifest(args.manifest, splits) + return splits + if not args.manifest.is_file(): + raise FileNotFoundError("manifest does not exist: %s" % args.manifest) + return load_train_val_manifest(args.manifest) + + +def _make_loaders( + args: argparse.Namespace, + splits: Any, + start_microstep: int, + rank: int, + world_size: int, +) -> Tuple[DataLoader, DataLoader]: + from src.data.phase2_v4 import ( + DeterministicBalancedBatchSampler, + Phase2PairDataset, + ) + + train_dataset = Phase2PairDataset( + splits.train, crop_size=args.crop_size, training=True, upscale_small=True + ) + val_dataset = Phase2PairDataset( + splits.val, crop_size=args.crop_size, training=False, upscale_small=True + ) + stop_step = args.run_until_step if args.run_until_step is not None else args.max_steps + total_microsteps = stop_step * args.grad_accum + if start_microstep > total_microsteps: + raise ValueError("resume step is beyond --run-until-step") + sampler = DeterministicBalancedBatchSampler( + [record.label for record in splits.train], + batch_size=args.batch_size, + steps=max(1, total_microsteps), + seed=args.seed, + start_microstep=start_microstep, + rank=rank, + world_size=world_size, + ) + loader_kwargs: Dict[str, Any] = { + "num_workers": args.workers, + "pin_memory": True, + } + if args.workers > 0: + loader_kwargs["persistent_workers"] = True + loader_kwargs["prefetch_factor"] = 2 + train_loader = DataLoader(train_dataset, batch_sampler=sampler, **loader_kwargs) + val_loader = DataLoader( + val_dataset, + batch_size=args.eval_batch_size, + shuffle=False, + drop_last=False, + **loader_kwargs, + ) + return train_loader, val_loader + + +def _architecture(args: argparse.Namespace) -> Dict[str, Any]: + return { + "name": "graph_resshift_v4", + "dims": list(args.dims), + "cond_dim": args.cond_dim, + "state_channels": 12, + "pixel_unshuffle_factor": 2, + "denoiser_input_channels": 36, + "prediction": "x0", + } + + +def _data_plan( + args: argparse.Namespace, + world_size: int, + amp_enabled: Optional[bool] = None, +) -> Dict[str, Any]: + global_micro_batch = int(args.batch_size) * int(world_size) + if amp_enabled is None: + amp_enabled = not bool(getattr(args, "no_amp", False)) + return { + "schema_version": 1, + "sampler": "deterministic_balanced_global_shard_v1", + "noise_plan": "per_sample_seed_v1", + "seed": int(args.seed), + "eval_seed": int(args.eval_seed), + "crop_size": int(args.crop_size), + "global_micro_batch": global_micro_batch, + "grad_accum": int(args.grad_accum), + "effective_batch": global_micro_batch * int(args.grad_accum), + "precision": "amp_fp16" if amp_enabled else "fp32", + } + + +def _schedule_config(args: argparse.Namespace) -> Dict[str, Any]: + return { + "timesteps": args.timesteps, + "eta_end": args.eta_end, + "min_noise": args.min_noise, + "power": args.power, + "kappa": args.kappa, + } + + +def _build_restorer(args: argparse.Namespace, device: torch.device) -> Phase2RestorationModule: + schedule = ResidualShiftSchedule( + timesteps=args.timesteps, + eta_end=args.eta_end, + min_noise=args.min_noise, + power=args.power, + kappa=args.kappa, + ) + conditioner = GraphConditionerV4(cond_dim=args.cond_dim, stage_dims=args.dims) + denoiser = GraphResidualShiftUNetV4(dims=args.dims, cond_dim=args.cond_dim) + return Phase2RestorationModule( + conditioner, denoiser, schedule, args.condition + ).to(device) + + +def _write_run_config(args: argparse.Namespace, path: Path) -> None: + payload = vars(args).copy() + for name, value in list(payload.items()): + if isinstance(value, Path): + payload[name] = str(value) + elif isinstance(value, tuple): + payload[name] = list(value) + _atomic_json_dump(payload, path) + + +def _prepare_output_directory( + args: argparse.Namespace, + rank: int, + resume_step: Optional[int] = None, +) -> None: + """Protect run provenance and write config only after contract validation.""" + + output_dir = Path(args.output_dir) + if args.resume is None: + nonempty = output_dir.exists() and any(output_dir.iterdir()) + if nonempty: + raise FileExistsError( + "fresh output directory is not empty: %s" % output_dir + ) + output_dir.mkdir(parents=True, exist_ok=True) + if args.ddp: + dist.barrier() + if rank == 0: + if args.resume is None: + destination = output_dir / "run_config.json" + else: + destination = output_dir / ( + "resume_config_step_%08d_%d.json" + % (int(resume_step or 0), time.time_ns()) + ) + _write_run_config(args, destination) + if args.ddp: + dist.barrier() + + +def validate_runtime_args(args: argparse.Namespace) -> int: + """Fail on invalid CLI combinations before touching CUDA or run outputs.""" + + if args.kappa is None and not args.calibrate_kappa: + raise ValueError("training requires an explicit frozen --kappa") + if args.kappa is not None and ( + not math.isfinite(args.kappa) or args.kappa < 0.0 + ): + raise ValueError("--kappa must be finite and non-negative") + if not math.isfinite(args.power) or args.power <= 0.0: + raise ValueError("--power must be finite and positive") + if not math.isfinite(args.ema_decay) or not 0.0 <= args.ema_decay < 1.0: + raise ValueError("--ema-decay must be finite and lie in [0, 1)") + if args.max_steps <= 500: + raise ValueError("--max-steps must exceed the 500-step warmup") + stop_step = args.run_until_step if args.run_until_step is not None else args.max_steps + if stop_step < 0 or stop_step > args.max_steps: + raise ValueError("--run-until-step must lie in [0, max_steps]") + if args.batch_size <= 0 or args.batch_size % 4: + raise ValueError("--batch-size must be positive and divisible by four") + if args.grad_accum <= 0: + raise ValueError("--grad-accum must be positive") + if args.resume is not None and args.init_checkpoint is not None: + raise ValueError("--resume and --init-checkpoint are mutually exclusive") + if args.calibrate_kappa and ( + args.resume is not None or args.init_checkpoint is not None + ): + raise ValueError("kappa calibration cannot resume or load model initialization") + if args.crop_size <= 0 or args.crop_size % 2: + raise ValueError("--crop-size must be a positive even integer") + if args.eval_batch_size <= 0: + raise ValueError("--eval-batch-size must be positive") + if args.workers < 0: + raise ValueError("--workers must be non-negative") + return int(stop_step) + + +def run(args: argparse.Namespace) -> None: + stop_step = validate_runtime_args(args) + + rank, world_size, local_rank, device = _distributed_context(args) + _seed_everything(args.seed, rank) + output_dir = args.output_dir + amp_enabled = device.type == "cuda" and not args.no_amp + + splits = _load_or_create_splits(args) + from src.data.phase2_v4 import ( + split_digest, + validate_clean_file_integrity, + validate_splits_against_checkpoint, + ) + + # Calibration and training are both pinned to the exact Phase-1 support + # provenance; no optimization mode may silently use a different split. + phase1_checkpoint = validate_phase1_artifact_header( + args.phase1_checkpoint, args.phase1_sha256 + ) + validate_splits_against_checkpoint(splits, phase1_checkpoint) + # Only canonical, provenance-validated paths may be read. Hashing before + # the split contract check could touch an arbitrary path from a tampered + # manifest (including data reserved outside the training/validation set). + validate_clean_file_integrity(splits) + if args.calibrate_kappa: + _prepare_output_directory(args, rank) + # Calibration is train-only and exactly domain balanced. A sequential + # traversal would exhaust the Rain13K prefix before seeing the smaller + # SIDD/LOLv2 domains when a sample cap is used. + from src.data.phase2_v4 import ( + DeterministicBalancedBatchSampler, + Phase2PairDataset, + ) + + calibration_dataset = Phase2PairDataset( + splits.train, crop_size=args.crop_size, training=True, upscale_small=True + ) + if args.calibration_images < 4: + raise ValueError("--calibration-images must be at least four") + calibration_batch = max(4, (args.eval_batch_size // 4) * 4) + calibration_steps = int( + math.ceil(float(args.calibration_images) / float(calibration_batch)) + ) + calibration_sampler = DeterministicBalancedBatchSampler( + [record.label for record in splits.train], + batch_size=calibration_batch, + steps=calibration_steps, + seed=args.seed, + ) + calibration_loader = DataLoader( + calibration_dataset, + batch_sampler=calibration_sampler, + num_workers=args.workers, + pin_memory=True, + ) + if rank == 0: + result = calibrate_kappa( + calibration_loader, + output_dir / "kappa_calibration.json", + max_images=args.calibration_images, + ) + print(json.dumps(result, sort_keys=True)) + if args.ddp: + dist.barrier() + dist.destroy_process_group() + return + + phase1, phase1_metadata = build_frozen_phase1( + args.phase1_checkpoint, args.phase1_sha256, device + ) + train_digest_value = split_digest(splits.train) + val_digest_value = split_digest(splits.val) + + model = _build_restorer(args, device) + architecture_config = _architecture(args) + schedule_config = _schedule_config(args) + data_plan = _data_plan(args, world_size, amp_enabled=amp_enabled) + if args.resume is not None: + resume_header = _torch_load(args.resume, map_location="cpu") + stored_contract = resume_header.get("contract", {}) + if "init_model_hash" not in stored_contract: + raise ValueError("resume checkpoint is missing init_model_hash") + # A DDP rank intentionally has a different pre-broadcast RNG stream; + # preserve and validate the immutable initialization provenance stored + # by the single-GPU source run rather than hashing throwaway weights. + init_hash = str(stored_contract["init_model_hash"]) + elif args.init_checkpoint is not None: + init_hash = load_shared_initialization( + args.init_checkpoint, + model, + target_condition=args.condition, + expected_architecture=architecture_config, + expected_schedule=schedule_config, + expected_data_plan=data_plan, + expected_phase1_sha256=phase1_metadata["sha256"], + expected_phase1_metadata=phase1_metadata, + expected_train_digest=train_digest_value, + expected_val_digest=val_digest_value, + expected_max_steps=args.max_steps, + expected_ema_decay=args.ema_decay, + ) + else: + init_hash = model_state_hash(model) + base_lr = float(getattr(args, "learning_rate", 1e-4)) + optimizer = torch.optim.AdamW( + model.parameters(), lr=base_lr, betas=(0.9, 0.99), weight_decay=1e-4 + ) + scheduler = build_lr_scheduler( + optimizer, max_steps=args.max_steps, base_lr=base_lr + ) + scaler = make_grad_scaler(amp_enabled) + ema = ExponentialMovingAverage(model, decay=args.ema_decay) + contract = CheckpointContract( + condition_mode=args.condition, + phase1_sha256=phase1_metadata["sha256"], + phase1_metadata=phase1_metadata, + train_digest=train_digest_value, + val_digest=val_digest_value, + schedule=schedule_config, + architecture=architecture_config, + data_plan=data_plan, + init_model_hash=init_hash, + max_steps=args.max_steps, + ema_decay=args.ema_decay, + ) + history: List[Dict[str, Any]] = [] + step = 0 + resumed_early_stop: Optional[Dict[str, Any]] = None + if args.resume is not None: + resumed = resume_training_checkpoint( + args.resume, model, ema, optimizer, scheduler, scaler, contract + ) + step, history = resumed.step, resumed.history + resumed_early_stop = resumed.early_stop + _prepare_output_directory(args, rank, resume_step=step) + elif rank == 0: + _prepare_output_directory(args, rank) + manager = BoundedCheckpointManager(output_dir) + save_training_checkpoint( + manager.path_for("init"), model, ema, optimizer, scheduler, scaler, + step=0, contract=contract, history=history, + ) + else: + _prepare_output_directory(args, rank) + + # Phase 1 is outside DistributedDataParallel and outside the optimizer. + phase1_parameter_ids = {id(parameter) for parameter in phase1.parameters()} + optimizer_parameter_ids = { + id(parameter) for group in optimizer.param_groups for parameter in group["params"] + } + if phase1_parameter_ids & optimizer_parameter_ids: + raise RuntimeError("Phase-1 parameters leaked into the Phase-2 optimizer") + + if args.ddp: + model = DistributedDataParallel( + model, + device_ids=[local_rank], + output_device=local_rank, + broadcast_buffers=False, + # MoE backends (v5+) hard-skip unselected experts per batch, so + # parameter usage is data-dependent and differs across ranks; + # without unused-parameter tracking the reducer deadlocks on the + # first batch whose expert set diverges. + find_unused_parameters=bool( + getattr(args, "ddp_find_unused", False) + ), + ) + start_microstep = step * args.grad_accum + train_loader, val_loader = _make_loaders( + args, splits, start_microstep, rank, world_size + ) + eval_steps = set(args.eval_steps) + milestone_steps = set(args.milestone_steps) + manager = BoundedCheckpointManager(output_dir) + best_score = max( + [float(item.get("macro_psnr", -float("inf"))) for item in history] + or [-float("inf")] + ) + + early_stopper = EarlyStopper( + int(getattr(args, "early_stop_patience", 0)), + float(getattr(args, "early_stop_min_delta", 0.02)), + ) + if resumed_early_stop: + early_stopper.load_state_dict(resumed_early_stop) + if rank == 0: + print("[resume] early-stop state restored: %r" % (resumed_early_stop,), flush=True) + freeze_encoder_steps = int(getattr(args, "freeze_encoder_steps", 0)) + + def do_evaluation(current_step: int) -> bool: + """Evaluate on rank zero; return whether training should stop.""" + nonlocal best_score + stop_flag = 0 + if args.ddp: + dist.barrier() + # Rank zero evaluates a complete, fixed-order validation set. + if rank == 0: + with ema.apply(model): + metrics = evaluate( + model, + phase1, + val_loader, + device, + args.eval_seed, + amp_enabled=amp_enabled, + ) + event = { + "event": "evaluation", + "step": current_step, + "condition": args.condition, + "macro_psnr": metrics["restored"]["macro_psnr"], + "macro_ssim": metrics["restored"]["macro_ssim"], + "metrics": metrics, + "time": time.time(), + } + history.append(event) + _append_jsonl(event, output_dir / "metrics.jsonl") + _atomic_json_dump(history, output_dir / "history.json") + print(json.dumps(event, sort_keys=True), flush=True) + if event["macro_psnr"] > best_score: + best_score = float(event["macro_psnr"]) + save_training_checkpoint( + manager.path_for("best"), model, ema, optimizer, scheduler, scaler, + step=current_step, contract=contract, history=history, + early_stop=early_stopper.state_dict(), + ) + if args.ddp: + dist.barrier() + + stop_requested = False + if step == 0 and 0 in eval_steps: + stop_requested = do_evaluation(0) + model.train() + phase1.eval() + optimizer.zero_grad(set_to_none=True) + loader_iterator = iter(train_loader) + extra_clean_iter = None + if getattr(args, "extra_clean_root", None): + from src.data.folder_crops import FolderCropDataset, infinite_batches + + extra_files = extra_clean_files(args.extra_clean_root) + extra_clean_iter = infinite_batches(DataLoader( + FolderCropDataset( + extra_files, size=int(args.crop_size), + seed=int(args.seed) * 31 + int(rank), return_full=True, + ), + batch_size=int(args.batch_size), shuffle=True, drop_last=True, + num_workers=int(getattr(args, "extra_clean_workers", 2)), pin_memory=device.type == "cuda", + )) + if rank == 0: + print("extra clean pool for identity pairs: %d files" % len(extra_files), flush=True) + nonfinite_forward_total = 0 + while step < stop_step: + accumulated_loss = 0.0 + nonfinite_forward_consecutive = 0 + for accumulation_index in range(args.grad_accum): + batch = next(loader_iterator) + degraded = batch["degraded"].to(device, non_blocking=True) + clean = batch["clean"].to(device, non_blocking=True) + use_full = ( + bool(getattr(args, "global_context", False)) + or bool(getattr(args, "exposure_pregain", False)) + ) and "full_degraded" in batch + full_degraded = batch["full_degraded"].to(device, non_blocking=True) if use_full else None + full_clean = batch["full_clean"].to(device, non_blocking=True) if use_full else None + aug_generator = torch.Generator() + aug_generator.manual_seed( + (int(args.seed) * 7919 + int(step) * 104729 + int(accumulation_index) * 31 + int(rank)) % (2 ** 63 - 1) + ) + degraded, full_degraded, _ = synthetic_noise_pairs( + degraded, clean, float(getattr(args, "noise_pair_prob", 0.0)), + aug_generator, full_degraded, full_clean, + ) + identity = identity_pair_mask( + clean.shape[0], float(getattr(args, "identity_pair_prob", 0.0)), device + ) + if bool(identity.any()): + extra_crop = extra_full = None + if extra_clean_iter is not None: + extra_batch = next(extra_clean_iter) + extra_crop = extra_batch["crop"].to(device, non_blocking=True) + extra_full = extra_batch["full"].to(device, non_blocking=True) + clean, full_clean = exposure_diverse_identity( + clean, full_clean, identity, aug_generator, + jitter=float(getattr(args, "identity_exposure_jitter", 0.0)), + extra_crop=extra_crop, extra_full=extra_full, + extra_prob=float(getattr(args, "extra_clean_prob", 0.0)), + ) + degraded = torch.where(identity.view(-1, 1, 1, 1), clean, degraded) + if full_degraded is not None: + full_degraded = torch.where(identity.view(-1, 1, 1, 1), full_clean, full_degraded) + # Representation call is intentionally performed even for D0/null. + with torch.cuda.amp.autocast(enabled=amp_enabled): + representation = phase1(degraded) + if full_degraded is not None: + representation.full_frame = phase1(full_degraded) + # Raw whole frame for image-statistics consumers (v10 pre-gain). + representation.full_image = full_degraded + u0_reference = pixel_unshuffle2(clean) + global_microstep = step * args.grad_accum + accumulation_index + sample_seed_values = batch["sample_seed"] + if isinstance(sample_seed_values, Tensor): + sample_seed_values = sample_seed_values.tolist() + timesteps, noise = deterministic_training_plan( + u0_reference, + args.timesteps, + args.seed, + global_microstep, + rank=rank, + sample_seeds=sample_seed_values, + ) + should_sync = accumulation_index == args.grad_accum - 1 + sync_context = ( + contextlib.nullcontext() + if should_sync or not isinstance(model, DistributedDataParallel) + else model.no_sync() + ) + with sync_context: + with torch.cuda.amp.autocast(enabled=amp_enabled): + loss = model( + clean, degraded, representation, timesteps, noise + ) + action = loss_overflow_action(loss, amp_enabled=amp_enabled) + if action == "fail": + raise FloatingPointError("non-finite training loss") + skipped = action == "skip" + if not skipped: + loss_value = float(loss.detach().float().item()) + scaled_loss = loss / float(args.grad_accum) + if skipped: + # fp16 range failure on this micro-batch: drop it (no + # backward, no loss contribution) and keep the step. + nonfinite_forward_consecutive += 1 + nonfinite_forward_total += 1 + if not nonfinite_loss_within_budget( + consecutive=nonfinite_forward_consecutive, + total=nonfinite_forward_total, + ): + raise FloatingPointError( + "non-finite training loss on %d consecutive micro-batches " + "(%d total) at logical step %d" + % (nonfinite_forward_consecutive, nonfinite_forward_total, step) + ) + # Free the retained graph: without the backward that would + # normally consume it, these activations would still be + # alive during the next forward and blow the memory budget. + del loss + continue + nonfinite_forward_consecutive = 0 + scaler.scale(scaled_loss).backward() + accumulated_loss += loss_value + # Drop the frozen half BEFORE unscaling: an fp16 overflow inside the + # frozen encoder would otherwise set the scaler's found_inf, be hidden + # from the grad-norm check by the mask, and make the scaler refuse the + # step (observed at step ~2350 of the first 15k run). + if freeze_encoder_steps > 0 and step < freeze_encoder_steps: + masked_encoder_grads = mask_encoder_gradients(model) + else: + masked_encoder_grads = 0 + if not has_any_gradient(model): + # Every micro-batch of this step overflowed in fp16 and was + # dropped. There is no update to apply: clear the state, advance + # the cursor and move on rather than reducing an empty gradient. + optimizer.zero_grad(set_to_none=True) + step += 1 + if rank == 0: + _append_jsonl( + {"event": "skipped_step", "step": step, + "reason": "all micro-batches non-finite", "time": time.time()}, + output_dir / "metrics.jsonl", + ) + continue + scaler.unscale_(optimizer) + grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) + if not is_globally_finite_scalar(grad_norm): + if not amp_enabled: + raise FloatingPointError("non-finite gradient norm") + recover_amp_gradient_overflow( + manager.path_for("overflow_recovery"), + model, + ema, + optimizer, + scheduler, + scaler, + step=step, + contract=contract, + history=history, + rank=rank, + distributed=args.ddp, + observed_grad_norm=float(grad_norm.detach().float().item()), + early_stop=early_stopper.state_dict(), + ) + grad_norm_value = float(grad_norm.detach().float().item()) + scaler_step_or_fail(scaler, optimizer) + optimizer.zero_grad(set_to_none=True) + scheduler.step() + ema.update(model) + step += 1 + + if rank == 0 and (step == 1 or step % 25 == 0): + event = { + "event": "train", + "step": step, + "loss": accumulated_loss / args.grad_accum, + "lr": optimizer.param_groups[0]["lr"], + "grad_norm": grad_norm_value, + "condition": args.condition, + "time": time.time(), + } + _append_jsonl(event, output_dir / "metrics.jsonl") + print(json.dumps(event, sort_keys=True), flush=True) + if step in eval_steps: + stop_requested = do_evaluation(step) + model.train() + phase1.eval() + if rank == 0 and step in milestone_steps: + save_training_checkpoint( + manager.path_for("milestone", step), model, ema, optimizer, + scheduler, scaler, step=step, contract=contract, history=history, + early_stop=early_stopper.state_dict(), + ) + manager.prune_milestones() + if rank == 0 and (step % 250 == 0 or step == stop_step): + save_training_checkpoint( + manager.path_for("last"), model, ema, optimizer, scheduler, scaler, + step=step, contract=contract, history=history, + early_stop=early_stopper.state_dict(), + ) + if stop_requested: + # Every rank leaves together: the flag was broadcast inside + # do_evaluation, so no rank is left waiting at the next barrier. + if rank == 0: + save_training_checkpoint( + manager.path_for("last"), model, ema, optimizer, scheduler, scaler, + step=step, contract=contract, history=history, + early_stop=early_stopper.state_dict(), + ) + print("[early-stop] training ended at step %d" % step, flush=True) + break + + if args.ddp: + dist.barrier() + dist.destroy_process_group() + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(build_parser().parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/train_phase2_unified_v7.py b/dataset/phase1_noise_20260906/code/train_phase2_unified_v7.py new file mode 100644 index 0000000000000000000000000000000000000000..dcd20d739480d5e8ab4bb91ab31c9ee378d12a78 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/train_phase2_unified_v7.py @@ -0,0 +1,1354 @@ +#!/usr/bin/env python3 +"""Phase 2 v7: unified two-step ResShift — one network, no external refiner. + +The gen-2 pipeline (v6.1 one-step + refiner) is re-expressed as an honest +two-step diffusion over the SAME weights: + + coarse t=2: u_2 = u_y-anchored marginal -> x0-MSE (content) + fine t=1: u_1 built from the model's OWN detached prediction via the + exact posterior -> image-space L1 + VGG (appearance) + +Chain-aware fine-step construction removes the exposure bias that made the +old 8-step chain destructive; timestep conditioning (AdaGN) lets one network +host both behaviours. Warm start: full v6.1 weights minus the schedule +buffers (T changes 8 -> 2). + +The VGG perceptual criterion is attached via ``object.__setattr__`` so it +never enters ``state_dict``/EMA/optimizer. +""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +from pathlib import Path +from typing import Any, Dict, Iterator, Mapping, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn +import torch.nn.functional as F + +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_graph_moe_v6 as v6 +from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule +from src.models.restoration.graph_moe_v6 import ( + MoEGraphConditionerV6, + MoEGraphResidualShiftUNetV6, +) +from src.models.restoration.graph_resshift_v4 import ( + ResidualShiftSchedule, + pixel_shuffle2, + pixel_unshuffle2, +) +from src.models.restoration.refiner_decoder import RefinerBlock +from src.models.restoration.uformer_moe_v7 import UformerMoEUNetV7 + +V7_VERSION = "unified_two_step_resshift_v1" +V7_WARMSTART_MAPPING_VERSION = "v6_full_state_minus_schedule_v1" + +# Phase-1's readout dimension; the output FiLM conditions on the raw +# representation vector, which is fixed by the frozen encoder architecture. +GLOBAL_CONDITION_DIM = 256 + +# Image-head submodules absent from a warm-start source are left at their +# zero-initialized state instead of failing the strict key check. +_V7_FRESH_HEAD_PREFIXES = ( + "full_res_tail.", "output_film.", "denoiser.pyramid_heads.", + "null_context", "null_global", "ctx_full_proj", "global_full_proj", + "photometric_head.", "exposure_pregain.", "colour_head.", + "denoiser.down_globals.", "denoiser.up_globals.", +) +# Phase-1 v5 PhotometricBranch state width (zeros when the encoder lacks it). +PHOTOMETRIC_STATE_DIM = 128 +_DEFAULT_PYRAMID_WEIGHTS = (0.1, 0.2, 0.3) + + +def _replace_bundle(bundle: Any, **changes: Any) -> Any: + import copy + import dataclasses + + if dataclasses.is_dataclass(bundle): + return dataclasses.replace(bundle, **changes) + clone = copy.copy(bundle) + for name, value in changes.items(): + setattr(clone, name, value) + return clone + + +class FullResTail(nn.Module): + """Shallow NAFNet-lite residual head at FULL image resolution. + + The diffusion trunk works entirely on the pixel-unshuffled half-res + state; this tail is the only place the network sees real pixels, so it + carries the fine-detail share (residual noise, sharpness) of the fine + objective. Input is (restored ‖ degraded); the output conv is + zero-initialized so the head is an exact identity at warm start. + """ + + def __init__(self, blocks: int = 3, width: int = 48) -> None: + super().__init__() + if blocks < 1: + raise ValueError("FullResTail requires at least one block") + self.entry = nn.Conv2d(6, width, 3, padding=1) + self.body = nn.Sequential( + *[RefinerBlock(width) for _ in range(int(blocks))] + ) + self.out = nn.Conv2d(width, 3, 3, padding=1) + nn.init.zeros_(self.out.weight) + nn.init.zeros_(self.out.bias) + + def forward(self, stacked: Tensor) -> Tensor: + return self.out(self.body(self.entry(stacked))) + +# BT.601 chroma rows (U, V). The luminance row is deliberately absent: the +# chroma objective must stay orthogonal to the L1/VGG terms that already +# constrain brightness, so only hue/saturation errors are re-weighted. Both +# rows must sum to exactly zero so a pure gray offset projects to zero chroma +# (the textbook U row is off by 1e-5 from rounding; the R coefficient below +# absorbs it). +_UV_FROM_RGB = ( + (-0.14714, -0.28886, 0.436), + (0.615, -0.51499, -0.10001), +) + + +def rgb_to_uv(image: Tensor) -> Tensor: + """Project an RGB batch [B,3,H,W] onto its BT.601 U/V chroma planes.""" + + if image.dim() != 4 or image.shape[1] != 3: + raise ValueError("rgb_to_uv expects a [B,3,H,W] batch") + weight = image.new_tensor(_UV_FROM_RGB) + return torch.einsum("bchw,oc->bohw", image, weight) + + +# BT.601 luma row; sums to exactly 1 so a uniform gray image maps to its own +# gray level. +_Y_FROM_RGB = (0.299, 0.587, 0.114) + +# The luma objective compares tone at this pooled resolution: coarse enough +# to be orthogonal to the pixel L1 (which already constrains detail), fine +# enough to catch regionally varying exposure errors, not just the mean. +_LUMA_POOL_GRID = 8 + + +def rgb_to_luma(image: Tensor) -> Tensor: + """Project an RGB batch [B,3,H,W] onto its BT.601 luma plane [B,1,H,W].""" + + if image.dim() != 4 or image.shape[1] != 3: + raise ValueError("rgb_to_luma expects a [B,3,H,W] batch") + weight = image.new_tensor(_Y_FROM_RGB).view(1, 3, 1, 1) + return (image * weight).sum(dim=1, keepdim=True) + + +def pooled_luma(image: Tensor, grid: int = _LUMA_POOL_GRID) -> Tensor: + """Coarse tone map: BT.601 luma average-pooled onto a grid×grid layout.""" + + return F.adaptive_avg_pool2d(rgb_to_luma(image), (grid, grid)) + +_V4_SCHEDULE_CONFIG = v4._schedule_config +_V4_DATA_PLAN = v4._data_plan + + +class GlobalPhotometricHead(nn.Module): + """Per-image global exposure controllable (v8). + + Measured on run A (probe_global_knob.py): a per-image global affine + ``a*x + b`` on the output is worth +7.2 dB oracle / ~+3 dB predictable on + lowlight, +6 / +2 on nearly-clean scene008, +1.4 / +1.2 on haze, and it + removes the systematic over-exposure of lowlight (oracle gain 0.82). The + colour (HV-plane) knob was worth only +0.5-0.9 dB, so the head predicts + intensity only. Inputs: Phase-1 global_condition + photometric_state of + the crop and, when available, of the whole frame. Zero-initialised + (exact identity), tanh-bounded (shrinkage: the pooled linear predictor + destroyed noise by -6.8 dB without it), ``dose`` scales the deltas at + inference and per-sample dropout keeps the identity path trained. + """ + + def __init__(self, hidden: int = 128, max_log_gain: float = 0.7, max_bias: float = 0.2) -> None: + super().__init__() + in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM) + self.net = nn.Sequential( + nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 2) + ) + nn.init.zeros_(self.net[-1].weight) + nn.init.zeros_(self.net[-1].bias) + self.max_log_gain = float(max_log_gain) + self.max_bias = float(max_bias) + + @staticmethod + def _vector(representation: Any) -> Tensor: + global_condition = representation.global_condition.float() + state = getattr(representation, "photometric_state", None) + if state is None: + state = global_condition.new_zeros(global_condition.shape[0], PHOTOMETRIC_STATE_DIM) + return torch.cat((global_condition, state.float()), dim=1) + + def coefficients(self, representation: Any) -> Tuple[Tensor, Tensor]: + """(log_gain, bias), each [B], already bounded.""" + crop = self._vector(representation) + full = getattr(representation, "full_frame", None) + full_vector = self._vector(full) if full is not None else torch.zeros_like(crop) + raw = self.net(torch.cat((crop, full_vector), dim=1)) + return self.max_log_gain * torch.tanh(raw[:, 0]), self.max_bias * torch.tanh(raw[:, 1]) + + def forward( + self, + image: Tensor, + representation: Any, + dose: float = 1.0, + drop_mask: Optional[Tensor] = None, + ) -> Tensor: + with torch.cuda.amp.autocast(enabled=False): + log_gain, bias = self.coefficients(representation) + if drop_mask is not None: + keep = (~drop_mask.to(torch.bool)).to(log_gain.dtype) + log_gain, bias = log_gain * keep, bias * keep + gain = (float(dose) * log_gain).exp().view(-1, 1, 1, 1) + bias = (float(dose) * bias).view(-1, 1, 1, 1) + return image.float() * gain + bias + + +# Whole-image exposure descriptors fed to the pre-gain (per image). +PREGAIN_STATS_DIM = 8 + + +def luma_statistics(image: Tensor) -> Tensor: + """[B, 8]: mean luma, log mean luma, luma p05/p50/p95, mean R/G/B.""" + + if image.dim() != 4 or image.shape[1] != 3: + raise ValueError("luma_statistics expects a [B,3,H,W] batch") + x = image.float().clamp(0.0, 1.0) + luma = rgb_to_luma(x).flatten(1) + mean = luma.mean(dim=1, keepdim=True) + probes = torch.tensor([0.05, 0.5, 0.95], device=luma.device, dtype=luma.dtype) + quantiles = torch.quantile(luma, probes, dim=1).transpose(0, 1) + channel_means = x.mean(dim=(2, 3)) + return torch.cat((mean, (mean + 1e-3).log(), quantiles, channel_means), dim=1) + + +class ExposurePreGain(nn.Module): + """Retinex-style per-image INPUT gain (v10). + + The v8 photometric head rescales the OUTPUT; the trunk still has to do + the x5-x10 brightening of a low-light input through a residual on u_y, + which is where the exposure overshoot and chroma loss come from. Every + published LOL method first estimates a global/illumination gain and + lets the restorer work in a normalised regime (Retinexformer's + illumination estimator). This module predicts one bounded log-gain per + image from the Phase-1 vectors of crop and whole frame (routing decides + "low-light" vs "dark but clean") plus raw luma statistics of both, and + multiplies the degraded image BEFORE pixel-unshuffle, so the residual + anchor u_y, the diffusion state and the full-res tail all see the gained + image. Zero-initialised (gain 1 -> bitwise identity), tanh-bounded, + ``dose`` scales the log-gain and per-sample dropout keeps gain-1 trained. + """ + + def __init__(self, hidden: int = 128, max_log_gain: float = 1.6) -> None: + super().__init__() + in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM) + 2 * PREGAIN_STATS_DIM + self.net = nn.Sequential( + nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 1) + ) + nn.init.zeros_(self.net[-1].weight) + nn.init.zeros_(self.net[-1].bias) + self.max_log_gain = float(max_log_gain) + + def log_gain(self, image: Tensor, representation: Any) -> Tensor: + crop_vector = GlobalPhotometricHead._vector(representation) + full = getattr(representation, "full_frame", None) + full_vector = ( + GlobalPhotometricHead._vector(full) if full is not None else torch.zeros_like(crop_vector) + ) + crop_stats = luma_statistics(image) + full_image = getattr(representation, "full_image", None) + full_stats = luma_statistics(full_image) if full_image is not None else crop_stats + raw = self.net(torch.cat((crop_vector, full_vector, crop_stats, full_stats), dim=1)) + return self.max_log_gain * torch.tanh(raw[:, 0]) + + def forward( + self, + image: Tensor, + representation: Any, + dose: float = 1.0, + drop_mask: Optional[Tensor] = None, + ) -> Tuple[Tensor, Tensor]: + """(gained image in fp32, log-gain [B]).""" + + with torch.cuda.amp.autocast(enabled=False): + log_gain = self.log_gain(image, representation) + if drop_mask is not None: + keep = (~drop_mask.to(torch.bool)).to(log_gain.dtype) + log_gain = log_gain * keep + gain = (float(dose) * log_gain).exp().view(-1, 1, 1, 1) + return image.float() * gain, log_gain + + +def pregain_target(clean: Tensor, degraded: Tensor, max_log_gain: float, eps: float = 1e-3) -> Tensor: + """Supervised target for the pre-gain: the log ratio of mean luma + clean/degraded per image, clamped to the head's bound. Identity and + noise pairs -> 0, low-light pairs -> the exposure lift, hazy pairs -> a + mild negative value (the clean scene is darker than its airlight). Gives + the gain a direct learning signal; measured on v10 (end-to-end only) the + gain had barely moved off 1.0 after 4k steps.""" + + ratio = (rgb_to_luma(clean.float()).mean(dim=(1, 2, 3)) + eps) / ( + rgb_to_luma(degraded.float()).mean(dim=(1, 2, 3)) + eps + ) + # Lift only (gain >= 1): a hazy input's clean scene is darker than its + # airlight, so an unclamped target darkened every hazy input by ~x0.7 and + # the trunk had to re-learn dehazing on inputs it never saw (v11 stage A, + # haze val 32.0 -> 30.4 in 2k steps). Darkening is trivial for the trunk; + # the Retinex-style pre-gain only needs to normalise under-exposure. + return ratio.log().clamp(0.0, float(max_log_gain)) + + +class GlobalColourHead(nn.Module): + """Per-image global colour transform on the OUTPUT (v12): y = M x + b with + M = diag(exp(d)) (I + O), d/O/b tanh-bounded, zero-initialised (identity). + + Measured on v11a outputs (LOLv2-real, whole image, oracle fit per image): + raw 19.3 -> intensity affine 27.5 -> 3x3 matrix + bias 29.3 dB, i.e. most + of the remaining low-light error is a global per-image colour/tone map + (gain, white balance, cast), which the intensity-only photometric head + cannot express. Predicted from the same inputs as the photometric head + (Phase-1 crop + whole-frame vectors and luma statistics); trained with + a supervised target (least-squares fit of the transform from the + detached output to the clean image) so it learns immediately, like the + pre-gain. + """ + + def __init__(self, hidden: int = 128, max_log_diag: float = 1.0, max_offdiag: float = 0.5, + max_bias: float = 0.25) -> None: + super().__init__() + in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM) + 2 * PREGAIN_STATS_DIM + self.net = nn.Sequential(nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 12)) + nn.init.zeros_(self.net[-1].weight) + nn.init.zeros_(self.net[-1].bias) + self.max_log_diag = float(max_log_diag) + self.max_offdiag = float(max_offdiag) + self.max_bias = float(max_bias) + + def coefficients(self, image: Tensor, representation: Any) -> Tuple[Tensor, Tensor]: + """(M [B,3,3], b [B,3]) — bounded; identity at initialisation.""" + crop_vector = GlobalPhotometricHead._vector(representation) + full = getattr(representation, "full_frame", None) + full_vector = GlobalPhotometricHead._vector(full) if full is not None else torch.zeros_like(crop_vector) + crop_stats = luma_statistics(image) + full_image = getattr(representation, "full_image", None) + full_stats = luma_statistics(full_image) if full_image is not None else crop_stats + raw = self.net(torch.cat((crop_vector, full_vector, crop_stats, full_stats), dim=1)) + log_diag = self.max_log_diag * torch.tanh(raw[:, 0:3]) + off = self.max_offdiag * torch.tanh(raw[:, 3:9]).view(-1, 3, 2) + bias = self.max_bias * torch.tanh(raw[:, 9:12]) + eye = torch.eye(3, device=raw.device, dtype=raw.dtype).unsqueeze(0) + # off-diagonal slots: row i gets the two entries j != i + offdiag = raw.new_zeros(raw.shape[0], 3, 3) + idx = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] + flat = off.reshape(-1, 6) + for k, (i, j) in enumerate(idx): + offdiag[:, i, j] = flat[:, k] + matrix = torch.diag_embed(log_diag.exp()) @ (eye + offdiag) + return matrix, bias + + def forward(self, image: Tensor, representation: Any, dose: float = 1.0, + drop_mask: Optional[Tensor] = None) -> Tensor: + with torch.cuda.amp.autocast(enabled=False): + matrix, bias = self.coefficients(image, representation) + if drop_mask is not None: + keep = (~drop_mask.to(torch.bool)).to(matrix.dtype).view(-1, 1, 1) + eye = torch.eye(3, device=matrix.device, dtype=matrix.dtype).unsqueeze(0) + matrix = keep * matrix + (1 - keep) * eye + bias = bias * keep.view(-1, 1) + if float(dose) != 1.0: + eye = torch.eye(3, device=matrix.device, dtype=matrix.dtype).unsqueeze(0) + matrix = eye + float(dose) * (matrix - eye) + bias = float(dose) * bias + x = image.float() + out = torch.einsum("bij,bjhw->bihw", matrix, x) + bias.view(-1, 3, 1, 1) + return out + + +def colour_target(output: Tensor, clean: Tensor, samples: int = 4096, seed: int = 0) -> Tuple[Tensor, Tensor]: + """Per-image least-squares fit of clean ~ M output + b on a pixel sample: + the supervised target of ``GlobalColourHead`` (returns M [B,3,3], b [B,3]).""" + + batch, _, height, width = output.shape + n = height * width + gen = torch.Generator(device="cpu").manual_seed(int(seed)) + index = torch.randperm(n, generator=gen)[: min(int(samples), n)].to(output.device) + x = output.detach().float().flatten(2)[:, :, index].transpose(1, 2) # [B,S,3] + y = clean.detach().float().flatten(2)[:, :, index].transpose(1, 2) + ones = torch.ones(batch, x.shape[1], 1, device=x.device, dtype=x.dtype) + xa = torch.cat((x, ones), dim=2) # [B,S,4] + # ridge-regularised normal equations (robust to flat/saturated images) + gram = xa.transpose(1, 2) @ xa + 1e-3 * torch.eye(4, device=x.device, dtype=x.dtype) + sol = torch.linalg.solve(gram, xa.transpose(1, 2) @ y) # [B,4,3]: y = xa @ sol + matrix = sol[:, :3, :].transpose(1, 2) # [B,3,3]: y_i = sum_j M_ij x_j + bias = sol[:, 3, :] + return matrix, bias + + +class Phase2UnifiedV7Module(v6.Phase2MoEV6Module): + """v6 graph-MoE module trained with the composite two-step objective.""" + + def __init__( + self, + *args, + fine_l1_weight: float = 1.0, + fine_vgg_weight: float = 0.1, + fine_chroma_weight: float = 0.0, + fine_luma_weight: float = 0.0, + tail_blocks: int = 0, + tail_width: int = 48, + use_output_film: bool = False, + cond_dropout_prob: float = 0.0, + pyramid_loss_weights: Sequence[float] = _DEFAULT_PYRAMID_WEIGHTS, + global_context: bool = False, + photometric_head: bool = False, + photometric_dropout: float = 0.0, + fine_chroma_space: str = "uv", + exposure_pregain: bool = False, + pregain_dropout: float = 0.0, + pregain_max_log_gain: float = 1.6, + pregain_target_weight: float = 0.0, + colour_head: bool = False, + colour_dropout: float = 0.0, + colour_target_weight: float = 0.0, + **kwargs, + ) -> None: + super().__init__(*args, **kwargs) + if fine_chroma_space not in ("uv", "hv"): + raise ValueError("fine_chroma_space must be 'uv' or 'hv'") + self.fine_chroma_space = str(fine_chroma_space) + self.photometric_head = GlobalPhotometricHead() if photometric_head else None + self.photometric_dropout = float(photometric_dropout) + self.exposure_pregain = ( + ExposurePreGain(max_log_gain=float(pregain_max_log_gain)) if exposure_pregain else None + ) + self.pregain_dropout = float(pregain_dropout) + self.pregain_target_weight = float(pregain_target_weight) + self.colour_head = GlobalColourHead() if colour_head else None + self.colour_dropout = float(colour_dropout) + self.colour_target_weight = float(colour_target_weight) + # Whole-frame context (Phase-1 on the full image) enters through the + # two live paths — added to the crop's context tokens and to the + # adaLN global vector — behind zero-init projections (identity at + # warm start). + if global_context: + cdim = int(self.conditioner.cond_dim) + self.ctx_full_proj = nn.Linear(cdim, cdim) + self.global_full_proj = nn.Linear(cdim, cdim) + for module in (self.ctx_full_proj, self.global_full_proj): + nn.init.zeros_(module.weight) + nn.init.zeros_(module.bias) + else: + self.ctx_full_proj = None + self.global_full_proj = None + self.cond_dropout_prob = float(cond_dropout_prob) + self.pyramid_loss_weights = tuple(float(w) for w in pyramid_loss_weights) + # Learned null condition (DGF): replaces the two live injection paths + # (cross-attention context, adaLN global vector). Zero-initialized so + # the untrained null branch coincides with the measured ablation. + if self.cond_dropout_prob > 0.0: + tokens = int(self.conditioner.num_nodes) + 2 + cond_dim = int(self.conditioner.cond_dim) + self.null_context = nn.Parameter(torch.zeros(1, tokens, cond_dim)) + self.null_global = nn.Parameter(torch.zeros(1, cond_dim)) + else: + self.null_context = None + self.null_global = None + self.fine_l1_weight = float(fine_l1_weight) + self.fine_vgg_weight = float(fine_vgg_weight) + self.fine_chroma_weight = float(fine_chroma_weight) + self.fine_luma_weight = float(fine_luma_weight) + self.full_res_tail = ( + FullResTail(blocks=int(tail_blocks), width=int(tail_width)) + if int(tail_blocks) > 0 + else None + ) + if use_output_film: + self.output_film = nn.Linear(GLOBAL_CONDITION_DIM, 6) + nn.init.zeros_(self.output_film.weight) + nn.init.zeros_(self.output_film.bias) + else: + self.output_film = None + self.eval_sample_steps = int(self.schedule.timesteps) + # Deliberately hidden from nn.Module bookkeeping: the criterion is + # part of the objective, not of the model state. + object.__setattr__(self, "_perceptual", None) + + def build_condition(self, representation: Any): + bundle = super().build_condition(representation) + full = getattr(representation, "full_frame", None) + if self.ctx_full_proj is None or full is None: + return bundle + full_bundle = self.conditioner(full, mode=self.condition_mode) + return _replace_bundle( + bundle, + context=bundle.context + self.ctx_full_proj(full_bundle.context.to(bundle.context.dtype)), + global_vector=bundle.global_vector + + self.global_full_proj(full_bundle.global_vector.to(bundle.global_vector.dtype)), + ) + + def null_condition(self, condition: Any, mask: Optional[Tensor] = None) -> Any: + """Swap the live injection paths for the learned null tokens. + + ``mask`` [B] selects rows to null (per-sample conditioning dropout); + ``None`` nulls the whole batch (unconditional branch at inference). + """ + + if self.null_context is None: + raise RuntimeError("model was built without null-condition tokens") + context = condition.context + global_vector = condition.global_vector + null_context = self.null_context.to(context.dtype).expand_as(context) + null_global = self.null_global.to(global_vector.dtype).expand_as(global_vector) + if mask is None: + new_context, new_global = null_context, null_global + else: + row = mask.view(-1, 1, 1).to(torch.bool) + new_context = torch.where(row, null_context, context) + new_global = torch.where(row.view(-1, 1), null_global, global_vector) + return _replace_bundle( + condition, context=new_context, global_vector=new_global + ) + + def predict_x0_pyramid( + self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition: Any + ): + """x0 prediction plus the coarse-to-fine band estimates (if any).""" + + if getattr(self.denoiser, "pyramid_heads", None) is None: + return self.predict_x0(u_t, u_y, timesteps, condition), [] + return self.denoiser(u_t, u_y, timesteps, condition, return_pyramid=True) + + def apply_pregain( + self, + degraded: Tensor, + representation: Any, + dose: float = 1.0, + drop_mask: Optional[Tensor] = None, + ) -> Tensor: + """Input-side exposure gain (v10); the input itself when disabled.""" + + if self.exposure_pregain is None: + return degraded + gained, _ = self.exposure_pregain(degraded, representation, dose=dose, drop_mask=drop_mask) + return gained.to(degraded.dtype) + + def apply_image_head( + self, + image: Tensor, + degraded: Tensor, + representation: Any, + photometric_dose: float = 1.0, + photometric_drop: Optional[Tensor] = None, + colour_dose: float = 1.0, + colour_drop: Optional[Tensor] = None, + ) -> Tensor: + """Full-res tail + global FiLM + global exposure controllable (+ v12 + global colour transform); exact identity at initialization.""" + + if self.full_res_tail is not None: + # fp32: the NAFNet SimpleGate products overflow fp16 once the + # pre-gain lifts a low-light input (x3.4 -> |activation| ~400 -> + # 400^2 > 65504; LOLv2 whole-image restoration went NaN on the + # MI325X run). The tail is 0.2M parameters; the cost is small. + with torch.cuda.amp.autocast(enabled=False): + image = image.float() + self.full_res_tail( + torch.cat((image.float(), degraded.float()), dim=1) + ) + if self.output_film is not None: + with torch.cuda.amp.autocast(enabled=False): + parameters = self.output_film( + representation.global_condition.float() + ) + scale, shift = parameters.view(-1, 2, 3, 1, 1).unbind(dim=1) + image = image * (1.0 + scale) + shift + if self.photometric_head is not None: + image = self.photometric_head( + image, representation, dose=photometric_dose, drop_mask=photometric_drop + ).to(image.dtype) + if self.colour_head is not None: + image = self.colour_head( + image, representation, dose=colour_dose, drop_mask=colour_drop + ).to(image.dtype) + return image + + def chroma_planes(self, image: Tensor) -> Tensor: + """Chroma planes for the fine chroma loss: BT.601 UV, or the HVI HV + plane whose intensity collapse down-weights chroma in dark pixels.""" + if self.fine_chroma_space == "hv": + from src.models.graph_encoder.hvi import rgb_to_hvi + + return rgb_to_hvi(image.float().clamp(0.0, 1.0), 0.2)[:, :2] + return rgb_to_uv(image) + + def _perceptual_loss(self, prediction: Tensor, target: Tensor) -> Tensor: + if self.fine_vgg_weight == 0.0: + return prediction.new_zeros(()) + if self._perceptual is None: + from src.models.restoration.refiner_decoder import VGGPerceptualLoss + + module = VGGPerceptualLoss().to(prediction.device) + object.__setattr__(self, "_perceptual", module) + with torch.cuda.amp.autocast(enabled=False): + return self._perceptual( + prediction.float().clamp(0.0, 1.0), target.float() + ) + + def training_loss( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> v6.MoETrainStepResult: + """Composite objective; the runtime-sampled ``timesteps`` is ignored + because every microstep trains both chain positions.""" + + del timesteps + pregain_drop = None + pregain_loss = clean.new_zeros(()) + if self.exposure_pregain is not None and self.training and self.pregain_dropout > 0.0: + pregain_drop = torch.rand(clean.shape[0], device=clean.device) < self.pregain_dropout + if self.exposure_pregain is not None and self.pregain_target_weight > 0.0: + # Direct supervision of the (unmasked) log-gain; the target is + # computed from the ORIGINAL degraded image before gaining. + with torch.cuda.amp.autocast(enabled=False): + raw_log_gain = self.exposure_pregain.log_gain(degraded, representation) + target = pregain_target(clean, degraded, self.exposure_pregain.max_log_gain) + pregain_loss = self.pregain_target_weight * (raw_log_gain - target).square().mean() + degraded = self.apply_pregain(degraded, representation, drop_mask=pregain_drop) + u0 = pixel_unshuffle2(clean) + uy = pixel_unshuffle2(degraded) + if noise is None: + noise = torch.randn_like(u0) + condition = self.build_condition(representation) + if self.training and self.cond_dropout_prob > 0.0: + drop = torch.rand(u0.shape[0], device=u0.device) < self.cond_dropout_prob + # Always route through the null tokens (a row-wise where), even + # when no row is dropped: the result is bitwise the conditioned + # bundle, but the null parameters stay in the autograd graph on + # every micro-batch, which DDP + no_sync accumulation requires. + condition = self.null_condition(condition, drop) + kappa = self.effective_kappa(condition) + terminal = self.schedule.timesteps + t_coarse = torch.full( + (u0.shape[0],), terminal, device=u0.device, dtype=torch.long + ) + u_t = self.schedule.q_sample(u0, uy, t_coarse, noise=noise, kappa=kappa) + coarse_prediction, pyramid = self.predict_x0_pyramid( + u_t, uy, t_coarse, condition + ) + coarse_loss = (coarse_prediction.float() - u0.float()).square().mean() + # Deep supervision of the coarse-to-fine bands: each decoder scale is + # asked for the area-downsampled clean state (MSE only; perceptual + # terms stay at full resolution). + pyramid_loss = coarse_prediction.new_zeros(()) + for weight, estimate in zip(self.pyramid_loss_weights, pyramid): + target = F.interpolate( + u0.float(), size=estimate.shape[-2:], mode="area" + ) + pyramid_loss = pyramid_loss + weight * ( + estimate.float() - target + ).square().mean() + + # Fine step is built from the model's OWN detached estimate — the + # network learns to polish its actual chain state, not a + # teacher-forced one. The mirrored noise keeps the plan replayable. + mean, variance = self.schedule.posterior_mean_variance( + u_t, coarse_prediction.detach(), t_coarse, kappa=kappa + ) + fine_noise = torch.flip(noise, dims=(-1,)) + u_fine = mean + torch.sqrt(variance) * fine_noise + t_fine = torch.full( + (u0.shape[0],), 1, device=u0.device, dtype=torch.long + ) + fine_prediction = self.predict_x0(u_fine, uy, t_fine, condition) + fine_image = pixel_shuffle2(fine_prediction.float()) + photometric_drop = None + if self.photometric_head is not None and self.training and self.photometric_dropout > 0.0: + photometric_drop = torch.rand(u0.shape[0], device=u0.device) < self.photometric_dropout + colour_drop = None + if self.colour_head is not None and self.training and self.colour_dropout > 0.0: + colour_drop = torch.rand(u0.shape[0], device=u0.device) < self.colour_dropout + colour_loss = fine_image.new_zeros(()) + if self.colour_head is not None and self.colour_target_weight > 0.0: + # Supervised target: the least-squares global map from the image + # BEFORE the colour head (tail + photometric head applied) to the + # clean image; the head must learn to predict it. + with torch.cuda.amp.autocast(enabled=False), torch.no_grad(): + # target and the head's image statistics need no gradient; + # keeping this pass out of autograd avoids a second full-res + # tail activation set (OOM at batch 32 on MI325X otherwise) + before = self.apply_image_head( + fine_image.detach(), degraded.float(), representation, + photometric_drop=photometric_drop, colour_dose=0.0, + ) + target_m, target_b = colour_target(before, clean.float()) + target_m = target_m.clamp(-3.0, 3.0) + target_b = target_b.clamp(-self.colour_head.max_bias, self.colour_head.max_bias) + pred_m, pred_b = self.colour_head.coefficients(before, representation) + colour_loss = self.colour_target_weight * ( + (pred_m - target_m).square().sum(dim=(1, 2)).mean() + + (pred_b - target_b).square().sum(dim=1).mean() + ) + fine_image = self.apply_image_head( + fine_image, degraded.float(), representation, + photometric_drop=photometric_drop, colour_drop=colour_drop, + ) + fine_l1 = F.l1_loss(fine_image, clean.float()) + fine_vgg = self._perceptual_loss(fine_image, clean) + if self.fine_chroma_weight != 0.0: + fine_chroma = F.l1_loss( + self.chroma_planes(fine_image), self.chroma_planes(clean.float()) + ) + else: + fine_chroma = fine_image.new_zeros(()) + if self.fine_luma_weight != 0.0: + fine_luma = F.l1_loss( + pooled_luma(fine_image), pooled_luma(clean.float()) + ) + else: + fine_luma = fine_image.new_zeros(()) + fine_loss = ( + self.fine_l1_weight * fine_l1 + + self.fine_vgg_weight * fine_vgg + + self.fine_chroma_weight * fine_chroma + + self.fine_luma_weight * fine_luma + ) + + gate_loss = ( + self.gate_anchor_weight * condition.gate.anchor_loss.float() + + self.gate_correction_weight + * condition.gate.correction_loss.float() + ) + if self.expert_kappa is not None and self.training: + self.expert_kappa.advance() + return v6.MoETrainStepResult( + loss=coarse_loss + pyramid_loss + fine_loss + gate_loss + pregain_loss + colour_loss, + reconstruction_loss=coarse_loss, + gate_loss=fine_loss, + u0_prediction=fine_prediction, + u0_target=u0, + u_t=u_t, + kappa=kappa.detach(), + ) + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +_BLOCK_KEY = __import__("re").compile(r"^denoiser\.(down_blocks|up_blocks)\.(\d+)\.(\d+)\.") + + +def _is_appended_block_key(name: str, donor: Mapping[str, Any]) -> bool: + """v11: a LeWin block whose index is beyond every block the donor has in + the same stage (appended, zero-init, identity) may be missing from the + donor; an index the donor DOES have must be present.""" + + match = _BLOCK_KEY.match(name) + if match is None: + return False + path, stage, index = match.group(1), match.group(2), int(match.group(3)) + prefix = "denoiser.%s.%s." % (path, stage) + donor_indices = { + int(key[len(prefix):].split(".")[0]) + for key in donor + if key.startswith(prefix) and key[len(prefix):].split(".")[0].isdigit() + } + return bool(donor_indices) and index > max(donor_indices) + + +def load_v6_warmstart( + path: Path, + expected_sha256: str, + model: Phase2UnifiedV7Module, + *, + weight_source: str = "ema", +) -> Dict[str, Any]: + """Load the full v6.1 state except the (reshaped) schedule buffers.""" + + actual = _file_sha256(path) + if actual.lower() != str(expected_sha256).lower(): + raise ValueError("v6 warmstart sha256 mismatch") + checkpoint = v4._torch_load(Path(path), map_location="cpu") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("warmstart must be a Phase-2 checkpoint") + if weight_source == "model": + state = checkpoint.get("model_state_dict") + elif weight_source == "ema": + ema_state = checkpoint.get("ema_state_dict") + state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None + else: + raise ValueError("weight_source must be 'model' or 'ema'") + if not isinstance(state, Mapping): + raise ValueError("v6 warmstart is missing the selected state") + + filtered = { + name: value + for name, value in state.items() + if not name.startswith("schedule.") + } + target = model.state_dict() + # Image-head submodules added AFTER the source run keep their fresh + # zero-initialized state (they are exact identities), so their absence + # from the source is tolerated — nothing else is. + import re as _re + + fresh_head_keys = sorted( + name + for name in target + if name not in filtered + and ( + name.startswith(_V7_FRESH_HEAD_PREFIXES) + or _re.match(r"^full_res_tail\.body\.\d+\.", name) is not None + or _is_appended_block_key(name, filtered) + ) + ) + expected = { + n + for n in target + if not n.startswith("schedule.") and n not in set(fresh_head_keys) + } + # Optional image-head modules the TARGET was built without (an ablation + # that drops the photometric head / pre-gain / colour head) may be present + # in the donor: their weights are dropped, everything else must match. + dropped_head_keys = sorted( + name for name in filtered + if name not in expected and name.startswith(_V7_FRESH_HEAD_PREFIXES) + ) + if dropped_head_keys: + filtered = {k: v for k, v in filtered.items() if k not in set(dropped_head_keys)} + print("[warmstart] dropping %d donor keys of heads absent from the target: %s" + % (len(dropped_head_keys), ", ".join(sorted({k.split(".")[0] for k in dropped_head_keys}))), + flush=True) + if set(filtered.keys()) != expected: + missing = sorted(expected - set(filtered)) + unexpected = sorted(set(filtered) - expected) + raise ValueError( + "v6 warmstart key mismatch; missing=%r unexpected=%r" + % (missing[:6], unexpected[:6]) + ) + result = model.load_state_dict(filtered, strict=False) + allowed_missing = set(fresh_head_keys) + if result.unexpected_keys or any( + not name.startswith("schedule.") and name not in allowed_missing + for name in result.missing_keys + ): + raise RuntimeError("v7 warmstart loader violated its allowlist") + return { + "mapping_version": V7_WARMSTART_MAPPING_VERSION, + "source_checkpoint_sha256": actual, + "source_step": int(checkpoint.get("step", -1)), + "weight_source": weight_source, + "schedule_reinitialized": True, + "fresh_head_keys": len(fresh_head_keys), + "dropped_head_keys": len(dropped_head_keys), + "materialized_state_hash": v4.model_state_hash(model), + } + + +def sample_unified_restoration( + model: nn.Module, + phase1: "v4.FrozenPhase1", + degraded: Tensor, + *, + seed: int, + record_ids: Optional[Sequence[str]] = None, + initial_noise: Optional[Tensor] = None, + amp_enabled: Optional[bool] = None, + dose: Optional[float] = None, + full_degraded: Optional[Tensor] = None, + photometric_dose: Optional[float] = None, + pregain_dose: Optional[float] = None, + colour_dose: Optional[float] = None, +) -> Tensor: + """v6 exact-posterior sampling plus the v7 image head. + + ``dose`` (DGF) interpolates the coarse-step x0 prediction between the + learned null branch and the conditioned branch: + x0 = x0(null) + dose * (x0(c) - x0(null)); the fine step always runs + fully conditioned. ``None`` (or 1.0) is the plain conditioned sampler. + + Mirrors ``v6.sample_moe_restoration`` step for step; the only addition is + ``apply_image_head`` on the shuffled image BEFORE crop/clamp, matching + the training-time order. Bitwise-identical to the v6 sampler when the + head is disabled (it is an exact identity then). + """ + + restorer = v4.unwrap_module(model) + if not isinstance(restorer, Phase2UnifiedV7Module): + raise TypeError("model must wrap Phase2UnifiedV7Module") + steps = int(getattr(restorer, "eval_sample_steps", 1)) + use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled) + with torch.cuda.amp.autocast(enabled=use_amp): + padded, size = v4.pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + if full_degraded is not None and getattr(restorer, "ctx_full_proj", None) is not None: + representation.full_frame = phase1(full_degraded.to(degraded.device)) + if full_degraded is not None: + representation.full_image = full_degraded.to(degraded.device) + # v10 input-side exposure gain (identity when the module is absent). + padded = restorer.apply_pregain( + padded, representation, + dose=1.0 if pregain_dose is None else float(pregain_dose), + ) + condition = restorer.build_condition(representation) + if float(getattr(restorer, "cond_dropout_prob", 0.0)) >= 1.0: + # A model trained with p = 1 never saw a real condition: sample + # it fully unconditionally (both steps); ``dose`` is meaningless. + condition = restorer.null_condition(condition) + dose = None + uy = pixel_unshuffle2(padded) + if initial_noise is None: + initial_noise = v4._noise_for_records( + uy, list(record_ids) if record_ids else None, + seed=seed, stage="initial", + ) + kappa_vector = restorer.effective_kappa(condition) + kappa = restorer.schedule.kappa_factor(kappa_vector, uy) + eta_terminal = restorer.schedule.eta[-1].to(uy.device, uy.dtype) + u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise + batch = uy.shape[0] + if steps <= 1: + timesteps = torch.full( + (batch,), restorer.schedule.timesteps, + device=uy.device, dtype=torch.long, + ) + u_t = restorer.predict_x0(u_t, uy, timesteps, condition) + else: + null_bundle = None + if dose is not None and float(dose) != 1.0: + null_bundle = restorer.null_condition(condition) + for step in restorer.schedule.reverse_timesteps(): + timesteps = torch.full( + (batch,), step, device=uy.device, dtype=torch.long + ) + u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition) + if null_bundle is not None and step == restorer.schedule.timesteps: + u0_null = restorer.predict_x0(u_t, uy, timesteps, null_bundle) + u0_hat = u0_null + float(dose) * (u0_hat - u0_null) + mean, variance = restorer.schedule.posterior_mean_variance( + u_t, u0_hat, timesteps, kappa=kappa_vector + ) + if step > 1: + noise = v4._noise_for_records( + u_t, list(record_ids) if record_ids else None, + seed=seed, stage=step, + ) + u_t = mean + torch.sqrt(variance) * noise + else: + u_t = mean + restored = pixel_shuffle2(u_t) + restored = restorer.apply_image_head( + restored, padded.to(restored.dtype), representation, + photometric_dose=1.0 if photometric_dose is None else float(photometric_dose), + colour_dose=1.0 if colour_dose is None else float(colour_dose), + ) + height, width = size + return restored[..., :height, :width].clamp(0.0, 1.0) + + +sample_unified_restoration.accepts_full_frame = True + + +BASE_BLOCKS_PER_STAGE = 2 + + +def _parse_extra_blocks(value: Any) -> Sequence[int]: + """Extra LeWin blocks appended per stage (v11), "" -> (0, 0, 0, 0).""" + + if value is None or (isinstance(value, str) and not value.strip()): + return (0, 0, 0, 0) + parts = ( + tuple(int(v) for v in value.split(",") if v.strip()) + if isinstance(value, str) else tuple(int(v) for v in value) + ) + if len(parts) != 4 or any(v < 0 for v in parts): + raise ValueError("extra blocks per stage must be four non-negative ints") + return parts + + +def blocks_per_stage(args: argparse.Namespace) -> Sequence[int]: + extra = _parse_extra_blocks(getattr(args, "extra_blocks_per_stage", "")) + return tuple(BASE_BLOCKS_PER_STAGE + int(e) for e in extra) + + +def _parse_scales(value: Any) -> Sequence[int]: + """Stage indices for the v10 global-attention blocks ("" -> none).""" + + if value is None: + return () + if isinstance(value, str): + return tuple(int(v) for v in value.split(",") if v.strip()) + return tuple(int(v) for v in value) + + +def _parse_weights(value: Any) -> Sequence[float]: + if value is None: + return _DEFAULT_PYRAMID_WEIGHTS + if isinstance(value, str): + return tuple(float(v) for v in value.split(",") if v.strip()) + return tuple(float(v) for v in value) + + +def _build_v7_restorer( + args: argparse.Namespace, device: torch.device +) -> Phase2UnifiedV7Module: + schedule = ResidualShiftSchedule( + timesteps=args.timesteps, eta_end=args.eta_end, + min_noise=args.min_noise, power=args.power, kappa=args.kappa, + ) + model = Phase2UnifiedV7Module( + conditioner=MoEGraphConditionerV6( + cond_dim=args.cond_dim, stage_dims=args.dims, + gate_hidden_dim=args.gate_hidden_dim, + gate_max_correction=args.gate_max_correction, + ), + denoiser=( + UformerMoEUNetV7( + dims=args.dims, cond_dim=args.cond_dim, + expert_rank=args.expert_rank, + pyramid_heads=bool(getattr(args, "pyramid_heads", False)), + global_attention_scales=_parse_scales( + getattr(args, "global_attention_scales", "") + ), + blocks_per_stage=blocks_per_stage(args), + grad_checkpoint=bool(getattr(args, "grad_checkpoint", False)), + ) + if args.backbone == "uformer" + else MoEGraphResidualShiftUNetV6( + dims=args.dims, cond_dim=args.cond_dim, + expert_rank=args.expert_rank, + ) + ), + schedule=schedule, + expert_kappa=ExpertKappaSchedule( + kappa_per_expert=v6._parse_kappa_values(args.expert_kappa_values), + kappa_global=float(args.kappa), + anneal_microsteps=0, + ), + condition_mode=args.condition, + gate_anchor_weight=args.gate_anchor_weight, + gate_correction_weight=args.gate_correction_weight, + fine_l1_weight=args.fine_l1_weight, + fine_vgg_weight=args.fine_vgg_weight, + fine_chroma_weight=float(getattr(args, "fine_chroma_weight", 0.0)), + fine_luma_weight=float(getattr(args, "fine_luma_weight", 0.0)), + tail_blocks=int(getattr(args, "full_res_tail_blocks", 0)), + tail_width=int(getattr(args, "full_res_tail_width", 48)), + use_output_film=bool(getattr(args, "output_film", False)), + global_context=bool(getattr(args, "global_context", False)), + cond_dropout_prob=float(getattr(args, "cond_dropout_prob", 0.0)), + pyramid_loss_weights=_parse_weights( + getattr(args, "pyramid_loss_weights", None) + ), + photometric_head=bool(getattr(args, "photometric_head", False)), + photometric_dropout=float(getattr(args, "photometric_dropout", 0.0)), + fine_chroma_space=str(getattr(args, "fine_chroma_space", "uv")), + exposure_pregain=bool(getattr(args, "exposure_pregain", False)), + pregain_dropout=float(getattr(args, "pregain_dropout", 0.0)), + pregain_max_log_gain=float(getattr(args, "pregain_max_log_gain", 1.6)), + pregain_target_weight=float(getattr(args, "pregain_target_weight", 0.0)), + colour_head=bool(getattr(args, "colour_head", False)), + colour_dropout=float(getattr(args, "colour_dropout", 0.0)), + colour_target_weight=float(getattr(args, "colour_target_weight", 0.0)), + ) + if args.resume is None and args.init_checkpoint is None: + if args.warmstart_v6 is not None: + audit = load_v6_warmstart( + args.warmstart_v6, args.warmstart_v6_sha256, model, + weight_source=args.warmstart_weight_source, + ) + elif bool(getattr(args, "allow_scratch", False)): + audit = {"mapping_version": "from_scratch"} + else: + raise ValueError( + "v7 requires --warmstart-v6, resume/init, or --allow-scratch" + ) + else: + source = args.resume if args.resume is not None else args.init_checkpoint + stored = v4._torch_load(Path(source), map_location="cpu") + architecture = stored.get("architecture") if isinstance(stored, Mapping) else None + audit = ( + dict(architecture.get("warmstart", {})) + if isinstance(architecture, Mapping) + else {"mapping_version": "resumed_state"} + ) + del stored + setattr(args, "_v7_warmstart_audit", audit) + if bool(getattr(args, "freeze_shared_trunk", False)): + for name, parameter in model.named_parameters(): + parameter.requires_grad_(v6._is_v6_only_key(name)) + return model.to(device) + + +def _v7_architecture(args: argparse.Namespace) -> Dict[str, Any]: + audit = getattr(args, "_v7_warmstart_audit", {}) + return { + "name": "unified_two_step_resshift_v7", + "version": 7, + "mechanism": V7_VERSION, + "backbone": str(getattr(args, "backbone", "conv")), + "moe": { + "expert_rank": int(args.expert_rank), + "gate_hidden_dim": int(args.gate_hidden_dim), + "gate_max_correction": float(args.gate_max_correction), + }, + "objective": { + "coarse": "x0_mse_fp32", + "fine": "chain_aware_l1_vgg", + "fine_l1_weight": float(args.fine_l1_weight), + "fine_vgg_weight": float(args.fine_vgg_weight), + "fine_chroma_weight": float( + getattr(args, "fine_chroma_weight", 0.0) + ), + "fine_chroma_space": ( + "hvi_hv_k0.2" if str(getattr(args, "fine_chroma_space", "uv")) == "hv" + else "yuv_bt601_uv" + ), + "fine_luma_weight": float(getattr(args, "fine_luma_weight", 0.0)), + "fine_luma_space": "yuv_bt601_y_pool%d" % _LUMA_POOL_GRID, + "fine_noise": "mirrored_coarse_noise", + }, + "coarse_to_fine": { + "pyramid_heads": bool(getattr(args, "pyramid_heads", False)), + "pyramid_loss_weights": list( + _parse_weights(getattr(args, "pyramid_loss_weights", None)) + ), + }, + "dose": { + "cond_dropout_prob": float(getattr(args, "cond_dropout_prob", 0.0)), + "null_paths": ["context", "global_vector"], + "identity_pair_prob": float(getattr(args, "identity_pair_prob", 0.0)), + }, + "global_context": bool(getattr(args, "global_context", False)), + "exposure_pregain": { + "enabled": bool(getattr(args, "exposure_pregain", False)), + "dropout": float(getattr(args, "pregain_dropout", 0.0)), + "max_log_gain": float(getattr(args, "pregain_max_log_gain", 1.6)), + "target_weight": float(getattr(args, "pregain_target_weight", 0.0)), + "target": "clamped_log_mean_luma_ratio_clean_over_degraded", + "inputs": ["global_condition", "photometric_state", "full_frame.*", + "luma_statistics(crop)", "luma_statistics(full_image)"], + "placement": "input_before_pixel_unshuffle", + }, + "global_attention_scales": list( + _parse_scales(getattr(args, "global_attention_scales", "")) + ), + "colour_head": { + "enabled": bool(getattr(args, "colour_head", False)), + "dropout": float(getattr(args, "colour_dropout", 0.0)), + "target_weight": float(getattr(args, "colour_target_weight", 0.0)), + "form": "diag(exp(d))(I+O)x+b, bounded, output side after the photometric head", + }, + "blocks_per_stage": list(blocks_per_stage(args)), + "grad_checkpoint": bool(getattr(args, "grad_checkpoint", False)), + "data_aug": { + "identity_pair_prob": float(getattr(args, "identity_pair_prob", 0.0)), + "noise_pair_prob": float(getattr(args, "noise_pair_prob", 0.0)), + "identity_exposure_jitter": float(getattr(args, "identity_exposure_jitter", 0.0)), + "extra_clean_root": ( + str(getattr(args, "extra_clean_root", None)) + if getattr(args, "extra_clean_root", None) else None + ), + "extra_clean_prob": float(getattr(args, "extra_clean_prob", 0.0)), + }, + "image_head": { + "full_res_tail_blocks": int( + getattr(args, "full_res_tail_blocks", 0) + ), + "full_res_tail_width": int( + getattr(args, "full_res_tail_width", 48) + ), + "output_film": bool(getattr(args, "output_film", False)), + "photometric_head": bool(getattr(args, "photometric_head", False)), + "photometric_dropout": float(getattr(args, "photometric_dropout", 0.0)), + "photometric_bounds": {"max_log_gain": 0.7, "max_bias": 0.2}, + "photometric_inputs": ["global_condition", "photometric_state", "full_frame.*"], + }, + "dims": list(args.dims), + "cond_dim": int(args.cond_dim), + "state_channels": 12, + "prediction": "x0", + "eval_sample_steps": int(args.timesteps), + "warmstart": dict(audit), + } + + +def _v7_schedule_config(args: argparse.Namespace) -> Dict[str, Any]: + result = dict(_V4_SCHEDULE_CONFIG(args)) + result["expert_kappa"] = { + "enabled": True, + "values": list(v6._parse_kappa_values(args.expert_kappa_values)), + "anneal_steps": 0, + "source": "normalized_node_strengths", + "posterior": "exact_per_sample_kappa", + } + result["unified_two_step"] = True + return result + + +def build_parser() -> argparse.ArgumentParser: + parser = v6.build_parser() + parser.description = __doc__ + parser.add_argument("--fine-l1-weight", type=float, default=1.0) + parser.add_argument("--fine-vgg-weight", type=float, default=0.1) + parser.add_argument( + "--fine-chroma-weight", type=float, default=0.0, + help="L1 weight on BT.601 U/V chroma planes of the fine prediction", + ) + parser.add_argument( + "--fine-luma-weight", type=float, default=0.0, + help="L1 weight on the 8x8-pooled BT.601 luma of the fine prediction", + ) + parser.add_argument( + "--full-res-tail-blocks", type=int, default=0, + help="NAFNet-lite blocks in the full-resolution image head (0 = off)", + ) + parser.add_argument("--full-res-tail-width", type=int, default=48) + parser.add_argument( + "--output-film", action="store_true", + help="global-condition FiLM (per-channel affine) on the output image", + ) + parser.add_argument( + "--pyramid-heads", action="store_true", + help="coarse-to-fine Laplacian band heads at 16/32/64 px (uformer)", + ) + parser.add_argument( + "--pyramid-loss-weights", default="0.1,0.2,0.3", + help="deep-supervision MSE weights for the 16/32/64 px bands", + ) + parser.add_argument( + "--cond-dropout-prob", type=float, default=0.0, + help="per-sample probability of swapping context/global_vector for " + "the learned null tokens (DGF)", + ) + parser.add_argument( + "--photometric-head", action="store_true", + help="global exposure controllable (log-gain, bias) on the output, " + "predicted from Phase-1 global_condition + photometric_state", + ) + parser.add_argument( + "--photometric-dropout", type=float, default=0.0, + help="per-sample probability of zeroing the photometric head (identity path)", + ) + parser.add_argument( + "--fine-chroma-space", choices=("uv", "hv"), default="uv", + help="chroma planes for --fine-chroma-weight: BT.601 UV or HVI HV (k=0.2)", + ) + parser.add_argument( + "--identity-exposure-jitter", type=float, default=0.0, + help="identity pairs get a random global gain exp(U(-j, j)) applied to input AND target", + ) + parser.add_argument( + "--extra-clean-root", default=None, + help="folder of extra clean images used for identity pairs (e.g. Snow100K gt)", + ) + parser.add_argument( + "--extra-clean-prob", type=float, default=0.5, + help="probability that an identity pair is drawn from --extra-clean-root", + ) + parser.add_argument( + "--exposure-pregain", action="store_true", + help="v10: per-image input gain (Retinex-style) predicted from Phase-1 " + "vectors + whole-frame luma statistics, applied before the trunk", + ) + parser.add_argument( + "--pregain-dropout", type=float, default=0.0, + help="per-sample probability of forcing the pre-gain to 1 (identity path)", + ) + parser.add_argument( + "--pregain-max-log-gain", type=float, default=1.6, + help="tanh bound of the pre-gain log-gain (1.6 = x0.2 .. x5)", + ) + parser.add_argument( + "--pregain-target-weight", type=float, default=0.0, + help="v11: weight of the supervised pre-gain loss (log-gain vs clamped log " + "luma ratio clean/degraded); 0 = end-to-end only", + ) + parser.add_argument( + "--colour-head", action="store_true", + help="v12: per-image global colour transform (3x3 + bias) on the output, " + "predicted from Phase-1 vectors + whole-frame luma statistics", + ) + parser.add_argument("--colour-dropout", type=float, default=0.0, + help="per-sample probability of forcing the colour head to identity") + parser.add_argument("--colour-target-weight", type=float, default=0.0, + help="weight of the supervised colour-head loss (least-squares target per image)") + parser.add_argument( + "--global-attention-scales", default="", + help="v10: comma-separated stage indices (0..3) that get a zero-init " + "whole-map self-attention block after the LeWin blocks, e.g. 2,3", + ) + parser.add_argument( + "--extra-blocks-per-stage", default="", + help="v11: LeWin blocks appended per stage beyond the base 2, e.g. 0,2,4,4 " + "(zero-init adaLN -> identity at warm start; down and up paths)", + ) + parser.add_argument( + "--grad-checkpoint", action="store_true", + help="v11: recompute transformer blocks in backward (single-process runs only " + "with torch 1.10 reentrant checkpoint + DDP find_unused)", + ) + parser.add_argument("--warmstart-v6", type=Path) + parser.add_argument("--warmstart-v6-sha256") + parser.add_argument( + "--backbone", choices=("conv", "uformer"), default="conv" + ) + parser.add_argument( + "--allow-scratch", action="store_true", + help="permit training without a warm start (uformer backbone)", + ) + return parser + + +@contextlib.contextmanager +def _installed_v7_backend(args: argparse.Namespace) -> Iterator[None]: + replacements = { + "_build_restorer": _build_v7_restorer, + "_architecture": _v7_architecture, + "_schedule_config": _v7_schedule_config, + "_data_plan": v6._moe_data_plan, + "sample_restoration": sample_unified_restoration, + } + originals = {name: getattr(v4, name) for name in replacements} + try: + for name, replacement in replacements.items(): + setattr(v4, name, replacement) + yield + finally: + for name, original in originals.items(): + setattr(v4, name, original) + + +def run(args: argparse.Namespace) -> None: + v4.validate_runtime_args(args) + if int(args.timesteps) != 2: + raise ValueError("v7 is a two-step process; pass --timesteps 2") + for name in ("fine_l1_weight", "fine_vgg_weight"): + if float(getattr(args, name)) < 0: + raise ValueError("%s must be non-negative" % name) + has_path = args.warmstart_v6 is not None + has_sha = args.warmstart_v6_sha256 is not None + if has_path != has_sha: + raise ValueError("warmstart path and sha256 go together") + with _installed_v7_backend(args): + v4.run(args) + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(build_parser().parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/train_refiner_a.py b/dataset/phase1_noise_20260906/code/train_refiner_a.py new file mode 100644 index 0000000000000000000000000000000000000000..2c95a885a1a861444cab175ab49507bbc5687e47 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/train_refiner_a.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Two-stage trainer for the option-A refiner decoder. + +Stage ``pretrain`` — decoder learns a natural-image prior first: clean crops + with light synthetic corruption -> clean, L1+VGG loss. +Stage ``finetune`` — frozen Phase-1 + frozen v4 U-Net produce the one-step + x0 regression on the fly; the refiner maps + (x0_hat, degraded) -> clean with the same loss. + +The one-step regressor with record-keyed noise reproduces the measured +22.68 dB macro baseline, and the refiner's zero-init head starts the full +pipeline exactly there. +""" + +from __future__ import annotations + +import argparse +import json +import math +import time +from pathlib import Path +from typing import Dict, Iterable, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn +import torch.nn.functional as F +from torch.utils.data import DataLoader + +import train_phase2_graph_resshift_v4 as v4 +from src.data.phase2_v4 import ( + DeterministicBalancedBatchSampler, + Phase2PairDataset, + load_train_val_manifest, +) +from src.models.restoration.refiner_decoder import ( + REFINER_VERSION, + RefinerDecoder, + VGGPerceptualLoss, +) + +V4_RUN = Path("outputs/phase2_graph_resshift_v4/gate_d5_seed42") + + +def light_corruption(clean: Tensor, generator: torch.Generator) -> Tensor: + """Mild, deterministic corruption for the natural-image-prior pretrain.""" + kind = int(torch.randint(0, 3, (1,), generator=generator)) + if kind == 0: + return clean.clone() + if kind == 1: + sigma = float(torch.empty(1).uniform_(0.005, 0.03, generator=generator)) + noise = torch.randn( + tuple(clean.shape), generator=generator, dtype=torch.float32 + ).to(clean.device) + return (clean + sigma * noise).clamp(0.0, 1.0) + sigma = float(torch.empty(1).uniform_(0.4, 1.2, generator=generator)) + size = int(2 * round(2 * sigma) + 1) + offsets = torch.arange(size, dtype=torch.float32) - size // 2 + kernel = torch.exp(-offsets.square() / (2 * sigma * sigma)) + kernel = (kernel / kernel.sum()).to(clean.device) + pad = size // 2 + row = kernel.view(1, 1, 1, size).expand(3, 1, 1, size) + col = kernel.view(1, 1, size, 1).expand(3, 1, size, 1) + blurred = F.conv2d(F.pad(clean, (pad, pad, 0, 0), mode="reflect"), row, groups=3) + return F.conv2d(F.pad(blurred, (0, 0, pad, pad), mode="reflect"), col, groups=3) + + +@torch.no_grad() +def one_step_x0( + model: nn.Module, + phase1, + degraded: Tensor, + record_ids: Sequence[str], + seed: int, + stage: str, +) -> Tensor: + """Single x0 prediction from u_T with record-keyed noise (frozen).""" + if hasattr(model, "effective_kappa"): + import train_phase2_graph_moe_v6 as v6 + + return v6.sample_moe_restoration( + model, phase1, degraded, seed=seed, + record_ids=list(record_ids), amp_enabled=degraded.is_cuda, + ) + padded, size = v4.pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + condition = model.build_condition(representation) + uy = v4.pixel_unshuffle2(padded) + noise = v4._noise_for_records(uy, list(record_ids), seed=seed, stage=stage) + eta_terminal = model.schedule.eta[-1].to(uy.device, uy.dtype) + kappa = model.schedule.kappa.to(uy.device, uy.dtype) + u_terminal = uy + kappa * torch.sqrt(eta_terminal) * noise + timesteps = torch.full( + (uy.shape[0],), model.schedule.timesteps, device=uy.device, dtype=torch.long + ) + u0_hat = model.predict_x0(u_terminal, uy, timesteps, condition) + out = v4.pixel_shuffle2(u0_hat) + height, width = size + return out[..., :height, :width].clamp(0.0, 1.0) + + +def load_frozen_regressor(device: torch.device, kind: str = "v4", run_dir: Path = None): + run_dir = Path(run_dir) if run_dir is not None else V4_RUN + cfg = json.loads((run_dir / "run_config.json").read_text()) + args = argparse.Namespace(**cfg) + for key in ("manifest", "data_root", "phase1_checkpoint"): + setattr(args, key, Path(str(getattr(args, key)))) + if kind == "v4": + model = v4._build_restorer(args, device) + elif kind == "v6": + import train_phase2_graph_moe_v6 as v6 + + for key in ("warmstart_v4", "resume", "init_checkpoint"): + if getattr(args, key, None) is not None: + setattr(args, key, Path(str(getattr(args, key)))) + args.resume = run_dir / "best.pt" + model = v6._build_moe_restorer(args, device) + model.eval_sample_steps = 1 + else: + raise ValueError("regressor kind must be v4 or v6") + checkpoint = v4._torch_load(run_dir / "best.pt") + model.load_state_dict(checkpoint["ema_state_dict"]["shadow"], strict=True) + model.eval() + for parameter in model.parameters(): + parameter.requires_grad_(False) + phase1, _ = v4.build_frozen_phase1( + args.phase1_checkpoint, args.phase1_sha256, device + ) + return model, phase1, args + + +def build_loaders(args, splits, batch_size: int, steps: int, seed: int): + train_dataset = Phase2PairDataset( + splits.train, crop_size=256, training=True, upscale_small=True + ) + sampler = DeterministicBalancedBatchSampler( + [record.label for record in splits.train] + if hasattr(splits.train[0], "label") + else [record.degradation for record in splits.train], + batch_size=batch_size, + steps=steps, + seed=seed, + ) + train_loader = DataLoader( + train_dataset, batch_sampler=sampler, num_workers=6, pin_memory=True + ) + val_loader = DataLoader( + Phase2PairDataset(splits.val, crop_size=256, training=False, upscale_small=True), + batch_size=8, shuffle=False, num_workers=4, pin_memory=True, + ) + return train_loader, val_loader + + +@torch.no_grad() +def evaluate( + refiner: RefinerDecoder, + regressor, + phase1, + loader: DataLoader, + device: torch.device, + eval_seed: int, +) -> Dict[str, object]: + refiner.eval() + per_domain: Dict[str, Dict[str, list]] = {} + for batch in loader: + degraded = batch["degraded"].to(device) + clean = batch["clean"].to(device) + record_ids = [str(value) for value in batch["record_id"]] + domains = [str(value) for value in batch["degradation"]] + x0_hat = one_step_x0( + regressor, phase1, degraded, record_ids, eval_seed, "initial" + ) + refined = refiner(x0_hat, degraded) + base_psnr = v4.rgb_psnr_per_image(x0_hat, clean).cpu().tolist() + ref_psnr = v4.rgb_psnr_per_image(refined, clean).cpu().tolist() + ref_ssim = v4.rgb_ssim_per_image(refined, clean).cpu().tolist() + for index, domain in enumerate(domains): + slot = per_domain.setdefault( + domain, {"base": [], "psnr": [], "ssim": []} + ) + slot["base"].append(base_psnr[index]) + slot["psnr"].append(ref_psnr[index]) + slot["ssim"].append(ref_ssim[index]) + summary: Dict[str, object] = {"per_domain": {}} + macro_p, macro_s, macro_b = [], [], [] + for domain, values in sorted(per_domain.items()): + base = sum(values["base"]) / len(values["base"]) + psnr = sum(values["psnr"]) / len(values["psnr"]) + ssim = sum(values["ssim"]) / len(values["ssim"]) + summary["per_domain"][domain] = { + "one_step_psnr": base, "refined_psnr": psnr, "refined_ssim": ssim, + "delta": psnr - base, "count": len(values["psnr"]), + } + macro_p.append(psnr) + macro_s.append(ssim) + macro_b.append(base) + summary["macro_refined_psnr"] = sum(macro_p) / len(macro_p) + summary["macro_refined_ssim"] = sum(macro_s) / len(macro_s) + summary["macro_one_step_psnr"] = sum(macro_b) / len(macro_b) + refiner.train() + return summary + + +def append_jsonl(payload: Dict[str, object], path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload, sort_keys=True) + "\n") + + +def run_stage( + stage: str, + refiner: RefinerDecoder, + perceptual: Optional[VGGPerceptualLoss], + regressor, + phase1, + loaders, + device: torch.device, + output_dir: Path, + args, +) -> None: + train_loader, val_loader = loaders + steps = args.pretrain_steps if stage == "pretrain" else args.finetune_steps + optimizer = torch.optim.AdamW( + refiner.parameters(), lr=args.lr, betas=(0.9, 0.99), weight_decay=1e-4 + ) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=max(1, steps), eta_min=args.lr * 0.01 + ) + best_macro = -1.0 + refiner.train() + iterator = iter(train_loader) + started = time.time() + for step in range(1, steps + 1): + batch = next(iterator) + clean = batch["clean"].to(device, non_blocking=True) + if stage == "pretrain": + generator = torch.Generator() + generator.manual_seed(args.seed * 100003 + step) + corrupted = light_corruption(clean, generator) + x0_hat, degraded = corrupted, corrupted + else: + degraded = batch["degraded"].to(device, non_blocking=True) + record_ids = [str(value) for value in batch["record_id"]] + x0_hat = one_step_x0( + regressor, phase1, degraded, record_ids, args.seed, step + ) + refined = refiner(x0_hat, degraded) + loss = F.l1_loss(refined, clean) + if perceptual is not None: + loss = loss + args.perceptual_weight * perceptual(refined, clean) + optimizer.zero_grad(set_to_none=True) + loss.backward() + torch.nn.utils.clip_grad_norm_(refiner.parameters(), 1.0) + optimizer.step() + scheduler.step() + if step % 50 == 0: + append_jsonl( + {"event": "train", "stage": stage, "step": step, + "loss": float(loss.detach()), + "lr": float(optimizer.param_groups[0]["lr"]), + "time": time.time()}, + output_dir / "metrics.jsonl", + ) + if stage == "finetune" and (step % args.eval_every == 0 or step == steps): + summary = evaluate( + refiner, regressor, phase1, val_loader, device, args.eval_seed + ) + summary.update({"event": "evaluation", "stage": stage, "step": step, + "time": time.time()}) + append_jsonl(summary, output_dir / "metrics.jsonl") + print(json.dumps( + {k: summary[k] for k in + ("step", "macro_one_step_psnr", "macro_refined_psnr", + "macro_refined_ssim")}, + sort_keys=True), flush=True) + if summary["macro_refined_psnr"] > best_macro: + best_macro = float(summary["macro_refined_psnr"]) + torch.save( + {"refiner_state_dict": refiner.state_dict(), + "stage": stage, "step": step, + "refiner_version": REFINER_VERSION, + "macro_refined_psnr": best_macro, + "config": vars(args)}, + str(output_dir / "refiner_best.pt"), + ) + torch.save( + {"refiner_state_dict": refiner.state_dict(), "stage": stage, + "step": steps, "refiner_version": REFINER_VERSION, + "config": vars(args)}, + str(output_dir / ("refiner_%s_last.pt" % stage)), + ) + print("stage %s done in %.1fs" % (stage, time.time() - started), flush=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--stage", choices=("pretrain", "finetune", "both"), + default="both") + parser.add_argument("--pretrain-steps", type=int, default=3000) + parser.add_argument("--finetune-steps", type=int, default=12000) + parser.add_argument("--batch-size", type=int, default=8) + parser.add_argument("--lr", type=float, default=2e-4) + parser.add_argument("--perceptual-weight", type=float, default=0.1) + parser.add_argument("--no-perceptual", action="store_true") + parser.add_argument("--eval-every", type=int, default=500) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--eval-seed", type=int, default=20260830) + parser.add_argument("--init-refiner", type=Path, default=None) + parser.add_argument("--regressor", choices=("v4", "v6"), default="v4") + parser.add_argument("--regressor-run", type=Path, default=None) + args = parser.parse_args() + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + output_dir = args.output_dir + output_dir.mkdir(parents=True, exist_ok=True) + (output_dir / "run_config.json").write_text( + json.dumps({k: str(v) for k, v in vars(args).items()}, + indent=2, sort_keys=True) + ) + torch.manual_seed(args.seed) + + regressor, phase1, v4_args = load_frozen_regressor( + device, kind=args.regressor, run_dir=args.regressor_run + ) + splits = load_train_val_manifest(v4_args.manifest) + total_steps = args.pretrain_steps + args.finetune_steps + loaders = build_loaders(args, splits, args.batch_size, total_steps, args.seed) + + refiner = RefinerDecoder().to(device) + if args.init_refiner is not None: + state = torch.load(str(args.init_refiner), map_location="cpu") + refiner.load_state_dict(state["refiner_state_dict"], strict=True) + print("initialized refiner from", args.init_refiner, flush=True) + perceptual = None + if not args.no_perceptual: + perceptual = VGGPerceptualLoss().to(device) + + if args.stage in ("pretrain", "both"): + run_stage("pretrain", refiner, perceptual, regressor, phase1, + loaders, device, output_dir, args) + if args.stage in ("finetune", "both"): + run_stage("finetune", refiner, perceptual, regressor, phase1, + loaders, device, output_dir, args) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/visualize_degradation_table.py b/dataset/phase1_noise_20260906/code/visualize_degradation_table.py new file mode 100644 index 0000000000000000000000000000000000000000..69f13909756cc7cb64710a11787d26e624d68290 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/visualize_degradation_table.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Overview table of the four degradation domains in the SCDC training data. + +One row per domain (haze / low-light / noise / rain), N deterministic samples +per row (evenly spaced over the record-id-sorted validation list — no +cherry-picking), each shown as the whole native frame: Degraded | Clean. +Cells are resized-to-cover and center-cropped to a fixed 3:2 box so frames of +different aspect ratios line up; the caption carries dataset, native size and +the degraded-vs-clean PSNR of the full frame. +""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import List, Sequence + +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +from src.data.phase2_v4 import load_train_val_manifest + +DOMAIN_ORDER = ("haze", "lowlight", "noise", "rain") +DOMAIN_LABELS = { + "haze": "Haze", + "lowlight": "Low-light", + "noise": "Noise", + "rain": "Rain", +} +_LANCZOS = getattr(getattr(Image, "Resampling", Image), "LANCZOS") + + +def _select_indices(count: int, per_domain: int) -> List[int]: + if count <= per_domain: + return list(range(count)) + if per_domain == 1: + return [count // 2] + step = (count - 1) / (per_domain - 1) + return sorted({int(round(position * step)) for position in range(per_domain)}) + + +def _native_crop_at( + image: Image.Image, width: int, height: int, fx: float = 0.5, fy: float = 0.5 +) -> Image.Image: + """Native-resolution crop whose center sits at fraction (fx, fy) of the frame.""" + left = int(round(fx * (image.width - width))) + top = int(round(fy * (image.height - height))) + return image.crop((left, top, left + width, top + height)) + + +def _cover(image: Image.Image, width: int, height: int) -> Image.Image: + scale = max(width / image.width, height / image.height) + resized = image.resize( + (max(width, int(math.ceil(image.width * scale))), + max(height, int(math.ceil(image.height * scale)))), + _LANCZOS, + ) + left = (resized.width - width) // 2 + top = (resized.height - height) // 2 + return resized.crop((left, top, left + width, top + height)) + + +def _cell_view( + image: Image.Image, width: int, height: int, native_threshold: float, + anchor=(0.5, 0.5), +): + """Whole frame (resize-to-cover) unless the frame is so much larger than the + cell that fine degradations (sensor noise, thin streaks) would be averaged + away by the downscale — then show a native-resolution center crop.""" + if min(image.width / width, image.height / height) >= native_threshold: + return _native_crop_at(image, width, height, *anchor), "native crop" + return _cover(image, width, height), "full frame" + + +def _pick_diverse(records, per_domain: int): + """Evenly spaced picks, but prefer one record per scene (split_group) + when the domain has at least per_domain distinct scenes.""" + groups = {} + for record in records: + groups.setdefault(record.split_group, []).append(record) + if len(groups) < per_domain: + return [records[i] for i in _select_indices(len(records), per_domain)] + keys = sorted(groups) + return [groups[keys[i]][0] for i in _select_indices(len(keys), per_domain)] + + +def _psnr(a: Image.Image, b: Image.Image) -> float: + x = np.asarray(a, dtype=np.float64) / 255.0 + y = np.asarray(b, dtype=np.float64) / 255.0 + mse = float(np.mean((x - y) ** 2)) + return 99.0 if mse <= 0 else 10.0 * math.log10(1.0 / mse) + + +def _font(size: int) -> ImageFont.ImageFont: + for candidate in ( + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/dejavu/DejaVuSans.ttf", + "/Library/Fonts/Arial.ttf", + ): + if Path(candidate).is_file(): + return ImageFont.truetype(candidate, size) + return ImageFont.load_default() + + +def build_table( + records_by_domain, per_domain: int, cell_w: int, cell_h: int, output: Path, + native_threshold: float = 3.0, +) -> dict: + pad, gap, label_w, header_h, caption_h = 16, 6, 150, 34, 30 + grid_w = per_domain * (2 * cell_w + gap) + (per_domain - 1) * 3 * gap + width = pad + label_w + grid_w + pad + height = pad + header_h + len(DOMAIN_ORDER) * (cell_h + caption_h + gap) + pad + canvas = Image.new("RGB", (width, height), (244, 245, 246)) + draw = ImageDraw.Draw(canvas) + font_h, font_c, font_l = _font(15), _font(12), _font(17) + summary = {} + for column in range(per_domain): + x0 = pad + label_w + column * (2 * cell_w + gap + 3 * gap) + draw.text((x0 + 4, pad + 8), "Degraded", fill=(199, 93, 58), font=font_h) + draw.text((x0 + cell_w + gap + 4, pad + 8), "Clean (GT)", fill=(38, 48, 66), font=font_h) + for row, domain in enumerate(DOMAIN_ORDER): + records = records_by_domain.get(domain, []) + picked = _pick_diverse(records, per_domain) + y0 = pad + header_h + row * (cell_h + caption_h + gap) + draw.text((pad, y0 + cell_h // 2 - 10), DOMAIN_LABELS[domain], fill=(38, 48, 66), font=font_l) + draw.text((pad, y0 + cell_h // 2 + 12), "%d val pairs" % len(records), fill=(107, 114, 128), font=font_c) + rows = [] + for column, record in enumerate(picked): + degraded = Image.open(record.degraded).convert("RGB") + clean = Image.open(record.clean).convert("RGB") + psnr = _psnr(degraded, clean) + x0 = pad + label_w + column * (2 * cell_w + gap + 3 * gap) + # Slide the native-crop window across the frame per column so a + # domain with few distinct scenes still shows different content. + anchor = ((column + 1.0) / (per_domain + 1.0), 0.35 if column % 2 == 0 else 0.65) + view_d, view_kind = _cell_view(degraded, cell_w, cell_h, native_threshold, anchor) + view_c, _ = _cell_view(clean, cell_w, cell_h, native_threshold, anchor) + canvas.paste(view_d, (x0, y0)) + canvas.paste(view_c, (x0 + cell_w + gap, y0)) + caption = "%s %dx%d PSNR %.1f dB [%s]" % ( + record.dataset, degraded.width, degraded.height, psnr, view_kind + ) + draw.text((x0 + 2, y0 + cell_h + 6), caption, fill=(55, 65, 81), font=font_c) + rows.append({ + "record_id": record.record_id, "dataset": record.dataset, + "size": [degraded.width, degraded.height], "psnr_degraded": psnr, + "view": view_kind, "split_group": record.split_group, + }) + summary[domain] = rows + canvas.save(str(output)) + return summary + + +def main(argv: Sequence[str] = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, default=Path("outputs/phase2_v7/uformer_dgf8k_seed42")) + parser.add_argument("--output", type=Path, default=Path("outputs/degradation_table.png")) + parser.add_argument("--per-domain", type=int, default=4) + parser.add_argument("--cell-width", type=int, default=240) + parser.add_argument("--cell-height", type=int, default=160) + parser.add_argument("--split", choices=("val", "train"), default="val") + parser.add_argument( + "--native-threshold", type=float, default=3.0, + help="show a native-res center crop when the frame is >= this many times the cell", + ) + args = parser.parse_args(argv) + + config = json.loads((args.run_dir / "run_config.json").read_text()) + splits = load_train_val_manifest(Path(config["manifest"])) + records = splits.val if args.split == "val" else splits.train + by_domain = {} + for record in records: + by_domain.setdefault(record.degradation, []).append(record) + for domain in by_domain: + by_domain[domain].sort(key=lambda r: r.record_id) + args.output.parent.mkdir(parents=True, exist_ok=True) + summary = build_table( + by_domain, args.per_domain, args.cell_width, args.cell_height, args.output, + native_threshold=args.native_threshold, + ) + (args.output.with_suffix(".json")).write_text(json.dumps(summary, indent=2)) + for domain, rows in summary.items(): + print(domain, ", ".join("%s %dx%d %.1f dB %s" % (r["dataset"], r["size"][0], r["size"][1], r["psnr_degraded"], r["view"]) for r in rows)) + print("saved", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/visualize_phase1_graph.py b/dataset/phase1_noise_20260906/code/visualize_phase1_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..6c730ab0840c0a6665ddefc7f1948259ac3092b9 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/visualize_phase1_graph.py @@ -0,0 +1,380 @@ +#!/usr/bin/env python3 +"""Sanity dashboard for the Phase-1 Blind Degradation Graph Encoder. + +Answers, with pictures, whether the graph representation is *plausible* on +its own terms, independent of how many dB it buys Phase-2: + + cases_.png per image: input | routing over the 6 nodes | severity + per branch | 4 spatial maps (16x16) | unknown-residual + norm — for degraded inputs AND their clean GT + (a sane encoder must react differently to the two). + confusion.png routing argmax share: true domain (and clean GT of each + domain) x node, over the whole validation set. + severity_calibration.png + predicted severity of the true branch vs raw residual + MAE |y - x| with Spearman rho per domain (calibration-free). + severity_ramp.png monotonic synthetic ramps on clean val images (noise + sigma, haze transmission, low-light gain, rain streaks): + mean severity and routing mass of every branch vs level. + ood.png synthetic unknown degradations (snow / blur / pixelate / + sharpen, from train_graph_encoder_v2.synthesize_ood): + where does the mass go — free slots or a known branch? + summary.json every aggregate number behind the figures. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path +from typing import Dict, List, Sequence + +import numpy as np +import torch +import torch.nn.functional as F + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest + +NODES = ("rain", "noise", "haze", "lowlight", "free1", "free2") +DOMAINS = ("rain", "noise", "haze", "lowlight") +COLORS = {"rain": "#2a78d6", "noise": "#eb6834", "haze": "#1baf7a", + "lowlight": "#eda100", "free1": "#9aa3af", "free2": "#6b7280"} +LABELS = {"rain": "Rain", "noise": "Noise", "haze": "Haze", "lowlight": "Low-light", + "free1": "Free-1", "free2": "Free-2"} + + +# --------------------------------------------------------------------------- # +# inference helpers +# --------------------------------------------------------------------------- # +@torch.no_grad() +def encode(phase1, images: torch.Tensor, batch: int = 16) -> Dict[str, torch.Tensor]: + out: Dict[str, List[torch.Tensor]] = { + "routing": [], "severity": [], "spatial": [], "residual_norm": []} + for start in range(0, images.shape[0], batch): + rep = phase1(images[start:start + batch]) + out["routing"].append(rep.routing_probs.float().cpu()) + out["severity"].append(rep.severity_coords.float().cpu()) + out["spatial"].append(rep.spatial_maps.float().cpu()) + out["residual_norm"].append(rep.unknown_residual.float().norm(dim=-1).cpu()) + return {k: torch.cat(v) for k, v in out.items()} + + +def spearman(a: Sequence[float], b: Sequence[float]) -> float: + if len(a) < 3: + return float("nan") + ra = np.argsort(np.argsort(a)).astype(np.float64) + rb = np.argsort(np.argsort(b)).astype(np.float64) + ra -= ra.mean(); rb -= rb.mean() + denom = math.sqrt(float((ra ** 2).sum() * (rb ** 2).sum())) + return float((ra * rb).sum() / denom) if denom > 0 else float("nan") + + +# --------------------------------------------------------------------------- # +# synthetic ramps (simple, monotonic, physically motivated) +# --------------------------------------------------------------------------- # +def ramp_noise(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + noise = torch.randn(clean.shape, generator=gen) * level + return (clean + noise.to(clean.device)).clamp(0, 1) + + +def ramp_haze(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + transmission = 1.0 - level # level 0 -> clear, 0.75 -> dense + airlight = 0.9 + return (clean * transmission + airlight * (1.0 - transmission)).clamp(0, 1) + + +def ramp_lowlight(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + gain = 1.0 - level # level 0 -> unchanged, 0.94 -> near black + return (clean * gain).clamp(0, 1) + + +def ramp_rain(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + if level <= 0: + return clean + b, _, h, w = clean.shape + seeds = (torch.rand((b, 1, h, w), generator=gen) < 0.002 * (1 + 4 * level)).float() + kernel = torch.zeros(1, 1, 15, 15) + for i in range(15): # a slanted streak PSF + j = min(14, max(0, int(round(i * 0.35)) + 4)) + kernel[0, 0, i, j] = 1.0 + kernel = kernel / kernel.sum() + streaks = F.conv2d(seeds, kernel, padding=7) + streaks = streaks / (streaks.amax(dim=(2, 3), keepdim=True) + 1e-6) + streaks = streaks.to(clean.device) * (0.35 + 0.65 * level) + return (clean + streaks).clamp(0, 1) + + +def make_transplant_ramp(residuals: torch.Tensor): + """Real degradation residuals (degraded - clean of val pairs) added to a + clean pool with a gain: level 1 = the real residual, >1 amplified.""" + def fn(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + idx = torch.randint(0, residuals.shape[0], (clean.shape[0],), generator=gen) + return (clean + level * residuals[idx].to(clean.device)).clamp(0, 1) + return fn + + +RAMPS = { + "noise": (ramp_noise, [0.0, 0.01, 0.02, 0.04, 0.08, 0.12]), + "haze": (ramp_haze, [0.0, 0.15, 0.3, 0.45, 0.6, 0.75]), + "lowlight": (ramp_lowlight, [0.0, 0.3, 0.5, 0.7, 0.85, 0.94]), + "rain": (ramp_rain, [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]), +} +TRANSPLANT_LEVELS = [0.0, 0.25, 0.5, 0.75, 1.0, 1.5] +RAMP_TITLES = { + "noise": "Gaussian noise (sigma)", "haze": "uniform haze (1 - t)", + "lowlight": "gain reduction", "rain": "synthetic streaks", + "noise_real": "REAL SIDD residual x gain", "rain_real": "REAL Rain13K residual x gain", +} + + +# --------------------------------------------------------------------------- # +# figures +# --------------------------------------------------------------------------- # +def _bars(ax, values: Sequence[float], names: Sequence[str], ylim=(0, 1), title=""): + pos = np.arange(len(values)) + ax.bar(pos, values, color=[COLORS[n] for n in names], width=0.7) + ax.set_xticks(pos) + ax.set_xticklabels([LABELS[n][:5] for n in names], fontsize=7) + ax.set_ylim(*ylim) + ax.tick_params(axis="y", labelsize=7) + if title: + ax.set_title(title, fontsize=8) + + +def fig_cases(plt, images, clean, enc_deg, enc_cln, ids, domain, path: Path): + n = images.shape[0] + fig, axes = plt.subplots(2 * n, 5, figsize=(15, 2.9 * 2 * n), squeeze=False) + for i in range(n): + for row, (img, enc, tag) in enumerate(( + (images[i], enc_deg, "degraded"), (clean[i], enc_cln, "clean GT"))): + r = 2 * i + row + axes[r][0].imshow(img.permute(1, 2, 0).numpy()) + axes[r][0].set_title("%s — %s" % (ids[i][:14], tag), fontsize=8) + _bars(axes[r][1], enc["routing"][i].tolist(), NODES, title="routing (softmax over 6 nodes)") + _bars(axes[r][2], enc["severity"][i].tolist(), DOMAINS, title="severity per branch") + mosaic = torch.cat([ + torch.cat([enc["spatial"][i][0], enc["spatial"][i][1]], dim=1), + torch.cat([enc["spatial"][i][2], enc["spatial"][i][3]], dim=1)], dim=0) + axes[r][3].imshow(mosaic.numpy(), vmin=0, vmax=1, cmap="magma") + maxes = enc["spatial"][i].amax(dim=(1, 2)).tolist() + axes[r][3].set_title("spatial 16x16 [rain noise / haze low]\nmax %.2f %.2f / %.2f %.2f" % tuple(maxes), fontsize=7) + top = int(enc["routing"][i].argmax()) + overlay = enc["spatial"][i][min(top, 3)] + up = F.interpolate(overlay[None, None], size=img.shape[-2:], mode="bilinear", + align_corners=False)[0, 0] + axes[r][4].imshow(img.permute(1, 2, 0).numpy()) + axes[r][4].imshow(up.numpy(), vmin=0, vmax=1, cmap="magma", alpha=0.45) + axes[r][4].set_title("map of top node (%s) |res| %.2f" % ( + LABELS[NODES[top]], float(enc["residual_norm"][i])), fontsize=8) + for c in (0, 3, 4): + axes[r][c].set_xticks(()); axes[r][c].set_yticks(()) + fig.suptitle("Phase-1 graph state — %s (val, center crops)" % LABELS[domain], fontsize=12) + fig.tight_layout(rect=(0, 0, 1, 0.98)) + fig.savefig(str(path), dpi=100) + plt.close(fig) + + +def fig_confusion(plt, matrix: np.ndarray, row_names: Sequence[str], path: Path): + fig, ax = plt.subplots(figsize=(7.5, 0.55 * len(row_names) + 1.6)) + ax.imshow(matrix, vmin=0, vmax=1, cmap="Blues", aspect="auto") + for r in range(matrix.shape[0]): + for c in range(matrix.shape[1]): + v = matrix[r, c] + ax.text(c, r, "%.2f" % v, ha="center", va="center", fontsize=8, + color="white" if v > 0.6 else "black") + ax.set_xticks(range(len(NODES))); ax.set_xticklabels([LABELS[n] for n in NODES], fontsize=8) + ax.set_yticks(range(len(row_names))); ax.set_yticklabels(row_names, fontsize=8) + ax.set_xlabel("routing argmax node", fontsize=9) + ax.set_title("Routing argmax share per input group (val)\nrows: degraded inputs, then clean GT of each domain", fontsize=10) + fig.tight_layout() + fig.savefig(str(path), dpi=110) + plt.close(fig) + + +def fig_calibration(plt, per_domain: Dict[str, Dict[str, List[float]]], path: Path): + fig, axes = plt.subplots(1, 4, figsize=(15, 3.6)) + for ax, d in zip(axes, DOMAINS): + x, y = per_domain[d]["raw_mae"], per_domain[d]["severity"] + ax.scatter(x, y, s=12, color=COLORS[d], alpha=0.75) + ax.set_title("%s rho=%.2f n=%d" % (LABELS[d], spearman(x, y), len(x)), fontsize=9) + ax.set_xlabel("raw residual MAE |y-x|", fontsize=8) + ax.set_ylabel("predicted severity (own branch)", fontsize=8) + ax.set_ylim(0, 1); ax.tick_params(labelsize=7) + fig.suptitle("Severity calibration on val (should rise with residual)", fontsize=11) + fig.tight_layout(rect=(0, 0, 1, 0.93)) + fig.savefig(str(path), dpi=110) + plt.close(fig) + + +def fig_ramp(plt, ramp: Dict[str, Dict[str, List[List[float]]]], path: Path): + keys = list(ramp.keys()) + fig, axes = plt.subplots(2, len(keys), figsize=(3.6 * len(keys), 6.2), squeeze=False) + for col, d in enumerate(keys): + levels = ramp[d]["levels"] + for j, n in enumerate(NODES): + axes[0][col].plot(range(len(levels)), [r[j] for r in ramp[d]["routing"]], + marker="o", ms=3, color=COLORS[n], label=LABELS[n]) + for j, b in enumerate(DOMAINS): + axes[1][col].plot(range(len(levels)), [s[j] for s in ramp[d]["severity"]], + marker="o", ms=3, color=COLORS[b], label=LABELS[b]) + for r, lab in ((0, "routing mass"), (1, "severity")): + axes[r][col].set_xticks(range(len(levels))) + axes[r][col].set_xticklabels(["%g" % v for v in levels], fontsize=7) + axes[r][col].set_ylim(0, 1); axes[r][col].tick_params(axis="y", labelsize=7) + axes[r][col].set_ylabel(lab, fontsize=8) + axes[0][col].set_title(RAMP_TITLES.get(d, d), fontsize=9) + axes[1][col].set_xlabel("level", fontsize=8) + axes[0][0].legend(fontsize=7, loc="upper left") + axes[1][0].legend(fontsize=7, loc="upper left") + fig.suptitle("Ramps on clean val images: the intended branch should rise alone (level 0 = clean)", fontsize=11) + fig.tight_layout(rect=(0, 0, 1, 0.94)) + fig.savefig(str(path), dpi=110) + plt.close(fig) + + +def fig_ood(plt, ood_examples, ood_mean: Dict[str, List[float]], path: Path): + kinds = list(ood_mean.keys()) + fig, axes = plt.subplots(2, len(kinds), figsize=(3.6 * len(kinds), 6.4), squeeze=False) + for c, k in enumerate(kinds): + axes[0][c].imshow(ood_examples[k].permute(1, 2, 0).numpy()) + axes[0][c].set_xticks(()); axes[0][c].set_yticks(()) + axes[0][c].set_title("OOD: %s" % k, fontsize=9) + _bars(axes[1][c], ood_mean[k], NODES, title="mean routing (n=%d)" % ood_examples["_n"]) + fig.suptitle("Unknown degradations: mass should land on the free nodes", fontsize=11) + fig.tight_layout(rect=(0, 0, 1, 0.93)) + fig.savefig(str(path), dpi=110) + plt.close(fig) + + +# --------------------------------------------------------------------------- # +def main() -> None: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", type=Path, default=Path("outputs/phase1_ll_v3/graph_encoder_best.pt")) + parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + parser.add_argument("--output-dir", type=Path, default=Path("outputs/phase1_vis")) + parser.add_argument("--per-domain", type=int, default=3) + parser.add_argument("--ramp-images", type=int, default=24) + parser.add_argument("--device", default="cuda") + args = parser.parse_args() + + device = torch.device(args.device) + sha = hashlib.sha256(args.checkpoint.read_bytes()).hexdigest() + phase1, _ = v4.build_frozen_phase1(args.checkpoint, sha, device) + args.output_dir.mkdir(parents=True, exist_ok=True) + + splits = load_train_val_manifest(args.manifest) + dataset = Phase2PairDataset(splits.val, crop_size=256, training=False, upscale_small=True) + by_domain: Dict[str, List[int]] = {} + for i, r in enumerate(splits.val): + by_domain.setdefault(r.degradation, []).append(i) + + summary: Dict[str, object] = {"checkpoint": str(args.checkpoint), "sha256": sha} + + # ---- whole-val pass: confusion + calibration ------------------------- # + conf_rows, conf_names = [], [] + calib: Dict[str, Dict[str, List[float]]] = {d: {"raw_mae": [], "severity": []} for d in DOMAINS} + per_domain_cache = {} + for d in DOMAINS: + idx = sorted(by_domain[d], key=lambda k: splits.val[k].record_id) + items = [dataset[k] for k in idx] + deg = torch.stack([it["degraded"] for it in items]).to(device) + cln = torch.stack([it["clean"] for it in items]).to(device) + enc_d, enc_c = encode(phase1, deg), encode(phase1, cln) + per_domain_cache[d] = (idx, items, deg.cpu(), cln.cpu(), enc_d, enc_c) + j = DOMAINS.index(d) + calib[d]["raw_mae"] = (deg - cln).abs().mean(dim=(1, 2, 3)).cpu().tolist() + calib[d]["severity"] = enc_d["severity"][:, j].tolist() + conf_rows.append(np.bincount(enc_d["routing"].argmax(1).numpy(), minlength=6) / len(idx)) + conf_names.append("%s input (n=%d)" % (LABELS[d], len(idx))) + for d in DOMAINS: + _, _, _, _, _, enc_c = per_domain_cache[d] + conf_rows.append(np.bincount(enc_c["routing"].argmax(1).numpy(), minlength=6) / enc_c["routing"].shape[0]) + conf_names.append("%s clean GT" % LABELS[d]) + matrix = np.stack(conf_rows) + fig_confusion(plt, matrix, conf_names, args.output_dir / "confusion.png") + fig_calibration(plt, calib, args.output_dir / "severity_calibration.png") + summary["confusion"] = {n: dict(zip(NODES, [float(v) for v in row])) for n, row in zip(conf_names, matrix)} + summary["severity_spearman"] = {d: spearman(calib[d]["raw_mae"], calib[d]["severity"]) for d in DOMAINS} + summary["mean_severity_own_branch"] = {d: float(np.mean(calib[d]["severity"])) for d in DOMAINS} + + # ---- per-domain case sheets ----------------------------------------- # + for d in DOMAINS: + idx, items, deg, cln, enc_d, enc_c = per_domain_cache[d] + count = len(idx) + picks = sorted({int(round(p * (count - 1) / max(1, args.per_domain - 1))) for p in range(args.per_domain)}) + sub = lambda enc: {k: v[picks] for k, v in enc.items()} + fig_cases(plt, deg[picks], cln[picks], sub(enc_d), sub(enc_c), + [items[k]["record_id"] for k in picks], d, args.output_dir / ("cases_%s.png" % d)) + + # ---- scene008 (external nearly clean) ------------------------------- # + p1_args = p1.build_parser().parse_args([]) + ext_splits = p1.build_data_splits(p1_args) + s8 = [r for r in ext_splits.locked_test if r.degradation == "noise"] + ds8 = ext.PairCropDataset(s8) + it8 = [ds8[i] for i in range(len(s8))] + deg8 = torch.stack([it["degraded"] for it in it8]).to(device) + cln8 = torch.stack([it["clean"] for it in it8]).to(device) + e8d, e8c = encode(phase1, deg8), encode(phase1, cln8) + picks8 = [0, len(s8) // 2, len(s8) - 1] + sub8 = lambda enc: {k: v[picks8] for k, v in enc.items()} + fig_cases(plt, deg8.cpu()[picks8], cln8.cpu()[picks8], sub8(e8d), sub8(e8c), + [it8[k]["record_id"] for k in picks8], "noise", args.output_dir / "cases_scene008.png") + summary["scene008"] = { + "input_routing_mean": dict(zip(NODES, e8d["routing"].mean(0).tolist())), + "clean_routing_mean": dict(zip(NODES, e8c["routing"].mean(0).tolist())), + "input_severity_mean": dict(zip(DOMAINS, e8d["severity"].mean(0).tolist())), + } + + # ---- ramps + OOD on a fixed clean pool ------------------------------ # + pool = [] + for d in DOMAINS: + _, _, _, cln, _, _ = per_domain_cache[d] + pool.append(cln[: args.ramp_images // 4]) + pool = torch.cat(pool).to(device) + ramps = dict(RAMPS) + for d in ("noise", "rain"): + _, _, deg_d, cln_d, _, _ = per_domain_cache[d] + ramps[d + "_real"] = (make_transplant_ramp(deg_d - cln_d), TRANSPLANT_LEVELS) + ramp_summary = {} + for d, (fn, levels) in ramps.items(): + routing_rows, severity_rows = [], [] + for level in levels: + gen = torch.Generator().manual_seed(1234) + enc = encode(phase1, fn(pool, level, gen)) + routing_rows.append(enc["routing"].mean(0).tolist()) + severity_rows.append(enc["severity"].mean(0).tolist()) + ramp_summary[d] = {"levels": levels, "routing": routing_rows, "severity": severity_rows} + fig_ramp(plt, ramp_summary, args.output_dir / "severity_ramp.png") + summary["ramps"] = ramp_summary + + ood_mean, ood_examples = {}, {"_n": int(pool.shape[0])} + for kind in p1.OOD_KINDS: + gen = torch.Generator().manual_seed(4321) + corrupted = p1.synthesize_ood(pool.cpu(), kind, gen).to(device) + enc = encode(phase1, corrupted) + ood_mean[kind] = enc["routing"].mean(0).tolist() + ood_examples[kind] = corrupted[0].cpu() + fig_ood(plt, ood_examples, ood_mean, args.output_dir / "ood.png") + summary["ood_routing_mean"] = {k: dict(zip(NODES, v)) for k, v in ood_mean.items()} + summary["clean_pool_routing_mean"] = dict(zip(NODES, encode(phase1, pool)["routing"].mean(0).tolist())) + + (args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2)) + print("spearman", json.dumps(summary["severity_spearman"])) + print("confusion rows:") + for n, row in zip(conf_names, matrix): + print(" %-24s %s" % (n, " ".join("%.2f" % v for v in row))) + print("ood:", json.dumps({k: [round(x, 2) for x in v] for k, v in ood_mean.items()})) + print("saved to", args.output_dir) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/visualize_phase2_tasks_v4.py b/dataset/phase1_noise_20260906/code/visualize_phase2_tasks_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..39fbb9e82b554c9eaa1f781915ad439fba9434b8 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/visualize_phase2_tasks_v4.py @@ -0,0 +1,866 @@ +#!/usr/bin/env python3 +"""Visualize Phase-2 v4 restoration quality for every degradation task. + +The utility reproduces the validation inference path exactly: frozen Phase 1, +EMA Phase-2 weights, validation center crops, and record-keyed diffusion noise. +Samples are selected without cherry-picking by baseline-PSNR quantiles after +deduplicating clean-image content. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from dataclasses import dataclass +from functools import wraps +from pathlib import Path +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple + +import numpy as np +import torch +from torch import Tensor + +from src.data.phase2_v4 import ( # noqa: E402 + Phase2PairDataset, + RestorationRecord, + load_train_val_manifest, + split_digest, + validate_clean_file_integrity, + validate_splits_against_checkpoint, +) +from src.models.restoration.graph_resshift_v4 import ( # noqa: E402 + GraphConditionerV4, + GraphResidualShiftUNetV4, + ResidualShiftSchedule, +) +from train_phase2_graph_resshift_v4 import ( # noqa: E402 + Phase2RestorationModule, + build_frozen_phase1, + rgb_psnr_per_image, + rgb_ssim_per_image, + sample_restoration, + validate_phase1_artifact_header, +) + + +DISPLAY_DOMAINS: Tuple[str, ...] = ("haze", "lowlight", "noise", "rain") +DOMAIN_LABELS = { + "haze": "Haze", + "lowlight": "Low-light", + "noise": "Noise", + "rain": "Rain", +} +QUANTILES: Tuple[float, ...] = (0.25, 0.50, 0.75) +QUANTILE_LABELS = ("P25 harder", "P50 median", "P75 easier") +METHOD_LABELS = ("Degraded", "Best EMA", "Final EMA", "Ground truth") +OKABE_ITO = ("#0072B2", "#D55E00", "#009E73", "#CC79A7") + + +def _pyplot() -> Any: + """Import matplotlib lazily so data/provenance helpers stay lightweight.""" + + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as pyplot + + return pyplot + + +def _close_new_figures(function: Callable[..., Any]) -> Callable[..., Any]: + """Close figures created by a renderer even when rendering raises.""" + + @wraps(function) + def wrapped(*args: Any, **kwargs: Any) -> Any: + pyplot = _pyplot() + existing = set(pyplot.get_fignums()) + try: + return function(*args, **kwargs) + finally: + for figure_number in set(pyplot.get_fignums()) - existing: + pyplot.close(figure_number) + + return wrapped + + +@dataclass(frozen=True) +class Candidate: + """One validation record and its degraded-input difficulty.""" + + index: int + domain: str + record_id: str + source_id: str + clean_content_sha256: str + baseline_psnr: float + + +@dataclass(frozen=True) +class SelectedSample: + """A quantile-selected sample with its display role.""" + + candidate: Candidate + quantile: float + quantile_label: str + + +def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(chunk_size), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _torch_load(path: Path) -> Dict[str, Any]: + try: + value = torch.load(str(path), map_location="cpu", weights_only=False) + except TypeError: + value = torch.load(str(path), map_location="cpu") + if not isinstance(value, dict): + raise ValueError("checkpoint root must be a dictionary") + return value + + +def validate_checkpoint_pair( + best: Mapping[str, Any], final: Mapping[str, Any] +) -> None: + """Reject weights that cannot be compared under one validation contract.""" + + for name, checkpoint in (("best", best), ("final", final)): + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("%s is not a Phase-2 v4 checkpoint" % name) + if checkpoint.get("condition_mode") != "full": + raise ValueError("%s checkpoint is not the full-conditioning arm" % name) + ema = checkpoint.get("ema_state_dict") + if not isinstance(ema, Mapping) or not isinstance(ema.get("shadow"), Mapping): + raise ValueError("%s checkpoint has no EMA shadow" % name) + immutable_keys = ( + "contract", + "architecture", + "schedule_config", + "phase1_sha256", + "phase1_metadata", + "train_digest", + "val_digest", + "init_model_hash", + ) + for key in immutable_keys: + if best.get(key) != final.get(key): + raise ValueError("checkpoint %s mismatch" % key) + if int(best.get("step", -1)) > int(final.get("step", -1)): + raise ValueError("best checkpoint cannot be newer than final checkpoint") + final_events = _evaluation_history(final) + selected_event = max(final_events, key=lambda event: float(event["macro_psnr"])) + if int(best.get("step", -1)) != int(selected_event["step"]): + raise ValueError("best checkpoint is not the macro-PSNR argmax") + best_events = _evaluation_history(best) + if int(best_events[-1]["step"]) != int(best["step"]): + raise ValueError("best checkpoint history does not end at its saved step") + if float(best_events[-1]["macro_psnr"]) != float(selected_event["macro_psnr"]): + raise ValueError("best checkpoint metric does not match final history") + + +def validate_control_checkpoint( + control: Mapping[str, Any], full: Mapping[str, Any] +) -> None: + """Pin a D0 control to the same initialization and validation contract.""" + + if control.get("schema_version") != 4 or control.get("phase") != 2: + raise ValueError("D0 control is not a Phase-2 v4 checkpoint") + if control.get("condition_mode") != "null": + raise ValueError("D0 control checkpoint must use null conditioning") + control_contract = dict(control.get("contract", {})) + full_contract = dict(full.get("contract", {})) + control_contract["condition_mode"] = "full" + if control_contract != full_contract: + raise ValueError("D0 control contract does not match D5") + immutable_keys = ( + "architecture", + "schedule_config", + "phase1_sha256", + "phase1_metadata", + "train_digest", + "val_digest", + "init_model_hash", + ) + for key in immutable_keys: + if control.get(key) != full.get(key): + raise ValueError("D0 control %s does not match D5" % key) + events = _evaluation_history(control) + if any(event.get("condition") != "null" for event in events): + raise ValueError("D0 evaluation history has a non-null condition") + if int(events[-1]["step"]) != int(control.get("step", -1)): + raise ValueError("D0 checkpoint history does not end at its saved step") + full_baseline = _evaluation_history(full)[0]["metrics"]["degraded_baseline"] + if any(event["metrics"]["degraded_baseline"] != full_baseline for event in events): + raise ValueError("D0 degraded baseline does not match D5") + + +def _deduplicate_clean_content(candidates: Sequence[Candidate]) -> List[Candidate]: + """Choose a median-severity representative for every distinct clean image.""" + + groups: Dict[str, List[Candidate]] = {} + for candidate in candidates: + groups.setdefault(candidate.clean_content_sha256, []).append(candidate) + result: List[Candidate] = [] + for clean_hash in sorted(groups): + group = groups[clean_hash] + target = float(np.median([value.baseline_psnr for value in group])) + result.append( + min( + group, + key=lambda value: ( + abs(value.baseline_psnr - target), + value.record_id, + ), + ) + ) + return result + + +def select_quantile_samples( + candidates: Sequence[Candidate], + quantiles: Sequence[float] = QUANTILES, +) -> List[SelectedSample]: + """Select unique records nearest requested PSNR quantiles deterministically.""" + + unique = _deduplicate_clean_content(candidates) + if len(unique) < len(quantiles): + raise ValueError("not enough distinct clean images for quantile selection") + values = np.asarray([item.baseline_psnr for item in unique], dtype=np.float64) + selected: List[SelectedSample] = [] + used = set() + for position, quantile in enumerate(quantiles): + if not 0.0 <= float(quantile) <= 1.0: + raise ValueError("quantiles must be in [0, 1]") + target = float(np.percentile(values, float(quantile) * 100.0)) + available = [item for item in unique if item.record_id not in used] + chosen = min( + available, + key=lambda item: ( + abs(item.baseline_psnr - target), + item.baseline_psnr, + item.record_id, + ), + ) + used.add(chosen.record_id) + label = ( + QUANTILE_LABELS[position] + if tuple(quantiles) == QUANTILES + else "P%02d" % int(round(float(quantile) * 100.0)) + ) + selected.append(SelectedSample(chosen, float(quantile), label)) + return selected + + +def _baseline_candidates( + records: Sequence[RestorationRecord], crop_size: int +) -> Tuple[List[Candidate], Dict[str, int], Dict[str, Dict[str, float]]]: + dataset = Phase2PairDataset( + records, crop_size=crop_size, training=False, upscale_small=True + ) + result: List[Candidate] = [] + counts = {domain: 0 for domain in DISPLAY_DOMAINS} + values: Dict[str, Dict[str, List[float]]] = { + domain: {"psnr": [], "ssim": []} for domain in DISPLAY_DOMAINS + } + for index, record in enumerate(records): + item = dataset[index] + degraded = item["degraded"].unsqueeze(0) + clean = item["clean"].unsqueeze(0) + psnr = float(rgb_psnr_per_image(degraded, clean).item()) + ssim = float(rgb_ssim_per_image(degraded, clean).item()) + result.append( + Candidate( + index=index, + domain=record.degradation, + record_id=record.record_id, + source_id=record.source_id, + clean_content_sha256=record.clean_content_sha256, + baseline_psnr=psnr, + ) + ) + counts[record.degradation] += 1 + values[record.degradation]["psnr"].append(psnr) + values[record.degradation]["ssim"].append(ssim) + summary = { + domain: { + metric: float(np.mean(values[domain][metric])) + for metric in ("psnr", "ssim") + } + for domain in DISPLAY_DOMAINS + } + return result, counts, summary + + +def validate_degraded_baseline( + checkpoint: Mapping[str, Any], + summary: Mapping[str, Mapping[str, float]], + counts: Mapping[str, int], + tolerance: float = 5e-5, +) -> None: + """Detect byte-level degraded-input drift through reported val metrics.""" + + expected = _evaluation_history(checkpoint)[0]["metrics"]["degraded_baseline"] + for domain in DISPLAY_DOMAINS: + expected_domain = expected["per_domain"][domain] + if int(expected_domain["count"]) != int(counts[domain]): + raise ValueError("%s validation count drift" % domain) + for metric in ("psnr", "ssim"): + if not math.isclose( + float(summary[domain][metric]), + float(expected_domain[metric]), + rel_tol=0.0, + abs_tol=float(tolerance), + ): + raise ValueError("%s degraded %s baseline drift" % (domain, metric)) + + +def _select_all_domains(candidates: Sequence[Candidate]) -> List[SelectedSample]: + selected: List[SelectedSample] = [] + for domain in DISPLAY_DOMAINS: + domain_candidates = [value for value in candidates if value.domain == domain] + if not domain_candidates: + raise ValueError("validation split has no %s samples" % domain) + selected.extend(select_quantile_samples(domain_candidates)) + return selected + + +def _load_selected_tensors( + records: Sequence[RestorationRecord], + selected: Sequence[SelectedSample], + crop_size: int, +) -> Tuple[Tensor, Tensor]: + chosen_records = [records[value.candidate.index] for value in selected] + dataset = Phase2PairDataset( + chosen_records, crop_size=crop_size, training=False, upscale_small=True + ) + items = [dataset[index] for index in range(len(dataset))] + degraded = torch.stack([item["degraded"] for item in items]) + clean = torch.stack([item["clean"] for item in items]) + return degraded, clean + + +def _build_ema_model( + checkpoint: Mapping[str, Any], device: torch.device +) -> Phase2RestorationModule: + architecture = checkpoint["architecture"] + schedule_config = checkpoint["schedule_config"] + model = Phase2RestorationModule( + GraphConditionerV4( + cond_dim=int(architecture["cond_dim"]), + stage_dims=tuple(int(value) for value in architecture["dims"]), + ), + GraphResidualShiftUNetV4( + dims=tuple(int(value) for value in architecture["dims"]), + cond_dim=int(architecture["cond_dim"]), + ), + ResidualShiftSchedule( + timesteps=int(schedule_config["timesteps"]), + eta_end=float(schedule_config["eta_end"]), + min_noise=float(schedule_config["min_noise"]), + power=float(schedule_config["power"]), + kappa=float(schedule_config["kappa"]), + ), + str(checkpoint["condition_mode"]), + ).to(device) + model.load_state_dict(checkpoint["ema_state_dict"]["shadow"], strict=True) + model.eval() + return model + + +def _restore_in_batches( + checkpoint: Mapping[str, Any], + phase1: torch.nn.Module, + degraded: Tensor, + record_ids: Sequence[str], + *, + device: torch.device, + seed: int, + batch_size: int, + amp_enabled: bool, +) -> Tensor: + model = _build_ema_model(checkpoint, device) + outputs: List[Tensor] = [] + try: + for start in range(0, degraded.shape[0], batch_size): + stop = min(start + batch_size, degraded.shape[0]) + restored = sample_restoration( + model, + phase1, + degraded[start:stop].to(device), + seed=seed, + record_ids=record_ids[start:stop], + amp_enabled=amp_enabled, + ) + outputs.append(restored.float().cpu()) + finally: + del model + if device.type == "cuda": + torch.cuda.empty_cache() + return torch.cat(outputs, dim=0) + + +def _metrics(prediction: Tensor, clean: Tensor) -> List[Dict[str, float]]: + psnr = rgb_psnr_per_image(prediction, clean).tolist() + ssim = rgb_ssim_per_image(prediction, clean).tolist() + return [ + {"psnr": float(psnr[index]), "ssim": float(ssim[index])} + for index in range(len(psnr)) + ] + + +def _image_array(tensor: Tensor) -> np.ndarray: + return tensor.detach().float().clamp(0.0, 1.0).permute(1, 2, 0).numpy() + + +def _crop_sha256(tensor: Tensor) -> str: + array = ( + tensor.detach() + .float() + .clamp(0.0, 1.0) + .mul(255.0) + .round() + .to(dtype=torch.uint8) + .contiguous() + .cpu() + .numpy() + ) + return hashlib.sha256(array.tobytes(order="C")).hexdigest() + + +def _metric_caption(metric: Optional[Mapping[str, float]]) -> str: + if metric is None: + return "" + return "PSNR %.2f dB\nSSIM %.3f" % (metric["psnr"], metric["ssim"]) + + +def _style_axes(axes: Iterable[Any]) -> None: + for axis in axes: + axis.set_xticks([]) + axis.set_yticks([]) + for spine in axis.spines.values(): + spine.set_visible(False) + + +@_close_new_figures +def _qualitative_grid( + path: Path, + title: str, + row_labels: Sequence[str], + degraded: Tensor, + best: Tensor, + final: Tensor, + clean: Tensor, + baseline_metrics: Sequence[Mapping[str, float]], + best_metrics: Sequence[Mapping[str, float]], + final_metrics: Sequence[Mapping[str, float]], + *, + dpi: int, +) -> None: + plt = _pyplot() + rows = degraded.shape[0] + fig, axes = plt.subplots(rows, 4, figsize=(10.4, 2.55 * rows), squeeze=False) + images = (degraded, best, final, clean) + metric_sets: Tuple[Sequence[Optional[Mapping[str, float]]], ...] = ( + baseline_metrics, + best_metrics, + final_metrics, + [None] * rows, + ) + for row in range(rows): + for column in range(4): + axis = axes[row][column] + axis.imshow(_image_array(images[column][row]), interpolation="nearest") + if row == 0: + axis.set_title(METHOD_LABELS[column], fontsize=10, fontweight="bold") + caption = _metric_caption(metric_sets[column][row]) + if caption: + axis.text( + 0.018, + 0.018, + caption, + transform=axis.transAxes, + ha="left", + va="bottom", + fontsize=6.5, + color="white", + bbox={ + "facecolor": "black", + "edgecolor": "none", + "alpha": 0.68, + "pad": 1.5, + }, + ) + axes[row][0].text( + -0.055, + 0.5, + row_labels[row], + transform=axes[row][0].transAxes, + rotation=90, + ha="right", + va="center", + fontsize=8, + fontweight="bold", + ) + _style_axes(axis for row_axes in axes for axis in row_axes) + fig.suptitle(title, fontsize=12, fontweight="bold", y=0.995) + fig.subplots_adjust( + left=0.075, + right=0.995, + top=0.94, + bottom=0.025, + hspace=0.10, + wspace=0.055, + ) + fig.savefig(str(path), dpi=dpi, bbox_inches="tight", facecolor="white") + plt.close(fig) + + +def _evaluation_history(checkpoint: Mapping[str, Any]) -> List[Dict[str, Any]]: + events = [ + dict(event) + for event in checkpoint.get("history", []) + if event.get("event") == "evaluation" + ] + if not events: + raise ValueError("checkpoint contains no evaluation history") + steps = [int(event["step"]) for event in events] + if steps != sorted(set(steps)): + raise ValueError("evaluation history steps must be unique and sorted") + return events + + +@_close_new_figures +def _plot_learning_dynamics( + path: Path, + final_checkpoint: Mapping[str, Any], + best_step: int, + d0_checkpoint: Optional[Mapping[str, Any]], + *, + dpi: int, +) -> None: + plt = _pyplot() + events = _evaluation_history(final_checkpoint) + steps = np.asarray([int(event["step"]) for event in events]) + fig, axes = plt.subplots(2, 2, figsize=(10.5, 7.1)) + styles = ("-", "--", "-.", ":") + markers = ("o", "s", "^", "D") + for metric_index, metric_name in enumerate(("psnr", "ssim")): + axis = axes[0][metric_index] + for index, domain in enumerate(DISPLAY_DOMAINS): + values = [ + event["metrics"]["restored"]["per_domain"][domain][metric_name] + for event in events + ] + baseline = events[0]["metrics"]["degraded_baseline"]["per_domain"][domain][metric_name] + axis.plot( + steps, + values, + color=OKABE_ITO[index], + linestyle=styles[index], + marker=markers[index], + markersize=3.5, + linewidth=1.4, + label=DOMAIN_LABELS[domain], + ) + axis.axhline(baseline, color=OKABE_ITO[index], linewidth=0.6, alpha=0.28) + axis.axvline(best_step, color="#333333", linewidth=0.9, linestyle="--") + axis.set_xlabel("Optimizer step") + axis.set_ylabel("PSNR (dB)" if metric_name == "psnr" else "SSIM") + axis.set_title("Per-task %s" % metric_name.upper(), fontweight="bold") + axis.grid(True, axis="y", linewidth=0.4, alpha=0.25) + axis.spines["top"].set_visible(False) + axis.spines["right"].set_visible(False) + axes[0][0].legend(frameon=False, fontsize=8, ncol=2) + + macro_axis = axes[1][0] + macro_axis.plot( + steps, + [float(event["macro_psnr"]) for event in events], + color="#0072B2", + marker="o", + linewidth=1.5, + markersize=3.5, + label="D5 full condition", + ) + if d0_checkpoint is not None: + d0_events = _evaluation_history(d0_checkpoint) + matched_steps = sorted(set(steps.tolist()) & {int(event["step"]) for event in d0_events}) + by_step = {int(event["step"]): event for event in d0_events} + macro_axis.plot( + matched_steps, + [float(by_step[step]["macro_psnr"]) for step in matched_steps], + color="#D55E00", + linestyle="--", + marker="s", + linewidth=1.4, + markersize=3.5, + label="D0 null condition", + ) + macro_axis.axvline(best_step, color="#333333", linewidth=0.9, linestyle="--") + macro_axis.set_xlabel("Optimizer step") + macro_axis.set_ylabel("Macro PSNR (dB)") + macro_axis.set_title("Representation utility control", fontweight="bold") + macro_axis.legend(frameon=False, fontsize=8) + macro_axis.grid(True, axis="y", linewidth=0.4, alpha=0.25) + macro_axis.spines["top"].set_visible(False) + macro_axis.spines["right"].set_visible(False) + + delta_axis = axes[1][1] + best_event = next(event for event in events if int(event["step"]) == best_step) + final_event = events[-1] + positions = np.arange(len(DISPLAY_DOMAINS), dtype=np.float64) + width = 0.34 + best_delta = [] + final_delta = [] + for domain in DISPLAY_DOMAINS: + baseline = best_event["metrics"]["degraded_baseline"]["per_domain"][domain]["psnr"] + best_delta.append(best_event["metrics"]["restored"]["per_domain"][domain]["psnr"] - baseline) + final_delta.append(final_event["metrics"]["restored"]["per_domain"][domain]["psnr"] - baseline) + delta_axis.barh(positions - width / 2.0, best_delta, height=width, color="#0072B2", label="Best") + delta_axis.barh(positions + width / 2.0, final_delta, height=width, color="#E69F00", label="Final") + delta_axis.axvline(0.0, color="#333333", linewidth=0.8) + delta_axis.set_yticks(positions) + delta_axis.set_yticklabels([DOMAIN_LABELS[domain] for domain in DISPLAY_DOMAINS]) + delta_axis.invert_yaxis() + delta_axis.set_xlabel("PSNR change vs degraded (dB)") + delta_axis.set_title("Task trade-off", fontweight="bold") + delta_axis.legend(frameon=False, fontsize=8) + delta_axis.spines["top"].set_visible(False) + delta_axis.spines["right"].set_visible(False) + delta_axis.grid(True, axis="x", linewidth=0.4, alpha=0.25) + + fig.suptitle("Phase-2 v4 learning dynamics", fontsize=12, fontweight="bold") + fig.subplots_adjust(left=0.09, right=0.98, top=0.92, bottom=0.08, hspace=0.34, wspace=0.28) + fig.savefig(str(path), dpi=dpi, bbox_inches="tight", facecolor="white") + plt.close(fig) + + +def _parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--phase1-checkpoint", type=Path, required=True) + parser.add_argument("--phase1-sha256", required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--best-checkpoint", type=Path, required=True) + parser.add_argument("--final-checkpoint", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--d0-checkpoint", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=4) + parser.add_argument("--dpi", type=int, default=300) + parser.add_argument("--no-amp", action="store_true") + return parser.parse_args(argv) + + +def run(args: argparse.Namespace) -> Dict[str, Any]: + if args.batch_size <= 0: + raise ValueError("batch-size must be positive") + if args.dpi < 72: + raise ValueError("dpi must be at least 72") + device = torch.device(args.device) + if device.type == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("CUDA was requested but is unavailable") + if device.type == "cuda": + torch.cuda.set_device(0 if device.index is None else int(device.index)) + + best = _torch_load(args.best_checkpoint) + final = _torch_load(args.final_checkpoint) + validate_checkpoint_pair(best, final) + control = None + if args.d0_checkpoint is not None: + control = _torch_load(args.d0_checkpoint) + validate_control_checkpoint(control, final) + if str(best["phase1_sha256"]) != str(args.phase1_sha256): + raise ValueError("Phase-1 SHA does not match the Phase-2 checkpoints") + + splits = load_train_val_manifest(args.manifest) + phase1_header = validate_phase1_artifact_header( + args.phase1_checkpoint, args.phase1_sha256 + ) + validate_splits_against_checkpoint(splits, phase1_header) + if split_digest(splits.train) != best["train_digest"]: + raise ValueError("training split digest does not match checkpoint") + if split_digest(splits.val) != best["val_digest"]: + raise ValueError("validation split digest does not match checkpoint") + validate_clean_file_integrity(splits) + + data_plan = best["contract"]["data_plan"] + crop_size = int(data_plan["crop_size"]) + eval_seed = int(data_plan["eval_seed"]) + candidates, val_counts, baseline_summary = _baseline_candidates( + splits.val, crop_size + ) + validate_degraded_baseline(final, baseline_summary, val_counts) + selected = _select_all_domains(candidates) + degraded, clean = _load_selected_tensors(splits.val, selected, crop_size) + record_ids = [value.candidate.record_id for value in selected] + + phase1, phase1_metadata = build_frozen_phase1( + args.phase1_checkpoint, args.phase1_sha256, device + ) + if phase1_metadata != best["phase1_metadata"]: + raise ValueError("Phase-1 metadata does not match Phase-2 checkpoint") + amp_enabled = device.type == "cuda" and not args.no_amp + best_images = _restore_in_batches( + best, + phase1, + degraded, + record_ids, + device=device, + seed=eval_seed, + batch_size=args.batch_size, + amp_enabled=amp_enabled, + ) + final_images = _restore_in_batches( + final, + phase1, + degraded, + record_ids, + device=device, + seed=eval_seed, + batch_size=args.batch_size, + amp_enabled=amp_enabled, + ) + + baseline_metrics = _metrics(degraded, clean) + best_metrics = _metrics(best_images, clean) + final_metrics = _metrics(final_images, clean) + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + artifacts: List[str] = [] + + for domain_index, domain in enumerate(DISPLAY_DOMAINS): + start = domain_index * len(QUANTILES) + stop = start + len(QUANTILES) + path = output_dir / ("task_%s.png" % domain) + row_labels = [ + "%s\n%s" % (selected[index].quantile_label, selected[index].candidate.source_id) + for index in range(start, stop) + ] + _qualitative_grid( + path, + "%s restoration: validation difficulty quantiles" % DOMAIN_LABELS[domain], + row_labels, + degraded[start:stop], + best_images[start:stop], + final_images[start:stop], + clean[start:stop], + baseline_metrics[start:stop], + best_metrics[start:stop], + final_metrics[start:stop], + dpi=args.dpi, + ) + artifacts.append(path.name) + + median_indices = [domain_index * 3 + 1 for domain_index in range(4)] + overview_path = output_dir / "overview_all_tasks.png" + _qualitative_grid( + overview_path, + "Phase-2 v4 restoration across degradation tasks", + [DOMAIN_LABELS[domain] for domain in DISPLAY_DOMAINS], + degraded[median_indices], + best_images[median_indices], + final_images[median_indices], + clean[median_indices], + [baseline_metrics[index] for index in median_indices], + [best_metrics[index] for index in median_indices], + [final_metrics[index] for index in median_indices], + dpi=args.dpi, + ) + artifacts.insert(0, overview_path.name) + + dynamics_path = output_dir / "learning_dynamics.png" + _plot_learning_dynamics( + dynamics_path, + final, + int(best["step"]), + control, + dpi=args.dpi, + ) + artifacts.append(dynamics_path.name) + + train_counts = {domain: 0 for domain in DISPLAY_DOMAINS} + for record in splits.train: + train_counts[record.degradation] += 1 + sample_payload = [] + for index, value in enumerate(selected): + record = splits.val[value.candidate.index] + sample_payload.append( + { + "domain": value.candidate.domain, + "quantile": value.quantile, + "quantile_label": value.quantile_label, + "record_id": value.candidate.record_id, + "source_id": value.candidate.source_id, + "clean_content_sha256": value.candidate.clean_content_sha256, + "degraded_path": str(record.degraded), + "degraded_file_sha256": sha256_file(record.degraded), + "degraded_crop_sha256": _crop_sha256(degraded[index]), + "baseline": baseline_metrics[index], + "best": best_metrics[index], + "final": final_metrics[index], + } + ) + report = { + "schema_version": 1, + "selection": { + "method": "clean-content-deduplicated baseline-PSNR quantiles", + "quantiles": list(QUANTILES), + "crop_size": crop_size, + "validation_only": True, + }, + "inference": { + "weights": "ema_state_dict.shadow", + "eval_seed": eval_seed, + "record_keyed_noise": True, + "amp_enabled": amp_enabled, + "device": str(device), + }, + "provenance": { + "phase1_checkpoint": str(args.phase1_checkpoint), + "phase1_sha256": sha256_file(args.phase1_checkpoint), + "manifest": str(args.manifest), + "manifest_sha256": sha256_file(args.manifest), + "train_digest": best["train_digest"], + "val_digest": best["val_digest"], + "best_checkpoint": str(args.best_checkpoint), + "best_checkpoint_sha256": sha256_file(args.best_checkpoint), + "best_step": int(best["step"]), + "final_checkpoint": str(args.final_checkpoint), + "final_checkpoint_sha256": sha256_file(args.final_checkpoint), + "final_step": int(final["step"]), + }, + "data_counts": { + "train": train_counts, + "validation": val_counts, + "quarantined_rain_pairs": int(splits.quarantine_count), + }, + "samples": sample_payload, + "artifacts": artifacts, + } + if control is not None: + report["provenance"].update( + { + "d0_control_checkpoint": str(args.d0_checkpoint), + "d0_control_checkpoint_sha256": sha256_file(args.d0_checkpoint), + "d0_control_step": int(control["step"]), + } + ) + report_path = output_dir / "visualization_report.json" + report_path.write_text( + json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(report, sort_keys=True)) + return report + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(_parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/visualize_scene008.py b/dataset/phase1_noise_20260906/code/visualize_scene008.py new file mode 100644 index 0000000000000000000000000000000000000000..b1b344e2533c7fcdd84d9b3264c0a4291f97cf80 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/visualize_scene008.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Qualitative look at the external nearly-clean set (noise scene008). + +Rows: three locked scene008 records; columns: input, DGF at dose 1, DGF at +dose 0, ground truth, with PSNR/SSIM against GT in each caption. +""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from eval_v7_external import V7Pipeline + + +def main() -> None: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--count", type=int, default=3) + args = parser.parse_args() + + device = torch.device("cuda") + pipe = V7Pipeline(args.run_dir, device) + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + records = [r for r in splits.locked_test if r.degradation == "noise"] + step = max(1, len(records) // args.count) + picked = records[::step][: args.count] + dataset = ext.PairCropDataset(picked) + items = [dataset[i] for i in range(len(picked))] + degraded = torch.stack([it["degraded"] for it in items]).to(device) + clean = torch.stack([it["clean"] for it in items]).to(device) + ids = [it["record_id"] for it in items] + full = (torch.stack([it["full_degraded"] for it in items]).to(device) + if "full_degraded" in items[0] else None) + outs = {} + with torch.no_grad(): + for label, dose in (("dose 1", None), ("dose 0", 0.0)): + pipe.dose = dose + outs[label] = pipe.restore(degraded, record_ids=ids, full_degraded=full)["restored"] + cols = [("Input", degraded)] + [(k, v) for k, v in outs.items()] + [("Ground truth", clean)] + fig, axes = plt.subplots(len(picked), len(cols), figsize=(3.4 * len(cols), 3.5 * len(picked)), squeeze=False) + for r in range(len(picked)): + for c, (title, tensor) in enumerate(cols): + ax = axes[r][c] + ax.imshow(tensor[r].clamp(0, 1).permute(1, 2, 0).cpu().numpy()) + ax.set_xticks(()); ax.set_yticks(()) + cap = title + if title != "Ground truth": + psnr = float(v4.rgb_psnr_per_image(tensor[r:r+1], clean[r:r+1])[0]) + ssim = float(v4.rgb_ssim_per_image(tensor[r:r+1], clean[r:r+1])[0]) + cap = "%s\nPSNR %.2f / SSIM %.3f" % (title, psnr, ssim) + ax.set_title(cap, fontsize=9) + axes[r][0].set_ylabel(ids[r][:22], fontsize=7) + fig.suptitle("scene008 (external, nearly clean) — %s" % args.run_dir.name, fontsize=12) + fig.tight_layout(rect=(0, 0, 1, 0.96)) + fig.savefig(str(args.output), dpi=110) + print("saved", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/code/visualize_v7_uformer.py b/dataset/phase1_noise_20260906/code/visualize_v7_uformer.py new file mode 100644 index 0000000000000000000000000000000000000000..2870d3c47b026e97e1ecb0ddaf5ca28f432b8a53 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/visualize_v7_uformer.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Qualitative grids for the v7-Uformer unified two-step checkpoint. + +Rebuilds the exact training/eval stack from the run's own ``run_config.json`` +and ``best.pt`` (EMA weights, 2-step exact-posterior sampling), then renders +per-domain Degraded | Restored | Ground-truth grids on validation center +crops. Samples are picked deterministically (first / middle / last of the +record-id-sorted validation list per domain) — no cherry-picking. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence + +import torch + +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_graph_moe_v6 as v6 +import train_phase2_unified_v7 as v7 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest + +DOMAIN_LABELS = { + "haze": "Haze", + "lowlight": "Low-light", + "noise": "Noise", + "rain": "Rain", +} + + +def _load_run_args(run_dir: Path) -> argparse.Namespace: + raw = json.loads((run_dir / "run_config.json").read_text()) + for key in ("manifest", "phase1_checkpoint", "data_root", "output_dir"): + if raw.get(key) is not None: + raw[key] = Path(raw[key]) + return argparse.Namespace(**raw) + + +def _select_indices(count: int, per_domain: int) -> List[int]: + if count <= per_domain: + return list(range(count)) + if per_domain == 1: + return [count // 2] + step = (count - 1) / (per_domain - 1) + return sorted({int(round(position * step)) for position in range(per_domain)}) + + +def _grid( + domain: str, + rows: Sequence[Dict[str, Any]], + output_path: Path, + checkpoint_step: int, +) -> None: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + figure, axes = plt.subplots( + len(rows), 3, figsize=(10.5, 3.6 * len(rows)), squeeze=False + ) + for row_index, row in enumerate(rows): + panels = ( + ("Degraded", row["degraded"], row["psnr_degraded"], row["ssim_degraded"]), + ("v7-Uformer", row["restored"], row["psnr_restored"], row["ssim_restored"]), + ("Ground truth", row["clean"], None, None), + ) + for column_index, (title, image, psnr, ssim) in enumerate(panels): + axis = axes[row_index][column_index] + axis.imshow(image.permute(1, 2, 0).numpy()) + axis.set_xticks(()) + axis.set_yticks(()) + caption = title + if psnr is not None: + caption = "%s\nPSNR %.2f / SSIM %.3f" % (title, psnr, ssim) + axis.set_title(caption, fontsize=10) + axes[row_index][0].set_ylabel(row["record_id"][:28], fontsize=8) + figure.suptitle( + "%s — v7-Uformer EMA @ step %d (2-step exact posterior)" + % (DOMAIN_LABELS.get(domain, domain), checkpoint_step), + fontsize=13, + ) + figure.tight_layout(rect=(0, 0, 1, 0.97)) + figure.savefig(str(output_path), dpi=110) + plt.close(figure) + + +def run(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--run-dir", type=Path, default=Path("outputs/phase2_v7/uformer_seed42") + ) + parser.add_argument("--output-dir", type=Path, default=None) + parser.add_argument("--per-domain", type=int, default=3) + parser.add_argument("--device", default="cuda") + args = parser.parse_args(argv) + + run_args = _load_run_args(args.run_dir) + device = torch.device(args.device) + output_dir = args.output_dir or (args.run_dir / "vis") + output_dir.mkdir(parents=True, exist_ok=True) + + checkpoint = v4._torch_load(args.run_dir / "best.pt", map_location="cpu") + checkpoint_step = int(checkpoint["step"]) + + model = v7._build_v7_restorer(run_args, device) + model.load_state_dict(checkpoint["ema_state_dict"]["shadow"], strict=True) + model.eval() + phase1, _ = v4.build_frozen_phase1( + run_args.phase1_checkpoint, run_args.phase1_sha256, device + ) + + splits = load_train_val_manifest(run_args.manifest) + dataset = Phase2PairDataset( + splits.val, crop_size=run_args.crop_size, training=False, upscale_small=True + ) + by_domain: Dict[str, List[int]] = {} + for index, record in enumerate(splits.val): + by_domain.setdefault(record.degradation, []).append(index) + + summary: Dict[str, Any] = {"checkpoint_step": checkpoint_step, "domains": {}} + for domain in sorted(by_domain): + ordered = sorted( + by_domain[domain], key=lambda position: splits.val[position].record_id + ) + picked = [ordered[i] for i in _select_indices(len(ordered), args.per_domain)] + items = [dataset[index] for index in picked] + degraded = torch.stack([item["degraded"] for item in items]).to(device) + clean = torch.stack([item["clean"] for item in items]).to(device) + full = torch.stack([item["full_degraded"] for item in items]).to(device) if "full_degraded" in items[0] else None + record_ids = [item["record_id"] for item in items] + with torch.no_grad(): + restored = v7.sample_unified_restoration( + model, phase1, degraded, + seed=run_args.eval_seed, record_ids=record_ids, + full_degraded=full, + ) + psnr_restored = v4.rgb_psnr_per_image(restored, clean) + ssim_restored = v4.rgb_ssim_per_image(restored, clean) + psnr_degraded = v4.rgb_psnr_per_image(degraded, clean) + ssim_degraded = v4.rgb_ssim_per_image(degraded, clean) + rows = [ + { + "record_id": record_ids[i], + "degraded": degraded[i].float().cpu(), + "restored": restored[i].float().cpu(), + "clean": clean[i].float().cpu(), + "psnr_degraded": float(psnr_degraded[i]), + "ssim_degraded": float(ssim_degraded[i]), + "psnr_restored": float(psnr_restored[i]), + "ssim_restored": float(ssim_restored[i]), + } + for i in range(len(record_ids)) + ] + output_path = output_dir / ("v7_uformer_%s.png" % domain) + _grid(domain, rows, output_path, checkpoint_step) + summary["domains"][domain] = [ + { + "record_id": row["record_id"], + "psnr_degraded": row["psnr_degraded"], + "psnr_restored": row["psnr_restored"], + "ssim_degraded": row["ssim_degraded"], + "ssim_restored": row["ssim_restored"], + } + for row in rows + ] + print( + "%s: %s" % ( + domain, + ", ".join( + "%s %.2f->%.2f dB" % ( + row["record_id"][:20], + row["psnr_degraded"], + row["psnr_restored"], + ) + for row in rows + ), + ) + ) + (output_dir / "summary.json").write_text(json.dumps(summary, indent=2)) + print("saved to %s" % output_dir) + return summary + + +if __name__ == "__main__": + run() diff --git a/dataset/phase1_noise_20260906/polyu_original/.phase1_asset.json b/dataset/phase1_noise_20260906/polyu_original/.phase1_asset.json new file mode 100644 index 0000000000000000000000000000000000000000..ded21833381a2332961712ec6f0179d856cb3aba --- /dev/null +++ b/dataset/phase1_noise_20260906/polyu_original/.phase1_asset.json @@ -0,0 +1,4 @@ +{ + "asset": "polyu_original", + "archive_sha256": "30a5c5739af1b27b3d3b8f68c1e2b00d0dd8d1ab836bb545377fe0e4dbfdd477" +} diff --git a/dataset/phase1_noise_20260906/trial_code_staging/.gitignore b/dataset/phase1_noise_20260906/trial_code_staging/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5414edcbc3204e42081ec255ae3dc1c0728c3085 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/.gitignore @@ -0,0 +1,22 @@ +# Python +__pycache__/ +*.pyc +*.pyo +.pytest_cache/ +.ruff_cache/ + +# Large model checkpoints / caches +*.pt +*.pth +*.ckpt + +# OS +.DS_Store + +# tool state and run artifacts +.omc/ +.omo/ +outputs/ +*.log +__pycache__/ +*.pt diff --git a/dataset/phase1_noise_20260906/trial_code_staging/ddp_nccl_sanity.py b/dataset/phase1_noise_20260906/trial_code_staging/ddp_nccl_sanity.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc4ee037c6c05714bdfc82b99fe2fc64e0ba4af --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/ddp_nccl_sanity.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""30-second NCCL/DDP platform sanity check for the dual-3090 box. + +Reproduces the exact collective interleave of the v4 training loop — +explicit scalar all_reduce, DDP bucket all-reduce from backward, grad-norm +clip, second scalar all_reduce — on a toy model. If THIS hangs, the platform +NCCL transport is at fault; if it passes, the bug is in the training runtime. +""" + +from __future__ import annotations + +import os +import time + +import torch +import torch.distributed as dist +from torch.nn.parallel import DistributedDataParallel + + +def log(rank: int, message: str) -> None: + print("[rank %d] %s" % (rank, message), flush=True) + + +def main() -> None: + dist.init_process_group(backend="nccl", init_method="env://") + rank = dist.get_rank() + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + torch.cuda.set_device(local_rank) + device = torch.device("cuda", local_rank) + + model = torch.nn.Sequential( + torch.nn.Conv2d(3, 32, 3, padding=1), + torch.nn.GELU(), + torch.nn.Conv2d(32, 3, 3, padding=1), + ).to(device) + model = DistributedDataParallel( + model, device_ids=[local_rank], output_device=local_rank, + broadcast_buffers=False, find_unused_parameters=False, + ) + scaler = torch.cuda.amp.GradScaler(enabled=True) + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) + + start = time.time() + for iteration in range(50): + data = torch.randn(8, 3, 64, 64, device=device) + with torch.cuda.amp.autocast(enabled=True): + loss = (model(data) - data).square().mean() + finite = torch.isfinite(loss.detach()).all().to(dtype=torch.int32) + dist.all_reduce(finite, op=dist.ReduceOp.MIN) + assert bool(finite.item()) + scaler.scale(loss).backward() + scaler.unscale_(optimizer) + grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + finite = torch.isfinite(grad_norm.detach()).all().to(dtype=torch.int32) + dist.all_reduce(finite, op=dist.ReduceOp.MIN) + assert bool(finite.item()) + scaler.step(optimizer) + scaler.update() + optimizer.zero_grad(set_to_none=True) + if iteration % 10 == 0: + log(rank, "iteration %d ok (%.1fs)" % (iteration, time.time() - start)) + log(rank, "SANITY PASS in %.1fs" % (time.time() - start)) + dist.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/diagnose_phase1_routing.py b/dataset/phase1_noise_20260906/trial_code_staging/diagnose_phase1_routing.py new file mode 100644 index 0000000000000000000000000000000000000000..cc3c21862b11950febd4c140fff93d4d7c37795f --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/diagnose_phase1_routing.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Routing / severity diagnosis of a Phase-1 checkpoint on the cases that +exposed the noise-concept drift: SIDD val noisy inputs and their clean GT, +scene008 (locked, nearly clean, dark textured), and lowlight inputs. +Prints mean routing per node and mean severity per branch for each group.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest + +NODES = ("rain", "noise", "haze", "lowlight", "free1", "free2") + + +def _summary(phase1, batch: torch.Tensor) -> dict: + with torch.no_grad(): + rep = phase1(batch) + routing = rep.routing_probs.mean(0).tolist() + severity = rep.severity_coords.mean(0).tolist() + argmax = rep.routing_probs.argmax(1) + return { + "routing": {n: round(v, 3) for n, v in zip(NODES, routing)}, + "severity": {n: round(v, 3) for n, v in zip(NODES[:4], severity)}, + "argmax_share": {n: round(float((argmax == i).float().mean()), 2) for i, n in enumerate(NODES)}, + "mean_luma": round(float(batch.mean()), 3), + "n": int(batch.shape[0]), + } + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", type=Path, required=True) + parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + parser.add_argument("--output", type=Path, default=None) + args = parser.parse_args() + device = torch.device("cuda") + import hashlib + sha = hashlib.sha256(args.checkpoint.read_bytes()).hexdigest() + phase1, _ = v4.build_frozen_phase1(args.checkpoint, sha, device) + + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + noise_locked = [r for r in splits.locked_test if r.degradation == "noise"] + ds = ext.PairCropDataset(noise_locked) + s8_deg = torch.stack([ds[i]["degraded"] for i in range(len(noise_locked))]).to(device) + s8_cln = torch.stack([ds[i]["clean"] for i in range(len(noise_locked))]).to(device) + + vs = load_train_val_manifest(args.manifest) + vd = Phase2PairDataset(vs.val, crop_size=256, training=False, upscale_small=True) + groups = {} + for domain in ("noise", "lowlight", "rain", "haze"): + idx = [i for i, r in enumerate(vs.val) if r.degradation == domain][:20] + groups["val_%s_input" % domain] = torch.stack([vd[i]["degraded"] for i in idx]).to(device) + groups["val_%s_clean" % domain] = torch.stack([vd[i]["clean"] for i in idx]).to(device) + groups["scene008_input"] = s8_deg + groups["scene008_clean"] = s8_cln + + report = {"checkpoint": str(args.checkpoint), "sha256": sha} + for name, batch in groups.items(): + report[name] = _summary(phase1, batch) + r = report[name] + print("%-22s route %-58s sev %s" % (name, json.dumps(r["routing"]), json.dumps(r["severity"]))) + if args.output: + args.output.write_text(json.dumps(report, indent=2)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/download_all_datasets.sh b/dataset/phase1_noise_20260906/trial_code_staging/download_all_datasets.sh new file mode 100644 index 0000000000000000000000000000000000000000..799357207fc0ced23dffb6fdd60fecf7bb7228b8 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/download_all_datasets.sh @@ -0,0 +1,118 @@ +#!/bin/bash +# Download all 5 datasets locally then upload to server +# Run this on your LOCAL machine (with internet access) + +set -e + +LOCAL_DIR="/Users/nguyenbinhan/Downloads/datasets" +SERVER="3090" +REMOTE_DIR="/home/admin_mcn/data" + +mkdir -p "$LOCAL_DIR" + +echo "==============================================" +echo "Downloading SCDC Datasets" +echo "==============================================" + +# 1. Rain200H +echo "" +echo "[1/5] Downloading Rain200H..." +cd "$LOCAL_DIR" +if [ ! -d "Rain200H" ]; then + 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" + if [ -f Rain200H.zip ] && [ $(stat -f%z Rain200H.zip 2>/dev/null || stat -c%s Rain200H.zip 2>/dev/null) -gt 1000000 ]; then + unzip -q Rain200H.zip -d Rain200H + rm Rain200H.zip + echo " Rain200H downloaded!" + else + echo " Download failed. Please manually download from:" + echo " https://drive.google.com/file/d/1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF/view" + mkdir -p Rain200H + fi +else + echo " Rain200H already exists" +fi + +# 2. LOLv2 +echo "" +echo "[2/5] Downloading LOLv2..." +cd "$LOCAL_DIR" +if [ ! -d "LOLv2" ]; then + echo " Please download LOLv2 manually from: https://daooshee.github.io/FOVDFE/" + echo " Expected structure: LOLv2/LOLv2/Real_captured/" + mkdir -p LOLv2/LOLv2/Real_captured +fi + +# 3. RESIDE (OTS) +echo "" +echo "[3/5] Downloading RESIDE..." +cd "$LOCAL_DIR" +if [ ! -d "RESIDE" ]; then + echo " Please download RESIDE manually from: https://github.com/x懦yzzz/RESIDE" + echo " Expected structure: RESIDE/OTS/OTS/" + mkdir -p RESIDE/OTS/OTS +fi + +# 4. GOPRO +echo "" +echo "[4/5] Downloading GOPRO..." +cd "$LOCAL_DIR" +if [ ! -d "GOPRO" ]; then + echo " Please download GOPRO manually from: https://github.com/SeungjunNah/DeepDeblur" + echo " Expected structure: GOPRO/train/blur/, GOPRO/train/sharp/" + mkdir -p GOPRO/train/blur GOPRO/train/sharp GOPRO/test/blur GOPRO/test/sharp +fi + +# 5. SIDD +echo "" +echo "[5/5] Downloading SIDD..." +cd "$LOCAL_DIR" +if [ ! -d "SIDD" ]; then + echo " SIDD requires registration at: https://sid.epfl.ch/" + echo " Please download manually after registration." + mkdir -p SIDD/SIDD_Benchmark +fi + +echo "" +echo "==============================================" +echo "Upload to Server" +echo "==============================================" + +echo "" +echo "Uploading Rain200H..." +if [ -d "$LOCAL_DIR/Rain200H" ]; then + if [ -d "$LOCAL_DIR/Rain200H/train_c" ] || [ -d "$LOCAL_DIR/Rain200H/rainy_image_extractions" ]; then + tar -czvf /tmp/rain200h.tar.gz -C "$LOCAL_DIR" Rain200H 2>/dev/null + scp /tmp/rain200h.tar.gz $SERVER:$REMOTE_DIR/ + ssh $SERVER "cd $REMOTE_DIR && tar -xzvf rain200h.tar.gz && rm rain200h.tar.gz" + rm /tmp/rain200h.tar.gz + echo " Rain200H uploaded!" + else + echo " Rain200H folder exists but structure is unexpected" + ls "$LOCAL_DIR/Rain200H/" + fi +else + echo " Rain200H not found locally" +fi + +echo "" +echo "==============================================" +echo "Summary" +echo "==============================================" +echo "" +echo "Datasets at $LOCAL_DIR:" +for dir in Rain200H LOLv2 RESIDE GOPRO SIDD; do + if [ -d "$LOCAL_DIR/$dir" ]; then + count=$(find "$LOCAL_DIR/$dir" -type f \( -name "*.png" -o -name "*.jpg" \) 2>/dev/null | wc -l) + echo " OK $dir ($count images)" + else + echo " MISSING $dir (not downloaded)" + fi +done + +echo "" +echo "Datasets on server $SERVER:" +ssh $SERVER "ls -la $REMOTE_DIR/ 2>/dev/null || echo 'Remote dir not found'" + +echo "" +echo "Done!" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/download_rain200h.sh b/dataset/phase1_noise_20260906/trial_code_staging/download_rain200h.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e099496543422f2ceb29105d75737ccabf875c8 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/download_rain200h.sh @@ -0,0 +1,61 @@ +#!/bin/bash +# Download Rain200H dataset for deraining +# Link: https://drive.google.com/file/d/1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF/view + +set -e + +DATA_ROOT="/home/admin_mcn/data" +RAIN_DIR="$DATA_ROOT/Rain200H" +mkdir -p "$RAIN_DIR" + +echo "==============================================" +echo "Downloading Rain200H Dataset" +echo "==============================================" + +# Method 1: Using gdown (if available) +if command -v gdown &> /dev/null; then + echo "Using gdown..." + cd "$DATA_ROOT" + gdown 1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF -O Rain200H.zip + unzip -q Rain200H.zip -d Rain200H + rm Rain200H.zip +# Method 2: Using wget/curl with direct link +else + echo "Installing gdown..." + pip3 install gdown + + echo "Downloading from Google Drive..." + cd "$DATA_ROOT" + gdown 1y8gjAvnt0kkf1dSEyauVFu2weLi53LmF -O Rain200H.zip + + echo "Extracting..." + unzip -q Rain200H.zip -d Rain200H + rm Rain200H.zip +fi + +echo "Checking structure..." +ls -la "$RAIN_DIR/" + +# Verify dataset structure +if [ -d "$RAIN_DIR/train_c" ] || [ -d "$RAIN_DIR/Rain200H/train_c" ]; then + echo "" + echo "==============================================" + echo "Rain200H Dataset Ready!" + echo "==============================================" + echo "Structure:" + find "$RAIN_DIR" -type d | head -10 + echo "" + echo "Sample counts:" + if [ -d "$RAIN_DIR/train_c" ]; then + echo " Train clean: $(ls "$RAIN_DIR/train_c/" 2>/dev/null | wc -l) images" + elif [ -d "$RAIN_DIR/Rain200H/train_c" ]; then + echo " Train clean: $(ls "$RAIN_DIR/Rain200H/train_c/" 2>/dev/null | wc -l) images" + fi +else + echo "" + echo "WARNING: Dataset structure not as expected." + echo "Please check $RAIN_DIR manually." +fi + +echo "" +echo "Done!" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/eval_full_frame.py b/dataset/phase1_noise_20260906/trial_code_staging/eval_full_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..bc728ad86963304605099569bc7fc10662eace93 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/eval_full_frame.py @@ -0,0 +1,424 @@ +#!/usr/bin/env python3 +"""Native-resolution, full-image evaluation of a v7-family checkpoint. + +Why a second protocol: ``eval_pipeline_external.py`` measures 256 center +crops taken AFTER ``_resize_center_crop`` (short side -> 256), i.e. every +external image is downscaled first (Test1200 384 -> 256 = 0.67x, RESIDE +0.62x, SIDD scene008 ~12x). Downscaling averages real noise away (scene008 +input reads 39 dB "nearly clean") and moves every set to a scale the trunk +never trained on (Phase-2 trains on NATIVE 256 crops). Published numbers are +full images at native resolution, so this evaluator restores the whole +image at native scale with overlapping 256 tiles (the training crop size), +Phase-1 per tile plus the aspect-squashed whole frame for global-context +models, optional x8 dihedral test-time augmentation, and reports RGB and +Y-channel PSNR/SSIM (deraining papers report Y) plus LPIPS. + +Groups: rain_locked (Test100+Test1200, 384x384), noise_locked_scene008 (SIDD +scene 008 at native 12 MP), haze_heldout (300 RESIDE), lowlight_lolv2_test +(the 100 LOLv2-real test images = the lowlight val split, directly +comparable to published LOLv2-real numbers). +""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import Callable, Dict, List, Optional, Sequence, Tuple + +import torch +from torch import Tensor +import torch.nn.functional as F +from torch.utils.data import DataLoader, Dataset + +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 + +RestoreFn = Callable[[Tensor, Sequence[str], Optional[Tensor]], Tensor] + +_LANCZOS = getattr(getattr(__import__("PIL.Image", fromlist=["Image"]), "Resampling", None), "LANCZOS", None) + + +# ---- dihedral test-time augmentation -------------------------------------- # +def dihedral_transform(image: Tensor, index: int) -> Tensor: + """Apply one of the 8 square symmetries (index 0 = identity). + + index = 4 * flip + rotation, rotation in {0,1,2,3} quarter turns + counter-clockwise, flip = horizontal mirror applied FIRST. + """ + + if not 0 <= int(index) < 8: + raise ValueError("dihedral index must be in [0, 8)") + out = image + if index >= 4: + out = torch.flip(out, dims=(-1,)) + return torch.rot90(out, k=int(index) % 4, dims=(-2, -1)) + + +def dihedral_inverse(image: Tensor, index: int) -> Tensor: + """Undo ``dihedral_transform(_, index)``.""" + + if not 0 <= int(index) < 8: + raise ValueError("dihedral index must be in [0, 8)") + out = torch.rot90(image, k=-(int(index) % 4), dims=(-2, -1)) + if index >= 4: + out = torch.flip(out, dims=(-1,)) + return out + + +# ---- tiling --------------------------------------------------------------- # +def tile_boxes(height: int, width: int, tile: int, overlap: int) -> List[Tuple[int, int]]: + """Top-left corners of ``tile``-sized boxes covering an image of at least + ``tile`` in both dimensions; the last row/column is flush with the edge.""" + + if tile <= 0 or overlap < 0 or overlap >= tile: + raise ValueError("need 0 <= overlap < tile") + if height < tile or width < tile: + raise ValueError("image must be at least one tile in both dimensions") + stride = tile - overlap + + def starts(length: int) -> List[int]: + positions = list(range(0, max(length - tile, 0) + 1, stride)) + if positions[-1] != length - tile: + positions.append(length - tile) + return positions + + return [(top, left) for top in starts(height) for left in starts(width)] + + +def blend_weights(tile: int, overlap: int, device=None, dtype=torch.float32) -> Tensor: + """[1,1,tile,tile] raised-cosine ramp over ``overlap`` pixels on every + edge, 1 in the interior; complementary ramps of adjacent tiles sum to 1.""" + + ramp = torch.ones(tile, device=device, dtype=dtype) + if overlap > 0: + positions = (torch.arange(overlap, device=device, dtype=dtype) + 0.5) / float(overlap) + edge = 0.5 - 0.5 * torch.cos(math.pi * positions) + ramp[:overlap] = edge + ramp[tile - overlap:] = torch.flip(edge, dims=(0,)) + return (ramp.view(-1, 1) * ramp.view(1, -1)).view(1, 1, tile, tile) + + +def _pad_to_tile(image: Tensor, tile: int) -> Tuple[Tensor, Tuple[int, int]]: + height, width = int(image.shape[-2]), int(image.shape[-1]) + pad_h, pad_w = max(tile - height, 0), max(tile - width, 0) + if pad_h == 0 and pad_w == 0: + return image, (height, width) + mode = "reflect" if pad_h < height and pad_w < width else "replicate" + return F.pad(image, (0, pad_w, 0, pad_h), mode=mode), (height, width) + + +@torch.no_grad() +def restore_tiled( + restore: RestoreFn, + image: Tensor, + record_id: str, + *, + tile: int = 256, + overlap: int = 64, + tile_batch: int = 8, + full_frame: Optional[Tensor] = None, +) -> Tensor: + """Restore one [1,3,H,W] image with overlapping tiles. + + ``restore(tiles [N,3,tile,tile], record_ids, full_frame [N,3,s,s] | None)`` + returns the restored tiles. Every tile gets a distinct record id so the + record-keyed sampler noise stays deterministic per tile. + """ + + if image.ndim != 4 or image.shape[0] != 1: + raise ValueError("restore_tiled expects a single [1,3,H,W] image") + padded, (height, width) = _pad_to_tile(image, tile) + boxes = tile_boxes(int(padded.shape[-2]), int(padded.shape[-1]), tile, overlap) + weights = blend_weights(tile, overlap, device=padded.device, dtype=torch.float32) + canvas = torch.zeros(1, padded.shape[1], padded.shape[-2], padded.shape[-1], + device=padded.device, dtype=torch.float32) + total = torch.zeros(1, 1, padded.shape[-2], padded.shape[-1], + device=padded.device, dtype=torch.float32) + for start in range(0, len(boxes), max(int(tile_batch), 1)): + chunk = boxes[start:start + max(int(tile_batch), 1)] + tiles = torch.cat([padded[..., t:t + tile, l:l + tile] for t, l in chunk], dim=0) + ids = ["%s|tile%d" % (record_id, start + k) for k in range(len(chunk))] + full = None if full_frame is None else full_frame.expand(len(chunk), -1, -1, -1) + restored = restore(tiles, ids, full).float() + if restored.shape != tiles.shape: + raise ValueError("restore must return tiles of the input shape") + for k, (t, l) in enumerate(chunk): + canvas[..., t:t + tile, l:l + tile] += restored[k:k + 1] * weights + total[..., t:t + tile, l:l + tile] += weights + return (canvas / total)[..., :height, :width] + + +# Every scale of the trunk must stay divisible by the 8x8 window: image/2 +# (pixel-unshuffle) then three /2 stages -> the image must be a multiple of +# 2 * 8 * 8 = 128 for the relative-position bias to apply at all four scales. +WHOLE_IMAGE_MULTIPLE = 128 + + +@torch.no_grad() +def restore_whole( + restore: RestoreFn, + image: Tensor, + record_id: str, + *, + multiple: int = WHOLE_IMAGE_MULTIPLE, + full_frame: Optional[Tensor] = None, +) -> Tensor: + """Restore one [1,3,H,W] image in a single pass (no tiles): reflect-pad + to a multiple of ``multiple`` so the window attention keeps its native + 8x8 windows at every scale, then crop back. Removes the per-tile + conditioning/exposure inconsistency of tiled inference.""" + + if image.ndim != 4 or image.shape[0] != 1: + raise ValueError("restore_whole expects a single [1,3,H,W] image") + height, width = int(image.shape[-2]), int(image.shape[-1]) + pad_h, pad_w = (-height) % multiple, (-width) % multiple + padded = image + if pad_h or pad_w: + mode = "reflect" if pad_h < height and pad_w < width else "replicate" + padded = F.pad(image, (0, pad_w, 0, pad_h), mode=mode) + restored = restore(padded, ["%s|whole" % record_id], full_frame).float() + if restored.shape != padded.shape: + raise ValueError("restore must return an image of the input shape") + return restored[..., :height, :width] + + +# TTA sets. x2 = identity + horizontal mirror only: rotations and the +# vertical flip change the orientation of rain streaks and put the sky at the +# bottom, which the model never saw (measured on v9a15k, tiled: x8 costs +# -2.4 dB on Test1200 and -1.0 dB on haze while helping isotropic noise). +TTA_TRANSFORMS = {1: (0,), 2: (0, 4), 8: tuple(range(8))} + + +@torch.no_grad() +def restore_full_frame( + restore: RestoreFn, + image: Tensor, + record_id: str, + *, + tta: int = 1, + full_frame: Optional[Tensor] = None, + whole_max_pixels: int = 0, + **tiling, +) -> Tensor: + """Restoration averaged over ``tta`` dihedral transforms (1 or 8). + + Images with at most ``whole_max_pixels`` pixels are restored in one pass + (``restore_whole``); larger ones (or all, when 0) with overlapping tiles. + """ + + if int(tta) not in TTA_TRANSFORMS: + raise ValueError("tta must be 1, 2 or 8") + pixels = int(image.shape[-2]) * int(image.shape[-1]) + whole = int(whole_max_pixels) > 0 and pixels <= int(whole_max_pixels) + outputs = [] + for index in TTA_TRANSFORMS[int(tta)]: + transformed = dihedral_transform(image, index) + full = None if full_frame is None else dihedral_transform(full_frame, index) + tag = "%s|d%d" % (record_id, index) + if whole: + restored = restore_whole(restore, transformed, tag, full_frame=full) + else: + restored = restore_tiled(restore, transformed, tag, full_frame=full, **tiling) + outputs.append(dihedral_inverse(restored, index)) + return torch.stack(outputs, dim=0).mean(dim=0).clamp(0.0, 1.0) + + +# ---- metrics -------------------------------------------------------------- # +def rgb_to_y601(image: Tensor) -> Tensor: + """BT.601 luma of an RGB [B,3,H,W] batch in [0,1] -> Y in [16,235]/255.""" + + if image.ndim != 4 or image.shape[1] != 3: + raise ValueError("rgb_to_y601 expects [B,3,H,W]") + r, g, b = image[:, 0:1].float(), image[:, 1:2].float(), image[:, 2:3].float() + return (16.0 + 65.481 * r + 128.553 * g + 24.966 * b) / 255.0 + + +def psnr_y_per_image(prediction: Tensor, target: Tensor) -> Tensor: + return v4.rgb_psnr_per_image(rgb_to_y601(prediction), rgb_to_y601(target)) + + +def ssim_y_per_image(prediction: Tensor, target: Tensor) -> Tensor: + return v4.rgb_ssim_per_image(rgb_to_y601(prediction), rgb_to_y601(target)) + + +def lpips_center(lpips_fn, prediction: Tensor, target: Tensor, max_side: int = 1024) -> Tensor: + """LPIPS on the full image, or on a central ``max_side`` window for very + large images (the AlexNet features of a 12 MP frame do not fit).""" + + height, width = prediction.shape[-2:] + if height > max_side or width > max_side: + top, left = max((height - max_side) // 2, 0), max((width - max_side) // 2, 0) + prediction = prediction[..., top:top + max_side, left:left + max_side] + target = target[..., top:top + max_side, left:left + max_side] + return lpips_fn(prediction * 2 - 1, target * 2 - 1).flatten() + + +# ---- data ----------------------------------------------------------------- # +class FullFrameDataset(Dataset): + """Native pairs (upscaled only when smaller than ``crop`` on the short + side, exactly Phase2PairDataset's rule) plus the aspect-squashed whole + frame used by global-context models.""" + + def __init__(self, records: Sequence, crop: int = 256) -> None: + self.records = list(records) + self.crop = int(crop) + + def __len__(self) -> int: + return len(self.records) + + def __getitem__(self, index: int): + record = self.records[index] + degraded, clean = p1._native_open_pair(record, self.crop) + full = degraded.resize((self.crop, self.crop), _LANCZOS) + return { + "degraded": p1._pil_to_tensor(degraded), + "clean": p1._pil_to_tensor(clean), + "full_degraded": p1._pil_to_tensor(full), + "record_id": record.record_id, + } + + +def external_groups(haze_count: int = 300) -> Dict[str, list]: + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rain = [r for r in splits.locked_test if r.degradation == "rain"] + noise = [r for r in splits.locked_test if r.degradation == "noise"] + lowlight = [r for r in splits.val if r.degradation == "lowlight"] + reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE") + used = { + r.split_group for r in list(splits.train) + list(splits.val) + if r.degradation == "haze" + } + haze = [r for r in reside[5000:] if r.split_group not in used][:haze_count] + return { + "rain_locked": rain, + "noise_locked_scene008": noise, + "haze_heldout": haze, + "lowlight_lolv2_test": lowlight, + } + + +def _mean(values: List[float]) -> float: + return float(sum(values) / len(values)) if values else float("nan") + + +@torch.no_grad() +def evaluate_group_full_frame( + restore: RestoreFn, + records: Sequence, + name: str, + device: torch.device, + lpips_fn=None, + *, + tta: int = 1, + tile: int = 256, + overlap: int = 64, + tile_batch: int = 8, + use_full_frame: bool = True, + workers: int = 2, + whole_max_pixels: int = 0, +) -> Dict[str, object]: + loader = DataLoader(FullFrameDataset(records, crop=tile), batch_size=1, + shuffle=False, num_workers=workers) + keys = ("psnr", "ssim", "psnr_y", "ssim_y", "lpips") + acc = {kind: {k: [] for k in keys} for kind in ("restored", "degraded")} + sizes = [] + for batch in loader: + degraded = batch["degraded"].to(device) + clean = batch["clean"].to(device) + full = batch["full_degraded"].to(device) if use_full_frame else None + record_id = str(batch["record_id"][0]) + restored = restore_full_frame( + restore, degraded, record_id, tta=tta, full_frame=full, + tile=tile, overlap=overlap, tile_batch=tile_batch, + whole_max_pixels=whole_max_pixels, + ) + sizes.append([int(degraded.shape[-2]), int(degraded.shape[-1])]) + for kind, image in (("restored", restored), ("degraded", degraded)): + slot = acc[kind] + slot["psnr"] += v4.rgb_psnr_per_image(image, clean).cpu().tolist() + slot["ssim"] += v4.rgb_ssim_per_image(image, clean).cpu().tolist() + slot["psnr_y"] += psnr_y_per_image(image, clean).cpu().tolist() + slot["ssim_y"] += ssim_y_per_image(image, clean).cpu().tolist() + if lpips_fn is not None: + slot["lpips"] += lpips_center(lpips_fn, image, clean).cpu().tolist() + report = { + "n": len(records), + "protocol": {"tile": tile, "overlap": overlap, "tta": int(tta), "native": True, + "full_frame_context": bool(use_full_frame), + "whole_max_pixels": int(whole_max_pixels)}, + "sizes_hw": sizes[:3], + } + for kind, slot in acc.items(): + report[kind] = {k: _mean(v) for k, v in slot.items() if v} + print(name, json.dumps(report, sort_keys=True), flush=True) + return report + + +def main(argv: Optional[Sequence[str]] = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--groups", default="rain_locked,noise_locked_scene008,haze_heldout,lowlight_lolv2_test") + parser.add_argument("--tta", type=int, default=1, choices=(1, 2, 8), + help="1 = none, 2 = + horizontal mirror (orientation-safe), 8 = full dihedral") + parser.add_argument("--tile", type=int, default=256) + parser.add_argument("--overlap", type=int, default=64) + parser.add_argument("--tile-batch", type=int, default=8) + parser.add_argument("--haze-count", type=int, default=300) + parser.add_argument("--dose", type=float, default=None) + parser.add_argument("--photometric-dose", type=float, default=None) + parser.add_argument( + "--whole-max-pixels", type=int, default=0, + help="restore images up to this many pixels in ONE pass (pad to x128) " + "instead of tiles; 0 = always tile. 1.2e6 covers LOL/RESIDE/Test1200.", + ) + parser.add_argument("--pregain-dose", type=float, default=None, + help="scale of the v10 input pre-gain log-gain (None = 1.0; 0 = off)") + parser.add_argument("--colour-dose", type=float, default=None, + help="scale of the v12 global colour head (None = 1.0; 0 = off)") + parser.add_argument("--checkpoint", default="best.pt", + help="file inside --run-dir to evaluate (best.pt, last.pt, milestone_%08d.pt)") + parser.add_argument("--no-lpips", action="store_true") + parser.add_argument("--limit", type=int, default=0, help="debug: first N records per group") + args = parser.parse_args(argv) + + from eval_v7_external import V7Pipeline + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + pipeline = V7Pipeline(args.run_dir, device, dose=args.dose, photometric_dose=args.photometric_dose, + checkpoint=args.checkpoint, pregain_dose=args.pregain_dose, + colour_dose=args.colour_dose) + seed = int(pipeline.args.eval_seed) + + def restore(tiles: Tensor, ids: Sequence[str], full: Optional[Tensor]) -> Tensor: + return pipeline.restore(tiles, record_ids=list(ids), seed=seed, full_degraded=full)["restored"] + + lpips_fn = None + if not args.no_lpips: + import lpips + + lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device) + groups = external_groups(args.haze_count) + report = {"run_dir": str(args.run_dir), "dose": args.dose, + "photometric_dose": args.photometric_dose, "tta": int(args.tta), + "whole_max_pixels": int(args.whole_max_pixels), + "checkpoint": pipeline.checkpoint_name, "checkpoint_step": pipeline.checkpoint_step, + "pregain_dose": args.pregain_dose} + for name in [g.strip() for g in args.groups.split(",") if g.strip()]: + records = groups[name] + if args.limit > 0: + records = records[: args.limit] + report[name] = evaluate_group_full_frame( + restore, records, name, device, lpips_fn, + tta=args.tta, tile=args.tile, overlap=args.overlap, tile_batch=args.tile_batch, + whole_max_pixels=args.whole_max_pixels, + ) + args.output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE", args.output, flush=True) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/eval_gen2_external.py b/dataset/phase1_noise_20260906/trial_code_staging/eval_gen2_external.py new file mode 100644 index 0000000000000000000000000000000000000000..ca1d592958d89627867edf68ecf1bec7bedfa96d --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/eval_gen2_external.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Official + external evaluation of the gen-2 pipeline (v6.1 + refiner).""" +import json +from pathlib import Path + +import torch + +import train_refiner_a as tr +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +from src.models.restoration.refiner_decoder import RefinerDecoder +import train_phase2_graph_resshift_v4 as v4 + + +class Gen2Pipeline: + def __init__(self, device): + self.device = device + self.regressor, self.phase1, self.args = tr.load_frozen_regressor( + device, kind="v6", run_dir=Path("outputs/phase2_moe_v6/v61_seed42") + ) + state = torch.load("outputs/refiner_v6_v1/refiner_best.pt", map_location="cpu") + refiner = RefinerDecoder() + refiner.load_state_dict(state["refiner_state_dict"], strict=True) + self.refiner = refiner.to(device).eval() + print("refiner best step:", state["step"], "macro:", round(state["macro_refined_psnr"], 3)) + + @torch.no_grad() + def restore(self, degraded, record_ids=None, seed=20260830): + degraded = degraded.to(self.device) + x0 = tr.one_step_x0(self.regressor, self.phase1, degraded, + [str(r) for r in record_ids], seed, "initial") + px, size = v4.pad_to_multiple(x0, multiple=4) + py, _ = v4.pad_to_multiple(degraded, multiple=4) + out = self.refiner(px, py) + h, w = size + return {"x0_hat": x0, "restored": out[..., :h, :w]} + + +def main(): + import lpips + device = torch.device("cuda") + pipeline = Gen2Pipeline(device) + lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device) + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rain = [r for r in splits.locked_test if r.degradation == "rain"] + noise = [r for r in splits.locked_test if r.degradation == "noise"] + reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE") + used = {r.split_group for r in list(splits.train) + list(splits.val) if r.degradation == "haze"} + haze = [r for r in reside[5000:] if r.split_group not in used][:300] + report = { + "rain_locked": ext.evaluate_group(pipeline, rain, "rain_locked", lpips_fn), + "noise_locked_scene008": ext.evaluate_group(pipeline, noise, "noise_locked", lpips_fn), + "haze_heldout": ext.evaluate_group(pipeline, haze, "haze_heldout", lpips_fn), + } + Path("outputs/gen2_external_v1.json").write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE outputs/gen2_external_v1.json") + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/eval_phase1_clean_relative.py b/dataset/phase1_noise_20260906/trial_code_staging/eval_phase1_clean_relative.py new file mode 100644 index 0000000000000000000000000000000000000000..de544e9553f3b5edcf97d9d41c50586c267df229 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/eval_phase1_clean_relative.py @@ -0,0 +1,669 @@ +"""Auditable real/synthetic evaluation for seven clean-relative factors. + +Test is an explicitly requested evaluation split, never a training selector. +Missing targets, collapsed targets, and unimplemented claims remain explicit. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from torch import Tensor +import torch.nn.functional as F +from torch.utils.data import DataLoader + +from train_phase1_clean_relative import ( + TYPE_ORDER, HELDOUT_PAIRS, TRAIN_PAIRS, atomic_json_save, file_digest, + functional_error, record_labels, residual_statistics, scene_component_ids, selected_indices, +) + + +def average_precision(targets, scores) -> float | None: + """Threshold-grouped AP: ties cannot gain an arbitrary ranking advantage.""" + labels = np.asarray(targets, dtype=np.int64) + values = np.asarray(scores, dtype=np.float64) + positives = int(labels.sum()) + if positives == 0: + return None + if len(labels) != len(values) or not np.isfinite(values).all(): + raise ValueError("Invalid average-precision inputs") + order = np.argsort(-values, kind="stable") + labels, values = labels[order], values[order] + cumulative = np.cumsum(labels) + ends = np.r_[np.flatnonzero(values[:-1] != values[1:]), len(values) - 1] + true_positive = cumulative[ends] + recalls = true_positive / positives + precisions = true_positive / (ends + 1) + return float(np.sum(np.diff(np.r_[0.0, recalls]) * precisions)) + + +def classification_report(labels: Tensor, logits: Tensor) -> dict[str, Any]: + labels, logits = labels.cpu(), logits.detach().float().cpu() + if len(labels) == 0: + raise ValueError("No records to evaluate") + probabilities = logits.sigmoid() + predicted = logits.argmax(1) + confusion = torch.bincount(labels * 7 + predicted, minlength=49).reshape(7, 7) + domains = {} + f1s, aps, supported_f1s = [], [], [] + for i, name in enumerate(TYPE_ORDER): + tp = int(confusion[i, i]) + support, predicted_count = int(confusion[i].sum()), int(confusion[:, i].sum()) + precision = tp / predicted_count if predicted_count else 0.0 + recall = tp / support if support else 0.0 + f1 = 2 * tp / (support + predicted_count) if support + predicted_count else 0.0 + ap = average_precision((labels == i).numpy(), probabilities[:, i].numpy()) + domains[name] = {"support": support, "precision": precision, "recall": recall, "f1": f1, "average_precision": ap} + f1s.append(f1) + if support: + supported_f1s.append(f1) + if ap is not None: + aps.append(ap) + return {"type_order": TYPE_ORDER, "records": len(labels), "confusion": confusion.tolist(), "per_domain": domains, + "accuracy": float((predicted == labels).float().mean()), "macro_f1": float(np.mean(f1s)), + "macro_f1_supported": float(np.mean(supported_f1s)), "supported_classes": len(supported_f1s), + "macro_average_precision_supported": float(np.mean(aps)) if aps else None, + "interpretation": "Single manifest-domain argmax; probabilities remain independent presence scores"} + + +def regression_report(targets, predictions) -> dict[str, Any]: + target, prediction = np.asarray(targets, dtype=float), np.asarray(predictions, dtype=float) + if not target.size: + return {"count": 0, "mae": None, "r2": None, "pearson": None, "target_variance": None} + variance = float(np.var(target)) + residual = float(np.sum((target - prediction) ** 2)) + total = float(np.sum((target - np.mean(target)) ** 2)) + 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 + return {"count": int(target.size), "mae": float(np.mean(np.abs(target - prediction))), + "r2": 1 - residual / total if total > 1e-12 else None, "pearson": correlation, + "target_variance": variance} + + +def binary_auc(known_scores, unknown_scores) -> float | None: + """Mann–Whitney AUC, including half credit for ties.""" + known, unknown = np.asarray(known_scores), np.asarray(unknown_scores) + if not len(known) or not len(unknown): + return None + return float(np.mean(unknown[:, None] > known[None, :]) + 0.5 * np.mean(unknown[:, None] == known[None, :])) + + +def _record_ids_digest(records) -> str: + identifiers = sorted(record["id"] for record in records) + return hashlib.sha256(json.dumps(identifiers, separators=(",", ":")).encode()).hexdigest() + + +def _noise_cohort(record: dict) -> str | None: + if record["type"] != "noise": + return None + if record.get("synthesis") == "noise": + profile = record.get("noise_profile") + if profile not in ("gaussian", "signal_dependent_gaussian"): + raise ValueError("Unrecognized synthetic noise source/profile") + return "synthetic_" + profile + if record.get("synthesis") is not None or record["dataset"] not in ("SIDD", "PolyU"): + raise ValueError("Unrecognized real noise source; explicit cohort mapping is required") + return "sidd_real" if record["dataset"] == "SIDD" else "polyu_real" + + +def _noise_evaluation_context(manifest, split: str) -> dict | None: + """Verify the actual parent file and all append-only prefixes, not ID spelling. + + Schema 1 keeps its existing evaluation API. Schema 2 fails closed rather + than silently claiming a legacy cohort from an unverified path or count. + """ + from src.data.clean_relative import validate_manifest + + payload = manifest if isinstance(manifest, dict) else json.loads(Path(manifest).read_text()) + if payload.get("schema_version") == 1 and "noise_expansion" not in payload: + return None + expansion = payload.get("noise_expansion", {}) + if not isinstance(expansion, dict): + raise ValueError("Noise stratification requires a parent preservation receipt") + receipt = expansion.get("base_manifest", {}) + if not isinstance(receipt, dict): + raise ValueError("Noise stratification requires a parent path/hash receipt") + path, expected_sha = receipt.get("path"), receipt.get("sha256") + if (not isinstance(path, str) or not Path(path).is_absolute() + or not isinstance(expected_sha, str) or len(expected_sha) != 64): + raise ValueError("Noise stratification requires a verified parent path/hash receipt") + try: + raw = Path(path).read_bytes() + except OSError as error: + raise ValueError(f"Cannot read noise evaluation parent manifest: {path}") from error + if hashlib.sha256(raw).hexdigest() != expected_sha: + raise ValueError("Noise evaluation parent manifest hash mismatch") + parent = json.loads(raw) + validate_manifest(parent) + if (parent.get("schema_version") != 1 or payload.get("schema_version") != 2 + or expansion.get("version") != 1 + or expansion.get("base_records_preserved") is not True + or expansion.get("base_split_assignments_preserved") is not True): + raise ValueError("Noise evaluation parent/schema preservation receipt is invalid") + for name in ("train", "val", "test"): + rows, original = payload.get(name, []), parent[name] + if rows[:len(original)] != original: + raise ValueError(f"Noise evaluation parent {name} prefix was changed") + if any(record["type"] != "noise" for record in rows[len(original):]): + raise ValueError("Noise expansion added non-noise records; shared negatives are not preserved") + records = payload[split] + # Resolve every source before model inference, including records omitted by a cap. + cohorts = [_noise_cohort(record) for record in records] + return {"records": records, "cohorts": cohorts, "parent_count": len(parent[split]), + "parent_manifest_path": path, "parent_manifest_sha256": expected_sha, + "parent_record_ids_sha256": _record_ids_digest(parent[split])} + + +def _noise_binary_report(predicted: Tensor, targets: Tensor) -> dict: + positives, negatives = int(targets.sum()), int((~targets).sum()) + tp = int((predicted & targets).sum()) + fp = int((predicted & ~targets).sum()) + fn = positives - tp + return {"true_positives": tp, "false_positives": fp, "false_negatives": fn, + "true_negatives": negatives - fp, + "precision": tp / (tp + fp) if tp + fp else None, + "recall": tp / positives if positives else None, + "f1": 2 * tp / (2 * tp + fp + fn) if positives else None, + "false_positive_rate": fp / negatives if negatives else None} + + +def _noise_stratification(context: dict, selected: list[int], labels: Tensor, logits: Tensor, + severity_targets: Tensor, severity_masks: Tensor, + severity_predictions: Tensor) -> dict: + records, names = context["records"], context["cohorts"] + selected_records = [records[index] for index in selected] + selected_names = [names[index] for index in selected] + parent_count = context["parent_count"] + parent_mask = torch.tensor([index < parent_count for index in selected], dtype=torch.bool) + noise_index = TYPE_ORDER.index("noise") + negative_mask = parent_mask & (labels != noise_index) + all_negatives = [record for record in records[:parent_count] if record["type"] != "noise"] + evaluated_negatives = [record for record, keep in zip(selected_records, negative_mask.tolist()) if keep] + predicted = logits.argmax(1) == noise_index + probabilities = logits.sigmoid()[:, noise_index] + thresholded = probabilities > .5 + negative_total, negative_count = len(all_negatives), len(evaluated_negatives) + negative_complete = negative_total == negative_count + by_domain = {} + for kind in TYPE_ORDER: + if kind == "noise": + continue + mask = negative_mask & (labels == TYPE_ORDER.index(kind)) + count = int(mask.sum()) + by_domain[kind] = { + "records_total": sum(record["type"] == kind for record in all_negatives), + "records_evaluated": count, + "argmax_noise_false_positives": int((predicted & mask).sum()), + "presence_false_positives_at_0_5": int((thresholded & mask).sum()), + "argmax_noise_false_positive_rate": float(predicted[mask].float().mean()) if count else None, + "presence_false_positive_rate_at_0_5": float(thresholded[mask].float().mean()) if count else None, + } + shared = {"records_total": negative_total, "records_evaluated": negative_count, + "scope": "all_parent_nonnoise_records" if negative_complete else "explicitly_capped", + "record_ids_sha256": _record_ids_digest(all_negatives), + "evaluated_record_ids_sha256": _record_ids_digest(evaluated_negatives), + "argmax_noise_false_positives": int((predicted & negative_mask).sum()), + "presence_false_positives_at_0_5": int((thresholded & negative_mask).sum()), + "by_domain": by_domain} + result = {} + for name in ("sidd_real", "polyu_real", "synthetic_gaussian", "synthetic_signal_dependent_gaussian"): + all_positives = [record for record, cohort in zip(records, names) if cohort == name] + positive_mask = torch.tensor([cohort == name for cohort in selected_names], dtype=torch.bool) + positive_rows = [record for record, keep in zip(selected_records, positive_mask.tolist()) if keep] + count, total = len(positive_rows), len(all_positives) + included = positive_mask | negative_mask + targets = positive_mask[included] + physical_mask = positive_mask & severity_masks[:, noise_index] + if name.endswith("real") and bool(physical_mask.any()): + raise ValueError("Real noise unexpectedly has physical severity labels") + if name.startswith("synthetic_") and int(physical_mask.sum()) != count: + raise ValueError("Synthetic noise is missing explicit physical severity labels") + physical = regression_report(severity_targets[physical_mask, noise_index].tolist(), + severity_predictions[physical_mask, noise_index].tolist()) + result[name] = { + "status": "measured" if count and negative_count else "insufficient_positive_or_negative_records", + "scope": "all_cohort_records_and_parent_negatives" if count == total and negative_complete else "explicitly_capped", + "positive_records_total": total, "positive_records_evaluated": count, + "negative_records_total": negative_total, "negative_records_evaluated": negative_count, + "evaluated_noise_prevalence": count / (count + negative_count) if count + negative_count else None, + "negative_pool_record_ids_sha256": shared["record_ids_sha256"], + "evaluated_negative_pool_record_ids_sha256": shared["evaluated_record_ids_sha256"], + "positive_record_ids_sha256": _record_ids_digest(all_positives), + "evaluated_positive_record_ids_sha256": _record_ids_digest(positive_rows), + "source_groups_total": len({(row["dataset"], row["group"]) for row in all_positives}), + "source_groups_evaluated": len({(row["dataset"], row["group"]) for row in positive_rows}), + "unique_clean_rgb_total": len({row["clean_content_sha256"] for row in all_positives}), + "unique_clean_rgb_evaluated": len({row["clean_content_sha256"] for row in positive_rows}), + "argmax_noise": _noise_binary_report(predicted[included], targets), + "presence_at_0_5": _noise_binary_report(thresholded[included], targets), + "noise_average_precision": average_precision(targets.numpy(), probabilities[included].numpy()) if negative_count else None, + "physical_severity": {"status": "measured_from_explicit_parameter_mask" if bool(physical_mask.any()) else "unsupported_without_physical_targets", + "known_target_records": int(physical_mask.sum()), + "unknown_target_records": count - int(physical_mask.sum()), **physical}, + } + legacy_count = int(parent_mask.sum()) + return { + "schema_version": 1, "status": "measured", "scope": "all_records" if len(selected) == len(records) else "explicitly_capped", + "parent_receipt": {key: context[key] for key in ("parent_manifest_path", "parent_manifest_sha256", "parent_record_ids_sha256")}, + "parent_all_split_prefixes_verified": True, + "fixed_legacy": {"records_total": parent_count, "records_evaluated": legacy_count, + "scope": "all_parent_records" if legacy_count == parent_count else "explicitly_capped", + "parent_manifest_sha256": context["parent_manifest_sha256"], + "classification": classification_report(labels[parent_mask], logits[parent_mask]) if legacy_count else None}, + "shared_parent_nonnoise_pool": shared, "cohorts": result, + "noise_record_counts": { + "real_total": sum(name in ("sidd_real", "polyu_real") for name in names), + "synthetic_total": sum(name is not None and name.startswith("synthetic_") for name in names), + "real_evaluated": sum(name in ("sidd_real", "polyu_real") for name in selected_names), + "synthetic_evaluated": sum(name is not None and name.startswith("synthetic_") for name in selected_names)}, + "interpretation": "Each source-positive cohort uses the SAME parent non-noise negative pool; other noise sources are excluded, not relabeled as negatives. Precision/AP depend on the reported prevalence; never pool synthetic records as evidence of real-noise quality.", + "group_limitations": "SIDD groups are physical scenes; PolyU camera/object groups are not independently verified physical scenes. Synthetic records share clean RGB content and are not independent scenes.", + } + + +def _loader(manifest, split, patch_size, batch_size, workers, cap, seed, protected_prefix=None): + from src.data.clean_relative import PairedDegradationDataset + + dataset = PairedDegradationDataset(manifest, split=split, crop_size=patch_size, seed=seed) + labels = record_labels(dataset) + selected = selected_indices(labels, cap, seed) + if not selected: + raise ValueError(f"Manifest split {split!r} is empty") + options = {"num_workers": workers, "generator": torch.Generator().manual_seed(seed), "persistent_workers": False} + if protected_prefix is None: + loader = DataLoader(dataset, batch_size=batch_size, sampler=selected, drop_last=False, **options) + else: + # Do not mix the parent's last (possibly short) batch with added rows. + groups = ([index for index in selected if index < protected_prefix], + [index for index in selected if index >= protected_prefix]) + batches = [group[start:start + batch_size] for group in groups for start in range(0, len(group), batch_size)] + selected = [index for batch in batches for index in batch] + loader = DataLoader(dataset, batch_sampler=batches, **options) + return dataset, selected, loader + + +@torch.inference_mode() +def evaluate_real(model, manifest: str, split: str, device, batch_size: int = 16, patch_size: int = 128, + workers: int = 0, max_records: int | None = None, seed: int = 42, + functional_enabled: bool = True) -> dict[str, Any]: + context = _noise_evaluation_context(manifest, split) + loader_options = {} if context is None else {"protected_prefix": context["parent_count"]} + dataset, selected, loader = _loader(manifest, split, patch_size, batch_size, workers, max_records, seed, **loader_options) + previous_mode = model.training + model.eval() + labels, logits, clean_probabilities, clean_norms, deltas = [], [], [], [], [] + paired_content, shuffled_content = [], [] + clean_proxy_l1, clean_proxy_psnr = [], [] + physical = {name: {"target": [], "prediction": []} for name in TYPE_ORDER} + severity_targets, severity_masks, severity_predictions = [], [], [] + try: + for batch in loader: + pair = model.forward_pair(batch["degraded"].to(device), batch["clean"].to(device)) + student, clean = pair["student"], pair["clean"] + if functional_enabled: + target_clean = batch["clean"].to(device) + origin = model.decode(clean["content"], torch.zeros_like(clean["delta"]), target_clean.shape[-2:]) + error = origin - target_clean + clean_proxy_l1.extend(error.abs().flatten(1).mean(1).cpu().tolist()) + clean_proxy_psnr.extend((-10 * error.square().flatten(1).mean(1).clamp_min(1e-12).log10()).cpu().tolist()) + # CPU DataLoader tensors can hold shared-memory FDs until released. + labels.append(batch["label"].clone()) + logits.append(student["presence_logits"].float().cpu()) + clean_probabilities.append(clean["presence_logits"].sigmoid().float().cpu()) + clean_norms.append(clean["delta"].norm(dim=1).float().cpu()) + deltas.append(student["delta"].float().cpu()) + if context is not None: + severity_targets.append(batch["severity"].clone()) + severity_masks.append(batch["severity_mask"].clone()) + severity_predictions.append(student["severity"].float().cpu()) + for k, name in enumerate(TYPE_ORDER): + mask = batch["severity_mask"][:, k] + physical[name]["target"].extend(batch["severity"][mask, k].tolist()) + physical[name]["prediction"].extend(student["severity"].cpu()[mask, k].tolist()) + paired_content.append((student["content"] - clean["content"]).square().flatten(1).mean(1).cpu()) + if len(batch["clean"]) > 1: + shuffled_content.append((student["content"] - clean["content"].roll(1, 0)).square().flatten(1).mean(1).cpu()) + finally: + model.train(previous_mode) + probabilities, norms, delta = torch.cat(clean_probabilities), torch.cat(clean_norms), torch.cat(deltas) + report = { + "split": split, "records_total": len(dataset), "records_evaluated": len(selected), + "scope": "all_records" if len(selected) == len(dataset) else "explicitly_capped", + "image_protocol": f"One deterministic paired {patch_size}x{patch_size} native crop per record; not full-image restoration", + "classification": classification_report(torch.cat(labels), torch.cat(logits)), + "clean": {"any_false_positive_rate_at_0_5": float((probabilities > 0.5).any(1).float().mean()), + "per_factor_false_positive_rate_at_0_5": dict(zip(TYPE_ORDER, (probabilities > 0.5).float().mean(0).tolist())), + "delta_norm_mean": float(norms.mean()), "delta_norm_p95": float(torch.quantile(norms, 0.95)), "delta_norm_max": float(norms.max())}, + "clean_origin_proxy": {"status": "measured" if functional_enabled else "unsupported_without_trained_proxy", + "rgb_l1": _mean(clean_proxy_l1), "psnr_mean_db": _mean(clean_proxy_psnr), + "definition": "G(content(clean), zero_delta) against clean; peak=1, MSE floor=1e-12, outputs not clamped"}, + "representation": {"mean_coordinate_variance": float(delta.var(0, unbiased=False).mean()), "mean_norm": float(delta.norm(dim=1).mean())}, + "paired_content": {"matched_feature_mse": float(torch.cat(paired_content).mean()), + "within_batch_shuffled_feature_mse": float(torch.cat(shuffled_content).mean()) if shuffled_content else None, + "interpretation": "Paired-feature consistency diagnostic; not an independence test"}, + "manifest_physical_severity": { + name: {"status": "measured_from_explicit_parameter_mask" if item["target"] else "unsupported_without_physical_targets", + **regression_report(item["target"], item["prediction"])} for name, item in physical.items()}, + "severity_interpretation": "Only supplied synthetic parameter masks are scored, e.g. generated JPEG; real domain names are not physical severity measurements", + } + if context is not None: + report["noise_stratification"] = _noise_stratification( + context, selected, torch.cat(labels), torch.cat(logits), + torch.cat(severity_targets), torch.cat(severity_masks), torch.cat(severity_predictions)) + return report + + +def _content_probe(baseline, descriptor, content, group_ids) -> dict[str, Any]: + """Does a global code predict observable scene information beyond type/dose?""" + groups = np.asarray(group_ids) + unique = np.unique(groups) + if len(unique) < 4: + return {"status": "insufficient_data", "reason": "Need at least four distinct source scenes for a disjoint probe split"} + train = np.isin(groups, unique[:len(unique) // 2]) + test = ~train + target = np.asarray(content, dtype=np.float64) + + def fit_error(features): + features = np.asarray(features, dtype=np.float64) + center, scale = features[train].mean(0), features[train].std(0).clip(1e-4) + normalized = (features - center) / scale + normalized = np.column_stack((np.ones(len(normalized)), normalized)) + penalty = np.eye(normalized.shape[1]) + penalty[0, 0] = 0 + coefficients = np.linalg.solve(normalized[train].T @ normalized[train] + penalty, normalized[train].T @ target[train]) + return float(np.mean((normalized[test] @ coefficients - target[test]) ** 2)) + + base = np.asarray(baseline) + base_error = fit_error(base) + augmented_error = fit_error(np.concatenate((base, np.asarray(descriptor)), axis=1)) + variance = float(target[test].var(0).mean()) + return {"status": "measured", "train_scenes": int(len(unique) // 2), "test_scenes": int(len(unique) - len(unique) // 2), + "baseline": "Ridge regression from type one-hot plus type-by-normalized-physical-severity", + "target": "Clean 4x4 RGB thumbnail, fixed observable rather than learned teacher target", + "baseline_mse": base_error, "baseline_plus_delta_mse": augmented_error, + "heldout_target_variance": variance, + "baseline_r2": 1 - base_error / variance if variance > 1e-12 else None, + "baseline_plus_delta_r2": 1 - augmented_error / variance if variance > 1e-12 else None, + "relative_improvement": (base_error - augmented_error) / base_error if base_error > 1e-12 else None, + "interpretation": "Positive held-out improvement is evidence of this specific content-prediction channel; not a proof of independence or universally undesirable content dependence"} + + +def physical_parameter_probe(rows: list[dict], kind: str) -> dict[str, Any]: + """Test within-factor information beyond dose, against fixed physical targets.""" + groups = [row["scene"] for row in rows] + if len(set(groups)) < 8: + return {"status": "insufficient_data", "reason": "Need at least eight distinct source scenes for this physical-parameter probe"} + if kind not in ("rain", "blur", "haze"): + return {"status": "unsupported", "reason": "No independently varied non-dose physical target in this synthetic operator"} + if kind == "haze": + target = [row["parameters"]["airlight"] for row in rows] + target_name = "airlight RGB" + else: + angles = np.deg2rad([row["parameters"]["angle"] for row in rows]) + target = np.column_stack((np.sin(2 * angles), np.cos(2 * angles))) + target_name = "sin(2*orientation), cos(2*orientation), respecting 180-degree line symmetry" + report = _content_probe([[row["parameters"]["severity"]] for row in rows], + [row["coefficients"] for row in rows], target, groups) + report["baseline"] = "Within-type normalized physical severity (type is constant); fixed ridge alpha=1" + report["target"] = target_name + report["interpretation"] = "Held-out-scene recovery of independently varied physical parameters from the active factor coordinates beyond a severity-only baseline" + report["factor_rank"] = len(rows[0]["coefficients"]) + report["baseline_plus_factor_coefficients_mse"] = report.pop("baseline_plus_delta_mse") + report["baseline_plus_factor_coefficients_r2"] = report.pop("baseline_plus_delta_r2") + return report + + +def _mean(values): + return float(np.mean(values)) if values else None + + +def _scene_indices(dataset, count: int, seed: int) -> list[int]: + """Select distinct manifest scene groups, not many variants of one image.""" + by_scene = {} + for i, scene in enumerate(scene_component_ids(dataset.records)): + by_scene.setdefault(scene, i) + order = np.random.default_rng(seed).permutation(len(by_scene))[:count] + values = list(by_scene.values()) + return [values[int(i)] for i in order] + + +@torch.inference_mode() +def evaluate_controlled(model, manifest: str, split: str, device, batch_size=8, patch_size=128, + scenes=28, seed=42, use_edges=True, functional_enabled=True) -> dict[str, Any]: + from src.data.clean_relative import PairedDegradationDataset, sample_degradation_parameters, synthesize_composition, synthesize_degradation + + dataset = PairedDegradationDataset(manifest, split=split, crop_size=patch_size, seed=seed) + indices = _scene_indices(dataset, scenes, seed) + if not indices: + return {"status": "unsupported", "reason": "No source scenes"} + model.eval() + severity = {name: {"target": [], "prediction": [], "parameters": []} for name in TYPE_ORDER} + transfer = {name: [] for name in TYPE_ORDER} + transfer_controls = {name: {mode: [] for mode in ("blind", "zero", "shuffled_paired")} for name in TYPE_ORDER} + physical_rows = {name: [] for name in TYPE_ORDER} + drop = {name: [] for name in TYPE_ORDER} + drop_baseline = {name: [] for name in TYPE_ORDER} + mixed_result = {"heldout_pairs": [], "seen_pairs_both_orders_new_scenes": []} + hf_statistics = {name: [] for name in TYPE_ORDER} + known_uncertainty, unknown_uncertainty = [], [] + probe_baseline, probe_descriptor, probe_content, probe_groups = [], [], [], [] + single_targets, single_logits, mixed_targets, mixed_logits = [], [], [], [] + swap_differences = [] + for start in range(0, len(indices), batch_size): + current = indices[start:start + batch_size] + x_cpu = torch.stack([dataset[i]["clean"] for i in current]) + x = x_cpu.to(device) + clean_rep = model(x) + # Roll against all selected scenes, so the final batch of one still has distinct content. + other_indices = [indices[(start + i + 1) % len(indices)] for i in range(len(current))] + other_cpu = torch.stack([dataset[i]["clean"] for i in other_indices]) + other = other_cpu.to(device) + other_clean_rep = model(other) + for k, name in enumerate(TYPE_ORDER): + ys, transferred_targets, targets, params = [], [], [], [] + for j in range(len(current)): + sample_seed = seed + current[j] * 1009 + k * 29 + param = sample_degradation_parameters(name, sample_seed, heldout=True) + y, _ = synthesize_degradation(x_cpu[j], name, parameters=param, seed=sample_seed) + target, _ = synthesize_degradation(other_cpu[j], name, parameters=param, seed=sample_seed) + ys.append(y) + transferred_targets.append(target) + targets.append(float(param["severity"])) + params.append(param) + y, other_y = torch.stack(ys).to(device), torch.stack(transferred_targets).to(device) + pair = model.forward_pair(y, x) + rep = pair["student"] + severity[name]["target"].extend(targets) + severity[name]["prediction"].extend(rep["severity"][:, k].cpu().tolist()) + severity[name]["parameters"].extend(params) + for j, param in enumerate(params): + physical_rows[name].append({"scene": current[j], "parameters": param, + "coefficients": rep["coefficients"][j, k].cpu().tolist()}) + single_targets.extend([k] * len(current)) + single_logits.append(rep["presence_logits"].cpu()) + known_uncertainty.extend((1 - rep["presence_logits"].sigmoid().max(1).values).cpu().tolist()) + if len(indices) > 1: + if functional_enabled: + transferred = model.decode(other_clean_rep["content"], pair["teacher"]["delta"], x.shape[-2:]) + transfer[name].extend(functional_error(transferred, other_y, other, torch.full((len(x),), k, device=device)).cpu().tolist()) + hf_error = (residual_statistics(transferred - other)[:, 6:] - residual_statistics(other_y - other)[:, 6:]).abs().mean(1) + hf_statistics[name].extend(hf_error.cpu().tolist()) + control_codes = {"blind": rep["delta"], "zero": torch.zeros_like(rep["delta"])} + if len(x) > 1: + control_codes["shuffled_paired"] = pair["teacher"]["delta"].roll(1, 0) + for mode, code in control_codes.items(): + control = model.decode(other_clean_rep["content"], code, x.shape[-2:]) + errors = functional_error(control, other_y, other, torch.full((len(x),), k, device=device)).cpu().tolist() + if mode == "shuffled_paired": + errors = [value for j, value in enumerate(errors) if params[j] != params[(j - 1) % len(x)]] + transfer_controls[name][mode].extend(errors) + other_teacher = model.encode_pair(other_y, other) + swap_differences.extend((pair["teacher"]["coefficients"][:, :7] - other_teacher["coefficients"][:, :7]).square().flatten(1).mean(1).cpu().tolist()) + if functional_enabled: + dropped_delta = model.drop_factor(pair["teacher"]["delta"], k) + dropped = model.decode(clean_rep["content"], dropped_delta, x.shape[-2:]) + untouched = model.decode(clean_rep["content"], pair["teacher"]["delta"], x.shape[-2:]) + drop[name].extend((dropped - x).abs().flatten(1).mean(1).cpu().tolist()) + drop_baseline[name].extend((untouched - x).abs().flatten(1).mean(1).cpu().tolist()) + one_hot = np.eye(7)[k] + content = F.adaptive_avg_pool2d(x, (4, 4)).flatten(1).cpu().tolist() + for j, target in enumerate(targets): + probe_baseline.append(np.r_[one_hot, one_hot * target]) + probe_descriptor.append(rep["delta"][j].cpu().numpy()) + probe_content.append(content[j]) + probe_groups.append(current[j]) + for regime, candidate_pairs in (("heldout_pairs", HELDOUT_PAIRS), ("seen_pairs_both_orders_new_scenes", TRAIN_PAIRS[:3])): + for a, b in candidate_pairs: + ya, yb, yab, yba = [], [], [], [] + for j, index in enumerate(current): + sample_seed = seed + index * 1009 + TYPE_ORDER.index(a) * 29 + pa = sample_degradation_parameters(a, sample_seed, heldout=False) + pb = sample_degradation_parameters(b, sample_seed + 1, heldout=False) + ya.append(synthesize_degradation(x_cpu[j], a, parameters=pa, seed=sample_seed)[0]) + yb.append(synthesize_degradation(x_cpu[j], b, parameters=pb, seed=sample_seed + 1)[0]) + yab.append(synthesize_composition(x_cpu[j], (a, b), parameters=(pa, pb), seed=sample_seed)[0]) + yba.append(synthesize_composition(x_cpu[j], (b, a), parameters=(pb, pa), seed=sample_seed)[0]) + first = model.encode_pair(torch.stack(ya).to(device), x) + second = model.encode_pair(torch.stack(yb).to(device), x) + ab = model.encode_pair(torch.stack(yab).to(device), x) + ba_pair = model.forward_pair(torch.stack(yba).to(device), x) + ba = ba_pair["teacher"] + composed = model.compose(first["delta"], second["delta"], TYPE_ORDER.index(a), TYPE_ORDER.index(b), use_edges=use_edges) + reverse = model.compose(second["delta"], first["delta"], TYPE_ORDER.index(b), TYPE_ORDER.index(a), use_edges=use_edges) + additive = first["delta"] + second["delta"] + raw_target = (ab["delta"] - ba["delta"]) + result = {"pair": [a, b], "count": len(current), + "forward_latent_mse": float(F.mse_loss(composed, ab["delta"])), + "forward_additive_latent_mse": float(F.mse_loss(additive, ab["delta"])), + "reverse_latent_mse": float(F.mse_loss(reverse, ba["delta"])), + "reverse_additive_latent_mse": float(F.mse_loss(additive, ba["delta"])), + "order_difference_mse": float(F.mse_loss(composed - reverse, raw_target)), + "order_target_mean_square": float(raw_target.square().mean())} + if functional_enabled: + stochastic = a in ("rain", "noise", "snow") or b in ("rain", "noise", "snow") + error_labels = torch.full((len(x),), 1 if stochastic else TYPE_ORDER.index(a), device=device) + for direction, code, observed in (("forward", composed, torch.stack(yab).to(device)), + ("reverse", reverse, torch.stack(yba).to(device))): + decoded = model.decode(clean_rep["content"], code, x.shape[-2:]) + additive_decoded = model.decode(clean_rep["content"], additive, x.shape[-2:]) + result[direction + "_functional_error"] = float(functional_error(decoded, observed, x, error_labels).mean()) + result[direction + "_additive_functional_error"] = float(functional_error(additive_decoded, observed, x, error_labels).mean()) + result[direction + "_pixel_l1"] = float((decoded - observed).abs().mean()) + result[direction + "_additive_pixel_l1"] = float((additive_decoded - observed).abs().mean()) + result[direction + "_residual_hf_l1"] = float((residual_statistics(decoded - x)[:, 6:] - residual_statistics(observed - x)[:, 6:]).abs().mean()) + # Counterfactual removal targets are remaining operators applied to clean. + for removed, remaining, remaining_image in ((a, b, torch.stack(yb).to(device)), (b, a, torch.stack(ya).to(device))): + labels_remaining = torch.full((len(x),), TYPE_ORDER.index(remaining), device=device) + for mode, code in (("paired", ba["delta"]), ("blind", ba_pair["student"]["delta"])): + dropped = model.decode(clean_rep["content"], model.drop_factor(code, TYPE_ORDER.index(removed)), x.shape[-2:]) + untouched = model.decode(clean_rep["content"], code, x.shape[-2:]) + prefix = f"reverse_drop_{removed}_retain_{remaining}_{mode}" + result[prefix + "_error"] = float(functional_error(dropped, remaining_image, x, labels_remaining).mean()) + result[prefix + "_before_drop_error"] = float(functional_error(untouched, remaining_image, x, labels_remaining).mean()) + else: + result["external_functional_status"] = "unsupported_without_trained_proxy" + mixed_result[regime].append(result) + target = torch.zeros(len(x), 7) + target[:, TYPE_ORDER.index(a)] = target[:, TYPE_ORDER.index(b)] = 1 + mixed_targets.append(target) + mixed_logits.append(ba_pair["student"]["presence_logits"].cpu()) + # Explicit unseen operator probe; not seven-family leave-one-out training. + occluded = x.clone() + h, w = x.shape[-2:] + occluded[:, :, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.5 + unknown = model(occluded) + unknown_uncertainty.extend((1 - unknown["presence_logits"].sigmoid().max(1).values).cpu().tolist()) + target = torch.cat(mixed_targets) + probability = torch.cat(mixed_logits).sigmoid() + binary = probability > 0.5 + mixed_ap = {name: average_precision(target[:, k].numpy(), probability[:, k].numpy()) for k, name in enumerate(TYPE_ORDER)} + return { + "status": "measured", "source_split": split, "distinct_source_scenes": len(indices), "requested_scenes": scenes, + "severity_regime": "Held-out normalized physical severity range supplied by synthetic operators", + "single_classification": classification_report(torch.tensor(single_targets), torch.cat(single_logits)), + "severity": {name: {**regression_report(item["target"], item["prediction"]), "physical_parameter_examples": item["parameters"][:3], + "target_definition": "Normalized generating parameter; never inferred from real domain labels"} for name, item in severity.items()}, + "within_factor_parameter_probes": {name: physical_parameter_probe(rows, name) for name, rows in physical_rows.items()}, + "cross_content_transfer": {"status": "measured" if functional_enabled and len(indices) > 1 else "unsupported_without_trained_proxy_and_distinct_content", + "per_domain_error": {name: _mean(values) for name, values in transfer.items()}, + "paired_teacher_error": {name: _mean(values) for name, values in transfer.items()}, + "controls": {name: {mode: {"count": len(values), "error": _mean(values)} for mode, values in modes.items()} for name, modes in transfer_controls.items()}, + "shuffled_baseline": "Same factor but mismatched generating parameters within batch; skipped if no distinct donor is available", + "native_hf_residual_statistics_l1": {name: _mean(values) for name, values in hf_statistics.items()}, + "matched_parameter_coefficient_mse": _mean(swap_differences), + "metric": "RGB L1 for deterministic types; residual mean/std and gradient/Laplacian RMS L1 for rain/noise/snow", + "limitation": "Deterministic proxy cannot generate a full conditional noise distribution"}, + "factor_drop": {name: {"clean_l1_after_drop": _mean(drop[name]), "clean_l1_before_drop": _mean(drop_baseline[name])} for name in TYPE_ORDER}, + "factor_drop_interpretation": "Controlled decoder intervention test; not a real-world causal identification claim", + "mixed": {"per_batch_results": mixed_result, "exact_presence_match_at_0_5": float((binary == target.bool()).all(1).float().mean()), + "per_factor_average_precision": mixed_ap, + "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", + "external_functional_targets": "Actual synthesized forward/reverse images; mixed-node removal targets the remaining operator on clean; additive and before-drop baselines included", + "target_definition": "Latent composition targets are jointly learned; errors measure agreement, not physical identifiability", + "basis_reference_noncollapse": "Consult real representation variance and order_target_mean_square alongside latent errors"}, + "content_probe": _content_probe(probe_baseline, probe_descriptor, probe_content, probe_groups), + "unseen_operator_probe": {"operator": "central gray occlusion", "score": "1 - maximum known presence probability", + "auc": binary_auc(known_uncertainty, unknown_uncertainty), + "known_count": len(known_uncertainty), "unknown_count": len(unknown_uncertainty), + "limitation": "One controlled unseen-operator probe, not calibrated open-set recognition"}, + "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"}, + } + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", required=True) + parser.add_argument("--manifest", required=True) + parser.add_argument("--split", choices=("val", "test"), default="val") + parser.add_argument("--output") + parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--patch-size", type=int, default=128) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--max-records", type=int, help="Explicit cap; omitted evaluates all real split records") + parser.add_argument("--synthetic-scenes", type=int, default=28) + parser.add_argument("--skip-controlled", action="store_true") + parser.add_argument("--no-edges", action="store_true", help="Inference ablation, separately labeled from retraining without edges") + return parser + + +def main(argv: list[str] | None = None) -> dict[str, Any]: + args = build_parser().parse_args(argv) + if min(args.batch_size, args.patch_size, args.threads, args.synthetic_scenes) <= 0 or args.num_workers < 0: + raise ValueError("Invalid batch, crop, thread, synthetic scene, or worker count") + torch.set_num_threads(args.threads) + from src.models.graph_encoder.clean_relative import CleanRelativeConfig, CleanRelativeGraphEncoder + + checkpoint = torch.load(args.checkpoint, map_location="cpu", weights_only=False) + config = CleanRelativeConfig(**checkpoint["model_config"]) + device = torch.device(args.device) + model = CleanRelativeGraphEncoder(config).to(device) + model.load_state_dict(checkpoint["model"]) + report = {"checkpoint": str(Path(args.checkpoint).resolve()), "checkpoint_sha256": file_digest(args.checkpoint), + "checkpoint_step": checkpoint["global_step"], "training_scope": checkpoint["run_config"]["scope"], + "manifest_sha256": file_digest(args.manifest), "arguments": vars(args), + "real": evaluate_real(model, args.manifest, args.split, device, args.batch_size, args.patch_size, + args.num_workers, args.max_records, args.seed, + functional_enabled=not checkpoint["run_config"]["arguments"].get("no_proxy", False))} + if not args.skip_controlled: + report["controlled"] = evaluate_controlled(model, args.manifest, args.split, device, min(args.batch_size, 8), + args.patch_size, args.synthetic_scenes, args.seed, + use_edges=not args.no_edges and not checkpoint["run_config"]["arguments"]["no_edges"], + functional_enabled=not checkpoint["run_config"]["arguments"].get("no_proxy", False)) + else: + report["controlled"] = {"status": "explicitly_skipped"} + output = Path(args.output) if args.output else Path(args.checkpoint).parent / f"evaluation_{args.split}_{Path(args.checkpoint).stem}.json" + atomic_json_save(report, output) + print(json.dumps({"output": str(output), "real": report["real"]}), flush=True) + return report + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/eval_pipeline_external.py b/dataset/phase1_noise_20260906/trial_code_staging/eval_pipeline_external.py new file mode 100644 index 0000000000000000000000000000000000000000..bad48e762c3caff563a4b8fcf88330ff3416254c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/eval_pipeline_external.py @@ -0,0 +1,143 @@ +#!/usr/bin/env python3 +"""Held-out evaluation of pipeline A on data Phase 2 never touched. + +Sources: + rain_locked Rain13K Test100+Test1200 (Phase-1 locked test, 1.200 pairs) + noise_locked SIDD scene 008 (locked, 20 pairs) + haze_heldout RESIDE hazy images beyond the first-5000 training window, + filtered so no clean source overlaps train/val groups. + +Center-crop 256 protocol, record-keyed noise, PSNR/SSIM/LPIPS for both the +one-step regression and the refined output. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List, Sequence + +import torch +from torch.utils.data import DataLoader, Dataset + +import infer_scdc_pipeline as pipe +import train_phase2_graph_resshift_v4 as v4 +import train_graph_encoder_v2 as p1 + + +class PairCropDataset(Dataset): + def __init__(self, records: Sequence, size: int = 256) -> None: + self.records = list(records) + self.size = size + + def __len__(self) -> int: + return len(self.records) + + def __getitem__(self, index: int): + record = self.records[index] + degraded, clean = p1.load_pair_uint8(record, self.size) + # Whole-frame view (aspect-squashed) for global-context models. + full = p1._open_rgb(record.degraded).resize((self.size, self.size)) + return { + "degraded": p1._pil_to_tensor(degraded), + "clean": p1._pil_to_tensor(clean), + "full_degraded": p1._pil_to_tensor(full), + "record_id": record.record_id, + } + + +def evaluate_group( + pipeline: "pipe.SCDCPipeline", records: Sequence, name: str, lpips_fn +) -> Dict[str, object]: + loader = DataLoader( + PairCropDataset(records), batch_size=8, shuffle=False, num_workers=4 + ) + acc: Dict[str, Dict[str, List[float]]] = {} + with torch.no_grad(): + for batch in loader: + clean = batch["clean"].to(pipeline.device) + extra = {} + if "full_degraded" in batch and getattr(pipeline, "accepts_full_frame", False): + extra["full_degraded"] = batch["full_degraded"] + result = pipeline.restore( + batch["degraded"], + record_ids=[str(v) for v in batch["record_id"]], + seed=int(pipeline.args.eval_seed), + **extra, + ) + for kind in ("x0_hat", "restored"): + slot = acc.setdefault( + kind, {"psnr": [], "ssim": [], "lpips": []} + ) + slot["psnr"] += v4.rgb_psnr_per_image( + result[kind], clean + ).cpu().tolist() + slot["ssim"] += v4.rgb_ssim_per_image( + result[kind], clean + ).cpu().tolist() + slot["lpips"] += lpips_fn( + result[kind] * 2 - 1, clean * 2 - 1 + ).flatten().cpu().tolist() + report = {"n": len(records)} + for kind, values in acc.items(): + report[kind] = { + metric: sum(items) / len(items) for metric, items in values.items() + } + print(name, json.dumps(report, sort_keys=True), flush=True) + return report + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--refiner", type=Path, + default=Path("outputs/refiner_a_v1/refiner_best.pt"), + ) + parser.add_argument( + "--output", type=Path, + default=Path("outputs/pipeline_eval_external_v1.json"), + ) + parser.add_argument("--haze-count", type=int, default=300) + args = parser.parse_args() + + device = torch.device("cuda") + pipeline = pipe.SCDCPipeline(args.refiner, device, sample_steps=1) + + import lpips + + lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device) + + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rain_locked = [r for r in splits.locked_test if r.degradation == "rain"] + noise_locked = [r for r in splits.locked_test if r.degradation == "noise"] + + # Held-out RESIDE: everything past the training window, minus any record + # whose clean source group appears in train or val. + reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE") + used_groups = { + r.split_group for r in list(splits.train) + list(splits.val) + if r.degradation == "haze" + } + haze_heldout = [ + r for r in reside[5000:] if r.split_group not in used_groups + ][: args.haze_count] + + report = { + "rain_locked_test100_1200": evaluate_group( + pipeline, rain_locked, "rain_locked", lpips_fn + ), + "noise_locked_sidd_scene008": evaluate_group( + pipeline, noise_locked, "noise_locked", lpips_fn + ), + "haze_heldout_reside": evaluate_group( + pipeline, haze_heldout, "haze_heldout", lpips_fn + ), + } + args.output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE", args.output, flush=True) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/eval_v7_external.py b/dataset/phase1_noise_20260906/trial_code_staging/eval_v7_external.py new file mode 100644 index 0000000000000000000000000000000000000000..87272076003c60e66ae14198f9e557fb3c647152 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/eval_v7_external.py @@ -0,0 +1,147 @@ +#!/usr/bin/env python3 +"""External held-out evaluation of a pure v7 checkpoint (no refiner). + +Reuses the gen-2 external protocol verbatim (same locked rain/noise sets, +same RESIDE held-out selection, same crops/metrics via +``eval_pipeline_external.evaluate_group``) so numbers are directly +comparable with ``outputs/gen2_external_v1.json``. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_moe_v6 as v6 +import train_phase2_graph_resshift_v4 as v4 +from visualize_v7_uformer import _load_run_args + + +class V7Pipeline: + def __init__( + self, run_dir: Path, device: torch.device, dose: float = None, + photometric_dose: float = None, checkpoint: str = "best.pt", + pregain_dose: float = None, colour_dose: float = None, + ) -> None: + import train_phase2_unified_v7 as v7 + + self.device = device + self.dose = dose + self.pregain_dose = pregain_dose + self.colour_dose = colour_dose + self.photometric_dose = photometric_dose + self.args = _load_run_args(run_dir) + # Any checkpoint of the run (best.pt, last.pt, milestone_%08d.pt): the + # val-macro selector behind best.pt is known to be a poor proxy for + # the external sets, so milestones/last are evaluated too. + self.checkpoint_name = str(checkpoint) + checkpoint = v4._torch_load(run_dir / self.checkpoint_name, map_location="cpu") + self.model = v7._build_v7_restorer(self.args, device) + self.model.load_state_dict( + checkpoint["ema_state_dict"]["shadow"], strict=True + ) + self.model.eval() + self.phase1, _ = v4.build_frozen_phase1( + self.args.phase1_checkpoint, self.args.phase1_sha256, device + ) + self.checkpoint_step = int(checkpoint["step"]) + print("v7 checkpoint %s step: %d" % (self.checkpoint_name, self.checkpoint_step)) + + accepts_full_frame = True + + @torch.no_grad() + def restore(self, degraded, record_ids=None, seed=20260830, full_degraded=None): + import train_phase2_unified_v7 as v7 + + degraded = degraded.to(self.device) + restored = v7.sample_unified_restoration( + self.model, self.phase1, degraded, + seed=int(seed), record_ids=[str(r) for r in record_ids], + dose=self.dose, + pregain_dose=self.pregain_dose, + colour_dose=self.colour_dose, + full_degraded=None if full_degraded is None else full_degraded.to(self.device), + photometric_dose=self.photometric_dose, + ) + # No refiner stage: the diffusion output IS the pipeline output. + return {"x0_hat": restored, "restored": restored} + + +def degraded_baseline(records, device) -> dict: + from torch.utils.data import DataLoader + + loader = DataLoader( + ext.PairCropDataset(records), batch_size=16, shuffle=False, num_workers=4 + ) + psnr, ssim = [], [] + for batch in loader: + clean = batch["clean"].to(device) + degraded = batch["degraded"].to(device) + psnr += v4.rgb_psnr_per_image(degraded, clean).cpu().tolist() + ssim += v4.rgb_ssim_per_image(degraded, clean).cpu().tolist() + return { + "psnr": sum(psnr) / len(psnr), + "ssim": sum(ssim) / len(ssim), + } + + +def main() -> None: + import lpips + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--run-dir", type=Path, + default=Path("outputs/phase2_v7/uformer_luma8k_seed42"), + ) + parser.add_argument( + "--output", type=Path, default=Path("outputs/v7_external_v1.json") + ) + parser.add_argument( + "--dose", type=float, default=None, + help="DGF guidance dose at the coarse step (None = plain conditioned)", + ) + parser.add_argument( + "--photometric-dose", type=float, default=None, + help="scale of the v8 global exposure head deltas (None = 1.0; 0 = off)", + ) + parser.add_argument("--checkpoint", default="best.pt", help="file inside --run-dir to evaluate") + args = parser.parse_args() + + device = torch.device("cuda") + pipeline = V7Pipeline(args.run_dir, device, dose=args.dose, photometric_dose=args.photometric_dose, + checkpoint=args.checkpoint) + lpips_fn = lpips.LPIPS(net="alex", verbose=False).to(device) + + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rain = [r for r in splits.locked_test if r.degradation == "rain"] + noise = [r for r in splits.locked_test if r.degradation == "noise"] + reside = p1.discover_reside_records(Path(p1_args.data_root) / "RESIDE") + used = { + r.split_group + for r in list(splits.train) + list(splits.val) + if r.degradation == "haze" + } + haze = [r for r in reside[5000:] if r.split_group not in used][:300] + + report = {"run_dir": str(args.run_dir), "dose": args.dose, "photometric_dose": args.photometric_dose, + "checkpoint": pipeline.checkpoint_name, "checkpoint_step": pipeline.checkpoint_step} + for name, records in ( + ("rain_locked", rain), + ("noise_locked_scene008", noise), + ("haze_heldout", haze), + ): + group = ext.evaluate_group(pipeline, records, name, lpips_fn) + group["degraded_baseline"] = degraded_baseline(records, device) + report[name] = group + args.output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/gate_phase1.sh b/dataset/phase1_noise_20260906/trial_code_staging/gate_phase1.sh new file mode 100644 index 0000000000000000000000000000000000000000..c786cb281cd0f28f1982e5c59c345243eaf2cc37 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/gate_phase1.sh @@ -0,0 +1,48 @@ +#!/bin/bash +set -u; cd /home/admin_mcn/scdc_ban; PY=/home/admin_mcn/anaconda3/bin/python +gate_for() { # $1 = run name ; writes outputs/$1_gate.json ; prints pass/score + local name=$1 ckpt=outputs/$1/graph_encoder_best.pt + CUDA_VISIBLE_DEVICES=0 $PY visualize_phase1_graph.py --checkpoint $ckpt --output-dir outputs/phase1_vis/$name > outputs/phase1_vis_$name.log 2>&1 + CAND=$name CUDA_VISIBLE_DEVICES=0 $PY - <<'PYEOF' > outputs/${name}_gate.log 2>&1 +import glob, hashlib, json, math, os, torch, numpy as np +from pathlib import Path +from PIL import Image +import train_phase2_graph_resshift_v4 as v4 +from visualize_phase1_graph import encode, NODES +name = os.environ["CAND"] +files = sorted(glob.glob("/home/admin_mcn/data/Snow100K/realistic/**/*.jpg", recursive=True)) +def load(f): + im = Image.open(f).convert("RGB"); w, h = im.size; s = 256 / min(w, h) + if s > 1: im = im.resize((max(256, math.ceil(w * s)), max(256, math.ceil(h * s))), Image.LANCZOS); w, h = im.size + l, t = (w - 256) // 2, (h - 256) // 2 + return torch.from_numpy(np.asarray(im.crop((l, t, l + 256, t + 256)), dtype=np.float32) / 255.).permute(2, 0, 1) +imgs = torch.stack([load(f) for f in files]) +ck = Path("outputs/%s/graph_encoder_best.pt" % name) +p1, _ = v4.build_frozen_phase1(ck, hashlib.sha256(ck.read_bytes()).hexdigest(), torch.device("cuda")) +enc = encode(p1, imgs.cuda()) +route = dict(zip(NODES, enc["routing"].mean(0).tolist())) +summary = json.load(open("outputs/phase1_vis/%s/summary.json" % name)) +conf = summary["confusion"] +row = lambda prefix: next(v for k, v in conf.items() if k.startswith(prefix)) +hist = json.load(open("outputs/%s/history.json" % name)) +best_f1 = max(e["val"].get("macro_f1", 0.0) for e in hist if "val" in e) +gates = { + "snow_real_free": (route["free1"] + route["free2"], 0.70, ">="), + # not worse than ll_v3 (0.46 haze->rain on the same val); the +0.3 dB + # claim for v8 does not depend on Phase-1 routing improving, only on it + # not regressing and on photometric_state existing. + "haze_to_rain_max": (row("Haze input")["rain"], 0.46, "<="), + "rain_to_rain_min": (row("Rain input")["rain"], 0.55, ">="), + "lowlight_to_lowlight_min": (row("Low-light input")["lowlight"], 0.85, ">="), +} +passed = {k: (v[0] >= v[1] if v[2] == ">=" else v[0] <= v[1]) for k, v in gates.items()} +report = {"candidate": name, "sha256": hashlib.sha256(ck.read_bytes()).hexdigest(), "snow_real_routing": route, + "gates": {k: {"value": v[0], "threshold": v[1], "pass": passed[k]} for k, v in gates.items()}, + "n_pass": int(sum(passed.values())), "pass": bool(all(passed.values())), "best_val_macro_f1": best_f1, + "noise_recall": row("Noise input")["noise"]} +Path("outputs/%s_gate.json" % name).write_text(json.dumps(report, indent=2)) +print(json.dumps(report)) +PYEOF + $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']))" +} +gate_for $1 diff --git a/dataset/phase1_noise_20260906/trial_code_staging/hf_bundle_upload.py b/dataset/phase1_noise_20260906/trial_code_staging/hf_bundle_upload.py new file mode 100644 index 0000000000000000000000000000000000000000..a0f668e93a25d0506d206e05209a6580f44c430e --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/hf_bundle_upload.py @@ -0,0 +1,193 @@ +#!/usr/bin/env python3 +"""Bundle exactly the data this project trains/evaluates on and upload it to +a Hugging Face dataset repo. + +Contents (all paths inside the tars are relative to two roots, recorded in +manifests/path_roots.json so the absolute paths in the manifests can be +rewritten on another machine): + Rain13K.tar every Rain13K file referenced by the Phase-1 splits + (train / val / locked test) and the Phase-2 manifest + RESIDE_used.tar the RESIDE hazy/clear files used in training/val plus + the 300 held-out evaluation scenes + LOLv2.tar LOLv2-real (train + test), as extracted + SIDD_Small.tar SIDD Small sRGB (all 160 scenes; 121 train / 19 val / + 20 locked scene 008) + Snow100K_gt.tar, Snow100K_synthetic.tar the clean pool and the real-OOD + pool used by Phase-1 v5 / Phase-2 identity pairs + manifests/ Phase-2 train/val manifest, quarantine list, file lists + per split, path roots, README +Token: HF_TOKEN environment variable only (never written to disk here). +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import time +from pathlib import Path + +HOME = Path("/home/admin_mcn") +ROOTS = { # absolute prefix -> archive prefix + str(HOME / "data") + "/": "data/", + str(HOME / ".cache" / "kagglehub") + "/": "kagglehub/", +} +REPO = "Anbinh93/image_restoration" + + +def relative(path: str) -> str: + for prefix, target in ROOTS.items(): + if path.startswith(prefix): + return target + path[len(prefix):] + raise ValueError("file outside the known roots: %s" % path) + + +def collect() -> dict: + sys.path.insert(0, str(HOME / "scdc_ban")) + import train_graph_encoder_v2 as p1 + import eval_full_frame as ff + + groups = ff.external_groups(300) + args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(args) + manifest = json.load(open(HOME / "scdc_ban/outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + lists: dict = {} + + def add(name, records): + files = set() + for r in records: + files.add(str(r.degraded)); files.add(str(r.clean)) + lists[name] = sorted(files) + + add("phase1_train", splits.train); add("phase1_val", splits.val); add("phase1_locked_test", splits.locked_test) + add("haze_heldout_300", groups["haze_heldout"]) + m = set() + for key in ("train", "val"): + for r in manifest[key]: + for f in ("degraded", "clean"): + if f in r: + m.add(str(r[f])) + lists["phase2_manifest"] = sorted(m) + return lists + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--staging", type=Path, default=HOME / "hf_staging/image_restoration") + parser.add_argument("--dry-run", action="store_true") + parser.add_argument("--skip-tar", action="store_true", help="tars already built; only upload") + args = parser.parse_args() + staging = args.staging + (staging / "manifests").mkdir(parents=True, exist_ok=True) + + lists = collect() + every = set() + for files in lists.values(): + every.update(files) + by_dataset = {"Rain13K": [], "RESIDE_used": [], "LOLv2": [], "SIDD_Small": []} + for f in sorted(every): + if "kagglehub" in f or "rain13k" in f.lower(): + by_dataset["Rain13K"].append(f) + elif "/RESIDE/" in f: + by_dataset["RESIDE_used"].append(f) + elif "/LOLv2/" in f: + by_dataset["LOLv2"].append(f) + elif "/SIDD/" in f: + by_dataset["SIDD_Small"].append(f) + else: + raise SystemExit("unclassified file: %s" % f) + # whole folders for the pools and the small datasets (LOLv2 / SIDD complete) + folders = { + "LOLv2": str(HOME / "data/LOLv2/lolv2_hf"), + "SIDD_Small": str(HOME / "data/SIDD/SIDD_Small_sRGB_Only"), + "Snow100K_gt": str(HOME / "data/Snow100K/train/all/gt"), + "Snow100K_synthetic": str(HOME / "data/Snow100K/train/all/synthetic"), + } + summary = {} + for name, files in by_dataset.items(): + size = sum(os.path.getsize(f) for f in files if os.path.exists(f)) + summary[name] = {"files": len(files), "bytes": size} + for name, folder in folders.items(): + total = sum(p.stat().st_size for p in Path(folder).rglob("*") if p.is_file()) + summary[name + "(folder)"] = {"bytes": total} + print("SUMMARY", json.dumps(summary), flush=True) + for name, files in lists.items(): + (staging / "manifests" / ("%s_files.txt" % name)).write_text("\n".join(relative(f) for f in files) + "\n") + (staging / "manifests" / "path_roots.json").write_text(json.dumps(ROOTS, indent=2)) + for src in (HOME / "scdc_ban/outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json", + HOME / "scdc_ban/src/data/rain13k_quarantine_v1.json"): + if src.exists(): + (staging / "manifests" / src.name).write_text(src.read_text()) + (staging / "README.md").write_text(README) + if args.dry_run: + return + + def tar(name: str, entries: list, listfile: bool) -> None: + out = staging / ("%s.tar" % name) + if out.exists() and args.skip_tar: + return + cmd = ["tar", "-cf", str(out), "-C", str(HOME), + "--transform", "s|^\\.cache/kagglehub/|kagglehub/|"] + if listfile: + lst = staging / "manifests" / ("_%s.lst" % name) + lst.write_text("\n".join(os.path.relpath(f, HOME) for f in entries) + "\n") + cmd += ["-T", str(lst)] + else: + cmd += [os.path.relpath(entries[0], HOME)] + t0 = time.time() + subprocess.run(cmd, check=True) + print("TAR %s %.2f GB in %.0fs" % (name, out.stat().st_size / 2**30, time.time() - t0), flush=True) + + tar("Rain13K", by_dataset["Rain13K"], True) + tar("RESIDE_used", by_dataset["RESIDE_used"], True) + for name, folder in folders.items(): + tar(name, [folder], False) + for lst in (staging / "manifests").glob("_*.lst"): + lst.unlink() + + from huggingface_hub import HfApi + + token = os.environ.get("HF_TOKEN") + if not token: + raise SystemExit("HF_TOKEN is not set") + api = HfApi(token=token) + api.create_repo(REPO, repo_type="dataset", exist_ok=True) + t0 = time.time() + api.upload_large_folder(repo_id=REPO, repo_type="dataset", folder_path=str(staging), + num_workers=4, print_report_every=60) + print("UPLOAD done in %.0f min -> https://huggingface.co/datasets/%s" % ((time.time() - t0) / 60, REPO), flush=True) + + +README = """--- +license: other +task_categories: [image-to-image] +tags: [image-restoration, deraining, dehazing, denoising, low-light] +--- +# SCDC image restoration data bundle + +Exactly the files used by the SCDC project (blind degradation graph encoder + +unified two-step ResShift restorer): https://github.com/anbinh93/SCDC + +| Archive | Content | +|---|---| +| `Rain13K.tar` | Rain13K pairs referenced by the Phase-1 splits (train / val / locked Test100+Test1200) and the Phase-2 manifest | +| `RESIDE_used.tar` | RESIDE hazy/clear files used for training/validation plus the 300 held-out evaluation scenes | +| `LOLv2.tar` | LOLv2-real, train (689) + test (100) | +| `SIDD_Small.tar` | SIDD Small sRGB, all 160 scenes (121 train / 19 val / 20 locked = scene 008) | +| `Snow100K_gt.tar`, `Snow100K_synthetic.tar` | Snow100K training gt (clean pool) and synthetic snow (real-unknown pool) | +| `manifests/` | `train_val_manifest_v1.json` (Phase-2 train/val, sha digests), `rain13k_quarantine_v1.json`, per-split file lists, `path_roots.json` | + +Paths inside the archives are relative to two roots (see `manifests/path_roots.json`): +`/home/admin_mcn/data/` -> `data/` and `/home/admin_mcn/.cache/kagglehub/` -> `kagglehub/`. +To reuse the manifests on another machine, extract everything under one directory +and rewrite the two absolute prefixes in the JSON files to that directory. + +All datasets belong to their original authors and keep their original licenses +(research use): Rain13K (Jiang et al. / MPRNet compilation), RESIDE (Li et al.), +LOLv2 (Yang et al.), SIDD (Abdelhamed et al.), Snow100K (Liu et al.). +""" + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/infer_scdc_pipeline.py b/dataset/phase1_noise_20260906/trial_code_staging/infer_scdc_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..97cfdece9e614990d8a623bf06c069088cc1149b --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/infer_scdc_pipeline.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +"""Complete SCDC inference pipeline (option A, two-stage). + + degraded -> frozen Phase-1 -> diffusion U-Net (1-step x0 by default, + optional k-step chain) -> refiner decoder -> restored image + +Usage: + # per-domain evaluation on the locked val split + python infer_scdc_pipeline.py --refiner outputs/refiner_a_v1/refiner_best.pt --eval + + # restore arbitrary images from a directory + python infer_scdc_pipeline.py --refiner ... --images in_dir --output out_dir +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, Optional, Sequence + +import torch +from torch import Tensor +from torch.utils.data import DataLoader + +import train_phase2_graph_resshift_v4 as v4 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from src.models.restoration.refiner_decoder import RefinerDecoder + +V4_RUN = Path("outputs/phase2_graph_resshift_v4/gate_d5_seed42") + + +class SCDCPipeline: + """Frozen Phase-1 + frozen one-step regressor + refiner decoder.""" + + def __init__( + self, + refiner_checkpoint: Optional[Path], + device: torch.device, + sample_steps: int = 1, + ) -> None: + if sample_steps < 1: + raise ValueError("sample_steps must be >= 1") + self.device = device + self.sample_steps = int(sample_steps) + cfg = json.loads((V4_RUN / "run_config.json").read_text()) + args = argparse.Namespace(**cfg) + for key in ("manifest", "data_root", "phase1_checkpoint"): + setattr(args, key, Path(str(getattr(args, key)))) + self.args = args + self.regressor = v4._build_restorer(args, device) + checkpoint = v4._torch_load(V4_RUN / "best.pt") + self.regressor.load_state_dict( + checkpoint["ema_state_dict"]["shadow"], strict=True + ) + self.regressor.eval() + for parameter in self.regressor.parameters(): + parameter.requires_grad_(False) + self.phase1, _ = v4.build_frozen_phase1( + args.phase1_checkpoint, args.phase1_sha256, device + ) + self.refiner: Optional[RefinerDecoder] = None + if refiner_checkpoint is not None: + state = torch.load(str(refiner_checkpoint), map_location="cpu") + refiner = RefinerDecoder() + refiner.load_state_dict(state["refiner_state_dict"], strict=True) + self.refiner = refiner.to(device).eval() + + @torch.no_grad() + def regress_x0( + self, degraded: Tensor, record_ids: Optional[Sequence[str]], seed: int + ) -> Tensor: + if self.sample_steps > 1: + return v4.sample_restoration( + self.regressor, self.phase1, degraded, + seed=seed, record_ids=list(record_ids) if record_ids else None, + ) + padded, size = v4.pad_to_multiple(degraded, multiple=16) + representation = self.phase1(padded) + condition = self.regressor.build_condition(representation) + uy = v4.pixel_unshuffle2(padded) + noise = v4._noise_for_records( + uy, list(record_ids) if record_ids else None, seed=seed, stage="initial" + ) + eta_terminal = self.regressor.schedule.eta[-1].to(uy.device, uy.dtype) + kappa = self.regressor.schedule.kappa.to(uy.device, uy.dtype) + u_terminal = uy + kappa * torch.sqrt(eta_terminal) * noise + timesteps = torch.full( + (uy.shape[0],), self.regressor.schedule.timesteps, + device=uy.device, dtype=torch.long, + ) + u0_hat = self.regressor.predict_x0(u_terminal, uy, timesteps, condition) + out = v4.pixel_shuffle2(u0_hat) + height, width = size + return out[..., :height, :width].clamp(0.0, 1.0) + + @torch.no_grad() + def restore( + self, + degraded: Tensor, + record_ids: Optional[Sequence[str]] = None, + seed: int = 20260830, + ) -> Dict[str, Tensor]: + degraded = degraded.to(self.device) + x0_hat = self.regress_x0(degraded, record_ids, seed) + if self.refiner is None: + return {"x0_hat": x0_hat, "restored": x0_hat} + padded_x0, size = v4.pad_to_multiple(x0_hat, multiple=4) + padded_y, _ = v4.pad_to_multiple(degraded, multiple=4) + refined = self.refiner(padded_x0, padded_y) + height, width = size + return {"x0_hat": x0_hat, "restored": refined[..., :height, :width]} + + +def run_eval(pipeline: SCDCPipeline, output: Path) -> None: + splits = load_train_val_manifest(pipeline.args.manifest) + loader = DataLoader( + Phase2PairDataset(splits.val, crop_size=256, training=False, + upscale_small=True), + batch_size=8, shuffle=False, num_workers=4, + ) + acc: Dict[str, Dict[str, list]] = {} + for batch in loader: + clean = batch["clean"].to(pipeline.device) + result = pipeline.restore( + batch["degraded"], + record_ids=[str(v) for v in batch["record_id"]], + seed=int(pipeline.args.eval_seed), + ) + for name in ("x0_hat", "restored"): + psnr = v4.rgb_psnr_per_image(result[name], clean).cpu().tolist() + ssim = v4.rgb_ssim_per_image(result[name], clean).cpu().tolist() + for domain, p, s in zip( + [str(v) for v in batch["degradation"]], psnr, ssim + ): + slot = acc.setdefault(name, {}).setdefault( + domain, {"psnr": [], "ssim": []} + ) + slot["psnr"].append(p) + slot["ssim"].append(s) + report: Dict[str, object] = {"sample_steps": pipeline.sample_steps} + for name, domains in acc.items(): + block = {} + for domain, values in sorted(domains.items()): + block[domain] = { + "psnr": sum(values["psnr"]) / len(values["psnr"]), + "ssim": sum(values["ssim"]) / len(values["ssim"]), + "count": len(values["psnr"]), + } + block["macro_psnr"] = sum(v["psnr"] for v in block.values()) / len(block) + block["macro_ssim"] = sum( + v["ssim"] for v in block.values() if isinstance(v, dict) + ) / len([v for v in block.values() if isinstance(v, dict)]) + report[name] = block + output.parent.mkdir(parents=True, exist_ok=True) + output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print(json.dumps(report, indent=2, sort_keys=True)) + + +def run_images(pipeline: SCDCPipeline, images: Path, output: Path) -> None: + from PIL import Image + import numpy as np + + output.mkdir(parents=True, exist_ok=True) + paths = sorted( + p for p in images.iterdir() + if p.suffix.lower() in (".png", ".jpg", ".jpeg", ".bmp") + ) + for path in paths: + array = np.asarray( + Image.open(path).convert("RGB"), dtype=np.float32 + ) / 255.0 + tensor = torch.from_numpy(array).permute(2, 0, 1).unsqueeze(0) + restored = pipeline.restore(tensor)["restored"][0] + out = (restored.clamp(0, 1).cpu().permute(1, 2, 0).numpy() * 255).astype( + "uint8" + ) + Image.fromarray(out).save(output / path.name) + print("restored", path.name, flush=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--refiner", type=Path, default=None) + parser.add_argument("--sample-steps", type=int, default=1) + parser.add_argument("--eval", action="store_true") + parser.add_argument("--images", type=Path, default=None) + parser.add_argument("--output", type=Path, + default=Path("outputs/pipeline_eval.json")) + args = parser.parse_args() + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + pipeline = SCDCPipeline(args.refiner, device, sample_steps=args.sample_steps) + if args.eval: + run_eval(pipeline, args.output) + if args.images is not None: + run_images(pipeline, args.images, args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/make_clean_pools.py b/dataset/phase1_noise_20260906/trial_code_staging/make_clean_pools.py new file mode 100644 index 0000000000000000000000000000000000000000..48e5d88e75103f8e85817098ad2ce5fa8f9ba612 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/make_clean_pools.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 +"""Build the identity-pair clean pools as symlink folders from the TRAIN +split only (SIDD GT of the 121 train pairs, LOL GT of the 689 train pairs), +so no validation / locked-test clean image ever enters training.""" + +import os +from pathlib import Path + +import train_graph_encoder_v2 as p1 + + +def main() -> None: + args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(args) + pools = { + "sidd_train_gt": sorted({str(r.clean) for r in splits.train if r.degradation == "noise"}), + "lol_train_gt": sorted({str(r.clean) for r in splits.train if r.degradation == "lowlight"}), + } + held = {str(r.clean) for r in list(splits.val) + list(splits.locked_test)} + for name, files in pools.items(): + assert not (set(files) & held), name + root = Path("outputs/clean_pools") / name + root.mkdir(parents=True, exist_ok=True) + for index, source in enumerate(files): + target = root / ("%05d_%s" % (index, Path(source).name)) + if not target.exists(): + os.symlink(source, target) + print(name, len(files), "files") + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/make_final_charts.py b/dataset/phase1_noise_20260906/trial_code_staging/make_final_charts.py new file mode 100644 index 0000000000000000000000000000000000000000..3c7c77de6d2c8493ffd117d5fdb05e99f1c3143d --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/make_final_charts.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +"""Static slide charts for the SCDC final report (matplotlib, light surface). + +Palette: validated categorical slots (blue, orange, aqua, yellow) in fixed +order; text in ink tokens; thin marks; recessive grid; no dual axes. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt + +SURFACE = "#fcfcfb" +INK = "#0b0b0b" +INK2 = "#52514e" +GRID = "#e6e5e1" +C = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"] # fixed categorical order +NEUTRAL = "#b9b8b3" + + +def _style(ax, title, xlabel=""): + ax.set_facecolor(SURFACE) + for side in ("top", "right", "left"): + ax.spines[side].set_visible(False) + ax.spines["bottom"].set_color(GRID) + ax.tick_params(colors=INK2, length=0) + ax.grid(axis="x", color=GRID, linewidth=0.8) + ax.set_axisbelow(True) + ax.set_title(title, loc="left", color=INK, fontsize=12, fontweight="semibold") + if xlabel: + ax.set_xlabel(xlabel, color=INK2) + + +def chart_progression(out: Path) -> None: + rows = [ + ("v4 ResShift 1-step (conv, 8-step train)", 22.68, 0.662, NEUTRAL), + ("v7 unified 2-step (conv, warm-start)", 23.41, 0.703, NEUTRAL), + ("v7 Uformer, from scratch 8k", 25.26, 0.777, C[0]), + ("+ chroma loss, warm-restart 16k", 26.44, 0.808, C[0]), + ("+ luma loss, 8k", 26.59, 0.811, C[0]), + ("+ full-res head + FiLM, 8k", 27.43, 0.846, C[0]), + ("+ DGF (null tokens, identity, pyramid), 8k", 27.50, 0.850, C[0]), + ("ref: Pipeline A (2 networks)", 26.76, 0.863, C[1]), + ("ref: gen-2 (2 networks)", 27.55, 0.874, C[1]), + ] + fig, ax = plt.subplots(figsize=(10, 5.2), facecolor=SURFACE) + names = [r[0] for r in rows][::-1] + vals = [r[1] for r in rows][::-1] + cols = [r[3] for r in rows][::-1] + ssim = [r[2] for r in rows][::-1] + import numpy as np + pos = np.arange(len(names)) + bars = ax.barh(pos, vals, color=cols, height=0.62, align="center") + ax.set_yticks(pos) + ax.set_yticklabels(names, color=INK, fontsize=9) + for y, v, s in zip(pos, vals, ssim): + ax.text(v + 0.06, y, "%.2f dB · SSIM %.3f" % (v, s), + va="center", ha="left", color=INK, fontsize=9) + ax.set_xlim(22, 28.6) + _style(ax, "Internal validation: macro PSNR by version\n(one network in blue, two-network references in orange)", "PSNR (dB)") + fig.tight_layout() + fig.savefig(str(out), dpi=160, facecolor=SURFACE) + plt.close(fig) + + +def chart_external(out: Path) -> None: + sets = ["Rain (locked, 1200)", "Haze (held-out, 300)", "Noise scene008 (20)"] + series = [ + ("Degraded input", [22.56, 18.17, 39.02], NEUTRAL), + ("gen-2, two networks", [26.71, 31.18, 22.35], C[1]), + ("head8k, one network", [28.02, 31.71, 27.09], C[0]), + ("DGF (w=1), one network", [27.88, 31.87, 26.50], C[2]), + ] + fig, ax = plt.subplots(figsize=(10, 4.6), facecolor=SURFACE) + import numpy as np + x = np.arange(len(sets)) + w = 0.19 + for i, (label, vals, col) in enumerate(series): + bars = ax.bar(x + (i - 1.5) * w, vals, width=w - 0.02, color=col, label=label) + for b, v in zip(bars, vals): + ax.text(b.get_x() + b.get_width() / 2, v + 0.4, "%.1f" % v, ha="center", va="bottom", color=INK, fontsize=8) + ax.set_xticks(x) + ax.set_xticklabels(sets, color=INK) + ax.set_ylim(15, 42) + ax.grid(axis="y", color=GRID, linewidth=0.8) + ax.grid(False, axis="x") + _style(ax, "External held-out PSNR\n(one network beats the two-network pipeline out of distribution)", "") + ax.set_ylabel("PSNR (dB)", color=INK2) + ax.legend(frameon=False, ncol=2, loc="upper center", fontsize=9) + fig.tight_layout() + fig.savefig(str(out), dpi=160, facecolor=SURFACE) + plt.close(fig) + + +def chart_probe(out: Path) -> None: + rows = [ + ("context (cross-attention tokens)", -3.68), + ("global_vector (adaLN)", -3.45), + ("unknown_residual (field)", -0.74), + ("global_condition (field)", -0.24), + ("node_tokens (field)", -0.16), + ("MoE gate + per-type κ (uniform)", -0.085), + ("routing_probs (field)", -0.05), + ("severity_coords (field)", -0.03), + ("spatial maps 16×16 (inject)", -0.01), + ("content latent 64 px (inject)", 0.00), + ] + fig, ax = plt.subplots(figsize=(10, 4.8), facecolor=SURFACE) + names = [r[0] for r in rows][::-1] + vals = [r[1] for r in rows][::-1] + cols = [C[0] if v < -1 else (C[3] if v < -0.1 else NEUTRAL) for v in vals] + import numpy as np + pos = np.arange(len(names)) + ax.barh(pos, vals, color=cols, height=0.62, align="center") + ax.set_yticks(pos) + ax.set_yticklabels(names, color=INK, fontsize=9) + for y, v in zip(pos, vals): + if v < -0.3: + ax.text(v - 0.05, y, "%+.2f dB" % v, va="center", ha="right", color=INK, fontsize=9) + else: + ax.text(0.06, y, "%+.2f dB" % v, va="center", ha="left", color=INK, fontsize=9) + ax.set_xlim(-4.2, 0.6) + _style(ax, "Inference-time ablation (head8k)\nmacro PSNR change when one Phase-1 tap is removed", "Δ macro PSNR (dB)") + fig.tight_layout() + fig.savefig(str(out), dpi=160, facecolor=SURFACE) + plt.close(fig) + + +def chart_control(out: Path, control: dict, conditioned: dict) -> None: + steps = sorted(set(control) & set(conditioned)) + fig, ax = plt.subplots(figsize=(10, 4.4), facecolor=SURFACE) + 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)") + 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)") + for s in (steps[-1],): + ax.text(s - 120, conditioned[s] + 0.12, "%.2f" % conditioned[s], color=INK, fontsize=9, ha="right") + ax.text(s - 120, control[s] - 0.3, "%.2f" % control[s], color=INK, fontsize=9, ha="right") + ax.set_xlabel("fine-tune step", color=INK2) + ax.set_ylabel("macro PSNR (dB)", color=INK2) + ax.grid(axis="y", color=GRID, linewidth=0.8) + ax.grid(False, axis="x") + _style(ax, "Does the trunk need Phase-1?\n(same recipe and warm start; conditioning on vs. off)", "") + ax.legend(frameon=False, loc="lower right", fontsize=9) + fig.tight_layout() + fig.savefig(str(out), dpi=160, facecolor=SURFACE) + plt.close(fig) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out-dir", type=Path, default=Path("outputs/final_charts")) + parser.add_argument("--control-metrics", type=Path, default=None) + parser.add_argument("--conditioned-metrics", type=Path, default=None) + args = parser.parse_args() + args.out_dir.mkdir(parents=True, exist_ok=True) + chart_progression(args.out_dir / "01_version_progression.png") + chart_external(args.out_dir / "02_external.png") + chart_probe(args.out_dir / "03_tap_probe.png") + if args.control_metrics and args.conditioned_metrics: + def evals(path): + out = {} + for line in open(path): + r = json.loads(line) + if r.get("event") == "evaluation": + out[int(r["step"])] = float(r["macro_psnr"]) + return out + chart_control(args.out_dir / "04_phase1_control.png", evals(args.control_metrics), evals(args.conditioned_metrics)) + print("charts written to", args.out_dir) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/probe_color_space.py b/dataset/phase1_noise_20260906/trial_code_staging/probe_color_space.py new file mode 100644 index 0000000000000000000000000000000000000000..1c6ecb21d50e859a481a9f4190100b9d660d519f --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/probe_color_space.py @@ -0,0 +1,291 @@ +#!/usr/bin/env python3 +"""Does an HVI colour state buy Phase-1 / Phase-2 anything? Three measurements, +no training required. + +H1 Representation: per-image colour features in HVI (hvi_colour_stats) vs the + current photometric stats (RGB/luma) vs YUV chroma stats — 5-fold linear + probe for {rain, noise, haze, lowlight, clean, real snow}; also a + colour-only variant (chroma features alone) to isolate the colour space. +H2 Error anatomy of the current Phase-2 (run A): how much of the remaining + squared error sits in the HV (colour) plane vs the I plane, per domain. +H3 Controllability ceiling: per-image GLOBAL fits on the output — I affine + (exposure knob), HV affine (colour knob: 2x2 matrix + bias), both — and + the PSNR each recovers. An upper bound on what a per-image colour + conditioning could deliver. +""" + +from __future__ import annotations + +import argparse +import glob +import json +import math +from pathlib import Path +from typing import Dict, List, Sequence, Tuple + +import numpy as np +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_unified_v7 as v7 +from eval_v7_external import V7Pipeline +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from src.models.graph_encoder.encoder import photometric_stats +from src.models.graph_encoder.hvi import ( + HVI_STAT_NAMES, hvi_colour_stats, hvi_to_rgb, rgb_to_hvi, +) + +DOMAINS = ("rain", "noise", "haze", "lowlight") +CLASSES = ("rain", "noise", "haze", "lowlight", "clean", "snow_real") +_EPS = 1e-8 + + +# --------------------------------------------------------------------------- # +# feature sets +# --------------------------------------------------------------------------- # +def _hh1_mad(plane: torch.Tensor) -> torch.Tensor: + x = plane[:, None] + hh = (x[..., 0::2, 0::2] - x[..., 0::2, 1::2] - x[..., 1::2, 0::2] + x[..., 1::2, 1::2]) / 2.0 + return hh.abs().flatten(1).median(dim=1).values / 0.6745 + + +def yuv_stats(rgb: torch.Tensor) -> torch.Tensor: + uv = v7.rgb_to_uv(rgb) + y = v7.rgb_to_luma(rgb)[:, 0] + radius = uv.norm(dim=1).flatten(1) + yf = y.flatten(1) + return torch.stack(( + uv[:, 0].flatten(1).mean(1), uv[:, 1].flatten(1).mean(1), + radius.mean(1), radius.std(1), radius.quantile(0.95, dim=1), + _hh1_mad(uv[:, 0]), _hh1_mad(uv[:, 1]), + yf.mean(1), yf.std(1), yf.quantile(0.05, dim=1), yf.quantile(0.95, dim=1), + ), dim=1) + + +FEATURE_SETS = { + "rgb_photometric14": lambda x, k: photometric_stats(x), + "yuv11": lambda x, k: yuv_stats(x), + "hvi13": lambda x, k: hvi_colour_stats(x, k), + # colour-only slices (no luminance information at all) + "rgb_colour3": lambda x, k: photometric_stats(x)[:, 6:9], + "yuv_colour7": lambda x, k: yuv_stats(x)[:, :7], + "hvi_colour7": lambda x, k: hvi_colour_stats(x, k)[:, :7], +} + + +@torch.no_grad() +def features_for(images: torch.Tensor, k: float, batch: int = 32) -> Dict[str, np.ndarray]: + out: Dict[str, List[torch.Tensor]] = {n: [] for n in FEATURE_SETS} + for start in range(0, images.shape[0], batch): + chunk = images[start:start + batch].float() + for name, fn in FEATURE_SETS.items(): + out[name].append(fn(chunk, k).float().cpu()) + return {n: torch.cat(v).numpy() for n, v in out.items()} + + +# --------------------------------------------------------------------------- # +# linear probe (torch multinomial logistic regression, 5-fold stratified) +# --------------------------------------------------------------------------- # +def _fit_logreg(x: torch.Tensor, y: torch.Tensor, n_classes: int, l2: float = 1e-3) -> torch.nn.Linear: + model = torch.nn.Linear(x.shape[1], n_classes) + opt = torch.optim.LBFGS(model.parameters(), lr=0.5, max_iter=300, line_search_fn="strong_wolfe") + counts = torch.bincount(y, minlength=n_classes).float().clamp_min(1) + weight = counts.sum() / (n_classes * counts) # class-balanced CE + + def closure(): + opt.zero_grad() + loss = torch.nn.functional.cross_entropy(model(x), y, weight=weight) + loss = loss + l2 * model.weight.square().sum() + loss.backward() + return loss + + opt.step(closure) + return model + + +def linear_probe(features: np.ndarray, labels: np.ndarray, n_classes: int, folds: int = 5, seed: int = 0) -> Dict[str, object]: + rng = np.random.RandomState(seed) + fold_of = np.zeros(len(labels), dtype=int) + for c in range(n_classes): + idx = np.where(labels == c)[0] + rng.shuffle(idx) + for f, chunk in enumerate(np.array_split(idx, folds)): + fold_of[chunk] = f + confusion = np.zeros((n_classes, n_classes), dtype=np.int64) + for f in range(folds): + tr, te = fold_of != f, fold_of == f + mu, sd = features[tr].mean(0), features[tr].std(0) + 1e-6 + xtr = torch.tensor((features[tr] - mu) / sd, dtype=torch.float32) + xte = torch.tensor((features[te] - mu) / sd, dtype=torch.float32) + model = _fit_logreg(xtr, torch.tensor(labels[tr]), n_classes) + with torch.no_grad(): + pred = model(xte).argmax(1).numpy() + for t, p in zip(labels[te], pred): + confusion[t, p] += 1 + recall = confusion.diagonal() / confusion.sum(1).clip(min=1) + return { + "balanced_accuracy": float(recall.mean()), + "per_class_recall": {CLASSES[i]: float(recall[i]) for i in range(n_classes)}, + "confusion": confusion.tolist(), + } + + +# --------------------------------------------------------------------------- # +# H2 / H3 on Phase-2 outputs +# --------------------------------------------------------------------------- # +def _lstsq(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + """Least squares a @ x = b (a [N,p], b [N,q]) via normal equations.""" + ata = a.T @ a + 1e-6 * torch.eye(a.shape[1], device=a.device, dtype=a.dtype) + return torch.linalg.solve(ata, a.T @ b) + + +def _psnr(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor: + return v4.rgb_psnr_per_image(x.clamp(0, 1), y) + + +@torch.no_grad() +def error_anatomy(restored: torch.Tensor, clean: torch.Tensor, k: float) -> Dict[str, torch.Tensor]: + hvi_r, hvi_c = rgb_to_hvi(restored, k), rgb_to_hvi(clean, k) + err = (hvi_r - hvi_c).square().flatten(2).mean(2) # [B,3] + uv_err = (v7.rgb_to_uv(restored) - v7.rgb_to_uv(clean)).square().flatten(2).mean(2).sum(1) + y_err = (v7.rgb_to_luma(restored) - v7.rgb_to_luma(clean)).square().flatten(1).mean(1) + n = restored.shape[0] + i_fit, hv_fit, both = [], [], [] + for i in range(n): + r, c = hvi_r[i].double(), hvi_c[i].double() + ones = torch.ones_like(r[2].flatten()) + # intensity affine + a_i = torch.stack((r[2].flatten(), ones), 1) + coef = _lstsq(a_i, c[2].flatten()[:, None]) + i_new = (a_i @ coef).reshape(r[2].shape).clamp(0, 1) + # HV affine (2x2 + bias) + a_hv = torch.stack((r[0].flatten(), r[1].flatten(), ones), 1) + coef_hv = _lstsq(a_hv, torch.stack((c[0].flatten(), c[1].flatten()), 1)) + hv_new = (a_hv @ coef_hv).T.reshape(2, *r[0].shape) + i_fit.append(torch.stack((r[0], r[1], i_new)).float()) + hv_fit.append(torch.stack((hv_new[0].float(), hv_new[1].float(), r[2].float()))) + both.append(torch.stack((hv_new[0].float(), hv_new[1].float(), i_new.float()))) + to_rgb = lambda lst: hvi_to_rgb(torch.stack(lst), k) + return { + "mse_H": err[:, 0], "mse_V": err[:, 1], "mse_I": err[:, 2], + "mse_UV": uv_err, "mse_Y": y_err, + "psnr_raw": _psnr(restored, clean), + "psnr_I_affine": _psnr(to_rgb(i_fit), clean), + "psnr_HV_affine": _psnr(to_rgb(hv_fit), clean), + "psnr_both": _psnr(to_rgb(both), clean), + "psnr_hvi_roundtrip": _psnr(hvi_to_rgb(hvi_r, k), clean), + } + + +# --------------------------------------------------------------------------- # +def _load_dir_images(pattern: str, size: int = 256) -> torch.Tensor: + from PIL import Image + files = sorted(glob.glob(pattern, recursive=True)) + out = [] + for f in files: + im = Image.open(f).convert("RGB") + w, h = im.size + s = size / min(w, h) + if s > 1: + im = im.resize((max(size, math.ceil(w * s)), max(size, math.ceil(h * s))), Image.LANCZOS) + w, h = im.size + l, t = (w - size) // 2, (h - size) // 2 + im = im.crop((l, t, l + size, t + size)) + out.append(torch.from_numpy(np.asarray(im, dtype=np.float32) / 255.0).permute(2, 0, 1)) + return torch.stack(out) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, default=Path("outputs/phase2_v7/uformer_p5_8k_seed42")) + parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + parser.add_argument("--snow-glob", default="/home/admin_mcn/data/Snow100K/realistic/**/*.jpg") + parser.add_argument("--output", type=Path, default=Path("outputs/color_space_probe.json")) + parser.add_argument("--k", type=float, default=0.2) + parser.add_argument("--device", default="cuda") + args = parser.parse_args() + device = torch.device(args.device) + + splits = load_train_val_manifest(args.manifest) + dataset = Phase2PairDataset(splits.val, crop_size=256, training=False, upscale_small=True) + groups: Dict[str, torch.Tensor] = {} + pairs: Dict[str, Tuple[torch.Tensor, torch.Tensor, List[str], torch.Tensor]] = {} + for d in DOMAINS: + idx = [i for i, r in enumerate(splits.val) if r.degradation == d] + items = [dataset[i] for i in idx] + deg = torch.stack([it["degraded"] for it in items]) + cln = torch.stack([it["clean"] for it in items]) + full = torch.stack([it["full_degraded"] for it in items]) + groups[d] = deg + groups["clean_" + d] = cln + pairs[d] = (deg, cln, [it["record_id"] for it in items], full) + p1_args = p1.build_parser().parse_args([]) + ext_splits = p1.build_data_splits(p1_args) + s8 = [r for r in ext_splits.locked_test if r.degradation == "noise"] + ds8 = ext.PairCropDataset(s8) + it8 = [ds8[i] for i in range(len(s8))] + groups["scene008_input"] = torch.stack([it["degraded"] for it in it8]) + groups["scene008_clean"] = torch.stack([it["clean"] for it in it8]) + pairs["scene008"] = (groups["scene008_input"], groups["scene008_clean"], + [it["record_id"] for it in it8], torch.stack([it["full_degraded"] for it in it8])) + groups["snow_real"] = _load_dir_images(args.snow_glob) + print("groups:", {k: int(v.shape[0]) for k, v in groups.items()}) + + # ---- H1 ------------------------------------------------------------- # + feats_by_group = {g: features_for(x.to(device), args.k) for g, x in groups.items()} + label_of = {d: i for i, d in enumerate(DOMAINS)} + rows, labels = {n: [] for n in FEATURE_SETS}, [] + for g, feats in feats_by_group.items(): + if g in label_of: + lab = label_of[g] + elif g.startswith("clean_") or g.startswith("scene008"): + lab = CLASSES.index("clean") + else: + lab = CLASSES.index("snow_real") + n = next(iter(feats.values())).shape[0] + labels.extend([lab] * n) + for name in FEATURE_SETS: + rows[name].append(feats[name]) + labels = np.array(labels) + h1 = {} + for name in FEATURE_SETS: + h1[name] = linear_probe(np.concatenate(rows[name]), labels, len(CLASSES)) + print("H1 %-20s bal.acc %.3f recall %s" % ( + name, h1[name]["balanced_accuracy"], + " ".join("%s=%.2f" % (c[:5], v) for c, v in h1[name]["per_class_recall"].items()))) + union = np.concatenate([np.concatenate(rows[n]) for n in ("rgb_photometric14", "hvi13")], axis=1) + h1["rgb14+hvi13"] = linear_probe(union, labels, len(CLASSES)) + print("H1 %-20s bal.acc %.3f" % ("rgb14+hvi13", h1["rgb14+hvi13"]["balanced_accuracy"])) + # group-mean HVI stats (for the report) + h1["group_mean_hvi"] = {g: dict(zip(HVI_STAT_NAMES, np.round(f["hvi13"].mean(0), 4).tolist())) + for g, f in feats_by_group.items()} + + # ---- H2 / H3 -------------------------------------------------------- # + pipe = V7Pipeline(args.run_dir, device) + h23 = {} + for name, (deg, cln, ids, full) in pairs.items(): + acc: Dict[str, List[torch.Tensor]] = {} + for start in range(0, deg.shape[0], 8): + sl = slice(start, start + 8) + restored = pipe.restore(deg[sl].to(device), record_ids=ids[sl], + full_degraded=full[sl].to(device))["restored"].float().clamp(0, 1) + for key, val in error_anatomy(restored, cln[sl].to(device), args.k).items(): + acc.setdefault(key, []).append(val.cpu()) + means = {k: float(torch.cat(v).mean()) for k, v in acc.items()} + hv = means["mse_H"] + means["mse_V"] + means["share_HV_of_HVI"] = hv / (hv + means["mse_I"] + _EPS) + means["share_UV_of_YUV"] = means["mse_UV"] / (means["mse_UV"] + means["mse_Y"] + _EPS) + means["n"] = int(deg.shape[0]) + h23[name] = means + 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" % ( + name, means["n"], means["psnr_raw"], means["psnr_I_affine"], means["psnr_HV_affine"], + means["psnr_both"], means["share_HV_of_HVI"], means["share_UV_of_YUV"], means["psnr_hvi_roundtrip"])) + + args.output.write_text(json.dumps({"run_dir": str(args.run_dir), "k": args.k, "H1": h1, "H2H3": h23}, indent=2)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/probe_global_knob.py b/dataset/phase1_noise_20260906/trial_code_staging/probe_global_knob.py new file mode 100644 index 0000000000000000000000000000000000000000..14ea0e5c5db9b1474e6fa20af7302d92584b6a18 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/probe_global_knob.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Is the per-image global photometric correction PREDICTABLE from the input? + +probe_color_space.py measured an oracle ceiling: fitting a global intensity +affine (2 params) and a global HV-plane affine (6 params) on the Phase-2 +output against GT recovers up to +7 dB (lowlight). Here we ask how much of +that a Phase-1-style predictor could deliver: ridge-regress the oracle +coefficients from blind input features (photometric14 + hvi13 of the crop and +of the whole frame), 5-fold, then apply the PREDICTED coefficients and measure +PSNR. Reports raw / predicted-knob / oracle-knob per domain, and R^2 per +coefficient. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Dict, List + +import numpy as np +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from eval_v7_external import V7Pipeline +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from src.models.graph_encoder.encoder import photometric_stats +from src.models.graph_encoder.hvi import hvi_colour_stats, hvi_to_rgb, rgb_to_hvi + +DOMAINS = ("rain", "noise", "haze", "lowlight") + + +def _lstsq(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + ata = a.T @ a + 1e-6 * torch.eye(a.shape[1], device=a.device, dtype=a.dtype) + return torch.linalg.solve(ata, a.T @ b) + + +@torch.no_grad() +def oracle_coefficients(restored: torch.Tensor, clean: torch.Tensor, k: float): + """Per image: I affine (a, b) and HV affine (2x3) fitted to GT.""" + hr, hc = rgb_to_hvi(restored, k).double(), rgb_to_hvi(clean, k).double() + coef_i, coef_hv = [], [] + for i in range(restored.shape[0]): + ones = torch.ones_like(hr[i, 2].flatten()) + a_i = torch.stack((hr[i, 2].flatten(), ones), 1) + coef_i.append(_lstsq(a_i, hc[i, 2].flatten()[:, None]).flatten()) + a_hv = torch.stack((hr[i, 0].flatten(), hr[i, 1].flatten(), ones), 1) + coef_hv.append(_lstsq(a_hv, torch.stack((hc[i, 0].flatten(), hc[i, 1].flatten()), 1)).flatten()) + return torch.stack(coef_i).float(), torch.stack(coef_hv).float() + + +@torch.no_grad() +def apply_knobs(restored: torch.Tensor, coef_i: torch.Tensor, coef_hv: torch.Tensor, k: float, + use_i: bool, use_hv: bool) -> torch.Tensor: + hvi = rgb_to_hvi(restored, k) + h, v, inten = hvi[:, 0], hvi[:, 1], hvi[:, 2] + if use_i: + inten = (inten * coef_i[:, 0, None, None] + coef_i[:, 1, None, None]).clamp(0, 1) + if use_hv: + m = coef_hv.view(-1, 3, 2) # rows: [h, v, 1] -> columns [h', v'] + h_new = h * m[:, 0, 0, None, None] + v * m[:, 1, 0, None, None] + m[:, 2, 0, None, None] + v_new = h * m[:, 0, 1, None, None] + v * m[:, 1, 1, None, None] + m[:, 2, 1, None, None] + h, v = h_new, v_new + return hvi_to_rgb(torch.stack((h, v, inten), 1), k) + + +def ridge_cv(x: np.ndarray, y: np.ndarray, folds: int = 5, alpha: float = 1.0, seed: int = 0) -> np.ndarray: + """Return out-of-fold predictions of y from x (standardised ridge).""" + rng = np.random.RandomState(seed) + order = rng.permutation(len(x)) + pred = np.zeros_like(y) + for f, te in enumerate(np.array_split(order, folds)): + tr = np.setdiff1d(order, te) + mu, sd = x[tr].mean(0), x[tr].std(0) + 1e-6 + xtr, xte = (x[tr] - mu) / sd, (x[te] - mu) / sd + xtr = np.concatenate([xtr, np.ones((len(xtr), 1))], 1) + xte = np.concatenate([xte, np.ones((len(xte), 1))], 1) + reg = alpha * np.eye(xtr.shape[1]); reg[-1, -1] = 0.0 + w = np.linalg.solve(xtr.T @ xtr + reg, xtr.T @ y[tr]) + pred[te] = xte @ w + return pred + + +def r2(y: np.ndarray, p: np.ndarray) -> float: + ss_res = ((y - p) ** 2).sum(0) + ss_tot = ((y - y.mean(0)) ** 2).sum(0) + 1e-12 + return float(np.mean(1.0 - ss_res / ss_tot)) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, default=Path("outputs/phase2_v7/uformer_p5_8k_seed42")) + parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + parser.add_argument("--output", type=Path, default=Path("outputs/global_knob_probe.json")) + parser.add_argument("--k", type=float, default=0.2) + parser.add_argument("--alpha", type=float, default=3.0) + args = parser.parse_args() + device = torch.device("cuda") + + splits = load_train_val_manifest(args.manifest) + dataset = Phase2PairDataset(splits.val, crop_size=256, training=False, upscale_small=True) + groups = {} + for d in DOMAINS: + idx = [i for i, r in enumerate(splits.val) if r.degradation == d] + items = [dataset[i] for i in idx] + groups[d] = (torch.stack([it["degraded"] for it in items]), torch.stack([it["clean"] for it in items]), + [it["record_id"] for it in items], torch.stack([it["full_degraded"] for it in items])) + p1_args = p1.build_parser().parse_args([]) + s8 = [r for r in p1.build_data_splits(p1_args).locked_test if r.degradation == "noise"] + ds8 = ext.PairCropDataset(s8) + it8 = [ds8[i] for i in range(len(s8))] + groups["scene008"] = (torch.stack([it["degraded"] for it in it8]), torch.stack([it["clean"] for it in it8]), + [it["record_id"] for it in it8], torch.stack([it["full_degraded"] for it in it8])) + + pipe = V7Pipeline(args.run_dir, device) + report: Dict[str, object] = {"run_dir": str(args.run_dir), "k": args.k, "alpha": args.alpha} + # pooled regression across domains too (a single predictor, as Phase-1 would be) + pooled: Dict[str, List[np.ndarray]] = {"x": [], "ci": [], "chv": [], "domain": []} + per_group: Dict[str, Dict[str, torch.Tensor]] = {} + for name, (deg, cln, ids, full) in groups.items(): + rest, feats, ci, chv = [], [], [], [] + for s in range(0, deg.shape[0], 8): + sl = slice(s, s + 8) + r = pipe.restore(deg[sl].to(device), record_ids=ids[sl], full_degraded=full[sl].to(device))["restored"].float().clamp(0, 1) + a, b = oracle_coefficients(r, cln[sl].to(device), args.k) + x_crop = torch.cat((photometric_stats(deg[sl].to(device)), hvi_colour_stats(deg[sl].to(device), args.k)), 1) + x_full = torch.cat((photometric_stats(full[sl].to(device)), hvi_colour_stats(full[sl].to(device), args.k)), 1) + rest.append(r.cpu()); feats.append(torch.cat((x_crop, x_full), 1).cpu()); ci.append(a.cpu()); chv.append(b.cpu()) + per_group[name] = {"restored": torch.cat(rest), "clean": cln, "x": torch.cat(feats), + "ci": torch.cat(ci), "chv": torch.cat(chv)} + pooled["x"].append(per_group[name]["x"].numpy()); pooled["ci"].append(per_group[name]["ci"].numpy()) + pooled["chv"].append(per_group[name]["chv"].numpy()); pooled["domain"].append(np.full(deg.shape[0], name)) + + X = np.concatenate(pooled["x"]); CI = np.concatenate(pooled["ci"]); CHV = np.concatenate(pooled["chv"]) + DOM = np.concatenate(pooled["domain"]) + pred_ci_pooled = ridge_cv(X, CI, alpha=args.alpha) + pred_chv_pooled = ridge_cv(X, CHV, alpha=args.alpha) + report["pooled_r2"] = {"I_affine": r2(CI, pred_ci_pooled), "HV_affine": r2(CHV, pred_chv_pooled)} + print("pooled R2 I-affine %.3f HV-affine %.3f" % (report["pooled_r2"]["I_affine"], report["pooled_r2"]["HV_affine"])) + + results = {} + for name, g in per_group.items(): + mask = DOM == name + x, ci, chv = g["x"].numpy(), g["ci"].numpy(), g["chv"].numpy() + pred_ci_own = ridge_cv(x, ci, alpha=args.alpha) if len(x) >= 10 else ci * 0 + ci.mean(0) + pred_chv_own = ridge_cv(x, chv, alpha=args.alpha) if len(x) >= 10 else chv * 0 + chv.mean(0) + variants = { + "raw": (None, None), + "oracle_I": (g["ci"], None), "oracle_both": (g["ci"], g["chv"]), + "pred_pooled_I": (torch.tensor(pred_ci_pooled[mask]), None), + "pred_pooled_both": (torch.tensor(pred_ci_pooled[mask]), torch.tensor(pred_chv_pooled[mask])), + "pred_own_I": (torch.tensor(pred_ci_own), None), + "pred_own_both": (torch.tensor(pred_ci_own), torch.tensor(pred_chv_own)), + "domain_mean_I": (torch.tensor(np.broadcast_to(ci.mean(0), ci.shape).copy()), None), + } + row = {"n": int(len(x)), "r2_own_I": r2(ci, pred_ci_own), "r2_own_HV": r2(chv, pred_chv_own), + "r2_pooled_I": r2(ci, pred_ci_pooled[mask]), "r2_pooled_HV": r2(chv, pred_chv_pooled[mask]), + "oracle_gain_mean": float(ci[:, 0].mean()), "oracle_gain_std": float(ci[:, 0].std()), + "oracle_bias_mean": float(ci[:, 1].mean()), "oracle_bias_std": float(ci[:, 1].std())} + for label, (a, b) in variants.items(): + psnrs = [] + for s in range(0, len(x), 16): + sl = slice(s, s + 16) + r = g["restored"][sl].to(device) + if a is None: + out = r + else: + out = apply_knobs(r, a[sl].to(device).float(), (b[sl].to(device).float() if b is not None else None), + args.k, use_i=True, use_hv=b is not None) + psnrs.append(v4.rgb_psnr_per_image(out.clamp(0, 1), g["clean"][sl].to(device)).cpu()) + row["psnr_" + label] = float(torch.cat(psnrs).mean()) + results[name] = row + print("%-9s n=%3d raw %.2f | oracle I %.2f both %.2f | pred(pooled) I %.2f both %.2f | pred(own) I %.2f both %.2f | domain-mean I %.2f | R2 own I %.2f HV %.2f pooled I %.2f HV %.2f | gain %.2f±%.2f bias %.3f±%.3f" % ( + name, row["n"], row["psnr_raw"], row["psnr_oracle_I"], row["psnr_oracle_both"], row["psnr_pred_pooled_I"], + row["psnr_pred_pooled_both"], row["psnr_pred_own_I"], row["psnr_pred_own_both"], row["psnr_domain_mean_I"], + row["r2_own_I"], row["r2_own_HV"], row["r2_pooled_I"], row["r2_pooled_HV"], + row["oracle_gain_mean"], row["oracle_gain_std"], row["oracle_bias_mean"], row["oracle_bias_std"])) + report["groups"] = results + args.output.write_text(json.dumps(report, indent=2)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/probe_phase1_scale.py b/dataset/phase1_noise_20260906/trial_code_staging/probe_phase1_scale.py new file mode 100644 index 0000000000000000000000000000000000000000..68469086901583c0b73e876554320c4579b49def --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/probe_phase1_scale.py @@ -0,0 +1,240 @@ +#!/usr/bin/env python3 +"""Does Phase-1's resize-centre-crop policy hide the degradation it must detect? + +The Phase-1 trainer (``train_graph_encoder_v2.PairDataset``) resizes every pair +so the short side is 256 and takes ONE centre crop. SIDD frames are ~4000x3000, +so the noise class is seen at ~12x downsampling (sensor noise averaged away); +Rain13K (384), LOL (600x400) and RESIDE (~550x413) are seen at ~1.5x. Phase-2 +and the Phase-1 dashboard consume native-resolution 256 crops instead. + +This probe routes the SAME validation pairs through one or more Phase-1 +checkpoints under three policies and reports the routing per domain (and per +ISO for SIDD): + + A trainer policy resize short side -> 256, centre crop + B native centre Phase-2 policy (upscale only if smaller than 256) + C native random K random native crops per pair (mean over crops) + +It also routes the Snow100K ``gt`` clean pool stratified by a dark-channel +haze proxy, with RESIDE hazy / clear and Rain13K / LOL clean crops as +reference distributions, to test whether the pool carries haze-like cues. +""" + +from __future__ import annotations + +import argparse +import json +import random +from collections import defaultdict +from pathlib import Path +from typing import Dict, List, Sequence, Tuple + +import torch +import torch.nn.functional as F +from PIL import Image + +import train_graph_encoder_v2 as v2 +import train_phase2_graph_resshift_v4 as v4 +from src.data.folder_crops import list_image_files + +NODES = ("rain", "noise", "haze", "lowlight", "free1", "free2") +DOMAIN_INDEX = {"rain": 0, "noise": 1, "haze": 2, "lowlight": 3} + + +def native_centre_crop(image: Image.Image, size: int) -> Image.Image: + width, height = image.size + if min(width, height) < size: + scale = float(size) / min(width, height) + image = image.resize( + (max(size, int(round(width * scale))), max(size, int(round(height * scale)))), + v2._LANCZOS, + ) + width, height = image.size + left, top = (width - size) // 2, (height - size) // 2 + return image.crop((left, top, left + size, top + size)) + + +def native_random_crops(image: Image.Image, size: int, count: int, seed: int) -> List[Image.Image]: + width, height = image.size + if min(width, height) < size: + return [native_centre_crop(image, size)] * count + rng = random.Random(seed) + crops = [] + for _ in range(count): + left = rng.randrange(width - size + 1) + top = rng.randrange(height - size + 1) + crops.append(image.crop((left, top, left + size, top + size))) + return crops + + +def sidd_iso(source_id: str) -> str: + parts = Path(source_id).name.split("_") + return parts[3] if len(parts) > 3 else "?" + + +def dark_channel_mean(images: torch.Tensor, patch: int = 15) -> torch.Tensor: + """Mean of the dark channel (He et al.): low for clear scenes, high for haze.""" + minimum = images.amin(dim=1, keepdim=True) + dark = -F.max_pool2d(-minimum, patch, stride=1, padding=patch // 2) + return dark.mean(dim=(1, 2, 3)) + + +def luma_contrast(images: torch.Tensor) -> torch.Tensor: + luma = 0.299 * images[:, 0] + 0.587 * images[:, 1] + 0.114 * images[:, 2] + return luma.flatten(1).std(dim=1) + + +@torch.no_grad() +def route(phase1, images: torch.Tensor, device: torch.device, batch: int = 16) -> torch.Tensor: + probs = [] + for start in range(0, images.shape[0], batch): + rep = phase1(images[start:start + batch].to(device)) + probs.append(rep.routing_probs.float().cpu()) + return torch.cat(probs) + + +def distribution(probs: torch.Tensor) -> Dict[str, float]: + argmax = probs.argmax(dim=1) + return {node: round(float((argmax == i).float().mean()), 3) for i, node in enumerate(NODES)} + + +def quantiles(values: torch.Tensor) -> Dict[str, float]: + qs = torch.tensor([0.1, 0.25, 0.5, 0.75, 0.9]) + return {"q%d" % int(q * 100): round(float(v), 4) for q, v in zip(qs, torch.quantile(values, qs))} + + +def run(argv: Sequence[str] | None = None) -> Dict[str, object]: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", action="append", required=True, + help="tag=path, repeatable") + parser.add_argument("--k-random", type=int, default=4) + parser.add_argument("--pool-root", default="/home/admin_mcn/data/Snow100K/train/all/gt") + parser.add_argument("--pool-count", type=int, default=512) + parser.add_argument("--image-size", type=int, default=256) + parser.add_argument("--output", type=Path, default=Path("outputs/phase1_scale_probe.json")) + parser.add_argument("--device", default="cuda") + args = parser.parse_args(argv) + device = torch.device(args.device) + size = args.image_size + + splits = v2.build_data_splits(v2.build_parser().parse_args([])) + records = list(splits.val) + print("val records: %d" % len(records), flush=True) + + # ---- load crops once ------------------------------------------------- # + per_policy: Dict[str, List[torch.Tensor]] = {"A": [], "B": [], "C": []} + meta: List[Tuple[str, str, str]] = [] # (domain, dataset, source_id) + clean_native: Dict[str, List[torch.Tensor]] = defaultdict(list) + hazy_native: List[torch.Tensor] = [] + for index, record in enumerate(records): + degraded = v2._open_rgb(record.degraded) + clean = v2._open_rgb(record.clean) + per_policy["A"].append(v2._pil_to_tensor(v2._resize_center_crop(degraded, size))) + per_policy["B"].append(v2._pil_to_tensor(native_centre_crop(degraded, size))) + crops = native_random_crops(degraded, size, args.k_random, seed=1000 + index) + per_policy["C"].append(torch.stack([v2._pil_to_tensor(c) for c in crops])) + meta.append((record.degradation, record.dataset, record.source_id)) + clean_native[record.degradation].append(v2._pil_to_tensor(native_centre_crop(clean, size))) + if record.degradation == "haze": + hazy_native.append(per_policy["B"][-1]) + if index % 50 == 0: + print("loaded %d/%d" % (index, len(records)), flush=True) + images_a = torch.stack(per_policy["A"]) + images_b = torch.stack(per_policy["B"]) + images_c = torch.stack(per_policy["C"]) # [N, K, 3, H, W] + + # ---- clean pool + haze proxy ---------------------------------------- # + pool_files = list_image_files(Path(args.pool_root)) + rng = random.Random(20260903) + pool_files = rng.sample(pool_files, min(args.pool_count, len(pool_files))) + pool = torch.stack([ + v2._pil_to_tensor(native_centre_crop(v2._open_rgb(path), size)) for path in pool_files + ]) + dcp_pool = dark_channel_mean(pool) + contrast_pool = luma_contrast(pool) + reference = { + "snow100k_gt_pool": {"dcp": quantiles(dcp_pool), "contrast": quantiles(contrast_pool)}, + "reside_hazy_val": {"dcp": quantiles(dark_channel_mean(torch.stack(hazy_native)))}, + } + for domain, crops in clean_native.items(): + stacked = torch.stack(crops) + reference["%s_clean_gt_val" % domain] = { + "dcp": quantiles(dark_channel_mean(stacked)), + "contrast": quantiles(luma_contrast(stacked)), + } + thresholds = torch.quantile(dcp_pool, torch.tensor([0.25, 0.5, 0.75])) + pool_quartile = torch.bucketize(dcp_pool, thresholds) + + # ---- route through each checkpoint ---------------------------------- # + results: Dict[str, object] = {"reference_dcp": reference, "checkpoints": {}} + for spec in args.checkpoint: + tag, path = spec.split("=", 1) + sha = v2.sha256_file(Path(path)) + phase1, _ = v4.build_frozen_phase1(Path(path), sha, device) + probs = { + "A": route(phase1, images_a, device), + "B": route(phase1, images_b, device), + "C": route(phase1, images_c.flatten(0, 1), device).view(len(records), args.k_random, -1).mean(dim=1), + } + report: Dict[str, object] = {"sha256": sha[:16], "domains": {}, "sidd_by_iso": {}, "pool": {}} + for domain, di in DOMAIN_INDEX.items(): + rows = [i for i, m in enumerate(meta) if m[0] == domain] + entry = {} + for policy, p in probs.items(): + sub = p[rows] + entry[policy] = { + "argmax": distribution(sub), + "own_prob_mean": round(float(sub[:, di].mean()), 3), + "free_prob_mean": round(float(sub[:, 4:].sum(dim=1).mean()), 3), + } + entry["agreement_A_B"] = round(float((probs["A"][rows].argmax(1) == probs["B"][rows].argmax(1)).float().mean()), 3) + report["domains"][domain] = entry + noise_rows = [i for i, m in enumerate(meta) if m[0] == "noise"] + by_iso: Dict[str, List[int]] = defaultdict(list) + for i in noise_rows: + by_iso[sidd_iso(meta[i][2])].append(i) + for iso, rows in sorted(by_iso.items()): + report["sidd_by_iso"][iso] = { + "n": len(rows), + **{policy: {"noise_prob": round(float(p[rows][:, 1].mean()), 3), + "argmax": distribution(p[rows])} for policy, p in probs.items()}, + } + pool_probs = route(phase1, pool, device) + report["pool"]["all"] = distribution(pool_probs) + for q in range(4): + rows = (pool_quartile == q).nonzero(as_tuple=True)[0] + report["pool"]["dcp_quartile_%d" % (q + 1)] = { + "n": int(rows.numel()), + "dcp_mean": round(float(dcp_pool[rows].mean()), 4), + "argmax": distribution(pool_probs[rows]), + "haze_prob_mean": round(float(pool_probs[rows][:, 2].mean()), 3), + } + results["checkpoints"][tag] = report + + print("=== %s (%s)" % (tag, sha[:12])) + for domain, entry in report["domains"].items(): + print(" %-8s A own=%.2f free=%.2f | B own=%.2f free=%.2f | C own=%.2f free=%.2f | agree(A,B)=%.2f" % ( + domain, entry["A"]["own_prob_mean"], entry["A"]["free_prob_mean"], + entry["B"]["own_prob_mean"], entry["B"]["free_prob_mean"], + entry["C"]["own_prob_mean"], entry["C"]["free_prob_mean"], entry["agreement_A_B"])) + print(" A argmax %s" % entry["A"]["argmax"]) + print(" B argmax %s" % entry["B"]["argmax"]) + for iso, entry in report["sidd_by_iso"].items(): + print(" SIDD ISO %s n=%d noise_prob A=%.2f B=%.2f C=%.2f B argmax %s" % ( + iso, entry["n"], entry["A"]["noise_prob"], entry["B"]["noise_prob"], entry["C"]["noise_prob"], entry["B"]["argmax"])) + print(" pool all: %s" % report["pool"]["all"]) + for q in range(4): + e = report["pool"]["dcp_quartile_%d" % (q + 1)] + print(" pool DCP q%d (mean %.3f): haze_prob %.2f argmax %s" % (q + 1, e["dcp_mean"], e["haze_prob_mean"], e["argmax"])) + del phase1 + torch.cuda.empty_cache() + + print("reference DCP: %s" % json.dumps(reference, indent=None)) + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(results, indent=2)) + print("saved %s" % args.output) + return results + + +if __name__ == "__main__": + run() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/probe_pregain.py b/dataset/phase1_noise_20260906/trial_code_staging/probe_pregain.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a1531a1f06a61afc91321982fd9c7fbcb4749e --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/probe_pregain.py @@ -0,0 +1,61 @@ +#!/usr/bin/env python3 +"""Print the v10 input pre-gain the model predicts per external group +(mean / min / max log-gain and gain), using the same Phase-1 crop + whole +frame inputs the sampler uses. Diagnoses e.g. a gain > 1 on bright hazy +images (clipping) vs the intended gain on low-light inputs.""" + +import argparse +import json +from pathlib import Path + +import torch + +import eval_full_frame as ff +import train_phase2_graph_resshift_v4 as v4 +from eval_v7_external import V7Pipeline + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--checkpoint", default="best.pt") + parser.add_argument("--groups", default="lowlight_lolv2_test,haze_heldout,rain_locked,noise_locked_scene008") + parser.add_argument("--limit", type=int, default=40) + parser.add_argument("--output", type=Path, default=None) + args = parser.parse_args() + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + pipeline = V7Pipeline(args.run_dir, device, checkpoint=args.checkpoint) + restorer = v4.unwrap_module(pipeline.model) + if getattr(restorer, "exposure_pregain", None) is None: + raise SystemExit("this run has no exposure pre-gain") + groups = ff.external_groups() + report = {} + for name in [g.strip() for g in args.groups.split(",") if g.strip()]: + dataset = ff.FullFrameDataset(groups[name][: args.limit]) + gains = [] + with torch.no_grad(): + for index in range(len(dataset)): + item = dataset[index] + degraded = item["degraded"].unsqueeze(0).to(device) + full = item["full_degraded"].unsqueeze(0).to(device) + # centre 256 crop as a Phase-1 tile, like the sampler's tiles + h, w = degraded.shape[-2:] + top, left = max((h - 256) // 2, 0), max((w - 256) // 2, 0) + crop = degraded[..., top:top + 256, left:left + 256] + rep = pipeline.phase1(crop) + if getattr(restorer, "ctx_full_proj", None) is not None: + rep.full_frame = pipeline.phase1(full) + rep.full_image = full + log_gain = restorer.exposure_pregain.log_gain(crop, rep) + gains.append(float(log_gain[0])) + t = torch.tensor(gains) + report[name] = {"n": len(gains), "log_gain_mean": float(t.mean()), "log_gain_min": float(t.min()), + "log_gain_max": float(t.max()), "gain_mean": float(t.exp().mean()), + "frac_gain_gt_1.05": float((t > 0.05).float().mean())} + print(name, json.dumps(report[name]), flush=True) + if args.output: + args.output.write_text(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/probe_scene008_tone.py b/dataset/phase1_noise_20260906/trial_code_staging/probe_scene008_tone.py new file mode 100644 index 0000000000000000000000000000000000000000..08a469b49eac5fb9624a4fec62ca77713affcef1 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/probe_scene008_tone.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +"""Is the scene008 (nearly clean, dark textured) failure a global tone shift? + +For every locked scene008 record: mean luma of input / restored / GT, per-channel +mean shift restored-GT, PSNR of the raw output, and PSNR after a single global +affine correction (gain+bias fitted on luma against GT). If the corrected PSNR +recovers most of the gap, the model is applying an exposure lift, not +destroying texture. Also reports the val degraded baselines per domain so +in-distribution gains can be read against the input quality. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from eval_v7_external import V7Pipeline +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from visualize_v7_uformer import _load_run_args + +LUMA = (0.299, 0.587, 0.114) + + +def luma(x: torch.Tensor) -> torch.Tensor: + return sum(x[:, c] * w for c, w in enumerate(LUMA)) + + +def affine_match(pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: + """Per-image global gain+bias on all channels fitted by least squares on luma.""" + out = [] + for p, t in zip(pred, target): + lp, lt = luma(p[None])[0].flatten(), luma(t[None])[0].flatten() + var = lp.var() + gain = ((lp - lp.mean()) * (lt - lt.mean())).mean() / var if var > 1e-8 else 1.0 + bias = lt.mean() - gain * lp.mean() + out.append((p * gain + bias).clamp(0, 1)) + return torch.stack(out) + + +def scene008(pipe: V7Pipeline, device, dose) -> dict: + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + records = [r for r in splits.locked_test if r.degradation == "noise"] + dataset = ext.PairCropDataset(records) + rows = [] + pipe.dose = dose + for start in range(0, len(records), 8): + items = [dataset[i] for i in range(start, min(start + 8, len(records)))] + degraded = torch.stack([it["degraded"] for it in items]).to(device) + clean = torch.stack([it["clean"] for it in items]).to(device) + ids = [it["record_id"] for it in items] + # Whole-frame view must reach the pipeline, otherwise a --global-context + # model silently runs without its full-frame branch (not deployment). + full = (torch.stack([it["full_degraded"] for it in items]).to(device) + if "full_degraded" in items[0] else None) + with torch.no_grad(): + restored = pipe.restore( + degraded, record_ids=ids, full_degraded=full + )["restored"].float().clamp(0, 1) + matched = affine_match(restored, clean) + for i, rid in enumerate(ids): + rows.append({ + "record_id": rid, + "luma_input": float(luma(degraded[i:i+1]).mean()), + "luma_restored": float(luma(restored[i:i+1]).mean()), + "luma_gt": float(luma(clean[i:i+1]).mean()), + "rgb_shift": [float((restored[i, c] - clean[i, c]).mean()) for c in range(3)], + "psnr_input": float(v4.rgb_psnr_per_image(degraded[i:i+1], clean[i:i+1])[0]), + "psnr_restored": float(v4.rgb_psnr_per_image(restored[i:i+1], clean[i:i+1])[0]), + "psnr_affine_matched": float(v4.rgb_psnr_per_image(matched[i:i+1], clean[i:i+1])[0]), + "ssim_restored": float(v4.rgb_ssim_per_image(restored[i:i+1], clean[i:i+1])[0]), + "ssim_affine_matched": float(v4.rgb_ssim_per_image(matched[i:i+1], clean[i:i+1])[0]), + }) + mean = lambda k: sum(r[k] for r in rows) / len(rows) + return { + "n": len(rows), "dose": dose, "rows": rows, + "mean": {k: mean(k) for k in ("luma_input", "luma_restored", "luma_gt", "psnr_input", + "psnr_restored", "psnr_affine_matched", + "ssim_restored", "ssim_affine_matched")}, + } + + +def val_baselines(run_args, device) -> dict: + splits = load_train_val_manifest(run_args.manifest) + dataset = Phase2PairDataset(splits.val, crop_size=run_args.crop_size, training=False) + acc = {} + for index, record in enumerate(splits.val): + item = dataset[index] + d, c = item["degraded"][None].to(device), item["clean"][None].to(device) + entry = acc.setdefault(record.degradation, {"psnr": [], "ssim": []}) + entry["psnr"].append(float(v4.rgb_psnr_per_image(d, c)[0])) + entry["ssim"].append(float(v4.rgb_ssim_per_image(d, c)[0])) + return {k: {"n": len(v["psnr"]), "psnr": sum(v["psnr"]) / len(v["psnr"]), + "ssim": sum(v["ssim"]) / len(v["ssim"])} for k, v in acc.items()} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--skip-val-baseline", action="store_true") + args = parser.parse_args() + device = torch.device("cuda") + pipe = V7Pipeline(args.run_dir, device) + report = { + "run_dir": str(args.run_dir), + "scene008_dose1": scene008(pipe, device, None), + "scene008_dose0": scene008(pipe, device, 0.0), + "val_degraded_baseline": ( + None if args.skip_val_baseline + else val_baselines(_load_run_args(args.run_dir), device) + ), + } + args.output.write_text(json.dumps(report, indent=2)) + for key in ("scene008_dose1", "scene008_dose0"): + m = report[key]["mean"] + print(key, " ".join("%s=%.3f" % (k, v) for k, v in m.items())) + print("val_degraded_baseline", json.dumps(report["val_degraded_baseline"])) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/probe_tone_oracle.py b/dataset/phase1_noise_20260906/trial_code_staging/probe_tone_oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3b7cf4102ba0982c1d607ea42eb71b306caf47 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/probe_tone_oracle.py @@ -0,0 +1,109 @@ +#!/usr/bin/env python3 +"""Oracle ceilings of global colour/tone controls on a run's outputs. + +For each image of a group (whole-image restoration), fit per image against +the GT and report the PSNR after each transform family: + raw model output + affine_I I' = a*I + b on intensity I = max(RGB), chroma ratios kept + gamma_I I' = a*I^g + b (the CIDNet C_k-style power on intensity) + matrix 3x3 colour matrix + bias on RGB (white balance / colour cast) + gamma+matrix both +The fits are least squares on the image itself (oracle), so the numbers are +ceilings, not predictions; compare with probe_global_knob.py (affine on RGB). +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +import torch + +import eval_full_frame as ff +import train_phase2_graph_resshift_v4 as v4 +from eval_v7_external import V7Pipeline + + +def psnr(a, b): + return float(-10 * torch.log10(((a - b) ** 2).mean().clamp_min(1e-12))) + + +def intensity(x): + return x.max(dim=1, keepdim=True).values.clamp_min(1e-6) + + +def fit_affine(i_out, i_gt): + x = torch.stack((i_out.flatten(), torch.ones_like(i_out.flatten())), 1) + sol = torch.linalg.lstsq(x, i_gt.flatten().unsqueeze(1)).solution.flatten() + return float(sol[0]), float(sol[1]) + + +def apply_intensity(x, new_i): + return (x * (new_i / intensity(x))).clamp(0, 1) + + +def best_gamma(x, gt): + best = (psnr(x, gt), 1.0, 1.0, 0.0) + i_out, i_gt = intensity(x), intensity(gt) + for g in [0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.25, 1.5, 1.75, 2.0]: + a, b = fit_affine(i_out ** g, i_gt) + cand = apply_intensity(x, (a * i_out ** g + b).clamp_min(1e-6)) + p = psnr(cand, gt) + if p > best[0]: + best = (p, g, a, b) + return best + + +def fit_matrix(x, gt): + px = x.flatten(2)[0].t() # [N,3] + py = gt.flatten(2)[0].t() + xa = torch.cat((px, torch.ones(px.shape[0], 1, device=px.device)), 1) + sol = torch.linalg.lstsq(xa, py).solution # [4,3] + out = (xa @ sol).t().reshape(1, 3, *x.shape[-2:]).clamp(0, 1) + return out + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--checkpoint", default="last.pt") + parser.add_argument("--group", default="lowlight_lolv2_test") + parser.add_argument("--limit", type=int, default=100) + parser.add_argument("--output", type=Path, default=None) + args = parser.parse_args() + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + pipe = V7Pipeline(args.run_dir, device, checkpoint=args.checkpoint) + seed = int(pipe.args.eval_seed) + records = ff.external_groups(300)[args.group][: args.limit] + ds = ff.FullFrameDataset(records) + acc = {k: [] for k in ("raw", "affine_I", "gamma_I", "matrix", "gamma+matrix")} + gammas = [] + with torch.no_grad(): + for i in range(len(ds)): + it = ds[i] + x = it["degraded"].unsqueeze(0).to(device) + gt = it["clean"].unsqueeze(0).to(device) + full = it["full_degraded"].unsqueeze(0).to(device) + out = ff.restore_full_frame( + lambda t, ids, f: pipe.restore(t, record_ids=list(ids), seed=seed, full_degraded=f)["restored"], + x, it["record_id"], tta=1, full_frame=full, whole_max_pixels=1200000).float() + acc["raw"].append(psnr(out, gt)) + a, b = fit_affine(intensity(out), intensity(gt)) + acc["affine_I"].append(psnr(apply_intensity(out, (a * intensity(out) + b).clamp_min(1e-6)), gt)) + p, g, a2, b2 = best_gamma(out, gt) + acc["gamma_I"].append(p); gammas.append(g) + m = fit_matrix(out, gt) + acc["matrix"].append(psnr(m, gt)) + gm = apply_intensity(out, (a2 * intensity(out) ** g + b2).clamp_min(1e-6)) + acc["gamma+matrix"].append(psnr(fit_matrix(gm, gt), gt)) + report = {k: sum(v) / len(v) for k, v in acc.items()} + report["gamma_median"] = float(torch.tensor(gammas).median()) + report["n"] = len(ds) + print("ORACLE", args.group, json.dumps({k: (round(v, 3) if isinstance(v, float) else v) for k, v in report.items()})) + if args.output: + args.output.write_text(json.dumps(report, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/probe_v11_memory.py b/dataset/phase1_noise_20260906/trial_code_staging/probe_v11_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbf14b55cf3789bc86513440c5f63828ee0837e --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/probe_v11_memory.py @@ -0,0 +1,96 @@ +#!/usr/bin/env python3 +"""Peak-memory / throughput probe for a v7-family training configuration. + +Builds the restorer exactly as the trainer would (same parser + builder), +runs ``--steps`` training micro-steps on synthetic batches at the given crop +and batch size with AMP, and prints peak allocated memory and step time so a +launcher can pick the batch size for each progressive-resolution stage +(v11) before committing both GPUs. Phase-1 is replaced by a synthetic +representation of the right shapes (its footprint is small and frozen). + +Usage: probe_v11_memory.py --crop 384 --batch 4 [--grad-checkpoint] -- +""" + +from __future__ import annotations + +import argparse +import json +import sys +import time +from types import SimpleNamespace + +import torch + +import train_phase2_unified_v7 as v7 + + +def synthetic_representation(batch: int, crop: int, device) -> SimpleNamespace: + latent = crop // 4 + rep = SimpleNamespace( + content_latent=torch.randn(batch, 128, latent, latent, device=device), + node_tokens=torch.randn(batch, 6, 256, device=device), + routing_probs=torch.softmax(torch.randn(batch, 6, device=device), dim=-1), + severity_coords=torch.rand(batch, 4, device=device), + spatial_maps=torch.rand(batch, 4, 16, 16, device=device), + unknown_residual=torch.randn(batch, 256, device=device), + global_condition=torch.randn(batch, 256, device=device), + photometric_state=torch.randn(batch, v7.PHOTOMETRIC_STATE_DIM, device=device), + ) + full = SimpleNamespace(**{k: (v.clone() if isinstance(v, torch.Tensor) else v) for k, v in vars(rep).items()}) + rep.full_frame = full + rep.full_image = torch.rand(batch, 3, 256, 256, device=device) + return rep + + +def main(argv=None) -> None: + argv = list(sys.argv[1:] if argv is None else argv) + if "--" not in argv: + raise SystemExit("usage: probe_v11_memory.py --crop N --batch N [--steps N] -- ") + split = argv.index("--") + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--crop", type=int, required=True) + parser.add_argument("--batch", type=int, required=True) + parser.add_argument("--steps", type=int, default=3) + parser.add_argument("--output", default=None) + probe = parser.parse_args(argv[:split]) + args = v7.build_parser().parse_args(argv[split + 1:] + ["--allow-scratch"]) + device = torch.device("cuda") + model = v7._build_v7_restorer(args, device) + model.train() + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5) + scaler = torch.cuda.amp.GradScaler() + torch.cuda.reset_peak_memory_stats(device) + timings = [] + for step in range(int(probe.steps)): + clean = torch.rand(probe.batch, 3, probe.crop, probe.crop, device=device) + degraded = torch.rand(probe.batch, 3, probe.crop, probe.crop, device=device) + rep = synthetic_representation(probe.batch, probe.crop, device) + timesteps = torch.full((probe.batch,), 2, device=device, dtype=torch.long) + torch.cuda.synchronize() + start = time.time() + with torch.cuda.amp.autocast(enabled=True): + result = model.training_loss(clean, degraded, rep, timesteps) + scaler.scale(result.loss).backward() + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) + scaler.step(optimizer) + scaler.update() + optimizer.zero_grad(set_to_none=True) + torch.cuda.synchronize() + timings.append(time.time() - start) + peak = torch.cuda.max_memory_allocated(device) / 2 ** 30 + params = sum(p.numel() for p in model.parameters()) / 1e6 + report = { + "crop": probe.crop, "batch": probe.batch, "params_M": round(params, 2), + "peak_gib": round(peak, 2), "step_s": round(sum(timings[1:]) / max(len(timings) - 1, 1), 3), + "grad_checkpoint": bool(getattr(args, "grad_checkpoint", False)), + "blocks_per_stage": list(v7.blocks_per_stage(args)), + } + print("PROBE " + json.dumps(report), flush=True) + if probe.output: + with open(probe.output, "w") as handle: + json.dump(report, handle) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/probe_v7_taps.py b/dataset/phase1_noise_20260906/trial_code_staging/probe_v7_taps.py new file mode 100644 index 0000000000000000000000000000000000000000..8d640a715e063388c29d691480fe88f47fe263b2 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/probe_v7_taps.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Inference-time tap sensitivity for a v7 checkpoint (no training). + +Two ablation levels, each evaluated on the full validation split with the +exact training-time sampler: + +* fields — one Phase-1 representation field at a time is replaced by its + batch mean (instance information removed, population statistics + kept); measures what the encoder's OUTPUTS contribute. +* channels — one conditioning channel of the bundle (context / global_vector / + content / spatial / gate) is neutralised; measures which of the + parallel INJECTION PATHS the trunk actually relies on. +""" + +from __future__ import annotations + +import argparse +import copy +import dataclasses +import json +from pathlib import Path +from typing import Any, Dict + +import torch +from torch import nn +from torch.utils.data import DataLoader + +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_unified_v7 as v7 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from visualize_v7_uformer import _load_run_args + +FIELDS = ( + "content_latent", "node_tokens", "routing_probs", "severity_coords", + "spatial_maps", "unknown_residual", "global_condition", +) +CHANNELS = ("context", "global_vector", "content", "spatial", "gate") +EXTRAS = ("gate_uniform", "no_conditioning") + + +def _batch_mean(value: torch.Tensor) -> torch.Tensor: + return value.mean(dim=0, keepdim=True).expand_as(value).contiguous() + + +class FieldAblatedPhase1(nn.Module): + def __init__(self, phase1: nn.Module, field: str) -> None: + super().__init__() + self.phase1 = phase1 + self.field = field + + def forward(self, degraded: torch.Tensor): + representation = self.phase1(degraded) + if self.field: + value = getattr(representation, self.field) + if torch.is_tensor(value): + setattr(representation, self.field, _batch_mean(value)) + return representation + + +def _replace(bundle: Any, **changes: Any) -> Any: + if dataclasses.is_dataclass(bundle): + return dataclasses.replace(bundle, **changes) + clone = copy.copy(bundle) + for name, value in changes.items(): + setattr(clone, name, value) + return clone + + +def _uniform_gate(gate: Any) -> Any: + strengths = torch.full_like(gate.strengths, 0.2) + mask = torch.ones_like(strengths) + return _replace( + gate, strengths=strengths, top2_mask=mask, + spatial_gates=torch.full_like(gate.spatial_gates, 0.5), + ) + + +def _neutralised_gate(gate: Any) -> Any: + strengths = _batch_mean(gate.strengths) + top2 = torch.topk(strengths, k=2, dim=1).indices + mask = torch.zeros_like(strengths).scatter_(1, top2, 1.0) + return _replace( + gate, strengths=strengths, top2_mask=mask, + spatial_gates=_batch_mean(gate.spatial_gates), + ) + + +def install_channel_ablation(restorer: nn.Module, channel: str) -> None: + original = restorer.build_condition + + def patched(representation: Any): + bundle = original(representation) + if not channel: + return bundle + if channel == "gate": + return _replace(bundle, gate=_neutralised_gate(bundle.gate)) + if channel == "gate_uniform": + return _replace(bundle, gate=_uniform_gate(bundle.gate)) + if channel == "no_conditioning": + return _replace( + bundle, + context=torch.zeros_like(bundle.context), + global_vector=torch.zeros_like(bundle.global_vector), + content=torch.zeros_like(bundle.content), + spatial=torch.zeros_like(bundle.spatial), + gate=_uniform_gate(bundle.gate), + ) + value = getattr(bundle, channel) + return _replace(bundle, **{channel: torch.zeros_like(value)}) + + restorer.build_condition = patched # type: ignore[assignment] + + +def _macro(result: Dict[str, Any]) -> Dict[str, float]: + restored = result.get("restored", result) + out = { + "macro_psnr": float(restored["macro_psnr"]), + "macro_ssim": float(restored["macro_ssim"]), + } + for domain, values in restored["per_domain"].items(): + out[domain] = float(values["psnr"]) + return out + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--run-dir", type=Path, + default=Path("outputs/phase2_v7/uformer_head8k_seed42"), + ) + parser.add_argument("--level", choices=("fields", "channels", "extras"), required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + + run_args = _load_run_args(args.run_dir) + device = torch.device("cuda") + checkpoint = v4._torch_load(args.run_dir / "best.pt", map_location="cpu") + model = v7._build_v7_restorer(run_args, device) + model.load_state_dict(checkpoint["ema_state_dict"]["shadow"], strict=True) + model.eval() + phase1, _ = v4.build_frozen_phase1( + run_args.phase1_checkpoint, run_args.phase1_sha256, device + ) + splits = load_train_val_manifest(run_args.manifest) + loader = DataLoader( + Phase2PairDataset( + splits.val, crop_size=run_args.crop_size, + training=False, upscale_small=True, + ), + batch_size=8, shuffle=False, num_workers=4, pin_memory=True, + ) + names = ("",) + {"fields": FIELDS, "channels": CHANNELS, "extras": EXTRAS}[args.level] + report: Dict[str, Any] = {"level": args.level, "run_dir": str(args.run_dir)} + pristine_build = model.build_condition + with v7._installed_v7_backend(run_args): + for name in names: + label = name or "baseline" + if args.level == "fields": + encoder = FieldAblatedPhase1(phase1, name) + model.build_condition = pristine_build + else: + encoder = phase1 + model.build_condition = pristine_build + install_channel_ablation(model, name) + with torch.no_grad(): + result = v4.evaluate( + model, encoder, loader, device, int(run_args.eval_seed) + ) + report[label] = _macro(result) + print(label, json.dumps(report[label]), flush=True) + args.output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/quick_eval_every.sh b/dataset/phase1_noise_20260906/trial_code_staging/quick_eval_every.sh new file mode 100644 index 0000000000000000000000000000000000000000..e7e77e43d279450def7eb41b36d14003905a0247 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/quick_eval_every.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Quick external check of a running stage every N steps (user request): +# when the train log passes each target step, snapshot last.pt and run the +# whole-image full-frame evaluator on LOLv2 / haze / Test1200 (no LPIPS, no +# 12 MP scene008) on the given GPU, sharing it with training. +# Usage: quick_eval_every.sh +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +RUN=$1; GPU=$2; TARGETS=${3//,/ } +RUN_DIR=outputs/phase2_v7/$RUN +LOG=outputs/phase2_v7/${RUN}_train.log +log() { echo "[quick $(date +%H:%M:%S)] $*"; } +current_step() { grep "\"event\": \"train\"" "$LOG" 2>/dev/null | tail -n 1 | grep -o "\"step\": [0-9]*" | grep -o "[0-9]*"; } +for target in $TARGETS; do + while true; do + s=$(current_step); s=${s:-0} + if [ "$s" -ge "$target" ]; then break; fi + 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 + sleep 120 + done + sleep 60 # let last.pt (written every 250 steps) settle + snap=$RUN_DIR/snapshot_${target}.pt + cp "$RUN_DIR/last.pt" "$snap" + step=$($PY -c "import torch; print(torch.load('$snap', map_location='cpu')['step'])") + log "snapshot for target $target = last.pt at step $step" + CUDA_VISIBLE_DEVICES=$GPU $PY -u eval_full_frame.py --run-dir "$RUN_DIR" --checkpoint "snapshot_${target}.pt" \ + --groups lowlight_lolv2_test,haze_heldout,rain_locked --whole-max-pixels 1200000 --tta 1 --no-lpips \ + --output outputs/quick_${RUN}_${target}.json >> outputs/phase2_v7/quick_eval_${RUN}.log 2>&1 \ + && log "wrote outputs/quick_${RUN}_${target}.json" || log "eval FAILED at $target" +done +log "done" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/relocate_manifest.py b/dataset/phase1_noise_20260906/trial_code_staging/relocate_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..e369216bfcc67fdf83f0c6d6f012943efbba57ec --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/relocate_manifest.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Rewrite the absolute file paths of a Phase-2 train/val manifest for another +machine and recompute the derived identities (record_id, split digests). + +The manifest's record ids and digests hash the absolute paths, so a plain +text substitution is rejected by ``load_train_val_manifest``; this rebuilds +the records through ``RestorationRecord`` so the new manifest validates. +Usage: + relocate_manifest.py --manifest in.json --output out.json \ + --map /home/admin_mcn/data/=/home/me/bundle/data/ \ + --map /home/admin_mcn/.cache/kagglehub/=/home/me/bundle/kagglehub/ +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from src.data.phase2_v4 import RestorationRecord, TrainValSplits, save_train_val_manifest, load_train_val_manifest + + +def relocate(path: str, mapping: list) -> str: + for old, new in mapping: + if path.startswith(old): + return new + path[len(old):] + raise ValueError("no mapping for %s" % path) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--map", action="append", default=[], help="OLD_PREFIX=NEW_PREFIX (repeatable)") + parser.add_argument("--check-files", action="store_true", help="verify every relocated file exists") + args = parser.parse_args() + mapping = [tuple(m.split("=", 1)) for m in args.map] + payload = json.loads(args.manifest.read_text(encoding="utf-8")) + + def rebuild(values): + records = [] + for v in values: + records.append(RestorationRecord( + degraded=Path(relocate(v["degraded"], mapping)), + clean=Path(relocate(v["clean"], mapping)), + degradation=v["degradation"], dataset=v["dataset"], source_id=v["source_id"], + split_group=v["split_group"], clean_content_sha256=v["clean_content_sha256"], + )) + return tuple(records) + + splits = TrainValSplits(train=rebuild(payload["train"]), val=rebuild(payload["val"]), + quarantine_count=int(payload["quarantine_count"])) + if args.check_files: + missing = [str(p) for r in splits.train + splits.val for p in (r.degraded, r.clean) if not p.exists()] + if missing: + raise SystemExit("%d missing files, e.g. %s" % (len(missing), missing[:3])) + save_train_val_manifest(args.output, splits) + reloaded = load_train_val_manifest(args.output) + print("relocated %d train / %d val records -> %s (validated: %d/%d)" % ( + len(splits.train), len(splits.val), args.output, len(reloaded.train), len(reloaded.val))) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_C_only.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_C_only.sh new file mode 100644 index 0000000000000000000000000000000000000000..3d7832747d6230153d9d0284b998a1597667b7b6 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_C_only.sh @@ -0,0 +1,73 @@ +#!/bin/bash +# Photometric ablation on the MI325X host (user request 2026-09-05): +# A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5 +# B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run) +# C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6 +# All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then +# whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt. +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +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/ +export OMP_NUM_THREADS=8 +export PYTORCH_ALLOC_CONF=expandable_segments:True +# Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A). +free_gpus() { + rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \ + | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' ' +} +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +STEPS=${STEPS:-5000} +EVLOG=outputs/phase2_v7/ablation_photometric_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[abl $(date +%H:%M:%S)] $*"; } + +BASE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \ + --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \ + --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \ + --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \ + --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02" +PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02" +COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05" + +launch() { # name gpu extra + local name=$1 gpu=$2 extra=$3 + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \ + >> outputs/phase2_v7/${name}_train.log 2>&1 & + log "launched $name on GPU$gpu pid $!" +} +wait_done() { # name + local name=$1 run_dir=outputs/phase2_v7/$1 + while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done + if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi +} +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } + +# C_colour only, on a given GPU (GPU 6 is contested by another tenant on this host) +GC=${GC:-5} +rm -rf outputs/phase2_v7/abl_C_colour +launch abl_C_colour "$GC" "$PHOTO $COLOUR" +wait_done abl_C_colour +log "C_colour finished" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_C_then_eval.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_C_then_eval.sh new file mode 100644 index 0000000000000000000000000000000000000000..cacf91fdedd0d2a2aa86aaf538ea1332130bd97a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_C_then_eval.sh @@ -0,0 +1,88 @@ +#!/bin/bash +# Photometric ablation on the MI325X host (user request 2026-09-05): +# A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5 +# B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run) +# C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6 +# All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then +# whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt. +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +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/ +export OMP_NUM_THREADS=8 +export PYTORCH_ALLOC_CONF=expandable_segments:True +# Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A). +free_gpus() { + rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \ + | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' ' +} +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +STEPS=${STEPS:-5000} +EVLOG=outputs/phase2_v7/ablation_photometric_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[abl $(date +%H:%M:%S)] $*"; } + +BASE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \ + --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \ + --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \ + --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \ + --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02" +PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02" +COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05" + +launch() { # name gpu extra + local name=$1 gpu=$2 extra=$3 + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \ + >> outputs/phase2_v7/${name}_train.log 2>&1 & + log "launched $name on GPU$gpu pid $!" +} +wait_done() { # name + local name=$1 run_dir=outputs/phase2_v7/$1 + while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done + if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi +} +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } + +# C_colour (relaunch after an external kill) + its evals + the comparison table. +GC=${GC:-5} +while pgrep -f "[e]val_full_frame.py" >/dev/null; do sleep 30; done # let the A/B evals finish first +rm -rf outputs/phase2_v7/abl_C_colour +launch abl_C_colour "$GC" "$PHOTO $COLOUR" +wait_done abl_C_colour +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 +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 +$PY - <<'PYEOF' +import json, os +rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"), + ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")] +print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008") +for name, p in rows: + if not os.path.exists(p): print(name, "missing"); continue + r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f] + print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % ( + name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"), + g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips"))) +PYEOF +log "ablation finished" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_photometric.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_photometric.sh new file mode 100644 index 0000000000000000000000000000000000000000..29b396406e090fa5b5beaeaf177a4013e82ff57c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_photometric.sh @@ -0,0 +1,94 @@ +#!/bin/bash +# Photometric ablation on the MI325X host (user request 2026-09-05): +# A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5 +# B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run) +# C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6 +# All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then +# whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt. +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +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/ +export OMP_NUM_THREADS=8 +export PYTORCH_ALLOC_CONF=expandable_segments:True +# Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A). +free_gpus() { + rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \ + | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' ' +} +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +STEPS=${STEPS:-5000} +EVLOG=outputs/phase2_v7/ablation_photometric_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[abl $(date +%H:%M:%S)] $*"; } + +BASE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \ + --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \ + --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \ + --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \ + --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02" +PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02" +COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05" + +launch() { # name gpu extra + local name=$1 gpu=$2 extra=$3 + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \ + >> outputs/phase2_v7/${name}_train.log 2>&1 & + log "launched $name on GPU$gpu pid $!" +} +wait_done() { # name + local name=$1 run_dir=outputs/phase2_v7/$1 + while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done + if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi +} +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } + +read -r GA GC _ <<< "$(free_gpus)" +[ -n "${GA:-}" ] && [ -n "${GC:-}" ] || { log "need two free GPUs, found: '$(free_gpus)'"; exit 1; } +log "using GPUs $GA (A_nophoto) and $GC (C_colour)" +launch abl_A_nophoto "$GA" "" +launch abl_C_colour "$GC" "$PHOTO $COLOUR" +wait_done abl_A_nophoto; wait_done abl_C_colour +# B = the stage-A run at the same step count +B_CKPT=outputs/phase2_v7/uformer_v11a_256_x/milestone_00005000.pt +[ -f $B_CKPT ] || log "WARNING: $B_CKPT missing" +( 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 + 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 ) & +( 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 + 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 ) & +wait +$PY - <<'PYEOF' +import json, os +rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"), + ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")] +print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008") +for name, p in rows: + if not os.path.exists(p): print(name, "missing"); continue + r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f] + print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % ( + name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"), + g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips"))) +PYEOF +log "ablation finished" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_seq.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_seq.sh new file mode 100644 index 0000000000000000000000000000000000000000..b74c0b9d9ac9c3ab2823cf31441b0379eb5c7297 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_ablation_seq.sh @@ -0,0 +1,96 @@ +#!/bin/bash +# Photometric ablation on the MI325X host (user request 2026-09-05): +# A_nophoto v11 recipe WITHOUT the photometric head and the pre-gain GPU 5 +# B_photo v11 recipe (photometric head + supervised pre-gain) = stage A milestone_00005000.pt (GPU 7 run) +# C_colour B + v12 global colour head (3x3 + bias, supervised target) GPU 6 +# All: warm-start v10 best@8k, batch 32, LR 7e-5, 5000 steps, no early stop; then +# whole-image full-frame evals (LOLv2 / haze / Test1200 / scene008) of last.pt. +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +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/ +export OMP_NUM_THREADS=8 +export PYTORCH_ALLOC_CONF=expandable_segments:True +# Shared host: pick GPUs that are actually free at launch time (VRAM < 5%), never GPU 7 (stage A). +free_gpus() { + rocm-smi --showmemuse 2>/dev/null | grep "VRAM%" | sed -E 's/.*GPU\[([0-9]+)\].*: *([0-9]+).*/\1 \2/' \ + | awk '$1 != 7 && $2 < 5 {print $1}' | tr '\n' ' ' +} +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +WARM=outputs/phase2_v7/uformer_v10_8k_seed42/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +STEPS=${STEPS:-5000} +EVLOG=outputs/phase2_v7/ablation_photometric_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[abl $(date +%H:%M:%S)] $*"; } + +BASE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 24 --extra-clean-workers 8 --seed 42 --eval-seed 20260830 \ + --global-context --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4 \ + --warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema \ + --crop-size 256 --batch-size 32 --grad-accum 1 --eval-batch-size 16 \ + --learning-rate 7e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,1000,2000,3000,4000,5000 --milestone-steps 5000 \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02" +PHOTO="--photometric-head --photometric-dropout 0.1 --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02" +COLOUR="--colour-head --colour-dropout 0.1 --colour-target-weight 0.05" + +launch() { # name gpu extra + local name=$1 gpu=$2 extra=$3 + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $BASE $extra --output-dir outputs/phase2_v7/$name \ + >> outputs/phase2_v7/${name}_train.log 2>&1 & + log "launched $name on GPU$gpu pid $!" +} +wait_done() { # name + local name=$1 run_dir=outputs/phase2_v7/$1 + while pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; do sleep 60; done + if grep -q "\"step\": $STEPS" "$run_dir/metrics.jsonl" 2>/dev/null; then log "$name done"; else log "$name ENDED EARLY (check log)"; fi +} +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } + +# Sequential variant for a contested host: A (already running or launched) then C on ONE device. +GA=${GA:-5}; GC=${GC:-5} +running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir outputs/phase2_v7/$1" >/dev/null; } +if ! running abl_A_nophoto && ! grep -q "\"step\": $STEPS" outputs/phase2_v7/abl_A_nophoto/metrics.jsonl 2>/dev/null; then + rm -rf outputs/phase2_v7/abl_A_nophoto; launch abl_A_nophoto "$GA" "" +fi +wait_done abl_A_nophoto +rm -rf outputs/phase2_v7/abl_C_colour +launch abl_C_colour "$GC" "$PHOTO $COLOUR" +wait_done abl_C_colour +B_CKPT=outputs/phase2_v7/uformer_v11a_256_x/milestone_00005000.pt +[ -f $B_CKPT ] || log "WARNING: $B_CKPT missing" +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 +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 +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 +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 +$PY - <<'PYEOF' +import json, os +rows = [("A_nophoto", "outputs/abl_A_nophoto_fullframe_whole_v1.json"), ("B_photo", "outputs/abl_B_photo_fullframe_whole_v1.json"), + ("C_colour", "outputs/abl_C_colour_fullframe_whole_v1.json"), ("C_colour(head off)", "outputs/abl_C_colour_nodose_fullframe_whole_v1.json")] +print("ABLATION whole-image: LOLv2 psnr/ssim | Test1200 psnr/Y | haze | scene008") +for name, p in rows: + if not os.path.exists(p): print(name, "missing"); continue + r = json.load(open(p)); g = lambda k, f: r[k]["restored"][f] + print("%-18s LOL %.3f/%.4f | rain %.3f/Y%.3f | haze %.3f | sc008 %.3f/L%.3f" % ( + name, g("lowlight_lolv2_test","psnr"), g("lowlight_lolv2_test","ssim"), g("rain_locked","psnr"), g("rain_locked","psnr_y"), + g("haze_heldout","psnr"), g("noise_locked_scene008","psnr"), g("noise_locked_scene008","lpips"))) +PYEOF +log "ablation finished" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5c.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5c.sh new file mode 100644 index 0000000000000000000000000000000000000000..114669878a6b3eec9943fcd35f74843cb614aab8 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5c.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# Phase-1 v5c pair (2026-09-03): the v5b recipe under the NATIVE crop policy +# (Phase-2 parity; SIDD seen at native resolution instead of ~12x downsampled). +# GPU0 phase1_v5c native + SupCon on known+paired-clean only (embed-members known_clean) +# GPU1 phase1_v5c_ab native + v5b SupCon membership (all) -> isolates the crop policy +# Both share one native SIDD cache; the second run starts only after the first +# has finished prebuilding it (severity_calibration.json appears after prebuild). +# Usage: bash run_phase1_v5c.sh (launch both) +# ONLY=v5c bash run_phase1_v5c.sh (launch one: v5c | v5c_ab) +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CACHE=outputs/phase1_cache/sidd_native_256 +DATA=/home/admin_mcn/data +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 8 --no-amp --seed 42 \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 \ + --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE" + +launch() { # $1 = run name, $2 = gpu, $3 = embed members + local name=$1 gpu=$2 members=$3 + mkdir -p outputs/$name + CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON \ + --embed-members $members --output-dir outputs/$name \ + > outputs/${name}_train.log 2>&1 < /dev/null & + echo "[v5c] launched $name on GPU$gpu (embed-members=$members) pid $!" +} + +wait_for_cache() { # wait until the first run wrote its calibration (cache prebuilt) + local name=$1 + for _ in $(seq 1 240); do + if [ -f outputs/$name/severity_calibration.json ]; then return 0; fi + if grep -q Traceback outputs/${name}_train.log 2>/dev/null; then echo "[v5c] $name crashed before cache"; return 1; fi + sleep 15 + done + echo "[v5c] timed out waiting for $name cache"; return 1 +} + +ONLY=${ONLY:-both} +case "$ONLY" in + v5c) launch phase1_v5c 0 known_clean ;; + v5c_ab) launch phase1_v5c_ab 1 all ;; + both) + launch phase1_v5c 0 known_clean + wait_for_cache phase1_v5c && launch phase1_v5c_ab 1 all + ;; + *) echo "ONLY must be v5c | v5c_ab | both"; exit 2 ;; +esac diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5d.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5d.sh new file mode 100644 index 0000000000000000000000000000000000000000..7b1fbed613de934bf15913d16fe056606436f85a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5d.sh @@ -0,0 +1,43 @@ +#!/bin/bash +# Phase-1 v5d pair (2026-09-03): v5c_ab recipe (native crops, v5b losses, +# SupCon members = all) + weight EMA (0.999) for evaluation/selection and the +# balanced selection key (0.5*F1 + 0.5*mean null terms), two seeds. +# GPU0 phase1_v5d seed 42 +# GPU1 phase1_v5d_s43 seed 43 +# Shares the native SIDD cache built by v5c; severity calibration is copied +# from phase1_v5c (same records, same policy -> same fingerprint). +# Usage: bash run_phase1_v5d.sh (both) +# ONLY=v5d|v5d_s43 bash run_phase1_v5d.sh +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CACHE=outputs/phase1_cache/sidd_native_256 +DATA=/home/admin_mcn/data +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 8 --no-amp \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \ + --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \ + --ema-decay 0.999 --selection balanced" + +launch() { # $1 = run name, $2 = gpu, $3 = seed + local name=$1 gpu=$2 seed=$3 + mkdir -p outputs/$name + [ -f outputs/$name/severity_calibration.json ] || cp outputs/phase1_v5c/severity_calibration.json outputs/$name/ 2>/dev/null + CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON \ + --seed $seed --output-dir outputs/$name \ + > outputs/${name}_train.log 2>&1 < /dev/null & + echo "[v5d] launched $name on GPU$gpu (seed $seed) pid $!" +} + +ONLY=${ONLY:-both} +case "$ONLY" in + v5d) launch phase1_v5d 0 42 ;; + v5d_s43) launch phase1_v5d_s43 1 43 ;; + both) launch phase1_v5d 0 42; sleep 20; launch phase1_v5d_s43 1 43 ;; + *) echo "ONLY must be v5d | v5d_s43 | both"; exit 2 ;; +esac diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5e.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5e.sh new file mode 100644 index 0000000000000000000000000000000000000000..501de37ec8659b9e88089f2a0516888548bfaa23 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5e.sh @@ -0,0 +1,57 @@ +#!/bin/bash +# Phase-1 v5e pair (2026-09-04): v5c_ab recipe (native crops, v5b losses, +# SupCon all, raw-weight eval, F1 selection) + residual-aware training crops +# and a crop-level severity floor. +# GPU0 phase1_v5e --crop-select residual --crop-candidates 4 --severity-floor 0.05 +# GPU1 phase1_v5e_ab --crop-select residual --crop-candidates 4 (no floor -> isolates the floor) +# Each launch can wait for a previous run's "Training complete" (WAIT0 / WAIT1 = +# path of that run's train log) so it starts as soon as the GPU frees up. +# Usage: WAIT0=outputs/phase1_v5d_train.log WAIT1=outputs/phase1_v5d_s43_train.log bash run_phase1_v5e.sh +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CACHE=outputs/phase1_cache/sidd_native_256 +DATA=/home/admin_mcn/data +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 8 --no-amp --seed 42 \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \ + --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \ + --crop-select residual --crop-candidates 4" + +wait_log() { # $1 = train log to wait for ("" = no wait) + [ -z "$1" ] && return 0 + while ! grep -q "Training complete" "$1" 2>/dev/null; do + if grep -q Traceback "$1" 2>/dev/null && ! pgrep -f "[t]rain_graph_encoder_v2.py.*$(basename ${1%_train.log})" >/dev/null; then + echo "[v5e] $1 crashed; launching anyway"; return 0 + fi + sleep 120 + done + sleep 30 +} + +launch() { # $1 = run name, $2 = gpu, $3 = extra flags + local name=$1 gpu=$2 extra=$3 + mkdir -p outputs/$name + [ -f outputs/$name/severity_calibration.json ] || cp outputs/phase1_v5c/severity_calibration.json outputs/$name/ 2>/dev/null + CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON $extra \ + --output-dir outputs/$name > outputs/${name}_train.log 2>&1 < /dev/null & + echo "[v5e] $(date +%H:%M) launched $name on GPU$gpu ($extra) pid $!" +} + +ONLY=${ONLY:-both} +WAIT0=${WAIT0:-}; WAIT1=${WAIT1:-} +case "$ONLY" in + v5e) wait_log "$WAIT0"; launch phase1_v5e 0 "--severity-floor 0.05" ;; + v5e_ab) wait_log "$WAIT1"; launch phase1_v5e_ab 1 "--severity-floor 0.0" ;; + both) + ( wait_log "$WAIT0"; launch phase1_v5e 0 "--severity-floor 0.05" ) & + ( wait_log "$WAIT1"; launch phase1_v5e_ab 1 "--severity-floor 0.0" ) & + wait + ;; + *) echo "ONLY must be v5e | v5e_ab | both"; exit 2 ;; +esac diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5f.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5f.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd6522742c4ec415bfb1e7394aa7e86643fb58a1 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_phase1_v5f.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# Phase-1 v5f pair (2026-09-04): v5c_ab recipe (RANDOM native crops) + crop-level severity floor only. +# SupCon all, raw-weight eval, F1 selection) + residual-aware training crops +# GPU0 phase1_v5f --severity-floor 0.05 +# GPU1 phase1_v5f_b --severity-floor 0.03 +# v5e showed max-residual crop selection biases training crops (sky/dense streaks) away from the val centre-crop distribution; the floor alone keeps the distribution and fixes empty-crop labels. Each launch can wait for a previous run (WAIT0/WAIT1 = its train log). +# path of that run's train log) so it starts as soon as the GPU frees up. +# Usage: WAIT1=outputs/phase1_v5e_ab_train.log bash run_phase1_v5f.sh +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CACHE=outputs/phase1_cache/sidd_native_256 +DATA=/home/admin_mcn/data +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 8 --no-amp --seed 42 \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \ + --ood-real-root $DATA/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $DATA/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \ + --crop-select random" + +wait_log() { # $1 = train log to wait for ("" = no wait) + [ -z "$1" ] && return 0 + while ! grep -q "Training complete" "$1" 2>/dev/null; do + if grep -q Traceback "$1" 2>/dev/null && ! pgrep -f "[t]rain_graph_encoder_v2.py.*$(basename ${1%_train.log})" >/dev/null; then + echo "[v5f] $1 crashed; launching anyway"; return 0 + fi + sleep 120 + done + sleep 30 +} + +launch() { # $1 = run name, $2 = gpu, $3 = extra flags + local name=$1 gpu=$2 extra=$3 + mkdir -p outputs/$name + [ -f outputs/$name/severity_calibration.json ] || cp outputs/phase1_v5c/severity_calibration.json outputs/$name/ 2>/dev/null + CUDA_VISIBLE_DEVICES=$gpu setsid nohup $PY train_graph_encoder_v2.py $COMMON $extra \ + --output-dir outputs/$name > outputs/${name}_train.log 2>&1 < /dev/null & + echo "[v5f] $(date +%H:%M) launched $name on GPU$gpu ($extra) pid $!" +} + +ONLY=${ONLY:-both} +WAIT0=${WAIT0:-}; WAIT1=${WAIT1:-} +case "$ONLY" in + v5f) wait_log "$WAIT0"; launch phase1_v5f 0 "--severity-floor 0.05" ;; + v5f_b) wait_log "$WAIT1"; launch phase1_v5f_b 1 "--severity-floor 0.03" ;; + both) + ( wait_log "$WAIT0"; launch phase1_v5f 0 "--severity-floor 0.05" ) & + ( wait_log "$WAIT1"; launch phase1_v5f_b 1 "--severity-floor 0.03" ) & + wait + ;; + *) echo "ONLY must be v5f | v5f_b | both"; exit 2 ;; +esac diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_dgf8k.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_dgf8k.sh new file mode 100644 index 0000000000000000000000000000000000000000..f07a0f8e9e35268261bc7e8bb5e81be79478af7b --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_dgf8k.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_dgf8k_seed42 +LOG=outputs/phase2_v7/uformer_dgf8k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_head8k_seed42/best.pt +WARMSTART_SHA=0168e543c6025514e7b98ef7ddd9e191de2bdcaca9072e0a796fadcf503cbc9c + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_dgf8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.10 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_head8k.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_head8k.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee858db19602fd2b582c8e6ad15c841b3c1d9865 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_head8k.sh @@ -0,0 +1,85 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_head8k_seed42 +LOG=outputs/phase2_v7/uformer_head8k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_luma8k_seed42/best.pt +WARMSTART_SHA=42c11eda0df3d4c3645a7013a831a5e965915d252895c2de58b5048d286e7817 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_head8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_luma8k.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_luma8k.sh new file mode 100644 index 0000000000000000000000000000000000000000..25820b8a239403cff0abb7959acf624d50b35c84 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_luma8k.sh @@ -0,0 +1,84 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_luma8k_seed42 +LOG=outputs/phase2_v7/uformer_luma8k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer16k_seed42/best.pt +WARMSTART_SHA=809241a2a2e11c1d5e87b292827a97a2d71aa86a7684996caf903bf870532c43 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_luma8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_nophase1.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_nophase1.sh new file mode 100644 index 0000000000000000000000000000000000000000..b69b9ce6764752ab54881c1231a784f3e84aa0dc --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_nophase1.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_nophase1_8k_seed42 +LOG=outputs/phase2_v7/uformer_nophase1_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_head8k_seed42/best.pt +WARMSTART_SHA=0168e543c6025514e7b98ef7ddd9e191de2bdcaca9072e0a796fadcf503cbc9c + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_nophase1_8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=0 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 3 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 1.0 --identity-pair-prob 0.10 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_p45.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_p45.sh new file mode 100644 index 0000000000000000000000000000000000000000..a4220dfefc17f16b5e74f0d9cb5f073ef6136ac4 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_p45.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_p45_8k_seed42 +LOG=outputs/phase2_v7/uformer_p45_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_dgf8k_seed42/best.pt +WARMSTART_SHA=f92dc6d37ffe4e8a55ce723a1acf51042bf9821b98eefeaebb8ba140b7ce0f97 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_p45_8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=1 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.10 --noise-pair-prob 0.20 --global-context \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_p5.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_p5.sh new file mode 100644 index 0000000000000000000000000000000000000000..c89b274eb6da857e97f5cfb48c0929dd126e80b9 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_p5.sh @@ -0,0 +1,87 @@ +#!/bin/bash +# Launch + auto-resume supervisor for the v7-uformer luma run. +# First launch warm-starts from the 16k+chroma best; every relaunch after a +# designed RecoverableAmpOverflow resumes from overflow_recovery.pt. Stops on +# completion (eval @8000), on a non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_p5_8k_seed42 +LOG=outputs/phase2_v7/uformer_p5_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_dgf8k_seed42/best.pt +WARMSTART_SHA=f92dc6d37ffe4e8a55ce723a1acf51042bf9821b98eefeaebb8ba140b7ce0f97 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_p5_8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=0 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.10 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows)" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v10.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v10.sh new file mode 100644 index 0000000000000000000000000000000000000000..1c14f3d6dc7eebd163999a9dbfc38032f560260a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v10.sh @@ -0,0 +1,137 @@ +#!/bin/bash +# v10 chain (2026-09-04): runs AFTER uformer_v9a15k_seed42 finishes. +# 1. wait until the 15k trainer is gone (eval@15000, early stop, or death) +# 2. GPU0 evals of v9a15k best.pt: locked crop protocol (comparable to A/B/v9a-4k), +# native full-frame protocol (eval_full_frame.py) for v9a15k, A, v9a-4k, B, +# scene008 tone probe, then full-frame x8 TTA for v9a15k +# 3. GPU1 v10 = A recipe on Phase-1 v5f, warm-start v9a15k best (EMA) +# + whole-frame context + photometric head + exposure-diverse identity +# pairs from SIDD-train-GT / LOL-train-GT / Snow100K-gt (balanced) +# + v10 input pre-gain (Retinex-style) + global attention at stages 2,3 +# 4. GPU0 v10_ab = v10 minus pre-gain and global attention (isolates the two new blocks), +# launched when the evals are done +# Each run has its own AMP-overflow supervisor (resume from overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +SRC_NAME=uformer_v9a15k_seed42 +SRC_RUN=outputs/phase2_v7/$SRC_NAME +SRC_LOG=outputs/phase2_v7/uformer_v9a15k_train.log +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt +STEPS=${STEPS:-8000} +MAX_RESTARTS=20 +export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 + +log() { echo "[v10 $(date +%H:%M:%S)] $*"; } +src_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$SRC_NAME" >/dev/null; } +src_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": 15000\|\"step\": 15000.*\"event\": \"evaluation\"" "$SRC_RUN/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$SRC_LOG" 2>/dev/null +} + +# ---- 1. wait for the source run ------------------------------------------ # +quiet=0 +while true; do + if src_complete && ! src_running; then log "source run complete"; break; fi + if ! src_running; then + quiet=$((quiet + 1)) + if [ "$quiet" -ge 6 ]; then log "source trainer absent for 6 polls without completion; proceeding with its best.pt"; break; fi + else + quiet=0 + fi + sleep 60 +done +sleep 30 +WARM=$SRC_RUN/best.pt +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +log "warm start $WARM sha=$WARM_SHA phase1=$PHASE1 sha=$PHASE1_SHA" + +# ---- shared recipe ---------------------------------------------------------- # +COMMON="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \ + --learning-rate 3e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,500,1000,2000,3000,4000,5000,6000,7000,8000 --milestone-steps 4000,8000 \ + --freeze-encoder-steps 1000 --early-stop-patience 4 --early-stop-min-delta 0.02 \ + --seed 42 --eval-seed 20260830 \ + --global-context --photometric-head --photometric-dropout 0.1 \ + --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6" +V10_EXTRA="--exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --global-attention-scales 2,3" + +launch() { # $1 name $2 gpu $3 fresh|resume $4 extra flags + local name=$1 gpu=$2 mode=$3 extra=$4 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log + local source + if [ "$mode" = "fresh" ]; then + source="--warmstart-v6 $WARM --warmstart-v6-sha256 $WARM_SHA --warmstart-weight-source ema" + else + source="--resume $run_dir/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$gpu nohup $PY -u train_phase2_unified_v7.py $COMMON $extra $source \ + --output-dir "$run_dir" >> "$log" 2>&1 & + log "launched $name on GPU$gpu ($mode) pid $!" +} + +supervise() { # $1 name $2 gpu $3 extra flags + local name=$1 gpu=$2 extra=$3 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log + running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; } + complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $STEPS\|\"step\": $STEPS.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null + } + overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; } + local restarts=0 seen + seen=$(overflows) + if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$name" "$gpu" resume "$extra"; else launch "$name" "$gpu" fresh "$extra"; fi + sleep 180 + while true; do + if complete; then log "$name complete (eval @$STEPS or early stop)"; return 0; fi + if ! running; then + local current; current=$(overflows) + if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then + restarts=$((restarts + 1)); seen=$current + log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch "$name" "$gpu" resume "$extra"; sleep 180 + else + log "$name process died WITHOUT a new overflow (or budget exhausted); giving up"; return 1 + fi + fi + sleep 45 + done +} + +# ---- 3. v10 on GPU1 (starts immediately) ----------------------------------- # +( supervise uformer_v10_8k_seed42 1 "$V10_EXTRA" ) & +V10_PID=$! + +# ---- 2. evals of the source run on GPU0 ------------------------------------ # +run_eval() { log "eval: $*"; CUDA_VISIBLE_DEVICES=0 $PY -u "$@" >> outputs/phase2_v7/uformer_v10_evals.log 2>&1 || log "eval FAILED: $*"; } +run_eval eval_v7_external.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_external_v1.json +run_eval eval_full_frame.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_fullframe_v1.json --tta 1 +run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_p5_8k_seed42 --output outputs/v7_p5_fullframe_v1.json --tta 1 +run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_v9a_8k_seed42 --output outputs/v7_v9a4k_fullframe_v1.json --tta 1 +run_eval eval_full_frame.py --run-dir outputs/phase2_v7/uformer_p45_8k_seed42 --output outputs/v7_p45_fullframe_v1.json --tta 1 +run_eval probe_scene008_tone.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_scene008_tone.json --skip-val-baseline +run_eval eval_full_frame.py --run-dir $SRC_RUN --output outputs/v7_v9a15k_fullframe_tta8_v1.json --tta 8 +log "evals done" + +# ---- 4. ablation on GPU0 ---------------------------------------------------- # +( supervise uformer_v10ab_8k_seed42 0 "" ) & +AB_PID=$! +wait $V10_PID; log "v10 supervisor exited ($?)" +wait $AB_PID; log "v10_ab supervisor exited ($?)" +log "chain finished" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v10ab_resume.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v10ab_resume.sh new file mode 100644 index 0000000000000000000000000000000000000000..b1b85e9973505853dc6764c8c21a8b9964c5154e --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v10ab_resume.sh @@ -0,0 +1,71 @@ +#!/bin/bash +# Resume uformer_v10ab_8k_seed42 from its overflow_recovery.pt after the +# 08:12 resume died on a contract mismatch (code synced mid-run added +# architecture keys; the runtime now tolerates added keys). Same recipe as +# run_uformer_v10.sh (v10_ab = COMMON without the v10 extras), GPU0, with the +# same overflow supervisor. +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +NAME=uformer_v10ab_8k_seed42 +RUN_DIR=outputs/phase2_v7/$NAME +LOG=outputs/phase2_v7/${NAME}_train.log +STEPS=8000 +GPU=${GPU:-0} +MAX_RESTARTS=20 +PHASE1=outputs/phase1_v5f/graph_encoder_best.pt +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt +export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 +log() { echo "[v10ab-resume $(date +%H:%M:%S)] $*"; } + +COMMON="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \ + --learning-rate 3e-5 --max-steps $STEPS --run-until-step $STEPS \ + --eval-steps 0,500,1000,2000,3000,4000,5000,6000,7000,8000 --milestone-steps 4000,8000 \ + --freeze-encoder-steps 1000 --early-stop-patience 4 --early-stop-min-delta 0.02 \ + --seed 42 --eval-seed 20260830 \ + --global-context --photometric-head --photometric-dropout 0.1 \ + --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6" + +running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $RUN_DIR" >/dev/null; } +complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $STEPS\|\"step\": $STEPS.*\"event\": \"evaluation\"" "$RUN_DIR/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$LOG" 2>/dev/null +} +overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null | head -n 1); echo "${n:-0}"; } +launch() { + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$GPU nohup $PY -u train_phase2_unified_v7.py $COMMON \ + --resume $RUN_DIR/overflow_recovery.pt --output-dir "$RUN_DIR" >> "$LOG" 2>&1 & + log "launched resume on GPU$GPU pid $!" +} + +[ -f "$RUN_DIR/overflow_recovery.pt" ] || { log "no overflow_recovery.pt; nothing to resume"; exit 1; } +if running; then log "already running"; exit 0; fi +restarts=0; seen=$(overflows) +launch; sleep 180 +while true; do + if complete; then log "complete"; break; fi + if ! running; then + current=$(overflows) + if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ]; then + restarts=$((restarts + 1)); seen=$current + log "relaunch #$restarts from overflow_recovery.pt (overflows=$current)"; launch; sleep 180 + else + log "died WITHOUT a new overflow; giving up"; break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v11.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v11.sh new file mode 100644 index 0000000000000000000000000000000000000000..7aa20989b64d55817293af76a5a754a424218b1f --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v11.sh @@ -0,0 +1,221 @@ +#!/bin/bash +# v11 chain (2026-09-05): capacity + budget + progressive resolution, both GPUs (DDP). +# 0. wait until the v10 chain is finished (no v10 supervisor, no trainer processes) +# 1. native full-frame + crop evals of v10 and v10_ab (GPU0 / GPU1 in parallel), then +# pick the warm start among {v10, v10_ab, v9a15k} by the mean of the four +# full-frame group PSNRs (lowlight LOLv2, rain Test1200 Y-channel, haze, scene008) +# 2. memory probe (GPU0) to pick per-stage batch sizes +# 3. stage A crop 256, 24k steps, DDP x2, LR 5e-5 +# stage B crop 320, 8k steps, DDP x2, LR 3e-5, warm-start best of A +# stage C crop 384, 8k steps, DDP x2 (or 1 GPU + grad checkpoint if the probe says so), LR 2e-5 +# recipe = v10 (pre-gain, global attention 2,3, whole-frame context, photometric head, +# exposure-diverse identity pools) + --extra-blocks-per-stage 0,2,4,4 (13.4M -> ~28.8M) +# 4. full-frame evals after every stage (TTA 1), TTA 8 after stage C +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,/home/admin_mcn/data/Snow100K/train/all/gt +MAX_RESTARTS=20 +MEM_BUDGET_GIB=${MEM_BUDGET_GIB:-19.5} +export PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 +EVLOG=outputs/phase2_v7/uformer_v11_evals.log + +log() { echo "[v11 $(date +%H:%M:%S)] $*"; } +trainers_running() { pgrep -f "[t]rain_phase2_unified_v7.py" >/dev/null; } +v10_chain_running() { pgrep -f "[r]un_uformer_v10.sh" >/dev/null; } + +# ---- 0. wait for the GPUs ------------------------------------------------- # +while v10_chain_running || trainers_running; do sleep 120; done +log "GPUs free" +sleep 30 + +# ---- 1. evals of the v10 pair + warm-start selection ---------------------- # +run_eval() { local gpu=$1; shift; log "eval GPU$gpu: $*"; CUDA_VISIBLE_DEVICES=$gpu $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } +# WARM_OVERRIDE= skips the evaluation sweep and the +# selection (user request 2026-09-05: start DDP training right away). +if [ -n "${WARM_OVERRIDE:-}" ]; then + WARM=$WARM_OVERRIDE + WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) + log "warm start OVERRIDE: $WARM sha=$WARM_SHA (evaluation sweep skipped)" +fi +if [ -z "${WARM_OVERRIDE:-}" ]; then +# Whole-image single pass for images <= 1.2 MP (LOL / RESIDE / Test1200); the +# 12 MP SIDD frames stay tiled. Tiling costs -2.1 dB on LOLv2 (per-tile +# exposure inconsistency), so every full-frame number below uses this mode. +WHOLE="--whole-max-pixels 1200000" +# best.pt is picked by val macro, which is a poor proxy for the external +# sets, so every candidate run is evaluated at best / milestone / last and +# the warm start is the best (run, checkpoint) pair on the full-frame score. +ckpt_tag() { echo "$1" | sed 's/\.pt$//; s/milestone_0*/m/'; } +eval_run_checkpoints() { # $1 gpu $2 run $3 tag $4.. checkpoints + local gpu=$1 run=$2 tag=$3; shift 3 + run_eval "$gpu" eval_v7_external.py --run-dir outputs/phase2_v7/$run --output outputs/v7_${tag}_external_v1.json + for ck in "$@"; do + [ -f outputs/phase2_v7/$run/$ck ] || { log "skip missing $run/$ck"; continue; } + run_eval "$gpu" eval_full_frame.py --run-dir outputs/phase2_v7/$run --checkpoint "$ck" \ + --output outputs/v7_${tag}_$(ckpt_tag "$ck")_fullframe_whole_v1.json --tta 1 $WHOLE + done +} +( eval_run_checkpoints 0 uformer_v10_8k_seed42 v10 best.pt milestone_00004000.pt last.pt + eval_run_checkpoints 0 uformer_v9a15k_seed42 v9a15k best.pt milestone_00008000.pt last.pt ) & +( eval_run_checkpoints 1 uformer_v10ab_8k_seed42 v10ab best.pt milestone_00004000.pt last.pt ) & +wait +SELECTION=$($PY - <<'PYEOF' +import glob, json, os, re, sys +runs = {"v10": "uformer_v10_8k_seed42", "v10ab": "uformer_v10ab_8k_seed42", "v9a15k": "uformer_v9a15k_seed42"} +def score(path): + r = json.load(open(path)) + try: + return (r["lowlight_lolv2_test"]["restored"]["psnr"] + r["rain_locked"]["restored"]["psnr_y"] + + r["haze_heldout"]["restored"]["psnr"] + r["noise_locked_scene008"]["restored"]["psnr"]) / 4.0, r.get("checkpoint", "best.pt") + except KeyError: + return None, None +scores = {} +for tag, run in runs.items(): + for path in glob.glob("outputs/v7_%s_*_fullframe_whole_v1.json" % tag): + value, ck = score(path) + if value is not None and ck and os.path.exists("outputs/phase2_v7/%s/%s" % (run, ck)): + scores[(run, ck)] = value +if not scores: + print("uformer_v9a15k_seed42 best.pt") +else: + (run, ck) = max(scores, key=scores.get) + print(run, ck) +sys.stderr.write("warm-start scores: %s\n" % json.dumps({"%s/%s" % k: round(v, 3) for k, v in sorted(scores.items())})) +PYEOF +) +read -r SOURCE SOURCE_CKPT <<< "$SELECTION" +log "warm start selected: $SOURCE/$SOURCE_CKPT" +WARM=outputs/phase2_v7/$SOURCE/$SOURCE_CKPT +WARM_SHA=$(sha256sum $WARM | cut -d' ' -f1) +fi + +# ---- shared recipe -------------------------------------------------------- # +RECIPE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers 4 --seed 42 --eval-seed 20260830 \ + --global-context --photometric-head --photometric-dropout 0.1 \ + --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4" + +# ---- 2. memory probe ------------------------------------------------------ # +probe() { # $1 crop $2 batch $3 extra -> peak GiB or 99 on failure + 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") + echo "$out" >> $EVLOG + 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)" +} +fits() { $PY -c "import sys; sys.exit(0 if float('$1') <= float('$MEM_BUDGET_GIB') else 1)"; } +pick_batch() { # $1 crop -> "batch accum" for DDP x2 with effective batch 16 (stdout = result only) + local crop=$1 peak + for cfg in "8 1" "4 2" "2 4"; do + set -- $cfg + peak=$(probe "$crop" "$1" "") + log "probe crop=$crop batch=$1 -> peak ${peak} GiB" >&2 + if fits "$peak"; then echo "$1 $2"; return 0; fi + done + echo "0 0" +} + +# ---- supervisor ----------------------------------------------------------- # +launch() { # name gpus mode(fresh|resume) crop batch accum steps lr evalsteps milestones extra warm + 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} + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log source + if [ "$mode" = "fresh" ]; then + source="--warmstart-v6 $warm --warmstart-v6-sha256 $(sha256sum $warm | cut -d' ' -f1) --warmstart-weight-source ema" + else + source="--resume $run_dir/overflow_recovery.pt" + fi + local common="$RECIPE $extra $source --output-dir $run_dir --crop-size $crop \ + --batch-size $batch --grad-accum $accum --eval-batch-size 4 \ + --learning-rate $lr --max-steps $steps --run-until-step $steps \ + --eval-steps $evals --milestone-steps $miles \ + --freeze-encoder-steps 1000 --early-stop-patience ${PATIENCE:-0} --early-stop-min-delta 0.02" + # shellcheck disable=SC2086 + if [ "$gpus" = "0,1" ]; then + CUDA_VISIBLE_DEVICES=0,1 nohup $PY -m torch.distributed.run --nproc_per_node=2 --master_port=29531 \ + train_phase2_unified_v7.py --ddp --ddp-find-unused $common >> "$log" 2>&1 & + else + CUDA_VISIBLE_DEVICES=$gpus nohup $PY -u train_phase2_unified_v7.py $common >> "$log" 2>&1 & + fi + log "launched $name on GPU$gpus ($mode, crop $crop, batch ${batch}x${accum}, $steps steps) pid $!" +} + +supervise() { # same args as launch (mode ignored) + local name=$1 gpus=$2 steps=$7 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log + running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; } + complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $steps\|\"step\": $steps.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null + } + overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; } + local restarts=0 seen; seen=$(overflows) + if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$1" "$2" resume "${@:4}"; else launch "$1" "$2" fresh "${@:4}"; fi + sleep 240 + while true; do + if complete; then log "$name complete"; return 0; fi + if ! running; then + local current; current=$(overflows) + if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then + restarts=$((restarts + 1)); seen=$current + log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch "$1" "$2" resume "${@:4}"; sleep 240 + else + log "$name died WITHOUT a new overflow (or budget exhausted); stopping the chain"; return 1 + fi + fi + sleep 60 + done +} + +stage_evals() { # $1 run name $2 tag $3 tta + run_eval 0 eval_v7_external.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_external_v1.json + 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 + 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 + if [ "$3" = "8" ]; then + # orientation-safe x2 (mirror) for every group; the full dihedral x8 only + # for isotropic noise (x8 costs -2.4 dB on rain / -1.0 dB on haze) + 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 + 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 + run_eval 1 probe_scene008_tone.py --run-dir outputs/phase2_v7/$1 --output outputs/v7_${2}_scene008_tone.json --skip-val-baseline + fi +} + +# ---- 3. stages ------------------------------------------------------------ # +A=uformer_v11a_256_seed42; B=uformer_v11b_320_seed42; C=uformer_v11c_384_seed42 + +read -r BA AA <<< "$(pick_batch 256)" +[ "$BA" = "0" ] && { log "no batch fits at 256; aborting"; exit 1; } +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 +stage_evals $A v11a 1 + +read -r BB AB <<< "$(pick_batch 320)" +[ "$BB" = "0" ] && { log "no batch fits at 320; aborting"; exit 1; } +# Stages warm-start from the END of the previous stage (last.pt = cosine +# schedule fully annealed): best.pt is picked by val macro, which does not +# track the external sets and can stay at the step-0 checkpoint. +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 +stage_evals $B v11b 1 + +read -r BC AC <<< "$(pick_batch 384)" +if [ "$BC" = "0" ]; then + log "384 does not fit without checkpointing on 2 ranks; running stage C on ONE GPU with --grad-checkpoint (batch 4 x accum 4)" + 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 +else + 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 +fi +stage_evals $C v11c 8 +log "chain finished" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v11_mi325x.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v11_mi325x.sh new file mode 100644 index 0000000000000000000000000000000000000000..2137ee21d595e3e7523d54327df0b91aa6f4614f --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v11_mi325x.sh @@ -0,0 +1,120 @@ +#!/bin/bash +# v11 on the MI325X host (kim.long-mi325x8), ONE GPU (default 7), no DDP. +# Same recipe as run_uformer_v11.sh; the 256 GB card takes the whole +# effective batch in one micro-batch, so batch/LR/steps are re-scaled: +# stage A crop 256 BATCH_A (probe: 2.6 GiB/sample) LR_A STEPS_A +# stage B crop 320 BATCH_B LR_B STEPS_B warm-start A/last.pt +# stage C crop 384 BATCH_C LR_C STEPS_C warm-start B/last.pt +# Data roots come from the HF bundle (SCDC_DATA_ROOT / SCDC_RAIN13K_ROOT). +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +# map this host's roots back to the canonical ones for the audited split digests +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/ +GPU=${GPU:-7} +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) +TAG=${TAG:-x} # run-name suffix: x = v11 on MI325X, v12 = Phase-1 v6 +WARM=${WARM:-outputs/phase2_v7/uformer_v10_8k_seed42/best.pt} +# identity-pair clean pools: TRAIN-split SIDD/LOL GTs only (built by make_clean_pools.py), plus Snow100K gt +POOLS=outputs/clean_pools/sidd_train_gt,outputs/clean_pools/lol_train_gt,$SCDC_DATA_ROOT/Snow100K/train/all/gt +# Probe on GPU 7 (30M params, crop 256): batch 16 -> 42 GiB 0.42 s (38 img/s), +# batch 32 -> 84 GiB 0.67 s (48 img/s), batch 64 -> 167 GiB 1.56 s (41 img/s), +# batch 96 OOM. Compute saturates at 32, so 32 gives the most images/s AND the +# most optimizer steps per hour; LR scaled by sqrt(32/16) from the 5e-5 recipe. +BATCH_A=${BATCH_A:-32}; LR_A=${LR_A:-7e-5}; STEPS_A=${STEPS_A:-20000} +BATCH_B=${BATCH_B:-20}; LR_B=${LR_B:-5e-5}; STEPS_B=${STEPS_B:-6000} +BATCH_C=${BATCH_C:-14}; LR_C=${LR_C:-3e-5}; STEPS_C=${STEPS_C:-6000} +WORKERS=${WORKERS:-32} +EXTRA_WORKERS=${EXTRA_WORKERS:-12} +export OMP_NUM_THREADS=${OMP_NUM_THREADS:-8} +MAX_RESTARTS=20 +EVLOG=outputs/phase2_v7/uformer_v11_${TAG}_evals.log +WHOLE="--whole-max-pixels 1200000" +log() { echo "[v11x $(date +%H:%M:%S)] $*"; } + +RECIPE="--backbone uformer --timesteps 2 \ + --phase1-checkpoint $PHASE1 --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --workers $WORKERS --extra-clean-workers $EXTRA_WORKERS --seed 42 --eval-seed 20260830 \ + --global-context --photometric-head --photometric-dropout 0.1 \ + --identity-pair-prob 0.15 --identity-exposure-jitter 0.7 \ + --extra-clean-root $POOLS --extra-clean-prob 0.6 \ + --exposure-pregain --pregain-dropout 0.1 --pregain-max-log-gain 1.6 --pregain-target-weight 0.02 \ + --global-attention-scales 2,3 --extra-blocks-per-stage 0,2,4,4" + +launch() { # name mode(fresh|resume) crop batch steps lr evalsteps milestones warm + local name=$1 mode=$2 crop=$3 batch=$4 steps=$5 lr=$6 evals=$7 miles=$8 warm=$9 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log source + if [ "$mode" = "fresh" ]; then + source="--warmstart-v6 $warm --warmstart-v6-sha256 $(sha256sum $warm | cut -d' ' -f1) --warmstart-weight-source ema" + else + source="--resume $run_dir/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$GPU nohup $PY -u train_phase2_unified_v7.py $RECIPE $source --output-dir $run_dir \ + --crop-size $crop --batch-size $batch --grad-accum 1 --eval-batch-size 16 \ + --learning-rate $lr --max-steps $steps --run-until-step $steps \ + --eval-steps $evals --milestone-steps $miles \ + --freeze-encoder-steps 500 --early-stop-patience 0 --early-stop-min-delta 0.02 >> "$log" 2>&1 & + log "launched $name on GPU$GPU ($mode, crop $crop, batch $batch, $steps steps, lr $lr) pid $!" +} + +supervise() { # same args as launch minus mode: name crop batch steps lr evals miles warm + local name=$1 steps=$4 + local run_dir=outputs/phase2_v7/$name log=outputs/phase2_v7/${name}_train.log + running() { pgrep -f "[t]rain_phase2_unified_v7.py.*output-dir $run_dir" >/dev/null; } + complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $steps\|\"step\": $steps.*\"event\": \"evaluation\"" "$run_dir/metrics.jsonl" 2>/dev/null \ + || grep -q "\[early-stop\] training ended" "$log" 2>/dev/null + } + overflows() { local n; n=$(grep -c "RecoverableAmpOverflow" "$log" 2>/dev/null | head -n 1); echo "${n:-0}"; } + local restarts=0 seen; seen=$(overflows) + if [ -f "$run_dir/overflow_recovery.pt" ]; then launch "$1" resume "${@:2}"; else launch "$1" fresh "${@:2}"; fi + sleep 240 + while true; do + if complete; then log "$name complete"; return 0; fi + if ! running; then + local current; current=$(overflows) + if [ "$current" -gt "$seen" ] && [ "$restarts" -lt "$MAX_RESTARTS" ] && [ -f "$run_dir/overflow_recovery.pt" ]; then + restarts=$((restarts + 1)); seen=$current + log "$name relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch "$1" resume "${@:2}"; sleep 240 + else + log "$name died WITHOUT a new overflow (or budget exhausted); stopping the chain"; return 1 + fi + fi + sleep 60 + done +} + +run_eval() { log "eval: $*"; CUDA_VISIBLE_DEVICES=$GPU $PY -u "$@" >> $EVLOG 2>&1 || log "eval FAILED: $*"; } +stage_evals() { # run tag tta + run_eval eval_v7_external.py --run-dir outputs/phase2_v7/$1 --checkpoint last.pt --output outputs/v7_${2}_external_v1.json + 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 + 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 + if [ "$3" = "8" ]; then + 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 + 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 + fi +} + +A=uformer_v11a_256_$TAG; B=uformer_v11b_320_$TAG; C=uformer_v11c_384_$TAG +log "warm start $WARM sha=$(sha256sum $WARM | cut -d' ' -f1) phase1 sha=$PHASE1_SHA GPU=$GPU" +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 +stage_evals $A v11a$TAG 1 +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 +stage_evals $B v11b$TAG 1 +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 +stage_evals $C v11c$TAG 8 +log "chain finished" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8a.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8a.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec8a6f2b1957505f839040be06b50012a7d96386 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8a.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# v8a: Phase-2 on Phase-1 v5 — A recipe (clean prior + tail 6) + whole-frame +# context (B) + global exposure controllable head + exposure-diverse identity +# pairs (Snow100K gt pool); chroma loss space = uv. Warm-start from A best. +# Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v8a_8k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v8a_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt +WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1) +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=0 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \ + --photometric-head --photometric-dropout 0.15 \ + --identity-exposure-jitter 0.9 \ + --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8b.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8b.sh new file mode 100644 index 0000000000000000000000000000000000000000..585f1192944af2c249f656370aea5d677cf9493d --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8b.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# v8b: Phase-2 on Phase-1 v5 — A recipe (clean prior + tail 6) + whole-frame +# context (B) + global exposure controllable head + exposure-diverse identity +# pairs (Snow100K gt pool); chroma loss space = hv. Warm-start from A best. +# Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v8b_8k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v8b_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt +WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1) +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=1 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-chroma-space hv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \ + --photometric-head --photometric-dropout 0.15 \ + --identity-exposure-jitter 0.9 \ + --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8c.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8c.sh new file mode 100644 index 0000000000000000000000000000000000000000..43aa51afdb3fc7e549c43c45c8f33c5efb8c0925 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v8c.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# v8c: identical recipe to v8a (uv chroma) but conditioned on Phase-1 v5b +# (HVI photometric branch, real-snow OOD). Isolates the Phase-1 choice vs v8a +# (ll_v3). Warm-start from A best (trunk was trained under ll_v3 conditioning). +# Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v8c_8k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v8c_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt +WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1) +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5b/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=1 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \ + --photometric-head --photometric-dropout 0.15 \ + --identity-exposure-jitter 0.9 \ + --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +restarts=0 +seen_overflows=$(overflow_count) +echo "[supervisor] fresh launch (prior overflows in log: $seen_overflows) phase1=$PHASE1 sha=$PHASE1_SHA" +launch fresh +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9a.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9a.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a1abf65d6eeec585fd790762d66f980dbba1b74 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9a.sh @@ -0,0 +1,94 @@ +#!/bin/bash +# v9a: the A recipe (uformer_p5) with ONE variable changed — Phase-1 is +# phase1_v5f (native crops + severity floor 0.05) instead of ll_v3. Same +# warm-start (dgf8k best, EMA), same 8k steps, same seed, same flags, so the +# macro PSNR is directly comparable to A's 27.903 / 0.8591. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer_v9a_8k_seed42 +LOG=outputs/phase2_v7/uformer_v9a_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_dgf8k_seed42/best.pt +WARMSTART_SHA=f92dc6d37ffe4e8a55ce723a1acf51042bf9821b98eefeaebb8ba140b7ce0f97 +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer_v9a_8k_seed42" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=0 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.10 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 2 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { local n; n=$(grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null | head -n 1); echo "${n:-0}"; } + +restarts=0 +seen_overflows=$(overflow_count) +if [ -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] resuming from an existing overflow_recovery.pt phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows in log: $seen_overflows)" + launch resume +else + echo "[supervisor] fresh launch phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows in log: $seen_overflows)" + launch fresh +fi +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9a15k.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9a15k.sh new file mode 100644 index 0000000000000000000000000000000000000000..5168c1589e716651b07dd188d30029b1fe453c7a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9a15k.sh @@ -0,0 +1,114 @@ +#!/bin/bash +# v9a-15k: the A recipe on Phase-1 v5f, trained to 15k steps across BOTH GPUs +# (torchrun DDP, world size 2), with a decoder-first curriculum and early +# stopping. +# +# * Phase-1 outputs/phase1_v5f/graph_encoder_best.pt (native crops + +# severity floor 0.05; 4/4 gates) +# * warm start uformer_dgf8k_seed42/best.pt (EMA) — the same source A used, +# so the 8k-step v9a numbers stay comparable +# * effective batch 16 = batch 8 x grad-accum 1 x 2 ranks (A: 8 x 2 x 1 rank) +# * --ddp-find-unused is REQUIRED: the MoE experts are hard-skipped per +# batch, so the used-parameter set differs across ranks and the reducer +# deadlocks on the first divergent batch (observed: both ranks spinning +# at 100% inside the grad-norm all_reduce, no step ever logged) +# * curriculum first 3000 steps train the decoder / conditioning / heads +# only (encoder gradients dropped), then the whole network +# * early stopping 3 evaluations without a macro-PSNR gain above 0.02 dB +# +# Auto-resume supervisor: a designed RecoverableAmpOverflow resumes from +# overflow_recovery.pt; anything else stops the run. +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v9a15k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v9a15k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=15000 +WARMSTART=outputs/phase2_v7/uformer_dgf8k_seed42/best.pt +WARMSTART_SHA=f92dc6d37ffe4e8a55ce723a1acf51042bf9821b98eefeaebb8ba140b7ce0f97 +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null || grep -q "\[early-stop\] training ended" "$LOG" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=0,1 nohup "$PY" -m torch.distributed.run \ + --nproc_per_node=2 --master_port=29517 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.10 --noise-pair-prob 0.20 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,5000,6000,7000,8000,10000,12000,15000 \ + --milestone-steps 4000,8000,12000 \ + --freeze-encoder-steps 3000 \ + --early-stop-patience 3 --early-stop-min-delta 0.02 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { local n; n=$(grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null | head -n 1); echo "${n:-0}"; } + +restarts=0 +seen_overflows=$(overflow_count) +if [ -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] resuming from an existing overflow_recovery.pt phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows: $seen_overflows)" + launch resume +else + echo "[supervisor] fresh launch phase1=$PHASE1 sha=$PHASE1_SHA ddp=2 steps=$FINAL_STEP (prior overflows: $seen_overflows)" + launch fresh +fi +sleep 120 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP or early stop); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + restarts=$((restarts + 1)) + seen_overflows=$current + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 120 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9b.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9b.sh new file mode 100644 index 0000000000000000000000000000000000000000..b8b5a722ebab86642ad32b0a68852d871a590b0e --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_uformer_v9b.sh @@ -0,0 +1,103 @@ +#!/bin/bash +# v9b: Phase-2 on Phase-1 v5f — A recipe + whole-frame context (B) + global +# exposure controllable head + exposure-diverse identity pairs (Snow100K gt); +# chroma loss space = uv. Warm-start from A best. Pairs with v9a (plain A +# recipe on the same Phase-1) to separate 'better Phase-1' from 'v8 features'. +# Auto-resume supervisor (RecoverableAmpOverflow -> overflow_recovery.pt). +set -u +cd /home/admin_mcn/scdc_ban +RUN_NAME=uformer_v9b_8k_seed42 +RUN_DIR=outputs/phase2_v7/$RUN_NAME +LOG=outputs/phase2_v7/uformer_v9b_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +FINAL_STEP=8000 +WARMSTART=outputs/phase2_v7/uformer_p5_8k_seed42/best.pt +WARMSTART_SHA=$(sha256sum $WARMSTART | cut -d' ' -f1) +PHASE1=${PHASE1_CKPT:-outputs/phase1_v5f/graph_encoder_best.pt} +PHASE1_SHA=$(sha256sum $PHASE1 | cut -d' ' -f1) + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*$RUN_NAME" >/dev/null; } +is_complete() { + grep -q "\"event\": \"evaluation\".*\"step\": $FINAL_STEP\|\"step\": $FINAL_STEP.*\"event\": \"evaluation\"" \ + "$RUN_DIR/metrics.jsonl" 2>/dev/null +} + +launch() { + if [ "$1" = "fresh" ]; then + SOURCE_FLAGS="--warmstart-v6 $WARMSTART --warmstart-v6-sha256 $WARMSTART_SHA --warmstart-weight-source ema" + else + SOURCE_FLAGS="--resume $RUN_DIR/overflow_recovery.pt" + fi + # shellcheck disable=SC2086 + # The whole-frame context path peaks at ~22 GB of the 24 GB card with + # batch 8, which OOMs as soon as a resume adds the optimizer moments up + # front. Half the micro-batch, twice the accumulation: same effective + # batch 16, ~11 GB peak. + CUDA_VISIBLE_DEVICES=1 PYTORCH_CUDA_ALLOC_CONF=max_split_size_mb:128 nohup "$PY" \ + train_phase2_unified_v7.py \ + --backbone uformer --timesteps 2 \ + $SOURCE_FLAGS \ + --phase1-checkpoint $PHASE1 \ + --phase1-sha256 $PHASE1_SHA \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-chroma-space uv --fine-luma-weight 0.5 --fine-vgg-weight 0.1 \ + --full-res-tail-blocks 6 --full-res-tail-width 48 --output-film \ + --pyramid-heads --pyramid-loss-weights 0.1,0.2,0.3 \ + --cond-dropout-prob 0.15 --identity-pair-prob 0.15 --noise-pair-prob 0.20 --global-context \ + --photometric-head --photometric-dropout 0.15 \ + --identity-exposure-jitter 0.9 \ + --extra-clean-root /home/admin_mcn/data/Snow100K/train/all/gt --extra-clean-prob 0.5 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 4 --grad-accum 4 --eval-batch-size 4 --workers 4 \ + --learning-rate 3e-5 --max-steps $FINAL_STEP --run-until-step $FINAL_STEP \ + --eval-steps 0,500,1000,2000,3000,4000,6000,8000 \ + --milestone-steps 4000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { local n; n=$(grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null | head -n 1); echo "${n:-0}"; } + +restarts=0 +seen_overflows=$(overflow_count) +if [ -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] resuming from an existing overflow_recovery.pt phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows in log: $seen_overflows)" + launch resume +else + echo "[supervisor] fresh launch phase1=$PHASE1 sha=$PHASE1_SHA (prior overflows in log: $seen_overflows)" + launch fresh +fi +sleep 90 + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @$FINAL_STEP present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] overflow logged but no recovery checkpoint; exiting" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch resume + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_v12_mi325x.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_v12_mi325x.sh new file mode 100644 index 0000000000000000000000000000000000000000..6d9a239c0d4e0efded1d7bc642182f602d85e818 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_v12_mi325x.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# v12 on the MI325X host, ONE GPU (default 5): +# stage 0 Phase-1 v6 = v5f recipe + oriented Haar bands (rain vs snow/noise) +# + root weight 1.0 (clean images collapse to the root in global space) +# + OOD global margin 0.25 (snow away from known-type centroids) +# stage 1+ Phase-2 v11 recipe chained on Phase-1 v6 (run_uformer_v11_mi325x.sh, TAG=v12) +set -u +cd /home/vunguyen/SCDC +PY=/home/vunguyen/miniforge3/envs/mavt/bin/python +export SCDC_DATA_ROOT=/home/vunguyen/data_bundle/extract/data +export SCDC_RAIN13K_ROOT=/home/vunguyen/data_bundle/extract/kagglehub/datasets/hngphchi/rain13k-resized/versions/1 +GPU=${GPU:-5} +NAME=phase1_v6 +CACHE=outputs/phase1_cache/sidd_native_256 +log() { echo "[v12 $(date +%H:%M:%S)] $*"; } + +COMMON="--batch-size 32 --eval-batch-size 16 --epochs 50 --steps-per-epoch 500 \ + --learning-rate 1e-4 --weight-decay 1e-4 --max-grad-norm 1.0 --image-size 256 \ + --workers 12 --no-amp --seed 42 \ + --photometric --photometric-dim 128 --photometric-weight 0.5 \ + --embed-weight 0.25 --embed-temperature 0.1 --embed-members all \ + --ood-real-root $SCDC_DATA_ROOT/Snow100K/train/all/synthetic --ood-real-prob 0.35 --ood-real-val-count 512 \ + --extra-clean-root $SCDC_DATA_ROOT/Snow100K/train/all/gt --extra-null-weight 0.05 \ + --reside-limit 5000 --reside-val-count 100 --run-final-test \ + --crop-policy native --sidd-native-crops 32 --cache-root $CACHE \ + --crop-select random --severity-floor 0.05 \ + --ll-oriented-bands --root-weight 1.0 --ood-global-margin-weight 0.25" + +mkdir -p outputs/$NAME +[ -f outputs/$NAME/severity_calibration.json ] || cp outputs/phase1_v5f/severity_calibration.json outputs/$NAME/ 2>/dev/null +if ! grep -q "Training complete" outputs/${NAME}_train.log 2>/dev/null; then + log "stage 0: Phase-1 v6 on GPU$GPU" + # shellcheck disable=SC2086 + CUDA_VISIBLE_DEVICES=$GPU $PY -u train_graph_encoder_v2.py $COMMON --output-dir outputs/$NAME > outputs/${NAME}_train.log 2>&1 + grep -q "Training complete" outputs/${NAME}_train.log || { log "Phase-1 v6 did not finish; see outputs/${NAME}_train.log"; exit 1; } +fi +log "Phase-1 v6 done: $(grep -o 'best.*' outputs/${NAME}_train.log | tail -n 1 | cut -c1-120)" +[ -f outputs/$NAME/graph_encoder_best.pt ] || { log "no graph_encoder_best.pt"; exit 1; } +log "stage 1+: Phase-2 v12 chain on GPU$GPU" +PHASE1_CKPT=outputs/$NAME/graph_encoder_best.pt TAG=v12 GPU=$GPU bash run_uformer_v11_mi325x.sh diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_v8_after_v5.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_v8_after_v5.sh new file mode 100644 index 0000000000000000000000000000000000000000..9357388d3a9ab6882716c8c2bffdb1fc24f9121a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_v8_after_v5.sh @@ -0,0 +1,91 @@ +#!/bin/bash +# Chain: wait for the Phase-1 v5 candidates to finish, run the sanity +# dashboard + real-snow gate on each, pick the best passing candidate, then +# launch the two Phase-2 v8 supervisors (v8a GPU0 = UV chroma, v8b GPU1 = HV +# chroma) on it. Stops before spending 2x8h GPU when no candidate passes. +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +CANDIDATES=${CANDIDATES:-"phase1_v5 phase1_v5b"} + +wait_for() { # $1 = run name + local dir=outputs/$1 log=outputs/$1_train.log + while true; do + if [ -f "$dir/locked_test_metrics.json" ] && grep -q "Training complete" "$log" 2>/dev/null; then return 0; fi + if grep -q "Traceback" "$log" 2>/dev/null && ! pgrep -f "[t]rain_graph_encoder_v2.py.*$1" >/dev/null; then + local age=$(( $(date +%s) - $(stat -c %Y "$log") )) + if [ "$age" -gt 120 ]; then echo "[chain] $1 crashed (log idle ${age}s)"; return 1; fi + fi + sleep 120 + done +} + +gate_for() { # $1 = run name ; writes outputs/$1_gate.json ; prints pass/score + local name=$1 ckpt=outputs/$1/graph_encoder_best.pt + CUDA_VISIBLE_DEVICES=0 $PY visualize_phase1_graph.py --checkpoint $ckpt --output-dir outputs/phase1_vis/$name > outputs/phase1_vis_$name.log 2>&1 + CAND=$name CUDA_VISIBLE_DEVICES=0 $PY - <<'PYEOF' > outputs/${name}_gate.log 2>&1 +import glob, hashlib, json, math, os, torch, numpy as np +from pathlib import Path +from PIL import Image +import train_phase2_graph_resshift_v4 as v4 +from visualize_phase1_graph import encode, NODES +name = os.environ["CAND"] +files = sorted(glob.glob("/home/admin_mcn/data/Snow100K/realistic/**/*.jpg", recursive=True)) +def load(f): + im = Image.open(f).convert("RGB"); w, h = im.size; s = 256 / min(w, h) + if s > 1: im = im.resize((max(256, math.ceil(w * s)), max(256, math.ceil(h * s))), Image.LANCZOS); w, h = im.size + l, t = (w - 256) // 2, (h - 256) // 2 + return torch.from_numpy(np.asarray(im.crop((l, t, l + 256, t + 256)), dtype=np.float32) / 255.).permute(2, 0, 1) +imgs = torch.stack([load(f) for f in files]) +ck = Path("outputs/%s/graph_encoder_best.pt" % name) +p1, _ = v4.build_frozen_phase1(ck, hashlib.sha256(ck.read_bytes()).hexdigest(), torch.device("cuda")) +enc = encode(p1, imgs.cuda()) +route = dict(zip(NODES, enc["routing"].mean(0).tolist())) +summary = json.load(open("outputs/phase1_vis/%s/summary.json" % name)) +conf = summary["confusion"] +row = lambda prefix: next(v for k, v in conf.items() if k.startswith(prefix)) +hist = json.load(open("outputs/%s/history.json" % name)) +best_f1 = max(e["val"].get("macro_f1", 0.0) for e in hist if "val" in e) +gates = { + "snow_real_free": (route["free1"] + route["free2"], 0.70, ">="), + # not worse than ll_v3 (0.46 haze->rain on the same val); the +0.3 dB + # claim for v8 does not depend on Phase-1 routing improving, only on it + # not regressing and on photometric_state existing. + "haze_to_rain_max": (row("Haze input")["rain"], 0.46, "<="), + "rain_to_rain_min": (row("Rain input")["rain"], 0.55, ">="), + "lowlight_to_lowlight_min": (row("Low-light input")["lowlight"], 0.85, ">="), +} +passed = {k: (v[0] >= v[1] if v[2] == ">=" else v[0] <= v[1]) for k, v in gates.items()} +report = {"candidate": name, "sha256": hashlib.sha256(ck.read_bytes()).hexdigest(), "snow_real_routing": route, + "gates": {k: {"value": v[0], "threshold": v[1], "pass": passed[k]} for k, v in gates.items()}, + "n_pass": int(sum(passed.values())), "pass": bool(all(passed.values())), "best_val_macro_f1": best_f1, + "noise_recall": row("Noise input")["noise"]} +Path("outputs/%s_gate.json" % name).write_text(json.dumps(report, indent=2)) +print(json.dumps(report)) +PYEOF + $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']))" +} + +best_name=""; best_key="" +for cand in $CANDIDATES; do + echo "[chain] waiting for $cand" + if ! wait_for $cand; then continue; fi + sleep 20 + echo "[chain] $cand done: $(sha256sum outputs/$cand/graph_encoder_best.pt | cut -c1-16); dashboard + gate" + read -r pass npass f1 <<< "$(gate_for $cand)" + echo "[chain] $cand gate pass=$pass n_pass=$npass best_val_f1=$f1 (outputs/${cand}_gate.json)" + key=$(printf "%d.%d.%s" "$pass" "$npass" "$f1") + if [ -z "$best_name" ] || [ "$(printf '%s\n%s\n' "$best_key" "$key" | sort -t. -k1,1n -k2,2n -k3,3n | tail -1)" = "$key" ]; then + best_name=$cand; best_key=$key + fi +done +if [ -z "$best_name" ]; then echo "[chain] no candidate finished; aborting"; exit 1; fi +if [ "${best_key%%.*}" != "1" ]; then + echo "[chain] GATE FAIL for every candidate (best=$best_name key=$best_key); NOT launching v8"; exit 2 +fi +export PHASE1_CKPT=outputs/$best_name/graph_encoder_best.pt +echo "[chain] GATE PASS -> $best_name ($PHASE1_CKPT); launching v8a (GPU0) and v8b (GPU1)" +nohup bash run_uformer_v8a.sh > outputs/phase2_v7/uformer_v8a_supervisor.log 2>&1 < /dev/null & +sleep 120 +nohup bash run_uformer_v8b.sh > outputs/phase2_v7/uformer_v8b_supervisor.log 2>&1 < /dev/null & +echo "[chain] both supervisors launched" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/run_v8_postrun.sh b/dataset/phase1_noise_20260906/trial_code_staging/run_v8_postrun.sh new file mode 100644 index 0000000000000000000000000000000000000000..d5586ecb6827e591146e678472440fcdad569388 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/run_v8_postrun.sh @@ -0,0 +1,35 @@ +#!/bin/bash +# After both v8 supervisors finish: per-run external eval, global-knob probe +# (how much of the oracle exposure gain the head captured), scene008 tone +# probe, qualitative grids; then the Phase-2 dose sweep for the head. +set -u +cd /home/admin_mcn/scdc_ban +PY=/home/admin_mcn/anaconda3/bin/python +done_run() { grep -q "run complete" "outputs/phase2_v7/uformer_$1_supervisor.log" 2>/dev/null; } +dead_run() { grep -qE "not restarting|exhausted|no recovery" "outputs/phase2_v7/uformer_$1_supervisor.log" 2>/dev/null; } +A_TAG=${A_TAG:-v8a}; B_TAG=${B_TAG:-v8b} +echo "[postrun] waiting for $A_TAG and $B_TAG supervisors" +while true; do + a_ok=0; b_ok=0 + if done_run $A_TAG || dead_run $A_TAG; then a_ok=1; fi + if done_run $B_TAG || dead_run $B_TAG; then b_ok=1; fi + if [ "$a_ok" = 1 ] && [ "$b_ok" = 1 ]; then break; fi + sleep 300 +done +sleep 60 +pkill -f "[t]rain_phase2_unified_v7.py.*uformer_v8" 2>/dev/null; sleep 20 +for pair in "$A_TAG 0" "$B_TAG 1"; do + set -- $pair; TAG=$1; GPU=$2; R=outputs/phase2_v7/uformer_${TAG}_8k_seed42 + if [ ! -f "$R/best.pt" ]; then echo "[postrun] $TAG has no best.pt; skipping"; continue; fi + ( + CUDA_VISIBLE_DEVICES=$GPU $PY eval_v7_external.py --run-dir $R --output outputs/v7_${TAG}_external_v1.json + CUDA_VISIBLE_DEVICES=$GPU $PY eval_v7_external.py --run-dir $R --output outputs/v7_${TAG}_external_pdose0.json --photometric-dose 0 + CUDA_VISIBLE_DEVICES=$GPU $PY probe_global_knob.py --run-dir $R --output outputs/global_knob_probe_${TAG}.json + CUDA_VISIBLE_DEVICES=$GPU $PY probe_scene008_tone.py --run-dir $R --output outputs/v7_${TAG}_scene008_tone.json --skip-val-baseline + CUDA_VISIBLE_DEVICES=$GPU $PY visualize_v7_uformer.py --run-dir $R --per-domain 3 + CUDA_VISIBLE_DEVICES=$GPU $PY visualize_scene008.py --run-dir $R --output $R/vis/scene008.png --count 3 + echo "[postrun] $TAG done" + ) > outputs/phase2_v7/${TAG}_postrun.log 2>&1 & +done +wait +echo "POSTRUN-ALL-DONE" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/supervise_uformer16k.sh b/dataset/phase1_noise_20260906/trial_code_staging/supervise_uformer16k.sh new file mode 100644 index 0000000000000000000000000000000000000000..e73d0f286f3ccd72f6278d544df12c0c51b4f058 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/supervise_uformer16k.sh @@ -0,0 +1,70 @@ +#!/bin/bash +# Auto-resume supervisor for outputs/phase2_v7/uformer16k_seed42. +# Relaunches training from overflow_recovery.pt after each designed +# RecoverableAmpOverflow exit; stops on completion (step 16000 evaluated), +# on any non-overflow failure, or after MAX_RESTARTS. +set -u +cd /home/admin_mcn/scdc_ban +RUN_DIR=outputs/phase2_v7/uformer16k_seed42 +LOG=outputs/phase2_v7/uformer16k_train.log +PY=/home/admin_mcn/anaconda3/bin/python +MAX_RESTARTS=20 +restarts=0 + +is_running() { pgrep -f "[t]rain_phase2_unified_v7.py.*uformer16k_seed42" >/dev/null; } +is_complete() { grep -q '"event": "evaluation".*"step": 16000\|"step": 16000.*"event": "evaluation"' "$RUN_DIR/metrics.jsonl" 2>/dev/null; } + +launch() { + nohup "$PY" -m torch.distributed.run --standalone --nproc_per_node=2 \ + train_phase2_unified_v7.py \ + --ddp --ddp-find-unused --backbone uformer --timesteps 2 \ + --resume "$RUN_DIR/overflow_recovery.pt" \ + --phase1-checkpoint outputs/phase1_ll_v3/graph_encoder_best.pt \ + --phase1-sha256 a05d4bd1fbc2e942607e96f813b5e3ec1c8f2dae25132d328ebf4a12c461733f \ + --manifest outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json \ + --output-dir "$RUN_DIR" \ + --fine-chroma-weight 0.5 --fine-vgg-weight 0.1 \ + --kappa 0.11607981286942959 \ + --expert-kappa-values 0.09780,0.03836,0.13436,0.41464,0.11608 \ + --eta-end 0.99 --min-noise 0.2 --power 0.3 \ + --cond-dim 256 --expert-rank 16 --gate-hidden-dim 128 --gate-max-correction 1.0 \ + --batch-size 8 --grad-accum 1 --eval-batch-size 8 --workers 4 \ + --learning-rate 5e-5 --max-steps 16000 --run-until-step 16000 \ + --eval-steps 0,1000,2000,3000,4000,6000,8000,10000,12000,14000,16000 \ + --milestone-steps 4000,8000,12000 \ + --seed 42 --eval-seed 20260830 >> "$LOG" 2>&1 & +} + +overflow_count() { grep -c "RecoverableAmpOverflow" "$LOG" 2>/dev/null || echo 0; } + +seen_overflows=$(overflow_count) +echo "[supervisor] start; overflows so far: $seen_overflows" + +while true; do + if is_complete; then + echo "[supervisor] run complete (eval @16000 present); exiting" + break + fi + if ! is_running; then + current=$(overflow_count) + if [ "$current" -gt "$seen_overflows" ] || [ "$restarts" -eq 0 ]; then + if [ "$restarts" -ge "$MAX_RESTARTS" ]; then + echo "[supervisor] restart budget exhausted ($MAX_RESTARTS); exiting" + break + fi + if [ ! -f "$RUN_DIR/overflow_recovery.pt" ]; then + echo "[supervisor] no recovery checkpoint; refusing to relaunch" + break + fi + seen_overflows=$current + restarts=$((restarts + 1)) + echo "[supervisor] relaunch #$restarts from overflow_recovery.pt (overflows=$current)" + launch + sleep 90 + else + echo "[supervisor] process died WITHOUT a new overflow; not restarting" + break + fi + fi + sleep 45 +done diff --git a/dataset/phase1_noise_20260906/trial_code_staging/sweep_v7_dose.py b/dataset/phase1_noise_20260906/trial_code_staging/sweep_v7_dose.py new file mode 100644 index 0000000000000000000000000000000000000000..741394158b134603c50babcb5339b522cf14179f --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/sweep_v7_dose.py @@ -0,0 +1,99 @@ +#!/usr/bin/env python3 +"""Dose sweep for a DGF-trained v7 checkpoint. + +For each dose w: full validation (per-domain PSNR/SSIM) with the coarse-step +guidance x0 = x0(null) + w (x0(c) - x0(null)), plus an IDENTITY test where the +clean image is fed as input (PSNR(f(x), x) per domain — the "do nothing" +score). Writes one JSON with everything. +""" + +from __future__ import annotations + +import argparse +import functools +import json +from pathlib import Path +from typing import Any, Dict + +import torch +from torch.utils.data import DataLoader, Dataset + +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_unified_v7 as v7 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest +from visualize_v7_uformer import _load_run_args + + +class CleanAsInput(Dataset): + def __init__(self, base: Dataset) -> None: + self.base = base + + def __len__(self) -> int: + return len(self.base) + + def __getitem__(self, index: int): + item = dict(self.base[index]) + item["degraded"] = item["clean"] + return item + + +def _summary(result: Dict[str, Any]) -> Dict[str, float]: + restored = result.get("restored", result) + out = { + "macro_psnr": float(restored["macro_psnr"]), + "macro_ssim": float(restored["macro_ssim"]), + } + for domain, values in restored["per_domain"].items(): + out[domain] = float(values["psnr"]) + return out + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--doses", default="0,0.25,0.5,0.75,1,1.25") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--skip-identity", action="store_true") + args = parser.parse_args() + + run_args = _load_run_args(args.run_dir) + device = torch.device("cuda") + checkpoint = v4._torch_load(args.run_dir / "best.pt", map_location="cpu") + model = v7._build_v7_restorer(run_args, device) + model.load_state_dict(checkpoint["ema_state_dict"]["shadow"], strict=True) + model.eval() + phase1, _ = v4.build_frozen_phase1( + run_args.phase1_checkpoint, run_args.phase1_sha256, device + ) + splits = load_train_val_manifest(run_args.manifest) + base = Phase2PairDataset( + splits.val, crop_size=run_args.crop_size, training=False, upscale_small=True + ) + loader_kwargs = dict(batch_size=8, shuffle=False, num_workers=4, pin_memory=True) + val_loader = DataLoader(base, **loader_kwargs) + identity_loader = DataLoader(CleanAsInput(base), **loader_kwargs) + + doses = [float(v) for v in args.doses.split(",")] + report: Dict[str, Any] = {"run_dir": str(args.run_dir), "step": int(checkpoint["step"])} + with v7._installed_v7_backend(run_args): + for dose in doses: + v4.sample_restoration = functools.partial( + v7.sample_unified_restoration, dose=dose + ) + with torch.no_grad(): + val = _summary(v4.evaluate(model, phase1, val_loader, device, int(run_args.eval_seed))) + entry = {"val": val} + if not args.skip_identity: + entry["identity"] = _summary( + v4.evaluate(model, phase1, identity_loader, device, int(run_args.eval_seed)) + ) + report["dose_%g" % dose] = entry + print("dose %g val %s" % (dose, json.dumps(val)), flush=True) + if "identity" in entry: + print(" identity %s" % json.dumps(entry["identity"]), flush=True) + args.output.write_text(json.dumps(report, indent=2, sort_keys=True)) + print("WROTE", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/test_train_graph_encoder_v2.py b/dataset/phase1_noise_20260906/trial_code_staging/test_train_graph_encoder_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..d97a83d38898b616f066d0acbbcc712c806dcd68 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/test_train_graph_encoder_v2.py @@ -0,0 +1,908 @@ +from pathlib import Path +from types import SimpleNamespace + +import math + +import pytest +import torch +import torch.nn as nn + +import train_graph_encoder_v2 as v2 +from src.models.graph_encoder.representation import aggregate_graph_condition + + +def _record(index, degradation="haze", group=None, dataset="RESIDE"): + source = str(index) + return v2.PairRecord( + degraded=Path("/deg") / (source + ".png"), + clean=Path("/clean") / (source + ".png"), + degradation=degradation, + dataset=dataset, + source_id=source, + split_group=group or source, + ) + + +def _png(path, value=0): + path.parent.mkdir(parents=True, exist_ok=True) + v2.Image.new("RGB", (12, 8), color=(value, value, value)).save(path) + + +def test_real_branch_order_preserves_deployed_positional_semantics(): + assert v2.BRANCH_ORDER == ("rain", "noise", "haze", "lowlight") + assert v2.BRANCH_TO_INDEX == { + "rain": 0, + "noise": 1, + "haze": 2, + "lowlight": 3, + } + + +def test_reside_first_5000_has_source_isolated_first_100_validation(): + records = [] + records.extend(_record(i, group="val-a") for i in range(95)) + records.extend(_record(i + 95, group="val-leak") for i in range(5)) + records.extend(_record(i + 100, group="val-leak") for i in range(5)) + records.extend(_record(i + 105) for i in range(4895)) + + train, val = v2.split_reside_records(records, limit=5000, val_count=100) + + assert len(val) == 100 + assert len(train) == 4895 + assert {r.split_group for r in train}.isdisjoint( + {r.split_group for r in val} + ) + + +def test_sidd_split_is_scene_disjoint_with_audited_live_counts(): + scene_counts = { + "001": 28, "002": 15, "003": 15, "004": 15, "005": 19, + "006": 19, "007": 20, "008": 20, "009": 6, "010": 3, + } + records = [] + index = 0 + for scene, count in scene_counts.items(): + for _ in range(count): + records.append(_record(index, "noise", scene, "SIDD")) + index += 1 + + train, val, locked = v2.split_sidd_records(records) + + assert (len(train), len(val), len(locked)) == (121, 19, 20) + groups = [{r.split_group for r in split} for split in (train, val, locked)] + assert groups[0].isdisjoint(groups[1]) + assert groups[0].isdisjoint(groups[2]) + assert groups[1].isdisjoint(groups[2]) + assert groups[1] == {"006"} + assert groups[2] == {"008"} + + +def test_sidd_scene_number_is_second_folder_token(): + assert v2.sidd_scene_number("0192_009_IP_00100_00200_3200_N") == "009" + with pytest.raises(ValueError, match="SIDD source directory"): + v2.sidd_scene_number("malformed") + + +def test_live_layout_discovery_and_source_leakage_guard(tmp_path): + lol = tmp_path / "lol" + _png(lol / "Train/Input/00001.png", 10) + _png(lol / "Train/GT/00001.png", 20) + assert len(v2.discover_lol_records(lol, "Train")) == 1 + + reside = tmp_path / "reside" + _png(reside / "clear/0001.jpg", 20) + _png(reside / "hazy/0001_0.8_0.1.jpg", 10) + assert v2.discover_reside_records(reside)[0].split_group == "0001" + + sidd = tmp_path / "sidd" + for scene in range(1, 11): + source = sidd / ("%04d_%03d_IP_00100_00200_3200_N" % (scene, scene)) + _png(source / "NOISY_SRGB_010.PNG", 10) + _png(source / "GT_SRGB_010.PNG", 20) + sidd_records = v2.discover_sidd_records(sidd) + parts = v2.split_sidd_records(sidd_records) + assert [len(part) for part in parts] == [8, 1, 1] + + shared = _record(0, group="same") + splits = v2.DataSplits((shared,), (shared,), (), 0) + with pytest.raises(ValueError, match="source leakage"): + v2.assert_split_isolation(splits) + + shared_clean = tmp_path / "shared-clean.png" + _png(shared_clean, 77) + train = v2.PairRecord( + shared_clean, shared_clean, "rain", "Rain13K", "a", "rain-a" + ) + val = v2.PairRecord( + shared_clean, shared_clean, "lowlight", "LOLv2", "b", "lol-b" + ) + with pytest.raises(ValueError, match="clean-content leakage"): + v2.assert_split_isolation(v2.DataSplits((train,), (val,), (), 0)) + + +def test_rain_adapter_uses_quarantine_and_only_test100_test1200(monkeypatch, tmp_path): + pairs = [] + for index in range(3): + degraded = tmp_path / ("d%d.png" % index) + clean = tmp_path / ("c%d.png" % index) + _png(degraded, index) + _png(clean, index + 1) + pairs.append((degraded, clean)) + captured = {} + + def fake_loader(root, **kwargs): + captured.update(kwargs) + return SimpleNamespace( + train_pairs=(pairs[0],), + official_test_pairs={"Test100": (pairs[1],), "Test1200": (pairs[2],)}, + quarantined_train_pair_count=1155, + ) + + monkeypatch.setattr(v2, "load_rain13k_resized", fake_loader) + train, val, locked, count = v2.build_rain_records(tmp_path, tmp_path / "q.json") + assert (len(train), len(val), len(locked), count) == (1, 1, 1, 1155) + assert captured["max_train_pairs"] == 0 + assert captured["quarantine_manifest"] == tmp_path / "q.json" + + +def test_build_data_splits_composes_domains_and_checks_counts(monkeypatch, tmp_path): + rain = _record(1, "rain", "r1", "Rain13K") + low_train = _record(2, "lowlight", "l1", "LOLv2") + low_val = _record(3, "lowlight", "l2", "LOLv2") + haze_train = _record(4, "haze", "h1", "RESIDE") + haze_val = _record(5, "haze", "h2", "RESIDE") + noise_train = _record(6, "noise", "n1", "SIDD") + noise_val = _record(7, "noise", "n2", "SIDD") + noise_test = _record(8, "noise", "n3", "SIDD") + monkeypatch.setattr(v2, "build_rain_records", lambda *args: ([rain], [rain], [rain], 1)) + monkeypatch.setattr( + v2, "discover_lol_records", + lambda root, split: [low_train] if split == "Train" else [low_val], + ) + monkeypatch.setattr(v2, "discover_reside_records", lambda root: [haze_train, haze_val]) + monkeypatch.setattr(v2, "split_reside_records", lambda *args: ([haze_train], [haze_val])) + monkeypatch.setattr(v2, "discover_sidd_records", lambda root: [noise_train, noise_val, noise_test]) + monkeypatch.setattr( + v2, "split_sidd_records", lambda records: ([noise_train], [noise_val], [noise_test]) + ) + monkeypatch.setattr(v2, "assert_split_isolation", lambda splits: None) + args = v2.build_parser().parse_args( + ["--data-root", str(tmp_path), "--allow-count-mismatch"] + ) + splits = v2.build_data_splits(args) + assert (len(splits.train), len(splits.val), len(splits.locked_test)) == (4, 4, 2) + + +def test_sidd_cache_is_main_process_only_and_calibration_is_persisted(tmp_path): + records = [] + for index, degradation in enumerate(v2.BRANCH_ORDER): + degraded = tmp_path / degradation / "degraded.png" + clean = tmp_path / degradation / "clean.png" + _png(degraded, 40 + index * 10) + _png(clean, 10) + records.append( + v2.PairRecord( + degraded, clean, degradation, + "SIDD" if degradation == "noise" else degradation, + str(index), str(index), + ) + ) + cache = tmp_path / "cache" + calibration = { + name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + for name in v2.BRANCH_ORDER + } + dataset = v2.PairDataset(records, 8, calibration, cache) + dataset.prepare_cache() + assert len(list(cache.glob("*.png"))) == 2 + sample = dataset[1] + assert sample["degraded"].shape == (3, 8, 8) + assert 0 <= sample["severity"] <= 1 + + output = tmp_path / "calibration.json" + fitted = v2.fit_training_calibration(records, 8, output, cache) + first_fingerprint = v2.json.loads(output.read_text(encoding="utf-8"))["fingerprint"] + assert set(fitted) == set(v2.BRANCH_ORDER) + assert all(values["pixel_q95"] > 0 for values in fitted.values()) + assert v2.fit_training_calibration(records, 8, output, cache) == fitted + + sidd_record = records[1] + old_paths = dataset._cache_paths(sidd_record) + old_mtime = sidd_record.degraded.stat().st_mtime_ns + _png(sidd_record.degraded, 222) + v2.os.utime( + sidd_record.degraded, + ns=(old_mtime + 1_000_000_000, old_mtime + 1_000_000_000), + ) + new_paths = dataset._cache_paths(sidd_record) + assert new_paths != old_paths + dataset.prepare_cache() + assert all(path.is_file() for path in new_paths) + v2.fit_training_calibration(records, 8, output, cache) + second_fingerprint = v2.json.loads(output.read_text(encoding="utf-8"))["fingerprint"] + assert second_fingerprint != first_fingerprint + + +def test_balanced_batch_sampler_is_exact_and_seeded_with_replacement(): + labels = [0, 0, 0, 1, 2, 3] + sampler_a = v2.BalancedBatchSampler(labels, batch_size=8, steps=3, seed=17) + sampler_b = v2.BalancedBatchSampler(labels, batch_size=8, steps=3, seed=17) + + batches_a = list(sampler_a) + assert batches_a == list(sampler_b) + assert len(batches_a) == 3 + for batch in batches_a: + assert [labels[i] for i in batch].count(0) == 2 + assert [labels[i] for i in batch].count(1) == 2 + assert [labels[i] for i in batch].count(2) == 2 + assert [labels[i] for i in batch].count(3) == 2 + with pytest.raises(ValueError, match="divisible"): + v2.BalancedBatchSampler(labels, batch_size=6, steps=1, seed=17) + + +def test_severity_proxy_is_deterministic_and_bounded(): + clean = torch.zeros(3, 4, 4) + degraded = torch.full((3, 4, 4), 0.25) + first = v2.residual_mae_severity(degraded, clean, 0.1, 0.4) + second = v2.residual_mae_severity(degraded, clean, 0.1, 0.4) + assert first.item() == pytest.approx(0.5) + assert torch.equal(first, second) + with pytest.raises(ValueError, match="p95"): + v2.residual_mae_severity(degraded, clean, 0.4, 0.4) + + +def test_spatial_supervision_rewards_selected_branch_and_suppresses_inactive(): + clean = torch.zeros(2, 3, 8, 8) + degraded = torch.ones(2, 3, 8, 8) + labels = torch.tensor([0, 2]) + q95 = torch.ones(4) + good = torch.zeros(2, 4, 2, 2) + good[0, 0] = 1 + good[1, 2] = 1 + bad = 1 - good + + good_loss, good_metrics = v2.spatial_supervision_loss( + good, degraded, clean, labels, q95 + ) + bad_loss, _ = v2.spatial_supervision_loss( + bad, degraded, clean, labels, q95 + ) + + assert good_loss < bad_loss + assert good_metrics["spatial_selected_mae"] == pytest.approx(0.0) + assert good_metrics["spatial_inactive_activation"] == pytest.approx(0.0) + + +def test_clean_forward_keeps_bn_statistics_frozen_but_allows_gradients(): + class TinyGraph(nn.Module): + def __init__(self): + super().__init__() + self.bn = nn.BatchNorm2d(3) + + def forward_student(self, image): + return self.bn(image) + + model = TinyGraph().train() + before = model.bn.running_mean.clone() + clean = torch.randn(2, 3, 4, 4, requires_grad=True) + + result = v2.forward_clean_bn_safe(model, clean) + result.sum().backward() + + assert torch.equal(model.bn.running_mean, before) + assert clean.grad is not None + assert model.training and model.bn.training + + +def test_free_tokens_are_scaled_by_absolute_posterior_mass(): + class ZeroBranch: + def get_branch_embedding(self, severity): + return torch.zeros(severity.shape[0], 1) + + tokens = torch.tensor([[[0.0], [10.0], [20.0]]]) + routing = torch.tensor([[1.0, 0.0, 0.0]]) + result = aggregate_graph_condition( + tokens, routing, torch.zeros(1, 1), [ZeroBranch()] + ) + assert torch.equal(result, torch.zeros_like(result)) + + +def test_semantic_token_affects_condition_only_when_its_route_is_active(): + class ZeroBranch: + def get_branch_embedding(self, severity): + return torch.zeros(severity.shape[0], 1) + + base = torch.tensor([[[1.0], [0.0], [0.0]]]) + changed = torch.tensor([[[3.0], [0.0], [0.0]]]) + active = torch.tensor([[1.0, 0.0, 0.0]]) + inactive = torch.tensor([[0.0, 0.5, 0.5]]) + args = (torch.zeros(1, 1), [ZeroBranch()]) + + assert not torch.equal( + aggregate_graph_condition(base, active, *args), + aggregate_graph_condition(changed, active, *args), + ) + assert torch.equal( + aggregate_graph_condition(base, inactive, *args), + aggregate_graph_condition(changed, inactive, *args), + ) + + +@pytest.mark.parametrize("dtype", [torch.float16, torch.bfloat16]) +def test_aggregation_preserves_amp_dtype(dtype): + class ZeroBranch: + def get_branch_embedding(self, severity): + return severity.new_zeros((severity.shape[0], 2)) + + result = aggregate_graph_condition( + torch.ones(1, 3, 2, dtype=dtype), + torch.tensor([[1.0, 0.0, 0.0]], dtype=dtype), + torch.zeros(1, 1, dtype=dtype), + [ZeroBranch()], + ) + assert result.dtype == dtype + + +def test_validation_metrics_include_per_class_and_safe_constant_correlation(): + metrics = v2.compute_validation_metrics( + labels=[0, 0, 1, 1], + predictions=[0, 4, 1, 5], + severity_targets=[0.5, 0.5, 0.2, 0.8], + severity_predictions=[0.5, 0.5, 0.3, 0.7], + unknown_routing=[0.1, 0.2, 0.3, 0.4], + entropies=[0.2, 0.2, 0.4, 0.4], + losses=[1.0, 1.0, 2.0, 2.0], + spatial_mae=[0.1, 0.1, 0.2, 0.2], + inactive_activation=[0.0, 0.0, 0.1, 0.1], + ) + assert metrics["accuracy"] == 0.5 + assert metrics["macro_f1"] < 1.0 + assert metrics["balanced_accuracy"] == 0.5 + assert len(metrics["confusion_matrix"]) == 4 + assert all(len(row) == 6 for row in metrics["confusion_matrix"]) + assert metrics["per_class"]["rain"]["severity_spearman"] == 0.0 + assert "spatial_selected_mae" in metrics["per_class"]["noise"] + + +def test_checkpoint_keeps_phase2_schema_and_trainer_state_separate(tmp_path): + model = nn.Linear(2, 2) + head = nn.Linear(2, 4) + payload = v2.make_checkpoint( + model=model, + aux_classifier=head, + optimizer=None, + scheduler=None, + scaler=None, + epoch=0, + best_score=0.2, + config={"branch_order": list(v2.BRANCH_ORDER)}, + provenance={"counts": {"train": 1}}, + history=[{"epoch": 0}], + severity_calibration={"rain": {"p05": 0.1, "p95": 0.5}}, + ) + assert payload["model_state_dict"].keys() == model.state_dict().keys() + assert "global_type_head" in payload["trainer_state"] + assert payload["branch_order"] == list(v2.BRANCH_ORDER) + + +def test_checkpoint_loader_rejects_legacy_aggregation_or_branch_semantics(tmp_path): + model = nn.Linear(2, 2) + checkpoint_path = tmp_path / "legacy.pt" + torch.save( + { + "model_state_dict": model.state_dict(), + "aggregation_version": 1, + "branch_order": ["blur", "noise", "jpeg", "lowlight"], + }, + checkpoint_path, + ) + with pytest.raises(ValueError, match="aggregation_version"): + v2._load_encoder_checkpoint(checkpoint_path, model, None, torch.device("cpu")) + + +def test_cli_requires_explicit_final_test_and_has_output_path(): + args = v2.build_parser().parse_args([]) + assert args.output_dir + assert args.run_final_test is False + + +def test_checkpoint_selection_is_lexicographic_by_macro_f1(): + better_f1 = {"macro_f1": 0.81, "severity_mae": 0.9, "spatial_selected_mae": 0.9} + better_aux = {"macro_f1": 0.80, "severity_mae": 0.0, "spatial_selected_mae": 0.0} + assert v2.selection_key(better_f1) > v2.selection_key(better_aux) + + +def test_supervised_objective_is_finite_and_backpropagates_all_core_losses(): + def graph(batch=2, dim=4): + return SimpleNamespace( + routing_probs=torch.softmax(torch.randn(batch, 6, requires_grad=True), -1), + severity_coords=torch.sigmoid(torch.randn(batch, 4, requires_grad=True)), + global_condition=torch.randn(batch, dim, requires_grad=True), + content_latent=torch.randn(batch, dim, 2, 2, requires_grad=True), + spatial_maps=torch.sigmoid(torch.randn(batch, 4, 2, 2, requires_grad=True)), + unknown_residual=torch.randn(batch, dim, requires_grad=True), + ) + + objective = v2.Phase1GraphObjective(node_dim=4) + degraded = torch.ones(2, 3, 8, 8) + clean = torch.zeros_like(degraded) + labels = torch.tensor([0, 2]) + result = objective( + graph(), graph(), degraded, clean, labels, + torch.tensor([0.3, 0.7]), torch.ones(4), torch.zeros(1, 4), + ) + result["total"].backward() + + assert torch.isfinite(result["total"]) + for key in ("route", "global_type", "severity", "root", "spatial"): + assert key in result and torch.isfinite(result[key]) + assert objective.global_type_head.weight.grad is not None + + +def test_real_encoder_balanced_batch_trains_semantic_tokens_and_strictly_reloads(): + config = v2.GraphConfig( + latent_channels=16, + node_dim=32, + spatial_map_size=(4, 4), + ) + model = v2.BlindDegradationGraphEncoder(config).train() + objective = v2.Phase1GraphObjective(node_dim=32) + clean = torch.rand(4, 3, 16, 16) + degraded = (clean + 0.1 * torch.rand_like(clean)).clamp(0, 1) + labels = torch.arange(4) + + graph_degraded = model.forward_student(degraded) + graph_clean = v2.forward_clean_bn_safe(model, clean) + losses = objective( + graph_degraded, graph_clean, degraded, clean, labels, + torch.linspace(0.2, 0.8, 4), torch.ones(4), model.clean_root(), + ) + losses["total"].backward() + + token_grad = model.token_generator.semantic_tokens.grad + assert token_grad is not None + assert torch.isfinite(token_grad).all() + assert (token_grad.norm(dim=1) > 0).all() + assert model.token_generator.feat_proj.weight.grad is not None + assert model.clean_root.embedding.grad is None + assert torch.equal( + model.clean_root.embedding, + torch.zeros_like(model.clean_root.embedding), + ) + clone = v2.BlindDegradationGraphEncoder(config) + clone.load_state_dict(model.state_dict(), strict=True) + + +def test_real_evaluate_train_checkpoint_and_provenance_smoke(tmp_path): + config = v2.GraphConfig( + latent_channels=16, + node_dim=32, + spatial_map_size=(4, 4), + ) + model = v2.BlindDegradationGraphEncoder(config) + objective = v2.Phase1GraphObjective(32) + batch = { + "degraded": torch.rand(4, 3, 16, 16), + "clean": torch.rand(4, 3, 16, 16), + "label": torch.arange(4), + "severity": torch.linspace(0.1, 0.9, 4), + } + metrics = v2.evaluate(model, [batch], torch.device("cpu"), torch.ones(4)) + assert metrics["sample_count"] == 4 + + optimizer = torch.optim.AdamW( + list(model.parameters()) + list(objective.parameters()), lr=1e-4 + ) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=1) + scaler = torch.cuda.amp.GradScaler(enabled=False) + trained = v2.train_one_epoch( + model, objective, [batch], optimizer, scaler, torch.device("cpu"), + torch.ones(4), False, 1.0, + ) + assert torch.isfinite(torch.tensor(trained["total"])) + + quarantine = tmp_path / "quarantine.json" + quarantine.write_text("{}", encoding="utf-8") + args = v2.build_parser().parse_args( + ["--quarantine-manifest", str(quarantine), "--workers", "0"] + ) + records = tuple(_record(i, name, dataset=name) for i, name in enumerate(v2.BRANCH_ORDER)) + splits = v2.DataSplits(records, records, records, 3) + provenance = v2.make_provenance(args, splits) + run_config = v2._configuration(args, config, v2.LossWeights()) + payload = v2.make_checkpoint( + model, objective.global_type_head, optimizer, scheduler, scaler, + 1, 0.5, run_config, provenance, [{"epoch": 0}], + {name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} for name in v2.BRANCH_ORDER}, + ) + checkpoint = tmp_path / "checkpoint.pt" + v2._atomic_torch_save(checkpoint, payload) + loaded = v2._load_encoder_checkpoint( + checkpoint, model, objective, torch.device("cpu") + ) + assert loaded["epoch"] == 1 + v2._atomic_write_json(tmp_path / "provenance.json", provenance) + assert (tmp_path / "provenance.json").is_file() + + +def test_build_loaders_yields_exactly_balanced_batch(tmp_path): + records = [] + calibration = {} + for index, name in enumerate(v2.BRANCH_ORDER): + degraded = tmp_path / name / "d.png" + clean = tmp_path / name / "c.png" + _png(degraded, 30 + index) + _png(clean, 10) + records.append(v2.PairRecord(degraded, clean, name, name, str(index), str(index))) + calibration[name] = {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + splits = v2.DataSplits(tuple(records), tuple(records), (), 0) + args = v2.build_parser().parse_args( + [ + "--workers", "0", "--batch-size", "4", "--eval-batch-size", "4", + "--steps-per-epoch", "1", "--image-size", "8", + ] + ) + train_loader, val_loader, _, _ = v2.build_loaders( + args, splits, calibration, torch.device("cpu"), tmp_path / "cache" + ) + assert sorted(next(iter(train_loader))["label"].tolist()) == [0, 1, 2, 3] + assert len(next(iter(val_loader))["label"]) == 4 + + +def test_eval_only_main_writes_config_provenance_and_metrics(monkeypatch, tmp_path): + checkpoint = tmp_path / "model.pt" + model = v2.BlindDegradationGraphEncoder(v2.GraphConfig()) + calibration = { + name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + for name in v2.BRANCH_ORDER + } + torch.save( + { + "model_state_dict": model.state_dict(), + "aggregation_version": v2.AGGREGATION_VERSION, + "branch_order": list(v2.BRANCH_ORDER), + "severity_calibration": calibration, + }, + checkpoint, + ) + quarantine = tmp_path / "quarantine.json" + quarantine.write_text("{}", encoding="utf-8") + monkeypatch.setattr(v2, "build_data_splits", lambda args: v2.DataSplits((), (), (), 0)) + monkeypatch.setattr(v2, "_make_eval_loader", lambda *args, **kwargs: []) + metrics = { + "accuracy": 0.0, "macro_f1": 0.0, "balanced_accuracy": 0.0, + "severity_mae": 0.0, "spatial_selected_mae": 0.0, + } + monkeypatch.setattr(v2, "evaluate", lambda *args, **kwargs: metrics) + output = tmp_path / "output" + + assert v2.main( + [ + "--eval-only", "--checkpoint", str(checkpoint), + "--output-dir", str(output), "--device", "cpu", "--workers", "0", + "--quarantine-manifest", str(quarantine), "--allow-count-mismatch", + ] + ) == 0 + assert (output / "config.json").is_file() + assert (output / "provenance.json").is_file() + assert (output / "eval_val_metrics.json").is_file() + + +# --------------------------------------------------------------------------- +# P1-LL (ll_v3): global low-frequency branch, null/OOD routing, selection +# --------------------------------------------------------------------------- + +from src.models.graph_encoder.encoder import ( # noqa: E402 + LLGlobalBranch, + haar_ll, + photometric_stats, +) + + +def _small_ll_config(**overrides): + defaults = dict( + latent_channels=16, + node_dim=32, + num_semantic_branches=4, + num_free_nodes=2, + use_ll_global=True, + ll_global_dim=32, + ) + defaults.update(overrides) + return v2.GraphConfig(**defaults) + + +def test_haar_ll_and_photometric_stats_are_finite_and_shaped(): + image = torch.rand(3, 3, 64, 64) + ll = haar_ll(image) + assert ll.shape == (3, 3, 32, 32) + # LL of a constant image is the constant (energy-preserving /2 scaling + # doubles the mean per level by design of the orthonormal transform). + stats = photometric_stats(image) + assert stats.shape == (3, LLGlobalBranch.STATS_DIM) + assert torch.isfinite(stats).all() + + +def test_ll_branch_is_deterministic_and_sized(): + torch.manual_seed(0) + branch = LLGlobalBranch(output_dim=32) + branch.eval() + image = torch.rand(2, 3, 64, 64) + with torch.no_grad(): + first = branch(image) + second = branch(image) + assert first.shape == (2, 32) + assert torch.equal(first, second) + + +def test_ll_config_gates_state_dict_and_preserves_phase2_contract(): + legacy = v2.BlindDegradationGraphEncoder( + v2.GraphConfig(latent_channels=16, node_dim=32) + ) + assert not any("ll_" in name for name in legacy.state_dict()) + + model = v2.BlindDegradationGraphEncoder(_small_ll_config()) + names = model.state_dict().keys() + assert any(name.startswith("ll_branch.") for name in names) + assert any(name.startswith("ll_condition.") for name in names) + + graph = model.forward_student(torch.rand(2, 3, 64, 64)) + assert graph.routing_probs.shape == (2, 6) + assert graph.severity_coords.shape == (2, 4) + assert graph.spatial_maps.shape[:2] == (2, 4) + assert graph.node_tokens.shape == (2, 6, 32) + assert graph.global_condition.shape == (2, 32) + v2.assert_phase2_contract(model) + + +def test_ll_condition_is_zero_initialized_for_v2_aggregation_equivalence(): + model = v2.BlindDegradationGraphEncoder(_small_ll_config()) + assert int(torch.count_nonzero(model.ll_condition.weight)) == 0 + assert int(torch.count_nonzero(model.ll_condition.bias)) == 0 + + +@pytest.mark.parametrize("kind", v2.OOD_KINDS) +def test_synthesize_ood_is_deterministic_bounded_and_nontrivial(kind): + clean = torch.rand(2, 3, 64, 64) + first = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(7)) + second = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(7)) + other = v2.synthesize_ood(clean, kind, torch.Generator().manual_seed(8)) + assert torch.equal(first, second) + assert first.shape == clean.shape + assert float(first.min()) >= -1e-5 and float(first.max()) <= 1.0 + 1e-5 + assert not torch.equal(first, clean) + if kind == "snow": + assert not torch.equal(first, other) + + +def test_objective_with_ood_routes_clean_and_ood_into_free_slots(): + torch.manual_seed(0) + config = _small_ll_config() + model = v2.BlindDegradationGraphEncoder(config) + objective = v2.Phase1GraphObjective(node_dim=32) + degraded = torch.rand(4, 3, 64, 64) + clean = torch.rand(4, 3, 64, 64) + ood = v2.synthesize_ood(clean, "snow", torch.Generator().manual_seed(3)) + labels = torch.tensor([0, 1, 2, 3]) + severity = torch.rand(4) + pixel_q95 = torch.ones(4) + + graph_degraded = model.forward_student(degraded) + graph_clean = model.forward_student(clean) + graph_ood = model.forward_student(ood) + losses = objective( + graph_degraded, graph_clean, degraded, clean, labels, severity, + pixel_q95, model.clean_root(), graph_ood=graph_ood, + ) + for name in ("null_route", "ood_route", "unknown_margin", "total"): + assert torch.isfinite(losses[name]), name + assert float(losses["null_route"]) > 0.0 + assert float(losses["ood_route"]) > 0.0 + + losses["total"].backward() + routing_grads = [ + parameter.grad + for name, parameter in model.state_predictor.routing_net.named_parameters() + if parameter.grad is not None + ] + assert routing_grads and any( + float(grad.abs().sum()) > 0 for grad in routing_grads + ) + + +def test_objective_without_ood_matches_legacy_signature(): + torch.manual_seed(0) + config = v2.GraphConfig(latent_channels=16, node_dim=32) + model = v2.BlindDegradationGraphEncoder(config) + objective = v2.Phase1GraphObjective(node_dim=32) + degraded = torch.rand(2, 3, 64, 64) + clean = torch.rand(2, 3, 64, 64) + losses = objective( + model.forward_student(degraded), model.forward_student(clean), + degraded, clean, torch.tensor([0, 1]), torch.rand(2), torch.ones(4), + model.clean_root(), + ) + assert float(losses["ood_route"]) == 0.0 + assert float(losses["unknown_margin"]) == 0.0 + assert torch.isfinite(losses["total"]) + + +def test_selection_key_prefers_null_routing_after_f1_and_accepts_legacy(): + base = { + "macro_f1": 0.9, "severity_mae": 0.1, "spatial_selected_mae": 0.1, + "severity_spearman": 0.0, + } + with_null = dict(base, null_accuracy_clean=1.0, null_accuracy_ood=0.8) + without_null = dict(base, null_accuracy_clean=0.1, null_accuracy_ood=0.1) + higher_f1 = dict(without_null, macro_f1=0.95) + assert v2.selection_key(with_null) > v2.selection_key(without_null) + assert v2.selection_key(higher_f1) > v2.selection_key(with_null) + legacy = { + "macro_f1": 0.9, "severity_mae": 0.2, "spatial_selected_mae": 0.1, + } + assert v2.selection_key(legacy) < v2.selection_key(base) + + +def test_validation_metrics_accept_null_audit_fields(): + metrics = v2.compute_validation_metrics( + labels=[0, 1], predictions=[0, 1], severity_targets=[0.1, 0.2], + severity_predictions=[0.1, 0.2], unknown_routing=[0.0, 0.0], + entropies=[0.1, 0.1], losses=[0.5, 0.5], spatial_mae=[0.1, 0.1], + inactive_activation=[0.0, 0.0], + null_accuracy_clean=0.75, null_accuracy_ood=0.5, unknown_norm_gap=0.2, + ) + assert metrics["null_accuracy_clean"] == 0.75 + assert metrics["null_accuracy_ood"] == 0.5 + assert metrics["unknown_norm_gap"] == 0.2 + + +def test_build_frozen_phase1_reconstructs_ll_architecture_from_checkpoint(tmp_path): + import train_phase2_graph_resshift_v4 as p2 + + config = _small_ll_config() + model = v2.BlindDegradationGraphEncoder(config) + head = torch.nn.Linear(32, 4) + graph_config_dict = dict(vars(config)) + checkpoint = v2.make_checkpoint( + model, head, None, None, None, epoch=1, best_score=0.5, + config={"graph_config": graph_config_dict}, + provenance={}, history=[], + severity_calibration={ + name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + for name in v2.BRANCH_ORDER + }, + ) + path = tmp_path / "phase1_ll.pt" + torch.save(checkpoint, str(path)) + sha = v2.sha256_file(path) + frozen, metadata = p2.build_frozen_phase1(path, sha, torch.device("cpu")) + assert frozen.encoder.ll_branch is not None + assert metadata["sha256"] == sha + representation = frozen(torch.rand(1, 3, 64, 64)) + assert representation.routing_probs.shape == (1, 6) + + +def test_pearson_and_spearman_ignore_non_finite_pairs(): + # NaN pairs are dropped; the remaining finite pairs correlate normally. + two_left = v2._pearson([1.0, float("nan"), 3.0], [1.0, 2.0, 3.0]) + assert abs(two_left - 1.0) < 1e-9 + clean = v2._pearson([1.0, 2.0, 3.0, float("nan")], [1.0, 2.0, 3.0, 5.0]) + assert abs(clean - 1.0) < 1e-9 + # All pairs non-finite -> fewer than two survivors -> safe zero. + assert v2._pearson([float("nan")] * 3, [1.0, 2.0, 3.0]) == 0.0 + assert math.isfinite(v2._spearman([float("inf")] * 3, [1.0, 2.0, 3.0])) + + +def test_sanitize_json_replaces_non_finite_and_write_survives(tmp_path): + payload = { + "ok": 1.5, + "bad": float("nan"), + "nested": [float("inf"), {"x": float("-inf"), "y": 2}], + } + sanitized = v2._sanitize_json(payload) + assert sanitized["bad"] is None + assert sanitized["nested"][0] is None + assert sanitized["nested"][1]["x"] is None + assert sanitized["nested"][1]["y"] == 2 + target = tmp_path / "history.json" + v2._atomic_write_json(target, payload) + import json as _json + + assert _json.loads(target.read_text())["bad"] is None + + +def test_selection_key_treats_non_finite_metrics_as_worst(): + healthy = { + "macro_f1": 0.5, "severity_mae": 0.2, "spatial_selected_mae": 0.2, + } + poisoned = { + "macro_f1": float("nan"), "severity_mae": 0.2, + "spatial_selected_mae": 0.2, + } + assert v2.selection_key(healthy) > v2.selection_key(poisoned) + + +def test_ll_branch_stays_fp32_under_autocast(): + branch = LLGlobalBranch(output_dim=32) + image = torch.rand(1, 3, 64, 64) + if torch.cuda.is_available(): + branch = branch.cuda() + image = image.cuda() + with torch.cuda.amp.autocast(enabled=True): + output = branch(image) + else: + output = branch(image) + assert output.dtype == torch.float32 + + +def test_synthesize_noise_is_deterministic_and_bounded() -> None: + clean = torch.rand(3, 3, 32, 32) + g1 = torch.Generator().manual_seed(11) + g2 = torch.Generator().manual_seed(11) + a = v2.synthesize_noise(clean, g1) + b = v2.synthesize_noise(clean, g2) + assert torch.equal(a, b) + assert float(a.min()) >= 0.0 and float(a.max()) <= 1.0 + assert float((a - clean).abs().mean()) > 1e-3 + bank = [torch.randn(3, 32, 32) * 0.05] + c = v2.synthesize_noise(clean, torch.Generator().manual_seed(3), bank) + assert c.shape == clean.shape + + +def test_apply_noise_positives_relabels_only_selected_non_noise() -> None: + clean = torch.rand(6, 3, 16, 16) + degraded = clean.clone() + labels = torch.tensor([0, v2.NOISE_INDEX, 2, 3, 0, 2]) + severity = torch.zeros(6) + calibration = {"p05": 0.0, "p95": 0.2} + new_deg, new_lab, new_sev, mask = v2.apply_noise_positives( + degraded, clean, labels, severity, 1.0, torch.Generator().manual_seed(5), + calibration, + ) + assert bool(mask[1]) is False # real noise sample untouched + assert torch.equal(new_lab[mask], torch.full((int(mask.sum()),), v2.NOISE_INDEX)) + assert torch.equal(new_deg[~mask], degraded[~mask]) + assert torch.equal(labels, torch.tensor([0, v2.NOISE_INDEX, 2, 3, 0, 2])) # not mutated + assert float(new_sev[mask].min()) > 0.0 and float(new_sev[mask].max()) <= 1.0 + untouched_deg, untouched_lab, _, zero_mask = v2.apply_noise_positives( + degraded, clean, labels, severity, 0.0, torch.Generator().manual_seed(5), calibration + ) + assert untouched_deg is degraded and untouched_lab is labels and not bool(zero_mask.any()) + + +def test_texture_null_weights_rank_textured_images_higher() -> None: + flat = torch.full((1, 3, 32, 32), 0.5) + textured = torch.rand(1, 3, 32, 32) + weights = v2.texture_null_weights(torch.cat([flat, textured], dim=0)) + assert weights.shape == (2,) + assert float(weights[1]) > float(weights[0]) + assert float(weights.min()) >= 0.5 and float(weights.max()) <= 1.5 + + +def test_objective_accepts_texture_weighted_null() -> None: + objective = v2.Phase1GraphObjective(node_dim=256, texture_weighted_null=True) + assert objective.texture_weighted_null is True + + +def test_sharpen_ood_kind_adds_detail_deterministically() -> None: + clean = torch.rand(2, 3, 32, 32) + a = v2.synthesize_ood(clean, "sharpen", torch.Generator().manual_seed(2)) + b = v2.synthesize_ood(clean, "sharpen", torch.Generator().manual_seed(2)) + assert torch.equal(a, b) + assert a.shape == clean.shape and float(a.min()) >= 0.0 and float(a.max()) <= 1.0 + assert float((a - clean).abs().mean()) > 1e-3 + assert "sharpen" in v2.OOD_KINDS + + +def test_transplant_only_noise_uses_bank_and_gain() -> None: + clean = torch.rand(2, 3, 16, 16) * 0.5 + bank = [torch.ones(3, 16, 16) * 0.1] + out = v2.synthesize_noise( + clean, torch.Generator().manual_seed(9), bank, synthetic_prob=0.0, gain_max=2.5 + ) + residual = out - clean + # transplant of a constant residual: per-image constant offset in [0.05, 0.25] + per_image = residual.flatten(1).mean(dim=1) + assert float(per_image.min()) >= 0.05 - 1e-6 and float(per_image.max()) <= 0.25 + 1e-6 + spread = residual.flatten(1).std(dim=1) + assert float(spread.max()) < 1e-5 diff --git a/dataset/phase1_noise_20260906/trial_code_staging/train_graph_encoder_v2.py b/dataset/phase1_noise_20260906/trial_code_staging/train_graph_encoder_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..2e755bf09f1436bfac0aae6f524b26d12a2cecff --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/train_graph_encoder_v2.py @@ -0,0 +1,2640 @@ +#!/usr/bin/env python3 +"""Leakage-safe Phase-1 graph encoder training and evaluation. + +The deployed graph encoder keeps its original positional semantics: +``blur, noise, jpeg, lowlight`` become the real paired domains +``rain, noise, haze, lowlight``. This module never uses the legacy +``CombinedGraphLoss`` or its degraded-as-teacher path. +""" + +from __future__ import annotations + +import argparse +import copy +import dataclasses +import hashlib +import json +import math +import os +import random +import sys +import time +from contextlib import contextmanager +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple + +import numpy as np +import torch +import torch.nn as nn +import torch.nn.functional as F +from PIL import Image +from torch.utils.data import DataLoader, Dataset, Sampler + +PROJECT_ROOT = Path(__file__).resolve().parent +if str(PROJECT_ROOT) not in sys.path: + sys.path.insert(0, str(PROJECT_ROOT)) + +from src.data.rain13k_resized import load_rain13k_resized # noqa: E402 +from src.models.graph_encoder.hvi import rgb_to_hvi # noqa: E402 +from src.models.graph_encoder import ( # noqa: E402 + BlindDegradationGraphEncoder, + GraphConfig, +) + + +BRANCH_ORDER: Tuple[str, ...] = ("rain", "noise", "haze", "lowlight") +BRANCH_TO_INDEX: Dict[str, int] = { + name: index for index, name in enumerate(BRANCH_ORDER) +} +NUM_KNOWN = len(BRANCH_ORDER) +NUM_GRAPH_ROUTES = 6 +AGGREGATION_VERSION = 2 +CACHE_VERSION = 1 +# v5c crop policies. "resize" (legacy, ll_v3/v5): shorter side -> image_size, +# centre crop — SIDD ~4000x3000 frames are downsampled ~12x, which averages +# the sensor noise away. "native" (Phase-2 parity): random native-resolution +# crops for training, centre crop for evaluation; SIDD crops come from a +# prebuilt native cache (sidd_native_crops per training pair, 1 for eval). +CROP_POLICIES: Tuple[str, ...] = ("resize", "native") +NATIVE_CACHE_TAG = b"SCDC_PHASE1_SIDD_NATIVE_CACHE_V1\0" +EMBED_MEMBERS: Tuple[str, ...] = ("all", "known_clean") +# v5e: training-crop selection. "random" = one native crop per draw; +# "residual" = draw crop_candidates crops and keep the one with the largest +# paired residual, so a sparse-rain / light-haze crop actually contains the +# degradation it is labelled with (34% of native Rain13K crops had severity +# < 0.05 under "random"). +CROP_SELECT: Tuple[str, ...] = ("random", "residual") +AUDITED_COUNTS = {"train": 18261, "val": 317, "locked_test": 1220} + +DEFAULT_DATA_ROOT = Path(os.environ.get("SCDC_DATA_ROOT", "/home/admin_mcn/data")) +DEFAULT_RAIN_ROOT = Path(os.environ.get( + "SCDC_RAIN13K_ROOT", + "/home/admin_mcn/.cache/kagglehub/datasets/hngphchi/rain13k-resized/versions/1", +)) +DEFAULT_OUTPUT_DIR = Path( + "/home/admin_mcn/scdc_ban/outputs/graph_encoder_v2" +) +DEFAULT_QUARANTINE = PROJECT_ROOT / "src/data/rain13k_quarantine_v1.json" + +try: + _LANCZOS = Image.Resampling.LANCZOS +except AttributeError: # Pillow < 9 + _LANCZOS = Image.LANCZOS + + +@dataclass(frozen=True) +class PairRecord: + degraded: Path + clean: Path + degradation: str + dataset: str + source_id: str + split_group: str + clean_content_sha256: Optional[str] = None + + @property + def label(self) -> int: + return BRANCH_TO_INDEX[self.degradation] + + @property + def record_id(self) -> str: + payload = "\0".join( + ( + self.dataset, + self.source_id, + str(self.degraded), + str(self.clean), + self.clean_content_sha256 or "", + ) + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +@dataclass(frozen=True) +class DataSplits: + train: Tuple[PairRecord, ...] + val: Tuple[PairRecord, ...] + locked_test: Tuple[PairRecord, ...] + quarantine_count: int + + +def set_seed(seed: int) -> None: + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(seed) + + +def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + while True: + chunk = handle.read(chunk_size) + if not chunk: + break + digest.update(chunk) + return digest.hexdigest() + + +def _image_files(directory: Path) -> List[Path]: + extensions = {".png", ".jpg", ".jpeg"} + return sorted( + path + for path in directory.iterdir() + if path.is_file() and path.suffix.lower() in extensions + ) + + +def _require_pair_directories(input_dir: Path, target_dir: Path, label: str) -> None: + for directory in (input_dir, target_dir): + if not directory.is_dir(): + raise FileNotFoundError("%s missing directory: %s" % (label, directory)) + + +def _content_group(path: Path) -> str: + return sha256_file(path) + + +def build_rain_records( + rain_root: Path, quarantine_manifest: Path +) -> Tuple[List[PairRecord], List[PairRecord], List[PairRecord], int]: + splits = load_rain13k_resized( + rain_root, + max_train_pairs=0, + seed=42, + quarantine_manifest=quarantine_manifest, + ) + + def convert(pairs: Iterable[Tuple[Path, Path]], origin: str) -> List[PairRecord]: + records = [] + for degraded, clean in pairs: + content_hash = _content_group(clean) + records.append( + PairRecord( + degraded=degraded, + clean=clean, + degradation="rain", + dataset="Rain13K", + source_id="%s:%s" % (origin, degraded.name), + split_group=content_hash, + clean_content_sha256=content_hash, + ) + ) + return records + + train = convert(splits.train_pairs, "train_resized") + val = convert(splits.official_test_pairs["Test100"], "Test100") + locked = convert(splits.official_test_pairs["Test1200"], "Test1200") + return train, val, locked, splits.quarantined_train_pair_count + + +def discover_lol_records(root: Path, split: str) -> List[PairRecord]: + input_dir = root / split / "Input" + target_dir = root / split / "GT" + _require_pair_directories(input_dir, target_dir, "LOLv2 %s" % split) + records = [] + for degraded in _image_files(input_dir): + clean = target_dir / degraded.name + if not clean.is_file(): + raise ValueError("LOLv2 %s missing GT for %s" % (split, degraded.name)) + content_hash = _content_group(clean) + records.append( + PairRecord( + degraded=degraded, + clean=clean, + degradation="lowlight", + dataset="LOLv2", + source_id=degraded.stem, + split_group=content_hash, + clean_content_sha256=content_hash, + ) + ) + if not records: + raise ValueError("LOLv2 %s contains no paired images" % split) + return records + + +def discover_reside_records(root: Path) -> List[PairRecord]: + hazy_dir = root / "hazy" + clear_dir = root / "clear" + _require_pair_directories(hazy_dir, clear_dir, "RESIDE") + clear_by_source = {path.stem: path for path in _image_files(clear_dir)} + clean_hash_by_source: Dict[str, str] = {} + records = [] + for degraded in _image_files(hazy_dir): + source = degraded.stem.split("_")[0] + clean = clear_by_source.get(source) + if clean is None: + continue + if source not in clean_hash_by_source: + clean_hash_by_source[source] = _content_group(clean) + records.append( + PairRecord( + degraded=degraded, + clean=clean, + degradation="haze", + dataset="RESIDE", + source_id=degraded.stem, + split_group=source, + clean_content_sha256=clean_hash_by_source[source], + ) + ) + if not records: + raise ValueError("RESIDE contains no paired images") + return records + + +def split_reside_records( + records: Sequence[PairRecord], limit: int = 5000, val_count: int = 100 +) -> Tuple[List[PairRecord], List[PairRecord]]: + if limit <= 0 or val_count <= 0 or val_count >= limit: + raise ValueError("RESIDE requires 0 < val_count < limit") + limited = list(records[:limit]) + if len(limited) < limit: + raise ValueError( + "RESIDE audited contract requires %d pairs, found %d" + % (limit, len(limited)) + ) + val = limited[:val_count] + val_groups = {record.split_group for record in val} + train = [ + record for record in limited[val_count:] + if record.split_group not in val_groups + ] + return train, val + + +def sidd_scene_number(source_id: str) -> str: + parts = source_id.split("_") + if len(parts) < 3 or len(parts[1]) != 3 or not parts[1].isdigit(): + raise ValueError("Malformed SIDD source directory: %s" % source_id) + return parts[1] + + +def discover_sidd_records(root: Path) -> List[PairRecord]: + if not root.is_dir(): + raise FileNotFoundError("SIDD Data directory does not exist: %s" % root) + records = [] + for source_dir in sorted(path for path in root.iterdir() if path.is_dir()): + noisy = sorted(source_dir.glob("NOISY_SRGB_*")) + clean = sorted(source_dir.glob("GT_SRGB_*")) + if len(noisy) != 1 or len(clean) != 1: + raise ValueError( + "SIDD source %s must contain one NOISY/GT pair" % source_dir.name + ) + records.append( + PairRecord( + degraded=noisy[0], + clean=clean[0], + degradation="noise", + dataset="SIDD", + source_id=source_dir.name, + split_group=sidd_scene_number(source_dir.name), + clean_content_sha256=_content_group(clean[0]), + ) + ) + if not records: + raise ValueError("SIDD contains no paired source directories") + return records + + +def split_sidd_records( + records: Sequence[PairRecord], +) -> Tuple[List[PairRecord], List[PairRecord], List[PairRecord]]: + by_scene: Dict[str, List[PairRecord]] = {} + for record in records: + by_scene.setdefault(record.split_group, []).append(record) + if len(by_scene) != 10: + raise ValueError( + "SIDD audited scene split requires 10 scenes, found %d" % len(by_scene) + ) + ordered_scenes = sorted( + by_scene, + key=lambda scene: (hashlib.sha256(scene.encode("utf-8")).digest(), scene), + ) + scene_partitions = (ordered_scenes[:8], ordered_scenes[8:9], ordered_scenes[9:]) + partitions = [] + for scenes in scene_partitions: + partitions.append( + [record for scene in scenes for record in by_scene[scene]] + ) + return partitions[0], partitions[1], partitions[2] + + +def assert_split_isolation(splits: DataSplits) -> None: + keys = [] + for records in (splits.train, splits.val, splits.locked_test): + keys.append({(record.dataset, record.split_group) for record in records}) + labels = ("train", "val", "locked_test") + for left in range(3): + for right in range(left + 1, 3): + overlap = keys[left] & keys[right] + if overlap: + preview = sorted(overlap)[:5] + raise ValueError( + "source leakage between %s and %s: %r" + % (labels[left], labels[right], preview) + ) + + # Dataset-scoped source IDs cannot detect the same clean image copied into + # a different corpus. Enforce dataset-agnostic exact content isolation too. + content_keys = [] + for records in (splits.train, splits.val, splits.locked_test): + identities = set() + for record in records: + identity = record.clean_content_sha256 + if identity is None: + if record.clean.is_file(): + identity = sha256_file(record.clean) + else: + identity = "unresolved:%s:%s" % ( + record.dataset, record.split_group + ) + identities.add(identity) + content_keys.append(identities) + for left in range(3): + for right in range(left + 1, 3): + overlap = content_keys[left] & content_keys[right] + if overlap: + raise ValueError( + "clean-content leakage between %s and %s: %r" + % (labels[left], labels[right], sorted(overlap)[:5]) + ) + + +def build_data_splits(args: argparse.Namespace) -> DataSplits: + rain_train, rain_val, rain_test, quarantine_count = build_rain_records( + Path(args.rain13k_root), Path(args.quarantine_manifest) + ) + lol_root = Path(args.data_root) / "LOLv2/lolv2_hf" + lol_train = discover_lol_records(lol_root, "Train") + lol_val = discover_lol_records(lol_root, "Test") + reside_all = discover_reside_records(Path(args.data_root) / "RESIDE") + reside_train, reside_val = split_reside_records( + reside_all, args.reside_limit, args.reside_val_count + ) + sidd_all = discover_sidd_records( + Path(args.data_root) / "SIDD/SIDD_Small_sRGB_Only/Data" + ) + sidd_train, sidd_val, sidd_test = split_sidd_records(sidd_all) + splits = DataSplits( + train=tuple(rain_train + lol_train + reside_train + sidd_train), + val=tuple(rain_val + lol_val + reside_val + sidd_val), + locked_test=tuple(rain_test + sidd_test), + quarantine_count=quarantine_count, + ) + assert_split_isolation(splits) + counts = { + "train": len(splits.train), + "val": len(splits.val), + "locked_test": len(splits.locked_test), + } + if not args.allow_count_mismatch and counts != AUDITED_COUNTS: + raise ValueError( + "live-data counts differ from audited contract: expected %r, got %r" + % (AUDITED_COUNTS, counts) + ) + return splits + + +class BalancedBatchSampler(Sampler[List[int]]): + """Exact per-batch class balance via inverse-frequency replacement.""" + + def __init__( + self, + labels: Sequence[int], + batch_size: int, + steps: int, + seed: int, + epoch: int = 0, + yield_seeds: bool = False, + ) -> None: + if batch_size <= 0 or batch_size % NUM_KNOWN: + raise ValueError("batch_size must be positive and divisible by 4") + if steps <= 0: + raise ValueError("steps must be positive") + self.by_class = [] + for class_index in range(NUM_KNOWN): + indices = [i for i, label in enumerate(labels) if label == class_index] + if not indices: + raise ValueError("balanced sampler has an empty class") + self.by_class.append(indices) + self.batch_size = batch_size + self.per_class = batch_size // NUM_KNOWN + self.steps = steps + self.seed = seed + self.epoch = epoch + # v5c: emit (record_index, sample_seed) so a native-crop dataset can + # draw a fresh, replayable crop per draw (Phase2PairDataset protocol). + # A separate generator keeps the record draws identical to yield_seeds=False. + self.yield_seeds = bool(yield_seeds) + + def __len__(self) -> int: + return self.steps + + def __iter__(self) -> Iterator[List[object]]: + generator = torch.Generator() + generator.manual_seed(self.seed + self.epoch * 1000003) + seed_generator = torch.Generator() + seed_generator.manual_seed(self.seed * 7 + self.epoch * 1000003 + 17) + for _ in range(self.steps): + batch = [] + for indices in self.by_class: + draws = torch.randint( + len(indices), (self.per_class,), generator=generator + ).tolist() + batch.extend(indices[position] for position in draws) + permutation = torch.randperm(len(batch), generator=generator).tolist() + ordered = [batch[position] for position in permutation] + if not self.yield_seeds: + yield ordered + continue + seeds = torch.randint(0, 2 ** 31 - 1, (len(ordered),), generator=seed_generator).tolist() + yield [(index, int(seed)) for index, seed in zip(ordered, seeds)] + + +def _open_rgb(path: Path) -> Image.Image: + try: + with Image.open(path) as image: + return image.convert("RGB").copy() + except Exception as exc: + raise RuntimeError("Failed to decode image %s: %s" % (path, exc)) from exc + + +def _resize_center_crop(image: Image.Image, size: int) -> Image.Image: + width, height = image.size + if width <= 0 or height <= 0: + raise ValueError("image has invalid dimensions: %r" % (image.size,)) + scale = float(size) / min(width, height) + resized = image.resize( + (max(size, int(round(width * scale))), max(size, int(round(height * scale)))), + _LANCZOS, + ) + left = (resized.width - size) // 2 + top = (resized.height - size) // 2 + return resized.crop((left, top, left + size, top + size)) + + +def load_pair_uint8(record: PairRecord, size: int) -> Tuple[Image.Image, Image.Image]: + degraded = _resize_center_crop(_open_rgb(record.degraded), size) + clean = _resize_center_crop(_open_rgb(record.clean), size) + return degraded, clean + + +def _pil_to_tensor(image: Image.Image) -> torch.Tensor: + array = np.asarray(image, dtype=np.uint8).copy() + return torch.from_numpy(array).permute(2, 0, 1).float().div_(255.0) + + +# ---- v5c native-resolution crop policy (Phase-2 parity) ------------------- # +def _native_open_pair(record: PairRecord, size: int) -> Tuple[Image.Image, Image.Image]: + """Open a pair at native resolution; upscale only when smaller than ``size`` + (exactly Phase2PairDataset's rule), never downscale.""" + degraded, clean = _open_rgb(record.degraded), _open_rgb(record.clean) + if degraded.size != clean.size: + raise ValueError( + "paired images must share a native size: %s is %r vs %r" + % (record.source_id, degraded.size, clean.size) + ) + width, height = degraded.size + if min(width, height) < size: + scale = float(size) / min(width, height) + resized = ( + max(size, int(math.ceil(width * scale))), + max(size, int(math.ceil(height * scale))), + ) + degraded = degraded.resize(resized, _LANCZOS) + clean = clean.resize(resized, _LANCZOS) + return degraded, clean + + +def _crop_box( + width: int, height: int, size: int, rng: Optional[random.Random] +) -> Tuple[int, int, int, int]: + if rng is None: + left, top = (width - size) // 2, (height - size) // 2 + else: + left = rng.randrange(width - size + 1) + top = rng.randrange(height - size + 1) + return (left, top, left + size, top + size) + + +def _sample_rng(record: PairRecord, sample_seed: int) -> random.Random: + digest = hashlib.sha256(("%s:%d" % (record.record_id, int(sample_seed))).encode("ascii")) + return random.Random(int(digest.hexdigest()[:16], 16)) + + +def _sidd_native_boxes( + record: PairRecord, width: int, height: int, size: int, count: int, training: bool +) -> List[Tuple[int, int, int, int]]: + """Deterministic native crop boxes for one SIDD pair: ``count`` random + boxes for training (seeded by the record id), the centre box for eval.""" + if not training: + return [_crop_box(width, height, size, None)] + digest = hashlib.sha256(("native-cache:%s" % record.record_id).encode("ascii")) + rng = random.Random(int(digest.hexdigest()[:16], 16)) + return [_crop_box(width, height, size, rng) for _ in range(count)] + + +def _select_pair_by_residual( + pairs: Sequence[Tuple[torch.Tensor, torch.Tensor]] +) -> Tuple[torch.Tensor, torch.Tensor]: + """Keep the candidate crop with the largest paired absolute residual.""" + if len(pairs) == 1: + return pairs[0] + scores = [float((degraded - clean).abs().mean()) for degraded, clean in pairs] + return pairs[max(range(len(pairs)), key=scores.__getitem__)] + + +def _native_cache_paths( + cache_dir: Path, record: PairRecord, image_size: int, crop_index: int +) -> Tuple[Path, Path]: + digest = hashlib.sha256(NATIVE_CACHE_TAG) + digest.update(record.record_id.encode("ascii")) + digest.update(str(image_size).encode("ascii")) + for source_path in (record.degraded, record.clean): + stat = source_path.stat() + contract = "%d:%d:%d:%d" % ( + stat.st_size, stat.st_mtime_ns, stat.st_ctime_ns, getattr(stat, "st_ino", 0) + ) + digest.update(contract.encode("ascii")) + digest.update(b"\0") + stem = "%s_n%d_c%02d_v%d" % (digest.hexdigest(), image_size, int(crop_index), CACHE_VERSION) + return cache_dir / (stem + "_deg.png"), cache_dir / (stem + "_clean.png") + + +def _atomic_image_save(image: Image.Image, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name( + ".%s.%d.%d.tmp" % (path.name, os.getpid(), time.time_ns()) + ) + try: + image.save(str(temporary), format="PNG") + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +class PairDataset(Dataset): + def __init__( + self, + records: Sequence[PairRecord], + image_size: int, + severity_calibration: Mapping[str, Mapping[str, float]], + cache_dir: Optional[Path] = None, + crop_policy: str = "resize", + training: bool = False, + sidd_native_crops: int = 32, + crop_select: str = "random", + crop_candidates: int = 4, + ) -> None: + if crop_policy not in CROP_POLICIES: + raise ValueError("crop_policy must be one of %r, got %r" % (CROP_POLICIES, crop_policy)) + if int(sidd_native_crops) < 1: + raise ValueError("sidd_native_crops must be >= 1") + if crop_select not in CROP_SELECT: + raise ValueError("crop_select must be one of %r, got %r" % (CROP_SELECT, crop_select)) + if int(crop_candidates) < 1: + raise ValueError("crop_candidates must be >= 1") + self.crop_select = str(crop_select) + self.crop_candidates = int(crop_candidates) + self.records = tuple(records) + self.image_size = image_size + self.severity_calibration = severity_calibration + self.cache_dir = cache_dir + self.crop_policy = str(crop_policy) + self.training = bool(training) + self.sidd_native_crops = int(sidd_native_crops) + + def __len__(self) -> int: + return len(self.records) + + @property + def native(self) -> bool: + return self.crop_policy == "native" + + def _sidd_crop_count(self) -> int: + return self.sidd_native_crops if self.training else 1 + + def _cache_paths(self, record: PairRecord) -> Tuple[Path, Path]: + assert self.cache_dir is not None + return _cache_paths(self.cache_dir, record, self.image_size) + + def _native_cache_paths(self, record: PairRecord, crop_index: int) -> Tuple[Path, Path]: + assert self.cache_dir is not None + return _native_cache_paths(self.cache_dir, record, self.image_size, crop_index) + + def prepare_cache(self) -> None: + if self.cache_dir is None: + return + self.cache_dir.mkdir(parents=True, exist_ok=True) + for record in self.records: + if record.dataset != "SIDD": + continue + if not self.native: + degraded_path, clean_path = self._cache_paths(record) + if degraded_path.is_file() and clean_path.is_file(): + continue + degraded, clean = load_pair_uint8(record, self.image_size) + _atomic_image_save(degraded, degraded_path) + _atomic_image_save(clean, clean_path) + continue + paths = [self._native_cache_paths(record, k) for k in range(self._sidd_crop_count())] + if all(d.is_file() and c.is_file() for d, c in paths): + continue + degraded, clean = _native_open_pair(record, self.image_size) + boxes = _sidd_native_boxes( + record, degraded.width, degraded.height, self.image_size, + self._sidd_crop_count(), self.training, + ) + for (degraded_path, clean_path), box in zip(paths, boxes): + _atomic_image_save(degraded.crop(box), degraded_path) + _atomic_image_save(clean.crop(box), clean_path) + + def _load( + self, record: PairRecord, rng: Optional[random.Random] = None + ) -> Tuple[torch.Tensor, torch.Tensor]: + if not self.native: + if self.cache_dir is None or record.dataset != "SIDD": + degraded, clean = load_pair_uint8(record, self.image_size) + else: + degraded_path, clean_path = self._cache_paths(record) + if not degraded_path.is_file() or not clean_path.is_file(): + raise RuntimeError( + "SIDD cache was not prebuilt in the main process: %s" % self.cache_dir + ) + degraded, clean = _open_rgb(degraded_path), _open_rgb(clean_path) + return _pil_to_tensor(degraded), _pil_to_tensor(clean) + candidates = ( + self.crop_candidates if (rng is not None and self.crop_select == "residual") else 1 + ) + if record.dataset == "SIDD" and self.cache_dir is not None: + pairs = [] + for _ in range(candidates): + crop_index = rng.randrange(self._sidd_crop_count()) if rng is not None else 0 + degraded_path, clean_path = self._native_cache_paths(record, crop_index) + if not degraded_path.is_file() or not clean_path.is_file(): + raise RuntimeError( + "SIDD native cache was not prebuilt in the main process: %s" % self.cache_dir + ) + pairs.append((_pil_to_tensor(_open_rgb(degraded_path)), _pil_to_tensor(_open_rgb(clean_path)))) + return _select_pair_by_residual(pairs) + degraded, clean = _native_open_pair(record, self.image_size) + pairs = [] + for _ in range(candidates): + box = _crop_box(degraded.width, degraded.height, self.image_size, rng) + pairs.append((_pil_to_tensor(degraded.crop(box)), _pil_to_tensor(clean.crop(box)))) + return _select_pair_by_residual(pairs) + + def __getitem__(self, item: object) -> Dict[str, object]: + # Native training draws come as (record_index, sample_seed) from the + # balanced sampler; a bare index always yields the deterministic + # centre crop (evaluation, calibration, legacy callers). + if isinstance(item, (tuple, list)): + if len(item) != 2: + raise TypeError("sampled items must be (record_index, sample_seed)") + index, sample_seed = int(item[0]), int(item[1]) + else: + index, sample_seed = int(item), None + record = self.records[index] + rng = ( + _sample_rng(record, sample_seed) + if (self.native and self.training and sample_seed is not None) else None + ) + degraded, clean = self._load(record, rng) + calibration = self.severity_calibration[record.degradation] + severity = residual_mae_severity( + degraded, clean, calibration["p05"], calibration["p95"] + ) + return { + "degraded": degraded, + "clean": clean, + "label": record.label, + "severity": severity, + "degradation": record.degradation, + "source_id": record.source_id, + } + + +def residual_mae_severity( + degraded: torch.Tensor, clean: torch.Tensor, p05: float, p95: float +) -> torch.Tensor: + if p95 <= p05: + raise ValueError("severity p95 must be greater than p05") + raw = (degraded - clean).abs().mean() + return ((raw - float(p05)) / float(p95 - p05)).clamp(0.0, 1.0) + + +def _cache_paths(cache_dir: Path, record: PairRecord, image_size: int) -> Tuple[Path, Path]: + digest = hashlib.sha256(b"SCDC_PHASE1_SIDD_CACHE_V1\0") + digest.update(record.record_id.encode("ascii")) + digest.update(str(image_size).encode("ascii")) + for source_path in (record.degraded, record.clean): + stat = source_path.stat() + contract = "%d:%d:%d:%d" % ( + stat.st_size, + stat.st_mtime_ns, + stat.st_ctime_ns, + getattr(stat, "st_ino", 0), + ) + digest.update(contract.encode("ascii")) + digest.update(b"\0") + stem = "%s_s%d_v%d" % (digest.hexdigest(), image_size, CACHE_VERSION) + return cache_dir / (stem + "_deg.png"), cache_dir / (stem + "_clean.png") + + +def _load_record_tensors( + record: PairRecord, + image_size: int, + sidd_cache_dir: Optional[Path], + crop_policy: str = "resize", +) -> Tuple[torch.Tensor, torch.Tensor]: + if record.dataset == "SIDD" and sidd_cache_dir is not None: + if crop_policy == "native": + # Crop 0 of the training cache (a seeded random native crop). + degraded_path, clean_path = _native_cache_paths(sidd_cache_dir, record, image_size, 0) + else: + degraded_path, clean_path = _cache_paths(sidd_cache_dir, record, image_size) + if not degraded_path.is_file() or not clean_path.is_file(): + raise RuntimeError("SIDD cache missing during calibration: %s" % degraded_path) + return _pil_to_tensor(_open_rgb(degraded_path)), _pil_to_tensor(_open_rgb(clean_path)) + if crop_policy == "native": + degraded, clean = _native_open_pair(record, image_size) + box = _crop_box(degraded.width, degraded.height, image_size, None) + return _pil_to_tensor(degraded.crop(box)), _pil_to_tensor(clean.crop(box)) + degraded, clean = load_pair_uint8(record, image_size) + return _pil_to_tensor(degraded), _pil_to_tensor(clean) + + +def _records_fingerprint( + records: Sequence[PairRecord], image_size: int, crop_policy: str = "resize" +) -> str: + digest = hashlib.sha256(b"SCDC_PHASE1_CALIBRATION_V1\0") + if crop_policy != "resize": + # Legacy digests (resize policy) stay byte-identical so ll_v3/v5 + # calibration caches remain valid. + digest.update(("crop_policy=%s\0" % crop_policy).encode("ascii")) + digest.update(str(image_size).encode("ascii")) + for record in records: + digest.update(record.record_id.encode("ascii")) + for source_path in (record.degraded, record.clean): + stat = source_path.stat() + digest.update( + ("%d:%d:%d:%d" % ( + stat.st_size, + stat.st_mtime_ns, + stat.st_ctime_ns, + getattr(stat, "st_ino", 0), + )).encode("ascii") + ) + digest.update(b"\0") + digest.update(b"\n") + return digest.hexdigest() + + +def _histogram_quantile(counts: np.ndarray, quantile: float) -> float: + total = int(counts.sum()) + if total <= 0: + return 1.0 + threshold = max(1, int(math.ceil(total * quantile))) + index = int(np.searchsorted(np.cumsum(counts), threshold, side="left")) + return min(1.0, max(1.0 / len(counts), float(index + 1) / len(counts))) + + +def fit_training_calibration( + records: Sequence[PairRecord], + image_size: int, + output_path: Path, + sidd_cache_dir: Optional[Path], + crop_policy: str = "resize", +) -> Dict[str, Dict[str, float]]: + """Fit train-only scalar p05/p95 and pixel q95, with a persistent cache.""" + fingerprint = _records_fingerprint(records, image_size, crop_policy) + if output_path.is_file(): + payload = json.loads(output_path.read_text(encoding="utf-8")) + if payload.get("fingerprint") == fingerprint: + return payload["domains"] + + maes: Dict[str, List[float]] = {name: [] for name in BRANCH_ORDER} + histograms = { + name: np.zeros(4096, dtype=np.int64) for name in BRANCH_ORDER + } + for record in records: + degraded, clean = _load_record_tensors(record, image_size, sidd_cache_dir, crop_policy) + residual = (degraded - clean).abs().mean(dim=0) + maes[record.degradation].append(float(residual.mean().item())) + histogram, _ = np.histogram( + residual.numpy(), bins=4096, range=(0.0, 1.0) + ) + histograms[record.degradation] += histogram + + domains: Dict[str, Dict[str, float]] = {} + for name in BRANCH_ORDER: + if not maes[name]: + raise ValueError("calibration has no training records for %s" % name) + p05, p95 = np.percentile(np.asarray(maes[name]), [5.0, 95.0]).tolist() + if p95 <= p05: + p95 = p05 + 1e-6 + domains[name] = { + "p05": float(p05), + "p95": float(p95), + "pixel_q95": _histogram_quantile(histograms[name], 0.95), + "sample_count": float(len(maes[name])), + } + _atomic_write_json( + output_path, + { + "version": 1, + "definition": ( + "paired native-resolution centre-crop RGB absolute residual" + if crop_policy == "native" + else "paired center-crop RGB absolute residual" + ), + "crop_policy": crop_policy, + "fit_split": "train_only", + "fingerprint": fingerprint, + "domains": domains, + }, + ) + return domains + + +@contextmanager +def _batch_norm_eval(model: nn.Module) -> Iterator[None]: + batch_norms = [ + module + for module in model.modules() + if isinstance(module, nn.modules.batchnorm._BatchNorm) + ] + states = [module.training for module in batch_norms] + try: + for module in batch_norms: + module.eval() + yield + finally: + for module, state in zip(batch_norms, states): + module.train(state) + + +def forward_clean_bn_safe(model: nn.Module, clean: torch.Tensor): + """Clean paired pass with gradients, without changing degraded BN statistics.""" + with _batch_norm_eval(model): + return model.forward_student(clean) + + +def spatial_supervision_loss( + spatial_maps: torch.Tensor, + degraded: torch.Tensor, + clean: torch.Tensor, + labels: torch.Tensor, + pixel_q95: torch.Tensor, +) -> Tuple[torch.Tensor, Dict[str, float]]: + if spatial_maps.ndim != 4 or spatial_maps.shape[1] != NUM_KNOWN: + raise ValueError("spatial_maps must be [B,4,H,W]") + residual = (degraded - clean).abs().mean(dim=1, keepdim=True) + target = F.adaptive_avg_pool2d(residual, spatial_maps.shape[-2:]) + scales = pixel_q95.to(spatial_maps.device).index_select(0, labels) + target = (target / scales.view(-1, 1, 1, 1).clamp_min(1e-6)).clamp(0, 1) + rows = torch.arange(labels.shape[0], device=labels.device) + selected = spatial_maps[rows, labels].unsqueeze(1) + selected_loss = F.smooth_l1_loss(selected, target) + selected_mae = (selected - target).abs().mean() + active_mask = F.one_hot(labels, NUM_KNOWN).to(spatial_maps.dtype) + inactive_mask = 1.0 - active_mask.view(-1, NUM_KNOWN, 1, 1) + inactive_square = (spatial_maps.square() * inactive_mask).sum() / ( + inactive_mask.sum() * spatial_maps.shape[-2] * spatial_maps.shape[-1] + ).clamp_min(1.0) + inactive_activation = (spatial_maps * inactive_mask).sum() / ( + inactive_mask.sum() * spatial_maps.shape[-2] * spatial_maps.shape[-1] + ).clamp_min(1.0) + loss = selected_loss + 0.25 * inactive_square + return loss, { + "spatial_selected_mae": float(selected_mae.detach().item()), + "spatial_inactive_activation": float(inactive_activation.detach().item()), + } + + +OOD_KINDS = ("snow", "blur", "pixelate", "sharpen") + + +def synthesize_ood( + clean: torch.Tensor, kind: str, generator: torch.Generator +) -> torch.Tensor: + """Deterministic synthetic OOD degradations disjoint from the four knowns. + + snow = blob occluders, blur = PSF loss, pixelate = compression-like. + Parameters are drawn from the CPU generator so plans replay exactly. + """ + if clean.ndim != 4 or clean.shape[1] != 3: + raise ValueError("clean must be a [B,3,H,W] tensor") + if kind == "snow": + batch, _, height, width = clean.shape + flakes = 96 + yy, xx = torch.meshgrid( + torch.arange(height, dtype=torch.float32), + torch.arange(width, dtype=torch.float32), + ) + yy = yy.to(clean.device) + xx = xx.to(clean.device) + result = [] + for index in range(batch): + params = torch.rand(flakes, 6, generator=generator) + cx = (params[:, 0] * (width - 1)).to(clean.device) + cy = (params[:, 1] * (height - 1)).to(clean.device) + radius = (1.0 + params[:, 2] * 4.0).to(clean.device) + # Near-circular flakes only: elongated blobs are statistically + # rain streaks and teach the router to dump real rain into the + # free slots (measured: rain argmax 97->61 with elong up to 3x). + elong = (1.0 + params[:, 3] * 0.5).to(clean.device) + opacity = (0.55 + params[:, 4] * 0.4).to(clean.device) + du = xx.unsqueeze(0) - cx.view(-1, 1, 1) + dv = yy.unsqueeze(0) - cy.view(-1, 1, 1) + blob = torch.exp( + -( + du.square() / (2.0 * (radius * elong).view(-1, 1, 1).square()) + + dv.square() / (2.0 * radius.view(-1, 1, 1).square()) + ) + ) + alpha = (opacity.view(-1, 1, 1) * blob).sum(dim=0).clamp(0, 1) + result.append(clean[index] * (1 - alpha) + alpha) + return torch.stack(result, dim=0) + if kind == "blur": + sigma = 1.5 + float(torch.rand(1, generator=generator)) * 2.0 + size = int(2 * round(3 * sigma) + 1) + offsets = torch.arange(size, dtype=torch.float32) - size // 2 + kernel = torch.exp(-offsets.square() / (2 * sigma * sigma)) + kernel = (kernel / kernel.sum()).to(clean.device) + pad = size // 2 + row = kernel.view(1, 1, 1, size).expand(3, 1, 1, size) + col = kernel.view(1, 1, size, 1).expand(3, 1, size, 1) + blurred = F.conv2d( + F.pad(clean, (pad, pad, 0, 0), mode="reflect"), row, groups=3 + ) + return F.conv2d( + F.pad(blurred, (0, 0, pad, pad), mode="reflect"), col, groups=3 + ) + if kind == "pixelate": + factor = 4 * (1 + int(torch.randint(0, 2, (1,), generator=generator))) + down = F.avg_pool2d(clean, factor) + return F.interpolate(down, size=clean.shape[-2:], mode="nearest") + if kind == "sharpen": + # Unsharp masking: MORE fine detail, no degradation. A hard negative + # for the noise concept (fine structured detail must route to null). + amount = 0.8 + 1.2 * float(torch.rand(1, generator=generator)) + kernel = torch.tensor( + [[1.0, 2.0, 1.0], [2.0, 4.0, 2.0], [1.0, 2.0, 1.0]], device=clean.device + ) / 16.0 + blurred = F.conv2d( + F.pad(clean, (1, 1, 1, 1), mode="reflect"), + kernel.view(1, 1, 3, 3).expand(3, 1, 3, 3), groups=3, + ) + return (clean + amount * (clean - blurred)).clamp(0.0, 1.0) + raise ValueError("unknown OOD kind %r" % kind) + + +NOISE_INDEX = BRANCH_ORDER.index("noise") + + +def synthesize_noise( + clean: torch.Tensor, + generator: torch.Generator, + residual_bank: Optional[Sequence[torch.Tensor]] = None, + synthetic_prob: float = 0.5, + gain_max: float = 1.4, +) -> torch.Tensor: + """Realistic noise positives on ANY clean image (deterministic). + + Two modes drawn per image: (a) heteroscedastic Poisson-Gaussian noise in + sRGB (sigma^2 = a*x + b), optionally 3x3-correlated to mimic demosaicing; + (b) transplant of a real SIDD residual (noisy - clean) from ``residual_bank`` + with a random flip. Purpose: the noise concept must be learned from noise + statistics on thousands of scenes, not memorised from 8 SIDD scenes. + """ + if clean.ndim != 4 or clean.shape[1] != 3: + raise ValueError("clean must be a [B,3,H,W] tensor") + batch = clean.shape[0] + outputs = [] + for index in range(batch): + image = clean[index] + use_bank = ( + residual_bank is not None and len(residual_bank) > 0 + and float(torch.rand(1, generator=generator)) >= float(synthetic_prob) + ) + if use_bank: + pick = int(torch.randint(0, len(residual_bank), (1,), generator=generator)) + residual = residual_bank[pick].to(image.device, image.dtype) + if residual.shape[-2:] != image.shape[-2:]: + residual = F.interpolate( + residual.unsqueeze(0), size=image.shape[-2:], mode="bilinear", + align_corners=False, + )[0] + flips = torch.rand(2, generator=generator) + if float(flips[0]) < 0.5: + residual = residual.flip(-1) + if float(flips[1]) < 0.5: + residual = residual.flip(-2) + gain = 0.5 + (float(gain_max) - 0.5) * float(torch.rand(1, generator=generator)) + noisy = image + gain * residual + else: + params = torch.rand(4, generator=generator) + a = 0.002 + 0.028 * float(params[0]) + b = 0.0002 + 0.006 * float(params[1]) + sigma = (a * image.clamp(0.0, 1.0) + b).sqrt() + noise = torch.randn(image.shape, generator=generator).to(image.device) + if float(params[2]) < 0.5: + kernel = torch.tensor( + [[1.0, 2.0, 1.0], [2.0, 4.0, 2.0], [1.0, 2.0, 1.0]], + device=image.device, + ) / 16.0 + noise = F.conv2d( + F.pad(noise.unsqueeze(0), (1, 1, 1, 1), mode="reflect"), + kernel.view(1, 1, 3, 3).expand(3, 1, 3, 3), groups=3, + )[0] * 1.6 # restore variance lost to the blur + noisy = image + sigma * noise + outputs.append(noisy.clamp(0.0, 1.0)) + return torch.stack(outputs, dim=0) + + +def apply_noise_positives( + degraded: torch.Tensor, + clean: torch.Tensor, + labels: torch.Tensor, + severity: torch.Tensor, + probability: float, + generator: torch.Generator, + noise_calibration: Mapping[str, float], + residual_bank: Optional[Sequence[torch.Tensor]] = None, + synthetic_prob: float = 0.5, + gain_max: float = 1.4, +) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]: + """Turn a random subset of NON-noise pairs into noise pairs. + + Returns new (degraded, labels, severity, mask) tensors; the originals are + not mutated. Severity targets use the same residual-MAE rule and the + noise-domain calibration as real SIDD pairs. + """ + if probability <= 0.0: + return degraded, labels, severity, torch.zeros_like(labels, dtype=torch.bool) + draw = torch.rand(labels.shape[0], generator=generator).to(labels.device) + mask = (draw < float(probability)) & (labels != NOISE_INDEX) + if not bool(mask.any()): + return degraded, labels, severity, mask + noisy = synthesize_noise( + clean, generator, residual_bank, synthetic_prob=synthetic_prob, gain_max=gain_max + ) + new_degraded = torch.where(mask.view(-1, 1, 1, 1), noisy, degraded) + new_labels = torch.where(mask, torch.full_like(labels, NOISE_INDEX), labels) + p05, p95 = float(noise_calibration["p05"]), float(noise_calibration["p95"]) + per_image = torch.stack([ + residual_mae_severity(noisy[i], clean[i], p05, p95) for i in range(labels.shape[0]) + ]).to(severity.dtype) + new_severity = torch.where(mask, per_image, severity) + return new_degraded, new_labels, new_severity, mask + + +def ood_global_margin_loss( + known_global: torch.Tensor, + known_labels: torch.Tensor, + ood_global: torch.Tensor, + margin: float = 0.5, +) -> torch.Tensor: + """v6: every real-OOD global vector must stay at least ``margin`` (in + L2-normalised space, so 0..2) away from the nearest KNOWN-type batch + centroid. Hinge only: nothing pulls OOD samples together or towards a + slot, so the free nodes keep their own geometry. Zero when the batch + has no OOD rows or no known rows.""" + + if ood_global.shape[0] == 0 or known_global.shape[0] == 0: + return known_global.new_tensor(0.0) + known = F.normalize(known_global.float(), dim=1) + ood = F.normalize(ood_global.float(), dim=1) + centroids = [] + for label in torch.unique(known_labels): + centroids.append(F.normalize(known[known_labels == label].mean(dim=0, keepdim=True), dim=1)) + centroids = torch.cat(centroids, dim=0) # [K', D] + distance = torch.cdist(ood, centroids) # [N, K'] + nearest = distance.min(dim=1).values + return F.relu(float(margin) - nearest).mean() + + +def texture_null_weights(clean: torch.Tensor) -> torch.Tensor: + """Per-image weights in [0.5, 1.5] rising with high-frequency texture. + + Clean images with strong structured high frequencies are the hardest + negatives for the noise concept (texture is not noise); they get the + strongest pull into the null slots. + """ + luma = (0.299 * clean[:, 0] + 0.587 * clean[:, 1] + 0.114 * clean[:, 2]).unsqueeze(1) + kernel = torch.tensor( + [[0.0, 1.0, 0.0], [1.0, -4.0, 1.0], [0.0, 1.0, 0.0]], device=clean.device, + dtype=luma.dtype, + ).view(1, 1, 3, 3) + response = F.conv2d(luma, kernel, padding=1) + variance = response.flatten(1).var(dim=1) + if variance.numel() < 2: + return torch.ones_like(variance) + ranks = variance.argsort().argsort().to(variance.dtype) + return 0.5 + ranks / max(1.0, float(variance.numel() - 1)) + + +class WeightEMA: + """Exponential moving average of the encoder weights (v5d). + + The shadow module is what gets evaluated, selected and written to + ``model_state_dict`` (Phase-2 consumes it). Floating-point buffers (the + BatchNorm running statistics of ``feature_extractor``) are averaged with + the same decay as the weights, exactly like timm's ModelEma: copying the + live statistics next to averaged conv weights collapsed routing (every + input -> rain) because BatchNorm makes the network sensitive to the + weight/statistic mismatch. Integer buffers (``num_batches_tracked``) are + copied. ``warmup`` uses ``min(decay, (1 + n) / (10 + n))`` so early + shadows are not dominated by the random initialisation. + """ + + def __init__(self, model: nn.Module, decay: float, warmup: bool = True) -> None: + if not 0.0 < float(decay) < 1.0: + raise ValueError("ema decay must be in (0, 1), got %r" % decay) + self.decay = float(decay) + self.warmup = bool(warmup) + self.updates = 0 + self.module = copy.deepcopy(model).eval() + for parameter in self.module.parameters(): + parameter.requires_grad_(False) + + def effective_decay(self, updates: int) -> float: + if not self.warmup: + return self.decay + return min(self.decay, (1.0 + updates) / (10.0 + updates)) + + @torch.no_grad() + def update(self, model: nn.Module) -> None: + self.updates += 1 + decay = self.effective_decay(self.updates) + live = dict(model.named_parameters()) + for name, shadow in self.module.named_parameters(): + shadow.mul_(decay).add_(live[name].detach().to(shadow.dtype), alpha=1.0 - decay) + live_buffers = dict(model.named_buffers()) + for name, shadow in self.module.named_buffers(): + if shadow.dtype.is_floating_point: + shadow.mul_(decay).add_(live_buffers[name].detach().to(shadow.dtype), alpha=1.0 - decay) + else: + shadow.copy_(live_buffers[name]) + + +@dataclass(frozen=True) +class LossWeights: + route: float = 1.0 + global_type: float = 0.5 + severity: float = 1.0 + root: float = 0.2 + content: float = 0.2 + # v3.1 rebalance: the free-slot attractor absorbed known-domain mass + # (rain 97->61); keep the null/OOD pull but halve it and raise the + # known-sample free-mass suppression. + unknown: float = 0.25 + spatial: float = 0.1 + null_route: float = 0.15 + ood_route: float = 0.15 + unknown_margin: float = 0.1 + # v5: metric separation on the readout embedding, supervised photometric + # shift (HVI global affine degraded->clean), and the null pull on an + # extra clean pool (Snow100K gt) that is not paired with any degradation. + embed: float = 0.0 + photometric: float = 0.0 + extra_null: float = 0.0 + # v6: margin between real-OOD global vectors and the known-type batch + # centroids (t-SNE showed snow and rain sharing one cloud in + # global_condition even though routing sends snow to the free slots). + ood_global_margin: float = 0.0 + + +CLEAN_CLASS = NUM_KNOWN +UNKNOWN_CLASS = NUM_KNOWN + 1 + + +def supervised_contrastive_loss( + embeddings: torch.Tensor, + labels: torch.Tensor, + temperature: float = 0.1, + unknown_label: Optional[int] = None, +) -> torch.Tensor: + """Supervised contrastive loss (Khosla et al.) on L2-normalised embeddings. + + Samples with ``unknown_label`` act only as negatives: they are pushed away + from every known class and from clean, but never pulled together (unknown + degradations are not one cluster). + """ + z = F.normalize(embeddings.float(), dim=1) + n = z.shape[0] + if n < 2: + return z.new_tensor(0.0) + logits = z @ z.T / float(temperature) + eye = torch.eye(n, dtype=torch.bool, device=z.device) + logits = logits.masked_fill(eye, -1e4) + log_prob = logits - torch.logsumexp(logits, dim=1, keepdim=True) + same = labels.view(-1, 1) == labels.view(1, -1) + positives = same & ~eye + if unknown_label is not None: + positives = positives & (labels.view(-1, 1) != int(unknown_label)) + counts = positives.sum(dim=1) + valid = counts > 0 + if not bool(valid.any()): + return z.new_tensor(0.0) + per_anchor = -(log_prob * positives.to(log_prob.dtype)).sum(dim=1)[valid] / counts[valid].to(log_prob.dtype) + return per_anchor.mean() + + +@torch.no_grad() +def photometric_shift_targets( + degraded: torch.Tensor, clean: torch.Tensor, k: float = 0.2 +) -> torch.Tensor: + """Per-image global affine degraded->clean in HVI, as an 8-vector: + (log gain_I, bias_I, M11-1, M21, M12, M22-1, t1, t2) where + [h', v'] = [h, v] @ M + t on the HV plane. Identity maps to zeros.""" + k_value = float(k.detach()) if torch.is_tensor(k) else float(k) + hd = rgb_to_hvi(degraded.float().clamp(0, 1), k_value) + hc = rgb_to_hvi(clean.float().clamp(0, 1), k_value) + x, y = hd[:, 2].flatten(1), hc[:, 2].flatten(1) + xm, ym = x.mean(1, keepdim=True), y.mean(1, keepdim=True) + var = ((x - xm) ** 2).mean(1) + cov = ((x - xm) * (y - ym)).mean(1) + gain = (cov / (var + 1e-6)).clamp(0.05, 20.0) + bias = ym.squeeze(1) - gain * xm.squeeze(1) + ones = torch.ones_like(x) + a_mat = torch.stack((hd[:, 0].flatten(1), hd[:, 1].flatten(1), ones), dim=2) # [B,N,3] + y_mat = torch.stack((hc[:, 0].flatten(1), hc[:, 1].flatten(1)), dim=2) # [B,N,2] + ata = a_mat.transpose(1, 2) @ a_mat + 1e-4 * torch.eye(3, device=x.device).unsqueeze(0) + aty = a_mat.transpose(1, 2) @ y_mat + # Batched tiny solves go through cuSOLVER in torch 1.10 and intermittently + # raise "CUDA error: misaligned address" (killed phase1_v5 at epoch 8). + # B x 3 x 3 in float64 on the CPU is exact and costs nothing. + try: + m = torch.linalg.solve(ata.double().cpu(), aty.double().cpu()).to(x.device, x.dtype) # [B,3,2] + except RuntimeError: + m = torch.tensor([[1.0, 0.0], [0.0, 1.0], [0.0, 0.0]], device=x.device, dtype=x.dtype) + m = m.unsqueeze(0).expand(x.shape[0], -1, -1).clone() + target = torch.stack(( + gain.log(), bias, + m[:, 0, 0] - 1.0, m[:, 1, 0], m[:, 0, 1], m[:, 1, 1] - 1.0, m[:, 2, 0], m[:, 2, 1], + ), dim=1) + return target.clamp(-3.0, 3.0) + + +# Real-OOD / extra-clean pools live in src.data.folder_crops (shared with +# the Phase-2 runtime); the names are re-exported for the trainer's callers. +from src.data.folder_crops import ( # noqa: E402 + FolderCropDataset, infinite_batches as _infinite_batches, list_image_files, +) + + +class Phase1GraphObjective(nn.Module): + """Paired supervised objective; contains only the trainer-side type head.""" + + def __init__( + self, + node_dim: int = 256, + weights: Optional[LossWeights] = None, + texture_weighted_null: bool = False, + readout_dim: int = 0, + embed_temperature: float = 0.1, + embed_dim: int = 128, + embed_members: str = "all", + severity_floor: float = 0.0, + ood_global_margin: float = 0.5, + ): + super().__init__() + if float(severity_floor) < 0.0: + raise ValueError("severity_floor must be >= 0") + # v5e: pairs whose crop-level severity is below the floor carry no + # visible degradation; they are supervised as clean (free slots, + # zero severity) instead of forcing a hard type route. + self.severity_floor = float(severity_floor) + self.ood_global_margin = float(ood_global_margin) + if embed_members not in EMBED_MEMBERS: + raise ValueError("embed_members must be one of %r, got %r" % (EMBED_MEMBERS, embed_members)) + self.global_type_head = nn.Linear(node_dim, NUM_KNOWN) + self.weights = weights or LossWeights() + self.texture_weighted_null = bool(texture_weighted_null) + self.embed_temperature = float(embed_temperature) + # v5c: "known_clean" keeps the extra clean pool and the OOD batch out of + # the contrastive term (v5/v5b: clean+pool were 64 of 128 samples and + # unknown-as-negative pushed real snow/light rain into the free slot). + self.embed_members = str(embed_members) + self.embed_projector = ( + nn.Sequential(nn.Linear(readout_dim, embed_dim), nn.SiLU(), nn.Linear(embed_dim, embed_dim)) + if self.weights.embed > 0.0 and readout_dim > 0 else None + ) + + def forward( + self, + graph_degraded, + graph_clean, + degraded: torch.Tensor, + clean: torch.Tensor, + labels: torch.Tensor, + severity_targets: torch.Tensor, + pixel_q95: torch.Tensor, + clean_root: torch.Tensor, + graph_ood=None, + graph_extra_clean=None, + photometric_k: float = 0.2, + ) -> Dict[str, torch.Tensor]: + rows = torch.arange(labels.shape[0], device=labels.device) + floored = ( + severity_targets < self.severity_floor + if self.severity_floor > 0.0 + else torch.zeros_like(labels, dtype=torch.bool) + ) + kept = ~floored + kept_rows = rows[kept] + kept_labels = labels[kept] + any_kept = bool(kept.any()) + zero = graph_degraded.routing_probs.new_tensor(0.0) + if any_kept: + selected_probability = graph_degraded.routing_probs[kept_rows, kept_labels] + route = -selected_probability.clamp_min(1e-8).log().mean() + global_type = F.cross_entropy( + self.global_type_head(graph_degraded.global_condition[kept_rows]), kept_labels + ) + selected_severity = graph_degraded.severity_coords[kept_rows, kept_labels] + severity_selected = F.smooth_l1_loss(selected_severity, severity_targets[kept_rows]) + severity_mask = 1.0 - F.one_hot(kept_labels, NUM_KNOWN).to( + graph_degraded.severity_coords.dtype + ) + severity_inactive = ( + graph_degraded.severity_coords[kept_rows].square() * severity_mask + ).sum() / severity_mask.sum().clamp_min(1.0) + else: + route, global_type, severity_selected, severity_inactive = zero, zero, zero, zero + if bool(floored.any()): + # No visible degradation in the crop: every severity coordinate is 0. + severity_inactive = severity_inactive + graph_degraded.severity_coords[floored].square().mean() + severity = severity_selected + 0.1 * severity_inactive + + # The clean root is the fixed graph origin for this supervised v2 run. + # Detaching prevents the target from chasing the clean representation. + anchor = clean_root.detach().to( + graph_clean.global_condition.device + ).expand_as( + graph_clean.global_condition + ) + root = ( + F.smooth_l1_loss(graph_clean.global_condition, anchor) + + graph_clean.severity_coords.square().mean() + + graph_clean.spatial_maps.square().mean() + + graph_clean.unknown_residual.square().mean() + ) + content = F.smooth_l1_loss( + graph_degraded.content_latent, graph_clean.content_latent + ) + if any_kept: + unknown = ( + graph_degraded.routing_probs[kept_rows, NUM_KNOWN:].sum(dim=1).mean() + + 0.1 * graph_degraded.unknown_residual[kept_rows].square().mean() + ) + spatial, spatial_metrics = spatial_supervision_loss( + graph_degraded.spatial_maps[kept_rows], + degraded[kept_rows], + clean[kept_rows], + kept_labels, + pixel_q95, + ) + else: + unknown = zero + spatial = zero + spatial_metrics = {"spatial_selected_mae": 0.0, "spatial_inactive_activation": 0.0} + if bool(floored.any()): + floor_null = ( + -graph_degraded.routing_probs[floored, NUM_KNOWN:].sum(dim=1).clamp_min(1e-8).log().mean() + ) + else: + floor_null = zero + floor_fraction = float(floored.float().mean()) if labels.numel() else 0.0 + + # Free slots are the null/other detector: clean and synthetic-OOD + # inputs must route into them, otherwise the suppression term above + # kills the unseen-degradation mechanism entirely. + null_terms = -graph_clean.routing_probs[:, NUM_KNOWN:].sum(dim=1).clamp_min(1e-8).log() + if self.texture_weighted_null: + null_weights = texture_null_weights(clean.float()).to(null_terms.dtype) + null_route = (null_terms * null_weights).sum() / null_weights.sum() + else: + null_route = null_terms.mean() + if graph_ood is not None: + ood_route = ( + -graph_ood.routing_probs[:, NUM_KNOWN:] + .sum(dim=1) + .clamp_min(1e-8) + .log() + .mean() + ) + scale = math.sqrt(graph_degraded.unknown_residual.shape[1]) + known_norm = graph_degraded.unknown_residual.float().norm(dim=1) / scale + ood_norm = graph_ood.unknown_residual.float().norm(dim=1) / scale + unknown_margin = F.relu( + 0.1 + known_norm.mean() - ood_norm.mean() + ) + ood_route = ood_route + 0.1 * graph_ood.severity_coords.square().mean() + else: + ood_route = route.new_tensor(0.0) + unknown_margin = route.new_tensor(0.0) + ood_global = route.new_tensor(0.0) + if graph_ood is not None and self.weights.ood_global_margin > 0.0 and any_kept: + ood_global = ood_global_margin_loss( + graph_degraded.global_condition[kept_rows], kept_labels, + graph_ood.global_condition, margin=self.ood_global_margin, + ) + + # ---- v5 terms --------------------------------------------------- # + embed = route.new_tensor(0.0) + if self.embed_projector is not None and getattr(graph_degraded, "readout", None) is not None: + feats = [graph_degraded.readout, graph_clean.readout] + degraded_labels = torch.where(floored, torch.full_like(labels, CLEAN_CLASS), labels) + labs = [degraded_labels, torch.full_like(labels, CLEAN_CLASS)] + include_pools = self.embed_members == "all" + if include_pools and graph_extra_clean is not None: + feats.append(graph_extra_clean.readout) + labs.append(torch.full((graph_extra_clean.readout.shape[0],), CLEAN_CLASS, dtype=labels.dtype, device=labels.device)) + if include_pools and graph_ood is not None: + feats.append(graph_ood.readout) + labs.append(torch.full((graph_ood.readout.shape[0],), UNKNOWN_CLASS, dtype=labels.dtype, device=labels.device)) + z = self.embed_projector(torch.cat(feats, dim=0).float()) + embed = supervised_contrastive_loss( + z, torch.cat(labs, dim=0), self.embed_temperature, unknown_label=UNKNOWN_CLASS + ) + photometric = route.new_tensor(0.0) + if self.weights.photometric > 0.0 and getattr(graph_degraded, "photometric_shift", None) is not None: + targets = photometric_shift_targets(degraded, clean, photometric_k) + terms = [F.smooth_l1_loss(graph_degraded.photometric_shift.float(), targets)] + terms.append(graph_clean.photometric_shift.float().abs().mean()) + if graph_extra_clean is not None and graph_extra_clean.photometric_shift is not None: + terms.append(graph_extra_clean.photometric_shift.float().abs().mean()) + photometric = sum(terms) / len(terms) + extra_null = route.new_tensor(0.0) + if graph_extra_clean is not None: + extra_null = ( + -graph_extra_clean.routing_probs[:, NUM_KNOWN:].sum(dim=1).clamp_min(1e-8).log().mean() + + graph_extra_clean.severity_coords.square().mean() + + 0.1 * graph_extra_clean.unknown_residual.square().mean() + ) + + weighted = { + "route": route * self.weights.route, + "global_type": global_type * self.weights.global_type, + "severity": severity * self.weights.severity, + "root": root * self.weights.root, + "content": content * self.weights.content, + "unknown": unknown * self.weights.unknown, + "spatial": spatial * self.weights.spatial, + "null_route": null_route * self.weights.null_route, + "ood_route": ood_route * self.weights.ood_route, + "unknown_margin": unknown_margin * self.weights.unknown_margin, + "embed": embed * self.weights.embed, + "photometric": photometric * self.weights.photometric, + "extra_null": extra_null * self.weights.extra_null, + "floor_null": floor_null * self.weights.null_route, + "ood_global": ood_global * self.weights.ood_global_margin, + } + total = sum(weighted.values()) + result = dict(weighted) + result["total"] = total + result["floor_fraction"] = total.new_tensor(floor_fraction) + result["spatial_selected_mae"] = total.new_tensor( + spatial_metrics["spatial_selected_mae"] + ) + result["spatial_inactive_activation"] = total.new_tensor( + spatial_metrics["spatial_inactive_activation"] + ) + return result + + +def _mean(values: Sequence[float]) -> float: + return float(sum(values) / len(values)) if values else 0.0 + + +def _average_ranks(values: Sequence[float]) -> List[float]: + order = sorted(range(len(values)), key=lambda index: (values[index], index)) + ranks = [0.0] * len(values) + position = 0 + while position < len(order): + end = position + 1 + while end < len(order) and values[order[end]] == values[order[position]]: + end += 1 + average = (position + 1 + end) / 2.0 + for ranked_index in order[position:end]: + ranks[ranked_index] = average + position = end + return ranks + + +def _pearson(left: Sequence[float], right: Sequence[float]) -> float: + if len(left) != len(right): + return 0.0 + finite_pairs = [ + (a, b) + for a, b in zip(left, right) + if math.isfinite(a) and math.isfinite(b) + ] + if len(finite_pairs) < 2: + return 0.0 + left = [a for a, _ in finite_pairs] + right = [b for _, b in finite_pairs] + left_mean, right_mean = _mean(left), _mean(right) + centered_left = [value - left_mean for value in left] + centered_right = [value - right_mean for value in right] + denominator = math.sqrt( + sum(value * value for value in centered_left) + * sum(value * value for value in centered_right) + ) + if denominator <= 1e-12: + return 0.0 + return float( + sum(a * b for a, b in zip(centered_left, centered_right)) / denominator + ) + + +def _spearman(left: Sequence[float], right: Sequence[float]) -> float: + return _pearson(_average_ranks(left), _average_ranks(right)) + + +def compute_validation_metrics( + labels: Sequence[int], + predictions: Sequence[int], + severity_targets: Sequence[float], + severity_predictions: Sequence[float], + unknown_routing: Sequence[float], + entropies: Sequence[float], + losses: Sequence[float], + spatial_mae: Sequence[float], + inactive_activation: Sequence[float], + clean_root_error: Optional[Sequence[float]] = None, + null_accuracy_clean: Optional[float] = None, + null_accuracy_ood: Optional[float] = None, + unknown_norm_gap: Optional[float] = None, +) -> Dict[str, object]: + lengths = { + len(labels), len(predictions), len(severity_targets), + len(severity_predictions), len(unknown_routing), len(entropies), + len(losses), len(spatial_mae), len(inactive_activation), + } + if len(lengths) != 1 or not labels: + raise ValueError("validation metric arrays must be aligned and non-empty") + if clean_root_error is None: + clean_root_error = [0.0] * len(labels) + if len(clean_root_error) != len(labels): + raise ValueError("clean_root_error must align with labels") + + confusion = [[0 for _ in range(NUM_GRAPH_ROUTES)] for _ in range(NUM_KNOWN)] + for truth, prediction in zip(labels, predictions): + if truth < 0 or truth >= NUM_KNOWN: + raise ValueError("truth label outside known classes") + if prediction < 0 or prediction >= NUM_GRAPH_ROUTES: + raise ValueError("prediction outside six graph routes") + confusion[truth][prediction] += 1 + + per_class: Dict[str, Dict[str, float]] = {} + f1_values, recalls = [], [] + for class_index, class_name in enumerate(BRANCH_ORDER): + indices = [i for i, label in enumerate(labels) if label == class_index] + support = len(indices) + true_positive = confusion[class_index][class_index] + false_negative = support - true_positive + false_positive = sum( + confusion[row][class_index] + for row in range(NUM_KNOWN) + if row != class_index + ) + precision = true_positive / max(1, true_positive + false_positive) + recall = true_positive / max(1, true_positive + false_negative) + f1 = 0.0 if precision + recall == 0 else 2 * precision * recall / (precision + recall) + if support > 0: + f1_values.append(f1) + recalls.append(recall) + targets = [severity_targets[i] for i in indices] + estimates = [severity_predictions[i] for i in indices] + per_class[class_name] = { + "support": float(support), + "accuracy": float(recall), + "precision": float(precision), + "f1": float(f1), + "severity_mae": _mean( + [abs(a - b) for a, b in zip(targets, estimates)] + ), + "severity_spearman": _spearman(targets, estimates), + "unknown_routing": _mean([unknown_routing[i] for i in indices]), + "routing_entropy": _mean([entropies[i] for i in indices]), + "loss": _mean([losses[i] for i in indices]), + "spatial_selected_mae": _mean([spatial_mae[i] for i in indices]), + "spatial_inactive_activation": _mean( + [inactive_activation[i] for i in indices] + ), + "clean_root_error": _mean([clean_root_error[i] for i in indices]), + } + + return { + "sample_count": len(labels), + "accuracy": sum(int(a == b) for a, b in zip(labels, predictions)) / len(labels), + "macro_f1": _mean(f1_values), + "balanced_accuracy": _mean(recalls), + "severity_mae": _mean( + [abs(a - b) for a, b in zip(severity_targets, severity_predictions)] + ), + "severity_spearman": _spearman(severity_targets, severity_predictions), + "unknown_routing": _mean(unknown_routing), + "unknown_prediction_rate": sum( + int(prediction >= NUM_KNOWN) for prediction in predictions + ) / len(predictions), + "routing_entropy": _mean(entropies), + "loss": _mean(losses), + "spatial_selected_mae": _mean(spatial_mae), + "spatial_inactive_activation": _mean(inactive_activation), + "clean_root_error": _mean(clean_root_error), + "null_accuracy_clean": ( + float(null_accuracy_clean) if null_accuracy_clean is not None else 0.0 + ), + "null_accuracy_ood": ( + float(null_accuracy_ood) if null_accuracy_ood is not None else 0.0 + ), + "unknown_norm_gap": ( + float(unknown_norm_gap) if unknown_norm_gap is not None else 0.0 + ), + "confusion_matrix": confusion, + "per_class": per_class, + } + + +def _per_sample_eval_values( + graph_degraded, + graph_clean, + degraded: torch.Tensor, + clean: torch.Tensor, + labels: torch.Tensor, + severity: torch.Tensor, + pixel_q95: torch.Tensor, + clean_root: torch.Tensor, +) -> Dict[str, torch.Tensor]: + rows = torch.arange(labels.shape[0], device=labels.device) + selected_severity = graph_degraded.severity_coords[rows, labels] + residual = (degraded - clean).abs().mean(dim=1, keepdim=True) + target_map = F.adaptive_avg_pool2d(residual, graph_degraded.spatial_maps.shape[-2:]) + scales = pixel_q95.index_select(0, labels).view(-1, 1, 1, 1).clamp_min(1e-6) + target_map = (target_map / scales).clamp(0, 1) + selected_map = graph_degraded.spatial_maps[rows, labels].unsqueeze(1) + active = F.one_hot(labels, NUM_KNOWN).to(degraded.dtype).view(-1, NUM_KNOWN, 1, 1) + inactive = (graph_degraded.spatial_maps * (1 - active)).sum(dim=(1, 2, 3)) / ( + (NUM_KNOWN - 1) * graph_degraded.spatial_maps.shape[-2] * graph_degraded.spatial_maps.shape[-1] + ) + root = clean_root.to(degraded.device).expand_as(graph_clean.global_condition) + root_error = ( + (graph_clean.global_condition - root).abs().mean(dim=1) + + graph_clean.severity_coords.abs().mean(dim=1) + + graph_clean.spatial_maps.abs().mean(dim=(1, 2, 3)) + + graph_clean.unknown_residual.abs().mean(dim=1) + ) + route_loss = -graph_degraded.routing_probs[rows, labels].clamp_min(1e-8).log() + spatial_mae = (selected_map - target_map).abs().mean(dim=(1, 2, 3)) + sample_loss = route_loss + (selected_severity - severity).abs() + 0.1 * spatial_mae + 0.2 * root_error + entropy = -( + graph_degraded.routing_probs + * graph_degraded.routing_probs.clamp_min(1e-8).log() + ).sum(dim=1) + return { + "predictions": graph_degraded.routing_probs.argmax(dim=1), + "severity_predictions": selected_severity, + "unknown_routing": graph_degraded.routing_probs[:, NUM_KNOWN:].sum(dim=1), + "entropy": entropy, + "loss": sample_loss, + "spatial_mae": spatial_mae, + "inactive_activation": inactive, + "clean_root_error": root_error, + } + + +def _sanitize_json(payload: object) -> object: + """Replace non-finite floats with None so logging can never abort a run.""" + if isinstance(payload, float): + return payload if math.isfinite(payload) else None + if isinstance(payload, dict): + return {key: _sanitize_json(value) for key, value in payload.items()} + if isinstance(payload, (list, tuple)): + return [_sanitize_json(value) for value in payload] + return payload + + +def _atomic_write_json(path: Path, payload: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name( + ".%s.%d.%d.tmp" % (path.name, os.getpid(), time.time_ns()) + ) + try: + temporary.write_text( + json.dumps( + _sanitize_json(payload), indent=2, sort_keys=True, allow_nan=False + ), + encoding="utf-8", + ) + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +def _atomic_torch_save(path: Path, payload: object) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name( + ".%s.%d.%d.tmp" % (path.name, os.getpid(), time.time_ns()) + ) + try: + torch.save(payload, str(temporary)) + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +def make_checkpoint( + model: nn.Module, + aux_classifier: nn.Module, + optimizer, + scheduler, + scaler, + epoch: int, + best_score: float, + config: Mapping[str, object], + provenance: Mapping[str, object], + history: Sequence[Mapping[str, object]], + severity_calibration: Mapping[str, Mapping[str, float]], + raw_model: Optional[nn.Module] = None, +) -> Dict[str, object]: + trainer_state: Dict[str, object] = { + "global_type_head": aux_classifier.state_dict(), + } + if raw_model is not None: + # v5d: ``model`` is the EMA shadow (what Phase-2 loads); keep the live + # weights trainer-side so a resume does not restart from the average. + trainer_state["raw_model_state_dict"] = raw_model.state_dict() + if optimizer is not None: + trainer_state["optimizer"] = optimizer.state_dict() + if scheduler is not None: + trainer_state["scheduler"] = scheduler.state_dict() + if scaler is not None: + trainer_state["grad_scaler"] = scaler.state_dict() + return { + "schema_version": 2, + "phase": 1, + "epoch": int(epoch), + "best_score": float(best_score), + # Phase 2 consumes this exact key with strict state loading. + "model_state_dict": model.state_dict(), + "trainer_state": trainer_state, + "branch_order": list(BRANCH_ORDER), + "aggregation_version": AGGREGATION_VERSION, + "config": dict(config), + "provenance": dict(provenance), + "history": list(history), + "severity_calibration": dict(severity_calibration), + } + + +def _record_counts(records: Sequence[PairRecord]) -> Dict[str, object]: + by_class = {name: 0 for name in BRANCH_ORDER} + by_dataset: Dict[str, int] = {} + unique_groups: Dict[str, set] = {} + for record in records: + by_class[record.degradation] += 1 + by_dataset[record.dataset] = by_dataset.get(record.dataset, 0) + 1 + unique_groups.setdefault(record.dataset, set()).add(record.split_group) + return { + "pairs": len(records), + "by_class": by_class, + "by_dataset": by_dataset, + "unique_groups_by_dataset": { + name: len(groups) for name, groups in sorted(unique_groups.items()) + }, + } + + +def _split_digest(records: Sequence[PairRecord]) -> str: + digest = hashlib.sha256(b"SCDC_PHASE1_SPLIT_V2\0") + for record in records: + digest.update(record.record_id.encode("ascii")) + digest.update(b"\n") + return digest.hexdigest() + + +def make_provenance(args: argparse.Namespace, splits: DataSplits) -> Dict[str, object]: + return { + "schema_version": 2, + "branch_order": list(BRANCH_ORDER), + "deployed_positional_mapping": { + "blur": "rain", "noise": "noise", "jpeg": "haze", "lowlight": "lowlight" + }, + "aggregation_version": AGGREGATION_VERSION, + "rain_quarantine_manifest": str(Path(args.quarantine_manifest).resolve()), + "rain_quarantine_sha256": sha256_file(Path(args.quarantine_manifest)), + "quarantined_rain_train_pairs": splits.quarantine_count, + "split_policy": { + "Rain13K": "quarantined train; Test100 val; Test1200 locked test", + "LOLv2": "Train only train; Test only val", + "RESIDE": "sorted first5000; first100 val; exclude every val source from train", + "SIDD": "scene_number grouped; SHA256 scene order; first8/next1/last1 scenes", + }, + "locked_test_policy": "never decoded until best selection and --run-final-test", + "counts": { + "train": _record_counts(splits.train), + "val": _record_counts(splits.val), + "locked_test": _record_counts(splits.locked_test), + }, + "split_digests": { + "train": _split_digest(splits.train), + "val": _split_digest(splits.val), + "locked_test": _split_digest(splits.locked_test), + }, + "crop_policy": str(getattr(args, "crop_policy", "resize")), + "sidd_cache": { + "version": CACHE_VERSION, + "format": ( + "paired RGB uint8 PNG native-resolution crops (%d random per train pair, centre for eval)" + % int(getattr(args, "sidd_native_crops", 32)) + if str(getattr(args, "crop_policy", "resize")) == "native" + else "paired RGB uint8 PNG after shorter-side resize + center crop" + ), + "prebuild": "main process, train and val only before optimization", + }, + "severity": { + "proxy": "paired RGB residual MAE", + "normalization": "per-domain train-only p05/p95", + "spatial_scale": "per-domain train-only residual-pixel q95", + }, + } + + +def _worker_seed(worker_id: int) -> None: + seed = torch.initial_seed() % (2 ** 32) + random.seed(seed) + np.random.seed(seed) + + +def _loader_kwargs(args: argparse.Namespace, device: torch.device) -> Dict[str, object]: + kwargs: Dict[str, object] = { + "num_workers": args.workers, + "pin_memory": device.type == "cuda", + "worker_init_fn": _worker_seed, + } + if args.workers > 0: + kwargs["persistent_workers"] = True + kwargs["prefetch_factor"] = args.prefetch_factor + return kwargs + + +def build_loaders( + args: argparse.Namespace, + splits: DataSplits, + calibration: Mapping[str, Mapping[str, float]], + device: torch.device, + cache_root: Path, +) -> Tuple[DataLoader, DataLoader, PairDataset, PairDataset]: + crop_policy = str(getattr(args, "crop_policy", "resize")) + sidd_native_crops = int(getattr(args, "sidd_native_crops", 32)) + train_dataset = PairDataset( + splits.train, args.image_size, calibration, cache_root / "train", + crop_policy=crop_policy, training=True, sidd_native_crops=sidd_native_crops, + crop_select=str(getattr(args, "crop_select", "random")), + crop_candidates=int(getattr(args, "crop_candidates", 4)), + ) + val_dataset = PairDataset( + splits.val, args.image_size, calibration, cache_root / "val", + crop_policy=crop_policy, training=False, sidd_native_crops=sidd_native_crops, + ) + # Build once in the main process; workers never touch 6.6GB raw SIDD pairs. + train_dataset.prepare_cache() + val_dataset.prepare_cache() + steps = args.steps_per_epoch or int(math.ceil(len(train_dataset) / args.batch_size)) + batch_sampler = BalancedBatchSampler( + [record.label for record in splits.train], + batch_size=args.batch_size, + steps=steps, + seed=args.seed, + yield_seeds=(crop_policy == "native"), + ) + kwargs = _loader_kwargs(args, device) + train_loader = DataLoader(train_dataset, batch_sampler=batch_sampler, **kwargs) + val_loader = DataLoader( + val_dataset, + batch_size=args.eval_batch_size, + shuffle=False, + drop_last=False, + **kwargs + ) + return train_loader, val_loader, train_dataset, val_dataset + + +@torch.no_grad() +def evaluate( + model: BlindDegradationGraphEncoder, + loader: DataLoader, + device: torch.device, + pixel_q95: torch.Tensor, + real_ood_loader: Optional[DataLoader] = None, +) -> Dict[str, object]: + model.eval() + collected: Dict[str, List[float]] = { + "labels": [], "predictions": [], "severity_targets": [], + "severity_predictions": [], "unknown_routing": [], "entropies": [], + "losses": [], "spatial_mae": [], "inactive_activation": [], + "clean_root_error": [], + } + for batch in loader: + degraded = batch["degraded"].to(device, non_blocking=True) + clean = batch["clean"].to(device, non_blocking=True) + labels = batch["label"].to(device, non_blocking=True).long() + severity = batch["severity"].to(device, non_blocking=True).float() + graph_degraded = model.forward_student(degraded) + graph_clean = forward_clean_bn_safe(model, clean) + values = _per_sample_eval_values( + graph_degraded, graph_clean, degraded, clean, labels, severity, + pixel_q95.to(device), model.clean_root(), + ) + collected["labels"].extend(labels.cpu().tolist()) + collected["severity_targets"].extend(severity.cpu().tolist()) + mapping = { + "predictions": "predictions", + "severity_predictions": "severity_predictions", + "unknown_routing": "unknown_routing", + "entropy": "entropies", + "loss": "losses", + "spatial_mae": "spatial_mae", + "inactive_activation": "inactive_activation", + "clean_root_error": "clean_root_error", + } + for source, target in mapping.items(): + collected[target].extend(values[source].detach().cpu().tolist()) + + # Null/OOD routing audit: clean inputs and deterministic synthetic OOD + # must land in the free slots, and OOD unknown-residual norms must sit + # above the in-domain norms for novelty scoring to have the right sign. + null_hits, ood_hits, null_total = 0, 0, 0 + known_norms: List[float] = [] + ood_norms: List[float] = [] + ood_generator = torch.Generator() + ood_generator.manual_seed(20260831) + for batch_index, batch in enumerate(loader): + clean = batch["clean"].to(device, non_blocking=True) + degraded = batch["degraded"].to(device, non_blocking=True) + kind = OOD_KINDS[batch_index % len(OOD_KINDS)] + ood = synthesize_ood(clean, kind, ood_generator) + graph_clean = model.forward_student(clean) + graph_ood = model.forward_student(ood) + graph_known = model.forward_student(degraded) + null_hits += int( + (graph_clean.routing_probs.argmax(dim=1) >= NUM_KNOWN).sum() + ) + ood_hits += int( + (graph_ood.routing_probs.argmax(dim=1) >= NUM_KNOWN).sum() + ) + null_total += clean.shape[0] + scale = math.sqrt(graph_known.unknown_residual.shape[1]) + known_norms.extend( + (graph_known.unknown_residual.norm(dim=1) / scale).cpu().tolist() + ) + ood_norms.extend( + (graph_ood.unknown_residual.norm(dim=1) / scale).cpu().tolist() + ) + metrics = compute_validation_metrics( + **collected, + null_accuracy_clean=null_hits / max(1, null_total), + null_accuracy_ood=ood_hits / max(1, null_total), + unknown_norm_gap=_mean(ood_norms) - _mean(known_norms), + ) + if real_ood_loader is not None: + # Held-out REAL unknown degradation (Snow100K synthetic snow): the + # synthetic-blob OOD score above did not transfer to it (ll_v3: 0.50). + real_hits, real_total, real_norms = 0, 0, [] + for images in real_ood_loader: + graph_real = model.forward_student(images.to(device, non_blocking=True)) + real_hits += int((graph_real.routing_probs.argmax(dim=1) >= NUM_KNOWN).sum()) + real_total += images.shape[0] + scale = math.sqrt(graph_real.unknown_residual.shape[1]) + real_norms.extend((graph_real.unknown_residual.norm(dim=1) / scale).cpu().tolist()) + metrics = dict(metrics) + metrics["null_accuracy_ood_real"] = real_hits / max(1, real_total) + metrics["unknown_norm_gap_real"] = _mean(real_norms) - _mean(known_norms) + return metrics + + +SELECTION_MODES: Tuple[str, ...] = ("f1", "balanced") + + +def selection_key( + metrics: Mapping[str, object], mode: str = "f1" +) -> Tuple[float, float, float, float, float]: + """Lexicographic selection: F1 first, then null/OOD routing, then + severity Spearman; MAE terms break exact ties. Missing keys default to + zero so legacy metric dictionaries keep their original ordering. + + ``mode="balanced"`` (v5d) puts ``0.5 * F1 + 0.5 * null_mean`` first so a + checkpoint cannot win on routing alone while failing null detection.""" + if mode not in SELECTION_MODES: + raise ValueError("selection mode must be one of %r, got %r" % (SELECTION_MODES, mode)) + + def _finite(value: object, fallback: float) -> float: + number = float(value) + return number if math.isfinite(number) else fallback + + null_terms = [ + _finite(metrics.get("null_accuracy_clean", 0.0), 0.0), + _finite(metrics.get("null_accuracy_ood", 0.0), 0.0), + ] + if "null_accuracy_ood_real" in metrics: + null_terms.append(_finite(metrics.get("null_accuracy_ood_real", 0.0), 0.0)) + null_mean = sum(null_terms) / len(null_terms) + f1 = _finite(metrics["macro_f1"], float("-inf")) + primary = f1 if mode == "f1" else (0.5 * f1 + 0.5 * null_mean if math.isfinite(f1) else f1) + return ( + primary, + null_mean, + _finite(metrics.get("severity_spearman", 0.0), float("-inf")), + -_finite(metrics["severity_mae"], float("inf")), + -_finite(metrics["spatial_selected_mae"], float("inf")), + ) + + +def train_one_epoch( + model: BlindDegradationGraphEncoder, + objective: Phase1GraphObjective, + loader: DataLoader, + optimizer: torch.optim.Optimizer, + scaler: torch.cuda.amp.GradScaler, + device: torch.device, + pixel_q95: torch.Tensor, + amp_enabled: bool, + max_grad_norm: float, + seed: int = 0, + epoch: int = 0, + noise_aug_prob: float = 0.0, + noise_calibration: Optional[Mapping[str, float]] = None, + residual_bank: Optional[List[torch.Tensor]] = None, + noise_aug_synthetic_prob: float = 0.5, + noise_aug_gain_max: float = 1.4, + real_ood_iter: Optional[Iterator[torch.Tensor]] = None, + real_ood_prob: float = 0.0, + extra_clean_iter: Optional[Iterator[torch.Tensor]] = None, + ema: Optional[WeightEMA] = None, +) -> Dict[str, float]: + model.train() + objective.train() + photometric_k = ( + model.photometric_branch.k.detach() if getattr(model, "photometric_branch", None) is not None else 0.2 + ) + synthetic_kinds = OOD_KINDS if real_ood_iter is None else tuple(k for k in OOD_KINDS if k != "snow") + totals: Dict[str, float] = {} + batches = 0 + for batch_index, batch in enumerate(loader): + degraded = batch["degraded"].to(device, non_blocking=True) + clean = batch["clean"].to(device, non_blocking=True) + labels = batch["label"].to(device, non_blocking=True).long() + severity = batch["severity"].to(device, non_blocking=True).float() + ood_generator = torch.Generator() + ood_generator.manual_seed( + (int(seed) * 1000003 + int(epoch) * 1009 + batch_index) % (2 ** 63 - 1) + ) + if noise_aug_prob > 0.0 and noise_calibration is not None: + # Keep a rolling bank of REAL SIDD residuals for transplanting. + if residual_bank is not None: + real = (labels == NOISE_INDEX).nonzero(as_tuple=True)[0] + for row in real.tolist()[:4]: + residual_bank.append((degraded[row] - clean[row]).detach()) + if len(residual_bank) > 64: + residual_bank.pop(0) + degraded, labels, severity, aug_mask = apply_noise_positives( + degraded, clean, labels, severity, noise_aug_prob, + ood_generator, noise_calibration, residual_bank, + synthetic_prob=noise_aug_synthetic_prob, gain_max=noise_aug_gain_max, + ) + totals["noise_aug_samples"] = totals.get("noise_aug_samples", 0.0) + float(aug_mask.sum()) + use_real_ood = ( + real_ood_iter is not None + and float(torch.rand(1, generator=ood_generator)) < float(real_ood_prob) + ) + if use_real_ood: + ood = next(real_ood_iter).to(device, non_blocking=True) + totals["ood_real_batches"] = totals.get("ood_real_batches", 0.0) + 1.0 + else: + ood_kind = synthetic_kinds[batch_index % len(synthetic_kinds)] + ood = synthesize_ood(clean, ood_kind, ood_generator) + extra_clean = ( + next(extra_clean_iter).to(device, non_blocking=True) + if extra_clean_iter is not None else None + ) + optimizer.zero_grad(set_to_none=True) + with torch.cuda.amp.autocast(enabled=amp_enabled): + graph_degraded = model.forward_student(degraded) + graph_clean = forward_clean_bn_safe(model, clean) + graph_ood = forward_clean_bn_safe(model, ood) + graph_extra = ( + forward_clean_bn_safe(model, extra_clean) if extra_clean is not None else None + ) + losses = objective( + graph_degraded, graph_clean, degraded, clean, labels, severity, + pixel_q95.to(device), model.clean_root(), + graph_ood=graph_ood, graph_extra_clean=graph_extra, + photometric_k=photometric_k, + ) + # A single non-finite batch must neither reach the optimizer nor + # poison the epoch metrics (a NaN in history.json aborts the run). + if not bool(torch.isfinite(losses["total"].detach())): + totals["nonfinite_batches"] = totals.get("nonfinite_batches", 0.0) + 1.0 + optimizer.zero_grad(set_to_none=True) + continue + scaler.scale(losses["total"]).backward() + scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_( + list(model.parameters()) + list(objective.parameters()), max_grad_norm + ) + scaler.step(optimizer) + scaler.update() + if ema is not None: + ema.update(model) + batches += 1 + for name, value in losses.items(): + totals[name] = totals.get(name, 0.0) + float(value.detach().item()) + averaged = { + name: value / max(1, batches) + for name, value in totals.items() + if name != "nonfinite_batches" + } + averaged["nonfinite_batches"] = totals.get("nonfinite_batches", 0.0) + if getattr(model, "photometric_branch", None) is not None: + averaged["photometric_k"] = float(model.photometric_branch.k.detach()) + return averaged + + +def assert_phase2_contract(model: BlindDegradationGraphEncoder) -> None: + clone = BlindDegradationGraphEncoder(model.config) + clone.load_state_dict(model.state_dict(), strict=True) + if clone.state_predictor.num_total != NUM_GRAPH_ROUTES: + raise RuntimeError("Phase2 contract requires six graph routes") + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Leakage-safe Phase-1 graph encoder trainer/evaluator" + ) + parser.add_argument("--data-root", default=str(DEFAULT_DATA_ROOT)) + parser.add_argument("--rain13k-root", default=str(DEFAULT_RAIN_ROOT)) + parser.add_argument("--quarantine-manifest", default=str(DEFAULT_QUARANTINE)) + parser.add_argument("--output-dir", default=str(DEFAULT_OUTPUT_DIR)) + parser.add_argument("--cache-root", default=None) + parser.add_argument("--epochs", type=int, default=50) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--eval-batch-size", type=int, default=16) + parser.add_argument("--steps-per-epoch", type=int, default=500) + parser.add_argument("--learning-rate", type=float, default=1e-4) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--max-grad-norm", type=float, default=1.0) + parser.add_argument("--image-size", type=int, default=256) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument("--prefetch-factor", type=int, default=2) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--device", default="cuda") + parser.add_argument("--no-amp", action="store_true") + parser.add_argument( + "--noise-aug-prob", type=float, default=0.0, + help="per-sample probability of turning a non-noise pair into a " + "synthetic/transplanted noise pair (noise-concept diversification)", + ) + parser.add_argument( + "--noise-aug-synthetic-prob", type=float, default=0.5, + help="share of noise positives drawn from the Poisson-Gaussian model " + "(the rest transplant real SIDD residuals); 0 = transplant only", + ) + parser.add_argument( + "--noise-aug-gain-max", type=float, default=1.4, + help="upper bound of the residual-transplant gain (lower bound 0.5)", + ) + parser.add_argument( + "--texture-null", action="store_true", + help="weight the clean->null routing loss by high-frequency texture", + ) + parser.add_argument("--reside-limit", type=int, default=5000) + parser.add_argument("--reside-val-count", type=int, default=100) + parser.add_argument("--allow-count-mismatch", action="store_true") + parser.add_argument("--run-final-test", action="store_true") + parser.add_argument("--eval-only", action="store_true") + parser.add_argument("--checkpoint", default=None) + # ---- v5: photometric branch, metric separation, real unknowns -------- # + parser.add_argument("--photometric", action="store_true", + help="add the HVI PhotometricBranch (colour/exposure state + shift head)") + parser.add_argument("--photometric-dim", type=int, default=128) + parser.add_argument("--embed-weight", type=float, default=0.0, + help="supervised-contrastive weight on the readout embedding (0 = off)") + parser.add_argument("--embed-temperature", type=float, default=0.1) + parser.add_argument("--photometric-weight", type=float, default=0.0, + help="weight of the supervised photometric-shift head (0 = off)") + parser.add_argument("--ood-real-root", default=None, + help="folder of REAL unknown-degradation images (e.g. Snow100K synthetic) used as OOD") + parser.add_argument("--ood-real-prob", type=float, default=0.5, + help="probability that a step's OOD batch is drawn from --ood-real-root") + parser.add_argument("--ood-real-val-count", type=int, default=512, + help="last N files of --ood-real-root (sorted) held out for null_accuracy_ood_real") + parser.add_argument("--extra-clean-root", default=None, + help="folder of extra clean images (e.g. Snow100K gt) for the null objective") + parser.add_argument("--extra-null-weight", type=float, default=0.15) + # ---- v5c: native-resolution crops (Phase-2 parity), SupCon membership -- # + parser.add_argument("--crop-policy", choices=CROP_POLICIES, default="resize", + help="resize = legacy shorter-side resize + centre crop (SIDD ~12x " + "downsampled); native = random native crops for training, " + "centre crop for eval, exactly like Phase-2") + parser.add_argument("--sidd-native-crops", type=int, default=32, + help="native 256 crops cached per SIDD training pair (eval: 1 centre crop)") + parser.add_argument("--embed-members", choices=EMBED_MEMBERS, default="all", + help="all = SupCon over degraded+clean+extra clean pool+OOD (v5); " + "known_clean = degraded + paired clean only") + # ---- v5d: EMA weights for eval/selection, balanced checkpoint selection # + parser.add_argument("--ema-decay", type=float, default=0.0, + help="EMA decay for the evaluated/selected weights (0 = off; v5d 0.999)") + parser.add_argument("--selection", choices=SELECTION_MODES, default="f1", + help="f1 = macro-F1 first (legacy); balanced = 0.5*F1 + 0.5*mean(null terms)") + # ---- v5e: residual-aware training crops, severity floor ---------------- # + parser.add_argument("--crop-select", choices=CROP_SELECT, default="random", + help="residual = keep the max-residual crop of --crop-candidates native crops (train only)") + parser.add_argument("--crop-candidates", type=int, default=4) + parser.add_argument("--ll-oriented-bands", action="store_true", + help="v6: add LH1/HL1 log-MAD + anisotropy to the LL global branch stats (rain vs snow/noise)") + parser.add_argument("--root-weight", type=float, default=None, + help="v6: override LossWeights.root (clean global_condition -> clean root); default 0.2") + parser.add_argument("--ood-global-margin-weight", type=float, default=0.0, + help="v6: weight of the hinge keeping real-OOD global vectors >= margin from known-type centroids") + parser.add_argument("--ood-global-margin", type=float, default=0.5, + help="v6: the margin (L2-normalised space, 0..2)") + parser.add_argument("--severity-floor", type=float, default=0.0, + help="training pairs with crop severity below this are supervised as clean (0 = off)") + return parser + + +def _configuration( + args: argparse.Namespace, graph_config: GraphConfig, weights: LossWeights +) -> Dict[str, object]: + return { + "cli": { + key: str(value) if isinstance(value, Path) else value + for key, value in vars(args).items() + }, + "graph_config": dict(vars(graph_config)), + "loss_weights": asdict(weights), + "branch_order": list(BRANCH_ORDER), + "aggregation_version": AGGREGATION_VERSION, + "phase1_arch": ( + "ll_v3" if getattr(graph_config, "use_ll_global", False) else "v2" + ), + } + + +def _pixel_q95_tensor( + calibration: Mapping[str, Mapping[str, float]] +) -> torch.Tensor: + return torch.tensor( + [float(calibration[name]["pixel_q95"]) for name in BRANCH_ORDER], + dtype=torch.float32, + ) + + +def _make_eval_loader( + args: argparse.Namespace, + records: Sequence[PairRecord], + calibration: Mapping[str, Mapping[str, float]], + device: torch.device, + cache_dir: Path, + prebuild_cache: bool, +) -> DataLoader: + dataset = PairDataset( + records, args.image_size, calibration, cache_dir, + crop_policy=str(getattr(args, "crop_policy", "resize")), training=False, + sidd_native_crops=int(getattr(args, "sidd_native_crops", 32)), + ) + if prebuild_cache: + dataset.prepare_cache() + return DataLoader( + dataset, + batch_size=args.eval_batch_size, + shuffle=False, + drop_last=False, + **_loader_kwargs(args, device) + ) + + +def _load_encoder_checkpoint( + checkpoint_path: Path, + model: BlindDegradationGraphEncoder, + objective: Optional[Phase1GraphObjective], + device: torch.device, +) -> Dict[str, object]: + checkpoint = torch.load(str(checkpoint_path), map_location=device) + if "model_state_dict" not in checkpoint: + raise ValueError("checkpoint lacks Phase2-compatible model_state_dict") + if checkpoint.get("aggregation_version") != AGGREGATION_VERSION: + raise ValueError( + "checkpoint aggregation_version must be %d, got %r" + % (AGGREGATION_VERSION, checkpoint.get("aggregation_version")) + ) + if tuple(checkpoint.get("branch_order", ())) != BRANCH_ORDER: + raise ValueError( + "checkpoint branch_order must be %r, got %r" + % (BRANCH_ORDER, checkpoint.get("branch_order")) + ) + model.load_state_dict(checkpoint["model_state_dict"], strict=True) + if objective is not None: + trainer_state = checkpoint.get("trainer_state", {}) + if "global_type_head" in trainer_state: + objective.global_type_head.load_state_dict( + trainer_state["global_type_head"], strict=True + ) + return checkpoint + + +def _run_locked_test( + args: argparse.Namespace, + model: BlindDegradationGraphEncoder, + splits: DataSplits, + calibration: Mapping[str, Mapping[str, float]], + device: torch.device, + cache_root: Path, + output_dir: Path, +) -> Dict[str, object]: + # This is the first point at which locked SIDD scene008 / Rain Test1200 decode. + loader = _make_eval_loader( + args, + splits.locked_test, + calibration, + device, + cache_root / "locked_test", + prebuild_cache=True, + ) + metrics = evaluate(model, loader, device, _pixel_q95_tensor(calibration)) + _atomic_write_json(output_dir / "locked_test_metrics.json", metrics) + return metrics + + +def main(argv: Optional[Sequence[str]] = None) -> int: + args = build_parser().parse_args(argv) + if args.epochs < 0: + raise ValueError("epochs must be non-negative") + if args.image_size <= 0: + raise ValueError("image-size must be positive") + if args.eval_only and not args.checkpoint: + raise ValueError("--eval-only requires --checkpoint") + + set_seed(args.seed) + output_dir = Path(args.output_dir).expanduser().resolve() + output_dir.mkdir(parents=True, exist_ok=True) + cache_root = ( + Path(args.cache_root).expanduser().resolve() + if args.cache_root else output_dir / ("cache/sidd_%d" % args.image_size) + ) + requested_device = torch.device(args.device) + if requested_device.type == "cuda" and not torch.cuda.is_available(): + print("CUDA unavailable; falling back to CPU", flush=True) + device = torch.device("cpu") + else: + device = requested_device + + print("Discovering and auditing data splits...", flush=True) + splits = build_data_splits(args) + provenance = make_provenance(args, splits) + _atomic_write_json(output_dir / "provenance.json", provenance) + + graph_config = GraphConfig( + use_ll_global=True, + use_photometric=bool(getattr(args, "photometric", False)), + photometric_dim=int(getattr(args, "photometric_dim", 128)), + ll_oriented_bands=bool(getattr(args, "ll_oriented_bands", False)), + ) + weights = LossWeights( + embed=float(getattr(args, "embed_weight", 0.0)), + photometric=float(getattr(args, "photometric_weight", 0.0)), + extra_null=float(getattr(args, "extra_null_weight", 0.15)) if getattr(args, "extra_clean_root", None) else 0.0, + ood_global_margin=float(getattr(args, "ood_global_margin_weight", 0.0)), + ) + if getattr(args, "root_weight", None) is not None: + weights = dataclasses.replace(weights, root=float(args.root_weight)) + config = _configuration(args, graph_config, weights) + _atomic_write_json(output_dir / "config.json", config) + model = BlindDegradationGraphEncoder(graph_config).to(device) + objective = Phase1GraphObjective( + graph_config.node_dim, weights, + texture_weighted_null=bool(getattr(args, "texture_null", False)), + readout_dim=int(getattr(model, "readout_dim", 0)), + embed_temperature=float(getattr(args, "embed_temperature", 0.1)), + embed_members=str(getattr(args, "embed_members", "all")), + severity_floor=float(getattr(args, "severity_floor", 0.0)), + ood_global_margin=float(getattr(args, "ood_global_margin", 0.5)), + ).to(device) + assert_phase2_contract(model) + crop_policy = str(getattr(args, "crop_policy", "resize")) + sidd_native_crops = int(getattr(args, "sidd_native_crops", 32)) + + if args.eval_only: + # The evaluated architecture is governed by the checkpoint's stored + # graph_config (legacy v2 checkpoints lack the ll_v3 branch), so the + # model must be rebuilt from it rather than the training default. + import inspect + + peek = torch.load(str(Path(args.checkpoint)), map_location="cpu") + stored_config: Dict[str, object] = {} + config_block = peek.get("config") if isinstance(peek, dict) else None + if isinstance(config_block, dict): + stored_config = dict(config_block.get("graph_config") or {}) + del peek + allowed = set( + inspect.signature(GraphConfig.__init__).parameters + ) - {"self"} + config_kwargs = { + key: value for key, value in stored_config.items() if key in allowed + } + if "spatial_map_size" in config_kwargs: + config_kwargs["spatial_map_size"] = tuple( + config_kwargs["spatial_map_size"] + ) + graph_config = GraphConfig(**config_kwargs) + model = BlindDegradationGraphEncoder(graph_config).to(device) + objective = Phase1GraphObjective( + graph_config.node_dim, weights, + texture_weighted_null=bool(getattr(args, "texture_null", False)), + ).to(device) + checkpoint = _load_encoder_checkpoint( + Path(args.checkpoint), model, objective, device + ) + calibration = checkpoint.get("severity_calibration") + if not calibration: + raise ValueError("checkpoint lacks train-only severity calibration") + val_loader = _make_eval_loader( + args, splits.val, calibration, device, cache_root / "val", True + ) + val_metrics = evaluate( + model, val_loader, device, _pixel_q95_tensor(calibration) + ) + _atomic_write_json(output_dir / "eval_val_metrics.json", val_metrics) + print(json.dumps({"val": val_metrics}, sort_keys=True), flush=True) + if args.run_final_test: + locked_metrics = _run_locked_test( + args, model, splits, calibration, device, cache_root, output_dir + ) + print(json.dumps({"locked_test": locked_metrics}, sort_keys=True), flush=True) + return 0 + + # Prebuild only train+val SIDD caches; locked test stays completely untouched. + dummy_calibration = { + name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} + for name in BRANCH_ORDER + } + PairDataset( + splits.train, args.image_size, dummy_calibration, cache_root / "train", + crop_policy=crop_policy, training=True, sidd_native_crops=sidd_native_crops, + ).prepare_cache() + PairDataset( + splits.val, args.image_size, dummy_calibration, cache_root / "val", + crop_policy=crop_policy, training=False, sidd_native_crops=sidd_native_crops, + ).prepare_cache() + calibration = fit_training_calibration( + splits.train, + args.image_size, + output_dir / "severity_calibration.json", + cache_root / "train", + crop_policy=crop_policy, + ) + pixel_q95 = _pixel_q95_tensor(calibration) + train_loader, val_loader, _, _ = build_loaders( + args, splits, calibration, device, cache_root + ) + # v5d: evaluate/select/save the EMA shadow; the live model keeps training. + ema_decay = float(getattr(args, "ema_decay", 0.0)) + ema = WeightEMA(model, ema_decay) if ema_decay > 0.0 else None + eval_model = ema.module if ema is not None else model + raw_model = model if ema is not None else None + selection = str(getattr(args, "selection", "f1")) + real_ood_iter, real_ood_val_loader, extra_clean_iter = None, None, None + pool_workers = max(0, min(4, int(args.workers))) + held_out_names: set = set() + if getattr(args, "ood_real_root", None): + real_files = list_image_files(Path(args.ood_real_root)) + val_count = max(0, min(int(args.ood_real_val_count), len(real_files) // 4)) + real_val = real_files[len(real_files) - val_count:] if val_count else [] + real_train = real_files[: len(real_files) - val_count] + held_out_names = {p.name for p in real_val} + real_ood_iter = _infinite_batches(DataLoader( + FolderCropDataset(real_train, args.image_size, seed=args.seed), + batch_size=args.batch_size, shuffle=True, drop_last=True, + num_workers=pool_workers, pin_memory=device.type == "cuda", + )) + if real_val: + real_ood_val_loader = DataLoader( + FolderCropDataset(real_val, args.image_size, seed=args.seed, deterministic=True), + batch_size=args.eval_batch_size, shuffle=False, + num_workers=min(2, pool_workers), pin_memory=device.type == "cuda", + ) + print("real OOD pool: %d train / %d held-out files" % (len(real_train), len(real_val)), flush=True) + if getattr(args, "extra_clean_root", None): + extra_files = [p for p in list_image_files(Path(args.extra_clean_root)) if p.name not in held_out_names] + extra_clean_iter = _infinite_batches(DataLoader( + FolderCropDataset(extra_files, args.image_size, seed=args.seed + 1), + batch_size=args.batch_size, shuffle=True, drop_last=True, + num_workers=pool_workers, pin_memory=device.type == "cuda", + )) + print("extra clean pool: %d files" % len(extra_files), flush=True) + + parameters = list(model.parameters()) + list(objective.parameters()) + optimizer = torch.optim.AdamW( + parameters, lr=args.learning_rate, weight_decay=args.weight_decay + ) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=max(1, args.epochs) + ) + amp_enabled = device.type == "cuda" and not args.no_amp + scaler = torch.cuda.amp.GradScaler(enabled=amp_enabled) + history: List[Mapping[str, object]] = [] + + # Mandatory epoch-0 random-initialization baseline, before any optimizer step. + baseline = evaluate(eval_model, val_loader, device, pixel_q95, real_ood_loader=real_ood_val_loader) + history.append({"epoch": 0, "phase": "baseline", "val": baseline}) + best_key = selection_key(baseline, selection) + best_epoch = 0 + best_path = output_dir / "graph_encoder_best.pt" + baseline_checkpoint = make_checkpoint( + eval_model, objective.global_type_head, optimizer, scheduler, scaler, + epoch=0, best_score=float(baseline["macro_f1"]), config=config, + provenance=provenance, history=history, + severity_calibration=calibration, raw_model=raw_model, + ) + _atomic_torch_save(best_path, baseline_checkpoint) + _atomic_write_json(output_dir / "history.json", history) + print(json.dumps({"epoch": 0, "val": baseline}, sort_keys=True), flush=True) + + residual_bank: List[torch.Tensor] = [] + for epoch in range(1, args.epochs + 1): + train_loader.batch_sampler.epoch = epoch + train_metrics = train_one_epoch( + model, objective, train_loader, optimizer, scaler, device, + pixel_q95, amp_enabled, args.max_grad_norm, + seed=args.seed, epoch=epoch, + noise_aug_prob=float(getattr(args, "noise_aug_prob", 0.0)), + noise_calibration=calibration.get("noise") if isinstance(calibration, Mapping) else None, + residual_bank=residual_bank, + noise_aug_synthetic_prob=float(getattr(args, "noise_aug_synthetic_prob", 0.5)), + noise_aug_gain_max=float(getattr(args, "noise_aug_gain_max", 1.4)), + real_ood_iter=real_ood_iter, + real_ood_prob=float(getattr(args, "ood_real_prob", 0.5)), + extra_clean_iter=extra_clean_iter, + ema=ema, + ) + scheduler.step() + val_metrics = evaluate(eval_model, val_loader, device, pixel_q95, real_ood_loader=real_ood_val_loader) + key = selection_key(val_metrics, selection) + history.append( + {"epoch": epoch, "phase": "train", "train": train_metrics, "val": val_metrics} + ) + if key > best_key: + best_key = key + best_epoch = epoch + _atomic_torch_save( + best_path, + make_checkpoint( + eval_model, objective.global_type_head, optimizer, scheduler, scaler, + epoch=epoch, best_score=float(val_metrics["macro_f1"]), + config=config, provenance=provenance, history=history, + severity_calibration=calibration, raw_model=raw_model, + ), + ) + _atomic_torch_save( + output_dir / "graph_encoder_last.pt", + make_checkpoint( + eval_model, objective.global_type_head, optimizer, scheduler, scaler, + epoch=epoch, best_score=float(best_key[0]), config=config, + provenance=provenance, history=history, + severity_calibration=calibration, raw_model=raw_model, + ), + ) + _atomic_write_json(output_dir / "history.json", history) + print( + json.dumps( + {"epoch": epoch, "best_epoch": best_epoch, "train": train_metrics, "val": val_metrics}, + sort_keys=True, + ), + flush=True, + ) + + # Final evaluation always reloads the selected checkpoint, never the last model. + _load_encoder_checkpoint(best_path, model, objective, device) + if args.run_final_test: + locked_metrics = _run_locked_test( + args, model, splits, calibration, device, cache_root, output_dir + ) + print(json.dumps({"locked_test": locked_metrics}, sort_keys=True), flush=True) + print("Training complete; best epoch %d" % best_epoch, flush=True) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/train_phase1_clean_relative.py b/dataset/phase1_noise_20260906/trial_code_staging/train_phase1_clean_relative.py new file mode 100644 index 0000000000000000000000000000000000000000..882b8c0ed9e9764ae8eed05ae3f0231c5d79c10d --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/train_phase1_clean_relative.py @@ -0,0 +1,622 @@ +"""Train seven clean-relative factors without modifying the legacy Phase-1 path. + +Real pairs provide domain labels, not physical severity labels. Controlled +operators supply the latter. Default uniform sampling consumes each selected +record once per epoch. Optional balanced noise sampling changes only real versus +synthetic noise exposure within the same domain slots and draw budget; domain +loss weighting and every model/objective setting remain unchanged. +""" + +from __future__ import annotations + +import argparse +import contextlib +from dataclasses import asdict, dataclass +import hashlib +import json +import math +import os +from pathlib import Path +import random +import subprocess +import sys +import tempfile +import time +from typing import Any + +import numpy as np +import torch +from torch import Tensor +import torch.nn.functional as F +from torch.utils.data import DataLoader + +TYPE_ORDER = ("rain", "noise", "haze", "lowlight", "snow", "blur", "jpeg") +HELDOUT_PAIRS = (("rain", "jpeg"), ("noise", "haze"), ("snow", "blur")) +TRAIN_PAIRS = tuple( + (a, b) for a in TYPE_ORDER for b in TYPE_ORDER + if a != b and frozenset((a, b)) not in {frozenset(pair) for pair in HELDOUT_PAIRS} +) + + +def epoch_indices(size: int, seed: int, epoch: int, start: int = 0) -> list[int]: + """An independently seeded permutation, resumable by consumed-record cursor.""" + if size < 0 or not 0 <= start <= size: + raise ValueError("Invalid dataset size or resume cursor") + generator = torch.Generator().manual_seed(seed + epoch * 1_000_003) + return torch.randperm(size, generator=generator).tolist()[start:] + + +def class_weights(labels: Tensor, num_classes: int = 7) -> Tensor: + counts = torch.bincount(labels.long(), minlength=num_classes).float() + present = counts > 0 + weights = torch.zeros_like(counts) + if present.any(): + weights[present] = len(labels) / (present.sum() * counts[present]) + return weights + + +def capture_rng() -> dict[str, Any]: + return { + "python": random.getstate(), "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), + "cuda": torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None, + } + + +def restore_rng(state: dict[str, Any]) -> None: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"].cpu()) + if state.get("cuda") is not None and torch.cuda.is_available(): + torch.cuda.set_rng_state_all([item.cpu() for item in state["cuda"]]) + + +def _atomic_write(path: Path, writer) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + descriptor, temporary = tempfile.mkstemp(prefix=path.name + ".", suffix=".tmp", dir=path.parent) + try: + with os.fdopen(descriptor, "wb") as handle: + writer(handle) + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary, path) + directory = os.open(path.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + finally: + if os.path.exists(temporary): + os.unlink(temporary) + + +def atomic_torch_save(payload: Any, path: str | Path) -> None: + _atomic_write(Path(path), lambda handle: torch.save(payload, handle)) + + +def atomic_json_save(payload: Any, path: str | Path) -> None: + encoded = json.dumps(payload, indent=2, allow_nan=False, default=str).encode("utf-8") + _atomic_write(Path(path), lambda handle: handle.write(encoded)) + + +def append_jsonl(path: Path, payload: Any) -> None: + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload, allow_nan=False, default=str) + "\n") + handle.flush() + os.fsync(handle.fileno()) + + +def safe_optimizer_step(model, optimizer, max_norm: float, scaler=None) -> tuple[bool, float | None]: + """Reject all nonfinite gradients before mutating optimizer or parameters.""" + if scaler is not None and scaler.is_enabled(): + scaler.unscale_(optimizer) + parameters = [p for p in model.parameters() if p.grad is not None] + finite = all(bool(torch.isfinite(p.grad).all()) for p in parameters) + norm = None + if finite and parameters: + measured = torch.nn.utils.clip_grad_norm_(parameters, max_norm) + finite = bool(torch.isfinite(measured)) + norm = float(measured) if finite else None + if finite: + if scaler is not None and scaler.is_enabled(): + scaler.step(optimizer) + else: + optimizer.step() + if scaler is not None and scaler.is_enabled(): + scaler.update() + if not finite: + optimizer.zero_grad(set_to_none=True) + return finite, norm + + +def file_digest(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def source_provenance() -> dict[str, Any]: + root = Path(__file__).resolve().parent + files = [Path(__file__), root / "eval_phase1_clean_relative.py", *sorted((root / "src").rglob("*.py"))] + hashes = {str(path.relative_to(root)): file_digest(path) for path in files if path.is_file()} + result: dict[str, Any] = {"source_sha256": hashes, "python": sys.version, "torch": torch.__version__} + for key, command in (("git_head", ["git", "rev-parse", "HEAD"]), ("git_status", ["git", "status", "--porcelain"])): + completed = subprocess.run(command, cwd=root, capture_output=True, text=True, check=False) + result[key] = completed.stdout.strip() if completed.returncode == 0 else None + result["source_digest"] = hashlib.sha256(json.dumps(hashes, sort_keys=True).encode()).hexdigest() + receipt = root / "DEPLOYMENT.json" + result["deployment_receipt"] = json.loads(receipt.read_text()) if receipt.is_file() else None + result["deployment_sha"] = os.environ.get("DEPLOYMENT_SHA") + return result + + +def record_labels(dataset) -> Tensor: + labels = [] + for record in dataset.records: + name = record.get("type", record.get("degradation")) + if name not in TYPE_ORDER: + raise ValueError(f"Unsupported manifest degradation: {name!r}") + labels.append(TYPE_ORDER.index(name)) + return torch.tensor(labels, dtype=torch.long) + + +def scene_component_ids(records: list[dict]) -> list[int]: + """Connect both dataset-scene groups and duplicate clean-image content.""" + parents = list(range(len(records))) + + def find(index): + while parents[index] != index: + parents[index] = parents[parents[index]] + index = parents[index] + return index + + seen = {} + for index, record in enumerate(records): + keys = (("group", record["dataset"], record["group"]), ("content", record["clean_content_sha256"])) + for key in keys: + if key in seen: + current, previous = find(index), find(seen[key]) + parents[max(current, previous)] = min(current, previous) + else: + seen[key] = index + return [find(index) for index in range(len(records))] + + +def selected_indices(labels: Tensor, cap: int | None, seed: int) -> list[int]: + """Deterministic stratified subset for explicitly capped smoke/quick checks.""" + if cap is None or cap >= len(labels): + return list(range(len(labels))) + if cap <= 0: + raise ValueError("An explicit record cap must be positive") + rng = random.Random(seed) + groups = [torch.where(labels == k)[0].tolist() for k in range(len(TYPE_ORDER))] + for group in groups: + rng.shuffle(group) + selected = [] + while len(selected) < cap: + for group in groups: + if group and len(selected) < cap: + selected.append(group.pop()) + return selected + + +@dataclass +class LossWeights: + presence: float = 1.0 + root: float = 1.0 + content: float = 0.1 + variance: float = 0.05 + subspace: float = 0.2 + free: float = 0.02 + distill: float = 0.5 + severity: float = 0.5 + invariance: float = 0.1 + proxy: float = 1.0 + transfer: float = 0.5 + interaction: float = 0.2 + spatial: float = 0.1 + photometric: float = 0.1 + + +def _mean_per_sample(value: Tensor) -> Tensor: + return value.reshape(len(value), -1).mean(1) + + +def image_statistics(image: Tensor) -> Tensor: + """Eight observable image summaries; differences are not physical parameters.""" + gray = image.mean(1, keepdim=True) + return torch.cat((image.mean((-2, -1)), image.std((-2, -1), unbiased=False), + (gray[..., 1:] - gray[..., :-1]).abs().mean((-2, -1)), + (gray[..., 1:, :] - gray[..., :-1, :]).abs().mean((-2, -1))), dim=1) + + +def residual_statistics(residual: Tensor) -> Tensor: + """Residual mean/std and native-grid gradient/Laplacian RMS (15 channels).""" + residual = residual.float() + dx = residual[..., 1:] - residual[..., :-1] + dy = residual[..., 1:, :] - residual[..., :-1, :] + laplace = (4 * residual[..., 1:-1, 1:-1] - residual[..., :-2, 1:-1] + - residual[..., 2:, 1:-1] - residual[..., 1:-1, :-2] - residual[..., 1:-1, 2:]) + def rms(item): + return (item.square().mean((-2, -1)) + 1e-8).sqrt() + return torch.cat((residual.mean((-2, -1)), residual.std((-2, -1), unbiased=False), + rms(dx), rms(dy), rms(laplace)), dim=1) + + +def supervised_terms(rep: dict, presence: Tensor, weights: Tensor, severity: Tensor | None = None, + severity_mask: Tensor | None = None) -> dict[str, Tensor]: + known = presence.shape[1] + positive = presence.sum(1).clamp_min(1) + bce = F.binary_cross_entropy_with_logits(rep["presence_logits"], presence, reduction="none").mean(1) + amplitudes = rep["amplitudes"][:, :known] + inactive = ((1 - presence) * amplitudes.square()).mean(1) + active_error = F.relu(0.25 - amplitudes).square() + if severity is None: + severity_loss = bce.new_zeros(()) + else: + mask = presence if severity_mask is None else severity_mask.to(presence) * presence + active_error = torch.where(mask.bool(), (amplitudes - severity).square(), active_error) + severity_loss = ((((rep["severity"] - severity).square() * mask).sum(1) / mask.sum(1).clamp_min(1)) * weights).mean() + active = (presence * active_error).sum(1) / positive + free = rep["amplitudes"][:, known:].square().mean(1) if rep["amplitudes"].shape[1] > known else bce * 0 + free = free + rep["residual"].square().mean(1) + return { + "presence": (bce * weights).mean(), + "subspace": ((active + inactive) * weights).mean(), + "free": (free * weights).mean(), "severity": severity_loss, + } + + +def pair_objective(model, pair: dict, clean: Tensor, degraded: Tensor, presence: Tensor, + weights: Tensor, loss_weights: LossWeights, severity: Tensor | None = None, + include_anchor: bool = True, severity_mask: Tensor | None = None) -> tuple[Tensor, dict[str, Tensor]]: + student, teacher, reference = pair["student"], pair["teacher"], pair["clean"] + terms = supervised_terms(student, presence, weights, severity, severity_mask) + teacher_terms = supervised_terms(teacher, presence, weights, severity, severity_mask) + terms = {key: (value + teacher_terms[key]) / 2 for key, value in terms.items()} + terms["distill"] = ((student["delta"] - teacher["delta"].detach()).square().mean(1) * weights).mean() + visible_change = F.interpolate((degraded - clean).abs().mean(1, keepdim=True), size=student["spatial"].shape[-2:], mode="area") + spatial_target = visible_change * presence[:, :, None, None] + # Domain-indexed observed change, not a claim of physical factor support. + terms["spatial"] = ((_mean_per_sample((student["spatial"] - spatial_target).square()) + + _mean_per_sample((teacher["spatial"] - spatial_target).square())) * weights).mean() / 2 + photometric_target = image_statistics(degraded) - image_statistics(clean) + terms["photometric"] = (((student["photometric"] - photometric_target).square().mean(1) + + (teacher["photometric"] - photometric_target).square().mean(1)) * weights).mean() / 2 + if include_anchor: + terms["root"] = reference["delta"].square().mean() + F.binary_cross_entropy_with_logits( + reference["presence_logits"], torch.zeros_like(presence)) + terms["root"] += reference["spatial"].square().mean() + terms["content"] = F.smooth_l1_loss(student["content"], reference["content"].detach()) + pooled = reference["content"].mean((-2, -1)).float() + terms["variance"] = F.relu(0.1 - torch.sqrt(pooled.var(0, unbiased=False) + 1e-4)).mean() if len(clean) > 1 else pooled.sum() * 0 + if loss_weights.proxy: + clean_hat = model.decode(reference["content"], torch.zeros_like(teacher["delta"]), clean.shape[-2:]) + degraded_hat = model.decode(reference["content"], teacher["delta"], clean.shape[-2:]) + terms["proxy"] = (_mean_per_sample((clean_hat - clean).abs()) * weights).mean() + terms["proxy"] += (functional_error(degraded_hat, degraded, clean, presence.argmax(1)) * weights).mean() + total = sum(getattr(loss_weights, key) * value for key, value in terms.items()) + return total, terms + + +def controlled_batch(clean_cpu: Tensor, step: int, seed: int, count: int, + pairs=TRAIN_PAIRS, heldout: bool = False, scene_ids: list[str] | None = None) -> dict[str, Any]: + """Matched operators on different content; labels come only from synthesis.""" + from src.data.clean_relative import sample_degradation_parameters, synthesize_composition, synthesize_degradation + + count = min(count, len(clean_cpu)) + scene_ids = scene_ids if scene_ids is not None else [str(i) for i in range(len(clean_cpu))] + partners = [next((j for j in range(len(clean_cpu)) if scene_ids[j] != scene_ids[i]), i) for i in range(count)] + cross_content_available = all(scene_ids[i] != scene_ids[j] for i, j in enumerate(partners)) + collected: dict[str, list] = {key: [] for key in ( + "clean", "other_clean", "single", "other_single", "second", "mixed", + "presence", "second_presence", "severity", "second_severity", "first_type", "second_type", + )} + specs = [] + for i in range(count): + a, b = pairs[(step * count + i) % len(pairs)] + sample_seed = seed + step * 10_007 + i * 101 + pa = sample_degradation_parameters(a, sample_seed, heldout=heldout) + pb = sample_degradation_parameters(b, sample_seed + 1, heldout=heldout) + x = clean_cpu[i] + other = clean_cpu[partners[i]] + ya, _ = synthesize_degradation(x, a, parameters=pa, seed=sample_seed) + yb, _ = synthesize_degradation(x, b, parameters=pb, seed=sample_seed + 1) + yother, _ = synthesize_degradation(other, a, parameters=pa, seed=sample_seed) + mixed, _ = synthesize_composition(x, (a, b), parameters=(pa, pb), seed=sample_seed) + active, second_active = torch.zeros(7), torch.zeros(7) + severity, second_severity = torch.zeros(7), torch.zeros(7) + active[TYPE_ORDER.index(a)] = second_active[TYPE_ORDER.index(b)] = 1 + severity[TYPE_ORDER.index(a)] = float(pa["severity"]) + second_severity[TYPE_ORDER.index(b)] = float(pb["severity"]) + values = (x, other, ya, yother, yb, mixed, active, second_active, severity, second_severity, + torch.tensor(TYPE_ORDER.index(a)), torch.tensor(TYPE_ORDER.index(b))) + for key, value in zip(collected, values): + collected[key].append(value) + specs.append({"first": a, "second": b, "first_parameters": pa, "second_parameters": pb}) + result = {key: torch.stack(values) for key, values in collected.items()} + result["specs"] = specs + result["cross_content_available"] = cross_content_available + return result + + +def synthetic_objective(model, data: dict, loss_weights: LossWeights, use_edges: bool) -> tuple[Tensor, dict[str, Tensor]]: + x = data["clean"] + single = model.forward_pair(data["single"], x) + second = model.forward_pair(data["second"], x) + mixed = model.forward_pair(data["mixed"], x) + pairs = ((single, data["single"], data["presence"], data["severity"]), + (second, data["second"], data["second_presence"], data["second_severity"]), + (mixed, data["mixed"], data["presence"] + data["second_presence"], data["severity"] + data["second_severity"])) + total = x.sum() * 0 + logs: dict[str, Tensor] = {} + for pair, degraded, presence, severity in pairs: + value, terms = pair_objective(model, pair, x, degraded, presence, x.new_ones(len(x)), loss_weights, + severity=severity, include_anchor=False) + total = total + value / len(pairs) + for key, item in terms.items(): + logs[key] = logs.get(key, x.sum() * 0) + item / len(pairs) + composed = model.compose(single["teacher"]["delta"], second["teacher"]["delta"], + data["first_type"], data["second_type"], use_edges=use_edges) + logs["interaction"] = F.mse_loss(composed, mixed["teacher"]["delta"].detach()) + total = total + loss_weights.interaction * logs["interaction"] + if data["cross_content_available"]: + other = model.forward_pair(data["other_single"], data["other_clean"]) + logs["invariance"] = F.mse_loss(single["teacher"]["coefficients"][:, :7], other["teacher"]["coefficients"][:, :7]) + total = total + loss_weights.invariance * logs["invariance"] + if loss_weights.transfer: + prediction = model.decode(other["clean"]["content"], single["teacher"]["delta"], x.shape[-2:]) + logs["transfer"] = functional_error(prediction, data["other_single"], data["other_clean"], data["first_type"]).mean() + total = total + loss_weights.transfer * logs["transfer"] + return total, logs + + +def functional_error(prediction: Tensor, target: Tensor, clean: Tensor, labels: Tensor) -> Tensor: + """Pixel error for deterministic operators; residual moments for random ones. + + Matching moments is deliberately not described as a full likelihood test. + """ + pixel = _mean_per_sample((prediction - target).abs()) + moments = (residual_statistics(prediction - clean) - residual_statistics(target - clean)).abs().mean(1) + stochastic = (labels == TYPE_ORDER.index("noise")) | (labels == TYPE_ORDER.index("rain")) | (labels == TYPE_ORDER.index("snow")) + return torch.where(stochastic, moments, pixel) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest", required=True) + parser.add_argument("--output-dir", required=True) + parser.add_argument("--epochs", type=int, default=10) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--patch-size", type=int, default=128) + parser.add_argument("--num-workers", type=int, default=4) + parser.add_argument("--threads", type=int, default=4) + parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu") + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--lr", type=float, default=2e-4) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--grad-clip", type=float, default=1.0) + parser.add_argument("--amp", choices=("none", "bfloat16", "float16"), default="none") + parser.add_argument("--synthetic-batch-size", type=int, default=4) + parser.add_argument("--synthetic-every", type=int, default=1) + parser.add_argument("--save-every", type=int, default=250) + parser.add_argument("--log-every", type=int, default=25) + parser.add_argument("--val-every", type=int, default=1) + parser.add_argument("--quick-val-records", type=int, default=224) + parser.add_argument("--max-train-records", type=int, help="Explicitly capped smoke run; omitted means ALL train records") + parser.add_argument("--max-steps", type=int, help="Explicit optimizer-attempt cap for a smoke run") + parser.add_argument("--noise-sampling", choices=("uniform", "balanced"), default="uniform", + help="Uniform legacy permutation, or balance only real/synthetic noise in unchanged noise slots") + parser.add_argument("--resume") + parser.add_argument("--no-edges", action="store_true", help="Disable ordered-composition correction; evidence attention remains enabled") + parser.add_argument("--prototype-only", action="store_true", help="Rank-one/type baseline; not capacity-matched") + parser.add_argument("--no-proxy", action="store_true") + return parser + + +def main(argv: list[str] | None = None) -> dict[str, Any]: + args = build_parser().parse_args(argv) + for key in ("epochs", "batch_size", "patch_size", "synthetic_batch_size", "synthetic_every", "save_every", "log_every", "val_every", "threads"): + if getattr(args, key) <= 0: + raise ValueError(f"--{key.replace('_', '-')} must be positive") + if args.num_workers < 0 or (args.max_steps is not None and args.max_steps <= 0): + raise ValueError("Invalid worker count or step cap") + if args.patch_size < 32 or args.patch_size % 16: + raise ValueError("Patch size must be >=32 and divisible by16") + torch.set_num_threads(args.threads) + random.seed(args.seed) + np.random.seed(args.seed) + torch.manual_seed(args.seed) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(args.seed) + device = torch.device(args.device) + if args.amp != "none" and device.type != "cuda": + raise ValueError("AMP is supported here only on CUDA/ROCm devices") + from src.data.clean_relative import PairedDegradationDataset + from src.data.noise_sampling import NoiseSamplingPlan, SAMPLING_VERSION + from src.models.graph_encoder.clean_relative import CleanRelativeConfig, CleanRelativeGraphEncoder + from eval_phase1_clean_relative import evaluate_real + + dataset = PairedDegradationDataset(args.manifest, split="train", crop_size=args.patch_size, seed=args.seed) + labels = record_labels(dataset) + scene_components = scene_component_ids(dataset.records) + selected = selected_indices(labels, args.max_train_records, args.seed) + if not selected: + raise ValueError("Training manifest contains no selected records") + if args.noise_sampling == "balanced" and args.max_train_records is not None: + raise ValueError("Balanced noise sampling forbids an explicit selected-record cap") + sampling = NoiseSamplingPlan(dataset.records, selected, args.seed, args.noise_sampling) + if args.max_steps is None and not sampling.coverage(args.epochs, 0)["all_selected_covered"]: + raise ValueError("Training round budget cannot visit every selected record under this sampling plan") + sample_weights = class_weights(labels[selected]).to(device) + config = CleanRelativeConfig(rank=1 if args.prototype_only else 8) + model = CleanRelativeGraphEncoder(config).to(device) + optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=args.weight_decay) + total_steps = args.epochs * math.ceil(len(selected) / args.batch_size) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=total_steps) + scaler = torch.amp.GradScaler("cuda", enabled=args.amp == "float16") + loss_weights = LossWeights(proxy=0 if args.no_proxy else 1, transfer=0 if args.no_proxy else 0.5) + output = Path(args.output_dir) + output.mkdir(parents=True, exist_ok=True) + manifest_sha = file_digest(args.manifest) + run_config = { + "arguments": vars(args), "model_config": asdict(config), "loss_weights": asdict(loss_weights), + "type_order": TYPE_ORDER, "manifest_sha256": manifest_sha, "provenance": source_provenance(), + "train_records_total": len(dataset), "train_records_selected": len(selected), + "class_counts": torch.bincount(labels[selected], minlength=7).tolist(), + "class_loss_weights": sample_weights.cpu().tolist(), + "sampling": ("epoch permutation without replacement; drop_last=False" if args.noise_sampling == "uniform" + else "unchanged domain slots; noise-only 50:50 real/synthetic shuffled cyclic queues; drop_last=False"), + "noise_sampling_plan": sampling.describe(args.epochs), + "scope": "smoke_capped" if args.max_train_records is not None or args.max_steps is not None else "full_manifest", + "train_compositions": TRAIN_PAIRS, "heldout_compositions": HELDOUT_PAIRS, + "no_edges_scope": "Only ordered-composition correction; not a complete no-message-passing ablation", + "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"], + } + epoch, cursor, global_step, optimizer_steps = 0, 0, 0, 0 + best_score = -float("inf") + skipped = 0 + if args.resume: + checkpoint = torch.load(args.resume, map_location="cpu", weights_only=False) + previous = checkpoint["run_config"] + if previous["manifest_sha256"] != manifest_sha or previous["model_config"] != asdict(config): + raise ValueError("Resume requires identical manifest and model configuration") + 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", "noise_sampling"): + if previous["arguments"].get(name) != vars(args).get(name): + raise ValueError(f"Resume changes training semantics: {name}") + if previous["provenance"]["source_digest"] != run_config["provenance"]["source_digest"]: + raise ValueError("Source changed since checkpoint; use a new run rather than silently hot-patching") + model.load_state_dict(checkpoint["model"]) + optimizer.load_state_dict(checkpoint["optimizer"]) + scheduler.load_state_dict(checkpoint["scheduler"]) + scaler.load_state_dict(checkpoint["scaler"]) + epoch, cursor = checkpoint["epoch"], checkpoint["cursor"] + expected_sampling_state = {"version": SAMPLING_VERSION, "mode": args.noise_sampling, + "epoch": epoch, "cursor": cursor, "round_draws": len(selected)} + if checkpoint.get("sampling_state") != expected_sampling_state: + raise ValueError("Checkpoint sampling replay state does not match consumed-draw cursor") + global_step, optimizer_steps = checkpoint["global_step"], checkpoint["optimizer_steps"] + best_score, skipped = checkpoint["best_score"], checkpoint["skipped_steps"] + restore_rng(checkpoint["rng"]) + atomic_json_save(run_config, output / f"resume_config_step{global_step}.json") + elif (output / "run_config.json").exists() or (output / "last.pt").exists(): + raise FileExistsError("Output directory already contains a run; use --resume or a new output directory") + else: + atomic_json_save(run_config, output / "run_config.json") + + def save(name="last.pt"): + atomic_torch_save({ + "schema_version": 1, "model": model.state_dict(), "model_config": asdict(config), + "optimizer": optimizer.state_dict(), "scheduler": scheduler.state_dict(), "scaler": scaler.state_dict(), + "rng": capture_rng(), "epoch": epoch, "cursor": cursor, "global_step": global_step, + "optimizer_steps": optimizer_steps, "best_score": best_score, "skipped_steps": skipped, + "sampling_state": {"version": SAMPLING_VERSION, "mode": args.noise_sampling, + "epoch": epoch, "cursor": cursor, "round_draws": len(selected)}, + "run_config": run_config, + }, output / name) + + started = time.monotonic() + consecutive_bad = 0 + metrics_path = output / "metrics.jsonl" + while epoch < args.epochs and (args.max_steps is None or global_step < args.max_steps): + dataset.set_epoch(epoch) + indices = sampling.round_indices(epoch, cursor) + loader = DataLoader(dataset, batch_size=args.batch_size, sampler=indices, drop_last=False, + num_workers=args.num_workers, pin_memory=device.type == "cuda", + generator=torch.Generator().manual_seed(args.seed + epoch), persistent_workers=False) + model.train() + for batch in loader: + optimizer.zero_grad(set_to_none=True) + clean_cpu = batch["clean"] + clean, degraded = clean_cpu.to(device), batch["degraded"].to(device) + label = batch["label"].to(device) + presence = batch["presence"].to(device) + dtype = torch.bfloat16 if args.amp == "bfloat16" else torch.float16 + autocast = torch.autocast(device_type="cuda", dtype=dtype) if args.amp != "none" else contextlib.nullcontext() + with autocast: + pair = model.forward_pair(degraded, clean) + loss, terms = pair_objective(model, pair, clean, degraded, presence, sample_weights[label], loss_weights, + severity=batch["severity"].to(device), severity_mask=batch["severity_mask"].to(device)) + if global_step % args.synthetic_every == 0: + scene_ids = [str(scene_components[int(i)]) for i in batch["index"]] + synthetic = controlled_batch(clean_cpu, global_step, args.seed, args.synthetic_batch_size, scene_ids=scene_ids) + synthetic = {key: value.to(device) if isinstance(value, Tensor) else value for key, value in synthetic.items()} + synthetic_loss, synthetic_terms = synthetic_objective(model, synthetic, loss_weights, not args.no_edges) + loss = loss + synthetic_loss + terms.update({"synthetic_" + key: value for key, value in synthetic_terms.items()}) + finite_loss = bool(torch.isfinite(loss)) + gradient_norm = None + if finite_loss: + scaler.scale(loss).backward() + accepted, gradient_norm = safe_optimizer_step(model, optimizer, args.grad_clip, scaler) + else: + accepted = False + optimizer.zero_grad(set_to_none=True) + cursor += len(clean) + global_step += 1 + if accepted: + scheduler.step() + optimizer_steps += 1 + consecutive_bad = 0 + else: + skipped += 1 + consecutive_bad += 1 + if global_step % args.log_every == 0 or not accepted or global_step == 1: + row = {"event": "train", "epoch": epoch, "cursor": cursor, "selected_records": len(selected), + "step": global_step, "optimizer_steps": optimizer_steps, "loss": float(loss.detach()) if finite_loss else None, + "accepted": accepted, "gradient_norm": gradient_norm, "lr": scheduler.get_last_lr()[0], + "elapsed_seconds": time.monotonic() - started, + "cuda_peak_allocated_bytes": torch.cuda.max_memory_allocated(device) if device.type == "cuda" else None, + "terms": {key: float(value.detach()) if torch.isfinite(value) else None for key, value in terms.items()}} + append_jsonl(metrics_path, row) + print(json.dumps(row), flush=True) + if global_step % args.save_every == 0 or consecutive_bad >= 3: + save() + if consecutive_bad >= 3: + raise FloatingPointError("Three consecutive nonfinite optimizer attempts; recoverable checkpoint saved") + if args.max_steps is not None and global_step >= args.max_steps: + break + if cursor == len(selected): + coverage = sampling.coverage(epoch, cursor) + append_jsonl(metrics_path, {"event": "epoch_coverage", "epoch": epoch, **coverage["round"], + "complete": True, "drop_last": False, "sampling_mode": args.noise_sampling, + "complete_semantics": "all planned round draws consumed; unique coverage is reported separately", + "cumulative": coverage["cumulative"]}) + epoch += 1 + cursor = 0 + if epoch % args.val_every == 0: + rng_before = capture_rng() + report = evaluate_real(model, args.manifest, "val", device, args.batch_size, args.patch_size, + args.num_workers, args.quick_val_records, args.seed, functional_enabled=not args.no_proxy) + restore_rng(rng_before) + score = report["classification"]["macro_f1"] + append_jsonl(metrics_path, {"event": "validation", "epoch": epoch, "step": global_step, "report": report}) + if score > best_score: + best_score = score + save("best.pt") + save() + rng_before = capture_rng() + report = evaluate_real(model, args.manifest, "val", device, args.batch_size, args.patch_size, + args.num_workers, None, args.seed, functional_enabled=not args.no_proxy) + restore_rng(rng_before) + sampling_coverage = sampling.coverage(epoch, cursor) + if epoch == args.epochs and not sampling_coverage["all_selected_covered"]: + raise RuntimeError("Completed draw budget did not visit every selected record") + final = {"status": "completed" if epoch == args.epochs else "smoke_step_cap", "epoch": epoch, "cursor": cursor, + "global_step": global_step, "optimizer_steps": optimizer_steps, "skipped_steps": skipped, + "elapsed_seconds": time.monotonic() - started, "sampling_coverage": sampling_coverage, + "full_validation": report} + atomic_json_save(final, output / "final_validation.json") + # A capped first epoch may have no quick-validation checkpoint yet. + if not (output / "best.pt").exists(): + best_score = report["classification"]["macro_f1"] + save("best.pt") + save() + print(json.dumps(final), flush=True) + return final + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_gated_resshift_v5.py b/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_gated_resshift_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..98cb2cb018205833c1f9ce52f71d2fa3eabe2011 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_gated_resshift_v5.py @@ -0,0 +1,1145 @@ +#!/usr/bin/env python3 +"""Train Phase 2 v5 with continuous soft experts and DA-CLIP-style control. + +The audited v4 data/DDP/AMP/checkpoint runtime is reused without modifying its +source. This entrypoint installs a scoped v5 backend for the duration of one +run: a five-way continuous router, zero-initialized expert adapters, learned +noise/time prompts, and an optional variance-preserving independent Gaussian +bank. The residual-shift schedule and exact posterior remain unchanged. +""" + +from __future__ import annotations + +import argparse +import contextlib +from dataclasses import dataclass +import hashlib +import math +from pathlib import Path +from typing import Any, Dict, Iterator, List, Mapping, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn + +import train_phase2_graph_resshift_v4 as v4 +from src.models.restoration.gated_graph_resshift_v5 import ( + EXPERT_KAPPA_VERSION, + EXPERT_ORDER, + NOISE_MIXER_VERSION, + ROUTER_VERSION, + ExpertKappaSchedule, + GatedConditionBundleV5, + GatedGraphConditionerV5, + GatedGraphResidualShiftUNetV5, + VariancePreservingNoiseMixer, +) +from src.models.restoration.graph_resshift_v4 import ( + BRANCH_ORDER, + FrozenPhase1, + ResidualShiftSchedule, + pad_to_multiple, + pixel_shuffle2, + pixel_unshuffle2, +) + + +V5_SCHEMA_VERSION = 5 +V4_WARMSTART_MAPPING_VERSION = "shared_keys_strict_v1" +NOISE_SEED_VERSION = "legacy_shared_plus_per_sample_expert_bank_v2" + +# Capture the stable backend before the scoped installer replaces names on the +# imported module. Calling these aliases avoids recursion inside the patch. +_V4_ARCHITECTURE = v4._architecture +_V4_DATA_PLAN = v4._data_plan +_V4_SCHEDULE_CONFIG = v4._schedule_config +_V4_LOAD_OR_CREATE_SPLITS = v4._load_or_create_splits +_V4_DETERMINISTIC_TRAINING_PLAN = v4.deterministic_training_plan +_V4_NOISE_FOR_RECORDS = v4._noise_for_records + + +@dataclass +class GatedTrainStepResult: + """Restoration objective plus routed-noise diagnostics.""" + + loss: Tensor + reconstruction_loss: Tensor + router_loss: Tensor + u0_prediction: Tensor + u0_target: Tensor + u_t: Tensor + mixed_noise: Tensor + kappa: Optional[Tensor] = None + + +class Phase2GatedRestorationModule(nn.Module): + """Trainable v5 module; frozen Phase-1 remains outside this object.""" + + def __init__( + self, + conditioner: GatedGraphConditionerV5, + denoiser: nn.Module, + schedule: ResidualShiftSchedule, + noise_mixer: VariancePreservingNoiseMixer, + condition_mode: str, + *, + router_anchor_weight: float = 0.01, + router_balance_weight: float = 0.01, + router_correction_weight: float = 0.001, + expert_kappa: Optional[ExpertKappaSchedule] = None, + ) -> None: + super().__init__() + if condition_mode not in ("full", "null"): + raise ValueError("condition_mode must be 'full' or 'null'") + for name, value in ( + ("router_anchor_weight", router_anchor_weight), + ("router_balance_weight", router_balance_weight), + ("router_correction_weight", router_correction_weight), + ): + if not math.isfinite(value) or value < 0.0: + raise ValueError("%s must be finite and non-negative" % name) + self.conditioner = conditioner + self.denoiser = denoiser + self.schedule = schedule + self.noise_mixer = noise_mixer + self.condition_mode = condition_mode + self.router_anchor_weight = float(router_anchor_weight) + self.router_balance_weight = float(router_balance_weight) + self.router_correction_weight = float(router_correction_weight) + self.expert_kappa = expert_kappa + + def build_condition(self, representation: Any) -> GatedConditionBundleV5: + return self.conditioner(representation, mode=self.condition_mode) + + def effective_kappa( + self, condition: GatedConditionBundleV5 + ) -> Optional[Tensor]: + """Per-sample kappa for the current gate, or None for the global one.""" + + if self.expert_kappa is None: + return None + return self.expert_kappa( + condition.expert_gates, condition.route_active + ) + + def predict_x0( + self, + u_t: Tensor, + u_y: Tensor, + timesteps: Tensor, + condition: GatedConditionBundleV5, + ) -> Tensor: + return self.denoiser(u_t, u_y, timesteps, condition) + + def route_noise( + self, noise_bank: Tensor, condition: GatedConditionBundleV5 + ) -> Tensor: + return self.noise_mixer( + noise_bank, + condition.expert_gates, + condition.route_active, + ) + + def forward( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Tensor, + ) -> Tensor: + # DDP must see the loss through forward, exactly as in v4. + return self.training_loss( + clean, degraded, representation, timesteps, noise + ).loss + + def training_loss( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise_bank: Tensor, + ) -> GatedTrainStepResult: + """FP32 x0 MSE plus label-free router regularization.""" + + u0 = pixel_unshuffle2(clean) + uy = pixel_unshuffle2(degraded) + condition = self.build_condition(representation) + # Kappa is read at the CURRENT anneal position, then the counter + # advances, so the first training microstep is exactly v4-equivalent. + kappa = self.effective_kappa(condition) + mixed_noise = self.route_noise(noise_bank, condition) + if mixed_noise.shape != u0.shape: + raise ValueError("routed noise must match the diffusion state") + u_t = self.schedule.q_sample( + u0, uy, timesteps, noise=mixed_noise, kappa=kappa + ) + prediction = self.predict_x0(u_t, uy, timesteps, condition) + reconstruction = (prediction.float() - u0.float()).square().mean() + router_loss = ( + self.router_anchor_weight * condition.router_anchor_loss.float() + + self.router_balance_weight * condition.router_balance_loss.float() + + self.router_correction_weight + * condition.router_correction_loss.float() + ) + total = reconstruction + router_loss + if self.expert_kappa is not None and self.training: + self.expert_kappa.advance() + return GatedTrainStepResult( + loss=total, + reconstruction_loss=reconstruction, + router_loss=router_loss, + u0_prediction=prediction, + u0_target=u0, + u_t=u_t, + mixed_noise=mixed_noise, + kappa=None if kappa is None else kappa.detach(), + ) + + +def deterministic_expert_training_plan( + reference: Tensor, + timesteps: int, + seed: int, + global_microstep: int, + rank: int = 0, + sample_seeds: Optional[Sequence[int]] = None, + num_experts: int = len(EXPERT_ORDER), +) -> Tuple[Tensor, Tensor]: + """Create a legacy shared stream plus independent expert Gaussians. + + Rank/order invariance requires the per-sample identities emitted by the + balanced sampler. Without ``sample_seeds`` the fallback deliberately + retains v4's rank-local behavior. + """ + + if reference.ndim != 4: + raise ValueError("reference must be a BCHW diffusion state") + if timesteps < 1 or num_experts < 1: + raise ValueError("timesteps and num_experts must be positive") + batch = reference.shape[0] + if sample_seeds is not None and len(sample_seeds) != batch: + raise ValueError("one sample seed is required per image") + + cpu_reference = torch.empty( + tuple(reference.shape), device="cpu", dtype=reference.dtype + ) + legacy_timesteps, legacy_noise = _V4_DETERMINISTIC_TRAINING_PLAN( + cpu_reference, + timesteps, + seed, + global_microstep, + rank=rank, + sample_seeds=sample_seeds, + ) + banks: List[Tensor] = [] + for index in range(batch): + sample_identity: Any + if sample_seeds is None: + sample_identity = ("rank", int(rank), "index", index) + else: + sample_identity = int(sample_seeds[index]) + streams: List[Tensor] = [legacy_noise[index]] + for expert_index in range(num_experts): + generator = torch.Generator(device="cpu") + generator.manual_seed( + v4._seed_value( + seed, + "train-v5", + global_microstep, + sample_identity, + "expert-noise", + expert_index, + ) + ) + streams.append( + torch.randn( + tuple(reference[index].shape), + generator=generator, + dtype=torch.float32, + ) + ) + banks.append(torch.stack(streams, dim=0)) + bank_tensor = torch.stack(banks, dim=0) + return legacy_timesteps.to(reference.device), bank_tensor.to( + device=reference.device, dtype=reference.dtype + ) + + +def _noise_bank_for_records( + reference: Tensor, + record_ids: Optional[Sequence[str]], + seed: int, + stage: Any, + num_experts: int = len(EXPERT_ORDER), +) -> Tensor: + if reference.ndim != 4: + raise ValueError("reference must be a BCHW diffusion state") + if record_ids is not None and len(record_ids) != reference.shape[0]: + raise ValueError("one record id is required per image") + cpu_reference = torch.empty( + tuple(reference.shape), device="cpu", dtype=reference.dtype + ) + shared = _V4_NOISE_FOR_RECORDS(cpu_reference, record_ids, seed, stage) + samples: List[Tensor] = [] + for index in range(reference.shape[0]): + identity = index if record_ids is None else str(record_ids[index]) + streams: List[Tensor] = [shared[index]] + for expert_index in range(num_experts): + streams.append( + v4._cpu_random_tensor( + reference[index].shape, + v4._seed_value( + seed, + "eval-v5", + identity, + stage, + "expert-noise", + expert_index, + ), + reference.dtype, + ) + ) + samples.append(torch.stack(streams, dim=0)) + return torch.stack(samples, dim=0).to(reference.device) + + +def _shared_noise_bank_for_records( + reference: Tensor, + record_ids: Optional[Sequence[str]], + seed: int, + stage: Any, + num_experts: int = len(EXPERT_ORDER), +) -> Tensor: + """Expose legacy v4 noise as a zero-copy shared-only v5 bank.""" + + shared = _V4_NOISE_FOR_RECORDS(reference, record_ids, seed, stage) + return shared.unsqueeze(1).expand( + -1, num_experts + 1, -1, -1, -1 + ) + + +@torch.no_grad() +def sample_gated_restoration( + model: nn.Module, + phase1: FrozenPhase1, + degraded: Tensor, + *, + seed: int, + record_ids: Optional[Sequence[str]] = None, + initial_noise_bank: Optional[Tensor] = None, + amp_enabled: Optional[bool] = None, +) -> Tensor: + """Run the unchanged exact posterior with one fixed soft gate per image.""" + + restorer = v4.unwrap_module(model) + if not isinstance(restorer, Phase2GatedRestorationModule): + raise TypeError("model must wrap Phase2GatedRestorationModule") + use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled) + with torch.cuda.amp.autocast(enabled=use_amp): + padded, original_size = pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + # The condition object, including its gate, is built exactly once and + # reused at every reverse step. + condition = restorer.build_condition(representation) + uy = pixel_unshuffle2(padded) + noise_bank_builder = ( + _shared_noise_bank_for_records + if restorer.noise_mixer.expert_fraction_value == 0.0 + else _noise_bank_for_records + ) + expected_shape = ( + uy.shape[0], + len(EXPERT_ORDER) + 1, + uy.shape[1], + uy.shape[2], + uy.shape[3], + ) + if initial_noise_bank is None: + initial_noise_bank = noise_bank_builder( + uy, record_ids, seed=seed, stage="initial" + ) + elif tuple(initial_noise_bank.shape) != expected_shape: + raise ValueError( + "initial_noise_bank must match [B, shared+experts, C, H, W]" + ) + else: + initial_noise_bank = initial_noise_bank.to( + device=uy.device, dtype=uy.dtype + ) + + initial_noise = restorer.route_noise(initial_noise_bank, condition) + eta_terminal = restorer.schedule.eta[-1].to( + device=uy.device, dtype=uy.dtype + ) + # One fixed per-sample kappa is used for the initial state and every + # posterior step, mirroring the fixed soft gate above. + kappa_override = restorer.effective_kappa(condition) + kappa = restorer.schedule.kappa_factor(kappa_override, uy) + u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise + batch = uy.shape[0] + for step in restorer.schedule.reverse_timesteps(): + timesteps = torch.full( + (batch,), step, device=uy.device, dtype=torch.long + ) + u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition) + mean, variance = restorer.schedule.posterior_mean_variance( + u_t, u0_hat, timesteps, kappa=kappa_override + ) + if step > 1: + bank = noise_bank_builder( + u_t, record_ids, seed=seed, stage=step + ) + routed_noise = restorer.route_noise(bank, condition) + u_t = mean + torch.sqrt(variance) * routed_noise + else: + u_t = mean + restored = pixel_shuffle2(u_t) + height, width = original_size + return restored[..., :height, :width].clamp(0.0, 1.0) + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + while True: + block = handle.read(1024 * 1024) + if not block: + break + digest.update(block) + return digest.hexdigest() + + +def _is_v5_only_key(name: str) -> bool: + return name.startswith( + ( + "conditioner.router.", + "denoiser.noise_type_tokens", + "denoiser.down_experts.", + "denoiser.up_experts.", + "noise_mixer.", + "expert_kappa.", + ) + ) + + +def _configure_trainable_paths( + model: Phase2GatedRestorationModule, *, train_shared_trunk: bool +) -> None: + """Freeze the v4 restoration trunk for the controlled adapter-first arm.""" + + for name, parameter in model.named_parameters(): + parameter.requires_grad_( + bool(train_shared_trunk) or _is_v5_only_key(name) + ) + + +def _validate_adapter_only_output_head( + state: Mapping[str, Any], architecture: Mapping[str, Any], source: str +) -> None: + optimization = architecture.get("optimization") + if not isinstance(optimization, Mapping): + raise ValueError("%s is missing v5 optimization provenance" % source) + shared_trainable = optimization.get("shared_trunk_trainable") + if not isinstance(shared_trainable, bool): + raise ValueError("%s has invalid shared-trunk provenance" % source) + if shared_trainable: + return + output_weight = state.get("denoiser.output_residual.weight") + if ( + not isinstance(output_weight, Tensor) + or not bool(torch.isfinite(output_weight).all()) + or int(torch.count_nonzero(output_weight).item()) == 0 + ): + raise ValueError( + "%s adapter-only state requires a finite nonzero output head" + % source + ) + + +def load_v4_warmstart( + path: Path, + expected_sha256: str, + model: Phase2GatedRestorationModule, + args: argparse.Namespace, + *, + weight_source: str, + expected_train_digest: str, + expected_val_digest: str, +) -> Dict[str, Any]: + """Strictly materialize all shared v4 weights before exposing v5 state.""" + + actual_sha256 = _file_sha256(path) + if actual_sha256.lower() != str(expected_sha256).lower(): + raise ValueError( + "v4 warmstart sha256 mismatch: expected %s, received %s" + % (expected_sha256, actual_sha256) + ) + checkpoint = v4._torch_load(path, map_location="cpu") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("warmstart must be a Phase-2 v4 checkpoint") + contract = checkpoint.get("contract") + if not isinstance(contract, Mapping): + raise ValueError("v4 warmstart is missing its canonical contract") + mirrored_fields = { + "condition_mode": "full", + "phase1_sha256": args.phase1_sha256, + "train_digest": str(expected_train_digest), + "val_digest": str(expected_val_digest), + } + for field, expected in mirrored_fields.items(): + if checkpoint.get(field) != expected or contract.get(field) != expected: + raise ValueError("v4 warmstart %s mismatch" % field) + phase1_metadata = checkpoint.get("phase1_metadata", {}) + if phase1_metadata != contract.get("phase1_metadata"): + raise ValueError("v4 warmstart Phase-1 metadata mirror mismatch") + if list(phase1_metadata.get("branch_order", ())) != list(BRANCH_ORDER): + raise ValueError("v4 warmstart branch_order mismatch") + + architecture = checkpoint.get("architecture", {}) + expected_architecture = _V4_ARCHITECTURE(args) + if contract.get("architecture") != architecture: + raise ValueError("v4 warmstart architecture mirror mismatch") + for field in ("name", "dims", "cond_dim", "state_channels"): + if architecture.get(field) != expected_architecture.get(field): + raise ValueError("v4 warmstart architecture %s mismatch" % field) + expected_schedule = _V4_SCHEDULE_CONFIG(args) + if ( + checkpoint.get("schedule_config") != expected_schedule + or contract.get("schedule") != expected_schedule + ): + raise ValueError("v4 warmstart schedule mismatch") + + if weight_source == "model": + state = checkpoint.get("model_state_dict") + elif weight_source == "ema": + ema_state = checkpoint.get("ema_state_dict") + state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None + else: + raise ValueError("weight_source must be 'model' or 'ema'") + if not isinstance(state, Mapping): + raise ValueError("v4 warmstart is missing the selected state") + if not bool(getattr(args, "train_shared_trunk", False)): + source_step = checkpoint.get("step") + if isinstance(source_step, bool) or not isinstance(source_step, int) or source_step <= 0: + raise ValueError( + "adapter-only warmstart requires a trained v4 checkpoint" + ) + output_weight = state.get("denoiser.output_residual.weight") + if ( + not isinstance(output_weight, Tensor) + or not bool(torch.isfinite(output_weight).all()) + or int(torch.count_nonzero(output_weight).item()) == 0 + ): + raise ValueError( + "adapter-only warmstart requires a finite nonzero v4 output head" + ) + + target_state = model.state_dict() + expected_shared = { + name for name in target_state.keys() if not _is_v5_only_key(name) + } + source_keys = set(state.keys()) + if source_keys != expected_shared: + missing = sorted(expected_shared - source_keys) + unexpected = sorted(source_keys - expected_shared) + raise ValueError( + "v4 warmstart shared key mismatch; missing=%r unexpected=%r" + % (missing, unexpected) + ) + for name in sorted(expected_shared): + value = state[name] + if not isinstance(value, Tensor) or value.shape != target_state[name].shape: + raise ValueError("v4 warmstart tensor shape mismatch: %s" % name) + + result = model.load_state_dict(state, strict=False) + expected_missing = sorted( + name for name in target_state.keys() if _is_v5_only_key(name) + ) + if sorted(result.missing_keys) != expected_missing or result.unexpected_keys: + raise RuntimeError("v4 warmstart loader violated its exact allowlist") + + audit = { + "mapping_version": V4_WARMSTART_MAPPING_VERSION, + "source_checkpoint_sha256": actual_sha256, + "source_schema_version": 4, + "source_step": int(checkpoint.get("step", -1)), + "source_condition_mode": checkpoint.get("condition_mode"), + "weight_source": weight_source, + "source_train_digest": checkpoint.get("train_digest"), + "source_val_digest": checkpoint.get("val_digest"), + "materialized_state_hash": v4.model_state_hash(model), + } + return audit + + +def _neutral_warmstart_audit() -> Dict[str, Any]: + return { + "mapping_version": V4_WARMSTART_MAPPING_VERSION, + "source_checkpoint_sha256": None, + "source_schema_version": None, + "source_step": None, + "source_condition_mode": None, + "weight_source": None, + "source_train_digest": None, + "source_val_digest": None, + "materialized_state_hash": None, + } + + +def _stored_warmstart_audit(path: Path) -> Dict[str, Any]: + checkpoint = v4._torch_load(path, map_location="cpu") + if checkpoint.get("schema_version") != V5_SCHEMA_VERSION: + raise ValueError("v5 state source has the wrong schema_version") + contract = checkpoint.get("contract") + architecture = contract.get("architecture") if isinstance(contract, Mapping) else None + warmstart = architecture.get("warmstart") if isinstance(architecture, Mapping) else None + if not isinstance(warmstart, Mapping): + raise ValueError("v5 state source is missing warmstart audit") + return dict(warmstart) + + +def _parse_expert_kappa_values(value: Optional[str]) -> Tuple[float, ...]: + """Parse and fail-closed validate five comma-separated expert kappas.""" + + if value is None: + raise ValueError("--expert-kappa requires --expert-kappa-values") + parts = [part.strip() for part in str(value).split(",")] + if len(parts) != len(EXPERT_ORDER): + raise ValueError( + "--expert-kappa-values requires %d comma-separated values in " + "EXPERT_ORDER %r" % (len(EXPERT_ORDER), list(EXPERT_ORDER)) + ) + values = [] + for name, part in zip(EXPERT_ORDER, parts): + try: + parsed = float(part) + except ValueError: + raise ValueError("expert kappa for %s is not a number" % name) + if not math.isfinite(parsed) or parsed <= 0.0: + raise ValueError( + "expert kappa for %s must be finite and positive" % name + ) + values.append(parsed) + return tuple(values) + + +def _build_expert_kappa( + args: argparse.Namespace, +) -> Optional[ExpertKappaSchedule]: + if not bool(getattr(args, "expert_kappa", False)): + return None + if args.kappa is None: + raise ValueError("--expert-kappa requires an explicit --kappa") + return ExpertKappaSchedule( + kappa_per_expert=_parse_expert_kappa_values(args.expert_kappa_values), + kappa_global=float(args.kappa), + anneal_microsteps=( + int(args.expert_kappa_anneal_steps) * int(args.grad_accum) + ), + ) + + +def _build_v5_restorer( + args: argparse.Namespace, device: torch.device +) -> Phase2GatedRestorationModule: + schedule = ResidualShiftSchedule( + timesteps=args.timesteps, + eta_end=args.eta_end, + min_noise=args.min_noise, + power=args.power, + kappa=args.kappa, + ) + conditioner = GatedGraphConditionerV5( + cond_dim=args.cond_dim, + stage_dims=args.dims, + router_hidden_dim=args.router_hidden_dim, + router_temperature=args.router_temperature, + router_max_correction=args.router_max_correction, + ) + denoiser = GatedGraphResidualShiftUNetV5( + dims=args.dims, + cond_dim=args.cond_dim, + adapter_rank=args.adapter_rank, + ) + model = Phase2GatedRestorationModule( + conditioner=conditioner, + denoiser=denoiser, + schedule=schedule, + noise_mixer=VariancePreservingNoiseMixer( + num_experts=len(EXPERT_ORDER), + expert_fraction=args.expert_noise_fraction, + ), + condition_mode=args.condition, + router_anchor_weight=args.router_anchor_weight, + router_balance_weight=args.router_balance_weight, + router_correction_weight=args.router_correction_weight, + expert_kappa=_build_expert_kappa(args), + ) + + if args.resume is not None: + audit = _stored_warmstart_audit(args.resume) + elif args.init_checkpoint is not None: + audit = _stored_warmstart_audit(args.init_checkpoint) + elif args.warmstart_v4 is not None: + train_digest = getattr(args, "_v5_train_digest", None) + val_digest = getattr(args, "_v5_val_digest", None) + if not isinstance(train_digest, str) or not isinstance(val_digest, str): + raise RuntimeError("v5 split digests must be resolved before warmstart") + audit = load_v4_warmstart( + args.warmstart_v4, + args.warmstart_v4_sha256, + model, + args, + weight_source=args.warmstart_weight_source, + expected_train_digest=train_digest, + expected_val_digest=val_digest, + ) + else: + audit = _neutral_warmstart_audit() + _configure_trainable_paths( + model, train_shared_trunk=bool(args.train_shared_trunk) + ) + setattr(args, "_v5_warmstart_audit", audit) + return model.to(device) + + +def _v5_architecture(args: argparse.Namespace) -> Dict[str, Any]: + audit = getattr(args, "_v5_warmstart_audit", None) + if not isinstance(audit, Mapping): + raise RuntimeError("v5 warmstart audit must be resolved before architecture") + return { + "name": "gated_graph_resshift_v5", + "version": 5, + "dims": list(args.dims), + "cond_dim": int(args.cond_dim), + "state_channels": 12, + "pixel_unshuffle_factor": 2, + "denoiser_input_channels": 36, + "prediction": "x0", + "expert_order": list(EXPERT_ORDER), + "router": { + "version": ROUTER_VERSION, + "temperature": float(args.router_temperature), + "max_correction": float(args.router_max_correction), + "hidden_dim": int(args.router_hidden_dim), + "balance_scope": "rank_local_microbatch_v1", + }, + "adapters": { + "rank": int(args.adapter_rank), + "placements": ["down0", "down1", "down2", "down3", "up2", "up1", "up0"], + "output_initialization": "zero", + }, + "noise_type_prompt": "zero_initialized_gate_weighted_tokens_v1", + "optimization": { + "shared_trunk_trainable": bool(args.train_shared_trunk), + "new_paths_trainable": True, + }, + "warmstart": dict(audit), + } + + +def _v5_schedule_config(args: argparse.Namespace) -> Dict[str, Any]: + result = dict(_V4_SCHEDULE_CONFIG(args)) + result["noise_routing"] = { + "mixer": NOISE_MIXER_VERSION, + "expert_fraction": float(args.expert_noise_fraction), + "gate_gradient": "stopped", + "schedule_modified": False, + "distribution_semantics": "iid_standard_normal_stochastic_ablation", + } + enabled = bool(getattr(args, "expert_kappa", False)) + result["expert_kappa"] = { + "enabled": enabled, + "version": EXPERT_KAPPA_VERSION if enabled else None, + "values": ( + list(_parse_expert_kappa_values(args.expert_kappa_values)) + if enabled + else None + ), + "anneal_steps": ( + int(args.expert_kappa_anneal_steps) if enabled else None + ), + "gate_gradient": "stopped", + "posterior": "exact_per_sample_kappa", + "modifies_forward_kappa": enabled, + } + return result + + +def _v5_data_plan( + args: argparse.Namespace, + world_size: int, + amp_enabled: Optional[bool] = None, +) -> Dict[str, Any]: + result = dict(_V4_DATA_PLAN(args, world_size, amp_enabled=amp_enabled)) + result["noise_plan"] = NOISE_SEED_VERSION + result["router_balance_topology"] = { + "scope": "rank_local_microbatch_v1", + "world_size": int(world_size), + "local_batch": int(args.batch_size), + } + return result + + +def save_v5_training_checkpoint( + path: Path, + model: nn.Module, + ema: v4.ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + *, + step: int, + contract: v4.CheckpointContract, + history: Sequence[Mapping[str, Any]], + recovery_marker: Optional[Mapping[str, Any]] = None, +) -> None: + payload: Dict[str, Any] = { + "schema_version": V5_SCHEMA_VERSION, + "phase": 2, + "architecture_version": 5, + "step": int(step), + "model_state_dict": v4.unwrap_module(model).state_dict(), + "ema_state_dict": ema.state_dict(), + "optimizer_state_dict": optimizer.state_dict(), + "scheduler_state_dict": scheduler.state_dict(), + "scaler_state_dict": scaler.state_dict(), + "rng_state": v4._rng_state(), + "contract": contract.to_dict(), + "condition_mode": contract.condition_mode, + "phase1_sha256": contract.phase1_sha256, + "phase1_metadata": dict(contract.phase1_metadata), + "train_digest": contract.train_digest, + "val_digest": contract.val_digest, + "schedule_config": dict(contract.schedule), + "architecture": dict(contract.architecture), + "data_plan": dict(contract.data_plan), + "warmstart_audit": dict(contract.architecture.get("warmstart", {})), + "init_model_hash": contract.init_model_hash, + "max_steps": contract.max_steps, + "ema_decay": contract.ema_decay, + "history": [dict(item) for item in history], + } + if recovery_marker is not None: + payload["recovery"] = dict(recovery_marker) + v4._atomic_torch_save(payload, Path(path)) + + +def resume_v5_training_checkpoint( + path: Path, + model: nn.Module, + ema: v4.ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + contract: v4.CheckpointContract, +) -> v4.ResumeState: + checkpoint = v4._torch_load(path, map_location="cpu") + if checkpoint.get("schema_version") != V5_SCHEMA_VERSION or checkpoint.get("phase") != 2: + raise ValueError("not a Phase-2 v5 checkpoint") + v4._validate_contract(checkpoint.get("contract", {}), contract) + for field in ( + "condition_mode", + "phase1_sha256", + "phase1_metadata", + "train_digest", + "val_digest", + "schedule_config", + "architecture", + "data_plan", + "warmstart_audit", + "init_model_hash", + "max_steps", + "ema_decay", + ): + if field == "schedule_config": + expected = contract.to_dict().get("schedule") + elif field == "warmstart_audit": + expected = contract.architecture.get("warmstart", {}) + else: + expected = contract.to_dict().get(field) + if checkpoint.get(field) != expected: + raise ValueError("v5 checkpoint top-level %s mismatch" % field) + state = checkpoint.get("model_state_dict") + if not isinstance(state, Mapping): + raise ValueError("v5 resume checkpoint is missing model state") + _validate_adapter_only_output_head( + state, contract.architecture, "v5 resume checkpoint" + ) + ema_state = checkpoint.get("ema_state_dict") + ema_shadow = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None + if not isinstance(ema_shadow, Mapping): + raise ValueError("v5 resume checkpoint is missing EMA shadow state") + _validate_adapter_only_output_head( + ema_shadow, contract.architecture, "v5 resume EMA" + ) + v4.unwrap_module(model).load_state_dict(state, strict=True) + ema.load_state_dict(ema_state) + optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) + scheduler.load_state_dict(checkpoint["scheduler_state_dict"]) + scaler.load_state_dict(checkpoint["scaler_state_dict"]) + v4._restore_rng_state(checkpoint["rng_state"]) + return v4.ResumeState( + step=int(checkpoint["step"]), + history=[dict(item) for item in checkpoint.get("history", [])], + ) + + +def load_shared_initialization_v5( + path: Path, + model: nn.Module, + *, + target_condition: str, + expected_architecture: Mapping[str, Any], + expected_schedule: Mapping[str, Any], + expected_data_plan: Mapping[str, Any], + expected_phase1_sha256: str, + expected_phase1_metadata: Mapping[str, Any], + expected_train_digest: str, + expected_val_digest: str, + expected_max_steps: int, + expected_ema_decay: float, +) -> str: + checkpoint = v4._torch_load(path, map_location="cpu") + if checkpoint.get("schema_version") != V5_SCHEMA_VERSION or checkpoint.get("phase") != 2: + raise ValueError("initialization must be a Phase-2 v5 checkpoint") + if checkpoint.get("step") != 0: + raise ValueError("shared initialization checkpoint must be at step zero") + source_contract = checkpoint.get("contract") + if not isinstance(source_contract, Mapping): + raise ValueError("initialization checkpoint is missing its contract") + expected_fields: Dict[str, Any] = { + "architecture": dict(expected_architecture), + "schedule": dict(expected_schedule), + "data_plan": dict(expected_data_plan), + "phase1_sha256": str(expected_phase1_sha256), + "phase1_metadata": dict(expected_phase1_metadata), + "train_digest": str(expected_train_digest), + "val_digest": str(expected_val_digest), + "max_steps": int(expected_max_steps), + "ema_decay": float(expected_ema_decay), + } + for field, expected in expected_fields.items(): + if source_contract.get(field) != expected: + raise ValueError("shared v5 initialization %s mismatch" % field) + mirror = "schedule_config" if field == "schedule" else field + if checkpoint.get(mirror) != expected: + raise ValueError("shared v5 top-level %s mismatch" % mirror) + source_condition = source_contract.get("condition_mode") + if source_condition != target_condition and not ( + source_condition == "null" and target_condition == "full" + ): + raise ValueError("shared v5 condition transition is forbidden") + state = checkpoint.get("model_state_dict") + if not isinstance(state, Mapping): + raise ValueError("shared v5 initialization has no model state") + _validate_adapter_only_output_head( + state, expected_architecture, "shared v5 initialization" + ) + target = v4.unwrap_module(model) + # Schedule buffers are scientific configuration rather than trainable + # initialization. Verify their bytes before any state mutates the target. + for name, expected_value in target.schedule.state_dict().items(): + source_value = state.get("schedule." + name) + if not isinstance(source_value, Tensor) or not torch.equal( + source_value.detach().cpu(), expected_value.detach().cpu() + ): + raise ValueError( + "shared v5 initialization schedule buffer mismatch: %s" % name + ) + target.load_state_dict(state, strict=True) + actual_hash = v4.model_state_hash(target) + if ( + source_contract.get("init_model_hash") != actual_hash + or checkpoint.get("init_model_hash") != actual_hash + ): + raise ValueError("shared v5 initialization model hash mismatch") + return actual_hash + + +def build_parser() -> argparse.ArgumentParser: + parser = v4.build_parser() + parser.description = __doc__ + parser.add_argument("--adapter-rank", type=int, default=16) + parser.add_argument("--router-hidden-dim", type=int, default=256) + parser.add_argument("--router-temperature", type=float, default=1.0) + parser.add_argument("--router-max-correction", type=float, default=2.0) + parser.add_argument("--router-anchor-weight", type=float, default=0.01) + parser.add_argument("--router-balance-weight", type=float, default=0.01) + parser.add_argument("--router-correction-weight", type=float, default=0.001) + parser.add_argument( + "--expert-noise-fraction", + type=float, + default=0.0, + help="conditional variance fraction from the independent expert bank", + ) + parser.add_argument( + "--expert-kappa", + action="store_true", + help="scale forward corruption with a gate-weighted per-type kappa", + ) + parser.add_argument( + "--expert-kappa-values", + type=str, + default=None, + help="five comma-separated kappas in EXPERT_ORDER " + "(rain,noise,haze,lowlight,generic)", + ) + parser.add_argument( + "--expert-kappa-anneal-steps", + type=int, + default=2000, + help="optimizer steps to anneal from the global kappa to the " + "gate-weighted per-type kappa (0 disables the anneal)", + ) + parser.add_argument( + "--train-shared-trunk", + action="store_true", + help="also fine-tune v4 shared weights; default trains only v5 paths", + ) + parser.add_argument("--warmstart-v4", type=Path) + parser.add_argument("--warmstart-v4-sha256") + parser.add_argument( + "--warmstart-weight-source", choices=("ema", "model"), default="ema" + ) + return parser + + +def validate_v5_runtime_args(args: argparse.Namespace) -> int: + stop_step = v4.validate_runtime_args(args) + if args.adapter_rank <= 0 or args.router_hidden_dim <= 0: + raise ValueError("adapter and router dimensions must be positive") + for name in ( + "router_temperature", + "router_max_correction", + ): + value = float(getattr(args, name)) + if not math.isfinite(value) or value <= 0.0: + raise ValueError("%s must be finite and positive" % name) + for name in ( + "router_anchor_weight", + "router_balance_weight", + "router_correction_weight", + ): + value = float(getattr(args, name)) + if not math.isfinite(value) or value < 0.0: + raise ValueError("%s must be finite and non-negative" % name) + if not math.isfinite(args.expert_noise_fraction) or not 0.0 <= args.expert_noise_fraction <= 1.0: + raise ValueError("--expert-noise-fraction must lie in [0, 1]") + if bool(getattr(args, "expert_kappa", False)): + _parse_expert_kappa_values(args.expert_kappa_values) + if args.kappa is None: + raise ValueError("--expert-kappa requires an explicit --kappa") + if int(args.expert_kappa_anneal_steps) < 0: + raise ValueError( + "--expert-kappa-anneal-steps must be non-negative" + ) + elif getattr(args, "expert_kappa_values", None) is not None: + raise ValueError( + "--expert-kappa-values is only valid together with --expert-kappa" + ) + has_warmstart_path = args.warmstart_v4 is not None + has_warmstart_sha = args.warmstart_v4_sha256 is not None + if has_warmstart_path != has_warmstart_sha: + raise ValueError("v4 warmstart path and sha256 must be supplied together") + if (args.resume is not None or args.init_checkpoint is not None) and ( + has_warmstart_path or has_warmstart_sha + ): + raise ValueError("v5 resume/init and v4 warmstart are mutually exclusive") + if has_warmstart_sha: + value = str(args.warmstart_v4_sha256).lower() + if len(value) != 64 or any(character not in "0123456789abcdef" for character in value): + raise ValueError("v4 warmstart sha256 must be 64 hexadecimal characters") + has_state_source = ( + args.resume is not None + or args.init_checkpoint is not None + or has_warmstart_path + ) + if ( + not args.calibrate_kappa + and not args.train_shared_trunk + and not has_state_source + ): + raise ValueError( + "adapter-only training requires a v4 warmstart or v5 state source" + ) + return stop_step + + +@contextlib.contextmanager +def _installed_v5_backend(args: argparse.Namespace) -> Iterator[None]: + """Temporarily route the stable v4 runtime through v5 implementations.""" + + def training_plan( + reference: Tensor, + timesteps: int, + seed: int, + global_microstep: int, + rank: int = 0, + sample_seeds: Optional[Sequence[int]] = None, + ) -> Tuple[Tensor, Tensor]: + if float(args.expert_noise_fraction) == 0.0: + timestep_values, shared = _V4_DETERMINISTIC_TRAINING_PLAN( + reference, + timesteps, + seed, + global_microstep, + rank=rank, + sample_seeds=sample_seeds, + ) + shared_bank = shared.unsqueeze(1).expand( + -1, len(EXPERT_ORDER) + 1, -1, -1, -1 + ) + return timestep_values, shared_bank + return deterministic_expert_training_plan( + reference, + timesteps, + seed, + global_microstep, + rank=rank, + sample_seeds=sample_seeds, + ) + + def load_or_create_splits(runtime_args: argparse.Namespace) -> Any: + splits = _V4_LOAD_OR_CREATE_SPLITS(runtime_args) + from src.data.phase2_v4 import split_digest + + setattr(runtime_args, "_v5_train_digest", split_digest(splits.train)) + setattr(runtime_args, "_v5_val_digest", split_digest(splits.val)) + return splits + + replacements = { + "_build_restorer": _build_v5_restorer, + "_load_or_create_splits": load_or_create_splits, + "_architecture": _v5_architecture, + "_schedule_config": _v5_schedule_config, + "_data_plan": _v5_data_plan, + "deterministic_training_plan": training_plan, + "sample_restoration": sample_gated_restoration, + "save_training_checkpoint": save_v5_training_checkpoint, + "resume_training_checkpoint": resume_v5_training_checkpoint, + "load_shared_initialization": load_shared_initialization_v5, + } + originals = {name: getattr(v4, name) for name in replacements} + try: + for name, replacement in replacements.items(): + setattr(v4, name, replacement) + yield + finally: + for name, original in originals.items(): + setattr(v4, name, original) + + +def run(args: argparse.Namespace) -> None: + validate_v5_runtime_args(args) + with _installed_v5_backend(args): + v4.run(args) + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(build_parser().parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_graph_moe_v6.py b/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_graph_moe_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..3ed9eb82197e4ff3421b0e089740005a937b8f7f --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_graph_moe_v6.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python3 +"""Phase 2 v6: graph-MoE restoration on the ll_v3 Phase-1 representation. + +Reuses the stable v4 runtime through a scoped backend install (the v5 +pattern). Differences from v5: + +* independent per-node sigmoid activations, strength = a_k * severity_k, + spatial expert gating, 3x3 experts, top-2 execution (graph_moe_v6.py); +* per-node kappa from normalized strengths (A7 machinery); +* the shared trunk FINETUNES (new Phase-1 changes the conditioning + distribution, so a frozen trunk would be mis-conditioned) — use + --learning-rate 5e-5; +* cross-Phase-1 warm start: v4 weights load although the Phase-1 checkpoint + differs; both SHAs are recorded in the audit; +* evaluation samples with --eval-sample-steps (default 1, the measured + strongest mode). +""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +import math +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterator, Mapping, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn + +import train_phase2_graph_resshift_v4 as v4 +from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule +from src.models.restoration.graph_moe_v6 import ( + MOE_V6_VERSION, + NUM_EXPERTS, + MoEConditionBundleV6, + MoEGraphConditionerV6, + MoEGraphResidualShiftUNetV6, + expert_kappa_from_strengths, +) +from src.models.restoration.graph_resshift_v4 import ( + FrozenPhase1, + ResidualShiftSchedule, + pad_to_multiple, + pixel_shuffle2, + pixel_unshuffle2, +) + +V6_WARMSTART_MAPPING_VERSION = "cross_phase1_shared_keys_v1" +DEFAULT_KAPPA_VALUES = "0.09780,0.03836,0.13436,0.41464,0.11608" + +_V4_ARCHITECTURE = v4._architecture +_V4_SCHEDULE_CONFIG = v4._schedule_config +_V4_DATA_PLAN = v4._data_plan + + +def _is_v6_only_key(name: str) -> bool: + return name.startswith( + ( + "conditioner.node_gate.", + "denoiser.strength_tokens", + "denoiser.down_experts.", + "denoiser.up_experts.", + "expert_kappa.", + ) + ) + + +@dataclass +class MoETrainStepResult: + loss: Tensor + reconstruction_loss: Tensor + gate_loss: Tensor + u0_prediction: Tensor + u0_target: Tensor + u_t: Tensor + kappa: Tensor + + +class Phase2MoEV6Module(nn.Module): + """Trainable v6 module; the frozen Phase-1 encoder stays outside.""" + + def __init__( + self, + conditioner: MoEGraphConditionerV6, + denoiser: MoEGraphResidualShiftUNetV6, + schedule: ResidualShiftSchedule, + expert_kappa: ExpertKappaSchedule, + condition_mode: str, + *, + gate_anchor_weight: float = 0.05, + gate_correction_weight: float = 0.001, + ) -> None: + super().__init__() + if condition_mode not in ("full", "null"): + raise ValueError("condition_mode must be 'full' or 'null'") + self.conditioner = conditioner + self.denoiser = denoiser + self.schedule = schedule + self.expert_kappa = expert_kappa + self.condition_mode = condition_mode + self.gate_anchor_weight = float(gate_anchor_weight) + self.gate_correction_weight = float(gate_correction_weight) + self.eval_sample_steps = 1 + + def build_condition(self, representation: Any) -> MoEConditionBundleV6: + return self.conditioner(representation, mode=self.condition_mode) + + def predict_x0( + self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition + ) -> Tensor: + return self.denoiser(u_t, u_y, timesteps, condition) + + def effective_kappa(self, condition: MoEConditionBundleV6) -> Tensor: + return expert_kappa_from_strengths( + self.expert_kappa, condition.gate, condition.route_active + ) + + def forward( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> Tensor: + return self.training_loss( + clean, degraded, representation, timesteps, noise=noise + ).loss + + def training_loss( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> MoETrainStepResult: + u0 = pixel_unshuffle2(clean) + uy = pixel_unshuffle2(degraded) + condition = self.build_condition(representation) + kappa = self.effective_kappa(condition) + u_t = self.schedule.q_sample(u0, uy, timesteps, noise=noise, kappa=kappa) + prediction = self.predict_x0(u_t, uy, timesteps, condition) + reconstruction = (prediction.float() - u0.float()).square().mean() + gate_loss = ( + self.gate_anchor_weight * condition.gate.anchor_loss.float() + + self.gate_correction_weight + * condition.gate.correction_loss.float() + ) + if self.expert_kappa is not None and self.training: + self.expert_kappa.advance() + return MoETrainStepResult( + loss=reconstruction + gate_loss, + reconstruction_loss=reconstruction, + gate_loss=gate_loss, + u0_prediction=prediction, + u0_target=u0, + u_t=u_t, + kappa=kappa.detach(), + ) + + +@torch.no_grad() +def sample_moe_restoration( + model: nn.Module, + phase1: FrozenPhase1, + degraded: Tensor, + *, + seed: int, + record_ids: Optional[Sequence[str]] = None, + initial_noise: Optional[Tensor] = None, + amp_enabled: Optional[bool] = None, +) -> Tensor: + """One-step x0 by default; the exact posterior chain when configured.""" + + restorer = v4.unwrap_module(model) + if not isinstance(restorer, Phase2MoEV6Module): + raise TypeError("model must wrap Phase2MoEV6Module") + steps = int(getattr(restorer, "eval_sample_steps", 1)) + use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled) + with torch.cuda.amp.autocast(enabled=use_amp): + padded, size = pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + condition = restorer.build_condition(representation) + uy = pixel_unshuffle2(padded) + if initial_noise is None: + initial_noise = v4._noise_for_records( + uy, list(record_ids) if record_ids else None, + seed=seed, stage="initial", + ) + kappa_vector = restorer.effective_kappa(condition) + kappa = restorer.schedule.kappa_factor(kappa_vector, uy) + eta_terminal = restorer.schedule.eta[-1].to(uy.device, uy.dtype) + u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise + batch = uy.shape[0] + if steps <= 1: + timesteps = torch.full( + (batch,), restorer.schedule.timesteps, + device=uy.device, dtype=torch.long, + ) + u_t = restorer.predict_x0(u_t, uy, timesteps, condition) + else: + for step in restorer.schedule.reverse_timesteps(): + timesteps = torch.full( + (batch,), step, device=uy.device, dtype=torch.long + ) + u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition) + mean, variance = restorer.schedule.posterior_mean_variance( + u_t, u0_hat, timesteps, kappa=kappa_vector + ) + if step > 1: + noise = v4._noise_for_records( + u_t, list(record_ids) if record_ids else None, + seed=seed, stage=step, + ) + u_t = mean + torch.sqrt(variance) * noise + else: + u_t = mean + restored = pixel_shuffle2(u_t) + height, width = size + return restored[..., :height, :width].clamp(0.0, 1.0) + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def load_v4_warmstart_moe( + path: Path, + expected_sha256: str, + model: Phase2MoEV6Module, + *, + weight_source: str, +) -> Dict[str, Any]: + """Load shared v4 trunk weights across a deliberate Phase-1 swap. + + Unlike the v5 loader this does NOT require the Phase-1 SHA to match: + v6 exists to move to the ll_v3 representation, and the trunk finetunes + to the new conditioning. Both facts are recorded in the audit. + """ + + actual = _file_sha256(path) + if actual.lower() != str(expected_sha256).lower(): + raise ValueError("v4 warmstart sha256 mismatch") + checkpoint = v4._torch_load(Path(path), map_location="cpu") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("warmstart must be a Phase-2 v4 checkpoint") + if checkpoint.get("condition_mode") != "full": + raise ValueError("v6 warmstart requires a full-condition v4 run") + if weight_source == "model": + state = checkpoint.get("model_state_dict") + elif weight_source == "ema": + ema_state = checkpoint.get("ema_state_dict") + state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None + else: + raise ValueError("weight_source must be 'model' or 'ema'") + if not isinstance(state, Mapping): + raise ValueError("v4 warmstart is missing the selected state") + + target = model.state_dict() + expected_shared = { + name for name in target if not _is_v6_only_key(name) + } + source_keys = set(state.keys()) + if source_keys != expected_shared: + missing = sorted(expected_shared - source_keys) + unexpected = sorted(source_keys - expected_shared) + raise ValueError( + "v4 warmstart shared key mismatch; missing=%r unexpected=%r" + % (missing[:8], unexpected[:8]) + ) + result = model.load_state_dict(state, strict=False) + expected_missing = sorted(name for name in target if _is_v6_only_key(name)) + if sorted(result.missing_keys) != expected_missing or result.unexpected_keys: + raise RuntimeError("v6 warmstart loader violated its allowlist") + return { + "mapping_version": V6_WARMSTART_MAPPING_VERSION, + "source_checkpoint_sha256": actual, + "source_step": int(checkpoint.get("step", -1)), + "weight_source": weight_source, + "source_phase1_sha256": checkpoint.get("phase1_sha256"), + "cross_phase1": True, + "materialized_state_hash": v4.model_state_hash(model), + } + + +def _parse_kappa_values(value: str) -> Tuple[float, ...]: + parts = [float(part) for part in str(value).split(",")] + if len(parts) != NUM_EXPERTS or any( + not math.isfinite(p) or p <= 0 for p in parts + ): + raise ValueError( + "--expert-kappa-values requires %d positive floats" % NUM_EXPERTS + ) + return tuple(parts) + + +def _build_moe_restorer( + args: argparse.Namespace, device: torch.device +) -> Phase2MoEV6Module: + schedule = ResidualShiftSchedule( + timesteps=args.timesteps, eta_end=args.eta_end, + min_noise=args.min_noise, power=args.power, kappa=args.kappa, + ) + conditioner = MoEGraphConditionerV6( + cond_dim=args.cond_dim, stage_dims=args.dims, + gate_hidden_dim=args.gate_hidden_dim, + gate_max_correction=args.gate_max_correction, + ) + denoiser = MoEGraphResidualShiftUNetV6( + dims=args.dims, cond_dim=args.cond_dim, expert_rank=args.expert_rank, + ) + expert_kappa = ExpertKappaSchedule( + kappa_per_expert=_parse_kappa_values(args.expert_kappa_values), + kappa_global=float(args.kappa), + anneal_microsteps=int(args.expert_kappa_anneal_steps) + * int(args.grad_accum), + ) + model = Phase2MoEV6Module( + conditioner=conditioner, denoiser=denoiser, schedule=schedule, + expert_kappa=expert_kappa, condition_mode=args.condition, + gate_anchor_weight=args.gate_anchor_weight, + gate_correction_weight=args.gate_correction_weight, + ) + model.eval_sample_steps = int(args.eval_sample_steps) + if args.resume is None and args.init_checkpoint is None: + if args.warmstart_v4 is None: + raise ValueError("v6 requires --warmstart-v4 (or resume/init)") + audit = load_v4_warmstart_moe( + args.warmstart_v4, args.warmstart_v4_sha256, model, + weight_source=args.warmstart_weight_source, + ) + else: + # Resume/init must reproduce the stored contract exactly, so the + # warm-start audit is read back from the checkpoint being resumed. + source = args.resume if args.resume is not None else args.init_checkpoint + stored = v4._torch_load(Path(source), map_location="cpu") + architecture = stored.get("architecture") if isinstance(stored, Mapping) else None + audit = ( + dict(architecture.get("warmstart", {})) + if isinstance(architecture, Mapping) + else {"mapping_version": "resumed_state"} + ) + del stored + setattr(args, "_v6_warmstart_audit", audit) + # Curriculum stage 1: only the v6 control paths learn while the trunk + # stays at its v4 warm start (run 1 showed that a free trunk under + # full gating from step 0 collapses lowlight/haze). + if bool(getattr(args, "freeze_shared_trunk", False)): + for name, parameter in model.named_parameters(): + parameter.requires_grad_(_is_v6_only_key(name)) + return model.to(device) + + +def _moe_architecture(args: argparse.Namespace) -> Dict[str, Any]: + audit = getattr(args, "_v6_warmstart_audit", {}) + return { + "name": "graph_moe_v6", + "version": 6, + "moe": { + "mechanism": MOE_V6_VERSION, + "expert_rank": int(args.expert_rank), + "gate_hidden_dim": int(args.gate_hidden_dim), + "gate_max_correction": float(args.gate_max_correction), + "activation": "independent_sigmoid_strength_severity", + "execution": "top2", + "spatial_gating": "phase1_maps_blend", + }, + "dims": list(args.dims), + "cond_dim": int(args.cond_dim), + "state_channels": 12, + "prediction": "x0", + "eval_sample_steps": int(args.eval_sample_steps), + "trunk": "v4_warmstart_curriculum", + "warmstart": dict(audit), + } + + +def _moe_schedule_config(args: argparse.Namespace) -> Dict[str, Any]: + result = dict(_V4_SCHEDULE_CONFIG(args)) + result["expert_kappa"] = { + "enabled": True, + "values": list(_parse_kappa_values(args.expert_kappa_values)), + "anneal_steps": int(args.expert_kappa_anneal_steps), + "source": "normalized_node_strengths", + "posterior": "exact_per_sample_kappa", + } + return result + + +def _moe_data_plan( + args: argparse.Namespace, world_size: int, amp_enabled=None +) -> Dict[str, Any]: + result = dict(_V4_DATA_PLAN(args, world_size, amp_enabled=amp_enabled)) + result["noise_plan"] = "v4_single_stream" + return result + + +def build_parser() -> argparse.ArgumentParser: + parser = v4.build_parser() + parser.description = __doc__ + parser.add_argument("--expert-rank", type=int, default=16) + parser.add_argument("--gate-hidden-dim", type=int, default=128) + parser.add_argument("--gate-max-correction", type=float, default=1.0) + parser.add_argument("--gate-anchor-weight", type=float, default=0.05) + parser.add_argument("--gate-correction-weight", type=float, default=0.001) + parser.add_argument( + "--expert-kappa-values", type=str, default=DEFAULT_KAPPA_VALUES + ) + parser.add_argument("--expert-kappa-anneal-steps", type=int, default=1000) + parser.add_argument("--eval-sample-steps", type=int, default=1) + parser.add_argument( + "--freeze-shared-trunk", + action="store_true", + help="curriculum stage 1: train only the v6 control paths", + ) + parser.add_argument("--warmstart-v4", type=Path) + parser.add_argument("--warmstart-v4-sha256") + parser.add_argument( + "--warmstart-weight-source", choices=("ema", "model"), default="ema" + ) + return parser + + +@contextlib.contextmanager +def _installed_v6_backend(args: argparse.Namespace) -> Iterator[None]: + replacements = { + "_build_restorer": _build_moe_restorer, + "_architecture": _moe_architecture, + "_schedule_config": _moe_schedule_config, + "_data_plan": _moe_data_plan, + "sample_restoration": sample_moe_restoration, + } + originals = {name: getattr(v4, name) for name in replacements} + try: + for name, replacement in replacements.items(): + setattr(v4, name, replacement) + yield + finally: + for name, original in originals.items(): + setattr(v4, name, original) + + +def run(args: argparse.Namespace) -> None: + v4.validate_runtime_args(args) + _parse_kappa_values(args.expert_kappa_values) + if args.eval_sample_steps < 1: + raise ValueError("--eval-sample-steps must be >= 1") + has_path = args.warmstart_v4 is not None + has_sha = args.warmstart_v4_sha256 is not None + if has_path != has_sha: + raise ValueError("warmstart path and sha256 go together") + with _installed_v6_backend(args): + v4.run(args) + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(build_parser().parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_graph_resshift_v4.py b/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_graph_resshift_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..eb1135beebd7543b81e41936165198f0882d37b0 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_graph_resshift_v4.py @@ -0,0 +1,2119 @@ +#!/usr/bin/env python3 +"""Train and evaluate graph-conditioned residual-shift restoration (Phase 2 v4). + +Phase 1 is an inference-only representation learner. This entrypoint never +feeds it clean targets, degradation labels, or any other oracle information. +The ``full`` and ``null`` arms instantiate exactly the same trainable module; +the latter masks the continuous graph condition after the conditioner so the +representation-utility gate is parameter matched. + +The implementation intentionally targets Python 3.9 and PyTorch 1.10 because +those are the versions installed on the training host. +""" + +from __future__ import annotations + +import argparse +import contextlib +import dataclasses +import hashlib +import json +import math +import os +import random +import time +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, Iterator, List, Mapping, Optional, Sequence, Tuple + +import numpy as np +import torch +from torch import Tensor, nn +import torch.distributed as dist +import torch.nn.functional as F +from torch.nn.parallel import DistributedDataParallel +from torch.utils.data import DataLoader + +from src.models.restoration.graph_resshift_v4 import ( + BRANCH_ORDER, + PHASE1_AGGREGATION_VERSION, + PHASE1_SCHEMA_VERSION, + FrozenPhase1, + GraphConditionerV4, + GraphResidualShiftUNetV4, + ResidualShiftSchedule, + load_phase1_checkpoint, + pad_to_multiple, + pixel_shuffle2, + pixel_unshuffle2, +) + + +DOMAINS: Tuple[str, ...] = tuple(BRANCH_ORDER) + + +@dataclass +class TrainStepResult: + """The exact x0 objective and useful detached diagnostics.""" + + loss: Tensor + u0_prediction: Tensor + u0_target: Tensor + u_t: Tensor + + +class Phase2RestorationModule(nn.Module): + """Trainable Phase-2 module; the frozen Phase-1 encoder is deliberately absent.""" + + def __init__( + self, + conditioner: GraphConditionerV4, + denoiser: GraphResidualShiftUNetV4, + schedule: ResidualShiftSchedule, + condition_mode: str, + ) -> None: + super().__init__() + if condition_mode not in ("full", "null"): + raise ValueError("condition_mode must be 'full' or 'null'") + self.conditioner = conditioner + self.denoiser = denoiser + self.schedule = schedule + self.condition_mode = condition_mode + + def build_condition(self, representation: Any) -> Any: + return self.conditioner(representation, mode=self.condition_mode) + + def predict_x0( + self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition: Any + ) -> Tensor: + return self.denoiser(u_t, u_y, timesteps, condition) + + def forward( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> Tensor: + """DDP-visible training forward. + + Keeping the objective behind ``forward`` is important: calling a + method on ``module`` directly would bypass DistributedDataParallel's + reducer preparation and make ``no_sync`` accumulation incorrect. + """ + + return self.training_loss( + clean, degraded, representation, timesteps, noise=noise + ).loss + + def training_loss( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> TrainStepResult: + """Uniform-timestep x0 prediction with one unweighted FP32 MSE.""" + + u0 = pixel_unshuffle2(clean) + uy = pixel_unshuffle2(degraded) + u_t = self.schedule.q_sample(u0, uy, timesteps, noise=noise) + prediction = self.predict_x0( + u_t, uy, timesteps, self.build_condition(representation) + ) + # Force the reduction to FP32 even when the U-Net runs under autocast. + loss = (prediction.float() - u0.float()).square().mean() + return TrainStepResult(loss, prediction, u0, u_t) + + +def apply_identity_pairs( + degraded: Tensor, clean: Tensor, probability: float +) -> Tensor: + """Replace a random subset of degraded inputs with their clean targets. + + Teaches the fixed point f(x) = x explicitly (the "do nothing" behaviour + missing from a training distribution that only contains degraded + inputs). Applied BEFORE the frozen Phase-1 call so the representation + sees the clean image too. + """ + + if probability <= 0.0: + return degraded + mask = torch.rand(clean.shape[0], device=clean.device) < float(probability) + if not bool(mask.any()): + return degraded + return torch.where(mask.view(-1, 1, 1, 1), clean, degraded) + + +def identity_pair_mask(batch_size: int, probability: float, device) -> Tensor: + if probability <= 0.0: + return torch.zeros(batch_size, dtype=torch.bool, device=device) + return torch.rand(batch_size, device=device) < float(probability) + + +def exposure_diverse_identity( + clean: Tensor, + full_clean: Optional[Tensor], + identity: Tensor, + generator: torch.Generator, + jitter: float = 0.0, + extra_crop: Optional[Tensor] = None, + extra_full: Optional[Tensor] = None, + extra_prob: float = 0.0, +) -> Tuple[Tensor, Optional[Tensor]]: + """Make identity pairs exposure- and content-diverse (v8). + + The trunk learned an exposure prior ("dark -> brighten, mid -> pull to + the training mean") because identity pairs only ever showed the bright + clean images of the four training domains (scene008 diagnosis: 9 of 12 + lost dB were a global tone shift). For the identity rows this (a) + optionally swaps the clean image for one from an external clean pool and + (b) multiplies input AND target by a random global gain exp(U(-j, j)), + clamped to [0, 1]. Returns the new (clean, full_clean); the caller copies + the identity rows of clean into degraded afterwards, so the pair stays + exactly (x, x). Deterministic through ``generator``. + """ + + if not bool(identity.any()): + return clean, full_clean + batch = clean.shape[0] + new_clean, new_full = clean.clone(), (full_clean.clone() if full_clean is not None else None) + if extra_crop is not None and extra_prob > 0.0: + swap = (torch.rand(batch, generator=generator) < float(extra_prob)).to(clean.device) & identity + if bool(swap.any()): + source = extra_crop[: batch].to(clean.device, clean.dtype) + if source.shape[0] < batch: + repeat = int(math.ceil(batch / source.shape[0])) + source = source.repeat(repeat, 1, 1, 1)[:batch] + new_clean = torch.where(swap.view(-1, 1, 1, 1), source, new_clean) + if new_full is not None: + full_source = (extra_full if extra_full is not None else extra_crop)[: batch] + full_source = full_source.to(clean.device, new_full.dtype) + if full_source.shape[0] < batch: + repeat = int(math.ceil(batch / full_source.shape[0])) + full_source = full_source.repeat(repeat, 1, 1, 1)[:batch] + if full_source.shape[-2:] != new_full.shape[-2:]: + full_source = F.interpolate(full_source, size=new_full.shape[-2:], mode="area") + new_full = torch.where(swap.view(-1, 1, 1, 1), full_source, new_full) + if jitter > 0.0: + log_gain = (torch.rand(batch, generator=generator) * 2.0 - 1.0) * float(jitter) + gain = log_gain.exp().to(clean.device, clean.dtype).view(-1, 1, 1, 1) + gain = torch.where(identity.view(-1, 1, 1, 1), gain, torch.ones_like(gain)) + new_clean = (new_clean * gain).clamp(0.0, 1.0) + if new_full is not None: + new_full = (new_full * gain.to(new_full.dtype)).clamp(0.0, 1.0) + return new_clean, new_full + + +def synthetic_noise_pairs( + degraded: Tensor, + clean: Tensor, + probability: float, + generator: torch.Generator, + full_degraded: Optional[Tensor] = None, + full_clean: Optional[Tensor] = None, +) -> Tuple[Tensor, Optional[Tensor], Tensor]: + """Clean-image prior for the trunk: turn a random subset of pairs into + (clean + heteroscedastic Poisson-Gaussian noise, clean). + + This is what the two-stage refiner had (pretraining on clean + light + corruption over every clean image) and the unified trunk never got. + The same noise parameters are applied to the whole-frame view so the + global context stays consistent with the crop. Deterministic per call + through ``generator``. Returns (degraded, full_degraded, mask).""" + + batch = clean.shape[0] + if probability <= 0.0: + return degraded, full_degraded, torch.zeros(batch, dtype=torch.bool, device=clean.device) + draw = torch.rand(batch, generator=generator) + mask = (draw < float(probability)).to(clean.device) + if not bool(mask.any()): + return degraded, full_degraded, mask + params = torch.rand(batch, 2, generator=generator) + a = (0.0005 + 0.0195 * params[:, 0]).to(clean.device).view(-1, 1, 1, 1) + b = (0.0001 + 0.0049 * params[:, 1]).to(clean.device).view(-1, 1, 1, 1) + eps = torch.randn(clean.shape, generator=generator).to(clean.device) + noisy = (clean + (a * clean.clamp(0, 1) + b).sqrt() * eps).clamp(0.0, 1.0) + new_degraded = torch.where(mask.view(-1, 1, 1, 1), noisy.to(degraded.dtype), degraded) + new_full = full_degraded + if full_degraded is not None and full_clean is not None: + eps_full = torch.randn(full_clean.shape, generator=generator).to(clean.device) + noisy_full = (full_clean + (a * full_clean.clamp(0, 1) + b).sqrt() * eps_full).clamp(0.0, 1.0) + new_full = torch.where(mask.view(-1, 1, 1, 1), noisy_full.to(full_degraded.dtype), full_degraded) + return new_degraded, new_full, mask + + +def extra_clean_files(spec: Any, balance: bool = True) -> List[Path]: + """Image files of one or more clean pools; ``spec`` is a path or a + comma-separated list of paths (v10: Snow100K gt + SIDD GT + LOL GT so + identity pairs cover dark, textured, real-camera clean images). + + ``balance`` repeats the entries of every smaller root until each root + has as many entries as the largest one, so a 121-image SIDD pool is + drawn as often as a 50k-image Snow100K pool (crops are re-randomised per + entry index, so repeated files still yield different crops). + """ + + from src.data.folder_crops import list_image_files + + roots = [part.strip() for part in str(spec).split(",") if part.strip()] + if not roots: + raise ValueError("extra clean pool needs at least one folder") + per_root = [list_image_files(Path(root)) for root in roots] + if any(not files for files in per_root): + raise ValueError("extra clean pool is empty: %s" % spec) + if balance and len(per_root) > 1: + target = max(len(files) for files in per_root) + per_root = [ + (files * int(math.ceil(target / len(files))))[:target] for files in per_root + ] + files: List[Path] = [] + for group in per_root: + files.extend(group) + return files + + +def unwrap_module(module: nn.Module) -> nn.Module: + return module.module if isinstance(module, DistributedDataParallel) else module + + +def _seed_value(seed: int, *parts: Any) -> int: + payload = "\0".join([str(int(seed))] + [str(part) for part in parts]) + digest = hashlib.sha256(payload.encode("utf-8")).digest() + # torch.Generator.manual_seed accepts a signed 64-bit-safe positive value. + return int.from_bytes(digest[:8], "little") % (2 ** 63 - 1) + + +def _cpu_random_tensor(shape: Sequence[int], seed: int, dtype: torch.dtype) -> Tensor: + generator = torch.Generator(device="cpu") + generator.manual_seed(int(seed)) + # CPU float16 normal generation was incomplete in older PyTorch versions. + return torch.randn(tuple(shape), generator=generator, dtype=torch.float32).to(dtype) + + +def deterministic_training_plan( + reference: Tensor, + timesteps: int, + seed: int, + global_microstep: int, + rank: int = 0, + sample_seeds: Optional[Sequence[int]] = None, +) -> Tuple[Tensor, Tensor]: + """Return a reproducible t/noise plan independent of global RNG state. + + ``sample_seeds`` are emitted by the global balanced sampler before its DDP + shard. Using them makes the union of two local rank plans exactly equal to + the corresponding single-GPU global micro-batch plan. + """ + + if timesteps < 1: + raise ValueError("timesteps must be positive") + if sample_seeds is not None: + if len(sample_seeds) != reference.shape[0]: + raise ValueError("one sample seed is required per training image") + timestep_values: List[Tensor] = [] + noises: List[Tensor] = [] + for index, sample_seed in enumerate(sample_seeds): + generator = torch.Generator(device="cpu") + generator.manual_seed( + _seed_value(seed, "train", global_microstep, int(sample_seed)) + ) + timestep_values.append( + torch.randint(1, timesteps + 1, (1,), generator=generator) + ) + noises.append( + torch.randn( + tuple(reference[index].shape), + generator=generator, + dtype=torch.float32, + ) + ) + t = torch.cat(timestep_values, dim=0).long() + noise = torch.stack(noises, dim=0) + return t.to(reference.device), noise.to( + reference.device, dtype=reference.dtype + ) + plan_seed = _seed_value(seed, "train", global_microstep, rank) + generator = torch.Generator(device="cpu") + generator.manual_seed(plan_seed) + t = torch.randint( + 1, timesteps + 1, (reference.shape[0],), generator=generator, dtype=torch.long + ) + noise = torch.randn(tuple(reference.shape), generator=generator, dtype=torch.float32) + return t.to(reference.device), noise.to(reference.device, dtype=reference.dtype) + + +def _noise_for_records( + reference: Tensor, + record_ids: Optional[Sequence[str]], + seed: int, + stage: Any, +) -> Tensor: + if record_ids is None: + return _cpu_random_tensor( + reference.shape, _seed_value(seed, "eval", stage), reference.dtype + ).to(reference.device) + if len(record_ids) != reference.shape[0]: + raise ValueError("one record id is required per image") + samples = [] + for index, record_id in enumerate(record_ids): + samples.append( + _cpu_random_tensor( + reference[index].shape, + _seed_value(seed, "eval", str(record_id), stage), + reference.dtype, + ) + ) + return torch.stack(samples, dim=0).to(reference.device) + + +@torch.no_grad() +def sample_restoration( + model: nn.Module, + phase1: FrozenPhase1, + degraded: Tensor, + *, + seed: int, + record_ids: Optional[Sequence[str]] = None, + initial_noise: Optional[Tensor] = None, + amp_enabled: Optional[bool] = None, +) -> Tensor: + """Run the exact ``T ... 1`` posterior and extract Phase-1 only once.""" + + restorer = unwrap_module(model) + if not isinstance(restorer, Phase2RestorationModule): + raise TypeError("model must wrap Phase2RestorationModule") + use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled) + with torch.cuda.amp.autocast(enabled=use_amp): + padded, original_size = pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + condition = restorer.build_condition(representation) + uy = pixel_unshuffle2(padded) + if initial_noise is None: + initial_noise = _noise_for_records( + uy, record_ids, seed=seed, stage="initial" + ) + elif initial_noise.shape != uy.shape: + raise ValueError("initial_noise must match the padded pixel-unshuffle state") + else: + initial_noise = initial_noise.to(device=uy.device, dtype=uy.dtype) + + eta_terminal = restorer.schedule.eta[-1].to(device=uy.device, dtype=uy.dtype) + kappa = restorer.schedule.kappa.to(device=uy.device, dtype=uy.dtype) + u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise + batch = uy.shape[0] + for step in restorer.schedule.reverse_timesteps(): + t = torch.full((batch,), step, device=uy.device, dtype=torch.long) + u0_hat = restorer.predict_x0(u_t, uy, t, condition) + mean, variance = restorer.schedule.posterior_mean_variance( + u_t, u0_hat, t + ) + if step > 1: + noise = _noise_for_records(u_t, record_ids, seed=seed, stage=step) + u_t = mean + torch.sqrt(variance) * noise + else: + # q(u_0 | u_1, u0_hat) is deterministic; never inject t=1 noise. + u_t = mean + restored = pixel_shuffle2(u_t) + height, width = original_size + return restored[..., :height, :width].clamp(0.0, 1.0) + + +def rgb_psnr_per_image(prediction: Tensor, target: Tensor) -> Tensor: + """Per-image RGB PSNR on [0, 1] values (no batch averaging).""" + + if prediction.shape != target.shape or prediction.ndim != 4: + raise ValueError("PSNR inputs must have the same BCHW shape") + mse = (prediction.float() - target.float()).square().flatten(1).mean(1) + return -10.0 * torch.log10(mse.clamp_min(torch.finfo(torch.float32).tiny)) + + +def _gaussian_window( + window_size: int, sigma: float, channels: int, device: torch.device +) -> Tensor: + coordinates = torch.arange(window_size, device=device, dtype=torch.float32) + coordinates = coordinates - float(window_size - 1) / 2.0 + kernel = torch.exp(-(coordinates.square()) / (2.0 * sigma * sigma)) + kernel = kernel / kernel.sum() + window = torch.outer(kernel, kernel) + return window.reshape(1, 1, window_size, window_size).repeat(channels, 1, 1, 1) + + +def rgb_ssim_per_image( + prediction: Tensor, + target: Tensor, + window_size: int = 11, + sigma: float = 1.5, +) -> Tensor: + """Windowed Gaussian RGB SSIM, reduced separately for every image.""" + + if prediction.shape != target.shape or prediction.ndim != 4: + raise ValueError("SSIM inputs must have the same BCHW shape") + if window_size <= 0 or window_size % 2 == 0: + raise ValueError("window_size must be a positive odd integer") + x, y = prediction.float(), target.float() + channels = x.shape[1] + window = _gaussian_window(window_size, sigma, channels, x.device) + padding = window_size // 2 + pad_mode = ( + "reflect" + if x.shape[-2] > padding and x.shape[-1] > padding + else "replicate" + ) + x_pad = F.pad(x, (padding, padding, padding, padding), mode=pad_mode) + y_pad = F.pad(y, (padding, padding, padding, padding), mode=pad_mode) + mu_x = F.conv2d(x_pad, window, groups=channels) + mu_y = F.conv2d(y_pad, window, groups=channels) + mu_x_sq, mu_y_sq, mu_xy = mu_x.square(), mu_y.square(), mu_x * mu_y + sigma_x = F.conv2d(x_pad * x_pad, window, groups=channels) - mu_x_sq + sigma_y = F.conv2d(y_pad * y_pad, window, groups=channels) - mu_y_sq + sigma_xy = F.conv2d(x_pad * y_pad, window, groups=channels) - mu_xy + c1, c2 = 0.01 ** 2, 0.03 ** 2 + numerator = (2.0 * mu_xy + c1) * (2.0 * sigma_xy + c2) + denominator = (mu_x_sq + mu_y_sq + c1) * (sigma_x + sigma_y + c2) + return (numerator / denominator.clamp_min(1e-12)).flatten(1).mean(1) + + +class DomainMetricAccumulator: + """Domain-first metric reduction used for model selection.""" + + def __init__(self, domains: Sequence[str] = DOMAINS) -> None: + self.domains = tuple(domains) + self.values: Dict[str, Dict[str, List[float]]] = { + domain: {"psnr": [], "ssim": []} for domain in self.domains + } + + def update(self, domain: str, psnr: float, ssim: float) -> None: + if domain not in self.values: + raise ValueError("unknown evaluation domain %r" % domain) + self.values[domain]["psnr"].append(float(psnr)) + self.values[domain]["ssim"].append(float(ssim)) + + def compute(self) -> Dict[str, Any]: + missing = [domain for domain in self.domains if not self.values[domain]["psnr"]] + if missing: + raise ValueError("evaluation has no images for domains %r" % missing) + per_domain: Dict[str, Dict[str, Any]] = {} + for domain in self.domains: + values = self.values[domain] + per_domain[domain] = { + "psnr": float(np.mean(values["psnr"])), + "ssim": float(np.mean(values["ssim"])), + "count": len(values["psnr"]), + } + macro_psnr = float(np.mean([per_domain[d]["psnr"] for d in self.domains])) + macro_ssim = float(np.mean([per_domain[d]["ssim"] for d in self.domains])) + all_psnr = [value for d in self.domains for value in self.values[d]["psnr"]] + all_ssim = [value for d in self.domains for value in self.values[d]["ssim"]] + return { + "per_domain": per_domain, + "macro_psnr": macro_psnr, + "macro_ssim": macro_ssim, + "image_weighted_psnr": float(np.mean(all_psnr)), + "image_weighted_ssim": float(np.mean(all_ssim)), + } + + +@torch.no_grad() +def evaluate( + model: nn.Module, + phase1: FrozenPhase1, + loader: Iterable[Mapping[str, Any]], + device: torch.device, + seed: int, + amp_enabled: Optional[bool] = None, +) -> Dict[str, Any]: + """Evaluate restoration and the degraded-input baseline in fixed order.""" + + model.eval() + phase1.eval() + restored_metrics = DomainMetricAccumulator() + baseline_metrics = DomainMetricAccumulator() + for batch in loader: + degraded = batch["degraded"].to(device, non_blocking=True) + clean = batch["clean"].to(device, non_blocking=True) + domains = [str(value) for value in batch["degradation"]] + record_ids = [str(value) for value in batch["record_id"]] + extra: Dict[str, Any] = {} + if "full_degraded" in batch and getattr(sample_restoration, "accepts_full_frame", False): + extra["full_degraded"] = batch["full_degraded"].to(device, non_blocking=True) + restored = sample_restoration( + model, + phase1, + degraded, + seed=seed, + record_ids=record_ids, + amp_enabled=amp_enabled, + **extra, + ) + psnr = rgb_psnr_per_image(restored, clean).cpu().tolist() + ssim = rgb_ssim_per_image(restored, clean).cpu().tolist() + base_psnr = rgb_psnr_per_image(degraded, clean).cpu().tolist() + base_ssim = rgb_ssim_per_image(degraded, clean).cpu().tolist() + for index, domain in enumerate(domains): + restored_metrics.update(domain, psnr[index], ssim[index]) + baseline_metrics.update(domain, base_psnr[index], base_ssim[index]) + return { + "restored": restored_metrics.compute(), + "degraded_baseline": baseline_metrics.compute(), + } + + +class ExponentialMovingAverage: + """Device-resident EMA over parameters and persistent buffers.""" + + def __init__(self, module: nn.Module, decay: float = 0.9999) -> None: + if not 0.0 <= decay < 1.0: + raise ValueError("EMA decay must satisfy 0 <= decay < 1") + self.decay = float(decay) + self.num_updates = 0 + self.shadow = { + name: value.detach().clone() + for name, value in unwrap_module(module).state_dict().items() + } + + @torch.no_grad() + def update(self, module: nn.Module) -> None: + current = unwrap_module(module).state_dict() + if current.keys() != self.shadow.keys(): + raise ValueError("EMA/model state keys changed") + self.num_updates += 1 + warmup_decay = float(1 + self.num_updates) / float(10 + self.num_updates) + effective_decay = min(self.decay, warmup_decay) + for name, value in current.items(): + source = value.detach() + if torch.is_floating_point(source): + self.shadow[name].mul_(effective_decay).add_( + source, alpha=1.0 - effective_decay + ) + else: + self.shadow[name].copy_(source) + + def state_dict(self) -> Dict[str, Any]: + return { + "decay": self.decay, + "num_updates": self.num_updates, + "shadow": {name: value.clone() for name, value in self.shadow.items()}, + } + + def load_state_dict(self, state: Mapping[str, Any]) -> None: + if float(state["decay"]) != self.decay: + raise ValueError("EMA decay mismatch") + update_count = state.get("num_updates") + if isinstance(update_count, bool) or not isinstance(update_count, int): + raise ValueError("EMA state is missing a valid update count") + if update_count < 0: + raise ValueError("EMA update count cannot be negative") + self.num_updates = update_count + shadow = state["shadow"] + if shadow.keys() != self.shadow.keys(): + raise ValueError("EMA state keys mismatch") + self.shadow = { + name: value.to( + device=self.shadow[name].device, dtype=self.shadow[name].dtype + ).clone() + for name, value in shadow.items() + } + + @contextlib.contextmanager + def apply(self, module: nn.Module) -> Iterator[None]: + target = unwrap_module(module) + original = {name: value.detach().clone() for name, value in target.state_dict().items()} + target.load_state_dict(self.shadow, strict=True) + try: + yield + finally: + target.load_state_dict(original, strict=True) + + +def make_grad_scaler(enabled: bool) -> torch.cuda.amp.GradScaler: + return torch.cuda.amp.GradScaler(enabled=bool(enabled)) + + +def scaler_step_or_fail( + scaler: torch.cuda.amp.GradScaler, + optimizer: torch.optim.Optimizer, +) -> None: + """Apply one AMP step, failing before any logical cursor can advance. + + PyTorch signals a skipped optimizer update by reducing the dynamic scale. + Continuing would desynchronize the sample cursor, LR scheduler, and EMA + from actual parameter updates, so deterministic v4 runs stop and resume + from their last atomic checkpoint instead. + """ + + scale_before = float(scaler.get_scale()) + scaler.step(optimizer) + scaler.update() + scale_after = float(scaler.get_scale()) + if scale_after < scale_before: + optimizer.zero_grad(set_to_none=True) + raise FloatingPointError( + "AMP overflow skipped the optimizer update; run stopped before " + "advancing scheduler, EMA, or logical step" + ) + + +class RecoverableAmpOverflow(FloatingPointError): + """AMP gradient overflow with an atomic unchanged-step resume checkpoint.""" + + +def collective_device() -> torch.device: + """Device the NCCL collectives must run on for this process.""" + + if torch.cuda.is_available(): + return torch.device("cuda", torch.cuda.current_device()) + return torch.device("cpu") + + +def has_any_gradient(model: nn.Module) -> bool: + """False when a step produced no gradient at all (every micro-batch was + dropped), in which case there is nothing to clip, reduce or apply.""" + + return any(p.grad is not None for p in unwrap_module(model).parameters()) + + +def is_globally_finite_scalar(value: Tensor) -> bool: + """Synchronize a scalar finite/non-finite decision across all DDP ranks.""" + + detached = value.detach() + if detached.numel() != 1: + raise ValueError("finite check requires a scalar tensor") + finite = torch.isfinite(detached).all().to(dtype=torch.int32) + if dist.is_available() and dist.is_initialized(): + # clip_grad_norm_ returns a CPU scalar when no parameter carries a + # gradient; NCCL rejects that with "Tensors must be CUDA and dense". + finite = finite.to(collective_device()) + dist.all_reduce(finite, op=dist.ReduceOp.MIN) + return bool(finite.item()) + + +def require_finite_tensor(value: Tensor, name: str) -> float: + """Return a scalar diagnostic or fail every DDP rank before state advances.""" + + if not is_globally_finite_scalar(value): + raise FloatingPointError("non-finite %s" % name) + return float(value.detach().float().item()) + + +def nonfinite_loss_within_budget( + *, consecutive: int, total: int, max_consecutive: int = 5, max_total: int = 100 +) -> bool: + """Isolated fp16 spikes are tolerable; a persistent NaN is not.""" + + return int(consecutive) < int(max_consecutive) and int(total) <= int(max_total) + + +# The encoder half of the Uformer denoiser: everything that consumes the +# input image on the way down. Freezing it for the first steps of a run lets +# the decoder, the conditioning path and the heads re-adapt to a NEW Phase-1 +# conditioning without disturbing generic features (the v6.1 lesson: opening +# the whole trunk from step 0 reproduces cross-domain interference). +ENCODER_PARAMETER_TOKENS: Tuple[str, ...] = ( + "input_projection", "down_blocks", "down_attentions", "downsamples", "down_experts", +) + + +def is_encoder_parameter(name: str) -> bool: + return any(token in name.split(".") for token in ENCODER_PARAMETER_TOKENS) + + +def mask_encoder_gradients(model: nn.Module) -> int: + """Drop encoder gradients before the optimizer sees them. + + Preferred over toggling ``requires_grad`` because DistributedDataParallel + fixes its reduction buckets at construction time; masking keeps the + backward graph identical and simply discards the reduced gradients. + """ + + masked = 0 + for name, parameter in unwrap_module(model).named_parameters(): + if parameter.grad is not None and is_encoder_parameter(name): + parameter.grad = None + masked += 1 + return masked + + +class EarlyStopper: + """Stop when ``patience`` consecutive evaluations bring no real gain.""" + + def __init__(self, patience: int, min_delta: float = 0.02) -> None: + self.patience = int(patience) + self.min_delta = float(min_delta) + self.best = -math.inf + self.strikes = 0 + + def update(self, score: float) -> bool: + if self.patience <= 0: + return False + value = float(score) + if value > self.best + self.min_delta: + self.best = value + self.strikes = 0 + return False + self.best = max(self.best, value) + self.strikes += 1 + return self.strikes >= self.patience + + def state_dict(self) -> Dict[str, Any]: + return {"best": float(self.best), "strikes": int(self.strikes)} + + def load_state_dict(self, state: Mapping[str, Any]) -> None: + """Restore best/strikes across an overflow resume (otherwise a resumed + run silently restarts its patience budget).""" + + self.best = float(state.get("best", -math.inf)) + self.strikes = int(state.get("strikes", 0)) + + +def loss_overflow_action(loss: Tensor, *, amp_enabled: bool) -> str: + """Decide what a (possibly non-finite) forward loss means. + + A NaN/Inf produced inside ``autocast`` is an fp16 range failure in the + forward pass. The AMP loss scale only multiplies the backward pass, so + backing it off and replaying the same batch reproduces the same NaN; + the batch is dropped instead (``skip``) and the step proceeds with the + remaining micro-batches. In fp32 a non-finite loss is a real defect and + stays fatal. + """ + + if is_globally_finite_scalar(loss): + return "ok" + return "skip" if amp_enabled else "fail" + + +def model_state_hash(module: nn.Module) -> str: + digest = hashlib.sha256() + for name, value in sorted(unwrap_module(module).state_dict().items()): + tensor = value.detach().cpu().contiguous() + digest.update(name.encode("utf-8")) + digest.update(str(tuple(tensor.shape)).encode("ascii")) + digest.update(str(tensor.dtype).encode("ascii")) + if tensor.dtype == torch.bfloat16: + tensor = tensor.float() + digest.update(tensor.numpy().tobytes()) + return digest.hexdigest() + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + while True: + block = handle.read(1024 * 1024) + if not block: + break + digest.update(block) + return digest.hexdigest() + + +def validate_phase1_artifact_header( + path: Path, expected_sha256: str +) -> Mapping[str, Any]: + """Pin calibration provenance without instantiating the unused encoder.""" + + actual_sha256 = _file_sha256(path) + if actual_sha256.lower() != str(expected_sha256).lower(): + raise ValueError( + "Phase-1 sha256 mismatch: expected %s, received %s" + % (expected_sha256, actual_sha256) + ) + checkpoint = _torch_load(path, map_location="cpu") + expected = { + "schema_version": PHASE1_SCHEMA_VERSION, + "phase": 1, + "aggregation_version": PHASE1_AGGREGATION_VERSION, + "branch_order": list(BRANCH_ORDER), + } + for field, value in expected.items(): + actual = checkpoint.get(field) + if field == "branch_order" and actual is not None: + actual = list(actual) + if actual != value: + raise ValueError( + "Phase-1 %s mismatch: expected %r, received %r" + % (field, value, actual) + ) + return checkpoint + + +@dataclass(frozen=True) +class CheckpointContract: + condition_mode: str + phase1_sha256: str + phase1_metadata: Mapping[str, Any] + train_digest: str + val_digest: str + schedule: Mapping[str, Any] + architecture: Mapping[str, Any] + data_plan: Mapping[str, Any] + init_model_hash: str + max_steps: int + ema_decay: float + + def to_dict(self) -> Dict[str, Any]: + return dataclasses.asdict(self) + + +@dataclass +class ResumeState: + step: int + history: List[Dict[str, Any]] + early_stop: Optional[Dict[str, Any]] = None + + +def _rng_state() -> Dict[str, Any]: + state: Dict[str, Any] = { + "python": random.getstate(), + "numpy": np.random.get_state(), + "torch": torch.get_rng_state(), + } + if torch.cuda.is_available(): + state["cuda"] = torch.cuda.get_rng_state_all() + return state + + +def _restore_rng_state(state: Mapping[str, Any]) -> None: + random.setstate(state["python"]) + np.random.set_state(state["numpy"]) + torch.set_rng_state(state["torch"]) + if torch.cuda.is_available() and "cuda" in state: + device_index = torch.cuda.current_device() + cuda_states = state["cuda"] + # In torchrun every process may see every GPU. Restoring all devices + # from every rank would create a cross-process race; each rank owns and + # restores only its active device. A single-visible-GPU gate checkpoint + # has one saved stream; it is the portable source stream for every rank. + source_index = device_index if device_index < len(cuda_states) else 0 + torch.cuda.set_rng_state(cuda_states[source_index], device=device_index) + + +def _atomic_torch_save(payload: Any, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(".%s.%d.tmp" % (path.name, os.getpid())) + try: + torch.save(payload, str(temporary)) + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +def _torch_load(path: Path, map_location: Any = "cpu") -> Any: + try: + return torch.load(str(path), map_location=map_location, weights_only=False) + except TypeError: + return torch.load(str(path), map_location=map_location) + + +def save_training_checkpoint( + path: Path, + model: nn.Module, + ema: ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + *, + step: int, + contract: CheckpointContract, + history: Sequence[Mapping[str, Any]], + recovery_marker: Optional[Mapping[str, Any]] = None, + early_stop: Optional[Mapping[str, Any]] = None, +) -> None: + payload = { + "schema_version": 4, + "phase": 2, + "step": int(step), + "model_state_dict": unwrap_module(model).state_dict(), + "ema_state_dict": ema.state_dict(), + "optimizer_state_dict": optimizer.state_dict(), + "scheduler_state_dict": scheduler.state_dict(), + "scaler_state_dict": scaler.state_dict(), + "rng_state": _rng_state(), + "early_stop": dict(early_stop) if early_stop is not None else None, + "contract": contract.to_dict(), + "condition_mode": contract.condition_mode, + "phase1_sha256": contract.phase1_sha256, + "phase1_metadata": dict(contract.phase1_metadata), + "train_digest": contract.train_digest, + "val_digest": contract.val_digest, + "schedule_config": dict(contract.schedule), + "architecture": dict(contract.architecture), + "init_model_hash": contract.init_model_hash, + "max_steps": contract.max_steps, + "ema_decay": contract.ema_decay, + "history": [dict(item) for item in history], + } + if recovery_marker is not None: + payload["recovery"] = dict(recovery_marker) + _atomic_torch_save(payload, Path(path)) + + +def recover_amp_gradient_overflow( + path: Path, + model: nn.Module, + ema: ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + *, + step: int, + contract: CheckpointContract, + history: Sequence[Mapping[str, Any]], + rank: int, + distributed: bool, + observed_grad_norm: float, + reason: str = "nonfinite_gradient_norm", + early_stop: Optional[Mapping[str, Any]] = None, +) -> None: + """Back off AMP exactly once, checkpoint unchanged state, then stop. + + This function is entered only after a globally synchronized non-finite + gradient decision. ``GradScaler.update(new_scale=...)`` both applies the + explicit backoff and resets its per-optimizer UNSCALED stage. The growth + tracker is reset separately because the public update API intentionally + preserves it when a caller supplies a scale. + """ + + scale_before = float(scaler.get_scale()) + scale_after = scale_before * float(scaler.get_backoff_factor()) + if not math.isfinite(scale_after) or scale_after <= 0.0: + raise FloatingPointError("AMP scaler produced an invalid recovery scale") + scaler.update(new_scale=scale_after) + growth_tracker = getattr(scaler, "_growth_tracker", None) + if not isinstance(growth_tracker, Tensor): + raise RuntimeError("AMP scaler growth tracker is unavailable for recovery") + growth_tracker.zero_() + optimizer.zero_grad(set_to_none=True) + + marker = { + "schema_version": 1, + "reason": str(reason), + "step": int(step), + "observed_grad_norm": repr(float(observed_grad_norm)), + "scale_before": scale_before, + "scale_after": scale_after, + "growth_tracker_reset": 0, + "optimizer_step_applied": False, + "replay_logical_step": int(step), + } + save_error: Optional[Exception] = None + if rank == 0: + try: + save_training_checkpoint( + path, + model, + ema, + optimizer, + scheduler, + scaler, + step=step, + contract=contract, + history=history, + recovery_marker=marker, + early_stop=early_stop, + ) + except Exception as error: # synchronize filesystem failures across DDP + save_error = error + save_succeeded = save_error is None + if distributed: + parameter = next(unwrap_module(model).parameters(), None) + flag_device = parameter.device if parameter is not None else torch.device("cpu") + save_flag = torch.tensor( + 1 if save_succeeded else 0, + dtype=torch.int32, + device=flag_device, + ) + # Every rank participates even when rank zero's atomic write failed, + # avoiding peers hanging forever in the subsequent success barrier. + dist.broadcast(save_flag, src=0) + save_succeeded = bool(save_flag.item()) + if not save_succeeded: + detail = ": %s" % save_error if save_error is not None else "" + raise RecoverableAmpOverflow( + "AMP overflow recovery checkpoint save failed on rank 0 at %s%s; " + "logical step %d was not advanced" + % (path, detail, step) + ) from save_error + if distributed: + dist.barrier() + raise RecoverableAmpOverflow( + "%s at logical step %d; scaler backed off " + "from %g to %g and recovery checkpoint saved at %s; resume from it " + "to replay the unchanged step" + % ( + "non-finite AMP gradient norm" + if reason == "nonfinite_gradient_norm" + else "non-finite AMP forward loss", + step, scale_before, scale_after, path, + ) + ) + + +def _contract_mismatches(actual: Any, expected: Any, path: str, added: List[str]) -> List[str]: + """Recursive comparison; a key that exists in ``expected`` (the running + code) but not in the stored ``actual`` is a field ADDED to the + architecture/schedule record after the checkpoint was written (recorded + in ``added``, tolerated); any other difference is a mismatch.""" + + if isinstance(expected, Mapping) and isinstance(actual, Mapping): + problems: List[str] = [] + for key in sorted(set(expected) | set(actual)): + child = "%s.%s" % (path, key) if path else str(key) + if key not in actual: + added.append(child) + continue + if key not in expected: + problems.append("%s removed" % child) + continue + problems.extend(_contract_mismatches(actual[key], expected[key], child, added)) + return problems + if actual != expected: + return ["%s: expected %r, received %r" % (path, expected, actual)] + return [] + + +def _validate_contract(actual: Mapping[str, Any], expected: CheckpointContract) -> None: + expected_fields = expected.to_dict() + for name, expected_value in expected_fields.items(): + actual_value = actual.get(name) + if actual_value == expected_value: + continue + added: List[str] = [] + problems = _contract_mismatches(actual_value, expected_value, name, added) + if problems: + raise ValueError( + "checkpoint contract %s mismatch: %s" % (name, "; ".join(problems[:6])) + ) + if added: + print( + "[resume] contract %s: tolerating %d field(s) added after the checkpoint: %s" + % (name, len(added), ", ".join(added[:8])), + flush=True, + ) + + +def resume_training_checkpoint( + path: Path, + model: nn.Module, + ema: ExponentialMovingAverage, + optimizer: torch.optim.Optimizer, + scheduler: torch.optim.lr_scheduler._LRScheduler, + scaler: torch.cuda.amp.GradScaler, + contract: CheckpointContract, +) -> ResumeState: + checkpoint = _torch_load(Path(path), map_location="cpu") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("not a Phase-2 v4 checkpoint") + _validate_contract(checkpoint.get("contract", {}), contract) + unwrap_module(model).load_state_dict(checkpoint["model_state_dict"], strict=True) + ema.load_state_dict(checkpoint["ema_state_dict"]) + optimizer.load_state_dict(checkpoint["optimizer_state_dict"]) + scheduler.load_state_dict(checkpoint["scheduler_state_dict"]) + scaler.load_state_dict(checkpoint["scaler_state_dict"]) + _restore_rng_state(checkpoint["rng_state"]) + stored_early_stop = checkpoint.get("early_stop") + return ResumeState( + step=int(checkpoint["step"]), + history=[dict(item) for item in checkpoint.get("history", [])], + early_stop=dict(stored_early_stop) if isinstance(stored_early_stop, Mapping) else None, + ) + + +def load_shared_initialization( + path: Path, + model: nn.Module, + *, + target_condition: str, + expected_architecture: Mapping[str, Any], + expected_schedule: Mapping[str, Any], + expected_data_plan: Mapping[str, Any], + expected_phase1_sha256: str, + expected_phase1_metadata: Mapping[str, Any], + expected_train_digest: str, + expected_val_digest: str, + expected_max_steps: int, + expected_ema_decay: float, +) -> str: + """Load a provenance-checked step-zero D0 initialization for the D5 gate.""" + + checkpoint = _torch_load(Path(path), map_location="cpu") + if not isinstance(checkpoint, Mapping): + raise ValueError("initialization checkpoint must be a mapping") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("initialization must be a Phase-2 v4 checkpoint") + source_step = checkpoint.get("step") + if isinstance(source_step, bool) or source_step != 0: + raise ValueError("shared initialization checkpoint must be at step zero") + source_contract = checkpoint.get("contract") + if not isinstance(source_contract, Mapping): + raise ValueError("initialization checkpoint is missing its contract") + for field, expected in ( + ("architecture", dict(expected_architecture)), + ("schedule", dict(expected_schedule)), + ("data_plan", dict(expected_data_plan)), + ): + if source_contract.get(field) != expected: + raise ValueError("shared initialization %s mismatch" % field) + expected_provenance: Dict[str, Any] = { + "phase1_sha256": str(expected_phase1_sha256), + "phase1_metadata": dict(expected_phase1_metadata), + "train_digest": str(expected_train_digest), + "val_digest": str(expected_val_digest), + "max_steps": int(expected_max_steps), + "ema_decay": float(expected_ema_decay), + } + # Validate both the canonical contract and its top-level audit mirrors. + # Requiring both prevents a partially edited checkpoint from becoming the + # shared D0/D5 initialization source. + for field, expected in expected_provenance.items(): + if source_contract.get(field) != expected: + raise ValueError( + "shared initialization contract %s mismatch" % field + ) + if checkpoint.get(field) != expected: + raise ValueError( + "shared initialization top-level %s mismatch" % field + ) + source_condition = source_contract.get("condition_mode") + if source_condition != target_condition and not ( + source_condition == "null" and target_condition == "full" + ): + raise ValueError( + "shared initialization condition transition %r -> %r is forbidden" + % (source_condition, target_condition) + ) + state = checkpoint.get("model_state_dict") + if not isinstance(state, Mapping): + raise ValueError("initialization checkpoint has no model state") + + target = unwrap_module(model) + # Schedule buffers are immutable scientific configuration, not trainable + # initialization. Compare them before loading so a mislabeled checkpoint + # cannot overwrite the CLI-built schedule while recording a different one. + for name, expected_value in target.schedule.state_dict().items(): + source_value = state.get("schedule." + name) + if not isinstance(source_value, Tensor) or not torch.equal( + source_value.detach().cpu(), expected_value.detach().cpu() + ): + raise ValueError("shared initialization schedule buffer mismatch: %s" % name) + target.load_state_dict(state, strict=True) + actual_hash = model_state_hash(target) + recorded_hash = source_contract.get("init_model_hash") + if recorded_hash != actual_hash or checkpoint.get("init_model_hash") != actual_hash: + raise ValueError("shared initialization model hash mismatch") + return actual_hash + + +class BoundedCheckpointManager: + """Only init/last/best/recovery plus at most three milestone files.""" + + def __init__(self, output_dir: Path, max_milestones: int = 3) -> None: + if max_milestones < 0 or max_milestones > 3: + raise ValueError("max_milestones must be between zero and three") + self.output_dir = Path(output_dir) + self.max_milestones = int(max_milestones) + + def path_for(self, kind: str, step: Optional[int] = None) -> Path: + if kind in ("init", "last", "best", "overflow_recovery"): + return self.output_dir / (kind + ".pt") + if kind == "milestone" and step is not None: + return self.output_dir / ("milestone_%08d.pt" % int(step)) + raise ValueError("unsupported checkpoint kind") + + def prune_milestones(self) -> None: + files = sorted(self.output_dir.glob("milestone_*.pt")) + for obsolete in files[: max(0, len(files) - self.max_milestones)]: + obsolete.unlink() + + +def build_lr_scheduler( + optimizer: torch.optim.Optimizer, + max_steps: int, + warmup_steps: int = 500, + min_lr: float = 1e-6, + base_lr: float = 1e-4, +) -> torch.optim.lr_scheduler.LambdaLR: + if max_steps <= warmup_steps: + raise ValueError("max_steps must exceed warmup_steps") + minimum_ratio = float(min_lr) / float(base_lr) + + def multiplier(step: int) -> float: + if step < warmup_steps: + return max(float(step + 1) / float(warmup_steps), 1.0 / warmup_steps) + progress = min(1.0, float(step - warmup_steps) / float(max_steps - warmup_steps)) + cosine = 0.5 * (1.0 + math.cos(math.pi * progress)) + return minimum_ratio + (1.0 - minimum_ratio) * cosine + + return torch.optim.lr_scheduler.LambdaLR(optimizer, multiplier) + + +def _atomic_json_dump(payload: Any, path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(".%s.%d.tmp" % (path.name, os.getpid())) + try: + with temporary.open("w", encoding="utf-8") as handle: + json.dump(payload, handle, indent=2, sort_keys=True) + handle.write("\n") + os.replace(str(temporary), str(path)) + finally: + if temporary.exists(): + temporary.unlink() + + +def _append_jsonl(payload: Mapping[str, Any], path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(dict(payload), sort_keys=True) + "\n") + + +@torch.no_grad() +def calibrate_kappa( + loader: Iterable[Mapping[str, Any]], + output_path: Path, + max_images: int = 4096, +) -> Dict[str, Any]: + """Train-only residual RMS audit; recommendation is the macro domain median.""" + + values: Dict[str, List[float]] = {domain: [] for domain in DOMAINS} + seen = 0 + for batch in loader: + clean = batch["clean"] + degraded = batch["degraded"] + domains = [str(value) for value in batch["degradation"]] + u0, uy = pixel_unshuffle2(clean), pixel_unshuffle2(degraded) + rms = (uy.float() - u0.float()).square().flatten(1).mean(1).sqrt().tolist() + for domain, value in zip(domains, rms): + values[domain].append(float(value)) + seen += 1 + if seen >= max_images: + break + if seen >= max_images: + break + missing = [domain for domain in DOMAINS if not values[domain]] + if missing: + raise ValueError("kappa calibration has no training samples for %r" % missing) + medians = {domain: float(np.median(values[domain])) for domain in DOMAINS} + payload = { + "schema_version": 1, + "source": "training_split_only", + "num_images": seen, + "per_domain_residual_rms_median": medians, + "recommended_kappa": float(np.median(list(medians.values()))), + } + _atomic_json_dump(payload, Path(output_path)) + return payload + + +def _parse_int_csv(value: str) -> Tuple[int, ...]: + if not value.strip(): + return () + result = tuple(sorted(set(int(item.strip()) for item in value.split(",")))) + if any(item < 0 for item in result): + raise argparse.ArgumentTypeError("steps must be non-negative") + return result + + +def _parse_dims(value: str) -> Tuple[int, int, int, int]: + result = tuple(int(item.strip()) for item in value.split(",")) + if len(result) != 4 or any(item <= 0 for item in result): + raise argparse.ArgumentTypeError("dims must be four positive comma-separated integers") + return result # type: ignore[return-value] + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--condition", choices=("full", "null"), default="full") + parser.add_argument("--phase1-checkpoint", type=Path, required=True) + parser.add_argument("--phase1-sha256", required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--create-manifest", action="store_true") + parser.add_argument("--data-root", type=Path, default=Path(os.environ.get("SCDC_DATA_ROOT", "/home/admin_mcn/data"))) + parser.add_argument("--rain13k-root", type=Path) + parser.add_argument("--quarantine-manifest", type=Path) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--batch-size", type=int, default=8) + parser.add_argument("--eval-batch-size", type=int, default=4) + parser.add_argument("--grad-accum", type=int, default=2) + parser.add_argument("--max-steps", type=int, default=40_000) + parser.add_argument("--run-until-step", type=int, default=None) + parser.add_argument( + "--eval-steps", + type=_parse_int_csv, + default=(0, 500, 1000, 2000, 5000, 10000, 20000, 40000), + ) + parser.add_argument("--milestone-steps", type=_parse_int_csv, default=()) + parser.add_argument("--workers", type=int, default=8) + parser.add_argument( + "--extra-clean-workers", type=int, default=2, + help="DataLoader workers for the extra clean pool (12 MP SIDD PNGs decode slowly; " + "2 workers capped the MI325X run at ~20%% GPU use)", + ) + parser.add_argument("--crop-size", type=int, default=256) + parser.add_argument("--dims", type=_parse_dims, default=(64, 128, 192, 256)) + parser.add_argument("--cond-dim", type=int, default=256) + parser.add_argument("--timesteps", type=int, default=8) + parser.add_argument("--eta-end", type=float, default=0.99) + parser.add_argument("--min-noise", type=float, default=0.2) + parser.add_argument("--power", type=float, default=0.3) + parser.add_argument("--kappa", type=float, default=None) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--eval-seed", type=int, default=20260830) + parser.add_argument("--device", default="cuda") + parser.add_argument("--ddp", action="store_true") + parser.add_argument( + "--freeze-encoder-steps", type=int, default=0, + help="train only the decoder/conditioning/heads for the first N steps " + "(encoder gradients are dropped); 0 = train everything from step 0", + ) + parser.add_argument( + "--early-stop-patience", type=int, default=0, + help="stop after N consecutive evaluations without a real macro-PSNR gain (0 = off)", + ) + parser.add_argument("--early-stop-min-delta", type=float, default=0.02) + parser.add_argument( + "--identity-pair-prob", type=float, default=0.0, + help="per-sample probability of feeding the clean target as input", + ) + parser.add_argument( + "--noise-pair-prob", type=float, default=0.0, + help="per-sample probability of a synthetic (clean+noise, clean) pair", + ) + parser.add_argument( + "--global-context", action="store_true", + help="run Phase-1 on the whole frame too and inject it (v7 backends)", + ) + parser.add_argument( + "--ddp-find-unused", action="store_true", + help="required for MoE backends under DDP (data-dependent expert use)", + ) + parser.add_argument("--no-amp", action="store_true") + parser.add_argument("--resume", type=Path) + parser.add_argument("--init-checkpoint", type=Path) + parser.add_argument("--ema-decay", type=float, default=0.9999) + parser.add_argument("--learning-rate", type=float, default=1e-4) + parser.add_argument("--calibrate-kappa", action="store_true") + parser.add_argument("--calibration-images", type=int, default=4096) + return parser + + +def _distributed_context(args: argparse.Namespace) -> Tuple[int, int, int, torch.device]: + if args.ddp: + if not torch.cuda.is_available(): + raise RuntimeError("DDP/NCCL requires CUDA") + if not dist.is_initialized(): + dist.init_process_group(backend="nccl", init_method="env://") + rank, world_size = dist.get_rank(), dist.get_world_size() + local_rank = int(os.environ.get("LOCAL_RANK", "0")) + torch.cuda.set_device(local_rank) + return rank, world_size, local_rank, torch.device("cuda", local_rank) + device = torch.device(args.device) + if device.type == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("CUDA was requested but is unavailable") + if device.type == "cuda": + device_index = 0 if device.index is None else int(device.index) + torch.cuda.set_device(device_index) + device = torch.device("cuda", device_index) + return 0, 1, 0, device + + +def _seed_everything(seed: int, rank: int) -> None: + value = int(seed) + int(rank) * 1000003 + random.seed(value) + np.random.seed(value % (2 ** 32)) + torch.manual_seed(value) + if torch.cuda.is_available(): + torch.cuda.manual_seed_all(value) + + +def build_frozen_phase1( + checkpoint_path: Path, expected_sha256: str, device: torch.device +) -> Tuple[FrozenPhase1, Dict[str, Any]]: + # Kept lazy so unit tests can run in checkouts that only contain Phase 2. + import inspect + + from src.models.graph_encoder import BlindDegradationGraphEncoder, GraphConfig + + # The encoder architecture is governed by the checkpoint's stored + # graph_config (e.g. the ll_v3 global branch); unknown or missing keys + # fall back to the legacy defaults so v2 checkpoints load unchanged. + peek = _torch_load(Path(checkpoint_path), map_location="cpu") + stored: Dict[str, Any] = {} + config_block = peek.get("config") if isinstance(peek, Mapping) else None + if isinstance(config_block, Mapping): + graph_block = config_block.get("graph_config") + if isinstance(graph_block, Mapping): + stored = dict(graph_block) + allowed = set(inspect.signature(GraphConfig.__init__).parameters) - {"self"} + kwargs = {key: value for key, value in stored.items() if key in allowed} + if "spatial_map_size" in kwargs: + kwargs["spatial_map_size"] = tuple(kwargs["spatial_map_size"]) + del peek + + encoder = BlindDegradationGraphEncoder(GraphConfig(**kwargs)) + metadata = load_phase1_checkpoint( + checkpoint_path, encoder, expected_sha256=expected_sha256, map_location="cpu" + ) + frozen = FrozenPhase1(encoder).to(device) + frozen.eval() + return frozen, metadata + + +def _load_or_create_splits(args: argparse.Namespace) -> Any: + from src.data.phase2_v4 import ( + build_train_val_splits, + load_train_val_manifest, + save_train_val_manifest, + ) + + if args.create_manifest: + if args.rain13k_root is None or args.quarantine_manifest is None: + raise ValueError("creating a manifest requires rain and quarantine paths") + splits = build_train_val_splits( + args.data_root, args.rain13k_root, args.quarantine_manifest + ) + save_train_val_manifest(args.manifest, splits) + return splits + if not args.manifest.is_file(): + raise FileNotFoundError("manifest does not exist: %s" % args.manifest) + return load_train_val_manifest(args.manifest) + + +def _make_loaders( + args: argparse.Namespace, + splits: Any, + start_microstep: int, + rank: int, + world_size: int, +) -> Tuple[DataLoader, DataLoader]: + from src.data.phase2_v4 import ( + DeterministicBalancedBatchSampler, + Phase2PairDataset, + ) + + train_dataset = Phase2PairDataset( + splits.train, crop_size=args.crop_size, training=True, upscale_small=True + ) + val_dataset = Phase2PairDataset( + splits.val, crop_size=args.crop_size, training=False, upscale_small=True + ) + stop_step = args.run_until_step if args.run_until_step is not None else args.max_steps + total_microsteps = stop_step * args.grad_accum + if start_microstep > total_microsteps: + raise ValueError("resume step is beyond --run-until-step") + sampler = DeterministicBalancedBatchSampler( + [record.label for record in splits.train], + batch_size=args.batch_size, + steps=max(1, total_microsteps), + seed=args.seed, + start_microstep=start_microstep, + rank=rank, + world_size=world_size, + ) + loader_kwargs: Dict[str, Any] = { + "num_workers": args.workers, + "pin_memory": True, + } + if args.workers > 0: + loader_kwargs["persistent_workers"] = True + loader_kwargs["prefetch_factor"] = 2 + train_loader = DataLoader(train_dataset, batch_sampler=sampler, **loader_kwargs) + val_loader = DataLoader( + val_dataset, + batch_size=args.eval_batch_size, + shuffle=False, + drop_last=False, + **loader_kwargs, + ) + return train_loader, val_loader + + +def _architecture(args: argparse.Namespace) -> Dict[str, Any]: + return { + "name": "graph_resshift_v4", + "dims": list(args.dims), + "cond_dim": args.cond_dim, + "state_channels": 12, + "pixel_unshuffle_factor": 2, + "denoiser_input_channels": 36, + "prediction": "x0", + } + + +def _data_plan( + args: argparse.Namespace, + world_size: int, + amp_enabled: Optional[bool] = None, +) -> Dict[str, Any]: + global_micro_batch = int(args.batch_size) * int(world_size) + if amp_enabled is None: + amp_enabled = not bool(getattr(args, "no_amp", False)) + return { + "schema_version": 1, + "sampler": "deterministic_balanced_global_shard_v1", + "noise_plan": "per_sample_seed_v1", + "seed": int(args.seed), + "eval_seed": int(args.eval_seed), + "crop_size": int(args.crop_size), + "global_micro_batch": global_micro_batch, + "grad_accum": int(args.grad_accum), + "effective_batch": global_micro_batch * int(args.grad_accum), + "precision": "amp_fp16" if amp_enabled else "fp32", + } + + +def _schedule_config(args: argparse.Namespace) -> Dict[str, Any]: + return { + "timesteps": args.timesteps, + "eta_end": args.eta_end, + "min_noise": args.min_noise, + "power": args.power, + "kappa": args.kappa, + } + + +def _build_restorer(args: argparse.Namespace, device: torch.device) -> Phase2RestorationModule: + schedule = ResidualShiftSchedule( + timesteps=args.timesteps, + eta_end=args.eta_end, + min_noise=args.min_noise, + power=args.power, + kappa=args.kappa, + ) + conditioner = GraphConditionerV4(cond_dim=args.cond_dim, stage_dims=args.dims) + denoiser = GraphResidualShiftUNetV4(dims=args.dims, cond_dim=args.cond_dim) + return Phase2RestorationModule( + conditioner, denoiser, schedule, args.condition + ).to(device) + + +def _write_run_config(args: argparse.Namespace, path: Path) -> None: + payload = vars(args).copy() + for name, value in list(payload.items()): + if isinstance(value, Path): + payload[name] = str(value) + elif isinstance(value, tuple): + payload[name] = list(value) + _atomic_json_dump(payload, path) + + +def _prepare_output_directory( + args: argparse.Namespace, + rank: int, + resume_step: Optional[int] = None, +) -> None: + """Protect run provenance and write config only after contract validation.""" + + output_dir = Path(args.output_dir) + if args.resume is None: + nonempty = output_dir.exists() and any(output_dir.iterdir()) + if nonempty: + raise FileExistsError( + "fresh output directory is not empty: %s" % output_dir + ) + output_dir.mkdir(parents=True, exist_ok=True) + if args.ddp: + dist.barrier() + if rank == 0: + if args.resume is None: + destination = output_dir / "run_config.json" + else: + destination = output_dir / ( + "resume_config_step_%08d_%d.json" + % (int(resume_step or 0), time.time_ns()) + ) + _write_run_config(args, destination) + if args.ddp: + dist.barrier() + + +def validate_runtime_args(args: argparse.Namespace) -> int: + """Fail on invalid CLI combinations before touching CUDA or run outputs.""" + + if args.kappa is None and not args.calibrate_kappa: + raise ValueError("training requires an explicit frozen --kappa") + if args.kappa is not None and ( + not math.isfinite(args.kappa) or args.kappa < 0.0 + ): + raise ValueError("--kappa must be finite and non-negative") + if not math.isfinite(args.power) or args.power <= 0.0: + raise ValueError("--power must be finite and positive") + if not math.isfinite(args.ema_decay) or not 0.0 <= args.ema_decay < 1.0: + raise ValueError("--ema-decay must be finite and lie in [0, 1)") + if args.max_steps <= 500: + raise ValueError("--max-steps must exceed the 500-step warmup") + stop_step = args.run_until_step if args.run_until_step is not None else args.max_steps + if stop_step < 0 or stop_step > args.max_steps: + raise ValueError("--run-until-step must lie in [0, max_steps]") + if args.batch_size <= 0 or args.batch_size % 4: + raise ValueError("--batch-size must be positive and divisible by four") + if args.grad_accum <= 0: + raise ValueError("--grad-accum must be positive") + if args.resume is not None and args.init_checkpoint is not None: + raise ValueError("--resume and --init-checkpoint are mutually exclusive") + if args.calibrate_kappa and ( + args.resume is not None or args.init_checkpoint is not None + ): + raise ValueError("kappa calibration cannot resume or load model initialization") + if args.crop_size <= 0 or args.crop_size % 2: + raise ValueError("--crop-size must be a positive even integer") + if args.eval_batch_size <= 0: + raise ValueError("--eval-batch-size must be positive") + if args.workers < 0: + raise ValueError("--workers must be non-negative") + return int(stop_step) + + +def run(args: argparse.Namespace) -> None: + stop_step = validate_runtime_args(args) + + rank, world_size, local_rank, device = _distributed_context(args) + _seed_everything(args.seed, rank) + output_dir = args.output_dir + amp_enabled = device.type == "cuda" and not args.no_amp + + splits = _load_or_create_splits(args) + from src.data.phase2_v4 import ( + split_digest, + validate_clean_file_integrity, + validate_splits_against_checkpoint, + ) + + # Calibration and training are both pinned to the exact Phase-1 support + # provenance; no optimization mode may silently use a different split. + phase1_checkpoint = validate_phase1_artifact_header( + args.phase1_checkpoint, args.phase1_sha256 + ) + validate_splits_against_checkpoint(splits, phase1_checkpoint) + # Only canonical, provenance-validated paths may be read. Hashing before + # the split contract check could touch an arbitrary path from a tampered + # manifest (including data reserved outside the training/validation set). + validate_clean_file_integrity(splits) + if args.calibrate_kappa: + _prepare_output_directory(args, rank) + # Calibration is train-only and exactly domain balanced. A sequential + # traversal would exhaust the Rain13K prefix before seeing the smaller + # SIDD/LOLv2 domains when a sample cap is used. + from src.data.phase2_v4 import ( + DeterministicBalancedBatchSampler, + Phase2PairDataset, + ) + + calibration_dataset = Phase2PairDataset( + splits.train, crop_size=args.crop_size, training=True, upscale_small=True + ) + if args.calibration_images < 4: + raise ValueError("--calibration-images must be at least four") + calibration_batch = max(4, (args.eval_batch_size // 4) * 4) + calibration_steps = int( + math.ceil(float(args.calibration_images) / float(calibration_batch)) + ) + calibration_sampler = DeterministicBalancedBatchSampler( + [record.label for record in splits.train], + batch_size=calibration_batch, + steps=calibration_steps, + seed=args.seed, + ) + calibration_loader = DataLoader( + calibration_dataset, + batch_sampler=calibration_sampler, + num_workers=args.workers, + pin_memory=True, + ) + if rank == 0: + result = calibrate_kappa( + calibration_loader, + output_dir / "kappa_calibration.json", + max_images=args.calibration_images, + ) + print(json.dumps(result, sort_keys=True)) + if args.ddp: + dist.barrier() + dist.destroy_process_group() + return + + phase1, phase1_metadata = build_frozen_phase1( + args.phase1_checkpoint, args.phase1_sha256, device + ) + train_digest_value = split_digest(splits.train) + val_digest_value = split_digest(splits.val) + + model = _build_restorer(args, device) + architecture_config = _architecture(args) + schedule_config = _schedule_config(args) + data_plan = _data_plan(args, world_size, amp_enabled=amp_enabled) + if args.resume is not None: + resume_header = _torch_load(args.resume, map_location="cpu") + stored_contract = resume_header.get("contract", {}) + if "init_model_hash" not in stored_contract: + raise ValueError("resume checkpoint is missing init_model_hash") + # A DDP rank intentionally has a different pre-broadcast RNG stream; + # preserve and validate the immutable initialization provenance stored + # by the single-GPU source run rather than hashing throwaway weights. + init_hash = str(stored_contract["init_model_hash"]) + elif args.init_checkpoint is not None: + init_hash = load_shared_initialization( + args.init_checkpoint, + model, + target_condition=args.condition, + expected_architecture=architecture_config, + expected_schedule=schedule_config, + expected_data_plan=data_plan, + expected_phase1_sha256=phase1_metadata["sha256"], + expected_phase1_metadata=phase1_metadata, + expected_train_digest=train_digest_value, + expected_val_digest=val_digest_value, + expected_max_steps=args.max_steps, + expected_ema_decay=args.ema_decay, + ) + else: + init_hash = model_state_hash(model) + base_lr = float(getattr(args, "learning_rate", 1e-4)) + optimizer = torch.optim.AdamW( + model.parameters(), lr=base_lr, betas=(0.9, 0.99), weight_decay=1e-4 + ) + scheduler = build_lr_scheduler( + optimizer, max_steps=args.max_steps, base_lr=base_lr + ) + scaler = make_grad_scaler(amp_enabled) + ema = ExponentialMovingAverage(model, decay=args.ema_decay) + contract = CheckpointContract( + condition_mode=args.condition, + phase1_sha256=phase1_metadata["sha256"], + phase1_metadata=phase1_metadata, + train_digest=train_digest_value, + val_digest=val_digest_value, + schedule=schedule_config, + architecture=architecture_config, + data_plan=data_plan, + init_model_hash=init_hash, + max_steps=args.max_steps, + ema_decay=args.ema_decay, + ) + history: List[Dict[str, Any]] = [] + step = 0 + resumed_early_stop: Optional[Dict[str, Any]] = None + if args.resume is not None: + resumed = resume_training_checkpoint( + args.resume, model, ema, optimizer, scheduler, scaler, contract + ) + step, history = resumed.step, resumed.history + resumed_early_stop = resumed.early_stop + _prepare_output_directory(args, rank, resume_step=step) + elif rank == 0: + _prepare_output_directory(args, rank) + manager = BoundedCheckpointManager(output_dir) + save_training_checkpoint( + manager.path_for("init"), model, ema, optimizer, scheduler, scaler, + step=0, contract=contract, history=history, + ) + else: + _prepare_output_directory(args, rank) + + # Phase 1 is outside DistributedDataParallel and outside the optimizer. + phase1_parameter_ids = {id(parameter) for parameter in phase1.parameters()} + optimizer_parameter_ids = { + id(parameter) for group in optimizer.param_groups for parameter in group["params"] + } + if phase1_parameter_ids & optimizer_parameter_ids: + raise RuntimeError("Phase-1 parameters leaked into the Phase-2 optimizer") + + if args.ddp: + model = DistributedDataParallel( + model, + device_ids=[local_rank], + output_device=local_rank, + broadcast_buffers=False, + # MoE backends (v5+) hard-skip unselected experts per batch, so + # parameter usage is data-dependent and differs across ranks; + # without unused-parameter tracking the reducer deadlocks on the + # first batch whose expert set diverges. + find_unused_parameters=bool( + getattr(args, "ddp_find_unused", False) + ), + ) + start_microstep = step * args.grad_accum + train_loader, val_loader = _make_loaders( + args, splits, start_microstep, rank, world_size + ) + eval_steps = set(args.eval_steps) + milestone_steps = set(args.milestone_steps) + manager = BoundedCheckpointManager(output_dir) + best_score = max( + [float(item.get("macro_psnr", -float("inf"))) for item in history] + or [-float("inf")] + ) + + early_stopper = EarlyStopper( + int(getattr(args, "early_stop_patience", 0)), + float(getattr(args, "early_stop_min_delta", 0.02)), + ) + if resumed_early_stop: + early_stopper.load_state_dict(resumed_early_stop) + if rank == 0: + print("[resume] early-stop state restored: %r" % (resumed_early_stop,), flush=True) + freeze_encoder_steps = int(getattr(args, "freeze_encoder_steps", 0)) + + def do_evaluation(current_step: int) -> bool: + """Evaluate on rank zero; return whether training should stop.""" + nonlocal best_score + stop_flag = 0 + if args.ddp: + dist.barrier() + # Rank zero evaluates a complete, fixed-order validation set. + if rank == 0: + with ema.apply(model): + metrics = evaluate( + model, + phase1, + val_loader, + device, + args.eval_seed, + amp_enabled=amp_enabled, + ) + event = { + "event": "evaluation", + "step": current_step, + "condition": args.condition, + "macro_psnr": metrics["restored"]["macro_psnr"], + "macro_ssim": metrics["restored"]["macro_ssim"], + "metrics": metrics, + "time": time.time(), + } + history.append(event) + _append_jsonl(event, output_dir / "metrics.jsonl") + _atomic_json_dump(history, output_dir / "history.json") + print(json.dumps(event, sort_keys=True), flush=True) + if event["macro_psnr"] > best_score: + best_score = float(event["macro_psnr"]) + save_training_checkpoint( + manager.path_for("best"), model, ema, optimizer, scheduler, scaler, + step=current_step, contract=contract, history=history, + early_stop=early_stopper.state_dict(), + ) + if args.ddp: + dist.barrier() + + stop_requested = False + if step == 0 and 0 in eval_steps: + stop_requested = do_evaluation(0) + model.train() + phase1.eval() + optimizer.zero_grad(set_to_none=True) + loader_iterator = iter(train_loader) + extra_clean_iter = None + if getattr(args, "extra_clean_root", None): + from src.data.folder_crops import FolderCropDataset, infinite_batches + + extra_files = extra_clean_files(args.extra_clean_root) + extra_clean_iter = infinite_batches(DataLoader( + FolderCropDataset( + extra_files, size=int(args.crop_size), + seed=int(args.seed) * 31 + int(rank), return_full=True, + ), + batch_size=int(args.batch_size), shuffle=True, drop_last=True, + num_workers=int(getattr(args, "extra_clean_workers", 2)), pin_memory=device.type == "cuda", + )) + if rank == 0: + print("extra clean pool for identity pairs: %d files" % len(extra_files), flush=True) + nonfinite_forward_total = 0 + while step < stop_step: + accumulated_loss = 0.0 + nonfinite_forward_consecutive = 0 + for accumulation_index in range(args.grad_accum): + batch = next(loader_iterator) + degraded = batch["degraded"].to(device, non_blocking=True) + clean = batch["clean"].to(device, non_blocking=True) + use_full = ( + bool(getattr(args, "global_context", False)) + or bool(getattr(args, "exposure_pregain", False)) + ) and "full_degraded" in batch + full_degraded = batch["full_degraded"].to(device, non_blocking=True) if use_full else None + full_clean = batch["full_clean"].to(device, non_blocking=True) if use_full else None + aug_generator = torch.Generator() + aug_generator.manual_seed( + (int(args.seed) * 7919 + int(step) * 104729 + int(accumulation_index) * 31 + int(rank)) % (2 ** 63 - 1) + ) + degraded, full_degraded, _ = synthetic_noise_pairs( + degraded, clean, float(getattr(args, "noise_pair_prob", 0.0)), + aug_generator, full_degraded, full_clean, + ) + identity = identity_pair_mask( + clean.shape[0], float(getattr(args, "identity_pair_prob", 0.0)), device + ) + if bool(identity.any()): + extra_crop = extra_full = None + if extra_clean_iter is not None: + extra_batch = next(extra_clean_iter) + extra_crop = extra_batch["crop"].to(device, non_blocking=True) + extra_full = extra_batch["full"].to(device, non_blocking=True) + clean, full_clean = exposure_diverse_identity( + clean, full_clean, identity, aug_generator, + jitter=float(getattr(args, "identity_exposure_jitter", 0.0)), + extra_crop=extra_crop, extra_full=extra_full, + extra_prob=float(getattr(args, "extra_clean_prob", 0.0)), + ) + degraded = torch.where(identity.view(-1, 1, 1, 1), clean, degraded) + if full_degraded is not None: + full_degraded = torch.where(identity.view(-1, 1, 1, 1), full_clean, full_degraded) + # Representation call is intentionally performed even for D0/null. + with torch.cuda.amp.autocast(enabled=amp_enabled): + representation = phase1(degraded) + if full_degraded is not None: + representation.full_frame = phase1(full_degraded) + # Raw whole frame for image-statistics consumers (v10 pre-gain). + representation.full_image = full_degraded + u0_reference = pixel_unshuffle2(clean) + global_microstep = step * args.grad_accum + accumulation_index + sample_seed_values = batch["sample_seed"] + if isinstance(sample_seed_values, Tensor): + sample_seed_values = sample_seed_values.tolist() + timesteps, noise = deterministic_training_plan( + u0_reference, + args.timesteps, + args.seed, + global_microstep, + rank=rank, + sample_seeds=sample_seed_values, + ) + should_sync = accumulation_index == args.grad_accum - 1 + sync_context = ( + contextlib.nullcontext() + if should_sync or not isinstance(model, DistributedDataParallel) + else model.no_sync() + ) + with sync_context: + with torch.cuda.amp.autocast(enabled=amp_enabled): + loss = model( + clean, degraded, representation, timesteps, noise + ) + action = loss_overflow_action(loss, amp_enabled=amp_enabled) + if action == "fail": + raise FloatingPointError("non-finite training loss") + skipped = action == "skip" + if not skipped: + loss_value = float(loss.detach().float().item()) + scaled_loss = loss / float(args.grad_accum) + if skipped: + # fp16 range failure on this micro-batch: drop it (no + # backward, no loss contribution) and keep the step. + nonfinite_forward_consecutive += 1 + nonfinite_forward_total += 1 + if not nonfinite_loss_within_budget( + consecutive=nonfinite_forward_consecutive, + total=nonfinite_forward_total, + ): + raise FloatingPointError( + "non-finite training loss on %d consecutive micro-batches " + "(%d total) at logical step %d" + % (nonfinite_forward_consecutive, nonfinite_forward_total, step) + ) + # Free the retained graph: without the backward that would + # normally consume it, these activations would still be + # alive during the next forward and blow the memory budget. + del loss + continue + nonfinite_forward_consecutive = 0 + scaler.scale(scaled_loss).backward() + accumulated_loss += loss_value + # Drop the frozen half BEFORE unscaling: an fp16 overflow inside the + # frozen encoder would otherwise set the scaler's found_inf, be hidden + # from the grad-norm check by the mask, and make the scaler refuse the + # step (observed at step ~2350 of the first 15k run). + if freeze_encoder_steps > 0 and step < freeze_encoder_steps: + masked_encoder_grads = mask_encoder_gradients(model) + else: + masked_encoder_grads = 0 + if not has_any_gradient(model): + # Every micro-batch of this step overflowed in fp16 and was + # dropped. There is no update to apply: clear the state, advance + # the cursor and move on rather than reducing an empty gradient. + optimizer.zero_grad(set_to_none=True) + step += 1 + if rank == 0: + _append_jsonl( + {"event": "skipped_step", "step": step, + "reason": "all micro-batches non-finite", "time": time.time()}, + output_dir / "metrics.jsonl", + ) + continue + scaler.unscale_(optimizer) + grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) + if not is_globally_finite_scalar(grad_norm): + if not amp_enabled: + raise FloatingPointError("non-finite gradient norm") + recover_amp_gradient_overflow( + manager.path_for("overflow_recovery"), + model, + ema, + optimizer, + scheduler, + scaler, + step=step, + contract=contract, + history=history, + rank=rank, + distributed=args.ddp, + observed_grad_norm=float(grad_norm.detach().float().item()), + early_stop=early_stopper.state_dict(), + ) + grad_norm_value = float(grad_norm.detach().float().item()) + scaler_step_or_fail(scaler, optimizer) + optimizer.zero_grad(set_to_none=True) + scheduler.step() + ema.update(model) + step += 1 + + if rank == 0 and (step == 1 or step % 25 == 0): + event = { + "event": "train", + "step": step, + "loss": accumulated_loss / args.grad_accum, + "lr": optimizer.param_groups[0]["lr"], + "grad_norm": grad_norm_value, + "condition": args.condition, + "time": time.time(), + } + _append_jsonl(event, output_dir / "metrics.jsonl") + print(json.dumps(event, sort_keys=True), flush=True) + if step in eval_steps: + stop_requested = do_evaluation(step) + model.train() + phase1.eval() + if rank == 0 and step in milestone_steps: + save_training_checkpoint( + manager.path_for("milestone", step), model, ema, optimizer, + scheduler, scaler, step=step, contract=contract, history=history, + early_stop=early_stopper.state_dict(), + ) + manager.prune_milestones() + if rank == 0 and (step % 250 == 0 or step == stop_step): + save_training_checkpoint( + manager.path_for("last"), model, ema, optimizer, scheduler, scaler, + step=step, contract=contract, history=history, + early_stop=early_stopper.state_dict(), + ) + if stop_requested: + # Every rank leaves together: the flag was broadcast inside + # do_evaluation, so no rank is left waiting at the next barrier. + if rank == 0: + save_training_checkpoint( + manager.path_for("last"), model, ema, optimizer, scheduler, scaler, + step=step, contract=contract, history=history, + early_stop=early_stopper.state_dict(), + ) + print("[early-stop] training ended at step %d" % step, flush=True) + break + + if args.ddp: + dist.barrier() + dist.destroy_process_group() + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(build_parser().parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_unified_v7.py b/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_unified_v7.py new file mode 100644 index 0000000000000000000000000000000000000000..dcd20d739480d5e8ab4bb91ab31c9ee378d12a78 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/train_phase2_unified_v7.py @@ -0,0 +1,1354 @@ +#!/usr/bin/env python3 +"""Phase 2 v7: unified two-step ResShift — one network, no external refiner. + +The gen-2 pipeline (v6.1 one-step + refiner) is re-expressed as an honest +two-step diffusion over the SAME weights: + + coarse t=2: u_2 = u_y-anchored marginal -> x0-MSE (content) + fine t=1: u_1 built from the model's OWN detached prediction via the + exact posterior -> image-space L1 + VGG (appearance) + +Chain-aware fine-step construction removes the exposure bias that made the +old 8-step chain destructive; timestep conditioning (AdaGN) lets one network +host both behaviours. Warm start: full v6.1 weights minus the schedule +buffers (T changes 8 -> 2). + +The VGG perceptual criterion is attached via ``object.__setattr__`` so it +never enters ``state_dict``/EMA/optimizer. +""" + +from __future__ import annotations + +import argparse +import contextlib +import hashlib +from pathlib import Path +from typing import Any, Dict, Iterator, Mapping, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn +import torch.nn.functional as F + +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_graph_moe_v6 as v6 +from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule +from src.models.restoration.graph_moe_v6 import ( + MoEGraphConditionerV6, + MoEGraphResidualShiftUNetV6, +) +from src.models.restoration.graph_resshift_v4 import ( + ResidualShiftSchedule, + pixel_shuffle2, + pixel_unshuffle2, +) +from src.models.restoration.refiner_decoder import RefinerBlock +from src.models.restoration.uformer_moe_v7 import UformerMoEUNetV7 + +V7_VERSION = "unified_two_step_resshift_v1" +V7_WARMSTART_MAPPING_VERSION = "v6_full_state_minus_schedule_v1" + +# Phase-1's readout dimension; the output FiLM conditions on the raw +# representation vector, which is fixed by the frozen encoder architecture. +GLOBAL_CONDITION_DIM = 256 + +# Image-head submodules absent from a warm-start source are left at their +# zero-initialized state instead of failing the strict key check. +_V7_FRESH_HEAD_PREFIXES = ( + "full_res_tail.", "output_film.", "denoiser.pyramid_heads.", + "null_context", "null_global", "ctx_full_proj", "global_full_proj", + "photometric_head.", "exposure_pregain.", "colour_head.", + "denoiser.down_globals.", "denoiser.up_globals.", +) +# Phase-1 v5 PhotometricBranch state width (zeros when the encoder lacks it). +PHOTOMETRIC_STATE_DIM = 128 +_DEFAULT_PYRAMID_WEIGHTS = (0.1, 0.2, 0.3) + + +def _replace_bundle(bundle: Any, **changes: Any) -> Any: + import copy + import dataclasses + + if dataclasses.is_dataclass(bundle): + return dataclasses.replace(bundle, **changes) + clone = copy.copy(bundle) + for name, value in changes.items(): + setattr(clone, name, value) + return clone + + +class FullResTail(nn.Module): + """Shallow NAFNet-lite residual head at FULL image resolution. + + The diffusion trunk works entirely on the pixel-unshuffled half-res + state; this tail is the only place the network sees real pixels, so it + carries the fine-detail share (residual noise, sharpness) of the fine + objective. Input is (restored ‖ degraded); the output conv is + zero-initialized so the head is an exact identity at warm start. + """ + + def __init__(self, blocks: int = 3, width: int = 48) -> None: + super().__init__() + if blocks < 1: + raise ValueError("FullResTail requires at least one block") + self.entry = nn.Conv2d(6, width, 3, padding=1) + self.body = nn.Sequential( + *[RefinerBlock(width) for _ in range(int(blocks))] + ) + self.out = nn.Conv2d(width, 3, 3, padding=1) + nn.init.zeros_(self.out.weight) + nn.init.zeros_(self.out.bias) + + def forward(self, stacked: Tensor) -> Tensor: + return self.out(self.body(self.entry(stacked))) + +# BT.601 chroma rows (U, V). The luminance row is deliberately absent: the +# chroma objective must stay orthogonal to the L1/VGG terms that already +# constrain brightness, so only hue/saturation errors are re-weighted. Both +# rows must sum to exactly zero so a pure gray offset projects to zero chroma +# (the textbook U row is off by 1e-5 from rounding; the R coefficient below +# absorbs it). +_UV_FROM_RGB = ( + (-0.14714, -0.28886, 0.436), + (0.615, -0.51499, -0.10001), +) + + +def rgb_to_uv(image: Tensor) -> Tensor: + """Project an RGB batch [B,3,H,W] onto its BT.601 U/V chroma planes.""" + + if image.dim() != 4 or image.shape[1] != 3: + raise ValueError("rgb_to_uv expects a [B,3,H,W] batch") + weight = image.new_tensor(_UV_FROM_RGB) + return torch.einsum("bchw,oc->bohw", image, weight) + + +# BT.601 luma row; sums to exactly 1 so a uniform gray image maps to its own +# gray level. +_Y_FROM_RGB = (0.299, 0.587, 0.114) + +# The luma objective compares tone at this pooled resolution: coarse enough +# to be orthogonal to the pixel L1 (which already constrains detail), fine +# enough to catch regionally varying exposure errors, not just the mean. +_LUMA_POOL_GRID = 8 + + +def rgb_to_luma(image: Tensor) -> Tensor: + """Project an RGB batch [B,3,H,W] onto its BT.601 luma plane [B,1,H,W].""" + + if image.dim() != 4 or image.shape[1] != 3: + raise ValueError("rgb_to_luma expects a [B,3,H,W] batch") + weight = image.new_tensor(_Y_FROM_RGB).view(1, 3, 1, 1) + return (image * weight).sum(dim=1, keepdim=True) + + +def pooled_luma(image: Tensor, grid: int = _LUMA_POOL_GRID) -> Tensor: + """Coarse tone map: BT.601 luma average-pooled onto a grid×grid layout.""" + + return F.adaptive_avg_pool2d(rgb_to_luma(image), (grid, grid)) + +_V4_SCHEDULE_CONFIG = v4._schedule_config +_V4_DATA_PLAN = v4._data_plan + + +class GlobalPhotometricHead(nn.Module): + """Per-image global exposure controllable (v8). + + Measured on run A (probe_global_knob.py): a per-image global affine + ``a*x + b`` on the output is worth +7.2 dB oracle / ~+3 dB predictable on + lowlight, +6 / +2 on nearly-clean scene008, +1.4 / +1.2 on haze, and it + removes the systematic over-exposure of lowlight (oracle gain 0.82). The + colour (HV-plane) knob was worth only +0.5-0.9 dB, so the head predicts + intensity only. Inputs: Phase-1 global_condition + photometric_state of + the crop and, when available, of the whole frame. Zero-initialised + (exact identity), tanh-bounded (shrinkage: the pooled linear predictor + destroyed noise by -6.8 dB without it), ``dose`` scales the deltas at + inference and per-sample dropout keeps the identity path trained. + """ + + def __init__(self, hidden: int = 128, max_log_gain: float = 0.7, max_bias: float = 0.2) -> None: + super().__init__() + in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM) + self.net = nn.Sequential( + nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 2) + ) + nn.init.zeros_(self.net[-1].weight) + nn.init.zeros_(self.net[-1].bias) + self.max_log_gain = float(max_log_gain) + self.max_bias = float(max_bias) + + @staticmethod + def _vector(representation: Any) -> Tensor: + global_condition = representation.global_condition.float() + state = getattr(representation, "photometric_state", None) + if state is None: + state = global_condition.new_zeros(global_condition.shape[0], PHOTOMETRIC_STATE_DIM) + return torch.cat((global_condition, state.float()), dim=1) + + def coefficients(self, representation: Any) -> Tuple[Tensor, Tensor]: + """(log_gain, bias), each [B], already bounded.""" + crop = self._vector(representation) + full = getattr(representation, "full_frame", None) + full_vector = self._vector(full) if full is not None else torch.zeros_like(crop) + raw = self.net(torch.cat((crop, full_vector), dim=1)) + return self.max_log_gain * torch.tanh(raw[:, 0]), self.max_bias * torch.tanh(raw[:, 1]) + + def forward( + self, + image: Tensor, + representation: Any, + dose: float = 1.0, + drop_mask: Optional[Tensor] = None, + ) -> Tensor: + with torch.cuda.amp.autocast(enabled=False): + log_gain, bias = self.coefficients(representation) + if drop_mask is not None: + keep = (~drop_mask.to(torch.bool)).to(log_gain.dtype) + log_gain, bias = log_gain * keep, bias * keep + gain = (float(dose) * log_gain).exp().view(-1, 1, 1, 1) + bias = (float(dose) * bias).view(-1, 1, 1, 1) + return image.float() * gain + bias + + +# Whole-image exposure descriptors fed to the pre-gain (per image). +PREGAIN_STATS_DIM = 8 + + +def luma_statistics(image: Tensor) -> Tensor: + """[B, 8]: mean luma, log mean luma, luma p05/p50/p95, mean R/G/B.""" + + if image.dim() != 4 or image.shape[1] != 3: + raise ValueError("luma_statistics expects a [B,3,H,W] batch") + x = image.float().clamp(0.0, 1.0) + luma = rgb_to_luma(x).flatten(1) + mean = luma.mean(dim=1, keepdim=True) + probes = torch.tensor([0.05, 0.5, 0.95], device=luma.device, dtype=luma.dtype) + quantiles = torch.quantile(luma, probes, dim=1).transpose(0, 1) + channel_means = x.mean(dim=(2, 3)) + return torch.cat((mean, (mean + 1e-3).log(), quantiles, channel_means), dim=1) + + +class ExposurePreGain(nn.Module): + """Retinex-style per-image INPUT gain (v10). + + The v8 photometric head rescales the OUTPUT; the trunk still has to do + the x5-x10 brightening of a low-light input through a residual on u_y, + which is where the exposure overshoot and chroma loss come from. Every + published LOL method first estimates a global/illumination gain and + lets the restorer work in a normalised regime (Retinexformer's + illumination estimator). This module predicts one bounded log-gain per + image from the Phase-1 vectors of crop and whole frame (routing decides + "low-light" vs "dark but clean") plus raw luma statistics of both, and + multiplies the degraded image BEFORE pixel-unshuffle, so the residual + anchor u_y, the diffusion state and the full-res tail all see the gained + image. Zero-initialised (gain 1 -> bitwise identity), tanh-bounded, + ``dose`` scales the log-gain and per-sample dropout keeps gain-1 trained. + """ + + def __init__(self, hidden: int = 128, max_log_gain: float = 1.6) -> None: + super().__init__() + in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM) + 2 * PREGAIN_STATS_DIM + self.net = nn.Sequential( + nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 1) + ) + nn.init.zeros_(self.net[-1].weight) + nn.init.zeros_(self.net[-1].bias) + self.max_log_gain = float(max_log_gain) + + def log_gain(self, image: Tensor, representation: Any) -> Tensor: + crop_vector = GlobalPhotometricHead._vector(representation) + full = getattr(representation, "full_frame", None) + full_vector = ( + GlobalPhotometricHead._vector(full) if full is not None else torch.zeros_like(crop_vector) + ) + crop_stats = luma_statistics(image) + full_image = getattr(representation, "full_image", None) + full_stats = luma_statistics(full_image) if full_image is not None else crop_stats + raw = self.net(torch.cat((crop_vector, full_vector, crop_stats, full_stats), dim=1)) + return self.max_log_gain * torch.tanh(raw[:, 0]) + + def forward( + self, + image: Tensor, + representation: Any, + dose: float = 1.0, + drop_mask: Optional[Tensor] = None, + ) -> Tuple[Tensor, Tensor]: + """(gained image in fp32, log-gain [B]).""" + + with torch.cuda.amp.autocast(enabled=False): + log_gain = self.log_gain(image, representation) + if drop_mask is not None: + keep = (~drop_mask.to(torch.bool)).to(log_gain.dtype) + log_gain = log_gain * keep + gain = (float(dose) * log_gain).exp().view(-1, 1, 1, 1) + return image.float() * gain, log_gain + + +def pregain_target(clean: Tensor, degraded: Tensor, max_log_gain: float, eps: float = 1e-3) -> Tensor: + """Supervised target for the pre-gain: the log ratio of mean luma + clean/degraded per image, clamped to the head's bound. Identity and + noise pairs -> 0, low-light pairs -> the exposure lift, hazy pairs -> a + mild negative value (the clean scene is darker than its airlight). Gives + the gain a direct learning signal; measured on v10 (end-to-end only) the + gain had barely moved off 1.0 after 4k steps.""" + + ratio = (rgb_to_luma(clean.float()).mean(dim=(1, 2, 3)) + eps) / ( + rgb_to_luma(degraded.float()).mean(dim=(1, 2, 3)) + eps + ) + # Lift only (gain >= 1): a hazy input's clean scene is darker than its + # airlight, so an unclamped target darkened every hazy input by ~x0.7 and + # the trunk had to re-learn dehazing on inputs it never saw (v11 stage A, + # haze val 32.0 -> 30.4 in 2k steps). Darkening is trivial for the trunk; + # the Retinex-style pre-gain only needs to normalise under-exposure. + return ratio.log().clamp(0.0, float(max_log_gain)) + + +class GlobalColourHead(nn.Module): + """Per-image global colour transform on the OUTPUT (v12): y = M x + b with + M = diag(exp(d)) (I + O), d/O/b tanh-bounded, zero-initialised (identity). + + Measured on v11a outputs (LOLv2-real, whole image, oracle fit per image): + raw 19.3 -> intensity affine 27.5 -> 3x3 matrix + bias 29.3 dB, i.e. most + of the remaining low-light error is a global per-image colour/tone map + (gain, white balance, cast), which the intensity-only photometric head + cannot express. Predicted from the same inputs as the photometric head + (Phase-1 crop + whole-frame vectors and luma statistics); trained with + a supervised target (least-squares fit of the transform from the + detached output to the clean image) so it learns immediately, like the + pre-gain. + """ + + def __init__(self, hidden: int = 128, max_log_diag: float = 1.0, max_offdiag: float = 0.5, + max_bias: float = 0.25) -> None: + super().__init__() + in_dim = 2 * (GLOBAL_CONDITION_DIM + PHOTOMETRIC_STATE_DIM) + 2 * PREGAIN_STATS_DIM + self.net = nn.Sequential(nn.Linear(in_dim, hidden), nn.SiLU(), nn.Linear(hidden, 12)) + nn.init.zeros_(self.net[-1].weight) + nn.init.zeros_(self.net[-1].bias) + self.max_log_diag = float(max_log_diag) + self.max_offdiag = float(max_offdiag) + self.max_bias = float(max_bias) + + def coefficients(self, image: Tensor, representation: Any) -> Tuple[Tensor, Tensor]: + """(M [B,3,3], b [B,3]) — bounded; identity at initialisation.""" + crop_vector = GlobalPhotometricHead._vector(representation) + full = getattr(representation, "full_frame", None) + full_vector = GlobalPhotometricHead._vector(full) if full is not None else torch.zeros_like(crop_vector) + crop_stats = luma_statistics(image) + full_image = getattr(representation, "full_image", None) + full_stats = luma_statistics(full_image) if full_image is not None else crop_stats + raw = self.net(torch.cat((crop_vector, full_vector, crop_stats, full_stats), dim=1)) + log_diag = self.max_log_diag * torch.tanh(raw[:, 0:3]) + off = self.max_offdiag * torch.tanh(raw[:, 3:9]).view(-1, 3, 2) + bias = self.max_bias * torch.tanh(raw[:, 9:12]) + eye = torch.eye(3, device=raw.device, dtype=raw.dtype).unsqueeze(0) + # off-diagonal slots: row i gets the two entries j != i + offdiag = raw.new_zeros(raw.shape[0], 3, 3) + idx = [(0, 1), (0, 2), (1, 0), (1, 2), (2, 0), (2, 1)] + flat = off.reshape(-1, 6) + for k, (i, j) in enumerate(idx): + offdiag[:, i, j] = flat[:, k] + matrix = torch.diag_embed(log_diag.exp()) @ (eye + offdiag) + return matrix, bias + + def forward(self, image: Tensor, representation: Any, dose: float = 1.0, + drop_mask: Optional[Tensor] = None) -> Tensor: + with torch.cuda.amp.autocast(enabled=False): + matrix, bias = self.coefficients(image, representation) + if drop_mask is not None: + keep = (~drop_mask.to(torch.bool)).to(matrix.dtype).view(-1, 1, 1) + eye = torch.eye(3, device=matrix.device, dtype=matrix.dtype).unsqueeze(0) + matrix = keep * matrix + (1 - keep) * eye + bias = bias * keep.view(-1, 1) + if float(dose) != 1.0: + eye = torch.eye(3, device=matrix.device, dtype=matrix.dtype).unsqueeze(0) + matrix = eye + float(dose) * (matrix - eye) + bias = float(dose) * bias + x = image.float() + out = torch.einsum("bij,bjhw->bihw", matrix, x) + bias.view(-1, 3, 1, 1) + return out + + +def colour_target(output: Tensor, clean: Tensor, samples: int = 4096, seed: int = 0) -> Tuple[Tensor, Tensor]: + """Per-image least-squares fit of clean ~ M output + b on a pixel sample: + the supervised target of ``GlobalColourHead`` (returns M [B,3,3], b [B,3]).""" + + batch, _, height, width = output.shape + n = height * width + gen = torch.Generator(device="cpu").manual_seed(int(seed)) + index = torch.randperm(n, generator=gen)[: min(int(samples), n)].to(output.device) + x = output.detach().float().flatten(2)[:, :, index].transpose(1, 2) # [B,S,3] + y = clean.detach().float().flatten(2)[:, :, index].transpose(1, 2) + ones = torch.ones(batch, x.shape[1], 1, device=x.device, dtype=x.dtype) + xa = torch.cat((x, ones), dim=2) # [B,S,4] + # ridge-regularised normal equations (robust to flat/saturated images) + gram = xa.transpose(1, 2) @ xa + 1e-3 * torch.eye(4, device=x.device, dtype=x.dtype) + sol = torch.linalg.solve(gram, xa.transpose(1, 2) @ y) # [B,4,3]: y = xa @ sol + matrix = sol[:, :3, :].transpose(1, 2) # [B,3,3]: y_i = sum_j M_ij x_j + bias = sol[:, 3, :] + return matrix, bias + + +class Phase2UnifiedV7Module(v6.Phase2MoEV6Module): + """v6 graph-MoE module trained with the composite two-step objective.""" + + def __init__( + self, + *args, + fine_l1_weight: float = 1.0, + fine_vgg_weight: float = 0.1, + fine_chroma_weight: float = 0.0, + fine_luma_weight: float = 0.0, + tail_blocks: int = 0, + tail_width: int = 48, + use_output_film: bool = False, + cond_dropout_prob: float = 0.0, + pyramid_loss_weights: Sequence[float] = _DEFAULT_PYRAMID_WEIGHTS, + global_context: bool = False, + photometric_head: bool = False, + photometric_dropout: float = 0.0, + fine_chroma_space: str = "uv", + exposure_pregain: bool = False, + pregain_dropout: float = 0.0, + pregain_max_log_gain: float = 1.6, + pregain_target_weight: float = 0.0, + colour_head: bool = False, + colour_dropout: float = 0.0, + colour_target_weight: float = 0.0, + **kwargs, + ) -> None: + super().__init__(*args, **kwargs) + if fine_chroma_space not in ("uv", "hv"): + raise ValueError("fine_chroma_space must be 'uv' or 'hv'") + self.fine_chroma_space = str(fine_chroma_space) + self.photometric_head = GlobalPhotometricHead() if photometric_head else None + self.photometric_dropout = float(photometric_dropout) + self.exposure_pregain = ( + ExposurePreGain(max_log_gain=float(pregain_max_log_gain)) if exposure_pregain else None + ) + self.pregain_dropout = float(pregain_dropout) + self.pregain_target_weight = float(pregain_target_weight) + self.colour_head = GlobalColourHead() if colour_head else None + self.colour_dropout = float(colour_dropout) + self.colour_target_weight = float(colour_target_weight) + # Whole-frame context (Phase-1 on the full image) enters through the + # two live paths — added to the crop's context tokens and to the + # adaLN global vector — behind zero-init projections (identity at + # warm start). + if global_context: + cdim = int(self.conditioner.cond_dim) + self.ctx_full_proj = nn.Linear(cdim, cdim) + self.global_full_proj = nn.Linear(cdim, cdim) + for module in (self.ctx_full_proj, self.global_full_proj): + nn.init.zeros_(module.weight) + nn.init.zeros_(module.bias) + else: + self.ctx_full_proj = None + self.global_full_proj = None + self.cond_dropout_prob = float(cond_dropout_prob) + self.pyramid_loss_weights = tuple(float(w) for w in pyramid_loss_weights) + # Learned null condition (DGF): replaces the two live injection paths + # (cross-attention context, adaLN global vector). Zero-initialized so + # the untrained null branch coincides with the measured ablation. + if self.cond_dropout_prob > 0.0: + tokens = int(self.conditioner.num_nodes) + 2 + cond_dim = int(self.conditioner.cond_dim) + self.null_context = nn.Parameter(torch.zeros(1, tokens, cond_dim)) + self.null_global = nn.Parameter(torch.zeros(1, cond_dim)) + else: + self.null_context = None + self.null_global = None + self.fine_l1_weight = float(fine_l1_weight) + self.fine_vgg_weight = float(fine_vgg_weight) + self.fine_chroma_weight = float(fine_chroma_weight) + self.fine_luma_weight = float(fine_luma_weight) + self.full_res_tail = ( + FullResTail(blocks=int(tail_blocks), width=int(tail_width)) + if int(tail_blocks) > 0 + else None + ) + if use_output_film: + self.output_film = nn.Linear(GLOBAL_CONDITION_DIM, 6) + nn.init.zeros_(self.output_film.weight) + nn.init.zeros_(self.output_film.bias) + else: + self.output_film = None + self.eval_sample_steps = int(self.schedule.timesteps) + # Deliberately hidden from nn.Module bookkeeping: the criterion is + # part of the objective, not of the model state. + object.__setattr__(self, "_perceptual", None) + + def build_condition(self, representation: Any): + bundle = super().build_condition(representation) + full = getattr(representation, "full_frame", None) + if self.ctx_full_proj is None or full is None: + return bundle + full_bundle = self.conditioner(full, mode=self.condition_mode) + return _replace_bundle( + bundle, + context=bundle.context + self.ctx_full_proj(full_bundle.context.to(bundle.context.dtype)), + global_vector=bundle.global_vector + + self.global_full_proj(full_bundle.global_vector.to(bundle.global_vector.dtype)), + ) + + def null_condition(self, condition: Any, mask: Optional[Tensor] = None) -> Any: + """Swap the live injection paths for the learned null tokens. + + ``mask`` [B] selects rows to null (per-sample conditioning dropout); + ``None`` nulls the whole batch (unconditional branch at inference). + """ + + if self.null_context is None: + raise RuntimeError("model was built without null-condition tokens") + context = condition.context + global_vector = condition.global_vector + null_context = self.null_context.to(context.dtype).expand_as(context) + null_global = self.null_global.to(global_vector.dtype).expand_as(global_vector) + if mask is None: + new_context, new_global = null_context, null_global + else: + row = mask.view(-1, 1, 1).to(torch.bool) + new_context = torch.where(row, null_context, context) + new_global = torch.where(row.view(-1, 1), null_global, global_vector) + return _replace_bundle( + condition, context=new_context, global_vector=new_global + ) + + def predict_x0_pyramid( + self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition: Any + ): + """x0 prediction plus the coarse-to-fine band estimates (if any).""" + + if getattr(self.denoiser, "pyramid_heads", None) is None: + return self.predict_x0(u_t, u_y, timesteps, condition), [] + return self.denoiser(u_t, u_y, timesteps, condition, return_pyramid=True) + + def apply_pregain( + self, + degraded: Tensor, + representation: Any, + dose: float = 1.0, + drop_mask: Optional[Tensor] = None, + ) -> Tensor: + """Input-side exposure gain (v10); the input itself when disabled.""" + + if self.exposure_pregain is None: + return degraded + gained, _ = self.exposure_pregain(degraded, representation, dose=dose, drop_mask=drop_mask) + return gained.to(degraded.dtype) + + def apply_image_head( + self, + image: Tensor, + degraded: Tensor, + representation: Any, + photometric_dose: float = 1.0, + photometric_drop: Optional[Tensor] = None, + colour_dose: float = 1.0, + colour_drop: Optional[Tensor] = None, + ) -> Tensor: + """Full-res tail + global FiLM + global exposure controllable (+ v12 + global colour transform); exact identity at initialization.""" + + if self.full_res_tail is not None: + # fp32: the NAFNet SimpleGate products overflow fp16 once the + # pre-gain lifts a low-light input (x3.4 -> |activation| ~400 -> + # 400^2 > 65504; LOLv2 whole-image restoration went NaN on the + # MI325X run). The tail is 0.2M parameters; the cost is small. + with torch.cuda.amp.autocast(enabled=False): + image = image.float() + self.full_res_tail( + torch.cat((image.float(), degraded.float()), dim=1) + ) + if self.output_film is not None: + with torch.cuda.amp.autocast(enabled=False): + parameters = self.output_film( + representation.global_condition.float() + ) + scale, shift = parameters.view(-1, 2, 3, 1, 1).unbind(dim=1) + image = image * (1.0 + scale) + shift + if self.photometric_head is not None: + image = self.photometric_head( + image, representation, dose=photometric_dose, drop_mask=photometric_drop + ).to(image.dtype) + if self.colour_head is not None: + image = self.colour_head( + image, representation, dose=colour_dose, drop_mask=colour_drop + ).to(image.dtype) + return image + + def chroma_planes(self, image: Tensor) -> Tensor: + """Chroma planes for the fine chroma loss: BT.601 UV, or the HVI HV + plane whose intensity collapse down-weights chroma in dark pixels.""" + if self.fine_chroma_space == "hv": + from src.models.graph_encoder.hvi import rgb_to_hvi + + return rgb_to_hvi(image.float().clamp(0.0, 1.0), 0.2)[:, :2] + return rgb_to_uv(image) + + def _perceptual_loss(self, prediction: Tensor, target: Tensor) -> Tensor: + if self.fine_vgg_weight == 0.0: + return prediction.new_zeros(()) + if self._perceptual is None: + from src.models.restoration.refiner_decoder import VGGPerceptualLoss + + module = VGGPerceptualLoss().to(prediction.device) + object.__setattr__(self, "_perceptual", module) + with torch.cuda.amp.autocast(enabled=False): + return self._perceptual( + prediction.float().clamp(0.0, 1.0), target.float() + ) + + def training_loss( + self, + clean: Tensor, + degraded: Tensor, + representation: Any, + timesteps: Tensor, + noise: Optional[Tensor] = None, + ) -> v6.MoETrainStepResult: + """Composite objective; the runtime-sampled ``timesteps`` is ignored + because every microstep trains both chain positions.""" + + del timesteps + pregain_drop = None + pregain_loss = clean.new_zeros(()) + if self.exposure_pregain is not None and self.training and self.pregain_dropout > 0.0: + pregain_drop = torch.rand(clean.shape[0], device=clean.device) < self.pregain_dropout + if self.exposure_pregain is not None and self.pregain_target_weight > 0.0: + # Direct supervision of the (unmasked) log-gain; the target is + # computed from the ORIGINAL degraded image before gaining. + with torch.cuda.amp.autocast(enabled=False): + raw_log_gain = self.exposure_pregain.log_gain(degraded, representation) + target = pregain_target(clean, degraded, self.exposure_pregain.max_log_gain) + pregain_loss = self.pregain_target_weight * (raw_log_gain - target).square().mean() + degraded = self.apply_pregain(degraded, representation, drop_mask=pregain_drop) + u0 = pixel_unshuffle2(clean) + uy = pixel_unshuffle2(degraded) + if noise is None: + noise = torch.randn_like(u0) + condition = self.build_condition(representation) + if self.training and self.cond_dropout_prob > 0.0: + drop = torch.rand(u0.shape[0], device=u0.device) < self.cond_dropout_prob + # Always route through the null tokens (a row-wise where), even + # when no row is dropped: the result is bitwise the conditioned + # bundle, but the null parameters stay in the autograd graph on + # every micro-batch, which DDP + no_sync accumulation requires. + condition = self.null_condition(condition, drop) + kappa = self.effective_kappa(condition) + terminal = self.schedule.timesteps + t_coarse = torch.full( + (u0.shape[0],), terminal, device=u0.device, dtype=torch.long + ) + u_t = self.schedule.q_sample(u0, uy, t_coarse, noise=noise, kappa=kappa) + coarse_prediction, pyramid = self.predict_x0_pyramid( + u_t, uy, t_coarse, condition + ) + coarse_loss = (coarse_prediction.float() - u0.float()).square().mean() + # Deep supervision of the coarse-to-fine bands: each decoder scale is + # asked for the area-downsampled clean state (MSE only; perceptual + # terms stay at full resolution). + pyramid_loss = coarse_prediction.new_zeros(()) + for weight, estimate in zip(self.pyramid_loss_weights, pyramid): + target = F.interpolate( + u0.float(), size=estimate.shape[-2:], mode="area" + ) + pyramid_loss = pyramid_loss + weight * ( + estimate.float() - target + ).square().mean() + + # Fine step is built from the model's OWN detached estimate — the + # network learns to polish its actual chain state, not a + # teacher-forced one. The mirrored noise keeps the plan replayable. + mean, variance = self.schedule.posterior_mean_variance( + u_t, coarse_prediction.detach(), t_coarse, kappa=kappa + ) + fine_noise = torch.flip(noise, dims=(-1,)) + u_fine = mean + torch.sqrt(variance) * fine_noise + t_fine = torch.full( + (u0.shape[0],), 1, device=u0.device, dtype=torch.long + ) + fine_prediction = self.predict_x0(u_fine, uy, t_fine, condition) + fine_image = pixel_shuffle2(fine_prediction.float()) + photometric_drop = None + if self.photometric_head is not None and self.training and self.photometric_dropout > 0.0: + photometric_drop = torch.rand(u0.shape[0], device=u0.device) < self.photometric_dropout + colour_drop = None + if self.colour_head is not None and self.training and self.colour_dropout > 0.0: + colour_drop = torch.rand(u0.shape[0], device=u0.device) < self.colour_dropout + colour_loss = fine_image.new_zeros(()) + if self.colour_head is not None and self.colour_target_weight > 0.0: + # Supervised target: the least-squares global map from the image + # BEFORE the colour head (tail + photometric head applied) to the + # clean image; the head must learn to predict it. + with torch.cuda.amp.autocast(enabled=False), torch.no_grad(): + # target and the head's image statistics need no gradient; + # keeping this pass out of autograd avoids a second full-res + # tail activation set (OOM at batch 32 on MI325X otherwise) + before = self.apply_image_head( + fine_image.detach(), degraded.float(), representation, + photometric_drop=photometric_drop, colour_dose=0.0, + ) + target_m, target_b = colour_target(before, clean.float()) + target_m = target_m.clamp(-3.0, 3.0) + target_b = target_b.clamp(-self.colour_head.max_bias, self.colour_head.max_bias) + pred_m, pred_b = self.colour_head.coefficients(before, representation) + colour_loss = self.colour_target_weight * ( + (pred_m - target_m).square().sum(dim=(1, 2)).mean() + + (pred_b - target_b).square().sum(dim=1).mean() + ) + fine_image = self.apply_image_head( + fine_image, degraded.float(), representation, + photometric_drop=photometric_drop, colour_drop=colour_drop, + ) + fine_l1 = F.l1_loss(fine_image, clean.float()) + fine_vgg = self._perceptual_loss(fine_image, clean) + if self.fine_chroma_weight != 0.0: + fine_chroma = F.l1_loss( + self.chroma_planes(fine_image), self.chroma_planes(clean.float()) + ) + else: + fine_chroma = fine_image.new_zeros(()) + if self.fine_luma_weight != 0.0: + fine_luma = F.l1_loss( + pooled_luma(fine_image), pooled_luma(clean.float()) + ) + else: + fine_luma = fine_image.new_zeros(()) + fine_loss = ( + self.fine_l1_weight * fine_l1 + + self.fine_vgg_weight * fine_vgg + + self.fine_chroma_weight * fine_chroma + + self.fine_luma_weight * fine_luma + ) + + gate_loss = ( + self.gate_anchor_weight * condition.gate.anchor_loss.float() + + self.gate_correction_weight + * condition.gate.correction_loss.float() + ) + if self.expert_kappa is not None and self.training: + self.expert_kappa.advance() + return v6.MoETrainStepResult( + loss=coarse_loss + pyramid_loss + fine_loss + gate_loss + pregain_loss + colour_loss, + reconstruction_loss=coarse_loss, + gate_loss=fine_loss, + u0_prediction=fine_prediction, + u0_target=u0, + u_t=u_t, + kappa=kappa.detach(), + ) + + +def _file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for block in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +_BLOCK_KEY = __import__("re").compile(r"^denoiser\.(down_blocks|up_blocks)\.(\d+)\.(\d+)\.") + + +def _is_appended_block_key(name: str, donor: Mapping[str, Any]) -> bool: + """v11: a LeWin block whose index is beyond every block the donor has in + the same stage (appended, zero-init, identity) may be missing from the + donor; an index the donor DOES have must be present.""" + + match = _BLOCK_KEY.match(name) + if match is None: + return False + path, stage, index = match.group(1), match.group(2), int(match.group(3)) + prefix = "denoiser.%s.%s." % (path, stage) + donor_indices = { + int(key[len(prefix):].split(".")[0]) + for key in donor + if key.startswith(prefix) and key[len(prefix):].split(".")[0].isdigit() + } + return bool(donor_indices) and index > max(donor_indices) + + +def load_v6_warmstart( + path: Path, + expected_sha256: str, + model: Phase2UnifiedV7Module, + *, + weight_source: str = "ema", +) -> Dict[str, Any]: + """Load the full v6.1 state except the (reshaped) schedule buffers.""" + + actual = _file_sha256(path) + if actual.lower() != str(expected_sha256).lower(): + raise ValueError("v6 warmstart sha256 mismatch") + checkpoint = v4._torch_load(Path(path), map_location="cpu") + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("warmstart must be a Phase-2 checkpoint") + if weight_source == "model": + state = checkpoint.get("model_state_dict") + elif weight_source == "ema": + ema_state = checkpoint.get("ema_state_dict") + state = ema_state.get("shadow") if isinstance(ema_state, Mapping) else None + else: + raise ValueError("weight_source must be 'model' or 'ema'") + if not isinstance(state, Mapping): + raise ValueError("v6 warmstart is missing the selected state") + + filtered = { + name: value + for name, value in state.items() + if not name.startswith("schedule.") + } + target = model.state_dict() + # Image-head submodules added AFTER the source run keep their fresh + # zero-initialized state (they are exact identities), so their absence + # from the source is tolerated — nothing else is. + import re as _re + + fresh_head_keys = sorted( + name + for name in target + if name not in filtered + and ( + name.startswith(_V7_FRESH_HEAD_PREFIXES) + or _re.match(r"^full_res_tail\.body\.\d+\.", name) is not None + or _is_appended_block_key(name, filtered) + ) + ) + expected = { + n + for n in target + if not n.startswith("schedule.") and n not in set(fresh_head_keys) + } + # Optional image-head modules the TARGET was built without (an ablation + # that drops the photometric head / pre-gain / colour head) may be present + # in the donor: their weights are dropped, everything else must match. + dropped_head_keys = sorted( + name for name in filtered + if name not in expected and name.startswith(_V7_FRESH_HEAD_PREFIXES) + ) + if dropped_head_keys: + filtered = {k: v for k, v in filtered.items() if k not in set(dropped_head_keys)} + print("[warmstart] dropping %d donor keys of heads absent from the target: %s" + % (len(dropped_head_keys), ", ".join(sorted({k.split(".")[0] for k in dropped_head_keys}))), + flush=True) + if set(filtered.keys()) != expected: + missing = sorted(expected - set(filtered)) + unexpected = sorted(set(filtered) - expected) + raise ValueError( + "v6 warmstart key mismatch; missing=%r unexpected=%r" + % (missing[:6], unexpected[:6]) + ) + result = model.load_state_dict(filtered, strict=False) + allowed_missing = set(fresh_head_keys) + if result.unexpected_keys or any( + not name.startswith("schedule.") and name not in allowed_missing + for name in result.missing_keys + ): + raise RuntimeError("v7 warmstart loader violated its allowlist") + return { + "mapping_version": V7_WARMSTART_MAPPING_VERSION, + "source_checkpoint_sha256": actual, + "source_step": int(checkpoint.get("step", -1)), + "weight_source": weight_source, + "schedule_reinitialized": True, + "fresh_head_keys": len(fresh_head_keys), + "dropped_head_keys": len(dropped_head_keys), + "materialized_state_hash": v4.model_state_hash(model), + } + + +def sample_unified_restoration( + model: nn.Module, + phase1: "v4.FrozenPhase1", + degraded: Tensor, + *, + seed: int, + record_ids: Optional[Sequence[str]] = None, + initial_noise: Optional[Tensor] = None, + amp_enabled: Optional[bool] = None, + dose: Optional[float] = None, + full_degraded: Optional[Tensor] = None, + photometric_dose: Optional[float] = None, + pregain_dose: Optional[float] = None, + colour_dose: Optional[float] = None, +) -> Tensor: + """v6 exact-posterior sampling plus the v7 image head. + + ``dose`` (DGF) interpolates the coarse-step x0 prediction between the + learned null branch and the conditioned branch: + x0 = x0(null) + dose * (x0(c) - x0(null)); the fine step always runs + fully conditioned. ``None`` (or 1.0) is the plain conditioned sampler. + + Mirrors ``v6.sample_moe_restoration`` step for step; the only addition is + ``apply_image_head`` on the shuffled image BEFORE crop/clamp, matching + the training-time order. Bitwise-identical to the v6 sampler when the + head is disabled (it is an exact identity then). + """ + + restorer = v4.unwrap_module(model) + if not isinstance(restorer, Phase2UnifiedV7Module): + raise TypeError("model must wrap Phase2UnifiedV7Module") + steps = int(getattr(restorer, "eval_sample_steps", 1)) + use_amp = degraded.is_cuda if amp_enabled is None else bool(amp_enabled) + with torch.cuda.amp.autocast(enabled=use_amp): + padded, size = v4.pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + if full_degraded is not None and getattr(restorer, "ctx_full_proj", None) is not None: + representation.full_frame = phase1(full_degraded.to(degraded.device)) + if full_degraded is not None: + representation.full_image = full_degraded.to(degraded.device) + # v10 input-side exposure gain (identity when the module is absent). + padded = restorer.apply_pregain( + padded, representation, + dose=1.0 if pregain_dose is None else float(pregain_dose), + ) + condition = restorer.build_condition(representation) + if float(getattr(restorer, "cond_dropout_prob", 0.0)) >= 1.0: + # A model trained with p = 1 never saw a real condition: sample + # it fully unconditionally (both steps); ``dose`` is meaningless. + condition = restorer.null_condition(condition) + dose = None + uy = pixel_unshuffle2(padded) + if initial_noise is None: + initial_noise = v4._noise_for_records( + uy, list(record_ids) if record_ids else None, + seed=seed, stage="initial", + ) + kappa_vector = restorer.effective_kappa(condition) + kappa = restorer.schedule.kappa_factor(kappa_vector, uy) + eta_terminal = restorer.schedule.eta[-1].to(uy.device, uy.dtype) + u_t = uy + kappa * torch.sqrt(eta_terminal) * initial_noise + batch = uy.shape[0] + if steps <= 1: + timesteps = torch.full( + (batch,), restorer.schedule.timesteps, + device=uy.device, dtype=torch.long, + ) + u_t = restorer.predict_x0(u_t, uy, timesteps, condition) + else: + null_bundle = None + if dose is not None and float(dose) != 1.0: + null_bundle = restorer.null_condition(condition) + for step in restorer.schedule.reverse_timesteps(): + timesteps = torch.full( + (batch,), step, device=uy.device, dtype=torch.long + ) + u0_hat = restorer.predict_x0(u_t, uy, timesteps, condition) + if null_bundle is not None and step == restorer.schedule.timesteps: + u0_null = restorer.predict_x0(u_t, uy, timesteps, null_bundle) + u0_hat = u0_null + float(dose) * (u0_hat - u0_null) + mean, variance = restorer.schedule.posterior_mean_variance( + u_t, u0_hat, timesteps, kappa=kappa_vector + ) + if step > 1: + noise = v4._noise_for_records( + u_t, list(record_ids) if record_ids else None, + seed=seed, stage=step, + ) + u_t = mean + torch.sqrt(variance) * noise + else: + u_t = mean + restored = pixel_shuffle2(u_t) + restored = restorer.apply_image_head( + restored, padded.to(restored.dtype), representation, + photometric_dose=1.0 if photometric_dose is None else float(photometric_dose), + colour_dose=1.0 if colour_dose is None else float(colour_dose), + ) + height, width = size + return restored[..., :height, :width].clamp(0.0, 1.0) + + +sample_unified_restoration.accepts_full_frame = True + + +BASE_BLOCKS_PER_STAGE = 2 + + +def _parse_extra_blocks(value: Any) -> Sequence[int]: + """Extra LeWin blocks appended per stage (v11), "" -> (0, 0, 0, 0).""" + + if value is None or (isinstance(value, str) and not value.strip()): + return (0, 0, 0, 0) + parts = ( + tuple(int(v) for v in value.split(",") if v.strip()) + if isinstance(value, str) else tuple(int(v) for v in value) + ) + if len(parts) != 4 or any(v < 0 for v in parts): + raise ValueError("extra blocks per stage must be four non-negative ints") + return parts + + +def blocks_per_stage(args: argparse.Namespace) -> Sequence[int]: + extra = _parse_extra_blocks(getattr(args, "extra_blocks_per_stage", "")) + return tuple(BASE_BLOCKS_PER_STAGE + int(e) for e in extra) + + +def _parse_scales(value: Any) -> Sequence[int]: + """Stage indices for the v10 global-attention blocks ("" -> none).""" + + if value is None: + return () + if isinstance(value, str): + return tuple(int(v) for v in value.split(",") if v.strip()) + return tuple(int(v) for v in value) + + +def _parse_weights(value: Any) -> Sequence[float]: + if value is None: + return _DEFAULT_PYRAMID_WEIGHTS + if isinstance(value, str): + return tuple(float(v) for v in value.split(",") if v.strip()) + return tuple(float(v) for v in value) + + +def _build_v7_restorer( + args: argparse.Namespace, device: torch.device +) -> Phase2UnifiedV7Module: + schedule = ResidualShiftSchedule( + timesteps=args.timesteps, eta_end=args.eta_end, + min_noise=args.min_noise, power=args.power, kappa=args.kappa, + ) + model = Phase2UnifiedV7Module( + conditioner=MoEGraphConditionerV6( + cond_dim=args.cond_dim, stage_dims=args.dims, + gate_hidden_dim=args.gate_hidden_dim, + gate_max_correction=args.gate_max_correction, + ), + denoiser=( + UformerMoEUNetV7( + dims=args.dims, cond_dim=args.cond_dim, + expert_rank=args.expert_rank, + pyramid_heads=bool(getattr(args, "pyramid_heads", False)), + global_attention_scales=_parse_scales( + getattr(args, "global_attention_scales", "") + ), + blocks_per_stage=blocks_per_stage(args), + grad_checkpoint=bool(getattr(args, "grad_checkpoint", False)), + ) + if args.backbone == "uformer" + else MoEGraphResidualShiftUNetV6( + dims=args.dims, cond_dim=args.cond_dim, + expert_rank=args.expert_rank, + ) + ), + schedule=schedule, + expert_kappa=ExpertKappaSchedule( + kappa_per_expert=v6._parse_kappa_values(args.expert_kappa_values), + kappa_global=float(args.kappa), + anneal_microsteps=0, + ), + condition_mode=args.condition, + gate_anchor_weight=args.gate_anchor_weight, + gate_correction_weight=args.gate_correction_weight, + fine_l1_weight=args.fine_l1_weight, + fine_vgg_weight=args.fine_vgg_weight, + fine_chroma_weight=float(getattr(args, "fine_chroma_weight", 0.0)), + fine_luma_weight=float(getattr(args, "fine_luma_weight", 0.0)), + tail_blocks=int(getattr(args, "full_res_tail_blocks", 0)), + tail_width=int(getattr(args, "full_res_tail_width", 48)), + use_output_film=bool(getattr(args, "output_film", False)), + global_context=bool(getattr(args, "global_context", False)), + cond_dropout_prob=float(getattr(args, "cond_dropout_prob", 0.0)), + pyramid_loss_weights=_parse_weights( + getattr(args, "pyramid_loss_weights", None) + ), + photometric_head=bool(getattr(args, "photometric_head", False)), + photometric_dropout=float(getattr(args, "photometric_dropout", 0.0)), + fine_chroma_space=str(getattr(args, "fine_chroma_space", "uv")), + exposure_pregain=bool(getattr(args, "exposure_pregain", False)), + pregain_dropout=float(getattr(args, "pregain_dropout", 0.0)), + pregain_max_log_gain=float(getattr(args, "pregain_max_log_gain", 1.6)), + pregain_target_weight=float(getattr(args, "pregain_target_weight", 0.0)), + colour_head=bool(getattr(args, "colour_head", False)), + colour_dropout=float(getattr(args, "colour_dropout", 0.0)), + colour_target_weight=float(getattr(args, "colour_target_weight", 0.0)), + ) + if args.resume is None and args.init_checkpoint is None: + if args.warmstart_v6 is not None: + audit = load_v6_warmstart( + args.warmstart_v6, args.warmstart_v6_sha256, model, + weight_source=args.warmstart_weight_source, + ) + elif bool(getattr(args, "allow_scratch", False)): + audit = {"mapping_version": "from_scratch"} + else: + raise ValueError( + "v7 requires --warmstart-v6, resume/init, or --allow-scratch" + ) + else: + source = args.resume if args.resume is not None else args.init_checkpoint + stored = v4._torch_load(Path(source), map_location="cpu") + architecture = stored.get("architecture") if isinstance(stored, Mapping) else None + audit = ( + dict(architecture.get("warmstart", {})) + if isinstance(architecture, Mapping) + else {"mapping_version": "resumed_state"} + ) + del stored + setattr(args, "_v7_warmstart_audit", audit) + if bool(getattr(args, "freeze_shared_trunk", False)): + for name, parameter in model.named_parameters(): + parameter.requires_grad_(v6._is_v6_only_key(name)) + return model.to(device) + + +def _v7_architecture(args: argparse.Namespace) -> Dict[str, Any]: + audit = getattr(args, "_v7_warmstart_audit", {}) + return { + "name": "unified_two_step_resshift_v7", + "version": 7, + "mechanism": V7_VERSION, + "backbone": str(getattr(args, "backbone", "conv")), + "moe": { + "expert_rank": int(args.expert_rank), + "gate_hidden_dim": int(args.gate_hidden_dim), + "gate_max_correction": float(args.gate_max_correction), + }, + "objective": { + "coarse": "x0_mse_fp32", + "fine": "chain_aware_l1_vgg", + "fine_l1_weight": float(args.fine_l1_weight), + "fine_vgg_weight": float(args.fine_vgg_weight), + "fine_chroma_weight": float( + getattr(args, "fine_chroma_weight", 0.0) + ), + "fine_chroma_space": ( + "hvi_hv_k0.2" if str(getattr(args, "fine_chroma_space", "uv")) == "hv" + else "yuv_bt601_uv" + ), + "fine_luma_weight": float(getattr(args, "fine_luma_weight", 0.0)), + "fine_luma_space": "yuv_bt601_y_pool%d" % _LUMA_POOL_GRID, + "fine_noise": "mirrored_coarse_noise", + }, + "coarse_to_fine": { + "pyramid_heads": bool(getattr(args, "pyramid_heads", False)), + "pyramid_loss_weights": list( + _parse_weights(getattr(args, "pyramid_loss_weights", None)) + ), + }, + "dose": { + "cond_dropout_prob": float(getattr(args, "cond_dropout_prob", 0.0)), + "null_paths": ["context", "global_vector"], + "identity_pair_prob": float(getattr(args, "identity_pair_prob", 0.0)), + }, + "global_context": bool(getattr(args, "global_context", False)), + "exposure_pregain": { + "enabled": bool(getattr(args, "exposure_pregain", False)), + "dropout": float(getattr(args, "pregain_dropout", 0.0)), + "max_log_gain": float(getattr(args, "pregain_max_log_gain", 1.6)), + "target_weight": float(getattr(args, "pregain_target_weight", 0.0)), + "target": "clamped_log_mean_luma_ratio_clean_over_degraded", + "inputs": ["global_condition", "photometric_state", "full_frame.*", + "luma_statistics(crop)", "luma_statistics(full_image)"], + "placement": "input_before_pixel_unshuffle", + }, + "global_attention_scales": list( + _parse_scales(getattr(args, "global_attention_scales", "")) + ), + "colour_head": { + "enabled": bool(getattr(args, "colour_head", False)), + "dropout": float(getattr(args, "colour_dropout", 0.0)), + "target_weight": float(getattr(args, "colour_target_weight", 0.0)), + "form": "diag(exp(d))(I+O)x+b, bounded, output side after the photometric head", + }, + "blocks_per_stage": list(blocks_per_stage(args)), + "grad_checkpoint": bool(getattr(args, "grad_checkpoint", False)), + "data_aug": { + "identity_pair_prob": float(getattr(args, "identity_pair_prob", 0.0)), + "noise_pair_prob": float(getattr(args, "noise_pair_prob", 0.0)), + "identity_exposure_jitter": float(getattr(args, "identity_exposure_jitter", 0.0)), + "extra_clean_root": ( + str(getattr(args, "extra_clean_root", None)) + if getattr(args, "extra_clean_root", None) else None + ), + "extra_clean_prob": float(getattr(args, "extra_clean_prob", 0.0)), + }, + "image_head": { + "full_res_tail_blocks": int( + getattr(args, "full_res_tail_blocks", 0) + ), + "full_res_tail_width": int( + getattr(args, "full_res_tail_width", 48) + ), + "output_film": bool(getattr(args, "output_film", False)), + "photometric_head": bool(getattr(args, "photometric_head", False)), + "photometric_dropout": float(getattr(args, "photometric_dropout", 0.0)), + "photometric_bounds": {"max_log_gain": 0.7, "max_bias": 0.2}, + "photometric_inputs": ["global_condition", "photometric_state", "full_frame.*"], + }, + "dims": list(args.dims), + "cond_dim": int(args.cond_dim), + "state_channels": 12, + "prediction": "x0", + "eval_sample_steps": int(args.timesteps), + "warmstart": dict(audit), + } + + +def _v7_schedule_config(args: argparse.Namespace) -> Dict[str, Any]: + result = dict(_V4_SCHEDULE_CONFIG(args)) + result["expert_kappa"] = { + "enabled": True, + "values": list(v6._parse_kappa_values(args.expert_kappa_values)), + "anneal_steps": 0, + "source": "normalized_node_strengths", + "posterior": "exact_per_sample_kappa", + } + result["unified_two_step"] = True + return result + + +def build_parser() -> argparse.ArgumentParser: + parser = v6.build_parser() + parser.description = __doc__ + parser.add_argument("--fine-l1-weight", type=float, default=1.0) + parser.add_argument("--fine-vgg-weight", type=float, default=0.1) + parser.add_argument( + "--fine-chroma-weight", type=float, default=0.0, + help="L1 weight on BT.601 U/V chroma planes of the fine prediction", + ) + parser.add_argument( + "--fine-luma-weight", type=float, default=0.0, + help="L1 weight on the 8x8-pooled BT.601 luma of the fine prediction", + ) + parser.add_argument( + "--full-res-tail-blocks", type=int, default=0, + help="NAFNet-lite blocks in the full-resolution image head (0 = off)", + ) + parser.add_argument("--full-res-tail-width", type=int, default=48) + parser.add_argument( + "--output-film", action="store_true", + help="global-condition FiLM (per-channel affine) on the output image", + ) + parser.add_argument( + "--pyramid-heads", action="store_true", + help="coarse-to-fine Laplacian band heads at 16/32/64 px (uformer)", + ) + parser.add_argument( + "--pyramid-loss-weights", default="0.1,0.2,0.3", + help="deep-supervision MSE weights for the 16/32/64 px bands", + ) + parser.add_argument( + "--cond-dropout-prob", type=float, default=0.0, + help="per-sample probability of swapping context/global_vector for " + "the learned null tokens (DGF)", + ) + parser.add_argument( + "--photometric-head", action="store_true", + help="global exposure controllable (log-gain, bias) on the output, " + "predicted from Phase-1 global_condition + photometric_state", + ) + parser.add_argument( + "--photometric-dropout", type=float, default=0.0, + help="per-sample probability of zeroing the photometric head (identity path)", + ) + parser.add_argument( + "--fine-chroma-space", choices=("uv", "hv"), default="uv", + help="chroma planes for --fine-chroma-weight: BT.601 UV or HVI HV (k=0.2)", + ) + parser.add_argument( + "--identity-exposure-jitter", type=float, default=0.0, + help="identity pairs get a random global gain exp(U(-j, j)) applied to input AND target", + ) + parser.add_argument( + "--extra-clean-root", default=None, + help="folder of extra clean images used for identity pairs (e.g. Snow100K gt)", + ) + parser.add_argument( + "--extra-clean-prob", type=float, default=0.5, + help="probability that an identity pair is drawn from --extra-clean-root", + ) + parser.add_argument( + "--exposure-pregain", action="store_true", + help="v10: per-image input gain (Retinex-style) predicted from Phase-1 " + "vectors + whole-frame luma statistics, applied before the trunk", + ) + parser.add_argument( + "--pregain-dropout", type=float, default=0.0, + help="per-sample probability of forcing the pre-gain to 1 (identity path)", + ) + parser.add_argument( + "--pregain-max-log-gain", type=float, default=1.6, + help="tanh bound of the pre-gain log-gain (1.6 = x0.2 .. x5)", + ) + parser.add_argument( + "--pregain-target-weight", type=float, default=0.0, + help="v11: weight of the supervised pre-gain loss (log-gain vs clamped log " + "luma ratio clean/degraded); 0 = end-to-end only", + ) + parser.add_argument( + "--colour-head", action="store_true", + help="v12: per-image global colour transform (3x3 + bias) on the output, " + "predicted from Phase-1 vectors + whole-frame luma statistics", + ) + parser.add_argument("--colour-dropout", type=float, default=0.0, + help="per-sample probability of forcing the colour head to identity") + parser.add_argument("--colour-target-weight", type=float, default=0.0, + help="weight of the supervised colour-head loss (least-squares target per image)") + parser.add_argument( + "--global-attention-scales", default="", + help="v10: comma-separated stage indices (0..3) that get a zero-init " + "whole-map self-attention block after the LeWin blocks, e.g. 2,3", + ) + parser.add_argument( + "--extra-blocks-per-stage", default="", + help="v11: LeWin blocks appended per stage beyond the base 2, e.g. 0,2,4,4 " + "(zero-init adaLN -> identity at warm start; down and up paths)", + ) + parser.add_argument( + "--grad-checkpoint", action="store_true", + help="v11: recompute transformer blocks in backward (single-process runs only " + "with torch 1.10 reentrant checkpoint + DDP find_unused)", + ) + parser.add_argument("--warmstart-v6", type=Path) + parser.add_argument("--warmstart-v6-sha256") + parser.add_argument( + "--backbone", choices=("conv", "uformer"), default="conv" + ) + parser.add_argument( + "--allow-scratch", action="store_true", + help="permit training without a warm start (uformer backbone)", + ) + return parser + + +@contextlib.contextmanager +def _installed_v7_backend(args: argparse.Namespace) -> Iterator[None]: + replacements = { + "_build_restorer": _build_v7_restorer, + "_architecture": _v7_architecture, + "_schedule_config": _v7_schedule_config, + "_data_plan": v6._moe_data_plan, + "sample_restoration": sample_unified_restoration, + } + originals = {name: getattr(v4, name) for name in replacements} + try: + for name, replacement in replacements.items(): + setattr(v4, name, replacement) + yield + finally: + for name, original in originals.items(): + setattr(v4, name, original) + + +def run(args: argparse.Namespace) -> None: + v4.validate_runtime_args(args) + if int(args.timesteps) != 2: + raise ValueError("v7 is a two-step process; pass --timesteps 2") + for name in ("fine_l1_weight", "fine_vgg_weight"): + if float(getattr(args, name)) < 0: + raise ValueError("%s must be non-negative" % name) + has_path = args.warmstart_v6 is not None + has_sha = args.warmstart_v6_sha256 is not None + if has_path != has_sha: + raise ValueError("warmstart path and sha256 go together") + with _installed_v7_backend(args): + v4.run(args) + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(build_parser().parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/train_refiner_a.py b/dataset/phase1_noise_20260906/trial_code_staging/train_refiner_a.py new file mode 100644 index 0000000000000000000000000000000000000000..2c95a885a1a861444cab175ab49507bbc5687e47 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/train_refiner_a.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +"""Two-stage trainer for the option-A refiner decoder. + +Stage ``pretrain`` — decoder learns a natural-image prior first: clean crops + with light synthetic corruption -> clean, L1+VGG loss. +Stage ``finetune`` — frozen Phase-1 + frozen v4 U-Net produce the one-step + x0 regression on the fly; the refiner maps + (x0_hat, degraded) -> clean with the same loss. + +The one-step regressor with record-keyed noise reproduces the measured +22.68 dB macro baseline, and the refiner's zero-init head starts the full +pipeline exactly there. +""" + +from __future__ import annotations + +import argparse +import json +import math +import time +from pathlib import Path +from typing import Dict, Iterable, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn +import torch.nn.functional as F +from torch.utils.data import DataLoader + +import train_phase2_graph_resshift_v4 as v4 +from src.data.phase2_v4 import ( + DeterministicBalancedBatchSampler, + Phase2PairDataset, + load_train_val_manifest, +) +from src.models.restoration.refiner_decoder import ( + REFINER_VERSION, + RefinerDecoder, + VGGPerceptualLoss, +) + +V4_RUN = Path("outputs/phase2_graph_resshift_v4/gate_d5_seed42") + + +def light_corruption(clean: Tensor, generator: torch.Generator) -> Tensor: + """Mild, deterministic corruption for the natural-image-prior pretrain.""" + kind = int(torch.randint(0, 3, (1,), generator=generator)) + if kind == 0: + return clean.clone() + if kind == 1: + sigma = float(torch.empty(1).uniform_(0.005, 0.03, generator=generator)) + noise = torch.randn( + tuple(clean.shape), generator=generator, dtype=torch.float32 + ).to(clean.device) + return (clean + sigma * noise).clamp(0.0, 1.0) + sigma = float(torch.empty(1).uniform_(0.4, 1.2, generator=generator)) + size = int(2 * round(2 * sigma) + 1) + offsets = torch.arange(size, dtype=torch.float32) - size // 2 + kernel = torch.exp(-offsets.square() / (2 * sigma * sigma)) + kernel = (kernel / kernel.sum()).to(clean.device) + pad = size // 2 + row = kernel.view(1, 1, 1, size).expand(3, 1, 1, size) + col = kernel.view(1, 1, size, 1).expand(3, 1, size, 1) + blurred = F.conv2d(F.pad(clean, (pad, pad, 0, 0), mode="reflect"), row, groups=3) + return F.conv2d(F.pad(blurred, (0, 0, pad, pad), mode="reflect"), col, groups=3) + + +@torch.no_grad() +def one_step_x0( + model: nn.Module, + phase1, + degraded: Tensor, + record_ids: Sequence[str], + seed: int, + stage: str, +) -> Tensor: + """Single x0 prediction from u_T with record-keyed noise (frozen).""" + if hasattr(model, "effective_kappa"): + import train_phase2_graph_moe_v6 as v6 + + return v6.sample_moe_restoration( + model, phase1, degraded, seed=seed, + record_ids=list(record_ids), amp_enabled=degraded.is_cuda, + ) + padded, size = v4.pad_to_multiple(degraded, multiple=16) + representation = phase1(padded) + condition = model.build_condition(representation) + uy = v4.pixel_unshuffle2(padded) + noise = v4._noise_for_records(uy, list(record_ids), seed=seed, stage=stage) + eta_terminal = model.schedule.eta[-1].to(uy.device, uy.dtype) + kappa = model.schedule.kappa.to(uy.device, uy.dtype) + u_terminal = uy + kappa * torch.sqrt(eta_terminal) * noise + timesteps = torch.full( + (uy.shape[0],), model.schedule.timesteps, device=uy.device, dtype=torch.long + ) + u0_hat = model.predict_x0(u_terminal, uy, timesteps, condition) + out = v4.pixel_shuffle2(u0_hat) + height, width = size + return out[..., :height, :width].clamp(0.0, 1.0) + + +def load_frozen_regressor(device: torch.device, kind: str = "v4", run_dir: Path = None): + run_dir = Path(run_dir) if run_dir is not None else V4_RUN + cfg = json.loads((run_dir / "run_config.json").read_text()) + args = argparse.Namespace(**cfg) + for key in ("manifest", "data_root", "phase1_checkpoint"): + setattr(args, key, Path(str(getattr(args, key)))) + if kind == "v4": + model = v4._build_restorer(args, device) + elif kind == "v6": + import train_phase2_graph_moe_v6 as v6 + + for key in ("warmstart_v4", "resume", "init_checkpoint"): + if getattr(args, key, None) is not None: + setattr(args, key, Path(str(getattr(args, key)))) + args.resume = run_dir / "best.pt" + model = v6._build_moe_restorer(args, device) + model.eval_sample_steps = 1 + else: + raise ValueError("regressor kind must be v4 or v6") + checkpoint = v4._torch_load(run_dir / "best.pt") + model.load_state_dict(checkpoint["ema_state_dict"]["shadow"], strict=True) + model.eval() + for parameter in model.parameters(): + parameter.requires_grad_(False) + phase1, _ = v4.build_frozen_phase1( + args.phase1_checkpoint, args.phase1_sha256, device + ) + return model, phase1, args + + +def build_loaders(args, splits, batch_size: int, steps: int, seed: int): + train_dataset = Phase2PairDataset( + splits.train, crop_size=256, training=True, upscale_small=True + ) + sampler = DeterministicBalancedBatchSampler( + [record.label for record in splits.train] + if hasattr(splits.train[0], "label") + else [record.degradation for record in splits.train], + batch_size=batch_size, + steps=steps, + seed=seed, + ) + train_loader = DataLoader( + train_dataset, batch_sampler=sampler, num_workers=6, pin_memory=True + ) + val_loader = DataLoader( + Phase2PairDataset(splits.val, crop_size=256, training=False, upscale_small=True), + batch_size=8, shuffle=False, num_workers=4, pin_memory=True, + ) + return train_loader, val_loader + + +@torch.no_grad() +def evaluate( + refiner: RefinerDecoder, + regressor, + phase1, + loader: DataLoader, + device: torch.device, + eval_seed: int, +) -> Dict[str, object]: + refiner.eval() + per_domain: Dict[str, Dict[str, list]] = {} + for batch in loader: + degraded = batch["degraded"].to(device) + clean = batch["clean"].to(device) + record_ids = [str(value) for value in batch["record_id"]] + domains = [str(value) for value in batch["degradation"]] + x0_hat = one_step_x0( + regressor, phase1, degraded, record_ids, eval_seed, "initial" + ) + refined = refiner(x0_hat, degraded) + base_psnr = v4.rgb_psnr_per_image(x0_hat, clean).cpu().tolist() + ref_psnr = v4.rgb_psnr_per_image(refined, clean).cpu().tolist() + ref_ssim = v4.rgb_ssim_per_image(refined, clean).cpu().tolist() + for index, domain in enumerate(domains): + slot = per_domain.setdefault( + domain, {"base": [], "psnr": [], "ssim": []} + ) + slot["base"].append(base_psnr[index]) + slot["psnr"].append(ref_psnr[index]) + slot["ssim"].append(ref_ssim[index]) + summary: Dict[str, object] = {"per_domain": {}} + macro_p, macro_s, macro_b = [], [], [] + for domain, values in sorted(per_domain.items()): + base = sum(values["base"]) / len(values["base"]) + psnr = sum(values["psnr"]) / len(values["psnr"]) + ssim = sum(values["ssim"]) / len(values["ssim"]) + summary["per_domain"][domain] = { + "one_step_psnr": base, "refined_psnr": psnr, "refined_ssim": ssim, + "delta": psnr - base, "count": len(values["psnr"]), + } + macro_p.append(psnr) + macro_s.append(ssim) + macro_b.append(base) + summary["macro_refined_psnr"] = sum(macro_p) / len(macro_p) + summary["macro_refined_ssim"] = sum(macro_s) / len(macro_s) + summary["macro_one_step_psnr"] = sum(macro_b) / len(macro_b) + refiner.train() + return summary + + +def append_jsonl(payload: Dict[str, object], path: Path) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(json.dumps(payload, sort_keys=True) + "\n") + + +def run_stage( + stage: str, + refiner: RefinerDecoder, + perceptual: Optional[VGGPerceptualLoss], + regressor, + phase1, + loaders, + device: torch.device, + output_dir: Path, + args, +) -> None: + train_loader, val_loader = loaders + steps = args.pretrain_steps if stage == "pretrain" else args.finetune_steps + optimizer = torch.optim.AdamW( + refiner.parameters(), lr=args.lr, betas=(0.9, 0.99), weight_decay=1e-4 + ) + scheduler = torch.optim.lr_scheduler.CosineAnnealingLR( + optimizer, T_max=max(1, steps), eta_min=args.lr * 0.01 + ) + best_macro = -1.0 + refiner.train() + iterator = iter(train_loader) + started = time.time() + for step in range(1, steps + 1): + batch = next(iterator) + clean = batch["clean"].to(device, non_blocking=True) + if stage == "pretrain": + generator = torch.Generator() + generator.manual_seed(args.seed * 100003 + step) + corrupted = light_corruption(clean, generator) + x0_hat, degraded = corrupted, corrupted + else: + degraded = batch["degraded"].to(device, non_blocking=True) + record_ids = [str(value) for value in batch["record_id"]] + x0_hat = one_step_x0( + regressor, phase1, degraded, record_ids, args.seed, step + ) + refined = refiner(x0_hat, degraded) + loss = F.l1_loss(refined, clean) + if perceptual is not None: + loss = loss + args.perceptual_weight * perceptual(refined, clean) + optimizer.zero_grad(set_to_none=True) + loss.backward() + torch.nn.utils.clip_grad_norm_(refiner.parameters(), 1.0) + optimizer.step() + scheduler.step() + if step % 50 == 0: + append_jsonl( + {"event": "train", "stage": stage, "step": step, + "loss": float(loss.detach()), + "lr": float(optimizer.param_groups[0]["lr"]), + "time": time.time()}, + output_dir / "metrics.jsonl", + ) + if stage == "finetune" and (step % args.eval_every == 0 or step == steps): + summary = evaluate( + refiner, regressor, phase1, val_loader, device, args.eval_seed + ) + summary.update({"event": "evaluation", "stage": stage, "step": step, + "time": time.time()}) + append_jsonl(summary, output_dir / "metrics.jsonl") + print(json.dumps( + {k: summary[k] for k in + ("step", "macro_one_step_psnr", "macro_refined_psnr", + "macro_refined_ssim")}, + sort_keys=True), flush=True) + if summary["macro_refined_psnr"] > best_macro: + best_macro = float(summary["macro_refined_psnr"]) + torch.save( + {"refiner_state_dict": refiner.state_dict(), + "stage": stage, "step": step, + "refiner_version": REFINER_VERSION, + "macro_refined_psnr": best_macro, + "config": vars(args)}, + str(output_dir / "refiner_best.pt"), + ) + torch.save( + {"refiner_state_dict": refiner.state_dict(), "stage": stage, + "step": steps, "refiner_version": REFINER_VERSION, + "config": vars(args)}, + str(output_dir / ("refiner_%s_last.pt" % stage)), + ) + print("stage %s done in %.1fs" % (stage, time.time() - started), flush=True) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--stage", choices=("pretrain", "finetune", "both"), + default="both") + parser.add_argument("--pretrain-steps", type=int, default=3000) + parser.add_argument("--finetune-steps", type=int, default=12000) + parser.add_argument("--batch-size", type=int, default=8) + parser.add_argument("--lr", type=float, default=2e-4) + parser.add_argument("--perceptual-weight", type=float, default=0.1) + parser.add_argument("--no-perceptual", action="store_true") + parser.add_argument("--eval-every", type=int, default=500) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--eval-seed", type=int, default=20260830) + parser.add_argument("--init-refiner", type=Path, default=None) + parser.add_argument("--regressor", choices=("v4", "v6"), default="v4") + parser.add_argument("--regressor-run", type=Path, default=None) + args = parser.parse_args() + + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + output_dir = args.output_dir + output_dir.mkdir(parents=True, exist_ok=True) + (output_dir / "run_config.json").write_text( + json.dumps({k: str(v) for k, v in vars(args).items()}, + indent=2, sort_keys=True) + ) + torch.manual_seed(args.seed) + + regressor, phase1, v4_args = load_frozen_regressor( + device, kind=args.regressor, run_dir=args.regressor_run + ) + splits = load_train_val_manifest(v4_args.manifest) + total_steps = args.pretrain_steps + args.finetune_steps + loaders = build_loaders(args, splits, args.batch_size, total_steps, args.seed) + + refiner = RefinerDecoder().to(device) + if args.init_refiner is not None: + state = torch.load(str(args.init_refiner), map_location="cpu") + refiner.load_state_dict(state["refiner_state_dict"], strict=True) + print("initialized refiner from", args.init_refiner, flush=True) + perceptual = None + if not args.no_perceptual: + perceptual = VGGPerceptualLoss().to(device) + + if args.stage in ("pretrain", "both"): + run_stage("pretrain", refiner, perceptual, regressor, phase1, + loaders, device, output_dir, args) + if args.stage in ("finetune", "both"): + run_stage("finetune", refiner, perceptual, regressor, phase1, + loaders, device, output_dir, args) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/visualize_degradation_table.py b/dataset/phase1_noise_20260906/trial_code_staging/visualize_degradation_table.py new file mode 100644 index 0000000000000000000000000000000000000000..69f13909756cc7cb64710a11787d26e624d68290 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/visualize_degradation_table.py @@ -0,0 +1,190 @@ +#!/usr/bin/env python3 +"""Overview table of the four degradation domains in the SCDC training data. + +One row per domain (haze / low-light / noise / rain), N deterministic samples +per row (evenly spaced over the record-id-sorted validation list — no +cherry-picking), each shown as the whole native frame: Degraded | Clean. +Cells are resized-to-cover and center-cropped to a fixed 3:2 box so frames of +different aspect ratios line up; the caption carries dataset, native size and +the degraded-vs-clean PSNR of the full frame. +""" + +from __future__ import annotations + +import argparse +import json +import math +from pathlib import Path +from typing import List, Sequence + +import numpy as np +from PIL import Image, ImageDraw, ImageFont + +from src.data.phase2_v4 import load_train_val_manifest + +DOMAIN_ORDER = ("haze", "lowlight", "noise", "rain") +DOMAIN_LABELS = { + "haze": "Haze", + "lowlight": "Low-light", + "noise": "Noise", + "rain": "Rain", +} +_LANCZOS = getattr(getattr(Image, "Resampling", Image), "LANCZOS") + + +def _select_indices(count: int, per_domain: int) -> List[int]: + if count <= per_domain: + return list(range(count)) + if per_domain == 1: + return [count // 2] + step = (count - 1) / (per_domain - 1) + return sorted({int(round(position * step)) for position in range(per_domain)}) + + +def _native_crop_at( + image: Image.Image, width: int, height: int, fx: float = 0.5, fy: float = 0.5 +) -> Image.Image: + """Native-resolution crop whose center sits at fraction (fx, fy) of the frame.""" + left = int(round(fx * (image.width - width))) + top = int(round(fy * (image.height - height))) + return image.crop((left, top, left + width, top + height)) + + +def _cover(image: Image.Image, width: int, height: int) -> Image.Image: + scale = max(width / image.width, height / image.height) + resized = image.resize( + (max(width, int(math.ceil(image.width * scale))), + max(height, int(math.ceil(image.height * scale)))), + _LANCZOS, + ) + left = (resized.width - width) // 2 + top = (resized.height - height) // 2 + return resized.crop((left, top, left + width, top + height)) + + +def _cell_view( + image: Image.Image, width: int, height: int, native_threshold: float, + anchor=(0.5, 0.5), +): + """Whole frame (resize-to-cover) unless the frame is so much larger than the + cell that fine degradations (sensor noise, thin streaks) would be averaged + away by the downscale — then show a native-resolution center crop.""" + if min(image.width / width, image.height / height) >= native_threshold: + return _native_crop_at(image, width, height, *anchor), "native crop" + return _cover(image, width, height), "full frame" + + +def _pick_diverse(records, per_domain: int): + """Evenly spaced picks, but prefer one record per scene (split_group) + when the domain has at least per_domain distinct scenes.""" + groups = {} + for record in records: + groups.setdefault(record.split_group, []).append(record) + if len(groups) < per_domain: + return [records[i] for i in _select_indices(len(records), per_domain)] + keys = sorted(groups) + return [groups[keys[i]][0] for i in _select_indices(len(keys), per_domain)] + + +def _psnr(a: Image.Image, b: Image.Image) -> float: + x = np.asarray(a, dtype=np.float64) / 255.0 + y = np.asarray(b, dtype=np.float64) / 255.0 + mse = float(np.mean((x - y) ** 2)) + return 99.0 if mse <= 0 else 10.0 * math.log10(1.0 / mse) + + +def _font(size: int) -> ImageFont.ImageFont: + for candidate in ( + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/dejavu/DejaVuSans.ttf", + "/Library/Fonts/Arial.ttf", + ): + if Path(candidate).is_file(): + return ImageFont.truetype(candidate, size) + return ImageFont.load_default() + + +def build_table( + records_by_domain, per_domain: int, cell_w: int, cell_h: int, output: Path, + native_threshold: float = 3.0, +) -> dict: + pad, gap, label_w, header_h, caption_h = 16, 6, 150, 34, 30 + grid_w = per_domain * (2 * cell_w + gap) + (per_domain - 1) * 3 * gap + width = pad + label_w + grid_w + pad + height = pad + header_h + len(DOMAIN_ORDER) * (cell_h + caption_h + gap) + pad + canvas = Image.new("RGB", (width, height), (244, 245, 246)) + draw = ImageDraw.Draw(canvas) + font_h, font_c, font_l = _font(15), _font(12), _font(17) + summary = {} + for column in range(per_domain): + x0 = pad + label_w + column * (2 * cell_w + gap + 3 * gap) + draw.text((x0 + 4, pad + 8), "Degraded", fill=(199, 93, 58), font=font_h) + draw.text((x0 + cell_w + gap + 4, pad + 8), "Clean (GT)", fill=(38, 48, 66), font=font_h) + for row, domain in enumerate(DOMAIN_ORDER): + records = records_by_domain.get(domain, []) + picked = _pick_diverse(records, per_domain) + y0 = pad + header_h + row * (cell_h + caption_h + gap) + draw.text((pad, y0 + cell_h // 2 - 10), DOMAIN_LABELS[domain], fill=(38, 48, 66), font=font_l) + draw.text((pad, y0 + cell_h // 2 + 12), "%d val pairs" % len(records), fill=(107, 114, 128), font=font_c) + rows = [] + for column, record in enumerate(picked): + degraded = Image.open(record.degraded).convert("RGB") + clean = Image.open(record.clean).convert("RGB") + psnr = _psnr(degraded, clean) + x0 = pad + label_w + column * (2 * cell_w + gap + 3 * gap) + # Slide the native-crop window across the frame per column so a + # domain with few distinct scenes still shows different content. + anchor = ((column + 1.0) / (per_domain + 1.0), 0.35 if column % 2 == 0 else 0.65) + view_d, view_kind = _cell_view(degraded, cell_w, cell_h, native_threshold, anchor) + view_c, _ = _cell_view(clean, cell_w, cell_h, native_threshold, anchor) + canvas.paste(view_d, (x0, y0)) + canvas.paste(view_c, (x0 + cell_w + gap, y0)) + caption = "%s %dx%d PSNR %.1f dB [%s]" % ( + record.dataset, degraded.width, degraded.height, psnr, view_kind + ) + draw.text((x0 + 2, y0 + cell_h + 6), caption, fill=(55, 65, 81), font=font_c) + rows.append({ + "record_id": record.record_id, "dataset": record.dataset, + "size": [degraded.width, degraded.height], "psnr_degraded": psnr, + "view": view_kind, "split_group": record.split_group, + }) + summary[domain] = rows + canvas.save(str(output)) + return summary + + +def main(argv: Sequence[str] = None) -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, default=Path("outputs/phase2_v7/uformer_dgf8k_seed42")) + parser.add_argument("--output", type=Path, default=Path("outputs/degradation_table.png")) + parser.add_argument("--per-domain", type=int, default=4) + parser.add_argument("--cell-width", type=int, default=240) + parser.add_argument("--cell-height", type=int, default=160) + parser.add_argument("--split", choices=("val", "train"), default="val") + parser.add_argument( + "--native-threshold", type=float, default=3.0, + help="show a native-res center crop when the frame is >= this many times the cell", + ) + args = parser.parse_args(argv) + + config = json.loads((args.run_dir / "run_config.json").read_text()) + splits = load_train_val_manifest(Path(config["manifest"])) + records = splits.val if args.split == "val" else splits.train + by_domain = {} + for record in records: + by_domain.setdefault(record.degradation, []).append(record) + for domain in by_domain: + by_domain[domain].sort(key=lambda r: r.record_id) + args.output.parent.mkdir(parents=True, exist_ok=True) + summary = build_table( + by_domain, args.per_domain, args.cell_width, args.cell_height, args.output, + native_threshold=args.native_threshold, + ) + (args.output.with_suffix(".json")).write_text(json.dumps(summary, indent=2)) + for domain, rows in summary.items(): + print(domain, ", ".join("%s %dx%d %.1f dB %s" % (r["dataset"], r["size"][0], r["size"][1], r["psnr_degraded"], r["view"]) for r in rows)) + print("saved", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase1_graph.py b/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase1_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..6c730ab0840c0a6665ddefc7f1948259ac3092b9 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase1_graph.py @@ -0,0 +1,380 @@ +#!/usr/bin/env python3 +"""Sanity dashboard for the Phase-1 Blind Degradation Graph Encoder. + +Answers, with pictures, whether the graph representation is *plausible* on +its own terms, independent of how many dB it buys Phase-2: + + cases_.png per image: input | routing over the 6 nodes | severity + per branch | 4 spatial maps (16x16) | unknown-residual + norm — for degraded inputs AND their clean GT + (a sane encoder must react differently to the two). + confusion.png routing argmax share: true domain (and clean GT of each + domain) x node, over the whole validation set. + severity_calibration.png + predicted severity of the true branch vs raw residual + MAE |y - x| with Spearman rho per domain (calibration-free). + severity_ramp.png monotonic synthetic ramps on clean val images (noise + sigma, haze transmission, low-light gain, rain streaks): + mean severity and routing mass of every branch vs level. + ood.png synthetic unknown degradations (snow / blur / pixelate / + sharpen, from train_graph_encoder_v2.synthesize_ood): + where does the mass go — free slots or a known branch? + summary.json every aggregate number behind the figures. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path +from typing import Dict, List, Sequence + +import numpy as np +import torch +import torch.nn.functional as F + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest + +NODES = ("rain", "noise", "haze", "lowlight", "free1", "free2") +DOMAINS = ("rain", "noise", "haze", "lowlight") +COLORS = {"rain": "#2a78d6", "noise": "#eb6834", "haze": "#1baf7a", + "lowlight": "#eda100", "free1": "#9aa3af", "free2": "#6b7280"} +LABELS = {"rain": "Rain", "noise": "Noise", "haze": "Haze", "lowlight": "Low-light", + "free1": "Free-1", "free2": "Free-2"} + + +# --------------------------------------------------------------------------- # +# inference helpers +# --------------------------------------------------------------------------- # +@torch.no_grad() +def encode(phase1, images: torch.Tensor, batch: int = 16) -> Dict[str, torch.Tensor]: + out: Dict[str, List[torch.Tensor]] = { + "routing": [], "severity": [], "spatial": [], "residual_norm": []} + for start in range(0, images.shape[0], batch): + rep = phase1(images[start:start + batch]) + out["routing"].append(rep.routing_probs.float().cpu()) + out["severity"].append(rep.severity_coords.float().cpu()) + out["spatial"].append(rep.spatial_maps.float().cpu()) + out["residual_norm"].append(rep.unknown_residual.float().norm(dim=-1).cpu()) + return {k: torch.cat(v) for k, v in out.items()} + + +def spearman(a: Sequence[float], b: Sequence[float]) -> float: + if len(a) < 3: + return float("nan") + ra = np.argsort(np.argsort(a)).astype(np.float64) + rb = np.argsort(np.argsort(b)).astype(np.float64) + ra -= ra.mean(); rb -= rb.mean() + denom = math.sqrt(float((ra ** 2).sum() * (rb ** 2).sum())) + return float((ra * rb).sum() / denom) if denom > 0 else float("nan") + + +# --------------------------------------------------------------------------- # +# synthetic ramps (simple, monotonic, physically motivated) +# --------------------------------------------------------------------------- # +def ramp_noise(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + noise = torch.randn(clean.shape, generator=gen) * level + return (clean + noise.to(clean.device)).clamp(0, 1) + + +def ramp_haze(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + transmission = 1.0 - level # level 0 -> clear, 0.75 -> dense + airlight = 0.9 + return (clean * transmission + airlight * (1.0 - transmission)).clamp(0, 1) + + +def ramp_lowlight(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + gain = 1.0 - level # level 0 -> unchanged, 0.94 -> near black + return (clean * gain).clamp(0, 1) + + +def ramp_rain(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + if level <= 0: + return clean + b, _, h, w = clean.shape + seeds = (torch.rand((b, 1, h, w), generator=gen) < 0.002 * (1 + 4 * level)).float() + kernel = torch.zeros(1, 1, 15, 15) + for i in range(15): # a slanted streak PSF + j = min(14, max(0, int(round(i * 0.35)) + 4)) + kernel[0, 0, i, j] = 1.0 + kernel = kernel / kernel.sum() + streaks = F.conv2d(seeds, kernel, padding=7) + streaks = streaks / (streaks.amax(dim=(2, 3), keepdim=True) + 1e-6) + streaks = streaks.to(clean.device) * (0.35 + 0.65 * level) + return (clean + streaks).clamp(0, 1) + + +def make_transplant_ramp(residuals: torch.Tensor): + """Real degradation residuals (degraded - clean of val pairs) added to a + clean pool with a gain: level 1 = the real residual, >1 amplified.""" + def fn(clean: torch.Tensor, level: float, gen: torch.Generator) -> torch.Tensor: + idx = torch.randint(0, residuals.shape[0], (clean.shape[0],), generator=gen) + return (clean + level * residuals[idx].to(clean.device)).clamp(0, 1) + return fn + + +RAMPS = { + "noise": (ramp_noise, [0.0, 0.01, 0.02, 0.04, 0.08, 0.12]), + "haze": (ramp_haze, [0.0, 0.15, 0.3, 0.45, 0.6, 0.75]), + "lowlight": (ramp_lowlight, [0.0, 0.3, 0.5, 0.7, 0.85, 0.94]), + "rain": (ramp_rain, [0.0, 0.2, 0.4, 0.6, 0.8, 1.0]), +} +TRANSPLANT_LEVELS = [0.0, 0.25, 0.5, 0.75, 1.0, 1.5] +RAMP_TITLES = { + "noise": "Gaussian noise (sigma)", "haze": "uniform haze (1 - t)", + "lowlight": "gain reduction", "rain": "synthetic streaks", + "noise_real": "REAL SIDD residual x gain", "rain_real": "REAL Rain13K residual x gain", +} + + +# --------------------------------------------------------------------------- # +# figures +# --------------------------------------------------------------------------- # +def _bars(ax, values: Sequence[float], names: Sequence[str], ylim=(0, 1), title=""): + pos = np.arange(len(values)) + ax.bar(pos, values, color=[COLORS[n] for n in names], width=0.7) + ax.set_xticks(pos) + ax.set_xticklabels([LABELS[n][:5] for n in names], fontsize=7) + ax.set_ylim(*ylim) + ax.tick_params(axis="y", labelsize=7) + if title: + ax.set_title(title, fontsize=8) + + +def fig_cases(plt, images, clean, enc_deg, enc_cln, ids, domain, path: Path): + n = images.shape[0] + fig, axes = plt.subplots(2 * n, 5, figsize=(15, 2.9 * 2 * n), squeeze=False) + for i in range(n): + for row, (img, enc, tag) in enumerate(( + (images[i], enc_deg, "degraded"), (clean[i], enc_cln, "clean GT"))): + r = 2 * i + row + axes[r][0].imshow(img.permute(1, 2, 0).numpy()) + axes[r][0].set_title("%s — %s" % (ids[i][:14], tag), fontsize=8) + _bars(axes[r][1], enc["routing"][i].tolist(), NODES, title="routing (softmax over 6 nodes)") + _bars(axes[r][2], enc["severity"][i].tolist(), DOMAINS, title="severity per branch") + mosaic = torch.cat([ + torch.cat([enc["spatial"][i][0], enc["spatial"][i][1]], dim=1), + torch.cat([enc["spatial"][i][2], enc["spatial"][i][3]], dim=1)], dim=0) + axes[r][3].imshow(mosaic.numpy(), vmin=0, vmax=1, cmap="magma") + maxes = enc["spatial"][i].amax(dim=(1, 2)).tolist() + axes[r][3].set_title("spatial 16x16 [rain noise / haze low]\nmax %.2f %.2f / %.2f %.2f" % tuple(maxes), fontsize=7) + top = int(enc["routing"][i].argmax()) + overlay = enc["spatial"][i][min(top, 3)] + up = F.interpolate(overlay[None, None], size=img.shape[-2:], mode="bilinear", + align_corners=False)[0, 0] + axes[r][4].imshow(img.permute(1, 2, 0).numpy()) + axes[r][4].imshow(up.numpy(), vmin=0, vmax=1, cmap="magma", alpha=0.45) + axes[r][4].set_title("map of top node (%s) |res| %.2f" % ( + LABELS[NODES[top]], float(enc["residual_norm"][i])), fontsize=8) + for c in (0, 3, 4): + axes[r][c].set_xticks(()); axes[r][c].set_yticks(()) + fig.suptitle("Phase-1 graph state — %s (val, center crops)" % LABELS[domain], fontsize=12) + fig.tight_layout(rect=(0, 0, 1, 0.98)) + fig.savefig(str(path), dpi=100) + plt.close(fig) + + +def fig_confusion(plt, matrix: np.ndarray, row_names: Sequence[str], path: Path): + fig, ax = plt.subplots(figsize=(7.5, 0.55 * len(row_names) + 1.6)) + ax.imshow(matrix, vmin=0, vmax=1, cmap="Blues", aspect="auto") + for r in range(matrix.shape[0]): + for c in range(matrix.shape[1]): + v = matrix[r, c] + ax.text(c, r, "%.2f" % v, ha="center", va="center", fontsize=8, + color="white" if v > 0.6 else "black") + ax.set_xticks(range(len(NODES))); ax.set_xticklabels([LABELS[n] for n in NODES], fontsize=8) + ax.set_yticks(range(len(row_names))); ax.set_yticklabels(row_names, fontsize=8) + ax.set_xlabel("routing argmax node", fontsize=9) + ax.set_title("Routing argmax share per input group (val)\nrows: degraded inputs, then clean GT of each domain", fontsize=10) + fig.tight_layout() + fig.savefig(str(path), dpi=110) + plt.close(fig) + + +def fig_calibration(plt, per_domain: Dict[str, Dict[str, List[float]]], path: Path): + fig, axes = plt.subplots(1, 4, figsize=(15, 3.6)) + for ax, d in zip(axes, DOMAINS): + x, y = per_domain[d]["raw_mae"], per_domain[d]["severity"] + ax.scatter(x, y, s=12, color=COLORS[d], alpha=0.75) + ax.set_title("%s rho=%.2f n=%d" % (LABELS[d], spearman(x, y), len(x)), fontsize=9) + ax.set_xlabel("raw residual MAE |y-x|", fontsize=8) + ax.set_ylabel("predicted severity (own branch)", fontsize=8) + ax.set_ylim(0, 1); ax.tick_params(labelsize=7) + fig.suptitle("Severity calibration on val (should rise with residual)", fontsize=11) + fig.tight_layout(rect=(0, 0, 1, 0.93)) + fig.savefig(str(path), dpi=110) + plt.close(fig) + + +def fig_ramp(plt, ramp: Dict[str, Dict[str, List[List[float]]]], path: Path): + keys = list(ramp.keys()) + fig, axes = plt.subplots(2, len(keys), figsize=(3.6 * len(keys), 6.2), squeeze=False) + for col, d in enumerate(keys): + levels = ramp[d]["levels"] + for j, n in enumerate(NODES): + axes[0][col].plot(range(len(levels)), [r[j] for r in ramp[d]["routing"]], + marker="o", ms=3, color=COLORS[n], label=LABELS[n]) + for j, b in enumerate(DOMAINS): + axes[1][col].plot(range(len(levels)), [s[j] for s in ramp[d]["severity"]], + marker="o", ms=3, color=COLORS[b], label=LABELS[b]) + for r, lab in ((0, "routing mass"), (1, "severity")): + axes[r][col].set_xticks(range(len(levels))) + axes[r][col].set_xticklabels(["%g" % v for v in levels], fontsize=7) + axes[r][col].set_ylim(0, 1); axes[r][col].tick_params(axis="y", labelsize=7) + axes[r][col].set_ylabel(lab, fontsize=8) + axes[0][col].set_title(RAMP_TITLES.get(d, d), fontsize=9) + axes[1][col].set_xlabel("level", fontsize=8) + axes[0][0].legend(fontsize=7, loc="upper left") + axes[1][0].legend(fontsize=7, loc="upper left") + fig.suptitle("Ramps on clean val images: the intended branch should rise alone (level 0 = clean)", fontsize=11) + fig.tight_layout(rect=(0, 0, 1, 0.94)) + fig.savefig(str(path), dpi=110) + plt.close(fig) + + +def fig_ood(plt, ood_examples, ood_mean: Dict[str, List[float]], path: Path): + kinds = list(ood_mean.keys()) + fig, axes = plt.subplots(2, len(kinds), figsize=(3.6 * len(kinds), 6.4), squeeze=False) + for c, k in enumerate(kinds): + axes[0][c].imshow(ood_examples[k].permute(1, 2, 0).numpy()) + axes[0][c].set_xticks(()); axes[0][c].set_yticks(()) + axes[0][c].set_title("OOD: %s" % k, fontsize=9) + _bars(axes[1][c], ood_mean[k], NODES, title="mean routing (n=%d)" % ood_examples["_n"]) + fig.suptitle("Unknown degradations: mass should land on the free nodes", fontsize=11) + fig.tight_layout(rect=(0, 0, 1, 0.93)) + fig.savefig(str(path), dpi=110) + plt.close(fig) + + +# --------------------------------------------------------------------------- # +def main() -> None: + import matplotlib + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", type=Path, default=Path("outputs/phase1_ll_v3/graph_encoder_best.pt")) + parser.add_argument("--manifest", type=Path, default=Path("outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json")) + parser.add_argument("--output-dir", type=Path, default=Path("outputs/phase1_vis")) + parser.add_argument("--per-domain", type=int, default=3) + parser.add_argument("--ramp-images", type=int, default=24) + parser.add_argument("--device", default="cuda") + args = parser.parse_args() + + device = torch.device(args.device) + sha = hashlib.sha256(args.checkpoint.read_bytes()).hexdigest() + phase1, _ = v4.build_frozen_phase1(args.checkpoint, sha, device) + args.output_dir.mkdir(parents=True, exist_ok=True) + + splits = load_train_val_manifest(args.manifest) + dataset = Phase2PairDataset(splits.val, crop_size=256, training=False, upscale_small=True) + by_domain: Dict[str, List[int]] = {} + for i, r in enumerate(splits.val): + by_domain.setdefault(r.degradation, []).append(i) + + summary: Dict[str, object] = {"checkpoint": str(args.checkpoint), "sha256": sha} + + # ---- whole-val pass: confusion + calibration ------------------------- # + conf_rows, conf_names = [], [] + calib: Dict[str, Dict[str, List[float]]] = {d: {"raw_mae": [], "severity": []} for d in DOMAINS} + per_domain_cache = {} + for d in DOMAINS: + idx = sorted(by_domain[d], key=lambda k: splits.val[k].record_id) + items = [dataset[k] for k in idx] + deg = torch.stack([it["degraded"] for it in items]).to(device) + cln = torch.stack([it["clean"] for it in items]).to(device) + enc_d, enc_c = encode(phase1, deg), encode(phase1, cln) + per_domain_cache[d] = (idx, items, deg.cpu(), cln.cpu(), enc_d, enc_c) + j = DOMAINS.index(d) + calib[d]["raw_mae"] = (deg - cln).abs().mean(dim=(1, 2, 3)).cpu().tolist() + calib[d]["severity"] = enc_d["severity"][:, j].tolist() + conf_rows.append(np.bincount(enc_d["routing"].argmax(1).numpy(), minlength=6) / len(idx)) + conf_names.append("%s input (n=%d)" % (LABELS[d], len(idx))) + for d in DOMAINS: + _, _, _, _, _, enc_c = per_domain_cache[d] + conf_rows.append(np.bincount(enc_c["routing"].argmax(1).numpy(), minlength=6) / enc_c["routing"].shape[0]) + conf_names.append("%s clean GT" % LABELS[d]) + matrix = np.stack(conf_rows) + fig_confusion(plt, matrix, conf_names, args.output_dir / "confusion.png") + fig_calibration(plt, calib, args.output_dir / "severity_calibration.png") + summary["confusion"] = {n: dict(zip(NODES, [float(v) for v in row])) for n, row in zip(conf_names, matrix)} + summary["severity_spearman"] = {d: spearman(calib[d]["raw_mae"], calib[d]["severity"]) for d in DOMAINS} + summary["mean_severity_own_branch"] = {d: float(np.mean(calib[d]["severity"])) for d in DOMAINS} + + # ---- per-domain case sheets ----------------------------------------- # + for d in DOMAINS: + idx, items, deg, cln, enc_d, enc_c = per_domain_cache[d] + count = len(idx) + picks = sorted({int(round(p * (count - 1) / max(1, args.per_domain - 1))) for p in range(args.per_domain)}) + sub = lambda enc: {k: v[picks] for k, v in enc.items()} + fig_cases(plt, deg[picks], cln[picks], sub(enc_d), sub(enc_c), + [items[k]["record_id"] for k in picks], d, args.output_dir / ("cases_%s.png" % d)) + + # ---- scene008 (external nearly clean) ------------------------------- # + p1_args = p1.build_parser().parse_args([]) + ext_splits = p1.build_data_splits(p1_args) + s8 = [r for r in ext_splits.locked_test if r.degradation == "noise"] + ds8 = ext.PairCropDataset(s8) + it8 = [ds8[i] for i in range(len(s8))] + deg8 = torch.stack([it["degraded"] for it in it8]).to(device) + cln8 = torch.stack([it["clean"] for it in it8]).to(device) + e8d, e8c = encode(phase1, deg8), encode(phase1, cln8) + picks8 = [0, len(s8) // 2, len(s8) - 1] + sub8 = lambda enc: {k: v[picks8] for k, v in enc.items()} + fig_cases(plt, deg8.cpu()[picks8], cln8.cpu()[picks8], sub8(e8d), sub8(e8c), + [it8[k]["record_id"] for k in picks8], "noise", args.output_dir / "cases_scene008.png") + summary["scene008"] = { + "input_routing_mean": dict(zip(NODES, e8d["routing"].mean(0).tolist())), + "clean_routing_mean": dict(zip(NODES, e8c["routing"].mean(0).tolist())), + "input_severity_mean": dict(zip(DOMAINS, e8d["severity"].mean(0).tolist())), + } + + # ---- ramps + OOD on a fixed clean pool ------------------------------ # + pool = [] + for d in DOMAINS: + _, _, _, cln, _, _ = per_domain_cache[d] + pool.append(cln[: args.ramp_images // 4]) + pool = torch.cat(pool).to(device) + ramps = dict(RAMPS) + for d in ("noise", "rain"): + _, _, deg_d, cln_d, _, _ = per_domain_cache[d] + ramps[d + "_real"] = (make_transplant_ramp(deg_d - cln_d), TRANSPLANT_LEVELS) + ramp_summary = {} + for d, (fn, levels) in ramps.items(): + routing_rows, severity_rows = [], [] + for level in levels: + gen = torch.Generator().manual_seed(1234) + enc = encode(phase1, fn(pool, level, gen)) + routing_rows.append(enc["routing"].mean(0).tolist()) + severity_rows.append(enc["severity"].mean(0).tolist()) + ramp_summary[d] = {"levels": levels, "routing": routing_rows, "severity": severity_rows} + fig_ramp(plt, ramp_summary, args.output_dir / "severity_ramp.png") + summary["ramps"] = ramp_summary + + ood_mean, ood_examples = {}, {"_n": int(pool.shape[0])} + for kind in p1.OOD_KINDS: + gen = torch.Generator().manual_seed(4321) + corrupted = p1.synthesize_ood(pool.cpu(), kind, gen).to(device) + enc = encode(phase1, corrupted) + ood_mean[kind] = enc["routing"].mean(0).tolist() + ood_examples[kind] = corrupted[0].cpu() + fig_ood(plt, ood_examples, ood_mean, args.output_dir / "ood.png") + summary["ood_routing_mean"] = {k: dict(zip(NODES, v)) for k, v in ood_mean.items()} + summary["clean_pool_routing_mean"] = dict(zip(NODES, encode(phase1, pool)["routing"].mean(0).tolist())) + + (args.output_dir / "summary.json").write_text(json.dumps(summary, indent=2)) + print("spearman", json.dumps(summary["severity_spearman"])) + print("confusion rows:") + for n, row in zip(conf_names, matrix): + print(" %-24s %s" % (n, " ".join("%.2f" % v for v in row))) + print("ood:", json.dumps({k: [round(x, 2) for x in v] for k, v in ood_mean.items()})) + print("saved to", args.output_dir) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase1_tsne.py b/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase1_tsne.py new file mode 100644 index 0000000000000000000000000000000000000000..e836ef5abcc2ad4642906f544f9f75d456e7a667 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase1_tsne.py @@ -0,0 +1,251 @@ +#!/usr/bin/env python3 +"""t-SNE / UMAP / PCA views of the Phase-1 degradation graph. + +Three panels per embedding field: + (a) coloured by group — four degraded types, their clean GTs, real OOD + (Snow100K synthetic), locked rain, SIDD scene008; + (b) coloured by the severity of the image's top node (continuous); + (c) the GRAPH itself: the per-image pre-aggregation graph vector + sum_k routing_k (anchor_k(sev_k) + token_k)/sqrt2 + free part, embedded + JOINTLY with the 4 x 8 branch anchors, the clean root and the 2 free + node embeddings, so the ordered branches and the free cluster are + visible as geometry, not just as colours. +Plus a JSON of quantitative complements (silhouette, kNN purity, +trustworthiness, severity ordering per type, free-mass AUROC), because a +t-SNE picture alone proves nothing. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np +import torch + +import eval_full_frame as ff +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 + +TYPES = ("rain", "noise", "haze", "lowlight") + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with open(path, "rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def _center(t: torch.Tensor, size: int = 256) -> torch.Tensor: + h, w = t.shape[-2:] + top, left = max((h - size) // 2, 0), max((w - size) // 2, 0) + return t[..., top:top + size, left:left + size] + + +def collect(phase1, records, name: str, per_group: int, device, which: str = "degraded"): + dataset = ff.FullFrameDataset(records[:per_group]) + rows = [] + with torch.no_grad(): + for index in range(len(dataset)): + item = dataset[index] + crop = _center(item[which]).unsqueeze(0).to(device) + rep = phase1(crop) + rows.append({ + "group": name, + "global": rep.global_condition[0].float().cpu().numpy(), + "unknown": rep.unknown_residual[0].float().cpu().numpy(), + "photo": getattr(rep, "photometric_state", torch.zeros(1, 1))[0].float().cpu().numpy(), + "tokens": rep.node_tokens[0].float().cpu().numpy(), + "routing": rep.routing_probs[0].float().cpu().numpy(), + "severity": rep.severity_coords[0].float().cpu().numpy(), + }) + return rows + + +def graph_vectors(encoder, rows): + """Per-image pre-aggregation graph vector plus the graph's own anchors.""" + branches = encoder.branches + with torch.no_grad(): + anchors = [b.anchor_embeddings[0].float().cpu().numpy() for b in branches] # 4 x [8, D] + root = encoder.clean_root().float().cpu().numpy()[0] + free = encoder.free_nodes().float().cpu().numpy() # [2, D] + vectors = [] + for r in rows: + tokens = torch.tensor(r["tokens"]) + routing = torch.tensor(r["routing"]) + sev = torch.tensor(r["severity"]) + branch_embs = torch.stack([ + branches[k].get_branch_embedding((sev[k] * branches[k].max_severity).view(1).to(branches[k].anchor_embeddings.device))[0, 0].float().cpu() + for k in range(len(branches)) + ]) + semantic = (branch_embs + tokens[: len(branches)]) / math.sqrt(2.0) + vec = (routing[: len(branches)].unsqueeze(-1) * semantic).sum(0) + vec = vec + (routing[len(branches):].unsqueeze(-1) * tokens[len(branches):]).sum(0) + vectors.append(vec.numpy()) + return np.stack(vectors), anchors, root, free + + +def embed(x: np.ndarray, method: str, seed: int = 0) -> np.ndarray: + from sklearn.decomposition import PCA + from sklearn.preprocessing import StandardScaler + + z = StandardScaler().fit_transform(x) + if method == "pca": + return PCA(n_components=2, random_state=seed).fit_transform(z) + if method == "umap": + import umap + + return umap.UMAP(n_components=2, random_state=seed, n_neighbors=30, min_dist=0.1).fit_transform(z) + from sklearn.manifold import TSNE + + perplexity = max(5, min(30, (len(z) - 1) // 3)) + return TSNE(n_components=2, perplexity=perplexity, init="pca", random_state=seed).fit_transform(z) + + +def metrics(x: np.ndarray, emb: np.ndarray, groups: list, rows: list) -> dict: + from scipy.stats import spearmanr + from sklearn.decomposition import PCA + from sklearn.manifold import trustworthiness + from sklearn.metrics import roc_auc_score, silhouette_score + from sklearn.neighbors import NearestNeighbors + + g = np.array(groups) + degraded = np.isin(g, TYPES) + out = {} + if degraded.sum() > 10 and len(set(g[degraded])) > 1: + out["silhouette_type_feature"] = float(silhouette_score(x[degraded], g[degraded])) + out["silhouette_type_embedding"] = float(silhouette_score(emb[degraded], g[degraded])) + knn = NearestNeighbors(n_neighbors=11).fit(x) + _, idx = knn.kneighbors(x) + out["knn10_purity_all_groups"] = float((g[idx[:, 1:]] == g[:, None]).mean()) + out["trustworthiness_k10"] = float(trustworthiness(x, emb, n_neighbors=10)) + free = np.array([r["routing"][len(TYPES):].sum() for r in rows]) + is_null = np.array([gg.startswith("clean") or gg == "snow_ood" for gg in groups]) + if is_null.any() and (~is_null).any(): + out["free_mass_auroc_null_vs_degraded"] = float(roc_auc_score(is_null, free)) + order = {} + for k, name in enumerate(TYPES): + mask = g == name + if mask.sum() > 10: + axis = PCA(n_components=1).fit_transform(x[mask])[:, 0] + sev = np.array([r["severity"][k] for r in rows])[mask] + rho = spearmanr(axis, sev).correlation + order[name] = float(abs(rho)) + out["severity_ordering_abs_spearman_pc1"] = order + return out + + +def plot(emb, groups, sevs, anchors2d, root2d, free2d, title, path): + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + g = np.array(groups) + palette = {"rain": "tab:blue", "noise": "tab:orange", "haze": "tab:green", "lowlight": "tab:red", + "clean_rain": "lightsteelblue", "clean_noise": "navajowhite", "clean_haze": "lightgreen", + "clean_lowlight": "lightcoral", "snow_ood": "black", "rain_locked": "royalblue", "scene008": "darkorange"} + fig, axes = plt.subplots(1, 3, figsize=(20, 6.2)) + ax = axes[0] + for name in sorted(set(groups)): + m = g == name + ax.scatter(emb[m, 0], emb[m, 1], s=9, c=palette.get(name, "grey"), label="%s (%d)" % (name, m.sum()), + alpha=0.75, marker="x" if name.startswith("clean") else ("^" if name == "snow_ood" else "o")) + ax.set_title("%s — by group" % title); ax.legend(fontsize=7, markerscale=1.6, loc="best") + ax = axes[1] + sc = ax.scatter(emb[:, 0], emb[:, 1], s=9, c=sevs, cmap="viridis", vmin=0, vmax=1) + ax.set_title("severity of the top node"); fig.colorbar(sc, ax=ax, fraction=0.04) + ax = axes[2] + for name in sorted(set(groups)): + m = g == name + ax.scatter(emb[m, 0], emb[m, 1], s=6, c=palette.get(name, "grey"), alpha=0.35) + if anchors2d is not None: + for k, name in enumerate(TYPES): + a = anchors2d[k] + ax.plot(a[:, 0], a[:, 1], "-", c=palette[name], lw=2) + ax.scatter(a[:, 0], a[:, 1], s=40, c=palette[name], edgecolors="k", zorder=5) + ax.annotate(name + " branch", a[-1], fontsize=8) + ax.scatter(root2d[0], root2d[1], s=160, marker="*", c="gold", edgecolors="k", zorder=6, label="clean root") + ax.scatter(free2d[:, 0], free2d[:, 1], s=90, marker="s", c="white", edgecolors="k", zorder=6, label="free nodes") + ax.legend(fontsize=8) + ax.set_title("graph geometry (anchors, root, free nodes)") + for a in axes: + a.set_xticks([]); a.set_yticks([]) + fig.tight_layout(); fig.savefig(path, dpi=140); plt.close(fig) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--checkpoint", type=Path, default=Path("outputs/phase1_v5f/graph_encoder_best.pt")) + parser.add_argument("--output-dir", type=Path, default=Path("outputs/phase1_tsne")) + parser.add_argument("--per-group", type=int, default=100) + parser.add_argument("--ood-count", type=int, default=200) + parser.add_argument("--methods", default="tsne,umap,pca") + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--ood-root", type=Path, default=None, + help="folder of real-unknown images (default: /Snow100K/train/all/synthetic)") + args = parser.parse_args() + device = torch.device("cuda" if torch.cuda.is_available() else "cpu") + phase1, _ = v4.build_frozen_phase1(args.checkpoint, _sha256(args.checkpoint), device) + encoder = phase1.encoder + + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + rows = [] + for name in TYPES: + recs = [r for r in splits.val if r.degradation == name] + rows += collect(phase1, recs, name, args.per_group, device, "degraded") + rows += collect(phase1, recs, "clean_" + name, args.per_group, device, "clean") + rows += collect(phase1, [r for r in splits.locked_test if r.degradation == "rain"], "rain_locked", args.per_group, device) + rows += collect(phase1, [r for r in splits.locked_test if r.degradation == "noise"], "scene008", 20, device) + ood_root = args.ood_root or Path(p1_args.data_root) / "Snow100K/train/all/synthetic" + if ood_root.is_dir(): + from src.data.folder_crops import FolderCropDataset, list_image_files + + files = list_image_files(ood_root) + step = max(len(files) // args.ood_count, 1) + ds = FolderCropDataset(files[::step][: args.ood_count], size=256, deterministic=True) + with torch.no_grad(): + for index in range(len(ds)): + rep = phase1(ds[index].unsqueeze(0).to(device)) + rows.append({"group": "snow_ood", "global": rep.global_condition[0].float().cpu().numpy(), + "unknown": rep.unknown_residual[0].float().cpu().numpy(), + "photo": getattr(rep, "photometric_state", torch.zeros(1, 1))[0].float().cpu().numpy(), + "tokens": rep.node_tokens[0].float().cpu().numpy(), + "routing": rep.routing_probs[0].float().cpu().numpy(), + "severity": rep.severity_coords[0].float().cpu().numpy()}) + groups = [r["group"] for r in rows] + sevs = np.array([r["severity"][int(np.argmax(r["routing"][:4]))] if np.argmax(r["routing"]) < 4 else 0.0 for r in rows]) + args.output_dir.mkdir(parents=True, exist_ok=True) + report = {"n": len(rows), "groups": {g: int(np.sum(np.array(groups) == g)) for g in set(groups)}} + graph_x, anchors, root, free = graph_vectors(encoder, rows) + fields = { + "global_condition": np.stack([r["global"] for r in rows]), + "unknown_residual": np.stack([r["unknown"] for r in rows]), + "graph_vector": graph_x, + } + for method in [m.strip() for m in args.methods.split(",") if m.strip()]: + for field, x in fields.items(): + if field == "graph_vector": + extra = np.concatenate([np.concatenate(anchors), root[None], free]) + joint = embed(np.concatenate([x, extra]), method, args.seed) + emb, e = joint[: len(x)], joint[len(x):] + anchors2d = [e[k * 8:(k + 1) * 8] for k in range(4)] + root2d, free2d = e[32], e[33:35] + else: + emb, anchors2d, root2d, free2d = embed(x, method, args.seed), None, None, None + path = args.output_dir / ("%s_%s.png" % (method, field)) + plot(emb, groups, sevs, anchors2d, root2d, free2d, "%s / %s" % (method, field), path) + report["%s/%s" % (method, field)] = metrics(x, emb, groups, rows) + print(method, field, json.dumps(report["%s/%s" % (method, field)]), flush=True) + (args.output_dir / "report.json").write_text(json.dumps(report, indent=2)) + print("WROTE", args.output_dir) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase2_tasks_v4.py b/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase2_tasks_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..39fbb9e82b554c9eaa1f781915ad439fba9434b8 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/visualize_phase2_tasks_v4.py @@ -0,0 +1,866 @@ +#!/usr/bin/env python3 +"""Visualize Phase-2 v4 restoration quality for every degradation task. + +The utility reproduces the validation inference path exactly: frozen Phase 1, +EMA Phase-2 weights, validation center crops, and record-keyed diffusion noise. +Samples are selected without cherry-picking by baseline-PSNR quantiles after +deduplicating clean-image content. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +from dataclasses import dataclass +from functools import wraps +from pathlib import Path +from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Sequence, Tuple + +import numpy as np +import torch +from torch import Tensor + +from src.data.phase2_v4 import ( # noqa: E402 + Phase2PairDataset, + RestorationRecord, + load_train_val_manifest, + split_digest, + validate_clean_file_integrity, + validate_splits_against_checkpoint, +) +from src.models.restoration.graph_resshift_v4 import ( # noqa: E402 + GraphConditionerV4, + GraphResidualShiftUNetV4, + ResidualShiftSchedule, +) +from train_phase2_graph_resshift_v4 import ( # noqa: E402 + Phase2RestorationModule, + build_frozen_phase1, + rgb_psnr_per_image, + rgb_ssim_per_image, + sample_restoration, + validate_phase1_artifact_header, +) + + +DISPLAY_DOMAINS: Tuple[str, ...] = ("haze", "lowlight", "noise", "rain") +DOMAIN_LABELS = { + "haze": "Haze", + "lowlight": "Low-light", + "noise": "Noise", + "rain": "Rain", +} +QUANTILES: Tuple[float, ...] = (0.25, 0.50, 0.75) +QUANTILE_LABELS = ("P25 harder", "P50 median", "P75 easier") +METHOD_LABELS = ("Degraded", "Best EMA", "Final EMA", "Ground truth") +OKABE_ITO = ("#0072B2", "#D55E00", "#009E73", "#CC79A7") + + +def _pyplot() -> Any: + """Import matplotlib lazily so data/provenance helpers stay lightweight.""" + + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as pyplot + + return pyplot + + +def _close_new_figures(function: Callable[..., Any]) -> Callable[..., Any]: + """Close figures created by a renderer even when rendering raises.""" + + @wraps(function) + def wrapped(*args: Any, **kwargs: Any) -> Any: + pyplot = _pyplot() + existing = set(pyplot.get_fignums()) + try: + return function(*args, **kwargs) + finally: + for figure_number in set(pyplot.get_fignums()) - existing: + pyplot.close(figure_number) + + return wrapped + + +@dataclass(frozen=True) +class Candidate: + """One validation record and its degraded-input difficulty.""" + + index: int + domain: str + record_id: str + source_id: str + clean_content_sha256: str + baseline_psnr: float + + +@dataclass(frozen=True) +class SelectedSample: + """A quantile-selected sample with its display role.""" + + candidate: Candidate + quantile: float + quantile_label: str + + +def sha256_file(path: Path, chunk_size: int = 1024 * 1024) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as handle: + for chunk in iter(lambda: handle.read(chunk_size), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _torch_load(path: Path) -> Dict[str, Any]: + try: + value = torch.load(str(path), map_location="cpu", weights_only=False) + except TypeError: + value = torch.load(str(path), map_location="cpu") + if not isinstance(value, dict): + raise ValueError("checkpoint root must be a dictionary") + return value + + +def validate_checkpoint_pair( + best: Mapping[str, Any], final: Mapping[str, Any] +) -> None: + """Reject weights that cannot be compared under one validation contract.""" + + for name, checkpoint in (("best", best), ("final", final)): + if checkpoint.get("schema_version") != 4 or checkpoint.get("phase") != 2: + raise ValueError("%s is not a Phase-2 v4 checkpoint" % name) + if checkpoint.get("condition_mode") != "full": + raise ValueError("%s checkpoint is not the full-conditioning arm" % name) + ema = checkpoint.get("ema_state_dict") + if not isinstance(ema, Mapping) or not isinstance(ema.get("shadow"), Mapping): + raise ValueError("%s checkpoint has no EMA shadow" % name) + immutable_keys = ( + "contract", + "architecture", + "schedule_config", + "phase1_sha256", + "phase1_metadata", + "train_digest", + "val_digest", + "init_model_hash", + ) + for key in immutable_keys: + if best.get(key) != final.get(key): + raise ValueError("checkpoint %s mismatch" % key) + if int(best.get("step", -1)) > int(final.get("step", -1)): + raise ValueError("best checkpoint cannot be newer than final checkpoint") + final_events = _evaluation_history(final) + selected_event = max(final_events, key=lambda event: float(event["macro_psnr"])) + if int(best.get("step", -1)) != int(selected_event["step"]): + raise ValueError("best checkpoint is not the macro-PSNR argmax") + best_events = _evaluation_history(best) + if int(best_events[-1]["step"]) != int(best["step"]): + raise ValueError("best checkpoint history does not end at its saved step") + if float(best_events[-1]["macro_psnr"]) != float(selected_event["macro_psnr"]): + raise ValueError("best checkpoint metric does not match final history") + + +def validate_control_checkpoint( + control: Mapping[str, Any], full: Mapping[str, Any] +) -> None: + """Pin a D0 control to the same initialization and validation contract.""" + + if control.get("schema_version") != 4 or control.get("phase") != 2: + raise ValueError("D0 control is not a Phase-2 v4 checkpoint") + if control.get("condition_mode") != "null": + raise ValueError("D0 control checkpoint must use null conditioning") + control_contract = dict(control.get("contract", {})) + full_contract = dict(full.get("contract", {})) + control_contract["condition_mode"] = "full" + if control_contract != full_contract: + raise ValueError("D0 control contract does not match D5") + immutable_keys = ( + "architecture", + "schedule_config", + "phase1_sha256", + "phase1_metadata", + "train_digest", + "val_digest", + "init_model_hash", + ) + for key in immutable_keys: + if control.get(key) != full.get(key): + raise ValueError("D0 control %s does not match D5" % key) + events = _evaluation_history(control) + if any(event.get("condition") != "null" for event in events): + raise ValueError("D0 evaluation history has a non-null condition") + if int(events[-1]["step"]) != int(control.get("step", -1)): + raise ValueError("D0 checkpoint history does not end at its saved step") + full_baseline = _evaluation_history(full)[0]["metrics"]["degraded_baseline"] + if any(event["metrics"]["degraded_baseline"] != full_baseline for event in events): + raise ValueError("D0 degraded baseline does not match D5") + + +def _deduplicate_clean_content(candidates: Sequence[Candidate]) -> List[Candidate]: + """Choose a median-severity representative for every distinct clean image.""" + + groups: Dict[str, List[Candidate]] = {} + for candidate in candidates: + groups.setdefault(candidate.clean_content_sha256, []).append(candidate) + result: List[Candidate] = [] + for clean_hash in sorted(groups): + group = groups[clean_hash] + target = float(np.median([value.baseline_psnr for value in group])) + result.append( + min( + group, + key=lambda value: ( + abs(value.baseline_psnr - target), + value.record_id, + ), + ) + ) + return result + + +def select_quantile_samples( + candidates: Sequence[Candidate], + quantiles: Sequence[float] = QUANTILES, +) -> List[SelectedSample]: + """Select unique records nearest requested PSNR quantiles deterministically.""" + + unique = _deduplicate_clean_content(candidates) + if len(unique) < len(quantiles): + raise ValueError("not enough distinct clean images for quantile selection") + values = np.asarray([item.baseline_psnr for item in unique], dtype=np.float64) + selected: List[SelectedSample] = [] + used = set() + for position, quantile in enumerate(quantiles): + if not 0.0 <= float(quantile) <= 1.0: + raise ValueError("quantiles must be in [0, 1]") + target = float(np.percentile(values, float(quantile) * 100.0)) + available = [item for item in unique if item.record_id not in used] + chosen = min( + available, + key=lambda item: ( + abs(item.baseline_psnr - target), + item.baseline_psnr, + item.record_id, + ), + ) + used.add(chosen.record_id) + label = ( + QUANTILE_LABELS[position] + if tuple(quantiles) == QUANTILES + else "P%02d" % int(round(float(quantile) * 100.0)) + ) + selected.append(SelectedSample(chosen, float(quantile), label)) + return selected + + +def _baseline_candidates( + records: Sequence[RestorationRecord], crop_size: int +) -> Tuple[List[Candidate], Dict[str, int], Dict[str, Dict[str, float]]]: + dataset = Phase2PairDataset( + records, crop_size=crop_size, training=False, upscale_small=True + ) + result: List[Candidate] = [] + counts = {domain: 0 for domain in DISPLAY_DOMAINS} + values: Dict[str, Dict[str, List[float]]] = { + domain: {"psnr": [], "ssim": []} for domain in DISPLAY_DOMAINS + } + for index, record in enumerate(records): + item = dataset[index] + degraded = item["degraded"].unsqueeze(0) + clean = item["clean"].unsqueeze(0) + psnr = float(rgb_psnr_per_image(degraded, clean).item()) + ssim = float(rgb_ssim_per_image(degraded, clean).item()) + result.append( + Candidate( + index=index, + domain=record.degradation, + record_id=record.record_id, + source_id=record.source_id, + clean_content_sha256=record.clean_content_sha256, + baseline_psnr=psnr, + ) + ) + counts[record.degradation] += 1 + values[record.degradation]["psnr"].append(psnr) + values[record.degradation]["ssim"].append(ssim) + summary = { + domain: { + metric: float(np.mean(values[domain][metric])) + for metric in ("psnr", "ssim") + } + for domain in DISPLAY_DOMAINS + } + return result, counts, summary + + +def validate_degraded_baseline( + checkpoint: Mapping[str, Any], + summary: Mapping[str, Mapping[str, float]], + counts: Mapping[str, int], + tolerance: float = 5e-5, +) -> None: + """Detect byte-level degraded-input drift through reported val metrics.""" + + expected = _evaluation_history(checkpoint)[0]["metrics"]["degraded_baseline"] + for domain in DISPLAY_DOMAINS: + expected_domain = expected["per_domain"][domain] + if int(expected_domain["count"]) != int(counts[domain]): + raise ValueError("%s validation count drift" % domain) + for metric in ("psnr", "ssim"): + if not math.isclose( + float(summary[domain][metric]), + float(expected_domain[metric]), + rel_tol=0.0, + abs_tol=float(tolerance), + ): + raise ValueError("%s degraded %s baseline drift" % (domain, metric)) + + +def _select_all_domains(candidates: Sequence[Candidate]) -> List[SelectedSample]: + selected: List[SelectedSample] = [] + for domain in DISPLAY_DOMAINS: + domain_candidates = [value for value in candidates if value.domain == domain] + if not domain_candidates: + raise ValueError("validation split has no %s samples" % domain) + selected.extend(select_quantile_samples(domain_candidates)) + return selected + + +def _load_selected_tensors( + records: Sequence[RestorationRecord], + selected: Sequence[SelectedSample], + crop_size: int, +) -> Tuple[Tensor, Tensor]: + chosen_records = [records[value.candidate.index] for value in selected] + dataset = Phase2PairDataset( + chosen_records, crop_size=crop_size, training=False, upscale_small=True + ) + items = [dataset[index] for index in range(len(dataset))] + degraded = torch.stack([item["degraded"] for item in items]) + clean = torch.stack([item["clean"] for item in items]) + return degraded, clean + + +def _build_ema_model( + checkpoint: Mapping[str, Any], device: torch.device +) -> Phase2RestorationModule: + architecture = checkpoint["architecture"] + schedule_config = checkpoint["schedule_config"] + model = Phase2RestorationModule( + GraphConditionerV4( + cond_dim=int(architecture["cond_dim"]), + stage_dims=tuple(int(value) for value in architecture["dims"]), + ), + GraphResidualShiftUNetV4( + dims=tuple(int(value) for value in architecture["dims"]), + cond_dim=int(architecture["cond_dim"]), + ), + ResidualShiftSchedule( + timesteps=int(schedule_config["timesteps"]), + eta_end=float(schedule_config["eta_end"]), + min_noise=float(schedule_config["min_noise"]), + power=float(schedule_config["power"]), + kappa=float(schedule_config["kappa"]), + ), + str(checkpoint["condition_mode"]), + ).to(device) + model.load_state_dict(checkpoint["ema_state_dict"]["shadow"], strict=True) + model.eval() + return model + + +def _restore_in_batches( + checkpoint: Mapping[str, Any], + phase1: torch.nn.Module, + degraded: Tensor, + record_ids: Sequence[str], + *, + device: torch.device, + seed: int, + batch_size: int, + amp_enabled: bool, +) -> Tensor: + model = _build_ema_model(checkpoint, device) + outputs: List[Tensor] = [] + try: + for start in range(0, degraded.shape[0], batch_size): + stop = min(start + batch_size, degraded.shape[0]) + restored = sample_restoration( + model, + phase1, + degraded[start:stop].to(device), + seed=seed, + record_ids=record_ids[start:stop], + amp_enabled=amp_enabled, + ) + outputs.append(restored.float().cpu()) + finally: + del model + if device.type == "cuda": + torch.cuda.empty_cache() + return torch.cat(outputs, dim=0) + + +def _metrics(prediction: Tensor, clean: Tensor) -> List[Dict[str, float]]: + psnr = rgb_psnr_per_image(prediction, clean).tolist() + ssim = rgb_ssim_per_image(prediction, clean).tolist() + return [ + {"psnr": float(psnr[index]), "ssim": float(ssim[index])} + for index in range(len(psnr)) + ] + + +def _image_array(tensor: Tensor) -> np.ndarray: + return tensor.detach().float().clamp(0.0, 1.0).permute(1, 2, 0).numpy() + + +def _crop_sha256(tensor: Tensor) -> str: + array = ( + tensor.detach() + .float() + .clamp(0.0, 1.0) + .mul(255.0) + .round() + .to(dtype=torch.uint8) + .contiguous() + .cpu() + .numpy() + ) + return hashlib.sha256(array.tobytes(order="C")).hexdigest() + + +def _metric_caption(metric: Optional[Mapping[str, float]]) -> str: + if metric is None: + return "" + return "PSNR %.2f dB\nSSIM %.3f" % (metric["psnr"], metric["ssim"]) + + +def _style_axes(axes: Iterable[Any]) -> None: + for axis in axes: + axis.set_xticks([]) + axis.set_yticks([]) + for spine in axis.spines.values(): + spine.set_visible(False) + + +@_close_new_figures +def _qualitative_grid( + path: Path, + title: str, + row_labels: Sequence[str], + degraded: Tensor, + best: Tensor, + final: Tensor, + clean: Tensor, + baseline_metrics: Sequence[Mapping[str, float]], + best_metrics: Sequence[Mapping[str, float]], + final_metrics: Sequence[Mapping[str, float]], + *, + dpi: int, +) -> None: + plt = _pyplot() + rows = degraded.shape[0] + fig, axes = plt.subplots(rows, 4, figsize=(10.4, 2.55 * rows), squeeze=False) + images = (degraded, best, final, clean) + metric_sets: Tuple[Sequence[Optional[Mapping[str, float]]], ...] = ( + baseline_metrics, + best_metrics, + final_metrics, + [None] * rows, + ) + for row in range(rows): + for column in range(4): + axis = axes[row][column] + axis.imshow(_image_array(images[column][row]), interpolation="nearest") + if row == 0: + axis.set_title(METHOD_LABELS[column], fontsize=10, fontweight="bold") + caption = _metric_caption(metric_sets[column][row]) + if caption: + axis.text( + 0.018, + 0.018, + caption, + transform=axis.transAxes, + ha="left", + va="bottom", + fontsize=6.5, + color="white", + bbox={ + "facecolor": "black", + "edgecolor": "none", + "alpha": 0.68, + "pad": 1.5, + }, + ) + axes[row][0].text( + -0.055, + 0.5, + row_labels[row], + transform=axes[row][0].transAxes, + rotation=90, + ha="right", + va="center", + fontsize=8, + fontweight="bold", + ) + _style_axes(axis for row_axes in axes for axis in row_axes) + fig.suptitle(title, fontsize=12, fontweight="bold", y=0.995) + fig.subplots_adjust( + left=0.075, + right=0.995, + top=0.94, + bottom=0.025, + hspace=0.10, + wspace=0.055, + ) + fig.savefig(str(path), dpi=dpi, bbox_inches="tight", facecolor="white") + plt.close(fig) + + +def _evaluation_history(checkpoint: Mapping[str, Any]) -> List[Dict[str, Any]]: + events = [ + dict(event) + for event in checkpoint.get("history", []) + if event.get("event") == "evaluation" + ] + if not events: + raise ValueError("checkpoint contains no evaluation history") + steps = [int(event["step"]) for event in events] + if steps != sorted(set(steps)): + raise ValueError("evaluation history steps must be unique and sorted") + return events + + +@_close_new_figures +def _plot_learning_dynamics( + path: Path, + final_checkpoint: Mapping[str, Any], + best_step: int, + d0_checkpoint: Optional[Mapping[str, Any]], + *, + dpi: int, +) -> None: + plt = _pyplot() + events = _evaluation_history(final_checkpoint) + steps = np.asarray([int(event["step"]) for event in events]) + fig, axes = plt.subplots(2, 2, figsize=(10.5, 7.1)) + styles = ("-", "--", "-.", ":") + markers = ("o", "s", "^", "D") + for metric_index, metric_name in enumerate(("psnr", "ssim")): + axis = axes[0][metric_index] + for index, domain in enumerate(DISPLAY_DOMAINS): + values = [ + event["metrics"]["restored"]["per_domain"][domain][metric_name] + for event in events + ] + baseline = events[0]["metrics"]["degraded_baseline"]["per_domain"][domain][metric_name] + axis.plot( + steps, + values, + color=OKABE_ITO[index], + linestyle=styles[index], + marker=markers[index], + markersize=3.5, + linewidth=1.4, + label=DOMAIN_LABELS[domain], + ) + axis.axhline(baseline, color=OKABE_ITO[index], linewidth=0.6, alpha=0.28) + axis.axvline(best_step, color="#333333", linewidth=0.9, linestyle="--") + axis.set_xlabel("Optimizer step") + axis.set_ylabel("PSNR (dB)" if metric_name == "psnr" else "SSIM") + axis.set_title("Per-task %s" % metric_name.upper(), fontweight="bold") + axis.grid(True, axis="y", linewidth=0.4, alpha=0.25) + axis.spines["top"].set_visible(False) + axis.spines["right"].set_visible(False) + axes[0][0].legend(frameon=False, fontsize=8, ncol=2) + + macro_axis = axes[1][0] + macro_axis.plot( + steps, + [float(event["macro_psnr"]) for event in events], + color="#0072B2", + marker="o", + linewidth=1.5, + markersize=3.5, + label="D5 full condition", + ) + if d0_checkpoint is not None: + d0_events = _evaluation_history(d0_checkpoint) + matched_steps = sorted(set(steps.tolist()) & {int(event["step"]) for event in d0_events}) + by_step = {int(event["step"]): event for event in d0_events} + macro_axis.plot( + matched_steps, + [float(by_step[step]["macro_psnr"]) for step in matched_steps], + color="#D55E00", + linestyle="--", + marker="s", + linewidth=1.4, + markersize=3.5, + label="D0 null condition", + ) + macro_axis.axvline(best_step, color="#333333", linewidth=0.9, linestyle="--") + macro_axis.set_xlabel("Optimizer step") + macro_axis.set_ylabel("Macro PSNR (dB)") + macro_axis.set_title("Representation utility control", fontweight="bold") + macro_axis.legend(frameon=False, fontsize=8) + macro_axis.grid(True, axis="y", linewidth=0.4, alpha=0.25) + macro_axis.spines["top"].set_visible(False) + macro_axis.spines["right"].set_visible(False) + + delta_axis = axes[1][1] + best_event = next(event for event in events if int(event["step"]) == best_step) + final_event = events[-1] + positions = np.arange(len(DISPLAY_DOMAINS), dtype=np.float64) + width = 0.34 + best_delta = [] + final_delta = [] + for domain in DISPLAY_DOMAINS: + baseline = best_event["metrics"]["degraded_baseline"]["per_domain"][domain]["psnr"] + best_delta.append(best_event["metrics"]["restored"]["per_domain"][domain]["psnr"] - baseline) + final_delta.append(final_event["metrics"]["restored"]["per_domain"][domain]["psnr"] - baseline) + delta_axis.barh(positions - width / 2.0, best_delta, height=width, color="#0072B2", label="Best") + delta_axis.barh(positions + width / 2.0, final_delta, height=width, color="#E69F00", label="Final") + delta_axis.axvline(0.0, color="#333333", linewidth=0.8) + delta_axis.set_yticks(positions) + delta_axis.set_yticklabels([DOMAIN_LABELS[domain] for domain in DISPLAY_DOMAINS]) + delta_axis.invert_yaxis() + delta_axis.set_xlabel("PSNR change vs degraded (dB)") + delta_axis.set_title("Task trade-off", fontweight="bold") + delta_axis.legend(frameon=False, fontsize=8) + delta_axis.spines["top"].set_visible(False) + delta_axis.spines["right"].set_visible(False) + delta_axis.grid(True, axis="x", linewidth=0.4, alpha=0.25) + + fig.suptitle("Phase-2 v4 learning dynamics", fontsize=12, fontweight="bold") + fig.subplots_adjust(left=0.09, right=0.98, top=0.92, bottom=0.08, hspace=0.34, wspace=0.28) + fig.savefig(str(path), dpi=dpi, bbox_inches="tight", facecolor="white") + plt.close(fig) + + +def _parse_args(argv: Optional[Sequence[str]] = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--phase1-checkpoint", type=Path, required=True) + parser.add_argument("--phase1-sha256", required=True) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--best-checkpoint", type=Path, required=True) + parser.add_argument("--final-checkpoint", type=Path, required=True) + parser.add_argument("--output-dir", type=Path, required=True) + parser.add_argument("--d0-checkpoint", type=Path) + parser.add_argument("--device", default="cuda:0") + parser.add_argument("--batch-size", type=int, default=4) + parser.add_argument("--dpi", type=int, default=300) + parser.add_argument("--no-amp", action="store_true") + return parser.parse_args(argv) + + +def run(args: argparse.Namespace) -> Dict[str, Any]: + if args.batch_size <= 0: + raise ValueError("batch-size must be positive") + if args.dpi < 72: + raise ValueError("dpi must be at least 72") + device = torch.device(args.device) + if device.type == "cuda" and not torch.cuda.is_available(): + raise RuntimeError("CUDA was requested but is unavailable") + if device.type == "cuda": + torch.cuda.set_device(0 if device.index is None else int(device.index)) + + best = _torch_load(args.best_checkpoint) + final = _torch_load(args.final_checkpoint) + validate_checkpoint_pair(best, final) + control = None + if args.d0_checkpoint is not None: + control = _torch_load(args.d0_checkpoint) + validate_control_checkpoint(control, final) + if str(best["phase1_sha256"]) != str(args.phase1_sha256): + raise ValueError("Phase-1 SHA does not match the Phase-2 checkpoints") + + splits = load_train_val_manifest(args.manifest) + phase1_header = validate_phase1_artifact_header( + args.phase1_checkpoint, args.phase1_sha256 + ) + validate_splits_against_checkpoint(splits, phase1_header) + if split_digest(splits.train) != best["train_digest"]: + raise ValueError("training split digest does not match checkpoint") + if split_digest(splits.val) != best["val_digest"]: + raise ValueError("validation split digest does not match checkpoint") + validate_clean_file_integrity(splits) + + data_plan = best["contract"]["data_plan"] + crop_size = int(data_plan["crop_size"]) + eval_seed = int(data_plan["eval_seed"]) + candidates, val_counts, baseline_summary = _baseline_candidates( + splits.val, crop_size + ) + validate_degraded_baseline(final, baseline_summary, val_counts) + selected = _select_all_domains(candidates) + degraded, clean = _load_selected_tensors(splits.val, selected, crop_size) + record_ids = [value.candidate.record_id for value in selected] + + phase1, phase1_metadata = build_frozen_phase1( + args.phase1_checkpoint, args.phase1_sha256, device + ) + if phase1_metadata != best["phase1_metadata"]: + raise ValueError("Phase-1 metadata does not match Phase-2 checkpoint") + amp_enabled = device.type == "cuda" and not args.no_amp + best_images = _restore_in_batches( + best, + phase1, + degraded, + record_ids, + device=device, + seed=eval_seed, + batch_size=args.batch_size, + amp_enabled=amp_enabled, + ) + final_images = _restore_in_batches( + final, + phase1, + degraded, + record_ids, + device=device, + seed=eval_seed, + batch_size=args.batch_size, + amp_enabled=amp_enabled, + ) + + baseline_metrics = _metrics(degraded, clean) + best_metrics = _metrics(best_images, clean) + final_metrics = _metrics(final_images, clean) + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + artifacts: List[str] = [] + + for domain_index, domain in enumerate(DISPLAY_DOMAINS): + start = domain_index * len(QUANTILES) + stop = start + len(QUANTILES) + path = output_dir / ("task_%s.png" % domain) + row_labels = [ + "%s\n%s" % (selected[index].quantile_label, selected[index].candidate.source_id) + for index in range(start, stop) + ] + _qualitative_grid( + path, + "%s restoration: validation difficulty quantiles" % DOMAIN_LABELS[domain], + row_labels, + degraded[start:stop], + best_images[start:stop], + final_images[start:stop], + clean[start:stop], + baseline_metrics[start:stop], + best_metrics[start:stop], + final_metrics[start:stop], + dpi=args.dpi, + ) + artifacts.append(path.name) + + median_indices = [domain_index * 3 + 1 for domain_index in range(4)] + overview_path = output_dir / "overview_all_tasks.png" + _qualitative_grid( + overview_path, + "Phase-2 v4 restoration across degradation tasks", + [DOMAIN_LABELS[domain] for domain in DISPLAY_DOMAINS], + degraded[median_indices], + best_images[median_indices], + final_images[median_indices], + clean[median_indices], + [baseline_metrics[index] for index in median_indices], + [best_metrics[index] for index in median_indices], + [final_metrics[index] for index in median_indices], + dpi=args.dpi, + ) + artifacts.insert(0, overview_path.name) + + dynamics_path = output_dir / "learning_dynamics.png" + _plot_learning_dynamics( + dynamics_path, + final, + int(best["step"]), + control, + dpi=args.dpi, + ) + artifacts.append(dynamics_path.name) + + train_counts = {domain: 0 for domain in DISPLAY_DOMAINS} + for record in splits.train: + train_counts[record.degradation] += 1 + sample_payload = [] + for index, value in enumerate(selected): + record = splits.val[value.candidate.index] + sample_payload.append( + { + "domain": value.candidate.domain, + "quantile": value.quantile, + "quantile_label": value.quantile_label, + "record_id": value.candidate.record_id, + "source_id": value.candidate.source_id, + "clean_content_sha256": value.candidate.clean_content_sha256, + "degraded_path": str(record.degraded), + "degraded_file_sha256": sha256_file(record.degraded), + "degraded_crop_sha256": _crop_sha256(degraded[index]), + "baseline": baseline_metrics[index], + "best": best_metrics[index], + "final": final_metrics[index], + } + ) + report = { + "schema_version": 1, + "selection": { + "method": "clean-content-deduplicated baseline-PSNR quantiles", + "quantiles": list(QUANTILES), + "crop_size": crop_size, + "validation_only": True, + }, + "inference": { + "weights": "ema_state_dict.shadow", + "eval_seed": eval_seed, + "record_keyed_noise": True, + "amp_enabled": amp_enabled, + "device": str(device), + }, + "provenance": { + "phase1_checkpoint": str(args.phase1_checkpoint), + "phase1_sha256": sha256_file(args.phase1_checkpoint), + "manifest": str(args.manifest), + "manifest_sha256": sha256_file(args.manifest), + "train_digest": best["train_digest"], + "val_digest": best["val_digest"], + "best_checkpoint": str(args.best_checkpoint), + "best_checkpoint_sha256": sha256_file(args.best_checkpoint), + "best_step": int(best["step"]), + "final_checkpoint": str(args.final_checkpoint), + "final_checkpoint_sha256": sha256_file(args.final_checkpoint), + "final_step": int(final["step"]), + }, + "data_counts": { + "train": train_counts, + "validation": val_counts, + "quarantined_rain_pairs": int(splits.quarantine_count), + }, + "samples": sample_payload, + "artifacts": artifacts, + } + if control is not None: + report["provenance"].update( + { + "d0_control_checkpoint": str(args.d0_checkpoint), + "d0_control_checkpoint_sha256": sha256_file(args.d0_checkpoint), + "d0_control_step": int(control["step"]), + } + ) + report_path = output_dir / "visualization_report.json" + report_path.write_text( + json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + print(json.dumps(report, sort_keys=True)) + return report + + +def main(argv: Optional[Sequence[str]] = None) -> None: + run(_parse_args(argv)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/visualize_scene008.py b/dataset/phase1_noise_20260906/trial_code_staging/visualize_scene008.py new file mode 100644 index 0000000000000000000000000000000000000000..b1b344e2533c7fcdd84d9b3264c0a4291f97cf80 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/visualize_scene008.py @@ -0,0 +1,73 @@ +#!/usr/bin/env python3 +"""Qualitative look at the external nearly-clean set (noise scene008). + +Rows: three locked scene008 records; columns: input, DGF at dose 1, DGF at +dose 0, ground truth, with PSNR/SSIM against GT in each caption. +""" + +from __future__ import annotations + +import argparse +from pathlib import Path + +import torch + +import eval_pipeline_external as ext +import train_graph_encoder_v2 as p1 +import train_phase2_graph_resshift_v4 as v4 +from eval_v7_external import V7Pipeline + + +def main() -> None: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--run-dir", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--count", type=int, default=3) + args = parser.parse_args() + + device = torch.device("cuda") + pipe = V7Pipeline(args.run_dir, device) + p1_args = p1.build_parser().parse_args([]) + splits = p1.build_data_splits(p1_args) + records = [r for r in splits.locked_test if r.degradation == "noise"] + step = max(1, len(records) // args.count) + picked = records[::step][: args.count] + dataset = ext.PairCropDataset(picked) + items = [dataset[i] for i in range(len(picked))] + degraded = torch.stack([it["degraded"] for it in items]).to(device) + clean = torch.stack([it["clean"] for it in items]).to(device) + ids = [it["record_id"] for it in items] + full = (torch.stack([it["full_degraded"] for it in items]).to(device) + if "full_degraded" in items[0] else None) + outs = {} + with torch.no_grad(): + for label, dose in (("dose 1", None), ("dose 0", 0.0)): + pipe.dose = dose + outs[label] = pipe.restore(degraded, record_ids=ids, full_degraded=full)["restored"] + cols = [("Input", degraded)] + [(k, v) for k, v in outs.items()] + [("Ground truth", clean)] + fig, axes = plt.subplots(len(picked), len(cols), figsize=(3.4 * len(cols), 3.5 * len(picked)), squeeze=False) + for r in range(len(picked)): + for c, (title, tensor) in enumerate(cols): + ax = axes[r][c] + ax.imshow(tensor[r].clamp(0, 1).permute(1, 2, 0).cpu().numpy()) + ax.set_xticks(()); ax.set_yticks(()) + cap = title + if title != "Ground truth": + psnr = float(v4.rgb_psnr_per_image(tensor[r:r+1], clean[r:r+1])[0]) + ssim = float(v4.rgb_ssim_per_image(tensor[r:r+1], clean[r:r+1])[0]) + cap = "%s\nPSNR %.2f / SSIM %.3f" % (title, psnr, ssim) + ax.set_title(cap, fontsize=9) + axes[r][0].set_ylabel(ids[r][:22], fontsize=7) + fig.suptitle("scene008 (external, nearly clean) — %s" % args.run_dir.name, fontsize=12) + fig.tight_layout(rect=(0, 0, 1, 0.96)) + fig.savefig(str(args.output), dpi=110) + print("saved", args.output) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/visualize_v7_uformer.py b/dataset/phase1_noise_20260906/trial_code_staging/visualize_v7_uformer.py new file mode 100644 index 0000000000000000000000000000000000000000..2870d3c47b026e97e1ecb0ddaf5ca28f432b8a53 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/visualize_v7_uformer.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Qualitative grids for the v7-Uformer unified two-step checkpoint. + +Rebuilds the exact training/eval stack from the run's own ``run_config.json`` +and ``best.pt`` (EMA weights, 2-step exact-posterior sampling), then renders +per-domain Degraded | Restored | Ground-truth grids on validation center +crops. Samples are picked deterministically (first / middle / last of the +record-id-sorted validation list per domain) — no cherry-picking. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any, Dict, List, Optional, Sequence + +import torch + +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_graph_moe_v6 as v6 +import train_phase2_unified_v7 as v7 +from src.data.phase2_v4 import Phase2PairDataset, load_train_val_manifest + +DOMAIN_LABELS = { + "haze": "Haze", + "lowlight": "Low-light", + "noise": "Noise", + "rain": "Rain", +} + + +def _load_run_args(run_dir: Path) -> argparse.Namespace: + raw = json.loads((run_dir / "run_config.json").read_text()) + for key in ("manifest", "phase1_checkpoint", "data_root", "output_dir"): + if raw.get(key) is not None: + raw[key] = Path(raw[key]) + return argparse.Namespace(**raw) + + +def _select_indices(count: int, per_domain: int) -> List[int]: + if count <= per_domain: + return list(range(count)) + if per_domain == 1: + return [count // 2] + step = (count - 1) / (per_domain - 1) + return sorted({int(round(position * step)) for position in range(per_domain)}) + + +def _grid( + domain: str, + rows: Sequence[Dict[str, Any]], + output_path: Path, + checkpoint_step: int, +) -> None: + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + figure, axes = plt.subplots( + len(rows), 3, figsize=(10.5, 3.6 * len(rows)), squeeze=False + ) + for row_index, row in enumerate(rows): + panels = ( + ("Degraded", row["degraded"], row["psnr_degraded"], row["ssim_degraded"]), + ("v7-Uformer", row["restored"], row["psnr_restored"], row["ssim_restored"]), + ("Ground truth", row["clean"], None, None), + ) + for column_index, (title, image, psnr, ssim) in enumerate(panels): + axis = axes[row_index][column_index] + axis.imshow(image.permute(1, 2, 0).numpy()) + axis.set_xticks(()) + axis.set_yticks(()) + caption = title + if psnr is not None: + caption = "%s\nPSNR %.2f / SSIM %.3f" % (title, psnr, ssim) + axis.set_title(caption, fontsize=10) + axes[row_index][0].set_ylabel(row["record_id"][:28], fontsize=8) + figure.suptitle( + "%s — v7-Uformer EMA @ step %d (2-step exact posterior)" + % (DOMAIN_LABELS.get(domain, domain), checkpoint_step), + fontsize=13, + ) + figure.tight_layout(rect=(0, 0, 1, 0.97)) + figure.savefig(str(output_path), dpi=110) + plt.close(figure) + + +def run(argv: Optional[Sequence[str]] = None) -> Dict[str, Any]: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--run-dir", type=Path, default=Path("outputs/phase2_v7/uformer_seed42") + ) + parser.add_argument("--output-dir", type=Path, default=None) + parser.add_argument("--per-domain", type=int, default=3) + parser.add_argument("--device", default="cuda") + args = parser.parse_args(argv) + + run_args = _load_run_args(args.run_dir) + device = torch.device(args.device) + output_dir = args.output_dir or (args.run_dir / "vis") + output_dir.mkdir(parents=True, exist_ok=True) + + checkpoint = v4._torch_load(args.run_dir / "best.pt", map_location="cpu") + checkpoint_step = int(checkpoint["step"]) + + model = v7._build_v7_restorer(run_args, device) + model.load_state_dict(checkpoint["ema_state_dict"]["shadow"], strict=True) + model.eval() + phase1, _ = v4.build_frozen_phase1( + run_args.phase1_checkpoint, run_args.phase1_sha256, device + ) + + splits = load_train_val_manifest(run_args.manifest) + dataset = Phase2PairDataset( + splits.val, crop_size=run_args.crop_size, training=False, upscale_small=True + ) + by_domain: Dict[str, List[int]] = {} + for index, record in enumerate(splits.val): + by_domain.setdefault(record.degradation, []).append(index) + + summary: Dict[str, Any] = {"checkpoint_step": checkpoint_step, "domains": {}} + for domain in sorted(by_domain): + ordered = sorted( + by_domain[domain], key=lambda position: splits.val[position].record_id + ) + picked = [ordered[i] for i in _select_indices(len(ordered), args.per_domain)] + items = [dataset[index] for index in picked] + degraded = torch.stack([item["degraded"] for item in items]).to(device) + clean = torch.stack([item["clean"] for item in items]).to(device) + full = torch.stack([item["full_degraded"] for item in items]).to(device) if "full_degraded" in items[0] else None + record_ids = [item["record_id"] for item in items] + with torch.no_grad(): + restored = v7.sample_unified_restoration( + model, phase1, degraded, + seed=run_args.eval_seed, record_ids=record_ids, + full_degraded=full, + ) + psnr_restored = v4.rgb_psnr_per_image(restored, clean) + ssim_restored = v4.rgb_ssim_per_image(restored, clean) + psnr_degraded = v4.rgb_psnr_per_image(degraded, clean) + ssim_degraded = v4.rgb_ssim_per_image(degraded, clean) + rows = [ + { + "record_id": record_ids[i], + "degraded": degraded[i].float().cpu(), + "restored": restored[i].float().cpu(), + "clean": clean[i].float().cpu(), + "psnr_degraded": float(psnr_degraded[i]), + "ssim_degraded": float(ssim_degraded[i]), + "psnr_restored": float(psnr_restored[i]), + "ssim_restored": float(ssim_restored[i]), + } + for i in range(len(record_ids)) + ] + output_path = output_dir / ("v7_uformer_%s.png" % domain) + _grid(domain, rows, output_path, checkpoint_step) + summary["domains"][domain] = [ + { + "record_id": row["record_id"], + "psnr_degraded": row["psnr_degraded"], + "psnr_restored": row["psnr_restored"], + "ssim_degraded": row["ssim_degraded"], + "ssim_restored": row["ssim_restored"], + } + for row in rows + ] + print( + "%s: %s" % ( + domain, + ", ".join( + "%s %.2f->%.2f dB" % ( + row["record_id"][:20], + row["psnr_degraded"], + row["psnr_restored"], + ) + for row in rows + ), + ) + ) + (output_dir / "summary.json").write_text(json.dumps(summary, indent=2)) + print("saved to %s" % output_dir) + return summary + + +if __name__ == "__main__": + run()