diff --git a/dataset/phase1_noise_20260906/code/.gitignore b/dataset/phase1_noise_20260906/code/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5414edcbc3204e42081ec255ae3dc1c0728c3085 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/.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/code/ddp_nccl_sanity.py b/dataset/phase1_noise_20260906/code/ddp_nccl_sanity.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc4ee037c6c05714bdfc82b99fe2fc64e0ba4af --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/make_clean_pools.py b/dataset/phase1_noise_20260906/code/make_clean_pools.py new file mode 100644 index 0000000000000000000000000000000000000000..48e5d88e75103f8e85817098ad2ce5fa8f9ba612 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/probe_global_knob.py b/dataset/phase1_noise_20260906/code/probe_global_knob.py new file mode 100644 index 0000000000000000000000000000000000000000..14ea0e5c5db9b1474e6fa20af7302d92584b6a18 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/probe_tone_oracle.py b/dataset/phase1_noise_20260906/code/probe_tone_oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..ab3b7cf4102ba0982c1d607ea42eb71b306caf47 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/probe_v7_taps.py b/dataset/phase1_noise_20260906/code/probe_v7_taps.py new file mode 100644 index 0000000000000000000000000000000000000000..8d640a715e063388c29d691480fe88f47fe263b2 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/relocate_manifest.py b/dataset/phase1_noise_20260906/code/relocate_manifest.py new file mode 100644 index 0000000000000000000000000000000000000000..e369216bfcc67fdf83f0c6d6f012943efbba57ec --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/run_phase1_v5f.sh b/dataset/phase1_noise_20260906/code/run_phase1_v5f.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd6522742c4ec415bfb1e7394aa7e86643fb58a1 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/run_uformer_v9a.sh b/dataset/phase1_noise_20260906/code/run_uformer_v9a.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a1abf65d6eeec585fd790762d66f980dbba1b74 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/run_uformer_v9a15k.sh b/dataset/phase1_noise_20260906/code/run_uformer_v9a15k.sh new file mode 100644 index 0000000000000000000000000000000000000000..5168c1589e716651b07dd188d30029b1fe453c7a --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/sweep_v7_dose.py b/dataset/phase1_noise_20260906/code/sweep_v7_dose.py new file mode 100644 index 0000000000000000000000000000000000000000..741394158b134603c50babcb5339b522cf14179f --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/code/visualize_phase1_tsne.py b/dataset/phase1_noise_20260906/code/visualize_phase1_tsne.py new file mode 100644 index 0000000000000000000000000000000000000000..e836ef5abcc2ad4642906f544f9f75d456e7a667 --- /dev/null +++ b/dataset/phase1_noise_20260906/code/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/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/.gitattributes b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..bdb0cabc87cf50106df6e15097dff816c8c3eb34 --- /dev/null +++ b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/.gitattributes @@ -0,0 +1,17 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/.gitignore b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..cd2946ad76b4402e5b3cab9243a9281aad228670 --- /dev/null +++ b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/.gitignore @@ -0,0 +1,47 @@ +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# ========================= +# Operating System Files +# ========================= + +# OSX +# ========================= + +.DS_Store +.AppleDouble +.LSOverride + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/ChangeLog.txt b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/ChangeLog.txt new file mode 100644 index 0000000000000000000000000000000000000000..7f18196e26ce8d761f237670d1bfb57a9c09a3d4 --- /dev/null +++ b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/ChangeLog.txt @@ -0,0 +1,2 @@ +07 Apr. 2018 - 1.0 +- Initial release \ No newline at end of file diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_bicycle_8_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_bicycle_8_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..9f175e38c0985808fcaaf47c1c950101e9051d28 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_bicycle_8_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_bicycle_8_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_bicycle_8_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..dbab706b6e8a450b805c9b43a82048eddc95461d Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_bicycle_8_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_4_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_4_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..8d9a306d0bec483ceb7c7e3624eddb808ba5cddd Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_4_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_5_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_5_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..2ab183360f1c96b9a85ddf8a01e5386ad30a5ee3 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_5_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_5_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_5_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..2dac026915882ed20ea5b893d60603b0694ce303 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_5_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_7_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_7_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..9a8f51d186e771707d605f03b76260823703732b Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_desk_7_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_2_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_2_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..ad25d1a4eed9b4fe605e800d529d05b3a8c67a1a Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_2_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_2_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_2_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..c1e4517126574910770d4e0e556bca0a76cfbda0 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_2_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_4_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_4_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..7f0a556d66e22a1bcca2deaa303d76b4207b7e68 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_4_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_4_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_4_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..7aa3a7d77aab95b222ea52428f495d19177a0ab3 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_160_6400_reciever_4_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_1_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_1_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..f64f1a7390659531b48e16d35a64b9375940b505 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_1_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_1_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_1_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..ff1d86b7a6c4b2d7f30260e158efe87a519ac0ee Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_1_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_3_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_3_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..12c632a227c4d61898a9bcfe1e8546a043d272c6 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon5D2_5_200_3200_toy_3_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_10_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_10_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..ce671c87f65e6d317f84daff633d3f19bd6daf5d Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_10_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_11_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_11_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..bb4bb873ed296f7fc659e7e433822001a5eae1f5 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_11_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_12_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_12_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..fc004f56c9edf4ec2d0318b3c60a99f00b536dac Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_3-5_125_1600_waterhouse_12_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_13_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_13_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..80d968bbfc79a16daa4ad7e24f784376ac2a98a3 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_13_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_16_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_16_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..3bb16acfa68f67d84b5b9416bf928a56ac85b055 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_16_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_3_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_3_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..47dd1e78d9d6804128d2acaf243a3d1e0be1ab33 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon600D_4-5_125_1600_toy_3_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_12800_printer_11_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_12800_printer_11_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..c869c4ba5fd635c9a55352dbe5947ba8a9bca152 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_12800_printer_11_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_3200_ball_2_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_3200_ball_2_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..27dd3a61cd8dd1c2cdec052c8c7fd049051d6979 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_3200_ball_2_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_3200_ball_6_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_3200_ball_6_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..2e1cea062fab2945ddea07fc4e62e99b9cd0d56c Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_3200_ball_6_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_800_GO_11_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_800_GO_11_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..f25fecb764c557e644d4a6f5d08edc7c814b315d Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Canon80D_8_8_800_GO_11_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_11_160_3200_classroom_15_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_11_160_3200_classroom_15_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..98101f1dca4bf0a1d22b96134dd22e68feeb20d8 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_11_160_3200_classroom_15_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_11_160_3200_classroom_4_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_11_160_3200_classroom_4_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..bc27107fe9a6e164937647519a40b70c92e1eb16 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_11_160_3200_classroom_4_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_15_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_15_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..fec312cb72a6d498ba794b604a7535acd57c3c5c Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_15_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_5_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_5_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..b34083f1c73b53b379415859ae7cc6f02b8c7491 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_5_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_9_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_9_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..be6e296b55eff12f5b6bdc3f749876f7b5a31e84 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_4-5_160_1800_classroom_9_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_2_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_2_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..87e9921526dfae66c03b4ef1fdd31a612f91333a Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_2_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_2_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_2_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..45ddf96f596d0d6d97732c5e060b57cb62453ceb Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_2_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_9_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_9_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..a7ddadccf7df90644973ec078bedc27ea18a1aa3 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5-6_160_6400_wall_9_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_100_4000_flower_15_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_100_4000_flower_15_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..6fb78f079286aa1c05e270305a8f133dadf791b9 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_100_4000_flower_15_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_100_4000_flower_2_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_100_4000_flower_2_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..e32d73d5bd3d6e3f714490ad6a50743e2b1b7398 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_100_4000_flower_2_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_125_6400_stair_7_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_125_6400_stair_7_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..40bbbd1625e4a005fedbf06af168a7895308cd6c Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_5_125_6400_stair_7_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant_1_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant_1_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..126ee123a26b41887844c94221ac4a5e56a352dc Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant_1_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant_6_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant_6_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..fc4441375ce7edf196ec22b908a3a2f24de8eabc Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant_6_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant__4_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant__4_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..1f0ed73f4a15b8574240699a3804caa98eb3eef5 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant__4_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant__4_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant__4_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..4180b840bd0236c1c41cc4407eed55bfd3670f89 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_6-3_125_5000_plant__4_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_3_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_3_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..3c0387ce6560e75f9560d67967bd79096cd9c3ca Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_3_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_5_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_5_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..bcc7d0adec131ef1572fa7723972ec8fec8c439f Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_5_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_7_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_7_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..ede189f42a7df2eefcced602db62c8139c5e3be7 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_7_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_8_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_8_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..88a27d609757175a89808d708043b509d0e92a55 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_8_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_8_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_8_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..757cc3ca7eeace47ef06a60a0fd9f0ad30317ccc Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_100_6400_bulletin_8_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_125_6400_photo_19_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_125_6400_photo_19_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..6b51de3372f5df65a3d721ac99dadf04d19bc6ad Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/NikonD800_8_125_6400_photo_19_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_13_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_13_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..1c8c2522a6764ad4d343da0cb9f1627b7164176e Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_13_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_14_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_14_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..60d5408c066a0fc41fff18ba0ac59c94709ea00d Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_14_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_14_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_14_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..de3b1aefdbdb7fb89f7010914537ee069a5c58b9 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_3-5_200_1600_classroom_14_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_1600_toy_10_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_1600_toy_10_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..8f8e680a9c120438aafcbd3bcb1093253461e8de Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_1600_toy_10_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_1600_toy_10_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_1600_toy_10_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..a031c3cc200fee3160a08fa661be9d5f51df1202 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_1600_toy_10_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_3200_plant_14_real.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_3200_plant_14_real.JPG new file mode 100644 index 0000000000000000000000000000000000000000..29e85b5cc781ef5841f4a9000762acb8ac180db6 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_3200_plant_14_real.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_6400_waterhouse_10_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_6400_waterhouse_10_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..fc72e1acce65c6330c4a9222c28f63eb819d47a6 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4-5_125_6400_waterhouse_10_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4_200_3200_door_10_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4_200_3200_door_10_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..d506e711d73216b26de69e724b50e75b18471a51 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4_200_3200_door_10_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4_200_3200_door_11_mean.JPG b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4_200_3200_door_11_mean.JPG new file mode 100644 index 0000000000000000000000000000000000000000..6b21e37137904ee61e24bea2ea55215dec6459c1 Binary files /dev/null and b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/CroppedImages/Sony_4_200_3200_door_11_mean.JPG differ diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/License.txt b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/License.txt new file mode 100644 index 0000000000000000000000000000000000000000..74f2d9d013a92cf91c060ef623e30a905ecf0375 --- /dev/null +++ b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/License.txt @@ -0,0 +1,27 @@ +Copyright (c) 2018,The Hong Kong Polytechnic University +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. + +3. Any redistribution, use, or modification is done solely for non-commercial + purposes. Examples of non-commercial uses are teaching, academic research, + public demonstrations and personal experimentation. + +%--------------------------------------------------------------------------------------------- +% Permission to use, copy, or modify this software and its documentation for +% educational and research purposes only and without fee is hereby granted, +% provided that this copyright notice and the original authors' names appear +% on all copies and supporting documentation. This program shall not be used, +% rewritten, or adapted as the basis of a commercial software or hardware +% product without first obtaining permission of the authors. The authors make +% no representations about the suitability of this software for any purpose. It is +% provided "as is" without express or implied warranty. +%--------------------------------------------------------------------------------------------- diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/Readme.txt b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/Readme.txt new file mode 100644 index 0000000000000000000000000000000000000000..7ffda8b3310cb0747f2643a0e75b15ad46e804c4 --- /dev/null +++ b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/Readme.txt @@ -0,0 +1,130 @@ +% =============================================================== +The dataset in this package provides the real-world noisy images +as described in the following paper: + + Jun Xu, Hui Li, Zhetong Liang, David Zhang, and Lei Zhang + Real-world Noisy Image Denoising: A New Benchmark + https://arxiv.org/abs/1804.02603, 2018. + + Please cite the paper if you are using this dataset in your research. + Please see the file License.txt for the license governing this code. + + Version: 1.1 (02/05/2019), see ChangeLog.txt + Contact: Jun Xu +% =============================================================== + +Note +--------------- +For more shots of training and test real-world noisy images, please refer to +1. (Multiple Folders) https://pan.baidu.com/s/1539s_gNN8zvDYxG-DbiDuA (code: gy9b). +2. (One Zip File) https://pan.baidu.com/s/1uK8XTFdD8xReMa5cs_NPLg. +3. (Google Drive) https://drive.google.com/file/d/1tzNY-WTk3HRI8MiixDp1-Es1k55VgRKS/view?usp=sharing + + +Overview +--------------- +This dataset contains 40 different scenes captured by 5 cameras from the 3 leading brands of cameras: +1) Canon EOS (5D Mark II, 80D, 600D); +2) Nikon (D800); +3) Sony (A7 II). + +We crop 100 regions of 512X512 from these 40 scenes: + The *Real.JPG are noisy images; + The *mean.JPG are "ground truth" images. + +Dataset Details +--------------- +Camera 1: Canon EOS 5D Mark II +Image Name Size Aperture Shutter Speed ISO Value +Canon5D2_bag 2784 x 1856 f/5 1/200s 6400 +Canon5D2_bicyc 2784 x 1856 f/5 1/160s 6400 +Canon5D2_chair 2784 x 1856 f/5 1/160s 3200 +Canon5D2_circu 2784 x 1856 f/5 1/160s 6400 +Canon5D2_desk 2784 x 1856 f/5 1/160s 6400 +Canon5D2_fruit 2784 x 1856 f/5 1/200s 3200 +Canon5D2_mouse 2784 x 1856 f/5 1/160s 3200 +Canon5D2_plug 2784 x 1856 f/5 1/160s 3200 +Canon5D2_recie 2784 x 1856 f/5 1/160s 6400 +Canon5D2_robot 2784 x 1856 f/5 1/160s 3200 +Canon5D2_toy 2784 x 1856 f/5 1/200s 3200 + + +Camera 2: Canon EOS 80D +Image Name Size Aperture Shutter Speed ISO Value +Canon80D_ball 2976 x 1680 f/8 1/8s 3200 +Canon80D_compr 2976 x 1680 f/8 1/8s 6400 +Canon80D_corne 2976 x 1680 f/8 1/8s 1600 +Canon80D_GO 2976 x 1680 f/8 1/8s 800 +Canon80D_print 2976 x 1680 f/8 1/8s 12800 + + +Camera 3: Canon EOS 600D +Image Name Size Aperture Shutter Speed ISO Value +Canon600_book 5184 x 3456 f/4.5 1/125s 1600 +Canon600_toy 5184 x 3456 f/4.5 1/125s 1600 +Canon600_water 5184 x 3456 f/3.5 1/125s 1600 + + +Camera 4: NIKON D800 +Image Name Size Aperture Shutter Speed ISO Value +Nikon800_bulle 3680 x 2456 f/8 1/100s 6400 +Nikon800_carbi 3680 x 2456 f/8 1/125s 4000 +Nikon800_class 3680 x 2456 f/4.5 1/160s 1600 +Nikon800_desch 3680 x 2456 f/11 1/160s 3200 +Nikon800_desk 3680 x 2456 f/4.5 1/160s 3200 +Nikon800_door 3680 x 2456 f/5.6 1/160s 6400 +Nikon800_flowe 3680 x 2456 f/5 1/100s 4000 +Nikon800_map 3680 x 2456 f/5 1/100s 4000 +Nikon800_photo 3680 x 2456 f/8 1/125s 6400 +Nikon800_plant 3680 x 2456 f/6.3 1/125s 5000 +Nikon800_plaso 3680 x 2456 f/10 1/100s 6400 +Nikon800_stair 3680 x 2456 f/5 1/125s 6400 +Nikon800_wall 3680 x 2456 f/5 1/100s 6400 + + + +Camera 5: SonyA7II ILCE-7M2 +Image Name Size Aperture Shutter Speed ISO Value +SonyA7II_book 3008 x 1688 f/4.5 1/125s 1600 +SonyA7II_class 3008 x 1688 f/3.5 1/200s 1600 +SonyA7II_compu 3008 x 1688 f/3.5 1/500s 3200 +SonyA7II_door 3008 x 1688 f/4 1/200s 3200 +SonyA7II_plant 3008 x 1688 f/4.5 1/125s 3200 +SonyA7II_stair 3008 x 1688 f/10 1/10s 1600 +SonyA7II_toy 3008 x 1688 f/4.5 1/125s 1600 +SonyA7II_water 3008 x 1688 f/4.5 1/125s 6400 + + +Other Datasets +--------------- +CC [1]: 15 cropped real-world noisy images from CC dataset. + This dataset can be found at http://snam.ml/research/ccnoise + The smaller 15 cropped images can be found on in the directory + ''Real_ccnoise_denoised_part'' of + https://github.com/csjunxu/MCWNNM_ICCV2017 + The *real.png are noisy images; + The *mean.png are "ground truth" images; + The *ours.png are images denoised by CC. + +DND [2]: 1000 cropped real-world noisy images from DND dataset. + Please download the dataset from https://noise.visinf.tu-darmstadt.de/ + and put the files in "DND_2017" directory accordingly. + +SID [3]: http://cchen156.web.engr.illinois.edu/SID.html + +SIDD [4]: Smartphone Image Denoising Dataset + https://www.eecs.yorku.ca/~kamel/sidd/index.php + +[1] Seonghyeon Nam*, Youngbae Hwang*, Yasuyuki Matsushita, Seon Joo Kim. A Holistic Approach to Cross-Channel Image Noise Modeling and its Application to Image Denoising. CVPR, 2016. +[2] Tobias Pl?tz and Stefan Roth. Benchmarking Denoising Algorithms with Real Photographs. CVPR, 2017. +[3] Chen Chen, Qifeng Chen, Jia Xu and Vladlen Koltun. Learning to See in the Dark. CVPR, 2018. +[4] Abdelrahman Abdelhamed, Lin S., Brown M. S. A High-Quality Denoising Dataset for Smartphone Cameras. CVPR, 2018. + +Dependency +------------ +This dataset does not depend on any external dataset. + + +Contact +------------ +If you have questions, problems with the code, or find a bug, please let us know. Contact Jun Xu at csjunxu@comp.polyu.edu.hk or nankaimathxujun@gmail.com diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/compute.m b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/compute.m new file mode 100644 index 0000000000000000000000000000000000000000..e8e05955db3ec10077dc3daf4dc6607dad2d3dd4 --- /dev/null +++ b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/compute.m @@ -0,0 +1,38 @@ +clear; + +Original_image_dir = 'E:\dataset_denoising\'; + +write_MAT_dir = ['C:\Users\csjunxu\Desktop\RID_Dataset\']; + +eval(['cd ' Original_image_dir]); +d = dir; +for i = 1:length(d) + if ( (d(i).isdir == 1) && ~strcmp(d(i).name,'.') && ~strcmp(d(i).name,'..') ) + filepath = d(i).name; + write_sRGB_dir = [write_MAT_dir 'github\' filepath '\']; + if ~isdir(write_sRGB_dir) + mkdir(write_sRGB_dir) + end + eval(['cd ' filepath]); + f = dir; + fpath = fullfile(Original_image_dir, filepath, '*.JPG'); + im_dir = dir(fpath); + im_num = length(im_dir)-3; + gap = floor( im_num /100 ); + index = 0; + for j = 1:gap:im_num + index = index + 1; + nI = double( imread(fullfile(Original_image_dir, filepath, im_dir(j).name)) ); + S = regexp(im_dir(j).name, '\.', 'split'); + fprintf('%d : %s \n', index, im_dir(j).name); + + nI(nI>255)=255; + nI(nI<0)=0; + imwrite(nI/255, [write_sRGB_dir im_dir(j).name]); + if index >= 100 + break; + end + end + cd .. + end +end \ No newline at end of file diff --git a/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/select.m b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/select.m new file mode 100644 index 0000000000000000000000000000000000000000..2f8268290d56d03d1bdd1c533a17c27b5f75d6df --- /dev/null +++ b/dataset/phase1_noise_20260906/polyu_original/PolyU-Real-World-Noisy-Images-Dataset-3af0f2646b267a00446fe4b7113a15e67bc80b4e/select.m @@ -0,0 +1,34 @@ + + +%% This is the program we use to obtian image sequences and mean images + + +clear;clc; +temp='SONY_A7II_ISO1600'; +img_dir =sprintf('G:/dataset_denoising/%s/',temp); %static scenes +out_dir = 'G:/dataset_denoising/added'; + +imgs = dir(fullfile(img_dir,'*.JPG')); +mean_values = zeros(length(imgs),2); +mean_values(:,2) = [1:length(imgs)]; +for i = 1:length(imgs) + img = double(imread(fullfile(img_dir,imgs(i).name))); + mean_v = mean(img(:)); + mean_values(i,1) = mean_v; + +end + +mean_values = mean_values(:,1); +[mean_values_sorted,index] = sort(mean_values); +index_chose = index(15:15+99,1); + +img = zeros(size(img)); +for i = 1:length(index_chose) +% if ~isdir(['added/temp']) +% mkdir(['added/temp']) +% end + copyfile(fullfile(img_dir,imgs(index_chose(i)).name),fullfile('G:/dataset_denoising','added',imgs(index_chose(i)).name)); + img = img + double(imread(fullfile(img_dir,imgs(index_chose(i)).name))); +end +gt = img/100; +imwrite(uint8(gt),'G:/dataset_denoising/added/groundtruth.jpg'); \ No newline at end of file diff --git a/dataset/phase1_noise_20260906/sidd_medium_srgb/mnt/d/SIDD_Medium_Srgb/ReadMe_sRGB.txt b/dataset/phase1_noise_20260906/sidd_medium_srgb/mnt/d/SIDD_Medium_Srgb/ReadMe_sRGB.txt new file mode 100644 index 0000000000000000000000000000000000000000..f99f37412fbf5989dc799513eedf36a158d402f5 --- /dev/null +++ b/dataset/phase1_noise_20260906/sidd_medium_srgb/mnt/d/SIDD_Medium_Srgb/ReadMe_sRGB.txt @@ -0,0 +1,55 @@ +*** This is a medium version of the Smartphone Image Denoising Dataset (SIDD) +[sRGB images] +============================================================================= + +The "Data" directory contains 320 image pairs (noisy and ground-truth, in sRGB space) representing 160 scene instances, two images from each scene instance. + +These images can be used for training/learning purposes. + +For each image, the following is provided in one directory: + +- Two noisy sRGB image (.PNG). +Gamma corrected, without any tone mapping. + +- Two ground truth sRGB image (.PNG), gamma corrected, without any tone mapping. +Gamma corrected, without any tone mapping. + +So, the total number of image files in the "Data" directory is 160 x (2 + 2) = 640. + + +*** Image directory naming convention: +====================================== + +Each image is stored in a directory with the name of the scene instance as follows: + +______ + +where: + +"smartphone-code" is one of the following: + +GP: Google Pixel +IP: iPhone 7 +S6: Samsung Galaxy S6 Edge +N6: Motorola Nexus 6 +G4: LG G4 + +and + +"illuminant-brightness-code" is one of the following: + +L: low light +N: normal brightness +H: high exposure + +For example, the following directory name: + +0052_002_S6_01600_01000_5500_N + +means that this is scene instance 52, from scene 2, captured be Samsung Galaxy S6 Edge (S6), using ISO level of 1600, using shutter speed of 1000 (i.e., exposure time of 1/1000 second), under illuminant temperature of 5500K, under normal (N) brightness. + + +*** Scene_Instance.txt +====================== + +This file contains the names of all directory names inside the "Data" directory, which also represent the scene instance names. \ No newline at end of file diff --git a/dataset/phase1_noise_20260906/sidd_medium_srgb/mnt/d/SIDD_Medium_Srgb/Scene_Instances.txt b/dataset/phase1_noise_20260906/sidd_medium_srgb/mnt/d/SIDD_Medium_Srgb/Scene_Instances.txt new file mode 100644 index 0000000000000000000000000000000000000000..1be47841bce686fb2629d38956976db77ed57676 --- /dev/null +++ b/dataset/phase1_noise_20260906/sidd_medium_srgb/mnt/d/SIDD_Medium_Srgb/Scene_Instances.txt @@ -0,0 +1,160 @@ +0001_001_S6_00100_00060_3200_L +0002_001_S6_00100_00020_3200_N +0003_001_S6_00100_00060_3200_H +0004_001_S6_00100_00060_4400_L +0005_001_S6_00100_00060_4400_N +0006_001_S6_00100_00060_4400_H +0007_001_S6_00100_00100_5500_L +0008_001_S6_00100_00100_5500_N +0010_001_S6_00800_00350_3200_N +0011_001_S6_00800_00500_5500_L +0012_001_S6_00800_00500_5500_N +0013_001_S6_03200_01250_3200_L +0014_001_S6_03200_01250_3200_N +0015_001_S6_03200_01600_5500_L +0016_001_S6_03200_01600_5500_N +0017_001_GP_00100_00060_5500_N +0018_001_GP_00100_00160_5500_L +0019_001_GP_00800_00640_5500_L +0020_001_GP_00800_00350_5500_N +0022_001_N6_00100_00060_5500_N +0023_001_N6_00800_00350_5500_N +0025_001_G4_00100_00060_5500_L +0027_001_G4_00800_00350_5500_L +0028_001_IP_00100_00160_5500_N +0029_001_IP_00800_01000_5500_N +0030_001_IP_01600_02000_5500_N +0032_001_IP_00800_01000_3200_N +0033_001_IP_00100_00160_3200_N +0034_002_GP_00100_00160_3200_N +0035_002_GP_00800_00350_3200_N +0036_002_GP_06400_03200_3200_N +0038_002_GP_00800_00640_3200_L +0039_002_IP_00100_00180_5500_L +0040_002_IP_00800_02000_5500_L +0042_002_IP_01600_03100_5500_N +0043_002_IP_00800_01520_5500_N +0044_002_IP_00100_00180_5500_N +0045_002_G4_00100_00060_3200_L +0047_002_G4_00800_00640_3200_L +0048_002_N6_00100_00100_5500_L +0050_002_N6_03200_03200_5500_L +0051_002_S6_00100_00060_5500_N +0052_002_S6_01600_01000_5500_N +0054_003_N6_00100_00160_5500_N +0055_003_N6_00800_01000_5500_N +0057_003_G4_00100_00125_5500_L +0059_003_G4_00800_01000_5500_L +0060_003_S6_00100_00100_4400_L +0062_003_S6_03200_02500_4400_L +0063_003_GP_00100_00100_4400_N +0064_003_GP_01600_01600_4400_N +0065_003_GP_10000_08460_4400_N +0066_003_GP_00100_00200_3200_L +0068_003_IP_00200_00400_3200_N +0069_003_IP_01000_02000_3200_N +0070_003_IP_02000_04000_3200_N +0072_003_IP_01000_02000_5500_L +0073_003_IP_00200_01000_5500_L +0075_004_N6_00800_00080_3200_L +0076_004_N6_03200_00320_3200_L +0077_004_G4_00100_00025_3200_N +0078_004_G4_00200_00050_3200_N +0080_004_S6_00200_00050_3200_N +0081_004_S6_00800_00160_4400_L +0083_004_GP_00050_00020_4400_N +0084_004_GP_00200_00100_4400_N +0086_004_GP_00100_00100_5500_L +0087_004_GP_00800_00640_5500_L +0088_004_IP_00100_00050_5500_N +0089_004_IP_00500_00250_5500_N +0090_004_IP_01600_00750_5500_N +0091_004_IP_00320_00080_3200_L +0092_004_IP_00640_00125_3200_L +0094_005_N6_00100_00050_3200_L +0096_005_N6_01600_01000_3200_L +0097_005_N6_03200_02000_3200_L +0098_005_G4_00100_00050_3200_N +0099_005_G4_00400_00200_3200_N +0101_005_S6_00100_00050_4400_L +0102_005_S6_00400_00200_4400_L +0104_005_S6_03200_01600_4400_L +0105_005_GP_00100_00100_4400_N +0106_005_GP_00400_00400_4400_N +0107_005_GP_01600_01600_4400_N +0108_005_GP_06400_06400_4400_N +0110_005_IP_00100_00100_5500_L +0111_005_IP_00400_00400_5500_L +0113_005_IP_01600_01520_5500_L +0114_005_IP_00100_00200_5500_N +0115_005_IP_00400_00750_5500_N +0116_005_IP_00800_01520_5500_N +0117_005_IP_01600_04160_5500_N +0118_006_N6_00100_00025_3200_L +0120_006_N6_01600_00400_3200_L +0121_006_N6_03200_01000_3200_L +0122_006_G4_00100_00050_3200_N +0123_006_G4_00400_00160_3200_N +0125_006_S6_00100_00050_4400_L +0126_006_S6_00400_00200_4400_L +0127_006_S6_01600_00800_4400_L +0129_006_GP_00100_00100_4400_N +0130_006_GP_00400_00400_4400_N +0132_006_GP_00100_00200_5500_L +0133_006_GP_00800_01600_5500_L +0134_006_IP_00100_00100_5500_N +0135_006_IP_00400_00400_5500_N +0136_006_IP_00800_00800_5500_N +0137_006_IP_01600_01600_5500_N +0138_006_IP_00100_00100_3200_L +0139_006_IP_00200_00200_3200_L +0140_006_IP_00800_00800_3200_L +0142_007_N6_00100_00100_4400_N +0144_007_N6_01600_01600_4400_N +0145_007_N6_03200_03200_4400_N +0146_007_N6_00400_00400_4400_N +0147_007_G4_00100_00100_4400_L +0149_007_G4_00800_00800_4400_L +0150_007_S6_00100_00100_5500_L +0151_007_S6_00800_00800_5500_L +0152_007_S6_01600_01600_5500_L +0154_007_S6_00400_00400_5500_L +0155_007_GP_00100_00100_5500_N +0156_007_GP_00800_00800_5500_N +0157_007_GP_01600_01600_5500_N +0159_007_IP_00100_00100_3200_L +0160_007_IP_00400_00400_3200_L +0161_007_IP_00800_00800_3200_L +0163_007_IP_00100_00100_3200_N +0164_007_IP_00400_00400_3200_N +0165_007_IP_00800_00800_3200_N +0166_007_IP_01600_01600_3200_N +0167_008_N6_00100_00050_4400_L +0168_008_N6_00400_00200_4400_L +0169_008_N6_00800_00400_4400_L +0170_008_N6_01600_00800_4400_L +0172_008_G4_00100_00100_4400_N +0173_008_G4_00400_00400_4400_N +0175_008_S6_00100_00025_5500_L +0177_008_S6_00800_00200_5500_L +0178_008_S6_01600_00400_5500_L +0179_008_S6_03200_00800_5500_L +0180_008_GP_00100_00100_5500_N +0181_008_GP_00800_00800_5500_N +0182_008_GP_03200_03200_5500_N +0184_008_IP_00100_00100_3200_L +0185_008_IP_00400_00400_3200_L +0186_008_IP_00800_00800_3200_L +0188_008_IP_00100_00100_3200_N +0189_008_IP_00400_00400_3200_N +0190_008_IP_00800_00800_3200_N +0191_008_IP_01600_01600_3200_N +0192_009_IP_00100_00200_3200_N +0193_009_IP_00800_02000_3200_N +0194_009_IP_01600_04000_3200_N +0195_009_IP_01600_04000_5500_L +0196_009_IP_00800_02000_5500_L +0197_009_IP_00100_00200_5500_L +0198_010_GP_00100_00200_5500_N +0199_010_GP_00800_01600_5500_N +0200_010_GP_01600_03200_5500_N \ No newline at end of file diff --git a/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/.gitignore b/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..bc1a1f6167d09c909aad37280b760bb715d0f1da --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/.gitignore @@ -0,0 +1,2 @@ +# Created by pytest automatically. +* diff --git a/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/CACHEDIR.TAG b/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/CACHEDIR.TAG new file mode 100644 index 0000000000000000000000000000000000000000..fce15ad7eaa74e5682b644c84efb75334c112f95 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/CACHEDIR.TAG @@ -0,0 +1,4 @@ +Signature: 8a477f597d28d172789f06886806bc55 +# This file is a cache directory tag created by pytest. +# For information about cache directory tags, see: +# https://bford.info/cachedir/spec.html diff --git a/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/README.md b/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b89018ced91c0a8af7f3f23ce8901870da89f3a0 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/README.md @@ -0,0 +1,8 @@ +# pytest cache directory # + +This directory contains data from the pytest's cache plugin, +which provides the `--lf` and `--ff` options, as well as the `cache` fixture. + +**Do not** commit this to version control. + +See [the docs](https://docs.pytest.org/en/stable/how-to/cache.html) for more information. diff --git a/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/v/cache/nodeids b/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/v/cache/nodeids new file mode 100644 index 0000000000000000000000000000000000000000..7d2d3f94b6f27171341393b6591620e6a5c22473 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/.pytest_cache/v/cache/nodeids @@ -0,0 +1,127 @@ +[ + "tests/test_clean_relative_data.py::test_composition_order_has_physical_effect", + "tests/test_clean_relative_data.py::test_dataset_covers_all_records_without_implicit_cap", + "tests/test_clean_relative_data.py::test_full_decode_audit_detects_reencoded_duplicate_content_and_caches", + "tests/test_clean_relative_data.py::test_grouped_partitions_keep_more_than_legacy_cap", + "tests/test_clean_relative_data.py::test_heldout_strength_ranges_are_disjoint", + "tests/test_clean_relative_data.py::test_invalid_pair_rejected_unless_explicit_exclusion", + "tests/test_clean_relative_data.py::test_isolation_excludes_entire_leaking_scene_and_reports_it", + "tests/test_clean_relative_data.py::test_jpeg_quality_units_and_zero_severity_identity", + "tests/test_clean_relative_data.py::test_strict_pair_discovery_rejects_unmatched_files", + "tests/test_clean_relative_data.py::test_synthesis_deterministic_and_params_reusable[blur]", + "tests/test_clean_relative_data.py::test_synthesis_deterministic_and_params_reusable[haze]", + "tests/test_clean_relative_data.py::test_synthesis_deterministic_and_params_reusable[jpeg]", + "tests/test_clean_relative_data.py::test_synthesis_deterministic_and_params_reusable[lowlight]", + "tests/test_clean_relative_data.py::test_synthesis_deterministic_and_params_reusable[noise]", + "tests/test_clean_relative_data.py::test_synthesis_deterministic_and_params_reusable[rain]", + "tests/test_clean_relative_data.py::test_synthesis_deterministic_and_params_reusable[snow]", + "tests/test_clean_relative_data.py::test_validate_manifest_rejects_content_leakage", + "tests/test_clean_relative_model.py::test_amp_keeps_basis_and_residual_in_float32_with_finite_gradients", + "tests/test_clean_relative_model.py::test_canonical_order_and_complete_blind_output", + "tests/test_clean_relative_model.py::test_drop_factor_accepts_batched_indices_and_removes_only_selected_subspace", + "tests/test_clean_relative_model.py::test_global_basis_is_orthonormal_and_residual_does_not_double_count", + "tests/test_clean_relative_model.py::test_identical_pair_has_exact_zero_teacher_displacement_in_train_mode", + "tests/test_clean_relative_model.py::test_interaction_has_exact_boundaries_order_and_no_edge_control", + "tests/test_clean_relative_model.py::test_invalid_basis_capacity_and_image_shapes_are_rejected", + "tests/test_clean_relative_model.py::test_node_tokens_are_trained_basis_contributions_with_exact_reconstruction", + "tests/test_clean_relative_model.py::test_proxy_native_resolution_has_conditional_checkerboard_capacity", + "tests/test_clean_relative_model.py::test_proxy_rejects_invalid_output_sizes[size0]", + "tests/test_clean_relative_model.py::test_proxy_rejects_invalid_output_sizes[size1]", + "tests/test_clean_relative_model.py::test_proxy_rejects_invalid_output_sizes[size2]", + "tests/test_clean_relative_model.py::test_proxy_rejects_invalid_output_sizes[size3]", + "tests/test_clean_relative_model.py::test_proxy_rejects_invalid_output_sizes[size4]", + "tests/test_clean_relative_model.py::test_teacher_proxy_and_both_evidence_streams_receive_gradients", + "tests/test_clean_relative_training.py::test_atomic_checkpoint_and_rng_roundtrip", + "tests/test_clean_relative_training.py::test_average_precision_ties_and_missing_positives_are_explicit", + "tests/test_clean_relative_training.py::test_class_weights_give_equal_epoch_mass_without_oversampling", + "tests/test_clean_relative_training.py::test_classification_report_does_not_hide_missing_classes", + "tests/test_clean_relative_training.py::test_constant_regression_target_is_not_perfect_evidence", + "tests/test_clean_relative_training.py::test_cross_content_synthesis_rejects_same_scene_variants", + "tests/test_clean_relative_training.py::test_epoch_permutation_covers_tail_and_resume_without_replacement", + "tests/test_clean_relative_training.py::test_full_training_resume_and_controlled_evaluation", + "tests/test_clean_relative_training.py::test_heldout_combinations_never_enter_train_schedule", + "tests/test_clean_relative_training.py::test_high_frequency_statistic_detects_noise_when_mean_is_unchanged", + "tests/test_clean_relative_training.py::test_nonfinite_gradient_never_changes_parameters", + "tests/test_clean_relative_training.py::test_objective_reaches_all_trainable_heads", + "tests/test_clean_relative_training.py::test_physical_parameter_probe_requires_enough_disjoint_scenes", + "tests/test_clean_relative_training.py::test_scene_components_link_video_groups_and_cross_group_duplicates", + "tests/test_clean_relative_training.py::test_train_and_eval_defaults_do_not_cap_full_splits", + "tests/test_clean_relative_training.py::test_unknown_physical_severity_is_not_supervised_as_zero", + "tests/test_phase1_discovery.py::test_complete_seven_dataset_discovery", + "tests/test_phase1_discovery.py::test_direct_div2k_valid_root_never_enters_training", + "tests/test_phase1_discovery.py::test_direct_lr_root_is_rejected", + "tests/test_phase1_discovery.py::test_split_keeps_every_clean_variant_together", + "tests/test_phase1_extra_download.py::test_archive_expansion_preflight_refuses_insufficient_space", + "tests/test_phase1_extra_download.py::test_download_guard_terminates_only_its_child", + "tests/test_phase1_extra_download.py::test_extract_stops_when_other_writers_consume_reserve", + "tests/test_phase1_extra_download.py::test_noise_assets_pin_source_and_distinguish_size_from_scene_count", + "tests/test_phase1_extra_download.py::test_preexisting_symlink_cannot_escape_destination", + "tests/test_phase1_extra_download.py::test_tar_rejects_links_before_extracting", + "tests/test_phase1_extra_download.py::test_unsafe_archive_paths_rejected[../escape]", + "tests/test_phase1_extra_download.py::test_unsafe_archive_paths_rejected[/absolute]", + "tests/test_phase1_extra_download.py::test_unsafe_archive_paths_rejected[a/../../escape]", + "tests/test_phase1_extra_download.py::test_unsafe_archive_paths_rejected[a\\\\b]", + "tests/test_phase1_extra_download.py::test_zip_extracts_regular_members", + "tests/test_phase1_noise_expansion.py::test_all_base_records_unchanged_and_clean_sources_keep_split", + "tests/test_phase1_noise_expansion.py::test_atomic_manifest_refuses_overwrite", + "tests/test_phase1_noise_expansion.py::test_duplicate_real_pair_and_transitive_new_bridge_never_drop_base", + "tests/test_phase1_noise_expansion.py::test_expansion_rehashes_after_same_size_and_mtime_change", + "tests/test_phase1_noise_expansion.py::test_expansion_rejects_changed_base_clean_pixels", + "tests/test_phase1_noise_expansion.py::test_explicit_noise_cannot_be_downgraded_to_schema_one", + "tests/test_phase1_noise_expansion.py::test_frozen_v1_schema_contract_rejects_explicit_noise_manifest", + "tests/test_phase1_noise_expansion.py::test_invalid_new_source_requires_explicit_quarantine_and_coverage", + "tests/test_phase1_noise_expansion.py::test_native_center_crop_and_noise_seed_replay_ignore_eval_loader_seed", + "tests/test_phase1_noise_expansion.py::test_new_content_conflict_cannot_leak_sidd_scene_into_base_test", + "tests/test_phase1_noise_expansion.py::test_new_only_component_prefers_test_without_reassigning_records", + "tests/test_phase1_noise_expansion.py::test_new_real_pair_audit_also_bypasses_stale_stat_cache", + "tests/test_phase1_noise_expansion.py::test_noise_loader_is_native_deterministic_and_masks_only_synthetic", + "tests/test_phase1_noise_expansion.py::test_noise_loader_rejects_invalid_parameters[noise_seed--1]", + "tests/test_phase1_noise_expansion.py::test_noise_loader_rejects_invalid_parameters[severity-2]", + "tests/test_phase1_noise_expansion.py::test_noise_loader_rejects_invalid_parameters[shot--1]", + "tests/test_phase1_noise_expansion.py::test_noise_loader_rejects_invalid_parameters[sigma-nan]", + "tests/test_phase1_noise_expansion.py::test_noise_loader_rejects_invalid_parameters[unrecognized-0.2]", + "tests/test_phase1_noise_expansion.py::test_polyu_original_test_only_ignores_crops_and_rejects_missing_pair", + "tests/test_phase1_noise_expansion.py::test_sidd_pairs_capture_ids_not_first_file_and_preserves_scene_holdouts", + "tests/test_phase1_noise_expansion.py::test_unknown_synthesis_and_profile_fail_closed", + "tests/test_phase1_noise_sampling.py::test_balance_rejects_caps_missing_groups_and_bad_mode", + "tests/test_phase1_noise_sampling.py::test_balanced_changes_only_noise_ids_and_visits_every_record_by_round_two", + "tests/test_phase1_noise_sampling.py::test_balanced_resume_cursor_and_odd_quotas_are_deterministic", + "tests/test_phase1_noise_sampling.py::test_balanced_training_resume_matches_uninterrupted_and_reports_true_coverage", + "tests/test_phase1_noise_sampling.py::test_sampling_does_not_consume_model_rng_and_default_is_uniform", + "tests/test_phase1_noise_sampling.py::test_uniform_sampling_exactly_preserves_previous_epoch_schedule", + "tests/test_phase1_noise_sampling.py::test_visit_zero_preserves_old_view_and_repeats_get_distinct_native_views", + "tests/test_phase1_noise_strata.py::test_capped_evaluation_labels_partial_legacy_and_negative_coverage", + "tests/test_phase1_noise_strata.py::test_functional_disabled_still_reports_source_classification", + "tests/test_phase1_noise_strata.py::test_legacy_view_matches_legacy_evaluation_and_schema1_output_is_unchanged", + "tests/test_phase1_noise_strata.py::test_real_physical_targets_cannot_be_silently_invented", + "tests/test_phase1_noise_strata.py::test_source_cohorts_share_parent_negatives_and_do_not_pool_other_noise", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[bad_hash-hash]", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[changed_prefix-prefix]", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[false_preservation-preservation]", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[missing_expansion-parent]", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[missing_path-parent]", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[missing_receipt-parent]", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[new_nonnoise-non-noise]", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[null_receipt-parent]", + "tests/test_phase1_noise_strata.py::test_stratification_fails_closed_before_inference[unknown_real-noise source]", + "tests/test_phase1_noise_strata.py::test_worker_labels_are_copied_before_retention", + "tests/test_phase1_noise_suite.py::test_different_output_parent_still_shares_predecessor_gpu_lock", + "tests/test_phase1_noise_suite.py::test_expanded_evaluation_must_skip_controls_explicitly", + "tests/test_phase1_noise_suite.py::test_noise_commands_two_uncapped_matched_runs_and_fixed_reference", + "tests/test_phase1_noise_suite.py::test_noise_completion_rejects_missing_coverage_and_skipped_steps", + "tests/test_phase1_noise_suite.py::test_noise_report_never_claims_unvalidated_results", + "tests/test_phase1_noise_suite.py::test_noise_report_renders_configured_budget", + "tests/test_phase1_noise_suite.py::test_parent_requires_hash_and_exact_base_records", + "tests/test_phase1_noise_suite.py::test_predecessor_must_finish_all_runs_on_same_gpu", + "tests/test_phase1_suite.py::test_correct_evaluation_provenance_is_accepted", + "tests/test_phase1_suite.py::test_interrupted_stage_cleans_up_its_real_child", + "tests/test_phase1_suite.py::test_report_counts_only_validated_complete_test_metrics", + "tests/test_phase1_suite.py::test_report_does_not_count_existing_unvalidated_results", + "tests/test_phase1_suite.py::test_report_does_not_invent_missing_results", + "tests/test_phase1_suite.py::test_stale_or_partial_evaluation_is_rejected[cap]", + "tests/test_phase1_suite.py::test_stale_or_partial_evaluation_is_rejected[checkpoint]", + "tests/test_phase1_suite.py::test_stale_or_partial_evaluation_is_rejected[manifest]", + "tests/test_phase1_suite.py::test_stale_or_partial_evaluation_is_rejected[seed]", + "tests/test_phase1_suite.py::test_stale_or_partial_evaluation_is_rejected[skip]", + "tests/test_phase1_suite.py::test_suite_commands_are_uncapped_and_native" +] \ No newline at end of file diff --git a/dataset/phase1_noise_20260906/trial_code_staging/__pycache__/eval_phase1_clean_relative.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/__pycache__/eval_phase1_clean_relative.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3be65e1baa8017a66c680ab382818d73b0293653 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/__pycache__/eval_phase1_clean_relative.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/__pycache__/train_phase1_clean_relative.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/__pycache__/train_phase1_clean_relative.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b314e35b5c0e703a5b46b9ddd99df91baa92d759 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/__pycache__/train_phase1_clean_relative.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/docs/figures/phase1_tsne_report.json b/dataset/phase1_noise_20260906/trial_code_staging/docs/figures/phase1_tsne_report.json new file mode 100644 index 0000000000000000000000000000000000000000..b07cf4ac897853c22eeb558da4e25e99f05c2565 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/docs/figures/phase1_tsne_report.json @@ -0,0 +1,133 @@ +{ + "n": 954, + "groups": { + "noise": 19, + "clean_rain": 98, + "clean_haze": 100, + "scene008": 20, + "haze": 100, + "rain": 98, + "snow_ood": 200, + "clean_lowlight": 100, + "lowlight": 100, + "clean_noise": 19, + "rain_locked": 100 + }, + "tsne/global_condition": { + "silhouette_type_feature": 0.6227694153785706, + "silhouette_type_embedding": 0.7218385934829712, + "knn10_purity_all_groups": 0.6053459119496856, + "trustworthiness_k10": 0.9924486976295864, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.826288206266019, + "noise": 0.8754385964912281, + "haze": 0.5689888988898889, + "lowlight": 0.47996399639963994 + } + }, + "tsne/unknown_residual": { + "silhouette_type_feature": -0.043470509350299835, + "silhouette_type_embedding": 0.09289053082466125, + "knn10_purity_all_groups": 0.5777777777777777, + "trustworthiness_k10": 0.9452783278549003, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.152098236486745, + "noise": 0.8543859649122807, + "haze": 0.4782358235823582, + "lowlight": 0.456057605760576 + } + }, + "tsne/graph_vector": { + "silhouette_type_feature": 0.4347238540649414, + "silhouette_type_embedding": 0.6353642344474792, + "knn10_purity_all_groups": 0.5707547169811321, + "trustworthiness_k10": 0.9937099099883954, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.06819406234792838, + "noise": 0.08070175438596491, + "haze": 0.31313531353135315, + "lowlight": 0.8318391839183916 + } + }, + "umap/global_condition": { + "silhouette_type_feature": 0.6227694153785706, + "silhouette_type_embedding": 0.7300851345062256, + "knn10_purity_all_groups": 0.6053459119496856, + "trustworthiness_k10": 0.9890062759052818, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.826288206266019, + "noise": 0.8754385964912281, + "haze": 0.5689888988898889, + "lowlight": 0.47996399639963994 + } + }, + "umap/unknown_residual": { + "silhouette_type_feature": -0.043470509350299835, + "silhouette_type_embedding": 0.03866301476955414, + "knn10_purity_all_groups": 0.5777777777777777, + "trustworthiness_k10": 0.9250723477068206, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.152098236486745, + "noise": 0.8543859649122807, + "haze": 0.4782358235823582, + "lowlight": 0.456057605760576 + } + }, + "umap/graph_vector": { + "silhouette_type_feature": 0.4347238540649414, + "silhouette_type_embedding": 0.6660717725753784, + "knn10_purity_all_groups": 0.5707547169811321, + "trustworthiness_k10": 0.9904875191130859, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.06819406234792838, + "noise": 0.08070175438596491, + "haze": 0.31313531353135315, + "lowlight": 0.8318391839183916 + } + }, + "pca/global_condition": { + "silhouette_type_feature": 0.6227694153785706, + "silhouette_type_embedding": 0.34093230962753296, + "knn10_purity_all_groups": 0.6053459119496856, + "trustworthiness_k10": 0.9009235711118483, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.826288206266019, + "noise": 0.8754385964912281, + "haze": 0.5689888988898889, + "lowlight": 0.47996399639963994 + } + }, + "pca/unknown_residual": { + "silhouette_type_feature": -0.043470509350299835, + "silhouette_type_embedding": -0.09672052413225174, + "knn10_purity_all_groups": 0.5777777777777777, + "trustworthiness_k10": 0.9137637672855453, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.152098236486745, + "noise": 0.8543859649122807, + "haze": 0.4782358235823582, + "lowlight": 0.456057605760576 + } + }, + "pca/graph_vector": { + "silhouette_type_feature": 0.4347238540649414, + "silhouette_type_embedding": 0.39952635765075684, + "knn10_purity_all_groups": 0.5707547169811321, + "trustworthiness_k10": 0.9811806609637351, + "free_mass_auroc_null_vs_degraded": 0.8473812569435532, + "severity_ordering_abs_spearman_pc1": { + "rain": 0.06819406234792838, + "noise": 0.08070175438596491, + "haze": 0.31313531353135315, + "lowlight": 0.8318391839183916 + } + } +} \ No newline at end of file diff --git a/dataset/phase1_noise_20260906/trial_code_staging/docs/final_version_summary_2026-09-02.md b/dataset/phase1_noise_20260906/trial_code_staging/docs/final_version_summary_2026-09-02.md new file mode 100644 index 0000000000000000000000000000000000000000..6ed7c2ad93d29f0981fe48188c144a9b7b603aa7 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/docs/final_version_summary_2026-09-02.md @@ -0,0 +1,174 @@ +# SCDC — Tổng hợp phiên bản cuối (nguồn cho slide) + +*Trạng thái 2026-09-02. Mọi số là seed 42, validation nội bộ 317 ảnh (haze 100 · lowlight 100 · noise 19 · rain 98, center-crop 256) trừ khi ghi khác. Hình: `outputs/final_charts/*.png`, `outputs/phase2_v7_dgf8k_vis/*.png`, `outputs/scene008_dgf.png`.* + +--- + +## 1. Bài toán và claim đứng vững + +**Blind all-in-one restoration**: một mạng, bốn suy hoá (haze / lowlight / noise / rain), không nhãn task lúc inference. + +Claim đứng được bằng số: +1. **Unified two-step diffusion một mạng** (T = 2, exact posterior ResShift) thay pipeline hai mạng "diffusion + refiner": nội bộ 27,50 / 0,850 (vs gen-2 hai mạng 27,55 / 0,874) và **thắng hai mạng trên cả 3 bộ external** (rain +1,2 · haze +0,7 · scene008 +4,2 dB). +2. **Backbone Uformer/LeWin xoá "định luật drift"**: mọi trunk conv trước đó luôn hy sinh lowlight khi tối ưu dài (v4, v6, v6.1, v7-conv); Uformer từ scratch leo đơn điệu 8k → 16k → … với best == final ở mọi chu kỳ. +3. **Head full-res train-chung an toàn ngoài phân phối, refiner train-rời thì không** — cùng một dung lượng, khác chỗ đặt. +4. **Identity trên ảnh sạch**: 27,8 → 40,4 dB nhờ cặp identity trong fine-tune. + +Claim phải nói cẩn thận (xem §7): vai trò của Phase-1 là **chẩn đoán + hỗ trợ haze**, không phải "điều kiện không thể thiếu" cho restoration. + +--- + +## 2. Kiến trúc bản cuối (`uformer_dgf8k_seed42`, best @6000) + +### Phase-1 — Blind Degradation Graph Encoder (`phase1_ll_v3`, đóng băng) +- Hai nhánh spatial + wavelet, thêm **LL-global branch** (Haar LL³ → attention 1-query + 14 thống kê photometric → 128-d) để giữ thông tin toàn cục (sửa lỗi "mất global"). +- Đầu ra graph: 6 node token (4 known + 2 free/null), routing, severity 4 chiều (calibrated), spatial maps 16×16, content latent 64 px, unknown residual, global condition 256-d. +- Null/OOD: free slots học từ ảnh sạch + OOD tổng hợp (snow/blur/pixelate); OOD → free 55–60/60, novelty gap 3–4×, "honest-null" (free-mass tương quan âm với residual mưa). + +### Phase-2 — v7 Unified two-step ResShift, backbone Uformer (~thông số dims 64/128/192/256, cond 256) +- **State**: pixel-unshuffle ×2, 12 kênh; anchor u_y; x0-prediction. +- **Lịch T = 2** (η = [0, 0,04, 0,98]); κ theo mẫu từ strengths của node (per-type κ calibrated). +- **Trunk**: LeWin blocks (window-attn 8×8 + LeFF + adaLN zero-init), cross-attention với 8 token graph ở 2 scale sâu, adaLN từ `global_vector`, MoE bank 5 expert (top-2) ở 7 vị trí, content inject @64 px, spatial inject @16 px. +- **Image head** (train-chung): tail NAFNet-lite 3 block × 48 kênh ở **full-res** (input restored ‖ y, zero-init) + **FiLM** đầu ra từ global condition (6 tham số). +- **Tháp Laplacian coarse-to-fine**: head zero-init ở 16/32/64 px trong không gian state, tái tạo telescoping với anchor u_y (identity chính xác khi δ = 0), deep supervision MSE λ = 0,1/0,2/0,3. +- **DGF**: token null học được cho `context` và `global_vector`; conditioning dropout p = 0,15; cặp identity q = 0,10; liều w ở inference (mặc định w = 1). +- **Inference**: 2 forward (coarse t=2 → posterior → fine t=1) + head; với liều w ≠ 1 thêm 1 forward null ở bước coarse. + +### Mất mát composite (một optimizer) +coarse x0-MSE (fp32) + tháp MSE + fine [L1 + 0,1·VGG + 0,5·chroma(UV) + 0,5·luma(pool 8×8)] + gate anchor/correction. + +--- + +## 3. Công thức huấn luyện (chuỗi warm-restart) + +| Chu kỳ | Thay đổi | Steps | LR đỉnh | Kết quả (macro / SSIM) | +|---|---|---:|---:|---:| +| 1 | Uformer từ scratch, unified two-step | 8k | 1e-4 | 25,26 / 0,777 | +| 2 | + chroma loss (DDP 2 GPU) | 16k | 5e-5 | 26,44 / 0,808 | +| 3 | + luma loss | 8k | 3e-5 | 26,59 / 0,811 | +| 4 | + full-res tail + FiLM | 8k | 3e-5 | 27,43 / 0,846 | +| 5 | + DGF (null tokens, identity, tháp Laplacian) | 8k | 3e-5 | **27,50 / 0,850** (w=1); 27,54 @w=0,5 | + +Hạ tầng: DDP 2×3090 (`find_unused_parameters=True` bắt buộc vì MoE hard-skip), EMA 0,9999, AMP + cơ chế `RecoverableAmpOverflow` (scaler dao động ở trần fp16 → auto-resume bằng supervisor, 0 step mất). Mỗi chu kỳ eval@0 trùng bitwise best chu kỳ trước (mọi thành phần mới zero-init/identity). + +--- + +## 4. Kết quả nội bộ + +### Bản cuối theo domain (dgf8k best @6000, w = 1) + +| Domain | Degraded | Bản cuối | gen-2 (2 mạng) | +|---|---:|---:|---:| +| Haze | 17,31 | **32,73** | 30,2 | +| Noise | 27,33 | **35,99** | 36,9 | +| Lowlight | 9,77 | 18,74 | 20,3 | +| Rain | 21,25 | 22,53 | 22,8 | +| **Macro / SSIM** | 18,91 / 0,551 | **27,50 / 0,850** | 27,55 / 0,874 | + +### Tiến hoá (hình 01) +22,68 (v4 1-step) → 23,41 (v7-conv) → 25,26 → 26,44 → 26,59 → 27,43 → 27,50. + +### Sweep liều (DGF, val) +w = 0: 27,49 / **0,852**, lowlight 18,87, rain 22,62 · w = 0,5: **27,54** · w = 1: 27,50 · w = 1,25: 27,43. Đường cong phẳng (xem §7, định luật 4). + +### Identity (ảnh sạch làm input, PSNR(f(x), x)) +head8k 27,8 (noise 23,6 — phá ảnh sạch) → **DGF 40,4** (noise 41,4 · lowlight 36,2 · haze 43,8 · rain 40,2). + +--- + +## 5. External held-out (hình 02) — PSNR / SSIM / LPIPS + +| Bộ | Degraded | gen-2 (2 mạng) | head8k | **DGF (w=1)** | +|---|---:|---:|---:|---:| +| Rain locked (1200) | 22,56 | 26,71 / 0,833 / 0,108 | **28,02** / 0,836 / 0,125 | 27,88 / 0,834 / 0,124 | +| Haze held-out (300) | 18,17 | 31,18 / 0,971 / 0,010 | 31,71 / 0,974 / 0,010 | **31,87 / 0,975 / 0,009** | +| Noise scene008 (20) | **39,02** | 22,35 / 0,801 / 0,085 | 27,09 / 0,765 / 0,328 | 26,50 / **0,825** / 0,193 | + +Ghi chú: rain nội bộ 22,5 bị GT lệch tone kéo thấp giả tạo — derain thật là 28 dB external. scene008 là cảnh vải **tối gần sạch**: mọi model đều "làm gì đó" (xem §7, định luật 6). + +--- + +## 6. Ablation / probe (hình 03) + +Probe leave-one-out ở inference trên head8k (full val): + +| Tắt | Δ macro | Đọc | +|---|---:|---| +| `context` (cross-attn tokens) | −3,68 | đường sống 1 (noise −13,4, **lowlight +1,95**) | +| `global_vector` (adaLN) | −3,45 | đường sống 2 (haze −6,0, lowlight +0,55) | +| `unknown_residual` (field) | −0,74 | field Phase-1 hữu ích nhất | +| `global_condition` / `node_tokens` | −0,24 / −0,16 | | +| MoE gate + κ per-type (uniform) | −0,085 | cơ chế MoE ≈ không dùng ở inference | +| routing / severity / spatial maps / content latent | ≈ 0 | plug chết | +| Rút toàn bộ Phase-1 (chưa train null) | −7,79 | | + +Kết luận cấu trúc: trunk dùng Phase-1 như một **bộ mô tả ảnh** (qua 2 đường), không dùng cấu trúc graph tường minh; 7 bank expert + content/spatial inject có thể prune. + +--- + +## 7. Định luật rút ra (mỗi cái có số đo) + +1. **Chain dài phá kết quả** (exposure bias): 1-step > 8-step; unified two-step chain-aware là điểm cân bằng. +2. **Drift law của conv-trunk** (lowlight bị hy sinh khi train dài) — Uformer + adaLN zero-init miễn nhiễm. +3. **Cùng dung lượng full-res: trong một graph/loss thì an toàn OOD, tách mạng thì overfit** (refiner −5 dB external; head train-chung giữ nguyên). +4. **Ablation tắt-điều-kiện trên model chưa có nhánh null đo "rụt rè off-manifold", không đo giá trị của điều kiện** — +1,95 lowlight biến mất sau khi nhánh null được train (w=0 chỉ +0,13). +5. **Warm-restart cosine = SGDR**: mỗi chu kỳ vắt thêm, lợi suất co (25,26 → +1,18 → +0,15 → +0,84 (head) → +0,07); "bão hoà" là do schedule, loss chưa từng phẳng ở LR còn sống. +6. **Identity phải được dạy bằng ảnh sạch giống phân phối triển khai** (tối, có vân, real-camera): identity nội bộ 40 dB không chuyển sang scene008. +7. **Overshoot lowlight cực đoan là trần thông tin**: input ~9,7 dB gần đen, độ sáng tuyệt đối của GT không có trong ảnh vào. + +--- + +## 8. Hai thí nghiệm quyết định (đã xong) + +### 8a. Control "không Phase-1" (p = 1, cùng recipe, cùng warm-start, eval hoàn toàn không điều kiện) + +| Step | Không Phase-1 | Có Phase-1 (dgf8k) | Chênh | +|---:|---:|---:|---:| +| 0 | 20,43 | 27,43 | −7,0 | +| 2000 | 26,49 | 27,27 | −0,78 | +| 4000 | 26,73 | 27,46 | −0,74 | +| 6000 | 27,03 / 0,847 | 27,50 / 0,850 | −0,47 | +| 8000 | **27,05 / 0,846** | 27,45 / 0,850 | **−0,40** | + +Phân bố chênh @8000: haze −1,85 · noise −0,58 · **lowlight +0,94 cho control** · rain −0,12. → **Phán quyết: chênh 0,40 dB (dải 0,2–0,5)** — Phase-1 giữ vai chẩn đoán / OOD / hỗ trợ haze (thông tin toàn cục airlight/transmission); restoration là công của trunk; với lowlight điều kiện gây over-drive. Caveat: control warm-start từ trọng số từng học có điều kiện — trả lời cho inference và fine-tune tiếp, chưa phải from-scratch. Hình: `outputs/final_charts/04_phase1_control.png`. + +### 8b. Phase-1 ll_v4/v4b — sửa khái niệm noise (ĐÓNG, âm tính) +Với 8 scene SIDD, cả nhiễu tổng hợp (v4) lẫn transplant residual thật + hard negative sharpen (v4b, 50 epoch, best epoch 18 F1 0,774) đều đẩy khái niệm noise về "hạt tối kiểu SIDD": + +| Ca | ll_v3 | v4 @20 | v4b best | v4b last | +|---|---:|---:|---:|---:| +| scene008 clean → noise | 0,41 | 0,81 | **0,90** | 0,67 | +| LOL clean GT → noise | 0,20 | 0,29 | 0,74 | 0,64 | +| SIDD val noise → noise | 0,04 | 0,03 | 0,08 | 0,05 | +| SIDD val noise → rain | 0,58 | 0,75 | 0,60 | 0,61 | + +Kết luận: giới hạn dữ liệu (8 scene), không phải weight hay loss — mọi augmentation nhiễu đều tăng dương tính giả trên ảnh sạch tối/có vân và không dạy được ca thiếu. Nhánh đóng; giữ ll_v3 làm Phase-1 chính thức. Hướng còn lại nếu muốn quay lại: dữ liệu nhiễu thật đa scene (SIDD full / ELD / PolyU) hoặc ước lượng noise-level cổ điển làm đặc trưng. + +--- + +## 9. Hạn chế và bước tiếp + +- 1 seed cho mọi số; noise val n = 19 (1 scene); chưa test mixed degradation; chưa có zero-shot restoration cho suy hoá unseen (chỉ có detection). +- Bước tiếp có căn cứ: (i) identity pairs từ ảnh sạch tối/có vân thật (SIDD GT, LOL GT) ở trunk; (ii) prune plug chết (content/spatial inject, MoE bank) → mạng gọn hơn; (iii) seed 43/44 cho chu kỳ cuối; (iv) benchmark công khai để so với AirNet/PromptIR/DA-CLIP. + +## 10. Tài sản +- Checkpoints (server 3090): `outputs/phase1_ll_v3/graph_encoder_best.pt`; `outputs/phase2_v7/{uformer_seed42,uformer16k_seed42,uformer_luma8k_seed42,uformer_head8k_seed42,uformer_dgf8k_seed42}/best.pt`. +- Scripts: `train_phase2_unified_v7.py`, `src/models/restoration/uformer_moe_v7.py`, `eval_v7_external.py`, `sweep_v7_dose.py`, `probe_v7_taps.py`, `visualize_v7_uformer.py`, `visualize_scene008.py`, `diagnose_phase1_routing.py`, `make_final_charts.py`. +- Số liệu JSON: `outputs/v7_*external*.json`, `outputs/v7_dgf_dose_sweep.json`, `outputs/v7_head_taps_*.json`, `outputs/v7_head8k_identity.json`, `outputs/phase1_ll_v*_routing_diag*.json`. + +## 11. Cập nhật sau bản tổng hợp — hai run A/B (2026-09-03) + +Hai run 8k warm-start từ dgf8k best, mỗi run một GPU, cùng recipe DGF + **clean-image prior** (cặp clean + Poisson-Gaussian, p = 0,20) + **tail full-res 6 block**; B thêm **Phase-1 nhìn toàn khung hình** (aspect-squash 256, hai đường cộng zero-init vào context và global_vector). + +| | dgf8k (bản cuối cũ) | **A** `uformer_p5_8k_seed42` | **B** `uformer_p45_8k_seed42` | +|---|---|---|---| +| Val macro PSNR / SSIM (best @6000) | 27,50 / 0,850 | **27,90** / 0,859 | 27,81 / **0,861** | +| haze / lowlight / noise / rain (PSNR) | 32,9 / 19,0 / 36,0 / 22,6 | 33,08 / 19,05 / **36,95** / 22,53 | 32,55 / **19,43** / 36,72 / 22,52 | +| External rain 1200 | 27,88 / 0,834 | 27,87 / 0,837 | 27,79 / 0,835 | +| External haze 300 | 31,87 / 0,975 | 31,54 / 0,976 | **31,92** / 0,975 | +| External scene008 (gần sạch, input 39,0) | 26,50 / 0,825 | 27,13 / 0,853 | **28,15** / 0,855 | + +- **#5 (noise kém refiner 0,9 dB): đóng dương.** Clean-image prior trong cùng một mạng đưa noise val lên 36,95 = refiner hai mạng (36,9); +0,41 dB macro so với dgf8k. +- **#4 (Phase-1 mất global): sửa đúng cơ chế, không đạt mốc tự đặt.** Toàn khung hình mang thông tin exposure toàn ảnh mà crop không có: lowlight +0,38, scene008 +1,0, haze external +0,38; nhưng val macro −0,10 (haze val chỉ 3 cảnh gốc, ngược dấu với haze external 300 cảnh). Claim đúng: *lựa chọn robustness*, không phải "cải thiện". +- **Chẩn đoán mới cho scene008:** một phép affine toàn cục trên output nâng 27,1 → 35,9 dB — lỗi là **exposure prior của trunk** (kéo tối ảnh sáng vừa, nâng sáng ảnh rất tối), không phải mất texture; Phase-1 và whole-frame context đều *giảm* lỗi này. Việc kế tiếp có bằng chứng: identity pairs từ ảnh clean đa dạng exposure. +- **Checkpoint bản cuối:** A cho bảng in-dist; B cho triển khai OOD. Ảnh vis: `outputs/phase2_v7/uformer_p5_8k_seed42/vis`, `outputs/phase2_v7/uformer_p45_8k_seed42/vis` (mỗi thư mục 4 lưới domain + `scene008.png`). Bảng tổng quan dữ liệu: `visualize_degradation_table.py`. diff --git a/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_clean_relative_seven_evaluation.md b/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_clean_relative_seven_evaluation.md new file mode 100644 index 0000000000000000000000000000000000000000..e04f000d60fae78e8208fa3f8758c46b66c37ea0 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_clean_relative_seven_evaluation.md @@ -0,0 +1,199 @@ +# Phase-1 clean-relative seven-degradation implementation and evaluation + +Date: 2026-09-06 (Asia/Ho_Chi_Minh). Status: implementation/data verified; model-quality results pending. + +## Decision and scope + +Combine the structured subspace node proposal with functional, clean-relative +supervision. A successful representation must distinguish degradation factors, +encode useful within-type variation, transfer controlled corruption parameters +across held-out contents, and support measurable composition interventions. +Neither a class cluster nor a small clean norm alone establishes these properties. + +Canonical known-type order: `rain, noise, haze, lowlight, snow, blur, jpeg`. +Snow is now a supervised known type, not an unknown/OOD training class. Two +additional free nodes are residual capacity, not independently identified classes. +The initial representation uses 256 dimensions and rank-8 node bases. A global +orthonormal bank or a consistent joint projection avoids double-counting shared +directions. Presence is independent sigmoid activation, not a categorical softmax. +Severity is supervised on explicitly known synthetic parameters; measured real-pair +residual strength is not called a physical severity ground truth. + +The new implementation is versioned separately from the legacy Phase-1. It must +not silently remap seven labels into the old four-label/six-node contract. Phase-2, +its checkpoints, pre-gain and spatial expert consumers are unchanged in this task. +A future Phase-2 adapter is a separate evaluated change. + +## Architecture and objectives + +1. Spatial and multi-band wavelet evidence feed dual-domain attention, separate + content features and a blind single-image degradation descriptor. +2. Paired clean/degraded features provide an explicitly identity-anchored training + descriptor. A feature difference is evidence of change, not a proof that all + content dependence cancels. Inference never receives the paired clean image. +3. Orthonormal bases yield amplitudes/coordinates and a consistent residual. + Independent presence, supervised parameter heads and within-type coordinates + are kept distinct. Clean corresponds to zero degradation, not zero content. +4. A lightweight proxy decoder is included from the start. Clean/degraded + reconstruction and controlled cross-content transfer anchor functional meaning. + It is not claimed to recover a uniquely identifiable causal model. +5. Shared, ordered pair interactions are departures from additivity in this chosen + representation. They vanish exactly if either input factor is absent. A no-edge + run isolates their benefit, but keeps the evidence attention and therefore is + not a complete no-message-passing ablation. Family hierarchies are deferred to avoid duplicated + family bases and an unvalidated hard taxonomy. + +Loss groups: clean origin and absence; paired content consistency plus functional +reconstruction to oppose content collapse; independent factor presence; known-node +support and constrained free capacity; synthetic parameter/severity supervision; +paired-to-blind agreement with supervised paired targets; matched-parameter +cross-content consistency; composition and functional transfer. All loss terms, +weights, finite-gradient failures and sample counts are logged. + +## Data contract: no hidden subset training + +Reference: [DA-CLIP repository](https://github.com/Algolzw/daclip-uir), which lists +ten tasks. Add motion blur and JPEG to the five existing degradation domains; +do not claim reproduction of DA-CLIP's full ten-task benchmark. + +| Type | Source | Training and evaluation policy | +|---|---|---| +| Rain | Existing Rain13K-resized | All valid available train pairs; preserve audited quarantine and official-test isolation. Resized-source limitation remains explicit. | +| Noise | Existing SIDD Small sRGB | All available scene-isolated records, native aligned crops; no image downsampling that averages away noise. Not the full SIDD Medium/benchmark corpus. | +| Haze | Existing RESIDE bundle | All valid available pairs, grouped by clean source; do not retain the old 5,000-pair cap. Bundle is an extracted subset, not full RESIDE. | +| Lowlight | Existing LOLv2 real | All paired train inputs; validation/test roles fixed before fitting. Not LOLv2 synthetic unless separately obtained. | +| Snow | Snow100K train and separately acquired test | Audit all 50,000 local train pairs before duplicate/leakage exclusions; hold out content groups. Acquire official test if public download is accessible. | +| Motion blur | GoPro Large | All train pairs, validation by training scene; official test kept locked. The larger raw-video archive is unnecessary. | +| JPEG | DIV2K HR + Flickr2K HR | All clean-source training records, on-the-fly compression; source split before generation. DIV2K validation provides held-out sources, not a source pool for training. | + +Downloader receipts record original URL, mirror URL/revision where applicable, +archive SHA-256, extraction counts and expanded bytes. Never execute downloaded +code. Missing or corrupt pairs, exact clean-content duplicates and conflicting +split assignments are errors or explicit audited exclusions, never silently skipped. +No validation/test record is moved into training to satisfy “all data.” + +An epoch is a shuffled traversal of every admitted training record, without +replacement and without dropping the last batch. Record counts and coverage are +persisted. Class-weighted objectives address imbalance without pretending fixed +replacement sampling has visited all images. Synthetic controls supplement, not +replace, the real paired datasets. + +Report three distinct quantities: original benchmark size, local discovered size, +and final split sizes after safety exclusions. “Full coverage” means the last +quantity, not unavailable original benchmark data. + +## Fixed evaluation matrix + +Use validation only for checkpoint selection. Lock test sources, synthetic seeds, +parameter grids, held-out unordered type pairs and operation orders before fitting. +Report macro averages and per-domain values; large Snow100K counts must not hide +failure on small SIDD/LOL domains. Test metrics never select a checkpoint. + +| Question | Primary evidence | Necessary control / limitation | +|---|---|---| +| Does clean map to an identity? | Clean descriptor norm distribution, false-positive presence, clean proxy error | Include naturally dark/low-texture clean scenes; zero norm alone is insufficient. | +| Are known nodes discriminative? | Per-domain precision/recall/F1/AP, confusion, multi-label mixture presence | Report source/dataset confounding; no class-cluster-as-disentanglement claim. | +| Are coordinates richer than class × severity? | Matched generating parameters across disjoint contents; within-type parameter retrieval/prediction | Compare a rank-1/prototype baseline and report its differing capacity. | +| Is severity meaningful? | Synthetic parameter MAE, correlation and calibration per type and parameter regime | Real residual proxies reported separately; no universal scalar ordering assumed. | +| Does the global code leak content? | Cross-content consistency at matched parameters; held-out content predictability where estimable | Cosine separation alone is not evidence of independence; local physical fields may depend on content. | +| Can codes do useful work? | Cross-content re-degradation proxy error vs zero/shuffled code; factor-removal tests | Random noise evaluated with suitable statistics as well as pixel error; PSNR is not a causal proof. | +| Do edges improve composition? | Held-out mixture presence, parameter recovery, functional error, both matched orders | No-edge run; latent R² secondary only, with target variance and frozen-reference status. | +| Does unknown detection generalize? | Clean/known vs never-trained corruption AUROC/AUPR, stated probe types | Residual norm can miss OOD captured by free nodes; this is not leave-one-type/family-out validation. | +| Are conclusions reproducible? | Seeds 42/43/44, means and variability; manifest/config/source hashes | A trial does not establish convergence or benchmark superiority. | + +Predeclared held-out composition candidates: rain+JPEG, noise+haze, snow+blur. +These pairs must be excluded in both orders from composition training. Distinguish +an unseen pair from a seen pair at unseen strengths. Synthetic renderers are named +approximations, not asserted exact generators of the real benchmarks. + +Checkpoint ranking initially uses fixed validation macro-F1, with clean false +positives, functional metrics and per-domain scores reported alongside it. Passing +classification alone does not authorize a claim of a successful representation. +No numerical success threshold is backfilled after viewing test outcomes. + +## Runs and operational gates + +1. CPU unit tests: projection/orthogonality, exact pair identity, interaction zero + boundaries, shape/dtype/gradients, manifest leakage, deterministic synthesis, + source-wide epoch coverage, checkpoint/resume and metric degeneracy handling. +2. Independent code review, including archive extraction/path safety and source + split isolation. Fix accepted findings before the full-data launch. +3. ROCm smoke on physical GPU index 5: one visible GPU, bounded batch, actual + device identity, finite forward/backward, checkpoint reload and evaluation. + Smoke caps must appear in run metadata and never masquerade as the full run. +4. Initial full-data trial: seed 42, five complete epochs. Start conservatively at + real batch 16, synthetic subbatch 4, native 256 crops; adjust only from measured + memory/throughput and record the resulting configuration. +5. After a finite initial run: full held-out evaluation. Sequential matched-budget + no-edge and rank-1/prototype controls and seeds 43/44 quantify improvements and + variability. Keep them on the same requested GPU; no opportunistic other GPUs. +6. Produce machine-readable metrics and a human-readable result report, including + failures, unsupported evaluations and source-availability limitations. Full + convergence, a Phase-2 gain and semantic family OOD require later experiments. + +Initial host audit: physical GPU 5 PCI `0000:AB:00.0`, MI325X 256-GiB-class device; +approximately 188 GiB already allocated by unrelated processes and 67 GiB free. +Do not kill or reconfigure those processes. Target a substantially smaller memory +footprint and confirm device mapping with ROCm visibility before launch. Root +filesystem initially had approximately 115 GB free. Reserve at least 25 GiB while +downloading/extracting. Existing checkpoints and datasets are not deletion targets. + +Commit and push to `codex/phase1-clean-relative-seven`. Deploy an immutable archive +of the committed SHA on the server, preserving `/home/vunguyen/SCDC` and existing +outputs. Launch logs/checkpoints live in a new run directory. Persist source SHA, +manifest hash, exact command, PID/session and status so remote progress is auditable. + +## Evidence log + +The final manifest is `/home/vunguyen/data_bundle/phase1_seven_extra/manifest_v1.json`. +SHA-256: `8f7be16638ee544eb97245871ce1c6d884920bb2973c14a64a09e4db64f88e24`. + +| Type | Train | Validation | Test | +|---|---:|---:|---:| +| Rain | 11,958 | 598 | 4,298 | +| Noise | 121 | 19 | 20 | +| Haze | 4,740 | 280 | 280 | +| Lowlight | 655 | 34 | 100 | +| Snow | 47,369 | 2,493 | 33,412 | +| Motion blur | 2,003 | 100 | 1,111 | +| JPEG | 3,278 | 172 | 100 | +| **Total** | **70,124** | **3,696** | **39,321** | + +Audit decoded and hashed all 217,860 unique files, with zero invalid files. +The existing versioned Rain quarantine excludes 1,155 source training records. +After discovery, 138 Snow records overlapping protected test content/groups +were excluded (132 train, 6 validation). All exclusions are recorded in the +manifest; no remaining record cap applies. Exact decoded RGB and source-group +isolation are verified; perceptual near-duplicate detection was not performed. + +Extra sources acquired: GoPro Large (2,103 train / 1,111 test pairs), DIV2K HR +(800 train / 100 validation images) and Flickr2K HR (2,650 images). The original +Snow100K test download was quota-blocked. The authors' [Histoformer dataset +mirror](https://github.com/sunshangquan/Histoformer#-datasets) supplied S/L test +partitions only (16,611 / 16,801 pairs); **test M is unavailable in this run**. +Receipts, archive hashes and pinned mirror revisions are retained under +`/home/vunguyen/data_bundle/phase1_seven_extra/`. Existing compressed/partial +archives and old checkpoints were not deleted. + +Physical GPU 5 is pinned by `ROCR_VISIBLE_DEVICES=GPU-8169d457412f2f76`, with +`HIP_VISIBLE_DEVICES` and `CUDA_VISIBLE_DEVICES` unset. Its PCI bus is decimal +171 (`AB`). Raw PyTorch ordinal 5 maps to another card on this host; the launcher +asserts exactly one visible GPU and the expected PCI identity before training. +The actual ROCm native-256 FP32 smoke passed five forward/backward steps at real +batch 16 / synthetic batch 4: steady mean 0.2984 seconds per step and peak allocated +2,472,867,840 bytes. This is a synthetic software smoke, not a measured full-data +throughput or restoration result. Receipt: `phase1_seven_extra/gpu5_smoke.json`. + +The fixed queue runs `full_seed42`, `no_composition_edges_seed42`, `rank1_seed42`, +`full_seed43`, `full_seed44` sequentially, each for five complete epochs. Each run +then evaluates all validation and test records plus 256 held-out controlled scenes +with evaluation seed 20260906. The summary includes only reports validated by the +queue; missing, partial or stale artifacts never contribute to seed means. + +All 86 selected CPU tests passed on the server's Python 3.12.14 / torch 2.10 ROCm +7.0 environment (GPU visibility disabled for CPU tests), covering the new pipeline +and legacy v5/v6 regressions. Independent review also exercised exact +interrupted/resumed equality, all trainable gradients and 25 focused operational +tests. No blocking HIGH/CRITICAL review finding remains. Deployment SHA and actual +run status accompany the launch handoff. This document contains no measured +model-quality claims yet. diff --git a/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_noise_trials_protocol.md b/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_noise_trials_protocol.md new file mode 100644 index 0000000000000000000000000000000000000000..93be913c642bb03d6335afe868445147f89c7068 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_noise_trials_protocol.md @@ -0,0 +1,63 @@ +# Noise-v2: hai lượt thử dữ liệu/sampling trên GPU5 + +Chốt ngày 2026-09-06 sau khi người dùng đồng ý thử. Đây là bước đầu của kế hoạch đánh giá lại Phase-1; **chưa sửa node, cạnh, model hoặc loss coefficients**, không chạy Phase-2 và không tự mở thêm seed/ablation. + +## Hai run và ngân sách + +| Run | Sampling trong lớp noise | Các loại khác | Seed | Ngân sách | +|---|---|---|---:|---| +| `noise_v2_uniform_seed42` | Permutation không replacement | Permutation cũ | 42 | 5 vòng × 89.913 draws | +| `noise_v2_balanced_seed42` | 50% real / 50% synthetic | Giữ nguyên record và vị trí từ lịch uniform | 42 | 5 vòng × 89.913 draws | + +Cả hai khởi tạo từ đầu, B16, native crop256, FP32, synthetic auxiliary batch4 mỗi bước, AdamW LR2e-4/weight_decay1e-4, gradient clip1, cùng cosine scheduler của trainer hiện tại. Mỗi run có **28.100 bước / 449.565 draws** nếu không skip. Mỗi vòng có last batch9, không drop-last. Không dùng `--max-train-records` hoặc `--max-steps` cho hai run chính. + +Hai noise-v2 run ngang ngân sách với nhau. V1 trước đó có 21.915 bước/350.620 draws: so sánh v2 với v1 là tham chiếu mô tả, **không phải ablation dữ liệu ngang compute**. Chỉ một seed cho sampling comparison, chưa đủ kết luận ý nghĩa thống kê. + +## Coverage và crop lặp + +Manifest noise-v2 có 242 record noise thật và 19.668 record synthetic; tổng 19.910 noise/vòng. Balanced giữ nguyên 19.910 vị trí noise trong lịch uniform và phân bổ 9.955 real + 9.955 synthetic. Không cân bằng lại cả bảy loại vì objective đã có inverse-frequency class weights; noise weight tính từ manifest gốc vẫn khoảng0,64514 ở cả hai run. + +Các queue cyclic có shuffle xác định theo seed bảo đảm đi hết source records trước khi lặp chu kỳ. Toàn bộ synthetic records được thăm hết trước cuối vòng2; các loại non-noise đầy đủ mỗi vòng. Real SIDD được lấy lặp là tăng số crop visits, không tăng số ảnh/cảnh vật lý. + +Sampler mang record index và visit number, không dùng bộ đếm cục bộ trong DataLoader worker. Các visit lặp được cấp RNG cho crop/flip/realization có thể tái lập; không lấy lại cố định một crop trong cùng vòng. Uniform/int-index giữ hành vi augmentation cũ. Resume dùng cùng seed, sampling mode, round/cursor và source hashes. + +Coverage ghi **draws, unique records và cumulative unique records** riêng. Không ghi nhầm89913unique cho mỗi vòng balanced. Run chỉ được queue chấp nhận khi đủ ngân sách,0skips và mọi record đã được thăm; thiếu coverage hoặc nonfinite steps là lỗi cần xem xét, không tự đổi cấu hình để qua kiểm tra. + +## Checkpoint và evaluation + +Checkpoint chính là **`last.pt` sau đủ budget**. Quick validation/best checkpoint của trainer vẫn chỉ là chẩn đoán; không chọn run hoặc đổi tỷ lệ sampling theo test. + +Mỗi run có bốn stage evaluation: + +1. `evaluation_reference_val_last.json`: toàn bộ3.696record validation v1 và controlled256scenes. +2. `evaluation_reference_test_last.json`: toàn bộ39.321record test v1 và controlled256scenes. +3. `evaluation_expanded_val_last.json`: toàn bộ4.747record validation noise-v2, tách nguồn, không chạy lại controlled trên nền ảnh khác. +4. `evaluation_expanded_test_last.json`: toàn bộ39.981record test noise-v2, tách nguồn, không chạy lại controlled trên nền ảnh khác. + +Eval seed20260906, B16, native crop256 và4workers. Báo cáo reference giữ cùng manifest/scene pool/controls với v1. Đọc clean origin/false positives, từng degradation, severity, content leakage, within-factor parameters, transfer với zero/shuffle, composition cả hai thứ tự, factor removal và OOD. Không gọi F1 tốt là disentanglement; đọc cả residual-statistics và pixel errors. + +Trong expanded evaluation, báo riêng: + +- SIDD thật40test captures; vẫn một physical scene test. +- PolyU thật40external pairs, không vào train; camera/object groups chưa được chứng minh hoàn toàn độc lập cảnh. +- Synthetic Gaussian và signal-dependent Gaussian, tổng600test records trên100nội dung ảnh sạch; severity là dose tổng hợp, không phải nhãn thật của SIDD/PolyU. + +Mỗi cohort positive-noise dùng **cùng pool non-noise negatives của parent** để tính precision/F1/AP, có pool hash, support và prevalence. Đồng thời báo recall/noise scores trên positives và false positives theo từng domain âm. Không dùng một tập chỉ có noise positives để báo “precision cao”. + +## Provenance và an toàn vận hành + +Training manifest: `/data/vunguyen13/SCDC_data/phase1_noise_20260906/manifest_noise_v2.json`, SHA256 `93212a3f2fa35db6511925c883c2c16a648a19dbe714fb76fd88c1f150d46c9f`. + +Reference parent: `/home/vunguyen/data_bundle/phase1_seven_extra/manifest_v1.json`, SHA256 `8f7be16638ee544eb97245871ce1c6d884920bb2973c14a64a09e4db64f88e24`. Kiểm hash và nguyên vẹn mọi prefix train/val/test trước khi chạy. + +Chỉ dùng physical **GPU5**, UUID `GPU-8169d457412f2f76`, PCI bus171; không dùng raw ordinal5. Queue mới phải đợi `/home/vunguyen/SCDC/outputs/phase1_clean_relative_seven_20260906` completed đủ năm run. Dùng chính GPU lock của queue cũ kể cả khi output ở volume khác; child kế thừa lock. Kiểm lại predecessor sau khi lấy lock. Không kill/dừng/restart process khác. + +Nguồn v1 `/home/vunguyen/SCDC_releases/phase1_seven_efdaf6e` được giữ nguyên. Nguồn thử mới ở release riêng sau review/commit; không rsync nóng khi đang train. Cấu hình, source, checkpoint/manifest hashes được khóa khi resume. + +Release mới clone label tensors giữ cho evaluation để tránh giữ shared-memory file descriptors. Giữ soft `RLIMIT_NOFILE=65536` đã được phép; không tăng tiếp. Tiến trình train chính và heartbeat chỉ khởi động run khi predecessor/lock/provenance hợp lệ. + +## Điều kiện kết luận và bước sau + +So sánh balanced với uniform trên legacy fixed test và từng nguồn noise; không dùng F1 gộp synthetic để che suy giảm trên real. Kiểm tra các domain khác có bị giảm, clean FP/content leak có tăng và SIDD/PolyU có cùng cải thiện không. Kiểm chứng quan hệ/node là các phép đo, không giả định data expansion đã sửa kiến trúc. + +Giữ các hạn chế: SIDD Medium chưa phải Full; cùng10cảnh vật lý, chỉ8train; profile synthetic chưa bao phủ read/shot độc lập hoặc sigma50; RESIDE local subset; Snow test S/L thiếuM; một crop mỗi ảnh; trial5vòng chưa chứng minh hội tụ. Sau hai run mới quyết định thí nghiệm node bypass hoặc functional composition. Không tự nối thêm training kiến trúc mới. diff --git a/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_pipeline_reassessment_noise_v2.md b/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_pipeline_reassessment_noise_v2.md new file mode 100644 index 0000000000000000000000000000000000000000..0007d893e48ecc394844e311da0bb3b7be23376a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/docs/phase1_pipeline_reassessment_noise_v2.md @@ -0,0 +1,179 @@ +# Phase-1: mở rộng noise và đánh giá lại thiết kế + +Ngày: 2026-09-06. Audit dựa trên source đóng băng `efdaf6e74d81030e11dc1451ddc34a0878d5e03a` và hai full-model seed 42/43 đã hoàn tất. Thay đổi trong nhánh noise-v2 chỉ liên quan dữ liệu; không nóng sửa model, objective hoặc run đang train. Các thí nghiệm bên dưới là đề xuất, chưa được chạy. + +## Kết luận chính + +Thiếu noise thật là một vấn đề thực tế, nhưng không giải thích hết các kết quả Phase-1. Phiên bản hiện tại có decomposition clean-relative, song **chưa buộc dự đoán/tái tạo suy giảm phải đi qua đúng node**, và **chưa buộc cạnh tạo ra đúng tác dụng của một tổ hợp suy giảm**. Cần tách cải thiện dữ liệu khỏi thay đổi kiến trúc/objective để biết điều gì có hiệu quả. + +Định nghĩa nên hướng tới là mã *tham số/toán tử suy giảm* có thể chuyển giữa các cảnh, tách khỏi *tác động quan sát được trên ảnh*. Noise phụ thuộc tín hiệu và haze phụ thuộc ảnh sạch; không phải mọi residual vật lý đều phải độc lập với content. + +## 1. Vì sao noise ít và mở rộng có thể sửa điều gì + +Manifest v1 dùng SIDD Small: 121 cặp train trên 8 cảnh vật lý, 19 cặp validation trên 1 cảnh, 20 cặp test trên 1 cảnh. Mỗi record được lấy một crop native 256×256/epoch. Run 5 epoch vì thế chỉ có **605 lượt crop noise thật**, ngoài noise tổng hợp online. + +[RESIDE](https://sites.google.com/view/reside-dehaze-datasets/) là bộ dữ liệu dehazing, không phải bộ cặp noisy/clean cho denoising. Có thể lấy ảnh sạch từ đó để tạo noise tổng hợp, nhưng ảnh haze có sẵn không được đổi nhãn thành noise. Lần mở rộng này dùng DIV2K/Flickr2K làm nền sạch theo recipe DA-CLIP và giữ RESIDE ở nhóm haze. + +Noise chiếm 0,17255% trong 70.124 record train; Snow chiếm 67,5503%. Với shuffle thông thường và B16, xác suất một batch có noise thật xấp xỉ 2,73%. Trọng số loss noise 82,791 không bổ sung ảnh, cảnh hay lượt lấy crop. Root/content loss cũng không có cùng trọng số theo loại. Nền sạch của synthetic controls được lấy từ batch real nên vẫn chịu lệch nguồn. + +SIDD Medium có 320 cặp nhưng vẫn 10 cảnh vật lý; nó tăng số lần chụp, không nhân đôi số cảnh. PolyU OriginalImages được giữ cho external test, không đưa các crop dẫn xuất của nó vào train. DIV2K/Flickr2K bổ sung nền sạch đa dạng cho noise tổng hợp, dùng đúng split đang có của từng ảnh sạch để không rò rỉ content giữa JPEG và noise. + +Với PolyU, group trong manifest là camera/object filename của ảnh nguồn. Chưa kiểm tra độc lập cảnh vật lý giữa mọi camera; không suy số group này thành số quan sát thống kê độc lập. SIDD thì dùng physical-scene ID do dataset cung cấp. + +Nguồn: + +- [SIDD của tác giả](https://abdokamel.github.io/sidd/): Small 160 cặp, Medium 320 cặp; Full khoảng 24.000 noisy training shots, không phải 24.000 cảnh. License MIT. Nguồn tải Medium được kiểm tra là HTTP; lưu SHA256 quan sát và kiểm CRC, không tuyên bố có xác thực mật mã từ checksum tác giả. +- [PolyU, phiên bản cố định](https://github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset/tree/3af0f2646b267a00446fe4b7113a15e67bc80b4e): phân biệt 40 cặp OriginalImages với 100 cặp crop dẫn xuất. Giữ [license phi thương mại/nghiên cứu](https://github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset/blob/3af0f2646b267a00446fe4b7113a15e67bc80b4e/License.txt). Chỉ các ảnh decode hợp lệ mới được nhận, có audit cho mọi loại bỏ. +- [DA-CLIP dataset recipe](https://github.com/Algolzw/daclip-uir#dataset-links): dùng DIV2K/Flickr2K để tạo noisy/JPEG. Đây không phải cùng phân phối với nhiễu cảm biến SIDD. + +### Kết quả mở rộng đã kiểm chứng trên server + +| Dữ liệu / split | Train | Validation | Test | +|---|---:|---:|---:| +| Noise thật v1 — SIDD Small | 121 | 19 | 20 | +| SIDD sau hợp nhất Small + Medium, loại trùng | 242 | 38 | 40 | +| PolyU ngoài miền | 0 | 0 | 40 | +| Noise tổng hợp DF2K, số record | 19.668 | 1.032 | 600 | +| Nội dung ảnh sạch DF2K riêng biệt theo decoded RGB | 3.221 | 170 | 100 | +| Tổng record của cả 7 loại trong manifest mới | 89.913 | 4.747 | 39.981 | + +Đã decode thành công toàn bộ **720 file của 360 cặp mới** và đọc/hash lại **3.550 đường dẫn nền sạch**. Trong 320 cặp Medium có 160 cặp trùng decoded noisy+clean với Small: nhận thêm 160 cặp SIDD và 40 cặp PolyU, không có ảnh hỏng hoặc xung đột split cần loại. Các file nguồn không bị xóa; 160 cặp trùng được ghi trong quarantine của phần bổ sung. + +3.550 đường dẫn DF2K tương ứng 3.491 nội dung RGB riêng biệt: có 57 đường dẫn lặp nội dung trong train và 2 trong validation, đã tồn tại ở parent. Giữ nguyên parent; sáu record theo profile×dose trên mỗi đường dẫn là **biến thể synthetic**, không phải sáu cảnh mới. Tổng phần thêm là **21.500 record noise = 200 cặp thật + 21.300 record synthetic**. Toàn bộ 134.641 ID là duy nhất; không có clean hash hoặc dataset/group tràn qua split. + +Noise nay chiếm 22,1436% record train, nhưng **98,7845% record trong chính lớp noise là synthetic**; noise thật chỉ chiếm 0,26915% toàn train. Nếu giữ `class_weights` hiện tại, trọng số noise tự giảm từ **82,791 xuống 0,64514** vì hàm này cân bằng loại, không cân bằng real/synthetic trong cùng loại (`train_phase1_clean_relative.py:47`). Vì vậy không được hiểu “thêm dữ liệu” là tự động tăng mức ưu tiên cho noise thật. Đây là lý do cần ablation sampling real/synthetic riêng và báo chất lượng trên noise thật riêng trước khi chọn recipe. + +## 2. Pipeline đang thực sự chạy + +Ảnh I đi qua spatial CNN và wavelet. Một bank learned queries đọc hai nguồn bằng attention, rồi trao đổi qua query self-attention. Chỉ trạng thái query 0 được lấy làm global feature h. Từ đó có: + +- `c(I)`: feature map spatial H/8; +- `Δ(I) = W h(I)`: mã global 256 chiều; +- `a_k = U_kᵀΔ`: tọa độ chiếu vào 7 known node và 2 free node; +- đóng góp của node `U_k a_k` và residual trực giao; +- các head presence, severity, photometric và decoder đều có thể đọc toàn bộ Δ. + +Nguồn: `src/models/graph_encoder/clean_relative.py`, `_evidence`, `decompose`, `_representation`, `compose`, `decode`. + +| Thành phần | Thiết kế ban đầu mong muốn | Hiện tại | +|---|---|---| +| Key của node | Bộ dò U_k tham gia routing theo degradation | U_k là basis chiếu sau global descriptor; attention đọc ảnh dùng learned queries khác | +| Value | Tọa độ biến thể trong đúng node | Có coefficients và basis contribution; consumer vẫn có thể đọc toàn bộ Δ | +| Severity | Một trục/coefficient có nghĩa vật lý | Giám sát norm của coefficients, đồng thời có head severity riêng trên Δ | +| Cạnh | Tương tác có tác dụng kiểm được lên ảnh | MLP trên hai toàn bộ Δ + type IDs, học latent MSE | +| Họ cha–con | Shared/private basis theo họ | Chưa có; một QR chung ép các basis trực giao | +| Free/OOD | Giải thích phần chưa biết và phát hiện OOD | Free/residual bị regularize mềm; OOD probe dùng 1−max presence, không dùng residual norm | +| Giao diện Phase-2 | Adapter cho legacy 8×256 | Hiện xuất 9 node contributions ×256 + residual; chưa tích hợp Phase-2 | + +## 3. Điểm cần sửa trong định nghĩa node + +### 3.1 Phép trừ theo cặp chưa tự triệt tiêu content + +Teacher dùng cùng linear head: + +`Δ_teacher(I,J) = W[h(I)−h(J)] = Δ(I)−Δ(J)`. + +Đây là một reference theo cặp, không phải teacher độc lập cung cấp tri thức degradation khác student. Phép trừ feature phi tuyến không bảo đảm content triệt tiêu. Giá trị số của distillation error tương ứng clean Δ, nhưng target bị detach nên gradient không giống một root loss trực tiếp độc lập trên clean encoder. + +`c(I)≈c(J)` chỉ ép consistency của c; không ngăn Δ đồng thời chứa content. Trong probe dự đoán thumbnail sạch 4×4 RGB trên các cảnh tách biệt, thêm Δ vào baseline type×severity giảm MSE **46,06% ở seed42 và 47,88% ở seed43**. Đây là bằng chứng về một kênh thông tin content cụ thể, không phải phép đo mutual information hay chứng minh mọi phụ thuộc content đều vô ích. + +Teacher `(J,J)` bằng 0 theo cấu trúc, nhưng blind encoder của ảnh sạch chưa đạt cùng điều đó: clean false-positive là **8,34%/8,87%**, mean‖Δ(J)‖ là **1,6856/1,7007**. Norm phụ thuộc thang latent/parameterization; không dùng riêng trị số tuyệt đối ấy để quy nguyên nhân thất bại. + +### 3.2 Node chưa phải đường bắt buộc + +Presence/severity heads đọc toàn bộ Δ (`model:211–212,289–292`), decoder cũng vậy (`220,370–374`). Invariance xuyên content chỉ phủ coefficients của 7 known nodes (`trainer:365`), không phủ free/residual. Vì thế kiến trúc cho phép thông tin đi vòng qua node được định danh. + +Chưa đo phân bổ năng lượng nên **chưa chứng minh residual là thủ phạm**. Thí nghiệm phù hợp là đo năng lượng known/free/residual rồi so sánh consumer nhận known coefficients, residual-on/off và full Δ, không mặc định phải bỏ residual hoàn toàn. + +Rank1 không phải baseline thuần class×severity hoặc cùng dung lượng: Δ vẫn 256 chiều, không gian bù danh nghĩa tăng từ 184 lên 247 chiều; không gian Δ thực có thể đạt còn bị linear head 128→256 giới hạn. + +### 3.3 Origin proxy hiện là clean autoencoder + +Proxy đang đo `G(c(J),0)≈J`, tức đầu vào content đã lấy từ ảnh sạch (`trainer:294`; `eval:125`). Nó **không phải** kiểm tra `G(c(I),0)≈J` từ ảnh hỏng. Vì vậy PSNR origin khoảng 22,5 dB không chứng minh xóa Δ sẽ làm sạch ảnh hỏng. + +Cần bổ sung test dirty-content/zero-Δ và can thiệp: bỏ factor k có xóa đúng k, đồng thời giữ các factor còn lại không? Đây mới gần với định nghĩa vận hành của node. + +## 4. Điểm thiếu trong học quan hệ + +Trong `synthetic_objective`: + +1. Single/second/mixed gọi `pair_objective(...include_anchor=False)` (`trainer:354–355`). +2. Proxy nằm trong nhánh `include_anchor`, nên không được áp dụng cho ba nhánh này (`286–297`). +3. Composed code chỉ học MSE với mixed teacher code detach (`359–362`). +4. Decoder transfer chỉ được học cho single đầu tiên (`368–370`), chưa cho composed code. +5. Factor removal được đo trong evaluation nhưng chưa có loss can thiệp tương ứng trong training. + +Vì vậy encoder và edge có thể học khớp latent mà decoder chưa bị buộc thực hiện đúng tác dụng của tổ hợp. Đây là giả thuyết cơ chế từ code, không phải chứng minh nguyên nhân duy nhất của số đo. + +| Heldout pairs, cả hai thứ tự | Learned edge | Own additive baseline | Edge tăng lỗi | +|---|---:|---:|---:| +| Full seed42 | 0,02868761 | 0,02332736 | 22,98% | +| Full seed43 | 0,02798944 | 0,02263501 | 23,66% | + +Đây là count-weighted **lỗi 15 thống kê residual** trên 256 cảnh × 3 cặp × 2 thứ tự. Mọi cặp đo đều có rain/noise/snow. Không phải PSNR hoặc pixel L1: aggregate forward pixel L1 cải thiện nhưng reverse pixel L1 xấu hơn ở cả hai seed. Không được kết luận mọi metric đều xấu đi hoặc pixel error tổng thể đều tốt lên. Mixture controls dùng strength trong miền train; nhãn heldout-severity chỉ áp dụng controlled singles. Cả hai thứ tự của seen pairs đều đã được train, chưa có kiểm tra thứ tự bị giữ lại độc lập. + +Thí nghiệm tiếp theo cho cạnh phải thêm functional loss trên `G(c, compose(Δ_a,Δ_b))`, so với đúng ảnh tổng hợp theo thứ tự; tách metric ảnh và metric phân phối/thống kê của noise. Chỉ thử sau khi single-node semantics được kiểm tra. + +## 5. Noise còn thiếu gì ngoài số lượng + +Recipe cũ cố định `sigma=.12*s`, `shot=.04*s`; read/shot luôn cùng thay đổi theo một scalar severity. Thêm nhiều ảnh sạch với nguyên recipe đó không chứng minh node rank8 học được các biến thể noise nhiều chiều. + +Hai profile noise-v2 tạo coverage rõ ràng hơn nhưng cũng chưa phải toàn bộ camera/ISP/noise distribution. Cần một bài kiểm tra riêng với read/shot thay đổi độc lập, correlation/màu và realization khác nhau, giữ profile giống nhau khi đổi content. Với real noise không có target vật lý, giữ severity mask unknown, không suy ISO hoặc nhãn dataset thành severity giả. + +Cụ thể, Gaussian noise-v2 có `sigma=.12*s`, với `s∈{.2,.4,.6}`: tương đương σ **6,12 / 12,24 / 18,36** trên thang 0–255 trước clipping. Profile phụ thuộc tín hiệu dùng `sigma=.02*s`, `shot=.12*s` và variance `sigma²+shot²*clean_RGB`. Đây là hai đường tham số cố định, không phải lưới read/shot độc lập. Ta tham khảo **nguồn nền sạch** từ DA-CLIP, chưa tái lập protocol noise-level 50 được ghi trong [script sinh LQ của DA-CLIP](https://github.com/Algolzw/daclip-uir/blob/main/scripts/generate_LQ.py). Cần thêm evaluation theo σ vật lý rộng hơn trước khi kết luận về noise nặng; không coi dose chuẩn hóa giữa các profile là cùng mức residual quan sát được. + +Decoder deterministic hiện khớp 15 thống kê residual (mean/std và gradient/Laplacian RMS), không mô hình đầy đủ phân phối corruption có điều kiện. Noise seed được dùng lại trong matched-parameter transfer; cần thêm test đổi realization. Eval v1 cố ý đánh dấu within-factor noise probe unsupported vì không có non-dose target độc lập. + +Một hạn chế nhãn khác: real dataset trả one-hot theo domain. Ảnh LOL có thể còn noise, nhưng nhãn hiện coi noise absent. Cần phân biệt nhãn domain với multi-label cơ chế vật lý; synthetic multi-hot chưa sửa được mọi nhãn âm không chắc của ảnh real. + +## 6. Những tín hiệu tích cực và giới hạn + +| Probe full model | Seed42 R² | Seed43 R² | +|---|---:|---:| +| Haze airlight, thêm coefficients ngoài severity | 0,3911 | 0,2533 | +| Blur orientation | −0,0600 | 0,1902 | +| Rain orientation | −0,0460 | −0,0072 | + +Haze có tín hiệu lặp lại; blur có tín hiệu phụ thuộc seed, không thể nói hoàn toàn không học được. Test noise F1 0,1242/0,1556 chỉ có support20; seed43 recall0,70 nhưng precision0,0875. F1 thấp không đơn giản nghĩa là model không nhận biết noise; nhiều false positive đến từ domain khác, nhất là Rain/Snow. + +Cả 7 severity regressions đều có R² âm trên controlled singles ngoại suy: train strength [0,08;0,70], test [0,80;0,98]. Noise MAE là 0,18208/0,21443. Đây là thất bại của phép thử ngoại suy cụ thể, với target variance nhỏ; không chứng minh model không học severity trong miền train. Evaluation tiếp theo cần tách interpolation và extrapolation. + +Các kết quả này mới 5 epoch, chưa chứng minh hội tụ. OOD hiện chỉ là central-gray-occlusion probe; chưa có leave-type/family-out retraining. V1 còn giới hạn RESIDE subset, SIDD Small, Snow test S/L thiếu M và một crop cố định mỗi ảnh real. Noise-v2 không tự sửa các giới hạn của những bộ còn lại. + +## 7. Chuỗi thí nghiệm nên làm sau data expansion + +1. **Data-only:** giữ nguyên model/objective, khởi tạo from-scratch cùng seed; đánh giá lại trên legacy test cố định, expanded real-noise và synthetic-noise riêng. Không gộp hàng trăm synthetic samples vào để che kết quả noise thật. Tách `expanded-real-only` và `expanded-real+synthetic` nếu cần quy đóng góp: thêm synthetic records cũng bổ sung target severity và thay đổi phân bố noise profiles, không chỉ tăng ảnh SIDD; chưa có head/loss phân loại profile riêng. So sánh matched optimizer-step budget; 5 epoch trên manifest lớn không phải cùng compute. Nếu dùng full-coverage budget thì báo riêng. +2. **Sampling-only:** giữ data/model, thử cân bằng loại rồi cân bằng real/synthetic noise, chọn scene→capture→crop; tăng crop exposures của ảnh noise thật. Báo exposure và số ảnh/cảnh riêng. Không trộn đây vào ablation data-only. +3. **Node-only:** energy audit, consumer restriction/residual ablations; test `G(c(I),0)`, drop-one/retain-others, parameter probe ngoài severity, đổi realization giữ noise profile. +4. **Relation-only:** explicit mixed/composed functional loss; addition vs ordered correction, heldout pairs và thứ tự; chỉ thay objective này trong lượt so sánh tương ứng. +5. **Family/open-set:** sau khi node có ý nghĩa kiểm được, mới thử shared/private family basis và leave-type/family-out. Adapter Phase-2 là một thí nghiệm riêng. + +Phần data-only cần giữ model/objective cũ nhưng dùng loader biết schema noise mới. Manifest mới dùng **schema 2**: frozen loader v1 sẽ từ chối ngay ở bước kiểm schema, trước khi có thể đọc nhầm ảnh nguồn sạch thành noisy image. Loader mới vẫn đọc được manifest v1; hạ schema của record noise tổng hợp xuống v1 cũng bị từ chối. Cũng không tái sử dụng nguyên launcher v1 vốn khóa manifest/source hash và ngân sách. Chưa khởi chạy bất kỳ training noise-v2 nào trong thay đổi này. + +## 8. Artifact, tái lập và kiểm chứng + +Nhánh dữ liệu riêng: `codex/phase1-noise-expansion`. Bản v1 đang chạy vẫn dùng release `/home/vunguyen/SCDC_releases/phase1_seven_efdaf6e`; không sửa release này, checkpoint, GPU mapping hoặc queue. Không tải SIDD Full trong đợt này, không sửa model/trainer/evaluator/sampler, không khởi chạy training noise-v2. + +Server `kim.long-mi325x8`: + +```text +Data root: /data/vunguyen13/SCDC_data/phase1_noise_20260906 +Code: /data/vunguyen13/SCDC_data/phase1_noise_20260906/code +Manifest: /data/vunguyen13/SCDC_data/phase1_noise_20260906/manifest_noise_v2.json +Audit: /data/vunguyen13/SCDC_data/phase1_noise_20260906/manifest_build.audit.json +CPU check: /data/vunguyen13/SCDC_data/phase1_noise_20260906/actual_loader_verification.json +Python: /home/vunguyen/miniforge3/envs/mavt/bin/python +``` + +Manifest SHA256: `93212a3f2fa35db6511925c883c2c16a648a19dbe714fb76fd88c1f150d46c9f`. + +Parent SHA256 không đổi: `8f7be16638ee544eb97245871ce1c6d884920bb2973c14a64a09e4db64f88e24`. + +Các receipt tải/giải nén cùng root giữ URL, license, kích thước và SHA256 quan sát. Hai archive được verifier đọc và hash lại độc lập: + +- SIDD Medium, 13.234.744.070 byte: `4387022a7bf1a35e2ebdc0c1c09697a5f964ea102b7fdcf5c0d8a38a1b233f98`. +- PolyU, 134.609.548 byte: `30a5c5739af1b27b3d3b8f68c1e2b00d0dd8d1ab836bb545377fe0e4dbfdd477`. + +95 test tập trung pass trên local và server; reviewer độc lập chạy 124 test liên quan/legacy đều pass. Kiểm tra CPU trên ảnh thật pass 21 so sánh loader cũ/mới (7 loại × 3 split) và 13 mẫu đại diện noise theo source/profile/split: đúng native crop 256, không có identity giả, real severity không bị gán giả, noise tổng hợp đổi realization theo epoch train và replay cố định khi eval. Đây là smoke test đại diện cho loader, **không phải** đánh giá model trên toàn bộ manifest; kiểm decode/hash của dữ liệu mới là đầy đủ. + +Kiểm tra hash trong bộ mở rộng luôn decode mới, bỏ qua cache theo size/mtime của helper cũ. Có regression test thay pixel nhưng giữ nguyên size và timestamp. Manifest được publish nguyên vẹn, từ chối overwrite; source hashes của generator/helper/loader nằm trong audit. Mọi record và split của parent được giữ nguyên và đã được verifier kiểm trực tiếp. diff --git a/dataset/phase1_noise_20260906/trial_code_staging/docs/project_progress_and_ideas_2026-08-30.md b/dataset/phase1_noise_20260906/trial_code_staging/docs/project_progress_and_ideas_2026-08-30.md new file mode 100644 index 0000000000000000000000000000000000000000..ee3dea2ac39ede8229e2e18ca7120955cff908a4 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/docs/project_progress_and_ideas_2026-08-30.md @@ -0,0 +1,1537 @@ +# SCDC — Cập nhật tiến độ và hướng phát triển + +**Ngày cập nhật:** 2026-08-30 + +**Phạm vi:** Phase 1 graph representation và Phase 2 residual-shift diffusion + +**Trạng thái tổng quát:** Phase 1 và Phase 2 v4 đã train; Phase 2 v5 đã implement và kiểm thử nhưng chưa train. + +## 1. Ý tưởng trung tâm + +SCDC được thiết kế theo hai phase có vai trò tách biệt: + +1. **Phase 1 học biểu diễn degradation liên tục**, không phải một classifier triển khai độc lập. +2. **Phase 2 dùng biểu diễn đó để điều khiển restoration diffusion** mà không cần degradation label khi inference. + +Giả thuyết hiện tại là Phase 1 đã tạo được guidance hữu ích, nhưng một shared restoration trunk duy nhất chưa đủ để tránh xung đột giữa rain, noise, haze và lowlight. Vì vậy, hướng tiếp theo là giữ content path dùng chung, đồng thời bổ sung soft gating và expert capacity theo degradation. + +## 2. Snapshot tiến độ + +| Hạng mục | Trạng thái | Kết luận ngắn | +|---|---|---| +| Dataset và split audit | Hoàn tất | 18.261 train, 317 validation; không phát hiện exact leakage train–validation | +| Phase 1 graph encoder | Đã train | Checkpoint tốt nhất ở epoch 20; routing mạnh, severity representation còn chưa đồng đều | +| Phase 2 v4 D0/null | Đã train | Control không dùng guidance, dừng ở 4.000 steps | +| Phase 2 v4 D5/full | Đã train | 20.000 steps; tốt nhất tại step 1.000, sau đó có cross-domain drift phù hợp giả thuyết task interference | +| Visualization v4 | Hoàn tất | Đã xuất overview, từng degradation và learning dynamics | +| Phase 2 v5 gating | Đã implement/test | Router, prompts, expert adapters và optional noise bank đã sẵn sàng | +| Experiment harness v5 | Chưa hoàn tất | Thiếu gate diagnostics, per-domain selector, generic freeze và ablation hooks | +| Training/evaluation v5 | Chưa chạy | Chưa có output directory, checkpoint hoặc metric v5 | +| Mixed/unknown degradation | Chưa đánh giá | Cần protocol và manifest riêng | + +## 3. Dữ liệu và tính toàn vẹn split + +### 3.1 Phân bố hiện tại + +| Degradation | Train | Validation | Tỷ lệ trong train | +|---|---:|---:|---:| +| Rain | 12.556 | 98 | 68,76% | +| Haze | 4.895 | 100 | 26,81% | +| Lowlight | 689 | 100 | 3,77% | +| Noise | 121 | 19 | 0,66% | +| **Tổng** | **18.261** | **317** | **100%** | + +Nguồn dữ liệu chính gồm Rain13K, RESIDE, LOLv2 và SIDD. Raw dataset mất cân bằng mạnh, đặc biệt với noise; trainer sử dụng deterministic four-domain balanced sampler với replacement và seed có thể replay. + +Locked test của Phase 1 có 1.220 mẫu, nhưng chỉ gồm 1.200 rain và 20 noise. Haze và lowlight có support bằng 0, vì vậy metric tổng trên locked test không được xem là bằng chứng cho cả bốn domain. + +### 3.2 Leakage audit + +- Đã quarantine 1.155 cặp Rain13K có nguy cơ trùng clean content. +- Train và validation có overlap bằng 0 theo `record_id`, `clean_content_sha256`, `split_group`, clean path, degraded path và `source_id`. +- Toàn bộ 37.156 image references trong manifest đều tồn tại tại thời điểm audit. +- Checkpoint khóa đúng train/validation digest; Phase 2 không đọc locked test trong quá trình train. + +Kết luận: **không phát hiện exact leakage**. Tuy nhiên, hash/source isolation không chứng minh được rằng không tồn tại perceptual near-duplicate; nếu cần benchmark công bố, nên bổ sung embedding-based near-duplicate audit. + +Manifest chuẩn: + +```text +outputs/phase2_graph_resshift_v4/train_val_manifest_v1.json +train digest: 769bcff66a209ffbf5195868f7f479309f1350a5bfb367c9e2c3a94d43cbba46 +val digest: 86f0c9723a4c89da6ed1be0da487094bc2938dd5e97e5c5ab68369bd16f8c38d +``` + +## 4. Phase 1 — representation learner + +### 4.1 Vai trò + +Tại inference, toàn pipeline chỉ nhận degraded image; clean target và degradation label không đi vào model conditioning. Khi train Phase 2, clean image vẫn được dùng làm target `x0`, còn label chỉ phục vụ balanced sampler và diagnostics. Phase 1 encoder được freeze hoàn toàn trong Phase 2. + +Biểu diễn đầu ra gồm: + +- content latent; +- 6 node tokens kích thước 256: 4 semantic nodes theo thứ tự `rain/noise/haze/lowlight` và 2 free nodes; +- soft routing posterior; +- 4 continuous severity coordinates; +- 4 spatial maps kích thước `16 × 16`; +- unknown residual; +- global condition 256 chiều. + +Objective học biểu diễn kết hợp route NLL, auxiliary type probe, severity regression, inactive suppression, clean-root anchoring, clean/degraded content consistency, spatial residual supervision và free/unknown suppression. Vì vậy accuracy chỉ là diagnostic probe cho separability, không phải mục tiêu cuối của Phase 1. + +### 4.2 Kết quả đã train + +Phase 1 được train 50 epochs, 500 steps mỗi epoch. Checkpoint được chọn theo validation macro-F1 và đạt tốt nhất tại epoch 20: + +| Metric validation | Giá trị | +|---|---:| +| Accuracy | 0,99369 | +| Balanced accuracy | 0,98429 | +| Macro-F1 | 0,98947 | +| Loss | 0,27624 | +| Severity Spearman | 0,27229 | + +Routing đã tách domain tốt, nhưng severity representation tại checkpoint được chọn còn yếu và không đồng đều. Trên locked test rain/noise, severity Spearman tổng là 0,85930 nhưng bị chi phối bởi rain: rain đạt 0,88265 trong khi noise là -0,03008 với chỉ 20 mẫu. + +Điều này dẫn đến hai kết luận: + +1. Phase 1 có tín hiệu đủ hứa hẹn để kiểm nghiệm soft prior cho restoration trong v5. +2. Không nên hard-classify degradation hoặc xem accuracy cao là bằng chứng representation đã hoàn thiện; severity, composition và unknown generalization vẫn cần đánh giá riêng. + +Checkpoint chuẩn: + +```text +outputs/phase1_graph_rain13k_v1/graph_encoder_best.pt +symlink: outputs/graph_encoder_best.pt +epoch: 20 +SHA256: cad4752262700052cc725d27a569e919773c53e745d5f1db97ad103e418f59d0 +``` + +### 4.3 Rủi ro source-of-truth + +Canonical Phase 1 source hiện có trên server trong: + +```text +train_graph_encoder_v2.py +src/models/graph_encoder/ +src/data/rain13k_quarantine_v1.json +``` + +Các file này chưa đầy đủ trong local repo. Cần đồng bộ và đưa vào version control trước khi tiếp tục thay đổi Phase 1 hoặc tái lập training từ local. + +## 5. Phase 2 v4 — shared graph-conditioned ResShift + +### 5.1 Kiến trúc + +- Ảnh được biến đổi lossless bằng pixel-unshuffle 2× thành state 12 channels. +- U-Net dự đoán trực tiếp clean state `x0` từ `[u_t, u_y, u_t - u_y]`. +- Bốn scale có width `[64, 128, 192, 256]`. +- Residual-shift schedule có 8 reverse steps và exact posterior. +- `kappa = 0,1160798129`, được calibrate trên 4.096 ảnh train, cân bằng theo domain. +- Phase 1 cung cấp context tokens, global AdaGN vector, content feature và spatial feature; không có hard degradation class trong forward path. +- Objective Phase 2 v4 là FP32 `x0` MSE. + +Hai control arm đã train: + +- **D0/null:** cùng kiến trúc nhưng bỏ Phase 1 guidance. +- **D5/full:** dùng đầy đủ graph representation. + +### 5.2 Kết quả chính + +| Model/checkpoint | Macro PSNR | Macro SSIM | +|---|---:|---:| +| Degraded baseline | 18,91395 | 0,55101 | +| v4 D0 best, step 1.000 | 21,99527 | 0,64531 | +| v4 D5 best, step 1.000 | **22,03713** | **0,65801** | +| v4 D5 final, step 20.000 | 21,42193 | 0,63898 | + +D5 chỉ hơn D0 `+0,04186 dB`, nhưng tăng SSIM `+0,01270`. Guidance vì vậy có tín hiệu hữu ích, song tác động không đồng đều giữa các domain. + +| Domain | Degraded | D5 best @1k | D5 final @20k | +|---|---:|---:|---:| +| Haze | 17,307 / 0,8287 | **23,044 / 0,8798** | 21,102 / 0,8774 | +| Lowlight | 9,766 / 0,1946 | **17,149 / 0,5952** | 10,380 / 0,2351 | +| Noise | 27,329 / 0,5075 | 27,070 / 0,5057 | **31,878 / 0,7005** | +| Rain | 21,254 / 0,6733 | 20,885 / 0,6513 | **22,328 / 0,7429** | + +Mỗi ô là `PSNR / SSIM`. + +### 5.3 Diễn giải + +- Step 1.000 tối ưu cho haze và lowlight nhưng làm noise/rain giảm nhẹ so với degraded input. +- Đến step 20.000, noise và rain cải thiện rõ, trong khi lowlight gần như sụp về baseline. +- Best-to-final drift là `-0,615 dB` macro PSNR. + +Kết quả một seed này **phù hợp với giả thuyết** task interference và optimization drift trong shared restoration trunk, nhưng chưa chứng minh quan hệ nhân quả. Imbalance, oversampling, loss hoặc schedule cũng có thể tạo ra drift tương tự. Working hypothesis hiện tại là Phase 1 có tín hiệu hữu ích, còn Phase 2 cần capacity/routing riêng hơn; cần xác nhận bằng multi-seed ablation và gradient-conflict diagnostics. + +Checkpoint chuẩn: + +```text +D5 best: outputs/phase2_graph_resshift_v4/gate_d5_seed42/best.pt +step: 1.000 +SHA256: 77d6f6ebf547bdc8ff6ef3c309005083a5d088380cf6abfac7179b972f29799c + +D5 final: outputs/phase2_graph_resshift_v4/gate_d5_seed42/last.pt +step: 20.000 +SHA256: 017c0126f5003a9010d50ce5222778780ad409f4a7c7762aa9cc59d8abefa72b +``` + +Visualizations: + +```text +outputs/phase2_graph_resshift_v4/visualizations_seed42/overview_all_tasks.png +outputs/phase2_graph_resshift_v4/visualizations_seed42/task_{haze,lowlight,noise,rain}.png +outputs/phase2_graph_resshift_v4/visualizations_seed42/learning_dynamics.png +outputs/phase2_graph_resshift_v4/visualizations_seed42/visualization_report.json +``` + +## 6. Phase 2 v5 — degradation-aware soft gating + +### 6.1 Trạng thái + +V5 đã được implement và vượt qua full Phase 2 regression suite `105/105` trên local và server. Hiện **chưa có training run, checkpoint hoặc metric v5**. + +Các file chính: + +```text +train_phase2_gated_resshift_v5.py +src/models/restoration/gated_graph_resshift_v5.py +tests/test_gated_graph_resshift_v5.py +tests/test_phase2_v5_trainer.py +``` + +### 6.2 Luồng điều khiển + +```mermaid +flowchart LR + Y[Degraded image y] --> P1[Frozen Phase 1] + P1 --> C[Content/global/spatial representation] + P1 --> D[Nodes/routing/severity/unknown] + D --> R[Soft degradation router] + R --> G[5 gates: rain, noise, haze, lowlight, generic] + C --> U[Shared ResShift U-Net] + G --> T[Noise/time prompt] + G --> A[7 expert adapter banks] + G --> N[Optional Gaussian stream mixer] + T --> U + A --> U + N --> Q[Forward corruption] + Q --> U + U --> X[Restored image] +``` + +V5 dùng **DA-CLIP-inspired separation of controls**, không phải reproduction của DA-CLIP. Content tiếp tục đi qua shared path; degradation representation điều khiển router, prompt và adapters. Tham khảo: [DA-CLIP paper](https://arxiv.org/abs/2310.01018) và [official implementation](https://github.com/Algolzw/daclip-uir). + +### 6.3 Những cơ chế đã implement + +- Router mềm 5 nhánh: `rain/noise/haze/lowlight/generic`. +- Prior ban đầu lấy trực tiếp từ 4 semantic routing slots; mass của 2 free slots được gộp vào generic expert. +- Router chỉ học bounded residual correction trên Phase 1 prior. +- Router không nhận clean target, degradation label hoặc content latent. +- Rank-16 low-rank `1 × 1` expert adapters được đặt ở 4 down stages và 3 up stages. +- Gate-weighted degradation token được cộng vào time/noise embedding. +- Adapter output được zero-initialize để warm-start không phá v4 behavior. +- Mặc định freeze v4 shared trunk và chỉ train router, prompt, adapters. +- Strict v4 warm-start kiểm tra SHA, schema, manifest/split digest và chọn EMA mặc định. +- Loss hiện tại: + +```text +L = MSE(x0_hat, x0) + + lambda_anchor * KL(stopgrad(prior) || gate) + + lambda_balance * L_balance + + lambda_correction * ||correction||^2 +``` + +### 6.4 Noise routing hiện tại: giới hạn cần nói rõ + +Optional noise bank đang dùng: + +```text +epsilon_route = sum_k g_k / ||g||_2 * epsilon_k +epsilon_mix = sqrt(1-rho) * epsilon_shared + sqrt(rho) * epsilon_route +``` + +Với các `epsilon_k ~ N(0, I)` độc lập, cả `epsilon_route` và `epsilon_mix` vẫn có phân phối `N(0, I)`. Vì vậy cơ chế này bảo toàn variance và route **random stream**, nhưng chưa tạo ra stochastic process có semantics/covariance riêng cho từng degradation. Gate còn được detach trong corruption branch để router không tối ưu loss bằng cách thao túng noise. + +Kết luận thực dụng: + +- Giữ `expert_noise_fraction = 0` cho mainline v5 đầu tiên. +- Xem routed Gaussian streams là ablation, không phải đóng góp chính. +- Guidance chính ở v5 nên đến từ prompt và expert adapters. + +## 7. Kế hoạch train và ablation v5 + +### P0 — Safe mainline run + +Model/trainer core của v5 đã implement, nhưng experiment harness dưới đây **chưa runnable đầy đủ**. Runtime kế thừa từ v4 hiện chọn `best.pt` chỉ bằng macro PSNR, không early-stop, chưa log gate/adapter diagnostics và chưa lưu metric theo group cho uncertainty analysis. + +#### P0 preparation — cần implement trước khi train + +1. Thêm gate mean/entropy, generic mass, `KL(prior || gate)`, correction norm và adapter residual norm theo stage/expert. +2. Lưu per-record metric cùng `split_group` và clean-content hash. +3. Thêm checkpoint selector có per-domain/worst-domain guardrail; có thể chọn offline, không bắt buộc dừng process sớm. +4. Thêm flag freeze generic adapter/prompt cho known-domain P0. Code hiện tại train toàn bộ 5 expert paths dù chưa có unknown supervision; khi generic bị freeze, generic mass nên fallback về shared v4 trunk. +5. Thêm forced/fixed-gate evaluation hook để đo correct gate và counterfactual wrong gate. + +#### P0 training — chạy sau preparation + +1. Warm-start từ EMA của v4 D5 best tại step 1.000. +2. Freeze shared trunk. +3. Đặt `expert_noise_fraction = 0`. +4. Freeze generic path; train four-known-expert adapters, prompt và bounded router correction. +5. Eval mỗi 250–500 steps với record-keyed noise. +6. Chọn checkpoint bằng macro metric kèm worst-domain constraint, không dùng macro PSNR đơn lẻ. + +Log bắt buộc: + +- gate mean và entropy theo domain; +- generic mass; +- `KL(prior || gate)` và correction norm; +- adapter residual norm theo stage/expert; +- PSNR, SSIM và paired delta kèm `split_group` trên từng record; +- best-to-current drift theo domain. + +### P1 — Ablation tối thiểu + +Bảng dưới là **protocol đề xuất**. A0 đã có; A2/A5 gần với đường code hiện tại. Fixed router, prompt-only, adapters-only, upper-trunk-only và forced-gate hooks vẫn phải được implement. `--train-shared-trunk` hiện unfreeze toàn trunk, không chỉ upper trunk. + +| Arm | Cấu hình | Câu hỏi | +|---|---|---| +| A0 | v4 D5 full | Baseline chuẩn | +| A1 | Fixed Phase 1 prior + adapters + prompt, `rho=0` | Soft gating có giảm task interference không? | +| A2 | A1 + learned bounded router correction | Router có cải thiện prior không? | +| A3 | Prompt-only | Prompt đóng góp bao nhiêu? | +| A4 | Adapters-only | Expert capacity đóng góp bao nhiêu? | +| A5 | A2 với `rho in {0.10, 0.25}` | Routed random stream có ích không? | +| A6 | A2 + unfreeze upper trunk, LR thấp | Adapter-only có phải bottleneck không? | + +Nên chạy ít nhất 3 seeds. Không bootstrap độc lập theo từng ảnh vì các record dùng chung clean content/scene. Số effective `split_group` hiện tại là rain 95, lowlight 43, haze 3 và noise 1. Có thể dùng paired cluster bootstrap theo `split_group` cho rain/lowlight; haze và đặc biệt noise cần thêm external held-out scenes trước khi đưa ra confidence interval về generalization. + +### P2 — Mixed degradation + +Softmax hiện tại ép các degradation cạnh tranh tổng mass bằng 1. Với hai degradation cùng mạnh, router có thể “average” thay vì kích hoạt đầy đủ cả hai. + +Nếu composite validation xác nhận giới hạn này, phiên bản tiếp theo nên tách: + +- independent semantic activation `a_k in [0,1]`; +- per-type severity `severity_k`; +- independent restoration strength `s_k = a_k * severity_k`; +- novelty/generic confidence `u`. + +```text +delta_h = (1-u) * sum_k s_k * A_k(h) + u * A_generic(h) +``` + +Composite protocol đề xuất: + +- lowlight + noise; +- rain + haze; +- rain + noise; +- haze + noise. + +Cần lưu degradation order và tham số trong manifest vì các phép biến đổi không giao hoán. Một số type-pair phải được giữ hoàn toàn ngoài train để đo compositional generalization. + +### P3 — Unknown degradation + +Generic expert hiện chưa có unknown training set thích hợp nên có nguy cơ trở thành average expert hoặc collapse. + +- Khi novelty cao, giảm known-expert residual và fallback về shared v4 trunk. +- Chỉ bật trainable generic expert sau khi có proxy unknown data. +- Có thể dùng blur, JPEG, snow hoặc raindrop làm OOD evaluation; proxy train và OOD test phải tách biệt. +- Novelty score nên kết hợp free-slot mass, routing entropy, maximum semantic mass và norm của unknown residual. + +### P4 — Type-specific stochastic process thực sự + +Nếu routed random stream không mang lại lợi ích, hướng đúng về mặt xác suất là học hoặc ước lượng covariance `C_k` từ restoration residual của từng degradation: + +```text +u_t = u_0 + eta_t(u_y-u_0) + kappa*sqrt(eta_t)*C(g)^(1/2)*epsilon +``` + +Posterior variance cũng phải thay đổi tương ứng: + +```text +Var(u_{t-1} | u_t, u_0) + = kappa^2 * eta_{t-1}/eta_t * (eta_t-eta_{t-1}) * C(g) +``` + +Nên bắt đầu bằng diagonal channel covariance hoặc fixed per-type `kappa_k`, chưa dùng full spatial covariance. Chỉ thay noise ở forward process mà không sửa posterior/sampler sẽ làm mất tính nhất quán của ResShift. + +## 8. Success criteria đề xuất + +### 8.1 P0 — bốn known domains + +- Macro PSNR trung bình qua ít nhất 3 seeds tăng tối thiểu `+0,20 dB` so với v4 D5 best. +- Macro SSIM tăng ít nhất `+0,005`. +- Không domain nào giảm quá `0,10 dB` hoặc `0,005 SSIM`. +- Correct gate tốt hơn counterfactual wrong-gate sau khi có forced-gate hook. +- Không known expert nào collapse; gate/correction ổn định qua seed. +- Best-to-late drift dưới `0,15 dB`, hoặc checkpoint selector bắt đúng Pareto point. +- Paired cluster-bootstrap interval dương trên các domain có đủ group; haze/noise phải được xác nhận trên external held-out scenes. + +### 8.2 P2 — mixed degradation + +- Mixed model tốt hơn single-expert forcing trên composite set. +- Cả hai active degradation nhận non-trivial strength và kết quả ổn định khi đổi severity. +- Type-pair hoàn toàn ngoài train vẫn cải thiện so với shared v4 baseline. + +### 8.3 P3 — unknown degradation + +- Unknown fallback không gây destructive restoration so với shared v4 trunk. +- Generic expert chỉ được xem là thành công sau khi có proxy train tách biệt OOD test. + +Ngoài PSNR/SSIM, nên bổ sung LPIPS. Không nên dùng FID trên validation set nhỏ hiện tại. + +## 9. Rủi ro và cách kiểm soát + +| Rủi ro | Cách kiểm soát | +|---|---| +| Noise chỉ có 121 train/19 val và 1 val scene group | Balanced sampler, augmentation và thêm external held-out noise scenes; không bootstrap theo ảnh | +| Oversampling noise gây overfit | Log source reuse, domain-specific early stopping, external noise test | +| Macro metric che lowlight collapse | Luôn log per-domain và worst-domain retention | +| Router lệch khỏi Phase 1 prior | KL anchor, bounded correction, counterfactual-gate test | +| Router “cheat” qua corruption | Detach gate trong noise branch và giữ variance cố định | +| Generic expert collapse | Shared-trunk fallback; chỉ train generic khi có unknown proxy | +| Mixed degradation bị softmax average | Independent activation + composition weights ở phiên bản sau | +| Global gate bỏ qua degradation cục bộ | Sau P0 mới thử spatial gating từ Phase 1 maps | +| Compute 5 experts mỗi layer | Benchmark latency; cân nhắc top-k execution sau khi quality ổn định | +| Source Phase 1 thiếu ở local | Đồng bộ canonical remote source và version-control trước thay đổi mới | + +## 10. Quyết định hiện tại + +1. Giữ Phase 1 frozen và giữ đúng vai trò representation learner. +2. Giữ toàn bộ v4 stack vì v5 phụ thuộc trực tiếp vào runtime, model và data v4. +3. Dùng v4 D5 best EMA làm warm-start, không dùng final 20k làm mainline. +4. Hoàn thiện P0 harness rồi train v5 adapter-only với `expert_noise_fraction = 0` và generic path frozen. +5. Sau khi có selector, chọn checkpoint bằng Pareto/per-domain guardrail, không chỉ bằng macro PSNR. +6. Chỉ nghiên cứu covariance-aware noise sau khi prompt/adapters đã được ablate rõ ràng. + +## 11. Việc cần làm tiếp theo + +- [ ] Đồng bộ canonical Phase 1 source từ server về local repo. +- [ ] Thêm config/run directory chuẩn cho v5 P0. +- [ ] Implement P0 logging, group-aware metric export và per-domain checkpoint selector. +- [ ] Implement generic freeze/shared-trunk fallback và forced/fixed-gate evaluation hooks. +- [ ] Bổ sung external held-out haze/noise scenes. +- [ ] Chạy v5 smoke test ngắn và kiểm tra zero-init/warm-start equivalence. +- [ ] Train P0 với eval mỗi 250–500 steps. +- [ ] Xuất visualization cùng format với v4 cho từng degradation. +- [ ] Implement ablation flags rồi chạy A1–A4 trước khi bật routed Gaussian streams. +- [ ] Bổ sung paired cluster bootstrap theo `split_group` và LPIPS evaluation. +- [ ] Thiết kế manifest deterministic cho mixed degradation. +- [ ] Thiết kế OOD split cho unknown degradation. + +## 12. Trạng thái vận hành + +- Full Phase 2 regression suite: `105 passed` trên local và server. +- Phase 1 data tests: `14 passed`. +- Không có training process đang chạy tại thời điểm cập nhật. +- Sau cleanup, `data + outputs` trên server còn 5,87 GB; khoảng 4,42 GiB đã được giải phóng. +- Legacy source/archive đã chuyển recoverably sang `/home/admin_mcn/scdc_legacy_20260830`. + +Lưu ý: `tests/test_relation_aware_encoder.py` là orphan test có từ trước cleanup; module tương ứng đã bị xóa ở commit cũ và không thuộc Phase 1 graph encoder chuẩn hiện tại. + +## 13. Addendum (2026-08-30, tối) — Per-type kappa (mức A): đã implement và xác nhận + +### 13.1 Diagnostic xác nhận giả thuyết kappa mis-scale + +Chạy trên `gate_d5_seed42/best.pt` (EMA, step 1.000), log `MSE(x0_hat, u0) / MSE(u_y, u0)` theo từng `(domain, t)` — kết quả tại `outputs/phase2_graph_resshift_v4/diagnostics/x0_mse_by_domain_t.json` (script `diag_x0_mse.py`): + +| t | haze | lowlight | noise | rain | +|---:|---:|---:|---:|---:| +| 1 | 0,058 | 0,058 | 0,920 | 0,322 | +| 4 | 0,073 | 0,072 | 0,978 | 0,415 | +| 8 | 0,239 | 0,210 | **1,383** | **1,070** | + +- **Noise không bao giờ thắng identity ở bất kỳ t nào**; từ t≥5 delta chủ động gây hại (ratio > 1 dù model nhận sẵn `u_y`). Nhiễu bơm vào bằng 0,43–2,12× residual thật. +- **Lowlight profile gần phẳng** — thành phần ngẫu nhiên vô nghĩa (0,07–0,34× residual), reverse chain thoái hoá thành regression lặp. +- Ratio tại t=8 đơn điệu theo `kappa·sqrt(eta_t)/residual_RMS` qua cả 4 domain. + +Gốc rễ định lượng: `calibrate_kappa()` đã tính per-domain residual RMS (rain 0,0978 / noise 0,0384 / haze 0,1344 / lowlight 0,4146 — spread 10,8×) rồi lấy median làm kappa toàn cục, tức loại bỏ đúng hai domain cực trị đang seesaw nhau. + +### 13.2 Implement (129/129 tests pass trên server, torch 1.10) + +- `ResidualShiftSchedule.q_sample/posterior_mean_variance` nhận optional per-sample `kappa` `[B]`; posterior vẫn exact vì kappa hằng theo chain của từng sample. Mặc định (None) giữ nguyên hành vi v4. +- `ExpertKappaSchedule` (v5): nội suy log-space `exp(ĝ·log kappa_k)` trên gate **đã detach** (router không thể tự bóp corruption — bất khả thi theo cấu trúc); anneal từ kappa toàn cục bằng counter microstep kiểu int buffer (EMA copy verbatim, resume khôi phục đúng); null-mode/zero-mass fallback bitwise về kappa toàn cục. +- Trainer v5: `--expert-kappa`, `--expert-kappa-values rain,noise,haze,lowlight,generic`, `--expert-kappa-anneal-steps` (mặc định 2000); fail-closed validation; ghi vào `schedule_config["expert_kappa"]` nên resume/contract guard tự bảo vệ; `expert_kappa.*` thuộc v5-only allowlist của warm-start. +- Smoke với checkpoint thật (`smoke_warmstart_kappa.py`): warm-start EMA D5 best → **bitwise v4-equivalent** tại anneal=0; full anneal đổi corruption đúng theo gate (input route haze → kappa 0,13436). + +### 13.3 Hệ quả cho kế hoạch + +- Thêm arm **A7 = A2 + per-type kappa** vào bảng P1; per-type kappa nên chạy TRƯỚC hoặc song song adapter ablation vì rẻ hơn và có cơ chế đo được. +- Giá trị đề xuất cho A7 lấy thẳng từ `calibration_seed42/kappa_calibration.json`: `0.09780,0.03836,0.13436,0.41464,0.11608` (generic = kappa toàn cục). +- Noise routing `epsilon_mix` (§6.4) giữ nguyên kết luận: vẫn là no-op thống kê; per-type kappa mới là cơ chế "truyền noise theo loại" có ngữ nghĩa thật đầu tiên. + +### 13.4 Kết quả A7 run đầu tiên (seed 42, 2026-08-31) + +Run: `outputs/phase2_gated_resshift_v5/a7_kappa_seed42` — warm-start EMA v4 D5 best, trunk frozen, `expert_noise_fraction=0`, per-type kappa anneal 0→2000, 8.000 steps với LR cosine trọn vẹn, eval 13 mốc. Không AMP overflow, không restart. `best.pt == last.pt` (step 8.000, SHA `6dcf7739…52c55`). + +| Domain | A7 @8000 | vs v4 D5 best @1000 | +|---|---:|---:| +| Lowlight | **18,129 / 0,5759** | **+0,980** / −0,0193 | +| Rain | 20,928 / 0,6554 | +0,043 / +0,0041 | +| Haze | 22,891 / 0,8809 | −0,153 / +0,0011 | +| Noise | 26,490 / 0,4926 | −0,580 / −0,0131 | +| **Macro** | **22,109 / 0,6512** | **+0,072** / −0,0068 | + +Đối chiếu success criteria §8.1 (một seed, chưa đủ 3): + +- Macro PSNR +0,072 — chưa đạt ngưỡng +0,20; macro SSIM −0,0068 — chưa đạt. +- Guardrail per-domain −0,10 dB: haze (−0,15) và noise (−0,58) vi phạm. +- **Drift: đạt tuyệt đối** — best == final, macro tăng đơn điệu sau khi anneal xong (21,78 @2k → 22,11 @8k), đối lập với v4 (−0,615 dB best→final). + +Diễn giải: + +1. **Lowlight xác nhận cơ chế**: +0,98 dB, đỉnh mới toàn dự án (18,13 so với 17,15), còn đang tăng ở step 8.000. Đúng chữ ký dự đoán: kappa 3,6× lớn hơn cho reverse chain việc để làm thay vì regression lặp. Ở cùng lượng step sau best, lowlight v4 đã rơi về ~10–12. +2. **Noise xác nhận bottleneck adapter**: kappa trung thực (0,038) lấy đi "nạng" Gaussian-denoising từng thổi noise lên 31,9 ở v4@20k, và adapter 1×1 phi-không-gian không học nổi SIDD denoising thật → 26,49, vẫn dưới degraded baseline. Khớp dự đoán đăng ký trước khi chạy (A4 under-deliver; A6 cần thiết). +3. Ổn định huấn luyện thay đổi hẳn: không cần chọn checkpoint sớm, không cần Pareto guardrail trong run này vì không có drift để né. + +Việc tiếp theo đề xuất: (a) A6-lite — unfreeze upper trunk LR thấp, hoặc adapter 3×3 cho hai scale thô, nhắm hồi phục noise/haze; (b) lặp ≥3 seeds trước khi kết luận; (c) cân nhắc kappa_noise mềm hơn (ví dụ trung bình hình học 0,066) nếu muốn giữ trunk frozen. + +### 13.5 Phát hiện quan trọng: reverse chain 8 bước đang PHÁ kết quả (2026-08-31) + +Probe `probe_chain_vs_onestep.py` — so PSNR per-domain giữa full 8-step chain và **một** forward x0-prediction từ `u_T` (cùng EMA weights, cùng record-keyed noise), kết quả tại `outputs/phase2_gated_resshift_v5/diagnostics_chain_vs_onestep.json`: + +| Domain | Degraded | v4 1-step | v4 chain | A7 1-step | A7 chain | +|---|---:|---:|---:|---:|---:| +| Rain | 21,25 | **21,62** | 20,89 | **21,68** | 20,93 | +| Lowlight | 9,77 | **19,23** | 17,15 | 18,36 | 18,13 | +| Haze | 17,31 | **23,35** | 23,04 | 23,52 | 22,89 | +| Noise | 27,33 | 26,52 | 27,07 | 26,44 | 26,49 | +| **Macro** | 18,91 | **22,68** | 22,04 | 22,50 | 22,11 | + +Kết luận: (1) chain thua hoặc hoà 1-step ở gần như mọi ô — exposure bias giữa teacher-forced x0-MSE training và autoregressive sampling; (2) **rain 1-step vượt degraded baseline ở cả hai model** — "derain kém" thực chất là "chain phá derain"; (3) chain chỉ giúp noise ở v4 (κ to → khử Gaussian tự bơm); (4) per-type κ của A7 thu hẹp gap chain-vs-1step của lowlight từ −2,08 còn −0,23 dB nhưng hạ trần 1-step (u_T nhiễu hơn); (5) **v4-best @ 1-step macro 22,68 là số tốt nhất toàn dự án, chi phí 0 training** — số bước sampling phải trở thành một trục eval/selection chính thức. + +### 13.6 Probe baseline Phase 1 trước LL-upgrade (2026-08-31) + +`probe_phase1_ood.py` → `outputs/phase1_probe_baseline.json` (server). OOD dùng snow/blur/JPEG **synthetic** trên clean val; severity đối chiếu proxy vật lý blind (darkness, HH1-MAD sigma, dark-channel). + +**Routing trên input thực của Phase 2 (val manifest):** + +| Group | argmax phân bố | free mass | unknown norm | +|---|---|---:|---:| +| rain (98) | rain 97 | ~2e-5 | 0,542 | +| lowlight (100) | lowlight 100 | ~7e-5 | 0,487 | +| **noise (19)** | **rain 17**, noise 2 | ~8e-5 | 0,572 | +| **haze (100)** | haze 61, **noise 29, rain 10** | ~3e-4 | 0,398 | +| **clean control (60)** | **haze 46**, rain 10, noise 4 (max-sem 0,948!) | 4e-4 | 0,365 | +| snow synth (60) | **haze 54** | 7e-5 | 0,371 | +| blur synth (60) | haze 51 | 3e-4 | 0,435 | +| jpeg q10 (60) | haze 50 | 4e-4 | 0,371 | + +**Severity vs proxy vật lý (Spearman):** haze **+0,97** (≈ dark channel); lowlight **+0,24** (yếu — đúng chẩn đoán exposure); noise **−0,46** (ĐẢO DẤU, n=19). + +Bốn kết luận: + +1. **Slot haze là "thùng rác mặc định", không phải detector**: clean/snow/blur/jpeg đều đổ về haze với confidence ~0,95. Không có trạng thái "không degradation"; 2 free slot chết hẳn (mass ≤ 4e-4 ở mọi group — free/unknown suppression loss đã giết cơ chế unseen-degradation); unknown residual norm còn **đảo chiều** (OOD thấp hơn in-domain) → vô dụng làm novelty score. +2. **Noise val bị route thành rain 89% mass** → trong A7, ảnh noise nhận κ_eff ≈ κ_rain (0,098) chứ không phải κ_noise (0,038): per-type κ **chưa từng thực sự được áp cho noise**. Kết quả noise của A7 phải diễn giải lại: router misroute + adapter bottleneck, không tách được hai yếu tố. +3. Haze mass loãng (0,655) → κ_eff haze ≈ 0,097 < κ_haze 0,134 — khớp với haze −0,15 trong A7. +4. Mâu thuẫn với "val accuracy 0,994" của Phase 1: số đó đo trên pipeline val riêng của Phase 1. Trên input thật của Phase 2 (crop 256 từ manifest), routing xấu hơn nhiều — cần kiểm tra preprocessing mismatch giữa hai pipeline. + +→ LL-upgrade (§ kế hoạch P1-LL) giờ có baseline định lượng để nghiệm thu: free-slot response với OOD, clean-state, severity Spearman lowlight/noise, routing noise/haze trên Phase-2 val. + +### 13.7 Kết quả P1-LL retrain lần 1 (ll_v3, 2026-08-31) + +Run: `outputs/phase1_ll_v3` — batch 32, full data/epoch (571 steps), 50 epochs, **fp32 toàn phần** (hai run AMP fp16 đều nổ NaN tại epoch 14–15 — bất ổn hệ thống của main path fp16; fp32 sạch 50/50 epochs, nf=0). Best epoch 16, macro-F1 0,793, SHA `a05d4bd1…733f`. Probe đối chiếu tại `outputs/phase1_probe_ll_v3.json`. + +**Thắng (cơ chế null/OOD — mục tiêu chính của upgrade):** + +| Group | Baseline (v2) | ll_v3 | +|---|---|---| +| Clean → | haze 46/60 (conf 0,95) | **free 52/60** ✓ | +| Snow → | haze 54/60 | **free 55/60** ✓ | +| Blur/JPEG → | haze 51/50 trên 60 | **free 60/60** ✓✓ | +| Unknown norm OOD vs known | ĐẢO CHIỀU (0,37 < 0,5) | **2,1–2,8 vs 0,5–0,8** ✓✓ | +| Noise severity rho (blind) | −0,46 | **+0,34** ✓ | + +**Giá phải trả (routing known-domain thoái hóa):** + +| Domain | Baseline argmax đúng | ll_v3 | +|---|---|---| +| rain | 97/98 | **61/98** (27 → free2, free mass 0,30) | +| lowlight | 100/100 | 96/100 | +| haze | 61/100 | 51/100 (rain hút 46) | +| noise | 2/19 | 0/19 | + +Chẩn đoán: (1) snow synthetic có elongation 1–3× theo góc gần dọc = **vệt mưa ngắn trá hình** → model học "streak → free" → rain thật bị hút theo; (2) trọng số null/ood (0,3+0,3) mạnh so với suppression free-mass trên known (0,1) → free2 thành attractor; (3) free1 chết, mọi việc dồn free2. + +**Kế hoạch v3.1 (một iteration ~3,5h):** snow tròn hơn (elong ≤ 1,5, bỏ thiên hướng góc dọc); `null_route/ood_route` 0,3 → 0,15; tăng suppression free-mass trên known 0,1 → 0,25; giữ nguyên phần còn lại. Nghiệm thu: giữ nguyên các cột thắng ở trên + rain ≥ 90, haze ≥ baseline 61, lowlight ≥ 99. + +### 13.8 Pipeline A hoàn chỉnh: 1-step + refiner decoder pretrain (2026-08-31) + +Kiến trúc: `y → Phase-1 (frozen) → U-Net v4-best 1-step x0 (frozen) → RefinerDecoder → ảnh`. Refiner = NAFNet-lite 3 scale (~5M params, zero-init head), **pretrain trước** trên clean + corruption nhẹ (prior ảnh tự nhiên, L1+VGG) rồi finetune 12k steps trên `û₀` thật. Files: `src/models/restoration/refiner_decoder.py`, `train_refiner_a.py`, `infer_scdc_pipeline.py`. Checkpoint: `outputs/refiner_a_v1/refiner_best.pt` (best @11.500). + +**Kết quả chính thức** (val 317, `outputs/pipeline_eval_v1.json` + `pipeline_lpips_v1.json`): + +| Domain | 1-step P/S/LPIPS | **Pipeline A** P/S/LPIPS | Δ PSNR | +|---|---|---|---:| +| Haze | 23,33 / 0,877 / 0,083 | **28,88 / 0,965 / 0,014** | +5,55 | +| Lowlight | 19,23 / 0,600 / 0,571 | **19,39 / 0,797 / 0,237** | +0,16 | +| Noise | 26,52 / 0,496 / 0,532 | **36,38 / 0,912 / 0,107** | +9,86 | +| Rain | 21,62 / 0,677 / 0,256 | **22,40 / 0,779 / 0,148** | +0,78 | +| **Macro** | 22,67 / 0,662 / 0,360 | **26,76 / 0,863 / 0,126** | **+4,09** | + +So mọi mốc cũ: v4 D5 chain 22,04 · A7 chain 22,11 · 1-step 22,68 → **Pipeline A 26,76** (+4,1 dB), SSIM 0,66 → 0,86, LPIPS giảm ~3×. Noise lần đầu được giải quyết thật (36,4 dB — decoder pretrain trên 18k clean đi vòng qua giới hạn 121 cặp SIDD). Caveat giữ nguyên: một seed; noise n=19/1 scene group — cần external held-out trước khi claim; lowlight PSNR gần như đứng (SSIM/LPIPS cải thiện mạnh) — trần exposure vẫn chờ Phase-1 mới. + +### 13.9 Phán quyết Phase-1 v3.x và phát hiện "honest null" (2026-08-31) + +v3.1 (snow tròn + rebalance): haze 63 ✓, lowlight-blind-rho 0,506 ✓✓, nhưng rain-argmax 51 và snow→free tụt 39/60 (best@7 quá sớm); last@50: snow 59/60 ✓✓ nhưng rain-free-mass 0,41. + +**Phát hiện then chốt**: free-mass trên rain **nghịch tương quan với residual thật** (v3-best: ρ=−0,294, p=0,003; crop mưa nhẹ nhận free-mass 0,368 vs mưa nặng 0,113) → phần lớn "rain leak" là **null-detection ĐÚNG trên crop gần sạch**; label-accuracy phạt oan hành vi đúng. Hệ quả: (1) ngưng iterate trọng số v3.x; (2) metric nghiệm thu routing phải là severity-aware (đánh giá theo mass × residual, không phải argmax vs label); (3) fix cấu trúc thật nằm ở v6 (sigmoid activation độc lập thay softmax). Ứng viên Phase-1 hiện tại: **v3-best** (OOD tốt + anti-corr rõ nhất) chờ ghép khi làm v6. + +### 13.10 v6 graph-MoE run 1 + cleanup codebase (2026-08-31) + +**v6 run 1** (`outputs/phase2_moe_v6/main_seed42`, trunk finetune 5e-5, Phase-1 ll_v3, 8k steps, eval 1-step): best @1000 = **21,90** (lowlight 18,20), sau đó trượt đơn điệu về 20,23 @8000 — lowlight sụp về 10,73 (≈ baseline), noise hội tụ về copy-input (27,32), **rain 21,97 giữ trên mốc v4 1-step (21,62) suốt run**. Chẩn đoán: mở trunk + full gating từ step 0 tái tạo interference kiểu v4 nhưng nặng hơn; v6.1 cần curriculum — freeze trunk giai đoạn đầu (như A7), chỉ unfreeze sau khi gate/adapter ổn định. Hai fix nền tảng phát sinh: `FrozenPhase1` ép fp32 vĩnh viễn (ll_v3 NaN dưới autocast); anchor gate chuyển BCE-with-logits (autocast-safe). + +**Cleanup codebase**: xoá 94 file legacy (experiments/training/losses/utils, downstream/wavelet models, stage_b/diffusion đời đầu, 8 relic tests, logs/outputs tracked); đưa toàn bộ canonical stack (43 file) vào git; hoà giải 10 commits GCRS-LD/D2 trên origin bằng merge `-s ours`; push `master` = `d5742b0`. Repo giờ là single source of truth; server scdc_ban CHƯA mirror (chờ quyết định — xem lệnh đề xuất trong chat). + +### 13.11 v6.1 curriculum + Pipeline gen-2 (2026-09-01) + +**v6.1** (curriculum 2 giai đoạn: freeze trunk 0→2000, unfreeze 2000→8000): stage-1 hồi lowlight về 18,08 với gate ổn định; sau khi mở trunk đạt best **22,41 @3000** (lowlight 19,28 — đỉnh 1-step; haze 23,67) rồi vẫn drift về 20,27. Kết luận cấu trúc qua v4/v6/v6.1: tối ưu trunk kéo dài luôn hy sinh lowlight — công thức đúng là *checkpoint-sớm + refiner*. Fix kỹ thuật: resume phải đọc lại warmstart-audit từ checkpoint (contract equality). + +**Pipeline gen-2** = Phase-1 ll_v3 → v6.1-best 1-step → refiner (transfer từ refiner-v4, finetune 8k trên û₀ v6.1): best @5500 — + +| Domain | 1-step | Gen-2 | Gen-1 (Pipeline A) | +|---|---:|---:|---:| +| Haze | 23,67 | **30,21 / 0,970** | 28,88 / 0,965 | +| Lowlight | 19,28 | **20,33 / 0,816** | 19,39 / 0,797 | +| Noise | 24,83 | **36,91 / 0,916** | 36,38 / 0,912 | +| Rain | 21,85 | **22,77 / 0,792** | 22,40 / 0,779 | +| **Macro** | 22,41 | **27,55 / 0,874** | 26,76 / 0,863 | + +External held-out gen-2: rain locked **+1,64** (26,71, tốt hơn gen-1); haze held-out **+5,28** (31,18); noise scene008 vẫn âm (−6,83, đỡ hơn gen-1 −10,68; LPIPS lại CẢI THIỆN 0,126→0,085 → lỗi thuần global-shift màu/exposure). Gen-2 thắng gen-1 trên mọi domain val + 2/3 external, và chạy trên nền tảng mới (honest-null routing, node-MoE, few-shot substrate). Checkpoints: `outputs/phase2_moe_v6/v61_seed42/best.pt` + `outputs/refiner_v6_v1/refiner_best.pt`. Caveat không đổi: 1 seed; noise ngoài-scene cần refiner v2 (color-jitter + trust-gate). + +### 13.12 v7 unified two-step + đối chứng backbone Uformer (2026-09-01) + +**v7** hợp nhất gen-2 thành MỘT mạng diffusion T=2: coarse t=2 (x0-MSE) + fine t=1 (L1+VGG image-space) với u₁ dựng chain-aware từ chính prediction (detach). Hai backbone chạy đối chứng, chỉ khác blocks: + +| Biến thể thuần-diffusion | Best macro | SSIM | Lowlight | Drift | +|---|---:|---:|---:|---| +| v4 chain 8-step | 22,04 | 0,658 | 17,15 | −0,6 | +| v4 1-step | 22,68 | 0,662 | 19,23 | — | +| v6.1 conv (curriculum) | 22,41 @3000 | — | 19,28 | nặng | +| v7-conv (warm-start v6.1) | 23,41 @750 | 0,703 | 19,88 | nặng sau 750 | +| **v7-Uformer (from scratch!)** | **25,26 @8000** | **0,777** | 18,02 | **KHÔNG** | + +Kết luận: (1) công thức unified two-step tự nó +0,7 dB (conv 23,41 > 22,68); (2) **backbone LeWin/Uformer thay đổi hẳn động học tối ưu** — cả 4 domain leo đồng thời suốt 8k steps (haze 29,9 · noise 30,7 · lowlight 18,0 · rain 22,4 cùng lúc — chưa run nào làm được), best==final, không cần curriculum, không cần early-checkpoint; định luật drift của conv-trunk KHÔNG áp dụng cho window-attention + adaLN zero-init. (3) Một lần AMP overflow @4397 được cơ chế recovery của runtime xử lý đúng thiết kế (resume, không mất tiến trình). Còn cách gen-2 hai-mạng (27,55/0,874) 2,3 dB — nhưng đường cong Uformer chưa bão hòa và chưa hề warm-start. Files: `src/models/restoration/uformer_moe_v7.py`, `--backbone uformer` trong `train_phase2_unified_v7.py`. Checkpoints: `outputs/phase2_v7/{main_seed42,uformer_seed42}/best.pt`. + +### 13.13 v7-Uformer: vis audit, chroma loss, DDP 2-GPU (2026-09-01) + +Vis audit checkpoint @8000 (mẫu máy móc đầu/giữa/cuối per domain, `visualize_v7_uformer.py`): haze gần giải xong (11,2→24,6 dB ca nặng); lowlight sáng đúng nhưng **mất chroma** (ghế xanh → nâu xám ca cực tối); noise còn residual chroma noise ca nặng; rain gỡ streak tốt nhưng PSNR bị **global tone shift** kéo xuống (SSIM vẫn tăng). → Hai lỗi đầu bảng đều thuộc nhóm màu/tone toàn cục. + +Hành động: (1) thêm **fine-chroma loss** — L1 trên mặt phẳng U/V BT.601 của fine prediction (`rgb_to_uv`, hàng ma trận zero-sum chính xác; flag `--fine-chroma-weight`, 13/13 test). (2) **DDP 2-GPU**: sanity NCCL thuần pass 0,1s; hang thật nằm ở **MoE top-2 hard-skip** (`SpatialExpertBank` bỏ expert không được chọn khỏi graph → rank phát thiếu bucket allreduce → deadlock; bắt bằng TORCH_DISTRIBUTED_DEBUG=DETAIL, fingerprint bucket [265980] lệch). Fix: flag `--ddp-find-unused` → `find_unused_parameters=True` cho backend MoE. Smoke 60 steps sạch, 0,54s/step (≈1,7×). + +Run đang chạy: `outputs/phase2_v7/uformer16k_seed42` — warm-start EMA best 25,26 (sha 00474e18…), cosine mới LR 5e-5, 16k steps, chroma 0,5, VGG 0,1, effective batch 16 (8×2 rank), eval 0/1k/…/16k. + +### 13.14 v7-Uformer-16k + chroma: KẾT QUẢ CUỐI (2026-09-01) + +**26,436 PSNR / 0,8082 SSIM @16000 — best == final, zero drift suốt 16k steps.** (+1,18 dB so với điểm warm-start 25,26; DDP 2 GPU, chroma 0,5, LR 5e-5 cosine.) Per-domain: haze **32,12** (vượt cả gen-2 hai-mạng 30,2) · noise 32,57 · lowlight 18,62 · rain 22,43. Cách Pipeline A hai-mạng (26,76) chỉ 0,32 dB PSNR; SSIM còn cách 0,055. + +Vis đối chứng cùng 12 mẫu: (1) **chroma loss làm đúng việc** — ghế sân vận động xanh trở lại (8k: nâu xám), residual chroma noise ca nhiễu nặng giảm rõ (+1,9 dB), haze mù dày +2→3,5 dB/mẫu; (2) **side-effect mới: exposure overshoot lowlight** — 2 mẫu quạt Midea bị đẩy sáng quá GT (17,0→12,8 dB per-sample dù aggregate lowlight tăng 18,0→18,6; SSIM vẫn tăng) — chroma term mù luminance nên không gây trực tiếp, khả năng do fine-loss cân bằng lại; hướng xử lý nếu cần: term luminance-histogram hoặc data-augment exposure jitter; (3) rain: gỡ streak tốt hơn, lỗi tone toàn cục ca tối vẫn còn (chroma term không chữa được luminance). + +Vận hành: 5 lần RecoverableAmpOverflow (vòng dao động GradScaler 262144↔65536 tại trần fp16) — toàn bộ tự resume bằng `supervise_uformer16k.sh`, không mất step nào. Checkpoint: `outputs/phase2_v7/uformer16k_seed42/best.pt` (step 16000). + +Scoreboard thuần-diffusion một mạng: v4 1-step 22,68 → v7-conv 23,41 → v7-Uformer-8k 25,26 → **v7-Uformer-16k+chroma 26,44**. + +### 13.15 v7-Uformer luma8k: KẾT QUẢ CUỐI (2026-09-01) + +**26,589 / 0,8110 @8000 — kỷ lục thuần-diffusion mới, best == final.** Warm-start từ 16k+chroma best (26,44), luma loss 0,5 (L1 trên luma Y pool 8×8, `pooled_luma`; test chứng minh bổ khuyết với chroma term). Per-domain: haze 32,39 · noise 32,84 · **lowlight 18,72 (kỷ lục)** · rain 22,41. Cách Pipeline A hai-mạng chỉ còn **0,17 dB PSNR** (26,76); khoảng cách SSIM 0,811 vs 0,863 vẫn là phần refiner/perceptual. + +Vis: không regression; haze mù dày +2,25 dB/mẫu, noise +0,3 đều, ghế lowlight giữ màu xanh. HAI MẪU QUẠT VẪN OVERSHOOT (12,5/12,3 — luma term không chữa được): input ~9,7 dB gần đen tuyệt đối → độ sáng GT là thông tin không thể phục hồi từ ảnh vào (mơ hồ thông tin, không phải lỗi thiết kế loss); model chọn exposure trung bình đã học. Định luật mới ghi nhận: **chuỗi warm-restart cosine hoạt động như SGDR** — mỗi chu kỳ vắt thêm được (25,26 → +1,18 → +0,15), lợi suất co dần; loss train chưa từng phẳng ở LR còn sống (bão hòa là do schedule, không phải dung lượng). + +Checkpoint: `outputs/phase2_v7/uformer_luma8k_seed42/best.pt`. Scoreboard một-mạng: 22,68 (v4 1-step) → 23,41 (v7-conv) → 25,26 (uformer 8k) → 26,44 (+chroma 16k) → **26,59 (+luma 8k)**. + +### 13.16 External eval v7-luma: MỘT MẠNG THẮNG HAI MẠNG NGOÀI PHÂN PHỐI (2026-09-01) + +`eval_v7_external.py` (protocol trùng bit với gen-2 external). Kết quả (PSNR/SSIM/LPIPS): + +| Set | Degraded | gen-2 (2 mạng) | v7-luma (1 mạng) | +|---|---:|---:|---:| +| rain_locked 1200 | 22,56 | 26,71 / 0,833 / 0,108 | **28,00 / 0,834 / 0,126** | +| haze_heldout 300 | 18,17 | 31,18 / 0,971 / 0,010 | **31,63 / 0,972 / 0,011** | +| noise scene008 (20) | **39,02** | 22,35 / 0,801 / 0,085 | 27,41 / 0,757 / 0,307 | + +Ba kết luận: (1) **v7 một-mạng vượt gen-2 hai-mạng trên CẢ BA bộ external về PSNR** (+1,30 / +0,46 / +5,06) — bảng xếp hạng nội bộ (gen-2 27,55 > v7 26,59) ĐẢO CHIỀU ngoài phân phối: refiner của gen-2 overfit phân phối nội bộ, mạng thống nhất khái quát tốt hơn — xác nhận mạnh nhất cho directive "pipeline thống nhất". (2) Rain external 28,00: điểm rain nội bộ 22,43 bị GT lệch tone kéo thấp giả tạo — khả năng derain thật mạnh hơn nhiều số nội bộ. (3) **Lỗi gốc #1 của cả hai thế hệ pipeline được định lượng chính xác: thiếu hành-vi-identity trên input gần sạch** — scene008 input 39,02 dB (gần như sạch) bị v7 kéo xuống 27,4 (LPIPS 0,307 → over-smoothing phá texture thật; gen-2 kéo xuống 22,4 vì color shift). Model luôn "làm gì đó" kể cả khi việc đúng là không làm gì. + +Hướng fix identity (chu kỳ tới, cùng full-res tail + LL-FiLM ở §13.15-plan): (a) cặp clean-clean severity-0 trong training (dạy "không làm gì"); (b) output residual có cổng severity: out = y + g(severity)·(model−y), severity Phase-1 đã calibrated sẵn. + +### 13.17 v7 head8k (full-res tail + FiLM): KẾT QUẢ CUỐI (2026-09-02) + +**27,433 / 0,8461 @8000 — kỷ lục một-mạng mới (+0,84 dB / +0,035 SSIM so với luma8k), best == final.** Per-domain: haze 33,05 · **noise 35,42 (+2,6)** · lowlight 18,78 (kỷ lục) · rain 22,48. Vis: noise per-sample +2,3…+2,6 dB, haze mù dày +1,3 — đúng địa bàn thiết kế của tail; rain/lowlight-overshoot giữ nguyên (giới hạn tone GT/mơ hồ thông tin đã xác lập). + +**Phán quyết external (câu hỏi quyết định):** rain 28,02/0,836 · haze 31,71/0,974 · noise scene008 27,09/0,765 — **giữ nguyên hoặc nhích lên so với luma8k** (rain +0,02, haze +0,08, scene008 −0,3 PSNR/+0,008 SSIM). Head train-chung KHÔNG lặp lại thảm hoạ khái quát của refiner train-rời (từng −5 dB external). Kết luận cấu trúc: **cùng một dung lượng full-res, đặt trong cùng graph/loss/optimizer thì an toàn ngoài phân phối; tách thành mạng thứ hai thì overfit** — định luật quan trọng nhất của kiến trúc hệ này. + +Vị thế: nội bộ 27,43/0,846 vs gen-2 27,55/0,874 (còn −0,12 PSNR / −0,028 SSIM); external một-mạng thắng gen-2 cả 3 bộ với cách biệt lớn (rain +1,31, haze +0,53, noise +4,74). Việc còn lại theo kế hoạch đã duyệt: fix #3 severity-gated identity (scene008 vẫn −11,9 vs input). Checkpoint: `outputs/phase2_v7/uformer_head8k_seed42/best.pt`; external: `outputs/v7_head_external_v1.json`. + +### 13.18 Probe độ nhạy đầu cắm Phase-1 → Phase-2 trên head8k (2026-09-02) + +`probe_v7_taps.py`: ablation ở inference trên full val (baseline 27,433/0,846). Kênh bundle: **context** (cross-attn 2 scale sâu + 1 up) −3,68 · **global_vector** (adaLN mọi block) −3,45 · content inject **0,000** · spatial inject −0,008 · gate batch-mean −0,03 · **gate uniform (xoá cả domain) −0,085** · tắt toàn bộ conditioning **−7,79 (19,64 ≈ degraded 18,91)**. Field Phase-1 (batch-mean): **unknown_residual −0,74** (noise −1,7) · global_condition −0,24 · node_tokens −0,16 · routing −0,05 · severity −0,03 · spatial_maps +0,005 · content_latent 0,000. (Caveat: val batch đơn-domain → batch-mean chỉ xoá biến thiên từng ảnh của routing/severity; gate-uniform bịt lỗ hổng này cho MoE.) + +Kết luận: (1) **~25 điểm cắm, chỉ 2 đường sống** — trunk dùng Phase-1 như một *mô tả dày đặc từng ảnh* (unknown_residual quan trọng nhất!) qua attention/adaLN, KHÔNG qua expert routing; content inject @64px, spatial inject @16px, 7 bank MoE + κ per-type + strength prompt ≈ chết ở inference (~0,1 dB gộp). (2) Phase-1 là "bộ não": rút hẳn thì trunk gần như identity (−7,8 dB) — nhưng đây là độ *phụ thuộc*, không phải giá trị so với trunk train-không-Phase-1. (3) **Nghịch lý lowlight: tắt context → lowlight +1,95 (20,73, vượt gen-2 20,3)**, tắt global_vector → +0,55: conditioning đang ép quá liều exposure — cùng gốc với overshoot lowlight và over-processing scene008: conditioning là cú đẩy phân loại, không có khái niệm "liều". + +Hướng rút ra: (A) **conditioning dropout kiểu CFG** (train với p≈0,15 xoá context/global_vector) → inference dùng hệ số w theo mẫu/domain (lowlight w<1, noise w≥1, ảnh sạch w→0) — một cơ chế trị 3 triệu chứng, tổng quát hoá fix #3; (B) cắt đầu cắm chết (content/spatial inject; xét gộp MoE sau ablation train); (C) Phase-1: nâng unknown_residual thành descriptor chính thức, calibrate severity lowlight theo exposure gain, spatial 16×16 hoặc lên 64×64 hoặc bỏ. + +### 13.19 Run DGF-8k đã launch (2026-09-02) + +Implement đầy đủ đề xuất DGF + decoder coarse-to-fine (docs/proposal_dose_guided_finetune_2026-09-02.md): +`--pyramid-heads` (3 head Laplacian 16/32/64 px, deep-supervision MSE λ 0,1/0,2/0,3, identity chính xác khi zero), +`--cond-dropout-prob 0,15` (token null học được thay `context` + `global_vector`, khởi tạo 0), `--identity-pair-prob 0,10` +(runtime v4: thay input bằng GT trước Phase-1), sampler `dose=w` ở bước coarse. 31/31 test v7 + 26 regression. +Warm-start head8k (sha 0168e543…), LR 3e-5 cosine 8k, DDP 2 GPU, run `outputs/phase2_v7/uformer_dgf8k_seed42`. +Eval trong training dùng w = 1 (so sánh được với head8k); đo liều bằng `sweep_v7_dose.py` (val + identity test) và +`eval_v7_external.py --dose` sau khi xong. + +Kiểm chứng identity: cùng process, denoiser cấu hình cũ vs DGF **bitwise giống nhau** (fp32 và fp16), band tích luỹ = 0. +Eval@0 lệch 7,6e-5 dB so với eval cuối của head8k — nguyên nhân là 4 buffer `schedule.*` trong EMA shadow của nguồn +bị **trôi làm tròn** (EMA áp lên buffer hằng: decay·x + (1−decay)·x ≠ x trong fp32 qua 8k bước); run mới dựng lại +schedule sạch từ args nên còn đúng hơn nguồn. Quirk vô hại nhưng đáng biết khi so bitwise giữa các run. + +### 13.19 DGF-8k: KẾT QUẢ ĐO (2026-09-02) — dự đoán liều KHÔNG thành, identity thành, và một phát hiện về Phase-1 + +Run `uformer_dgf8k_seed42` (warm-start head8k; dropout p=0,15 với token null học được; identity pairs q=0,10; tháp Laplacian 16/32/64 + deep supervision λ=0,1/0,2/0,3; LR 3e-5 cosine 8k, DDP). Best @6000 **27,499/0,8499** (w=1); cuối 27,454. + +**Sweep liều (val, coarse-step dose):** w=0 → 27,49/**0,852**, low 18,87, rain 22,62 (kỷ lục), noise 36,02; w=0,5 → **27,54** (kỷ lục macro); w=1 → 27,50; w=1,25 → 27,43. Đường cong PHẲNG: lowlight chỉ +0,13 tại w=0, KHÔNG phải +1,5 như dự đoán. +*Vì sao:* +1,95 đo trên head8k đến từ nhánh null *chưa train* (context=0 là input off-manifold → mạng under-restore → vô tình khớp các mẫu overshoot). Sau DGF nhánh null được train và **phục hồi tốt không cần chẩn đoán** (nó tự suy suy hoá từ u_y) → hai nhánh hội tụ, knob w mất đòn bẩy. **Kết luận về hệ: conditioning của Phase-1 phần lớn dư thừa với trunk này**; haze là domain còn dùng conditioning nhiều nhất (32,46@w0 → 32,81@w0,75). + +**Identity (ảnh sạch làm input, PSNR(f(x),x)):** head8k **27,8** (noise 23,6 — phá ảnh sạch thật) → DGF **40,4** (noise 41,4, low 36,2, haze 43,8) ở mọi w. Identity pairs làm đúng việc; +12,6 dB. + +**External:** w=1: rain 27,88 / haze **31,87** / scene008 26,50 (LPIPS **0,19** vs head8k 0,33); w=0: rain 27,78 / haze 31,60 / scene008 **24,93** (tệ hơn). Vis scene008: đây là cảnh **vải tối** (SIDD scene 008), input ≈ GT (43–44 dB); dose 0 → nhánh null **kéo sáng như lowlight** (12,8 dB, cháy); dose 1 → mờ + sáng nhẹ (26–32). Identity nội bộ 40 dB không chuyển sang đây vì ảnh sạch nội bộ (sáng, ít texture) không giống ảnh sạch tối có vân. + +**Chẩn đoán Phase-1 trên scene008 (routing/severity trung bình 20 ảnh):** degraded → noise 0,41 / low 0,29 / rain 0,27, sev_noise 0,35; **clean GT → GẦN Y HỆT** (noise 0,41, sev_noise 0,33). Đối chiếu val: SIDD noise thật → **rain 0,58, noise 0,04**; SIDD clean GT → lowlight 0,45 + free 0,50. → Phase-1 (a) đọc vân vải sạch thành "noise", (b) đọc SIDD noise thật thành "rain": **khái niệm noise của Phase-1 bị lệch**, severity noise không dùng được làm liều. Lỗi identity ngoài phân phối là lỗi hai tầng: chẩn đoán sai + trunk (kể cả nhánh null) tự đọc "tối" thành lowlight. + +**Ghi nhận thành phần:** tháp coarse-to-fine chưa ablate riêng (noise 36,0 / SSIM +0,004 có thể một phần từ đây). Định luật mới: (1) ablation "tắt điều kiện" trên model *chưa* train nhánh null đo lường sự rụt rè off-manifold, không đo giá trị của điều kiện; (2) identity phải được dạy bằng ảnh sạch **giống phân phối triển khai** (tối, có vân, real-camera), không chỉ GT nội bộ. + +**Việc tiếp theo có căn cứ:** (i) thí nghiệm quyết định cho claim "representation model": train nhánh null thuần (p=1) và so với có Phase-1 — nếu chênh < 0,3 dB, claim phải chuyển sang "Phase-1 = chẩn đoán/OOD + severity", không phải "điều kiện cho restoration"; (ii) sửa Phase-1 noise concept: thêm negatives clean-texture và real-noise positives (SIDD) vào null/severity supervision; (iii) identity pairs từ SIDD GT tối + clean-texture. Files: `sweep_v7_dose.py`, `visualize_scene008.py`; số đo `outputs/v7_dgf_dose_sweep.json`, `outputs/v7_dgf_external_w{0,1}.json`, `outputs/v7_head8k_identity.json`, `outputs/scene008_dgf.png`. + +### 13.20 Hai thí nghiệm quyết định đang chạy (launch 2026-09-02) + +**(1) Control "không Phase-1"** — `outputs/phase2_v7/uformer_nophase1_8k_seed42` (GPU0, 1 GPU, batch 8×accum 2): đúng recipe dgf8k nhưng `--cond-dropout-prob 1.0` (mọi mẫu dùng token null; sampler tự chạy hoàn toàn không điều kiện cho model p=1). Warm-start head8k. Eval@0 = 20,43 (nhánh null chưa train). Câu hỏi: hội tụ về đâu so với dgf8k 27,50/0,850 (w=1). Ngưỡng đọc: chênh >0,5 dB → Phase-1 có giá trị điều kiện thật; 0,2–0,5 → vai trò chẩn đoán/OOD; <0,2 → bỏ Phase-1 khỏi đường phục hồi. *Caveat*: control warm-start từ trọng số từng học có điều kiện — trả lời "có cần Phase-1 ở inference/fine-tune tiếp" chứ chưa phải "từ đầu"; nếu gần bằng, câu hỏi from-scratch còn lại nhưng claim thực dụng đã đủ. + +**(2) Phase-1 ll_v4 — sửa khái niệm noise** — `outputs/phase1_ll_v4` (GPU1, recipe ll_v3: 50 epoch, batch 32, fp32) + hai bổ sung: (a) `--noise-aug-prob 0.25`: với xác suất 0,25 biến cặp non-noise thành cặp noise bằng nhiễu Poisson-Gaussian dị phương sai trên sRGB (σ² = a·x + b, tuỳ chọn tương quan 3×3) hoặc **transplant residual SIDD thật** (ngân hàng 64 residual cuốn chiếu từ batch, lật ngẫu nhiên, gain 0,6–1,4); nhãn = noise, severity = cùng quy tắc residual-MAE với calibration noise. Mục đích: học thống kê nhiễu trên hàng nghìn cảnh thay vì thuộc 8 scene SIDD. (b) `--texture-null`: null_route có trọng số theo phương sai Laplacian của ảnh sạch (0,5–1,5) — ảnh sạch nhiều vân là hard negative của "noise". Tiêu chí thành công: SIDD val noise route → noise (hiện rain 0,58); scene008 clean GT → free/severity thấp (hiện noise 0,41/0,33); F1/null/rho không giảm. Sau đó Phase-2 phải warm-restart với Phase-1 mới (contract SHA đổi). + +**Cập nhật (2) — v4 dừng ở epoch 20, thay bằng v4b.** Chẩn đoán routing trên checkpoint v4 epoch 20 (`diagnose_phase1_routing.py`): scene008 clean → noise **0,81** (baseline ll_v3 0,41 — tệ hơn), SIDD val noise → rain 0,75 (baseline 0,58). Nhiễu Poisson-Gaussian tổng hợp dạy "hạt mịn trên ảnh có vân = noise" — trùng vân vải scene008; val_noise *clean* → lowlight/free (không rain) nên chính pattern nhiễu SIDD val bị đọc là rain — transplant residual 8 scene chưa phủ biên độ/cấu trúc đó. **v4b** (`outputs/phase1_ll_v4b`): transplant-only (`--noise-aug-synthetic-prob 0`), gain residual 0,5–2,5 (`--noise-aug-gain-max 2.5`), thêm OOD kind **sharpen** (unsharp mask → null: chi tiết mịn ≠ noise; lưu ý metric null_accuracy_ood đổi định nghĩa vs v3), giữ `--texture-null`. Baseline chẩn đoán ll_v3 lưu `outputs/phase1_ll_v3_routing_diag.json` (cũng lộ: LOL clean GT → haze 0,32 + noise 0,20). + +**v4b epoch 19 — chẩn đoán routing (cùng thước với v3):** scene008 clean → noise **0,84** / sev 0,64 (v3: 0,41/0,33; v4: 0,81/0,50); LOL clean GT → noise **0,64** (v3: 0,20); SIDD val noise → rain 0,54 + lowlight 0,43, noise 0,03 (không đổi); rain input → noise 0,29 (v3: 0,05). Kết luận sớm: **cả hai thiết kế augmentation đều đẩy khái niệm noise về "hạt tối kiểu SIDD"** và làm tăng dương tính giả trên ảnh sạch tối/có vân, trong khi ca thiếu (SIDD val noise) vẫn không được nhận. Với 8 scene SIDD huấn luyện, augmentation không tạo ra khái niệm noise khái quát được; F1 tổng thể vẫn ~v3 (0,73–0,77) nên model không hỏng, chỉ không đạt mục tiêu của (2). Để chạy hết 50 epoch (GPU1 rảnh) và chẩn đoán checkpoint cuối trước khi đóng nhánh. + + +**v4b kết thúc (50 epoch, best epoch 18 F1 0,774) — chẩn đoán cuối:** scene008 clean → noise 0,90/sev 0,67 (best) · 0,67 (last); LOL clean GT → noise 0,74 / 0,64; SIDD val noise → noise 0,08 / 0,05, rain 0,60 / 0,61. **Nhánh (2) đóng, âm tính**: với 8 scene SIDD, augmentation nhiễu (tổng hợp hoặc transplant) làm tăng dương tính giả trên ảnh sạch tối/có vân và không dạy được ca thiếu. Giữ ll_v3 làm Phase-1 chính thức. Số đo: `outputs/phase1_ll_v4b_routing_diag_{best,last}.json`. + + +### 13.21 Control "không Phase-1" — KẾT QUẢ (2026-09-02) + +`uformer_nophase1_8k_seed42` (p = 1, eval hoàn toàn không điều kiện, 1 GPU, cùng recipe/warm-start với dgf8k): 20,43 @0 → 26,49 @2k → 26,73 @4k → 27,03 @6k → **27,05 / 0,846 @8k** vs dgf8k 27,45 / 0,850 → **chênh −0,40 dB**. Theo domain @8k: haze −1,85 · noise −0,58 · lowlight **+0,94** (control hơn) · rain −0,12. Phán quyết theo ngưỡng §13.20: dải 0,2–0,5 → Phase-1 = chẩn đoán / OOD / hỗ trợ haze; restoration là công của trunk. Caveat warm-start (chưa from-scratch). Hình `outputs/final_charts/04_phase1_control.png`; deck `slides/build_deck.js`. + +### 13.22 Giải quyết #4 (global LL của Phase-1 không có giá trị) và #5 (noise kém refiner 0,9) — hai run A/B (launch 2026-09-02) + +**Chẩn đoán #4:** Phase-1 và trunk nhìn CÙNG một crop 256 → Phase-1 không mang thông tin nào trunk không tự suy được (control: 0,4 dB, chỉ haze). Cách duy nhất để "global" có giá trị thật: Phase-1 nhìn **toàn khung hình** (aspect-squash 256×256) và đưa vào trunk qua hai đường sống — cộng vào context tokens (Linear zero-init) và vào `global_vector` adaLN (Linear zero-init). Dataset trả thêm `full_degraded`/`full_clean`; runtime forward Phase-1 hai lần; sampler nhận `full_degraded`. Identity tại init (eval@0 = 27,498617 trùng bitwise dgf8k best). + +**Chẩn đoán #5:** refiner hai mạng thắng noise vì được pretrain bằng clean-image prior (clean + nhiễu nhẹ trên MỌI ảnh sạch); trunk chỉ thấy 121 cặp SIDD/8 scene. Tái tạo trong một mạng: cặp (clean + Poisson-Gaussian σ²=a·x+b, a∈[0,0005;0,02], b∈[0,0001;0,005], clean) với xác suất 0,20 trên clean của cả 4 domain, áp cùng tham số cho toàn khung; deterministic theo (seed, step, rank). Kèm tail full-res 3 → **6 block** (block mới identity: beta/gamma = 0; warm-start dung nạp `full_res_tail.body.N.*` mới). + +**Thiết kế A/B (2 GPU, 1 GPU mỗi run, batch 8×accum 2, warm-start dgf8k best, LR 3e-5, 8k):** +- A `uformer_p5_8k_seed42` (GPU0): recipe dgf8k + noise-pair 0,20 + tail 6. +- B `uformer_p45_8k_seed42` (GPU1): A + `--global-context`. +B − A = giá trị của toàn khung; A − dgf8k = giá trị của clean prior + tail. Tiêu chí: noise ≥ 36,9 (bằng refiner) cho #5; B − A ≥ 0,3 dB (đặc biệt haze/lowlight) cho #4. Sau đó external cần evaluator trả full frame (chưa làm; ghi chú). + +### 13.23 Run A (p5: clean-image prior + tail 6) — KẾT QUẢ, và chẩn đoán scene008 là lỗi exposure toàn cục (2026-09-03) + +**A trên val (EMA, 2-step):** best @6000 = **27,903 / 0,8591**, final @8000 = 27,883 / 0,8598 (lần đầu best ≠ final, chênh 0,02 dB — trong nhiễu). Quỹ đạo: 27,499 (0) → 27,667 (500) → 27,574 (1k) → 27,541 (2k) → 27,617 (3k) → 27,778 (4k) → 27,903 (6k) → 27,883 (8k). 3 overflow AMP (step 4072, 6289, 7042), supervisor relaunch 3 lần, 0 step mất. Per-domain @6000: haze 33,08 · lowlight 19,05 · **noise 36,95** · rain 22,53. **#5 đạt** (mốc 36,9 = refiner hai mạng). So với dgf8k best (27,498): +0,41 dB macro. + +**Baseline ảnh hỏng của val** (đo lần đầu, center-crop 256): rain 21,25/0,673 · lowlight 9,77/0,195 · haze 17,31/0,829 · noise 27,33/0,507. Hệ quả: rain val chỉ +1,3 dB trong khi rain external +5,3 dB — tập rain val (98 cặp, 95 cảnh) toàn mưa nặng và GT Rain13K lệch tone/độ nét so với ảnh hỏng (vd. zebra: mưa xoá sạch, SSIM 0,785→0,851 nhưng PSNR 23,60→21,53). Rain val PSNR do đó là thước đo yếu; đọc SSIM. + +**A external** (`outputs/v7_p5_external_v1.json`, protocol khoá): rain 27,867 / 0,8367 / LPIPS 0,1224 · scene008 **27,125 / 0,8528 / 0,1538** · haze 31,544 / 0,9756 / 0,0095. So với dgf8k(w=1): rain bằng, haze −0,33 PSNR (SSIM bằng), scene008 +0,6 PSNR / +0,03 SSIM / −0,04 LPIPS — tốt nhất trong các run v7 nhưng vẫn kém xa input (39,02 / 0,954). + +**Chẩn đoán scene008 (`probe_scene008_tone.py`, `outputs/v7_p5_scene008_tone.json`):** một phép affine toàn cục (gain+bias khớp GT trên luma, per-image) áp lên output nâng PSNR trung bình 27,13 → **35,87** (dose 1) / 26,76 → **36,43** (dose 0), SSIM 0,853 → 0,930 / 0,858 → 0,943. ⇒ ~9 trong 12 dB thiệt hại là **lệch exposure toàn cục**, không phải mất texture. Ba nhóm: +- luma 0,21–0,27 (9/20 ảnh): output bị kéo tối ~0,06–0,08 trên cả 3 kênh → 22–23 dB, sau khớp 36–38. +- luma 0,06–0,09 (2 ảnh): bị nâng sáng lên 0,34–0,42 (8,5 và 30 dB ở dose 1; 9,2 và 11,5 ở dose 0) → xử lý như lowlight. +- luma ≈0,13 (5 ảnh): 43 → 34 dB và khớp affine KHÔNG cứu (34,2) → đây mới là phần smoothing texture vải (~9 dB). +Ở **dose 0 lỗi còn nặng hơn** (0b7d0ffa: 0,09 → 0,34 thay vì 0,11 khi có điều kiện) ⇒ exposure regression nằm ở **trunk** — prior "tối → làm sáng, vừa → kéo về ~0,18" học từ phân bố train (ảnh tối trong train hầu như luôn là lowlight có GT sáng; clean train hầu như không có ảnh tối/texture). Phase-1 đang *giảm* lỗi này chứ không gây ra. + +**Routing Phase-1 (ll_v3) trên scene008 (`outputs/phase1_ll_v3_routing_scene008.json`):** input noise 0,41 · lowlight 0,29 · rain 0,27 · free2 0,04; clean gần y hệt (noise 0,41 · lowlight 0,28 · rain 0,22 · free2 0,09) — Phase-1 không bao giờ gọi scene008 là "sạch" (clean val của domain khác: free2 0,45–0,95), nhưng severity lowlight chỉ 0,04 nên lệnh "làm sáng" không đến từ Phase-1. Ghi nhận thêm: SIDD **val** noisy được route rain 0,58 / noise 0,04 — tập noise val (1 cảnh) không được Phase-1 nhận là noise; #5 đạt là nhờ trunk + clean prior, không nhờ routing. + +**Kết luận A:** #5 đóng dương (noise 36,95 in-dist; scene008 tốt nhất v7). Vấn đề scene008 đổi tên: không phải "khử chưa sạch" mà là **exposure prior của trunk trên ảnh clean tối/vừa + smoothing texture ở vùng rất tối**. Hướng sửa có bằng chứng: identity pairs (q) lấy từ clean **đa dạng exposure** (dark/textured thật, không chỉ clean train sáng) + ràng buộc luma-pooled trên identity pairs; đây là việc đã hoãn ở §13.17, giờ có số để ưu tiên. B (whole-frame context) đang chạy, ghi ở §13.24. + +### 13.24 Run B (p4+p5: whole-frame Phase-1 context) — KẾT QUẢ và kết luận #4 (2026-09-03) + +**B trên val (EMA):** best @6000 = **27,806 / 0,8610** (SSIM cao nhất mọi run), final @8000 = 27,751 / 0,8605. Quỹ đạo: 27,499 → 27,613 (500) → 27,468 (1k) → 27,523 (2k) → 27,517 (3k) → 27,618 (4k) → 27,806 (6k) → 27,751 (8k). 2 overflow AMP (4200, 6678), 0 step mất. Per-domain @6000 (PSNR/SSIM): haze 32,55/0,979 · lowlight 19,43/0,776 · noise 36,72/0,912 · rain 22,52/0,778. + +**B − A trên val @6000:** macro **−0,10 dB / +0,002 SSIM**; haze −0,53 · lowlight **+0,38** (SSIM +0,011) · noise −0,23 · rain −0,01. Ba mốc 3k/4k/6k đều âm (−0,10 / −0,16 / −0,10). Tiêu chí §13.22 (B − A ≥ 0,3 macro, đặc biệt haze/lowlight): **không đạt** — lowlight đạt, haze ngược dấu, macro âm. + +**B external** (`outputs/v7_p45_external_v1.json`, evaluator truyền full frame): rain 27,787 / 0,8349 / 0,1236 · scene008 **28,148 / 0,8549 / 0,1635** · haze **31,924 / 0,9754 / 0,0094**. So với A: rain −0,08 · haze **+0,38** · scene008 **+1,02**. Cả hai bộ haze (300 cảnh RESIDE held-out) và scene008 đều nghiêng về B; haze val (3 cảnh gốc, §13.23) và haze external (300 cảnh) **ngược dấu** ⇒ haze val không đủ để phán xử #4. + +**Probe tone scene008 cho B (đúng cấu hình, có full frame; `outputs/v7_p45_scene008_tone.json`):** dose 1 28,15 → khớp affine 35,88; luma output trung bình **0,208 = GT 0,204** (A: 0,187). Nhóm luma 0,21–0,27 bớt bị kéo tối rõ rệt: 132b6470 22,4 → 25,8 · 80bf4639 23,4 → 29,7 · 25e98c05 22,9 → 30,6 · 7520151c 27,4 → 32,8 (output luma 0,195–0,254 thay vì 0,16–0,23). Nhưng ảnh rất tối 0b7d0ffa bị nâng mạnh hơn (0,11 → 0,26; 30,0 → 14,7): toàn khung scene008 tối nên context toàn khung càng "khẳng định lowlight". Nhóm luma ≈0,13 không đổi (texture smoothing, không phải tone). ⇒ Context toàn khung đúng là mang **thông tin exposure toàn ảnh** mà crop không có, và nó sửa được phần "kéo tối" của exposure prior; nó không sửa được phần "nâng sáng ảnh rất tối" (vì cả ảnh đều tối) và không đụng tới texture. + +**Lưu ý infra:** `probe_scene008_tone.py` và `visualize_scene008.py` ban đầu gọi `restore()` không truyền `full_degraded` → model `--global-context` chạy thiếu nhánh toàn khung (28,15 external vs 26,69 probe). Đã sửa cả hai (truyền `full_degraded` khi dataset có); mọi công cụ gọi `restore()` với model B phải truyền full frame. + +**Kết luận #4:** "Phase-1 mất global (LL)" được sửa đúng cơ chế — thông tin global có giá trị thật chỉ khi Phase-1 nhìn **ngoài crop**; giá trị đó nằm ở exposure toàn ảnh (lowlight +0,38 val; scene008 +1,0; haze external +0,38) chứ không phải ở "LL của cùng crop" (§13.21: 0,4 dB). Trên val in-dist nó trả giá −0,1 dB macro (haze val 3 cảnh, noise 1 cảnh). **Không đạt mốc +0,3 tự đặt** nên không claim "global context cải thiện"; claim đúng: *whole-frame context là lựa chọn robustness: hơn A trên 2/3 bộ external và SSIM val, kém 0,1 dB PSNR val*. Checkpoint đề xuất làm bản cuối: **A** cho leaderboard in-dist (27,90) / **B** cho triển khai OOD (external haze + nearly-clean). Việc mở còn lại có bằng chứng: identity pairs đa dạng exposure (sửa phần "nâng sáng ảnh rất tối" + texture smoothing), multi-seed, benchmark công khai. + +### 13.25 Dashboard "sanity" cho Phase-1 — cơ chế visualize để xác nhận tính hợp lý của graph state (2026-09-03) + +**Công cụ:** `visualize_phase1_graph.py --checkpoint --output-dir outputs/phase1_vis/` (GPU, ~2 phút). Sinh: `cases_.png` (mỗi ảnh: input | routing 6 node | severity 4 nhánh | 4 spatial map 16×16 kèm max | map của node top chồng lên ảnh, cho cả ảnh hỏng và clean GT của nó), `cases_scene008.png`, `confusion.png` (argmax routing theo nhóm input trên toàn val, gồm cả clean GT), `severity_calibration.png` (severity nhánh đúng vs MAE residual thô, Spearman ρ), `severity_ramp.png` (ramp đơn điệu trên clean val: Gaussian σ, haze đồng nhất 1−t, giảm gain, streak tổng hợp, **và residual thật của SIDD / Rain13K nhân gain 0→1,5**), `ood.png` (snow/blur/pixelate/sharpen từ `synthesize_ood`), `summary.json`. Đây là bài kiểm tra bắt buộc cho mọi checkpoint Phase-1 trước khi cắm vào Phase-2. + +**ll_v3 (Phase-1 chính thức):** +- Routing argmax trên val: rain 0,62 (free2 0,28) · **noise 0,05** (rain 0,53, lowlight 0,32) · haze 0,51 (**rain 0,46**) · lowlight 0,96. Clean GT: haze → free2 1,00; rain → free2 0,65; noise → lowlight 0,47 / free2 0,47; lowlight → free2 0,48 / rain 0,29. +- Severity ρ (nhánh đúng vs MAE): haze 0,73 (ba đường sigmoid, mỗi đường một cảnh gốc với β tăng — đơn điệu trong cảnh, lệch offset giữa cảnh), lowlight 0,50, noise 0,41, rain 0,30; severity trung bình nhánh đúng: lowlight 0,56, haze 0,31, rain 0,17, **noise 0,07**. +- Ramp: lowlight hoàn hảo (routing 0,30 → 1,00, severity 0,10 → 0,67 đơn điệu); haze đơn điệu tới 0,56 rồi haze đặc (1−t = 0,75) rơi vào free2 0,63; **residual SIDD thật nhân gain → node RAIN 0,74, node noise 0,01**; Gaussian σ = 0,12 → rain 0,82. Residual Rain13K thật → rain 0,62 (đúng). +- OOD: snow / blur / pixelate → free2 0,93 / 0,96 / 0,97 (null detection rất tốt); sharpen → hỗn hợp (rain 0,25, lowlight 0,20, free2 0,44). Clean pool → free2 0,64. +- Spatial map 16×16: gần như trống (max thấp) trừ haze đặc — nhất quán với probe §13.16 (spatial inject ≈ 0). +- scene008: input và clean gần y hệt (noise 0,41 / lowlight 0,29 / rain 0,27, free2 ≤ 0,09). + +**ll_v4b (đã đóng âm ở §13.19, chạy để kiểm tra dashboard có phân biệt được không):** node noise "tỉnh" với residual SIDD thật ở gain nhỏ (0,52 @0,25) nhưng suy giảm khi gain tăng (rain 0,48 @1,5) — noise = "nhiễu nhẹ", nhiễu nặng vẫn là rain; đổi lại **dương tính giả tràn lan**: clean GT của rain → noise 0,48, của lowlight → noise 0,67, của haze → noise 0,30; clean pool ở gain 0 → noise 0,36; scene008 → noise 0,90 cả input lẫn clean; snow → noise 0,35, sharpen → noise 0,40; free2 cho clean sụp (lowlight clean 0,04). Dashboard tái hiện đúng lý do đóng âm bằng hình. + +**Đọc cho điểm 6 (giá trị Phase-1 và nợ kiến trúc):** +1. Graph state **hợp lý ở 2,5/4 nhánh**: lowlight xuất sắc, haze khá (severity đơn điệu, nhưng haze nhẹ bị gọi là rain), rain đúng với residual thật; **nhánh noise chết** — "rain" đã trở thành node "nhiễu loạn cộng tần số cao" nói chung. Nhãn ngữ nghĩa của MoE per-type vì thế không đáng tin cho noise, phù hợp với việc gate MoE ≈ 0 khi suy luận. +2. **Null/OOD detection là phần đáng giá nhất** của Phase-1 (0,93–0,97 cho unknown có cấu trúc; clean thật → free2 phần lớn) và là thứ Phase-2 không tự có. Khi cắt đầu cắm chết, giữ: routing/free-mass (chẩn đoán), severity haze/lowlight, `unknown_residual`, `global_condition`; cắt được: spatial maps, content inject, MoE gate/κ per-type. +3. Nhánh noise chỉ sống lại bằng dữ liệu nhiễu thật nhiều cảnh (§13.19), không bằng loss — v4b là minh chứng hình ảnh. +4. Với bài viết: hình `confusion.png` + `severity_ramp.png` + `ood.png` là bộ ba figure đủ để claim "representation = chẩn đoán có hiệu chuẩn + null detection", và cũng đủ trung thực để nói nhánh noise chưa đạt. + +### 13.26 Snow100K và mục tiêu "phân tách khoảng cách" cho Phase-1 (2026-09-03, đang chuẩn bị) + +**Đề xuất (user):** tải Snow100K, train lại Stage 1 với mục tiêu tách được khoảng cách giữa các loại suy hoá trong biểu diễn. + +**Dữ liệu:** Snow100K (Liu et al., DesnowNet 2018): train 50k (7,8 GB), test 50k (7,8 GB, chia S/M/L), realistic 1329 ảnh (67 MB); file tải về là tar.gz dù đặt tên .zip. Đã tải về `/home/admin_mcn/data/Snow100K/` (realistic xong; train đang tải ~6,5 MB/s). + +**Đo trước khi làm gì (ll_v3 trên 1329 ảnh tuyết thật, center-crop 256):** routing trung bình free2 **0,50** · rain **0,37** · haze 0,08 · lowlight 0,05 · noise 0,01; severity rain 0,10. ⇒ Snow tổng hợp (blob) trong `synthesize_ood` đã dạy "snow → free2 0,93" nhưng **không tổng quát sang tuyết thật**: một nửa tuyết thật bị gọi là mưa. Tuyết thật vì thế là negative "khó" đúng nghĩa cho node rain — cùng trục "nhiễu loạn cộng tần số cao" mà dashboard §13.25 chỉ ra đã sụp (noise thật → rain 0,74). ll_v4b còn tệ hơn: noise 0,41 / rain 0,23 / free2 0,28. + +**Chẩn đoán cấu trúc:** `BranchSeparationLoss` hiện tính khoảng cách margin trên **vector routing softmax 4 chiều**, không phải trên embedding; Geodesic/Ranking tác động lên scalar routing×severity; Sparse là L1 trên routing. Không có hạng mục nào ép embedding của rain / noise / snow tách nhau, nên encoder chọn biên rẻ nhất: "cộng tần số cao → rain", "trông như cảnh SIDD → noise". Muốn "phân tách distance" thì phải đưa metric về không gian readout (pooled feat ‖ LL-global) hoặc node token. + +**Hai phương án (chờ quyết định):** +- **A — snow là node known thứ 5 (+ khả năng khử tuyết):** Phase-1 `num_semantic_branches` 5 → mọi shape phía Phase-2 đổi (node tokens 7, MoE 6 expert, κ per-type 6, conditioner), cần thêm cặp Snow100K vào Phase-2 và cân lại sampler; gần như train lại Phase-2 từ warm-start bán phần. Chi phí ~2–3 ngày GPU; được thêm một domain. +- **B — snow thật là "unknown" thật trong objective null + loss metric trên embedding:** thay snow blob tổng hợp bằng Snow100K trong nhánh OOD (giữ blur/pixelate/sharpen), thêm `EmbeddingSeparationLoss` (supervised-contrastive trên readout chuẩn hoá L2, nhiệt độ 0,1; lớp = 4 known + clean; unknown bị đẩy xa mọi known nhưng không ép thành một cụm) và giữ CE routing. Shape Phase-2 không đổi; chỉ cần re-warm-start Phase-2 (8k) với SHA Phase-1 mới. Chi phí ~1 ngày. Không thêm khả năng khử tuyết; realistic 1329 dùng làm bộ OOD test thật. +- Cả hai đều **không** cứu node noise nếu không có dữ liệu nhiễu thật nhiều cảnh (§13.19, §13.25). + +**Cổng đánh giá cho Phase-1 mới (dashboard §13.25 + realistic snow):** tuyết thật → free ≥ 0,85 (từ 0,50); haze val → rain ≤ 0,15 (từ 0,46); rain val → rain ≥ 0,80 (từ 0,62); clean GT → free ≥ 0,80 mọi domain; silhouette của readout theo lớp tăng; Phase-2 re-warm-start không mất dB trên val/external. + +### 13.27 Kiểm chứng ý tưởng "controllable cho màu" (HVI / CIDNet) bằng probe không train (2026-09-03) + +**Ý tưởng (user):** thay vì để LL/HH kiểm soát tất cả, thêm một controllable riêng cho màu trong không gian màu tách sáng khỏi màu, ví dụ HVI của CIDNet (CVPR 2025: I = max(R,G,B); mặt HV = C_k·S·(cos 2πh, sin 2πh) với C_k = (sin(πI/2)+ε)^k làm co mặt màu ở pixel tối; k học được; CIDNet = 2 nhánh UNet HV/I với cross-attention I→HV). + +**Đã làm:** `src/models/graph_encoder/hvi.py` (HVIT/PHVIT khả vi, 13 thống kê màu `hvi_colour_stats`, 5 unit test pass), `probe_color_space.py`, `probe_global_knob.py`; kết quả `outputs/color_space_probe.json`, `outputs/global_knob_probe.json`. + +**H1 — biểu diễn (linear probe 5-fold, 6 lớp: 4 domain hỏng + sạch + tuyết thật, balanced acc):** photometric14 hiện tại **0,765** · YUV11 0,816 · HVI13 0,821 · RGB14+HVI13 **0,843**. Chỉ đặc trưng màu: RGB(3 mean) 0,62 · YUV chroma 0,70 · HVI chroma 0,66. Tăng nằm ở tuyết thật (0,49→0,78) và haze (0,88→0,98). ⇒ Phase-1 **thiếu thống kê màu** và bù vào thì lợi +5–8 điểm; nhưng ở mức biểu diễn HVI ≈ YUV, phần "intensity collapse" không phải thứ tạo khác biệt. + +**H3 — trần của núm toàn cục (affine oracle per-image trên output của A, khớp GT):** + +| Domain | raw | núm I (2 tham số) | núm HV (6 tham số) | cả hai | +|---|---|---|---|---| +| lowlight | 19,05 | **26,29** | 19,60 | 27,20 | +| scene008 | 27,13 | **33,10** | 28,07 | 35,69 | +| rain val | 22,53 | 25,81 | 23,02 | 26,94 | +| haze | 33,08 | 34,49 | 33,16 | 34,75 | +| noise | 36,95 | 36,99 | 37,15 | 37,27 | + +Núm **cường độ** đáng +7,2 dB ở lowlight và +6 dB ở scene008; núm **màu** chỉ +0,5–0,9 dB. (H2 "tỉ phần lỗi HV/I" không dùng được để so vì thang HV và I khác nhau; H3 là thước đo công bằng.) + +**H3b — phần dự đoán được từ input (ridge 5-fold trên photometric14+HVI13 của crop và toàn khung → hệ số oracle, rồi áp hệ số dự đoán):** + +| Domain | raw | dự đoán theo domain, núm I | dự đoán theo domain, cả hai | chỉ gain trung bình domain | R² I | oracle gain a (GT = a·out + b) | +|---|---|---|---|---|---|---| +| lowlight | 19,05 | **22,13** | 22,32 | 21,73 | 0,29 | 0,82 ± 0,14 | +| rain val | 22,53 | 23,83 | 24,10 | 23,16 | 0,33 | 0,91 ± 0,09 (b = 0,07) | +| haze | 33,08 | 34,25 | 34,40 | 33,24 | **0,77** | 1,02 ± 0,03 | +| scene008 | 27,13 | 29,15 | 29,88 | 27,58 | 0,26 | 0,95 ± 0,17 | +| noise | 36,95 | 36,92 | 36,42 | 36,94 | — | 1,00 ± 0,01 | + +Predictor **pooled** (một mô hình tuyến tính cho mọi domain) làm noise sụp −6,8 dB và haze −0,7 → mọi núm phải mặc định identity, co (shrinkage) mạnh và có cổng theo độ tự tin. Đọc: (i) phần *dự đoán được* của núm exposure là ~+3 dB lowlight, +1,2 haze, +1,3 rain, +2 scene008; (ii) phần lớn của nó là **thiên lệch hệ thống theo domain** — A đang *thừa sáng* lowlight ~18% (a = 0,82) và chưa nâng tone rain val (a = 0,91, b = 0,07 = lệch tone GT Rain13K); chỉ áp gain trung bình domain đã lấy được 21,73 ở lowlight; (iii) phần còn lại (R² ≈ 0,3) là exposure GT do người chụp chọn, không phục hồi được từ thống kê toàn cục — đúng với lập luận cũ, nhưng lập luận cũ đã bỏ sót phần thiên lệch hệ thống; (iv) haze là ngoại lệ đẹp: R² 0,77, núm exposure gần như dự đoán được hết. + +**Kết luận cho ý tưởng:** *không* nên xây một nhánh màu HV riêng trong Phase-1 để điều khiển màu — trần chỉ +0,5–0,9 dB và phần dự đoán được ≈ +0,2–0,7. Thứ đáng xây là **một controllable toàn cục cho cường độ** (2 tham số per ảnh, dự đoán từ representation toàn khung, zero-init về identity, có dose), giá trị đo được +1–3 dB ở lowlight/rain/haze và sửa luôn thiên lệch thừa sáng lowlight. HVI vẫn hữu ích ở hai chỗ khác: (a) 7 thống kê màu (HVI hoặc YUV) bổ sung vào `photometric_stats` của Phase-1 v5 (+5–8 điểm phân tách, đặc biệt tuyết thật và haze); (b) không gian loss chroma của Phase-2: L1 trên mặt HV với C_k tự động giảm trọng số chroma ở pixel tối — ứng viên thay UV-L1, cần một run để kiểm. Việc dùng CIDNet nguyên bản (2 nhánh UNet) không phù hợp vì Phase-2 đã là một trunk thống nhất; chỉ mượn không gian màu và ý "tách I khỏi HV" cho head điều khiển. + +**Thiết kế đề xuất (để làm cùng B):** `GlobalPhotometricHead`: từ `global_condition` (+ nhánh toàn khung) dự đoán Δ = (log a, b) cho I và, tuỳ chọn, (2×2, bias) cho HV; áp trên output HVI của Phase-2 rồi PHVIT về RGB; zero-init (identity), loss chung, conditioning-dropout riêng cho Δ để có dose; đo bằng chính hai probe này (oracle vs đạt được) và cổng: lowlight ≥ 21,5 val, noise không đổi, external rain/haze không giảm. + +### 13.28 Phase-1 v5 và Phase-2 v8 — thiết kế đã hiện thực và phóng (2026-09-03) + +**Đính chính §13.26:** trainer v2 (`train_graph_encoder_v2.py`) không dùng `CombinedGraphLoss`/`BranchSeparationLoss` của `losses.py`; objective thực tế là `Phase1GraphObjective` (route CE, global-type CE, severity, root, content, unknown, spatial, null, ood). Kết luận không đổi: chưa từng có hạng mục metric nào trên embedding. + +**Phase-1 v5 (`outputs/phase1_v5`, GPU1, phóng 12:28, ~2,5 phút/epoch × 50):** +- `PhotometricBranch` (`encoder.py`): HVI(Ĥ,V̂,I) 32×32 → conv → 8×8 token → 1-query attention (64) ‖ 13 `hvi_colour_stats` → MLP (64) → LayerNorm 128-d `photometric_state`; k học được (`log_k`, init 0,2, kẹp [0,05; 2]); `shift_head` 128→8 zero-init dự đoán photometric shift. Cắm: ghép vào readout của `GraphStatePredictor` (readout 384-d = feat 128 ‖ LL 128 ‖ photometric 128), cộng zero-init vào `global_condition` (`photometric_condition`), xuất `photometric_state` / `photometric_shift` / `readout` trong `GraphRepresentation` (None trên checkpoint cũ; ll_v3 vẫn load). +- Loss mới trong `Phase1GraphObjective`: `embed` = supervised-contrastive (τ 0,1) trên projector(readout) với lớp {4 known, clean=4, unknown=5 chỉ làm negative}, gồm degraded + clean cặp + clean pool + OOD; `photometric` = smooth-L1 giữa `photometric_shift` và oracle affine HVI từ cặp (`photometric_shift_targets`: log-gain, bias trên I; 2×2+bias trên HV; clean → 0); `extra_null` = kéo clean pool vào free slot + severity/residual ≈ 0. Trọng số 0,5 / 0,5 / 0,15. +- Dữ liệu: `--ood-real-root` Snow100K `synthetic` (49.936 train, 512 giữ lại → `null_accuracy_ood_real` vào selection key), xác suất 0,5 thay batch OOD tổng hợp (bỏ snow blob, giữ blur/pixelate/sharpen); `--extra-clean-root` Snow100K `gt` (49.936, loại trùng tên với 512 giữ lại). `src/data/folder_crops.py` dùng chung hai trainer. +- Test: `tests/test_phase1_v5.py` (8) + `tests/test_hvi.py` (5) + `test_train_graph_encoder_v2.py` → 62 pass trên server (torch 1.10). Smoke 1 epoch × 8 step sạch. + +**Phase-2 v8 (`run_uformer_v8a.sh` GPU0, `run_uformer_v8b.sh` GPU1; phóng tự động bởi `run_v8_after_v5.sh` sau khi Phase-1 v5 xong và qua cổng):** +- `GlobalPhotometricHead` (`train_phase2_unified_v7.py`): MLP 768→128→2 trên [global_condition ‖ photometric_state] của crop và của toàn khung (0 khi thiếu) → (log-gain, bias) kẹp tanh (±0,7; ±0,2), áp `a·x+b` trên output sau tail+FiLM; zero-init (identity bitwise), `--photometric-dropout 0,15` per-sample giữ đường identity, `photometric_dose` khi suy luận (`eval_v7_external.py --photometric-dose`). Chọn affine RGB thay vì I-affine trong HVI vì cùng trần đo được (35,87 vs 35,9 dB scene008) và không có gradient qua atan2. +- Identity pairs đa dạng exposure (`exposure_diverse_identity` trong runtime v4): với hàng identity, xác suất 0,5 đổi clean sang crop từ pool Snow100K gt (kèm full frame squash), rồi nhân gain exp(U(−0,9; 0,9)) cho cả input lẫn target, kẹp [0,1]; xác suất identity nâng 0,10 → 0,15. +- `--fine-chroma-space uv|hv`: v8a giữ UV (BT.601), v8b dùng mặt HV của HVI (C_k giảm trọng số chroma pixel tối) — ablation duy nhất giữa hai run. +- Recipe còn lại = B (global-context) + A (noise pairs 0,20, tail 6), warm-start `uformer_p5_8k_seed42/best.pt`, Phase-1 = v5 best, 8k step, LR 3e-5. +- Cổng trước khi phóng (`run_v8_after_v5.sh` → `outputs/phase1_v5_gate.json`): tuyết thật → free ≥ 0,70 (từ 0,50), haze → rain ≤ 0,30 (từ 0,46), rain → rain ≥ 0,55, lowlight → lowlight ≥ 0,85; kèm dashboard `outputs/phase1_vis/ll_v5`. +- Test: `tests/test_unified_v8.py` (6): head identity/bound/dose/dropout, loss bitwise không đổi khi head zero-init, HV chroma hữu hạn và khác UV, identity pairs xác định và giữ cặp (x, x), parser + architecture record. + +**Nhật ký chạy v5 (2026-09-03, chiều):** (1) run đầu crash ở epoch 8: `torch.linalg.solve` batched 3×3 trên CUDA của torch 1.10 ném "misaligned address" (bug cuSOLVER cho ma trận nhỏ, ngẫu nhiên) → giải trên CPU fp64, phóng lại 12:59 (quỹ đạo xác định, trùng số). (2) Đến epoch 9: F1 v5 0,60 so với ll_v3 0,72 cùng epoch; ma trận nhầm lẫn cho thấy hụt **toàn bộ ở noise** (recall 0,21 vs 0,68; 11–12/19 ảnh SIDD val → free slot), haze / rain / lowlight tương đương. Nguyên nhân cấu trúc: tuyết thật + 50k ảnh sạch dạy "hạt/texture ngoài 4 domain → null" và node noise 8 cảnh không cạnh tranh nổi; SupCon coi unknown là negative của noise. (3) Chạy song song **v5b** trên GPU0 (`--embed-weight 0.25 --extra-null-weight 0.05 --ood-real-prob 0.35`) làm bảo hiểm; chuỗi `run_v8_after_v5.sh` giờ chờ cả hai, chấm cổng cho cả hai (`outputs/_gate.json`, có thêm `noise_recall` và `best_val_macro_f1`), chọn ứng viên qua cổng có F1 cao hơn làm Phase-1 cho v8a/v8b (qua biến `PHASE1_CKPT`). + +### 13.29 Phase-1 v5 / v5b — kết quả cuối, cổng, và quyết định phóng v8 (2026-09-03, 17:15–17:40) + +**Hai run xong 50/50 epoch (không NaN, không crash sau fix cuSOLVER).** v5 (`embed 0,5 / extra_null 0,15 / ood_real 0,5`) best epoch **4**, F1 val 0,629, sau đó dao động 0,55–0,60 tới cuối; v5b (`embed 0,25 / extra_null 0,05 / ood_real 0,35`) best epoch **17**, F1 0,668, cuối 0,617. Cả hai dưới ll_v3 (0,793). Dashboard (`outputs/phase1_vis/phase1_v5{,b}`) và cổng (`outputs/phase1_v5{,b}_gate.json`): + +| Chỉ số (argmax routing trên val trừ khi ghi khác) | ll_v3 | v5 | v5b | +|---|---|---|---| +| F1 val (best epoch) | 0,793 (ep 16) | 0,629 (ep 4) | 0,668 (ep 17) | +| rain → rain / → free | 0,62 / 0,28 | 0,37 / 0,54 | **0,24 / 0,72** | +| noise → noise / → rain | 0,05 / 0,53 | 0,05 / 0,68 | **0,00** / 0,63 | +| haze → haze / → rain / → free | 0,51 / 0,46 / – | 0,35 / 0,49 / 0 | 0,35 / **0,00** / 0,65 | +| lowlight → lowlight | 0,96 | 0,99 | 0,95 | +| clean GT → free (haze / rain / noise / lowlight) | 1,00 / 0,65 / 0,47 / 0,48 | 1,00 / 0,76 / 0,79 / 0,75 | 1,00 / 0,94 / 0,74 / 0,92 | +| Tuyết thật Snow100K → free | 0,50 | 0,71 | **0,92** | +| OOD tổng hợp snow / blur / pixelate → free | 0,93 / 0,96 / 0,97 | 0,73 / 0,90 / 0,97 | 0,99 / 0,99 / 1,00 | +| scene008 (input) → noise | 0,41 | 0,86 | 0,70 | +| Severity ρ haze / lowlight / noise / rain | 0,73 / 0,50 / 0,41 / 0,30 | 0,65 / 0,38 / 0,89 / 0,32 | 0,70 / 0,46 / **−0,42** / 0,34 | +| Locked test (rain 1200 + noise 20): F1 / null clean / null OOD / noise acc / rain acc | – | 0,775 / 0,79 / 0,87 / 0,95 / 0,63 | 0,679 / 0,95 / 0,96 / 0,70 / 0,36 | +| Cổng (4 điều kiện) | – | 2/4 (trượt haze→rain 0,49; rain→rain 0,37) | 3/4 (trượt rain→rain 0,245) | + +**Đọc kết quả.** +1. **Free slot thành "hố hút":** tuyết thật + 50k ảnh sạch + SupCon coi unknown là negative đã dạy free1 = "mọi thứ không phải lowlight". Rain và haze rò sang free ồ ạt (v5b: 0,72 và 0,65), node noise chết hẳn (ρ −0,42). Mục tiêu "phân tách khoảng cách" (§13.26) chỉ đạt trên trục **known ↔ unknown** (clean GT → free 0,74–1,00; tuyết thật 0,92; OOD 0,99), không đạt giữa các loại đã biết — cấu trúc 4 node yếu đi. +2. **Phần được:** null detection tốt nhất từ trước tới nay, haze → rain của ll_v3 (0,46) biến mất ở v5b (0,00), severity haze/lowlight giữ nguyên, lowlight vẫn ~0,95–0,99. Locked-test null accuracy 0,95/0,96 (v5b) so với 0,79/0,87 (v5). +3. **Vì sao best epoch sớm rồi phẳng:** loss `embed` ~1,8 gần như không giảm suốt 50 epoch (SupCon trên readout với batch cân lớp nhưng khối lượng clean/unknown lớn) và kéo readout về phân cụm known/unknown thay vì 4 loại; giảm trọng số (v5b) chỉ đỡ một phần. Kết luận giữ nguyên với §13.25: node noise chỉ sống lại bằng dữ liệu nhiễu thật nhiều cảnh, không bằng loss. +4. **Tên gọi v8 sau khi cổng trượt:** chuỗi `run_v8_after_v5.sh` dừng đúng thiết kế ("GATE FAIL for every candidate; NOT launching v8"). Theo chỉ đạo "Phase 1 xong train luôn Phase 2", phóng thủ công lúc 17:25: + - **v8a** (`run_uformer_v8a.sh`, GPU0) với `PHASE1_CKPT=outputs/phase1_ll_v3/graph_encoder_best.pt` (`a05d4bd1…`): cô lập head phơi sáng + identity đa exposure so với A trên **cùng** Phase-1. `GlobalPhotometricHead` nhận `photometric_state = 0` khi checkpoint không có nhánh photometric (đã kiểm chứng bằng smoke trước đó: eval@0 = 27,9026 = A). + - **v8c** (`run_uformer_v8c.sh`, GPU1, mới): đúng recipe v8a (UV chroma) nhưng Phase-1 = **v5b** (`dcb82b62…`) — trả lời trực tiếp "Phase-1 mới có giúp Phase-2 không". **v8b (HV chroma) hoãn**: probe §13.27 cho thấy nút màu HV chỉ đáng +0,5–0,9 dB, câu hỏi Phase-1 quan trọng hơn cho 8 giờ GPU. + - `run_v8_postrun.sh` nhận `A_TAG`/`B_TAG` (đã phóng lại với `B_TAG=v8c`). +5. **eval@0 (cùng trọng số A, chỉ đổi điều kiện hoá):** v8a **27,903** (haze 33,08 · lowlight 19,05 · noise 36,95 · rain 22,53) — identity bit-exact với A; v8c **24,786** (haze **24,05** · lowlight 19,54 · noise 33,79 · rain 21,76). Đổi Phase-1 sang v5b làm thân mạng warm-start mất 3,1 dB macro ngay step 0, tập trung ở haze (−9,0: haze giờ đi vào free slot nên expert/κ per-type sai) và noise (−3,2); lowlight +0,5 (nhánh photometric đã có ích cho FiLM ngay cả khi head còn zero). Đánh giá v8c theo mức hồi phục ở 2k–8k; lưu ý bất lợi có hệ thống: thân mạng được huấn luyện dưới điều kiện hoá ll_v3 nên so sánh này thiên vị v8a. +6. **Nếu còn quay lại Phase-1:** (a) giới hạn lực hút free slot — chỉ dùng một phần pool clean, bỏ unknown khỏi tập negative của noise trong SupCon hoặc thêm margin theo lớp; (b) dữ liệu nhiễu thật đa cảnh cho node noise (không đổi); (c) giữ null detection của v5b làm mục tiêu cứng vì đây là phần Phase-2 không tự có. + +### 13.30 Dừng v8, tập trung cải thiện Phase-1 v5 — nguyên nhân gốc: chính sách crop (2026-09-03, tối) + +**Quyết định của người dùng:** dừng v8a/v8c (17:35, chỉ có eval@0), tập trung cải thiện v5. Phân tích quỹ đạo theo epoch (`history.json` của ll_v3 / v5 / v5b) và probe mới `probe_phase1_scale.py` (`outputs/phase1_scale_probe.json`). + +**Phát hiện 1 — trainer Phase-1 chưa từng thấy nhiễu thật.** `PairDataset` dùng `_resize_center_crop`: thu nhỏ cạnh ngắn về 256 rồi cắt giữa. Kích thước gốc: Rain13K-resized 384², LOL 600×400, RESIDE ~550×413 (thu 1,5×), **SIDD 4032×3024 / 5328×3000 (thu ~12×)** — nhiễu cảm biến bị trung bình hoá gần hết. Phase-2 (`Phase2PairDataset`) và dashboard cắt 256 ở độ phân giải gốc. Cùng 19 ảnh SIDD val, cùng checkpoint: + +| Chính sách crop | ll_v3 noise→noise | own-prob | v5b noise→noise | rain→rain ll_v3 / v5b | khớp argmax A↔B | +|---|---|---|---|---|---| +| A: trainer (thu 12×, cắt giữa) | 0,84 | 0,83 | 0,37 | 0,745 / 0,61 | – | +| B: gốc, cắt giữa (Phase-2) | **0,05** (rain 0,53) | 0,04 | **0,00** (rain 0,63) | 0,62 / **0,245** | noise 0,05 · rain 0,72 / 0,61 · haze 0,85 · lowlight 0,94 | + +ISO 200–3200: A cho noise-prob 1,00, B cho 0,00. Node noise của mọi Phase-1 đến nay = "cảnh SIDD thu nhỏ" (nhận diện 8 cảnh/màu), không phải nhiễu; đó là lý do dashboard §13.25 thấy "node noise chết" trong khi val của trainer báo 0,6–0,9. Rain cũng lệch thang (streak mảnh hơn khi thu 1,5×), giải thích v5b: val trainer 0,61 nhưng dashboard 0,245. Mọi số F1 val của Phase-1 trước đây đo ở thang khác với thang Phase-2 tiêu thụ. + +**Phát hiện 2 — pool Snow100K không "mù".** Dark-channel trung vị của pool 0,16 ≈ clean GT rain/lowlight (0,18–0,20), xa RESIDE hazy (0,35); ll_v3 gọi pool là haze chỉ 3% (8% ở tứ phân vị DCP cao nhất), gọi rain 17% (texture). Giả thuyết "pool dạy haze nhẹ → free" (§13.29) yếu; pool góp phần vào rain→free, nhưng lực chính là lệch thang. + +**Phát hiện 3 — quỹ đạo.** ll_v3: noise (thang A) lên 0,84 ở epoch 10, haze tăng chậm 0,35→0,57 tới epoch 40. v5: noise kẹt 0,16–0,26 từ epoch 3 (12/19 ảnh → free), haze đứng 0,35 từ epoch 5, rain dao động 0,46–0,78; loss `embed` phẳng ~1,8 suốt run. v5b tương tự, best epoch 17. Trong SupCon v5, clean (cặp + pool) chiếm 64/128 mẫu, unknown là negative của mọi lớp. + +**v5c (đã hiện thực, `train_graph_encoder_v2.py`, 7 test mới `tests/test_phase1_v5c.py`, hồi quy 64 pass):** +- `--crop-policy native`: train = random crop 256 ở độ phân giải gốc (sampler phát `(index, sample_seed)` như Phase-2 để replay được), val/calibration = cắt giữa gốc, chỉ upscale khi ảnh nhỏ hơn 256 (đúng luật Phase-2). SIDD: cache gốc `--sidd-native-crops 32` crop/cặp train (deterministic theo record id), 1 crop giữa cho val; fingerprint calibration và tên cache đổi theo policy (cache legacy giữ nguyên). +- `--embed-members known_clean`: SupCon chỉ trên 4 lớp + clean cặp (bỏ pool và OOD). +- Còn lại = v5b (photometric 0,5; embed 0,25; extra_null 0,05; ood_real 0,35; 50 epoch fp32). +- `run_phase1_v5c.sh`: GPU0 `phase1_v5c` (native + known_clean), GPU1 `phase1_v5c_ab` (native + embed all = v5b chỉ đổi crop) để tách tác dụng; cache dùng chung `outputs/phase1_cache/sidd_native_256`, run 2 chờ run 1 dựng xong cache. +- Tiêu chí: F1 val (nay đo ở thang gốc, so sánh được với dashboard) ≥ ll_v3 ở thang gốc (probe: rain 0,62 · noise 0,05 · haze 0,51 · lowlight 0,96); node noise sống ở độ phân giải gốc (noise→noise ≥ 0,6 trên SIDD val, ramp residual SIDD thật → noise); giữ null detection của v5b (tuyết thật ≥ 0,85, clean → free ≥ 0,8). + +### 13.31 Kết quả v5c / v5c_ab — crop gốc làm sống node noise, F1 0,91 ở thang Phase-2 (2026-09-03, 21:30) + +Hai run xong 50/50 epoch (~2 h). Tất cả số dưới đây đo ở **thang gốc** (val của trainer nay = chính sách Phase-2; dashboard `outputs/phase1_vis/`; gate `gate_phase1.sh ` → `outputs/_gate.json`). + +| | ll_v3 (probe, thang gốc) | v5b best (dashboard) | **v5c_ab ep 17 (best F1)** | **v5c_ab ep 50 (last)** | v5c ep 19 (best F1) | +|---|---|---|---|---|---| +| F1 val | ≈0,55 | 0,668 (thang cũ) | **0,911** | 0,853 | 0,913 | +| rain→rain / →free | 0,62 / 0,28 | 0,245 / 0,72 | 0,86 / 0,10 | 0,82 / 0,17 | 0,92 / 0,00 | +| noise→noise | 0,05 | 0,00 | **1,00** | **1,00** | **1,00** | +| haze→haze / →rain / →free | 0,51 / 0,46 / – | 0,35 / 0,00 / 0,65 | 0,79 / 0,00 / 0,21 | 0,53 / 0,11 / 0,36 | 0,82 / 0,18 / 0,00 | +| lowlight | 0,96 | 0,95 | 0,95 | 0,95 | 0,96 | +| clean GT→free (rain / lowlight / haze / noise) | 0,65 / 0,48 / 1,00 / 0,47 | 0,94 / 0,92 / 1,00 / 0,74 | 0,63 / 0,51 / 1,00 / 0,95 | 0,80 / 0,66 / 1,00 / 0,95 | 0,53 / 0,51 / 0,70 / 0,95 | +| clean pool→free | 0,64 | 0,97 | 0,77 | 0,86 | 0,67 | +| tuyết thật→free (gate ≥0,70) | 0,50 | 0,92 | 0,69 ✗ | **0,78 ✓** | 0,55 ✗ | +| OOD snow / blur / pixelate→free | 0,93 / 0,96 / 0,97 | 0,99 / 0,99 / 1,00 | 0,73 / 0,98 / 0,99 | 0,82 / 1,00 / 1,00 | 0,58 / 0,99 / 0,99 | +| Severity ρ haze / noise / lowlight / rain | 0,73 / 0,41 / 0,50 / 0,30 | 0,70 / −0,42 / 0,46 / 0,34 | 0,91 / 0,93 / 0,61 / 0,37 | 0,90 / 0,97 / 0,66 / 0,36 | 0,89 / 0,98 / 0,57 / 0,30 | +| Ramp residual SIDD thật ×1 → noise | 0,01 (rain 0,74) | – | 0,72 | 0,70 | 0,74 | +| scene008 → noise | 0,41 | 0,70 | 0,67 | 0,70 | 0,85 | +| Locked test F1 / noise acc / rain acc | – | 0,679 / 0,70 / 0,36 | 0,799 / 1,00 / 0,66 | – | 0,756 / 0,95 / 0,58 | +| Gate 4 điều kiện | – | 3/4 | 3/4 | **4/4** | 3/4 | + +**Đọc kết quả.** +1. **Node noise sống thật**: 1,00 trên SIDD val gốc từ epoch 5–8 và giữ tới cuối ở cả hai run; ramp residual SIDD thật đơn điệu 0,24→0,76 vào node noise (ll_v3: vào rain 0,74); severity ρ noise 0,93–0,98; scene008 → noise 0,67–0,85. Chỉ đổi chính sách crop, không đổi loss, không thêm dữ liệu. +2. **Rain và haze cũng tốt hơn ll_v3 ở thang gốc**: rain 0,82–0,92 (ll_v3 0,62), haze 0,53–0,82 (0,51), haze→rain 0,00–0,18 (0,46). Haze severity ρ 0,90. +3. **Ablation SupCon**: v5c (`known_clean`) không tăng F1 (0,913 vs 0,911) nhưng null yếu hơn hẳn (tuyết thật 0,55 vs 0,69–0,78; clean pool 0,67 vs 0,77–0,86; haze GT → rain 0,30). Giữ `embed-members all` (unknown làm negative có ích cho free slot). v5c đóng. +4. **Đánh đổi còn lại — tam giác rain/haze/free dao động theo epoch**: haze→rain nhảy 0,0↔0,5 và tuyết thật 0,3↔0,6 giữa các epoch 12–25 khi LR còn cao; epoch cuối (LR≈0) cân bằng hơn best-F1: ep 50 qua 4/4 gate với haze 0,53, ep 17 haze 0,79 nhưng trượt tuyết thật (0,69). Selection key hiện thiên về F1. Hướng v5d: EMA trọng số để đánh giá/chọn (làm phẳng dao động) + selection key cân bằng F1 với null (clean, OOD tổng hợp, tuyết thật). +5. **Còn lại chưa giải**: rain clean GT → rain 0,15–0,27 và lowlight clean GT → haze/noise 0,2–0,3 (LOL GT hơi bệt/nhiễu), rain severity ρ chỉ 0,36 (Rain13K GT lệch tone nên MAE residual không phải proxy tốt cho lượng mưa). + +**Ứng viên Phase-1 hiện tại:** `outputs/phase1_v5c_ab/graph_encoder_last.pt` (ep 50, 4/4 gate) hoặc `graph_encoder_best.pt` (ep 17, F1 cao nhất); cả hai có `photometric_state` cho v8. + +### 13.32 v5d (EMA + selection cân bằng) — kết quả giữa chừng, lỗi EMA/BatchNorm, và chẩn đoán gốc của tam giác rain/haze/free → v5e (2026-09-04, 00:00–01:30) + +**v5d lần 1 hỏng vì EMA sao chép running stats.** Đánh giá bằng EMA cho F1 0,12 ở epoch 3 (mọi ảnh → rain) trong khi trọng số live bình thường (F1 0,48). Nội suy w = (1−t)·raw + t·EMA: t = 0,05 vẫn tốt (0,71), t = 0,2 sụp (0,37); EMA chỉ trên `feature_extractor` (có BatchNorm) tái hiện sụp đổ, EMA chỉ trên các head lại tốt hơn raw (0,646 vs 0,476). Nguyên nhân: `WeightEMA` trung bình trọng số conv nhưng sao chép running_mean/var từ bản live → BN thấy thống kê không khớp trọng số. Sửa: trung bình cả buffer float cùng decay (chuẩn timm ModelEma); sau sửa EMA bám raw (epoch 2: 0,31 vs 0,35, null 0,99 cả hai). Hai run hỏng lưu ở `outputs/phase1_v5d*_badema`. + +**v5d lần 2 (đang chạy, seed 42 GPU0 / seed 43 GPU1, phóng 22:40):** EMA làm mượt nhưng hội tụ vào **chế độ "haze nhẹ → rain"**: từ epoch 25 đến 41, seed 42 đứng yên ở F1 0,80, rain 0,62–0,66 (free 0,33), haze 0,58 với **haze→rain 0,42**, tuyết thật 0,30–0,44, clean 0,63–0,77. Không tốt hơn v5c_ab (best 0,911 / last 0,853, haze→rain 0,00–0,11). Selection cân bằng chọn epoch 6 (F1 0,60, null ≈ 0,97) vì null được tối đa hoá "miễn phí" khi mọi thứ còn ở free → key này thiên về checkpoint chưa chín; giữ selection F1 cho v5e. Kết luận tạm: EMA không phải đòn bẩy đúng; vấn đề nằm ở dữ liệu nhãn. + +**Chẩn đoán gốc (probe trên val gốc, 3 checkpoint):** +- Haze bị gọi sai luôn là **haze nhẹ**: severity trung bình 0,09 khi → free (v5c_ab best), 0,20–0,28 khi → rain (v5d, v5c_ab last); haze đậm (~0,5) luôn đúng. +- **34% cặp Rain13K train có severity crop < 0,05** (41% < 0,10; median 0,24): crop 256 gốc của ảnh 384 với mưa thưa thường **không chứa vệt mưa**, nhưng vẫn mang nhãn cứng "rain" trong route CE. Node rain học "cảnh ngoài trời gần như sạch" → hút haze nhẹ (haze→rain) và clean GT (rain clean GT → rain 0,15–0,27 ở v5c_ab). Haze train: 10% < 0,05. + +**v5e (đã hiện thực, 5 test mới, 66 test pass trên server, smoke sạch; launcher tự chờ v5d xong từng GPU):** +- `--crop-select residual --crop-candidates 4`: khi train, rút 4 crop gốc và giữ crop có residual lớn nhất (SIDD: 4 crop trong cache); val giữ nguyên cắt giữa. +- `--severity-floor 0.05`: cặp có severity crop dưới sàn được giám sát như clean (route → free, severity → 0, nhãn embed = clean, bỏ khỏi CE loại/spatial/unknown); sàn 0 = bitwise như cũ. Smoke báo `floor_fraction` 0,125 sau khi đã chọn crop theo residual. +- Cặp: `phase1_v5e` (residual + sàn 0,05, GPU0 sau v5d seed 42) và `phase1_v5e_ab` (residual, sàn 0, GPU1 sau v5d seed 43) để tách tác dụng của sàn. Đánh giá trọng số raw, selection F1, còn lại = v5c_ab. `autogate_phase1.sh` tự chạy dashboard + gate cho best và last của cả 4 run khi xong. + +**v5d đóng âm (01:45).** Seed 42 xong 50 epoch: best theo key cân bằng = epoch 6 (dashboard: rain 0,00 → free 0,96, haze 0,42, tuyết thật 0,90; locked test rain acc 0,00) — checkpoint chưa chín; last (epoch 50): rain 0,62, haze 0,59 với **haze→rain 0,41**, rain clean GT → rain 0,35, tuyết thật 0,695 (trượt gate), noise 1,00. Cả hai kém v5c_ab. Seed 43 dừng chủ động ở epoch 36 (plateau 12 epoch ở cùng chế độ, haze→rain 0,52) để trao GPU1 cho v5e_ab lúc 01:46. Kết luận: EMA làm mượt nhưng hội tụ vào chế độ xấu; key cân bằng bị null "miễn phí" đánh lừa. Giữ lại trong mã (`--ema-decay`, `--selection`) nhưng v5e dùng raw + F1. Bài học vận hành: lệnh ssh gộp `pkill -f "[r]un_x.sh"` với `bash run_x.sh` trong cùng chuỗi tự khớp và giết chính shell; tách kill và launch thành hai lệnh ssh. + +### 13.33 v5e — sàn severity làm đúng việc, chọn crop theo residual làm hại → v5f (2026-09-04, 05:00) + +**v5e (residual-select + sàn 0,05) xong 50 epoch; best epoch 20.** Dashboard best (thang gốc): rain 0,64 (free 0,33) · noise 1,00 · haze **0,74** với **haze→rain 0,00** · lowlight 0,96; clean GT → free: rain 0,85 · noise 1,00 · haze 1,00 · lowlight 0,67; clean pool → free 0,83; OOD snow/blur/pixelate → free 0,82/0,98/0,99; tuyết thật → free **0,77**; severity ρ haze 0,90 · noise 0,97 · lowlight 0,53 · rain 0,35; scene008 → noise 0,50; locked test F1 0,797 (noise 0,90, rain 0,61). **Gate 4/4.** Đây là checkpoint cân bằng nhất đến nay (v5c_ab ep 17: rain 0,86 / haze 0,79 nhưng tuyết thật 0,69 ✗; ep 50: rain 0,82 / haze 0,53). Suốt run, haze→rain giữ ≤ 0,2 và null cao (0,85–0,92 / 0,9–0,97 / 0,6–0,9) — điều chưa run nào trước đó có ở mọi epoch; đổi lại rain recall dao động 0,3–0,7 (epoch cuối 0,34, F1 0,75). + +**v5e_ab (residual-select, không sàn) — ablation:** ổn định ở mức kém từ epoch 20: F1 0,72–0,75, rain 0,5–0,6, haze 0,35 với haze→rain 0,4–0,6, tuyết thật 0,4–0,55 — **kém cả v5c_ab** (cùng recipe, chỉ khác cách chọn crop). Kết luận: **chọn crop theo residual lớn nhất làm hại**: crop residual-max của RESIDE là vùng trời/haze đặc, của Rain13K là vùng vệt mưa dày → phân bố train lệch khỏi crop giữa của val/Phase-2; haze nhẹ và mưa vừa bị đẩy sang rain/free. Sàn severity là thứ mang lại haze→rain ≈ 0 và null cao; rain recall thấp của v5e đến từ chọn crop, không phải từ sàn. + +**v5f (đang chạy):** recipe v5c_ab (crop ngẫu nhiên) + chỉ sàn severity: `phase1_v5f` sàn 0,05 (GPU0, 04:56) và `phase1_v5f_b` sàn 0,03 (GPU1, tự phóng sau khi v5e_ab xong ~05:50). Kỳ vọng: rain recall của v5c_ab (0,8+) với haze→rain và null của v5e. `autogate_phase1.sh` chấm best + last khi xong (~08:00 / ~09:00). + +### 13.34 v5f — sàn severity đơn thuần là đáp án: Phase-1 tốt nhất, 4/4 gate cả best lẫn last (2026-09-04, 08:11) + +`phase1_v5f` (crop gốc ngẫu nhiên + **chỉ** sàn severity 0,05; 16–17% mẫu train rơi dưới sàn) xong 50 epoch, best epoch 30. Cả checkpoint best và last đều qua **4/4 cổng**. + +| Chỉ số (thang gốc) | ll_v3 | v5c_ab ep17 | v5e ep20 | **v5f ep30 (best)** | v5f ep50 (last) | +|---|---|---|---|---|---| +| F1 val | ≈0,55 | 0,911 | 0,872 | **0,912** | 0,860 | +| rain → rain / → free | 0,62 / 0,28 | 0,86 / 0,10 | 0,64 / 0,33 | **0,89 / 0,11** | 0,78 / 0,22 | +| noise → noise | 0,05 | 1,00 | 1,00 | **1,00** | 1,00 | +| haze → haze / → rain | 0,51 / 0,46 | 0,79 / 0,00 | 0,74 / 0,00 | 0,74 / **0,00** | 0,58 / 0,00 | +| lowlight | 0,96 | 0,95 | 0,96 | 0,95 | 0,94 | +| clean GT → free (rain / noise / haze / low) | 0,65 / 0,47 / 1,00 / 0,48 | 0,63 / 0,95 / 1,00 / 0,51 | 0,85 / 1,00 / 1,00 / 0,67 | 0,83 / 0,95 / 1,00 / 0,68 | **0,95 / 1,00 / 1,00 / 0,76** | +| clean pool → free | 0,64 | 0,77 | 0,83 | 0,88 | **0,92** | +| tuyết thật → free | 0,50 | 0,69 ✗ | 0,77 | 0,75 ✓ | **0,85** ✓ | +| OOD snow/blur/pixelate → free | 0,93/0,96/0,97 | 0,73/0,98/0,99 | 0,82/0,98/0,99 | 0,85/0,96/0,96 | 0,91/0,97/0,98 | +| Severity ρ haze / noise / low / rain | 0,73/0,41/0,50/0,30 | 0,91/0,93/0,61/0,37 | 0,90/0,97/0,53/0,35 | **0,93/0,97/0,52/0,35** | 0,90/0,98/0,52/0,29 | +| Ramp residual SIDD thật (0→1,5) → noise | 0,01 (đi vào rain) | 0,24→0,76 | – | 0,00→0,67 | 0,00→0,73 | +| Ramp residual Rain13K thật → rain | 0,62 @1 | – | – | **0,04→0,84 đơn điệu** | 0,01→0,70 | +| Locked test F1 / noise acc / rain acc | – | 0,799 / 1,00 / 0,66 | 0,797 / 0,90 / 0,61 | **0,894 / 0,95 / 0,72** | – | +| Cổng | – | 3/4 | 4/4 | **4/4** | **4/4** | + +**Kết luận chuỗi ablation (v5c → v5f).** +1. **Crop gốc** (v5c) làm sống node noise: 0,05 → 1,00. Không loss nào, không dữ liệu nào làm được điều đó. +2. **Sàn severity** (v5f) sửa nhãn của 34% crop rain rỗng: haze→rain 0,46 → **0,00**, clean GT → free tăng đều, tuyết thật 0,50 → 0,75–0,85, đồng thời rain recall lên cao nhất (0,89). Cả hai ramp residual thật đều đơn điệu — biểu diễn hiệu chuẩn theo cường độ thật, không chỉ phân loại. +3. **Chọn crop theo residual** (v5e) có hại: kéo phân bố train về vùng trời/vệt mưa dày, rain recall tụt còn 0,64 và v5e_ab (không sàn) rơi lại haze→rain 0,49. +4. **EMA + selection cân bằng** (v5d) vô ích: EMA hội tụ vào chế độ xấu, key cân bằng chọn checkpoint chưa chín. + +**Ứng viên Phase-1 chính thức: `outputs/phase1_v5f/graph_encoder_best.pt` (epoch 30).** Nếu Phase-2 cần null detection tối đa hơn là rain recall, `graph_encoder_last.pt` (ep 50, tuyết thật 0,85, clean rain GT → free 0,95) là lựa chọn thay thế, cũng 4/4 cổng. + +`phase1_v5f_b` (sàn 0,03) đang chạy tới epoch 50 (~10:10) để xác định độ nhạy của ngưỡng sàn; ep 36 hiện ở F1 0,82 với rain 0,49 — sàn thấp hơn không tốt hơn. + +### 13.35 Phase-2 trên Phase-1 v5f — v9a thắng A trên MỌI benchmark ngoại bộ khi mới đi nửa chặng (2026-09-04, dừng 14:50) + +Hai nhánh, cùng Phase-1 `phase1_v5f/graph_encoder_best.pt` (`3486c7b5…`), dừng theo yêu cầu để đánh giá sớm: +- **v9a** = **đúng công thức A** (`uformer_p5`: warm-start `dgf8k` best/EMA, không global-context, identity 0,10, tail 6, 8k step, LR 3e-5), **chỉ đổi Phase-1** ll_v3 → v5f. Dừng ở bước 5325; checkpoint tốt nhất là **bước 4000** (nửa ngân sách). +- **v9b** = công thức v8 (global-context + `GlobalPhotometricHead` + identity đa exposure) trên cùng v5f. Chỉ đạt 1325 bước (xem "Sự cố" bên dưới); đánh giá từ run đó. + +**Val (thang gốc, 317 ảnh):** + +| Run (bước) | macro | haze | lowlight | noise | rain | +|---|---|---|---|---|---| +| A (6000, best) | **27,903** | **33,08** | 19,05 | **36,95** | 22,53 | +| v9a (4000, best) | 27,585 | 32,24 | 18,95 | 36,60 | **22,55** | +| v9b (1000) | 27,113 | 30,25 | **19,19** | 36,58 | 22,48 | + +**Ngoại bộ / locked (PSNR / SSIM / LPIPS) — bộ số quyết định:** + +| Run | Rain locked Test1200 (n=1200) | Haze held-out (n=300) | scene008 SIDD locked (n=20) | +|---|---|---|---| +| A (8k, ll_v3) | 27,867 / 0,8367 / 0,122 | 31,544 / 0,9756 / 0,009 | 27,125 / 0,8528 / 0,154 | +| B (8k, ll_v3 + ctx) | 27,787 / 0,8349 / 0,124 | **31,924** / 0,9754 / 0,009 | 28,148 / 0,8549 / 0,164 | +| **v9a (4k, v5f)** | **28,100 / 0,8402 / 0,115** | 31,567 / 0,9712 / 0,010 | 27,671 / 0,8662 / 0,129 | +| v9b (1,3k, v5f + v8) | 27,755 / 0,8362 / 0,117 | 31,399 / 0,9714 / 0,011 | 27,474 / **0,8722 / 0,126** | +| (đầu vào hỏng) | 22,562 / 0,7336 | 18,170 / 0,8383 | 39,018 / 0,9543 | + +**Đọc kết quả — nghịch lý val ngược dấu với ngoại bộ.** v9a thua A 0,32 dB trên val macro nhưng **thắng trên cả ba bộ ngoại bộ**: rain locked +0,23 dB / +0,0035 SSIM / −0,007 LPIPS trên 1200 ảnh, scene008 +0,55 dB / +0,013 SSIM / **−0,025 LPIPS**, haze ngang (+0,02 dB). Nguyên nhân: val là hỗn hợp tổng hợp mà thân mạng warm-start đã được tinh chỉnh dưới điều kiện hoá ll_v3 (haze RESIDE-val là nơi khớp nhất, −0,84 dB), còn Test1200 và scene008 chưa từng vào huấn luyện. **Val macro PSNR không còn là thước đo đúng để chọn Phase-1.** + +**scene008 — chứng cứ cơ chế (probe tông màu, 20 ảnh):** đầu vào 39,02 dB (gần sạch), nên phục hồi *làm hỏng* ảnh; câu hỏi là hỏng ít hay nhiều. + +| | luma phục hồi (GT 0,204) | PSNR thô | PSNR sau affine từng ảnh | SSIM thô | +|---|---|---|---|---| +| A (6k) | 0,187 (tối đi) | 27,125 | 35,868 | 0,853 | +| **v9a (4k)** | 0,213 (sát GT hơn) | **27,671** | **36,886** | **0,866** | + +v9a vừa giảm lệch phơi sáng (luma 0,213 so với 0,187 khi GT là 0,204) vừa nâng trần sau khi khớp affine (36,89 so với 35,87), tức là **cả tông màu lẫn kết cấu đều tốt hơn**, không phải đánh đổi. Đây đúng là hệ quả trực tiếp của v5f: ảnh gần sạch được định tuyến vào free slot (clean → free 0,83–0,95, clean pool 0,88) nên mạng can thiệp nhẹ tay hơn. + +**Phân tích hai hướng.** +1. **Hướng A (v9a — Phase-1 tốt hơn, công thức cũ):** thắng rõ, rẻ, không thêm tham số nào. Mới 4000/8000 bước và đường val vẫn đang lên (26,21 → 27,59), nên các con số ngoại bộ ở trên là **cận dưới**. Đây là hướng nên chạy hết 8k và là kết quả chính để báo cáo. +2. **Hướng B (v9b — thêm ngữ cảnh toàn khung + head phơi sáng):** mới 1325 bước (16% ngân sách) mà đã đạt **SSIM và LPIPS tốt nhất trên scene008** (0,8722 / 0,126) — đúng điểm yếu mà head phơi sáng nhắm tới — nhưng PSNR còn thấp hơn v9a ở mọi mục. Chưa kết luận được; cần chạy đủ 8k. Chi phí gấp đôi v9a mỗi bước (batch 4 × tích luỹ 4 sau khi chạm trần bộ nhớ). + +**Sự cố kỹ thuật và cách xử lý (đã sửa, có test):** +- NaN ở forward dưới AMP làm chết run. Lần sửa đầu định tuyến nó vào đường lùi thang AMP là **sai**: thang chỉ nhân cho backward nên replay lại NaN y hệt, và `scaler.update()` còn assert khi thang chưa khởi tạo. Sửa đúng: **bỏ micro-batch hỏng** (không backward, không tính loss) kèm hạn mức 5 lần liên tiếp / 100 lần tổng (`loss_overflow_action`, `nonfinite_loss_within_budget`). +- Supervisor: `overflow_count` trả về giá trị rỗng khiến so sánh số nguyên lỗi và nó bỏ cuộc thay vì khởi động lại; nay luôn trả số và tự resume nếu thấy `overflow_recovery.pt`. +- v9b OOM thật ở ~22 GB/24 GB với batch 8 → batch 4 × tích luỹ 4 (batch hiệu dụng không đổi), đỉnh ~12 GB. +- v9a gặp một lần tràn số gradient ở bước 4745 và supervisor tự phục hồi đúng thiết kế. + +### 13.36 Phân tích lại toàn tuyến — Phase-1 đã "SOTA" chưa, và điểm nghẽn nằm ở Phase-1 hay ở mạng diffusion (2026-09-04, 22:30) + +Mục đích: trả lời ba câu hỏi bằng số đã đo trong tài liệu này (không thêm run mới): (1) từng khâu của pipeline đang đứng ở đâu; (2) Phase-1 v5f đã đạt mức SOTA chưa; (3) nên đầu tư tiếp vào Phase-1 hay vào kiến trúc phục hồi phía sau. + +#### 13.36.1 Run `uformer_v9a15k_seed42` (2 GPU DDP, curriculum đóng băng encoder 3k, early-stop 3×0,02 dB) + +| Bước | 0 | 500 | 1k | 2k | 3k (mở encoder) | 4k | 5k | 6k | 7k | 8k | +|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:| +| val macro | 26,208 | 26,953 | 27,005 | 27,107 | 27,276 | 27,413 | 27,488 | 27,556 | **27,661** | 27,604 | + +Per-domain @7k: haze 32,39 · lowlight 18,82 · noise 36,88 · rain 22,55; @8k: haze 32,24 · lowlight 18,68 · noise 36,97 · rain 22,53 (A best @6k: 33,08 · 19,05 · 36,95 · 22,53). Tốc độ 25,6 bước/phút; hai lần tràn số AMP (bước 3047 và 6657, supervisor tự phục hồi, 0 bước mất); 2 micro-batch bị bỏ vì loss non-finite. Eval @8k là **strike early-stop đầu tiên** (−0,06 dB so best @7k); @10k = 27,639 (haze 32,31 · lowlight 18,66 · noise 37,03 · rain 22,56) là strike 2. **Người dùng cho dừng run ở bước ~9,9k (23:46) để triển khai v10/v11 ngay**; best.pt = bước 7000 (27,661) là checkpoint được đánh giá và làm warm-start. Ước tính xong ~03:10. Đường val vẫn thấp hơn A (−0,24 dB @7k) đúng như §13.35 dự báo: val macro là hiện tượng warm-start; phán quyết chỉ dựa trên rain locked / haze held-out / scene008 sau khi xong. + +**External (giao thức crop cũ, để so với A/B/v9a-4k) của v9a15k best@7k — đo 23:52 sau khi dừng:** + +| Run | Rain locked Test1200 | scene008 SIDD locked | Haze held-out | +|---|---|---|---| +| A (8k, ll_v3) | 27,867 / 0,8367 / 0,122 | 27,125 / 0,8528 / 0,154 | 31,544 / 0,9756 / 0,009 | +| B (8k, ll_v3 + ctx) | 27,787 / 0,8349 / 0,124 | 28,148 / 0,8549 / 0,164 | **31,924** / 0,9754 / 0,009 | +| v9a-4k (v5f) | 28,100 / **0,8402** / **0,115** | 27,671 / **0,8662** / **0,129** | 31,567 / 0,9712 / 0,010 | +| **v9a15k best@7k (v5f, DDP, decoder-first)** | **28,130** / 0,8401 / 0,116 | **28,436** / 0,8644 / 0,135 | 31,812 / 0,9742 / 0,009 | + +v9a15k là PSNR cao nhất trên cả ba bộ (scene008 +0,77 so v9a-4k, +1,31 so A; haze +0,25 so v9a-4k), SSIM/LPIPS ngang v9a-4k. Đây là warm-start của v10 (eval@0 của v10 = 27,6608, trùng bitwise với best 15k: mọi module mới đúng là identity). + +#### 13.36.2 Từng khâu của pipeline — hiện trạng và điểm yếu đã đo + +| # | Khâu | Hiện trạng | Điểm yếu đã đo | Nguồn | +|---|---|---|---|---| +| 1 | Dữ liệu | 18.261 train / 317 val; rain 69 %, haze 27 %, lowlight 3,8 %, noise **0,66 % (121 cặp, 8 cảnh SIDD)**; sampler cân bằng | Noise thiếu dữ liệu tuyệt đối; rain val (98 cặp mưa nặng, GT lệch tone) chỉ cho +1,3 dB nên PSNR rain val gần vô nghĩa; haze val 3 cảnh, noise val 1 cảnh | §3, §13.23 | +| 2 | Phase-1 (v5f) | Crop gốc 256 + sàn severity 0,05; F1 0,912 val / 0,894 locked; rain 0,89 · noise 1,00 · haze 0,74 · lowlight 0,95; tuyết thật → free 0,75; ramp thật đơn điệu; ρ haze 0,93 · noise 0,97 | Haze nhẹ → free (recall 0,74); ρ lowlight 0,52 và rain 0,35 (severity = MAE residual, không phải "liều"); LL toàn khung chưa có (v8/v9b dở dang) | §13.34 | +| 3 | Giao diện Phase-1 → Phase-2 | ~25 điểm cắm | **Chỉ 2 đường sống** (cross-attn context −3,68, adaLN global −3,45); routing −0,05, severity −0,03, spatial +0,005, content 0,000; MoE 7 bank + κ per-type + gate uniform ≈ **−0,085** (0,18M tham số, gần chết) | §13.18 | +| 4 | Trunk (UformerMoE v7) | **13,39M** tham số (denoiser 12,5M; dims 64/128/192/256, 2 LeWin/stage, window 8; tail 0,20M; conditioner 0,69M); pixel-unshuffle 2× | Nhỏ hơn 2–4× so với Restormer 26M / AdaIR ~29M / PromptIR ~36M / Uformer-B ~51M; cửa sổ 8 trên state 128² → thiếu đường "tông màu toàn ảnh" (lowlight overshoot, scene008 kéo tối) | §13.13, §13.23 | +| 5 | Sampler / diffusion | ResShift T=2: coarse t=2 (x0-MSE) + fine t=1 (L1+VGG) | Chain 8 bước **phá** kết quả (§13.5), 1-step > chain, 2-step chỉ +0,7 dB so 1-step → phần "diffusion" đóng góp ít; về PSNR đây gần như một regressor có điều kiện | §13.5, §13.12 | +| 6 | Loss / curriculum | x0-MSE + L1 + VGG 0,1 + chroma/luma 0,5 + tháp Laplacian + identity 0,10 + noise-pair 0,20 + cond-dropout 0,15 | Identity nội bộ 40 dB nhưng scene008 (sạch, tối, có vân) vẫn −11 dB so input: identity chỉ được dạy trên clean sáng | §13.19, §13.23 | +| 7 | Ngân sách train | Chuỗi warm-start uformer → luma8k → head8k → dgf8k → v9a15k ≈ **47k bước × 16 crop ≈ 0,75M mẫu**, LR 3e-5 | SOTA đơn tác vụ: ~300k bước, batch 8–64, crop lũy tiến tới 384 → gấp 5–10× | §13.12–13.35 | +| 8 | Đánh giá | Val 317 (center-crop 256); external: Test1200 (1200) + RESIDE held-out (300) + scene008 (20), **đều center-crop 256** | Số công bố là toàn ảnh; muốn so SOTA phải có evaluator toàn khung (tile/pad) và TTA | `eval_pipeline_external.py` | + +#### 13.36.3 Phase-1 đã SOTA chưa? + +Hai cách hiểu, hai câu trả lời: + +1. **Theo nghĩa "bộ phân loại suy giảm" (closed-set):** chưa. DA-CLIP báo 99,2 % trên 10 loại suy giảm; DCPT / DyNet dùng pretrain phân loại suy giảm để đạt trung bình 32,9 dB trên 3 tác vụ; các bộ phân loại kiểu này đạt ~99–100 % vì test cùng phân phối, ảnh toàn khung, không có lớp "sạch", không OOD. Phase-1 v5f đo trên crop 256 với **34 % crop rain không có vệt mưa** (nhãn gốc sai ở mức crop), có 2 free slot, có OOD thật (tuyết, blur, pixelate): F1 0,912, haze recall 0,74 (phần thiếu là haze nhẹ → free, đúng với ngữ nghĩa sàn severity). Với ràng buộc đó, 0,89–0,91 gần trần của nhãn crop, nhưng không thể gọi là SOTA theo thước closed-set. +2. **Theo nghĩa "biểu diễn suy giảm hiệu chuẩn, có null/OOD, có severity":** không có benchmark chuẩn để so; các tính chất đã đo (ramp thật đơn điệu cho rain 0,04→0,84 và SIDD 0→0,67; ρ severity 0,93/0,97 cho haze/noise; tuyết thật → free 0,75–0,85; clean pool → free 0,88–0,92) là những thứ DA-CLIP/PromptIR không đo và không có. Đây là đóng góp của Phase-1, nhưng là đóng góp *về chẩn đoán*, chưa được chứng minh là đóng góp *về chất lượng phục hồi*. + +**Điều quyết định không phải Phase-1 có SOTA hay không, mà là Phase-1 còn bao nhiêu đòn bẩy lên PSNR/LPIPS cuối:** +- Control không Phase-1 (p = 1, cùng warm-start): **−0,40 dB** macro (haze −1,85 · noise −0,58 · rain −0,12 · lowlight **+0,94**) — §13.21. +- Đổi Phase-1 từ ll_v3 (F1 ≈ 0,55) sang v5f (F1 0,91): rain locked **+0,23**, scene008 **+0,55 / LPIPS −0,025**, haze +0,02 — §13.35. Tức là nâng F1 gần gấp đôi chỉ mua được 0,2–0,5 dB ngoại bộ, và phần lớn đến từ *null* (ảnh gần sạch → free → can thiệp nhẹ), không từ routing 4 lớp. +- Knob liều sau DGF phẳng (§13.19): trunk đã tự suy suy hoá từ u_y; conditioning phần lớn dư thừa trừ haze. +- Đường sống duy nhất đang mang thông tin trunk *không tự có*: **phơi sáng toàn khung** (B: lowlight +0,38 val, haze ext +0,38, scene008 +1,02 — §13.24). + +⇒ Cận trên thực dụng của mọi cải tiến Phase-1 tiếp theo, với giao diện hiện tại, là **~0,5 dB**; cải tiến duy nhất có bằng chứng vượt ngưỡng đó là mô tả phơi sáng ngoài crop (v8/v9b), và giá trị của nó được hiện thực ở phía Phase-2 (đường tông màu toàn ảnh), không ở phía phân loại. + +#### 13.36.4 Khoảng cách tới SOTA phục hồi theo domain (số của ta là center-crop 256; số công bố là toàn ảnh — chỉ so bậc) + +| Domain | Ta (tốt nhất) | Công bố | Khoảng cách | Nguyên nhân chính (theo bằng chứng) | +|---|---|---|---|---| +| Lowlight — **LOLv2-real test, đúng 100 ảnh val của ta** | 18,8–19,4 (A/B/v9a) | Retinexformer 22,80 · CIDNet 24,11 · LRAR 24,28 (không GT-mean); ~29–30 khi hiệu chỉnh GT-mean | **≥ 4 dB** | Trunk: thiếu đường ước lượng gain/illumination toàn ảnh; control không Phase-1 còn *hơn* +0,94 → conditioning đẩy phơi sáng sai; SOTA LOL đều có bộ ước lượng illumination toàn khung (Retinex) | +| Rain — Test1200 | 28,10 / 0,840 (v9a 4k) | Restormer 33,19 / 0,926 · MPRNet 32,91 / 0,916 | **~5 dB** | Dung lượng 13M và ~0,75M mẫu (Restormer 26M, 300k bước); rain gần như không dùng conditioning (−0,12) → thuần Phase-2 | +| Noise — SIDD | val 36,9 (19 crop, 1 cảnh); scene008 gần-sạch 27,7 (input 39,0) | Restormer 40,02 · NAFNet 40,30 (SIDD val 1280 patch) | ~3 dB, khác tập | 121 cặp train / 8 cảnh (SOTA dùng SIDD-Medium 320 ảnh ≈ 30k patch); identity trên ảnh sạch tối/có vân chưa dạy | +| Haze — RESIDE held-out 300 | 31,6–31,9 / 0,975 | All-in-one trên SOTS-outdoor: AdaIR 31,06 · MoCE-IR 31,34 · DCPT 31,91; đơn tác vụ DehazeFormer ≈ 34–35 | ~0–3 dB, khác tập | Domain duy nhất Phase-1 thực sự giúp (−1,85 khi bỏ); gần mức all-in-one | + +Kết luận: khoảng cách 3–5 dB trên lowlight/rain/noise lớn hơn **một bậc** so với đòn bẩy còn lại của Phase-1 (≤ 0,5 dB). Một Phase-1 hoàn hảo cũng không kéo lowlight từ 19 lên 23 hay rain từ 28 lên 33. + +#### 13.36.5 Quyết định đề xuất: giữ Phase-1 v5f, can thiệp Phase-2 — xếp hạng đòn bẩy + +| Ưu tiên | Can thiệp | Bằng chứng | Kỳ vọng | Chi phí | +|---|---|---|---|---| +| **1** | **Đường tông màu toàn ảnh**: whole-frame context (B) + `GlobalPhotometricHead` (v8) dự đoán gain/gamma toàn ảnh áp trước trunk (kiểu illumination estimator của Retinexformer) + identity pairs từ clean **tối, có vân** (SIDD GT, Snow100K gt) + ràng buộc luma-pooled | §13.23 (9/12 dB scene008 là exposure), §13.24 (B +0,38/+1,02), §13.21 (control lowlight +0,94), v9b SSIM/LPIPS scene008 tốt nhất ở 16 % ngân sách | lowlight +2…+3 dB, scene008 +3…+8 dB | ~0,1–0,7M tham số, 8k bước, 1 GPU | +| **2** | **Dung lượng + ngân sách**: dims 64/128/256/384 hoặc 3 block/stage (≈ 30M), 40–60k bước, crop lũy tiến 256→320, giữ ResShift T=2 | §13.12 (Uformer không drift, leo đồng thời), §13.36.4 (rain/noise thuần Phase-2) | rain +1…+2 dB, noise +1 dB | 2 GPU, ~1,5–2 ngày; kiểm tra bộ nhớ 24 GB ở AMP | +| **3** | **Evaluator toàn khung + TTA** (tile/pad theo window 8; lật/xoay ×8) | Bắt buộc để so số công bố; TTA thường +0,1…+0,3 dB miễn phí | +0,2 dB và số so sánh được | 0 train | +| **4** | **Dữ liệu noise**: SIDD-Medium đủ 320 cảnh cho Phase-2 (và cho Phase-1 nếu train lại) | §13.19–13.20: 8 cảnh không đủ để học khái niệm noise; §13.23 #5 đạt nhờ clean-prior | noise +1…+2 dB in-dist; Phase-1 noise khái quát hơn | tải dữ liệu, không đổi mã | +| **5** | **Cắt điểm cắm chết** (content/spatial inject, MoE rank-16) hoặc thay bằng adapter routing-gated đủ lớn | §13.18 | Không tăng PSNR; làm claim sạch, giảm 0,2M tham số | nhỏ | +| Phase-1 (chỉ khi có consumer) | severity lowlight = log-gain phơi sáng, severity rain = mật độ mask vệt (thay MAE) → dùng làm liều cho đường tông màu ở mục 1 | ρ lowlight 0,52 / rain 0,35; §13.18 severity −0,03 (chưa ai dùng) | chỉ có giá trị đi kèm mục 1 | 1 GPU, 2 h | + +Không đề xuất tiếp: sửa haze recall 0,74 của Phase-1 (haze đã gần all-in-one SOTA và là domain conditioning giúp nhiều nhất; phần thiếu là haze nhẹ → free, đúng ngữ nghĩa), thêm seed Phase-1 (v5f đã 4/4 gate cả best lẫn last), hay quay lại chain nhiều bước (đã chứng minh phá kết quả). + +#### 13.36.6 Kế hoạch sau khi 15k xong + +1. External eval + probe tông màu cho `uformer_v9a15k_seed42/best.pt`; bảng A / B / v9a-4k / v9a-15k; chọn checkpoint nền (kỳ vọng v9a-15k). +2. **v10** (1 GPU, 8k, warm-start v9a-15k): mục 1 + Phase-1 severity theo gain (đổi Phase-1 cần train lại ≈ 2 h, có thể chạy song song trên GPU còn lại trước). +3. **v11** (2 GPU, 40k+): mục 2, warm-start từ v9a-15k với "net2net" mở rộng width, hoặc from scratch nếu warm-start không dung nạp. +4. Evaluator toàn khung + TTA (mục 3) làm trước v10 để mọi số mới đều so được với công bố. +Tiêu chí thành công (external, toàn khung): lowlight ≥ 22 dB trên LOLv2-real, Test1200 ≥ 30 dB, scene008 ≥ 33 dB (input 39), haze không giảm. + +### 13.37 Ý tưởng từ Stable Diffusion 2 đối chiếu với pipeline, thiết kế v10, và một lỗi giao thức đánh giá ngoại bộ (2026-09-04, 23:30) + +**Yêu cầu:** tham khảo thêm ý tưởng từ Stable Diffusion 2 (SD2) cho hướng Phase-2 đã duyệt ở §13.36. Bảng dưới đối chiếu từng cơ chế của SD2 với pipeline và ghi rõ lấy hay không, vì sao. + +| Ý tưởng SD2 | Trong pipeline hiện tại | Quyết định | +|---|---|---| +| **Latent diffusion trên VAE f8 + UNet 865M pretrained** (StableSR / DiffBIR / SUPIR dùng SD làm prior) | Ta làm ở không gian pixel (pixel-unshuffle 2×, lossless), 13,4M tham số | **Không** cho mục tiêu hiện tại: VAE KL-f8 tái tạo chỉ ~24–27 dB PSNR nên trần rain/noise/haze thấp hơn số ta đang có; UNet 865M không train được tử tế trên 3090/torch 1.10; và các phương pháp dòng này thắng ở LPIPS/FID ảnh thật, thua PSNR. Chỉ xét lại nếu chuyển thước đo sang perceptual/real-world, và khi đó là một nhánh riêng, không phải mạng thống nhất. | +| **Attention toàn cục chỉ ở các thang thô** (UNet SD: self-attention ở 32/16/8 latent, conv ở thang mịn) | LeWin cửa sổ 8×8 ở cả 4 thang → ở thang 16×16 trạng thái vẫn chỉ nhìn 1/4 crop | **Lấy → v10 `--global-attention-scales 2,3`**: block self-attention toàn bản đồ (1024 và 256 token) sau các LeWin block ở hai thang thô, adaLN zero-init nên identity ở warm-start. Cho crop một trường tiếp nhận toàn khối cho phơi sáng/airlight/mức nhiễu. | +| **Điều kiện ảnh cộng thêm kênh vào input** (depth2img, x4-upscaler nối LR vào input) | Đã có: `[u_t, u_y, u_t − u_y]`; spatial map Phase-1 cắm ở 16 px đã đo là chết (+0,005) | Không thêm: thông tin từng pixel của Phase-1 là dư thừa với trunk (§13.18). | +| **Noise-level conditioning / làm hỏng ảnh điều kiện + embedding mức nhiễu** (x4-upscaler, cascaded diffusion) | Chưa có | Hoãn: có lợi cho robustness ngoài phân phối, không có bằng chứng trên các bộ hiện tại; thêm vào sau v10 nếu external thật (Rain100H/real) được đưa vào. | +| **v-prediction** (SD2-768-v) | Dự đoán x0, T = 2 | Không: v-pred có ích ở nhiều bước/nhiều mức nhiễu; ở T = 2 với ResShift, x0 đã là lựa chọn tốt nhất đo được (chain 8 bước phá kết quả). | +| **Offset noise** (mẹo để SD2 sinh ảnh rất tối/rất sáng) | Nhiễu iid trong ResShift; mạng dự đoán x0 bằng MSE nên đổi mean toàn ảnh không bị cản | Không cần ở dạng nhiễu; **vấn đề thật là prior phơi sáng của trunk** → giải bằng pre-gain (dưới). | +| **unCLIP / image-variation: embedding ảnh pretrained làm điều kiện toàn cục** (DA-CLIP cùng họ) | Phase-1 global_condition đã là embedding toàn cục học riêng; open_clip chưa cài | Hoãn: thêm ViT 86M ở inference đi ngược "một mạng"; giá trị PSNR của DA-CLIP-style thấp. Xét lại nếu cần OOD semantic. | +| **Classifier-free guidance** | Có (cond-dropout 0,15, knob liều) nhưng đường cong phẳng (§13.19) | Giữ nguyên. | +| **Huấn luyện lũy tiến theo độ phân giải** (256 → 512 → 768) | Chỉ train 256 | **Lấy cho v11**: 256 → 320/384 ở giai đoạn cuối, đi kèm evaluator toàn khung. | +| **Gradient checkpointing / EMA / AMP** | EMA + AMP có | Gradient checkpointing dùng cho v11 (dung lượng ~30M trên 24 GB). | + +**Lỗi giao thức phát hiện khi viết evaluator toàn khung.** `eval_pipeline_external.py` lấy crop 256 *sau* `_resize_center_crop` (cạnh ngắn → 256): Test1200 384² bị thu 0,67×, RESIDE 550×411 thu 0,62×, và SIDD scene008 4032×3024 thu **~12×**. Thu 12× lấy trung bình hết nhiễu thật → đó là lý do input scene008 đọc "39 dB gần sạch": bộ này chưa bao giờ là bài khử nhiễu, nó là bài identity ở thang không ai train. Cùng lỗi thang với Phase-1 ở §13.30, nay ở phía Phase-2: trunk train trên crop **gốc** 256 nhưng external đo ở 0,62–0,67× (rain/haze) và 1/12 (noise). Số ngoại bộ cũ vẫn so sánh được *giữa các run* (cùng giao thức) nhưng **không so được với công bố**. Evaluator mới `eval_full_frame.py`: ảnh nguyên khung ở độ phân giải gốc, tile 256 chồng 64 với trọng số raised-cosine (tile kề nhau cộng đúng 1), Phase-1 theo tile + toàn khung squash cho model global-context, TTA ×8 dihedral tuỳ chọn, PSNR/SSIM RGB **và kênh Y** (derain công bố kênh Y), LPIPS toàn ảnh (crop giữa 1024 với ảnh 12 MP); thêm nhóm **`lowlight_lolv2_test`** = đúng 100 ảnh test LOLv2-real (600×400) để so trực tiếp với công bố. 8 test (`tests/test_eval_full_frame.py`): nghịch đảo dihedral, phủ tile, blend identity bitwise ở kích thước lẻ, TTA trung bình hoá. + +**v10 — hiện thực (`tests/test_unified_v10.py`, 10 test; 123 test Phase-2 pass local):** +1. **`--exposure-pregain`** (`ExposurePreGain`): một log-gain toàn ảnh, tanh-bounded ±1,6 (×0,2…×5), dự đoán từ global_condition + photometric_state của crop và của toàn khung **cộng thống kê luma thô** (mean, log-mean, p05/p50/p95, mean R/G/B của crop và toàn khung), **nhân vào ảnh hỏng trước pixel-unshuffle** nên neo u_y, trạng thái diffusion và tail full-res đều thấy ảnh đã nâng; Phase-1 vẫn nhìn ảnh gốc. Đây là illumination estimator kiểu Retinexformer: trunk làm việc ở chế độ đã chuẩn hoá thay vì phải tạo ×5–10 độ sáng bằng residual trên u_y (nguồn của overshoot và mất chroma, §13.13). Zero-init → bitwise identity; dropout theo mẫu (`--pregain-dropout 0.1`) giữ đường gain-1; `pregain_dose` ở sampler. Routing Phase-1 trong đầu vào là thứ phân biệt "lowlight cần nâng" với "sạch nhưng tối" (scene008). +2. **`--global-attention-scales 2,3`** (`GlobalAttentionBlock`): như bảng trên. +3. **Pool clean nhiều nguồn, cân bằng** (`extra_clean_files`, `--extra-clean-root a,b,c`): mỗi thư mục được lặp entry cho bằng thư mục lớn nhất nên SIDD-train-GT (121 ảnh 12 MP, tối, có vân) được rút ngang Snow100K gt (50k). Pool trên server: `outputs/clean_pools/{sidd_train_gt,lol_train_gt}` (symlink từ record train, đã kiểm tra không trùng val/locked) + Snow100K gt. Kèm `--identity-pair-prob 0.15 --identity-exposure-jitter 0.7`: identity pairs tối/sáng ×0,5–×2 dạy pre-gain "ảnh sạch tối → gain 1". +4. Runtime: `representation.full_image` (toàn khung thô) được gắn ở train và sampler; `use_full` bật khi có global-context **hoặc** pre-gain. + +**Chuỗi chạy `run_uformer_v10.sh`** (đã phóng, tự chờ 15k xong): GPU0 đánh giá `v9a15k` best (giao thức crop cũ để so A/B/v9a-4k; giao thức toàn khung cho v9a15k, A, v9a-4k, B; probe tông màu; TTA ×8), rồi **v10_ab** (v8 recipe + pool mới, không pre-gain/global-attn). GPU1 **v10** ngay khi 15k xong: v9a recipe + v8 pieces + pre-gain + global-attn, warm-start v9a15k best (EMA), 8k bước, batch 4 × tích luỹ 4, đóng băng encoder 1k, early-stop 4 × 0,02. v10 − v10_ab = giá trị của hai cơ chế mới; v10_ab − v9a15k = giá trị của v8 pieces + pool. Phán quyết trên giao thức toàn khung: lowlight LOLv2-real, scene008 gốc, Test1200, haze. + +### 13.38 v11 — dung lượng ~29M, ngân sách 40k bước, train lũy tiến 256 → 320 → 384, gradient checkpointing (2026-09-05, 00:30) + +Người dùng duyệt hai ý lấy từ SD2: attention toàn cục ở thang thô (đã nằm trong v10) và train lũy tiến theo độ phân giải + gradient checkpointing cho mạng ~30M (v11). Hiện thực (`tests/test_unified_v11.py`, 5 test; 144 test Phase-2 pass): + +**Tăng dung lượng bằng chiều sâu, không bằng chiều rộng.** Mở rộng width (net2net) không bảo toàn hàm qua GroupNorm/attention nên phá warm-start; thay vào đó `--extra-blocks-per-stage 0,2,4,4` **nối thêm** LeWin block sau hai block gốc ở mỗi stage (cả nhánh xuống lẫn lên), adaLN zero-init nên **bitwise identity** khi warm-start (test). Tham số: 12,5M → 27,3M, cộng attention toàn cục 2,3 → **28,8M** (denoiser). Dung lượng dồn vào các thang 64²/32²/16² của trạng thái (kiểu UNet SD: rẻ về activation, giàu về ngữ cảnh), thang mịn 128² giữ nguyên. Bộ nạp warm-start có luật mới `_is_appended_block_key`: chỉ tha thiếu cho block có chỉ số **vượt** mọi block của nguồn ở cùng stage; nguồn sâu hơn đích bị từ chối. + +**Gradient checkpointing** (`--grad-checkpoint`): mỗi LeWin/global block được tính lại trong backward (`torch.utils.checkpoint`, reentrant trên torch 1.10, autocast được bảo toàn); test chứng minh loss và **mọi gradient** bằng nhau với đường không checkpoint. Ràng buộc đã ghi vào mã: reentrant checkpoint không tương thích với DDP `find_unused_parameters` khi block chạy hai lần mỗi iteration (coarse + fine) — mà MoE bắt buộc `find_unused` — nên chỉ dùng cho run **một GPU**; launcher chỉ bật nó ở stage 384 nếu probe cho thấy 2 rank không đủ bộ nhớ. + +**Train lũy tiến theo stage** (`run_uformer_v11.sh`, đã phóng, tự chờ chuỗi v10 xong): đổi crop giữa run phá contract checkpoint (crop_size nằm trong contract), nên mỗi độ phân giải là một run warm-start từ best (EMA) của stage trước, giống warm-restart của Restormer: +- **A** 256, 24k bước, DDP ×2, LR 5e-5; **B** 320, 8k, LR 3e-5; **C** 384, 8k, LR 2e-5. Batch mỗi rank do `probe_v11_memory.py` chọn trước mỗi stage (thử 8×1 → 4×2 → 2×4, ngưỡng 19,5 GiB, batch hiệu dụng 16); đóng băng encoder 1k bước đầu mỗi stage, early-stop 5 × 0,02. +- Warm-start của A chọn tự động trong {v10, v10_ab, v9a15k} theo trung bình 4 nhóm toàn khung (LOLv2 PSNR, Test1200 PSNR-Y, haze, scene008 gốc) sau khi chain chạy full-frame eval cho v10/v10_ab (chuỗi v10 chỉ eval v9a15k/A/v9a-4k/B). +- Sau mỗi stage: eval crop cũ + toàn khung TTA 1; sau C thêm TTA 8 và probe tông màu. Val macro ở 320/384 đo trên crop giữa lớn hơn nên **không so được** với lịch sử 256; early-stop chỉ so trong stage. +- Ước thời gian: v10/v10_ab xong ~15:00–16:00 05-09; A ~24k/2 GPU ≈ 16 h; B, C ≈ 6–8 h mỗi stage → v11 hoàn tất khoảng 07-09. + +**Không làm**: đổi width, bỏ MoE (giữ để warm-start và so sánh sạch; cắt sau khi có số v11), thêm dữ liệu SIDD-Medium (cần tải ~ vài GB, chờ người dùng xác nhận tải). + +### 13.39 Giao thức toàn khung: tile làm lệch phơi sáng (−2,1 dB LOLv2), bảng toàn ảnh A / B / v9a-4k / v9a15k, và khoảng cách thật tới công bố (2026-09-05, 01:30) + +**Run 15k dừng theo yêu cầu ở bước ~10,1k** (strike 2 ở 10k); best.pt = bước 7000. Chuỗi v10 tự khởi động 23:52: v10 train trên GPU1 (eval@0 = 27,6608, trùng bitwise với best 15k — mọi module mới là identity), GPU0 đánh giá. + +**Tile so với một lượt toàn ảnh (v9a15k best@7k, cùng độ phân giải gốc, TTA 1):** + +| Nhóm | Tile 256/chồng 64 | Một lượt toàn ảnh (pad ×128) | Δ | +|---|---|---|---| +| LOLv2-real test (100, 600×400) | 16,88 / Y 18,39 | **19,01 / Y 20,76** | **+2,13** | +| Haze held-out (300, 550×411) | 30,86 / Y 32,66 | **32,09 / Y 34,01** | **+1,23** | +| Test1200 (1200, 384²) | 28,62 / Y 30,20 | 28,73 / Y 30,31 | +0,10 | + +Mỗi tile tự quyết phơi sáng/airlight từ Phase-1 của riêng nó nên các ô lệch nhau ở tần số thấp; blend chồng chỉ giấu vết nối chứ không sửa mức. Kết luận giao thức: ảnh ≤ 1,2 MP đo **một lượt** (`--whole-max-pixels 1200000`; đệm phản chiếu tới bội của 128 để cửa sổ 8×8 giữ nguyên ở 4 thang), chỉ SIDD 12 MP còn tile. Chuỗi v11 đã đổi sang chế độ này (eval chọn warm-start và eval từng stage). Bài học cho mô hình: điều kiện theo crop là gánh nặng khi suy luận ảnh lớn — đúng chỗ context toàn khung + pre-gain toàn ảnh của v10 nhắm tới. + +**Bảng toàn khung, độ phân giải gốc, một lượt (scene008 12 MP vẫn tile), PSNR RGB / PSNR-Y / SSIM / LPIPS:** + +| Run | LOLv2-real test | Test1200 | Haze held-out | scene008 gốc (tile) | +|---|---|---|---|---| +| Ảnh hỏng | 9,72 / 11,09 / 0,199 / 0,519 | 22,29 / 23,78 / 0,700 / 0,276 | 18,00 / 19,46 / 0,829 / 0,082 | 26,47 / 30,62 / 0,554 / 0,465 | +| A (8k, ll_v3) | 19,60 / 21,45 / 0,775 / 0,310 | 28,46 / 30,05 / 0,834 / 0,145 | 31,82 / 33,72 / 0,973 / 0,011 | 29,80 / 31,52 / 0,814 / 0,341 | +| B (8k, ll_v3 + ctx) | **19,71 / 21,53 / 0,779 / 0,308** | 28,41 / 29,98 / 0,833 / 0,146 | 31,99 / 33,90 / 0,972 / 0,011 | 30,31 / – / 0,819 / 0,341 | +| v9a-4k (v5f) | 19,17 / 20,96 / 0,753 / 0,313 | 28,72 / 30,32 / 0,838 / 0,140 | 31,94 / 33,85 / 0,972 / 0,011 | 32,17 / – / 0,836 / 0,307 | +| **v9a15k@7k (v5f)** | 19,01 / 20,76 / 0,752 / 0,312 | **28,73 / 30,31 / 0,838 / 0,141** | **32,09 / 34,01** / 0,972 / 0,011 | **32,62 / 34,48 / 0,842 / 0,295** | + +Đọc: hai run trên Phase-1 v5f (v9a-4k, v9a15k) thắng rain (+0,3), haze (+0,1…+0,3) và **thắng lớn noise gốc** (+2,4…+2,8 dB so A, LPIPS 0,341 → 0,295) nhưng **thua lowlight 0,4–0,7 dB** so A/B — cùng dấu với val (18,82 so 19,05); 15k so 4k: noise +0,45, haze +0,15, rain ngang, lowlight −0,16. Ở thang gốc scene008 là bài khử nhiễu thật (+6,2 dB so input); câu chuyện "input 39 dB bị phá" của §13.16–13.23 phần lớn là artefact thu 12×, phần còn lại (LPIPS 0,29) là làm mịn vân vải. + +**Khoảng cách thật tới công bố (cùng giao thức toàn ảnh):** LOLv2-real 19,0–19,7 so Retinexformer 22,80 / CIDNet 24,11 → **3–5 dB**, vẫn là khoảng cách lớn nhất và là mục tiêu của v10; Test1200 kênh Y 30,3 so Restormer 33,19 → **~2,9 dB** (không phải ~5 như giao thức crop gợi ý) → mục tiêu của v11; haze và SIDD không cùng tập, chỉ tham khảo. Số đo: `outputs/v7_{p5,p45,v9a4k,v9a15k}_fullframe_whole_v1.json` (nhóm nhỏ), `outputs/v7_*_fullframe_v1.json` (tile, có scene008). + +**TTA có hướng (đo 01:48, v9a15k, giao thức tile):** TTA ×8 dihedral cho LOLv2 +0,12, scene008 +0,48 (LPIPS 0,295 → 0,272) nhưng **Test1200 −2,36 dB và haze −1,02**: xoay 90° đổi hướng vệt mưa, lật dọc/xoay 180° đưa trời xuống đáy — model chưa từng thấy. Evaluator có thêm `--tta 2` (identity + lật ngang, an toàn với hướng); chuỗi v11 dùng ×2 cho mọi nhóm và ×8 chỉ cho scene008 (nhiễu đẳng hướng). Số đo: `outputs/v7_v9a15k_fullframe_tta8_v1.json`. + +**Trạng thái 01:53:** v10 (GPU1) eval@1000 = **27,743** (haze 32,37 · lowlight **19,15** · noise 36,96 · rain 22,49) — vượt warm-start 27,661 khi encoder còn đóng băng, lowlight +0,33 và đã hơn A trên val; v10_ab phóng 01:48 trên GPU0 (eval@0 = 27,661). v11 chờ. + +### 13.40 Chẩn đoán giữa chừng v10 (milestone 4000): attention toàn cục có ích, pre-gain end-to-end không học; thêm loss giám sát pre-gain cho v11 (2026-09-05, 07:20) + +**Bối cảnh:** v10 (pre-gain + attention toàn cục 2,3 + v8 pieces) trên val: 27,743@1k (best), rồi 27,54–27,58 ở 3k–5k với **haze val tụt ~1 dB** (32,68 → 31,7) trong khi v10_ab (không hai cơ chế mới) giữ 32,4–32,6 và đạt 27,760@4k. Cần biết cơ chế nào gây tụt trước khi v11 (đang chờ) mang cả hai. + +**Probe pre-gain (`probe_pregain.py`, v10 milestone 4000, 40 ảnh/nhóm):** log-gain trung bình lowlight **0,047** (×1,05; max ×1,07), haze 0,0004, rain 0,001, scene008 −0,005. Sau 4k bước pre-gain gần như vẫn là identity: tín hiệu gradient gián tiếp qua trunk quá yếu (trunk đã tự làm sáng, head zero-init + tanh + dropout 0,1 + LR 3e-5). + +**Eval toàn khung một lượt (haze held-out 300, LOLv2-real 100), milestone 4000:** + +| | Haze held-out | LOLv2-real | +|---|---|---| +| v10 (pre-gain + global-attn) | 32,419 / Y 34,36 | 19,078 / Y 20,80 | +| v10, tắt pre-gain lúc suy luận (`--pregain-dose 0`) | 32,436 | 19,147 | +| v10_ab (không pre-gain, không global-attn) | 32,178 | 18,906 | +| (v9a15k best@7k, cùng giao thức) | 32,09 | 19,01 | +| (A / B) | 31,82 / 31,99 | 19,60 / 19,71 | + +Đọc: (1) **attention toàn cục có ích** trên held-out: v10 hơn v10_ab +0,24 haze, +0,17 lowlight ở cùng bước; haze *val* tụt là hiện tượng 3 cảnh, không tái hiện trên 300 ảnh → giữ `--global-attention-scales 2,3` cho v11. (2) **Pre-gain chưa đóng góp**: tắt nó lúc suy luận còn nhỉnh hơn (+0,02 / +0,07) vì gain ×1,05 học lỡ là nhiễu. (3) Lowlight vẫn kém A/B ~0,5 dB — khoảng cách của Phase-1 v5f trên lowlight chưa được cơ chế nào bù. + +**Sửa cho v11 (đã hiện thực, 2 test, 114 test pass server, commit `2f8efea`/`acb0a71`):** `--pregain-target-weight 0.02` — loss giám sát trực tiếp log-gain với mục tiêu = log(luma trung bình clean / luma trung bình degraded) kẹp ±1,6, tính trên ảnh hỏng gốc trước khi nhân gain; identity/noise pair → 0, lowlight → +1,6, haze → âm nhẹ. Đây là illumination estimator có giám sát kiểu Retinex thay vì hy vọng gradient end-to-end. Recipe v11 giữ pre-gain + attention toàn cục + loss mới. Nếu v11 stage A vẫn không dời gain (probe sau 4k bước), bỏ pre-gain. + +### 13.41 v10 xong; v11 stage A phóng bằng DDP từ v10 best@8k (2026-09-05, 11:15) + +**v10 / v10_ab kết thúc 8k bước (10:49).** Val cuối: v10 **27,751** (haze 32,00 · lowlight 19,18 · noise 37,24 · rain 22,59; best mới, best.pt = 8000); v10_ab 27,628 (best 27,760@4000). External giao thức crop cũ (best.pt): v10 rain 28,027 / scene008 **30,474** / haze **32,461** so v9a15k 28,130 / 28,436 / 31,812 và v10_ab 27,933 / 30,453 / 32,366 → v10 hơn v9a15k +2,0 dB scene008, +0,65 haze, −0,1 rain. Bảng toàn khung đầy đủ chưa đo: người dùng yêu cầu **bỏ đợt chấm điểm và cho v11 train DDP ngay**. + +**v11 stage A đang chạy** (`uformer_v11a_256_seed42`, 11:07): warm-start `uformer_v10_8k_seed42/best.pt` (bước 8000, `WARM_OVERRIDE`), recipe v10 + `--extra-blocks-per-stage 0,2,4,4` + `--pregain-target-weight 0.02`, 30,05M tham số (probe), DDP 2 GPU, batch 4 × tích luỹ 2 mỗi rank (batch 8 tràn 24 GB, batch 4 dùng 12,65 GiB probe / ~16 GB thực), LR 5e-5, 24k bước, ~27 bước/phút → xong ~02:00 06-09; rồi stage B 320 và C 384 tự nối. Hai lỗi launcher đã sửa trong lúc phóng: hàm probe in log vào stdout làm hỏng chuỗi batch (torchrun chết ngay), và resume mất trạng thái early-stop (§13.40 → đã lưu qua checkpoint). + +**Sự cố DDP và cách sửa (11:18–11:25):** lần phóng đầu chết ở bước 250 với "Expected to mark a variable ready only once" tại tham số MoE expert. v11 là run DDP đầu tiên dùng tích luỹ gradient (`no_sync`) cùng `find_unused`: expert bị bỏ qua cứng tuỳ batch và null token chỉ vào đồ thị khi có hàng bị drop, nên tập tham số "dùng" đổi giữa hai micro-batch của một bước — DDP không chịu được. Sửa gốc trong `SpatialExpertBank.forward` (luôn tính mọi expert, nhân trọng số 0 → kết quả bitwise như cũ, test đối chiếu với cài đặt cũ) và `training_loss` (luôn đi qua `null_condition` với mask theo hàng). 126 test pass. Phóng lại 11:25; 13:00 ở bước 2.275, 0 traceback, ~24 bước/phút. + +**Chỉnh giữa chừng stage A (13:05, resume từ bước 2.250):** val @1k/2k = 27,449 / 27,452 với **lowlight 19,18 → 20,04 → 20,33** (pre-gain có giám sát bắt đầu làm việc) nhưng haze 32,0 → 30,4 và noise 37,2 → 36,5. Nguyên nhân haze: mục tiêu pre-gain của cặp haze âm (cảnh sạch tối hơn airlight) nên ảnh haze bị làm tối ×0,7 và trunk phải học lại dehaze trên đầu vào lạ. Sửa: mục tiêu **chỉ nâng sáng** (`clamp(0, 1,6)`), haze/rain/noise → 0. Đồng thời tắt early-stop (val macro không theo external, và best.pt có thể kẹt ở bước 0 = trọng số v10) và **nối stage B/C từ `last.pt`** (cosine đã hạ hết) thay vì best.pt; eval cuối stage chấm cả last lẫn best. Resume bằng cách chép last.pt → overflow_recovery.pt; supervisor báo `[resume] early-stop state restored`; 13:08 hai GPU 100 %. + +### 13.42 Chuyển sang máy MI325X (kim.long-mi325x8) — dữ liệu lên HF, mã và checkpoint sang máy mới, train một GPU (2026-09-05, 14:00–15:00) + +Người dùng dừng v11 trên 3090 ("lâu quá"), yêu cầu (1) đẩy mã v11 lên git (đã ở `origin/master`), (2) đẩy dữ liệu lên Hugging Face, (3) chuyển sang server mới và train trên **một GPU 7, dùng hết GPU**. + +**Dữ liệu:** `hf_bundle_upload.py` đóng gói đúng những file các split/manifest dùng thành 6 tar (SIDD Small 6,6 GB, Snow100K gt 2,6 / synthetic 3,1, Rain13K 1,5, LOLv2 1,1, RESIDE dùng + held-out 0,9) + `manifests/` (manifest Phase-2, quarantine, danh sách file từng split, `path_roots.json`) → https://huggingface.co/datasets/Anbinh93/image_restoration (public; 15,85 GB, tải lên 28 phút; token chỉ qua env). Sau đó thêm `Rain13K_full.tar` (1,8 GB, cả thư mục Kaggle resized) vì `load_rain13k_resized` cần đủ cấu trúc test_resized/* và các cặp bị quarantine cũng phải tồn tại; và `checkpoints/` (Phase-1 v5f best + calibration, v10 best@8k, v11a last@3250). + +**Máy mới:** 8× MI325X 256 GB, ROCm 7.0, env conda `mavt` (Python 3.12, torch 2.10+rocm7.0, lpips), GPU 0–4 bị người khác chiếm, 5/6/7 trống; đĩa 2 TB còn ~110 GB; repo private nên chuyển mã bằng `git archive` → `~/SCDC` (không phải git repo); dữ liệu tải từ HF về `~/data_bundle/extract/{data,kagglehub}` (16 GB, ~250 MB/s). + +**Thay đổi mã cho di động:** `SCDC_DATA_ROOT` / `SCDC_RAIN13K_ROOT` ghi đè gốc dữ liệu mặc định (`/home/admin_mcn/...`); `relocate_manifest.py` viết lại đường dẫn tuyệt đối trong manifest Phase-2 và **tính lại record_id + digest** (record_id băm cả đường dẫn nên thay chuỗi đơn thuần bị `load_train_val_manifest` từ chối) — 18.261/317 record xác thực lại đúng; `make_clean_pools.py` dựng pool identity từ split train (SIDD 121, LOL 689) bằng symlink; `run_uformer_v11_mi325x.sh` = recipe v11 trên một GPU, không DDP, batch/LR/steps tham số hoá. Hệ quả: các checkpoint cũ **không resume** được (digest trong contract khác) nhưng **warm-start** được (`load_v6_warmstart` chỉ kiểm sha + keys). + +**Kiểm chứng trên ROCm:** suite pytest 193/194 pass ở lần chạy `-x` (test lỗi duy nhất là sampler v5 gated cũ, `allclose` số học trên torch 2.10, không nằm trên đường v7/v11); probe `probe_v11_memory.py` trên GPU 7 với mạng 30M: batch 16 → 42 GiB, 0,42 s/bước; batch 32 → 84 GiB, 0,67 s/bước (≈48 mẫu/s so với ≈5,7 mẫu/s của cặp 3090, tức ~8× theo mẫu). + +**Phóng trên MI325X (15:40 VN / 08:40 UTC).** Ba lần phóng: (1) chết ở kiểm tra "digest split khác contract chuẩn" vì record_id băm đường dẫn tuyệt đối → thêm `SCDC_PATH_RELOCATION` (ánh xạ gốc mới → gốc cũ khi tính digest chuẩn, dùng cho cả hằng số contract lẫn provenance của checkpoint Phase-1; test); (2) chạy nhưng GPU chỉ ~20 %, 1,65 s/bước: pool ảnh sạch (SIDD 12 MP PNG) chỉ có 2 worker cố định và tiến trình chính ăn 49 lõi CPU vì thread OpenMP → thêm `--extra-clean-workers` (12), `--workers 32`, `OMP_NUM_THREADS=8`; (3) **0,75 s/bước, GPU 77–99 %**, ≈43 ảnh/giây so với ≈5,7 của cặp 3090 (7,5×). Cấu hình: `uformer_v11a_256_x`, batch 32 (84 GB), LR 7e-5, 20k bước (640k mẫu ≈ 35 epoch), eval mỗi 2k, milestone 5k/10k/15k/20k, warm-start v10 best@8k, không early-stop; stage B 320 (batch 20, 6k) và C 384 (batch 14, 6k) tự nối từ `last.pt`. Bổ sung HF: `Rain13K_missing.tar` (8.310 file còn thiếu để loader kiểm tra đủ cấu trúc và cặp bị quarantine), `RESIDE_fix.tar` (5 ảnh của cửa sổ 5.000 đầu bị Phase-1 loại — thiếu chúng thì cửa sổ trượt và 5 cảnh held-out lọt vào train), README ghi chú. + +### 13.43 Thiết kế kịch bản thử nghiệm cho bài báo — đánh trúng ba đóng góp (2026-09-05) + +**Ba đóng góp cần chứng minh, mỗi đóng góp một bộ thí nghiệm riêng, không trộn:** +- **C1 — Không gian trạng thái suy giảm mở, hiệu chuẩn (Phase-1):** nhận biết loại + mức độ + vị trí + "sạch/lạ" mà không cần nhãn lúc suy luận. +- **C2 — Một mạng phục hồi duy nhất điều khiển bởi trạng thái đó, hành xử đúng liều:** khử đúng mức, không phá ảnh sạch, chịu được suy giảm chồng nhau và OOD. +- **C3 — Giao thức đánh giá trung thực cho bài mù:** độ phân giải gốc, một lượt toàn ảnh, TTA an toàn hướng, tập khoá, và các bộ "hành vi" (identity, liều, hỗn hợp, OOD) mà benchmark all-in-one hiện không có. + +#### 13.43.1 Thí nghiệm Phase-1 (C1) + +Phase-1 không được đánh giá bằng accuracy closed-set (các bài all-in-one báo ~99 % vì test cùng phân phối, không có lớp sạch). Đánh giá theo 5 năng lực, mỗi năng lực một metric chuẩn: + +| Năng lực | Bộ đo | Metric | Baseline so sánh | +|---|---|---|---| +| Nhận loại (in-distribution) | val 317 + locked test (Test1200 + SIDD 008), crop gốc 256 | macro-F1, balanced accuracy | DA-CLIP degradation head (trọng số công bố), ResNet/ViT classifier train cùng crop + lớp "clean", AirNet CBDE + kNN, PromptIR prompt + linear probe | +| Phát hiện "sạch" (null) | clean pool (GT của 4 bộ + Snow100K gt + DIV2K/Flickr sạch) | tỉ lệ → free, FPR@95 % TPR với score = 1 − free mass | classifier + ngưỡng softmax, max-logit, energy score | +| OOD (suy giảm chưa thấy) | Snow100K thật, blur GoPro, JPEG, pixelate, moiré | AUROC, FPR@95 với score = free mass hoặc ‖unknown‖ | cùng các baseline trên với MSP/energy | +| Hiệu chuẩn mức độ | ramp thật: residual SIDD ×{0…1,5}, mưa thật ×α, haze theo t, gain phơi sáng | Spearman ρ theo loại, **tính đơn điệu** của ramp, ECE giữa severity và MAE thật | hồi quy severity đặt trên backbone baseline | +| Suy giảm chồng nhau | tổng hợp có GT: haze+rain, lowlight+noise, rain+noise (mỗi cặp 300 ảnh) | Jaccard(top-k routing, tập thật), ρ severity từng thành phần, mAP spatial map vs mask residual | classifier đa nhãn | + +Ablation Phase-1 (mỗi run ~2 h, cùng seed 42, báo 3 seed cho bản cuối): chính sách crop (cũ / gốc), sàn severity (0 / 0,03 / 0,05), LLGlobalBranch, PhotometricBranch, số node tự do (0 / 1 / 2), số anchor mỗi nhánh (4 / 8 / 16), spatial map, SupCon members, pool OOD Snow100K. Hai ablation quan trọng nhất (crop, sàn) báo thêm **tác động xuôi dòng** lên Phase-2 (cùng recipe, chỉ đổi Phase-1) trên bộ ngoại bộ. + +#### 13.43.2 Thí nghiệm Phase-2 (C2) — không chỉ diffusion + +**Bảng chính (so với công bố) — khuyến nghị dùng giao thức 5-task all-in-one chuẩn** để so trực tiếp với PromptIR / AdaIR / MoCE-IR / DA-CLIP-UIR / InstructIR: dehaze OTS → SOTS-outdoor, derain Rain100L, denoise Gaussian σ15/25/50 (BSD68/Urban100), deblur GoPro, low-light LOL-v1. Lý do: số của họ chỉ có ý nghĩa trên đúng dữ liệu đó; bộ hiện tại (Rain13K bản resized Kaggle, RESIDE 5000 ảnh, LOLv2-real, SIDD Small) không so sánh công bằng được. Chi phí: thêm loader Gaussian/GoPro/LOL-v1, train lại một lần trên MI325X (~1 ngày). Metric: PSNR/SSIM theo đúng quy ước từng bộ (derain kênh Y, còn lại RGB), kèm LPIPS. + +**Bảng thứ hai (đóng góp thật) — bài mù mở trên dữ liệu thật**, nơi các bài all-in-one không đo: SIDD nhiễu thật (validation 1280 patch + scene008 gốc), LOLv2-real, Test1200/Rain13K gốc (tải lại bản gốc từ MPRNet), RESIDE held-out; **và bốn bộ hành vi**: +- **Identity / không phá ảnh sạch:** PSNR(f(x), x) trên clean pool đa phơi sáng (SIDD GT tối có vân, LOL GT, DIV2K); ngưỡng "vô hại" ≥ 40 dB. +- **Đường cong liều:** PSNR phục hồi theo bin severity thật (5 bin) cho mỗi loại; phải đơn điệu và không âm ở bin 0. Baseline all-in-one thường âm ở bin 0. +- **Hỗn hợp:** haze+rain, lowlight+noise, rain+noise tổng hợp có GT; PSNR/SSIM và "phần dư theo loại" (còn haze bao nhiêu sau khi khử). +- **OOD an toàn:** tuyết thật, blur: không có GT → NIQE/MUSIQ của đầu ra so đầu vào, tỉ lệ "không làm hại" (không giảm quá 1 điểm MUSIQ). + +**Diffusion hay mô hình khác?** Khung điều khiển (context token + adaLN + pre-gain + head phơi sáng) không phụ thuộc bộ khử nhiễu. Chạy ba biến thể cùng trunk, cùng điều kiện: (a) ResShift T=2 (mặc định), (b) T=1 = regressor x0 thuần (không nhiễu), (c) T=4; và một biến thể trunk khác: Restormer-style (conv/attention kênh) thay LeWin. Kỳ vọng và cách đọc: PSNR gần nhau giữa (a) và (b) (đã đo: 2-step chỉ +0,7 so 1-step), LPIPS/DISTS tốt hơn ở (a); nếu đúng thì tuyên bố là "framework điều khiển", diffusion là lựa chọn perceptual, không phải điều kiện cần. Metric perceptual: LPIPS, DISTS; no-reference: NIQE, MUSIQ; hiệu năng: tham số, FLOPs, độ trễ 512² theo số bước. + +#### 13.43.3 Ablation — một bảng, mỗi hàng trả lời một câu hỏi + +Cùng warm-start, cùng 8k bước trên MI325X (~1,5 h/run ở batch 32), báo val + 4 bộ ngoại bộ + identity + LPIPS: + +| Hàng | Câu hỏi | Đã có số? | +|---|---|---| +| Không Phase-1 (p = 1), warm-start **và** from scratch | Phase-1 có cần cho phục hồi không | warm-start: −0,40 (§13.21); from scratch: chưa | +| Nhãn cứng one-hot (oracle) / nhãn dự đoán bởi classifier thay trạng thái mềm | Trạng thái mở, mềm hơn nhãn cứng ở đâu (identity, hỗn hợp, OOD) | chưa — **ablation then chốt cho C1→C2** | +| Đổi Phase-1 ll_v3 → v5f, cùng recipe | Chất lượng Phase-1 truyền xuống bao nhiêu | có (§13.35) | +| Tắt từng trường lúc suy luận (context, global, unknown, routing, severity, spatial) | Trunk dùng trường nào | có (§13.18) | +| Context toàn khung on/off | Thông tin ngoài crop | có (B − A) | +| Pre-gain giám sát on/off; head phơi sáng on/off | Đường tông màu | v11 | +| Identity pairs on/off, pool tối có vân on/off | Hành vi không phá ảnh sạch | một phần (dgf8k) | +| Attention toàn cục 2,3 on/off | Trường tiếp nhận toàn crop | có (v10 vs v10_ab) | +| T = 1 / 2 / 4 | Diffusion có cần | một phần (§13.5, 13.12) | +| 13M / 29M; 256 / lũy tiến 384 | Dung lượng, độ phân giải | v11 | +| Sàn severity, crop gốc (ở Phase-1) → Phase-2 | Dữ liệu Phase-1 ảnh hưởng xuôi dòng | một phần | + +Mỗi ablation 1 seed; mô hình chính 3 seed với khoảng tin cậy cluster-bootstrap theo cảnh (không bootstrap theo ảnh vì record dùng chung cảnh, §7). + +#### 13.43.4 Việc cần làm trước khi chạy bảng +1. Tải lại Rain13K gốc (MPRNet) và, nếu chọn giao thức 5-task, thêm loader Gaussian/GoPro/LOL-v1. +2. Evaluator: thêm PSNR-Y/SSIM-Y theo mã MATLAB chuẩn, DISTS, NIQE/MUSIQ; bộ hỗn hợp tổng hợp có GT; bộ ramp thật; clean pool đa phơi sáng. +3. Baseline: tải trọng số công bố (PromptIR, AdaIR, MoCE-IR, DA-CLIP-UIR, Restormer, DehazeFormer, Retinexformer, CIDNet) và chạy qua **cùng** evaluator toàn khung. +4. Ablation "nhãn cứng thay trạng thái mềm" (thêm cờ `--condition-mode onehot` dùng oracle label / classifier). + +#### 13.43.5 Kịch bản cụ thể: dữ liệu, đối thủ, bảng + +**Bảng D — dữ liệu.** 5 loại đã biết (K = 5 nhánh ngữ nghĩa, khớp giao thức 5-task) + 3 loại giữ lại làm OOD cho node tự do + nhiễu thật để kiểm định node noise trên dữ liệu thật. + +| Loại | Train (chuẩn) | Test công bố | Vai trò | +|---|---|---|---| +| Haze | RESIDE OTS (72k, hoặc 5k subset) | SOTS-outdoor 500 | biết | +| Rain | Rain100L 200 (5-task) và Rain13K 13.712 gốc | Rain100L 100; Test100 / Rain100H / Rain100L / Test2800 / Test1200 | biết | +| Noise (Gaussian) | BSD400 + WED 4.744, σ ∈ {15, 25, 50} | BSD68, Urban100 | biết (so công bố) | +| Noise (thật) | SIDD-Medium 320 | SIDD validation 1.280 patch, scene008 gốc | biết (đóng góp) | +| Low-light | LOL-v1 485; LOLv2-real 689 | LOL-v1 15; LOLv2-real 100 | biết | +| Blur | GoPro 2.103 | GoPro 1.111 | biết | +| Snow | Snow100K (không train) | Snow100K-S/M/L, CSD | **OOD** | +| JPEG / pixelate / moiré | không train | LIVE1 Q10–40, tổng hợp | **OOD** | +| Sạch | GT của các bộ trên + DIV2K, Flickr2K | 500 ảnh đa phơi sáng | identity / null | +| Hỗn hợp | tổng hợp từ GT: haze+rain, low+noise, rain+noise, haze+low | 300 mỗi cặp, có GT | composition | + +**Bảng P1 — Phase-1 so với ai, đo gì.** + +| Phương pháp | Bản chất | Nhận loại (F1) | Null (FPR@95) | OOD (AUROC) | Severity (ρ, đơn điệu) | Hỗn hợp (Jaccard) | +|---|---|---|---|---|---|---| +| ResNet-50 / ViT-B classifier + lớp clean, cùng crop | closed-set có clean | ✓ | MSP | MSP/energy | hồi quy gắn thêm | đa nhãn | +| CLIP zero-shot ("a photo with rain") | không train | ✓ | – | – | – | – | +| DA-CLIP degradation head | closed-set, trọng số công bố | ✓ | MSP | MSP | – | – | +| AirNet CBDE + kNN / linear probe | contrastive | ✓ | kNN dist | kNN dist | – | – | +| PromptIR prompt weights + probe | ẩn | ✓ | – | – | – | – | +| **SCDC Phase-1** | đồ thị mở | ✓ | free mass | free mass / ‖unknown‖ | ✓ | ✓ | + +**Bảng P2 — Phase-2 so với ai (cùng evaluator toàn khung, trọng số công bố).** + +| Nhóm | Phương pháp | Bộ so | +|---|---|---| +| Đơn tác vụ | Restormer (Rain13K, Gaussian, SIDD), MPRNet, DehazeFormer-L (SOTS), NAFNet (SIDD, GoPro), Retinexformer, CIDNet (LOL) | từng benchmark | +| All-in-one 3/5-task | AirNet, PromptIR, AdaIR, MoCE-IR, DA-CLIP-UIR, InstructIR (DCPT/DyNet nếu có trọng số) | SOTS, Rain100L, BSD68, GoPro, LOL + 4 bộ hành vi | +| Diffusion phục hồi | DiffUIR, AutoDIR (nếu có trọng số) | như trên, thêm LPIPS/DISTS | +| **SCDC** | T=2 (chính), T=1, T=4, trunk Restormer-style | tất cả | + +Cột metric: PSNR/SSIM theo quy ước bộ (derain kênh Y), LPIPS, DISTS; hành vi: identity PSNR trên clean 500, đường cong liều (PSNR theo 5 bin severity), hỗn hợp PSNR/SSIM, OOD ΔMUSIQ; hiệu năng: tham số, FLOPs, ms/ảnh 512². + +**Bảng A — ablation (cùng warm-start, 8k bước, batch 32 trên MI325X ≈ 1,5 h/run).** Cột: val macro · SOTS · Rain100L · BSD68 σ25 · GoPro · LOL · SIDD · identity · LPIPS. + +| # | Hàng | Câu hỏi | +|---|---|---| +| A1 | Full SCDC | tham chiếu | +| A2 | không Phase-1 (p = 1), warm-start | Phase-1 có cần khi fine-tune | +| A3 | không Phase-1, from scratch | Phase-1 có cần từ đầu | +| A4 | one-hot oracle label thay trạng thái mềm | mềm/mở hơn nhãn cứng ở đâu | +| A5 | one-hot từ classifier (ResNet) | như A4 với nhãn thực tế | +| A6 | Phase-1 không sàn severity / crop cũ | dữ liệu Phase-1 truyền xuống | +| A7 | không node tự do (K only) | null/OOD có cần slot riêng | +| A8 | tắt context / global / unknown / routing / severity / spatial (suy luận) | trường nào được dùng | +| A9 | không context toàn khung | thông tin ngoài crop | +| A10 | không pre-gain / không head phơi sáng | đường tông màu | +| A11 | không identity pairs / pool sáng thay pool tối | không phá ảnh sạch | +| A12 | không attention toàn cục | trường tiếp nhận | +| A13 | T = 1 / T = 4 | diffusion có cần | +| A14 | trunk Restormer-style | khung không phụ thuộc trunk | +| A15 | 13M thay 29M; chỉ 256 thay lũy tiến | dung lượng, độ phân giải | +| A16 | không MoE expert | dọn phần đã đo là chết | + +Ngân sách: P1 baseline train ≈ 5 run × 2 h; A ≈ 16 run × 1,5 h ≈ 1 ngày GPU; bảng chính 5-task train lại ≈ 1 ngày; mô hình chính 3 seed ≈ 1,5 ngày. Tổng ≈ 4–5 ngày trên một MI325X. + +### 13.44 t-SNE / UMAP / PCA của đồ thị Phase-1 v5f (2026-09-05, chạy trên MI325X) + +`visualize_phase1_tsne.py` (hình `docs/figures/tsne_*.png`, số `docs/figures/phase1_tsne_report.json`): 954 crop 256 = val 4 loại (rain 98, noise 19, haze 100, lowlight 100) + GT sạch tương ứng + Test1200 (100) + scene008 (20) + 200 ảnh tuyết OOD. Ba trường: `global_condition`, `unknown_residual`, và **vector đồ thị** Σ routing·(anchor(sev)+token)/√2 nhúng chung với 32 anchor, gốc sạch, 2 node tự do. + +| Trường | silhouette theo loại (đặc trưng / t-SNE) | kNN-10 purity (11 nhóm) | AUROC free-mass sạch+OOD vs hỏng | ρ severity theo PC1: rain / noise / haze / lowlight | +|---|---|---|---|---| +| global_condition | 0,62 / 0,72 | 0,61 | 0,85 | 0,83 / 0,88 / 0,57 / 0,48 | +| unknown_residual | −0,04 / 0,09 | 0,58 | 0,85 | 0,15 / 0,85 / 0,48 / 0,46 | +| vector đồ thị | 0,44 / 0,64 | 0,57 | 0,85 | 0,07 / 0,08 / 0,31 / 0,83 | + +Đọc hình: (1) lowlight, haze, noise (+scene008) là ba cụm tách rời với **gradient severity dọc cụm** (haze: cánh tay dài từ nhẹ đến nặng; lowlight và noise cũng có thứ tự). (2) **Rain và tuyết OOD lẫn nhau** trong global_condition và vector đồ thị: node rain vẫn là "cảnh ngoài trời có thể có vệt", tuyết chỉ tách ở routing (→ free 0,75) chứ không tách trong vector; đây là chỗ cần nhánh có hướng (HL/LH) hoặc loss tách OOD trên vector. (3) **Ảnh sạch không gom về một gốc**: clean của mỗi loại nằm cạnh cụm hỏng của loại đó (nội dung lẫn vào global_condition); clean haze còn tạo lưới điểm trùng nhau vì RESIDE nhân bản cùng cảnh sạch. (4) Các polyline anchor nhỏ và xoắn quanh gốc/free node (init 0,02, học chậm); chỉ nhánh lowlight kéo dài về cụm lowlight — thứ tự severity đến từ token nhiều hơn từ anchor. (5) unknown_residual không mang cấu trúc loại (silhouette ≈ 0) nhưng lại là trường Phase-2 dùng nhiều nhất (−0,74 dB): nó mã hoá "cảnh/dòng dữ liệu" hơn là suy giảm. + +Hệ quả cho bài báo: hình t-SNE của global_condition dùng được làm hình chính về không gian trạng thái (3/4 nhánh có thứ tự); cần thêm (a) loss tách OOD/rain trên vector, (b) loss kéo mọi ảnh sạch về gốc trong không gian global (root loss hiện chỉ ở không gian node), (c) anchor spacing đủ lớn hoặc chuẩn hoá để hình học nhánh nổi lên trong nhúng. + +### 13.45 Đề xuất v12 (2026-09-05) — điều kiện tiên quyết: đọc số v11 stage A trên MI325X trước + +Cổng quyết định từ v11 (giao thức toàn khung): (G1) pre-gain giám sát có kéo LOLv2-real lên ≥ +1 dB so v10 không; (G2) 28,8M + lũy tiến có kéo Test1200 kênh Y lên ≥ +1 dB không; (G3) probe pre-gain sau 4k bước có gain ≠ 1 không. Từ đó v12 chọn nhánh: + +**v12-A — Phase-1 v6 (sửa ba điểm yếu t-SNE §13.44, giữ giao diện):** +1. Loss kéo *mọi* ảnh sạch về gốc trong không gian `global_condition` (hiện root loss chỉ ở không gian node) → clean thành một cụm, không nằm cạnh cụm hỏng cùng loại. +2. Loss tách OOD trên vector đồ thị/global (margin giữa tuyết thật và rain), cộng đặc trưng băng có hướng (HL/LH Haar hoặc đường cong năng lượng theo băng) để rain ≠ snow ≠ nhiễu. +3. Chuẩn hoá anchor (LayerNorm + spacing cố định) để hình học nhánh nổi trong nhúng; loss đơn điệu severity dọc anchor. +4. Nếu chọn giao thức 5-task: K = 5 nhánh (thêm blur), Gaussian noise vào node noise, retrain 2 h. + +**v12-B — Phase-2 "dose-controlled" (nếu G1 thất bại):** +1. Thay gain vô hướng bằng **bản đồ illumination** 16×16 → upsample (Retinex đầy đủ), giám sát bằng tỉ số luma cục bộ; áp trước trunk. +2. Cắt điểm cắm chết (MoE 7 bank, content/spatial inject) → −0,4M tham số, DDP không cần find_unused; chuyển κ per-type thành κ toàn cục. +3. T=1 regressor làm mô hình PSNR chính, T=2 làm biến thể perceptual (nếu A13 xác nhận). +4. Cặp hỗn hợp tổng hợp (haze+rain, low+noise) trong train với severity đa thành phần → kiểm composition thật sự. + +**v12-C — dữ liệu và giao thức (song song, không phụ thuộc G):** Rain13K gốc, SIDD-Medium, LOL-v1, GoPro, Gaussian (5-task); evaluator DISTS/NIQE/MUSIQ, bộ hỗn hợp, bộ ramp, clean pool; baseline công bố qua cùng evaluator; cờ `--condition-mode onehot` cho ablation then chốt A4/A5. + +Thứ tự khuyến nghị: C ngay (không cần GPU nhiều), rồi A (2 h/run) trong lúc v11 chạy, B sau khi có G1–G3. + +### 13.46 Khái niệm đồ thị suy giảm — định nghĩa node và cạnh (2026-09-05) + +Hiện trạng: "đồ thị" trong mã là một **cây sao có thứ tự** (gốc sạch → 4 chuỗi anchor × 8 + 2 node tự do); quan hệ chỉ tồn tại dưới dạng hình học (vị trí trên chuỗi) và một self-attention không giám sát giữa 6 token. Không có cạnh nào được định nghĩa hay giám sát tường minh. Đề xuất định nghĩa lại G = (V, E) để "đồ thị" đúng nghĩa là biểu diễn quan hệ: + +**Node V** + +| Node | Ý nghĩa | Số lượng | Tham số | +|---|---|---|---| +| v₀ gốc sạch | trạng thái không suy giảm, severity = 0 mọi nhánh | 1 | embedding | +| v_{k,j} anchor mức | trạng thái "loại k ở mức j" (thứ tự chặt chẽ theo severity) | K × L (4 × 8) | embedding có ràng buộc đơn điệu | +| c_m node họ (taxonomy) | cha chung của các loại cùng cơ chế vật lý: *cộng tần cao* {rain, snow, noise}, *suy giảm truyền* {haze, lowlight} | 2 | embedding | +| u_i node tự do | suy giảm chưa gặp, gắn dưới node họ gần nhất (tuyết → cộng tần cao, gần rain nhưng khác node) | 2 | embedding | +| s node cảnh | ngữ cảnh không phải suy giảm: phơi sáng, airlight, nội dung toàn cục (z_scene ở §13.45/§ trả lời chồng lấp) | 1 | tính từ LL/HVI | + +**Cạnh E (mỗi cạnh có nghĩa và cách giám sát riêng)** + +| Cạnh | Quan hệ | Trọng số | Giám sát | +|---|---|---|---| +| v_{k,j} → v_{k,j+1} | "nặng hơn" (thứ tự) | cố định | loss đơn điệu severity dọc chuỗi, ramp thật | +| v₀ → v_{k,1} | "khởi phát" | cố định | root loss (ảnh sạch → v₀, z_deg = 0) | +| c_m → v_{k,·}, c_m → u_i | "cùng họ" | cố định theo taxonomy | OOD được kéo về node tự do *dưới đúng họ* (margin với anh em, không với cả đồ thị) | +| v_k ↔ v_l (k ≠ l) | "đồng xuất hiện / tương tác" A_kl | học được, đối xứng | cặp hỗn hợp tổng hợp có GT (haze+rain, low+noise…): routing đa nhãn và cạnh e_kl = 1; prior vật lý: haze↔lowlight (đều làm giảm tương phản), rain↔noise (đều cộng tần cao) | +| ảnh → v | "được giải thích bởi" (routing p_k, vị trí t_k, hỗ trợ không gian m_k) | tính từ ảnh | route CE, severity, spatial như nay | +| ảnh → s | "diễn ra trong cảnh" | tính từ ảnh | nhất quán hỏng↔sạch cùng cảnh | + +**Một ảnh là một đồ thị con được kích hoạt**: tập node có mass (p), vị trí trên chuỗi (t), bản đồ hỗ trợ (m), cạnh tương tác đang bật (e_kl = p_k p_l A_kl), và node cảnh s. Token của node được tính bằng **truyền thông điệp có kề học được** thay vì self-attention tự do: h_k ← base_k + W_k z_deg + Σ_l e_kl · φ(h_l); 1–2 vòng; token cảnh không nhận thông điệp từ node suy giảm (giữ trực giao). Readout cho Phase-2 = các token đang kích hoạt + token cảnh + vector cạnh. A_kl là ma trận 4×4 (6×6 với node tự do) xem được, trả lời trực tiếp "loại nào tương tác với loại nào" — thứ mà hiện nay không tồn tại. + +**Khác gì hiện tại và cần gì:** (1) thêm 2 node họ và ma trận A học được (≈ 40 tham số); (2) thay self-attention token bằng GAT-lite có mask kề (mã nhỏ); (3) dữ liệu hỗn hợp tổng hợp có GT để cạnh tương tác có nhãn (đã nằm trong v12-B4/13.43); (4) loss đơn điệu dọc chuỗi và margin trong-họ cho OOD (v6 đã có margin toàn cục); (5) tách z_deg / z_scene (§13.45). Đây là Phase-1 v7; giữ nguyên contract 8 token cho Phase-2 nên không phải sửa trunk. + +### 13.47 Nghĩ lại ý tưởng đồ thị (2026-09-05, người dùng: "ý tưởng graph đầu tiên có vấn đề") + +**Vấn đề của ý tưởng gốc, theo bằng chứng đã đo:** +1. Node = nhãn bộ dữ liệu, không phải yếu tố vật lý → "đồ thị" là bộ phân loại mềm được vẽ lại; quan hệ giữa node chưa từng được định nghĩa hay giám sát (§13.46). +2. Severity = MAE residual tương đối theo bộ dữ liệu (Rain13K lệch tone → ρ 0,35), không phải đại lượng vật lý; thứ tự dọc nhánh đến từ token, anchor gần như không học (t-SNE §13.44). +3. Bộ phục hồi không dùng cấu trúc: routing −0,05, severity −0,03, spatial 0, MoE 0,1 dB; nó dùng hai vector dày (§13.18). Không Phase-1 chỉ −0,4 dB (§13.21). Tuyên bố "trạng thái đồ thị điều khiển phục hồi" không được số ủng hộ. +4. Hỗn hợp suy giảm chưa bao giờ được train (dữ liệu đơn nhãn) → mọi claim về composition chưa kiểm. +5. Node tự do / unknown không có ngữ nghĩa; unknown_residual trở thành mô tả cảnh. +Những gì **thật sự có tác dụng** đều là cơ chế vật lý/toàn cục: crop gốc, sàn severity (dữ liệu), context phơi sáng toàn khung, clean prior, identity pairs, pre-gain, suy luận toàn ảnh. + +**Ba cách đặt lại bài toán:** +- **A. Mô hình yếu tố vật lý (đồ thị *toán tử*, không phải đồ thị nhãn):** ảnh hỏng I = 𝒜(airlight, t) ∘ 𝒢(gain, gamma) ∘ 𝒮(streak density, hướng, độ dày) (J) + n(σ, cấu trúc). Node = toán tử, cạnh = thứ tự hợp thành, trạng thái = tham số θ từng ảnh, hiệu chuẩn bằng tổng hợp có θ thật (RESIDE có t, A; mưa tổng hợp có mật độ/góc; gain LOL; σ SIDD từ residual). "Sạch" = θ trung tính; hỗn hợp có sẵn theo cấu trúc; OOD = residual sau khi giải thích bằng toán tử. Phục hồi = trunk điều kiện bởi θ **cộng** tiền xử lý nghịch đảo (pre-gain là trường hợp đầu tiên đã có). +- **B. Bỏ claim đồ thị, giữ descriptor:** z dày + SupCon + severity + head null/OOD (kiểu DA-CLIP/AirNet có thêm open-set); trung thực nhất với số hiện có, đóng góp = open-set + hiệu chuẩn + hành vi identity. Ít mới. +- **C. Đồ thị thật trên vùng ảnh (trường suy giảm):** node = vùng/patch với trạng thái cục bộ, cạnh = kề/giống nhau, truyền thông điệp cho nhất quán toàn ảnh (đúng lỗi tile −2,1 dB và nhu cầu context toàn khung); đầu ra là **bản đồ liều** không gian. + +**Khuyến nghị: A + C = "trường suy giảm vật lý"**: ước lượng θ theo lưới thô (streak, t/A, gain, σ), một đồ thị nhẹ trên vùng làm mượt/nhất quán toàn ảnh, trunk nhận θ làm điều kiện dày và tiền xử lý vật lý; null/OOD = θ trung tính + residual. Giữ toàn bộ phần đã chứng minh có ích, bỏ đồ thị nhãn, và mọi claim kiểm được bằng θ thật. + +**Kiểm chứng nhanh (1–2 ngày):** (i) tổng hợp dữ liệu có θ thật, train bộ ước lượng trường, đo R²/thứ tự từng tham số và hỗn hợp; (ii) cắm trường vào trunk hiện có (token từ pooled θ + adaLN) và so với điều kiện v5f trên cùng trunk bằng hạ tầng "đổi Phase-1, giữ recipe" (§13.35); (iii) t-SNE lại trên θ: ảnh sạch phải gom ở θ trung tính theo định nghĩa. + +### 13.43 Ablation photometric trên MI325X (5k bước, cùng warm-start v10 best@8k, recipe v11, batch 32, LR 7e-5) và head màu v12 (2026-09-05, 16:03 UTC) + +Câu hỏi của người dùng: nhánh photometric (head phơi sáng + pre-gain) có đáng không, và "ma trận màu + gamma" kiểu HVI-CIDNet+ (arXiv 2507.06814) có lấy được gì. Trước đó, oracle trên output v11a (LOLv2, toàn khung, khớp GT từng ảnh): thô 19,34 → affine cường độ 27,46 → gamma+affine 27,88 → **ma trận 3×3 + bias 29,30** → gamma+ma trận 29,88: gần 10 dB còn lại là biến đổi màu/tông toàn cục theo ảnh. Hiện thực `GlobalColourHead` (v12): y = diag(e^d)(I+O)x + b trên output, bounded, zero-init, loss giám sát bằng nghiệm bình phương tối thiểu từng ảnh (`colour_target`, ridge, 4.096 pixel), dropout 0,1, liều `--colour-dose`. + +**Eval toàn khung một lượt (LOLv2-real 100 · Test1200 1200 · haze 300 · scene008 20 gốc), `last.pt` sau 5k bước:** + +| Biến thể | LOLv2 PSNR / SSIM | Test1200 PSNR / Y | Haze | scene008 PSNR / LPIPS | +|---|---|---|---|---| +| A_nophoto (không head phơi sáng, không pre-gain) | 18,72 / 0,757 | 28,81 / 30,38 | **32,58** | 33,75 / 0,283 | +| B_photo (= stage A milestone 5000; LR chưa hạ hết) | **19,34 / 0,786** | **29,11 / 30,68** | 32,31 | 33,56 / 0,293 | +| C_colour (B + head màu v12, cosine 5k hạ hết) | 19,12 / 0,784 | 28,86 / 30,43 | 32,41 | **33,77 / 0,279** | +| C_colour, tắt head màu lúc suy luận | 18,80 / 0,781 | 28,91 / 30,49 | 32,36 | 33,78 / 0,278 | +| Tham chiếu v9a15k best@7k (13M) | 19,01 / 0,752 | 28,73 / 30,31 | 32,09 | 32,62 / 0,295 | + +Đọc: (1) **Nhánh photometric đáng giữ nhưng nhỏ**: A→B LOLv2 +0,62 dB / +0,029 SSIM, rain +0,29; đổi lại haze −0,28, scene008 −0,19 (B là checkpoint giữa lịch LR nên so A–C sạch hơn: C hơn A LOLv2 +0,40, haze −0,17, rain +0,05). (2) **Head màu v12 cho +0,32 dB LOLv2 riêng phần nó** (19,12 so 18,80 khi tắt), gần như trung tính ở domain khác — tức phần *dự đoán được* của biến đổi màu toàn cục chỉ ~0,3 dB trong khi trần oracle là ~10 dB: phần còn lại là phơi sáng/cân bằng trắng do người chụp chọn cho GT, không suy được từ input (cùng kết luận §13.27 với núm cường độ). (3) Cả ba biến thể 30M ở 5k bước đều vượt v9a15k trên rain (+0,1…+0,4), haze (+0,2…+0,5) và scene008 (+0,9…+1,2); **LOLv2 vẫn kẹt 18,7–19,3**, dưới A cũ (19,60) và xa CIDNet 24,3. Kết luận: khoảng cách lowlight không nằm ở head toàn cục nữa; hoặc chấp nhận nó là nhiễu GT của LOL (như GT-mean trong văn liệu), hoặc phải đổi biểu diễn của trunk (HVI hai nhánh) và train riêng lowlight — ngoài phạm vi mạng thống nhất hiện tại. + +**Vận hành:** stage A (`uformer_v11a_256_x`) bị giết từ bên ngoài lúc 13:26 UTC ở bước ~14.850 cùng phút với C (máy dùng chung); last.pt = 14.750, milestone 5k/10k; val @10k 27,711 (lowlight 20,05, noise 38,04), @14k 27,626. Người dùng yêu cầu dừng toàn bộ lúc 16:23 UTC. Số đo: `outputs/abl_{A_nophoto,B_photo,C_colour,C_colour_nodose}_fullframe_whole_v1.json` trên kim.long-mi325x8. + +### 13.48 Đặt lại Phase-1: suy giảm là *độ dịch chuyển khỏi ảnh sạch* (2026-09-05) + +Đề bài của người dùng: Phase-1 = "biểu diễn dữ liệu suy giảm theo ảnh sạch", cần tách được (1) node tồn tại thế nào, key/value là gì, học node từ node sạch ra sao; (2) nối node bằng cách nào (mô hình hoá quan hệ); rồi r đi vào dual attention của pipeline hiện tại. + +**Kiểm tra mã hiện tại** (`train_graph_encoder_v2.py` ≈ dòng 1376–1391): ảnh sạch cặp chỉ dùng để (a) kéo `global_condition` của ảnh sạch về **một điểm** `clean_root` cố định, ép severity/spatial/unknown về 0, (b) ép `content_latent` bất biến, (c) tính target severity (MAE). Biểu diễn suy giảm **chưa bao giờ được định nghĩa là hiệu giữa ảnh hỏng và ảnh sạch cùng nội dung**. Đó là gốc của ba lỗi đo được: ảnh sạch không gom về root (vì root là một điểm, nội dung không thể sụp), unknown_residual mang cảnh, anchor không học. + +#### Nguyên lý +Encoder E: I ↦ (c, Δ). c ∈ ℝ^{d_c} là mã nội dung; Δ ∈ ℝ^{d} là **độ dịch chuyển suy giảm** (degradation displacement). Định nghĩa: +- Node sạch (gốc): Δ = 0. Không ép c của ảnh sạch về đâu cả. +- Với cặp (J sạch, I = D_k(J; θ)): c(I) ≈ c(J) và Δ(I) nằm trong node k. Nội dung **triệt tiêu theo cấu trúc** vì node được học từ *hiệu* giữa hai ảnh cùng nội dung, không phải từ ảnh tuyệt đối. + +#### 1. Node: tồn tại, key, value +- **Tồn tại:** node k là một **không gian con** m chiều U_k ∈ ℝ^{d×m} (m ≈ 8) đi qua gốc trong Δ-space, không phải một điểm hay một tia. Tia (anchor cũ) quá cứng: trong một loại còn có biến thể (góc/độ dày vệt mưa, màu airlight, phổ nhiễu theo ISO). +- **Key** = U_k: bộ dò của node. Năng lượng chiếu ‖U_kᵀΔ‖² đo "node k giải thích được bao nhiêu độ dịch chuyển". Routing r_k = softmax_k(‖U_kᵀΔ‖²/τ) kèm key phần dư. +- **Value** = a_k = U_kᵀΔ ∈ ℝ^m: **toạ độ của thể hiện** suy giảm trong node. Toạ độ đầu a_k[0] là severity (được giám sát), các toạ độ còn lại là biến thể trong loại. Token gửi Phase-2: t_k = e_k + W_k a_k (e_k học được = danh tính node). +- **Node gốc:** token t_0 học được (điểm quy chiếu "sạch"), value = 0. +- **Node tự do:** U_free học không nhãn để giải thích phần dư Δ − Σ_k U_k U_kᵀ Δ (kiểu PCA có học); **node phần dư:** t_res = W_r · phần dư còn lại → điểm OOD = ‖phần dư‖. +- **Học node từ node sạch** (mọi bộ đều có cặp: Rain13K, SIDD, RESIDE, LOL, Snow100K; clean pools là mẫu null và nền tổng hợp): + 1. Gốc: ‖Δ(J)‖ → 0; hinge ‖Δ(I)‖ ≥ m₀ với ảnh hỏng (thay severity floor). + 2. Nội dung: c(I) ≈ sg(c(J)) (đối xứng nửa trọng số), LOL dùng tolerant loss vì lệch nhẹ. + 3. Gán node: ‖U_kᵀΔ(I)‖² ≥ (1−ε)‖Δ(I)‖² cho nhãn k; năng lượng ở U_l≠k → 0; trực giao **mềm** giữa các U (không ép giữa các loại thật sự đồng xảy ra như lowlight–noise, việc đó để cạnh tương tác lo). + 4. Severity: a_k[0] hồi quy tham số vật lý khi biết (t/A của RESIDE, gain LOL, σ SIDD ước từ residual, mật độ lớp mưa) và ranking đơn điệu khi không biết; MAE chỉ là dự phòng. + 5. (Tuỳ chọn, mạnh) Decoder proxy G ở 64×64: G(c(I), Δ(I)) ≈ I↓ và **G(c(I), 0) ≈ J↓** — định nghĩa *vận hành* của node gốc: xoá Δ là xoá suy giảm. Cấy ghép: G(c(J'), Δ(I)) ≈ D_k(J') khi tổng hợp được. Node tồn tại ⇔ xoá thành phần của nó trong Δ xoá đúng suy giảm đó. + +#### 2. Cạnh: chỉ giữ quan hệ đo được và giám sát được +- **Họ (kinship, cạnh cha–con):** U_k = [U_fam(k) | U_k^spec]; rain và snow chia sẻ U_additive-HF, haze ∈ attenuation, lowlight ∈ photometric, noise ∈ stochastic. Loại chưa thấy chiếu được vào U_fam nhưng không vào U_k^spec → "OOD nhưng thuộc họ additive" (open-set có ngữ nghĩa). +- **Hợp thành / tương tác (cạnh có hướng):** Δ(D_a∘D_b(J)) = U_a a_a + U_b a_b + ε_ab(a_a, a_b). ε_ab = 0 ⇒ độc lập (cộng được); ε_ab ≠ 0 ⇒ tương tác (nhiễu sau haze bị pha loãng, mưa trên ảnh tối đổi tương phản). Học ε từ **hỗn hợp tổng hợp** có sẵn: lớp mưa I−J cấy từ Rain13K sang ảnh sạch khác, haze theo t/A, gain/gamma, nhiễu Poisson–Gauss, ngân hàng residual SIDD (đã có trong mã). Đây là quan hệ đầu tiên của đồ thị có thể **dự đoán tổ hợp chưa thấy** và kiểm bằng số. +- **Thứ tự trong node:** a_k[0] đơn điệu theo severity (ranking loss). +- **Truyền thông điệp (một bước):** t_k' = t_k + Σ_l r_l · M(ε_kl(a_k, a_l)). Đơn suy giảm ⇒ identity; hỗn hợp ⇒ token biết tương tác. + +#### 3. r và dual attention của pipeline hiện tại +- Attention 1 (trong Phase-1, trên đồ thị): query = Δ, key = U_k → routing, severity, value a_k. +- Attention 2 (Phase-2, Uformer): query = đặc trưng pixel, key/value = token [t_0, t_1..t_K, t_free, t_res, t_photo] — đúng giao diện 8×256 của `GraphConditionerV4` hiện có, nên Phase-2 không đổi cấu trúc. +- Vector toàn cục cho adaLN = Δ (không nội dung) ‖ trạng thái photometric. Bỏ content inject và spatial inject (đo = 0,000 / +0,005). +- `ExposurePreGain` đọc thẳng a_lowlight[0] (gain vật lý) thay vì suy từ vector đen. + +``` +ảnh I ──► backbone (CNN ‖ LL ‖ HVI) ──► c (nội dung, 256) + └──► Δ (dịch chuyển, 256) ── query + bank {U_k} (key) ──► a_k = U_kᵀΔ (value) ─► severity a_k[0], routing r_k + phần dư ─► U_free, t_res, điểm OOD + cạnh ε_kl (hợp thành) + họ U_fam ──► truyền thông điệp ──► token t_k' + r = { [t_0, t_1..t_4, t_free, t_res, t_photo] → cross-attn ; Δ‖photo → adaLN } +``` + +#### Vì sao chữa đúng các lỗi đã đo +| Lỗi đo được | Cơ chế mới | +|---|---| +| Ảnh sạch không gom về root | Gốc là Δ = 0 theo định nghĩa; c tự do nên không phải sụp nội dung | +| unknown_residual = cảnh | Phần dư sống trong Δ-space đã triệt tiêu nội dung nhờ cặp | +| Rain–snow rối | Cùng họ additive (được phép gần), tách bằng U^spec có margin; t-SNE kỳ vọng hai nhánh trong một sector | +| Anchor không học | Không còn anchor điểm; node là không gian con có giám sát năng lượng chiếu | +| Restorer bỏ qua routing/severity | Token = hàm của (r_k, a_k); global = Δ thuần suy giảm → phép thử "vặn a_k[0]" trực tiếp đo tính điều khiển | +| Hỗn hợp chưa kiểm | Cạnh ε học và kiểm trên tổ hợp giữ lại | + +#### Đánh giá Phase-1 mới (thay bộ metrics cũ) +1. Origin test: ‖Δ‖ sạch vs hỏng (AUROC, null rate). +2. Content-leak test bằng cặp: cos(Δ) cùng nội dung–khác suy giảm phải thấp; khác nội dung–cùng suy giảm phải cao (đo trực tiếp, không cần t-SNE). +3. Routing/purity theo node; severity ρ với **tham số thật** của tổng hợp. +4. Compositionality: R² dự đoán Δ của hỗn hợp từ thành phần trên tổ hợp giữ lại. +5. Open-set: AUROC theo loại + tỉ lệ gán đúng họ cho loại chưa thấy. +6. (Nếu có proxy) PSNR G(c,0) vs J↓: bằng chứng nhân quả. +7. Phase-2: đổi Phase-1 giữ recipe (§13.35); vặn/hoán đổi a_k → đầu ra đổi đơn điệu. + +#### Rủi ro +- Cặp LOL lệch nhẹ → nội dung không ép cứng. - Trực giao quá cứng phá các loại đồng xảy ra → mềm + cạnh tương tác. - Restorer vẫn có thể bỏ qua trạng thái → proxy decoder và phép thử vặn a_k là cách biết sớm. - Tổng hợp hỗn hợp phải giữ phân phối gần thật (dùng lớp mưa/residual thật thay vì mô phỏng thuần). + +#### Kế hoạch tối thiểu (2–3 ngày MI325X, chỉ Phase-1) +Hai head (c, Δ) trên backbone hiện có; bank K=4 + 2 free, m=8, họ 4; loss 1–4 + hợp thành trên hỗn hợp tổng hợp; chưa dùng proxy. Đo test 1–5. Đạt thì cắm vào Phase-2 qua hạ tầng đổi Phase-1; chưa đạt thì thêm proxy decoder trước khi động vào Phase-2. diff --git a/dataset/phase1_noise_20260906/trial_code_staging/docs/proposal_dose_guided_finetune_2026-09-02.md b/dataset/phase1_noise_20260906/trial_code_staging/docs/proposal_dose_guided_finetune_2026-09-02.md new file mode 100644 index 0000000000000000000000000000000000000000..73e58b38d3e033c8a1527df0c8a7a867131f9fb1 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/docs/proposal_dose_guided_finetune_2026-09-02.md @@ -0,0 +1,159 @@ +# Đề xuất fine-tune: Dose-Guided Fine-Tuning (DGF) cho SCDC v7 + +*2026-09-02 — dựa trên probe §13.18 (head8k, 27,43/0,846).* + +## 1. Bài toán, phát biểu hình thức + +Trunk học f_θ(u_t, u_y, c) ≈ E[u₀ | u_t, u_y, c] với c = Φ(y) là biểu diễn graph của Phase-1. +Phân phối huấn luyện chỉ chứa y bị suy hoá trong dải đã thấy. Với input cần hiệu chỉnh +**nhỏ hơn liều trung bình của lớp** (ảnh sạch, ảnh nhẹ, ảnh có GT tối hơn kỳ vọng của lớp), +kỳ vọng có điều kiện bị kéo về hiệu chỉnh trung bình → *over-restoration*. + +Bằng chứng đo được (probe, inference-time ablation trên full val): + +| Quan sát | Số đo | +|---|---| +| Tắt `context` → lowlight | **+1,95 dB** (20,73 > gen-2 20,3) | +| Tắt `global_vector` → lowlight | +0,55 dB | +| scene008 (input 39,0 dB) → output | 27,1 dB (−11,9) | +| MoE gate / κ per-type / routing / severity | ≈ 0 đóng góp (gate-uniform −0,085) | +| Rút toàn bộ Phase-1 | −7,79 (19,64 ≈ degraded 18,91) | + +Kết luận cấu trúc: c là **cú đẩy phân loại** vào attention/adaLN; hệ không có bậc tự do +"cường độ". Các tín hiệu được thiết kế cho việc đó (severity, κ per-type, strengths) +không được trunk dùng. + +## 2. Liên hệ nghiên cứu + +- **Điều khiển cường độ phục hồi (CNN)**: Deep Network Interpolation (Wang et al., CVPR 2019), + AdaFM (He et al., CVPR 2019), CFSNet — một knob liên tục cho strength. DGF là phiên bản + cho diffusion có điều kiện. +- **Classifier-free guidance** (Ho & Salimans, 2022): ε̂ = ε(∅) + w·(ε(c) − ε(∅)). Sinh ảnh dùng + w > 1 (bám điều kiện ↔ đa dạng). Phục hồi cần fidelity với input → khai thác miền **w ≤ 1** + ("under-guidance"), ít được nghiên cứu. Guidance interval (Kynkäänniemi et al., 2024), + Autoguidance (Karras et al., 2024), CFG-rescale, và các phương pháp CFG động theo feedback + (arXiv 2509.16131) đều hội tụ về một điểm: **w là knob theo mẫu và theo bước, không phải hằng**. +- **Restoration diffusion có knob**: StableSR (CFW blend feature), DiffBIR/SUPIR (CFG với negative + prompt); DA-CLIP: condition embedding, không có liều. +- **Identity / over-processing trong all-in-one**: báo cáo LoViF 2026 (arXiv 2604.19445) ghi nhận + practice thay input bằng GT với p = 0,15 + identity loss; các work 2025 thêm "degradation + intensity head" để chỉnh strength theo mức độ suy hoá. Thành phần identity của DGF là practice + đã được cộng đồng hội tụ. +- **LoRA cho AIO diffusion**: Degradation-Aware LoRA (arXiv 2508.03373) — phương án B của DGF. + +## 3. Phương pháp + +### 3.1 Học nhánh null (conditioning dropout) +Trong fine-tune, với xác suất **p = 0,15** thay c bằng ∅: **token null học được** cho `context` +(8 token) và vector null cho `global_vector`, khởi tạo 0 (trùng ablation đã đo). Giữ nguyên +u_y — nhánh null vẫn thấy ảnh vào, chỉ mất chẩn đoán của Phase-1. Một mạng, hai hành vi. +Mất mát composite hiện hành không đổi. + +### 3.2 Neo identity +Với xác suất **q = 0,10** dùng cặp sạch–sạch (x, x): buộc f(x) = x cho cả nhánh c (Phase-1 nhìn +ảnh sạch) lẫn nhánh ∅. Đây là nơi Phase-1 học "sạch" nghĩa là gì trong không gian điều kiện. + +### 3.3 Inference: liều theo mẫu +x̂₀^(w) = x̂₀(∅) + w · (x̂₀(c) − x̂₀(∅)), trên không gian dự đoán x₀ (ResShift dự đoán x₀). +Áp ở **bước coarse t = 2** (quyết định toàn cục: exposure, màu, độ mù); bước fine t = 1 chạy +full-c (chi tiết) — biến thể "guidance interval". Đối chứng: áp cả hai bước. + +Chọn w — ba mức, tăng dần: +1. **Hằng theo domain**, sweep trên val (baseline minh bạch). +2. **w = g(s)**, s = severity/độ tin cậy của Phase-1, g đơn điệu calibrate trên nửa val + (isotonic). Ảnh sạch → s ≈ 0 → w ≈ 0 → identity (đóng scene008); lowlight → w nhỏ; + noise/haze nặng → w ≈ 1. Đây là nơi severity coords có việc thật. +3. Head nhỏ dự đoán w từ c (tuỳ chọn, rủi ro overfit). + +Chi phí: thêm 1 forward ở bước coarse → 3 forward thay vì 2 (+50 %). Distill sau nếu cần. + +### 3.4 Cái gì được fine-tune +- **A (đề xuất chính)**: full trunk + head, warm-restart từ head8k, LR 3e-5 cosine 8k, EMA, + DDP — công thức đã chứng minh zero-drift. Thêm: token null (context 8×256, global 1×d). +- **B (nếu A làm tụt nhánh c > 0,1 dB)**: LoRA rank 8–16 chỉ trên hai đường sống + (k/v projection của cross-attention, `global_embedding`, Linear modulation của LeWin) + + token null; đóng băng phần còn lại. Probe cho biết chính xác nơi conditioning đi vào, + nên LoRA đặt trúng chỗ và bảo toàn nghiệm head8k. + +## 4. Dự đoán định lượng (kiểm chứng được) + +| Đại lượng | Dự đoán | +|---|---| +| Lowlight, w ∈ [0, 0,3] tại coarse | ≥ +1,5 dB (cận trên đã đo +1,95 với nhánh null *chưa* train); mục tiêu ≥ 20,3 | +| Noise/haze/rain tại w = 1 | giữ ≥ 27,3 macro (dự phòng −0,1 do dropout) | +| scene008 | PSNR_out ≥ PSNR_in − 1 dB (hiện −11,9); LPIPS < 0,1 | +| Macro nội bộ | ≥ 27,8 nếu lowlight đạt 20,3 → vượt gen-2 (27,55) cả nội bộ | + +## 5. Protocol đánh giá + +1. Một run fine-tune 8k DDP (≈ 2 h). +2. Sweep w ∈ {0, 0,25, 0,5, 0,75, 1, 1,25, 1,5} × {coarse-only, both} trên val theo domain → bảng 2 chiều. +3. Calibrate g(s) trên nửa val, kiểm trên nửa còn lại (không chọn w trên tập báo cáo). +4. External 3 bộ locked + **identity test**: PSNR(f(x), x) trên ảnh sạch. +5. Seed 43 lặp fine-tune để có độ lệch chuẩn. + +Tiêu chí thành công: lowlight ≥ 20,3 · macro ≥ 27,6 · scene008 ≥ 35 · external rain/haze không giảm > 0,1. + +## 6. Rủi ro và đối sách + +- Dropout làm yếu nhánh c → p nhỏ, theo dõi eval w = 1 mỗi 1k; fallback LoRA (B). +- Ngoại suy w > 1 trong x₀-space gây artifact → clamp [0, 1] mặc định; nếu thử w > 1 dùng rescale. +- Nhánh null học "phục hồi trung bình" thay vì identity → chính vì thế cần q > 0. +- g(s) phụ thuộc calibration severity Phase-1 (ρ = 0,58) → bắt đầu bằng per-domain, g(s) là nâng cấp. +- DDP: dropout bằng cách *thay token* (không bỏ nhánh) → graph không đổi → an toàn với find_unused. + +## 7. Đóng góp + +1. Định lượng lần đầu hiện tượng **conditioning over-drive** trong AIO diffusion (probe) và + chuyển guidance scale từ knob sinh ảnh (w > 1) thành **knob liều phục hồi** (w ≤ 1). +2. Đóng vòng representation → dose: severity của graph điều khiển w — tinh thần "expert chọn + trên graph" đặt ở nơi nó thực sự có tác dụng. +3. Một mạng, không refiner, không mạng phụ; chi phí +1 forward. + +## Nguồn + +- Ho & Salimans, *Classifier-Free Diffusion Guidance*, 2022. +- Kynkäänniemi et al., *Applying Guidance in a Limited Interval*, 2024. · Karras et al., *Autoguidance*, 2024. +- Dynamic CFG via online feedback: https://arxiv.org/pdf/2509.16131 · Revisiting CFG methods: https://arxiv.org/html/2608.16786 +- LoViF 2026 AIO challenge report (identity replacement p = 0,15): https://arxiv.org/pdf/2604.19445 +- Degradation-Aware LoRA for AIO diffusion: https://arxiv.org/pdf/2508.03373 +- Uncertainty-aware diffusion bridge AIO: https://arxiv.org/pdf/2601.21592 · GenDeg: https://arxiv.org/abs/2411.17687 +- AIO survey (TPAMI 2025): https://github.com/Harbinzzy/All-in-One-Image-Restoration-Survey +- Wang et al., *Deep Network Interpolation*, CVPR 2019 · He et al., *AdaFM*, CVPR 2019. + +## 3.5 Decoder coarse-to-fine: Laplacian residual heads + liều theo thang (bổ sung 2026-09-02) + +Hiện đường up của UNet đưa ra state 12-kênh một lần ở 128 px (half-res), rồi tail sửa ở 256 px. +Coarse-to-fine đúng nghĩa: mỗi tầng decoder **cam kết một ước lượng ở thang của nó**, tầng +sau chỉ thêm dải tần cao hơn. + +**Tháp Laplacian với anchor u_y (giữ identity chính xác).** Gọi D_s là downsample về thang s +(16/32/64/128 px trong không gian state), U là upsample ×2 cố định. Định nghĩa dải tần của anchor +L_s(u_y) = D_s(u_y) − U(D_{s/2}(u_y)) (L_16 = D_16(u_y)). Mỗi tầng decoder có head zero-init +δ_s (12 kênh); ước lượng đệ quy: + + u_16 = L_16(u_y) + δ_16 + u_s = U(u_{s/2}) + L_s(u_y) + δ_s s = 32, 64, 128 + x̂ = shuffle(u_128) + tail(...) tầng 256 px = dải cuối + +Vì tổng telescoping của các L_s tái tạo đúng u_y, khi mọi δ = 0 thì u_128 = u_y — **warm-start +từ head8k giữ bitwise** (head hiện có trở thành δ_128, các head mới zero-init). + +**Deep supervision.** Bước coarse: MSE(u_s, D_s(u_0)) với trọng số λ = 0,1 / 0,2 / 0,3 cho 16 / 32 / 64 px, +cộng mất mát 128 px hiện hành. Bước fine: composite full-res không đổi (L1 + VGG + chroma + luma +trên ảnh sau tail). Mỗi tầng học đúng dải tần của mình: tone/exposure/màu ở 16–32 px (nơi FiLM và +LL-global sống), cạnh và texture ở 64–128 px, noise residual ở 256 px. + +**Liều theo thang (guidance interval trên không gian thang).** Kết hợp với §3.3: nội suy nhánh +∅/c **theo từng dải**, δ_s^(w) = δ_s(∅) + w_s·(δ_s(c) − δ_s(∅)), với lịch w_16 = w (liều toàn cục), +w_s tăng dần về 1 ở 128/256 px. Ý nghĩa: chẩn đoán của Phase-1 quyết định *bao nhiêu* ở thang +thô (exposure, màu, độ mù), còn chi tiết luôn được điều kiện đầy đủ. Phiên bản đầu dùng một w +chung cho bước coarse; lịch theo thang là ablation. + +**Chi phí / rủi ro.** Ba head 1×1 (vài nghìn tham số), dải Laplacian tính từ u_y (rẻ), ba mất mát +phụ ở thang thấp (rẻ). Rủi ro chính: deep supervision ở thang thô có thể làm mờ nếu λ quá lớn — +giữ λ nhỏ và chỉ MSE (không perceptual) ở thang thô. + +**Một run duy nhất.** DGF (§3.1–3.3) + tháp coarse-to-fine (§3.5) đều zero-init/identity tại +khởi tạo → eval@0 trùng head8k; các thành phần trực giao nên có thể ablate bằng cách tắt từng +phần ở inference. diff --git a/dataset/phase1_noise_20260906/trial_code_staging/docs/staged_training_plan.md b/dataset/phase1_noise_20260906/trial_code_staging/docs/staged_training_plan.md new file mode 100644 index 0000000000000000000000000000000000000000..167c0f28e9c823d0385f096b7e8ad531a269ef6e --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/docs/staged_training_plan.md @@ -0,0 +1,262 @@ +# Staged Training Plan for Relation-Aware DC-AE + +## Overview + +This document describes the staged training strategy for the Relation-Aware DC-AE encoder, following the plan in `relation_aware_dcae_suggested_changes.md`. + +## Current Status + +### Implemented +- `src/models/relation_aware_encoder.py` - Full relation-aware encoder architecture +- `tests/test_relation_aware_encoder.py` - 28 passing tests + +### Key Components +1. **Dual Relation Transformer Block** - Spatial + Channel attention with adaptive gate +2. **Multi-Scale Feature Extraction** - F32, F16, F8, F4 memory +3. **DegradationQueryAttention** - 4 learnable degradation queries +4. **LatentQueryAttention** - 16 latent queries for reconstruction +5. **OrthogonalityRegularization** - Node diversity regularization + +--- + +## Staged Training Strategy + +### Stage A: Structural Replacement + +**Goal**: Replace late DC-AE stages with relation blocks, keep everything else frozen. + +``` +Frozen: +- Early DC-AE encoder layers +- DC-AE decoder + +Trainable: +- Dual Relation Blocks (32×32, 16×16, 8×8, 4×4) +- Multi-scale projection +- Latent query head +- Degradation query head +``` + +**Training objective**: +``` +L = λ_rec * L_reconstruction + λ_latent * L_latent_preservation +``` + +Where: +- `L_reconstruction`: L1 loss between decoded image and original +- `L_latent_preservation`: L1 loss between new latent and DC-AE latent + +**Duration**: 20-30 epochs +**Expected outcome**: Relation blocks learn to preserve reconstruction while introducing relational modeling. + +--- + +### Stage B: Multi-Scale Relation Modeling + +**Goal**: Enable degradation query attention to access multi-scale memory. + +``` +Frozen: +- Early DC-AE encoder +- DC-AE decoder +- Relation blocks from Stage A + +Trainable: +- Degradation query attention +- Node projection MLP +``` + +**Training objective**: +``` +L = λ_deg * L_degradation + λ_node * L_node_diversity +``` + +Where: +- `L_degradation`: Clean-degraded displacement loss +- `L_node_diversity`: Orthogonality regularization on nodes + +**Duration**: 20-30 epochs +**Expected outcome**: Nodes learn to capture different degradation axes. + +--- + +### Stage C: End-to-End Fine-tuning + +**Goal**: Fine-tune the complete encoder with all objectives. + +``` +Trainable: +- Everything (relation blocks, queries, projections) +- Optional: decoder + +Frozen: +- DC-AE teacher (for latent preservation) +``` + +**Training objective**: +``` +L = λ_rec * L_reconstruction + + λ_latent * L_latent_preservation + + λ_deg * L_degradation + + λ_node * L_node_diversity + + λ_clean * L_clean_anchor +``` + +**Duration**: 10-20 epochs +**Expected outcome**: All components jointly optimized for degradation representation. + +--- + +## Integration with Stage B v2 + +### Current Pipeline (Stage B v2) + +``` +Image [B, 3, 256, 256] + ↓ +DC-AE Encoder (frozen) + ↓ +Latent [B, 128, 4, 4] + ↓ +dcae_descriptor() + ↓ +Descriptor [B, 512] + ↓ +DescriptorNodeProjector + ↓ +4 × Node [B, 4, 16] + ↓ +OrderedGraphComposer + ↓ +Composed displacement [B, 64] +``` + +### Proposed Pipeline (with Relation-Aware Encoder) + +``` +Image [B, 3, 256, 256] + ↓ +Relation-Aware DC-AE Encoder + ├── Early DC-AE (frozen) + ├── Dual Relation Blocks (trainable) + └── Multi-Scale Memory + ↓ + ┌───────┴───────┐ + ↓ ↓ +Latent Queries Degradation Queries + ↓ ↓ +[B, 128, 4, 4] [B, 4, 256] + ↓ ↓ +DC-AE Decoder NodeQueryProjector + ↓ + [B, 4, 16] + ↓ + OrderedGraphComposer + ↓ + Composed displacement [B, 64] +``` + +--- + +## New Training Losses + +### For Relation-Aware Encoder + +```python +# Degradation displacement loss +def degradation_displacement_loss(nodes_degraded, nodes_clean): + """Clean images should have nodes near origin.""" + return nodes_clean.norm(dim=-1).mean() + +# Node orthogonality loss +def node_orthogonality_loss(nodes): + """Nodes should represent different degradation axes.""" + nodes_norm = F.normalize(nodes, dim=-1) + similarity = torch.bmm(nodes_norm, nodes_norm.transpose(1, 2)) + mask = 1 - torch.eye(nodes.shape[1], device=nodes.device).unsqueeze(0) + return (similarity * mask).abs().sum() / mask.sum() + +# Latent preservation loss +def latent_preservation_loss(latent_new, latent_dcae): + """New latent should match DC-AE latent structure.""" + return F.l1_loss(latent_new, latent_dcae.detach()) +``` + +--- + +## Ablation Variants + +Following the plan in `relation_aware_dcae_suggested_changes.md`: + +| Variant | Description | +|---------|-------------| +| A0 | Original DC-AE + handcrafted descriptor (baseline) | +| A1 | Original DC-AE + Transformer descriptor | +| A2 | Original DC-AE + Node Query Attention | +| A3 | Replace late EfficientViT blocks with Dual Relation blocks | +| A4 | A3 + multi-scale relation memory | +| A5 | A4 + latent query aggregation | +| A6 | A5 + degradation query head | +| A7 | A6 + relation block at 64×64 | +| A8 | A7 + learnable PixelUnshuffle residual projection | +| A9 | A8 + optional frequency memory | + +**Recommended first implementation**: A6 (full relation-aware with late blocks only) + +--- + +## Next Steps + +1. **Hook DC-AE encoder** to extract multi-scale features (F32, F16, F8, F4) +2. **Create training script** for Stage A (reconstruction + latent preservation) +3. **Integrate with stage_b_v2** by replacing `dcae_descriptor()` + `DescriptorNodeProjector` +4. **Run ablation A0-A6** to isolate improvements + +--- + +## Memory Requirements + +With the relation-aware encoder: + +| Component | Memory Estimate (FP32) | +|-----------|----------------------| +| Dual Relation Blocks (4 stages) | ~200M params | +| Query Attention | ~50M params | +| Projections | ~10M params | +| **Total trainable** | ~260M params | + +For comparison: +- DC-AE encoder: ~700M params (frozen) +- Stage B model: ~5M params (trainable) + +**Total with relation-aware**: ~265M trainable params + +--- + +## Expected Impact on JPEG E3 + +The main motivation for this change is improving JPEG E3 ρ (currently 0.62-0.70). + +**Why it should help**: + +1. **Multi-scale features**: JPEG artifacts (8×8 blocking) are most visible at 8×8, 16×16 resolutions +2. **Spatial attention**: Can learn to detect periodic blocking patterns +3. **Channel attention**: Can capture frequency-like combinations +4. **Query-based aggregation**: Can focus on artifact-relevant regions + +**Expected improvement**: JPEG E3 ρ ≥ 0.80 (matching blur/noise/lowlight) + +--- + +## Compatibility Notes + +### DC-AE Decoder Compatibility +- Latent output must remain `[B, 128, 4, 4]` +- Use `LatentQueryAttention` to maintain compatibility +- Reconstruction quality should be preserved + +### Stage B v2 Compatibility +- Node output shape: `[B, 4, 16]` (unchanged) +- Graph composer: unchanged +- All other losses: unchanged +- Selection policy: unchanged diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/expand_phase1_noise.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/expand_phase1_noise.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1b7b663b14250778bd026fbabeff96f10793e5ad Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/expand_phase1_noise.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/fetch_phase1_extra.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/fetch_phase1_extra.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6368a1ef1530cbeed5d91313ec1353e5d4a0e2c3 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/fetch_phase1_extra.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/prepare_phase1_seven.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/prepare_phase1_seven.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5256eecbae32a8302c11de29f1b5dbdedde0e229 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/prepare_phase1_seven.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/report_phase1_seven.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/report_phase1_seven.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b7c6f4947d7996fa01cffcc7cdff18f2e5239c1a Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/report_phase1_seven.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/run_phase1_seven_suite.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/run_phase1_seven_suite.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a69450772eceaf1aa12e4a1a2763c98340f26ddf Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/scripts/__pycache__/run_phase1_seven_suite.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/benchmark_phase1_gpu.py b/dataset/phase1_noise_20260906/trial_code_staging/scripts/benchmark_phase1_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..d7bfd9249cd7e01e2da0123259a0f383e02b4537 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/scripts/benchmark_phase1_gpu.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python3 +"""Finite native-resolution training smoke with explicit ROCm device evidence.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import sys +import time + +import torch + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from src.models.graph_encoder.clean_relative import CleanRelativeGraphEncoder # noqa: E402 +from train_phase1_clean_relative import (LossWeights, atomic_json_save, controlled_batch, # noqa: E402 + pair_objective, synthetic_objective, safe_optimizer_step) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--batch-size", default=16, type=int) + parser.add_argument("--synthetic-batch-size", default=4, type=int) + parser.add_argument("--patch-size", default=256, type=int) + parser.add_argument("--steps", default=5, type=int) + parser.add_argument("--expected-pci-bus", default=171, type=int) + args = parser.parse_args() + if min(args.batch_size, args.synthetic_batch_size, args.patch_size, args.steps) <= 0: + parser.error("Dimensions and steps must be positive") + torch.set_num_threads(4) + if torch.cuda.device_count() != 1: + raise RuntimeError("Expose exactly one intended device before benchmarking") + properties = torch.cuda.get_device_properties(0) + if properties.pci_bus_id != args.expected_pci_bus: + raise RuntimeError(f"Wrong GPU PCI bus: {properties.pci_bus_id}") + device = torch.device("cuda:0") + torch.manual_seed(42) + model = CleanRelativeGraphEncoder().to(device).train() + optimizer = torch.optim.AdamW(model.parameters(), lr=2e-4) + clean_cpu = torch.rand(args.batch_size, 3, args.patch_size, args.patch_size) + clean = clean_cpu.to(device) + degraded = (clean + torch.randn_like(clean) * .04).clamp(0, 1) + presence = clean.new_zeros(args.batch_size, 7) + presence[:, 1] = 1 + weights = LossWeights() + timings, losses = [], [] + for step in range(args.steps): + torch.cuda.synchronize() + started = time.monotonic() + optimizer.zero_grad(set_to_none=True) + pair = model.forward_pair(degraded, clean) + loss, _ = pair_objective(model, pair, clean, degraded, presence, + clean.new_ones(args.batch_size), weights) + data = controlled_batch(clean_cpu, step, 42, args.synthetic_batch_size) + data = {key: value.to(device) if isinstance(value, torch.Tensor) else value for key, value in data.items()} + auxiliary, _ = synthetic_objective(model, data, weights, True) + loss = loss + auxiliary + if not bool(torch.isfinite(loss)): + raise FloatingPointError("Nonfinite smoke loss") + loss.backward() + accepted, norm = safe_optimizer_step(model, optimizer, 1.) + if not accepted: + raise FloatingPointError("Nonfinite smoke gradient") + torch.cuda.synchronize() + timings.append(time.monotonic() - started) + losses.append(float(loss.detach())) + print(json.dumps({"step": step, "seconds": timings[-1], "loss": losses[-1], "gradient_norm": norm}), flush=True) + report = {"status": "passed", "scope": "synthetic_software_smoke_not_dataset_training", + "device": str(properties), "pci_bus": properties.pci_bus_id, + "torch": torch.__version__, "hip": torch.version.hip, + "batch_size": args.batch_size, "patch_size": args.patch_size, + "synthetic_batch_size": args.synthetic_batch_size, "step_seconds": timings, + "steady_seconds_per_step": sum(timings[1:]) / max(1, len(timings) - 1), + "losses": losses, "peak_allocated_bytes": torch.cuda.max_memory_allocated(), + "peak_reserved_bytes": torch.cuda.max_memory_reserved(), + "free_total_bytes_after": torch.cuda.mem_get_info()} + atomic_json_save(report, args.output) + print(json.dumps(report), flush=True) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/expand_phase1_noise.py b/dataset/phase1_noise_20260906/trial_code_staging/scripts/expand_phase1_noise.py new file mode 100644 index 0000000000000000000000000000000000000000..bff722116f6037a93862ef3d3afd779c5cc2c090 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/scripts/expand_phase1_noise.py @@ -0,0 +1,375 @@ +#!/usr/bin/env python3 +"""Create manifest v2 by appending noise data to an unchanged frozen v1 parent. + +No base record is removed, moved, or rewritten. Synthetic records reuse clean +files, not stored noisy images. New real pairs may be quarantined for duplicate +pixels or split conflicts. Invalid images fail unless explicitly quarantined. +The schema bump makes frozen v1 loaders fail before misreading online noise as +identity pairs. Base files and all existing records/splits remain unchanged. +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +from copy import deepcopy +import hashlib +import json +import os +from pathlib import Path +import re +import sys +import tempfile + +from PIL import Image + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(PROJECT_ROOT)) + +from scripts.prepare_phase1_seven import _decode_cached, record # noqa: E402 +from src.data.clean_relative import ( # noqa: E402 + NOISE_PROFILES, _seed_from, image_files, validate_manifest, +) + +SPLITS = ("train", "val", "test") +STRENGTHS = (.2, .4, .6) +POLYU_REVISION = "3af0f2646b267a00446fe4b7113a15e67bc80b4e" + + +def _empty(): + return {split: [] for split in SPLITS} + + +def _decode_fresh_metadata(path): + """Reuse the parent RGB hash format but bypass its stat-keyed LRU cache. + + File size and mtime can remain identical after a rewrite (including on + coarse-timestamp filesystems). Expansion is an integrity boundary, so a + cached decode cannot attest that source pixels still match the manifest. + The pinned parent helper's undecorated function performs a full fresh load. + """ + metadata = Path(path).stat() + return _decode_cached.__wrapped__(path, metadata.st_size, metadata.st_mtime_ns) + + +def discover_sidd_medium(root: Path, base_scene_splits: dict[str, str], + expected_pairs: int = 320) -> dict[str, list[dict]]: + """Match each capture suffix, not merely the first file of each instance.""" + grouped = defaultdict(dict) + for path in image_files(root): + match = re.fullmatch(r"(?:(\d{4})_)?(NOISY|GT)_SRGB_(\d+)", path.stem, re.IGNORECASE) + scene = re.fullmatch(r"(\d{4})_(\d{3})_.+", path.parent.name) + if not match or not scene or (match[1] and match[1] != scene[1]): + raise ValueError(f"Unrecognized SIDD Medium image/instance: {path}") + key = (path.parent, match[3]) + role = match[2].upper() + if role in grouped[key]: + raise ValueError(f"Duplicate SIDD role/capture: {path}") + grouped[key][role] = path + result = _empty() + for (folder, capture), roles in sorted(grouped.items()): + if set(roles) != {"NOISY", "GT"}: + raise ValueError(f"SIDD unmatched NOISY/GT capture {folder}/{capture}") + group = folder.name.split("_")[1] + if not 1 <= int(group) <= 10: + raise ValueError(f"Unexpected SIDD physical scene: {group}") + prescribed = "val" if group == "006" else "test" if group == "008" else "train" + split = base_scene_splits.get(group, prescribed) + if split != prescribed: + raise ValueError(f"Base SIDD scene {group} disagrees with protected 006-val/008-test policy") + result[split].append(record( + roles["NOISY"], roles["GT"], "noise", "SIDD", group, "SIDD_Medium_sRGB", + noise_source="SIDD_Medium_sRGB", capture_id=capture, scene_instance=folder.name, + license="MIT", source_url="https://abdokamel.github.io/sidd/", + )) + count = sum(map(len, result.values())) + if count != expected_pairs: + raise ValueError(f"SIDD Medium expected {expected_pairs} pairs, discovered {count}") + return result + + +def discover_polyu(root: Path, expected_pairs: int = 40) -> dict[str, list[dict]]: + directories = ([root] if root.name == "OriginalImages" and root.is_dir() + else sorted(p for p in root.rglob("OriginalImages") if p.is_dir())) + if len(directories) != 1: + raise ValueError(f"Expected exactly one PolyU OriginalImages directory: {root}") + grouped = defaultdict(dict) + for path in image_files(directories[0]): + match = re.fullmatch(r"(.+)_(Real|mean)", path.stem, re.IGNORECASE) + if not match: + raise ValueError(f"Unrecognized PolyU original image: {path}") + role = match[2].lower() + if role in grouped[match[1]]: + raise ValueError(f"Duplicate PolyU role: {path}") + grouped[match[1]][role] = path + result = _empty() + for group, roles in sorted(grouped.items()): + if set(roles) != {"real", "mean"}: + raise ValueError(f"PolyU unmatched Real/mean scene: {group}") + result["test"].append(record( + roles["real"], roles["mean"], "noise", "PolyU", group, "PolyU_OriginalImages", + noise_source="PolyU_external", license="PolyU non-commercial research license", + source_revision=POLYU_REVISION, + source_url="https://github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset", + evaluation_role="external_test_only", + )) + if len(result["test"]) != expected_pairs: + raise ValueError(f"PolyU expected {expected_pairs} original pairs, discovered {len(result['test'])}") + return result + + +def _audit_new_pairs(candidates, quarantine_invalid): + kept, excluded, decoded = _empty(), [], set() + for split in SPLITS: + for item in candidates[split]: + try: + clean, noisy = _decode_fresh_metadata(item["clean"]), _decode_fresh_metadata(item["degraded"]) + decoded.update((item["clean"], item["degraded"])) + if (clean["width"], clean["height"]) != (noisy["width"], noisy["height"]): + raise ValueError("unaligned pair dimensions") + except (OSError, ValueError, Image.DecompressionBombError) as error: + if not quarantine_invalid: + raise ValueError(f"Invalid new noise pair {item['id']}: {error}") from error + excluded.append({**item, "original_split": split, "reason": "invalid_new_pair", "detail": str(error)}) + continue + kept[split].append({**item, "clean_content_sha256": clean["rgb_sha256"], + "degraded_content_sha256": noisy["rgb_sha256"], + "width": clean["width"], "height": clean["height"]}) + return kept, excluded, len(decoded) + + +def retain_new_candidates(base, candidates): + """Protect immutable base splits even against transitive new scene bridges.""" + parent = {} + + def find(key): + parent.setdefault(key, key) + while parent[key] != key: + parent[key] = parent[parent[key]] + key = parent[key] + return key + + def keys(item): + return ("content:" + item["clean_content_sha256"], + "group:" + json.dumps([item["dataset"], item["group"]])) + + for source in (base, candidates): + for split in SPLITS: + for item in source[split]: + first, second = map(find, keys(item)) + if first != second: + parent[first] = second + protected, requested = defaultdict(set), defaultdict(set) + for split in SPLITS: + for item in base[split]: + protected[find(keys(item)[0])].add(split) + for item in candidates[split]: + requested[find(keys(item)[0])].add(split) + pair_hashes = { + (r["type"], r["clean_content_sha256"], r["degraded_content_sha256"]) + for split in SPLITS for r in base[split] + if not r.get("synthesis") and r.get("degraded_content_sha256") + } + kept, excluded = _empty(), [] + for split in reversed(SPLITS): + for item in candidates[split]: + component = find(keys(item)[0]) + locked = protected[component] + reason, winner = None, None + if len(locked) > 1: + reason = "new_component_bridges_protected_base_splits" + else: + winner = (next(iter(locked)) if locked + else max(requested[component], key=SPLITS.index)) + if split != winner: + reason = "cross_split_content_or_group_overlap" + pair = (item["type"], item["clean_content_sha256"], item["degraded_content_sha256"]) + if reason is None and pair in pair_hashes: + reason = "decoded_pair_duplicate" + if reason: + excluded.append({**item, "original_split": split, "reason": reason, + "protected_split": winner, "protected_base_splits": sorted(locked)}) + else: + pair_hashes.add(pair) + kept[split].append(item) + return kept, excluded + + +def _synthetic_records(base, seed): + generated, source_paths = _empty(), set() + for split in SPLITS: + seen_paths = set() + for source in base[split]: + if source.get("synthesis") != "jpeg": + continue + if source["dataset"] not in ("DIV2K", "Flickr2K"): + raise ValueError(f"Explicit DF2K expansion received unexpected JPEG source {source['dataset']}") + if source["clean"] in seen_paths: + continue + seen_paths.add(source["clean"]) + metadata = _decode_fresh_metadata(source["clean"]) + if metadata["rgb_sha256"] != source["clean_content_sha256"]: + raise ValueError(f"Base JPEG clean file no longer matches audited pixels: {source['clean']}") + source_paths.add(source["clean"]) + for profile in NOISE_PROFILES: + for strength in STRENGTHS: + identifier = hashlib.sha256(f"noise_v1\0{source['id']}\0{profile}\0{strength}".encode()).hexdigest() + params = {"severity": strength, + "sigma": (.12 if profile == "gaussian" else .02) * strength, + "shot": 0. if profile == "gaussian" else .12 * strength, + "noise_seed": _seed_from(seed, identifier, "noise_v1")} + generated[split].append({ + "id": identifier, "clean": source["clean"], "degraded": source["clean"], + "type": "noise", "dataset": source["dataset"], "group": source["group"], + "source": source.get("source", source["id"]), "parent_record_id": source["id"], + "noise_source": "DF2K_explicit_synthetic", "synthesis": "noise", + "noise_synthesis_version": 1, "noise_profile": profile, "noise_parameters": params, + "clean_content_sha256": metadata["rgb_sha256"], + "degraded_content_sha256": metadata["rgb_sha256"], + "degraded_content_hash_role": "clean_source_before_online_synthesis", + "width": metadata["width"], "height": metadata["height"], + }) + return generated, len(source_paths) + + +def _summary(splits): + result = {} + for split in SPLITS: + rows = splits[split] + noise = [r for r in rows if r["type"] == "noise"] + real = [r for r in noise if not r.get("synthesis")] + synthetic = [r for r in noise if r.get("synthesis") == "noise"] + source_key = lambda r: r.get("noise_source", r["dataset"]) # noqa: E731 + result[split] = { + "all_records": len(rows), "records_by_type": dict(Counter(r["type"] for r in rows)), + "noise_records_by_source": dict(Counter(source_key(r) for r in noise)), + "real_noise_records": len(real), "synthetic_noise_records": len(synthetic), + "real_noise_clean_images": len({r["clean_content_sha256"] for r in real}), + "synthetic_noise_clean_images": len({r["clean_content_sha256"] for r in synthetic}), + "real_noise_scene_or_source_groups": len({(r["dataset"], r["group"]) for r in real}), + "real_noise_groups_by_source": { + source: len({(r["dataset"], r["group"]) for r in real if source_key(r) == source}) + for source in sorted({source_key(r) for r in real})}, + } + return result + + +def build_expansion(base, *, seed=20260906, sidd_medium_root=None, polyu_root=None, + expected_sidd_pairs=320, expected_polyu_pairs=40, quarantine_invalid=False, + base_receipt=None): + validate_manifest(base) + if base["schema_version"] != 1: + raise ValueError("Noise expansion requires a frozen schema_version=1 parent manifest") + if isinstance(seed, bool) or not isinstance(seed, int) or not 0 <= seed < 2 ** 31: + raise ValueError("seed must be an integer in [0,2**31)") + scene_splits = {r["group"]: split for split in SPLITS for r in base[split] if r["dataset"] == "SIDD"} + candidates = _empty() + for root, discover, kwargs in ( + (sidd_medium_root, discover_sidd_medium, {"base_scene_splits": scene_splits, "expected_pairs": expected_sidd_pairs}), + (polyu_root, discover_polyu, {"expected_pairs": expected_polyu_pairs}), + ): + if root is not None: + found = discover(Path(root), **kwargs) + for split in SPLITS: + candidates[split].extend(found[split]) + discovered = sum(map(len, candidates.values())) + audited, invalid, decoded = _audit_new_pairs(candidates, quarantine_invalid) + admitted, conflicts = retain_new_candidates(base, audited) + synthetic, source_count = _synthetic_records(base, seed) + expanded = deepcopy(base) + expanded["schema_version"] = 2 + for split in SPLITS: + expanded[split].extend(admitted[split] + synthetic[split]) + assert expanded[split][:len(base[split])] == base[split] + validate_manifest(expanded) + quarantine = invalid + conflicts + if discovered != sum(map(len, admitted.values())) + len(quarantine): + raise AssertionError("New real noise coverage accounting failed") + expanded["noise_expansion"] = { + "version": 1, "seed": seed, "base_manifest": base_receipt, + "manifest_schema_version": 2, "parent_manifest_schema_version": 1, + "base_records_preserved": True, "base_split_assignments_preserved": True, + "summary": _summary(expanded), "new_real_discovered_pairs": discovered, + "new_real_admitted_pairs": sum(map(len, admitted.values())), + "new_real_decoded_files": decoded, "synthetic_source_paths_checked": source_count, + "quarantine": quarantine, "coverage_accounting_pass": True, + "quarantine_invalid_explicit": quarantine_invalid, + "generator_source_sha256": { + relative: hashlib.sha256((PROJECT_ROOT / relative).read_bytes()).hexdigest() + for relative in ("scripts/expand_phase1_noise.py", "scripts/prepare_phase1_seven.py", + "src/data/clean_relative.py")}, + "group_semantics": { + "SIDD": "physical scene number, ignoring capture-instance and repeated shot", + "PolyU": "original camera/object filename group; not independently verified physical-scene independence", + "DIV2K/Flickr2K": "clean-image source identity, shared with parent JPEG split", + }, + "sources": {"sidd_medium_root": str(sidd_medium_root) if sidd_medium_root else None, + "sidd_expected_pairs": expected_sidd_pairs if sidd_medium_root else None, + "polyu_root": str(polyu_root) if polyu_root else None, + "polyu_expected_pairs": expected_polyu_pairs if polyu_root else None, + "polyu_revision": POLYU_REVISION if polyu_root else None}, + "synthesis": { + "profiles": list(NOISE_PROFILES), "strengths": list(STRENGTHS), + "variance_formula": "sigma**2 + shot**2 * clean_RGB; output clipped to [0,1]", + "units": "sigma: read-noise std; shot: sqrt(signal-dependent variance slope), normalized RGB", + "severity": "explicit normalized synthetic dose, NOT real noise ground truth", + "train_replay": "noise_seed = _seed_from(manifest_noise_seed, record_id, epoch, 'noise_v1')", + "evaluation_replay": "manifest noise_seed unchanged; fixed native center crop", + "parameter_coverage": "two fixed profile curves x three doses; NOT independent 2-D read/shot coverage", + }, + "limitations": [ + "Legacy audit describes the parent manifest; use noise_expansion.summary for current counts.", + "Manifest schema v2 deliberately rejects frozen v1 loaders; use the upgraded loader for online noise.", + "SIDD Medium adds captures, not new physical scenes beyond the existing ten.", + "Exact decoded RGB and scene groups only; no perceptual near-duplicate detection.", + "PolyU is external test only and subject to non-commercial research license.", + "PolyU has 40 original image pairs; cross-camera independence of physical scenes is not independently verified.", + "Legacy evaluator pools real and synthetic noise: source/profile-stratified evaluation is required before interpretation.", + ], + } + return expanded + + +def write_manifest_exclusive(output: Path, manifest: dict): + """Publish a complete JSON atomically, without an overwrite race.""" + output.parent.mkdir(parents=True, exist_ok=True) + handle, temporary = tempfile.mkstemp(prefix=output.name + ".", suffix=".tmp", dir=output.parent) + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump(manifest, stream, indent=2, allow_nan=False) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.link(temporary, output) + finally: + Path(temporary).unlink(missing_ok=True) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--base-manifest", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--sidd-medium-root", type=Path) + parser.add_argument("--polyu-root", type=Path) + parser.add_argument("--expected-sidd-pairs", type=int, default=320) + parser.add_argument("--expected-polyu-pairs", type=int, default=40) + parser.add_argument("--seed", type=int, default=20260906) + parser.add_argument("--quarantine-invalid", action="store_true") + args = parser.parse_args() + if args.output.exists(): + raise FileExistsError(args.output) + if args.expected_sidd_pairs <= 0 or args.expected_polyu_pairs <= 0: + parser.error("Expected source pair counts must be positive") + raw = args.base_manifest.read_bytes() + expanded = build_expansion( + json.loads(raw), seed=args.seed, sidd_medium_root=args.sidd_medium_root, polyu_root=args.polyu_root, + expected_sidd_pairs=args.expected_sidd_pairs, expected_polyu_pairs=args.expected_polyu_pairs, + quarantine_invalid=args.quarantine_invalid, + base_receipt={"path": str(args.base_manifest.resolve()), "sha256": hashlib.sha256(raw).hexdigest()}, + ) + write_manifest_exclusive(args.output, expanded) + print(json.dumps({"manifest": str(args.output.resolve()), **expanded["noise_expansion"]}, indent=2)) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/fetch_phase1_extra.py b/dataset/phase1_noise_20260906/trial_code_staging/scripts/fetch_phase1_extra.py new file mode 100644 index 0000000000000000000000000000000000000000..a0c70ca4f0ca2dc66e865f83e9ee1fead1970281 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/scripts/fetch_phase1_extra.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +"""Fetch explicitly selected public Phase-1 assets; never execute archive contents. + +Original benchmark/source links are recorded alongside mirrors. Archives are kept +for reproducibility. Run one asset per process to make failures independently +resumable. No credentials or model checkpoints are downloaded by this script. +""" +from __future__ import annotations + +import argparse +import hashlib +import json +from pathlib import Path, PurePosixPath +import shutil +import stat +import subprocess +import sys +import tarfile +import time +import zipfile + + +ASSETS = { + "sidd_medium_srgb": { + "url": "http://130.63.97.225/share/SIDD_Medium_Srgb.zip", + "file": "SIDD_Medium_Srgb.zip", "directory": "sidd_medium_srgb", + "archive_bytes_expected": 13_234_744_070, + "source": "https://abdokamel.github.io/sidd/", + "original": "http://130.63.97.225/share/download_benchmark.html", + "license": "MIT", "expected_pairs": 320, "physical_scenes": 10, + "transport_note": "Author HTTP mirror; no published checksum pinned. Record observed SHA256; ZIP extraction verifies member CRCs. Not cryptographic source authentication.", + }, + "polyu_original": { + "url": "https://codeload.github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset/zip/3af0f2646b267a00446fe4b7113a15e67bc80b4e", + "file": "PolyU_3af0f2646b267a00446fe4b7113a15e67bc80b4e.zip", + "directory": "polyu_original", "revision": "3af0f2646b267a00446fe4b7113a15e67bc80b4e", + "source": "https://github.com/csjunxu/PolyU-Real-World-Noisy-Images-Dataset", + "license": "Non-commercial teaching, academic research and personal experimentation; retain License.txt", + "expected_original_pairs": 40, "original_image_bytes": 131_932_359, + "use": "external_test_only_original_images", + "scope_note": "Archive also contains 100 derived crop pairs; these are not additional scenes and are not admitted.", + }, + "gopro": { + "repo": "snah/GOPRO_Large", "file": "GOPRO_Large.zip", "directory": "gopro", + "revision": "592978466ae510d2734b199cad2fc79a346bda1c", "archive_bytes_expected": 9540471600, + "sha256": "24532c036712515cf33803704421311c91f6a080e76049d7e5e7fd22389f128e", + "source": "https://github.com/Algolzw/daclip-uir#dataset-links", + "original": "https://drive.google.com/file/d/1y4wvPdOG3mojpFCHTqLgriexhbjoWVkK/view", + }, + "div2k_train": { + "url": "https://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_train_HR.zip", + "file": "DIV2K_train_HR.zip", "directory": "div2k_train", + "archive_bytes_expected": 3530603713, + "source": "https://data.vision.ee.ethz.ch/cvl/DIV2K/", + }, + "div2k_valid": { + "url": "https://data.vision.ee.ethz.ch/cvl/DIV2K/DIV2K_valid_HR.zip", + "file": "DIV2K_valid_HR.zip", "directory": "div2k_valid", + "source": "https://data.vision.ee.ethz.ch/cvl/DIV2K/", + }, + "flickr2k": { + "repo": "yangtao9009/Flickr2K", "file": "Flickr2K.zip", "directory": "flickr2k", + "revision": "790432e75172aaf1c2c350825fb7b2b821603881", "archive_bytes_expected": 11645004887, + "sha256": "6efb757849c39926258108cee2111a9d26976c6e3726a09bf179834f17ba78f8", + "source": "https://github.com/Algolzw/daclip-uir#dataset-links", + "original": "https://cv.snu.ac.kr/research/EDSR/Flickr2K.tar", + "mirror_note": "HR-only mirror also used by deepinv.datasets.Flickr2kHR", + }, + "snow_test": { + "drive_id": "15z-A3i3Z2ybdKuyxwYRA8YKxIA8_kTDm", + "file": "Snow100K-testset.tar.gz", "directory": "snow_test", + "source": "https://sites.google.com/view/yunfuliu/desnownet", + }, + "snow_l_gt": {"drive_id": "1GdEW9TpEzcViW_pjxscbitDOoHKkxlsR", "file": "snow_l_gt.zip", "directory": "snow_l_gt", "source": "https://github.com/sunshangquan/Histoformer#-datasets"}, + "snow_l_synthetic": {"drive_id": "1OdpEbYnS_MRnmozTbTyOov5mq4di8Dl4", "file": "snow_l_synthetic.zip", "directory": "snow_l_synthetic", "source": "https://github.com/sunshangquan/Histoformer#-datasets"}, + "snow_s_gt": {"drive_id": "1jxyAdI0eNLKqFH63AroFM-Rdx7WGgzBS", "file": "snow_s_gt.zip", "directory": "snow_s_gt", "source": "https://github.com/sunshangquan/Histoformer#-datasets"}, + "snow_s_synthetic": {"drive_id": "1wXXg9lymva5kVvIV_l9zdDB9_G0q0WD8", "file": "snow_s_synthetic.zip", "directory": "snow_s_synthetic", "source": "https://github.com/sunshangquan/Histoformer#-datasets"}, +} + + +def monitored_download(command: list[str], root: Path, reserve_bytes: int) -> None: + """Stop only our child downloader if shared-disk headroom is endangered.""" + process = subprocess.Popen(command) + try: + while process.poll() is None: + # One GiB guard absorbs writes between polls and termination latency. + if shutil.disk_usage(root).free < reserve_bytes + 1024**3: + raise RuntimeError("Stopping own download to preserve shared-disk reserve") + time.sleep(1) + if process.returncode: + raise subprocess.CalledProcessError(process.returncode, command) + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + +def guarded_copy(source, output, filesystem_root: Path, reserve_bytes: int) -> None: + """Also protect extraction from concurrent writers on the shared filesystem.""" + while True: + chunk = source.read(1024 * 1024) + if not chunk: + break + if shutil.disk_usage(filesystem_root).free < reserve_bytes + 1024**3: + raise RuntimeError("Stopping extraction to preserve shared-disk reserve") + output.write(chunk) + + +def digest(path: Path) -> str: + value = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): + value.update(chunk) + return value.hexdigest() + + +def atomic_json(path: Path, payload: dict) -> None: + temporary = path.with_suffix(path.suffix + ".tmp") + temporary.write_text(json.dumps(payload, indent=2) + "\n") + temporary.replace(path) + + +def safe_target(destination: Path, name: str) -> Path: + member = PurePosixPath(name) + if member.is_absolute() or ".." in member.parts or "\\" in name: + raise ValueError(f"Unsafe archive member: {name!r}") + target = destination.joinpath(*member.parts) + if not target.resolve().is_relative_to(destination.resolve()): + raise ValueError(f"Archive member escapes destination: {name!r}") + return target + + +def extract_checked(archive: Path, destination: Path, reserve_bytes: int) -> dict: + """Reject links/special files and check expanded disk budget before writing.""" + files = 0 + expanded = 0 + if zipfile.is_zipfile(archive): + with zipfile.ZipFile(archive) as handle: + members = handle.infolist() + for member in members: + safe_target(destination, member.filename) + mode = stat.S_IFMT(member.external_attr >> 16) + if mode not in (0, stat.S_IFREG, stat.S_IFDIR): + raise ValueError("Archive contains link or special file") + expanded += member.file_size + if shutil.disk_usage(destination.parent).free < expanded + reserve_bytes: + raise RuntimeError(f"Insufficient space for {expanded} expanded bytes plus reserve") + destination.mkdir(parents=True, exist_ok=True) + for member in members: + target = safe_target(destination, member.filename) + if member.is_dir(): + target.mkdir(parents=True, exist_ok=True) + else: + target.parent.mkdir(parents=True, exist_ok=True) + with handle.open(member) as source, target.open("wb") as output: + guarded_copy(source, output, destination.parent, reserve_bytes) + files += 1 + else: + with tarfile.open(archive, "r:*") as handle: + members = handle.getmembers() + for member in members: + safe_target(destination, member.name) + if not (member.isfile() or member.isdir()): + raise ValueError(f"Non-regular archive member: {member.name}") + expanded += member.size + if shutil.disk_usage(destination.parent).free < expanded + reserve_bytes: + raise RuntimeError(f"Insufficient space for {expanded} expanded bytes plus reserve") + destination.mkdir(parents=True, exist_ok=True) + for member in members: + target = safe_target(destination, member.name) + if member.isdir(): + target.mkdir(parents=True, exist_ok=True) + else: + target.parent.mkdir(parents=True, exist_ok=True) + source = handle.extractfile(member) + if source is None: + raise ValueError(f"Unreadable member {member.name}") + with source, target.open("wb") as output: + guarded_copy(source, output, destination.parent, reserve_bytes) + files += 1 + return {"extracted_files": files, "expanded_bytes": expanded} + + +def fetch(asset: str, root: Path, reserve_gib: float = 25.0, transport: str = "curl") -> dict: + specification = dict(ASSETS[asset]) + root = root.resolve() + root.mkdir(parents=True, exist_ok=True) + archive_dir = root / "archives" + archive_dir.mkdir(exist_ok=True) + destination = root / specification["directory"] + receipt_path = root / f"{asset}.receipt.json" + receipt = None + if receipt_path.is_file(): + receipt = json.loads(receipt_path.read_text()) + for key in ("asset", "file", "repo", "revision", "sha256", "drive_id", "url"): + expected = asset if key == "asset" else specification.get(key) + if expected is not None and receipt.get(key) not in (None, expected): + raise ValueError(f"Existing receipt provenance differs at {key}") + if receipt.get("complete") and destination.is_dir(): + print(json.dumps({"asset": asset, "status": "already_complete", "receipt": str(receipt_path)}), flush=True) + return receipt + reserve_bytes = int(reserve_gib * 1024**3) + if shutil.disk_usage(root).free < reserve_bytes: + raise RuntimeError("Disk already below reserved free space") + archive = archive_dir / specification["file"] + record = {"asset": asset, **specification, "started_unix": time.time(), "complete": False} + if receipt: + record["started_unix"] = receipt.get("started_unix", record["started_unix"]) + if "repo" in specification: + # Public repository revisions and LFS hashes were independently resolved + # during source audit. Retrying does not query HEAD or change provenance. + url = f"https://huggingface.co/datasets/{specification['repo']}/resolve/{specification['revision']}/{specification['file']}?download=true" + else: + url = specification.get("url") + if url: + if receipt and receipt.get("download_url") not in (None, url): + raise ValueError("Existing partial download URL does not match pinned source") + record["download_url"] = url + atomic_json(receipt_path, record) + if not archive.is_file(): + partial = archive.with_suffix(archive.suffix + ".part") + use_hf = transport == "hf" and "repo" in specification + already = partial.stat().st_size if partial.exists() and not use_hf else 0 + # Known HF/archive sizes are exact. The conservative 10-GiB fallback is + # only a preflight estimate; live reserve checks also cover unknown sizes. + remaining = max(0, specification.get("archive_bytes_expected", 10 * 1024**3) - already) + if shutil.disk_usage(root).free < remaining + reserve_bytes + 1024**3: + raise RuntimeError(f"Insufficient headroom for {remaining} remaining archive bytes") + if use_hf: + code = "from huggingface_hub import hf_hub_download; import sys; print(hf_hub_download(sys.argv[1],sys.argv[2],repo_type='dataset',revision=sys.argv[3],local_dir=sys.argv[4],token=False))" + monitored_download([sys.executable, "-c", code, specification["repo"], specification["file"], specification["revision"], str(archive_dir)], root, reserve_bytes) + elif "drive_id" in specification: + code = "import gdown,sys; result=gdown.download(id=sys.argv[1],output=sys.argv[2],quiet=False,resume=True); sys.exit(0 if result else 1)" + monitored_download([sys.executable, "-c", code, specification["drive_id"], str(partial)], root, reserve_bytes) + else: + # cURL validates TLS, propagates errors and resumes only this asset's partial file. + monitored_download(["curl", "--fail", "--location", "--retry", "4", "--retry-delay", "5", + "--connect-timeout", "30", "--speed-time", "120", "--speed-limit", "1024", + "--continue-at", "-", "--output", str(partial), str(url)], root, reserve_bytes) + if not use_hf: + partial.replace(archive) + if specification.get("archive_bytes_expected") and archive.stat().st_size != specification["archive_bytes_expected"]: + raise ValueError(f"Archive size mismatch for {archive}; retained for inspection") + actual_hash = digest(archive) + if specification.get("sha256") and actual_hash != specification["sha256"]: + raise ValueError(f"Checksum mismatch for {archive}; retained for inspection") + record.update({"sha256_observed": actual_hash, "archive_bytes": archive.stat().st_size}) + atomic_json(receipt_path, record) + # Never overwrite an unrelated existing extraction directory. + marker = destination / ".phase1_asset.json" + if destination.exists(): + if not marker.is_file() or json.loads(marker.read_text()).get("archive_sha256") != actual_hash: + raise FileExistsError(f"Existing unowned extraction directory: {destination}") + destination.mkdir(parents=True, exist_ok=True) + atomic_json(marker, {"asset": asset, "archive_sha256": actual_hash}) + record.update(extract_checked(archive, destination, reserve_bytes)) + record.update({"complete": True, "completed_unix": time.time(), "destination": str(destination)}) + atomic_json(receipt_path, record) + print(json.dumps(record), flush=True) + return record + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--asset", choices=ASSETS, required=True) + parser.add_argument("--root", type=Path, required=True) + parser.add_argument("--reserve-gib", type=float, default=25.0) + parser.add_argument("--transport", choices=("curl", "hf"), default="curl") + args = parser.parse_args() + if args.reserve_gib < 10: + parser.error("reserve-gib must be at least 10") + fetch(args.asset, args.root, args.reserve_gib, args.transport) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/prepare_phase1_seven.py b/dataset/phase1_noise_20260906/trial_code_staging/scripts/prepare_phase1_seven.py new file mode 100644 index 0000000000000000000000000000000000000000..8636fb164d764263b220434be9e2f1d209c31d91 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/scripts/prepare_phase1_seven.py @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +"""Build and audit all available seven-type pairs; never truncate datasets. + +Official tests are locked. Validation is reserved by clean/scene group from +training. Where no official test exists locally, an explicitly labelled internal +group holdout is created. Exact decoded-RGB duplicate content cannot cross splits; +near duplicates/resized copies are not claimed to be detected by exact hashing. +""" + +from __future__ import annotations + +import argparse +from collections import Counter +from concurrent.futures import ThreadPoolExecutor +from functools import lru_cache +import hashlib +import json +from pathlib import Path +import sqlite3 +import struct +import sys +import time + +from PIL import Image + +PROJECT_ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(PROJECT_ROOT)) + +from src.data.clean_relative import ( # noqa: E402 + TYPES, discover_exact_pairs, image_files, isolate_splits, validate_manifest, +) +from src.data.rain13k_resized import load_rain13k_resized # noqa: E402 + + +def record(degraded: Path, clean: Path, kind: str, dataset: str, group: str, + source: str, **extra) -> dict: + degraded, clean = degraded.resolve(), clean.resolve() + identifier = hashlib.sha256(f"{dataset}\0{source}\0{degraded}\0{clean}".encode()).hexdigest() + return {"id": identifier, "clean": str(clean), "degraded": str(degraded), + "type": kind, "dataset": dataset, "group": group, "source": source, **extra} + + +def split_training(records: list[dict], seed: int, val_fraction: float, + test_fraction: float = 0.) -> dict[str, list[dict]]: + """Partition clean-content/scene components BEFORE selecting holdouts. + + Multiple rain variants may have different GT filenames but identical pixels. + All such variants must be assigned together, not discarded after the split. + Invalid images remain for the later explicit invalid-pair audit. + """ + paths = sorted({r["clean"] for r in records if r.get("clean") and not r.get("clean_content_sha256")}) + + def clean_hash(path): + try: + return path, _decode_metadata(path)["rgb_sha256"] + except (OSError, ValueError, Image.DecompressionBombError): + return path, "unreadable:" + path + + with ThreadPoolExecutor(max_workers=4) as pool: + hashes = dict(pool.map(clean_hash, paths)) + parent = {} + + def find(key): + parent.setdefault(key, key) + while parent[key] != key: + parent[key] = parent[parent[key]] + key = parent[key] + return key + + for item in records: + group = f"group:{item.get('dataset', '')}:{item['group']}" + content = "content:" + (item.get("clean_content_sha256") or hashes.get(item.get("clean"), group)) + first, second = find(group), find(content) + if first != second: + parent[max(first, second)] = min(first, second) + components = {item["id"]: find(f"group:{item.get('dataset', '')}:{item['group']}") for item in records} + groups = sorted(set(components.values()), + key=lambda group: hashlib.sha256(f"{seed}:{group}".encode()).digest()) + if len(groups) < (3 if test_fraction > 0 else 2): + raise ValueError(f"Too few content/scene groups for safe split: {len(groups)}") + n_val = max(1, round(len(groups) * val_fraction)) + n_test = max(1, round(len(groups) * test_fraction)) if test_fraction > 0 else 0 + if n_val + n_test >= len(groups): + raise ValueError("Holdout fractions leave no training groups") + val = set(groups[:n_val]) + test = set(groups[n_val:n_val + n_test]) + result = {"train": [], "val": [], "test": []} + for item in records: + component = components[item["id"]] + split = "val" if component in val else "test" if component in test else "train" + result[split].append(item) + return result + + +def _find_named(root: Path, name: str) -> list[Path]: + return sorted({p for p in root.rglob(name) if p.is_dir()} | ({root} if root.name == name and root.is_dir() else set())) + + +def discover(args) -> tuple[dict[str, list[dict]], dict]: + splits = {"train": [], "val": [], "test": []} + audit = {"availability": {}, "policies": {}, "discovery_exclusions": []} + + def add(partitions): + for split in splits: + splits[split].extend(partitions.get(split, [])) + + # The upstream strict loader verifies the complete Kaggle target inventory + # before applying its versioned train/test contamination quarantine. + rain = load_rain13k_resized(args.rain13k_root, max_train_pairs=0, seed=args.seed, + quarantine_manifest=args.quarantine_manifest) + train = [record(i, j, "rain", "Rain13K", j.stem, "train") for i, j in rain.train_pairs] + add(split_training(train, args.seed, args.val_fraction)) + for name, pairs in rain.official_test_pairs.items(): + splits["test"].extend(record(i, j, "rain", "Rain13K", f"official:{name}:{j.stem}", name) for i, j in pairs) + audit["discovery_exclusions"].append({"dataset": "Rain13K", "reason": "versioned_train_test_quarantine", + "count": rain.quarantined_train_pair_count, + "evidence": str(Path(args.quarantine_manifest).resolve())}) + audit["policies"]["Rain13K"] = "All surviving train pairs; grouped train validation; all five official test sets locked." + + lol = args.data_root / "LOLv2" / "lolv2_hf" + train = [record(i, j, "lowlight", "LOLv2", j.stem, "Train") + for i, j in discover_exact_pairs(lol / "Train" / "Input", lol / "Train" / "GT")] + add(split_training(train, args.seed, args.val_fraction)) + splits["test"].extend(record(i, j, "lowlight", "LOLv2", f"official:{j.stem}", "Test") + for i, j in discover_exact_pairs(lol / "Test" / "Input", lol / "Test" / "GT")) + audit["policies"]["LOLv2"] = "All local Train pairs with grouped validation; official Test locked." + + reside = args.data_root / "RESIDE" + clean_lookup = {p.stem: p for p in image_files(reside / "clear")} + if len(clean_lookup) != len(image_files(reside / "clear")): + raise ValueError("RESIDE clean stems are ambiguous across subdirectories") + train = [] + used = set() + for degraded in image_files(reside / "hazy"): + source = degraded.stem.split("_")[0] + if source not in clean_lookup: + raise ValueError(f"RESIDE unmatched degraded image: {degraded}") + used.add(source) + train.append(record(degraded, clean_lookup[source], "haze", "RESIDE", source, degraded.stem)) + if not train: + raise ValueError("RESIDE has no pairs") + add(split_training(train, args.seed, args.val_fraction, args.val_fraction)) + audit["availability"]["RESIDE"] = {"all_local_pairs": len(train), "unused_clean_files": len(set(clean_lookup) - used), + "full_original_benchmark_verified": False} + audit["policies"]["RESIDE"] = "ALL local hazy pairs (no first5000 cap); source-group internal validation and test; source bundle may be a benchmark subset." + + sidd = args.data_root / "SIDD" / "SIDD_Small_sRGB_Only" / "Data" + if not sidd.is_dir(): + raise FileNotFoundError(sidd) + train = [] + for scene in sorted(p for p in sidd.iterdir() if p.is_dir()): + noisy = sorted(scene.glob("NOISY_SRGB_*")) + clean = sorted(scene.glob("GT_SRGB_*")) + parts = scene.name.split("_") + if len(noisy) != 1 or len(clean) != 1 or len(parts) < 3 or not parts[1].isdigit(): + raise ValueError(f"SIDD requires one NOISY/GT pair and identifiable scene: {scene}") + train.append(record(noisy[0], clean[0], "noise", "SIDD", parts[1], scene.name)) + # Preserve the previous audited ten-scene assignment when that source is used. + groups = sorted({r["group"] for r in train}, key=lambda g: (hashlib.sha256(g.encode()).digest(), g)) + if len(groups) == 10: + val_group, test_group = groups[8], groups[9] + add({"train": [r for r in train if r["group"] not in (val_group, test_group)], + "val": [r for r in train if r["group"] == val_group], + "test": [r for r in train if r["group"] == test_group]}) + else: + add(split_training(train, args.seed, args.val_fraction, args.val_fraction)) + audit["policies"]["SIDD"] = "All local source pairs; scene-group internal holdouts; native crops, no downsampling; not official SIDD benchmark test." + + snow_root = args.data_root / "Snow100K" + snow_train = snow_root / "train" / "all" + train = [record(i, j, "snow", "Snow100K", j.stem, "train") + for i, j in discover_exact_pairs(snow_train / "synthetic", snow_train / "gt")] + snow_tests = [] + roots = [p for p in (snow_root / "test", args.snow_test_root) if p and p.is_dir()] + seen_snow_test_pairs = set() + for root in roots: + for gt in _find_named(root, "gt"): + synthetic = gt.parent / "synthetic" + if not synthetic.is_dir(): + continue + for i, j in discover_exact_pairs(synthetic, gt): + key = (str(i.resolve()), str(j.resolve())) + if key in seen_snow_test_pairs: + continue + seen_snow_test_pairs.add(key) + snow_tests.append(record(i, j, "snow", "Snow100K", f"official:{j.stem}", str(gt.parent))) + add(split_training(train, args.seed, args.val_fraction, 0. if snow_tests else args.val_fraction)) + splits["test"].extend(snow_tests) + audit["availability"]["Snow100K"] = {"all_local_train_pairs": len(train), "official_test_pairs": len(snow_tests)} + audit["policies"]["Snow100K"] = "All native paired training files; content-group validation; official test locked when present, otherwise explicit internal test holdout." + + gopro_train, gopro_test = [], [] + for sharp in _find_named(args.gopro_root, "sharp"): + blur = sharp.parent / "blur" + if not blur.is_dir(): + raise ValueError(f"GoPro sharp directory lacks blur sibling: {sharp}") + relative = sharp.relative_to(args.gopro_root) + is_test = any(part.lower() in ("test", "testing") for part in relative.parts) + is_train = any(part.lower() in ("train", "training") for part in relative.parts) + if not is_test and not is_train: + raise ValueError(f"GoPro split cannot be established from path: {sharp}") + target = gopro_test if is_test else gopro_train + target.extend(record(i, j, "blur", "GoPro", sharp.parent.name, str(relative)) + for i, j in discover_exact_pairs(blur, sharp)) + if not gopro_train or not gopro_test: + raise ValueError("GoPro requires both complete train and official test scene/blur+sharp directories") + add(split_training(gopro_train, args.seed, args.val_fraction)) + splits["test"].extend(gopro_test) + audit["availability"]["GoPro"] = {"all_local_train_pairs": len(gopro_train), "official_test_pairs": len(gopro_test)} + audit["policies"]["GoPro"] = "All native train pairs; whole training scenes reserved for validation; official test scenes locked." + + jpeg_train, jpeg_test = [], [] + jpeg_sources = [(args.div2k_root, "DIV2K"), (args.flickr2k_root, "Flickr2K")] + if getattr(args, "div2k_valid_root", None) is not None: + jpeg_sources.append((args.div2k_valid_root, "DIV2K")) + for root, dataset in jpeg_sources: + files = image_files(root) + if not files: + raise ValueError(f"No JPEG clean source images: {root}") + for clean in files: + relative = clean.relative_to(root) + lower_parts = (root.name.lower(),) + tuple(part.lower() for part in relative.parts[:-1]) + # Do not accidentally train from super-resolution LR variants. + if any("_lr" in part or part in ("lr", "x2", "x3", "x4", "x8") for part in lower_parts): + raise ValueError(f"JPEG source contains LR variants; point root at original HR images: {clean}") + is_test = dataset == "DIV2K" and any("valid" in part or "test" in part for part in lower_parts) + item = record(clean, clean, "jpeg", dataset, clean.stem, str(relative), synthesis="jpeg") + (jpeg_test if is_test else jpeg_train).append(item) + availability = audit["availability"].setdefault(dataset, {"all_local_clean_images": 0, "source_roots": []}) + availability["all_local_clean_images"] += len(files) + availability["source_roots"].append(str(root.resolve())) + add(split_training(jpeg_train, args.seed, args.val_fraction, 0. if jpeg_test else args.val_fraction)) + splits["test"].extend(jpeg_test) + audit["policies"]["JPEG"] = "Actual on-the-fly JPEG on native DIV2K/Flickr2K HR crops; grouped train validation; DIV2K validation HR used as locked clean-image test when present (not a paired JPEG benchmark)." + return splits, audit + + +def _decode_metadata(path: str) -> dict: + metadata = Path(path).stat() + return _decode_cached(path, metadata.st_size, metadata.st_mtime_ns) + + +@lru_cache(maxsize=200_000) +def _decode_cached(path: str, size: int, mtime_ns: int) -> dict: + # Keyed by file identity metadata so a changed input cannot reuse a stale + # in-process hash after the persistent SQLite cache correctly invalidates it. + with Image.open(path) as image: + rgb = image.convert("RGB") + rgb.load() + width, height = rgb.size + digest = hashlib.sha256(b"SCDC_RGB_V1\0" + struct.pack(">II", width, height)) + digest.update(rgb.tobytes()) + return {"width": width, "height": height, "rgb_sha256": digest.hexdigest()} + + +class ImageAuditCache: + """Stat-invalidated decoded-pixel cache; SQLite updates remain in main thread.""" + + def __init__(self, path: Path): + path.parent.mkdir(parents=True, exist_ok=True) + self.db = sqlite3.connect(str(path)) + self.db.execute("CREATE TABLE IF NOT EXISTS images(path TEXT PRIMARY KEY, size INTEGER, mtime_ns INTEGER, metadata TEXT)") + + def get(self, path: str): + stat = Path(path).stat() + row = self.db.execute("SELECT size,mtime_ns,metadata FROM images WHERE path=?", (path,)).fetchone() + if row and row[0] == stat.st_size and row[1] == stat.st_mtime_ns: + return json.loads(row[2]) + return None + + def put(self, path: str, metadata: dict): + stat = Path(path).stat() + self.db.execute("INSERT OR REPLACE INTO images VALUES(?,?,?,?)", + (path, stat.st_size, stat.st_mtime_ns, json.dumps(metadata))) + + def close(self): + self.db.commit() + self.db.close() + + +def audit_files(splits, cache_path: Path, workers: int, exclude_invalid: bool): + paths = sorted({r[field] for records in splits.values() for r in records for field in ("clean", "degraded")}) + cache = ImageAuditCache(cache_path) + metadata, errors, pending = {}, {}, [] + try: + for path in paths: + try: + cached = cache.get(path) + if cached is None: + pending.append(path) + else: + metadata[path] = cached + except OSError as error: + errors[path] = str(error) + + def decode_safe(path): + try: + return path, _decode_metadata(path), None + except (OSError, ValueError, Image.DecompressionBombError) as error: + return path, None, str(error) + + with ThreadPoolExecutor(max_workers=workers) as pool: + for index, (path, data, error) in enumerate(pool.map(decode_safe, pending), 1): + if error: + errors[path] = error + else: + metadata[path] = data + cache.put(path, data) + if index % 1000 == 0: + cache.db.commit() + print(f"Decoded/hashed {index}/{len(pending)} new files; cached {len(paths) - len(pending)}", flush=True) + finally: + cache.close() + kept, excluded = {split: [] for split in splits}, [] + for split, records in splits.items(): + for item in records: + bad = [path for path in (item["clean"], item["degraded"]) if path in errors] + reason = None + if bad: + reason = {path: errors[path] for path in bad} + else: + clean, degraded = metadata[item["clean"]], metadata[item["degraded"]] + if (clean["width"], clean["height"]) != (degraded["width"], degraded["height"]): + reason = "unaligned_dimensions" + if reason: + excluded.append({**item, "original_split": split, "reason": "invalid_pair", "detail": reason}) + else: + kept[split].append({**item, "clean_content_sha256": clean["rgb_sha256"], + "degraded_content_sha256": degraded["rgb_sha256"], + "width": clean["width"], "height": clean["height"]}) + if excluded and not exclude_invalid: + raise ValueError(f"Found {len(excluded)} invalid pairs; first={excluded[0]}. Repair inputs or explicitly pass --exclude-invalid to retain an exclusion audit.") + return kept, excluded, {"unique_files": len(paths), "decoded_new_files": len(pending), "invalid_files": errors, + "hash_spec": "sha256(SCDC_RGB_V1 NUL + uint32_be(width,height) + decoded RGB bytes)", + "near_duplicate_detection": False} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--data-root", type=Path, required=True) + parser.add_argument("--rain13k-root", type=Path, required=True) + parser.add_argument("--gopro-root", type=Path, required=True) + parser.add_argument("--div2k-root", type=Path, required=True) + parser.add_argument("--div2k-valid-root", type=Path, help="Separate official validation HR root when archives are extracted separately") + parser.add_argument("--flickr2k-root", type=Path, required=True) + parser.add_argument("--snow-test-root", type=Path) + parser.add_argument("--quarantine-manifest", type=Path, default=PROJECT_ROOT / "src/data/rain13k_quarantine_v1.json") + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--hash-cache", type=Path) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--val-fraction", type=float, default=.05) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--exclude-invalid", action="store_true", help="Explicitly exclude corrupt/unaligned pairs and list every exclusion; default is fail closed.") + args = parser.parse_args() + if not 0 < args.val_fraction < .4 or args.workers < 1: + parser.error("Require 0 < val-fraction < .4 and workers >= 1") + started = time.time() + splits, audit = discover(args) + discovered = {split: dict(Counter(r["dataset"] for r in records)) for split, records in splits.items()} + discovered_count = sum(map(len, splits.values())) + print(json.dumps({"discovered_before_validation": discovered, "pairs": discovered_count}), flush=True) + cache_path = args.hash_cache or args.output.with_suffix(".image_hashes.sqlite") + splits, invalid, file_audit = audit_files(splits, cache_path, args.workers, args.exclude_invalid) + splits, leakage = isolate_splits(splits) + exclusions = invalid + leakage + retained = sum(map(len, splits.values())) + if retained + len(exclusions) != discovered_count: + raise AssertionError("Coverage accounting failed") + audit.update({"discovered_before_validation": discovered, "discovered_pairs_after_quarantine": discovered_count, + "retained_pairs": retained, "excluded_pairs_after_discovery": len(exclusions), + "coverage_accounting_pass": True, "implicit_record_cap": None, "file_validation": file_audit, + "exclusions": exclusions, "seed": args.seed, "elapsed_seconds": time.time() - started, + "test_lock": "No test samples may select checkpoints or tune hyperparameters; final test only after configuration freeze."}) + manifest = {"schema_version": 1, "types": list(TYPES), **splits, "audit": audit} + audit["counts_by_type"] = validate_manifest(manifest, require_all_types=True) + args.output.parent.mkdir(parents=True, exist_ok=True) + temporary = args.output.with_name(args.output.name + ".tmp") + temporary.write_text(json.dumps(manifest, indent=2) + "\n") + temporary.replace(args.output) + print(json.dumps({"manifest": str(args.output.resolve()), "counts": audit["counts_by_type"], + "excluded_pairs": len(exclusions), "elapsed_seconds": audit["elapsed_seconds"]}, indent=2), flush=True) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/report_phase1_seven.py b/dataset/phase1_noise_20260906/trial_code_staging/scripts/report_phase1_seven.py new file mode 100644 index 0000000000000000000000000000000000000000..81b068c13c7662b2105b7c92002b5ba6a88dea96 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/scripts/report_phase1_seven.py @@ -0,0 +1,166 @@ +#!/usr/bin/env python3 +"""Summarize measured suite artifacts; missing runs are never counted as results.""" +from __future__ import annotations + +import argparse +import json +from pathlib import Path +import statistics + + +def write_noise_report(root: Path, config: dict, state: dict) -> dict: + """Describe only validated noise trials; never infer disentanglement from F1.""" + validated = set(state.get("completed_runs", [])) + measured, rows = {}, [] + for name in config["commands"]: + if name not in validated: + rows.append(f"| {name} | chưa có kết quả được xác minh | — | — |") + continue + reference_path = root / name / "evaluation_reference_test_last.json" + expanded_path = root / name / "evaluation_expanded_test_last.json" + reference = json.loads(reference_path.read_text()) + expanded = json.loads(expanded_path.read_text()) + for report, expected_sha in ((reference, config["reference_manifest_sha256"]), + (expanded, config["manifest_sha256"])): + real = report.get("real", {}) + if (report.get("manifest_sha256") != expected_sha + or report.get("training_scope") != "full_manifest" + or real.get("scope") != "all_records" or real.get("split") != "test" + or real.get("records_total") != real.get("records_evaluated")): + raise ValueError(f"Noise trial {name} has inconsistent report provenance") + if reference.get("checkpoint_sha256") != expanded.get("checkpoint_sha256"): + raise ValueError(f"Noise trial {name} reports use different checkpoints") + strata = expanded["real"].get("noise_stratification", {}) + if strata.get("status") != "measured": + raise ValueError(f"Noise trial {name} lacks measured source strata") + real = reference["real"] + measured[name] = { + "checkpoint_sha256": reference["checkpoint_sha256"], + "reference_classification": real["classification"], "reference_clean": real["clean"], + "noise_stratification": strata, + "reference_full_report": str(reference_path), "expanded_full_report": str(expanded_path), + } + rows.append(f"| {name} | {real['records_evaluated']} | {real['classification']['macro_f1']:.4f} | " + f"{real['clean']['any_false_positive_rate_at_0_5']:.4f} |") + summary = {"suite_status": state.get("status"), "protocol": "noise-v2", + "primary_checkpoint": "last.pt", "expected_runs": list(config["commands"]), + "measured_runs": list(measured), "results": measured, + "manifest_sha256": config["manifest_sha256"], + "reference_manifest_sha256": config["reference_manifest_sha256"], + "source_digest": config["source_digest"], + "matched_steps_per_run": config.get("matched_steps_per_run"), + "interpretation": "One seed, two v2 runs matched to each other; old v1 is not a compute-matched data ablation"} + rounds = config.get("settings", {}).get("epochs", "chưa xác định") + train_records = sum(config.get("counts", {}).get("train", {}).values()) or "chưa xác định" + budget = config.get("matched_steps_per_run", "chưa xác định") + lines = ["# Phase-1 noise-v2: dữ liệu và sampling", "", + f"Trạng thái: **{state.get('status', 'unknown')}**. Chỉ tính các run đã được queue xác minh.", "", + "Hai run giữ nguyên model/objective, class weights, batch/crop và ngân sách; " + "chỉ thay phân bổ real/synthetic trong các vị trí noise. Checkpoint chính: `last.pt`.", "", + "| Run | Record trên legacy test cố định | Macro-F1 | Clean false-positive rate |", + "|---|---:|---:|---:|", *rows, "", + "## Noise thật và synthetic phải đọc riêng", "", + "`suite_summary.json/results/*/noise_stratification` chứa SIDD, PolyU và từng synthetic profile; " + "precision/F1 dùng cùng pool non-noise negatives, kèm số positive/negative và prevalence. " + "Không dùng F1 trên một nhóm chỉ có positive noise để suy ra độ chính xác ngoài miền.", "", + "## Kiểm chứng representation", "", + "Các file `evaluation_reference_test_last.json` giữ controlled probes trên cùng legacy manifest: " + "origin, severity, content leakage, within-factor parameters, zero/shuffle transfer controls, " + "composition hai thứ tự, factor removal và OOD. Đọc cả residual statistics và pixel metrics; " + "F1 không phải bằng chứng disentanglement. Expanded evaluation không chạy lại controls trên nền ảnh khác.", "", + "## Giới hạn", "", + f"- Mỗi v2 run có {rounds} vòng, {train_records} record gốc/vòng và {budget} bước khi không skip. " + "Hai v2 run ngang budget với nhau; không mặc định ngang compute với v1.", + "- Balanced sampling tăng crop visits của SIDD, không tăng số cảnh; toàn bộ record được kiểm coverage tích lũy.", + "- Chỉ một seed; không khẳng định ý nghĩa thống kê, hội tụ hoặc lợi thế kiến trúc.", + "- PolyU chỉ external test, 40 camera/object groups chưa được xác minh hoàn toàn độc lập cảnh.", + "- Synthetic gồm hai profile, chưa bao phủ read/shot độc lập hoặc protocol sigma-50 của DA-CLIP.", + "- Legacy RESIDE là local subset, Snow test S/L thiếu M; đánh giá một native crop mỗi ảnh.", + "- Origin proxy dùng clean content; OOD occlusion không phải leave-type/family-out. Chưa sửa node/cạnh hoặc Phase-2.", ""] + for filename, content in (("suite_summary.json", json.dumps(summary, indent=2) + "\n"), + ("evaluation_report.md", "\n".join(lines))): + target = root / filename + temporary = target.with_suffix(target.suffix + ".tmp") + temporary.write_text(content) + temporary.replace(target) + return summary + + +def write_report(root: Path) -> dict: + config = json.loads((root / "suite_config.json").read_text()) + state_path = root / "suite_status.json" + state = json.loads(state_path.read_text()) if state_path.exists() else {"status": "unknown"} + if config.get("settings", {}).get("protocol") == "noise-v2": + return write_noise_report(root, config, state) + validated_runs = set(state.get("completed_runs", [])) + rows, measured = [], {} + for name in config["commands"]: + path = root / name / "evaluation_test_best.json" + if not path.exists(): + rows.append(f"| {name} | chưa có kết quả | — | — |") + continue + if name not in validated_runs: + rows.append(f"| {name} | kết quả chưa được queue xác minh | — | — |") + continue + report = json.loads(path.read_text()) + real = report["real"] + if (report.get("manifest_sha256") != config["manifest_sha256"] + or report.get("training_scope") != "full_manifest" + or real.get("scope") != "all_records" or real.get("split") != "test" + or real.get("records_total") != real.get("records_evaluated")): + raise ValueError(f"Validated run {name} has inconsistent test-report provenance") + measured[name] = report + rows.append(f"| {name} | {real['records_evaluated']} | {real['classification']['macro_f1']:.4f} | {real['clean']['any_false_positive_rate_at_0_5']:.4f} |") + seed_scores = [measured[name]["real"]["classification"]["macro_f1"] + for name in ("full_seed42", "full_seed43", "full_seed44") if name in measured] + summary = {"suite_status": state.get("status"), "source_digest": config["source_digest"], + "manifest_sha256": config["manifest_sha256"], "measured_runs": list(measured), + "expected_runs": list(config["commands"]), "full_model_seeds_measured": len(seed_scores), + "macro_f1_seed_mean": statistics.mean(seed_scores) if seed_scores else None, + "macro_f1_seed_sample_std": statistics.stdev(seed_scores) if len(seed_scores) > 1 else None} + lines = ["# Phase-1: báo cáo thử nghiệm clean-relative, 7 loại suy giảm", "", + f"Trạng thái queue: **{state.get('status', 'unknown')}**. Đây là kết quả trial có ngân sách cố định, không phải bằng chứng đã hội tụ.", "", + f"Manifest SHA-256: `{config['manifest_sha256']}`.", "", + "| Run | Số cặp test đã đánh giá | Macro-F1 (7 loại) | Clean false-positive rate |", + "|---|---:|---:|---:|", *rows, "", + f"Có kết quả của {len(seed_scores)}/3 seed mô hình đầy đủ."] + if seed_scores: + lines += [f"Macro-F1 trung bình: {summary['macro_f1_seed_mean']:.4f}; " + + (f"độ lệch chuẩn mẫu: {summary['macro_f1_seed_sample_std']:.4f}." if len(seed_scores) > 1 else "chưa đủ seed để tính độ lệch chuẩn."), ""] + primary = measured.get("full_seed42") + if primary: + lines += ["## Kết quả theo loại — full_seed42", "", "| Loại | Số cặp | F1 | AP |", "|---|---:|---:|---:|"] + for kind, values in primary["real"]["classification"]["per_domain"].items(): + ap = "không xác định" if values["average_precision"] is None else f"{values['average_precision']:.4f}" + lines.append(f"| {kind} | {values['support']} | {values['f1']:.4f} | {ap} |") + lines += ["", "## Kiểm tra representation", "", + "Các báo cáo JSON từng run chứa: clean origin, severity/parameter probes, " + "content prediction trên scene tách biệt, chuyển mã blind/paired với zero/shuffle controls, " + "hợp thành hai thứ tự, loại bỏ yếu tố và OOD probe. Không suy ra kết luận disentanglement chỉ từ F1.", ""] + lines += ["## Giới hạn cần giữ khi diễn giải", "", + "- Mỗi ảnh real được đánh giá bằng một crop native cố định; không phải đánh giá restoration toàn khung ảnh.", + "- RESIDE và SIDD dùng đúng phiên bản local đã kiểm kê, không đại diện toàn bộ benchmark gốc.", + "- Snow100K test hiện là các phần S/L tải được; phần M của test gốc chưa có.", + "- Synthetic controls là xấp xỉ có tham số; real labels không tự cung cấp severity vật lý.", + "- no_composition_edges chỉ bỏ hiệu chỉnh tương tác có thứ tự; vẫn giữ attention trích bằng chứng.", + "- rank1 không phải baseline cùng số tham số; xem thêm baseline class×severity trong parameter probes.", + "- OOD mới là probe operator chưa thấy; leave-one-type/family-out cần các lần huấn luyện khác.", + "- Không có kết quả Phase-2 trong thử nghiệm này.", ""] + for filename, content in (("suite_summary.json", json.dumps(summary, indent=2) + "\n"), + ("evaluation_report.md", "\n".join(lines))): + target = root / filename + temporary = target.with_suffix(target.suffix + ".tmp") + temporary.write_text(content) + temporary.replace(target) + return summary + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--suite-root", type=Path, required=True) + args = parser.parse_args() + print(json.dumps(write_report(args.suite_root.resolve()))) + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/scripts/run_phase1_seven_suite.py b/dataset/phase1_noise_20260906/trial_code_staging/scripts/run_phase1_seven_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..7218b27abeea615dc360fb774b3330652a3fbf24 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/scripts/run_phase1_seven_suite.py @@ -0,0 +1,317 @@ +#!/usr/bin/env python3 +"""Run a fixed, sequential full-data trial/ablation suite on one physical GPU. + +Failures stop the queue; this launcher never silently changes code, data, GPU, +batch size, or training budget. Re-running requires --resume-suite and identical +configuration. It never launches Phase-2. +""" +from __future__ import annotations + +import argparse +import fcntl +import json +import math +import os +from pathlib import Path +import signal +import subprocess +import sys +import time + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +from train_phase1_clean_relative import atomic_json_save, file_digest, source_provenance # noqa: E402 +from src.data.clean_relative import validate_manifest # noqa: E402 +from scripts.report_phase1_seven import write_report # noqa: E402 + + +RUNS = (("full_seed42", 42, ()), ("no_composition_edges_seed42", 42, ("--no-edges",)), + ("rank1_seed42", 42, ("--prototype-only",)), ("full_seed43", 43, ()), + ("full_seed44", 44, ())) +NOISE_RUNS = (("noise_v2_uniform_seed42", 42, ("--noise-sampling", "uniform")), + ("noise_v2_balanced_seed42", 42, ("--noise-sampling", "balanced"))) + + +def validate_noise_parent(manifest, reference_path): + parent = json.loads(reference_path.read_text()) + receipt = manifest.get("noise_expansion", {}).get("base_manifest", {}) + if (manifest.get("schema_version") != 2 or parent.get("schema_version") != 1 + or receipt.get("sha256") != file_digest(reference_path) + or any(manifest[split][:len(parent[split])] != parent[split] for split in ("train", "val", "test"))): + raise ValueError("Noise-v2 requires the audited parent hash and unchanged base prefixes") + return parent + + +def validate_predecessor(root, reference_sha, gpu_uuid, pci_bus): + status = json.loads((root / "suite_status.json").read_text()) + config = json.loads((root / "suite_config.json").read_text()) + if (status.get("status") != "completed" or status.get("child_pid") is not None + or status.get("completed_runs") != [name for name, _, _ in RUNS] + or status.get("gpu_uuid") != gpu_uuid or status.get("expected_pci_bus") != pci_bus + or config.get("manifest_sha256") != reference_sha): + raise ValueError("Predecessor seven-type suite must finish unchanged before noise trials") + + +def suite_lock_path(args): + # Noise trials share the predecessor's existing GPU lock even when their + # output is placed on another volume. Its orphaned child inherits that lock. + parent = (args.predecessor_suite.parent if getattr(args, "protocol", "seven") == "noise-v2" + else args.output_root.parent) + return parent / f".phase1_{args.gpu_uuid}.lock" + + +def validate_noise_completion(final, records, epochs, batch_size): + expected = epochs * math.ceil(records / batch_size) + coverage = final.get("sampling_coverage", {}) + if (final.get("status") != "completed" or final.get("epoch") != epochs or final.get("cursor") != 0 + or final.get("global_step") != expected or final.get("optimizer_steps") != expected + or final.get("skipped_steps") != 0 or coverage.get("cumulative_unique_records") != records + or coverage.get("all_selected_covered") is not True): + raise ValueError("Noise trial did not satisfy its matched budget and full-record coverage contract") + + +def evaluation_stages(args, directory): + if getattr(args, "protocol", "seven") == "noise-v2": + return [{"split": split, "manifest": manifest, "controlled": controlled, + "name": f"eval_{label}_{split}", "output": directory / f"evaluation_{label}_{split}_last.json"} + for label, manifest, controlled in (("reference", args.reference_manifest, True), + ("expanded", args.manifest, False)) + for split in ("val", "test")] + return [{"split": split, "manifest": args.manifest, "controlled": True, + "name": f"eval_{split}", "output": directory / f"evaluation_{split}_best.json"} + for split in ("val", "test")] + + +def terminate_owned_group(child): + """Only the new session/process group created for our own stage is targeted.""" + try: + os.killpg(child.pid, signal.SIGTERM) + except ProcessLookupError: + return + try: + child.wait(timeout=10) + except subprocess.TimeoutExpired: + try: + os.killpg(child.pid, signal.SIGKILL) + except ProcessLookupError: + pass + child.wait() + + +def run_owned_command(command, environment, log, lock_fd, on_start): + child = subprocess.Popen(command, cwd=ROOT, env=environment, stdout=log, + stderr=subprocess.STDOUT, start_new_session=True, + pass_fds=(lock_fd,)) + try: + on_start(child) + code = child.wait() + finally: + if child.poll() is None or child.returncode: + terminate_owned_group(child) + if code: + raise subprocess.CalledProcessError(code, command) + + +def validate_evaluation(report, manifest, manifest_sha, checkpoint_sha, split, args, *, controlled=True): + real, probes = report.get("real", {}), report.get("controlled", {}) + expected = {"split": split, "patch_size": args.patch_size, "seed": 20260906, + "synthetic_scenes": args.synthetic_scenes, "max_records": None, + "skip_controlled": not controlled, "no_edges": False} + if (report.get("manifest_sha256") != manifest_sha or report.get("checkpoint_sha256") != checkpoint_sha + or report.get("training_scope") != "full_manifest" + or real.get("scope") != "all_records" or real.get("split") != split + or real.get("records_total") != len(manifest[split]) + or real.get("records_evaluated") != len(manifest[split]) + or (controlled and (probes.get("status") != "measured" or probes.get("source_split") != split + or probes.get("requested_scenes") != args.synthetic_scenes)) + or (not controlled and probes.get("status") != "explicitly_skipped") + or any(report.get("arguments", {}).get(key) != value for key, value in expected.items())): + raise ValueError("Stale, incomplete or differently configured evaluation report; cannot satisfy this suite") + + +def commands(args, name: str, seed: int, flags: tuple): + directory = args.output_root / name + train = [args.python, "-u", str(ROOT / "train_phase1_clean_relative.py"), + "--manifest", str(args.manifest), "--output-dir", str(directory), + "--epochs", str(args.epochs), "--batch-size", str(args.batch_size), + "--synthetic-batch-size", str(args.synthetic_batch_size), + "--patch-size", str(args.patch_size), "--num-workers", str(args.workers), + "--threads", "4", "--device", "cuda", "--seed", str(seed), + "--save-every", "250", "--log-every", "25", *flags] + evaluations = [] + checkpoint = "last.pt" if getattr(args, "protocol", "seven") == "noise-v2" else "best.pt" + for stage in evaluation_stages(args, directory): + evaluations.append([args.python, "-u", str(ROOT / "eval_phase1_clean_relative.py"), + "--checkpoint", str(directory / checkpoint), "--manifest", str(stage["manifest"]), + "--split", stage["split"], "--output", str(stage["output"]), + "--device", "cuda", "--batch-size", str(args.batch_size), + "--patch-size", str(args.patch_size), "--num-workers", str(args.workers), + "--threads", "4", "--seed", "20260906", "--synthetic-scenes", str(args.synthetic_scenes), + *([] if stage["controlled"] else ["--skip-controlled"])]) + return train, evaluations + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--manifest", type=Path, required=True) + parser.add_argument("--output-root", type=Path, required=True) + parser.add_argument("--python", default=sys.executable) + parser.add_argument("--epochs", type=int, default=5) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--synthetic-batch-size", type=int, default=4) + parser.add_argument("--patch-size", type=int, default=256) + parser.add_argument("--synthetic-scenes", type=int, default=256) + parser.add_argument("--workers", type=int, default=4) + parser.add_argument("--gpu-uuid", default="GPU-8169d457412f2f76") + parser.add_argument("--expected-pci-bus", type=int, default=171) + parser.add_argument("--initial-only", action="store_true", help="Explicitly run only full_seed42, not all controls") + parser.add_argument("--protocol", choices=("seven", "noise-v2"), default="seven") + parser.add_argument("--reference-manifest", type=Path, help="Frozen v1 parent for noise-v2 comparisons") + parser.add_argument("--predecessor-suite", type=Path, help="Completed v1 suite required before noise-v2 GPU work") + parser.add_argument("--resume-suite", action="store_true") + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args() + if min(args.epochs, args.batch_size, args.synthetic_batch_size, args.patch_size, args.synthetic_scenes) <= 0 or args.workers < 0: + parser.error("Invalid training budget or dimensions") + args.manifest = args.manifest.resolve() + args.output_root = args.output_root.resolve() + manifest = json.loads(args.manifest.read_text()) + counts = validate_manifest(manifest, require_all_types=True) + if any(counts["test"][kind] == 0 for kind in manifest["types"]): + raise ValueError("Suite requires a declared held-out test source for all seven types") + reference = None + noise_protocol = args.protocol == "noise-v2" + if noise_protocol: + if args.initial_only or args.reference_manifest is None or args.predecessor_suite is None or args.epochs < 2: + parser.error("Noise-v2 requires both trials, >=2 rounds, --reference-manifest and --predecessor-suite") + args.reference_manifest = args.reference_manifest.resolve() + args.predecessor_suite = args.predecessor_suite.resolve() + reference = validate_noise_parent(manifest, args.reference_manifest) + validate_manifest(reference, require_all_types=True) + runs = NOISE_RUNS + else: + if args.reference_manifest is not None or args.predecessor_suite is not None: + parser.error("Reference/predecessor options belong to the noise-v2 protocol") + runs = RUNS[:1] if args.initial_only else RUNS + plan = {name: commands(args, name, seed, flags) for name, seed, flags in runs} + if args.dry_run: + print(json.dumps({"protocol": args.protocol, "counts": counts, "commands": plan, + "steps_per_run": args.epochs * math.ceil(len(manifest["train"]) / args.batch_size)}, indent=2)) + return + if noise_protocol: + validate_predecessor(args.predecessor_suite, file_digest(args.reference_manifest), + args.gpu_uuid, args.expected_pci_bus) + args.output_root.mkdir(parents=True, exist_ok=True) + settings = {key: str(value) if isinstance(value, Path) else value for key, value in vars(args).items() + if key not in ("resume_suite", "dry_run")} + config = {"settings": settings, "manifest_sha256": file_digest(args.manifest), "counts": counts, + "source_digest": source_provenance()["source_digest"], "commands": plan, + "launcher_sha256": file_digest(__file__), + "reporter_sha256": file_digest(ROOT / "scripts/report_phase1_seven.py"), + "scope": ("All selected records covered; balanced rounds may repeat IDs; truthful coverage and visit logs" + if noise_protocol else "All admitted training records per epoch; explicit heldout/probe limitations in evaluation reports")} + if noise_protocol: + config.update({"reference_manifest_sha256": file_digest(args.reference_manifest), + "primary_checkpoint": "last.pt", "matched_steps_per_run": args.epochs * math.ceil(len(manifest["train"]) / args.batch_size), + "reference_comparison": "These two v2 runs match each other; prior v1 is not assumed compute-matched"}) + # Same-user lock prevents a second copy of this queue, not other users' jobs. + lock_path = suite_lock_path(args) + with lock_path.open("a") as lock: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + if noise_protocol: + validate_predecessor(args.predecessor_suite, file_digest(args.reference_manifest), + args.gpu_uuid, args.expected_pci_bus) + config_path = args.output_root / "suite_config.json" + if config_path.exists(): + if not args.resume_suite: + raise FileExistsError("Existing suite requires --resume-suite") + old = json.loads(config_path.read_text()) + if old != json.loads(json.dumps(config)): + raise ValueError("Suite configuration/source/manifest changed; refuse ambiguous resume") + else: + if any((args.output_root / name).exists() for name, _, _ in runs): + raise FileExistsError("New suite must not adopt pre-existing unowned run directories") + atomic_json_save(config, config_path) + environment = os.environ.copy() + for key in ("CUDA_VISIBLE_DEVICES", "HIP_VISIBLE_DEVICES"): + environment.pop(key, None) + environment.update({"ROCR_VISIBLE_DEVICES": args.gpu_uuid, "OMP_NUM_THREADS": "4", + "OPENBLAS_NUM_THREADS": "4", "PYTHONUNBUFFERED": "1"}) + verify = "import torch,sys; assert torch.cuda.device_count()==1; p=torch.cuda.get_device_properties(0); assert p.pci_bus_id==int(sys.argv[1]); print(p)" + subprocess.run([args.python, "-c", verify, str(args.expected_pci_bus)], env=environment, check=True) + status_path = args.output_root / "suite_status.json" + status = {"status": "running", "suite_pid": os.getpid(), "started_unix": time.time(), "completed_runs": [], + "gpu_uuid": args.gpu_uuid, "expected_pci_bus": args.expected_pci_bus} + + def interrupted(signum, frame): + raise InterruptedError(f"Suite received signal {signum}; stopping owned stage") + + signal.signal(signal.SIGTERM, interrupted) + + def execute(command, run_name, stage): + directory = args.output_root / run_name + directory.mkdir(exist_ok=True) + log_path = directory / f"{stage}.log" + with log_path.open("a") as log: + def started(child): + status.update({"current_run": run_name, "stage": stage, "child_pid": child.pid, + "command": command, "log": str(log_path), "updated_unix": time.time()}) + atomic_json_save(status, status_path) + # The child inherits the lock so parent SIGKILL cannot permit a + # concurrent queue to resume while this trainer still runs. + run_owned_command(command, environment, log, lock.fileno(), started) + status["child_pid"] = None + + try: + for name, seed, flags in runs: + directory = args.output_root / name + train, evaluations = commands(args, name, seed, flags) + final_path = directory / "final_validation.json" + finished = json.loads(final_path.read_text()).get("status") == "completed" if final_path.exists() else False + if finished: + prior = json.loads((directory / "run_config.json").read_text()) + final = json.loads(final_path.read_text()) + if (prior.get("manifest_sha256") != config["manifest_sha256"] + or prior.get("provenance", {}).get("source_digest") != config["source_digest"] + or prior.get("scope") != "full_manifest" or final.get("epoch") != args.epochs + or final.get("cursor") != 0 + or prior.get("arguments", {}).get("seed") != seed + or prior.get("arguments", {}).get("no_edges") != ("--no-edges" in flags) + or prior.get("model_config", {}).get("rank") != (1 if "--prototype-only" in flags else 8) + or (noise_protocol and prior.get("arguments", {}).get("noise_sampling") != flags[-1])): + raise ValueError("Completed run provenance/budget does not match suite") + if not finished: + if (directory / "last.pt").exists(): + train += ["--resume", str(directory / "last.pt")] + execute(train, name, "train") + if json.loads(final_path.read_text()).get("status") != "completed": + raise RuntimeError(f"Run {name} did not complete its full epoch budget") + if noise_protocol: + validate_noise_completion(json.loads(final_path.read_text()), len(manifest["train"]), args.epochs, args.batch_size) + for stage, command in zip(evaluation_stages(args, directory), evaluations): + split, report_path = stage["split"], stage["output"] + if not report_path.exists(): + execute(command, name, stage["name"]) + report = json.loads(report_path.read_text()) + evaluated_manifest = reference if stage["manifest"] == args.reference_manifest else manifest + validate_evaluation(report, evaluated_manifest, file_digest(stage["manifest"]), + file_digest(directory / ("last.pt" if noise_protocol else "best.pt")), split, args, + controlled=stage["controlled"]) + if noise_protocol and not stage["controlled"]: + strata = report.get("real", {}).get("noise_stratification", {}) + if strata.get("status") != "measured": + raise ValueError("Expanded noise evaluation lacks verified source-stratified metrics") + status["completed_runs"].append(name) + atomic_json_save(status, status_path) + write_report(args.output_root) + status.update({"status": "completed", "completed_unix": time.time(), "child_pid": None}) + atomic_json_save(status, status_path) + write_report(args.output_root) + except BaseException as error: + status.update({"status": "failed", "error": str(error), "updated_unix": time.time(), "child_pid": None}) + atomic_json_save(status, status_path) + raise + + +if __name__ == "__main__": + main() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/slides/README.md b/dataset/phase1_noise_20260906/trial_code_staging/slides/README.md new file mode 100644 index 0000000000000000000000000000000000000000..06c2ba86ce1268f7f013404e012ad50416aeca96 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/slides/README.md @@ -0,0 +1,17 @@ +# Slide deck generator + +`build_deck.js` builds `SCDC_Final_Deck.pptx` with pptxgenjs, styled after the +MAVT engineering-brief template (13.33x7.5 in, F4F5F6 ground, Arial + Courier +New, C75D3A accent, accent-bar panels, Courier footer with page numbers, +speaker notes). It expects the rendered figures under `outputs/` (charts from +`make_final_charts.py`, grids from `visualize_v7_uformer.py`, +`outputs/scene008_dgf.png`). Run from a directory whose parent holds `outputs/` +(the working copy lives in `outputs/deck/`): + +```bash +cd outputs/deck && npm install pptxgenjs && node build_deck.js +``` + +Optional: `CONTROL_ROWS='[["Step",...],...]' CONTROL_NOTE='...' node build_deck.js` +fills the Phase-1 control table on slide 11. Rendering for QA on macOS without +LibreOffice: PowerPoint AppleScript `save ... as save as PDF`, then `pdftoppm`. diff --git a/dataset/phase1_noise_20260906/trial_code_staging/slides/build_deck.js b/dataset/phase1_noise_20260906/trial_code_staging/slides/build_deck.js new file mode 100644 index 0000000000000000000000000000000000000000..78fb6c3257ade8b4c1e3bb80e72d4fe77736c9c3 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/slides/build_deck.js @@ -0,0 +1,381 @@ +// SCDC final-report deck, styled after the MAVT engineering-brief template: +// 13.33x7.5 in, cool-grey ground, Arial + Courier New, rust accent, panels +// with a 0.03" accent bar, Courier footer with page number, speaker notes. +const pptxgen = require("pptxgenjs"); +const path = require("path"); + +const ROOT = path.resolve(__dirname, ".."); +const IMG = { + progression: path.join(ROOT, "final_charts/01_version_progression.png"), + external: path.join(ROOT, "final_charts/02_external.png"), + probe: path.join(ROOT, "final_charts/03_tap_probe.png"), + control: path.join(ROOT, "final_charts/04_phase1_control.png"), + haze: path.join(ROOT, "phase2_v7_dgf8k_vis/v7_uformer_haze.png"), + noise: path.join(ROOT, "phase2_v7_dgf8k_vis/v7_uformer_noise.png"), + lowlight: path.join(ROOT, "phase2_v7_dgf8k_vis/v7_uformer_lowlight.png"), + rain: path.join(ROOT, "phase2_v7_dgf8k_vis/v7_uformer_rain.png"), + scene008: path.join(ROOT, "scene008_dgf.png"), +}; +const fs = require("fs"); + +// ---- template tokens +const BG = "F4F5F6", INK = "263042", INK2 = "374151", MUTED = "6B7280", FAINT = "9AA3AF"; +const RULE = "D8DCE2", PANEL = "ECF1F5", WHITE = "FFFFFF", ACCENT = "C75D3A"; +const SANS = "Arial", MONO = "Courier New"; +const L = 0.75, W = 11.83, FOOT = "SCDC · Unified Restoration Diffusion · Final Report 2026"; + +const pres = new pptxgen(); +pres.layout = "LAYOUT_WIDE"; +pres.author = "SCDC"; +pres.title = "SCDC — Final Version"; + +let page = 0; +function base(eyebrow, headline, sub, notes) { + const s = pres.addSlide(); + page += 1; + s.background = { color: BG }; + s.addText(eyebrow, { x: L, y: 0.62, w: W, h: 0.2, fontFace: MONO, fontSize: 9, color: ACCENT, charSpacing: 2, margin: 0 }); + s.addText(headline, { x: L, y: 0.86, w: W, h: 0.46, fontFace: SANS, fontSize: 21, bold: true, color: INK, margin: 0, fit: "shrink" }); + if (sub) s.addText(sub, { x: L, y: 1.4, w: W, h: 0.34, fontFace: SANS, fontSize: 11, color: INK2, margin: 0 }); + s.addShape(pres.shapes.LINE, { x: L, y: 6.98, w: W, h: 0, line: { color: RULE, width: 0.75 } }); + s.addText(FOOT, { x: L, y: 7.08, w: 6, h: 0.2, fontFace: MONO, fontSize: 8, color: FAINT, margin: 0 }); + s.addText(String(page), { x: 12.2, y: 7.08, w: 0.38, h: 0.2, fontFace: MONO, fontSize: 8, color: FAINT, align: "right", margin: 0 }); + if (notes) s.addNotes(notes); + return s; +} +function label(s, text, x, y, w) { + s.addText(text, { x, y, w, h: 0.18, fontFace: MONO, fontSize: 8.5, color: MUTED, charSpacing: 1.5, margin: 0 }); +} +function panel(s, x, y, w, h, opts = {}) { + s.addShape(pres.shapes.RECTANGLE, { x, y, w, h, fill: { color: opts.fill || WHITE }, line: { color: RULE, width: 0.75 } }); + if (opts.bar !== false) s.addShape(pres.shapes.RECTANGLE, { x: x - 0.02, y, w: 0.03, h, fill: { color: opts.barColor || ACCENT }, line: { color: opts.barColor || ACCENT, width: 0 } }); +} +function body(s, lines, x, y, w, h, opts = {}) { + const runs = lines.map((t, i) => { + const o = typeof t === "string" ? { text: t } : t; + return { text: o.text, options: Object.assign({ breakLine: i < lines.length - 1, bold: !!o.bold, color: o.color || INK2, bullet: !!o.bullet, fontSize: o.size || opts.size || 10.5 }, o.options || {}) }; + }); + s.addText(runs, { x, y, w, h, fontFace: SANS, fontSize: opts.size || 10.5, color: INK2, valign: "top", margin: 0, paraSpaceAfter: opts.gap == null ? 3 : opts.gap }); +} +function stat(s, value, caption, x, y, w, color) { + s.addText(value, { x, y, w, h: 0.42, fontFace: SANS, fontSize: 23, bold: true, color: color || INK, margin: 0 }); + s.addText(caption, { x, y: y + 0.42, w, h: 0.34, fontFace: SANS, fontSize: 9, color: MUTED, margin: 0, valign: "top" }); +} +function mono(s, text, x, y, w, h, size) { + s.addText(text, { x, y, w, h, fontFace: MONO, fontSize: size || 9.5, color: INK, margin: 0, valign: "top" }); +} +function img(s, key, x, y, w, h) { + if (!fs.existsSync(IMG[key])) { panel(s, x, y, w, h, { bar: false }); mono(s, "[missing " + key + "]", x + 0.2, y + 0.2, w - 0.4, 0.3); return; } + s.addImage({ path: IMG[key], x, y, w, h, sizing: { type: "contain", w, h } }); +} +function table(s, rows, x, y, colW, opts = {}) { + const rowH = opts.rowH || 0.27; + const data = rows.map((r, ri) => r.map((c, ci) => ({ + text: String(c), + options: { + fontFace: ci === 0 ? SANS : MONO, fontSize: opts.size || 9.5, + bold: ri === 0 || (opts.boldCol != null && ci === opts.boldCol), + color: ri === 0 ? MUTED : INK, align: ci === 0 ? "left" : "right", + fill: { color: ri === 0 ? PANEL : WHITE }, margin: [2, 6, 2, 6], + border: { type: "solid", pt: 0.5, color: RULE }, + }, + }))); + s.addTable(data, { x, y, colW, rowH, fontFace: SANS }); +} + +// ------------------------------------------------------------------ 1 · title +{ + const s = pres.addSlide(); page += 1; s.background = { color: BG }; + s.addText("SCDC / IMAGE RESTORATION · FINAL REPORT 2026", { x: L, y: 1.15, w: W, h: 0.22, fontFace: MONO, fontSize: 9.5, color: ACCENT, charSpacing: 2, margin: 0 }); + s.addText("Blind all-in-one restoration", { x: L, y: 1.5, w: W, h: 0.8, fontFace: SANS, fontSize: 40, bold: true, color: INK, margin: 0 }); + s.addText([{ text: "with ", options: {} }, { text: "one", options: { color: ACCENT } }, { text: " diffusion network", options: {} }], { x: L, y: 2.25, w: W, h: 0.8, fontFace: SANS, fontSize: 40, bold: true, color: INK, margin: 0 }); + s.addText("Graph degradation representation · Unified two-step ResShift · Uformer trunk with a full-resolution head", { x: L, y: 3.15, w: W, h: 0.3, fontFace: SANS, fontSize: 12.5, color: INK2, margin: 0 }); + const cols = [ + ["REPRESENTATION", "Phase-1 graph encoder: 4 node đã biết + 2 free/null, severity, OOD detection"], + ["RESTORATION", "Phase-2: một mạng, T = 2, exact posterior, head full-res train-chung"], + ["EVIDENCE", "27,50 / 0,850 nội bộ · thắng pipeline hai mạng trên cả 3 bộ external"], + ]; + cols.forEach((c, i) => { + const x = L + i * 3.95; + s.addShape(pres.shapes.LINE, { x, y: 4.15, w: 3.6, h: 0, line: { color: ACCENT, width: 1.5 } }); + label(s, c[0], x, 4.3, 3.6); + body(s, [c[1]], x, 4.55, 3.55, 0.8, { size: 10.5 }); + }); + s.addText("haze · lowlight · noise · rain — không nhãn task lúc inference — seed 42, 2×RTX 3090", { x: L, y: 5.75, w: W, h: 0.25, fontFace: MONO, fontSize: 9, color: MUTED, margin: 0 }); + s.addShape(pres.shapes.LINE, { x: L, y: 6.98, w: W, h: 0, line: { color: RULE, width: 0.75 } }); + s.addText(FOOT, { x: L, y: 7.08, w: 6, h: 0.2, fontFace: MONO, fontSize: 8, color: FAINT, margin: 0 }); + s.addText("1", { x: 12.2, y: 7.08, w: 0.38, h: 0.2, fontFace: MONO, fontSize: 8, color: FAINT, align: "right", margin: 0 }); + s.addNotes("Bản cuối của SCDC: một mạng diffusion hai bước, có head full-res và FiLM, được điều kiện hoá bởi graph của Phase-1. Mọi số trong deck là seed 42; nội bộ 317 ảnh val; external là ba bộ locked."); +} + +// ------------------------------------------------------------------ 2 · problem +{ + const s = base("BÀI TOÁN · VÌ SAO PHẢI THỐNG NHẤT", "Bốn suy hoá, một model, không nhãn — pipeline hai mạng thì chắp vá", + "Điểm xuất phát của chu kỳ cuối: gen-2 = diffusion 1-step + refiner tách rời. Đẹp ở val nội bộ, nhưng là hai mạng ghép, và external lộ ngay.", + "Motivating problem: hai mạng ghép — refiner học riêng — overfit phân phối nội bộ. Directive của dự án: một pipeline thống nhất, hiệu quả với diffusion, không phải hai mạng chắp vá."); + label(s, "INPUT · ĐỘ KHÓ THEO DOMAIN (PSNR ẢNH VÀO)", L, 2.1, 6.5); + const doms = [["Haze", "17,3"], ["Lowlight", "9,8"], ["Noise", "27,3"], ["Rain", "21,3"]]; + doms.forEach((d, i) => { + const x = L + i * 1.55; + s.addShape(pres.shapes.RECTANGLE, { x, y: 2.4, w: 1.35, h: 0.95, fill: { color: WHITE }, line: { color: RULE, width: 0.75 } }); + s.addText(d[1], { x: x + 0.12, y: 2.47, w: 1.15, h: 0.45, fontFace: SANS, fontSize: 21, bold: true, color: INK, margin: 0 }); + s.addText(d[0], { x: x + 0.12, y: 2.92, w: 1.15, h: 0.3, fontFace: MONO, fontSize: 8.5, color: MUTED, margin: 0 }); + }); + body(s, [ + { text: "Blind: ", bold: true, options: { color: INK } }, + "Phase-1 phải tự suy loại và mức suy hoá; không có prompt, không có nhãn.", + { text: "All-in-one: ", bold: true, options: { color: INK } }, + "một bộ trọng số cho cả bốn — các task dễ giẫm nhau (định luật drift, slide 5).", + { text: "Thước đo: ", bold: true, options: { color: INK } }, + "macro PSNR/SSIM nội bộ (317 ảnh) + ba bộ external locked (rain 1200 · haze 300 · scene008 20).", + ], L, 3.6, 6.4, 2.1, { size: 10.5, gap: 2 }); + + panel(s, 7.5, 2.1, 5.08, 3.55); + label(s, "GEN-2 TRƯỚC CHU KỲ CUỐI · HAI MẠNG", 7.75, 2.28, 4.6); + body(s, [ + "y → Phase-1 → U-Net 1-step x̂₀ → RefinerDecoder (NAFNet-lite, train riêng) → x̂", + { text: "Nội bộ 27,55 / 0,874 — nhưng:", bold: true, options: { color: INK } }, + { text: "refiner train rời overfit val: external noise −5 dB so với mạng thuần", bullet: true }, + { text: "hai optimizer, hai loss, hai checkpoint — không phải một quá trình diffusion", bullet: true }, + { text: "artifact nhỏ (snow lấm tấm) vẫn lọt", bullet: true }, + ], 7.75, 2.55, 4.65, 2.2, { size: 10.5 }); + s.addText("Yêu cầu: giữ chất lượng của refiner nhưng nằm TRONG một mạng, một loss.", { x: 7.75, y: 4.95, w: 4.65, h: 0.55, fontFace: SANS, fontSize: 10.5, italic: true, color: ACCENT, margin: 0 }); + + panel(s, L, 5.9, 11.83, 0.85, { fill: PANEL }); + s.addText([{ text: "Câu hỏi của chu kỳ cuối: ", options: { bold: true, color: INK } }, { text: "một mạng diffusion có đuổi kịp hai mạng không — và cái gì trong Phase-1 thực sự được dùng?", options: { color: INK2 } }], { x: L + 0.25, y: 6.1, w: 11.3, h: 0.5, fontFace: SANS, fontSize: 11, margin: 0 }); +} + +// ------------------------------------------------------------------ 3 · architecture +{ + const s = base("KIẾN TRÚC · BẢN CUỐI (uformer_dgf8k, best @6000)", "Hai pha, một quá trình: graph chẩn đoán → diffusion hai bước → head full-res", + "Mọi thành phần mới đều zero-init/identity: eval@0 của từng chu kỳ trùng bitwise best chu kỳ trước.", + "Phase-1 đóng băng (ll_v3). Phase-2: pixel-unshuffle x2 thành state 12 kênh, anchor u_y, dự đoán x0. Coarse t=2 rồi posterior chính xác rồi fine t=1, sau đó pixel-shuffle và head full-res. Liều w ở inference là tuỳ chọn."); + // pipeline boxes + const boxes = [ + ["y", "ảnh vào", 0.9], ["Phase-1", "graph encoder\n(frozen)", 1.55], ["context ‖ adaLN", "8 token · global vec\n(2 đường sống)", 1.75], + ["Uformer t=2", "coarse x̂₀\nx0-MSE + tháp", 1.55], ["posterior", "exact, κ theo mẫu", 1.35], ["Uformer t=1", "fine x̂₀\nL1+VGG+UV+Y", 1.55], ["head", "tail 256px + FiLM", 1.35], ["x̂", "ảnh ra", 0.9], + ]; + let x = L; const y = 2.05; + boxes.forEach((b, i) => { + const w = b[2]; + const hi = i === 3 || i === 5; + s.addShape(pres.shapes.RECTANGLE, { x, y, w, h: 0.8, fill: { color: hi ? PANEL : WHITE }, line: { color: hi ? ACCENT : RULE, width: hi ? 1.25 : 0.75 } }); + s.addText(b[0], { x: x + 0.08, y: y + 0.07, w: w - 0.16, h: 0.28, fontFace: MONO, fontSize: 9.5, bold: true, color: INK, margin: 0 }); + s.addText(b[1], { x: x + 0.08, y: y + 0.36, w: w - 0.16, h: 0.42, fontFace: SANS, fontSize: 8, color: MUTED, margin: 0, valign: "top" }); + if (i < boxes.length - 1) s.addText("→", { x: x + w - 0.02, y: y + 0.25, w: 0.24, h: 0.3, fontFace: SANS, fontSize: 12, color: FAINT, margin: 0, align: "center" }); + x += w + 0.2; + }); + // three detail panels + const P = [ + ["PHASE-1 · GRAPH ENCODER (ll_v3)", [ + "Hai nhánh spatial + wavelet; LL-global branch (Haar LL³ + 14 thống kê photometric) giữ thông tin toàn cục", + "Đầu ra: 6 node token (4 known + 2 free), routing, severity 4-d calibrated, spatial maps 16×16, content 64 px, unknown residual, global condition 256-d", + "Null/OOD: free slots học từ ảnh sạch + OOD tổng hợp — OOD → free 55–60/60, novelty gap 3–4×", + ]], + ["PHASE-2 · TRUNK UFORMER, T = 2", [ + "LeWin block: window-attn 8×8 + LeFF + adaLN zero-init; dims 64/128/192/256, cond 256", + "Cross-attention với 8 token graph ở 2 scale sâu; adaLN từ global_vector; MoE 5 expert top-2 ở 7 vị trí; per-type κ", + "η = [0 · 0,04 · 0,98]; fine step dựng từ chính prediction (detach) qua posterior chính xác", + ]], + ["IMAGE HEAD + DGF (train-chung)", [ + "Tail NAFNet-lite 3×48 ở FULL-RES (restored ‖ y) + FiLM 6 tham số từ global condition", + "Tháp Laplacian 16/32/64 px với anchor u_y — identity chính xác khi δ = 0, deep supervision λ 0,1/0,2/0,3", + "Token null học được (context, global) · dropout p 0,15 · identity pairs q 0,10 · liều w ở inference", + ]], + ]; + P.forEach((p, i) => { + const px = L + i * 3.98; const py = 3.25; + panel(s, px, py, 3.85, 2.3); + label(s, p[0], px + 0.25, py + 0.18, 3.5); + body(s, p[1].map(t => ({ text: t, bullet: true })), px + 0.25, py + 0.45, 3.45, 1.8, { size: 9.5, gap: 4 }); + }); + s.addText("Mất mát composite, một optimizer: coarse x0-MSE (fp32) + tháp MSE + fine [L1 + 0,1·VGG + 0,5·chroma(UV) + 0,5·luma(pool 8×8)] + gate anchor/correction", { x: L, y: 5.85, w: W, h: 0.5, fontFace: MONO, fontSize: 9, color: INK, margin: 0 }); +} + +// ------------------------------------------------------------------ 4 · method: unified two-step +{ + const s = base("PHƯƠNG PHÁP · UNIFIED TWO-STEP RESSHIFT", "Refiner được nội hoá thành bước fine của chính quá trình diffusion", + "Hai bước trên cùng trọng số, điều kiện thời gian bằng adaLN — không mạng phụ, không optimizer thứ hai.", + "ResShift: u_t = u0 + eta_t (u_y - u0) + kappa sqrt(eta_t) eps. Với T=2, bước coarse quyết định nội dung toàn cục, bước fine đánh bóng. Bước fine được dựng từ dự đoán của chính model (detach) nên không có exposure bias."); + panel(s, L, 2.05, 5.75, 4.0); + label(s, "FORWARD / REVERSE (T = 2)", L + 0.25, 2.23, 5.3); + mono(s, "u_t = u₀ + η_t (u_y − u₀) + κ √η_t · ε\nη = [0, 0,04, 0,98]\n\ncoarse t=2: x̂₀ = f(u₂, u_y, c) → x0-MSE fp32\n u₁ ~ q(u₁ | u₂, x̂₀.detach)\n (posterior chính xác, κ theo mẫu)\nfine t=1: x̂₀' = f(u₁, u_y, c) → shuffle → head\n L1 + 0,1·VGG + 0,5·UV + 0,5·Y", L + 0.25, 2.5, 5.3, 2.0, 8.5); + body(s, [ + { text: "Vì sao T = 2 chứ không phải chain dài: ", bold: true, options: { color: INK } }, + "đo được từ v4: chain 8 bước 22,04 < 1-step 22,68 (exposure bias). Hai bước chain-aware là điểm cân bằng: 23,41 với cùng trunk conv (+0,7).", + { text: "Noise fine = torch.flip(noise coarse): ", bold: true, options: { color: INK } }, + "kế hoạch nhiễu vẫn replay được theo record — mọi eval tái lập bitwise.", + ], L + 0.25, 4.5, 5.3, 1.45, { size: 10, gap: 2 }); + + panel(s, 6.85, 2.05, 5.73, 4.0, { fill: PANEL }); + label(s, "LIÊN HỆ VỚI GEN-2 HAI MẠNG", 7.1, 2.23, 5.2); + const map = [["gen-2", "bản cuối"], ["U-Net 1-step x̂₀ (MSE)", "bước coarse t = 2 (x0-MSE + tháp)"], ["RefinerDecoder train riêng (L1+VGG)", "bước fine t = 1 + head full-res, cùng loss"], ["2 optimizer · 2 checkpoint", "1 optimizer · 1 EMA · 1 checkpoint"], ["external noise −5 dB (overfit)", "external giữ nguyên hoặc tăng"]]; + map.forEach((r, i) => { + const yy = 2.55 + i * 0.56; + s.addText(r[0], { x: 7.1, y: yy, w: 2.5, h: 0.5, fontFace: SANS, fontSize: 9.5, color: MUTED, margin: 0, valign: "middle" }); + s.addText("→", { x: 9.6, y: yy, w: 0.3, h: 0.5, fontFace: SANS, fontSize: 11, color: FAINT, margin: 0, valign: "middle" }); + s.addText(r[1], { x: 9.95, y: yy, w: 2.55, h: 0.5, fontFace: SANS, fontSize: 9.5, bold: i === 0, color: INK, margin: 0, valign: "middle" }); + if (i < map.length - 1) s.addShape(pres.shapes.LINE, { x: 7.1, y: yy + 0.53, w: 5.35, h: 0, line: { color: RULE, width: 0.5 } }); + }); + s.addText("Định luật 3: cùng một dung lượng full-res — đặt trong cùng graph/loss/optimizer thì an toàn ngoài phân phối; tách thành mạng thứ hai thì overfit.", { x: L, y: 6.25, w: W, h: 0.5, fontFace: SANS, fontSize: 10.5, italic: true, color: ACCENT, margin: 0 }); +} + +// ------------------------------------------------------------------ 5 · backbone / drift law +{ + const s = base("BACKBONE · VÌ SAO UFORMER", "Window-attention + adaLN zero-init xoá định luật drift của conv-trunk", + "Mọi trunk conv (v4, v6, v6.1, v7-conv) đều hy sinh lowlight khi tối ưu dài. Uformer từ scratch leo đơn điệu, best == final ở mọi chu kỳ.", + "Đây là phát hiện kiến trúc lớn nhất: cùng recipe, đổi block conv sang LeWin thì lowlight không còn bị hy sinh và không cần curriculum hay cứu checkpoint sớm."); + const rows = [["Biến thể (một mạng)", "Best macro", "SSIM", "Drift"], ["v4 chain 8-step", "22,04", "0,658", "−0,6"], ["v4 1-step", "22,68", "0,662", "—"], ["v7-conv unified (warm-start)", "23,41 @750", "0,703", "nặng sau 750"], ["v7-Uformer from scratch", "25,26 @8000", "0,777", "không"], ["… + 16k + 8k + 8k + 8k", "27,50", "0,850", "không"]]; + table(s, rows, L, 2.1, [2.7, 1.2, 0.75, 1.65], { size: 9.5, rowH: 0.3 }); + stat(s, "0", "chu kỳ bị drift trên Uformer (5 chu kỳ, 48k steps)", L, 4.25, 2.1, ACCENT); + stat(s, "23,41 → 22,16", "v7-conv: đỉnh @750 rồi sụp về @8000 (lowlight sụp trước)", L + 2.3, 4.25, 3.0); + stat(s, "+1,18 / +0,15 / +0,84 / +0,07", "lãi từng chu kỳ warm-restart (SGDR) — schedule quyết định “hội tụ”, loss chưa từng phẳng ở LR còn sống", L, 5.3, 6.2); + + panel(s, 7.5, 2.1, 5.08, 3.9); + label(s, "LEWIN BLOCK · NHỮNG GÌ KHÁC CONV", 7.75, 2.28, 4.6); + body(s, [ + { text: "WindowAttention 8×8, rel-pos bias, tự thu window ở map nhỏ", bullet: true }, + { text: "LeFF: pointwise → depthwise → pointwise, GELU", bullet: true }, + { text: "adaLN 6 tham số zero-init từ (time ⊕ global_vector ⊕ strength prompt)", bullet: true }, + { text: "Cùng hợp đồng điều kiện với conv v6: cross-attn coarse, inject @64/@16, MoE bank, zero-init output", bullet: true }, + { text: "Cùng số tham số cỡ ~12M trunk; DDP 2 GPU cần find_unused_parameters (MoE hard-skip)", bullet: true }, + ], 7.75, 2.55, 4.65, 2.4, { size: 10, gap: 4 }); + s.addText("Giả thuyết cơ chế: adaLN zero-init cho phép điều kiện thời gian/graph điều biến từng block mà không phá đường tắt identity; conv-trunk phải “chia sẻ” kênh giữa task nên lowlight (ít mẫu khó nhất) bị bỏ rơi.", { x: 7.75, y: 5.05, w: 4.65, h: 0.85, fontFace: SANS, fontSize: 9.5, italic: true, color: INK2, margin: 0 }); +} + +// ------------------------------------------------------------------ 6 · progression +{ + const s = base("KẾT QUẢ · TIẾN HOÁ PHIÊN BẢN", "22,7 → 27,5 dB macro qua năm chu kỳ warm-restart, không chu kỳ nào lùi", + "Mỗi chu kỳ thêm đúng một cơ chế zero-init, eval@0 trùng bitwise chu kỳ trước — nên mỗi cột chênh là đóng góp của riêng cơ chế đó.", + "Chart: thanh xanh là một mạng, cam là tham chiếu hai mạng. Chú ý head full-res là bước nhảy SSIM lớn nhất — đúng chẩn đoán trần nửa độ phân giải."); + img(s, "progression", L, 2.0, 7.6, 4.0); + const items = [["+2,58", "Uformer scratch vs v7-conv: backbone", INK], ["+1,18", "chroma UV + 16k warm-restart: màu lowlight, chroma noise", INK], ["+0,84 / +0,035", "head full-res + FiLM: noise +2,6, SSIM nhảy lớn nhất", ACCENT], ["+0,07 / +12,6", "DGF: macro nhỏ, identity ảnh sạch 27,8 → 40,4 dB", INK]]; + items.forEach((it, i) => stat(s, it[0], it[1], 8.65, 2.05 + i * 1.02, 3.9, it[2])); +} + +// ------------------------------------------------------------------ 7 · internal results by domain +{ + const s = base("KẾT QUẢ · NỘI BỘ THEO DOMAIN", "Haze, noise đã vượt/ngang hai mạng; lowlight, rain là hai mặt trận còn lại", + "dgf8k best @6000, liều w = 1. Sweep liều: w = 0,5 cho macro 27,54; w = 0 cho SSIM 0,852 — đường cong phẳng (slide 11).", + "Rain nội bộ bị GT lệch tone kéo thấp giả tạo — external rain 28,0 dB. Lowlight cực đoan là trần thông tin: input ~9,7 dB gần đen, độ sáng tuyệt đối của GT không có trong ảnh vào."); + const rows = [["Domain", "Degraded", "Bản cuối", "gen-2 (2 mạng)", "n"], ["Haze", "17,31", "32,73", "30,2", "100"], ["Noise", "27,33", "35,99", "36,9", "19"], ["Lowlight", "9,77", "18,74", "20,3", "100"], ["Rain", "21,25", "22,53", "22,8", "98"], ["Macro PSNR", "18,91", "27,50", "27,55", "317"], ["Macro SSIM", "0,551", "0,850", "0,874", ""]]; + table(s, rows, L, 2.05, [1.6, 1.1, 1.15, 1.35, 0.6], { size: 10, rowH: 0.32, boldCol: 2 }); + body(s, [ + { text: "Haze 32,7: ", bold: true, options: { color: INK } }, "vượt hai mạng 2,5 dB; FiLM + LL-global đúng địa bàn.", + { text: "Noise 36,0: ", bold: true, options: { color: INK } }, "tail full-res +2,6; còn kém refiner 0,9 (n = 19, 1 scene).", + { text: "Lowlight 18,7: ", bold: true, options: { color: INK } }, "cấu trúc tốt (SSIM 0,39 → 0,75), màu đã sửa bằng chroma, overshoot cực đoan là trần thông tin.", + { text: "Rain 22,5: ", bold: true, options: { color: INK } }, "streak gỡ tốt, PSNR bị tone GT; external 28,0.", + ], L, 4.5, 5.9, 1.9, { size: 10, gap: 2 }); + img(s, "noise", 7.1, 1.95, 5.5, 4.5); + label(s, "NOISE · DEGRADED | BẢN CUỐI | GT · KHÔNG CHERRY-PICK", 7.1, 6.55, 5.5); +} + +// ------------------------------------------------------------------ 8 · qualitative haze + rain +{ + const s = base("ĐỊNH TÍNH · HAZE VÀ RAIN", "Khử mù gần trùng GT kể cả mù dày; derain sạch streak, phần thua là tone GT", + "Ba mẫu mỗi domain chọn máy móc theo record-id (đầu / giữa / cuối) — không cherry-pick. Mỗi ô ghi PSNR / SSIM so với GT.", + "Hàng zebra và bờ biển ở rain: streak gỡ tốt, SSIM tăng, nhưng PSNR giảm vì ảnh ra lệch tone toàn cục so với GT — đây là đặc thù của cặp dữ liệu rain, không phải lỗi derain."); + img(s, "haze", L, 1.95, 5.8, 4.9); + img(s, "rain", 6.78, 1.95, 5.8, 4.9); +} + +// ------------------------------------------------------------------ 9 · qualitative lowlight + limits +{ + const s = base("ĐỊNH TÍNH · LOWLIGHT VÀ HAI TRẦN ĐÃ XÁC LẬP", "Màu trở lại nhờ chroma loss; ca gần đen tuyệt đối là trần thông tin", + "Ghế sân vận động: 8k → nâu xám, bản cuối → xanh. Hai mẫu quạt (input 9,7 dB): overshoot còn nguyên qua chroma, luma, head, DGF.", + "Hai trần: (1) độ sáng tuyệt đối của GT không có trong ảnh vào gần đen; (2) scene008 tối có vân — model đọc tối thành lowlight và vân thành noise. Cả hai không sửa được bằng loss thêm."); + img(s, "lowlight", L, 1.95, 5.8, 4.9); + panel(s, 6.9, 1.95, 5.68, 4.9, { fill: PANEL }); + label(s, "HAI TRẦN — ĐO ĐƯỢC, KHÔNG ĐOÁN", 7.15, 2.13, 5.2); + body(s, [ + { text: "1 · Overshoot lowlight cực đoan", bold: true, options: { color: INK } }, + "Input ~9,7 dB gần đen tuyệt đối. Chroma loss, luma loss (pool 8×8), head, DGF: per-sample vẫn 12,3–12,8 dB trong khi aggregate lowlight tăng 18,0 → 18,8. Độ sáng tuyệt đối của GT là thông tin không tồn tại trong ảnh vào.", + { text: "2 · Ảnh sạch tối, có vân (scene008)", bold: true, options: { color: INK } }, + "Input 39–44 dB ≈ GT. Phase-1 gán clean GT là noise 0,41 / severity 0,33 — y hệt bản degraded. Nhánh null kéo sáng như lowlight (12,8 dB), nhánh có điều kiện làm mờ nhẹ (26–32).", + { text: "Hệ quả thiết kế", bold: true, options: { color: INK } }, + "Identity phải được dạy bằng ảnh sạch giống phân phối triển khai (tối, có vân, real-camera); identity nội bộ 40 dB không chuyển sang đây.", + ], 7.15, 2.4, 5.2, 4.3, { size: 11, gap: 6 }); +} + +// ------------------------------------------------------------------ 10 · external +{ + const s = base("KẾT QUẢ · EXTERNAL HELD-OUT", "Ngoài phân phối, một mạng thắng hai mạng trên cả ba bộ — bảng nội bộ đảo chiều", + "Cùng protocol locked: rain 1200 · RESIDE held-out 300 · SIDD scene008 20. PSNR / SSIM / LPIPS; số trên cột là PSNR.", + "Refiner của gen-2 overfit val nội bộ: external noise thua 4,7 dB. Head full-res train-chung của bản cuối giữ hoặc tăng external. scene008 vẫn không về identity vì lý do ở slide 9."); + img(s, "external", L, 1.95, 7.4, 3.4); + const rows = [["Bộ · PSNR / SSIM", "gen-2", "bản cuối"], ["Rain 1200", "26,71 / 0,833", "27,88 / 0,834"], ["Haze 300", "31,18 / 0,971", "31,87 / 0,975"], ["scene008", "22,35 / 0,801", "26,50 / 0,825"]]; + table(s, rows, 8.45, 2.0, [1.35, 1.4, 1.4], { size: 9, rowH: 0.3 }); + body(s, [ + { text: "Rain: ", bold: true, options: { color: INK } }, "+1,2 dB so với hai mạng; nội bộ 22,5 là số bị GT lệch tone.", + { text: "Haze: ", bold: true, options: { color: INK } }, "+0,7; LPIPS 0,010 → 0,009 — gần trùng GT.", + { text: "scene008: ", bold: true, options: { color: INK } }, "+4,2 dB và LPIPS 0,33 → 0,19 so với head8k, nhưng vẫn −12 so với input 39 dB (trần 2).", + ], 8.45, 3.4, 4.1, 2.0, { size: 9.5, gap: 2 }); + panel(s, L, 5.6, 11.83, 1.15, { fill: PANEL }); + s.addText([{ text: "Định luật 3 (đo hai lần): ", options: { bold: true, color: INK } }, { text: "cùng dung lượng full-res, refiner train rời mất 5 dB external; head train chung trong một graph/loss/optimizer giữ nguyên — vị trí đặt dung lượng quyết định khái quát hoá, không phải dung lượng.", options: { color: INK2 } }], { x: L + 0.25, y: 5.78, w: 11.3, h: 0.8, fontFace: SANS, fontSize: 10.5, margin: 0 }); +} + +// ------------------------------------------------------------------ 11 · what Phase-1 is worth +{ + const s = base("PHASE-1 ĐÁNG BAO NHIÊU · PROBE, DGF, CONTROL", "Trunk dùng Phase-1 như bộ mô tả ảnh qua hai đường; cấu trúc graph gần như không dùng", + "Probe leave-one-out ở inference (head8k), sweep liều sau DGF, và control p = 1 (không Phase-1, cùng recipe và warm-start).", + "Ba bằng chứng chồng nhau: probe cho thấy hai đường sống và các plug chết; DGF cho thấy nhánh null được train phục hồi gần bằng nhánh có điều kiện; control p=1 định lượng giá trị thật của Phase-1 — tập trung ở haze."); + img(s, "probe", L, 1.95, 6.1, 2.95); + panel(s, 7.1, 1.95, 5.48, 2.95); + label(s, "SWEEP LIỀU SAU DGF (val, coarse-step)", 7.35, 2.13, 5.0); + const rows = [["w", "macro", "SSIM", "low", "haze"], ["0", "27,49", "0,852", "18,87", "32,46"], ["0,5", "27,54", "0,851", "18,80", "32,77"], ["1", "27,50", "0,850", "18,74", "32,73"], ["1,25", "27,43", "0,849", "18,68", "32,55"]]; + table(s, rows, 7.35, 2.38, [0.7, 1.0, 1.0, 1.0, 1.0], { size: 9, rowH: 0.26 }); + s.addText("Phẳng: +1,95 lowlight của ablation biến mất khi nhánh null được train. Ablation trên model chưa có nhánh null đo “rụt rè off-manifold”, không đo giá trị của điều kiện (định luật 4).", { x: 7.35, y: 3.8, w: 5.0, h: 1.0, fontFace: SANS, fontSize: 9.5, italic: true, color: INK2, margin: 0 }); + panel(s, L, 5.1, 11.83, 1.65, { fill: PANEL }); + label(s, "BA SỐ ĐO ĐI CÙNG", L + 0.25, 5.28, 6); + stat(s, "−7,79 dB", "rút toàn bộ Phase-1 khỏi head8k (nhánh null CHƯA train) — ảo giác về giá trị điều kiện", L + 0.25, 5.55, 3.6); + stat(s, "−0,085 dB", "xoá hoàn toàn MoE gate + κ per-type: cơ chế liều cũ không được dùng", L + 4.1, 5.55, 3.6); + stat(s, "27,8 → 40,4 dB", "identity trên ảnh sạch trước/sau cặp identity (DGF) — ở mọi w", L + 7.95, 5.55, 3.6, ACCENT); +} + +// ------------------------------------------------------------------ 12 · control: no Phase-1 +{ + const s = base("CONTROL · TRUNK CÓ CẦN PHASE-1 KHÔNG", "Tắt điều kiện, giữ nguyên recipe: khoảng cách co về ~0,5 dB và nằm ở haze", + "p = 1: mọi mẫu dùng token null khi fine-tune, eval hoàn toàn không điều kiện (cả hai bước). 1 GPU, batch 8 × accum 2.", + process.env.CONTROL_NOTES || "Control xuất phát 20,4 (nhánh null chưa train) và leo về sát model có điều kiện. Phần chênh còn lại tập trung ở haze — thông tin toàn cục airlight/transmission — và một phần noise; lowlight của control cao hơn (không bị over-drive)."); + img(s, "control", L, 1.95, 7.3, 3.3); + const CONTROL_ROWS = JSON.parse(process.env.CONTROL_ROWS || "null") || [["Step", "2000", "4000", "6000", "8000"], ["Không Phase-1", "26,49", "26,73", "27,03", "đang chạy"], ["Có Phase-1", "27,27", "27,46", "27,50", "27,45"], ["Chênh", "−0,78", "−0,74", "−0,47", "—"]]; + table(s, CONTROL_ROWS, 8.35, 2.0, [1.45, 0.7, 0.7, 0.7, 0.7], { size: 9, rowH: 0.28 }); + label(s, "PHÂN BỐ CHÊNH THEO DOMAIN (" + (process.env.CONTROL_STEP || "@6000") + ")", 8.35, 3.3, 4.2); + const DOM = JSON.parse(process.env.CONTROL_DOMAINS || "null") || [["Haze", "−1,94"], ["Noise", "−0,67"], ["Lowlight", "+0,86"], ["Rain", "−0,13"]]; + DOM.forEach((r, i) => { + const yy = 3.55 + i * 0.36; + s.addText(r[0], { x: 8.35, y: yy, w: 1.6, h: 0.32, fontFace: SANS, fontSize: 10, color: INK2, margin: 0, valign: "middle" }); + s.addText(r[1], { x: 10.0, y: yy, w: 1.2, h: 0.32, fontFace: MONO, fontSize: 10.5, bold: true, color: r[1].startsWith("+") ? "1C7C54" : ACCENT, margin: 0, valign: "middle", align: "right" }); + s.addText(i === 0 ? "control thua nhiều nhất" : i === 2 ? "control HƠN (không over-drive)" : "", { x: 11.3, y: yy, w: 1.3, h: 0.32, fontFace: SANS, fontSize: 8, color: MUTED, margin: 0, valign: "middle" }); + }); + panel(s, L, 5.55, 11.83, 1.05, { fill: PANEL }); + s.addText([{ text: "Đọc cho claim: ", options: { bold: true, color: INK } }, { text: process.env.CONTROL_VERDICT || "chênh 0,2–0,5 dB → Phase-1 giữ vai chẩn đoán / OOD / hỗ trợ haze; restoration là công của trunk. Caveat: control warm-start từ trọng số từng học có điều kiện — trả lời cho inference và fine-tune tiếp, chưa phải from-scratch.", options: { color: INK2 } }], { x: L + 0.25, y: 5.72, w: 11.3, h: 0.8, fontFace: SANS, fontSize: 10.5, margin: 0, valign: "top" }); +} + +// ------------------------------------------------------------------ 13 · conclusions +{ + const s = base("KẾT LUẬN · CLAIM ĐỨNG ĐƯỢC VÀ BƯỚC TIẾP", "Một mạng hai bước thay được hai mạng; Phase-1 là chẩn đoán + hỗ trợ haze", + "Mọi claim bên trái có số đo trong deck; mọi hạn chế bên phải là điều reviewer sẽ hỏi.", + "Kết luận trung thực: paper là về restoration diffusion thống nhất với các định luật đo được; phần representation phải được viết đúng vai trò của nó."); + panel(s, L, 2.0, 5.8, 3.5); + label(s, "ĐỨNG ĐƯỢC", L + 0.25, 2.18, 5.3); + body(s, [ + { text: "Unified two-step một mạng: 27,50 / 0,850 nội bộ; thắng hai mạng external cả 3 bộ", bullet: true }, + { text: "Uformer/LeWin xoá định luật drift: 5 chu kỳ, best == final", bullet: true }, + { text: "Head full-res train-chung an toàn OOD; refiner tách rời thì không", bullet: true }, + { text: "Identity ảnh sạch 27,8 → 40,4 dB (cặp identity)", bullet: true }, + { text: "Phase-1: OOD/null detection thật (55–60/60), honest-null; conditioning đáng ~0,5 dB, tập trung ở haze", bullet: true }, + { text: "Bảy định luật vận hành có số đo (drift, chain, vị trí dung lượng, ablation null, SGDR, identity phân phối, trần thông tin)", bullet: true }, + ], L + 0.25, 2.45, 5.3, 2.95, { size: 11, gap: 7 }); + panel(s, 6.78, 2.0, 5.8, 3.5, { barColor: FAINT }); + label(s, "HẠN CHẾ · BƯỚC TIẾP", 7.03, 2.18, 5.3); + body(s, [ + { text: "1 seed; noise val n = 19 (1 scene); chưa test mixed degradation; unseen degradation mới có detection, chưa có restoration", bullet: true }, + { text: "Khái niệm noise của Phase-1 lệch (SIDD noise thật → rain 0,58); hai lần sửa bằng augmentation đều âm tính — giới hạn 8 scene", bullet: true }, + { text: "Tiếp: identity pairs từ ảnh sạch tối/có vân thật ở trunk; prune plug chết (content/spatial inject, MoE bank)", bullet: true }, + { text: "Tiếp: seed 43/44 cho chu kỳ cuối; benchmark công khai để so AirNet / PromptIR / DA-CLIP", bullet: true }, + { text: "Câu hỏi mở: Phase-1 from scratch có cần cho trunk không — control mới trả lời cho trường hợp warm-start", bullet: true }, + ], 7.03, 2.45, 5.3, 2.95, { size: 11, gap: 7 }); +} + +pres.writeFile({ fileName: path.join(__dirname, "SCDC_Final_Deck.pptx") }).then(f => console.log("wrote", f)); diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/__init__.py b/dataset/phase1_noise_20260906/trial_code_staging/src/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/__pycache__/__init__.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52acd907e0bacaef413544254bef6a40c1e3ac4f Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/__pycache__/__init__.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/__init__.py b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/__init__.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43a8caaf32e646fa61016bb78dd9a3b9b746a2c6 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/__init__.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/clean_relative.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/clean_relative.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a13bf349ef51ea98ea982161fffbd4b7e2f6eb78 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/clean_relative.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/noise_sampling.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/noise_sampling.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc6b78f89d8434d93f54b5e932aec216eeb842c5 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/noise_sampling.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/phase1_v2.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/phase1_v2.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0298670a26c3304a070d2db069d1980332c0a590 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/phase1_v2.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/rain13k_resized.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/rain13k_resized.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94e136b6d163c625ccb148d57d163e51c05e3617 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/data/__pycache__/rain13k_resized.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/clean_relative.py b/dataset/phase1_noise_20260906/trial_code_staging/src/data/clean_relative.py new file mode 100644 index 0000000000000000000000000000000000000000..f571c15d2d63f1ea22a24fd5a6a2c206fbf6b723 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/data/clean_relative.py @@ -0,0 +1,406 @@ +"""Uncapped paired data and explicitly approximate, controlled interventions. + +Physical parameters are ground truth ONLY for the synthetic controls below. +Real datasets supply type/pair supervision, never invented physical labels. +All image crops are native-resolution; small images are padded, not resized. +Manifest v1 remains readable; explicit online noise requires manifest v2 so +older loaders reject these records instead of misreading them as clean pairs. +""" + +from __future__ import annotations + +import hashlib +import io +import json +import math +from pathlib import Path +import random +from typing import Any, Mapping, Sequence + +import numpy as np +from PIL import Image +import torch +import torch.nn.functional as F +from torch.utils.data import Dataset + + +TYPES = ("rain", "noise", "haze", "lowlight", "snow", "blur", "jpeg") +TYPE_ORDER = TYPES +IMAGE_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png", ".bmp", ".tif", ".tiff", ".webp"}) +NOISE_PROFILES = ("gaussian", "signal_dependent_gaussian") + + +def validate_noise_record(record: Mapping[str, Any]) -> None: + """Validate the versioned explicit-noise manifest contract, not old controls. + + sigma is read-noise standard deviation and shot is the square root of the + signal-dependent variance slope, both in normalized RGB units. This is a + Gaussian approximation in RGB, not a claim to simulate the RAW camera ISP. + """ + if record.get("type") != "noise" or record.get("noise_profile") not in NOISE_PROFILES: + raise ValueError("Explicit noise requires type=noise and a known noise profile") + if record.get("noise_synthesis_version") != 1: + raise ValueError("Explicit noise requires noise_synthesis_version=1") + params = record.get("noise_parameters") + if not isinstance(params, dict) or set(params) != {"severity", "sigma", "shot", "noise_seed"}: + raise ValueError("Explicit noise parameters require exactly severity, sigma, shot, noise_seed") + for name in ("severity", "sigma", "shot"): + value = params[name] + if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value): + raise ValueError(f"Explicit noise {name} must be finite numeric") + if not 0 <= value <= 1: + raise ValueError(f"Explicit noise {name} must lie in [0,1]") + if params["severity"] <= 0 or params["sigma"] ** 2 + params["shot"] ** 2 <= 0: + raise ValueError("Explicit noise must have positive dose and variance") + seed = params["noise_seed"] + if isinstance(seed, bool) or not isinstance(seed, int) or not 0 <= seed < 2 ** 31: + raise ValueError("Explicit noise_seed must be an integer in [0,2**31)") + if ((record["noise_profile"] == "gaussian" and params["shot"] != 0) + or (record["noise_profile"] == "signal_dependent_gaussian" and params["shot"] <= 0)): + raise ValueError("Explicit noise profile disagrees with signal-dependent variance") + if record.get("clean") != record.get("degraded"): + raise ValueError("Explicit noise stores only one clean source path; synthesize after cropping") + + +def image_files(directory: Path) -> list[Path]: + if not directory.is_dir(): + raise FileNotFoundError(f"Missing image directory: {directory}") + return sorted(p for p in directory.rglob("*") if p.is_file() and p.suffix.lower() in IMAGE_EXTENSIONS) + + +def discover_exact_pairs(degraded_dir: Path, clean_dir: Path) -> list[tuple[Path, Path]]: + """Require a bijection by relative filename; unmatched targets also fail.""" + inputs = {p.relative_to(degraded_dir).as_posix(): p for p in image_files(degraded_dir)} + targets = {p.relative_to(clean_dir).as_posix(): p for p in image_files(clean_dir)} + if set(inputs) != set(targets): + raise ValueError( + f"pairing mismatch: {degraded_dir} / {clean_dir}; " + f"missing clean={sorted(set(inputs) - set(targets))[:10]}, " + f"missing degraded={sorted(set(targets) - set(inputs))[:10]}" + ) + if not inputs: + raise ValueError(f"No image pairs: {degraded_dir}") + return [(inputs[name], targets[name]) for name in sorted(inputs)] + + +def isolate_splits(splits: Mapping[str, Sequence[dict]]) -> tuple[dict[str, list[dict]], list[dict]]: + """Exclude lower-priority overlapping content/groups, including transitivity. + + A connected component links decoded-identical clean images and a dataset's + scene/group. Locked test wins over validation, which wins over training. + Different degradations of the same clean within ONE split are retained. + """ + parent: dict[str, str] = {} + + def find(key: str) -> str: + parent.setdefault(key, key) + while parent[key] != key: + parent[key] = parent[parent[key]] + key = parent[key] + return key + + def union(a: str, b: str) -> None: + first, second = find(a), find(b) + if first != second: + parent[first] = second + + def keys(record: dict) -> tuple[str, str]: + content = record.get("clean_content_sha256") + if not content: + raise ValueError(f"Missing clean content hash: {record.get('id')}") + return (f"content:{content}", f"group:{record['dataset']}:{record['group']}") + + for split in ("train", "val", "test"): + for record in splits.get(split, []): + union(*keys(record)) + priority = {"train": 0, "val": 1, "test": 2} + winner: dict[str, str] = {} + for split in priority: + for record in splits.get(split, []): + component = find(keys(record)[0]) + if priority[split] > priority.get(winner.get(component, ""), -1): + winner[component] = split + kept = {split: [] for split in priority} + excluded = [] + for split in priority: + for record in splits.get(split, []): + retained_split = winner[find(keys(record)[0])] + if retained_split == split: + kept[split].append(record) + else: + excluded.append({**record, "original_split": split, "protected_split": retained_split, + "reason": "cross_split_content_or_group_overlap"}) + return kept, excluded + + +def validate_manifest(manifest: Mapping[str, Any], *, require_all_types: bool = False) -> dict: + version = manifest.get("schema_version") + if version not in (1, 2) or tuple(manifest.get("types", ())) != TYPES: + raise ValueError("Manifest schema_version=1 or 2 and canonical seven-type order are required") + seen_ids: set[str] = set() + content_splits: dict[str, str] = {} + group_splits: dict[tuple[str, str], str] = {} + counts = {} + for split in ("train", "val", "test"): + records = manifest.get(split) + if not isinstance(records, list): + raise ValueError(f"Manifest {split} must be a list") + counts[split] = {kind: 0 for kind in TYPES} + for record in records: + for required in ("id", "clean", "degraded", "type", "dataset", "group", "clean_content_sha256"): + if required not in record or record[required] in (None, ""): + raise ValueError(f"Manifest record missing {required}: {record}") + if record["type"] not in TYPES: + raise ValueError(f"Unknown degradation type {record['type']}") + synthesis = record.get("synthesis") + if synthesis not in (None, "jpeg", "noise"): + raise ValueError(f"Unknown manifest synthesis {synthesis!r}") + if synthesis == "jpeg" and record["type"] != "jpeg": + raise ValueError("JPEG synthesis requires type=jpeg") + if synthesis == "noise": + if version != 2: + raise ValueError("Explicit noise synthesis requires manifest schema_version=2") + validate_noise_record(record) + if record["id"] in seen_ids: + raise ValueError(f"Duplicate record id {record['id']}") + seen_ids.add(record["id"]) + content = record["clean_content_sha256"] + group = (record["dataset"], record["group"]) + if content_splits.setdefault(content, split) != split or group_splits.setdefault(group, split) != split: + raise ValueError(f"Cross-split content/group leakage at {record['id']}") + counts[split][record["type"]] += 1 + if require_all_types and split in ("train", "val") and any(counts[split][kind] == 0 for kind in TYPES): + raise ValueError(f"Every type must be represented in {split}: {counts[split]}") + return counts + + +def _seed_from(*parts: Any) -> int: + value = "\0".join(str(p) for p in parts) + return int.from_bytes(hashlib.sha256(value.encode()).digest()[:8], "big") % (2 ** 31) + + +class PairedDegradationDataset(Dataset): + """One item per record; an explicit (index, visit) requests a repeated view. + + Integer indices and visit zero preserve the previous crop and synthesis + sequence exactly. Sampling/replacement decisions belong to the trainer. + """ + + def __init__(self, manifest_path: str | Path | Mapping[str, Any], split: str = "train", + crop_size: int = 128, seed: int = 42): + manifest = (dict(manifest_path) if isinstance(manifest_path, Mapping) + else json.loads(Path(manifest_path).read_text())) + validate_manifest(manifest) + if split not in ("train", "val", "test"): + raise ValueError(f"Unknown split {split}") + if crop_size <= 0: + raise ValueError("crop_size must be positive") + self.records = manifest[split] + self.split, self.crop_size, self.seed, self.epoch = split, crop_size, seed, 0 + + def set_epoch(self, epoch: int) -> None: + # Call before creating each epoch's iterator; persistent workers must + # be disabled unless the caller propagates this state to its workers. + self.epoch = int(epoch) + + def __len__(self) -> int: + return len(self.records) + + @staticmethod + def _read(path: str) -> torch.Tensor: + with Image.open(path) as image: + array = np.array(image.convert("RGB"), dtype=np.uint8, copy=True) + return torch.from_numpy(array).permute(2, 0, 1).float().div_(255.) + + def __getitem__(self, index: int | tuple[int, int]) -> dict[str, Any]: + visit = 0 + if isinstance(index, tuple): + if len(index) != 2: + raise ValueError("Expected (record_index, visit) sampler entry") + index, visit = index + if type(visit) is not int or visit < 0: + raise ValueError("Sampler visit must be a nonnegative integer") + if visit > 0 and self.split != "train": + raise ValueError("Positive sampler visits are restricted to training") + record = self.records[index] + clean = self._read(record["clean"]) + degraded = clean.clone() if record.get("synthesis") in ("jpeg", "noise") else self._read(record["degraded"]) + if degraded.shape != clean.shape: + raise ValueError(f"Unaligned pair shapes at {record['id']}: {degraded.shape} vs {clean.shape}") + side = self.crop_size + height, width = clean.shape[-2:] + pad = (0, max(0, side - width), 0, max(0, side - height)) + if any(pad): + clean, degraded = F.pad(clean, pad, mode="replicate"), F.pad(degraded, pad, mode="replicate") + height, width = clean.shape[-2:] + rng = random.Random(_seed_from(self.seed, self.epoch if self.split == "train" else 0, record["id"])) + top = rng.randrange(height - side + 1) if self.split == "train" else (height - side) // 2 + left = rng.randrange(width - side + 1) if self.split == "train" else (width - side) // 2 + view_positions = (height - side + 1) * (width - side + 1) + if visit > 0: + # Traverse native crop positions without repetition until exhausted; + # then invert the horizontal augmentation for a second traversal. + # This remains deterministic after worker-prefetch/resume and never + # resizes an image. Constant/symmetric images may look identical. + stride = 1 + _seed_from(self.seed, self.epoch, record["id"], "noise_visit_v1") % view_positions + while math.gcd(stride, view_positions) != 1: + stride += 1 + position = (top * (width - side + 1) + left + visit * stride) % view_positions + top, left = divmod(position, width - side + 1) + clean = clean[:, top:top + side, left:left + side].contiguous() + degraded = degraded[:, top:top + side, left:left + side].contiguous() + label = TYPES.index(record["type"]) + severity = torch.zeros(len(TYPES)) + severity_mask = torch.zeros(len(TYPES), dtype=torch.bool) + if record.get("synthesis") == "jpeg": + epoch = self.epoch if self.split == "train" else 0 + params = sample_degradation_parameters("jpeg", _seed_from(self.seed, epoch, record["id"], "jpeg")) + degraded, params = synthesize_degradation(clean, "jpeg", params) + severity[label], severity_mask[label] = params["severity"], True + elif record.get("synthesis") == "noise": + params = dict(record["noise_parameters"]) + # The manifest seed replays evaluation independently of loader seed. + # Training changes only realization by epoch, never physical dose. + if self.split == "train": + params["noise_seed"] = _seed_from(params["noise_seed"], record["id"], self.epoch, "noise_v1") + if visit > 0: + params["noise_seed"] = _seed_from(params["noise_seed"], visit, "noise_visit_v1") + degraded, params = synthesize_degradation(clean, "noise", params) + severity[label], severity_mask[label] = params["severity"], True + flip = self.split == "train" and rng.random() < .5 + if visit > 0: + flip ^= bool((visit // view_positions) % 2) + if flip: + clean, degraded = clean.flip(-1), degraded.flip(-1) + presence = torch.zeros(len(TYPES)) + presence[label] = 1. + return {"clean": clean, "degraded": degraded, "label": torch.tensor(label, dtype=torch.long), + "presence": presence, "severity": severity, "severity_mask": severity_mask, + "record_id": record["id"], "group": record["group"], "dataset": record["dataset"], + "index": index, "type": record["type"]} + + +def sample_degradation_parameters(kind: str, seed: int = 0, heldout: bool = False) -> dict[str, Any]: + """Train strengths [.08,.70]; extrapolation strengths [.80,.98]. + + These approximate controls are not a claim to simulate all real examples. + JPEG's physical quality is integer 1..100, inverse to normalized severity. + """ + if kind not in TYPES: + raise ValueError(f"Unknown degradation {kind}") + rng = random.Random(seed) + severity = rng.uniform(.80, .98) if heldout else rng.uniform(.08, .70) + common = {"severity": severity} + if kind == "noise": + return {**common, "sigma": .12 * severity, "shot": .04 * severity, + "noise_seed": rng.randrange(2 ** 31)} + if kind == "haze": + return {**common, "transmission": 1. - .90 * severity, + "airlight": [rng.uniform(.7, 1.) for _ in range(3)]} + if kind == "lowlight": + return {**common, "gain": math.exp(-2.5 * severity), "gamma": 1. + .8 * severity} + if kind == "blur": + return {**common, "length": max(1, int(round(1. + 24. * severity))), "angle": rng.uniform(0., 180.)} + if kind == "rain": + return {**common, "density": .003 + .025 * severity, "opacity": .15 + .75 * severity, + "length": max(3, int(round(3. + 24. * severity))), "angle": rng.uniform(55., 125.), + "noise_seed": rng.randrange(2 ** 31)} + if kind == "snow": + return {**common, "density": .0005 + .008 * severity, "opacity": .2 + .75 * severity, + "radius": max(1, int(round(1. + 3. * severity))), "noise_seed": rng.randrange(2 ** 31)} + quality = max(1, min(100, int(round(100. - 95. * severity)))) + return {"severity": (100. - quality) / 95., "quality": quality} + + +def _line_kernel(length: int, angle: float, device: torch.device, dtype: torch.dtype) -> torch.Tensor: + size = max(1, int(length)) + size += 1 - size % 2 + kernel = torch.zeros(size, size, device=device, dtype=dtype) + radius = (size - 1) / 2 + steps = torch.linspace(-radius, radius, max(1, size * 4), device=device) + radians = math.radians(angle) + xx = (radius + steps * math.cos(radians)).round().long().clamp(0, size - 1) + yy = (radius + steps * math.sin(radians)).round().long().clamp(0, size - 1) + kernel[yy, xx] = 1. + return kernel / kernel.sum() + + +def _filter(image: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor: + channels = image.shape[0] + pad = kernel.shape[-1] // 2 + padded = F.pad(image.unsqueeze(0), (pad, pad, pad, pad), mode="replicate") + return F.conv2d(padded, kernel[None, None].expand(channels, 1, -1, -1), groups=channels)[0] + + +def synthesize_degradation(clean: torch.Tensor, kind: str, + parameters: Mapping[str, Any] | None = None, seed: int = 0, + heldout: bool = False) -> tuple[torch.Tensor, dict[str, Any]]: + """Apply one controlled CHW float-image operation without altering parameters. + + Seeds are embedded in sampled stochastic parameters, so parameter transfer + preserves both physical settings and realization for same-shaped images. + JPEG is an actual Pillow JPEG encode/decode, not a differentiable surrogate. + """ + if kind not in TYPES or clean.ndim != 3 or clean.shape[0] != 3: + raise ValueError("Expected canonical degradation and RGB CHW image") + if not torch.is_floating_point(clean): + raise ValueError("clean must be floating point in [0,1]") + params = dict(parameters) if parameters is not None else sample_degradation_parameters(kind, seed, heldout) + if "severity" not in params or not 0. <= float(params["severity"]) <= 1.: + raise ValueError("parameters require severity in [0,1]") + if kind == "jpeg" and (not isinstance(params.get("quality"), int) or not 1 <= params["quality"] <= 100): + raise ValueError("JPEG quality must be an integer in [1,100]") + if float(params["severity"]) == 0.: + return clean.clone(), params + if kind in ("noise", "rain", "snow"): + if "noise_seed" not in params: + raise ValueError("Stochastic parameters require noise_seed for repeatable transfer") + generator = torch.Generator(device=clean.device).manual_seed(int(params["noise_seed"])) + if kind == "noise": + field = torch.randn(clean.shape, generator=generator, device=clean.device, dtype=clean.dtype) + result = clean + field * torch.sqrt(float(params["sigma"]) ** 2 + float(params.get("shot", 0.)) ** 2 * clean.clamp_min(0)) + elif kind == "haze": + transmission = float(params["transmission"]) + airlight = clean.new_tensor(params["airlight"]).reshape(3, 1, 1) + result = transmission * clean + (1. - transmission) * airlight + elif kind == "lowlight": + result = float(params["gain"]) * clean.clamp_min(0).pow(float(params["gamma"])) + elif kind == "blur": + result = _filter(clean, _line_kernel(int(params["length"]), float(params["angle"]), clean.device, clean.dtype)) + elif kind == "rain": + field = (torch.rand((1, *clean.shape[-2:]), generator=generator, device=clean.device) < float(params["density"])).to(clean.dtype) + kernel = _line_kernel(int(params["length"]), float(params["angle"]), clean.device, clean.dtype) + streaks = (_filter(field, kernel) * int(params["length"])).clamp(0, 1) + result = clean + float(params["opacity"]) * streaks + elif kind == "snow": + field = (torch.rand((1, *clean.shape[-2:]), generator=generator, device=clean.device) < float(params["density"])).to(clean.dtype) + radius = int(params["radius"]) + axis = torch.arange(-radius, radius + 1, device=clean.device, dtype=clean.dtype) + yy, xx = torch.meshgrid(axis, axis, indexing="ij") + kernel = torch.exp(-(xx.square() + yy.square()) / max(.5, radius ** 2 / 2.)) + alpha = (float(params["opacity"]) * _filter(field, kernel)).clamp(0, 1) + result = clean * (1. - alpha) + alpha + else: + source = (clean.detach().cpu().clamp(0, 1).permute(1, 2, 0).numpy() * 255.).round().astype(np.uint8) + buffer = io.BytesIO() + Image.fromarray(source).save(buffer, format="JPEG", quality=params["quality"], subsampling=2) + buffer.seek(0) + with Image.open(buffer) as image: + array = np.array(image.convert("RGB"), copy=True) + result = torch.from_numpy(array).permute(2, 0, 1).to(device=clean.device, dtype=clean.dtype) / 255. + return result.clamp(0., 1.), params + + +def synthesize_composition(clean: torch.Tensor, types: Sequence[str], + parameters: Sequence[Mapping[str, Any]] | None = None, + seed: int = 0, heldout: bool = False) -> tuple[torch.Tensor, list[dict[str, Any]]]: + """Apply types left-to-right: ['noise','haze'] means haze(noise(clean)).""" + if parameters is not None and len(parameters) != len(types): + raise ValueError("One parameter dictionary is required per composition step") + image = clean + used = [] + for index, kind in enumerate(types): + params = None if parameters is None else parameters[index] + image, actual = synthesize_degradation(image, kind, params, _seed_from(seed, index, kind), heldout) + used.append(actual) + return image, used diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/folder_crops.py b/dataset/phase1_noise_20260906/trial_code_staging/src/data/folder_crops.py new file mode 100644 index 0000000000000000000000000000000000000000..8e737b765d3e70a7ba929a680106bfab4abd1ce3 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/data/folder_crops.py @@ -0,0 +1,104 @@ +"""Square crops from a flat folder of images (no labels, no pairs). + +Used for the real-unknown pool (Snow100K synthetic snow) and the extra clean +pool (Snow100K gt) in Phase-1 v5, and for exposure-diverse identity pairs in +Phase-2 v8. Deterministic per (seed, epoch, index) so plans replay exactly. +""" + +from __future__ import annotations + +import math +import random +from pathlib import Path +from typing import Dict, Iterator, List, Sequence, Union + +import numpy as np +import torch +from PIL import Image +from torch.utils.data import DataLoader, Dataset + +_IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png", ".bmp") +_LANCZOS = getattr(getattr(Image, "Resampling", Image), "LANCZOS") +_FLIP = getattr(getattr(Image, "Transpose", Image), "FLIP_LEFT_RIGHT") + + +def list_image_files(root: Union[str, Path]) -> List[Path]: + root = Path(root) + if not root.is_dir(): + raise FileNotFoundError("image folder not found: %s" % root) + return sorted(p for p in root.rglob("*") if p.suffix.lower() in _IMAGE_SUFFIXES) + + +def _to_tensor(image: Image.Image) -> torch.Tensor: + array = np.asarray(image, dtype=np.float32) / 255.0 + return torch.from_numpy(array).permute(2, 0, 1).contiguous() + + +class FolderCropDataset(Dataset): + """Random (or centre) ``size`` crops; ``return_full`` adds the aspect- + squashed whole frame the way Phase2PairDataset does for global context.""" + + def __init__( + self, + files: Sequence[Union[str, Path]], + size: int, + seed: int = 0, + deterministic: bool = False, + return_full: bool = False, + ) -> None: + if not files: + raise ValueError("FolderCropDataset requires at least one file") + self.files = [Path(f) for f in files] + self.size = int(size) + self.seed = int(seed) + self.deterministic = bool(deterministic) + self.return_full = bool(return_full) + self.epoch = 0 + + def __len__(self) -> int: + return len(self.files) + + def _open(self, index: int) -> Image.Image: + with Image.open(self.files[index]) as handle: + image = handle.convert("RGB") + width, height = image.size + if min(width, height) < self.size: + scale = self.size / min(width, height) + image = image.resize( + (max(self.size, int(math.ceil(width * scale))), + max(self.size, int(math.ceil(height * scale)))), + _LANCZOS, + ) + return image + + def __getitem__(self, index: int): + image = self._open(index) + width, height = image.size + if self.deterministic: + left, top, flip = (width - self.size) // 2, (height - self.size) // 2, False + else: + rng = random.Random((self.seed * 1000003 + self.epoch * 7919 + index) % (2 ** 63 - 1)) + left = rng.randrange(width - self.size + 1) + top = rng.randrange(height - self.size + 1) + flip = bool(rng.getrandbits(1)) + crop = image.crop((left, top, left + self.size, top + self.size)) + if flip: + crop = crop.transpose(_FLIP) + if not self.return_full: + return _to_tensor(crop) + full = image.resize((self.size, self.size), _LANCZOS) + if flip: + full = full.transpose(_FLIP) + return {"crop": _to_tensor(crop), "full": _to_tensor(full)} + + +def infinite_batches(loader: DataLoader) -> Iterator: + """Cycle a loader forever, bumping ``dataset.epoch`` so crops re-randomise.""" + epoch = 0 + while True: + dataset = getattr(loader, "dataset", None) + if dataset is not None and hasattr(dataset, "epoch"): + dataset.epoch = epoch + for batch in loader: + yield batch + epoch += 1 diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/noise_sampling.py b/dataset/phase1_noise_20260906/trial_code_staging/src/data/noise_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..c0501427effea3dccf999e521da28b5cb2d9364f --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/data/noise_sampling.py @@ -0,0 +1,147 @@ +"""Deterministic noise-only draw balance without changing domain exposure. + +Uniform mode is the original epoch permutation. Balanced mode keeps every +non-noise record and noise slot at its original position, replacing only noise +IDs from independently shuffled cyclic real/synthetic queues. Cycles continue +across rounds; a queue-cycle visit identifies repeated views reproducibly. +""" + +from __future__ import annotations + +from collections import Counter +import hashlib +import json +from typing import Sequence + +import torch + +from src.data.clean_relative import _seed_from + +SAMPLING_VERSION = 1 + + +class NoiseSamplingPlan: + """A stateless-by-round replay plan; cached permutations are only an optimization.""" + + def __init__(self, records: Sequence[dict], selected: Sequence[int], seed: int, + mode: str = "uniform"): + if mode not in ("uniform", "balanced"): + raise ValueError(f"Unknown noise sampling mode {mode!r}") + self.records, self.selected, self.seed, self.mode = records, list(selected), seed, mode + if (len(set(self.selected)) != len(self.selected) + or any(type(i) is not int or not 0 <= i < len(records) for i in self.selected)): + raise ValueError("Selected record indices must be unique and in range") + if mode == "balanced" and set(self.selected) != set(range(len(records))): + raise ValueError("Balanced sampling requires all manifest records; selected caps are forbidden") + self.real = [i for i in self.selected if records[i]["type"] == "noise" and not records[i].get("synthesis")] + self.synthetic = [i for i in self.selected if records[i]["type"] == "noise" and records[i].get("synthesis") == "noise"] + self.noise_count = len(self.real) + len(self.synthetic) + if any(records[i]["type"] == "noise" and records[i].get("synthesis") not in (None, "noise") for i in self.selected): + raise ValueError("Noise records require real pairs or explicit noise synthesis") + if mode == "balanced" and (not self.real or not self.synthetic): + raise ValueError("Balanced sampling requires both real and synthetic noise records") + self._permutations: dict[tuple[str, int], list[int]] = {} + + def _quota(self, epoch: int) -> tuple[int, int]: + half, odd = divmod(self.noise_count, 2) + real = half + (odd if epoch % 2 == 0 else 0) + return real, self.noise_count - real + + def _draws_before(self, epoch: int) -> tuple[int, int]: + half, odd = divmod(self.noise_count, 2) + return epoch * half + ((epoch + 1) // 2) * odd, epoch * half + (epoch // 2) * odd + + def _queue(self, role: str, offset: int, count: int) -> list[tuple[int, int]]: + source = self.real if role == "real" else self.synthetic + result = [] + while count: + cycle, position = divmod(offset, len(source)) + key = (role, cycle) + if key not in self._permutations: + generator = torch.Generator().manual_seed(_seed_from(self.seed, "noise_queue_v1", role, cycle)) + order = torch.randperm(len(source), generator=generator).tolist() + self._permutations[key] = [source[i] for i in order] + amount = min(count, len(source) - position) + result.extend((i, cycle) for i in self._permutations[key][position:position + amount]) + count -= amount + offset += amount + return result + + def round_indices(self, epoch: int, start: int = 0) -> list[int | tuple[int, int]]: + if type(epoch) is not int or epoch < 0 or type(start) is not int or not 0 <= start <= len(self.selected): + raise ValueError("Invalid noise sampling round or consumed-draw cursor") + # Deliberately identical to the previous trainer's epoch_indices. + generator = torch.Generator().manual_seed(self.seed + epoch * 1_000_003) + order = [self.selected[i] for i in torch.randperm(len(self.selected), generator=generator).tolist()] + if self.mode == "uniform": + return order[start:] + real_quota, synthetic_quota = self._quota(epoch) + real_before, synthetic_before = self._draws_before(epoch) + real_queue = iter(self._queue("real", real_before, real_quota)) + synthetic_queue = iter(self._queue("synthetic", synthetic_before, synthetic_quota)) + slots = [True] * real_quota + [False] * synthetic_quota + generator = torch.Generator().manual_seed(_seed_from(self.seed, "noise_slots_v1", epoch)) + slot_order = iter(slots[i] for i in torch.randperm(self.noise_count, generator=generator).tolist()) + result: list[int | tuple[int, int]] = [] + for original in order: + if self.records[original]["type"] != "noise": + result.append(original) + else: + result.append(next(real_queue) if next(slot_order) else next(synthetic_queue)) + return result[start:] + + def _exposure(self, indices: Sequence[int]) -> dict: + unique = set(indices) + counts_by_type, by_source, by_profile, by_group = Counter(), Counter(), Counter(), Counter() + real, synthetic = [], [] + for index in indices: + row = self.records[index] + counts_by_type[row["type"]] += 1 + if row["type"] != "noise": + continue + by_source[row.get("noise_source", row["dataset"])] += 1 + if row.get("synthesis") == "noise": + synthetic.append(index) + by_profile[row["noise_profile"]] += 1 + else: + real.append(index) + by_group[json.dumps([row["dataset"], row["group"]])] += 1 + return {"draws": len(indices), "unique_records": len(unique), "expected_records": len(self.selected), + "all_selected_records_visited": unique == set(self.selected), + "draws_by_type": dict(counts_by_type), + "noise": {"real_draws": len(real), "synthetic_draws": len(synthetic), + "real_unique_records": len(set(real)), "synthetic_unique_records": len(set(synthetic)), + "draws_by_source": dict(by_source), "synthetic_draws_by_profile": dict(by_profile), + "real_draws_by_scene_or_source_group": dict(by_group)}} + + def coverage(self, epoch: int, cursor: int) -> dict: + """Reconstruct only consumed draws, including a partial resumed round. + + epoch is the number of previously completed rounds; cursor counts draws + in the current round. A full-round cursor is also accepted pre-increment. + """ + if type(cursor) is not int or not 0 <= cursor <= len(self.selected): + raise ValueError("Invalid consumed-draw coverage cursor") + current = self.round_indices(epoch)[:cursor] + prior = [item for previous in range(epoch) for item in self.round_indices(previous)] + underlying = lambda item: item[0] if isinstance(item, tuple) else item # noqa: E731 + current_ids = [underlying(item) for item in current] + cumulative = self._exposure([underlying(item) for item in prior] + current_ids) + return {"version": SAMPLING_VERSION, "mode": self.mode, "completed_rounds": epoch, + "current_round_draws": cursor, "round": self._exposure(current_ids), "cumulative": cumulative, + "cumulative_unique_records": cumulative["unique_records"], + "all_selected_covered": cumulative["all_selected_records_visited"], + "all_manifest_records_covered": cumulative["unique_records"] == len(self.records)} + + def describe(self, rounds: int) -> dict: + return {"version": SAMPLING_VERSION, "mode": self.mode, "draws_per_round": len(self.selected), + "real_noise_records": len(self.real), "synthetic_noise_records": len(self.synthetic), + "selected_ids_sha256": hashlib.sha256(json.dumps([self.records[i]["id"] for i in self.selected]).encode()).hexdigest(), + "planned_noise_quotas": [dict(zip(("real", "synthetic"), self._quota(epoch))) + if self.mode == "balanced" else {"real": len(self.real), "synthetic": len(self.synthetic)} + for epoch in range(rounds)], + "queue_policy": ("not used: original permutation without replacement" if self.mode == "uniform" + else "independent shuffled cyclic real/synthetic queues continuing across rounds"), + "view_policy": ("legacy integer-index views unchanged" if self.mode == "uniform" + else "visit0=legacy; positive queue-cycle visits use noise_visit_v1 native-view traversal and noise seeds"), + "scope": "noise real/synthetic exposure only; original domain slot positions and class loss weights unchanged"} diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/phase1_v2.py b/dataset/phase1_noise_20260906/trial_code_staging/src/data/phase1_v2.py new file mode 100644 index 0000000000000000000000000000000000000000..ce282bdb6d6df872357df0f6c2230d06ea117b4a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/data/phase1_v2.py @@ -0,0 +1,928 @@ +"""Deterministic data generation for the corrected Phase 1 pilot. + +The module separates source splitting, crop selection, and degradation sampling. +Every decision is derived from stable SHA256 keys, so manifests and generated +samples can be reconstructed without relying on process-global random state. + +Combo names use underscores in place of the composition symbol. Regardless of +name, operators are always applied in camera order: blur, low-light, noise, +then JPEG. +""" + +from __future__ import annotations + +import hashlib +import io +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import asdict, dataclass +from functools import cache +from pathlib import Path +from typing import Any, Dict, List, Literal, Optional, Tuple + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image +from torch.utils.data import Dataset + +Mode = Literal["support", "validation_gap", "locked"] + +# Canonical order for every degradation vector, classifier head, cache, and +# metric. Keep the legacy aliases because existing callers import them. +TYPE_ORDER: Tuple[str, ...] = ("blur", "lowlight", "noise", "jpeg") +DEGRADATIONS: Tuple[str, ...] = TYPE_ORDER +PHYSICAL_ORDER: Tuple[str, ...] = TYPE_ORDER + +# N_B means the set {noise, blur}; the tuple records actual application order. +TRAIN_COMBINATIONS: Dict[str, Tuple[str, ...]] = { + "N_B": ("blur", "noise"), + "N_L": ("lowlight", "noise"), + "B_J": ("blur", "jpeg"), + "L_J": ("lowlight", "jpeg"), +} +UNSEEN_COMBINATIONS: Dict[str, Tuple[str, ...]] = { + "N_J": ("noise", "jpeg"), + "B_L": ("blur", "lowlight"), + "N_B_L": ("blur", "lowlight", "noise"), +} + +# Values are physical operator parameters, not normalized labels. +SEVERITY_RANGES: Dict[str, Dict[str, Any]] = { + "noise": { + "train": (10.0, 50.0), + "gap": (25.0, 35.0), + "extrap": 70.0, + "discrete": False, + }, + "blur": { + "train": (0.8, 2.4), + "gap": (1.4, 1.8), + "extrap": 3.0, + "discrete": False, + }, + "lowlight": { + "train": (1.5, 3.0), + "gap": (2.0, 2.4), + "extrap": 3.5, + "discrete": False, + }, + "jpeg": { + "train": (10, 50), + "gap": (25, 35), + "extrap": 5, + "discrete": True, + }, +} + + +@dataclass(frozen=True) +class CropRecord: + """A serializable, deterministic crop from one clean source image.""" + + source_dataset: str + source_id: str + source_path: str + source_sha256: str + split: Literal["train", "val", "test"] + crop_index: int + top: int + left: int + size: int = 256 + + @property + def crop_id(self) -> str: + """Return the stable identifier used to join crops and sample specs.""" + + return f"{self.split}:{self.source_id}:{self.crop_index}" + + def to_dict(self) -> Dict[str, Any]: + """Return a JSON-compatible dictionary.""" + + return asdict(self) + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> "CropRecord": + """Reconstruct a crop record from :meth:`to_dict` output.""" + + return cls(**dict(value)) + + +@dataclass(frozen=True) +class SampleSpec: + """Serializable instructions for generating one degraded sample. + + ``components``, ``physical_values``, and ``severities`` share the same + order. For compositions, ``component_indices`` points to single-degradation + specs with the same crop and physical parameter. + """ + + sample_index: int + crop_id: str + source_id: str + split: Literal["train", "val", "test"] + mode: Mode + degradation: str + regime: str + components: Tuple[str, ...] + physical_values: Tuple[float, ...] + severities: Tuple[float, ...] + component_indices: Tuple[int, ...] = () + noise_seed: Optional[int] = None + + @property + def is_composition(self) -> bool: + """Whether this sample contains more than one degradation.""" + + return len(self.components) > 1 + + def to_dict(self) -> Dict[str, Any]: + """Return a JSON-compatible dictionary.""" + + value = asdict(self) + value["components"] = list(self.components) + value["physical_values"] = list(self.physical_values) + value["severities"] = list(self.severities) + value["component_indices"] = list(self.component_indices) + return value + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> "SampleSpec": + """Reconstruct a sample spec from :meth:`to_dict` output.""" + + data = dict(value) + for name in ( + "components", + "physical_values", + "severities", + "component_indices", + ): + data[name] = tuple(data.get(name, ())) + return cls(**data) + + +def _digest_int(key: str) -> int: + return int.from_bytes(hashlib.sha256(key.encode("utf-8")).digest()[:8], "big") + + +def _unit_interval(key: str) -> float: + # Midpoints avoid ever sampling an inclusive gap boundary. + return (_digest_int(key) + 0.5) / float(2**64) + + +def _find_div2k_dir(data_root: Path, directory_name: str) -> Path: + candidates = ( + data_root / directory_name, + data_root / "div2k" / directory_name, + ) + for candidate in candidates: + if candidate.is_dir(): + return candidate + raise FileNotFoundError( + f"Could not find {directory_name} under {data_root} or {data_root / 'div2k'}" + ) + + +def _image_files(directory: Path) -> List[Path]: + suffixes = {".png", ".jpg", ".jpeg"} + files = [path for path in directory.iterdir() if path.suffix.lower() in suffixes] + if not files: + raise ValueError(f"No images found in {directory}") + return files + + +def _sha256_source_order(paths: Iterable[Path]) -> List[Path]: + return sorted( + paths, + key=lambda path: (hashlib.sha256(path.name.encode("utf-8")).digest(), path.name), + ) + + +def _crop_records( + paths: Sequence[Path], + split: Literal["train", "val", "test"], + crop_size: int, + crops_per_source: int, + seed: int, + source_hashes: Mapping[Path, str], +) -> List[CropRecord]: + records: List[CropRecord] = [] + for path in paths: + with Image.open(path) as image: + width, height = image.size + if width < crop_size or height < crop_size: + raise ValueError( + f"Source {path} is {width}x{height}, smaller than {crop_size}x{crop_size}" + ) + + source_dataset = "DIV2K" + source_id = f"{source_dataset}:{path.stem}" + for crop_index in range(crops_per_source): + prefix = f"{seed}:{path.name}:{crop_index}" + top = _digest_int(f"{prefix}:top") % (height - crop_size + 1) + left = _digest_int(f"{prefix}:left") % (width - crop_size + 1) + records.append( + CropRecord( + source_dataset=source_dataset, + source_id=source_id, + source_path=str(path.resolve()), + source_sha256=source_hashes[path], + split=split, + crop_index=crop_index, + top=top, + left=left, + size=crop_size, + ) + ) + return records + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _source_hashes(paths: Sequence[Path]) -> Dict[Path, str]: + """Hash each unique source file exactly once for manifest provenance.""" + + return {path: _sha256_file(path) for path in dict.fromkeys(paths)} + + +def _reject_cross_split_duplicate_bytes( + split_paths: Mapping[str, Sequence[Path]], source_hashes: Mapping[Path, str] +) -> None: + owners: Dict[str, Tuple[str, Path]] = {} + for split, paths in split_paths.items(): + for path in paths: + digest = source_hashes[path] + previous = owners.get(digest) + if previous is not None and previous[0] != split: + raise ValueError( + "Duplicate source bytes cross data splits: " + f"{previous[1]} ({previous[0]}) and {path} ({split})" + ) + owners.setdefault(digest, (split, path)) + + +def build_crop_manifest( + data_root: str | Path, + *, + train_cap: int = 720, + val_cap: int = 80, + test_cap: Optional[int] = None, + crop_size: int = 256, + crops_per_source: int = 4, + seed: int = 0, + include_locked: bool = True, +) -> List[CropRecord]: + """Build the source-first DIV2K train/val/test crop manifest. + + Sources in ``DIV2K_train_HR`` are ordered by SHA256 of their file names. + The first ``train_cap`` sources become train and the next ``val_cap`` become + validation. Every source in ``DIV2K_valid_HR`` is locked test data unless + ``test_cap`` is set for a smoke run. The defaults implement the 720/80 + support split and lock all 100 official validation images. + """ + + root = Path(data_root) + if train_cap < 0 or val_cap < 0: + raise ValueError("train_cap and val_cap must be non-negative") + if test_cap is not None and test_cap < 0: + raise ValueError("test_cap must be non-negative or None") + if crop_size <= 0 or crops_per_source <= 0: + raise ValueError("crop_size and crops_per_source must be positive") + + support_dir = _find_div2k_dir(root, "DIV2K_train_HR") + support_sources = _sha256_source_order(_image_files(support_dir)) + required = train_cap + val_cap + if len(support_sources) < required: + raise ValueError( + f"Need {required} DIV2K train sources, found {len(support_sources)}; " + "set smaller caps for a smoke run" + ) + + train_sources = support_sources[:train_cap] + val_sources = support_sources[train_cap:required] + locked_sources: List[Path] = [] + if include_locked: + locked_dir = _find_div2k_dir(root, "DIV2K_valid_HR") + locked_sources = _sha256_source_order(_image_files(locked_dir)) + if test_cap is not None: + locked_sources = locked_sources[:test_cap] + + hashes = _source_hashes([*train_sources, *val_sources, *locked_sources]) + _reject_cross_split_duplicate_bytes( + {"train": train_sources, "val": val_sources, "test": locked_sources}, hashes + ) + train_ids = {path.stem for path in train_sources} + val_ids = {path.stem for path in val_sources} + test_ids = {path.stem for path in locked_sources} + if not train_ids.isdisjoint(val_ids): + raise ValueError("train and validation source IDs overlap") + if not train_ids.isdisjoint(test_ids): + raise ValueError("train and locked source IDs overlap") + if not val_ids.isdisjoint(test_ids): + raise ValueError("validation and locked source IDs overlap") + + manifest = _crop_records( + train_sources, "train", crop_size, crops_per_source, seed, hashes + ) + manifest += _crop_records( + val_sources, "val", crop_size, crops_per_source, seed, hashes + ) + manifest += _crop_records( + locked_sources, "test", crop_size, crops_per_source, seed, hashes + ) + expected = (len(train_sources) + len(val_sources) + len(locked_sources)) * crops_per_source + if len(manifest) != expected: + raise RuntimeError( + f"Crop manifest count mismatch: expected {expected}, got {len(manifest)}" + ) + return manifest + + +def build_locked_crop_manifest( + data_root: str | Path, + *, + test_cap: Optional[int] = None, + crop_size: int = 256, + crops_per_source: int = 4, + seed: int = 0, +) -> List[CropRecord]: + """Build only the locked DIV2K validation manifest. + + This separate entry point lets a train-only invocation avoid listing, + loading, or hashing any locked source bytes. + """ + + if test_cap is not None and test_cap < 0: + raise ValueError("test_cap must be non-negative or None") + if crop_size <= 0 or crops_per_source <= 0: + raise ValueError("crop_size and crops_per_source must be positive") + locked_dir = _find_div2k_dir(Path(data_root), "DIV2K_valid_HR") + sources = _sha256_source_order(_image_files(locked_dir)) + if test_cap is not None: + sources = sources[:test_cap] + hashes = _source_hashes(sources) + return _crop_records(sources, "test", crop_size, crops_per_source, seed, hashes) + + +@cache +def _verify_source_stat( + source_path: str, + expected_sha256: str, + stat_key: Tuple[int, int, int, int, int], +) -> None: + del stat_key + actual = _sha256_file(Path(source_path)) + if actual != expected_sha256: + raise RuntimeError( + f"Source SHA256 mismatch for {source_path}: " + f"expected {expected_sha256}, got {actual}" + ) + + +def _verify_source(record: CropRecord) -> None: + path = Path(record.source_path) + stat = path.stat() + stat_key = ( + stat.st_dev, + stat.st_ino, + stat.st_size, + stat.st_mtime_ns, + stat.st_ctime_ns, + ) + _verify_source_stat(str(path), record.source_sha256, stat_key) + + +def validate_source_integrity(records: Sequence[CropRecord]) -> None: + """Verify each unique source once before materializing a feature cache.""" + + expected_by_path: Dict[str, str] = {} + for record in records: + previous = expected_by_path.setdefault(record.source_path, record.source_sha256) + if previous != record.source_sha256: + raise ValueError( + f"Manifest records disagree on SHA256 for {record.source_path}" + ) + for record in records: + if expected_by_path.pop(record.source_path, None) is not None: + _verify_source(record) + + +def load_clean_patch(record: CropRecord) -> torch.Tensor: + """Load a SHA-verified manifest crop as an RGB CHW tensor in [0, 1].""" + + _verify_source(record) + with Image.open(record.source_path) as image: + image = image.convert("RGB") + patch = image.crop( + ( + record.left, + record.top, + record.left + record.size, + record.top + record.size, + ) + ) + array = np.asarray(patch, dtype=np.uint8).copy() + return torch.from_numpy(array).permute(2, 0, 1).float().div_(255.0) + + +def normalize_severity(degradation: str, physical_value: float) -> float: + """Map a physical parameter to a monotonic normalized severity label.""" + + value = float(physical_value) + if degradation == "noise": + return value / 70.0 + if degradation == "blur": + return value / 3.0 + if degradation == "lowlight": + return (value - 1.0) / (3.5 - 1.0) + if degradation == "jpeg": + # Compression becomes physically stronger as quality falls. + return (100.0 - value) / 100.0 + raise ValueError(f"Unknown degradation: {degradation}") + + +def _sample_train_value(degradation: str, key: str, branch: int) -> float: + config = SEVERITY_RANGES[degradation] + train_min, train_max = config["train"] + gap_start, gap_end = config["gap"] + if config["discrete"]: + choices = ( + list(range(int(train_min), int(gap_start))) + if branch == 0 + else list(range(int(gap_end) + 1, int(train_max) + 1)) + ) + return float(choices[_digest_int(key) % len(choices)]) + + low, high = (train_min, gap_start) if branch == 0 else (gap_end, train_max) + return float(low + _unit_interval(key) * (high - low)) + + +def _noise_seed(key: str) -> int: + return _digest_int(f"noise:{key}") % (2**63 - 1) + + +def _gap_values(degradation: str, points: int) -> Tuple[float, ...]: + if points <= 0: + raise ValueError("gap_points must be positive") + gap_start, gap_end = SEVERITY_RANGES[degradation]["gap"] + if points == 1: + return ((float(gap_start) + float(gap_end)) / 2.0,) + if SEVERITY_RANGES[degradation]["discrete"]: + count = int(gap_end) - int(gap_start) + 1 + if points > count: + raise ValueError(f"gap_points cannot exceed {count} for JPEG") + offsets = [round(index * (count - 1) / (points - 1)) for index in range(points)] + return tuple(float(int(gap_start) + offset) for offset in offsets) + step = (float(gap_end) - float(gap_start)) / (points - 1) + return tuple(float(gap_start) + index * step for index in range(points)) + + +def _ordered_crops(crop_manifest: Sequence[CropRecord], mode: Mode) -> List[CropRecord]: + wanted = { + "support": {"train", "val"}, + "validation_gap": {"val"}, + "locked": {"test"}, + }[mode] + selected = [record for record in crop_manifest if record.split in wanted] + split_rank = {"train": 0, "val": 1, "test": 2} + return sorted( + selected, + key=lambda record: ( + split_rank[record.split], + record.source_id, + record.crop_index, + record.source_path, + ), + ) + + +def _append_single( + specs: List[SampleSpec], + record: CropRecord, + mode: Mode, + degradation: str, + physical_value: float, + regime: str, + key: str, +) -> int: + index = len(specs) + specs.append( + SampleSpec( + sample_index=index, + crop_id=record.crop_id, + source_id=record.source_id, + split=record.split, + mode=mode, + degradation=degradation, + regime=regime, + components=(degradation,), + physical_values=(float(physical_value),), + severities=(normalize_severity(degradation, physical_value),), + noise_seed=_noise_seed(key) if degradation == "noise" else None, + ) + ) + return index + + +def _append_combo( + specs: List[SampleSpec], + record: CropRecord, + mode: Mode, + combo_name: str, + components: Tuple[str, ...], + component_indices: Tuple[int, ...], + regime: str, +) -> None: + referenced = [specs[index] for index in component_indices] + values = tuple(spec.physical_values[0] for spec in referenced) + severities = tuple(spec.severities[0] for spec in referenced) + noise_specs = [spec for spec in referenced if spec.components == ("noise",)] + specs.append( + SampleSpec( + sample_index=len(specs), + crop_id=record.crop_id, + source_id=record.source_id, + split=record.split, + mode=mode, + degradation=combo_name, + regime=regime, + components=components, + physical_values=values, + severities=severities, + component_indices=component_indices, + noise_seed=noise_specs[0].noise_seed if noise_specs else None, + ) + ) + + +def _validate_sample_specs(specs: Sequence[SampleSpec]) -> None: + order = {name: index for index, name in enumerate(PHYSICAL_ORDER)} + for position, spec in enumerate(specs): + if spec.sample_index != position: + raise ValueError("Sample indices must match list positions") + if "rain" in spec.components or spec.degradation == "rain": + raise ValueError("Rain is forbidden in Phase 1 sample specs") + if not ( + len(spec.components) == len(spec.physical_values) == len(spec.severities) + ): + raise ValueError("Sample components, physical values, and severities misalign") + if any(component not in order for component in spec.components): + raise ValueError(f"Unknown sample components: {spec.components}") + if tuple(sorted(spec.components, key=order.__getitem__)) != spec.components: + raise ValueError("Sample components are not in physical application order") + if spec.is_composition: + if len(spec.component_indices) != len(spec.components): + raise ValueError("Composition references do not align with components") + for component, value, reference_index in zip( + spec.components, spec.physical_values, spec.component_indices + ): + if not 0 <= reference_index < position: + raise ValueError("Composition reference must point to an earlier sample") + reference = specs[reference_index] + if reference.is_composition: + raise ValueError("Composition reference must point to a single") + if reference.crop_id != spec.crop_id: + raise ValueError("Composition reference crosses crop boundaries") + if reference.components != (component,): + raise ValueError("Composition reference has the wrong component type") + if reference.physical_values != (value,): + raise ValueError("Composition reference has the wrong physical value") + if "noise" in spec.components: + noise_position = spec.components.index("noise") + noise_reference = specs[spec.component_indices[noise_position]] + if spec.noise_seed != noise_reference.noise_seed: + raise ValueError("Composition noise seed differs from its single") + else: + if spec.component_indices: + raise ValueError("Single-degradation spec cannot have component references") + + +def build_sample_specs( + crop_manifest: Sequence[CropRecord], + mode: Mode = "support", + *, + seed: int = 0, + gap_points: int = 3, +) -> List[SampleSpec]: + """Create deterministic support, validation-gap, or locked instructions. + + Support mode emits two gap-excluding singles and the four seen train + combinations. Validation-gap and locked modes emit identical gap+extrap + singles followed by four seen and three unseen combinations, but consume + only val and test records respectively. + """ + + if mode not in ("support", "validation_gap", "locked"): + raise ValueError("mode must be 'support', 'validation_gap', or 'locked'") + records = _ordered_crops(crop_manifest, mode) + specs: List[SampleSpec] = [] + + for record in records: + key_prefix = f"{seed}:{record.crop_id}" + if mode == "support": + references: Dict[str, List[int]] = {name: [] for name in DEGRADATIONS} + for degradation in DEGRADATIONS: + for branch in range(2): + key = f"{key_prefix}:{degradation}:{branch}" + value = _sample_train_value(degradation, key, branch) + references[degradation].append( + _append_single( + specs, + record, + mode, + degradation, + value, + "train", + key, + ) + ) + + for combo_name, components in TRAIN_COMBINATIONS.items(): + component_indices = tuple( + references[name][ + _digest_int( + f"{key_prefix}:combo:{combo_name}:component:{name}:branch" + ) + % 2 + ] + for name in components + ) + _append_combo( + specs, + record, + mode, + combo_name, + components, + component_indices, + "seen_combo", + ) + else: + gap_references: Dict[str, List[int]] = {name: [] for name in DEGRADATIONS} + for degradation in DEGRADATIONS: + for gap_number, value in enumerate(_gap_values(degradation, gap_points)): + key = f"{key_prefix}:{degradation}:gap:{gap_number}" + gap_references[degradation].append( + _append_single( + specs, + record, + mode, + degradation, + value, + "gap", + key, + ) + ) + extrap_value = float(SEVERITY_RANGES[degradation]["extrap"]) + _append_single( + specs, + record, + mode, + degradation, + extrap_value, + "extrap", + f"{key_prefix}:{degradation}:extrap", + ) + + midpoint = gap_points // 2 + for combo_name, components in TRAIN_COMBINATIONS.items(): + component_indices = tuple( + gap_references[name][midpoint] for name in components + ) + _append_combo( + specs, + record, + mode, + combo_name, + components, + component_indices, + "seen_combo", + ) + for combo_name, components in UNSEEN_COMBINATIONS.items(): + component_indices = tuple( + gap_references[name][midpoint] for name in components + ) + _append_combo( + specs, + record, + mode, + combo_name, + components, + component_indices, + "unseen_combo", + ) + + expected_per_patch = 12 if mode == "support" else 4 * (gap_points + 1) + 7 + expected = len(records) * expected_per_patch + if len(specs) != expected: + raise RuntimeError( + f"Sample-spec count mismatch: expected {expected}, got {len(specs)}" + ) + _validate_sample_specs(specs) + return specs + + +def _validate_image(image: torch.Tensor) -> None: + if image.ndim != 3 or image.shape[0] != 3: + raise ValueError("Expected an RGB CHW tensor") + if not image.is_floating_point(): + raise TypeError("Expected a floating-point image tensor") + + +def _gaussian_blur(image: torch.Tensor, sigma: float) -> torch.Tensor: + if sigma <= 0: + raise ValueError("Gaussian blur sigma must be positive") + work = image.float() + radius = max(1, int(np.ceil(3.0 * sigma))) + coordinates = torch.arange(-radius, radius + 1, device=work.device, dtype=work.dtype) + kernel_1d = torch.exp(-(coordinates**2) / (2.0 * sigma**2)) + kernel_1d /= kernel_1d.sum() + kernel = torch.outer(kernel_1d, kernel_1d) + kernel = kernel.expand(work.shape[0], 1, -1, -1) + mode = "reflect" if radius < min(work.shape[-2:]) else "replicate" + padded = F.pad(work.unsqueeze(0), (radius, radius, radius, radius), mode=mode) + blurred = F.conv2d(padded, kernel, groups=work.shape[0]).squeeze(0) + return blurred.to(dtype=image.dtype).clamp_(0.0, 1.0) + + +def _pil_jpeg(image: torch.Tensor, quality: int) -> torch.Tensor: + if not 1 <= quality <= 100: + raise ValueError("JPEG quality must be an integer in [1, 100]") + device, dtype = image.device, image.dtype + array = ( + image.detach() + .cpu() + .clamp(0.0, 1.0) + .mul(255.0) + .round() + .to(torch.uint8) + .permute(1, 2, 0) + .numpy() + ) + buffer = io.BytesIO() + Image.fromarray(array).save( + buffer, + format="JPEG", + quality=quality, + subsampling=0, + optimize=False, + ) + buffer.seek(0) + with Image.open(buffer) as decoded: + decoded.load() + result = np.asarray(decoded.convert("RGB"), dtype=np.uint8).copy() + return ( + torch.from_numpy(result) + .permute(2, 0, 1) + .to(device=device, dtype=dtype) + .div_(255.0) + ) + + +def apply_single( + image: torch.Tensor, + degradation: str, + physical_value: float, + *, + noise_seed: int = 0, +) -> torch.Tensor: + """Apply one degradation using its physical parameter. + + Noise ``physical_value`` is sigma in 8-bit intensity units, blur is Gaussian + sigma, low-light is gamma in ``x ** gamma``, and JPEG is an integer PIL + quality. The local noise seed does not modify global Torch RNG state. + """ + + _validate_image(image) + value = float(physical_value) + if degradation == "noise": + if value < 0: + raise ValueError("Noise sigma must be non-negative") + generator = torch.Generator(device="cpu") + generator.manual_seed(int(noise_seed)) + noise = torch.randn(image.shape, generator=generator, dtype=torch.float32) + noise = noise.to(device=image.device, dtype=image.dtype).mul_(value / 255.0) + return (image + noise).clamp(0.0, 1.0) + if degradation == "blur": + return _gaussian_blur(image, value) + if degradation == "lowlight": + if value < 1.0: + raise ValueError("Low-light gamma must be at least 1") + return image.clamp(0.0, 1.0).pow(value) + if degradation == "jpeg": + quality = int(value) + if value != quality: + raise ValueError("JPEG quality must be discrete") + return _pil_jpeg(image, quality) + raise ValueError(f"Unknown degradation: {degradation}") + + +def apply_composition( + image: torch.Tensor, + physical_values: Mapping[str, float], + *, + noise_seed: int = 0, +) -> torch.Tensor: + """Apply a component mapping in fixed physical camera order.""" + + unknown = set(physical_values) - set(DEGRADATIONS) + if unknown: + raise ValueError(f"Unknown degradation components: {sorted(unknown)}") + if len(physical_values) < 2: + raise ValueError("A composition requires at least two components") + result = image + for degradation in PHYSICAL_ORDER: + if degradation in physical_values: + result = apply_single( + result, + degradation, + physical_values[degradation], + noise_seed=noise_seed, + ) + return result + + +class ControlledDegradationDataset(Dataset): + """Materialize deterministic clean/degraded pairs from manifests and specs.""" + + def __init__( + self, + crop_manifest: Sequence[CropRecord], + sample_specs: Optional[Sequence[SampleSpec]] = None, + *, + mode: Mode = "support", + seed: int = 0, + gap_points: int = 3, + ) -> None: + self.crop_manifest = list(crop_manifest) + self.specs = ( + list(sample_specs) + if sample_specs is not None + else build_sample_specs( + self.crop_manifest, + mode=mode, + seed=seed, + gap_points=gap_points, + ) + ) + self.sample_specs = self.specs + self._crops = {record.crop_id: record for record in self.crop_manifest} + if len(self._crops) != len(self.crop_manifest): + raise ValueError("Crop IDs must be unique") + missing = {spec.crop_id for spec in self.specs} - set(self._crops) + if missing: + raise ValueError(f"Sample specs reference missing crops: {sorted(missing)}") + _validate_sample_specs(self.specs) + + def __len__(self) -> int: + return len(self.specs) + + def __getitem__(self, index: int) -> Dict[str, Any]: + spec = self.specs[index] + clean = load_clean_patch(self._crops[spec.crop_id]) + values = dict(zip(spec.components, spec.physical_values)) + if spec.is_composition: + degraded = apply_composition( + clean, + values, + noise_seed=spec.noise_seed or 0, + ) + else: + degraded = apply_single( + clean, + spec.components[0], + spec.physical_values[0], + noise_seed=spec.noise_seed or 0, + ) + + severity_vector = torch.zeros(len(PHYSICAL_ORDER), dtype=torch.float32) + physical_vector = torch.zeros(len(PHYSICAL_ORDER), dtype=torch.float32) + component_references = torch.full((len(PHYSICAL_ORDER),), -1, dtype=torch.long) + for component_number, (component, value, severity) in enumerate( + zip(spec.components, spec.physical_values, spec.severities) + ): + position = PHYSICAL_ORDER.index(component) + severity_vector[position] = severity + physical_vector[position] = value + if spec.is_composition: + component_references[position] = spec.component_indices[component_number] + + return { + "clean": clean, + "degraded": degraded, + "type": spec.degradation, + "severity": max(spec.severities), + "severity_vector": severity_vector, + "physical_values": physical_vector, + "component_indices": component_references, + "sample_index": spec.sample_index, + "source_id": spec.source_id, + "crop_id": spec.crop_id, + "split": spec.split, + "mode": spec.mode, + "regime": spec.regime, + } diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/phase2_v4.py b/dataset/phase1_noise_20260906/trial_code_staging/src/data/phase2_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..7e33412d9f9e29bd1d013afc408cf9361aea90f6 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/data/phase2_v4.py @@ -0,0 +1,942 @@ +"""Leakage-safe paired data contracts for Phase-2 restoration. + +Only the Phase-1 train and validation sources are reconstructed here. Locked +test sets deliberately have no representation in this module or its manifest +schema, which makes accidentally touching them during optimization difficult. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import os +import random +import re +import tempfile +from dataclasses import asdict, dataclass +from pathlib import Path, PurePosixPath +from typing import Dict, Iterator, List, Mapping, Optional, Sequence, Tuple, Union + +import numpy as np +import torch +from PIL import Image +from torch.utils.data import Dataset, Sampler + + +BRANCH_ORDER: Tuple[str, ...] = ("rain", "noise", "haze", "lowlight") +BRANCH_TO_INDEX = {name: index for index, name in enumerate(BRANCH_ORDER)} +EXPECTED_COUNTS: Tuple[int, int] = (18261, 317) +EXPECTED_DIGESTS: Tuple[str, str] = ( + "769bcff66a209ffbf5195868f7f479309f1350a5bfb367c9e2c3a94d43cbba46", + "86f0c9723a4c89da6ed1be0da487094bc2938dd5e97e5c5ab68369bd16f8c38d", +) +EXPECTED_QUARANTINE_COUNT = 1155 +SUPPORTED_EXTENSIONS = frozenset((".png", ".jpg", ".jpeg")) +_HEX64 = re.compile(r"^[0-9a-f]{64}$") + +try: + _LANCZOS = Image.Resampling.LANCZOS +except AttributeError: # Pillow < 9 + _LANCZOS = Image.LANCZOS +try: + _FLIP_LEFT_RIGHT = Image.Transpose.FLIP_LEFT_RIGHT +except AttributeError: # Pillow < 9 + _FLIP_LEFT_RIGHT = Image.FLIP_LEFT_RIGHT + + +@dataclass(frozen=True) +class RestorationRecord: + degraded: Path + clean: Path + degradation: str + dataset: str + source_id: str + split_group: str + clean_content_sha256: str + + def __post_init__(self) -> None: + object.__setattr__(self, "degraded", Path(self.degraded)) + object.__setattr__(self, "clean", Path(self.clean)) + if self.degradation not in BRANCH_TO_INDEX: + raise ValueError("unknown degradation: %r" % (self.degradation,)) + for name in ("dataset", "source_id", "split_group"): + value = getattr(self, name) + if not isinstance(value, str) or not value: + raise ValueError("%s must be a non-empty string" % name) + if not isinstance(self.clean_content_sha256, str) or _HEX64.fullmatch( + self.clean_content_sha256 + ) is None: + raise ValueError("clean_content_sha256 must be 64 lowercase hex digits") + + @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, + ) + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + def to_dict(self) -> Dict[str, object]: + value = asdict(self) + value["degraded"] = str(self.degraded) + value["clean"] = str(self.clean) + value["label"] = self.label + value["record_id"] = self.record_id + return value + + @classmethod + def from_dict(cls, value: Mapping[str, object]) -> "RestorationRecord": + if not isinstance(value, Mapping): + raise ValueError("manifest record must be an object") + expected = { + "degraded", + "clean", + "degradation", + "dataset", + "source_id", + "split_group", + "clean_content_sha256", + "label", + "record_id", + } + if set(value) != expected: + raise ValueError("manifest record fields do not match the v4 schema") + record = cls( + degraded=Path(_required_string(value, "degraded")), + clean=Path(_required_string(value, "clean")), + degradation=_required_string(value, "degradation"), + dataset=_required_string(value, "dataset"), + source_id=_required_string(value, "source_id"), + split_group=_required_string(value, "split_group"), + clean_content_sha256=_required_string(value, "clean_content_sha256"), + ) + label = value["label"] + if ( + isinstance(label, bool) + or not isinstance(label, int) + or label != record.label + or not isinstance(value["record_id"], str) + or value["record_id"] != record.record_id + ): + raise ValueError("manifest record derived identity mismatch") + return record + + +@dataclass(frozen=True) +class TrainValSplits: + train: Tuple[RestorationRecord, ...] + val: Tuple[RestorationRecord, ...] + quarantine_count: int + + def __post_init__(self) -> None: + object.__setattr__(self, "train", tuple(self.train)) + object.__setattr__(self, "val", tuple(self.val)) + if ( + isinstance(self.quarantine_count, bool) + or not isinstance(self.quarantine_count, int) + or self.quarantine_count < 0 + ): + raise ValueError("quarantine_count must be a non-negative integer") + + +def _required_string(value: Mapping[str, object], key: str) -> str: + item = value.get(key) + if not isinstance(item, str) or not item: + raise ValueError("%s must be a non-empty string" % key) + return item + + +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_map(directory: Path, label: str, recursive: bool = False) -> Dict[str, Path]: + if not directory.is_dir(): + raise FileNotFoundError("%s missing directory: %s" % (label, directory)) + candidates = directory.rglob("*") if recursive else directory.iterdir() + files: Dict[str, Path] = {} + for path in candidates: + if path.suffix.lower() not in SUPPORTED_EXTENSIONS or not path.is_file(): + continue + key = path.relative_to(directory).as_posix() if recursive else path.name + if key in files: + raise ValueError("%s duplicate image key: %s" % (label, key)) + files[key] = path + if not files: + raise ValueError("%s contains no supported images" % label) + return {key: files[key] for key in sorted(files)} + + +def _paired_paths( + degraded_dir: Path, clean_dir: Path, label: str, recursive: bool = False +) -> List[Tuple[str, Path, Path]]: + degraded = _image_map(degraded_dir, "%s input" % label, recursive) + clean = _image_map(clean_dir, "%s target" % label, recursive) + if set(degraded) != set(clean): + missing_clean = sorted(set(degraded) - set(clean))[:5] + missing_degraded = sorted(set(clean) - set(degraded))[:5] + raise ValueError( + "%s pairing is not bijective; missing clean=%r missing degraded=%r" + % (label, missing_clean, missing_degraded) + ) + return [(name, degraded[name], clean[name]) for name in sorted(degraded)] + + +def _load_quarantine_paths(path: Path) -> Tuple[frozenset, int, int]: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise ValueError("malformed Rain13K quarantine manifest: %s" % exc) from exc + if not isinstance(payload, dict) or payload.get("schema_version") != 1: + raise ValueError("Rain13K quarantine manifest schema_version must be 1") + dataset = payload.get("dataset") + summary = payload.get("summary") + groups = payload.get("excluded_train_targets") + if not isinstance(dataset, dict) or not isinstance(summary, dict) or not isinstance(groups, list): + raise ValueError("Rain13K quarantine manifest has malformed top-level fields") + if dataset.get("handle") != "hngphchi/rain13k-resized" or dataset.get("version") != 1: + raise ValueError("Rain13K quarantine manifest identifies the wrong dataset") + train_count = dataset.get("train_pair_count") + affected = summary.get("affected_train_pairs") + group_count = summary.get("excluded_train_target_groups") + if ( + isinstance(train_count, bool) + or not isinstance(train_count, int) + or isinstance(affected, bool) + or not isinstance(affected, int) + or isinstance(group_count, bool) + or not isinstance(group_count, int) + or group_count != len(groups) + ): + raise ValueError("Rain13K quarantine manifest count fields are malformed") + excluded = set() + for group in groups: + if not isinstance(group, dict) or not isinstance(group.get("train_targets"), list): + raise ValueError("Rain13K quarantine group is malformed") + if not group["train_targets"]: + raise ValueError("Rain13K quarantine group has no train targets") + for target in group["train_targets"]: + if not isinstance(target, dict): + raise ValueError("Rain13K quarantine target is malformed") + relative = target.get("relative_path") + if not isinstance(relative, str): + raise ValueError("Rain13K quarantine relative_path is malformed") + file_hash = target.get("file_sha256") + if ( + not isinstance(file_hash, str) + or _HEX64.fullmatch(file_hash.lower()) is None + ): + raise ValueError("Rain13K quarantine file_sha256 is malformed") + pure = PurePosixPath(relative) + if ( + pure.is_absolute() + or pure.as_posix() != relative + or pure.parts[:2] != ("train_resized", "target") + or len(pure.parts) < 3 + or ".." in pure.parts + ): + raise ValueError("unsafe Rain13K quarantine relative_path: %r" % relative) + if relative in excluded: + raise ValueError("duplicate Rain13K quarantine path: %s" % relative) + excluded.add(relative) + if len(excluded) != affected: + raise ValueError("Rain13K quarantine affected pair count mismatch") + return frozenset(excluded), train_count, affected + + +def _make_record( + degraded: Path, + clean: Path, + degradation: str, + dataset: str, + source_id: str, + split_group: str, + clean_hash: Optional[str] = None, +) -> RestorationRecord: + return RestorationRecord( + degraded=degraded, + clean=clean, + degradation=degradation, + dataset=dataset, + source_id=source_id, + split_group=split_group, + clean_content_sha256=clean_hash or _sha256_file(clean), + ) + + +def _build_rain_train_val( + rain_root: Path, quarantine_manifest: Path +) -> Tuple[List[RestorationRecord], List[RestorationRecord], int]: + excluded, expected_raw_train, affected = _load_quarantine_paths(quarantine_manifest) + raw_train = _paired_paths( + rain_root / "train_resized" / "input", + rain_root / "train_resized" / "target", + "Rain13K train_resized", + recursive=True, + ) + if len(raw_train) != expected_raw_train: + raise ValueError( + "Rain13K raw train count mismatch: expected %d, got %d" + % (expected_raw_train, len(raw_train)) + ) + observed_names = { + "train_resized/target/%s" % relative for relative, _, _ in raw_train + } + missing = excluded - observed_names + if missing: + raise ValueError("quarantine references absent Rain13K train paths: %r" % sorted(missing)[:5]) + + train = [] + for relative, degraded, clean in raw_train: + quarantine_key = "train_resized/target/%s" % relative + if quarantine_key in excluded: + continue + content_hash = _sha256_file(clean) + train.append( + _make_record( + degraded, + clean, + "rain", + "Rain13K", + "train_resized:%s" % degraded.name, + content_hash, + content_hash, + ) + ) + if len(train) != expected_raw_train - affected: + raise ValueError("Rain13K quarantined train count mismatch") + + raw_val = _paired_paths( + rain_root / "test_resized" / "Test100" / "input", + rain_root / "test_resized" / "Test100" / "target", + "Rain13K Test100", + recursive=True, + ) + if len(raw_val) != 98: + raise ValueError("Rain13K Test100 audited count must be 98") + val = [] + for _, degraded, clean in raw_val: + content_hash = _sha256_file(clean) + val.append( + _make_record( + degraded, + clean, + "rain", + "Rain13K", + "Test100:%s" % degraded.name, + content_hash, + content_hash, + ) + ) + return train, val, affected + + +def _build_lol_train_val(data_root: Path) -> Tuple[List[RestorationRecord], List[RestorationRecord]]: + root = data_root / "LOLv2" / "lolv2_hf" + + def build(split: str, expected: int) -> List[RestorationRecord]: + pairs = _paired_paths( + root / split / "Input", root / split / "GT", "LOLv2 %s" % split + ) + if len(pairs) != expected: + raise ValueError("LOLv2 %s audited count must be %d" % (split, expected)) + records = [] + for _, degraded, clean in pairs: + content_hash = _sha256_file(clean) + records.append( + _make_record( + degraded, + clean, + "lowlight", + "LOLv2", + degraded.stem, + content_hash, + content_hash, + ) + ) + return records + + return build("Train", 689), build("Test", 100) + + +def _directory_image_names(directory: Path, label: str) -> List[str]: + if not directory.is_dir(): + raise FileNotFoundError("%s missing directory: %s" % (label, directory)) + try: + names = os.listdir(str(directory)) + except OSError as exc: + raise ValueError("could not enumerate %s: %s" % (label, exc)) from exc + return sorted(name for name in names if Path(name).suffix.lower() in SUPPORTED_EXTENSIONS) + + +def _build_reside_train_val( + data_root: Path, +) -> Tuple[List[RestorationRecord], List[RestorationRecord]]: + root = data_root / "RESIDE" + hazy_dir, clear_dir = root / "hazy", root / "clear" + hazy_names = _directory_image_names(hazy_dir, "RESIDE hazy") + if len(hazy_names) < 5000: + raise ValueError("RESIDE requires at least 5000 sorted hazy images") + selected_hazy = hazy_names[:5000] + if not clear_dir.is_dir(): + raise FileNotFoundError("RESIDE clear missing directory: %s" % clear_dir) + + selected = [] + for name in selected_hazy: + degraded = hazy_dir / name + source = Path(name).stem.split("_")[0] + if not source or "_" not in Path(name).stem: + raise ValueError("malformed RESIDE hazy filename: %s" % name) + # Canonical RESIDE ITS uses exactly ``clear/.jpg``. Resolving + # the selected source directly avoids enumerating the 1,918 clear + # sources held out beyond the first-5000 Phase-1 support contract. + clean = clear_dir / (source + ".jpg") + if not degraded.is_file() or not clean.is_file(): + raise ValueError("RESIDE selected pair is not made of regular files: %s" % name) + selected.append((degraded, clean, source)) + + val_pairs = selected[:100] + val_groups = {source for _, _, source in val_pairs} + train_pairs = [pair for pair in selected[100:] if pair[2] not in val_groups] + if len(train_pairs) != 4895 or len(val_pairs) != 100: + raise ValueError("RESIDE audited split count mismatch") + hashes: Dict[str, str] = {} + + def records(pairs: Sequence[Tuple[Path, Path, str]]) -> List[RestorationRecord]: + output = [] + for degraded, clean, source in pairs: + content_hash = hashes.get(source) + if content_hash is None: + content_hash = _sha256_file(clean) + hashes[source] = content_hash + output.append( + _make_record( + degraded, + clean, + "haze", + "RESIDE", + degraded.stem, + source, + content_hash, + ) + ) + return output + + return records(train_pairs), records(val_pairs) + + +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 _build_sidd_train_val( + data_root: Path, +) -> Tuple[List[RestorationRecord], List[RestorationRecord]]: + root = data_root / "SIDD" / "SIDD_Small_sRGB_Only" / "Data" + if not root.is_dir(): + raise FileNotFoundError("SIDD Data directory does not exist: %s" % root) + # The audited SIDD-small corpus has scenes 001..010. Derive the first nine + # from that public schema, then glob only those scene patterns: the tenth + # (locked) scene is never listed, statted, or represented by a Path object. + audited_scenes = tuple("%03d" % number for number in range(1, 11)) + ordered_scenes = sorted( + audited_scenes, + key=lambda scene: (hashlib.sha256(scene.encode("utf-8")).digest(), scene), + ) + train_scenes = frozenset(ordered_scenes[:8]) + val_scenes = frozenset(ordered_scenes[8:9]) + by_scene: Dict[str, List[str]] = {} + for scene in ordered_scenes[:9]: + matches = sorted(path.name for path in root.glob("*_%s_*" % scene)) + if not matches: + raise ValueError("SIDD selected scene %s has no source directories" % scene) + for name in matches: + if _sidd_scene_number(name) != scene: + raise ValueError("SIDD scene glob returned malformed source: %s" % name) + by_scene[scene] = matches + + def build(scenes: frozenset) -> List[RestorationRecord]: + output = [] + for scene in ordered_scenes[:9]: + if scene not in scenes: + continue + for source_id in by_scene[scene]: + source_dir = root / source_id + if not source_dir.is_dir(): + raise ValueError("selected SIDD source is not a directory: %s" % source_id) + members = sorted(os.listdir(str(source_dir))) + noisy = [name for name in members if name.startswith("NOISY_SRGB_")] + clean = [name for name in members if name.startswith("GT_SRGB_")] + if len(noisy) != 1 or len(clean) != 1: + raise ValueError("SIDD source %s must contain one NOISY/GT pair" % source_id) + degraded_path = source_dir / noisy[0] + clean_path = source_dir / clean[0] + if not degraded_path.is_file() or not clean_path.is_file(): + raise ValueError("selected SIDD pair is not made of regular files") + output.append( + _make_record( + degraded_path, + clean_path, + "noise", + "SIDD", + source_id, + scene, + ) + ) + return output + + train, val = build(train_scenes), build(val_scenes) + if len(train) != 121 or len(val) != 19: + raise ValueError("SIDD audited train/validation count mismatch") + return train, val + + +def _assert_train_val_isolation(splits: TrainValSplits) -> None: + train_groups = {(record.dataset, record.split_group) for record in splits.train} + val_groups = {(record.dataset, record.split_group) for record in splits.val} + overlap = train_groups & val_groups + if overlap: + raise ValueError("source leakage between train and validation: %r" % sorted(overlap)[:5]) + train_content = {record.clean_content_sha256 for record in splits.train} + val_content = {record.clean_content_sha256 for record in splits.val} + content_overlap = train_content & val_content + if content_overlap: + raise ValueError("clean-content leakage between train and validation") + for label, records in (("train", splits.train), ("validation", splits.val)): + identifiers = [record.record_id for record in records] + if len(identifiers) != len(set(identifiers)): + raise ValueError("duplicate %s restoration records" % label) + + +def build_train_val_splits( + data_root: Union[str, Path], + rain_root: Union[str, Path], + quarantine_manifest: Union[str, Path], +) -> TrainValSplits: + """Reconstruct exactly the Phase-1 support splits without any locked data.""" + + data_path = Path(data_root).expanduser() + rain_path = Path(rain_root).expanduser() + quarantine_path = Path(quarantine_manifest).expanduser() + rain_train, rain_val, quarantine_count = _build_rain_train_val( + rain_path, quarantine_path + ) + lol_train, lol_val = _build_lol_train_val(data_path) + reside_train, reside_val = _build_reside_train_val(data_path) + sidd_train, sidd_val = _build_sidd_train_val(data_path) + splits = TrainValSplits( + train=tuple(rain_train + lol_train + reside_train + sidd_train), + val=tuple(rain_val + lol_val + reside_val + sidd_val), + quarantine_count=quarantine_count, + ) + if (len(splits.train), len(splits.val)) != EXPECTED_COUNTS: + raise ValueError( + "live train/validation counts differ from audited contract: expected %r, got %r" + % (EXPECTED_COUNTS, (len(splits.train), len(splits.val))) + ) + if quarantine_count != EXPECTED_QUARANTINE_COUNT: + raise ValueError("live quarantine count differs from audited contract") + _assert_train_val_isolation(splits) + for label, records in (("train", splits.train), ("validation", splits.val)): + if set(record.degradation for record in records) != set(BRANCH_ORDER): + raise ValueError("%s split does not contain all four degradations" % label) + return splits + + +def split_digest(records: Sequence[RestorationRecord]) -> 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 validate_clean_file_integrity(splits: TrainValSplits) -> None: + """Re-hash each unique train/validation clean file once before a run. + + Manifest identities protect serialization, while this explicit preflight + protects against files being deleted, replaced, or modified after the + manifest was written. It is intentionally not called from ``__getitem__``. + """ + + expected_by_path: Dict[Path, str] = {} + for record in tuple(splits.train) + tuple(splits.val): + previous = expected_by_path.setdefault( + record.clean, record.clean_content_sha256 + ) + if previous != record.clean_content_sha256: + raise ValueError( + "manifest records disagree on expected SHA256 for clean file %s" + % record.clean + ) + for clean_path, expected in expected_by_path.items(): + if not clean_path.exists(): + raise FileNotFoundError("clean file is missing: %s" % clean_path) + if not clean_path.is_file(): + raise ValueError("clean path is not a regular file: %s" % clean_path) + actual = _sha256_file(clean_path) + if actual != expected: + raise ValueError( + "clean file SHA256 drift for %s: expected %s, got %s" + % (clean_path, expected, actual) + ) + + +def path_relocation_back_map() -> List[Tuple[str, str]]: + """``SCDC_PATH_RELOCATION="NEW_PREFIX=OLD_PREFIX,NEW=OLD"``: how the data + roots on this host map back to the roots the canonical digests and the + Phase-1 checkpoint provenance were computed with (record ids hash the + absolute paths, so a relocated copy of the data has different local + digests while being the same audited split).""" + + value = os.environ.get("SCDC_PATH_RELOCATION", "").strip() + if not value: + return [] + pairs = [] + for item in value.split(","): + if "=" not in item: + raise ValueError("SCDC_PATH_RELOCATION entries must be NEW=OLD: %r" % item) + new, old = item.split("=", 1) + pairs.append((new, old)) + return pairs + + +def canonical_split_digest(records: Sequence[RestorationRecord]) -> str: + """Split digest as it would read at the canonical (original) data roots.""" + + back = path_relocation_back_map() + if not back: + return split_digest(records) + + def relocate(path: Path) -> Path: + text = str(path) + for new, old in back: + if text.startswith(new): + return Path(old + text[len(new):]) + return path + + canonical = [ + RestorationRecord( + degraded=relocate(r.degraded), clean=relocate(r.clean), degradation=r.degradation, + dataset=r.dataset, source_id=r.source_id, split_group=r.split_group, + clean_content_sha256=r.clean_content_sha256, + ) + for r in records + ] + return split_digest(canonical) + + +def validate_splits_against_checkpoint( + splits: TrainValSplits, + checkpoint: Mapping[str, object], + expected_counts: Optional[Tuple[int, int]] = EXPECTED_COUNTS, + expected_digests: Optional[Tuple[str, str]] = EXPECTED_DIGESTS, +) -> None: + _assert_train_val_isolation(splits) + counts = (len(splits.train), len(splits.val)) + digests = (canonical_split_digest(splits.train), canonical_split_digest(splits.val)) + if expected_counts is not None and counts != tuple(expected_counts): + raise ValueError("local train/validation counts do not match the canonical contract") + if expected_digests is not None and digests != tuple(expected_digests): + raise ValueError("local train/validation split digests do not match the canonical contract") + provenance = checkpoint.get("provenance") if isinstance(checkpoint, Mapping) else None + if not isinstance(provenance, Mapping): + raise ValueError("checkpoint has no Phase-1 provenance object") + checkpoint_counts = provenance.get("counts") + checkpoint_digests = provenance.get("split_digests") + if not isinstance(checkpoint_counts, Mapping) or not isinstance(checkpoint_digests, Mapping): + raise ValueError("checkpoint provenance omits train/validation contracts") + for key, label, actual_count, actual_digest in ( + ("train", "training", counts[0], digests[0]), + ("val", "validation", counts[1], digests[1]), + ): + count_object = checkpoint_counts.get(key) + if not isinstance(count_object, Mapping) or count_object.get("pairs") != actual_count: + raise ValueError("checkpoint %s split count mismatch" % label) + if checkpoint_digests.get(key) != actual_digest: + raise ValueError("checkpoint %s split digest mismatch" % label) + if provenance.get("quarantined_rain_train_pairs") != splits.quarantine_count: + raise ValueError("checkpoint quarantine count mismatch") + + +def save_train_val_manifest(path: Union[str, Path], splits: TrainValSplits) -> None: + _assert_train_val_isolation(splits) + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + payload = { + "schema_version": 1, + "quarantine_count": splits.quarantine_count, + "train_digest": split_digest(splits.train), + "val_digest": split_digest(splits.val), + "train": [record.to_dict() for record in splits.train], + "val": [record.to_dict() for record in splits.val], + } + temporary_name = None + try: + with tempfile.NamedTemporaryFile( + mode="w", + encoding="utf-8", + dir=str(destination.parent), + prefix=".%s." % destination.name, + suffix=".tmp", + delete=False, + ) as handle: + temporary_name = handle.name + json.dump(payload, handle, indent=2, sort_keys=True) + handle.write("\n") + handle.flush() + os.fsync(handle.fileno()) + os.replace(temporary_name, str(destination)) + temporary_name = None + finally: + if temporary_name is not None: + try: + os.unlink(temporary_name) + except FileNotFoundError: + pass + + +def load_train_val_manifest(path: Union[str, Path]) -> TrainValSplits: + try: + payload = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise ValueError("malformed Phase-2 train/validation manifest: %s" % exc) from exc + if not isinstance(payload, dict): + raise ValueError("Phase-2 manifest root must be an object") + if any("locked" in str(key).lower() or str(key).lower() == "test" for key in payload): + raise ValueError("locked/test keys are forbidden in a Phase-2 optimization manifest") + expected = { + "schema_version", + "quarantine_count", + "train_digest", + "val_digest", + "train", + "val", + } + if set(payload) != expected or payload.get("schema_version") != 1: + raise ValueError("Phase-2 train/validation manifest schema mismatch") + if not isinstance(payload["train"], list) or not isinstance(payload["val"], list): + raise ValueError("Phase-2 manifest train and val must be arrays") + quarantine_count = payload["quarantine_count"] + if isinstance(quarantine_count, bool) or not isinstance(quarantine_count, int): + raise ValueError("Phase-2 manifest quarantine_count must be an integer") + splits = TrainValSplits( + train=tuple(RestorationRecord.from_dict(value) for value in payload["train"]), + val=tuple(RestorationRecord.from_dict(value) for value in payload["val"]), + quarantine_count=quarantine_count, + ) + if payload["train_digest"] != split_digest(splits.train): + raise ValueError("Phase-2 manifest training split digest mismatch") + if payload["val_digest"] != split_digest(splits.val): + raise ValueError("Phase-2 manifest validation split digest mismatch") + _assert_train_val_isolation(splits) + return splits + + +def _open_rgb(path: Path) -> Image.Image: + try: + with Image.open(str(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 _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) + + +class Phase2PairDataset(Dataset): + """Aligned native-pair crops; labels are returned only for sampling/logging.""" + + def __init__( + self, + records: Sequence[RestorationRecord], + crop_size: int = 256, + training: bool = True, + upscale_small: bool = True, + ) -> None: + if crop_size <= 0: + raise ValueError("crop_size must be positive") + if not records: + raise ValueError("Phase2PairDataset requires at least one record") + self.records = tuple(records) + self.crop_size = int(crop_size) + self.training = bool(training) + self.upscale_small = bool(upscale_small) + + def __len__(self) -> int: + return len(self.records) + + def __getitem__(self, item: object) -> Dict[str, object]: + if self.training: + if not isinstance(item, (tuple, list)) or len(item) != 2: + raise TypeError("training items require (record_index, sample_seed)") + index, sample_seed = item + if not isinstance(index, (int, np.integer)) or not isinstance( + sample_seed, (int, np.integer) + ): + raise TypeError("record_index and sample_seed must be integers") + effective_sample_seed = int(sample_seed) + rng = random.Random(effective_sample_seed) + else: + if not isinstance(item, (int, np.integer)): + raise TypeError("validation items require an integer record index") + index = item + effective_sample_seed = -1 + rng = None + index = int(index) + record = self.records[index] + degraded, clean = _open_rgb(record.degraded), _open_rgb(record.clean) + if degraded.size != clean.size: + raise ValueError( + "paired images must have the same native size: %s is %r vs %r" + % (record.record_id, degraded.size, clean.size) + ) + width, height = degraded.size + if min(width, height) < self.crop_size: + if not self.upscale_small: + raise ValueError("native pair is smaller than crop_size") + scale = float(self.crop_size) / min(width, height) + resized = ( + max(self.crop_size, int(math.ceil(width * scale))), + max(self.crop_size, int(math.ceil(height * scale))), + ) + degraded = degraded.resize(resized, _LANCZOS) + clean = clean.resize(resized, _LANCZOS) + width, height = resized + if rng is None: + left = (width - self.crop_size) // 2 + top = (height - self.crop_size) // 2 + flip = False + else: + left = rng.randrange(width - self.crop_size + 1) + top = rng.randrange(height - self.crop_size + 1) + flip = bool(rng.getrandbits(1)) + box = (left, top, left + self.crop_size, top + self.crop_size) + # Whole-frame views (aspect-squashed to crop_size) carry the context + # that lies OUTSIDE the crop — sky/airlight, global exposure, flat + # regions for noise level — which a crop-only encoder cannot see. + full_degraded = degraded.resize((self.crop_size, self.crop_size), _LANCZOS) + full_clean = clean.resize((self.crop_size, self.crop_size), _LANCZOS) + degraded, clean = degraded.crop(box), clean.crop(box) + if flip: + degraded = degraded.transpose(_FLIP_LEFT_RIGHT) + clean = clean.transpose(_FLIP_LEFT_RIGHT) + full_degraded = full_degraded.transpose(_FLIP_LEFT_RIGHT) + full_clean = full_clean.transpose(_FLIP_LEFT_RIGHT) + return { + "degraded": _pil_to_tensor(degraded), + "clean": _pil_to_tensor(clean), + "full_degraded": _pil_to_tensor(full_degraded), + "full_clean": _pil_to_tensor(full_clean), + "label": record.label, + "degradation": record.degradation, + "source_id": record.source_id, + "record_id": record.record_id, + "sample_seed": effective_sample_seed, + } + + +def _seed_from_parts(*parts: object) -> int: + digest = hashlib.sha256(b"SCDC_PHASE2_SAMPLER_V1\0") + for part in parts: + digest.update(str(part).encode("utf-8")) + digest.update(b"\0") + return int.from_bytes(digest.digest()[:8], "big") % (2 ** 63 - 1) + + +class DeterministicBalancedBatchSampler(Sampler): + """Exact local class balance with replayable crop seeds and DDP rank shards.""" + + def __init__( + self, + labels: Sequence[int], + batch_size: int, + steps: int, + seed: int, + start_microstep: int = 0, + rank: int = 0, + world_size: int = 1, + ) -> None: + if batch_size <= 0 or batch_size % len(BRANCH_ORDER): + raise ValueError("batch_size must be positive and divisible by four") + if steps <= 0: + raise ValueError("steps must be positive") + if start_microstep < 0 or start_microstep > steps: + raise ValueError("start_microstep must be between zero and steps") + if world_size <= 0 or rank < 0 or rank >= world_size: + raise ValueError("rank must satisfy 0 <= rank < world_size") + self.by_class: List[Tuple[int, ...]] = [] + for class_index in range(len(BRANCH_ORDER)): + indices = tuple( + position for position, label in enumerate(labels) if int(label) == class_index + ) + if not indices: + raise ValueError("balanced sampler has an empty class") + self.by_class.append(indices) + if any(int(label) not in range(len(BRANCH_ORDER)) for label in labels): + raise ValueError("balanced sampler received an invalid label") + self.batch_size = int(batch_size) + self.steps = int(steps) + self.seed = int(seed) + self.start_microstep = int(start_microstep) + self.rank = int(rank) + self.world_size = int(world_size) + self.per_class = self.batch_size // len(BRANCH_ORDER) + + def __len__(self) -> int: + return self.steps - self.start_microstep + + def __iter__(self) -> Iterator[List[Tuple[int, int]]]: + for microstep in range(self.start_microstep, self.steps): + generator = torch.Generator() + generator.manual_seed(_seed_from_parts(self.seed, microstep, "draw")) + local: List[Tuple[int, int]] = [] + global_per_class = self.per_class * self.world_size + for class_index, indices in enumerate(self.by_class): + draws = torch.randint( + len(indices), (global_per_class,), generator=generator + ).tolist() + start = self.rank * self.per_class + stop = start + self.per_class + for global_slot in range(start, stop): + record_index = indices[draws[global_slot]] + sample_seed = _seed_from_parts( + self.seed, + microstep, + class_index, + global_slot, + record_index, + "crop", + ) + local.append((record_index, sample_seed)) + permutation = torch.randperm(len(local), generator=generator).tolist() + yield [local[position] for position in permutation] + + +def seed_worker(worker_id: int) -> None: + del worker_id + seed = torch.initial_seed() % (2 ** 32) + random.seed(seed) + np.random.seed(seed) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/rain13k_quarantine_v1.json b/dataset/phase1_noise_20260906/trial_code_staging/src/data/rain13k_quarantine_v1.json new file mode 100644 index 0000000000000000000000000000000000000000..50716eeebd8cbc60b2f4c6a7b2c69abfdd607746 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/data/rain13k_quarantine_v1.json @@ -0,0 +1,10437 @@ +{ + "dataset": { + "decoded_dimensions_wh": [ + 384, + 384 + ], + "decoded_image_mode": "RGB", + "handle": "hngphchi/rain13k-resized", + "official_test_pair_count": 4298, + "relative_train_input": "train_resized/input", + "relative_train_target": "train_resized/target", + "total_image_files": 36018, + "total_pair_count": 18009, + "target_inventory_v1": { + "algorithm": "sha256(domain_prefix_bytes || concatenated_sorted_records)", + "digest_sha256": "3aab7f16db5721ac1893329fbfb4e0e5754ca431fd4120e5d09c053ae6bb9eac", + "domain_prefix_hex": "534344435f5241494e31334b5f5441524745545f494e56454e544f52595f563100", + "file_selection": "regular files that are immediate children of each included_target_dirs entry; relative paths are POSIX paths rooted at the Kaggle dataset version directory", + "included_target_dirs": [ + "train_resized/target", + "test_resized/Rain100H/target", + "test_resized/Rain100L/target", + "test_resized/Test100/target", + "test_resized/Test1200/target", + "test_resized/Test2800/target" + ], + "record_count": 18009, + "record_count_by_dir": { + "test_resized/Rain100H/target": 100, + "test_resized/Rain100L/target": 100, + "test_resized/Test100/target": 98, + "test_resized/Test1200/target": 1200, + "test_resized/Test2800/target": 2800, + "train_resized/target": 13711 + }, + "raw_bytes_by_dir": { + "test_resized/Rain100H/target": 24895886, + "test_resized/Rain100L/target": 24895886, + "test_resized/Test100/target": 21953893, + "test_resized/Test1200/target": 272675776, + "test_resized/Test2800/target": 93080246, + "train_resized/target": 398718202 + }, + "record_format": "relative_path_utf8 || 0x00 || lowercase_raw_file_sha256_hex_ascii || 0x0a", + "sort_order": "ascending lexicographic order of relative_path UTF-8 bytes", + "total_raw_bytes": 836219889 + }, + "train_pair_count": 13711, + "version": 1 + }, + "exact_content_audit": { + "cross_test_shared_unique_decoded_hashes": { + "Rain100H__Rain100L": 91, + "Rain100H__Test100": 0, + "Rain100H__Test1200": 0, + "Rain100H__Test2800": 0, + "Rain100L__Test100": 0, + "Rain100L__Test1200": 0, + "Rain100L__Test2800": 0, + "Test100__Test1200": 0, + "Test100__Test2800": 0, + "Test1200__Test2800": 0 + }, + "per_split": { + "Rain100H": { + "duplicate_pair_instances": 9, + "pair_instances": 100, + "unique_decoded_target_sha256": 91 + }, + "Rain100L": { + "duplicate_pair_instances": 9, + "pair_instances": 100, + "unique_decoded_target_sha256": 91 + }, + "Test100": { + "duplicate_pair_instances": 3, + "pair_instances": 98, + "unique_decoded_target_sha256": 95 + }, + "Test1200": { + "duplicate_pair_instances": 36, + "pair_instances": 1200, + "unique_decoded_target_sha256": 1164 + }, + "Test2800": { + "duplicate_pair_instances": 2600, + "pair_instances": 2800, + "unique_decoded_target_sha256": 200 + }, + "train": { + "duplicate_pair_instances": 12031, + "pair_instances": 13711, + "unique_decoded_target_sha256": 1680 + } + }, + "train_to_test_shared_unique_decoded_hashes": { + "Rain100H": 0, + "Rain100L": 0, + "Test100": 0, + "Test1200": 0, + "Test2800": 0 + } + }, + "excluded_train_targets": [ + { + "decoded_rgb_sha256": "003457ab19cb2f5e4b1a09e077b4e02e7a2e304bafb6a42b59ce2bf7068044df", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 40.022181, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "75ffb50f8402047e8fe2abeea73f0268a025be53b184991a49607bc50e9ce63f", + "test_representative_target": "test_resized/Test2800/target/872_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 49.484156 + } + ], + "train_targets": [ + { + "file_sha256": "f79a72e1f6552da7c0b1cf1ff946aa42b78da6001811c8ef33712c1b3eac8a6d", + "relative_path": "train_resized/target/215.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0305eece704b610b8476408083eb7cd1153dfa8a40f38d3e931323ec6fcf339d", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 21.417388, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a5034f69b9d43b3eca9a792870aaf7078fa73d4146ebfb5d8f5f9a6d7abd6a33", + "test_representative_target": "test_resized/Test2800/target/969_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.697509 + } + ], + "train_targets": [ + { + "file_sha256": "947637468410bd6a48b9e1e7d82c13cb8411babfca65f9b9a044cb26f3f6d5e4", + "relative_path": "train_resized/target/1230.jpg" + }, + { + "file_sha256": "947637468410bd6a48b9e1e7d82c13cb8411babfca65f9b9a044cb26f3f6d5e4", + "relative_path": "train_resized/target/1530.jpg" + }, + { + "file_sha256": "947637468410bd6a48b9e1e7d82c13cb8411babfca65f9b9a044cb26f3f6d5e4", + "relative_path": "train_resized/target/1830.jpg" + }, + { + "file_sha256": "947637468410bd6a48b9e1e7d82c13cb8411babfca65f9b9a044cb26f3f6d5e4", + "relative_path": "train_resized/target/2130.jpg" + }, + { + "file_sha256": "947637468410bd6a48b9e1e7d82c13cb8411babfca65f9b9a044cb26f3f6d5e4", + "relative_path": "train_resized/target/2430.jpg" + }, + { + "file_sha256": "947637468410bd6a48b9e1e7d82c13cb8411babfca65f9b9a044cb26f3f6d5e4", + "relative_path": "train_resized/target/930.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "03a0aa4dbf590110f7f3e0a14c703d46239724620918253236ffbd17d838ccda", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 39.18638, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a96c613c98f6f514f6aea5b55898ef4ae50948c5a10dc67c2637e8086821c471", + "test_representative_target": "test_resized/Test2800/target/906_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 49.081124 + } + ], + "train_targets": [ + { + "file_sha256": "2eae848237059b5548164342512ec04b5396c476ace2fa95a031c144da88aa9e", + "relative_path": "train_resized/target/16.jpg" + }, + { + "file_sha256": "2eae848237059b5548164342512ec04b5396c476ace2fa95a031c144da88aa9e", + "relative_path": "train_resized/target/435.jpg" + }, + { + "file_sha256": "2eae848237059b5548164342512ec04b5396c476ace2fa95a031c144da88aa9e", + "relative_path": "train_resized/target/78.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "07838c69abd20a5ef1581a5301f12be07357a504c1d6d2c01c9d6082ac12c189", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.030148, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "ea8d74fe73c2aef5822f8230bc5be1727c731cb68b599b7c69c5add75f20d6b9", + "test_representative_target": "test_resized/Rain100H/target/49.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.721478 + }, + { + "full_rgb_psnr_db": 25.030148, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "ea8d74fe73c2aef5822f8230bc5be1727c731cb68b599b7c69c5add75f20d6b9", + "test_representative_target": "test_resized/Rain100L/target/49.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.721478 + } + ], + "train_targets": [ + { + "file_sha256": "71e5950e2e89dcb744fbb06ded0a85ff9345add7e1762fda1d130d0d6237374d", + "relative_path": "train_resized/target/1153.jpg" + }, + { + "file_sha256": "71e5950e2e89dcb744fbb06ded0a85ff9345add7e1762fda1d130d0d6237374d", + "relative_path": "train_resized/target/1453.jpg" + }, + { + "file_sha256": "71e5950e2e89dcb744fbb06ded0a85ff9345add7e1762fda1d130d0d6237374d", + "relative_path": "train_resized/target/1753.jpg" + }, + { + "file_sha256": "71e5950e2e89dcb744fbb06ded0a85ff9345add7e1762fda1d130d0d6237374d", + "relative_path": "train_resized/target/2053.jpg" + }, + { + "file_sha256": "71e5950e2e89dcb744fbb06ded0a85ff9345add7e1762fda1d130d0d6237374d", + "relative_path": "train_resized/target/2353.jpg" + }, + { + "file_sha256": "71e5950e2e89dcb744fbb06ded0a85ff9345add7e1762fda1d130d0d6237374d", + "relative_path": "train_resized/target/853.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0aaf8e63abc77d1cecc7ddf452a81f2dd0c0b8ee973372d7416f04ae2db5b981", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.466271, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8e762b53d346d301298df9b605db692b4a69cf178ab8d7f77a0cb35b67d870ec", + "test_representative_target": "test_resized/Rain100H/target/2.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 41.87863 + }, + { + "full_rgb_psnr_db": 30.466271, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8e762b53d346d301298df9b605db692b4a69cf178ab8d7f77a0cb35b67d870ec", + "test_representative_target": "test_resized/Rain100L/target/2.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 41.87863 + } + ], + "train_targets": [ + { + "file_sha256": "1f09d242d8ce5f0bb4f3e4d838b9a317b2808e86d14f8d2f759a7f505b1454f7", + "relative_path": "train_resized/target/1022.jpg" + }, + { + "file_sha256": "1f09d242d8ce5f0bb4f3e4d838b9a317b2808e86d14f8d2f759a7f505b1454f7", + "relative_path": "train_resized/target/1322.jpg" + }, + { + "file_sha256": "1f09d242d8ce5f0bb4f3e4d838b9a317b2808e86d14f8d2f759a7f505b1454f7", + "relative_path": "train_resized/target/1622.jpg" + }, + { + "file_sha256": "1f09d242d8ce5f0bb4f3e4d838b9a317b2808e86d14f8d2f759a7f505b1454f7", + "relative_path": "train_resized/target/1922.jpg" + }, + { + "file_sha256": "1f09d242d8ce5f0bb4f3e4d838b9a317b2808e86d14f8d2f759a7f505b1454f7", + "relative_path": "train_resized/target/2222.jpg" + }, + { + "file_sha256": "1f09d242d8ce5f0bb4f3e4d838b9a317b2808e86d14f8d2f759a7f505b1454f7", + "relative_path": "train_resized/target/722.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0aec41aaf21c5b78651b27cd47ff3134930a5040042cd9a537a96323c8e44c00", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.970821, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "5508fdfc432c9b1a09db2c9ffe2d4b84eb6f314f7e8c9b478acc3ca2feb1d6f6", + "test_representative_target": "test_resized/Rain100H/target/84.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.04178 + }, + { + "full_rgb_psnr_db": 24.970821, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "5508fdfc432c9b1a09db2c9ffe2d4b84eb6f314f7e8c9b478acc3ca2feb1d6f6", + "test_representative_target": "test_resized/Rain100L/target/84.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.04178 + } + ], + "train_targets": [ + { + "file_sha256": "c7c7bcde3dd06e5b4ac1210e89bf6243885696856bc0aad146cb457a4233d72b", + "relative_path": "train_resized/target/1185.jpg" + }, + { + "file_sha256": "c7c7bcde3dd06e5b4ac1210e89bf6243885696856bc0aad146cb457a4233d72b", + "relative_path": "train_resized/target/1485.jpg" + }, + { + "file_sha256": "c7c7bcde3dd06e5b4ac1210e89bf6243885696856bc0aad146cb457a4233d72b", + "relative_path": "train_resized/target/1785.jpg" + }, + { + "file_sha256": "c7c7bcde3dd06e5b4ac1210e89bf6243885696856bc0aad146cb457a4233d72b", + "relative_path": "train_resized/target/2085.jpg" + }, + { + "file_sha256": "c7c7bcde3dd06e5b4ac1210e89bf6243885696856bc0aad146cb457a4233d72b", + "relative_path": "train_resized/target/2385.jpg" + }, + { + "file_sha256": "c7c7bcde3dd06e5b4ac1210e89bf6243885696856bc0aad146cb457a4233d72b", + "relative_path": "train_resized/target/885.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0af4f47fc902cef6d07403a068328674f4195c561cb3b1041ec5153bfc0834d8", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 40.019055, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "75ffb50f8402047e8fe2abeea73f0268a025be53b184991a49607bc50e9ce63f", + "test_representative_target": "test_resized/Test2800/target/872_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 49.465373 + } + ], + "train_targets": [ + { + "file_sha256": "72007142ac2bdb422d47c78470c219997fc3881988c7d090198ded3cec9329c1", + "relative_path": "train_resized/target/218.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0c323cedb980425ea8a9dcbdc38a3f0bffff04f9f0251a842f4785212df81a36", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 21.299056, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "dd8954b0e59a3f0ad882abffd20116c3a4878caf308aa3baf473a9ca301994fa", + "test_representative_target": "test_resized/Rain100H/target/99.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.201729 + }, + { + "full_rgb_psnr_db": 21.299056, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "dd8954b0e59a3f0ad882abffd20116c3a4878caf308aa3baf473a9ca301994fa", + "test_representative_target": "test_resized/Rain100L/target/99.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.201729 + } + ], + "train_targets": [ + { + "file_sha256": "18338920bac8baeb7be8edd19a7bc1d8d590d0f140d478c113da86b9948761f6", + "relative_path": "train_resized/target/1199.jpg" + }, + { + "file_sha256": "18338920bac8baeb7be8edd19a7bc1d8d590d0f140d478c113da86b9948761f6", + "relative_path": "train_resized/target/1499.jpg" + }, + { + "file_sha256": "18338920bac8baeb7be8edd19a7bc1d8d590d0f140d478c113da86b9948761f6", + "relative_path": "train_resized/target/1799.jpg" + }, + { + "file_sha256": "18338920bac8baeb7be8edd19a7bc1d8d590d0f140d478c113da86b9948761f6", + "relative_path": "train_resized/target/2099.jpg" + }, + { + "file_sha256": "18338920bac8baeb7be8edd19a7bc1d8d590d0f140d478c113da86b9948761f6", + "relative_path": "train_resized/target/2399.jpg" + }, + { + "file_sha256": "18338920bac8baeb7be8edd19a7bc1d8d590d0f140d478c113da86b9948761f6", + "relative_path": "train_resized/target/899.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0ccb6ac51825d7c1739f82e90d5ec404b036ac6abe6ff79c362612928bf9f02e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.014795, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c4f3970373ef0a5470d481d06247f50a8fb1fb2e3835969c0c62641ec38e1f5f", + "test_representative_target": "test_resized/Rain100H/target/42.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.734701 + }, + { + "full_rgb_psnr_db": 25.014795, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c4f3970373ef0a5470d481d06247f50a8fb1fb2e3835969c0c62641ec38e1f5f", + "test_representative_target": "test_resized/Rain100L/target/42.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.734701 + }, + { + "full_rgb_psnr_db": 25.131865, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b9f57f3ed10c469070b3e628398d438fc977287dac58ebed40f53cd234aeaded", + "test_representative_target": "test_resized/Test2800/target/917_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.975945 + } + ], + "train_targets": [ + { + "file_sha256": "0959f83ae6258d9ba80787d51ade2827ded4bd026854b9e70db49ec39053d425", + "relative_path": "train_resized/target/1147.jpg" + }, + { + "file_sha256": "0959f83ae6258d9ba80787d51ade2827ded4bd026854b9e70db49ec39053d425", + "relative_path": "train_resized/target/1447.jpg" + }, + { + "file_sha256": "0959f83ae6258d9ba80787d51ade2827ded4bd026854b9e70db49ec39053d425", + "relative_path": "train_resized/target/1747.jpg" + }, + { + "file_sha256": "0959f83ae6258d9ba80787d51ade2827ded4bd026854b9e70db49ec39053d425", + "relative_path": "train_resized/target/2047.jpg" + }, + { + "file_sha256": "0959f83ae6258d9ba80787d51ade2827ded4bd026854b9e70db49ec39053d425", + "relative_path": "train_resized/target/2347.jpg" + }, + { + "file_sha256": "0959f83ae6258d9ba80787d51ade2827ded4bd026854b9e70db49ec39053d425", + "relative_path": "train_resized/target/847.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0d35c0155cfe5f21701945818cbe00e753a0d46d28b1f0e56155e8ce559bba92", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 39.095931, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cbb610ccef97b387f426df5f51a1a1ff778b78472da7d689f848ff3aeec1f237", + "test_representative_target": "test_resized/Test2800/target/960_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 48.733808 + } + ], + "train_targets": [ + { + "file_sha256": "d0e3a20342decc6542cf68026c40f149b02690b4f91080d913e616033f69dcb5", + "relative_path": "train_resized/target/117.jpg" + }, + { + "file_sha256": "d0e3a20342decc6542cf68026c40f149b02690b4f91080d913e616033f69dcb5", + "relative_path": "train_resized/target/268.jpg" + }, + { + "file_sha256": "d0e3a20342decc6542cf68026c40f149b02690b4f91080d913e616033f69dcb5", + "relative_path": "train_resized/target/334.jpg" + }, + { + "file_sha256": "d0e3a20342decc6542cf68026c40f149b02690b4f91080d913e616033f69dcb5", + "relative_path": "train_resized/target/342.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0dae21329475fc227ff9a2c7212647b13090e29845b0a440ce230b3385149271", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.460896, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "21f4b23393e3f499a5c66463ddf7d94cbb7e0f9a580479b25d6de64789d59d5d", + "test_representative_target": "test_resized/Test2800/target/817_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.777616 + } + ], + "train_targets": [ + { + "file_sha256": "654dc3b0ebc4196840fff9f7fa805ba0d96e0ab29416ab30526eaaa44622e19c", + "relative_path": "train_resized/target/1067.jpg" + }, + { + "file_sha256": "654dc3b0ebc4196840fff9f7fa805ba0d96e0ab29416ab30526eaaa44622e19c", + "relative_path": "train_resized/target/1367.jpg" + }, + { + "file_sha256": "654dc3b0ebc4196840fff9f7fa805ba0d96e0ab29416ab30526eaaa44622e19c", + "relative_path": "train_resized/target/1667.jpg" + }, + { + "file_sha256": "654dc3b0ebc4196840fff9f7fa805ba0d96e0ab29416ab30526eaaa44622e19c", + "relative_path": "train_resized/target/1967.jpg" + }, + { + "file_sha256": "654dc3b0ebc4196840fff9f7fa805ba0d96e0ab29416ab30526eaaa44622e19c", + "relative_path": "train_resized/target/2267.jpg" + }, + { + "file_sha256": "654dc3b0ebc4196840fff9f7fa805ba0d96e0ab29416ab30526eaaa44622e19c", + "relative_path": "train_resized/target/767.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "0e9985f4770bbb46fa2bdf10d3e42d4fad66e788abde1e398bb1ed01e3cf1c04", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 29.156535, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "69ffe7b9d968a1becc6ced9e856b2673d9e61277820ef09c46364df871c34777", + "test_representative_target": "test_resized/Rain100H/target/62.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.918173 + }, + { + "full_rgb_psnr_db": 29.156535, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "69ffe7b9d968a1becc6ced9e856b2673d9e61277820ef09c46364df871c34777", + "test_representative_target": "test_resized/Rain100L/target/62.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.918173 + } + ], + "train_targets": [ + { + "file_sha256": "84ff5b0de176799fbdde155320bf62e2ebbaa81be1d87e7ffa9346f3f037aaf4", + "relative_path": "train_resized/target/1165.jpg" + }, + { + "file_sha256": "84ff5b0de176799fbdde155320bf62e2ebbaa81be1d87e7ffa9346f3f037aaf4", + "relative_path": "train_resized/target/1465.jpg" + }, + { + "file_sha256": "84ff5b0de176799fbdde155320bf62e2ebbaa81be1d87e7ffa9346f3f037aaf4", + "relative_path": "train_resized/target/1765.jpg" + }, + { + "file_sha256": "84ff5b0de176799fbdde155320bf62e2ebbaa81be1d87e7ffa9346f3f037aaf4", + "relative_path": "train_resized/target/2065.jpg" + }, + { + "file_sha256": "84ff5b0de176799fbdde155320bf62e2ebbaa81be1d87e7ffa9346f3f037aaf4", + "relative_path": "train_resized/target/2365.jpg" + }, + { + "file_sha256": "84ff5b0de176799fbdde155320bf62e2ebbaa81be1d87e7ffa9346f3f037aaf4", + "relative_path": "train_resized/target/865.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "1073b9e992d270492e0f4c39f5613d88e4aef4dc5ce9aeae33368556a533c043", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.629861, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "24d13a96d0f5e62318d351764aa4896306406907455df06f41dd8d3e25ef96ca", + "test_representative_target": "test_resized/Rain100H/target/1.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.342114 + }, + { + "full_rgb_psnr_db": 27.629861, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "24d13a96d0f5e62318d351764aa4896306406907455df06f41dd8d3e25ef96ca", + "test_representative_target": "test_resized/Rain100L/target/1.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.342114 + } + ], + "train_targets": [ + { + "file_sha256": "385dcfef7e97ef59ef3750355147a1bd64c35e023ec2e4dfb92ee7cfdffc78f6", + "relative_path": "train_resized/target/1013.jpg" + }, + { + "file_sha256": "385dcfef7e97ef59ef3750355147a1bd64c35e023ec2e4dfb92ee7cfdffc78f6", + "relative_path": "train_resized/target/1313.jpg" + }, + { + "file_sha256": "385dcfef7e97ef59ef3750355147a1bd64c35e023ec2e4dfb92ee7cfdffc78f6", + "relative_path": "train_resized/target/1613.jpg" + }, + { + "file_sha256": "385dcfef7e97ef59ef3750355147a1bd64c35e023ec2e4dfb92ee7cfdffc78f6", + "relative_path": "train_resized/target/1913.jpg" + }, + { + "file_sha256": "385dcfef7e97ef59ef3750355147a1bd64c35e023ec2e4dfb92ee7cfdffc78f6", + "relative_path": "train_resized/target/2213.jpg" + }, + { + "file_sha256": "385dcfef7e97ef59ef3750355147a1bd64c35e023ec2e4dfb92ee7cfdffc78f6", + "relative_path": "train_resized/target/713.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "15ad221b4cf20f69755e044396b3baa1ea20e1fee8f1d1cedbd030610d8a3f77", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 39.098605, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cbb610ccef97b387f426df5f51a1a1ff778b78472da7d689f848ff3aeec1f237", + "test_representative_target": "test_resized/Test2800/target/960_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 48.733402 + } + ], + "train_targets": [ + { + "file_sha256": "05052bcbbf92791c1ac118ea0be76ceaf3bb063a2011ddae91dd86683c61d3f6", + "relative_path": "train_resized/target/466.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "17ef1df8e90e8415089951861366157727eb7f822f795a363812d88678052295", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 38.882367, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "0557b215b578b1d255d05703cc5cf5d7eabe643bff46394695e26fa43d28c0de", + "test_representative_target": "test_resized/Test2800/target/955_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 48.106837 + } + ], + "train_targets": [ + { + "file_sha256": "c869a5a934d442e353c7e49003d561202359d931edd3efec85c440d1cc700c0c", + "relative_path": "train_resized/target/130.jpg" + }, + { + "file_sha256": "c869a5a934d442e353c7e49003d561202359d931edd3efec85c440d1cc700c0c", + "relative_path": "train_resized/target/328.jpg" + }, + { + "file_sha256": "c869a5a934d442e353c7e49003d561202359d931edd3efec85c440d1cc700c0c", + "relative_path": "train_resized/target/76.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "18c7a39d7d6caaf57b76e90df5d71ac872902bacbe13d95c1554995ca16e3fcf", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.280239, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c335b51267ab1ec811e891f956e5b80c269f850f6c43fec167f67f4ac7423df4", + "test_representative_target": "test_resized/Test100/target/55.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.433501 + } + ], + "train_targets": [ + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8939.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8940.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8941.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8942.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8943.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8944.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8945.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8946.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8947.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8948.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8949.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8950.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8951.jpg" + }, + { + "file_sha256": "fc34223249d2e2ab043c784dee45d94c93f448784212dfb6c6a074030af00e4c", + "relative_path": "train_resized/target/8952.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "1b2a917c280aacadd3720f735ea8e845592a23f5010bf3a23cde158e7bc071ac", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.65987, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4ea781eb0580da781e04255bf863a750b32983868f81eec1490b0156168b8813", + "test_representative_target": "test_resized/Test2800/target/944_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.42844 + } + ], + "train_targets": [ + { + "file_sha256": "c6d914c0bb5c2f40b344b164cede8e7928ef70c2d8986909cb634717edb7fe31", + "relative_path": "train_resized/target/221.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "1e1997cd76c75378d917511cd00a10422182a452cc42263af83e1e09764023a0", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 29.142144, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "82db448aa2643b09ebe56cb1acf76383df34f5847c989fd4621499745620202e", + "test_representative_target": "test_resized/Rain100H/target/17.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.550423 + }, + { + "full_rgb_psnr_db": 29.142144, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "82db448aa2643b09ebe56cb1acf76383df34f5847c989fd4621499745620202e", + "test_representative_target": "test_resized/Rain100L/target/17.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.550423 + } + ], + "train_targets": [ + { + "file_sha256": "9823a504fc3514324312b5d1fce3a33b388d73cfc1a71509d582c67329a34123", + "relative_path": "train_resized/target/1124.jpg" + }, + { + "file_sha256": "9823a504fc3514324312b5d1fce3a33b388d73cfc1a71509d582c67329a34123", + "relative_path": "train_resized/target/1424.jpg" + }, + { + "file_sha256": "9823a504fc3514324312b5d1fce3a33b388d73cfc1a71509d582c67329a34123", + "relative_path": "train_resized/target/1724.jpg" + }, + { + "file_sha256": "9823a504fc3514324312b5d1fce3a33b388d73cfc1a71509d582c67329a34123", + "relative_path": "train_resized/target/2024.jpg" + }, + { + "file_sha256": "9823a504fc3514324312b5d1fce3a33b388d73cfc1a71509d582c67329a34123", + "relative_path": "train_resized/target/2324.jpg" + }, + { + "file_sha256": "9823a504fc3514324312b5d1fce3a33b388d73cfc1a71509d582c67329a34123", + "relative_path": "train_resized/target/824.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "1fdd342b8565cc58a182c01caa5dd4fd819d59c4d24b0547497faa6a2eb73267", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.453186, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "39f5733153f531dd97e737219389984aab8a10496ac9b77008e795ae46fab442", + "test_representative_target": "test_resized/Test2800/target/980_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.941605 + } + ], + "train_targets": [ + { + "file_sha256": "4cdbc2f075636b04a6485cc921e18659f23821819ec70ed943a3c79ccf481089", + "relative_path": "train_resized/target/1247.jpg" + }, + { + "file_sha256": "4cdbc2f075636b04a6485cc921e18659f23821819ec70ed943a3c79ccf481089", + "relative_path": "train_resized/target/1547.jpg" + }, + { + "file_sha256": "4cdbc2f075636b04a6485cc921e18659f23821819ec70ed943a3c79ccf481089", + "relative_path": "train_resized/target/1847.jpg" + }, + { + "file_sha256": "4cdbc2f075636b04a6485cc921e18659f23821819ec70ed943a3c79ccf481089", + "relative_path": "train_resized/target/2147.jpg" + }, + { + "file_sha256": "4cdbc2f075636b04a6485cc921e18659f23821819ec70ed943a3c79ccf481089", + "relative_path": "train_resized/target/2447.jpg" + }, + { + "file_sha256": "4cdbc2f075636b04a6485cc921e18659f23821819ec70ed943a3c79ccf481089", + "relative_path": "train_resized/target/947.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "22603004c070027b4cc955242580c6a21921d760d98832581949765af6a1dce1", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.909282, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8708e2c17f51ec711cbb2672771559efa8432fc451edbc5df670d650b5bbae8c", + "test_representative_target": "test_resized/Test2800/target/975_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 33.937465 + } + ], + "train_targets": [ + { + "file_sha256": "96b0f602ba83ac48bc6cd9764e31b566fc9f2f3ce0976cc3e39b9d8e91ae1812", + "relative_path": "train_resized/target/588.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "25612d1e25409eac342a86d50bf0b74dbf9b0b1fc45da7f1d1d65989fd4cf4d4", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.30405, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "a2fd5f3f69ddf29a5de4a34898dfe98b9a764b8424bca6759995aa05d5ef79fd", + "test_representative_target": "test_resized/Test100/target/77.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.877256 + } + ], + "train_targets": [ + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2919.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2920.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2921.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2922.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2923.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2924.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2925.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2926.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2927.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2928.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2929.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2930.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2931.jpg" + }, + { + "file_sha256": "70d000991f65a9030b90482d3b9ff66a65e76e691678ee7d81d754d3183d7226", + "relative_path": "train_resized/target/2932.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "25d5c65da44f77285889b427e7799d5c8bb160f8d0e1018a160d5b1a7d08bb0b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.564665, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "2a48ff4fc96a04771d8927323d00b8dd9739f2f1c3b3aafc6642778260d4699f", + "test_representative_target": "test_resized/Test2800/target/956_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 48.45352 + } + ], + "train_targets": [ + { + "file_sha256": "e7d0c642c6dea389621f49da3936f8ad2064af4cf5d5191a399807d40c19a415", + "relative_path": "train_resized/target/64.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "25e38a0a1b8fa07eec3471758bf5530f34d54a482ce517848f41e364c8b351d7", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.243427, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b309dc77fe0cd9b4d21572aedad9d4b8870658d595839d8590da6d1ef7e2b349", + "test_representative_target": "test_resized/Test2800/target/994_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 33.95097 + } + ], + "train_targets": [ + { + "file_sha256": "57ad412904115a4762b846cd5c9e1c9e42e397a93891aec44dd54679673827b7", + "relative_path": "train_resized/target/92.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "2c6f9c4331f6118bcedc54687701da8ee66183a3dfa4bbe30c509149d60164a9", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.791713, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "d39f8039f928025cb0b2ab15476be744ad4ab90208f8de93d88eab92524b78ed", + "test_representative_target": "test_resized/Rain100H/target/93.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.224045 + }, + { + "full_rgb_psnr_db": 22.791713, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "d39f8039f928025cb0b2ab15476be744ad4ab90208f8de93d88eab92524b78ed", + "test_representative_target": "test_resized/Rain100L/target/93.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.224045 + } + ], + "train_targets": [ + { + "file_sha256": "00c430fb195c6c3cd180ef38833fbefc27bf91459089582d13168f3dbbbbb5be", + "relative_path": "train_resized/target/1193.jpg" + }, + { + "file_sha256": "00c430fb195c6c3cd180ef38833fbefc27bf91459089582d13168f3dbbbbb5be", + "relative_path": "train_resized/target/1493.jpg" + }, + { + "file_sha256": "00c430fb195c6c3cd180ef38833fbefc27bf91459089582d13168f3dbbbbb5be", + "relative_path": "train_resized/target/1793.jpg" + }, + { + "file_sha256": "00c430fb195c6c3cd180ef38833fbefc27bf91459089582d13168f3dbbbbb5be", + "relative_path": "train_resized/target/2093.jpg" + }, + { + "file_sha256": "00c430fb195c6c3cd180ef38833fbefc27bf91459089582d13168f3dbbbbb5be", + "relative_path": "train_resized/target/2393.jpg" + }, + { + "file_sha256": "00c430fb195c6c3cd180ef38833fbefc27bf91459089582d13168f3dbbbbb5be", + "relative_path": "train_resized/target/893.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "2dfec85a17673465840900b087a3fd8e1d69216e0d68e4e4ba1829eb1a996787", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 38.25371, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "5c1c6030c1e8e1ac44d9e2f1c4e6451b7451bc96912cd7a14a18d6a96ce22fcb", + "test_representative_target": "test_resized/Test2800/target/808_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 48.004024 + } + ], + "train_targets": [ + { + "file_sha256": "607f63f7ed434a32254e0a9fd64f1a5adb5dda1b61c64cb3b542350576cd1406", + "relative_path": "train_resized/target/226.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "2ee2c30ed1e9a9a6937c883e267e463784e9d9aec4a840b60ec7b7a2d4fa1162", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.752239, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "2d974d66d98d4a3efa808b7bf033d4cfe8f3acd1ca3bb43612db0e630b677640", + "test_representative_target": "test_resized/Test100/target/63.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.959245 + }, + { + "full_rgb_psnr_db": 34.752302, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "7bc133e95f279243ad07f513a53c141a90bbadecad52197e41e592c1fa1d3994", + "test_representative_target": "test_resized/Test100/target/60.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.958976 + }, + { + "full_rgb_psnr_db": 34.752273, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "85a1429a2626e8d6943ea1b2a7fb5b206d8142212152222c349a6160e8ec9de7", + "test_representative_target": "test_resized/Test100/target/87.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.959245 + } + ], + "train_targets": [ + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9275.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9276.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9277.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9278.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9279.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9280.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9281.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9282.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9283.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9284.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9285.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9286.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9287.jpg" + }, + { + "file_sha256": "f0c7fde9fb4694086852e34a46d3b82faa96b816dca7b3d0e0c563636c7d50bc", + "relative_path": "train_resized/target/9288.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "2f141479fe6f5d44aa3bf00406f3df86411baec50846a595e072f840fa56235c", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 42.858909, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "5fec7a32e7316139131d41d363dbf1c3c393d1f8ed88ca8117df6596c547d5a6", + "test_representative_target": "test_resized/Test2800/target/826_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 52.21049 + } + ], + "train_targets": [ + { + "file_sha256": "fd8b91e4580de21970b412026c31ff05b6f4f36bd1079aee30ce40a205c83da3", + "relative_path": "train_resized/target/396.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "30790f93fa3e17347bc64889b43be7e7c5384098c445acf221878ff8569e4b19", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 39.987628, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "30f10b0e5bfc1b178c8991f3f9853a0359a4f0d1616334d6123e941f4267fd02", + "test_representative_target": "test_resized/Test100/target/74.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 49.170453 + }, + { + "full_rgb_psnr_db": 39.98776, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "58727d57cb1c46482562c1bfce65dcbd65e9616f9e2519a4b0ce95cb9977cf39", + "test_representative_target": "test_resized/Test100/target/86.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 49.170004 + }, + { + "full_rgb_psnr_db": 39.987586, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "95094839872f1dd8e631408ec5de6f49a32f91606bd84d721a889581b97f9e7a", + "test_representative_target": "test_resized/Test100/target/82.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 49.170453 + } + ], + "train_targets": [ + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10185.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10186.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10187.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10188.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10189.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10190.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10191.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10192.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10193.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10194.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10195.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10196.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10197.jpg" + }, + { + "file_sha256": "b8ae4c6034ac9f3d1107bd64e1760d4b9f70bad05ef425e331d639e66d603135", + "relative_path": "train_resized/target/10198.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "318c7413575392a1dbfd40e8d9d95d20cc17cb5ce70b491cb2debe0240ef9e88", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.640317, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "083cca7e74294f5462fbc3a177a12d855eb725891dcd5c9fd9215183f7ad287f", + "test_representative_target": "test_resized/Rain100H/target/21.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 41.386845 + }, + { + "full_rgb_psnr_db": 26.640317, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "083cca7e74294f5462fbc3a177a12d855eb725891dcd5c9fd9215183f7ad287f", + "test_representative_target": "test_resized/Rain100L/target/21.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 41.386845 + } + ], + "train_targets": [ + { + "file_sha256": "e7e89eb238c4a4ad349585b7263e273547dcb775dfe6417da04802d917601876", + "relative_path": "train_resized/target/1128.jpg" + }, + { + "file_sha256": "e7e89eb238c4a4ad349585b7263e273547dcb775dfe6417da04802d917601876", + "relative_path": "train_resized/target/1428.jpg" + }, + { + "file_sha256": "e7e89eb238c4a4ad349585b7263e273547dcb775dfe6417da04802d917601876", + "relative_path": "train_resized/target/1728.jpg" + }, + { + "file_sha256": "e7e89eb238c4a4ad349585b7263e273547dcb775dfe6417da04802d917601876", + "relative_path": "train_resized/target/2028.jpg" + }, + { + "file_sha256": "e7e89eb238c4a4ad349585b7263e273547dcb775dfe6417da04802d917601876", + "relative_path": "train_resized/target/2328.jpg" + }, + { + "file_sha256": "e7e89eb238c4a4ad349585b7263e273547dcb775dfe6417da04802d917601876", + "relative_path": "train_resized/target/828.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "32f84852215a4eced1a9339b2a637224d1374f9e84c23677eb62b402c72d3e91", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.223455, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8344ec9c91795d9d5203a0b3a17653d13df46298444545660d4b68a3339a98b8", + "test_representative_target": "test_resized/Rain100H/target/47.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 37.062693 + }, + { + "full_rgb_psnr_db": 30.223455, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8344ec9c91795d9d5203a0b3a17653d13df46298444545660d4b68a3339a98b8", + "test_representative_target": "test_resized/Rain100L/target/47.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 37.062693 + } + ], + "train_targets": [ + { + "file_sha256": "f5a639b06217c7b45ff4eba5022b50831bc1287b3ab89878dfeaf11617df2894", + "relative_path": "train_resized/target/1116.jpg" + }, + { + "file_sha256": "f5a639b06217c7b45ff4eba5022b50831bc1287b3ab89878dfeaf11617df2894", + "relative_path": "train_resized/target/1416.jpg" + }, + { + "file_sha256": "f5a639b06217c7b45ff4eba5022b50831bc1287b3ab89878dfeaf11617df2894", + "relative_path": "train_resized/target/1716.jpg" + }, + { + "file_sha256": "f5a639b06217c7b45ff4eba5022b50831bc1287b3ab89878dfeaf11617df2894", + "relative_path": "train_resized/target/2016.jpg" + }, + { + "file_sha256": "f5a639b06217c7b45ff4eba5022b50831bc1287b3ab89878dfeaf11617df2894", + "relative_path": "train_resized/target/2316.jpg" + }, + { + "file_sha256": "f5a639b06217c7b45ff4eba5022b50831bc1287b3ab89878dfeaf11617df2894", + "relative_path": "train_resized/target/816.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "333bb6eeca848987c2768e2f12174bae219af037964a8195e3bbcb03c18fd9cd", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.394729, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "2ae7a5edfb4dd08a941a0996a2e7f3c4c6e387e5082b6931b30cec39d6a016a2", + "test_representative_target": "test_resized/Rain100H/target/10.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 37.729554 + }, + { + "full_rgb_psnr_db": 25.394729, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "2ae7a5edfb4dd08a941a0996a2e7f3c4c6e387e5082b6931b30cec39d6a016a2", + "test_representative_target": "test_resized/Rain100L/target/10.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 37.729554 + } + ], + "train_targets": [ + { + "file_sha256": "3bf71de4037eadb42c65e5c1bb2c03a7eec5e208877ecee688b71e64f1c658c6", + "relative_path": "train_resized/target/1118.jpg" + }, + { + "file_sha256": "3bf71de4037eadb42c65e5c1bb2c03a7eec5e208877ecee688b71e64f1c658c6", + "relative_path": "train_resized/target/1418.jpg" + }, + { + "file_sha256": "3bf71de4037eadb42c65e5c1bb2c03a7eec5e208877ecee688b71e64f1c658c6", + "relative_path": "train_resized/target/1718.jpg" + }, + { + "file_sha256": "3bf71de4037eadb42c65e5c1bb2c03a7eec5e208877ecee688b71e64f1c658c6", + "relative_path": "train_resized/target/2018.jpg" + }, + { + "file_sha256": "3bf71de4037eadb42c65e5c1bb2c03a7eec5e208877ecee688b71e64f1c658c6", + "relative_path": "train_resized/target/2318.jpg" + }, + { + "file_sha256": "3bf71de4037eadb42c65e5c1bb2c03a7eec5e208877ecee688b71e64f1c658c6", + "relative_path": "train_resized/target/818.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "341cb4d559ad6f09404b301f8b09ac43729cf721c542346e86211e11740a66fa", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.405539, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b7f827e60fe499de92ad1bfab97b09cef556672dc48987fc6a432e9da06c42dc", + "test_representative_target": "test_resized/Rain100H/target/76.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.043544 + }, + { + "full_rgb_psnr_db": 25.405539, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b7f827e60fe499de92ad1bfab97b09cef556672dc48987fc6a432e9da06c42dc", + "test_representative_target": "test_resized/Rain100L/target/76.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.043544 + }, + { + "full_rgb_psnr_db": 25.87766, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "2a265c5777182e24ce641ab3b47470ae535182295168cbc4fa5082a1403ba851", + "test_representative_target": "test_resized/Test2800/target/940_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.67498 + } + ], + "train_targets": [ + { + "file_sha256": "1d828b10062a3855e43a21f56e88ec08c95b1af3ce6d3a5e645d46b02049dfd1", + "relative_path": "train_resized/target/1178.jpg" + }, + { + "file_sha256": "1d828b10062a3855e43a21f56e88ec08c95b1af3ce6d3a5e645d46b02049dfd1", + "relative_path": "train_resized/target/1478.jpg" + }, + { + "file_sha256": "1d828b10062a3855e43a21f56e88ec08c95b1af3ce6d3a5e645d46b02049dfd1", + "relative_path": "train_resized/target/1778.jpg" + }, + { + "file_sha256": "1d828b10062a3855e43a21f56e88ec08c95b1af3ce6d3a5e645d46b02049dfd1", + "relative_path": "train_resized/target/2078.jpg" + }, + { + "file_sha256": "1d828b10062a3855e43a21f56e88ec08c95b1af3ce6d3a5e645d46b02049dfd1", + "relative_path": "train_resized/target/2378.jpg" + }, + { + "file_sha256": "1d828b10062a3855e43a21f56e88ec08c95b1af3ce6d3a5e645d46b02049dfd1", + "relative_path": "train_resized/target/878.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "346bcf5b1c7969fa05aae47ec64912e113f41a30790102f6e96cc4ca982a39e2", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.934209, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "e737ea17d83b66399adba54110f2b9751b83aecf8d2f7bb7050ed6b67d4980ab", + "test_representative_target": "test_resized/Rain100H/target/37.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.119755 + }, + { + "full_rgb_psnr_db": 25.934209, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "e737ea17d83b66399adba54110f2b9751b83aecf8d2f7bb7050ed6b67d4980ab", + "test_representative_target": "test_resized/Rain100L/target/37.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.119755 + } + ], + "train_targets": [ + { + "file_sha256": "6dd3e4927b4b088ab72b7b84ea9fe4be177d294eaeb489155af194ec2add0337", + "relative_path": "train_resized/target/185.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "3667eba807a3c5abcd7dcc0160878f7733e0a9f19e114992fa0fac62954f29b5", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.312575, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "f81db4aada39ac8b488e0bad131d05663694f507d1cde3f414c855bb2776af1c", + "test_representative_target": "test_resized/Rain100H/target/19.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.748226 + }, + { + "full_rgb_psnr_db": 25.312575, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "f81db4aada39ac8b488e0bad131d05663694f507d1cde3f414c855bb2776af1c", + "test_representative_target": "test_resized/Rain100L/target/19.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.748226 + }, + { + "full_rgb_psnr_db": 25.466586, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "20a48ce6dd71895e2002d1e192bbf14255d5becfccb23c63300e80aade1bea4a", + "test_representative_target": "test_resized/Test2800/target/894_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.032788 + } + ], + "train_targets": [ + { + "file_sha256": "6cf5cf71b25290c37aaeddbeba79bdbb77850d383b369c30509044ec6039b16c", + "relative_path": "train_resized/target/1126.jpg" + }, + { + "file_sha256": "6cf5cf71b25290c37aaeddbeba79bdbb77850d383b369c30509044ec6039b16c", + "relative_path": "train_resized/target/1426.jpg" + }, + { + "file_sha256": "6cf5cf71b25290c37aaeddbeba79bdbb77850d383b369c30509044ec6039b16c", + "relative_path": "train_resized/target/1726.jpg" + }, + { + "file_sha256": "6cf5cf71b25290c37aaeddbeba79bdbb77850d383b369c30509044ec6039b16c", + "relative_path": "train_resized/target/2026.jpg" + }, + { + "file_sha256": "6cf5cf71b25290c37aaeddbeba79bdbb77850d383b369c30509044ec6039b16c", + "relative_path": "train_resized/target/2326.jpg" + }, + { + "file_sha256": "6cf5cf71b25290c37aaeddbeba79bdbb77850d383b369c30509044ec6039b16c", + "relative_path": "train_resized/target/826.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "372f0807e25fa17d7fc83aeaebf51aba91b8992c47ce51a35e411169c0a5cf42", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.354343, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "bcab48b5234ae68f89dd69925e15cbddcbefb590806dc03acfb25c3e74c83dcc", + "test_representative_target": "test_resized/Test2800/target/939_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.47809 + } + ], + "train_targets": [ + { + "file_sha256": "9325bda7208ea1a7d2b70b92f59ff56cbb2bcd44a95e9d448c632902629c4488", + "relative_path": "train_resized/target/545.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "376e05f0fc196314bd544333968d89f36834a8c7fc264e54f20074fec2045b56", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.789199, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "d39f8039f928025cb0b2ab15476be744ad4ab90208f8de93d88eab92524b78ed", + "test_representative_target": "test_resized/Rain100H/target/93.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.206537 + }, + { + "full_rgb_psnr_db": 22.789199, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "d39f8039f928025cb0b2ab15476be744ad4ab90208f8de93d88eab92524b78ed", + "test_representative_target": "test_resized/Rain100L/target/93.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.206537 + } + ], + "train_targets": [ + { + "file_sha256": "534bbb669386631adfbe490d2be74e4df6cb94b5739493e3fdf16372fe7652b8", + "relative_path": "train_resized/target/181.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "37c14350c3e322a5d5d5b733606c7ac897f898c1ab9f3481467cc48a53d82c0b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 35.754172, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "5632ec7bdd0a714ecf286aedb0c443d30375687aab14d93ef7a8e27f4469f7b8", + "test_representative_target": "test_resized/Rain100H/target/15.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 44.309765 + }, + { + "full_rgb_psnr_db": 35.754172, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "5632ec7bdd0a714ecf286aedb0c443d30375687aab14d93ef7a8e27f4469f7b8", + "test_representative_target": "test_resized/Rain100L/target/15.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 44.309765 + } + ], + "train_targets": [ + { + "file_sha256": "6322cb9ff1a5f96f503e864dbd4b869d1cba41e356c86c758af5d43852665196", + "relative_path": "train_resized/target/1122.jpg" + }, + { + "file_sha256": "6322cb9ff1a5f96f503e864dbd4b869d1cba41e356c86c758af5d43852665196", + "relative_path": "train_resized/target/1422.jpg" + }, + { + "file_sha256": "6322cb9ff1a5f96f503e864dbd4b869d1cba41e356c86c758af5d43852665196", + "relative_path": "train_resized/target/1722.jpg" + }, + { + "file_sha256": "6322cb9ff1a5f96f503e864dbd4b869d1cba41e356c86c758af5d43852665196", + "relative_path": "train_resized/target/2022.jpg" + }, + { + "file_sha256": "6322cb9ff1a5f96f503e864dbd4b869d1cba41e356c86c758af5d43852665196", + "relative_path": "train_resized/target/2322.jpg" + }, + { + "file_sha256": "6322cb9ff1a5f96f503e864dbd4b869d1cba41e356c86c758af5d43852665196", + "relative_path": "train_resized/target/822.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "3b032345f88359d5ab1b8c8c413a8ddbafb0e713fa7d0c22a6827de580edb4b5", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.788579, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "1a367ada4b394f18b1f072999432397a703b77cd0d78a5454cd56281ad713e80", + "test_representative_target": "test_resized/Test100/target/73.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.669321 + } + ], + "train_targets": [ + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9065.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9066.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9067.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9068.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9069.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9070.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9071.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9072.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9073.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9074.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9075.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9076.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9077.jpg" + }, + { + "file_sha256": "04ceafcf6def220b7125c9b4074c3dc4b05b5248e95470bbf02c2dd5a3df3eb7", + "relative_path": "train_resized/target/9078.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "3b77a249752f95c60e93dc1d7cb6ea399c2995f156b9bdf7a3440d8803606504", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.706881, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "2690b44901fbbe24aa03da603aea25c5e767fb98f057cb57fb0ecd233dbe76bf", + "test_representative_target": "test_resized/Rain100H/target/25.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 38.517064 + }, + { + "full_rgb_psnr_db": 24.706881, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "2690b44901fbbe24aa03da603aea25c5e767fb98f057cb57fb0ecd233dbe76bf", + "test_representative_target": "test_resized/Rain100L/target/25.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 38.517064 + } + ], + "train_targets": [ + { + "file_sha256": "43af4586e6c7a8926d3d03c8f956c785918355c403244448aeb37d7ed75a5f35", + "relative_path": "train_resized/target/1114.jpg" + }, + { + "file_sha256": "43af4586e6c7a8926d3d03c8f956c785918355c403244448aeb37d7ed75a5f35", + "relative_path": "train_resized/target/1414.jpg" + }, + { + "file_sha256": "43af4586e6c7a8926d3d03c8f956c785918355c403244448aeb37d7ed75a5f35", + "relative_path": "train_resized/target/1714.jpg" + }, + { + "file_sha256": "43af4586e6c7a8926d3d03c8f956c785918355c403244448aeb37d7ed75a5f35", + "relative_path": "train_resized/target/2014.jpg" + }, + { + "file_sha256": "43af4586e6c7a8926d3d03c8f956c785918355c403244448aeb37d7ed75a5f35", + "relative_path": "train_resized/target/2314.jpg" + }, + { + "file_sha256": "43af4586e6c7a8926d3d03c8f956c785918355c403244448aeb37d7ed75a5f35", + "relative_path": "train_resized/target/814.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "3c37317a5521bd84f5cc98ce25b832397dd46bc32a5d63b31b14eb118fa0ab2b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 36.466761, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "ebee00248fd142a04849d11b723a7db969f6d56f1031b4e391205a9fc66804de", + "test_representative_target": "test_resized/Test100/target/66.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.318599 + } + ], + "train_targets": [ + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10815.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10816.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10817.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10818.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10819.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10820.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10821.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10822.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10823.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10824.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10825.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10826.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10827.jpg" + }, + { + "file_sha256": "2896fcc4b86a3994c66ed8de5f98dc9b10cd4535e09cc2ae05d4bac51e9b761e", + "relative_path": "train_resized/target/10828.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "3c452b66e9b9b3f80546f60f3fe0a80967142af1225293b5d9063a4c23b826d5", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.09632, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "8712aa0a875167e78b1057f6d9e7978b03031c2345ed8ec4077c1121460fded0", + "test_representative_target": "test_resized/Rain100H/target/94.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 41.633137 + }, + { + "full_rgb_psnr_db": 28.09632, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "8712aa0a875167e78b1057f6d9e7978b03031c2345ed8ec4077c1121460fded0", + "test_representative_target": "test_resized/Rain100L/target/94.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 41.633137 + } + ], + "train_targets": [ + { + "file_sha256": "d651e084d4a601380c182d938653e0a898ec74148fbe4e864bc2e4fe63282e95", + "relative_path": "train_resized/target/1194.jpg" + }, + { + "file_sha256": "d651e084d4a601380c182d938653e0a898ec74148fbe4e864bc2e4fe63282e95", + "relative_path": "train_resized/target/1494.jpg" + }, + { + "file_sha256": "d651e084d4a601380c182d938653e0a898ec74148fbe4e864bc2e4fe63282e95", + "relative_path": "train_resized/target/1794.jpg" + }, + { + "file_sha256": "d651e084d4a601380c182d938653e0a898ec74148fbe4e864bc2e4fe63282e95", + "relative_path": "train_resized/target/2094.jpg" + }, + { + "file_sha256": "d651e084d4a601380c182d938653e0a898ec74148fbe4e864bc2e4fe63282e95", + "relative_path": "train_resized/target/2394.jpg" + }, + { + "file_sha256": "d651e084d4a601380c182d938653e0a898ec74148fbe4e864bc2e4fe63282e95", + "relative_path": "train_resized/target/894.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "3d82735d93b17517046b5fac2edc27df2742485f74ddb5418c8f50697faa3c1f", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.00711, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c4f3970373ef0a5470d481d06247f50a8fb1fb2e3835969c0c62641ec38e1f5f", + "test_representative_target": "test_resized/Rain100H/target/42.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.70436 + }, + { + "full_rgb_psnr_db": 25.00711, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c4f3970373ef0a5470d481d06247f50a8fb1fb2e3835969c0c62641ec38e1f5f", + "test_representative_target": "test_resized/Rain100L/target/42.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.70436 + }, + { + "full_rgb_psnr_db": 25.127928, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b9f57f3ed10c469070b3e628398d438fc977287dac58ebed40f53cd234aeaded", + "test_representative_target": "test_resized/Test2800/target/917_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.964388 + } + ], + "train_targets": [ + { + "file_sha256": "e32c1081af203cae39088d924933ca5e51f0f5f94a089b7bb8ab63aca510003a", + "relative_path": "train_resized/target/81.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "3e43c81142ab18fc1fe441b05c1408e2209cb0248f3246e4f7c1ec277cc7cca6", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.212341, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9533fdb6bccba3a0045944de7c08663184c11b2fdc229ce455f2c09d54997f53", + "test_representative_target": "test_resized/Rain100H/target/27.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.404612 + }, + { + "full_rgb_psnr_db": 26.212341, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9533fdb6bccba3a0045944de7c08663184c11b2fdc229ce455f2c09d54997f53", + "test_representative_target": "test_resized/Rain100L/target/27.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.404612 + }, + { + "full_rgb_psnr_db": 26.427504, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "4499cb8f8834a1475002b3ce65fd317cdd4d5ecc9ed7c4ea8e06e319fa547c0d", + "test_representative_target": "test_resized/Test2800/target/909_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 39.117744 + } + ], + "train_targets": [ + { + "file_sha256": "bde53047e6cd7d62c527a2ef990e868c34d5f2b233c6e0d01a971befd78f2b5d", + "relative_path": "train_resized/target/1133.jpg" + }, + { + "file_sha256": "bde53047e6cd7d62c527a2ef990e868c34d5f2b233c6e0d01a971befd78f2b5d", + "relative_path": "train_resized/target/1433.jpg" + }, + { + "file_sha256": "bde53047e6cd7d62c527a2ef990e868c34d5f2b233c6e0d01a971befd78f2b5d", + "relative_path": "train_resized/target/1733.jpg" + }, + { + "file_sha256": "bde53047e6cd7d62c527a2ef990e868c34d5f2b233c6e0d01a971befd78f2b5d", + "relative_path": "train_resized/target/2033.jpg" + }, + { + "file_sha256": "bde53047e6cd7d62c527a2ef990e868c34d5f2b233c6e0d01a971befd78f2b5d", + "relative_path": "train_resized/target/2333.jpg" + }, + { + "file_sha256": "bde53047e6cd7d62c527a2ef990e868c34d5f2b233c6e0d01a971befd78f2b5d", + "relative_path": "train_resized/target/833.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "3ece780c8dfb76a54c357bd6a4c5a91420b0058e0ce88a1f5dd6b1298b74d94d", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.835939, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cec577f5122e0ec336459f7f9f485f36ac7ecff475371f2878329e5a138953ee", + "test_representative_target": "test_resized/Rain100H/target/88.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.036105 + }, + { + "full_rgb_psnr_db": 28.835939, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cec577f5122e0ec336459f7f9f485f36ac7ecff475371f2878329e5a138953ee", + "test_representative_target": "test_resized/Rain100L/target/88.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.036105 + } + ], + "train_targets": [ + { + "file_sha256": "c9def7767cdd236e3ce68cf481f7b4f44222c938457f7263aa38f00c8dee6680", + "relative_path": "train_resized/target/13.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "405b99d258703db4dd51688d13b5feb9edd4e8728bff059685ae919bef4cee8b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.583494, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "928718141044bc4423470b5b76641b64ea783a3add3e8646faa966e090af9c3b", + "test_representative_target": "test_resized/Rain100H/target/70.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.013213 + }, + { + "full_rgb_psnr_db": 24.583494, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "928718141044bc4423470b5b76641b64ea783a3add3e8646faa966e090af9c3b", + "test_representative_target": "test_resized/Rain100L/target/70.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.013213 + }, + { + "full_rgb_psnr_db": 24.656791, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "73b2b94a218a3da33b7f65d5e7744ffee4fd548a834f4edd72e189116dab8ef8", + "test_representative_target": "test_resized/Test2800/target/932_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.280588 + } + ], + "train_targets": [ + { + "file_sha256": "d5ac91c5270d6e2ab2d3697b209bbd1ce04fa4f5d82c3f6522a4d15460677521", + "relative_path": "train_resized/target/376.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "40b488c6131b513ec040e9b5792bed44427a36498c51fe1f2392520478a0d0df", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.105795, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "3a43a838579fcbe4fac5b8c1bd6318dcde2e337c66404a515257e5091e2dc01e", + "test_representative_target": "test_resized/Test2800/target/978_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.512162 + } + ], + "train_targets": [ + { + "file_sha256": "cb7ea7bb404e5d92fd2b5751ce449c9c46ee66b8a9f5b0a7b699f8c584de8f27", + "relative_path": "train_resized/target/1245.jpg" + }, + { + "file_sha256": "cb7ea7bb404e5d92fd2b5751ce449c9c46ee66b8a9f5b0a7b699f8c584de8f27", + "relative_path": "train_resized/target/1545.jpg" + }, + { + "file_sha256": "cb7ea7bb404e5d92fd2b5751ce449c9c46ee66b8a9f5b0a7b699f8c584de8f27", + "relative_path": "train_resized/target/1845.jpg" + }, + { + "file_sha256": "cb7ea7bb404e5d92fd2b5751ce449c9c46ee66b8a9f5b0a7b699f8c584de8f27", + "relative_path": "train_resized/target/2145.jpg" + }, + { + "file_sha256": "cb7ea7bb404e5d92fd2b5751ce449c9c46ee66b8a9f5b0a7b699f8c584de8f27", + "relative_path": "train_resized/target/2445.jpg" + }, + { + "file_sha256": "cb7ea7bb404e5d92fd2b5751ce449c9c46ee66b8a9f5b0a7b699f8c584de8f27", + "relative_path": "train_resized/target/945.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "40dace86cdf7b7258b4afbdd25288d4abf040ee2aadee4f3af191e5dc7ee6acc", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.41718, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4161965fe3971b91bf75b7539a690fe8572e0946306c5c3bce7bc12629204fc7", + "test_representative_target": "test_resized/Rain100H/target/38.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.764671 + }, + { + "full_rgb_psnr_db": 25.41718, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4161965fe3971b91bf75b7539a690fe8572e0946306c5c3bce7bc12629204fc7", + "test_representative_target": "test_resized/Rain100L/target/38.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.764671 + } + ], + "train_targets": [ + { + "file_sha256": "bf4cdd8479ad47cdfd386b32405dda628129072c3e2afcbf12c7a6340031e5c1", + "relative_path": "train_resized/target/1143.jpg" + }, + { + "file_sha256": "bf4cdd8479ad47cdfd386b32405dda628129072c3e2afcbf12c7a6340031e5c1", + "relative_path": "train_resized/target/1443.jpg" + }, + { + "file_sha256": "bf4cdd8479ad47cdfd386b32405dda628129072c3e2afcbf12c7a6340031e5c1", + "relative_path": "train_resized/target/1743.jpg" + }, + { + "file_sha256": "bf4cdd8479ad47cdfd386b32405dda628129072c3e2afcbf12c7a6340031e5c1", + "relative_path": "train_resized/target/2043.jpg" + }, + { + "file_sha256": "bf4cdd8479ad47cdfd386b32405dda628129072c3e2afcbf12c7a6340031e5c1", + "relative_path": "train_resized/target/2343.jpg" + }, + { + "file_sha256": "bf4cdd8479ad47cdfd386b32405dda628129072c3e2afcbf12c7a6340031e5c1", + "relative_path": "train_resized/target/843.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "4171bbee3fdad5ad030425ce328edfd1f5a7d6da8f9d59aca2709701724fb9d5", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.348305, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "4043dd1140d3ab6f0cb9de714f662fecd1e5b256dd8bfca083a9b8be0944240c", + "test_representative_target": "test_resized/Rain100H/target/45.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.160064 + }, + { + "full_rgb_psnr_db": 23.348305, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "4043dd1140d3ab6f0cb9de714f662fecd1e5b256dd8bfca083a9b8be0944240c", + "test_representative_target": "test_resized/Rain100L/target/45.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.160064 + } + ], + "train_targets": [ + { + "file_sha256": "594067ca7255786626dfb0fa76f738005d9985d58132a94b1487541a65971deb", + "relative_path": "train_resized/target/166.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "45dc11899f9ac3bea0c7e867fb7906deee64375e3fe3f1879237732507f38360", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.887757, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "1f012f718be05b7ad960d780ff82894a858e40b40c67ad17b6f574f2a24be2db", + "test_representative_target": "test_resized/Rain100H/target/40.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.464599 + }, + { + "full_rgb_psnr_db": 24.887757, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "1f012f718be05b7ad960d780ff82894a858e40b40c67ad17b6f574f2a24be2db", + "test_representative_target": "test_resized/Rain100L/target/40.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.464599 + }, + { + "full_rgb_psnr_db": 24.920003, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "74d5d61496457c6c4a18117e9d9fb50a67bb0ef1be8296a48c34d2e4e10bc464", + "test_representative_target": "test_resized/Test2800/target/915_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.693826 + } + ], + "train_targets": [ + { + "file_sha256": "95a96957a8d53e84c07f9f012785f62866e8bafe24f3abaa799bf5bca873b7d6", + "relative_path": "train_resized/target/1145.jpg" + }, + { + "file_sha256": "95a96957a8d53e84c07f9f012785f62866e8bafe24f3abaa799bf5bca873b7d6", + "relative_path": "train_resized/target/1445.jpg" + }, + { + "file_sha256": "95a96957a8d53e84c07f9f012785f62866e8bafe24f3abaa799bf5bca873b7d6", + "relative_path": "train_resized/target/1745.jpg" + }, + { + "file_sha256": "95a96957a8d53e84c07f9f012785f62866e8bafe24f3abaa799bf5bca873b7d6", + "relative_path": "train_resized/target/2045.jpg" + }, + { + "file_sha256": "95a96957a8d53e84c07f9f012785f62866e8bafe24f3abaa799bf5bca873b7d6", + "relative_path": "train_resized/target/2345.jpg" + }, + { + "file_sha256": "95a96957a8d53e84c07f9f012785f62866e8bafe24f3abaa799bf5bca873b7d6", + "relative_path": "train_resized/target/845.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "463415d5c1662a30b120ba10b27cee48e9569c78f36877e61402b493a1b1b5a7", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.295251, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "0f22c90938dd5f363b7825741212d03d6b0295401b529bde203b94e0acf9c60d", + "test_representative_target": "test_resized/Rain100H/target/95.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 40.477092 + }, + { + "full_rgb_psnr_db": 30.295251, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "0f22c90938dd5f363b7825741212d03d6b0295401b529bde203b94e0acf9c60d", + "test_representative_target": "test_resized/Rain100L/target/95.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 40.477092 + } + ], + "train_targets": [ + { + "file_sha256": "aded3d595d7e1cf864997b95802c3b041df4e46d73e92258ebebf464050343f4", + "relative_path": "train_resized/target/1195.jpg" + }, + { + "file_sha256": "aded3d595d7e1cf864997b95802c3b041df4e46d73e92258ebebf464050343f4", + "relative_path": "train_resized/target/1495.jpg" + }, + { + "file_sha256": "aded3d595d7e1cf864997b95802c3b041df4e46d73e92258ebebf464050343f4", + "relative_path": "train_resized/target/1795.jpg" + }, + { + "file_sha256": "aded3d595d7e1cf864997b95802c3b041df4e46d73e92258ebebf464050343f4", + "relative_path": "train_resized/target/2095.jpg" + }, + { + "file_sha256": "aded3d595d7e1cf864997b95802c3b041df4e46d73e92258ebebf464050343f4", + "relative_path": "train_resized/target/2395.jpg" + }, + { + "file_sha256": "aded3d595d7e1cf864997b95802c3b041df4e46d73e92258ebebf464050343f4", + "relative_path": "train_resized/target/895.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "48895bf53c760f3a192614414e7a13307e3af0a1f0004af8de633383c66e0091", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 38.462136, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "0bb7c8d3f6c2340c8118bc42c8a44fcbb091013b0cbd2b16b4b191482a126ad7", + "test_representative_target": "test_resized/Test2800/target/946_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 48.622758 + } + ], + "train_targets": [ + { + "file_sha256": "d27665dde1093d0876d64fcf10d0b6fdf90ccdb0894a83bc00960253b5270eb6", + "relative_path": "train_resized/target/472.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "48a1bd0dbc16a6e363f24addbc344bb0049cd9584c39edb67c05fd2f7cd50daa", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 20.703884, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b9274673c1b0168a399df38878b724ecc29bfed36629b6be38a928bdfc1461d9", + "test_representative_target": "test_resized/Rain100H/target/24.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.187223 + }, + { + "full_rgb_psnr_db": 20.703884, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b9274673c1b0168a399df38878b724ecc29bfed36629b6be38a928bdfc1461d9", + "test_representative_target": "test_resized/Rain100L/target/24.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.187223 + } + ], + "train_targets": [ + { + "file_sha256": "55dad8259d4bc57b40d35be282a8822566b0f885a237e73732da761d41cf919b", + "relative_path": "train_resized/target/1131.jpg" + }, + { + "file_sha256": "55dad8259d4bc57b40d35be282a8822566b0f885a237e73732da761d41cf919b", + "relative_path": "train_resized/target/1431.jpg" + }, + { + "file_sha256": "55dad8259d4bc57b40d35be282a8822566b0f885a237e73732da761d41cf919b", + "relative_path": "train_resized/target/1731.jpg" + }, + { + "file_sha256": "55dad8259d4bc57b40d35be282a8822566b0f885a237e73732da761d41cf919b", + "relative_path": "train_resized/target/2031.jpg" + }, + { + "file_sha256": "55dad8259d4bc57b40d35be282a8822566b0f885a237e73732da761d41cf919b", + "relative_path": "train_resized/target/2331.jpg" + }, + { + "file_sha256": "55dad8259d4bc57b40d35be282a8822566b0f885a237e73732da761d41cf919b", + "relative_path": "train_resized/target/831.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "496112b59f85d5dc58d6607fcc3a5d198132aa70cd9c2ec3d701810a3840dad1", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.014223, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "36a21011ae2700a26e478c423b28b4a6d06d86d88e8baf0c931179f91380a7a9", + "test_representative_target": "test_resized/Rain100H/target/14.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 40.294968 + }, + { + "full_rgb_psnr_db": 28.014223, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "36a21011ae2700a26e478c423b28b4a6d06d86d88e8baf0c931179f91380a7a9", + "test_representative_target": "test_resized/Rain100L/target/14.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 40.294968 + } + ], + "train_targets": [ + { + "file_sha256": "08d03f214d8ded63dbb0ef884734a57c9d88971138c6acdd4324dd879f8cf8d7", + "relative_path": "train_resized/target/1113.jpg" + }, + { + "file_sha256": "08d03f214d8ded63dbb0ef884734a57c9d88971138c6acdd4324dd879f8cf8d7", + "relative_path": "train_resized/target/1413.jpg" + }, + { + "file_sha256": "08d03f214d8ded63dbb0ef884734a57c9d88971138c6acdd4324dd879f8cf8d7", + "relative_path": "train_resized/target/1713.jpg" + }, + { + "file_sha256": "08d03f214d8ded63dbb0ef884734a57c9d88971138c6acdd4324dd879f8cf8d7", + "relative_path": "train_resized/target/2013.jpg" + }, + { + "file_sha256": "08d03f214d8ded63dbb0ef884734a57c9d88971138c6acdd4324dd879f8cf8d7", + "relative_path": "train_resized/target/2313.jpg" + }, + { + "file_sha256": "08d03f214d8ded63dbb0ef884734a57c9d88971138c6acdd4324dd879f8cf8d7", + "relative_path": "train_resized/target/813.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "4c70f80c5a2a1525555d218bb020192aeaefe4934c47d7b10f0eb9938a64ae77", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.892041, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "1f012f718be05b7ad960d780ff82894a858e40b40c67ad17b6f574f2a24be2db", + "test_representative_target": "test_resized/Rain100H/target/40.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.474025 + }, + { + "full_rgb_psnr_db": 24.892041, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "1f012f718be05b7ad960d780ff82894a858e40b40c67ad17b6f574f2a24be2db", + "test_representative_target": "test_resized/Rain100L/target/40.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.474025 + }, + { + "full_rgb_psnr_db": 24.923996, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "74d5d61496457c6c4a18117e9d9fb50a67bb0ef1be8296a48c34d2e4e10bc464", + "test_representative_target": "test_resized/Test2800/target/915_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.711659 + } + ], + "train_targets": [ + { + "file_sha256": "428f746696dd466cb5b36467883d10aef7b9dc46c3448f7f950ff7574e5d5444", + "relative_path": "train_resized/target/52.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "4d12451e52290d0673717d293e439b5c6a00369a7046f81d5e5e7ae127b1c99b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.05974, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "5d34ccd30d1bde007f6064c16fefce1702c20a73a013dc7d324df080bcb8b7f3", + "test_representative_target": "test_resized/Rain100H/target/90.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.853803 + }, + { + "full_rgb_psnr_db": 26.05974, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "5d34ccd30d1bde007f6064c16fefce1702c20a73a013dc7d324df080bcb8b7f3", + "test_representative_target": "test_resized/Rain100L/target/90.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.853803 + }, + { + "full_rgb_psnr_db": 26.257687, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "3fbe506f8f82fca6948f4a3e61f2d4d257a9124899bb41676171ead0d1f4efba", + "test_representative_target": "test_resized/Test2800/target/947_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.07527 + } + ], + "train_targets": [ + { + "file_sha256": "290c119bb33c1557600a4aec2e6ed5217b4c434f15346f3adb7f489a761aeff4", + "relative_path": "train_resized/target/1191.jpg" + }, + { + "file_sha256": "290c119bb33c1557600a4aec2e6ed5217b4c434f15346f3adb7f489a761aeff4", + "relative_path": "train_resized/target/1491.jpg" + }, + { + "file_sha256": "290c119bb33c1557600a4aec2e6ed5217b4c434f15346f3adb7f489a761aeff4", + "relative_path": "train_resized/target/1791.jpg" + }, + { + "file_sha256": "290c119bb33c1557600a4aec2e6ed5217b4c434f15346f3adb7f489a761aeff4", + "relative_path": "train_resized/target/2091.jpg" + }, + { + "file_sha256": "290c119bb33c1557600a4aec2e6ed5217b4c434f15346f3adb7f489a761aeff4", + "relative_path": "train_resized/target/2391.jpg" + }, + { + "file_sha256": "290c119bb33c1557600a4aec2e6ed5217b4c434f15346f3adb7f489a761aeff4", + "relative_path": "train_resized/target/891.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "4e54d9fe4f965238333d7e4d7fec31a6c69e9c58629504834a9fe96252bd6a4d", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.235826, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "0af2becf79b76819d9712bcdd9a0d894638ccc1f14c66221816397768732bbfe", + "test_representative_target": "test_resized/Test2800/target/964_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 33.909282 + } + ], + "train_targets": [ + { + "file_sha256": "23f3058017d8f40501bb00e7a5c77723998b532f6c5ee4ff7602ff42694948d2", + "relative_path": "train_resized/target/581.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "4e695ba0bd931c795f74f3ff0599ce3ab15bbd4343479a749ab85694e1fa1ce8", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.93759, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "e737ea17d83b66399adba54110f2b9751b83aecf8d2f7bb7050ed6b67d4980ab", + "test_representative_target": "test_resized/Rain100H/target/37.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.157143 + }, + { + "full_rgb_psnr_db": 25.93759, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "e737ea17d83b66399adba54110f2b9751b83aecf8d2f7bb7050ed6b67d4980ab", + "test_representative_target": "test_resized/Rain100L/target/37.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.157143 + } + ], + "train_targets": [ + { + "file_sha256": "fb1a8ad164ff11045700e611cd7199a8d1522bec9880609a154e32b86b41435d", + "relative_path": "train_resized/target/1142.jpg" + }, + { + "file_sha256": "fb1a8ad164ff11045700e611cd7199a8d1522bec9880609a154e32b86b41435d", + "relative_path": "train_resized/target/1442.jpg" + }, + { + "file_sha256": "fb1a8ad164ff11045700e611cd7199a8d1522bec9880609a154e32b86b41435d", + "relative_path": "train_resized/target/1742.jpg" + }, + { + "file_sha256": "fb1a8ad164ff11045700e611cd7199a8d1522bec9880609a154e32b86b41435d", + "relative_path": "train_resized/target/2042.jpg" + }, + { + "file_sha256": "fb1a8ad164ff11045700e611cd7199a8d1522bec9880609a154e32b86b41435d", + "relative_path": "train_resized/target/2342.jpg" + }, + { + "file_sha256": "fb1a8ad164ff11045700e611cd7199a8d1522bec9880609a154e32b86b41435d", + "relative_path": "train_resized/target/842.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "4e8a9e50dd70dccfeffba8aa91210304da96bb4920c10f9e45b18d0a1770fa87", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.983613, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a8bf5885b786ccbe9d9628d01913fd000f5a8c7c4554693620a5bd617489907d", + "test_representative_target": "test_resized/Rain100H/target/11.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 38.159384 + }, + { + "full_rgb_psnr_db": 30.983613, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a8bf5885b786ccbe9d9628d01913fd000f5a8c7c4554693620a5bd617489907d", + "test_representative_target": "test_resized/Rain100L/target/11.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 38.159384 + } + ], + "train_targets": [ + { + "file_sha256": "eadd974763d432bf586a5c903f032f1089f01ce671fb51fdf1261afaee02dd72", + "relative_path": "train_resized/target/1119.jpg" + }, + { + "file_sha256": "eadd974763d432bf586a5c903f032f1089f01ce671fb51fdf1261afaee02dd72", + "relative_path": "train_resized/target/1419.jpg" + }, + { + "file_sha256": "eadd974763d432bf586a5c903f032f1089f01ce671fb51fdf1261afaee02dd72", + "relative_path": "train_resized/target/1719.jpg" + }, + { + "file_sha256": "eadd974763d432bf586a5c903f032f1089f01ce671fb51fdf1261afaee02dd72", + "relative_path": "train_resized/target/2019.jpg" + }, + { + "file_sha256": "eadd974763d432bf586a5c903f032f1089f01ce671fb51fdf1261afaee02dd72", + "relative_path": "train_resized/target/2319.jpg" + }, + { + "file_sha256": "eadd974763d432bf586a5c903f032f1089f01ce671fb51fdf1261afaee02dd72", + "relative_path": "train_resized/target/819.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "4fd06a8c93b9a69506aa9b914c028a0afb486e8932557cfd9df9ebaa05dee589", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.586747, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a3a3010fd6c5ebae8d1759c156a0b762969ab2a2110c156d49e5c0b9e8e5f17c", + "test_representative_target": "test_resized/Test2800/target/997_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.54286 + } + ], + "train_targets": [ + { + "file_sha256": "36bbe15cb4c4deefa3b1d580da8417ae022a1497c082acc435893d9329d41b30", + "relative_path": "train_resized/target/627.jpg" + }, + { + "file_sha256": "36bbe15cb4c4deefa3b1d580da8417ae022a1497c082acc435893d9329d41b30", + "relative_path": "train_resized/target/641.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "50773bf870cf0da3030759e7e78338d635471ddcaccac27ba41afcccf93bcc67", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.058792, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c35eebc58ec685da71160eedd3dd607f9954a57a0bc8a4af0233b7a6852ae9c9", + "test_representative_target": "test_resized/Test2800/target/935_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.418964 + } + ], + "train_targets": [ + { + "file_sha256": "18943337ecffff56f1b48aacc8fbc4a23805d67381003344e2ebd1d05a9a25d1", + "relative_path": "train_resized/target/602.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "517e86ac66539ecb9188404e7b821c1b9cd7d794856e01d1fbd30ccd43df97eb", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.592336, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "928718141044bc4423470b5b76641b64ea783a3add3e8646faa966e090af9c3b", + "test_representative_target": "test_resized/Rain100H/target/70.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.066344 + }, + { + "full_rgb_psnr_db": 24.592336, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "928718141044bc4423470b5b76641b64ea783a3add3e8646faa966e090af9c3b", + "test_representative_target": "test_resized/Rain100L/target/70.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.066344 + }, + { + "full_rgb_psnr_db": 24.657626, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "73b2b94a218a3da33b7f65d5e7744ffee4fd548a834f4edd72e189116dab8ef8", + "test_representative_target": "test_resized/Test2800/target/932_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.287029 + } + ], + "train_targets": [ + { + "file_sha256": "df5ce8510970be6368a85e732439a61843bf91b565515cc1d3e6350e6c89ed0d", + "relative_path": "train_resized/target/1172.jpg" + }, + { + "file_sha256": "df5ce8510970be6368a85e732439a61843bf91b565515cc1d3e6350e6c89ed0d", + "relative_path": "train_resized/target/1472.jpg" + }, + { + "file_sha256": "df5ce8510970be6368a85e732439a61843bf91b565515cc1d3e6350e6c89ed0d", + "relative_path": "train_resized/target/1772.jpg" + }, + { + "file_sha256": "df5ce8510970be6368a85e732439a61843bf91b565515cc1d3e6350e6c89ed0d", + "relative_path": "train_resized/target/2072.jpg" + }, + { + "file_sha256": "df5ce8510970be6368a85e732439a61843bf91b565515cc1d3e6350e6c89ed0d", + "relative_path": "train_resized/target/2372.jpg" + }, + { + "file_sha256": "df5ce8510970be6368a85e732439a61843bf91b565515cc1d3e6350e6c89ed0d", + "relative_path": "train_resized/target/872.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "51837014f51d22a9a3d28995a3a0e8dd67cb542b934df91b087a2fa7e74b5ea0", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.29575, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "67dbd30b28c0c817b73a7e721571a747c8034b075723a448c7a00ec4736e6d3a", + "test_representative_target": "test_resized/Test2800/target/922_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.678427 + } + ], + "train_targets": [ + { + "file_sha256": "2c577aa1d636643fec43a10a93fbab3372591c486210af2e9b5e7fa8bff7d1d4", + "relative_path": "train_resized/target/463.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "526cea0c11b96a8d754e96a6644e63e637fa5d06216787b5495ccad38a767cfd", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.291147, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8ee2aeccbcae65bed2ca903966cb6e13f4a2dbc30a449b70d31d88247e12c3db", + "test_representative_target": "test_resized/Rain100H/target/52.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.147674 + }, + { + "full_rgb_psnr_db": 28.291147, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8ee2aeccbcae65bed2ca903966cb6e13f4a2dbc30a449b70d31d88247e12c3db", + "test_representative_target": "test_resized/Rain100L/target/52.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.147674 + }, + { + "full_rgb_psnr_db": 28.529436, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "2250c82ffa5b9bd5a3f0e5713eddb5e4afc9df0c666dcf33a609b303adff8716", + "test_representative_target": "test_resized/Test2800/target/923_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.564987 + } + ], + "train_targets": [ + { + "file_sha256": "acf432e6cf85fab129547ba5f66a5f90d941f35cf22f9f919f34801238d3528d", + "relative_path": "train_resized/target/1156.jpg" + }, + { + "file_sha256": "acf432e6cf85fab129547ba5f66a5f90d941f35cf22f9f919f34801238d3528d", + "relative_path": "train_resized/target/1456.jpg" + }, + { + "file_sha256": "acf432e6cf85fab129547ba5f66a5f90d941f35cf22f9f919f34801238d3528d", + "relative_path": "train_resized/target/1756.jpg" + }, + { + "file_sha256": "acf432e6cf85fab129547ba5f66a5f90d941f35cf22f9f919f34801238d3528d", + "relative_path": "train_resized/target/2056.jpg" + }, + { + "file_sha256": "acf432e6cf85fab129547ba5f66a5f90d941f35cf22f9f919f34801238d3528d", + "relative_path": "train_resized/target/2356.jpg" + }, + { + "file_sha256": "acf432e6cf85fab129547ba5f66a5f90d941f35cf22f9f919f34801238d3528d", + "relative_path": "train_resized/target/856.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "532a4eab4544e0d9deec544d42196e26ee0b38d2a1a5f09923ec4984343dbefa", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.35971, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "13d54e8ec730aaa8f84e64b955cd0d98c66af948916826388234c7c60ba3505b", + "test_representative_target": "test_resized/Rain100H/target/100.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.209839 + }, + { + "full_rgb_psnr_db": 25.35971, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "13d54e8ec730aaa8f84e64b955cd0d98c66af948916826388234c7c60ba3505b", + "test_representative_target": "test_resized/Rain100L/target/100.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.209839 + }, + { + "full_rgb_psnr_db": 25.492232, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "64366d4c3a771a092541a2bb26ff7d396d66dfca3b17fa7b85aaeb90fc7603d9", + "test_representative_target": "test_resized/Test2800/target/951_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 38.890713 + } + ], + "train_targets": [ + { + "file_sha256": "e043618c90c4ae49c1b08ce3210a591dd5d9b4f2ed95827a96c7edc687ed0280", + "relative_path": "train_resized/target/1200.jpg" + }, + { + "file_sha256": "e043618c90c4ae49c1b08ce3210a591dd5d9b4f2ed95827a96c7edc687ed0280", + "relative_path": "train_resized/target/1500.jpg" + }, + { + "file_sha256": "e043618c90c4ae49c1b08ce3210a591dd5d9b4f2ed95827a96c7edc687ed0280", + "relative_path": "train_resized/target/1800.jpg" + }, + { + "file_sha256": "e043618c90c4ae49c1b08ce3210a591dd5d9b4f2ed95827a96c7edc687ed0280", + "relative_path": "train_resized/target/2100.jpg" + }, + { + "file_sha256": "e043618c90c4ae49c1b08ce3210a591dd5d9b4f2ed95827a96c7edc687ed0280", + "relative_path": "train_resized/target/2400.jpg" + }, + { + "file_sha256": "e043618c90c4ae49c1b08ce3210a591dd5d9b4f2ed95827a96c7edc687ed0280", + "relative_path": "train_resized/target/900.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "53d88e23e21bbb83b573b28f25e86031cc6abebe9ab89593ecb02b5a42037468", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.334958, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8db3daa6b6b0d710a5ceadc54f2f7edcc752acd7708d15fb06bee6a5fd5bcde6", + "test_representative_target": "test_resized/Rain100H/target/73.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.956123 + }, + { + "full_rgb_psnr_db": 27.334958, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8db3daa6b6b0d710a5ceadc54f2f7edcc752acd7708d15fb06bee6a5fd5bcde6", + "test_representative_target": "test_resized/Rain100L/target/73.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.956123 + } + ], + "train_targets": [ + { + "file_sha256": "d9e01ea86c3c2852340233f3baafb82dc14fb77d84346cbc58275bc506a73a62", + "relative_path": "train_resized/target/1175.jpg" + }, + { + "file_sha256": "d9e01ea86c3c2852340233f3baafb82dc14fb77d84346cbc58275bc506a73a62", + "relative_path": "train_resized/target/1475.jpg" + }, + { + "file_sha256": "d9e01ea86c3c2852340233f3baafb82dc14fb77d84346cbc58275bc506a73a62", + "relative_path": "train_resized/target/1775.jpg" + }, + { + "file_sha256": "d9e01ea86c3c2852340233f3baafb82dc14fb77d84346cbc58275bc506a73a62", + "relative_path": "train_resized/target/2075.jpg" + }, + { + "file_sha256": "d9e01ea86c3c2852340233f3baafb82dc14fb77d84346cbc58275bc506a73a62", + "relative_path": "train_resized/target/2375.jpg" + }, + { + "file_sha256": "d9e01ea86c3c2852340233f3baafb82dc14fb77d84346cbc58275bc506a73a62", + "relative_path": "train_resized/target/875.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "55573ade661e64b0c721c643ab3dd99db87866fb8548a54ca0fc5547130bd8c4", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.877504, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "83413cd77c3544deba746b70418e80680340cfc39ab39b2aacb137ceeaa1d9d3", + "test_representative_target": "test_resized/Test2800/target/974_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.13774 + } + ], + "train_targets": [ + { + "file_sha256": "e4724ff044001a99cec9fea736417dbeaede01afc2dd08fc964e283b61a6e578", + "relative_path": "train_resized/target/1066.jpg" + }, + { + "file_sha256": "e4724ff044001a99cec9fea736417dbeaede01afc2dd08fc964e283b61a6e578", + "relative_path": "train_resized/target/1366.jpg" + }, + { + "file_sha256": "e4724ff044001a99cec9fea736417dbeaede01afc2dd08fc964e283b61a6e578", + "relative_path": "train_resized/target/1666.jpg" + }, + { + "file_sha256": "e4724ff044001a99cec9fea736417dbeaede01afc2dd08fc964e283b61a6e578", + "relative_path": "train_resized/target/1966.jpg" + }, + { + "file_sha256": "e4724ff044001a99cec9fea736417dbeaede01afc2dd08fc964e283b61a6e578", + "relative_path": "train_resized/target/2266.jpg" + }, + { + "file_sha256": "e4724ff044001a99cec9fea736417dbeaede01afc2dd08fc964e283b61a6e578", + "relative_path": "train_resized/target/766.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "565778480864890d652821e7ee9319d505ab06db531dd5e06e3fa9db01dd9def", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.235692, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "5517ef836415aea2dc38ec3ef671ccd743c6f2c16238e6619baaf5203c929a08", + "test_representative_target": "test_resized/Rain100H/target/68.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.884119 + }, + { + "full_rgb_psnr_db": 26.235692, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "5517ef836415aea2dc38ec3ef671ccd743c6f2c16238e6619baaf5203c929a08", + "test_representative_target": "test_resized/Rain100L/target/68.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.884119 + } + ], + "train_targets": [ + { + "file_sha256": "2586324f847235b67ec7493a2dd42eaf2d98f1c9b887c56f02deaf11651af00a", + "relative_path": "train_resized/target/1171.jpg" + }, + { + "file_sha256": "2586324f847235b67ec7493a2dd42eaf2d98f1c9b887c56f02deaf11651af00a", + "relative_path": "train_resized/target/1471.jpg" + }, + { + "file_sha256": "2586324f847235b67ec7493a2dd42eaf2d98f1c9b887c56f02deaf11651af00a", + "relative_path": "train_resized/target/1771.jpg" + }, + { + "file_sha256": "2586324f847235b67ec7493a2dd42eaf2d98f1c9b887c56f02deaf11651af00a", + "relative_path": "train_resized/target/2071.jpg" + }, + { + "file_sha256": "2586324f847235b67ec7493a2dd42eaf2d98f1c9b887c56f02deaf11651af00a", + "relative_path": "train_resized/target/2371.jpg" + }, + { + "file_sha256": "2586324f847235b67ec7493a2dd42eaf2d98f1c9b887c56f02deaf11651af00a", + "relative_path": "train_resized/target/871.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "56ef4ca18c32826460b977f6fb3faec16994a0fa873d61eb465da5e65663e583", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.059136, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c35eebc58ec685da71160eedd3dd607f9954a57a0bc8a4af0233b7a6852ae9c9", + "test_representative_target": "test_resized/Test2800/target/935_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.429342 + } + ], + "train_targets": [ + { + "file_sha256": "0c5d627f4be3ada791a18c3a8f1bef0d9f628fbb7ec66629912c36219e88e021", + "relative_path": "train_resized/target/504.jpg" + }, + { + "file_sha256": "0c5d627f4be3ada791a18c3a8f1bef0d9f628fbb7ec66629912c36219e88e021", + "relative_path": "train_resized/target/549.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "56f93f621c4037541ed4bf5077b92c8005dcfc57136cef8f96d448f635c591a5", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.58077, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "066cb99817e953cbdc72d725ce01c104d967a76f55a371b630b172599c4a98ae", + "test_representative_target": "test_resized/Rain100H/target/29.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.737306 + }, + { + "full_rgb_psnr_db": 28.58077, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "066cb99817e953cbdc72d725ce01c104d967a76f55a371b630b172599c4a98ae", + "test_representative_target": "test_resized/Rain100L/target/29.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.737306 + } + ], + "train_targets": [ + { + "file_sha256": "6ae7a85ba378bd7d3b104ef9ef4e4474efa4247b65748bfecfb73ab7c1838e4c", + "relative_path": "train_resized/target/1135.jpg" + }, + { + "file_sha256": "6ae7a85ba378bd7d3b104ef9ef4e4474efa4247b65748bfecfb73ab7c1838e4c", + "relative_path": "train_resized/target/1435.jpg" + }, + { + "file_sha256": "6ae7a85ba378bd7d3b104ef9ef4e4474efa4247b65748bfecfb73ab7c1838e4c", + "relative_path": "train_resized/target/1735.jpg" + }, + { + "file_sha256": "6ae7a85ba378bd7d3b104ef9ef4e4474efa4247b65748bfecfb73ab7c1838e4c", + "relative_path": "train_resized/target/2035.jpg" + }, + { + "file_sha256": "6ae7a85ba378bd7d3b104ef9ef4e4474efa4247b65748bfecfb73ab7c1838e4c", + "relative_path": "train_resized/target/2335.jpg" + }, + { + "file_sha256": "6ae7a85ba378bd7d3b104ef9ef4e4474efa4247b65748bfecfb73ab7c1838e4c", + "relative_path": "train_resized/target/835.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "577d0d9b60b7065ea25f9645e82fe95d47e6dd7db6f65844767d96d2f1152640", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.582877, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "928718141044bc4423470b5b76641b64ea783a3add3e8646faa966e090af9c3b", + "test_representative_target": "test_resized/Rain100H/target/70.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.020011 + }, + { + "full_rgb_psnr_db": 24.582877, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "928718141044bc4423470b5b76641b64ea783a3add3e8646faa966e090af9c3b", + "test_representative_target": "test_resized/Rain100L/target/70.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.020011 + }, + { + "full_rgb_psnr_db": 24.656324, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "73b2b94a218a3da33b7f65d5e7744ffee4fd548a834f4edd72e189116dab8ef8", + "test_representative_target": "test_resized/Test2800/target/932_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.286753 + } + ], + "train_targets": [ + { + "file_sha256": "f1765c7b57a5a3fb3ae0039d93731a885bbeb93a812889caccd3fdf591593dbd", + "relative_path": "train_resized/target/237.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "5a345f87d29cd29c583f292d498e78a919b74ac4cb447a634c020b10971b6cf3", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.28307, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "ad62858b87eb330c3dcc158a9bca0e77dd11dc243d8b12f2929724f126df26ce", + "test_representative_target": "test_resized/Rain100H/target/51.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.7414 + }, + { + "full_rgb_psnr_db": 22.28307, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "ad62858b87eb330c3dcc158a9bca0e77dd11dc243d8b12f2929724f126df26ce", + "test_representative_target": "test_resized/Rain100L/target/51.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.7414 + } + ], + "train_targets": [ + { + "file_sha256": "e1b549b880d9b8ef382b4a0e6cfed27b6a55ac800ee6798847efb616c19c31ea", + "relative_path": "train_resized/target/1155.jpg" + }, + { + "file_sha256": "e1b549b880d9b8ef382b4a0e6cfed27b6a55ac800ee6798847efb616c19c31ea", + "relative_path": "train_resized/target/1455.jpg" + }, + { + "file_sha256": "e1b549b880d9b8ef382b4a0e6cfed27b6a55ac800ee6798847efb616c19c31ea", + "relative_path": "train_resized/target/1755.jpg" + }, + { + "file_sha256": "e1b549b880d9b8ef382b4a0e6cfed27b6a55ac800ee6798847efb616c19c31ea", + "relative_path": "train_resized/target/2055.jpg" + }, + { + "file_sha256": "e1b549b880d9b8ef382b4a0e6cfed27b6a55ac800ee6798847efb616c19c31ea", + "relative_path": "train_resized/target/2355.jpg" + }, + { + "file_sha256": "e1b549b880d9b8ef382b4a0e6cfed27b6a55ac800ee6798847efb616c19c31ea", + "relative_path": "train_resized/target/855.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "5b7a8cee0295dc6b0dcf2e0f1b54308f1752566df332234a8faa478345867930", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.729488, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "214b140be2b3c24a2935e99446a1c12aa6e2ee7066ca77127d0e375ccf7e01a3", + "test_representative_target": "test_resized/Rain100H/target/16.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 32.489641 + }, + { + "full_rgb_psnr_db": 24.729488, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "214b140be2b3c24a2935e99446a1c12aa6e2ee7066ca77127d0e375ccf7e01a3", + "test_representative_target": "test_resized/Rain100L/target/16.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 32.489641 + }, + { + "full_rgb_psnr_db": 25.025714, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "bfd0eb2c2284d97bde8e1593a249e82fbea015319345b94aca2a4f8454b8e7b6", + "test_representative_target": "test_resized/Test100/target/90.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 32.802667 + } + ], + "train_targets": [ + { + "file_sha256": "259411868de4e50848d864179e1208a94d5af937095afe0baf2d6f611202cf48", + "relative_path": "train_resized/target/1123.jpg" + }, + { + "file_sha256": "259411868de4e50848d864179e1208a94d5af937095afe0baf2d6f611202cf48", + "relative_path": "train_resized/target/1423.jpg" + }, + { + "file_sha256": "259411868de4e50848d864179e1208a94d5af937095afe0baf2d6f611202cf48", + "relative_path": "train_resized/target/1723.jpg" + }, + { + "file_sha256": "259411868de4e50848d864179e1208a94d5af937095afe0baf2d6f611202cf48", + "relative_path": "train_resized/target/2023.jpg" + }, + { + "file_sha256": "259411868de4e50848d864179e1208a94d5af937095afe0baf2d6f611202cf48", + "relative_path": "train_resized/target/2323.jpg" + }, + { + "file_sha256": "259411868de4e50848d864179e1208a94d5af937095afe0baf2d6f611202cf48", + "relative_path": "train_resized/target/823.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "5bc537ab3940d09a8305fd4a1e62a37f5b801585258cdda9965b99a58ded5ee5", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 33.504326, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a55ff030b1ef3b48cb9409587b3c0c4656e20e3e01380b0f9092e013090df594", + "test_representative_target": "test_resized/Rain100H/target/50.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 42.20552 + }, + { + "full_rgb_psnr_db": 33.504326, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a55ff030b1ef3b48cb9409587b3c0c4656e20e3e01380b0f9092e013090df594", + "test_representative_target": "test_resized/Rain100L/target/50.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 42.20552 + } + ], + "train_targets": [ + { + "file_sha256": "c24ae38bf696cd77e9faec717bf7ea6ec4b1fa3132e85b69de8db54b43f3c410", + "relative_path": "train_resized/target/1154.jpg" + }, + { + "file_sha256": "c24ae38bf696cd77e9faec717bf7ea6ec4b1fa3132e85b69de8db54b43f3c410", + "relative_path": "train_resized/target/1454.jpg" + }, + { + "file_sha256": "c24ae38bf696cd77e9faec717bf7ea6ec4b1fa3132e85b69de8db54b43f3c410", + "relative_path": "train_resized/target/1754.jpg" + }, + { + "file_sha256": "c24ae38bf696cd77e9faec717bf7ea6ec4b1fa3132e85b69de8db54b43f3c410", + "relative_path": "train_resized/target/2054.jpg" + }, + { + "file_sha256": "c24ae38bf696cd77e9faec717bf7ea6ec4b1fa3132e85b69de8db54b43f3c410", + "relative_path": "train_resized/target/2354.jpg" + }, + { + "file_sha256": "c24ae38bf696cd77e9faec717bf7ea6ec4b1fa3132e85b69de8db54b43f3c410", + "relative_path": "train_resized/target/854.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "5db1e0fdacaf44e96f16ffa96997a9043d1cae782014a97de1a690b290d67df3", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.625305, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "862052655143a08cdbca2294f32f77b9106bf317ff81196da5b627aa6de1e247", + "test_representative_target": "test_resized/Test2800/target/983_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.759554 + } + ], + "train_targets": [ + { + "file_sha256": "2e37c19d61a0343ec085e395913198e6fb2c4ed951c8a994cc77124582b065c7", + "relative_path": "train_resized/target/630.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "5ff700b2a1ebe412e6b4e8b799d3649900d5a114bb9a2e696e932589f1f82f4e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.70419, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a4181082f0a838f2880bc8b2818e9890141f796544a3f223894e1137a773ed34", + "test_representative_target": "test_resized/Rain100H/target/12.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 39.81781 + }, + { + "full_rgb_psnr_db": 28.70419, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a4181082f0a838f2880bc8b2818e9890141f796544a3f223894e1137a773ed34", + "test_representative_target": "test_resized/Rain100L/target/12.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 39.81781 + } + ], + "train_targets": [ + { + "file_sha256": "1fbe027b26b033fe72b96da6efbbb1a8c7d7c9b9f1f34edf5f51831e4f1977a0", + "relative_path": "train_resized/target/1120.jpg" + }, + { + "file_sha256": "1fbe027b26b033fe72b96da6efbbb1a8c7d7c9b9f1f34edf5f51831e4f1977a0", + "relative_path": "train_resized/target/1420.jpg" + }, + { + "file_sha256": "1fbe027b26b033fe72b96da6efbbb1a8c7d7c9b9f1f34edf5f51831e4f1977a0", + "relative_path": "train_resized/target/1720.jpg" + }, + { + "file_sha256": "1fbe027b26b033fe72b96da6efbbb1a8c7d7c9b9f1f34edf5f51831e4f1977a0", + "relative_path": "train_resized/target/2020.jpg" + }, + { + "file_sha256": "1fbe027b26b033fe72b96da6efbbb1a8c7d7c9b9f1f34edf5f51831e4f1977a0", + "relative_path": "train_resized/target/2320.jpg" + }, + { + "file_sha256": "1fbe027b26b033fe72b96da6efbbb1a8c7d7c9b9f1f34edf5f51831e4f1977a0", + "relative_path": "train_resized/target/820.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6207f4b1b183cc94a75ad77ac089c435cf3afa3c77fa84377ab37af63173afcb", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.464894, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "e242dd8ff3e88a4ee806e9ea66dfb03b02273a878357cfb7734c1d70d381355e", + "test_representative_target": "test_resized/Test2800/target/963_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.450774 + } + ], + "train_targets": [ + { + "file_sha256": "1bc71de054a91b6f7be28f9b065cab5514d95bf620d331447ceac770213fde2c", + "relative_path": "train_resized/target/1224.jpg" + }, + { + "file_sha256": "1bc71de054a91b6f7be28f9b065cab5514d95bf620d331447ceac770213fde2c", + "relative_path": "train_resized/target/1524.jpg" + }, + { + "file_sha256": "1bc71de054a91b6f7be28f9b065cab5514d95bf620d331447ceac770213fde2c", + "relative_path": "train_resized/target/1824.jpg" + }, + { + "file_sha256": "1bc71de054a91b6f7be28f9b065cab5514d95bf620d331447ceac770213fde2c", + "relative_path": "train_resized/target/2124.jpg" + }, + { + "file_sha256": "1bc71de054a91b6f7be28f9b065cab5514d95bf620d331447ceac770213fde2c", + "relative_path": "train_resized/target/2424.jpg" + }, + { + "file_sha256": "1bc71de054a91b6f7be28f9b065cab5514d95bf620d331447ceac770213fde2c", + "relative_path": "train_resized/target/924.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "63410d2c4de1193754ff189e4a24473af2f6eedc6697ac5f622cd63d2988622e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 35.693507, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "bb86dfd6da275b1e54b48291d4e8c6d21d3596046c2d0fec28ccfc31954146cb", + "test_representative_target": "test_resized/Test100/target/83.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.597655 + }, + { + "full_rgb_psnr_db": 35.693657, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "f10354f07f8cf7404bef9c224d482946a26ad21405cee90f9a5fcaa1a6e0948f", + "test_representative_target": "test_resized/Test100/target/61.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.597343 + } + ], + "train_targets": [ + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11543.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11544.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11545.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11546.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11547.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11548.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11549.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11550.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11551.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11552.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11553.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11554.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11555.jpg" + }, + { + "file_sha256": "94bc6cd0efd74f9ee4595e4a9c50c1dbe0b47a6981dfc22a7e139e5d6f2381ca", + "relative_path": "train_resized/target/11556.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "63b9b5187861ef172cf0d8d4aced5b2a46b6149c6fe54eceda7fa7dcd5325579", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 29.369981, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8e0f3890419bd5a1b1686fb245d4937b4e615276b416aeb7004b977076777cba", + "test_representative_target": "test_resized/Rain100H/target/96.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.403248 + }, + { + "full_rgb_psnr_db": 29.369981, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8e0f3890419bd5a1b1686fb245d4937b4e615276b416aeb7004b977076777cba", + "test_representative_target": "test_resized/Rain100L/target/96.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.403248 + } + ], + "train_targets": [ + { + "file_sha256": "2ae64675a4a598739a86374b255873eb60991c526fc120e584b857ebbb9e0603", + "relative_path": "train_resized/target/1196.jpg" + }, + { + "file_sha256": "2ae64675a4a598739a86374b255873eb60991c526fc120e584b857ebbb9e0603", + "relative_path": "train_resized/target/1496.jpg" + }, + { + "file_sha256": "2ae64675a4a598739a86374b255873eb60991c526fc120e584b857ebbb9e0603", + "relative_path": "train_resized/target/1796.jpg" + }, + { + "file_sha256": "2ae64675a4a598739a86374b255873eb60991c526fc120e584b857ebbb9e0603", + "relative_path": "train_resized/target/2096.jpg" + }, + { + "file_sha256": "2ae64675a4a598739a86374b255873eb60991c526fc120e584b857ebbb9e0603", + "relative_path": "train_resized/target/2396.jpg" + }, + { + "file_sha256": "2ae64675a4a598739a86374b255873eb60991c526fc120e584b857ebbb9e0603", + "relative_path": "train_resized/target/896.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "64a47a7f895ec3ba116e0de0106be368a7ae4dd0ee528ac4046c397b5d73b72b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.025916, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "aa5e1861a3b9c6f31be91684196ebab2081b3b247f30c3579e36ee23a95cf160", + "test_representative_target": "test_resized/Test100/target/6.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.138877 + } + ], + "train_targets": [ + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2779.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2780.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2781.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2782.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2783.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2784.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2785.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2786.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2787.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2788.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2789.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2790.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2791.jpg" + }, + { + "file_sha256": "0e0188affecc1a829e559eaa7e9fe8ad32155ed410f78c3047cbf74571a8f78d", + "relative_path": "train_resized/target/2792.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "65e2d0f46f3e9dd88e671dfed358138830e86f973916f17252b5a3f933480501", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.660827, + "phash_hamming": 4, + "test_decoded_rgb_sha256": "c1dd62b0b48cc02889b0d79a70b875665da409f26fdf54d3b512da59031e2d94", + "test_representative_target": "test_resized/Rain100H/target/58.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 37.015388 + }, + { + "full_rgb_psnr_db": 24.660827, + "phash_hamming": 4, + "test_decoded_rgb_sha256": "c1dd62b0b48cc02889b0d79a70b875665da409f26fdf54d3b512da59031e2d94", + "test_representative_target": "test_resized/Rain100L/target/58.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 37.015388 + } + ], + "train_targets": [ + { + "file_sha256": "9c0caf8f93758180b70026dde7da511db01901a0deb513da26bd12e182fc9aee", + "relative_path": "train_resized/target/1117.jpg" + }, + { + "file_sha256": "9c0caf8f93758180b70026dde7da511db01901a0deb513da26bd12e182fc9aee", + "relative_path": "train_resized/target/1417.jpg" + }, + { + "file_sha256": "9c0caf8f93758180b70026dde7da511db01901a0deb513da26bd12e182fc9aee", + "relative_path": "train_resized/target/1717.jpg" + }, + { + "file_sha256": "9c0caf8f93758180b70026dde7da511db01901a0deb513da26bd12e182fc9aee", + "relative_path": "train_resized/target/2017.jpg" + }, + { + "file_sha256": "9c0caf8f93758180b70026dde7da511db01901a0deb513da26bd12e182fc9aee", + "relative_path": "train_resized/target/2317.jpg" + }, + { + "file_sha256": "9c0caf8f93758180b70026dde7da511db01901a0deb513da26bd12e182fc9aee", + "relative_path": "train_resized/target/817.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "68126eaf5cf23376c4872e8044e51a5706e91fa7a8ad4562d2bf96fd4feec61e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.47359, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c0068730ceff2eddd13cf2092cda354fd1f4acf16c268171c51f32154f2b8a5c", + "test_representative_target": "test_resized/Rain100H/target/31.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.203211 + }, + { + "full_rgb_psnr_db": 28.47359, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c0068730ceff2eddd13cf2092cda354fd1f4acf16c268171c51f32154f2b8a5c", + "test_representative_target": "test_resized/Rain100L/target/31.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.203211 + } + ], + "train_targets": [ + { + "file_sha256": "3cf4794246aae0f4bbfd3dc08bc26a4abe72e55b80b127991da935771a1afe47", + "relative_path": "train_resized/target/1137.jpg" + }, + { + "file_sha256": "3cf4794246aae0f4bbfd3dc08bc26a4abe72e55b80b127991da935771a1afe47", + "relative_path": "train_resized/target/1437.jpg" + }, + { + "file_sha256": "3cf4794246aae0f4bbfd3dc08bc26a4abe72e55b80b127991da935771a1afe47", + "relative_path": "train_resized/target/1737.jpg" + }, + { + "file_sha256": "3cf4794246aae0f4bbfd3dc08bc26a4abe72e55b80b127991da935771a1afe47", + "relative_path": "train_resized/target/2037.jpg" + }, + { + "file_sha256": "3cf4794246aae0f4bbfd3dc08bc26a4abe72e55b80b127991da935771a1afe47", + "relative_path": "train_resized/target/2337.jpg" + }, + { + "file_sha256": "3cf4794246aae0f4bbfd3dc08bc26a4abe72e55b80b127991da935771a1afe47", + "relative_path": "train_resized/target/837.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "68f45fea30cb5b2daf772f05c2850070018942d2c523b6d269751ec70aa75ab0", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.890489, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cb3cc085e4c5919424b783d84d176f353b1820bfb057ac04249866958f5b29d5", + "test_representative_target": "test_resized/Rain100H/target/98.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.412686 + }, + { + "full_rgb_psnr_db": 28.890489, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cb3cc085e4c5919424b783d84d176f353b1820bfb057ac04249866958f5b29d5", + "test_representative_target": "test_resized/Rain100L/target/98.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.412686 + } + ], + "train_targets": [ + { + "file_sha256": "8548b4ae6c6f53d890a73f402a04a607f561da6fcedde04cc4d8bbcde00d33d2", + "relative_path": "train_resized/target/1198.jpg" + }, + { + "file_sha256": "8548b4ae6c6f53d890a73f402a04a607f561da6fcedde04cc4d8bbcde00d33d2", + "relative_path": "train_resized/target/1498.jpg" + }, + { + "file_sha256": "8548b4ae6c6f53d890a73f402a04a607f561da6fcedde04cc4d8bbcde00d33d2", + "relative_path": "train_resized/target/1798.jpg" + }, + { + "file_sha256": "8548b4ae6c6f53d890a73f402a04a607f561da6fcedde04cc4d8bbcde00d33d2", + "relative_path": "train_resized/target/2098.jpg" + }, + { + "file_sha256": "8548b4ae6c6f53d890a73f402a04a607f561da6fcedde04cc4d8bbcde00d33d2", + "relative_path": "train_resized/target/2398.jpg" + }, + { + "file_sha256": "8548b4ae6c6f53d890a73f402a04a607f561da6fcedde04cc4d8bbcde00d33d2", + "relative_path": "train_resized/target/898.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6a12cbac2ccbc31b31fb12f4f19c2dceda5ad6be3b8ed5eee5fc69f66b9a5192", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.726113, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "02c0b4c15b14f2336f8045ec14b083698efa428bf0e327cb774c620a32eddfa1", + "test_representative_target": "test_resized/Rain100H/target/22.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.685344 + }, + { + "full_rgb_psnr_db": 25.726113, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "02c0b4c15b14f2336f8045ec14b083698efa428bf0e327cb774c620a32eddfa1", + "test_representative_target": "test_resized/Rain100L/target/22.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.685344 + } + ], + "train_targets": [ + { + "file_sha256": "f544befcf744d5a8181ab93b7130474f50fbe449fb64dd05ba448b31771fb98d", + "relative_path": "train_resized/target/1129.jpg" + }, + { + "file_sha256": "f544befcf744d5a8181ab93b7130474f50fbe449fb64dd05ba448b31771fb98d", + "relative_path": "train_resized/target/1429.jpg" + }, + { + "file_sha256": "f544befcf744d5a8181ab93b7130474f50fbe449fb64dd05ba448b31771fb98d", + "relative_path": "train_resized/target/1729.jpg" + }, + { + "file_sha256": "f544befcf744d5a8181ab93b7130474f50fbe449fb64dd05ba448b31771fb98d", + "relative_path": "train_resized/target/2029.jpg" + }, + { + "file_sha256": "f544befcf744d5a8181ab93b7130474f50fbe449fb64dd05ba448b31771fb98d", + "relative_path": "train_resized/target/2329.jpg" + }, + { + "file_sha256": "f544befcf744d5a8181ab93b7130474f50fbe449fb64dd05ba448b31771fb98d", + "relative_path": "train_resized/target/829.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6a13f194a7660c2a2d86a785fabb5e7ae732f9f2cc2e58368fbceccdf6ec18d1", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.910395, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8708e2c17f51ec711cbb2672771559efa8432fc451edbc5df670d650b5bbae8c", + "test_representative_target": "test_resized/Test2800/target/975_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 33.941706 + } + ], + "train_targets": [ + { + "file_sha256": "63e3bd66d7648d5cb6de103ada405f8acbe2f3e9d3139353110c5b076865a422", + "relative_path": "train_resized/target/695.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6a2e19337d4473f0642a97ecddc6f73b15dd3645aa6fa72359272cecccb6819f", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.948526, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a64d1358f5549abe5634e572126b2639dfef5b472a89b969b338362414fdc2ef", + "test_representative_target": "test_resized/Rain100H/target/64.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.872396 + }, + { + "full_rgb_psnr_db": 30.948526, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a64d1358f5549abe5634e572126b2639dfef5b472a89b969b338362414fdc2ef", + "test_representative_target": "test_resized/Rain100L/target/64.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.872396 + } + ], + "train_targets": [ + { + "file_sha256": "190b97ad0a851e55328e1074f31ee577fe50eb1b17c3581f2502925f4975557f", + "relative_path": "train_resized/target/1167.jpg" + }, + { + "file_sha256": "190b97ad0a851e55328e1074f31ee577fe50eb1b17c3581f2502925f4975557f", + "relative_path": "train_resized/target/1467.jpg" + }, + { + "file_sha256": "190b97ad0a851e55328e1074f31ee577fe50eb1b17c3581f2502925f4975557f", + "relative_path": "train_resized/target/1767.jpg" + }, + { + "file_sha256": "190b97ad0a851e55328e1074f31ee577fe50eb1b17c3581f2502925f4975557f", + "relative_path": "train_resized/target/2067.jpg" + }, + { + "file_sha256": "190b97ad0a851e55328e1074f31ee577fe50eb1b17c3581f2502925f4975557f", + "relative_path": "train_resized/target/2367.jpg" + }, + { + "file_sha256": "190b97ad0a851e55328e1074f31ee577fe50eb1b17c3581f2502925f4975557f", + "relative_path": "train_resized/target/867.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6cc2c0a311d8f0295c4fd4fdb4e2e10e36b6976c957de6aa9a79a44efefadf57", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.275389, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "798b3c48e3cc0398fb465f807f5d3b2414a1195c66b6f393538c935af2acd5c2", + "test_representative_target": "test_resized/Rain100H/target/86.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.793177 + }, + { + "full_rgb_psnr_db": 26.275389, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "798b3c48e3cc0398fb465f807f5d3b2414a1195c66b6f393538c935af2acd5c2", + "test_representative_target": "test_resized/Rain100L/target/86.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.793177 + } + ], + "train_targets": [ + { + "file_sha256": "8bc100c2bb5b2f1066aae7de75935290b3b70bb2c23b5eef0797c227bf20a306", + "relative_path": "train_resized/target/1187.jpg" + }, + { + "file_sha256": "8bc100c2bb5b2f1066aae7de75935290b3b70bb2c23b5eef0797c227bf20a306", + "relative_path": "train_resized/target/1487.jpg" + }, + { + "file_sha256": "8bc100c2bb5b2f1066aae7de75935290b3b70bb2c23b5eef0797c227bf20a306", + "relative_path": "train_resized/target/1787.jpg" + }, + { + "file_sha256": "8bc100c2bb5b2f1066aae7de75935290b3b70bb2c23b5eef0797c227bf20a306", + "relative_path": "train_resized/target/2087.jpg" + }, + { + "file_sha256": "8bc100c2bb5b2f1066aae7de75935290b3b70bb2c23b5eef0797c227bf20a306", + "relative_path": "train_resized/target/2387.jpg" + }, + { + "file_sha256": "8bc100c2bb5b2f1066aae7de75935290b3b70bb2c23b5eef0797c227bf20a306", + "relative_path": "train_resized/target/887.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6d5e41776276eb007bef45d02b7d89fa18996c179d998549f4ff6601147e113c", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.825248, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "c9b78b48c75d1753f6021ae0ed8b19ed1707b03a78c6e9c2555e3fed29c16a88", + "test_representative_target": "test_resized/Test2800/target/828_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.416201 + } + ], + "train_targets": [ + { + "file_sha256": "50a2bd986caf929d2e5b2525cd8323026d1724cca1069965ae0822acbd987669", + "relative_path": "train_resized/target/1073.jpg" + }, + { + "file_sha256": "50a2bd986caf929d2e5b2525cd8323026d1724cca1069965ae0822acbd987669", + "relative_path": "train_resized/target/1373.jpg" + }, + { + "file_sha256": "50a2bd986caf929d2e5b2525cd8323026d1724cca1069965ae0822acbd987669", + "relative_path": "train_resized/target/1673.jpg" + }, + { + "file_sha256": "50a2bd986caf929d2e5b2525cd8323026d1724cca1069965ae0822acbd987669", + "relative_path": "train_resized/target/1973.jpg" + }, + { + "file_sha256": "50a2bd986caf929d2e5b2525cd8323026d1724cca1069965ae0822acbd987669", + "relative_path": "train_resized/target/2273.jpg" + }, + { + "file_sha256": "50a2bd986caf929d2e5b2525cd8323026d1724cca1069965ae0822acbd987669", + "relative_path": "train_resized/target/773.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6e2c9b9930de96e2f84919a23341eff3503f13c7a430ce7d105846d5040c7cdb", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 36.949814, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "11f0a57a6921b4cf98e09be8106b3222c4a1f5a027c098e2d9ed7eaff2f78c1b", + "test_representative_target": "test_resized/Test2800/target/856_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.841976 + } + ], + "train_targets": [ + { + "file_sha256": "452d417de99e42fad2e07bbf6af5815c0a10617ad6779b552137cb2a01046e94", + "relative_path": "train_resized/target/148.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6e6321221dee634cb08b74f6f8df5647d5c2029558db4fe0bdf0bddc20895bef", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 20.874276, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "45a147dc3cc4f44f1dc0d06a3454b67ea647d3b3972fedff8983fa33437b3a06", + "test_representative_target": "test_resized/Rain100H/target/28.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.917051 + }, + { + "full_rgb_psnr_db": 20.874276, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "45a147dc3cc4f44f1dc0d06a3454b67ea647d3b3972fedff8983fa33437b3a06", + "test_representative_target": "test_resized/Rain100L/target/28.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.917051 + } + ], + "train_targets": [ + { + "file_sha256": "52710dbd86de4b2cc97a198f4502aaeb25b79d001f993d39b79fd25ad4166f5f", + "relative_path": "train_resized/target/1134.jpg" + }, + { + "file_sha256": "52710dbd86de4b2cc97a198f4502aaeb25b79d001f993d39b79fd25ad4166f5f", + "relative_path": "train_resized/target/1434.jpg" + }, + { + "file_sha256": "52710dbd86de4b2cc97a198f4502aaeb25b79d001f993d39b79fd25ad4166f5f", + "relative_path": "train_resized/target/1734.jpg" + }, + { + "file_sha256": "52710dbd86de4b2cc97a198f4502aaeb25b79d001f993d39b79fd25ad4166f5f", + "relative_path": "train_resized/target/2034.jpg" + }, + { + "file_sha256": "52710dbd86de4b2cc97a198f4502aaeb25b79d001f993d39b79fd25ad4166f5f", + "relative_path": "train_resized/target/2334.jpg" + }, + { + "file_sha256": "52710dbd86de4b2cc97a198f4502aaeb25b79d001f993d39b79fd25ad4166f5f", + "relative_path": "train_resized/target/834.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6ec91227e809cbb6436fada373b77c56218f445bbbb451a144d04b699452f5a7", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.206952, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8344ec9c91795d9d5203a0b3a17653d13df46298444545660d4b68a3339a98b8", + "test_representative_target": "test_resized/Rain100H/target/47.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 37.001604 + }, + { + "full_rgb_psnr_db": 30.206952, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8344ec9c91795d9d5203a0b3a17653d13df46298444545660d4b68a3339a98b8", + "test_representative_target": "test_resized/Rain100L/target/47.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 37.001604 + } + ], + "train_targets": [ + { + "file_sha256": "1398ad3dc21d113bcaad2ff834f30dbc2b46e3a4233550b1c1aab2c990b215e2", + "relative_path": "train_resized/target/150.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6ed68d54a8fd750d050e9bf1c06a6c03d1176d5a2da360a7e345b7246358f578", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.160726, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "da3bc7612e69bac3efc71d141b9f2b0ecdbe90aba0d078a343da27024ff5da6e", + "test_representative_target": "test_resized/Rain100H/target/92.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.891765 + }, + { + "full_rgb_psnr_db": 23.160726, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "da3bc7612e69bac3efc71d141b9f2b0ecdbe90aba0d078a343da27024ff5da6e", + "test_representative_target": "test_resized/Rain100L/target/92.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.891765 + } + ], + "train_targets": [ + { + "file_sha256": "ae12d8971ca13b1d6eeba62682df01e63e41ed3db33659ac4ad34ec7fbede8b4", + "relative_path": "train_resized/target/1192.jpg" + }, + { + "file_sha256": "ae12d8971ca13b1d6eeba62682df01e63e41ed3db33659ac4ad34ec7fbede8b4", + "relative_path": "train_resized/target/1492.jpg" + }, + { + "file_sha256": "ae12d8971ca13b1d6eeba62682df01e63e41ed3db33659ac4ad34ec7fbede8b4", + "relative_path": "train_resized/target/1792.jpg" + }, + { + "file_sha256": "ae12d8971ca13b1d6eeba62682df01e63e41ed3db33659ac4ad34ec7fbede8b4", + "relative_path": "train_resized/target/2092.jpg" + }, + { + "file_sha256": "ae12d8971ca13b1d6eeba62682df01e63e41ed3db33659ac4ad34ec7fbede8b4", + "relative_path": "train_resized/target/2392.jpg" + }, + { + "file_sha256": "ae12d8971ca13b1d6eeba62682df01e63e41ed3db33659ac4ad34ec7fbede8b4", + "relative_path": "train_resized/target/892.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "6f845edd88a2156d45452494fd9b423771a97de3809878185d91a2bb11f0255c", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.428031, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "7018c55bb378832b8d51e16c85765b629d330dc1dcf4588c1f673a45f88cca8c", + "test_representative_target": "test_resized/Rain100H/target/55.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 33.788008 + }, + { + "full_rgb_psnr_db": 22.428031, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "7018c55bb378832b8d51e16c85765b629d330dc1dcf4588c1f673a45f88cca8c", + "test_representative_target": "test_resized/Rain100L/target/55.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 33.788008 + }, + { + "full_rgb_psnr_db": 22.541035, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "1df6379d9ed3cad7e277a5e2a72cfd8416a0a212d93f47b80a36d4d5ed5be503", + "test_representative_target": "test_resized/Test2800/target/998_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.228366 + } + ], + "train_targets": [ + { + "file_sha256": "5b58128fbc1252bcfbb0ce8bf1f48d21a07365a4d88c22a0974cb2364cac8286", + "relative_path": "train_resized/target/1159.jpg" + }, + { + "file_sha256": "5b58128fbc1252bcfbb0ce8bf1f48d21a07365a4d88c22a0974cb2364cac8286", + "relative_path": "train_resized/target/1459.jpg" + }, + { + "file_sha256": "5b58128fbc1252bcfbb0ce8bf1f48d21a07365a4d88c22a0974cb2364cac8286", + "relative_path": "train_resized/target/1759.jpg" + }, + { + "file_sha256": "5b58128fbc1252bcfbb0ce8bf1f48d21a07365a4d88c22a0974cb2364cac8286", + "relative_path": "train_resized/target/2059.jpg" + }, + { + "file_sha256": "5b58128fbc1252bcfbb0ce8bf1f48d21a07365a4d88c22a0974cb2364cac8286", + "relative_path": "train_resized/target/2359.jpg" + }, + { + "file_sha256": "5b58128fbc1252bcfbb0ce8bf1f48d21a07365a4d88c22a0974cb2364cac8286", + "relative_path": "train_resized/target/859.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "710669d7da4bad1cc2f574167d10bfb64d179acd24e6eeaae2ce1b197969feda", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.142184, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "f4e6a004933760042d2d4bce2f14fd757acac51b33196680c8666884a8859f51", + "test_representative_target": "test_resized/Rain100H/target/54.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.17419 + }, + { + "full_rgb_psnr_db": 25.142184, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "f4e6a004933760042d2d4bce2f14fd757acac51b33196680c8666884a8859f51", + "test_representative_target": "test_resized/Rain100L/target/54.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.17419 + } + ], + "train_targets": [ + { + "file_sha256": "35430832cf4fa23d0bd14e7d79be14dc0a7848e36076edeeb5c261b06048be65", + "relative_path": "train_resized/target/1158.jpg" + }, + { + "file_sha256": "35430832cf4fa23d0bd14e7d79be14dc0a7848e36076edeeb5c261b06048be65", + "relative_path": "train_resized/target/1458.jpg" + }, + { + "file_sha256": "35430832cf4fa23d0bd14e7d79be14dc0a7848e36076edeeb5c261b06048be65", + "relative_path": "train_resized/target/1758.jpg" + }, + { + "file_sha256": "35430832cf4fa23d0bd14e7d79be14dc0a7848e36076edeeb5c261b06048be65", + "relative_path": "train_resized/target/2058.jpg" + }, + { + "file_sha256": "35430832cf4fa23d0bd14e7d79be14dc0a7848e36076edeeb5c261b06048be65", + "relative_path": "train_resized/target/2358.jpg" + }, + { + "file_sha256": "35430832cf4fa23d0bd14e7d79be14dc0a7848e36076edeeb5c261b06048be65", + "relative_path": "train_resized/target/858.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "710c4a5aeb392d5e63358a2a4c4e4fa3771494d31af34b82183e04322aeca43b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.354499, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8e536602fadca3a8bbd0adf1487a918e9daa15610b71cb5137014e8f48b9aa60", + "test_representative_target": "test_resized/Rain100H/target/74.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.679102 + }, + { + "full_rgb_psnr_db": 24.354499, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8e536602fadca3a8bbd0adf1487a918e9daa15610b71cb5137014e8f48b9aa60", + "test_representative_target": "test_resized/Rain100L/target/74.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.679102 + } + ], + "train_targets": [ + { + "file_sha256": "51be587872f02a309ea2a0a4dd04dac118cbefe2eeca4f9795a6c2c0f3a7b597", + "relative_path": "train_resized/target/1176.jpg" + }, + { + "file_sha256": "51be587872f02a309ea2a0a4dd04dac118cbefe2eeca4f9795a6c2c0f3a7b597", + "relative_path": "train_resized/target/1476.jpg" + }, + { + "file_sha256": "51be587872f02a309ea2a0a4dd04dac118cbefe2eeca4f9795a6c2c0f3a7b597", + "relative_path": "train_resized/target/1776.jpg" + }, + { + "file_sha256": "51be587872f02a309ea2a0a4dd04dac118cbefe2eeca4f9795a6c2c0f3a7b597", + "relative_path": "train_resized/target/2076.jpg" + }, + { + "file_sha256": "51be587872f02a309ea2a0a4dd04dac118cbefe2eeca4f9795a6c2c0f3a7b597", + "relative_path": "train_resized/target/2376.jpg" + }, + { + "file_sha256": "51be587872f02a309ea2a0a4dd04dac118cbefe2eeca4f9795a6c2c0f3a7b597", + "relative_path": "train_resized/target/876.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "71163934a8ab71c123ddc364629dc3b155d2484aa357aeff5cc14c6ff31a4239", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.451009, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "fff3615036e385e0e608aeddacbb5347809ad4b567ed6f8a6c8ecc3bb67e62b0", + "test_representative_target": "test_resized/Rain100H/target/87.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.791773 + }, + { + "full_rgb_psnr_db": 26.451009, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "fff3615036e385e0e608aeddacbb5347809ad4b567ed6f8a6c8ecc3bb67e62b0", + "test_representative_target": "test_resized/Rain100L/target/87.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.791773 + } + ], + "train_targets": [ + { + "file_sha256": "09e6c51fff0f07e33ea2da20b8a08706122cdee735f0b3abe6d3ff315b338298", + "relative_path": "train_resized/target/1188.jpg" + }, + { + "file_sha256": "09e6c51fff0f07e33ea2da20b8a08706122cdee735f0b3abe6d3ff315b338298", + "relative_path": "train_resized/target/1488.jpg" + }, + { + "file_sha256": "09e6c51fff0f07e33ea2da20b8a08706122cdee735f0b3abe6d3ff315b338298", + "relative_path": "train_resized/target/1788.jpg" + }, + { + "file_sha256": "09e6c51fff0f07e33ea2da20b8a08706122cdee735f0b3abe6d3ff315b338298", + "relative_path": "train_resized/target/2088.jpg" + }, + { + "file_sha256": "09e6c51fff0f07e33ea2da20b8a08706122cdee735f0b3abe6d3ff315b338298", + "relative_path": "train_resized/target/2388.jpg" + }, + { + "file_sha256": "09e6c51fff0f07e33ea2da20b8a08706122cdee735f0b3abe6d3ff315b338298", + "relative_path": "train_resized/target/888.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "71a7f2f4780544764ff295fdc6120cc71fcbccdc0ef928bfc23176530ec74650", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.373164, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "6e09cce75675f801269bf7b35e044dae832c545a6bee9286ad0f5357d6bea6e9", + "test_representative_target": "test_resized/Rain100H/target/79.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 40.692423 + }, + { + "full_rgb_psnr_db": 30.373164, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "6e09cce75675f801269bf7b35e044dae832c545a6bee9286ad0f5357d6bea6e9", + "test_representative_target": "test_resized/Rain100L/target/79.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 40.692423 + } + ], + "train_targets": [ + { + "file_sha256": "15c769c28b55bb18d3f00adf058a658d11331acd03459178339c8abbcd23913c", + "relative_path": "train_resized/target/1181.jpg" + }, + { + "file_sha256": "15c769c28b55bb18d3f00adf058a658d11331acd03459178339c8abbcd23913c", + "relative_path": "train_resized/target/1481.jpg" + }, + { + "file_sha256": "15c769c28b55bb18d3f00adf058a658d11331acd03459178339c8abbcd23913c", + "relative_path": "train_resized/target/1781.jpg" + }, + { + "file_sha256": "15c769c28b55bb18d3f00adf058a658d11331acd03459178339c8abbcd23913c", + "relative_path": "train_resized/target/2081.jpg" + }, + { + "file_sha256": "15c769c28b55bb18d3f00adf058a658d11331acd03459178339c8abbcd23913c", + "relative_path": "train_resized/target/2381.jpg" + }, + { + "file_sha256": "15c769c28b55bb18d3f00adf058a658d11331acd03459178339c8abbcd23913c", + "relative_path": "train_resized/target/881.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "73262e694f27e23f9c5303e45db16483986489d1d2e2f58a66be2109c5b02d80", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.052754, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "9aaf7e3a9fa0b38fa84564f00f336e1fee05ebcb004d18246c5e16a8f5387fab", + "test_representative_target": "test_resized/Rain100H/target/20.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.245492 + }, + { + "full_rgb_psnr_db": 26.052754, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "9aaf7e3a9fa0b38fa84564f00f336e1fee05ebcb004d18246c5e16a8f5387fab", + "test_representative_target": "test_resized/Rain100L/target/20.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.245492 + } + ], + "train_targets": [ + { + "file_sha256": "744aacdb3ae96b451dd5757d9581faa1a6798000da5443614067d1b36f602cdd", + "relative_path": "train_resized/target/1127.jpg" + }, + { + "file_sha256": "744aacdb3ae96b451dd5757d9581faa1a6798000da5443614067d1b36f602cdd", + "relative_path": "train_resized/target/1427.jpg" + }, + { + "file_sha256": "744aacdb3ae96b451dd5757d9581faa1a6798000da5443614067d1b36f602cdd", + "relative_path": "train_resized/target/1727.jpg" + }, + { + "file_sha256": "744aacdb3ae96b451dd5757d9581faa1a6798000da5443614067d1b36f602cdd", + "relative_path": "train_resized/target/2027.jpg" + }, + { + "file_sha256": "744aacdb3ae96b451dd5757d9581faa1a6798000da5443614067d1b36f602cdd", + "relative_path": "train_resized/target/2327.jpg" + }, + { + "file_sha256": "744aacdb3ae96b451dd5757d9581faa1a6798000da5443614067d1b36f602cdd", + "relative_path": "train_resized/target/827.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "734a15e3a212b7b49e4cf2e265a8ca011ff14addf79fb7197903816a9c9f7011", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.923372, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cec577f5122e0ec336459f7f9f485f36ac7ecff475371f2878329e5a138953ee", + "test_representative_target": "test_resized/Rain100H/target/88.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.346626 + }, + { + "full_rgb_psnr_db": 28.923372, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cec577f5122e0ec336459f7f9f485f36ac7ecff475371f2878329e5a138953ee", + "test_representative_target": "test_resized/Rain100L/target/88.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.346626 + } + ], + "train_targets": [ + { + "file_sha256": "19e3522532226d788bb8e84516054e434b2ddd37211d6af38004fa368d29d553", + "relative_path": "train_resized/target/1189.jpg" + }, + { + "file_sha256": "19e3522532226d788bb8e84516054e434b2ddd37211d6af38004fa368d29d553", + "relative_path": "train_resized/target/1489.jpg" + }, + { + "file_sha256": "19e3522532226d788bb8e84516054e434b2ddd37211d6af38004fa368d29d553", + "relative_path": "train_resized/target/1789.jpg" + }, + { + "file_sha256": "19e3522532226d788bb8e84516054e434b2ddd37211d6af38004fa368d29d553", + "relative_path": "train_resized/target/2089.jpg" + }, + { + "file_sha256": "19e3522532226d788bb8e84516054e434b2ddd37211d6af38004fa368d29d553", + "relative_path": "train_resized/target/2389.jpg" + }, + { + "file_sha256": "19e3522532226d788bb8e84516054e434b2ddd37211d6af38004fa368d29d553", + "relative_path": "train_resized/target/889.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "745e598fb977bacf7fba5a6d1a98eb40a87d0fb4b30f119a19310b4592a92b06", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.465828, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "0ad25bbe98300fb44546395fa6801ae835ede2d2be524079e17a33978b6953e1", + "test_representative_target": "test_resized/Rain100H/target/35.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.465709 + }, + { + "full_rgb_psnr_db": 26.465828, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "0ad25bbe98300fb44546395fa6801ae835ede2d2be524079e17a33978b6953e1", + "test_representative_target": "test_resized/Rain100L/target/35.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.465709 + } + ], + "train_targets": [ + { + "file_sha256": "24935455bd7a39565241a67df00998fdf7293d502456d578e7c58ddebf230f4e", + "relative_path": "train_resized/target/1141.jpg" + }, + { + "file_sha256": "24935455bd7a39565241a67df00998fdf7293d502456d578e7c58ddebf230f4e", + "relative_path": "train_resized/target/1441.jpg" + }, + { + "file_sha256": "24935455bd7a39565241a67df00998fdf7293d502456d578e7c58ddebf230f4e", + "relative_path": "train_resized/target/1741.jpg" + }, + { + "file_sha256": "24935455bd7a39565241a67df00998fdf7293d502456d578e7c58ddebf230f4e", + "relative_path": "train_resized/target/2041.jpg" + }, + { + "file_sha256": "24935455bd7a39565241a67df00998fdf7293d502456d578e7c58ddebf230f4e", + "relative_path": "train_resized/target/2341.jpg" + }, + { + "file_sha256": "24935455bd7a39565241a67df00998fdf7293d502456d578e7c58ddebf230f4e", + "relative_path": "train_resized/target/841.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "74bc719955f146b3b689487d521da2b727920fda2e65d3ec129c9589c0447daf", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 38.807829, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "bdd70511342fcabb25682146aecba3c9cddbabf867c95c93053f321537d57177", + "test_representative_target": "test_resized/Test2800/target/958_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.994765 + } + ], + "train_targets": [ + { + "file_sha256": "d74e0bc5c4ecef099aa77bf3f7dbd3c4e80247d8bf419b2da653f1140e2537b8", + "relative_path": "train_resized/target/197.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "75d496bfd008c9aced6c9fc3b3449bbc6652885e086fe44a2b9a3fc850fde86e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.760289, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "504005532d84f15ac05d8cb3ae5ad117b01ee63cde35273e99960e13b725cdc3", + "test_representative_target": "test_resized/Test2800/target/954_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.728336 + } + ], + "train_targets": [ + { + "file_sha256": "6ef402f9597dd773c4dd2b46518f158fb10727911d5c58d29962c592a67bc845", + "relative_path": "train_resized/target/639.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "7714332e9f133eb49e27e9e4e0ee32949acfd1b060162fce7f0dcd4ac134011d", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.944895, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8c44ea1bcca14fc6c5f5af4c8a22951db8b66eddb53f1727bc09da3f9cdd4773", + "test_representative_target": "test_resized/Test100/target/62.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.848934 + } + ], + "train_targets": [ + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3101.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3102.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3103.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3104.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3105.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3106.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3107.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3108.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3109.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3110.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3111.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3112.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3113.jpg" + }, + { + "file_sha256": "798a5b655329f58a3d2c3e76468f029afd7857b8a1902641aefe95e2120f6226", + "relative_path": "train_resized/target/3114.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "794b15e303328d71e5d977dcbad8b677ce9598291e089d046be69fdf7f19f120", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.273336, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "3873ef50e38897399579d8a1053b80a21e2158d031b5e1285ebc9a39a5611bf7", + "test_representative_target": "test_resized/Rain100H/target/32.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 40.286135 + }, + { + "full_rgb_psnr_db": 27.273336, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "3873ef50e38897399579d8a1053b80a21e2158d031b5e1285ebc9a39a5611bf7", + "test_representative_target": "test_resized/Rain100L/target/32.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 40.286135 + }, + { + "full_rgb_psnr_db": 27.442536, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "dbd14107a466f7c6bd92f7336c9c808ef5d646a5e99c938aa5a2b122d9433e2e", + "test_representative_target": "test_resized/Test2800/target/912_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 41.069804 + } + ], + "train_targets": [ + { + "file_sha256": "aa9aae576f1630efceffda95d2787d1fac4da113e4dd1797da575a44ef8b408c", + "relative_path": "train_resized/target/1138.jpg" + }, + { + "file_sha256": "aa9aae576f1630efceffda95d2787d1fac4da113e4dd1797da575a44ef8b408c", + "relative_path": "train_resized/target/1438.jpg" + }, + { + "file_sha256": "aa9aae576f1630efceffda95d2787d1fac4da113e4dd1797da575a44ef8b408c", + "relative_path": "train_resized/target/1738.jpg" + }, + { + "file_sha256": "aa9aae576f1630efceffda95d2787d1fac4da113e4dd1797da575a44ef8b408c", + "relative_path": "train_resized/target/2038.jpg" + }, + { + "file_sha256": "aa9aae576f1630efceffda95d2787d1fac4da113e4dd1797da575a44ef8b408c", + "relative_path": "train_resized/target/2338.jpg" + }, + { + "file_sha256": "aa9aae576f1630efceffda95d2787d1fac4da113e4dd1797da575a44ef8b408c", + "relative_path": "train_resized/target/838.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "7a375bf0ef4f56b859889066ed49bfaac7154f58a98c1bea12ecde499c1ff3d6", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 29.713876, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "3e1c829a3e44da7199870882aa4c5cd95c6a77a7ee3be3b7f3559bbe065b0d43", + "test_representative_target": "test_resized/Rain100H/target/66.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.412022 + }, + { + "full_rgb_psnr_db": 29.713876, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "3e1c829a3e44da7199870882aa4c5cd95c6a77a7ee3be3b7f3559bbe065b0d43", + "test_representative_target": "test_resized/Rain100L/target/66.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.412022 + } + ], + "train_targets": [ + { + "file_sha256": "a92dae2aaba7590da9c23a2178a5f3a2b44920ae617f600a73f0c80453c93137", + "relative_path": "train_resized/target/1169.jpg" + }, + { + "file_sha256": "a92dae2aaba7590da9c23a2178a5f3a2b44920ae617f600a73f0c80453c93137", + "relative_path": "train_resized/target/1469.jpg" + }, + { + "file_sha256": "a92dae2aaba7590da9c23a2178a5f3a2b44920ae617f600a73f0c80453c93137", + "relative_path": "train_resized/target/1769.jpg" + }, + { + "file_sha256": "a92dae2aaba7590da9c23a2178a5f3a2b44920ae617f600a73f0c80453c93137", + "relative_path": "train_resized/target/2069.jpg" + }, + { + "file_sha256": "a92dae2aaba7590da9c23a2178a5f3a2b44920ae617f600a73f0c80453c93137", + "relative_path": "train_resized/target/2369.jpg" + }, + { + "file_sha256": "a92dae2aaba7590da9c23a2178a5f3a2b44920ae617f600a73f0c80453c93137", + "relative_path": "train_resized/target/869.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "7a5c28dbd95778dc8270a4bd74e9549039eff3d6c7fe4d1894cc617228abc2b5", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.285549, + "phash_hamming": 4, + "test_decoded_rgb_sha256": "c3f67a7558f235a6e76ce34982f07d542892b7e45a856add83ebbe0b132a3afb", + "test_representative_target": "test_resized/Rain100H/target/36.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 36.364616 + }, + { + "full_rgb_psnr_db": 25.285549, + "phash_hamming": 4, + "test_decoded_rgb_sha256": "c3f67a7558f235a6e76ce34982f07d542892b7e45a856add83ebbe0b132a3afb", + "test_representative_target": "test_resized/Rain100L/target/36.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 36.364616 + } + ], + "train_targets": [ + { + "file_sha256": "1db9d8febbc6f7a8f5f027d2a5801db6d4e600b7065142671d806da661396cc9", + "relative_path": "train_resized/target/1115.jpg" + }, + { + "file_sha256": "1db9d8febbc6f7a8f5f027d2a5801db6d4e600b7065142671d806da661396cc9", + "relative_path": "train_resized/target/1415.jpg" + }, + { + "file_sha256": "1db9d8febbc6f7a8f5f027d2a5801db6d4e600b7065142671d806da661396cc9", + "relative_path": "train_resized/target/1715.jpg" + }, + { + "file_sha256": "1db9d8febbc6f7a8f5f027d2a5801db6d4e600b7065142671d806da661396cc9", + "relative_path": "train_resized/target/2015.jpg" + }, + { + "file_sha256": "1db9d8febbc6f7a8f5f027d2a5801db6d4e600b7065142671d806da661396cc9", + "relative_path": "train_resized/target/2315.jpg" + }, + { + "file_sha256": "1db9d8febbc6f7a8f5f027d2a5801db6d4e600b7065142671d806da661396cc9", + "relative_path": "train_resized/target/815.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "7b804f403b0dd0a282fc964e90197f5308ddb85eaede802b765e2e3bf4be0938", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.267476, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "9e640e48d61560578fd3247b3696be20f7336f96723650d7bb5f691bbb9bb68e", + "test_representative_target": "test_resized/Rain100H/target/72.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.923659 + }, + { + "full_rgb_psnr_db": 32.267476, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "9e640e48d61560578fd3247b3696be20f7336f96723650d7bb5f691bbb9bb68e", + "test_representative_target": "test_resized/Rain100L/target/72.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.923659 + }, + { + "full_rgb_psnr_db": 33.113188, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "c4e72b359fecf998919b296323e0fdfb0cc2670d6a071387071a1da49beaaa1f", + "test_representative_target": "test_resized/Test2800/target/934_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 38.616903 + } + ], + "train_targets": [ + { + "file_sha256": "06f9e351e2dd30c51dc451bea5adebb8dd91f9c2a73d0249217198c38abfad1d", + "relative_path": "train_resized/target/1174.jpg" + }, + { + "file_sha256": "06f9e351e2dd30c51dc451bea5adebb8dd91f9c2a73d0249217198c38abfad1d", + "relative_path": "train_resized/target/1474.jpg" + }, + { + "file_sha256": "06f9e351e2dd30c51dc451bea5adebb8dd91f9c2a73d0249217198c38abfad1d", + "relative_path": "train_resized/target/1774.jpg" + }, + { + "file_sha256": "06f9e351e2dd30c51dc451bea5adebb8dd91f9c2a73d0249217198c38abfad1d", + "relative_path": "train_resized/target/2074.jpg" + }, + { + "file_sha256": "06f9e351e2dd30c51dc451bea5adebb8dd91f9c2a73d0249217198c38abfad1d", + "relative_path": "train_resized/target/2374.jpg" + }, + { + "file_sha256": "06f9e351e2dd30c51dc451bea5adebb8dd91f9c2a73d0249217198c38abfad1d", + "relative_path": "train_resized/target/874.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "7bff6d320df20c02f62c5fda37077b0ef5310d86da01982729f1571a4f02ee58", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.758788, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "504005532d84f15ac05d8cb3ae5ad117b01ee63cde35273e99960e13b725cdc3", + "test_representative_target": "test_resized/Test2800/target/954_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.711633 + } + ], + "train_targets": [ + { + "file_sha256": "9450fc2c4d589602700200cdf36e3bece684324133e6daac98fc44f488d351f3", + "relative_path": "train_resized/target/529.jpg" + }, + { + "file_sha256": "9450fc2c4d589602700200cdf36e3bece684324133e6daac98fc44f488d351f3", + "relative_path": "train_resized/target/624.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "7d2099252a1c100541d544051dccf7f9413ddd13ee6600b17b26378ab8b80b2e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 19.407345, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "f132702b222fb69d3a9dcabf0515c64bb99919cf13005cdda4df47213f8de8fb", + "test_representative_target": "test_resized/Rain100H/target/26.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 31.672294 + }, + { + "full_rgb_psnr_db": 19.407345, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "f132702b222fb69d3a9dcabf0515c64bb99919cf13005cdda4df47213f8de8fb", + "test_representative_target": "test_resized/Rain100L/target/26.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 31.672294 + } + ], + "train_targets": [ + { + "file_sha256": "7d0f827831ae5fb9588a17e83b037b902b521537a5a4a650eaaf6dc147fe29c9", + "relative_path": "train_resized/target/1132.jpg" + }, + { + "file_sha256": "7d0f827831ae5fb9588a17e83b037b902b521537a5a4a650eaaf6dc147fe29c9", + "relative_path": "train_resized/target/1432.jpg" + }, + { + "file_sha256": "7d0f827831ae5fb9588a17e83b037b902b521537a5a4a650eaaf6dc147fe29c9", + "relative_path": "train_resized/target/1732.jpg" + }, + { + "file_sha256": "7d0f827831ae5fb9588a17e83b037b902b521537a5a4a650eaaf6dc147fe29c9", + "relative_path": "train_resized/target/2032.jpg" + }, + { + "file_sha256": "7d0f827831ae5fb9588a17e83b037b902b521537a5a4a650eaaf6dc147fe29c9", + "relative_path": "train_resized/target/2332.jpg" + }, + { + "file_sha256": "7d0f827831ae5fb9588a17e83b037b902b521537a5a4a650eaaf6dc147fe29c9", + "relative_path": "train_resized/target/832.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "7f39d22dce4ab749b8efb809af262dcc1c24572ee80a94257fb1b0bb878aafdd", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.903312, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "848a38ac31e820d14f8a4482b82fdb60f74898ed1580256dad59c78beee7f50a", + "test_representative_target": "test_resized/Test2800/target/982_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.310754 + } + ], + "train_targets": [ + { + "file_sha256": "83b6dd17af6b71df779ea1e5d8c5e66cbe1a7a071d1bc4f76a5912ca4dc8c64c", + "relative_path": "train_resized/target/296.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "7f3c9e3e87bf19ab16fb11ffc6e873a2f6782718ee79f4a6a0365f6289a79522", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 39.789592, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "994ace52533006cf1485d2021f0ab1a808251f4c376ad147dbd239b62e94fda6", + "test_representative_target": "test_resized/Test2800/target/950_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 49.223763 + } + ], + "train_targets": [ + { + "file_sha256": "9de575e6c07f200320054cfd0affe55002c3596854e28a3a6334db83d529dd83", + "relative_path": "train_resized/target/377.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "82d6a81b1e6b77c70cd97a52a7ab224ed5cc5fcacb92e035021f1f9d4ed08515", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.909956, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8708e2c17f51ec711cbb2672771559efa8432fc451edbc5df670d650b5bbae8c", + "test_representative_target": "test_resized/Test2800/target/975_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 33.936011 + } + ], + "train_targets": [ + { + "file_sha256": "2aa5d0a8aaa2faf6c751e68f33afbeeeaa773241a644ab5bbe3d5119c2d33a10", + "relative_path": "train_resized/target/616.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "85a9cc5f774e73d3b8495c7a19768d1abd9e8514a5b34cda02abf76aa614313b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.378887, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "fb94203417da7b201491561f4c664d5dd01d11bdde0eb6170002791241aeac71", + "test_representative_target": "test_resized/Rain100H/target/57.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.873273 + }, + { + "full_rgb_psnr_db": 24.378887, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "fb94203417da7b201491561f4c664d5dd01d11bdde0eb6170002791241aeac71", + "test_representative_target": "test_resized/Rain100L/target/57.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.873273 + } + ], + "train_targets": [ + { + "file_sha256": "bdd74f62c3921d365285090086d003a213c67d71972ab3b11d1cc1439c84f6d2", + "relative_path": "train_resized/target/1161.jpg" + }, + { + "file_sha256": "bdd74f62c3921d365285090086d003a213c67d71972ab3b11d1cc1439c84f6d2", + "relative_path": "train_resized/target/1461.jpg" + }, + { + "file_sha256": "bdd74f62c3921d365285090086d003a213c67d71972ab3b11d1cc1439c84f6d2", + "relative_path": "train_resized/target/1761.jpg" + }, + { + "file_sha256": "bdd74f62c3921d365285090086d003a213c67d71972ab3b11d1cc1439c84f6d2", + "relative_path": "train_resized/target/2061.jpg" + }, + { + "file_sha256": "bdd74f62c3921d365285090086d003a213c67d71972ab3b11d1cc1439c84f6d2", + "relative_path": "train_resized/target/2361.jpg" + }, + { + "file_sha256": "bdd74f62c3921d365285090086d003a213c67d71972ab3b11d1cc1439c84f6d2", + "relative_path": "train_resized/target/861.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "86ba223ebf3f0c57aa96acc54873aac058889432b68580cf102a6d9226d70df6", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 36.90489, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "bf003c65d9212fde6cb8cf0675bcae6e1ada11056cea3614bd48895d1135022c", + "test_representative_target": "test_resized/Rain100H/target/89.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 43.154458 + }, + { + "full_rgb_psnr_db": 36.90489, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "bf003c65d9212fde6cb8cf0675bcae6e1ada11056cea3614bd48895d1135022c", + "test_representative_target": "test_resized/Rain100L/target/89.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 43.154458 + } + ], + "train_targets": [ + { + "file_sha256": "db42754ebf3960ced6253f3852d777c00365bacbc5cfb22efe06e76cf1281436", + "relative_path": "train_resized/target/1190.jpg" + }, + { + "file_sha256": "db42754ebf3960ced6253f3852d777c00365bacbc5cfb22efe06e76cf1281436", + "relative_path": "train_resized/target/1490.jpg" + }, + { + "file_sha256": "db42754ebf3960ced6253f3852d777c00365bacbc5cfb22efe06e76cf1281436", + "relative_path": "train_resized/target/1790.jpg" + }, + { + "file_sha256": "db42754ebf3960ced6253f3852d777c00365bacbc5cfb22efe06e76cf1281436", + "relative_path": "train_resized/target/2090.jpg" + }, + { + "file_sha256": "db42754ebf3960ced6253f3852d777c00365bacbc5cfb22efe06e76cf1281436", + "relative_path": "train_resized/target/2390.jpg" + }, + { + "file_sha256": "db42754ebf3960ced6253f3852d777c00365bacbc5cfb22efe06e76cf1281436", + "relative_path": "train_resized/target/890.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "8939038218575a64a32802873c9170d6603f52394b935abd8bcba7f41e916022", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.872716, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "393ce9c91882c9a338e3f7b0265df36fe4211546b149efbbbe1a1ad0f69cca3b", + "test_representative_target": "test_resized/Test100/target/67.png", + "test_split": "Test100", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 46.746748 + } + ], + "train_targets": [ + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12019.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12020.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12021.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12022.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12023.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12024.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12025.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12026.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12027.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12028.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12029.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12030.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12031.jpg" + }, + { + "file_sha256": "21ffbdc2aa63ab17ecf49dcc922b8c1565b04cecf61fdb36b450d934598f74f5", + "relative_path": "train_resized/target/12032.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "8a2b37f56b8ea6943c6e8422165981a7516452c7bf10e2aadd9f3ede581e883f", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.045593, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9d5f8e518984b317bb46bc33cfdb2fb3c9d5a00b4bac046be76184ee2c773d48", + "test_representative_target": "test_resized/Rain100H/target/44.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.453319 + }, + { + "full_rgb_psnr_db": 25.045593, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9d5f8e518984b317bb46bc33cfdb2fb3c9d5a00b4bac046be76184ee2c773d48", + "test_representative_target": "test_resized/Rain100L/target/44.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.453319 + }, + { + "full_rgb_psnr_db": 25.27701, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "587d3b825fc8a40d7371f667b6fc9273c73a785fb13b5b39a6941b8dc4eff49d", + "test_representative_target": "test_resized/Test2800/target/919_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.236824 + } + ], + "train_targets": [ + { + "file_sha256": "c9a184b7d48f4ee8574356ca359ec4d82983b916153cb6ffb62f49a642f6c82f", + "relative_path": "train_resized/target/1149.jpg" + }, + { + "file_sha256": "c9a184b7d48f4ee8574356ca359ec4d82983b916153cb6ffb62f49a642f6c82f", + "relative_path": "train_resized/target/1449.jpg" + }, + { + "file_sha256": "c9a184b7d48f4ee8574356ca359ec4d82983b916153cb6ffb62f49a642f6c82f", + "relative_path": "train_resized/target/1749.jpg" + }, + { + "file_sha256": "c9a184b7d48f4ee8574356ca359ec4d82983b916153cb6ffb62f49a642f6c82f", + "relative_path": "train_resized/target/2049.jpg" + }, + { + "file_sha256": "c9a184b7d48f4ee8574356ca359ec4d82983b916153cb6ffb62f49a642f6c82f", + "relative_path": "train_resized/target/2349.jpg" + }, + { + "file_sha256": "c9a184b7d48f4ee8574356ca359ec4d82983b916153cb6ffb62f49a642f6c82f", + "relative_path": "train_resized/target/849.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "8b5e08d636bd16fe2ebe8054881e68f63706ac5b7a3464ef90be30d39b4a905b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 35.484178, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c64093be216c281e066eec1f128067bd8799023f507cb53d0a6107612e5e81f9", + "test_representative_target": "test_resized/Test2800/target/916_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 46.984959 + } + ], + "train_targets": [ + { + "file_sha256": "c56ed8aadac35ad972b183cad3296515f256bae2b473a2b942e47bf0c213f370", + "relative_path": "train_resized/target/392.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "8cb1e1bf619a59294b5fe10e5d7d73808cda41a0778c9200e3f8f4c6dc6331b9", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.664462, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "e9de5a1cb340bc2978ab0d20791b8ec920231a5141e68f6d251192ee275acb79", + "test_representative_target": "test_resized/Rain100H/target/53.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.763917 + }, + { + "full_rgb_psnr_db": 25.664462, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "e9de5a1cb340bc2978ab0d20791b8ec920231a5141e68f6d251192ee275acb79", + "test_representative_target": "test_resized/Rain100L/target/53.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.763917 + }, + { + "full_rgb_psnr_db": 25.819543, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "bfac501f7a604607d55056da814de8936560b239ae05d57e1c4775d6f9dfc133", + "test_representative_target": "test_resized/Test2800/target/925_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.057428 + } + ], + "train_targets": [ + { + "file_sha256": "0fcc11a21fa79dedc244bd12cf56255c5fbf213249493f1e932b2164c7be20d0", + "relative_path": "train_resized/target/1157.jpg" + }, + { + "file_sha256": "0fcc11a21fa79dedc244bd12cf56255c5fbf213249493f1e932b2164c7be20d0", + "relative_path": "train_resized/target/1457.jpg" + }, + { + "file_sha256": "0fcc11a21fa79dedc244bd12cf56255c5fbf213249493f1e932b2164c7be20d0", + "relative_path": "train_resized/target/1757.jpg" + }, + { + "file_sha256": "0fcc11a21fa79dedc244bd12cf56255c5fbf213249493f1e932b2164c7be20d0", + "relative_path": "train_resized/target/2057.jpg" + }, + { + "file_sha256": "0fcc11a21fa79dedc244bd12cf56255c5fbf213249493f1e932b2164c7be20d0", + "relative_path": "train_resized/target/2357.jpg" + }, + { + "file_sha256": "0fcc11a21fa79dedc244bd12cf56255c5fbf213249493f1e932b2164c7be20d0", + "relative_path": "train_resized/target/857.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "8cbc7298875336a2d3c84103b9931d4785b425f755ce4a39c593397c7a419626", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.863642, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "1b325372fc29988b3023662b4f459ff1b57dec8c9fb1d083b487a35e2e328094", + "test_representative_target": "test_resized/Rain100H/target/82.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.01454 + }, + { + "full_rgb_psnr_db": 22.863642, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "1b325372fc29988b3023662b4f459ff1b57dec8c9fb1d083b487a35e2e328094", + "test_representative_target": "test_resized/Rain100L/target/82.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.01454 + } + ], + "train_targets": [ + { + "file_sha256": "ce005cb26d0eae6c74cfb81e58e5bec6fb66ba436d63d8888fa6d624f93579f0", + "relative_path": "train_resized/target/1183.jpg" + }, + { + "file_sha256": "ce005cb26d0eae6c74cfb81e58e5bec6fb66ba436d63d8888fa6d624f93579f0", + "relative_path": "train_resized/target/1483.jpg" + }, + { + "file_sha256": "ce005cb26d0eae6c74cfb81e58e5bec6fb66ba436d63d8888fa6d624f93579f0", + "relative_path": "train_resized/target/1783.jpg" + }, + { + "file_sha256": "ce005cb26d0eae6c74cfb81e58e5bec6fb66ba436d63d8888fa6d624f93579f0", + "relative_path": "train_resized/target/2083.jpg" + }, + { + "file_sha256": "ce005cb26d0eae6c74cfb81e58e5bec6fb66ba436d63d8888fa6d624f93579f0", + "relative_path": "train_resized/target/2383.jpg" + }, + { + "file_sha256": "ce005cb26d0eae6c74cfb81e58e5bec6fb66ba436d63d8888fa6d624f93579f0", + "relative_path": "train_resized/target/883.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "8d79b563fad82417da37cccc36960f3cb00d1c97ac9c992cefc8aee573a6fc23", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.488765, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4488aa8ee1be1ab833a09b863682c554a15c0fd527cb47fde98ca5889b770226", + "test_representative_target": "test_resized/Rain100H/target/77.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.726991 + }, + { + "full_rgb_psnr_db": 22.488765, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4488aa8ee1be1ab833a09b863682c554a15c0fd527cb47fde98ca5889b770226", + "test_representative_target": "test_resized/Rain100L/target/77.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.726991 + } + ], + "train_targets": [ + { + "file_sha256": "1469eea1a929124c24eb0ddca019ca8efcf14709a42918642b23b382d80218b9", + "relative_path": "train_resized/target/1179.jpg" + }, + { + "file_sha256": "1469eea1a929124c24eb0ddca019ca8efcf14709a42918642b23b382d80218b9", + "relative_path": "train_resized/target/1479.jpg" + }, + { + "file_sha256": "1469eea1a929124c24eb0ddca019ca8efcf14709a42918642b23b382d80218b9", + "relative_path": "train_resized/target/1779.jpg" + }, + { + "file_sha256": "1469eea1a929124c24eb0ddca019ca8efcf14709a42918642b23b382d80218b9", + "relative_path": "train_resized/target/2079.jpg" + }, + { + "file_sha256": "1469eea1a929124c24eb0ddca019ca8efcf14709a42918642b23b382d80218b9", + "relative_path": "train_resized/target/2379.jpg" + }, + { + "file_sha256": "1469eea1a929124c24eb0ddca019ca8efcf14709a42918642b23b382d80218b9", + "relative_path": "train_resized/target/879.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "8dcfdff1f1438c317f95c604aad98559518ff6b32cd70d6f460bb1f59b1d1fcd", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.511824, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "7a22833fa7ae074ebee9bba8dc1c95e0df2f0793f5981cae07085073844e557f", + "test_representative_target": "test_resized/Rain100H/target/78.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.851108 + }, + { + "full_rgb_psnr_db": 30.511824, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "7a22833fa7ae074ebee9bba8dc1c95e0df2f0793f5981cae07085073844e557f", + "test_representative_target": "test_resized/Rain100L/target/78.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.851108 + } + ], + "train_targets": [ + { + "file_sha256": "c3f44868fd309e12d155efc2817918b3b7d28dba9cf53db829d37df4521b46c2", + "relative_path": "train_resized/target/1180.jpg" + }, + { + "file_sha256": "c3f44868fd309e12d155efc2817918b3b7d28dba9cf53db829d37df4521b46c2", + "relative_path": "train_resized/target/1480.jpg" + }, + { + "file_sha256": "c3f44868fd309e12d155efc2817918b3b7d28dba9cf53db829d37df4521b46c2", + "relative_path": "train_resized/target/1780.jpg" + }, + { + "file_sha256": "c3f44868fd309e12d155efc2817918b3b7d28dba9cf53db829d37df4521b46c2", + "relative_path": "train_resized/target/2080.jpg" + }, + { + "file_sha256": "c3f44868fd309e12d155efc2817918b3b7d28dba9cf53db829d37df4521b46c2", + "relative_path": "train_resized/target/2380.jpg" + }, + { + "file_sha256": "c3f44868fd309e12d155efc2817918b3b7d28dba9cf53db829d37df4521b46c2", + "relative_path": "train_resized/target/880.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "8ea2cedb98d141150b70e0f4423ec0df167740447ecb2645adb8024165c7b444", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.48639, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a692d3cac26ce169aa13ab8d85bac6cf5f0463a16f7d3a4aea957e2e90c14826", + "test_representative_target": "test_resized/Rain100H/target/75.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.188645 + }, + { + "full_rgb_psnr_db": 25.48639, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a692d3cac26ce169aa13ab8d85bac6cf5f0463a16f7d3a4aea957e2e90c14826", + "test_representative_target": "test_resized/Rain100L/target/75.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.188645 + } + ], + "train_targets": [ + { + "file_sha256": "789f907ed2e744d271e0c2f006cb562ff18f34ae8efa1df86de1a89515ffe204", + "relative_path": "train_resized/target/1177.jpg" + }, + { + "file_sha256": "789f907ed2e744d271e0c2f006cb562ff18f34ae8efa1df86de1a89515ffe204", + "relative_path": "train_resized/target/1477.jpg" + }, + { + "file_sha256": "789f907ed2e744d271e0c2f006cb562ff18f34ae8efa1df86de1a89515ffe204", + "relative_path": "train_resized/target/1777.jpg" + }, + { + "file_sha256": "789f907ed2e744d271e0c2f006cb562ff18f34ae8efa1df86de1a89515ffe204", + "relative_path": "train_resized/target/2077.jpg" + }, + { + "file_sha256": "789f907ed2e744d271e0c2f006cb562ff18f34ae8efa1df86de1a89515ffe204", + "relative_path": "train_resized/target/2377.jpg" + }, + { + "file_sha256": "789f907ed2e744d271e0c2f006cb562ff18f34ae8efa1df86de1a89515ffe204", + "relative_path": "train_resized/target/877.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "9020ec0656398fb0fd4a642d8135eba86b5cdbad64c556f0698f106d94f8594f", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 29.941073, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b92cb0ff61adda7b34583a0b5649a53470d520b984cd04cb54bee4d1bd07966b", + "test_representative_target": "test_resized/Rain100H/target/18.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.128812 + }, + { + "full_rgb_psnr_db": 29.941073, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b92cb0ff61adda7b34583a0b5649a53470d520b984cd04cb54bee4d1bd07966b", + "test_representative_target": "test_resized/Rain100L/target/18.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.128812 + } + ], + "train_targets": [ + { + "file_sha256": "0218d6a4897d1e2bc5ea396ecc06c2418a99685ca75b6a4da064fce9166191c4", + "relative_path": "train_resized/target/1125.jpg" + }, + { + "file_sha256": "0218d6a4897d1e2bc5ea396ecc06c2418a99685ca75b6a4da064fce9166191c4", + "relative_path": "train_resized/target/1425.jpg" + }, + { + "file_sha256": "0218d6a4897d1e2bc5ea396ecc06c2418a99685ca75b6a4da064fce9166191c4", + "relative_path": "train_resized/target/1725.jpg" + }, + { + "file_sha256": "0218d6a4897d1e2bc5ea396ecc06c2418a99685ca75b6a4da064fce9166191c4", + "relative_path": "train_resized/target/2025.jpg" + }, + { + "file_sha256": "0218d6a4897d1e2bc5ea396ecc06c2418a99685ca75b6a4da064fce9166191c4", + "relative_path": "train_resized/target/2325.jpg" + }, + { + "file_sha256": "0218d6a4897d1e2bc5ea396ecc06c2418a99685ca75b6a4da064fce9166191c4", + "relative_path": "train_resized/target/825.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "921be506364f2b4b5db49f96d8d28e5a77c56c3ca902e1f86f1fe7352bf9f026", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.582317, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "928718141044bc4423470b5b76641b64ea783a3add3e8646faa966e090af9c3b", + "test_representative_target": "test_resized/Rain100H/target/70.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.010921 + }, + { + "full_rgb_psnr_db": 24.582317, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "928718141044bc4423470b5b76641b64ea783a3add3e8646faa966e090af9c3b", + "test_representative_target": "test_resized/Rain100L/target/70.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.010921 + }, + { + "full_rgb_psnr_db": 24.655537, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "73b2b94a218a3da33b7f65d5e7744ffee4fd548a834f4edd72e189116dab8ef8", + "test_representative_target": "test_resized/Test2800/target/932_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.275256 + } + ], + "train_targets": [ + { + "file_sha256": "81b248ec3e503bb3f80dc21c839eb5a13c1280e0c3014566d8f885e09dd503fe", + "relative_path": "train_resized/target/305.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "95e735eb18e651abb56004ec3dd8a9e35fb854cf02dc85c491623bbdb12bc62a", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 35.299165, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "70551de4465b1803144056da0e35e320d38a55807e2758016be09d0d1cbffd65", + "test_representative_target": "test_resized/Test100/target/65.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.576979 + }, + { + "full_rgb_psnr_db": 35.298009, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "dae46b522926a742a8e1dd0c363933534c448c9377197d08769cbf77f2ae388f", + "test_representative_target": "test_resized/Test100/target/54.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.572663 + } + ], + "train_targets": [ + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9779.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9780.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9781.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9782.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9783.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9784.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9785.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9786.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9787.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9788.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9789.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9790.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9791.jpg" + }, + { + "file_sha256": "9872cfb15a75be818311454a96ea69795643417eae18b3045ccaf0623acbcc30", + "relative_path": "train_resized/target/9792.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "9675ad2114d05127d6e1aeec69509b62027f3ff28a6ff55ce55e441a0b40f67a", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 19.455848, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "f7d5492592084647e08c653c637d7ada9b4afddabb8a65190fb43454b6f0cd38", + "test_representative_target": "test_resized/Test2800/target/977_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 34.345157 + } + ], + "train_targets": [ + { + "file_sha256": "078a7266225a6cee6f2a7d73039fee7c08be10ee7e383f30a749fa6fd253409e", + "relative_path": "train_resized/target/1069.jpg" + }, + { + "file_sha256": "078a7266225a6cee6f2a7d73039fee7c08be10ee7e383f30a749fa6fd253409e", + "relative_path": "train_resized/target/1369.jpg" + }, + { + "file_sha256": "078a7266225a6cee6f2a7d73039fee7c08be10ee7e383f30a749fa6fd253409e", + "relative_path": "train_resized/target/1669.jpg" + }, + { + "file_sha256": "078a7266225a6cee6f2a7d73039fee7c08be10ee7e383f30a749fa6fd253409e", + "relative_path": "train_resized/target/1969.jpg" + }, + { + "file_sha256": "078a7266225a6cee6f2a7d73039fee7c08be10ee7e383f30a749fa6fd253409e", + "relative_path": "train_resized/target/2269.jpg" + }, + { + "file_sha256": "078a7266225a6cee6f2a7d73039fee7c08be10ee7e383f30a749fa6fd253409e", + "relative_path": "train_resized/target/769.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "96d77c7c588e8c460f7dab22c8450c10246dd7cc59cc9fc4f312fe585f4ed3db", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 36.478658, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "249c7a696c63f0a6593c4df655f33d7fefc221e3cf1c5968697e47866d7ec2a4", + "test_representative_target": "test_resized/Test100/target/58.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 48.002651 + } + ], + "train_targets": [ + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9387.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9388.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9389.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9390.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9391.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9392.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9393.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9394.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9395.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9396.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9397.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9398.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9399.jpg" + }, + { + "file_sha256": "41e2b5fc6b7239cd74f55aad596377a81e389b3aa5d2dae6c5481d5dc3bef17c", + "relative_path": "train_resized/target/9400.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "9c900bd2af82e78aa576dfeb018a95a121a264d9f46704577dfc49311f622dac", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.590362, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a3a3010fd6c5ebae8d1759c156a0b762969ab2a2110c156d49e5c0b9e8e5f17c", + "test_representative_target": "test_resized/Test2800/target/997_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.569395 + } + ], + "train_targets": [ + { + "file_sha256": "14b5e5b742b4ba3d412e1c313f7a2c0479d9bec7673620278fb49c82991d12a6", + "relative_path": "train_resized/target/646.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "9fd423f76baf0d957632a6513b3bd6ae33cc6b7322c67f9e6cc89dd6d338b24e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.369463, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "e8ef462822b0c0ea7867cc3c76b868639f560d12565f59e7d032545ec00588af", + "test_representative_target": "test_resized/Test2800/target/836_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.199359 + } + ], + "train_targets": [ + { + "file_sha256": "1b5b800565a746fe1271581ca9f1d69c9318efee1687d0590657e888fe851b40", + "relative_path": "train_resized/target/1082.jpg" + }, + { + "file_sha256": "1b5b800565a746fe1271581ca9f1d69c9318efee1687d0590657e888fe851b40", + "relative_path": "train_resized/target/1382.jpg" + }, + { + "file_sha256": "1b5b800565a746fe1271581ca9f1d69c9318efee1687d0590657e888fe851b40", + "relative_path": "train_resized/target/1682.jpg" + }, + { + "file_sha256": "1b5b800565a746fe1271581ca9f1d69c9318efee1687d0590657e888fe851b40", + "relative_path": "train_resized/target/1982.jpg" + }, + { + "file_sha256": "1b5b800565a746fe1271581ca9f1d69c9318efee1687d0590657e888fe851b40", + "relative_path": "train_resized/target/2282.jpg" + }, + { + "file_sha256": "1b5b800565a746fe1271581ca9f1d69c9318efee1687d0590657e888fe851b40", + "relative_path": "train_resized/target/782.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a10c0963858ab3ee502e15ce028d343be579217621cb8b74188b5c39d01fa825", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.199078, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "865cbd0f5bb0b033655bab9d72a2b717cd5afb26faf2ec2445fbf2c01bb1b955", + "test_representative_target": "test_resized/Rain100H/target/33.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.937909 + }, + { + "full_rgb_psnr_db": 28.199078, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "865cbd0f5bb0b033655bab9d72a2b717cd5afb26faf2ec2445fbf2c01bb1b955", + "test_representative_target": "test_resized/Rain100L/target/33.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.937909 + } + ], + "train_targets": [ + { + "file_sha256": "2738b220416f9c8235767b6aa5a03802282fd60fd9ca1e323fd11bdfddacedf1", + "relative_path": "train_resized/target/1139.jpg" + }, + { + "file_sha256": "2738b220416f9c8235767b6aa5a03802282fd60fd9ca1e323fd11bdfddacedf1", + "relative_path": "train_resized/target/1439.jpg" + }, + { + "file_sha256": "2738b220416f9c8235767b6aa5a03802282fd60fd9ca1e323fd11bdfddacedf1", + "relative_path": "train_resized/target/1739.jpg" + }, + { + "file_sha256": "2738b220416f9c8235767b6aa5a03802282fd60fd9ca1e323fd11bdfddacedf1", + "relative_path": "train_resized/target/2039.jpg" + }, + { + "file_sha256": "2738b220416f9c8235767b6aa5a03802282fd60fd9ca1e323fd11bdfddacedf1", + "relative_path": "train_resized/target/2339.jpg" + }, + { + "file_sha256": "2738b220416f9c8235767b6aa5a03802282fd60fd9ca1e323fd11bdfddacedf1", + "relative_path": "train_resized/target/839.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a2c8f50a0caecac25bff7de5df2fbc53d10ed2290fdd1d2c1604ad85575ae16c", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.870052, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "eddb0de10da48ba292d7912bc8e779439db2ebab233b62d4377d7750b54e3202", + "test_representative_target": "test_resized/Rain100H/target/46.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.130251 + }, + { + "full_rgb_psnr_db": 22.870052, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "eddb0de10da48ba292d7912bc8e779439db2ebab233b62d4377d7750b54e3202", + "test_representative_target": "test_resized/Rain100L/target/46.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.130251 + } + ], + "train_targets": [ + { + "file_sha256": "43795720c2a2ae97a9bceef8e5964a35357a9c4f66ce655f463ff8c76ec31010", + "relative_path": "train_resized/target/1151.jpg" + }, + { + "file_sha256": "43795720c2a2ae97a9bceef8e5964a35357a9c4f66ce655f463ff8c76ec31010", + "relative_path": "train_resized/target/1451.jpg" + }, + { + "file_sha256": "43795720c2a2ae97a9bceef8e5964a35357a9c4f66ce655f463ff8c76ec31010", + "relative_path": "train_resized/target/1751.jpg" + }, + { + "file_sha256": "43795720c2a2ae97a9bceef8e5964a35357a9c4f66ce655f463ff8c76ec31010", + "relative_path": "train_resized/target/2051.jpg" + }, + { + "file_sha256": "43795720c2a2ae97a9bceef8e5964a35357a9c4f66ce655f463ff8c76ec31010", + "relative_path": "train_resized/target/2351.jpg" + }, + { + "file_sha256": "43795720c2a2ae97a9bceef8e5964a35357a9c4f66ce655f463ff8c76ec31010", + "relative_path": "train_resized/target/851.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a5085d4fe2513eefa1b224e85e5f5e0c837d7da70d6f2acd8d48cc6e3cc93fc2", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.759258, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "504005532d84f15ac05d8cb3ae5ad117b01ee63cde35273e99960e13b725cdc3", + "test_representative_target": "test_resized/Test2800/target/954_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.713546 + } + ], + "train_targets": [ + { + "file_sha256": "1c25a629947bffff7561381c62687d3c30340cd5a10de1385b2d9cfe06b8d709", + "relative_path": "train_resized/target/573.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a515b07e6902cdf063b9235b26eae1b55e89509ccd2b14e29ee9fb36e3bdbd09", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 29.151205, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "d2f9e07894ec5792c1e0faec4efb2f76396934b284024b1dfb0d373d0a76629a", + "test_representative_target": "test_resized/Rain100H/target/48.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.592204 + }, + { + "full_rgb_psnr_db": 29.151205, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "d2f9e07894ec5792c1e0faec4efb2f76396934b284024b1dfb0d373d0a76629a", + "test_representative_target": "test_resized/Rain100L/target/48.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 39.592204 + } + ], + "train_targets": [ + { + "file_sha256": "3adaa8d78e1154e64dbef14f0b2fc3935468bcd5b11f608c8bc6f88a81dad8fc", + "relative_path": "train_resized/target/1152.jpg" + }, + { + "file_sha256": "3adaa8d78e1154e64dbef14f0b2fc3935468bcd5b11f608c8bc6f88a81dad8fc", + "relative_path": "train_resized/target/1452.jpg" + }, + { + "file_sha256": "3adaa8d78e1154e64dbef14f0b2fc3935468bcd5b11f608c8bc6f88a81dad8fc", + "relative_path": "train_resized/target/1752.jpg" + }, + { + "file_sha256": "3adaa8d78e1154e64dbef14f0b2fc3935468bcd5b11f608c8bc6f88a81dad8fc", + "relative_path": "train_resized/target/2052.jpg" + }, + { + "file_sha256": "3adaa8d78e1154e64dbef14f0b2fc3935468bcd5b11f608c8bc6f88a81dad8fc", + "relative_path": "train_resized/target/2352.jpg" + }, + { + "file_sha256": "3adaa8d78e1154e64dbef14f0b2fc3935468bcd5b11f608c8bc6f88a81dad8fc", + "relative_path": "train_resized/target/852.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a5313808f592f93ac1878cec8d7e4b3c86664c2f53a2045a275ae32518c2de1e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.465378, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "e242dd8ff3e88a4ee806e9ea66dfb03b02273a878357cfb7734c1d70d381355e", + "test_representative_target": "test_resized/Test2800/target/963_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.445448 + } + ], + "train_targets": [ + { + "file_sha256": "4b70804754fd9add043a7f2419de248adb5cb04147c686c5dac57fd2189f4ff4", + "relative_path": "train_resized/target/4.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a5b4021302824d0c2c603e7e861576f16fc30b712dd9efb54017190949108cf2", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.646533, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "a9694208bef00b3ef6d3f4d3a0000b97604df46a0386f443214a47e7cdba0ac6", + "test_representative_target": "test_resized/Test2800/target/959_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 40.199573 + } + ], + "train_targets": [ + { + "file_sha256": "9f4a44aca47030da534cac3b9b923b4e57fc0bb70ee1dd55e1a246f6a52fafe0", + "relative_path": "train_resized/target/1021.jpg" + }, + { + "file_sha256": "9f4a44aca47030da534cac3b9b923b4e57fc0bb70ee1dd55e1a246f6a52fafe0", + "relative_path": "train_resized/target/1321.jpg" + }, + { + "file_sha256": "9f4a44aca47030da534cac3b9b923b4e57fc0bb70ee1dd55e1a246f6a52fafe0", + "relative_path": "train_resized/target/1621.jpg" + }, + { + "file_sha256": "9f4a44aca47030da534cac3b9b923b4e57fc0bb70ee1dd55e1a246f6a52fafe0", + "relative_path": "train_resized/target/1921.jpg" + }, + { + "file_sha256": "9f4a44aca47030da534cac3b9b923b4e57fc0bb70ee1dd55e1a246f6a52fafe0", + "relative_path": "train_resized/target/2221.jpg" + }, + { + "file_sha256": "9f4a44aca47030da534cac3b9b923b4e57fc0bb70ee1dd55e1a246f6a52fafe0", + "relative_path": "train_resized/target/721.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a61d33256980596a7144a3e1268b5aeb1b5f6f00e6e82abf65304b0ab322f835", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.29819, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "67dbd30b28c0c817b73a7e721571a747c8034b075723a448c7a00ec4736e6d3a", + "test_representative_target": "test_resized/Test2800/target/922_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.685439 + } + ], + "train_targets": [ + { + "file_sha256": "7cb9fe802353dfd321d9125650a199294cd3afd3dee2a023fe3c0dfdf20bc533", + "relative_path": "train_resized/target/411.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a62fbb6c5cf27a168b05e6317661238bf37d314d792f0afe9021724e12359adf", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 21.311732, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c4e0613f98eb82ed776563199830f32d8a2416584f2adb6b3e66ddac23e52021", + "test_representative_target": "test_resized/Test2800/target/822_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 33.706269 + } + ], + "train_targets": [ + { + "file_sha256": "0db80dc8fd3e03040472276b74e0716be454e9e15911a348ee2edeb9a1ee9c5c", + "relative_path": "train_resized/target/1071.jpg" + }, + { + "file_sha256": "0db80dc8fd3e03040472276b74e0716be454e9e15911a348ee2edeb9a1ee9c5c", + "relative_path": "train_resized/target/1371.jpg" + }, + { + "file_sha256": "0db80dc8fd3e03040472276b74e0716be454e9e15911a348ee2edeb9a1ee9c5c", + "relative_path": "train_resized/target/1671.jpg" + }, + { + "file_sha256": "0db80dc8fd3e03040472276b74e0716be454e9e15911a348ee2edeb9a1ee9c5c", + "relative_path": "train_resized/target/1971.jpg" + }, + { + "file_sha256": "0db80dc8fd3e03040472276b74e0716be454e9e15911a348ee2edeb9a1ee9c5c", + "relative_path": "train_resized/target/2271.jpg" + }, + { + "file_sha256": "0db80dc8fd3e03040472276b74e0716be454e9e15911a348ee2edeb9a1ee9c5c", + "relative_path": "train_resized/target/771.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a66626f771730d4996346adebb9d9368ed24f019022dfd9216d64162a9658a7f", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 35.853801, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "da6e3fd09235da03487c20aea4b05e06414a0421cbc5c0f94a6f0525c993c684", + "test_representative_target": "test_resized/Test100/target/69.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.652391 + } + ], + "train_targets": [ + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11571.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11572.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11573.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11574.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11575.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11576.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11577.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11578.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11579.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11580.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11581.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11582.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11583.jpg" + }, + { + "file_sha256": "bbcb22c4c54492d60044c353882df4170d9b3ff19e7b7628034e75260af50115", + "relative_path": "train_resized/target/11584.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "a793231c13b21d8a4a1f2d3516b2f5a773fcff67a5419d990d974e77fcb92582", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.456165, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cae89291b0363c7bc034ae849680f21689ac27eb3ccd6faa9440dd5de1131180", + "test_representative_target": "test_resized/Test100/target/84.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.424607 + } + ], + "train_targets": [ + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7861.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7862.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7863.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7864.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7865.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7866.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7867.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7868.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7869.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7870.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7871.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7872.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7873.jpg" + }, + { + "file_sha256": "e4f21a29f4bcd3fd7e0993f533e68f982801fe1fa3b0b11a866c91316539e31e", + "relative_path": "train_resized/target/7874.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "aa55a6a67174309c07d495608e5c8c39763043c60545162320c6bfe99eb0febc", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.75888, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9ed84a04c465f8772c3c76bbe210a1e8fa65a6dd8ca588779c936b49e207ea07", + "test_representative_target": "test_resized/Test100/target/89.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.039619 + } + ], + "train_targets": [ + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3115.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3116.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3117.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3118.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3119.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3120.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3121.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3122.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3123.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3124.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3125.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3126.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3127.jpg" + }, + { + "file_sha256": "7dd131d9a0ee6f05db1f508e56a25d018febe46a72f1e9064208b2b4f612d163", + "relative_path": "train_resized/target/3128.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "ab9157109b00d26110832c3b3237fef9f442546b9e1c34dd590e9fc23a0b014b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.49113, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "473d47b73749771167459c9cb2a6003e4d4a711365d7bfbb72cb672b7682e7e3", + "test_representative_target": "test_resized/Rain100H/target/61.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.786219 + }, + { + "full_rgb_psnr_db": 26.49113, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "473d47b73749771167459c9cb2a6003e4d4a711365d7bfbb72cb672b7682e7e3", + "test_representative_target": "test_resized/Rain100L/target/61.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.786219 + }, + { + "full_rgb_psnr_db": 26.744912, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "7d830d4c1c4c13c6e007175b1fafb32578f8ffa8044d8c2a791536913ab9d0e5", + "test_representative_target": "test_resized/Test2800/target/1000_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.208494 + } + ], + "train_targets": [ + { + "file_sha256": "0023b4aeb4331905310e65db57a2ee851cbb932bbf2b7da3643584bcfc71aba3", + "relative_path": "train_resized/target/1164.jpg" + }, + { + "file_sha256": "0023b4aeb4331905310e65db57a2ee851cbb932bbf2b7da3643584bcfc71aba3", + "relative_path": "train_resized/target/1464.jpg" + }, + { + "file_sha256": "0023b4aeb4331905310e65db57a2ee851cbb932bbf2b7da3643584bcfc71aba3", + "relative_path": "train_resized/target/1764.jpg" + }, + { + "file_sha256": "0023b4aeb4331905310e65db57a2ee851cbb932bbf2b7da3643584bcfc71aba3", + "relative_path": "train_resized/target/2064.jpg" + }, + { + "file_sha256": "0023b4aeb4331905310e65db57a2ee851cbb932bbf2b7da3643584bcfc71aba3", + "relative_path": "train_resized/target/2364.jpg" + }, + { + "file_sha256": "0023b4aeb4331905310e65db57a2ee851cbb932bbf2b7da3643584bcfc71aba3", + "relative_path": "train_resized/target/864.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "af6993b0c7bf6adecb8dfc255ccbe1abc6759369f3ad568770972a2444996dd0", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 35.760884, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a52e9e06fcfaf6f5ddf2d7b61b01820a22e0860bafadcf25efd981bc8c5de0bf", + "test_representative_target": "test_resized/Test100/target/79.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.818338 + } + ], + "train_targets": [ + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9751.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9752.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9753.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9754.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9755.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9756.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9757.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9758.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9759.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9760.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9761.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9762.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9763.jpg" + }, + { + "file_sha256": "2333ac9e1396847f7ba127d0661892a8b23f7148e1773283821de60c79182908", + "relative_path": "train_resized/target/9764.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "b3e609a8e6375b53748db04d6ff341259b0ac90a3fc55fd00581590d39eb2a3b", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.899977, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "848a38ac31e820d14f8a4482b82fdb60f74898ed1580256dad59c78beee7f50a", + "test_representative_target": "test_resized/Test2800/target/982_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.296066 + } + ], + "train_targets": [ + { + "file_sha256": "dfd5ab9c43b2db7f14f00f93a5cf93ddef3722f90522ff412bd4af949cddce97", + "relative_path": "train_resized/target/1249.jpg" + }, + { + "file_sha256": "dfd5ab9c43b2db7f14f00f93a5cf93ddef3722f90522ff412bd4af949cddce97", + "relative_path": "train_resized/target/1549.jpg" + }, + { + "file_sha256": "dfd5ab9c43b2db7f14f00f93a5cf93ddef3722f90522ff412bd4af949cddce97", + "relative_path": "train_resized/target/1849.jpg" + }, + { + "file_sha256": "dfd5ab9c43b2db7f14f00f93a5cf93ddef3722f90522ff412bd4af949cddce97", + "relative_path": "train_resized/target/2149.jpg" + }, + { + "file_sha256": "dfd5ab9c43b2db7f14f00f93a5cf93ddef3722f90522ff412bd4af949cddce97", + "relative_path": "train_resized/target/2449.jpg" + }, + { + "file_sha256": "dfd5ab9c43b2db7f14f00f93a5cf93ddef3722f90522ff412bd4af949cddce97", + "relative_path": "train_resized/target/949.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "b4601634a78f1c21838d3a4e9ed1cd1812751cf1c420d6efc11ce68c6625b65d", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.346564, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a9af9a96c39eceb61af1e574a5a7e6f406dedf3c89e6d229c66074476678ecd2", + "test_representative_target": "test_resized/Test100/target/88.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 44.706513 + } + ], + "train_targets": [ + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10787.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10788.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10789.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10790.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10791.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10792.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10793.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10794.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10795.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10796.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10797.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10798.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10799.jpg" + }, + { + "file_sha256": "7e416858c2cd9be16a8841df8ff63919318a6ebd4972725f3731509c19d0963a", + "relative_path": "train_resized/target/10800.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "ba073e0c4d4d8676204727dafd6e9d127c07aaf0aa2ccbb3400c217493c6bc60", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 17.910418, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9cbb29b6aacd4eac8fa2875c9b15388a2a515c4864a032b57ce3a2617ef53802", + "test_representative_target": "test_resized/Rain100H/target/85.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 33.021681 + }, + { + "full_rgb_psnr_db": 17.910418, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9cbb29b6aacd4eac8fa2875c9b15388a2a515c4864a032b57ce3a2617ef53802", + "test_representative_target": "test_resized/Rain100L/target/85.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 33.021681 + } + ], + "train_targets": [ + { + "file_sha256": "5cb959e33afdd1ab3c1ea72c20a6f230877ddf0956e55394172c07864a61a61b", + "relative_path": "train_resized/target/1186.jpg" + }, + { + "file_sha256": "5cb959e33afdd1ab3c1ea72c20a6f230877ddf0956e55394172c07864a61a61b", + "relative_path": "train_resized/target/1486.jpg" + }, + { + "file_sha256": "5cb959e33afdd1ab3c1ea72c20a6f230877ddf0956e55394172c07864a61a61b", + "relative_path": "train_resized/target/1786.jpg" + }, + { + "file_sha256": "5cb959e33afdd1ab3c1ea72c20a6f230877ddf0956e55394172c07864a61a61b", + "relative_path": "train_resized/target/2086.jpg" + }, + { + "file_sha256": "5cb959e33afdd1ab3c1ea72c20a6f230877ddf0956e55394172c07864a61a61b", + "relative_path": "train_resized/target/2386.jpg" + }, + { + "file_sha256": "5cb959e33afdd1ab3c1ea72c20a6f230877ddf0956e55394172c07864a61a61b", + "relative_path": "train_resized/target/886.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "ba40e4011b070125a6c5096467578d51cb98176fd45d59e0566d82d93a3aed81", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.645788, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "8da4a595b7a95c7b6960162b789d746363c24bed3e71e646987489d58f7cef7d", + "test_representative_target": "test_resized/Test100/target/72.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.243331 + } + ], + "train_targets": [ + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3031.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3032.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3033.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3034.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3035.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3036.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3037.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3038.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3039.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3040.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3041.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3042.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3043.jpg" + }, + { + "file_sha256": "561700e5a68d612919a66edf74f6e6bde718058ff7bed48bd7c8646f2825b06e", + "relative_path": "train_resized/target/3044.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "bad0f7ce444be66b72dfc1c259e4afcf7ee2d286998754be74440638b10a7c42", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.903172, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "fa844812782ab835963a0046d69ffd1123b8053dd25ff1e1617a88f313b4e68b", + "test_representative_target": "test_resized/Rain100H/target/83.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 42.107554 + }, + { + "full_rgb_psnr_db": 30.903172, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "fa844812782ab835963a0046d69ffd1123b8053dd25ff1e1617a88f313b4e68b", + "test_representative_target": "test_resized/Rain100L/target/83.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 42.107554 + } + ], + "train_targets": [ + { + "file_sha256": "1cf9c6b6f0a0148ae79d50a1f6ac78bc5fc1f60963eec2f4e6b555b74b189a20", + "relative_path": "train_resized/target/1184.jpg" + }, + { + "file_sha256": "1cf9c6b6f0a0148ae79d50a1f6ac78bc5fc1f60963eec2f4e6b555b74b189a20", + "relative_path": "train_resized/target/1484.jpg" + }, + { + "file_sha256": "1cf9c6b6f0a0148ae79d50a1f6ac78bc5fc1f60963eec2f4e6b555b74b189a20", + "relative_path": "train_resized/target/1784.jpg" + }, + { + "file_sha256": "1cf9c6b6f0a0148ae79d50a1f6ac78bc5fc1f60963eec2f4e6b555b74b189a20", + "relative_path": "train_resized/target/2084.jpg" + }, + { + "file_sha256": "1cf9c6b6f0a0148ae79d50a1f6ac78bc5fc1f60963eec2f4e6b555b74b189a20", + "relative_path": "train_resized/target/2384.jpg" + }, + { + "file_sha256": "1cf9c6b6f0a0148ae79d50a1f6ac78bc5fc1f60963eec2f4e6b555b74b189a20", + "relative_path": "train_resized/target/884.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "bd86c7db8489178b71b2d0c1ae5aaf2cafa06b0ac5febd38aa13c300950bcba3", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.829734, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "fda14226e027f95d2d85d15785cd9c15e167908fe0d8e584aefa02bde5faa113", + "test_representative_target": "test_resized/Test2800/target/991_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.949039 + } + ], + "train_targets": [ + { + "file_sha256": "2d246f7520de44ac974b8c44bd47e7fdf84398531c13475950291bd791909f7f", + "relative_path": "train_resized/target/521.jpg" + }, + { + "file_sha256": "2d246f7520de44ac974b8c44bd47e7fdf84398531c13475950291bd791909f7f", + "relative_path": "train_resized/target/575.jpg" + }, + { + "file_sha256": "2d246f7520de44ac974b8c44bd47e7fdf84398531c13475950291bd791909f7f", + "relative_path": "train_resized/target/670.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c00d558315e3ac12469e94b9ef8b68fc318914dde065aac087d4b07701fb4010", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 36.843208, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "6cd67bd1dc3840834ca9e7d0e4c5c8060d41db378cc8ea1cdfc3d3f0b1c75180", + "test_representative_target": "test_resized/Test2800/target/984_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 49.173148 + } + ], + "train_targets": [ + { + "file_sha256": "0c1e5a685d4536c80945151de2bf9e391530c863cae6fe0c98c4938593412f13", + "relative_path": "train_resized/target/478.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c0f71a9e24059a6973cacb1142be50260cca566ee990587bafb78dd79cadcffa", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 35.623559, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "e98038015b70af36844dd5fb4b62d4575d72ab673da0a6ee7e62cba1fccaf788", + "test_representative_target": "test_resized/Test2800/target/929_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.557516 + } + ], + "train_targets": [ + { + "file_sha256": "5a69663f8da08f134441ab95bce4748456c76021ec18a0535cc3465b01e934a5", + "relative_path": "train_resized/target/476.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c18ab6e90f961fcdc7ebaa6d6ef64ce6b93ba99fed04c45d52e29f15870d94c0", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.789563, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "d39f8039f928025cb0b2ab15476be744ad4ab90208f8de93d88eab92524b78ed", + "test_representative_target": "test_resized/Rain100H/target/93.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.204971 + }, + { + "full_rgb_psnr_db": 22.789563, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "d39f8039f928025cb0b2ab15476be744ad4ab90208f8de93d88eab92524b78ed", + "test_representative_target": "test_resized/Rain100L/target/93.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.204971 + } + ], + "train_targets": [ + { + "file_sha256": "c3fc28fdb5096870c1da7bafda352b9d25506b923b09d9020240a9f69ec43744", + "relative_path": "train_resized/target/12.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c2b4ec0cd6cfb12676202013a5ca347fcef791548c290c2de1b9af796375e714", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.35153, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "4043dd1140d3ab6f0cb9de714f662fecd1e5b256dd8bfca083a9b8be0944240c", + "test_representative_target": "test_resized/Rain100H/target/45.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.177878 + }, + { + "full_rgb_psnr_db": 23.35153, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "4043dd1140d3ab6f0cb9de714f662fecd1e5b256dd8bfca083a9b8be0944240c", + "test_representative_target": "test_resized/Rain100L/target/45.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.177878 + } + ], + "train_targets": [ + { + "file_sha256": "b112de328788bd325d7df4f93c6115d66adb645fc50965972fa63c0b461178a9", + "relative_path": "train_resized/target/1150.jpg" + }, + { + "file_sha256": "b112de328788bd325d7df4f93c6115d66adb645fc50965972fa63c0b461178a9", + "relative_path": "train_resized/target/1450.jpg" + }, + { + "file_sha256": "b112de328788bd325d7df4f93c6115d66adb645fc50965972fa63c0b461178a9", + "relative_path": "train_resized/target/1750.jpg" + }, + { + "file_sha256": "b112de328788bd325d7df4f93c6115d66adb645fc50965972fa63c0b461178a9", + "relative_path": "train_resized/target/2050.jpg" + }, + { + "file_sha256": "b112de328788bd325d7df4f93c6115d66adb645fc50965972fa63c0b461178a9", + "relative_path": "train_resized/target/2350.jpg" + }, + { + "file_sha256": "b112de328788bd325d7df4f93c6115d66adb645fc50965972fa63c0b461178a9", + "relative_path": "train_resized/target/850.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c460da2338a7483576021ce80564a926da0e42913006e2a3b0ee7c48a327ede6", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.241211, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "786460ebc3ae9f409252a4ca1eaec1153304b422090c5fc999a900171cfe49f4", + "test_representative_target": "test_resized/Rain100H/target/3.png", + "test_split": "Rain100H", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 33.180992 + }, + { + "full_rgb_psnr_db": 22.241211, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "786460ebc3ae9f409252a4ca1eaec1153304b422090c5fc999a900171cfe49f4", + "test_representative_target": "test_resized/Rain100L/target/3.png", + "test_split": "Rain100L", + "test_target_group_size": 2, + "thumbnail_rgb_psnr_db": 33.180992 + } + ], + "train_targets": [ + { + "file_sha256": "89995830b09efd2009e392792f1d3c145caaf9e07f675290bd45a47d8cecac7e", + "relative_path": "train_resized/target/1112.jpg" + }, + { + "file_sha256": "89995830b09efd2009e392792f1d3c145caaf9e07f675290bd45a47d8cecac7e", + "relative_path": "train_resized/target/1412.jpg" + }, + { + "file_sha256": "89995830b09efd2009e392792f1d3c145caaf9e07f675290bd45a47d8cecac7e", + "relative_path": "train_resized/target/1712.jpg" + }, + { + "file_sha256": "89995830b09efd2009e392792f1d3c145caaf9e07f675290bd45a47d8cecac7e", + "relative_path": "train_resized/target/2012.jpg" + }, + { + "file_sha256": "89995830b09efd2009e392792f1d3c145caaf9e07f675290bd45a47d8cecac7e", + "relative_path": "train_resized/target/2312.jpg" + }, + { + "file_sha256": "89995830b09efd2009e392792f1d3c145caaf9e07f675290bd45a47d8cecac7e", + "relative_path": "train_resized/target/812.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c599f3bbe5d721b730f19fffc276345f782f57474725ba7e6feccdd8389f8193", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 36.374649, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "0fb88474486a738e3f80f3fb31bb48a5e43b6b7c08d5554c245bf4867dc4031e", + "test_representative_target": "test_resized/Test100/target/71.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.525116 + } + ], + "train_targets": [ + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11501.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11502.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11503.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11504.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11505.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11506.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11507.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11508.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11509.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11510.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11511.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11512.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11513.jpg" + }, + { + "file_sha256": "8b66fd107d181808bec87f1d28bc01f47bfc66e9129c0f2c4ce072a074462b66", + "relative_path": "train_resized/target/11514.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c5ea44d50d056b9eb3b2e6c33882be88636b94f6a3244564b5abb1c84babd3a4", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.304364, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "aad965c7b0a8e27d7e433beb87fe51f849109116357ee6efef747871cb0090b1", + "test_representative_target": "test_resized/Test2800/target/986_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.460531 + } + ], + "train_targets": [ + { + "file_sha256": "be099c060c538c8f8b5d5de78b1e81e3a0fa9b459eb4dd22bbaff87210a66633", + "relative_path": "train_resized/target/1099.jpg" + }, + { + "file_sha256": "be099c060c538c8f8b5d5de78b1e81e3a0fa9b459eb4dd22bbaff87210a66633", + "relative_path": "train_resized/target/1399.jpg" + }, + { + "file_sha256": "be099c060c538c8f8b5d5de78b1e81e3a0fa9b459eb4dd22bbaff87210a66633", + "relative_path": "train_resized/target/1699.jpg" + }, + { + "file_sha256": "be099c060c538c8f8b5d5de78b1e81e3a0fa9b459eb4dd22bbaff87210a66633", + "relative_path": "train_resized/target/1999.jpg" + }, + { + "file_sha256": "be099c060c538c8f8b5d5de78b1e81e3a0fa9b459eb4dd22bbaff87210a66633", + "relative_path": "train_resized/target/2299.jpg" + }, + { + "file_sha256": "be099c060c538c8f8b5d5de78b1e81e3a0fa9b459eb4dd22bbaff87210a66633", + "relative_path": "train_resized/target/799.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c88b5fa546daa732e1b1c70aeb841e813a498021eef1eb62c8292b2a4c067c3a", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.299511, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "64510637ffc9a359cb4a213772b7299c50260bc77ae2700509d4f3e7039f6867", + "test_representative_target": "test_resized/Rain100H/target/60.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 40.936487 + }, + { + "full_rgb_psnr_db": 34.299511, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "64510637ffc9a359cb4a213772b7299c50260bc77ae2700509d4f3e7039f6867", + "test_representative_target": "test_resized/Rain100L/target/60.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 40.936487 + } + ], + "train_targets": [ + { + "file_sha256": "eb1a49660900592a0c8e265382d835a76a21aa0dd0666ba2a00e87067b347f7e", + "relative_path": "train_resized/target/1163.jpg" + }, + { + "file_sha256": "eb1a49660900592a0c8e265382d835a76a21aa0dd0666ba2a00e87067b347f7e", + "relative_path": "train_resized/target/1463.jpg" + }, + { + "file_sha256": "eb1a49660900592a0c8e265382d835a76a21aa0dd0666ba2a00e87067b347f7e", + "relative_path": "train_resized/target/1763.jpg" + }, + { + "file_sha256": "eb1a49660900592a0c8e265382d835a76a21aa0dd0666ba2a00e87067b347f7e", + "relative_path": "train_resized/target/2063.jpg" + }, + { + "file_sha256": "eb1a49660900592a0c8e265382d835a76a21aa0dd0666ba2a00e87067b347f7e", + "relative_path": "train_resized/target/2363.jpg" + }, + { + "file_sha256": "eb1a49660900592a0c8e265382d835a76a21aa0dd0666ba2a00e87067b347f7e", + "relative_path": "train_resized/target/863.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c8c9fe1208a17861e0c5e814b9f7b5017d428216316ed765c20112940958523d", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.658564, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4ea781eb0580da781e04255bf863a750b32983868f81eec1490b0156168b8813", + "test_representative_target": "test_resized/Test2800/target/944_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.426937 + } + ], + "train_targets": [ + { + "file_sha256": "6e5a1599a1c68e71268711be72ef8814999b320cc9f21a25cc693d2492e481d0", + "relative_path": "train_resized/target/349.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "c900973e38ee0ecf11727cf4ef5343b38d8bfdc0238777ba05acc5e387b8d814", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.023103, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "51db2495a2a9cf934f7e4e3434e32e9a4bdb695120d5e7526edfc6739bc6ccb8", + "test_representative_target": "test_resized/Test100/target/80.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.096192 + }, + { + "full_rgb_psnr_db": 34.023064, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "707b8304f184dff3356ed1ca2d2451e7ca517cee33193706680611cf29a98f18", + "test_representative_target": "test_resized/Test100/target/94.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.100618 + } + ], + "train_targets": [ + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12915.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12916.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12917.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12918.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12919.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12920.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12921.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12922.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12923.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12924.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12925.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12926.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12927.jpg" + }, + { + "file_sha256": "c283bbb99598633e9d48e3a2eba2d628a3a12796b7b4afeebefed20512622abe", + "relative_path": "train_resized/target/12928.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "ca0d1a12ea02e82f40f6338c0704d424bc965490f06f188750905a8a03533e0a", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 39.613423, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "28990d22875a8a33b24b54b68b06e991bc9695fb36b4c80a3d6620c368031a88", + "test_representative_target": "test_resized/Test2800/target/962_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 48.468775 + } + ], + "train_targets": [ + { + "file_sha256": "43c926f0022a3ee80fb083aa262ac258d3829d04d8a0664f1b320ded3b099b98", + "relative_path": "train_resized/target/11.jpg" + }, + { + "file_sha256": "43c926f0022a3ee80fb083aa262ac258d3829d04d8a0664f1b320ded3b099b98", + "relative_path": "train_resized/target/492.jpg" + }, + { + "file_sha256": "43c926f0022a3ee80fb083aa262ac258d3829d04d8a0664f1b320ded3b099b98", + "relative_path": "train_resized/target/5.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "cbcd3f6c0fae4f0c0828df35f47f8f8598cb0cbbad2889f24c4a78c62e026244", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.610767, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "101e5db0c3289ddb55b2d29090d7a6356af150cdb73a687f870dbb4aee316475", + "test_representative_target": "test_resized/Rain100H/target/81.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.506892 + }, + { + "full_rgb_psnr_db": 22.610767, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "101e5db0c3289ddb55b2d29090d7a6356af150cdb73a687f870dbb4aee316475", + "test_representative_target": "test_resized/Rain100L/target/81.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.506892 + } + ], + "train_targets": [ + { + "file_sha256": "b8c311cd960d6ef87884f4f306f8574cf1c60ab7444e4c1f31420c0bb690af31", + "relative_path": "train_resized/target/1182.jpg" + }, + { + "file_sha256": "b8c311cd960d6ef87884f4f306f8574cf1c60ab7444e4c1f31420c0bb690af31", + "relative_path": "train_resized/target/1482.jpg" + }, + { + "file_sha256": "b8c311cd960d6ef87884f4f306f8574cf1c60ab7444e4c1f31420c0bb690af31", + "relative_path": "train_resized/target/1782.jpg" + }, + { + "file_sha256": "b8c311cd960d6ef87884f4f306f8574cf1c60ab7444e4c1f31420c0bb690af31", + "relative_path": "train_resized/target/2082.jpg" + }, + { + "file_sha256": "b8c311cd960d6ef87884f4f306f8574cf1c60ab7444e4c1f31420c0bb690af31", + "relative_path": "train_resized/target/2382.jpg" + }, + { + "file_sha256": "b8c311cd960d6ef87884f4f306f8574cf1c60ab7444e4c1f31420c0bb690af31", + "relative_path": "train_resized/target/882.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "cbd3b1d316c90429e1a444aade811fd4c856b6551476ae0b3a02ee87c6ad9097", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.837235, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cec577f5122e0ec336459f7f9f485f36ac7ecff475371f2878329e5a138953ee", + "test_representative_target": "test_resized/Rain100H/target/88.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.035638 + }, + { + "full_rgb_psnr_db": 28.837235, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cec577f5122e0ec336459f7f9f485f36ac7ecff475371f2878329e5a138953ee", + "test_representative_target": "test_resized/Rain100L/target/88.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.035638 + } + ], + "train_targets": [ + { + "file_sha256": "667f64d76d48774979ccf48c731fc39d5ba7432df093b31bbf8c321d8630951d", + "relative_path": "train_resized/target/261.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "cc0acdc8151ead9a8799842e6c6dfa9a2cc46c7a47c60495a7c7ade32a3f6da2", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.658571, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4ea781eb0580da781e04255bf863a750b32983868f81eec1490b0156168b8813", + "test_representative_target": "test_resized/Test2800/target/944_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.426336 + } + ], + "train_targets": [ + { + "file_sha256": "96aa844654421148478c4a0be2768f57a15481e5b0130f59213da2313704b837", + "relative_path": "train_resized/target/400.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "cd3e99cfe9a7d3012b97af0ffc20c7ed27888b81f051c1ffd38e6925397aea03", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.540868, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4ae99e61cf818376fae8843b4aff4e971a67646b9115e4d236ab78ae70425306", + "test_representative_target": "test_resized/Rain100H/target/41.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 33.770218 + }, + { + "full_rgb_psnr_db": 24.540868, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "4ae99e61cf818376fae8843b4aff4e971a67646b9115e4d236ab78ae70425306", + "test_representative_target": "test_resized/Rain100L/target/41.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 33.770218 + } + ], + "train_targets": [ + { + "file_sha256": "b551b1cb6be3b2d6911f4ea8bfe92cc63a8eaa63c729b35eb7a483b0df021e47", + "relative_path": "train_resized/target/1146.jpg" + }, + { + "file_sha256": "b551b1cb6be3b2d6911f4ea8bfe92cc63a8eaa63c729b35eb7a483b0df021e47", + "relative_path": "train_resized/target/1446.jpg" + }, + { + "file_sha256": "b551b1cb6be3b2d6911f4ea8bfe92cc63a8eaa63c729b35eb7a483b0df021e47", + "relative_path": "train_resized/target/1746.jpg" + }, + { + "file_sha256": "b551b1cb6be3b2d6911f4ea8bfe92cc63a8eaa63c729b35eb7a483b0df021e47", + "relative_path": "train_resized/target/2046.jpg" + }, + { + "file_sha256": "b551b1cb6be3b2d6911f4ea8bfe92cc63a8eaa63c729b35eb7a483b0df021e47", + "relative_path": "train_resized/target/2346.jpg" + }, + { + "file_sha256": "b551b1cb6be3b2d6911f4ea8bfe92cc63a8eaa63c729b35eb7a483b0df021e47", + "relative_path": "train_resized/target/846.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "d13877aadcbb88c5a46d7ba40cbb3f8557fae1b875634990441325ba0b0fb7c4", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 21.856579, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c61c0d5db0b0b79e1bca6a5eaf9a2cfb3ce66e4dbf3511a900c6666925c352fe", + "test_representative_target": "test_resized/Test2800/target/957_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.047536 + } + ], + "train_targets": [ + { + "file_sha256": "8b84f91332fc3a1941bb6f705a43053ed463d169e672cfcb167724271ef2a906", + "relative_path": "train_resized/target/660.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "d25044248893f4c890c58916861465372e048550204083fb42ba3631d77a1e97", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 38.800709, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "bdd70511342fcabb25682146aecba3c9cddbabf867c95c93053f321537d57177", + "test_representative_target": "test_resized/Test2800/target/958_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 47.989289 + } + ], + "train_targets": [ + { + "file_sha256": "f348d303629e036851928e68bf0b2b4e8a31ba48fa039bed51fe7bef011cd3fa", + "relative_path": "train_resized/target/455.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "d295c92e43a6532f50f90c6ac5ef72aa253d799061ba0efc1ff8494a42afd3ad", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.634944, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "baa454bb988f8c807bb21c886f59e363498213e44abe4e42f4c3c54aa4cea5bc", + "test_representative_target": "test_resized/Test2800/target/875_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.534006 + } + ], + "train_targets": [ + { + "file_sha256": "9c005ed570ccd0611738b196e440308d0bc60a493a7ce114b109f5b3d2f01ca8", + "relative_path": "train_resized/target/1109.jpg" + }, + { + "file_sha256": "9c005ed570ccd0611738b196e440308d0bc60a493a7ce114b109f5b3d2f01ca8", + "relative_path": "train_resized/target/1409.jpg" + }, + { + "file_sha256": "9c005ed570ccd0611738b196e440308d0bc60a493a7ce114b109f5b3d2f01ca8", + "relative_path": "train_resized/target/1709.jpg" + }, + { + "file_sha256": "9c005ed570ccd0611738b196e440308d0bc60a493a7ce114b109f5b3d2f01ca8", + "relative_path": "train_resized/target/2009.jpg" + }, + { + "file_sha256": "9c005ed570ccd0611738b196e440308d0bc60a493a7ce114b109f5b3d2f01ca8", + "relative_path": "train_resized/target/2309.jpg" + }, + { + "file_sha256": "9c005ed570ccd0611738b196e440308d0bc60a493a7ce114b109f5b3d2f01ca8", + "relative_path": "train_resized/target/809.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "d2fa8fe22466806246aaa07677c6b074bbddc547fcd87b72d23643624096b341", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.019427, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9d5f8e518984b317bb46bc33cfdb2fb3c9d5a00b4bac046be76184ee2c773d48", + "test_representative_target": "test_resized/Rain100H/target/44.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.239749 + }, + { + "full_rgb_psnr_db": 25.019427, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9d5f8e518984b317bb46bc33cfdb2fb3c9d5a00b4bac046be76184ee2c773d48", + "test_representative_target": "test_resized/Rain100L/target/44.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 36.239749 + }, + { + "full_rgb_psnr_db": 25.2803, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "587d3b825fc8a40d7371f667b6fc9273c73a785fb13b5b39a6941b8dc4eff49d", + "test_representative_target": "test_resized/Test2800/target/919_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.156617 + } + ], + "train_targets": [ + { + "file_sha256": "cd3f6f273e08c0a0976d60aab5bae3a1ea0f6678bb3fc6a24674f16727d56603", + "relative_path": "train_resized/target/458.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "d6aa038b554d248acab26baeca2ffb7cf9a7d558c482b06dd4c0ac3b9b9664c1", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 39.613361, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "28990d22875a8a33b24b54b68b06e991bc9695fb36b4c80a3d6620c368031a88", + "test_representative_target": "test_resized/Test2800/target/962_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 48.46572 + } + ], + "train_targets": [ + { + "file_sha256": "e7707a3f675d8456753e8d4dbaf980cc279a2c8571dca60190cb6b703b75a1dc", + "relative_path": "train_resized/target/186.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "d6c9302b55b998755d1a5327dc850038ebc98cc4645fe02e269315faa441a0a6", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 37.253245, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "196b58f2a4526da4067aafe7c6e51a18a3aae74ab86c89d332e183bb167908ee", + "test_representative_target": "test_resized/Test100/target/68.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 48.160949 + } + ], + "train_targets": [ + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8225.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8226.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8227.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8228.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8229.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8230.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8231.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8232.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8233.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8234.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8235.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8236.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8237.jpg" + }, + { + "file_sha256": "4767847026ecd8326614132b51bd94558dc452a168419025aad11565b91c2d92", + "relative_path": "train_resized/target/8238.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "d839cc6e643cfd4843e88c26103a9ca0251263c5e78f1e4b2ba1bf385c734590", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.932707, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "d61670e1a58631fb0f79d9c0e165152dc608a5dfda1241a0032901de13a542ca", + "test_representative_target": "test_resized/Rain100H/target/59.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.837556 + }, + { + "full_rgb_psnr_db": 22.932707, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "d61670e1a58631fb0f79d9c0e165152dc608a5dfda1241a0032901de13a542ca", + "test_representative_target": "test_resized/Rain100L/target/59.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.837556 + } + ], + "train_targets": [ + { + "file_sha256": "14aca4613e3629bad15781a8621779adb7b26ee991161c9a55b2780d8eac8fe6", + "relative_path": "train_resized/target/1162.jpg" + }, + { + "file_sha256": "14aca4613e3629bad15781a8621779adb7b26ee991161c9a55b2780d8eac8fe6", + "relative_path": "train_resized/target/1462.jpg" + }, + { + "file_sha256": "14aca4613e3629bad15781a8621779adb7b26ee991161c9a55b2780d8eac8fe6", + "relative_path": "train_resized/target/1762.jpg" + }, + { + "file_sha256": "14aca4613e3629bad15781a8621779adb7b26ee991161c9a55b2780d8eac8fe6", + "relative_path": "train_resized/target/2062.jpg" + }, + { + "file_sha256": "14aca4613e3629bad15781a8621779adb7b26ee991161c9a55b2780d8eac8fe6", + "relative_path": "train_resized/target/2362.jpg" + }, + { + "file_sha256": "14aca4613e3629bad15781a8621779adb7b26ee991161c9a55b2780d8eac8fe6", + "relative_path": "train_resized/target/862.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "d94e06d83b50d5f14efa6c6ce63b1183a87e63b5dfc477361ad4e862bfad03ed", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.516079, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "0cd0da28ba16c97df216e9f3d5d6edd077c5a55a6bb4f69532b0fc6733b15e7f", + "test_representative_target": "test_resized/Rain100H/target/67.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.068788 + }, + { + "full_rgb_psnr_db": 23.516079, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "0cd0da28ba16c97df216e9f3d5d6edd077c5a55a6bb4f69532b0fc6733b15e7f", + "test_representative_target": "test_resized/Rain100L/target/67.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.068788 + } + ], + "train_targets": [ + { + "file_sha256": "f20503982c1f1607666da832c5743ae1a2be1599101726bab8a1ac5efb97a23f", + "relative_path": "train_resized/target/1170.jpg" + }, + { + "file_sha256": "f20503982c1f1607666da832c5743ae1a2be1599101726bab8a1ac5efb97a23f", + "relative_path": "train_resized/target/1470.jpg" + }, + { + "file_sha256": "f20503982c1f1607666da832c5743ae1a2be1599101726bab8a1ac5efb97a23f", + "relative_path": "train_resized/target/1770.jpg" + }, + { + "file_sha256": "f20503982c1f1607666da832c5743ae1a2be1599101726bab8a1ac5efb97a23f", + "relative_path": "train_resized/target/2070.jpg" + }, + { + "file_sha256": "f20503982c1f1607666da832c5743ae1a2be1599101726bab8a1ac5efb97a23f", + "relative_path": "train_resized/target/2370.jpg" + }, + { + "file_sha256": "f20503982c1f1607666da832c5743ae1a2be1599101726bab8a1ac5efb97a23f", + "relative_path": "train_resized/target/870.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "db0ec4c2cac4e3af2bbfeb12672228cc20dd81298dfc6db0a007eb0216cb62c6", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 36.933882, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "775d9cb9bade9404ec986e80a43ff988d8b56f1226a454f9ba5eef80a123d9d8", + "test_representative_target": "test_resized/Test100/target/81.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.613941 + }, + { + "full_rgb_psnr_db": 36.933785, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "9a28b0638350f20d1cec556ad26bee2970f887164f14003940f824801b9b19fb", + "test_representative_target": "test_resized/Test100/target/95.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.612686 + } + ], + "train_targets": [ + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9541.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9542.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9543.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9544.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9545.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9546.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9547.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9548.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9549.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9550.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9551.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9552.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9553.jpg" + }, + { + "file_sha256": "0734e0e8fae841d3946cf2874e13ac5e682c0ef096d924dc50116a2fe85ebf77", + "relative_path": "train_resized/target/9554.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "db2906497847ba6a10dd91ea12b108063c8d0f90cad5e34574eeb8d784832cc7", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 36.302954, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "22acefb5e570bcd274c703b4db13bd457585865750be2fb2e3502a6c8c07b26a", + "test_representative_target": "test_resized/Test100/target/93.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.147871 + } + ], + "train_targets": [ + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11935.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11936.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11937.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11938.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11939.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11940.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11941.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11942.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11943.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11944.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11945.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11946.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11947.jpg" + }, + { + "file_sha256": "439b4ed71af3bcd593692ecdff972ce82313d8d5bd991dd9e7c0bb4ca33d9339", + "relative_path": "train_resized/target/11948.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "dbc252659373a3d2264103f1c95c6a639218e1c0ac2ff0a91e4eaab2098ad0dd", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.917858, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "1b03ecf6ed4ce4f5f2fe6ea99cc8c126e69eff024de3ec2da93a9acd7cb37090", + "test_representative_target": "test_resized/Test100/target/76.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.051732 + } + ], + "train_targets": [ + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11249.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11250.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11251.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11252.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11253.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11254.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11255.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11256.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11257.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11258.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11259.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11260.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11261.jpg" + }, + { + "file_sha256": "5f4b1cbc68b9f914ee069add98771d959ada3cf805f26a5fedf201dc3f2c9c92", + "relative_path": "train_resized/target/11262.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "dbff55f6d129923b523e688876a8a6f105e2d36e9cc795d177eef501097aa292", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.355559, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "bcab48b5234ae68f89dd69925e15cbddcbefb590806dc03acfb25c3e74c83dcc", + "test_representative_target": "test_resized/Test2800/target/939_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.485578 + } + ], + "train_targets": [ + { + "file_sha256": "71111fe2624e59a70bcfb5997696bdf961c3754fe299db50dc7f25cef47833e2", + "relative_path": "train_resized/target/554.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "dd334fd4cd704b057728f7cb8630621c4773c72ca78e78af9e7f0cbee5a5776c", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.05799, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "c35eebc58ec685da71160eedd3dd607f9954a57a0bc8a4af0233b7a6852ae9c9", + "test_representative_target": "test_resized/Test2800/target/935_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.422731 + } + ], + "train_targets": [ + { + "file_sha256": "b7a9fc81209d85bc06582a20fe46e6c34c4cf5dbfe35ac8b3b18875e01b0258a", + "relative_path": "train_resized/target/538.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e0ba282382a933dee20fb8d45f47840256aa677137ab280098dae0c08ae2e8f9", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.664501, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "fc7a3cc5b06649900c45dedf13e77fbdad99a7debbc26df5d174cd1e58dbac05", + "test_representative_target": "test_resized/Rain100H/target/13.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.659008 + }, + { + "full_rgb_psnr_db": 27.664501, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "fc7a3cc5b06649900c45dedf13e77fbdad99a7debbc26df5d174cd1e58dbac05", + "test_representative_target": "test_resized/Rain100L/target/13.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.659008 + } + ], + "train_targets": [ + { + "file_sha256": "4e1d2d9def668ec833fade594982193404a6f448032bc0a46019e17637163f1d", + "relative_path": "train_resized/target/1121.jpg" + }, + { + "file_sha256": "4e1d2d9def668ec833fade594982193404a6f448032bc0a46019e17637163f1d", + "relative_path": "train_resized/target/1421.jpg" + }, + { + "file_sha256": "4e1d2d9def668ec833fade594982193404a6f448032bc0a46019e17637163f1d", + "relative_path": "train_resized/target/1721.jpg" + }, + { + "file_sha256": "4e1d2d9def668ec833fade594982193404a6f448032bc0a46019e17637163f1d", + "relative_path": "train_resized/target/2021.jpg" + }, + { + "file_sha256": "4e1d2d9def668ec833fade594982193404a6f448032bc0a46019e17637163f1d", + "relative_path": "train_resized/target/2321.jpg" + }, + { + "file_sha256": "4e1d2d9def668ec833fade594982193404a6f448032bc0a46019e17637163f1d", + "relative_path": "train_resized/target/821.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e11f424f465f304649399a9e458c3a8ea1571e5e64f19611754c480ef1813e34", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.842422, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "1ebe83ccb15f30fe6cf84f997dc3bab8e89ce7cce0c2648a29fe2a7953d403fa", + "test_representative_target": "test_resized/Test2800/target/810_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 39.192646 + } + ], + "train_targets": [ + { + "file_sha256": "291b49a56837187b1ad19bfa001e4dfb1b5ff780887ec5d4f18970c87293ce2f", + "relative_path": "train_resized/target/1060.jpg" + }, + { + "file_sha256": "291b49a56837187b1ad19bfa001e4dfb1b5ff780887ec5d4f18970c87293ce2f", + "relative_path": "train_resized/target/1360.jpg" + }, + { + "file_sha256": "291b49a56837187b1ad19bfa001e4dfb1b5ff780887ec5d4f18970c87293ce2f", + "relative_path": "train_resized/target/1660.jpg" + }, + { + "file_sha256": "291b49a56837187b1ad19bfa001e4dfb1b5ff780887ec5d4f18970c87293ce2f", + "relative_path": "train_resized/target/1960.jpg" + }, + { + "file_sha256": "291b49a56837187b1ad19bfa001e4dfb1b5ff780887ec5d4f18970c87293ce2f", + "relative_path": "train_resized/target/2260.jpg" + }, + { + "file_sha256": "291b49a56837187b1ad19bfa001e4dfb1b5ff780887ec5d4f18970c87293ce2f", + "relative_path": "train_resized/target/760.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e23de0f27c62005d54c328aea21387e76c79c32b16a6fc874a5aa13376014241", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.649198, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "1eb4d3ab73377a76b23a69ead6cb41c9eb85db379d72a7e9d2bb0d21e8f30494", + "test_representative_target": "test_resized/Test100/target/91.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.709521 + }, + { + "full_rgb_psnr_db": 32.649552, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "4d12d4a5d50fe3390a01547800d8e6a7cad9bede991afd209f1579ce255807c9", + "test_representative_target": "test_resized/Test100/target/70.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.710533 + } + ], + "train_targets": [ + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10045.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10046.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10047.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10048.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10049.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10050.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10051.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10052.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10053.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10054.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10055.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10056.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10057.jpg" + }, + { + "file_sha256": "30140bb461b03f7d57a000b2617e038e4cbc8f386fa34d9727ae44c141795deb", + "relative_path": "train_resized/target/10058.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e24b8a8f2f6db78f2570c8e4906cac6211e7b0c9bf9cd487809d6c719e1cc322", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.160874, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "0963e223c545021a8a975f42455bb12b1b0f4396c15fe65970a45cc09f415cae", + "test_representative_target": "test_resized/Rain100H/target/43.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.541496 + }, + { + "full_rgb_psnr_db": 25.160874, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "0963e223c545021a8a975f42455bb12b1b0f4396c15fe65970a45cc09f415cae", + "test_representative_target": "test_resized/Rain100L/target/43.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.541496 + }, + { + "full_rgb_psnr_db": 25.244088, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "aaf9745e95bfdd673bead92ec95a10a12a6d709c3de8f7de470f0cfa9d1e4a47", + "test_representative_target": "test_resized/Test2800/target/918_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.737051 + } + ], + "train_targets": [ + { + "file_sha256": "aadd0676fbda70e6a8d61928b9fbc24e73e7a04b3d85b8057e7defb92a397fb2", + "relative_path": "train_resized/target/1148.jpg" + }, + { + "file_sha256": "aadd0676fbda70e6a8d61928b9fbc24e73e7a04b3d85b8057e7defb92a397fb2", + "relative_path": "train_resized/target/1448.jpg" + }, + { + "file_sha256": "aadd0676fbda70e6a8d61928b9fbc24e73e7a04b3d85b8057e7defb92a397fb2", + "relative_path": "train_resized/target/1748.jpg" + }, + { + "file_sha256": "aadd0676fbda70e6a8d61928b9fbc24e73e7a04b3d85b8057e7defb92a397fb2", + "relative_path": "train_resized/target/2048.jpg" + }, + { + "file_sha256": "aadd0676fbda70e6a8d61928b9fbc24e73e7a04b3d85b8057e7defb92a397fb2", + "relative_path": "train_resized/target/2348.jpg" + }, + { + "file_sha256": "aadd0676fbda70e6a8d61928b9fbc24e73e7a04b3d85b8057e7defb92a397fb2", + "relative_path": "train_resized/target/848.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e28f2de8aa2e6b1060d294f028fa22d02b129c3b90c44909439a957cec2f8d95", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 28.258384, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "2e0a1e0146582253df57ae4884c260e4f7355b47476727eee94f0fb3ff0748d5", + "test_representative_target": "test_resized/Test2800/target/967_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.90344 + } + ], + "train_targets": [ + { + "file_sha256": "7be5ed41e2257cffc6daa3256972700c9192469f3844ca315a584ea4e5909e47", + "relative_path": "train_resized/target/1046.jpg" + }, + { + "file_sha256": "7be5ed41e2257cffc6daa3256972700c9192469f3844ca315a584ea4e5909e47", + "relative_path": "train_resized/target/1346.jpg" + }, + { + "file_sha256": "7be5ed41e2257cffc6daa3256972700c9192469f3844ca315a584ea4e5909e47", + "relative_path": "train_resized/target/1646.jpg" + }, + { + "file_sha256": "7be5ed41e2257cffc6daa3256972700c9192469f3844ca315a584ea4e5909e47", + "relative_path": "train_resized/target/1946.jpg" + }, + { + "file_sha256": "7be5ed41e2257cffc6daa3256972700c9192469f3844ca315a584ea4e5909e47", + "relative_path": "train_resized/target/2246.jpg" + }, + { + "file_sha256": "7be5ed41e2257cffc6daa3256972700c9192469f3844ca315a584ea4e5909e47", + "relative_path": "train_resized/target/746.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e352478c69e7745553d7bbae9a70c6eb3f7bb8f8b2939cdc87655c9722f8976e", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.093132, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "7c9c1ee46e1e4bb2e5896f366ba9389f997b2ea8133ccdc0033bf3d04c3e2d85", + "test_representative_target": "test_resized/Rain100H/target/56.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.075492 + }, + { + "full_rgb_psnr_db": 27.093132, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "7c9c1ee46e1e4bb2e5896f366ba9389f997b2ea8133ccdc0033bf3d04c3e2d85", + "test_representative_target": "test_resized/Rain100L/target/56.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 38.075492 + }, + { + "full_rgb_psnr_db": 27.360666, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "a6a4204ffbcd00b6fd622430cdb4d4c3b96e092748e30e5256fe5e1139268674", + "test_representative_target": "test_resized/Test2800/target/999_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 38.585748 + } + ], + "train_targets": [ + { + "file_sha256": "87cb2ba1c614d9ef8eddc1ddc8095149162885b483796b2e9474392068701f8d", + "relative_path": "train_resized/target/1160.jpg" + }, + { + "file_sha256": "87cb2ba1c614d9ef8eddc1ddc8095149162885b483796b2e9474392068701f8d", + "relative_path": "train_resized/target/1460.jpg" + }, + { + "file_sha256": "87cb2ba1c614d9ef8eddc1ddc8095149162885b483796b2e9474392068701f8d", + "relative_path": "train_resized/target/1760.jpg" + }, + { + "file_sha256": "87cb2ba1c614d9ef8eddc1ddc8095149162885b483796b2e9474392068701f8d", + "relative_path": "train_resized/target/2060.jpg" + }, + { + "file_sha256": "87cb2ba1c614d9ef8eddc1ddc8095149162885b483796b2e9474392068701f8d", + "relative_path": "train_resized/target/2360.jpg" + }, + { + "file_sha256": "87cb2ba1c614d9ef8eddc1ddc8095149162885b483796b2e9474392068701f8d", + "relative_path": "train_resized/target/860.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e79a00bec9b81643e6edf14d54e16fe226ac3dbd6b63cefe728bd0cf4cf07021", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 40.71874, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b6aa2b0f6ab5abf490e620cf29f4a36efdc104318f3b2c164c302aae2baea6da", + "test_representative_target": "test_resized/Test2800/target/948_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 49.541975 + } + ], + "train_targets": [ + { + "file_sha256": "edd135a9a7bcbddb749e7dad94dd228b6eeb9a641714ccc9fd6f3ab4344f75d3", + "relative_path": "train_resized/target/99.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e80ddb0c11f2f5e58682d2e46cbb5a233525287f8d98a669a1b0809b96705d20", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 33.060345, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "ae6f142b28f64ffc4d4b2f1f82f61d6763f90c33eff703919e79863184be1bf1", + "test_representative_target": "test_resized/Test100/target/97.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.371541 + }, + { + "full_rgb_psnr_db": 33.060609, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "d957abee90c4764c4b243437d662b29751165db496c93e9b35af2965bc1c9174", + "test_representative_target": "test_resized/Test100/target/78.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.369891 + } + ], + "train_targets": [ + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11445.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11446.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11447.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11448.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11449.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11450.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11451.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11452.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11453.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11454.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11455.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11456.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11457.jpg" + }, + { + "file_sha256": "bb2e604639a3b4aab986bd982a4a16e063b235a8ed9603203e68833056e3fe0e", + "relative_path": "train_resized/target/11458.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e8276232f4e56a244402de4572a9ebfe7d65190e264b9a948ff18f92813c2749", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.222751, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "87e5c9558d8bb9b9587a2810b7f02dab248c8701cdab87458d07742dc9db836a", + "test_representative_target": "test_resized/Rain100H/target/39.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.67943 + }, + { + "full_rgb_psnr_db": 24.222751, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "87e5c9558d8bb9b9587a2810b7f02dab248c8701cdab87458d07742dc9db836a", + "test_representative_target": "test_resized/Rain100L/target/39.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.67943 + }, + { + "full_rgb_psnr_db": 24.383895, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "1bef299f5f24b06456f81f602adfafbdc78df80a74a9e5b410c803f102e2d845", + "test_representative_target": "test_resized/Test2800/target/914_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 36.448302 + } + ], + "train_targets": [ + { + "file_sha256": "f3ca27e11f5e994e88b96ee58ba397358e927341df029ccc242f33fda14674e0", + "relative_path": "train_resized/target/1144.jpg" + }, + { + "file_sha256": "f3ca27e11f5e994e88b96ee58ba397358e927341df029ccc242f33fda14674e0", + "relative_path": "train_resized/target/1444.jpg" + }, + { + "file_sha256": "f3ca27e11f5e994e88b96ee58ba397358e927341df029ccc242f33fda14674e0", + "relative_path": "train_resized/target/1744.jpg" + }, + { + "file_sha256": "f3ca27e11f5e994e88b96ee58ba397358e927341df029ccc242f33fda14674e0", + "relative_path": "train_resized/target/2044.jpg" + }, + { + "file_sha256": "f3ca27e11f5e994e88b96ee58ba397358e927341df029ccc242f33fda14674e0", + "relative_path": "train_resized/target/2344.jpg" + }, + { + "file_sha256": "f3ca27e11f5e994e88b96ee58ba397358e927341df029ccc242f33fda14674e0", + "relative_path": "train_resized/target/844.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "e86d60828e6746f6a1bb29f36fcdddd2ac494034e7239fc958450b34bd711534", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.244888, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "aa5e1861a3b9c6f31be91684196ebab2081b3b247f30c3579e36ee23a95cf160", + "test_representative_target": "test_resized/Test100/target/6.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.526787 + } + ], + "train_targets": [ + { + "file_sha256": "dc6f927828586a5bccff0185d1f428bfda5a4b9e2d3060372b4fbffe80e9c248", + "relative_path": "train_resized/target/460.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f0e7fc07e3aa7e1ff708c0e92003fa4f5af5fd1b5d5f769d23983868c76952dd", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.395929, + "phash_hamming": 4, + "test_decoded_rgb_sha256": "ece8cb97e270d79bee6c6fee76d682ffb1adc4f8b2f8d70ab87f830acad44333", + "test_representative_target": "test_resized/Test2800/target/971_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.41937 + } + ], + "train_targets": [ + { + "file_sha256": "0c63f01b3ff192511e19e5cc7826a9eea45340d778f6f0029689d138f032450c", + "relative_path": "train_resized/target/1232.jpg" + }, + { + "file_sha256": "0c63f01b3ff192511e19e5cc7826a9eea45340d778f6f0029689d138f032450c", + "relative_path": "train_resized/target/1532.jpg" + }, + { + "file_sha256": "0c63f01b3ff192511e19e5cc7826a9eea45340d778f6f0029689d138f032450c", + "relative_path": "train_resized/target/1832.jpg" + }, + { + "file_sha256": "0c63f01b3ff192511e19e5cc7826a9eea45340d778f6f0029689d138f032450c", + "relative_path": "train_resized/target/2132.jpg" + }, + { + "file_sha256": "0c63f01b3ff192511e19e5cc7826a9eea45340d778f6f0029689d138f032450c", + "relative_path": "train_resized/target/2432.jpg" + }, + { + "file_sha256": "0c63f01b3ff192511e19e5cc7826a9eea45340d778f6f0029689d138f032450c", + "relative_path": "train_resized/target/932.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f22e9c32b619f54195777d186b09579a202603de223f8f38d52a58ff70925616", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.182601, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "f20b0382828a956e3af8bbeaa62af363e799b09f634b44f8ddadfab62806b3ce", + "test_representative_target": "test_resized/Test100/target/96.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.634084 + } + ], + "train_targets": [ + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2863.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2864.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2865.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2866.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2867.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2868.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2869.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2870.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2871.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2872.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2873.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2874.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2875.jpg" + }, + { + "file_sha256": "930cf3ede36fa8624087fcd0ddfc09223d6a42273ad0455d753ac1bf62e28362", + "relative_path": "train_resized/target/2876.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f33ddb94cce0de0f1c5d86f7d4ff92f6902113492aec00836061aec7cbe01fff", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 26.628499, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "0849efc564e943a5d559ac68fedf9d782b40bdf037a21abcf7ca0ee92f64d94f", + "test_representative_target": "test_resized/Rain100H/target/30.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.00553 + }, + { + "full_rgb_psnr_db": 26.628499, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "0849efc564e943a5d559ac68fedf9d782b40bdf037a21abcf7ca0ee92f64d94f", + "test_representative_target": "test_resized/Rain100L/target/30.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.00553 + } + ], + "train_targets": [ + { + "file_sha256": "15729cd53752981504c5270bab29a8b81566d7ea09b53379eac6dd23e26cca3e", + "relative_path": "train_resized/target/1136.jpg" + }, + { + "file_sha256": "15729cd53752981504c5270bab29a8b81566d7ea09b53379eac6dd23e26cca3e", + "relative_path": "train_resized/target/1436.jpg" + }, + { + "file_sha256": "15729cd53752981504c5270bab29a8b81566d7ea09b53379eac6dd23e26cca3e", + "relative_path": "train_resized/target/1736.jpg" + }, + { + "file_sha256": "15729cd53752981504c5270bab29a8b81566d7ea09b53379eac6dd23e26cca3e", + "relative_path": "train_resized/target/2036.jpg" + }, + { + "file_sha256": "15729cd53752981504c5270bab29a8b81566d7ea09b53379eac6dd23e26cca3e", + "relative_path": "train_resized/target/2336.jpg" + }, + { + "file_sha256": "15729cd53752981504c5270bab29a8b81566d7ea09b53379eac6dd23e26cca3e", + "relative_path": "train_resized/target/836.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f41e1ebdea005152e52cbfcb331faa5e58154f55687112252870f5d01299b714", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.362691, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "6239f02bcbf117e167f08b34653c7dc357e2a28e6247d99608b346f3dd9eed39", + "test_representative_target": "test_resized/Test100/target/51.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.821658 + }, + { + "full_rgb_psnr_db": 32.362651, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "9bc1530523f4ed94be3f75348b024e7da74ef7b2a6a11b7fb61fe6c2e3c43983", + "test_representative_target": "test_resized/Test100/target/53.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 46.823227 + } + ], + "train_targets": [ + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9135.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9136.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9137.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9138.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9139.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9140.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9141.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9142.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9143.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9144.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9145.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9146.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9147.jpg" + }, + { + "file_sha256": "c278d3c61b45e151003b02f9779f25e10aa7aa66d017047f3c7dfadd921098fb", + "relative_path": "train_resized/target/9148.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f57bdbf1c6f24d8b109b7b2ee3bf393a98cbaf19670ec45ac2461c4ad1bd1da6", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 32.860515, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "cac7ba0d1b0a4175a5579d51c3753826836c1d53a5321acc1a40f500e2cdfed1", + "test_representative_target": "test_resized/Test100/target/85.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 45.072352 + } + ], + "train_targets": [ + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9457.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9458.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9459.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9460.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9461.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9462.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9463.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9464.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9465.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9466.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9467.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9468.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9469.jpg" + }, + { + "file_sha256": "4d9708e9b82b5145cb734122c26b72bef892f6b11e1033105c8ce749281737a2", + "relative_path": "train_resized/target/9470.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f5ff02ef6c3cd1199cfd5dce60a0e17b2db3872a06f8be4ab8e3914c1081d0b3", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.995248, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "de50981c8f8b25fddce94b3776008297a9faa29ff523ef6b199eade3ae7c0c84", + "test_representative_target": "test_resized/Rain100H/target/97.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.849222 + }, + { + "full_rgb_psnr_db": 23.995248, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "de50981c8f8b25fddce94b3776008297a9faa29ff523ef6b199eade3ae7c0c84", + "test_representative_target": "test_resized/Rain100L/target/97.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 34.849222 + }, + { + "full_rgb_psnr_db": 24.171002, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "28d1b8e7f759e372fa522e159eccf1c67db03df370deb91c3ac7fe4f6ef73789", + "test_representative_target": "test_resized/Test2800/target/949_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.328023 + } + ], + "train_targets": [ + { + "file_sha256": "0e7633e4daea282fe8bebbbf145bf6dc7fd82345d10cdd3f90da086bd710f9af", + "relative_path": "train_resized/target/1197.jpg" + }, + { + "file_sha256": "0e7633e4daea282fe8bebbbf145bf6dc7fd82345d10cdd3f90da086bd710f9af", + "relative_path": "train_resized/target/1497.jpg" + }, + { + "file_sha256": "0e7633e4daea282fe8bebbbf145bf6dc7fd82345d10cdd3f90da086bd710f9af", + "relative_path": "train_resized/target/1797.jpg" + }, + { + "file_sha256": "0e7633e4daea282fe8bebbbf145bf6dc7fd82345d10cdd3f90da086bd710f9af", + "relative_path": "train_resized/target/2097.jpg" + }, + { + "file_sha256": "0e7633e4daea282fe8bebbbf145bf6dc7fd82345d10cdd3f90da086bd710f9af", + "relative_path": "train_resized/target/2397.jpg" + }, + { + "file_sha256": "0e7633e4daea282fe8bebbbf145bf6dc7fd82345d10cdd3f90da086bd710f9af", + "relative_path": "train_resized/target/897.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f603724a42f1b234964559c2f554399f409c7173ec5cf2c5383541fa351c64b3", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.614596, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "f4e959869e060541c466843fda48928f6b709d712622f7cc59d6961a15440fbe", + "test_representative_target": "test_resized/Test2800/target/849_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 39.047778 + } + ], + "train_targets": [ + { + "file_sha256": "1283526916499907e02aec80bc838959ba73800eacdf527ed76e1f21b576955a", + "relative_path": "train_resized/target/1095.jpg" + }, + { + "file_sha256": "1283526916499907e02aec80bc838959ba73800eacdf527ed76e1f21b576955a", + "relative_path": "train_resized/target/1395.jpg" + }, + { + "file_sha256": "1283526916499907e02aec80bc838959ba73800eacdf527ed76e1f21b576955a", + "relative_path": "train_resized/target/1695.jpg" + }, + { + "file_sha256": "1283526916499907e02aec80bc838959ba73800eacdf527ed76e1f21b576955a", + "relative_path": "train_resized/target/1995.jpg" + }, + { + "file_sha256": "1283526916499907e02aec80bc838959ba73800eacdf527ed76e1f21b576955a", + "relative_path": "train_resized/target/2295.jpg" + }, + { + "file_sha256": "1283526916499907e02aec80bc838959ba73800eacdf527ed76e1f21b576955a", + "relative_path": "train_resized/target/795.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f657c50a901ffc4ec26745dce8963f1639c93a7a166856bb7d7121877da8fb38", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 34.809199, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "d4211db05aa4553ce48e8369729c3d1d5fcf44b1aaea7c98809724a49b46a9f4", + "test_representative_target": "test_resized/Test100/target/3.png", + "test_split": "Test100", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 47.331223 + } + ], + "train_targets": [ + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8869.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8870.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8871.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8872.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8873.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8874.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8875.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8876.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8877.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8878.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8879.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8880.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8881.jpg" + }, + { + "file_sha256": "6e8068cac4f200d36c82b1fd31c506f99f93b18e119c201cc84a62dffc04547d", + "relative_path": "train_resized/target/8882.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f800a692c506775937767d828d9118f1f7cebd4cc4f2e433bfb910ed73cec414", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 22.169259, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "fb37f7fc91fbd31328a43b3601364d9db16b2d36b16555315dd8ca3b4e1e24f5", + "test_representative_target": "test_resized/Rain100H/target/63.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.702868 + }, + { + "full_rgb_psnr_db": 22.169259, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "fb37f7fc91fbd31328a43b3601364d9db16b2d36b16555315dd8ca3b4e1e24f5", + "test_representative_target": "test_resized/Rain100L/target/63.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.702868 + } + ], + "train_targets": [ + { + "file_sha256": "f33e29796d9db0a7acbc4b6cef2747683f87562956da957751b7660434e64967", + "relative_path": "train_resized/target/1166.jpg" + }, + { + "file_sha256": "f33e29796d9db0a7acbc4b6cef2747683f87562956da957751b7660434e64967", + "relative_path": "train_resized/target/1466.jpg" + }, + { + "file_sha256": "f33e29796d9db0a7acbc4b6cef2747683f87562956da957751b7660434e64967", + "relative_path": "train_resized/target/1766.jpg" + }, + { + "file_sha256": "f33e29796d9db0a7acbc4b6cef2747683f87562956da957751b7660434e64967", + "relative_path": "train_resized/target/2066.jpg" + }, + { + "file_sha256": "f33e29796d9db0a7acbc4b6cef2747683f87562956da957751b7660434e64967", + "relative_path": "train_resized/target/2366.jpg" + }, + { + "file_sha256": "f33e29796d9db0a7acbc4b6cef2747683f87562956da957751b7660434e64967", + "relative_path": "train_resized/target/866.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f8546b91635cb175d88b1260c788305e0b94da15a265def6b4d967f9caa4e6c2", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.886427, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "ea0c3fcd0eedbfacd5fd6f88380b6d57e79a5f8a1afbab9437400ffce5f4340a", + "test_representative_target": "test_resized/Rain100H/target/23.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.469166 + }, + { + "full_rgb_psnr_db": 27.886427, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "ea0c3fcd0eedbfacd5fd6f88380b6d57e79a5f8a1afbab9437400ffce5f4340a", + "test_representative_target": "test_resized/Rain100L/target/23.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 35.469166 + } + ], + "train_targets": [ + { + "file_sha256": "53db15c56f525e4226d10959d9bce265b8c667edc4851f7c5264445745a88937", + "relative_path": "train_resized/target/1130.jpg" + }, + { + "file_sha256": "53db15c56f525e4226d10959d9bce265b8c667edc4851f7c5264445745a88937", + "relative_path": "train_resized/target/1430.jpg" + }, + { + "file_sha256": "53db15c56f525e4226d10959d9bce265b8c667edc4851f7c5264445745a88937", + "relative_path": "train_resized/target/1730.jpg" + }, + { + "file_sha256": "53db15c56f525e4226d10959d9bce265b8c667edc4851f7c5264445745a88937", + "relative_path": "train_resized/target/2030.jpg" + }, + { + "file_sha256": "53db15c56f525e4226d10959d9bce265b8c667edc4851f7c5264445745a88937", + "relative_path": "train_resized/target/2330.jpg" + }, + { + "file_sha256": "53db15c56f525e4226d10959d9bce265b8c667edc4851f7c5264445745a88937", + "relative_path": "train_resized/target/830.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "f8feb1cfecac9e0199424e014d1b23decb6ac6822279a128caca8ee0ed5492a8", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 27.357139, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "bcab48b5234ae68f89dd69925e15cbddcbefb590806dc03acfb25c3e74c83dcc", + "test_representative_target": "test_resized/Test2800/target/939_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.485182 + } + ], + "train_targets": [ + { + "file_sha256": "652488a0121a164217a5b0391fddc089a4508b4554ca9e977b09ce07062b7af4", + "relative_path": "train_resized/target/689.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "fb3c257fe214dbd0890da8c270b93796b61e0a96606085628fe140c71aae3927", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 24.189673, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b4715a8387ac954d525fba815b022ead6d809c940dd61c614a071df6d9f5e1a3", + "test_representative_target": "test_resized/Rain100H/target/65.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 32.237274 + }, + { + "full_rgb_psnr_db": 24.189673, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "b4715a8387ac954d525fba815b022ead6d809c940dd61c614a071df6d9f5e1a3", + "test_representative_target": "test_resized/Rain100L/target/65.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 32.237274 + } + ], + "train_targets": [ + { + "file_sha256": "67a091e68c6f984a6d49c202ed2f173aedb4d08d465b6b0fc3c38400b9a9b44f", + "relative_path": "train_resized/target/1168.jpg" + }, + { + "file_sha256": "67a091e68c6f984a6d49c202ed2f173aedb4d08d465b6b0fc3c38400b9a9b44f", + "relative_path": "train_resized/target/1468.jpg" + }, + { + "file_sha256": "67a091e68c6f984a6d49c202ed2f173aedb4d08d465b6b0fc3c38400b9a9b44f", + "relative_path": "train_resized/target/1768.jpg" + }, + { + "file_sha256": "67a091e68c6f984a6d49c202ed2f173aedb4d08d465b6b0fc3c38400b9a9b44f", + "relative_path": "train_resized/target/2068.jpg" + }, + { + "file_sha256": "67a091e68c6f984a6d49c202ed2f173aedb4d08d465b6b0fc3c38400b9a9b44f", + "relative_path": "train_resized/target/2368.jpg" + }, + { + "file_sha256": "67a091e68c6f984a6d49c202ed2f173aedb4d08d465b6b0fc3c38400b9a9b44f", + "relative_path": "train_resized/target/868.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "fcd9c6d6099443088ce31f63927ced4ecdefc004b7f18e2fa7a8ca3d995c0261", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 23.629863, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "f2b2c3ec98541deaec7bcd581de361d36e0c0763e7c49e16446922e2b197618a", + "test_representative_target": "test_resized/Test2800/target/823_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 35.055711 + } + ], + "train_targets": [ + { + "file_sha256": "8e47ccae6efb28a1f3c9d327568d20fff664d4f891ab25987abff6a647d5c500", + "relative_path": "train_resized/target/1072.jpg" + }, + { + "file_sha256": "8e47ccae6efb28a1f3c9d327568d20fff664d4f891ab25987abff6a647d5c500", + "relative_path": "train_resized/target/1372.jpg" + }, + { + "file_sha256": "8e47ccae6efb28a1f3c9d327568d20fff664d4f891ab25987abff6a647d5c500", + "relative_path": "train_resized/target/1672.jpg" + }, + { + "file_sha256": "8e47ccae6efb28a1f3c9d327568d20fff664d4f891ab25987abff6a647d5c500", + "relative_path": "train_resized/target/1972.jpg" + }, + { + "file_sha256": "8e47ccae6efb28a1f3c9d327568d20fff664d4f891ab25987abff6a647d5c500", + "relative_path": "train_resized/target/2272.jpg" + }, + { + "file_sha256": "8e47ccae6efb28a1f3c9d327568d20fff664d4f891ab25987abff6a647d5c500", + "relative_path": "train_resized/target/772.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "fdc4559d82f19dd66a57988f063c374de4f0ddffbfdf9cb5ffd6d1c5d62d1a45", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 30.462668, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "595e92b38d099446b5e7cc625e36862152c58369fd91bd6c78b03511ab96d56e", + "test_representative_target": "test_resized/Rain100H/target/71.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.354747 + }, + { + "full_rgb_psnr_db": 30.462668, + "phash_hamming": 0, + "test_decoded_rgb_sha256": "595e92b38d099446b5e7cc625e36862152c58369fd91bd6c78b03511ab96d56e", + "test_representative_target": "test_resized/Rain100L/target/71.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.354747 + } + ], + "train_targets": [ + { + "file_sha256": "d6dc3215542fcbc595daf42c7f4930e99dc18d343859e88ae6730ab57bc77131", + "relative_path": "train_resized/target/1173.jpg" + }, + { + "file_sha256": "d6dc3215542fcbc595daf42c7f4930e99dc18d343859e88ae6730ab57bc77131", + "relative_path": "train_resized/target/1473.jpg" + }, + { + "file_sha256": "d6dc3215542fcbc595daf42c7f4930e99dc18d343859e88ae6730ab57bc77131", + "relative_path": "train_resized/target/1773.jpg" + }, + { + "file_sha256": "d6dc3215542fcbc595daf42c7f4930e99dc18d343859e88ae6730ab57bc77131", + "relative_path": "train_resized/target/2073.jpg" + }, + { + "file_sha256": "d6dc3215542fcbc595daf42c7f4930e99dc18d343859e88ae6730ab57bc77131", + "relative_path": "train_resized/target/2373.jpg" + }, + { + "file_sha256": "d6dc3215542fcbc595daf42c7f4930e99dc18d343859e88ae6730ab57bc77131", + "relative_path": "train_resized/target/873.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "fe8f66623e18bd0aeca539772110ba9444712f2588f44f80b737f76e38f38022", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 25.97511, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "a58d73fcfbea8ed29b59be9a6287d3867fb304bb8e66c16269ae74df74289260", + "test_representative_target": "test_resized/Rain100H/target/34.png", + "test_split": "Rain100H", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.062665 + }, + { + "full_rgb_psnr_db": 25.97511, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "a58d73fcfbea8ed29b59be9a6287d3867fb304bb8e66c16269ae74df74289260", + "test_representative_target": "test_resized/Rain100L/target/34.png", + "test_split": "Rain100L", + "test_target_group_size": 1, + "thumbnail_rgb_psnr_db": 37.062665 + }, + { + "full_rgb_psnr_db": 26.163824, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "ca958dfc45f6cdc6a95367e7c67d48d107863fbcfc40793292901d267980d503", + "test_representative_target": "test_resized/Test2800/target/913_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.455311 + } + ], + "train_targets": [ + { + "file_sha256": "71324d3b6fcd9d7c250bab893b4525fea08104424c4bf2806ee0d8383344cf65", + "relative_path": "train_resized/target/1140.jpg" + }, + { + "file_sha256": "71324d3b6fcd9d7c250bab893b4525fea08104424c4bf2806ee0d8383344cf65", + "relative_path": "train_resized/target/1440.jpg" + }, + { + "file_sha256": "71324d3b6fcd9d7c250bab893b4525fea08104424c4bf2806ee0d8383344cf65", + "relative_path": "train_resized/target/1740.jpg" + }, + { + "file_sha256": "71324d3b6fcd9d7c250bab893b4525fea08104424c4bf2806ee0d8383344cf65", + "relative_path": "train_resized/target/2040.jpg" + }, + { + "file_sha256": "71324d3b6fcd9d7c250bab893b4525fea08104424c4bf2806ee0d8383344cf65", + "relative_path": "train_resized/target/2340.jpg" + }, + { + "file_sha256": "71324d3b6fcd9d7c250bab893b4525fea08104424c4bf2806ee0d8383344cf65", + "relative_path": "train_resized/target/840.jpg" + } + ] + }, + { + "decoded_rgb_sha256": "ff33f21b8e0b4d940eca1c7ed9e7c5e6bd9e286866c5ef755aaf1121622ed8c4", + "dimensions_wh": [ + 384, + 384 + ], + "evidence": [ + { + "full_rgb_psnr_db": 19.610665, + "phash_hamming": 2, + "test_decoded_rgb_sha256": "4ca48571dba4d04e16239956f8f48e728e01af65ef3547a3fdf2599dad1fa0cd", + "test_representative_target": "test_resized/Test2800/target/874_1.jpg", + "test_split": "Test2800", + "test_target_group_size": 14, + "thumbnail_rgb_psnr_db": 37.316518 + } + ], + "train_targets": [ + { + "file_sha256": "1b5f4c37af5578d3d50df7c5034d6bf5cd560bc1915551f00f38c9cc92995270", + "relative_path": "train_resized/target/280.jpg" + } + ] + } + ], + "hash_spec": { + "decoded_rgb_sha256": "sha256(b'SCDC_RGB_V1\\0' || uint32_be(width) || uint32_be(height) || row_major_RGB_uint8_bytes)", + "file_sha256": "sha256(raw on-disk target file bytes)" + }, + "per_test": { + "Rain100H": { + "evidence_edges": 104, + "exact_decoded_target_groups": 91, + "implicated_train_decoded_rgb_sha256": [ + "07838c69abd20a5ef1581a5301f12be07357a504c1d6d2c01c9d6082ac12c189", + "0aaf8e63abc77d1cecc7ddf452a81f2dd0c0b8ee973372d7416f04ae2db5b981", + "0aec41aaf21c5b78651b27cd47ff3134930a5040042cd9a537a96323c8e44c00", + "0c323cedb980425ea8a9dcbdc38a3f0bffff04f9f0251a842f4785212df81a36", + "0ccb6ac51825d7c1739f82e90d5ec404b036ac6abe6ff79c362612928bf9f02e", + "0e9985f4770bbb46fa2bdf10d3e42d4fad66e788abde1e398bb1ed01e3cf1c04", + "1073b9e992d270492e0f4c39f5613d88e4aef4dc5ce9aeae33368556a533c043", + "1e1997cd76c75378d917511cd00a10422182a452cc42263af83e1e09764023a0", + "2c6f9c4331f6118bcedc54687701da8ee66183a3dfa4bbe30c509149d60164a9", + "318c7413575392a1dbfd40e8d9d95d20cc17cb5ce70b491cb2debe0240ef9e88", + "32f84852215a4eced1a9339b2a637224d1374f9e84c23677eb62b402c72d3e91", + "333bb6eeca848987c2768e2f12174bae219af037964a8195e3bbcb03c18fd9cd", + "341cb4d559ad6f09404b301f8b09ac43729cf721c542346e86211e11740a66fa", + "346bcf5b1c7969fa05aae47ec64912e113f41a30790102f6e96cc4ca982a39e2", + "3667eba807a3c5abcd7dcc0160878f7733e0a9f19e114992fa0fac62954f29b5", + "376e05f0fc196314bd544333968d89f36834a8c7fc264e54f20074fec2045b56", + "37c14350c3e322a5d5d5b733606c7ac897f898c1ab9f3481467cc48a53d82c0b", + "3b77a249752f95c60e93dc1d7cb6ea399c2995f156b9bdf7a3440d8803606504", + "3c452b66e9b9b3f80546f60f3fe0a80967142af1225293b5d9063a4c23b826d5", + "3d82735d93b17517046b5fac2edc27df2742485f74ddb5418c8f50697faa3c1f", + "3e43c81142ab18fc1fe441b05c1408e2209cb0248f3246e4f7c1ec277cc7cca6", + "3ece780c8dfb76a54c357bd6a4c5a91420b0058e0ce88a1f5dd6b1298b74d94d", + "405b99d258703db4dd51688d13b5feb9edd4e8728bff059685ae919bef4cee8b", + "40dace86cdf7b7258b4afbdd25288d4abf040ee2aadee4f3af191e5dc7ee6acc", + "4171bbee3fdad5ad030425ce328edfd1f5a7d6da8f9d59aca2709701724fb9d5", + "45dc11899f9ac3bea0c7e867fb7906deee64375e3fe3f1879237732507f38360", + "463415d5c1662a30b120ba10b27cee48e9569c78f36877e61402b493a1b1b5a7", + "48a1bd0dbc16a6e363f24addbc344bb0049cd9584c39edb67c05fd2f7cd50daa", + "496112b59f85d5dc58d6607fcc3a5d198132aa70cd9c2ec3d701810a3840dad1", + "4c70f80c5a2a1525555d218bb020192aeaefe4934c47d7b10f0eb9938a64ae77", + "4d12451e52290d0673717d293e439b5c6a00369a7046f81d5e5e7ae127b1c99b", + "4e695ba0bd931c795f74f3ff0599ce3ab15bbd4343479a749ab85694e1fa1ce8", + "4e8a9e50dd70dccfeffba8aa91210304da96bb4920c10f9e45b18d0a1770fa87", + "517e86ac66539ecb9188404e7b821c1b9cd7d794856e01d1fbd30ccd43df97eb", + "526cea0c11b96a8d754e96a6644e63e637fa5d06216787b5495ccad38a767cfd", + "532a4eab4544e0d9deec544d42196e26ee0b38d2a1a5f09923ec4984343dbefa", + "53d88e23e21bbb83b573b28f25e86031cc6abebe9ab89593ecb02b5a42037468", + "565778480864890d652821e7ee9319d505ab06db531dd5e06e3fa9db01dd9def", + "56f93f621c4037541ed4bf5077b92c8005dcfc57136cef8f96d448f635c591a5", + "577d0d9b60b7065ea25f9645e82fe95d47e6dd7db6f65844767d96d2f1152640", + "5a345f87d29cd29c583f292d498e78a919b74ac4cb447a634c020b10971b6cf3", + "5b7a8cee0295dc6b0dcf2e0f1b54308f1752566df332234a8faa478345867930", + "5bc537ab3940d09a8305fd4a1e62a37f5b801585258cdda9965b99a58ded5ee5", + "5ff700b2a1ebe412e6b4e8b799d3649900d5a114bb9a2e696e932589f1f82f4e", + "63b9b5187861ef172cf0d8d4aced5b2a46b6149c6fe54eceda7fa7dcd5325579", + "65e2d0f46f3e9dd88e671dfed358138830e86f973916f17252b5a3f933480501", + "68126eaf5cf23376c4872e8044e51a5706e91fa7a8ad4562d2bf96fd4feec61e", + "68f45fea30cb5b2daf772f05c2850070018942d2c523b6d269751ec70aa75ab0", + "6a12cbac2ccbc31b31fb12f4f19c2dceda5ad6be3b8ed5eee5fc69f66b9a5192", + "6a2e19337d4473f0642a97ecddc6f73b15dd3645aa6fa72359272cecccb6819f", + "6cc2c0a311d8f0295c4fd4fdb4e2e10e36b6976c957de6aa9a79a44efefadf57", + "6e6321221dee634cb08b74f6f8df5647d5c2029558db4fe0bdf0bddc20895bef", + "6ec91227e809cbb6436fada373b77c56218f445bbbb451a144d04b699452f5a7", + "6ed68d54a8fd750d050e9bf1c06a6c03d1176d5a2da360a7e345b7246358f578", + "6f845edd88a2156d45452494fd9b423771a97de3809878185d91a2bb11f0255c", + "710669d7da4bad1cc2f574167d10bfb64d179acd24e6eeaae2ce1b197969feda", + "710c4a5aeb392d5e63358a2a4c4e4fa3771494d31af34b82183e04322aeca43b", + "71163934a8ab71c123ddc364629dc3b155d2484aa357aeff5cc14c6ff31a4239", + "71a7f2f4780544764ff295fdc6120cc71fcbccdc0ef928bfc23176530ec74650", + "73262e694f27e23f9c5303e45db16483986489d1d2e2f58a66be2109c5b02d80", + "734a15e3a212b7b49e4cf2e265a8ca011ff14addf79fb7197903816a9c9f7011", + "745e598fb977bacf7fba5a6d1a98eb40a87d0fb4b30f119a19310b4592a92b06", + "794b15e303328d71e5d977dcbad8b677ce9598291e089d046be69fdf7f19f120", + "7a375bf0ef4f56b859889066ed49bfaac7154f58a98c1bea12ecde499c1ff3d6", + "7a5c28dbd95778dc8270a4bd74e9549039eff3d6c7fe4d1894cc617228abc2b5", + "7b804f403b0dd0a282fc964e90197f5308ddb85eaede802b765e2e3bf4be0938", + "7d2099252a1c100541d544051dccf7f9413ddd13ee6600b17b26378ab8b80b2e", + "85a9cc5f774e73d3b8495c7a19768d1abd9e8514a5b34cda02abf76aa614313b", + "86ba223ebf3f0c57aa96acc54873aac058889432b68580cf102a6d9226d70df6", + "8a2b37f56b8ea6943c6e8422165981a7516452c7bf10e2aadd9f3ede581e883f", + "8cb1e1bf619a59294b5fe10e5d7d73808cda41a0778c9200e3f8f4c6dc6331b9", + "8cbc7298875336a2d3c84103b9931d4785b425f755ce4a39c593397c7a419626", + "8d79b563fad82417da37cccc36960f3cb00d1c97ac9c992cefc8aee573a6fc23", + "8dcfdff1f1438c317f95c604aad98559518ff6b32cd70d6f460bb1f59b1d1fcd", + "8ea2cedb98d141150b70e0f4423ec0df167740447ecb2645adb8024165c7b444", + "9020ec0656398fb0fd4a642d8135eba86b5cdbad64c556f0698f106d94f8594f", + "921be506364f2b4b5db49f96d8d28e5a77c56c3ca902e1f86f1fe7352bf9f026", + "a10c0963858ab3ee502e15ce028d343be579217621cb8b74188b5c39d01fa825", + "a2c8f50a0caecac25bff7de5df2fbc53d10ed2290fdd1d2c1604ad85575ae16c", + "a515b07e6902cdf063b9235b26eae1b55e89509ccd2b14e29ee9fb36e3bdbd09", + "ab9157109b00d26110832c3b3237fef9f442546b9e1c34dd590e9fc23a0b014b", + "ba073e0c4d4d8676204727dafd6e9d127c07aaf0aa2ccbb3400c217493c6bc60", + "bad0f7ce444be66b72dfc1c259e4afcf7ee2d286998754be74440638b10a7c42", + "c18ab6e90f961fcdc7ebaa6d6ef64ce6b93ba99fed04c45d52e29f15870d94c0", + "c2b4ec0cd6cfb12676202013a5ca347fcef791548c290c2de1b9af796375e714", + "c460da2338a7483576021ce80564a926da0e42913006e2a3b0ee7c48a327ede6", + "c88b5fa546daa732e1b1c70aeb841e813a498021eef1eb62c8292b2a4c067c3a", + "cbcd3f6c0fae4f0c0828df35f47f8f8598cb0cbbad2889f24c4a78c62e026244", + "cbd3b1d316c90429e1a444aade811fd4c856b6551476ae0b3a02ee87c6ad9097", + "cd3e99cfe9a7d3012b97af0ffc20c7ed27888b81f051c1ffd38e6925397aea03", + "d2fa8fe22466806246aaa07677c6b074bbddc547fcd87b72d23643624096b341", + "d839cc6e643cfd4843e88c26103a9ca0251263c5e78f1e4b2ba1bf385c734590", + "d94e06d83b50d5f14efa6c6ce63b1183a87e63b5dfc477361ad4e862bfad03ed", + "e0ba282382a933dee20fb8d45f47840256aa677137ab280098dae0c08ae2e8f9", + "e24b8a8f2f6db78f2570c8e4906cac6211e7b0c9bf9cd487809d6c719e1cc322", + "e352478c69e7745553d7bbae9a70c6eb3f7bb8f8b2939cdc87655c9722f8976e", + "e8276232f4e56a244402de4572a9ebfe7d65190e264b9a948ff18f92813c2749", + "f33ddb94cce0de0f1c5d86f7d4ff92f6902113492aec00836061aec7cbe01fff", + "f5ff02ef6c3cd1199cfd5dce60a0e17b2db3872a06f8be4ab8e3914c1081d0b3", + "f800a692c506775937767d828d9118f1f7cebd4cc4f2e433bfb910ed73cec414", + "f8546b91635cb175d88b1260c788305e0b94da15a265def6b4d967f9caa4e6c2", + "fb3c257fe214dbd0890da8c270b93796b61e0a96606085628fe140c71aae3927", + "fdc4559d82f19dd66a57988f063c374de4f0ddffbfdf9cb5ffd6d1c5d62d1a45", + "fe8f66623e18bd0aeca539772110ba9444712f2588f44f80b737f76e38f38022" + ], + "implicated_train_pair_instances": 559, + "implicated_train_target_groups": 104, + "matched_test_pair_instances": 100, + "matched_test_target_groups": 91, + "test_pair_count": 100 + }, + "Rain100L": { + "evidence_edges": 104, + "exact_decoded_target_groups": 91, + "implicated_train_decoded_rgb_sha256": [ + "07838c69abd20a5ef1581a5301f12be07357a504c1d6d2c01c9d6082ac12c189", + "0aaf8e63abc77d1cecc7ddf452a81f2dd0c0b8ee973372d7416f04ae2db5b981", + "0aec41aaf21c5b78651b27cd47ff3134930a5040042cd9a537a96323c8e44c00", + "0c323cedb980425ea8a9dcbdc38a3f0bffff04f9f0251a842f4785212df81a36", + "0ccb6ac51825d7c1739f82e90d5ec404b036ac6abe6ff79c362612928bf9f02e", + "0e9985f4770bbb46fa2bdf10d3e42d4fad66e788abde1e398bb1ed01e3cf1c04", + "1073b9e992d270492e0f4c39f5613d88e4aef4dc5ce9aeae33368556a533c043", + "1e1997cd76c75378d917511cd00a10422182a452cc42263af83e1e09764023a0", + "2c6f9c4331f6118bcedc54687701da8ee66183a3dfa4bbe30c509149d60164a9", + "318c7413575392a1dbfd40e8d9d95d20cc17cb5ce70b491cb2debe0240ef9e88", + "32f84852215a4eced1a9339b2a637224d1374f9e84c23677eb62b402c72d3e91", + "333bb6eeca848987c2768e2f12174bae219af037964a8195e3bbcb03c18fd9cd", + "341cb4d559ad6f09404b301f8b09ac43729cf721c542346e86211e11740a66fa", + "346bcf5b1c7969fa05aae47ec64912e113f41a30790102f6e96cc4ca982a39e2", + "3667eba807a3c5abcd7dcc0160878f7733e0a9f19e114992fa0fac62954f29b5", + "376e05f0fc196314bd544333968d89f36834a8c7fc264e54f20074fec2045b56", + "37c14350c3e322a5d5d5b733606c7ac897f898c1ab9f3481467cc48a53d82c0b", + "3b77a249752f95c60e93dc1d7cb6ea399c2995f156b9bdf7a3440d8803606504", + "3c452b66e9b9b3f80546f60f3fe0a80967142af1225293b5d9063a4c23b826d5", + "3d82735d93b17517046b5fac2edc27df2742485f74ddb5418c8f50697faa3c1f", + "3e43c81142ab18fc1fe441b05c1408e2209cb0248f3246e4f7c1ec277cc7cca6", + "3ece780c8dfb76a54c357bd6a4c5a91420b0058e0ce88a1f5dd6b1298b74d94d", + "405b99d258703db4dd51688d13b5feb9edd4e8728bff059685ae919bef4cee8b", + "40dace86cdf7b7258b4afbdd25288d4abf040ee2aadee4f3af191e5dc7ee6acc", + "4171bbee3fdad5ad030425ce328edfd1f5a7d6da8f9d59aca2709701724fb9d5", + "45dc11899f9ac3bea0c7e867fb7906deee64375e3fe3f1879237732507f38360", + "463415d5c1662a30b120ba10b27cee48e9569c78f36877e61402b493a1b1b5a7", + "48a1bd0dbc16a6e363f24addbc344bb0049cd9584c39edb67c05fd2f7cd50daa", + "496112b59f85d5dc58d6607fcc3a5d198132aa70cd9c2ec3d701810a3840dad1", + "4c70f80c5a2a1525555d218bb020192aeaefe4934c47d7b10f0eb9938a64ae77", + "4d12451e52290d0673717d293e439b5c6a00369a7046f81d5e5e7ae127b1c99b", + "4e695ba0bd931c795f74f3ff0599ce3ab15bbd4343479a749ab85694e1fa1ce8", + "4e8a9e50dd70dccfeffba8aa91210304da96bb4920c10f9e45b18d0a1770fa87", + "517e86ac66539ecb9188404e7b821c1b9cd7d794856e01d1fbd30ccd43df97eb", + "526cea0c11b96a8d754e96a6644e63e637fa5d06216787b5495ccad38a767cfd", + "532a4eab4544e0d9deec544d42196e26ee0b38d2a1a5f09923ec4984343dbefa", + "53d88e23e21bbb83b573b28f25e86031cc6abebe9ab89593ecb02b5a42037468", + "565778480864890d652821e7ee9319d505ab06db531dd5e06e3fa9db01dd9def", + "56f93f621c4037541ed4bf5077b92c8005dcfc57136cef8f96d448f635c591a5", + "577d0d9b60b7065ea25f9645e82fe95d47e6dd7db6f65844767d96d2f1152640", + "5a345f87d29cd29c583f292d498e78a919b74ac4cb447a634c020b10971b6cf3", + "5b7a8cee0295dc6b0dcf2e0f1b54308f1752566df332234a8faa478345867930", + "5bc537ab3940d09a8305fd4a1e62a37f5b801585258cdda9965b99a58ded5ee5", + "5ff700b2a1ebe412e6b4e8b799d3649900d5a114bb9a2e696e932589f1f82f4e", + "63b9b5187861ef172cf0d8d4aced5b2a46b6149c6fe54eceda7fa7dcd5325579", + "65e2d0f46f3e9dd88e671dfed358138830e86f973916f17252b5a3f933480501", + "68126eaf5cf23376c4872e8044e51a5706e91fa7a8ad4562d2bf96fd4feec61e", + "68f45fea30cb5b2daf772f05c2850070018942d2c523b6d269751ec70aa75ab0", + "6a12cbac2ccbc31b31fb12f4f19c2dceda5ad6be3b8ed5eee5fc69f66b9a5192", + "6a2e19337d4473f0642a97ecddc6f73b15dd3645aa6fa72359272cecccb6819f", + "6cc2c0a311d8f0295c4fd4fdb4e2e10e36b6976c957de6aa9a79a44efefadf57", + "6e6321221dee634cb08b74f6f8df5647d5c2029558db4fe0bdf0bddc20895bef", + "6ec91227e809cbb6436fada373b77c56218f445bbbb451a144d04b699452f5a7", + "6ed68d54a8fd750d050e9bf1c06a6c03d1176d5a2da360a7e345b7246358f578", + "6f845edd88a2156d45452494fd9b423771a97de3809878185d91a2bb11f0255c", + "710669d7da4bad1cc2f574167d10bfb64d179acd24e6eeaae2ce1b197969feda", + "710c4a5aeb392d5e63358a2a4c4e4fa3771494d31af34b82183e04322aeca43b", + "71163934a8ab71c123ddc364629dc3b155d2484aa357aeff5cc14c6ff31a4239", + "71a7f2f4780544764ff295fdc6120cc71fcbccdc0ef928bfc23176530ec74650", + "73262e694f27e23f9c5303e45db16483986489d1d2e2f58a66be2109c5b02d80", + "734a15e3a212b7b49e4cf2e265a8ca011ff14addf79fb7197903816a9c9f7011", + "745e598fb977bacf7fba5a6d1a98eb40a87d0fb4b30f119a19310b4592a92b06", + "794b15e303328d71e5d977dcbad8b677ce9598291e089d046be69fdf7f19f120", + "7a375bf0ef4f56b859889066ed49bfaac7154f58a98c1bea12ecde499c1ff3d6", + "7a5c28dbd95778dc8270a4bd74e9549039eff3d6c7fe4d1894cc617228abc2b5", + "7b804f403b0dd0a282fc964e90197f5308ddb85eaede802b765e2e3bf4be0938", + "7d2099252a1c100541d544051dccf7f9413ddd13ee6600b17b26378ab8b80b2e", + "85a9cc5f774e73d3b8495c7a19768d1abd9e8514a5b34cda02abf76aa614313b", + "86ba223ebf3f0c57aa96acc54873aac058889432b68580cf102a6d9226d70df6", + "8a2b37f56b8ea6943c6e8422165981a7516452c7bf10e2aadd9f3ede581e883f", + "8cb1e1bf619a59294b5fe10e5d7d73808cda41a0778c9200e3f8f4c6dc6331b9", + "8cbc7298875336a2d3c84103b9931d4785b425f755ce4a39c593397c7a419626", + "8d79b563fad82417da37cccc36960f3cb00d1c97ac9c992cefc8aee573a6fc23", + "8dcfdff1f1438c317f95c604aad98559518ff6b32cd70d6f460bb1f59b1d1fcd", + "8ea2cedb98d141150b70e0f4423ec0df167740447ecb2645adb8024165c7b444", + "9020ec0656398fb0fd4a642d8135eba86b5cdbad64c556f0698f106d94f8594f", + "921be506364f2b4b5db49f96d8d28e5a77c56c3ca902e1f86f1fe7352bf9f026", + "a10c0963858ab3ee502e15ce028d343be579217621cb8b74188b5c39d01fa825", + "a2c8f50a0caecac25bff7de5df2fbc53d10ed2290fdd1d2c1604ad85575ae16c", + "a515b07e6902cdf063b9235b26eae1b55e89509ccd2b14e29ee9fb36e3bdbd09", + "ab9157109b00d26110832c3b3237fef9f442546b9e1c34dd590e9fc23a0b014b", + "ba073e0c4d4d8676204727dafd6e9d127c07aaf0aa2ccbb3400c217493c6bc60", + "bad0f7ce444be66b72dfc1c259e4afcf7ee2d286998754be74440638b10a7c42", + "c18ab6e90f961fcdc7ebaa6d6ef64ce6b93ba99fed04c45d52e29f15870d94c0", + "c2b4ec0cd6cfb12676202013a5ca347fcef791548c290c2de1b9af796375e714", + "c460da2338a7483576021ce80564a926da0e42913006e2a3b0ee7c48a327ede6", + "c88b5fa546daa732e1b1c70aeb841e813a498021eef1eb62c8292b2a4c067c3a", + "cbcd3f6c0fae4f0c0828df35f47f8f8598cb0cbbad2889f24c4a78c62e026244", + "cbd3b1d316c90429e1a444aade811fd4c856b6551476ae0b3a02ee87c6ad9097", + "cd3e99cfe9a7d3012b97af0ffc20c7ed27888b81f051c1ffd38e6925397aea03", + "d2fa8fe22466806246aaa07677c6b074bbddc547fcd87b72d23643624096b341", + "d839cc6e643cfd4843e88c26103a9ca0251263c5e78f1e4b2ba1bf385c734590", + "d94e06d83b50d5f14efa6c6ce63b1183a87e63b5dfc477361ad4e862bfad03ed", + "e0ba282382a933dee20fb8d45f47840256aa677137ab280098dae0c08ae2e8f9", + "e24b8a8f2f6db78f2570c8e4906cac6211e7b0c9bf9cd487809d6c719e1cc322", + "e352478c69e7745553d7bbae9a70c6eb3f7bb8f8b2939cdc87655c9722f8976e", + "e8276232f4e56a244402de4572a9ebfe7d65190e264b9a948ff18f92813c2749", + "f33ddb94cce0de0f1c5d86f7d4ff92f6902113492aec00836061aec7cbe01fff", + "f5ff02ef6c3cd1199cfd5dce60a0e17b2db3872a06f8be4ab8e3914c1081d0b3", + "f800a692c506775937767d828d9118f1f7cebd4cc4f2e433bfb910ed73cec414", + "f8546b91635cb175d88b1260c788305e0b94da15a265def6b4d967f9caa4e6c2", + "fb3c257fe214dbd0890da8c270b93796b61e0a96606085628fe140c71aae3927", + "fdc4559d82f19dd66a57988f063c374de4f0ddffbfdf9cb5ffd6d1c5d62d1a45", + "fe8f66623e18bd0aeca539772110ba9444712f2588f44f80b737f76e38f38022" + ], + "implicated_train_pair_instances": 559, + "implicated_train_target_groups": 104, + "matched_test_pair_instances": 100, + "matched_test_target_groups": 91, + "test_pair_count": 100 + }, + "Test100": { + "evidence_edges": 43, + "exact_decoded_target_groups": 95, + "implicated_train_decoded_rgb_sha256": [ + "18c7a39d7d6caaf57b76e90df5d71ac872902bacbe13d95c1554995ca16e3fcf", + "25612d1e25409eac342a86d50bf0b74dbf9b0b1fc45da7f1d1d65989fd4cf4d4", + "2ee2c30ed1e9a9a6937c883e267e463784e9d9aec4a840b60ec7b7a2d4fa1162", + "30790f93fa3e17347bc64889b43be7e7c5384098c445acf221878ff8569e4b19", + "3b032345f88359d5ab1b8c8c413a8ddbafb0e713fa7d0c22a6827de580edb4b5", + "3c37317a5521bd84f5cc98ce25b832397dd46bc32a5d63b31b14eb118fa0ab2b", + "5b7a8cee0295dc6b0dcf2e0f1b54308f1752566df332234a8faa478345867930", + "63410d2c4de1193754ff189e4a24473af2f6eedc6697ac5f622cd63d2988622e", + "64a47a7f895ec3ba116e0de0106be368a7ae4dd0ee528ac4046c397b5d73b72b", + "7714332e9f133eb49e27e9e4e0ee32949acfd1b060162fce7f0dcd4ac134011d", + "8939038218575a64a32802873c9170d6603f52394b935abd8bcba7f41e916022", + "95e735eb18e651abb56004ec3dd8a9e35fb854cf02dc85c491623bbdb12bc62a", + "96d77c7c588e8c460f7dab22c8450c10246dd7cc59cc9fc4f312fe585f4ed3db", + "a66626f771730d4996346adebb9d9368ed24f019022dfd9216d64162a9658a7f", + "a793231c13b21d8a4a1f2d3516b2f5a773fcff67a5419d990d974e77fcb92582", + "aa55a6a67174309c07d495608e5c8c39763043c60545162320c6bfe99eb0febc", + "af6993b0c7bf6adecb8dfc255ccbe1abc6759369f3ad568770972a2444996dd0", + "b4601634a78f1c21838d3a4e9ed1cd1812751cf1c420d6efc11ce68c6625b65d", + "ba40e4011b070125a6c5096467578d51cb98176fd45d59e0566d82d93a3aed81", + "c599f3bbe5d721b730f19fffc276345f782f57474725ba7e6feccdd8389f8193", + "c900973e38ee0ecf11727cf4ef5343b38d8bfdc0238777ba05acc5e387b8d814", + "d6c9302b55b998755d1a5327dc850038ebc98cc4645fe02e269315faa441a0a6", + "db0ec4c2cac4e3af2bbfeb12672228cc20dd81298dfc6db0a007eb0216cb62c6", + "db2906497847ba6a10dd91ea12b108063c8d0f90cad5e34574eeb8d784832cc7", + "dbc252659373a3d2264103f1c95c6a639218e1c0ac2ff0a91e4eaab2098ad0dd", + "e23de0f27c62005d54c328aea21387e76c79c32b16a6fc874a5aa13376014241", + "e80ddb0c11f2f5e58682d2e46cbb5a233525287f8d98a669a1b0809b96705d20", + "e86d60828e6746f6a1bb29f36fcdddd2ac494034e7239fc958450b34bd711534", + "f22e9c32b619f54195777d186b09579a202603de223f8f38d52a58ff70925616", + "f41e1ebdea005152e52cbfcb331faa5e58154f55687112252870f5d01299b714", + "f57bdbf1c6f24d8b109b7b2ee3bf393a98cbaf19670ec45ac2461c4ad1bd1da6", + "f657c50a901ffc4ec26745dce8963f1639c93a7a166856bb7d7121877da8fb38" + ], + "implicated_train_pair_instances": 427, + "implicated_train_target_groups": 32, + "matched_test_pair_instances": 43, + "matched_test_target_groups": 42, + "test_pair_count": 98 + }, + "Test1200": { + "evidence_edges": 0, + "exact_decoded_target_groups": 1164, + "implicated_train_decoded_rgb_sha256": [], + "implicated_train_pair_instances": 0, + "implicated_train_target_groups": 0, + "matched_test_pair_instances": 0, + "matched_test_target_groups": 0, + "test_pair_count": 1200 + }, + "Test2800": { + "evidence_edges": 92, + "exact_decoded_target_groups": 200, + "implicated_train_decoded_rgb_sha256": [ + "003457ab19cb2f5e4b1a09e077b4e02e7a2e304bafb6a42b59ce2bf7068044df", + "0305eece704b610b8476408083eb7cd1153dfa8a40f38d3e931323ec6fcf339d", + "03a0aa4dbf590110f7f3e0a14c703d46239724620918253236ffbd17d838ccda", + "0af4f47fc902cef6d07403a068328674f4195c561cb3b1041ec5153bfc0834d8", + "0ccb6ac51825d7c1739f82e90d5ec404b036ac6abe6ff79c362612928bf9f02e", + "0d35c0155cfe5f21701945818cbe00e753a0d46d28b1f0e56155e8ce559bba92", + "0dae21329475fc227ff9a2c7212647b13090e29845b0a440ce230b3385149271", + "15ad221b4cf20f69755e044396b3baa1ea20e1fee8f1d1cedbd030610d8a3f77", + "17ef1df8e90e8415089951861366157727eb7f822f795a363812d88678052295", + "1b2a917c280aacadd3720f735ea8e845592a23f5010bf3a23cde158e7bc071ac", + "1fdd342b8565cc58a182c01caa5dd4fd819d59c4d24b0547497faa6a2eb73267", + "22603004c070027b4cc955242580c6a21921d760d98832581949765af6a1dce1", + "25d5c65da44f77285889b427e7799d5c8bb160f8d0e1018a160d5b1a7d08bb0b", + "25e38a0a1b8fa07eec3471758bf5530f34d54a482ce517848f41e364c8b351d7", + "2dfec85a17673465840900b087a3fd8e1d69216e0d68e4e4ba1829eb1a996787", + "2f141479fe6f5d44aa3bf00406f3df86411baec50846a595e072f840fa56235c", + "341cb4d559ad6f09404b301f8b09ac43729cf721c542346e86211e11740a66fa", + "3667eba807a3c5abcd7dcc0160878f7733e0a9f19e114992fa0fac62954f29b5", + "372f0807e25fa17d7fc83aeaebf51aba91b8992c47ce51a35e411169c0a5cf42", + "3d82735d93b17517046b5fac2edc27df2742485f74ddb5418c8f50697faa3c1f", + "3e43c81142ab18fc1fe441b05c1408e2209cb0248f3246e4f7c1ec277cc7cca6", + "405b99d258703db4dd51688d13b5feb9edd4e8728bff059685ae919bef4cee8b", + "40b488c6131b513ec040e9b5792bed44427a36498c51fe1f2392520478a0d0df", + "45dc11899f9ac3bea0c7e867fb7906deee64375e3fe3f1879237732507f38360", + "48895bf53c760f3a192614414e7a13307e3af0a1f0004af8de633383c66e0091", + "4c70f80c5a2a1525555d218bb020192aeaefe4934c47d7b10f0eb9938a64ae77", + "4d12451e52290d0673717d293e439b5c6a00369a7046f81d5e5e7ae127b1c99b", + "4e54d9fe4f965238333d7e4d7fec31a6c69e9c58629504834a9fe96252bd6a4d", + "4fd06a8c93b9a69506aa9b914c028a0afb486e8932557cfd9df9ebaa05dee589", + "50773bf870cf0da3030759e7e78338d635471ddcaccac27ba41afcccf93bcc67", + "517e86ac66539ecb9188404e7b821c1b9cd7d794856e01d1fbd30ccd43df97eb", + "51837014f51d22a9a3d28995a3a0e8dd67cb542b934df91b087a2fa7e74b5ea0", + "526cea0c11b96a8d754e96a6644e63e637fa5d06216787b5495ccad38a767cfd", + "532a4eab4544e0d9deec544d42196e26ee0b38d2a1a5f09923ec4984343dbefa", + "55573ade661e64b0c721c643ab3dd99db87866fb8548a54ca0fc5547130bd8c4", + "56ef4ca18c32826460b977f6fb3faec16994a0fa873d61eb465da5e65663e583", + "577d0d9b60b7065ea25f9645e82fe95d47e6dd7db6f65844767d96d2f1152640", + "5db1e0fdacaf44e96f16ffa96997a9043d1cae782014a97de1a690b290d67df3", + "6207f4b1b183cc94a75ad77ac089c435cf3afa3c77fa84377ab37af63173afcb", + "6a13f194a7660c2a2d86a785fabb5e7ae732f9f2cc2e58368fbceccdf6ec18d1", + "6d5e41776276eb007bef45d02b7d89fa18996c179d998549f4ff6601147e113c", + "6e2c9b9930de96e2f84919a23341eff3503f13c7a430ce7d105846d5040c7cdb", + "6f845edd88a2156d45452494fd9b423771a97de3809878185d91a2bb11f0255c", + "74bc719955f146b3b689487d521da2b727920fda2e65d3ec129c9589c0447daf", + "75d496bfd008c9aced6c9fc3b3449bbc6652885e086fe44a2b9a3fc850fde86e", + "794b15e303328d71e5d977dcbad8b677ce9598291e089d046be69fdf7f19f120", + "7b804f403b0dd0a282fc964e90197f5308ddb85eaede802b765e2e3bf4be0938", + "7bff6d320df20c02f62c5fda37077b0ef5310d86da01982729f1571a4f02ee58", + "7f39d22dce4ab749b8efb809af262dcc1c24572ee80a94257fb1b0bb878aafdd", + "7f3c9e3e87bf19ab16fb11ffc6e873a2f6782718ee79f4a6a0365f6289a79522", + "82d6a81b1e6b77c70cd97a52a7ab224ed5cc5fcacb92e035021f1f9d4ed08515", + "8a2b37f56b8ea6943c6e8422165981a7516452c7bf10e2aadd9f3ede581e883f", + "8b5e08d636bd16fe2ebe8054881e68f63706ac5b7a3464ef90be30d39b4a905b", + "8cb1e1bf619a59294b5fe10e5d7d73808cda41a0778c9200e3f8f4c6dc6331b9", + "921be506364f2b4b5db49f96d8d28e5a77c56c3ca902e1f86f1fe7352bf9f026", + "9675ad2114d05127d6e1aeec69509b62027f3ff28a6ff55ce55e441a0b40f67a", + "9c900bd2af82e78aa576dfeb018a95a121a264d9f46704577dfc49311f622dac", + "9fd423f76baf0d957632a6513b3bd6ae33cc6b7322c67f9e6cc89dd6d338b24e", + "a5085d4fe2513eefa1b224e85e5f5e0c837d7da70d6f2acd8d48cc6e3cc93fc2", + "a5313808f592f93ac1878cec8d7e4b3c86664c2f53a2045a275ae32518c2de1e", + "a5b4021302824d0c2c603e7e861576f16fc30b712dd9efb54017190949108cf2", + "a61d33256980596a7144a3e1268b5aeb1b5f6f00e6e82abf65304b0ab322f835", + "a62fbb6c5cf27a168b05e6317661238bf37d314d792f0afe9021724e12359adf", + "ab9157109b00d26110832c3b3237fef9f442546b9e1c34dd590e9fc23a0b014b", + "b3e609a8e6375b53748db04d6ff341259b0ac90a3fc55fd00581590d39eb2a3b", + "bd86c7db8489178b71b2d0c1ae5aaf2cafa06b0ac5febd38aa13c300950bcba3", + "c00d558315e3ac12469e94b9ef8b68fc318914dde065aac087d4b07701fb4010", + "c0f71a9e24059a6973cacb1142be50260cca566ee990587bafb78dd79cadcffa", + "c5ea44d50d056b9eb3b2e6c33882be88636b94f6a3244564b5abb1c84babd3a4", + "c8c9fe1208a17861e0c5e814b9f7b5017d428216316ed765c20112940958523d", + "ca0d1a12ea02e82f40f6338c0704d424bc965490f06f188750905a8a03533e0a", + "cc0acdc8151ead9a8799842e6c6dfa9a2cc46c7a47c60495a7c7ade32a3f6da2", + "d13877aadcbb88c5a46d7ba40cbb3f8557fae1b875634990441325ba0b0fb7c4", + "d25044248893f4c890c58916861465372e048550204083fb42ba3631d77a1e97", + "d295c92e43a6532f50f90c6ac5ef72aa253d799061ba0efc1ff8494a42afd3ad", + "d2fa8fe22466806246aaa07677c6b074bbddc547fcd87b72d23643624096b341", + "d6aa038b554d248acab26baeca2ffb7cf9a7d558c482b06dd4c0ac3b9b9664c1", + "dbff55f6d129923b523e688876a8a6f105e2d36e9cc795d177eef501097aa292", + "dd334fd4cd704b057728f7cb8630621c4773c72ca78e78af9e7f0cbee5a5776c", + "e11f424f465f304649399a9e458c3a8ea1571e5e64f19611754c480ef1813e34", + "e24b8a8f2f6db78f2570c8e4906cac6211e7b0c9bf9cd487809d6c719e1cc322", + "e28f2de8aa2e6b1060d294f028fa22d02b129c3b90c44909439a957cec2f8d95", + "e352478c69e7745553d7bbae9a70c6eb3f7bb8f8b2939cdc87655c9722f8976e", + "e79a00bec9b81643e6edf14d54e16fe226ac3dbd6b63cefe728bd0cf4cf07021", + "e8276232f4e56a244402de4572a9ebfe7d65190e264b9a948ff18f92813c2749", + "f0e7fc07e3aa7e1ff708c0e92003fa4f5af5fd1b5d5f769d23983868c76952dd", + "f5ff02ef6c3cd1199cfd5dce60a0e17b2db3872a06f8be4ab8e3914c1081d0b3", + "f603724a42f1b234964559c2f554399f409c7173ec5cf2c5383541fa351c64b3", + "f8feb1cfecac9e0199424e014d1b23decb6ac6822279a128caca8ee0ed5492a8", + "fcd9c6d6099443088ce31f63927ced4ecdefc004b7f18e2fa7a8ca3d995c0261", + "fe8f66623e18bd0aeca539772110ba9444712f2588f44f80b737f76e38f38022", + "ff33f21b8e0b4d940eca1c7ed9e7c5e6bd9e286866c5ef755aaf1121622ed8c4" + ], + "implicated_train_pair_instances": 301, + "implicated_train_target_groups": 92, + "matched_test_pair_instances": 952, + "matched_test_target_groups": 68, + "test_pair_count": 2800 + } + }, + "quarantine_rule": { + "full_rgb_psnr_db_role": "evidence only; not a quarantine gate", + "implementation_versions": { + "Pillow": "11.3.0", + "numpy": "1.21.5", + "opencv": "4.7.0", + "python": "3.9.12" + }, + "phash_hamming_max_inclusive": 4, + "phash_spec": "PIL LANCZOS resize grayscale to 32x32; OpenCV float32 DCT; top-left 8x8; threshold all 64 coefficients by median of coefficients 1..63; pack comparison bits little-index order", + "purpose": "conservative source-level near-duplicate exclusion; exact decoded hashes alone miss re-encoded copies", + "thumbnail_rgb_psnr_min_db_inclusive": 30.0, + "thumbnail_spec": "PIL LANCZOS resize decoded RGB to 64x64; float32 RGB PSNR over all pixels/channels" + }, + "schema_version": 1, + "summary": { + "affected_train_pairs": 1155, + "evidence_edges": 343, + "excluded_train_target_groups": 201, + "unique_excluded_train_file_sha256": 201 + } +} diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/data/rain13k_resized.py b/dataset/phase1_noise_20260906/trial_code_staging/src/data/rain13k_resized.py new file mode 100644 index 0000000000000000000000000000000000000000..2dcb71088326c1a9be4bf049138e9623a2e42461 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/data/rain13k_resized.py @@ -0,0 +1,721 @@ +"""Strict, side-effect-free loader for the Kaggle Rain13K-resized dataset. + +This module only discovers and validates local files. Downloading the dataset is +an explicit, separate operation handled by ``download_rain13k.py``. +""" + +from __future__ import annotations + +import hashlib +import json +import random +import re +from dataclasses import dataclass +from pathlib import Path, PurePosixPath +from types import MappingProxyType +from typing import FrozenSet, Mapping, Optional, Tuple, Union + + +DATASET_HANDLE = "hngphchi/rain13k-resized" +DATASET_VERSION = 1 +QUARANTINE_SCHEMA_VERSION = 1 +DECODED_RGB_SHA256_SPEC = ( + "sha256(b'SCDC_RGB_V1\\0' || uint32_be(width) || uint32_be(height) || " + "row_major_RGB_uint8_bytes)" +) +FILE_SHA256_SPEC = "sha256(raw on-disk target file bytes)" +TARGET_INVENTORY_ALGORITHM = ( + "sha256(domain_prefix_bytes || concatenated_sorted_records)" +) +TARGET_INVENTORY_DOMAIN_PREFIX = b"SCDC_RAIN13K_TARGET_INVENTORY_V1\0" +TARGET_INVENTORY_FILE_SELECTION = ( + "regular files that are immediate children of each included_target_dirs " + "entry; relative paths are POSIX paths rooted at the Kaggle dataset " + "version directory" +) +TARGET_INVENTORY_RECORD_FORMAT = ( + "relative_path_utf8 || 0x00 || lowercase_raw_file_sha256_hex_ascii || 0x0a" +) +TARGET_INVENTORY_SORT_ORDER = ( + "ascending lexicographic order of relative_path UTF-8 bytes" +) +TARGET_INVENTORY_DIRS = ( + "train_resized/target", + "test_resized/Rain100H/target", + "test_resized/Rain100L/target", + "test_resized/Test100/target", + "test_resized/Test1200/target", + "test_resized/Test2800/target", +) +SUPPORTED_EXTENSIONS = frozenset({".jpg", ".jpeg", ".png"}) +OFFICIAL_TEST_SETS = ("Rain100H", "Rain100L", "Test100", "Test1200", "Test2800") +_SHA256_HEX = re.compile(r"^[0-9a-fA-F]{64}$") + +ImagePair = Tuple[Path, Path] + + +@dataclass(frozen=True) +class Rain13KResizedSplits: + """Validated train pairs and isolated official-test pairs.""" + + train_pairs: Tuple[ImagePair, ...] + official_test_pairs: Mapping[str, Tuple[ImagePair, ...]] + quarantined_train_pair_count: int + + +@dataclass(frozen=True) +class _QuarantineSpec: + file_hashes: FrozenSet[str] + expected_hash_by_relative_path: Mapping[str, str] + expected_pair_count: int + expected_evidence_count: int + train_pair_count: int + official_test_pair_count: int + total_pair_count: int + target_inventory_digest: str + inventory_record_count_by_dir: Mapping[str, int] + inventory_raw_bytes_by_dir: Mapping[str, int] + inventory_total_raw_bytes: int + + +def _supported_files(directory: Path) -> Mapping[str, Path]: + files = ( + path + for path in directory.rglob("*") + if path.is_file() and path.suffix.lower() in SUPPORTED_EXTENSIONS + ) + return { + path.relative_to(directory).as_posix(): path + for path in sorted(files, key=lambda item: item.relative_to(directory).as_posix()) + } + + +def _preview(names: Tuple[str, ...], limit: int = 5) -> str: + displayed = ", ".join(names[:limit]) + remaining = len(names) - limit + if remaining > 0: + displayed += f", ... (+{remaining} more)" + return displayed + + +def _load_bijective_pairs(split_root: Path, label: str) -> Tuple[ImagePair, ...]: + input_dir = split_root / "input" + target_dir = split_root / "target" + for role, directory in (("input", input_dir), ("target", target_dir)): + if not directory.exists(): + raise FileNotFoundError( + f"Rain13K-resized {label} is missing required {role} directory: " + f"{directory}" + ) + if not directory.is_dir(): + raise NotADirectoryError( + f"Rain13K-resized {label} {role} path is not a directory: " + f"{directory}" + ) + + input_files = _supported_files(input_dir) + target_files = _supported_files(target_dir) + if not input_files and not target_files: + raise ValueError( + f"Rain13K-resized {label} contains no supported image files " + f"({', '.join(sorted(SUPPORTED_EXTENSIONS))})" + ) + + input_names = set(input_files) + target_names = set(target_files) + missing_targets = tuple(sorted(input_names - target_names)) + missing_inputs = tuple(sorted(target_names - input_names)) + if missing_targets or missing_inputs: + details = [] + if missing_targets: + details.append(f"missing target for: {_preview(missing_targets)}") + if missing_inputs: + details.append(f"missing input for: {_preview(missing_inputs)}") + raise ValueError( + f"Rain13K-resized {label} input/target pairing mismatch by exact " + f"relative filename; {'; '.join(details)}" + ) + + return tuple( + (input_files[relative_name], target_files[relative_name]) + for relative_name in sorted(input_names) + ) + + +def _validated_sha256(value: object, label: str) -> str: + if not isinstance(value, str) or _SHA256_HEX.fullmatch(value) is None: + raise ValueError(f"Rain13K quarantine manifest {label} must be 64 hex digits") + return value.lower() + + +def _required_nonnegative_int( + mapping: Mapping[str, object], + key: str, + label: str, +) -> int: + value = mapping.get(key) + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError( + f"Rain13K quarantine manifest {label}.{key} must be a " + "non-negative integer" + ) + return value + + +def _required_directory_counts( + value: object, + label: str, +) -> Mapping[str, int]: + if not isinstance(value, dict) or set(value) != set(TARGET_INVENTORY_DIRS): + raise ValueError( + f"Rain13K quarantine manifest {label} must contain exactly the six " + "target inventory directories" + ) + counts = { + relative_dir: _required_nonnegative_int(value, relative_dir, label) + for relative_dir in TARGET_INVENTORY_DIRS + } + return MappingProxyType(counts) + + +def _load_quarantine_manifest(path: Union[str, Path]) -> _QuarantineSpec: + manifest_path = Path(path).expanduser() + if not manifest_path.exists(): + raise FileNotFoundError( + f"Rain13K quarantine manifest does not exist: {manifest_path}" + ) + if not manifest_path.is_file(): + raise ValueError( + f"Rain13K quarantine manifest is not a regular file: {manifest_path}" + ) + + try: + payload = json.loads(manifest_path.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as exc: + raise ValueError( + f"Rain13K quarantine manifest has malformed JSON: {manifest_path}: {exc}" + ) from exc + if not isinstance(payload, dict): + raise ValueError("Rain13K quarantine manifest root must be a JSON object") + + schema_version = payload.get("schema_version") + if ( + isinstance(schema_version, bool) + or not isinstance(schema_version, int) + or schema_version != QUARANTINE_SCHEMA_VERSION + ): + raise ValueError( + "Rain13K quarantine manifest schema_version must be " + f"{QUARANTINE_SCHEMA_VERSION}, got {schema_version!r}" + ) + + dataset = payload.get("dataset") + if not isinstance(dataset, dict): + raise ValueError("Rain13K quarantine manifest dataset must be an object") + if dataset.get("handle") != DATASET_HANDLE: + raise ValueError( + "Rain13K quarantine manifest dataset handle must be " + f"{DATASET_HANDLE!r}, got {dataset.get('handle')!r}" + ) + dataset_version = dataset.get("version") + if ( + isinstance(dataset_version, bool) + or not isinstance(dataset_version, int) + or dataset_version != DATASET_VERSION + ): + raise ValueError( + "Rain13K quarantine manifest dataset version must be " + f"{DATASET_VERSION}, got {dataset_version!r}" + ) + + train_pair_count = _required_nonnegative_int( + dataset, + "train_pair_count", + "dataset", + ) + official_test_pair_count = _required_nonnegative_int( + dataset, + "official_test_pair_count", + "dataset", + ) + total_pair_count = _required_nonnegative_int( + dataset, + "total_pair_count", + "dataset", + ) + if train_pair_count + official_test_pair_count != total_pair_count: + raise ValueError( + "Rain13K quarantine manifest dataset pair counts are inconsistent" + ) + + inventory = dataset.get("target_inventory_v1") + if not isinstance(inventory, dict): + raise ValueError( + "Rain13K quarantine manifest dataset.target_inventory_v1 must be " + "an object" + ) + exact_inventory_strings = { + "algorithm": TARGET_INVENTORY_ALGORITHM, + "domain_prefix_hex": TARGET_INVENTORY_DOMAIN_PREFIX.hex(), + "file_selection": TARGET_INVENTORY_FILE_SELECTION, + "record_format": TARGET_INVENTORY_RECORD_FORMAT, + "sort_order": TARGET_INVENTORY_SORT_ORDER, + } + for key, expected in exact_inventory_strings.items(): + if inventory.get(key) != expected: + raise ValueError( + "Rain13K quarantine manifest target inventory specification " + f"mismatch for {key}: expected {expected!r}, " + f"got {inventory.get(key)!r}" + ) + if inventory.get("included_target_dirs") != list(TARGET_INVENTORY_DIRS): + raise ValueError( + "Rain13K quarantine manifest target inventory directories do not " + "match the v1 specification" + ) + target_inventory_digest = _validated_sha256( + inventory.get("digest_sha256"), + "dataset.target_inventory_v1.digest_sha256", + ) + inventory_record_count = _required_nonnegative_int( + inventory, + "record_count", + "dataset.target_inventory_v1", + ) + inventory_total_raw_bytes = _required_nonnegative_int( + inventory, + "total_raw_bytes", + "dataset.target_inventory_v1", + ) + inventory_record_count_by_dir = _required_directory_counts( + inventory.get("record_count_by_dir"), + "dataset.target_inventory_v1.record_count_by_dir", + ) + inventory_raw_bytes_by_dir = _required_directory_counts( + inventory.get("raw_bytes_by_dir"), + "dataset.target_inventory_v1.raw_bytes_by_dir", + ) + if sum(inventory_record_count_by_dir.values()) != inventory_record_count: + raise ValueError( + "Rain13K quarantine manifest target inventory record counts are " + "inconsistent" + ) + if sum(inventory_raw_bytes_by_dir.values()) != inventory_total_raw_bytes: + raise ValueError( + "Rain13K quarantine manifest target inventory raw byte counts are " + "inconsistent" + ) + if inventory_record_count != total_pair_count: + raise ValueError( + "Rain13K quarantine manifest target inventory record count must " + "equal dataset.total_pair_count" + ) + if ( + inventory_record_count_by_dir["train_resized/target"] + != train_pair_count + ): + raise ValueError( + "Rain13K quarantine manifest train target inventory count does not " + "match dataset.train_pair_count" + ) + if ( + inventory_record_count - train_pair_count + != official_test_pair_count + ): + raise ValueError( + "Rain13K quarantine manifest official target inventory count does " + "not match dataset.official_test_pair_count" + ) + + hash_spec = payload.get("hash_spec") + expected_hash_spec = { + "decoded_rgb_sha256": DECODED_RGB_SHA256_SPEC, + "file_sha256": FILE_SHA256_SPEC, + } + if hash_spec != expected_hash_spec: + raise ValueError( + "Rain13K quarantine manifest hash_spec does not exactly match the " + "v1 hash specification" + ) + + summary = payload.get("summary") + if not isinstance(summary, dict): + raise ValueError("Rain13K quarantine manifest summary must be an object") + expected_pair_count = _required_nonnegative_int( + summary, + "affected_train_pairs", + "summary", + ) + expected_group_count = _required_nonnegative_int( + summary, + "excluded_train_target_groups", + "summary", + ) + expected_evidence_count = _required_nonnegative_int( + summary, + "evidence_edges", + "summary", + ) + expected_unique_hashes = _required_nonnegative_int( + summary, + "unique_excluded_train_file_sha256", + "summary", + ) + + groups = payload.get("excluded_train_targets") + if not isinstance(groups, list): + raise ValueError( + "Rain13K quarantine manifest excluded_train_targets must be an array" + ) + if len(groups) != expected_group_count: + raise ValueError( + "Rain13K quarantine manifest group count mismatch: summary declares " + f"{expected_group_count}, found {len(groups)}" + ) + + target_hashes = {} + file_hashes = set() + evidence_count = 0 + for group_index, group in enumerate(groups): + if not isinstance(group, dict): + raise ValueError( + "Rain13K quarantine manifest excluded_train_targets" + f"[{group_index}] must be an object" + ) + _validated_sha256( + group.get("decoded_rgb_sha256"), + f"excluded_train_targets[{group_index}].decoded_rgb_sha256", + ) + + evidence_items = group.get("evidence") + if not isinstance(evidence_items, list): + raise ValueError( + "Rain13K quarantine manifest excluded_train_targets" + f"[{group_index}].evidence must be an array" + ) + evidence_count += len(evidence_items) + for evidence_index, evidence in enumerate(evidence_items): + if not isinstance(evidence, dict): + raise ValueError( + "Rain13K quarantine manifest evidence entry must be an object" + ) + _validated_sha256( + evidence.get("test_decoded_rgb_sha256"), + "excluded_train_targets" + f"[{group_index}].evidence[{evidence_index}]" + ".test_decoded_rgb_sha256", + ) + + train_targets = group.get("train_targets") + if not isinstance(train_targets, list) or not train_targets: + raise ValueError( + "Rain13K quarantine manifest excluded_train_targets" + f"[{group_index}].train_targets must be a non-empty array" + ) + for target_index, target in enumerate(train_targets): + if not isinstance(target, dict): + raise ValueError( + "Rain13K quarantine manifest train target entry must be an object" + ) + relative_path = target.get("relative_path") + if not isinstance(relative_path, str) or not relative_path: + raise ValueError( + "Rain13K quarantine manifest train target relative_path " + "must be a non-empty string" + ) + normalized = PurePosixPath(relative_path) + if ( + normalized.is_absolute() + or normalized.as_posix() != relative_path + or normalized.parts[:2] != ("train_resized", "target") + or len(normalized.parts) < 3 + or ".." in normalized.parts + ): + raise ValueError( + "Rain13K quarantine manifest train target relative_path must " + "be canonical and under train_resized/target: " + f"{relative_path!r}" + ) + if relative_path in target_hashes: + raise ValueError( + "Rain13K quarantine manifest contains duplicate train target " + f"path: {relative_path}" + ) + file_hash = _validated_sha256( + target.get("file_sha256"), + "excluded_train_targets" + f"[{group_index}].train_targets[{target_index}].file_sha256", + ) + target_hashes[relative_path] = file_hash + file_hashes.add(file_hash) + + if len(target_hashes) != expected_pair_count: + raise ValueError( + "Rain13K quarantine manifest affected pair count mismatch: summary " + f"declares {expected_pair_count}, found {len(target_hashes)}" + ) + if expected_unique_hashes != len(file_hashes): + raise ValueError( + "Rain13K quarantine manifest unique file SHA256 count mismatch: " + f"summary declares {expected_unique_hashes!r}, found {len(file_hashes)}" + ) + if evidence_count != expected_evidence_count: + raise ValueError( + "Rain13K quarantine manifest evidence count mismatch: summary " + f"declares {expected_evidence_count}, found {evidence_count}" + ) + + per_test = payload.get("per_test") + if not isinstance(per_test, dict) or set(per_test) != set(OFFICIAL_TEST_SETS): + raise ValueError( + "Rain13K quarantine manifest per_test must contain exactly the five " + "official test sets" + ) + for test_name in OFFICIAL_TEST_SETS: + test_summary = per_test[test_name] + if not isinstance(test_summary, dict): + raise ValueError( + f"Rain13K quarantine manifest per_test.{test_name} must be an object" + ) + implicated_hashes = test_summary.get( + "implicated_train_decoded_rgb_sha256" + ) + if not isinstance(implicated_hashes, list): + raise ValueError( + "Rain13K quarantine manifest " + f"per_test.{test_name}.implicated_train_decoded_rgb_sha256 " + "must be an array" + ) + for hash_index, decoded_hash in enumerate(implicated_hashes): + _validated_sha256( + decoded_hash, + f"per_test.{test_name}.implicated_train_decoded_rgb_sha256" + f"[{hash_index}]", + ) + + return _QuarantineSpec( + file_hashes=frozenset(file_hashes), + expected_hash_by_relative_path=MappingProxyType(target_hashes), + expected_pair_count=expected_pair_count, + expected_evidence_count=expected_evidence_count, + train_pair_count=train_pair_count, + official_test_pair_count=official_test_pair_count, + total_pair_count=total_pair_count, + target_inventory_digest=target_inventory_digest, + inventory_record_count_by_dir=inventory_record_count_by_dir, + inventory_raw_bytes_by_dir=inventory_raw_bytes_by_dir, + inventory_total_raw_bytes=inventory_total_raw_bytes, + ) + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as source: + for chunk in iter(lambda: source.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _verify_target_inventory( + dataset_root: Path, + train_pairs: Tuple[ImagePair, ...], + official_test_pairs: Mapping[str, Tuple[ImagePair, ...]], + spec: _QuarantineSpec, +) -> Mapping[str, str]: + if len(train_pairs) != spec.train_pair_count: + raise ValueError( + "Rain13K v1 train pair count mismatch: expected " + f"{spec.train_pair_count}, got {len(train_pairs)}" + ) + observed_official_pairs = sum(len(pairs) for pairs in official_test_pairs.values()) + if observed_official_pairs != spec.official_test_pair_count: + raise ValueError( + "Rain13K v1 official test pair count mismatch: expected " + f"{spec.official_test_pair_count}, got {observed_official_pairs}" + ) + if len(train_pairs) + observed_official_pairs != spec.total_pair_count: + raise ValueError("Rain13K v1 total pair count does not match the manifest") + for test_name, pairs in official_test_pairs.items(): + relative_dir = f"test_resized/{test_name}/target" + expected_count = spec.inventory_record_count_by_dir[relative_dir] + if len(pairs) != expected_count: + raise ValueError( + f"Rain13K v1 {test_name} pair count mismatch: expected " + f"{expected_count}, got {len(pairs)}" + ) + + records = [] + target_hashes = {} + observed_record_counts = {} + observed_raw_bytes = {} + for relative_dir in TARGET_INVENTORY_DIRS: + target_dir = dataset_root / relative_dir + target_files = tuple(path for path in target_dir.iterdir() if path.is_file()) + observed_record_counts[relative_dir] = len(target_files) + observed_raw_bytes[relative_dir] = sum( + path.stat().st_size for path in target_files + ) + for target_path in target_files: + relative_path = target_path.relative_to(dataset_root).as_posix() + file_hash = _sha256_file(target_path) + records.append((relative_path, file_hash)) + target_hashes[relative_path] = file_hash + + if observed_record_counts != dict(spec.inventory_record_count_by_dir): + raise ValueError( + "Rain13K v1 target inventory record counts do not match the manifest" + ) + if observed_raw_bytes != dict(spec.inventory_raw_bytes_by_dir): + raise ValueError( + "Rain13K v1 target inventory raw byte counts do not match the manifest" + ) + if sum(observed_raw_bytes.values()) != spec.inventory_total_raw_bytes: + raise ValueError( + "Rain13K v1 target inventory total raw bytes do not match the manifest" + ) + + inventory_digest = hashlib.sha256(TARGET_INVENTORY_DOMAIN_PREFIX) + for relative_path, file_hash in sorted( + records, + key=lambda record: record[0].encode("utf-8"), + ): + inventory_digest.update(relative_path.encode("utf-8")) + inventory_digest.update(b"\0") + inventory_digest.update(file_hash.encode("ascii")) + inventory_digest.update(b"\n") + actual_inventory_digest = inventory_digest.hexdigest() + if actual_inventory_digest != spec.target_inventory_digest: + raise ValueError( + "Rain13K v1 target inventory digest mismatch: expected " + f"{spec.target_inventory_digest}, got {actual_inventory_digest}" + ) + + return MappingProxyType(target_hashes) + + +def _apply_quarantine( + dataset_root: Path, + train_pairs: Tuple[ImagePair, ...], + spec: _QuarantineSpec, + target_hashes: Mapping[str, str], +) -> Tuple[Tuple[ImagePair, ...], int]: + kept_pairs = [] + seen_manifest_paths = set() + quarantined_count = 0 + + for pair in train_pairs: + target_path = pair[1] + relative_path = target_path.relative_to(dataset_root).as_posix() + actual_hash = target_hashes.get(relative_path) + if actual_hash is None: + raise ValueError( + "Rain13K v1 target inventory omitted train target: " + f"{relative_path}" + ) + expected_hash = spec.expected_hash_by_relative_path.get(relative_path) + if expected_hash is not None: + seen_manifest_paths.add(relative_path) + if actual_hash != expected_hash: + raise ValueError( + "Rain13K quarantine manifest file_sha256 mismatch for " + f"{relative_path}: expected {expected_hash}, got {actual_hash}" + ) + + if actual_hash in spec.file_hashes: + quarantined_count += 1 + else: + kept_pairs.append(pair) + + missing_paths = sorted( + set(spec.expected_hash_by_relative_path) - seen_manifest_paths + ) + if missing_paths: + raise ValueError( + "Rain13K quarantine manifest references train targets absent from " + f"this dataset: {_preview(tuple(missing_paths))}" + ) + if quarantined_count != spec.expected_pair_count: + raise ValueError( + "Rain13K quarantine manifest matched an unexpected number of train " + f"pairs: expected {spec.expected_pair_count}, got {quarantined_count}" + ) + + return tuple(kept_pairs), quarantined_count + + +def _validate_max_train_pairs(max_train_pairs: Optional[int]) -> None: + if max_train_pairs is None: + return + if isinstance(max_train_pairs, bool) or not isinstance(max_train_pairs, int): + raise TypeError("max_train_pairs must be an integer, zero, or None") + if max_train_pairs < 0: + raise ValueError("max_train_pairs must be non-negative") + + +def load_rain13k_resized( + root: Union[str, Path], + max_train_pairs: Optional[int] = 0, + seed: int = 42, + quarantine_manifest: Optional[Union[str, Path]] = None, +) -> Rain13KResizedSplits: + """Load local Rain13K-resized pairs after strict structure validation. + + A configured quarantine manifest is verified against dataset version 1 and + applied to raw target-file SHA256 hashes before ``max_train_pairs``. A cap + of zero or ``None`` retains every non-quarantined train pair. Official test + pairs are always returned separately and are never merged into training. + """ + + dataset_root = Path(root).expanduser() + if not dataset_root.exists(): + raise FileNotFoundError( + f"Rain13K-resized root does not exist: {dataset_root}. " + "Run download_rain13k.py and pass its resolved path via " + "--rain13k-root." + ) + if not dataset_root.is_dir(): + raise NotADirectoryError( + f"Rain13K-resized root is not a directory: {dataset_root}" + ) + dataset_root = dataset_root.resolve() + _validate_max_train_pairs(max_train_pairs) + + train_pairs = _load_bijective_pairs( + dataset_root / "train_resized", + "train_resized", + ) + official_test_pairs = { + test_name: _load_bijective_pairs( + dataset_root / "test_resized" / test_name, + f"test_resized/{test_name}", + ) + for test_name in OFFICIAL_TEST_SETS + } + + quarantined_train_pair_count = 0 + if quarantine_manifest is not None: + quarantine_spec = _load_quarantine_manifest(quarantine_manifest) + target_hashes = _verify_target_inventory( + dataset_root, + train_pairs, + official_test_pairs, + quarantine_spec, + ) + train_pairs, quarantined_train_pair_count = _apply_quarantine( + dataset_root, + train_pairs, + quarantine_spec, + target_hashes, + ) + + if max_train_pairs is not None and 0 < max_train_pairs < len(train_pairs): + selected_indices = sorted( + random.Random(seed).sample(range(len(train_pairs)), max_train_pairs) + ) + train_pairs = tuple(train_pairs[index] for index in selected_indices) + + return Rain13KResizedSplits( + train_pairs=train_pairs, + official_test_pairs=MappingProxyType(official_test_pairs), + quarantined_train_pair_count=quarantined_train_pair_count, + ) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/__init__.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..92adc7a01ba5ca352ceaa181709903165a906499 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/__init__.py @@ -0,0 +1,29 @@ +"""Models package for SCDC. + +Deployed Phase-1 lives in :mod:`src.models.graph_encoder`; Phase-2 restoration +stacks live in :mod:`src.models.restoration`. The dual-domain degradation +transformer (:mod:`src.models.degradation`) is kept as the spatial/wavelet +reference lineage. +""" + +from .degradation import ( + TYPE_ORDER, + QUERY_NAMES, + UNKNOWN_INDEX, + NUM_KNOWN_TYPES, + NUM_TYPE_CLASSES, + DualDomainDegradationTransformer, + DegradationLosses, + create_degradation_transformer, +) + +__all__ = [ + "TYPE_ORDER", + "QUERY_NAMES", + "UNKNOWN_INDEX", + "NUM_KNOWN_TYPES", + "NUM_TYPE_CLASSES", + "DualDomainDegradationTransformer", + "DegradationLosses", + "create_degradation_transformer", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/__pycache__/__init__.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9af2b2ca4f070cb585916335808f019d22bc66c1 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/__pycache__/__init__.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__init__.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f5ab2126a15c68c1726a44265311506c1f750999 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__init__.py @@ -0,0 +1,63 @@ +"""Dual-Domain Degradation Transformer package. + +Replaces the previous DC-AE-displacement / FastDualDomainEncoder classifiers: +the classifier is now a dedicated dual-domain transformer that never touches +DC-AE. DC-AE remains the frozen latent space for restoration only. +""" + +from .constants import ( + NUM_KNOWN_TYPES, + NUM_TYPE_CLASSES, + QUERY_NAMES, + TYPE_ORDER, + UNKNOWN_INDEX, + multi_hot, + severity_vector, + type_index, +) +from .losses import DegradationLosses, LossConfig +from .metrics import ( + ClassificationReport, + classification_report, + gate_s0_check_embedding, + gate_s0_check_pair, + primary_type_index, + predicted_type_index, + severity_correlations, +) +from .model import ( + DOMAIN_NAMES, + DualDomainDegradationTransformer, + SeverityMapLoss, + count_trainable_parameters, + create_degradation_transformer, +) + +__all__ = [ + # Constants + "TYPE_ORDER", + "QUERY_NAMES", + "NUM_KNOWN_TYPES", + "NUM_TYPE_CLASSES", + "UNKNOWN_INDEX", + "type_index", + "multi_hot", + "severity_vector", + # Model + "DualDomainDegradationTransformer", + "SeverityMapLoss", + "DOMAIN_NAMES", + "count_trainable_parameters", + "create_degradation_transformer", + # Losses + "DegradationLosses", + "LossConfig", + # Metrics and gates + "ClassificationReport", + "classification_report", + "gate_s0_check_pair", + "gate_s0_check_embedding", + "primary_type_index", + "predicted_type_index", + "severity_correlations", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/__init__.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf3c72afe00827fab440301a302a1dd6faad4f54 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/__init__.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/constants.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/constants.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ced8fbfad0eff9fd233574c6564ba52bd1ae2dd3 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/constants.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/losses.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/losses.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..68eea110062cb4dae26160d01fe6d9d654f8bd21 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/losses.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/metrics.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/metrics.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e78f41235172a17ad2feccf57fb438e37900d2d6 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/metrics.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/model.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/model.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2ff2db8628214e384c3257fc2fc856c9153752d Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/model.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/spatial_branch.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/spatial_branch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae0277d154364761210c903ec404c7c7b06cfac6 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/spatial_branch.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/transformer.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/transformer.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cea5d71c3384f638ef2fa944dd178b84caf78198 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/transformer.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/wavelet_branch.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/wavelet_branch.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33a63911c56888d2a73c3018ef0d285e4d6bb74b Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/__pycache__/wavelet_branch.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/constants.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..0068795a33b6340b2bc2ba9d7ddc3213058fe59b --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/constants.py @@ -0,0 +1,100 @@ +"""Canonical degradation constants for the Dual-Domain Degradation Transformer. + +Gate S2: there is exactly one label order in the whole pipeline. Every spec, +cache, classifier head, severity vector, and metric must derive from +``TYPE_ORDER`` here. The order matches the physical camera application order +in :mod:`src.data.phase1_v2` and the equality is asserted at import time so a +future reorder cannot silently desynchronize features and labels. +""" + +from __future__ import annotations + +from typing import Sequence, Tuple + +import torch + +# Allow override for extended type sets +_EXTENDED_TYPE_ORDER: Tuple[str, ...] = None +_EXTENDED_NUM_KNOWN: int = None +_EXTENDED_NUM_CLASSES: int = None + +def set_extended_types(type_order: Tuple[str, ...]): + """Set extended type order for multi-dataset training.""" + global _EXTENDED_TYPE_ORDER, _EXTENDED_NUM_KNOWN, _EXTENDED_NUM_CLASSES + _EXTENDED_TYPE_ORDER = type_order + _EXTENDED_NUM_KNOWN = len(type_order) + _EXTENDED_NUM_CLASSES = _EXTENDED_NUM_KNOWN + 1 # known + unknown + +from ...data.phase1_v2 import TYPE_ORDER as _BASE_TYPE_ORDER + +# Export TYPE_ORDER for backwards compatibility +TYPE_ORDER = _BASE_TYPE_ORDER + +NUM_KNOWN_TYPES: int = 4 # default: blur, lowlight, noise, jpeg +UNKNOWN_INDEX: int = NUM_KNOWN_TYPES # 4 +NUM_TYPE_CLASSES: int = NUM_KNOWN_TYPES + 1 # 4 known + unknown +QUERY_NAMES: Tuple[str, ...] = ("Qblur", "Qlowlight", "Qnoise", "Qjpeg", "Qunknown") + +_BASE_TYPE_TO_INDEX = {name: index for index, name in enumerate(_BASE_TYPE_ORDER)} + + +def _get_type_order(): + return _EXTENDED_TYPE_ORDER if _EXTENDED_TYPE_ORDER else _BASE_TYPE_ORDER + + +def _get_num_known(): + return _EXTENDED_NUM_KNOWN if _EXTENDED_NUM_KNOWN else NUM_KNOWN_TYPES + + +def _get_num_classes(): + return _EXTENDED_NUM_CLASSES if _EXTENDED_NUM_CLASSES else NUM_TYPE_CLASSES + + +def _type_to_index(name: str) -> int: + """Return the canonical index of a degradation name.""" + if _EXTENDED_TYPE_ORDER: + return _EXTENDED_TYPE_ORDER.index(name) + return _BASE_TYPE_TO_INDEX[name] + + +def type_index(name: str) -> int: + """Return the canonical index of a known degradation name.""" + + try: + return _type_to_index(name) + except ValueError as error: + raise KeyError( + f"Unknown degradation '{name}'. Known types: {TYPE_ORDER}" + ) from error + + +def multi_hot(components: Sequence[str]) -> torch.Tensor: + """Return a ``NUM_TYPE_CLASSES`` float target vector for a sample. + + Positions of present components are 1.0. A clean sample is all-zero; + ``unknown`` is reserved for explicit outlier-exposure corruptions rather + than conflating "no degradation" with "unseen degradation". + """ + + vector = torch.zeros(NUM_TYPE_CLASSES, dtype=torch.float32) + seen = set() + for component in components: + try: + idx = _type_to_index(component) + except ValueError: + raise KeyError(f"Unknown degradation component: {component}") + if component not in seen: + vector[idx] = 1.0 + seen.add(component) + return vector + + +def severity_vector(components: Sequence[str], severities: Sequence[float]) -> torch.Tensor: + """Scatter normalized severities into canonical ``NUM_KNOWN_TYPES`` order.""" + + if len(components) != len(severities): + raise ValueError("components and severities must align") + vector = torch.zeros(NUM_KNOWN_TYPES, dtype=torch.float32) + for component, severity in zip(components, severities): + vector[_type_to_index(component)] = float(severity) + return vector diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/losses.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..431aec0ec4888a5394f6b937f564f922368f9359 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/losses.py @@ -0,0 +1,296 @@ +"""Losses for the Dual-Domain Degradation Transformer. + +Total objective:: + + L = lt*L_type + ls*L_severity + lr*L_ranking + lc*L_clean_zero + + lp*L_pair + ld*L_domain_agreement + +* ``L_type``: sigmoid focal loss over the five query logits (multi-hot targets + so compositions are supported natively). +* ``L_severity``: SmoothL1 restricted to active degradation types. +* ``L_ranking``: margin ranking that keeps severity ordering between samples + of the same type (tensorized pairwise). +* ``L_clean_zero``: a clean image must map close to the origin (embedding + norm plus suppressed type/severity mass). +* ``L_pair``: same crop + same type embeddings keep direction and grow with + severity. +* ``L_domain_agreement``: single-domain predictions must not contradict the + dual-domain prediction. + +All reductions are tensorized; no Python double loops over the batch. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import Tensor + +from .constants import UNKNOWN_INDEX + + +@dataclass +class LossConfig: + lambda_type: float = 2.0 # Increased: type is priority + lambda_severity: float = 0.5 # Decreased: secondary + lambda_ranking: float = 0.1 # Decreased + lambda_clean_zero: float = 0.3 # Decreased + lambda_pair: float = 0.1 # Decreased + lambda_domain_agreement: float = 0.05 # Decreased + lambda_unknown_exposure: float = 0.2 + # Severity penalty pushing absent-type predictions to zero. + lambda_absent_severity: float = 0.1 # Decreased + # Focal hyper-parameters. + focal_gamma: float = 2.0 + focal_alpha: float = 0.25 + # Ranking margins. + rank_margin: float = 0.05 + severity_gap: float = 0.05 + # Pair consistency. + pair_direction_margin: float = 0.5 + pair_magnitude_margin: float = 0.02 + + +def sigmoid_focal_loss( + logits: Tensor, + targets: Tensor, + gamma: float = 2.0, + alpha: float = 0.25, +) -> Tensor: + """Multi-label binary focal loss, averaged over batch and classes.""" + + probs = torch.sigmoid(logits) + ce = F.binary_cross_entropy_with_logits(logits, targets, reduction="none") + p_t = probs * targets + (1.0 - probs) * (1.0 - targets) + alpha_t = alpha * targets + (1.0 - alpha) * (1.0 - targets) + return (alpha_t * (1.0 - p_t).pow(gamma) * ce).mean() + + +def ranking_loss( + severity_pred: Tensor, + severity_target: Tensor, + active_mask: Tensor, + margin: float = 0.05, + min_gap: float = 0.05, +) -> Tensor: + """Pairwise margin ranking within shared active types. + + severity_pred/target: [B, K]; active_mask: [B, K] bool. + """ + + total = severity_pred.new_zeros(()) + count = 0 + for k in range(severity_pred.shape[1]): + idx = active_mask[:, k].nonzero(as_tuple=True)[0] + if idx.numel() < 2: + continue + pred = severity_pred[idx, k] + target = severity_target[idx, k] + diff_t = target.unsqueeze(0) - target.unsqueeze(1) # [i, j] = target_j - target_i + pair_mask = diff_t.abs() >= min_gap + if not pair_mask.any(): + continue + sign = torch.sign(diff_t) + # pred_j should exceed pred_i by `margin` whenever target_j > target_i. + violation = F.relu(margin - sign * (pred.unsqueeze(0) - pred.unsqueeze(1))) + total = total + (violation * pair_mask).sum() + count += int(pair_mask.sum().item()) + if count == 0: + return severity_pred.new_zeros(()) + return total / count + + +def clean_zero_loss( + embedding: Tensor, + type_logits: Tensor, + severity: Tensor, +) -> Dict[str, Tensor]: + """Clean images must sit at the origin of every output space.""" + + embed_norm = embedding.norm(dim=-1).mean() + type_mass = torch.sigmoid(type_logits).mean() + severity_mass = severity.mean() + return { + "clean_zero": embed_norm + type_mass + severity_mass, + "clean_embed_norm": embed_norm.detach(), + } + + +def _pairs_by_key(keys: Tensor): + """Yield all index pairs sharing an identical key value.""" + + unique = torch.unique(keys) + for value in unique: + idx = (keys == value).nonzero(as_tuple=True)[0] + n = idx.numel() + if n < 2: + continue + grid = torch.triu_indices(n, n, offset=1, device=keys.device) + yield idx[grid[0]], idx[grid[1]] + + +def pair_loss( + embedding: Tensor, + crop_keys: Tensor, + type_keys: Tensor, + severity_target: Tensor, + active_mask: Tensor, + direction_margin: float = 0.5, + magnitude_margin: float = 0.02, +) -> Tensor: + """Same crop + same type pairs: aligned direction, monotone magnitude.""" + + valid = type_keys >= 0 + if valid.sum() < 2: + return embedding.new_zeros(()) + embedding = embedding[valid] + crop_keys = crop_keys[valid] + type_keys = type_keys[valid] + severity_target = severity_target[valid] + active_mask = active_mask[valid] + + normed = F.normalize(embedding, dim=-1) + norms = embedding.norm(dim=-1) + total = embedding.new_zeros(()) + count = 0 + for i, j in _pairs_by_key(crop_keys * 1000 + type_keys): + shared_types = active_mask[i] & active_mask[j] + if not shared_types.any(): + continue + cosine = (normed[i] * normed[j]).sum(dim=-1) + total = total + F.relu(direction_margin - cosine).sum() + sev_i = (severity_target[i] * shared_types).sum(dim=-1) + sev_j = (severity_target[j] * shared_types).sum(dim=-1) + sign = torch.sign(sev_i - sev_j) + violation = F.relu(magnitude_margin - sign * (norms[i] - norms[j])) + equal = (sign == 0).float() + total = total + (violation * (1.0 - equal)).sum() + count += int(shared_types.sum().item()) + if count == 0: + return embedding.new_zeros(()) + return total / count + + +def domain_agreement_loss(pred_a: dict, pred_b: dict) -> Dict[str, Tensor]: + """Single-domain vs dual-domain consistency.""" + + prob_a = torch.sigmoid(pred_a["type_logits"]) + prob_b = torch.sigmoid(pred_b["type_logits"]) + type_consistency = 0.5 * ( + F.mse_loss(prob_a, prob_b.detach()) + + F.mse_loss(prob_b, prob_a.detach()) + ) + cos = F.cosine_similarity( + pred_a["degradation_embedding"], pred_b["degradation_embedding"], dim=-1 + ).mean() + agreement = type_consistency + (1.0 - cos) + return {"domain_agreement": agreement, "domain_cosine": cos.detach()} + + +class DegradationLosses(nn.Module): + """Weighted combination of all degradation-classifier losses.""" + + def __init__(self, config: Optional[LossConfig] = None): + super().__init__() + self.config = config or LossConfig() + + def forward( + self, + preds: dict, + multi_hot: Tensor, + severity_target: Tensor, + active_mask: Tensor, + crop_keys: Optional[Tensor] = None, + type_keys: Optional[Tensor] = None, + domain_preds: Optional[dict] = None, + clean_preds: Optional[dict] = None, + unknown_preds: Optional[dict] = None, + domain_anchor_preds: Optional[dict] = None, + ) -> Dict[str, Tensor]: + cfg = self.config + components: Dict[str, Tensor] = {} + + components["type"] = sigmoid_focal_loss( + preds["type_logits"], multi_hot, cfg.focal_gamma, cfg.focal_alpha + ) + + errors = F.smooth_l1_loss(preds["severity"], severity_target, reduction="none", beta=0.1) + components["severity"] = (errors * active_mask.float()).sum() / active_mask.float().sum().clamp_min(1.0) + if cfg.lambda_absent_severity > 0: + absent = (~active_mask).float() + absent_err = preds["severity"].abs() * absent + components["severity_absent"] = absent_err.sum() / absent.sum().clamp_min(1.0) + + components["ranking"] = ranking_loss( + preds["severity"], + severity_target, + active_mask, + margin=cfg.rank_margin, + min_gap=cfg.severity_gap, + ) + + if clean_preds is not None: + clean_components = clean_zero_loss( + clean_preds["degradation_embedding"], + clean_preds["type_logits"], + clean_preds["severity"], + ) + components.update(clean_components) + + if unknown_preds is not None: + unknown_target = torch.zeros_like(unknown_preds["type_logits"]) + unknown_target[:, UNKNOWN_INDEX] = 1.0 + components["unknown_type"] = sigmoid_focal_loss( + unknown_preds["type_logits"], + unknown_target, + cfg.focal_gamma, + cfg.focal_alpha, + ) + + if ( + crop_keys is not None + and type_keys is not None + and (crop_keys * 1000 + type_keys).unique().numel() < crop_keys.numel() + ): + pair_embedding = preds["degradation_embedding"] + if clean_preds is not None: + pair_embedding = ( + pair_embedding - clean_preds["degradation_embedding"] + ) + components["pair"] = pair_loss( + pair_embedding, + crop_keys, + type_keys, + severity_target, + active_mask, + cfg.pair_direction_margin, + cfg.pair_magnitude_margin, + ) + else: + components["pair"] = preds["degradation_embedding"].new_zeros(()) + + if domain_preds is not None: + components.update( + domain_agreement_loss(domain_anchor_preds or preds, domain_preds) + ) + + total = ( + cfg.lambda_type * components["type"] + + cfg.lambda_unknown_exposure + * components.get("unknown_type", preds["type_logits"].new_zeros(())) + + cfg.lambda_severity * components["severity"] + + cfg.lambda_ranking * components["ranking"] + + cfg.lambda_clean_zero * components.get("clean_zero", preds["type_logits"].new_zeros(())) + + cfg.lambda_pair * components.get("pair", preds["type_logits"].new_zeros(())) + + cfg.lambda_domain_agreement + * components.get("domain_agreement", preds["type_logits"].new_zeros(())) + ) + if "severity_absent" in components: + total = total + cfg.lambda_absent_severity * components["severity_absent"] + + components["total"] = total + return {key: value for key, value in components.items()} diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/metrics.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..d7030e7c40af8864090877d50131220f9a8b0efa --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/metrics.py @@ -0,0 +1,215 @@ +"""Sanity gates and evaluation metrics for the degradation classifier. + +Gate S0: a degraded image must actually differ from its clean source, and the +classifier's embedding displacement must be non-zero. +Gate S1: overfit a tiny split (run from the trainer ``--gate overfit``). +Gate S2: canonical label order is enforced by importing +:func:`src.models.degradation.constants` (raises on mismatch). +Gate S3: ablation presets A0..A6 are built by :func:`create_degradation_transformer`. + +Metrics include raw accuracy, predicted-class histogram, confusion matrix and +Hungarian-matched accuracy so a label permutation can never hide as "low but +real" performance. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from itertools import permutations +from typing import Dict + +import numpy as np +import torch +from torch import Tensor + +from .constants import NUM_KNOWN_TYPES, TYPE_ORDER + + +def gate_s0_check_pair( + clean: Tensor, + degraded: Tensor, + l1_threshold: float = 1e-4, +) -> Dict[str, object]: + """Assert the degradation operator actually modified the image.""" + + if clean.shape != degraded.shape: + raise ValueError("clean/degraded shape mismatch") + l1 = (clean - degraded).abs().mean().item() + max_abs = (clean - degraded).abs().max().item() + passed = l1 > l1_threshold + return { + "passed": bool(passed), + "l1": l1, + "max_abs": max_abs, + "threshold": l1_threshold, + "reason": None if passed else f"L1(clean, degraded)={l1:.6f} <= {l1_threshold}", + } + + +def gate_s0_check_embedding( + embedding_clean: Tensor, + embedding_degraded: Tensor, + min_displacement: float = 0.0, +) -> Dict[str, object]: + """E(degraded) - E(clean) must not vanish.""" + + delta = embedding_degraded - embedding_clean + displacement = delta.norm(dim=-1) + max_abs = delta.abs().flatten(1).max(dim=1).values + mean_norm = displacement.mean().item() + min_max_abs = max_abs.min().item() + return { + "passed": bool(min_max_abs > min_displacement), + "mean_embedding_displacement": mean_norm, + "min_max_abs_displacement": min_max_abs, + "min_required": min_displacement, + } + + +@dataclass +class ClassificationReport: + accuracy: float + hungarian_accuracy: float + confusion_matrix: np.ndarray # [4 targets, 5 predictions] + predicted_histogram: np.ndarray # [5] including unknown + multilabel_macro_f1: float + composition_exact_match: float + composition_jaccard: float + class_order: tuple = TYPE_ORDER + + +def primary_type_index(multi_hot: Tensor) -> Tensor: + """Canonical index of the first active known type; unknown -> 4.""" + + known = multi_hot[:, :NUM_KNOWN_TYPES] + first = known.float().argmax(dim=1) + has_type = known.float().sum(dim=1) > 0 + return torch.where(has_type, first, torch.full_like(first, NUM_KNOWN_TYPES)) + + +def predicted_type_index(type_logits: Tensor) -> Tensor: + """Argmax prediction including the unknown class.""" + + return type_logits.argmax(dim=1) + + +def classification_report( + type_logits: Tensor, + multi_hot_targets: Tensor, +) -> ClassificationReport: + # Four-class accuracy and permutation checks are defined on singles only; + # compositions are multi-label and have no unambiguous primary class. + singles = multi_hot_targets[:, :NUM_KNOWN_TYPES].sum(dim=1) == 1 + targets = primary_type_index(multi_hot_targets[singles]).cpu().numpy() + preds = predicted_type_index(type_logits[singles]).cpu().numpy() + + accuracy = float((preds == targets).mean()) if len(targets) else 0.0 + confusion = np.zeros((NUM_KNOWN_TYPES, NUM_KNOWN_TYPES + 1), dtype=np.int64) + histogram = np.zeros(NUM_KNOWN_TYPES + 1, dtype=np.int64) + for target, pred in zip(targets, preds): + histogram[pred] += 1 + if target < NUM_KNOWN_TYPES: + confusion[target, pred] += 1 + + hungarian = _hungarian_accuracy_from_confusion( + confusion[:, :NUM_KNOWN_TYPES], + denominator=int(confusion.sum()), + ) + + known_targets = multi_hot_targets[:, :NUM_KNOWN_TYPES].bool().cpu().numpy() + known_predictions = ( + type_logits[:, :NUM_KNOWN_TYPES].sigmoid() >= 0.5 + ).cpu().numpy() + f1_values = [] + for index in range(NUM_KNOWN_TYPES): + target = known_targets[:, index] + prediction = known_predictions[:, index] + tp = np.logical_and(target, prediction).sum() + fp = np.logical_and(~target, prediction).sum() + fn = np.logical_and(target, ~prediction).sum() + denominator = 2 * tp + fp + fn + f1_values.append(2 * tp / denominator if denominator else 0.0) + composition_rows = known_targets.sum(axis=1) > 1 + if composition_rows.any(): + target_compositions = known_targets[composition_rows] + predicted_compositions = known_predictions[composition_rows] + exact_match = float( + np.all(target_compositions == predicted_compositions, axis=1).mean() + ) + intersection = np.logical_and( + target_compositions, predicted_compositions + ).sum(axis=1) + union = np.logical_or(target_compositions, predicted_compositions).sum(axis=1) + jaccard = float(np.mean(intersection / union)) + else: + exact_match = 0.0 + jaccard = 0.0 + return ClassificationReport( + accuracy=accuracy, + hungarian_accuracy=hungarian, + confusion_matrix=confusion, + predicted_histogram=histogram, + multilabel_macro_f1=float(np.mean(f1_values)), + composition_exact_match=exact_match, + composition_jaccard=jaccard, + ) + + +def _hungarian_accuracy_from_confusion( + confusion: np.ndarray, + denominator: int | None = None, +) -> float: + # Four classes have only 4! = 24 assignments. Exhaustive maximization is + # exactly equivalent to Hungarian matching here and avoids a heavyweight + # SciPy dependency in the training/evaluation path. + rows = np.arange(confusion.shape[0]) + matched = max( + int(confusion[rows, np.asarray(columns)].sum()) + for columns in permutations(range(confusion.shape[1]), confusion.shape[0]) + ) + total = int(confusion.sum()) if denominator is None else denominator + return matched / total if total else 0.0 + + +def _rankdata(values: np.ndarray) -> np.ndarray: + """Average ranks for ties, equivalent to scipy.stats.rankdata.""" + + order = np.argsort(values, kind="mergesort") + sorted_values = values[order] + ranks = np.empty(len(values), dtype=np.float64) + start = 0 + while start < len(values): + end = start + 1 + while end < len(values) and sorted_values[end] == sorted_values[start]: + end += 1 + ranks[order[start:end]] = (start + end - 1) / 2.0 + start = end + return ranks + + +def _spearman(x: np.ndarray, y: np.ndarray) -> float: + x_rank = _rankdata(np.asarray(x)) + y_rank = _rankdata(np.asarray(y)) + if np.ptp(x_rank) == 0 or np.ptp(y_rank) == 0: + return float("nan") + return float(np.corrcoef(x_rank, y_rank)[0, 1]) + + +def severity_correlations( + severity_pred: Tensor, + severity_target: Tensor, + active_mask: Tensor, +) -> Dict[str, float]: + """Per-type Spearman rho between predictions and labels.""" + + report: Dict[str, float] = {} + pred = severity_pred.detach().cpu().numpy() + target = severity_target.detach().cpu().numpy() + mask = active_mask.detach().cpu().numpy() + for k, name in enumerate(TYPE_ORDER): + rows = mask[:, k].astype(bool) + if rows.sum() >= 3 and np.ptp(target[rows, k]) > 0: + report[name] = _spearman(pred[rows, k], target[rows, k]) + if mask.sum() >= 3: + report["overall"] = _spearman(pred[mask], target[mask]) + return report diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/model.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/model.py new file mode 100644 index 0000000000000000000000000000000000000000..85be2e7f9e4a65fc11d65f6fd6e101d306e780b1 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/model.py @@ -0,0 +1,345 @@ +"""Dual-Domain Degradation Transformer (full model). + +Pipeline:: + + degraded image ──┬─► Pixel/illumination stem ──► spatial tokens (H/16) + │ │ + ├─► Haar 3-level wavelet encoder ► wavelet tokens (4x4) + │ │ + └────────────► Dual-domain query transformer ◄────┘ + │ + Type · severity · confidence · degradation embedding + │ + (frozen DC-AE stays outside: restoration latent space only) + +Outputs:: + + { + "degradation_embedding": [B, 128], + "type_logits": [B, 5], # blur|lowlight|noise|jpeg|unknown + "confidence": [B, 5], + "severity": [B, 4], # normalized, canonical TYPE_ORDER + "spatial_severity_map": [B, 4, H/8, W/8], + } + +The ``domains`` argument selects which key/value streams the queries may +attend to (ablations A0/A1); ``modality_dropout`` randomly disables a domain +per sample during training; ``shuffle_wavelet=True`` rolls the wavelet stream +across the batch (control A6). +""" + +from __future__ import annotations + +from typing import Optional, Sequence, Tuple + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from .constants import NUM_KNOWN_TYPES, NUM_TYPE_CLASSES +from .losses import LossConfig +from .spatial_branch import SpatialBranch +from .transformer import DegradationHeads, DualDomainFusion +from .wavelet_branch import WaveletBranch + +DOMAIN_NAMES = ("spatial", "wavelet") + + +def _single_query_heads(hidden_dim: int, embed_dim: int) -> nn.Module: + """A3-style heads fed by one generic readout query.""" + + class SingleQueryHeads(nn.Module): + def __init__(self): + super().__init__() + self.type_proj = nn.Linear(hidden_dim, NUM_TYPE_CLASSES) + self.severity_proj = nn.Linear(hidden_dim, NUM_KNOWN_TYPES) + self.embedding_proj = nn.Sequential( + nn.Linear(hidden_dim, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, embed_dim), + ) + + def forward(self, query_states: Tensor) -> dict: + pooled = query_states.mean(dim=1) # [B, H] + type_logits = self.type_proj(pooled) + return { + "type_logits": type_logits, + "confidence": torch.sigmoid(type_logits), + "severity": torch.sigmoid(self.severity_proj(pooled)), + "degradation_embedding": self.embedding_proj(pooled), + } + + return SingleQueryHeads() + + +class ConcatFusion(nn.Module): + """A2 baseline: global pooling + concat instead of cross attention.""" + + def __init__(self, token_dim: int, hidden_dim: int, num_queries: int): + super().__init__() + self.num_queries = num_queries + self.mlp = nn.Sequential( + nn.Linear(token_dim * 2, hidden_dim * 2), + nn.GELU(), + nn.Linear(hidden_dim * 2, hidden_dim), + nn.LayerNorm(hidden_dim), + ) + self.query_embed = nn.Parameter(torch.zeros(num_queries, hidden_dim)) + nn.init.trunc_normal_(self.query_embed, std=0.02) + + def forward(self, spatial_tokens: Tensor, wavelet_tokens: Tensor, active_domains=None) -> Tensor: + spatial = spatial_tokens.mean(dim=1) + wavelet = wavelet_tokens.mean(dim=1) + if active_domains is not None: + spatial = spatial * active_domains[:, 0, None].to(spatial.dtype) + wavelet = wavelet * active_domains[:, 1, None].to(wavelet.dtype) + pooled = torch.cat([spatial, wavelet], dim=-1) + context = self.mlp(pooled).unsqueeze(1) # [B, 1, H] + return context + self.query_embed.unsqueeze(0) + + +class DualDomainDegradationTransformer(nn.Module): + def __init__( + self, + token_dim: int = 96, + hidden_dim: int = 192, + embed_dim: int = 128, + num_blocks: int = 4, + num_heads: int = 4, + num_queries: int = 5, + fusion_mode: str = "transformer", + shuffle_wavelet: bool = False, + blocks_per_stage: int = 4, + ): + super().__init__() + if fusion_mode not in ("transformer", "concat"): + raise ValueError("fusion_mode must be 'transformer' or 'concat'") + self.fusion_mode = fusion_mode + self.shuffle_wavelet = shuffle_wavelet + self.hidden_dim = hidden_dim + + self.spatial_branch = SpatialBranch(token_dim=token_dim, blocks_per_stage=blocks_per_stage) + self.wavelet_branch = WaveletBranch(token_dim=token_dim) + self.severity_map_refine = nn.Sequential( + nn.Conv2d(token_dim, token_dim, kernel_size=3, padding=1, groups=token_dim), + nn.Conv2d(token_dim, token_dim, kernel_size=1), + nn.GELU(), + ) + + if fusion_mode == "transformer" and num_queries == 1: + self.fusion = DualDomainFusion( + token_dim=token_dim, + hidden_dim=hidden_dim, + num_queries=1, + num_blocks=num_blocks, + num_heads=num_heads, + ) + self.heads = _single_query_heads(hidden_dim, embed_dim) + elif fusion_mode == "transformer": + if num_queries != NUM_TYPE_CLASSES: + raise ValueError( + "Transformer fusion expects one query per type class " + f"({NUM_TYPE_CLASSES}) or a single generic query (1)." + ) + self.fusion = DualDomainFusion( + token_dim=token_dim, + hidden_dim=hidden_dim, + num_queries=num_queries, + num_blocks=num_blocks, + num_heads=num_heads, + ) + self.heads = DegradationHeads(hidden_dim=hidden_dim, embed_dim=embed_dim) + else: + self.fusion = ConcatFusion( + token_dim=token_dim, hidden_dim=hidden_dim, num_queries=num_queries + ) + self.heads = _single_query_heads(hidden_dim, embed_dim) + + self.severity_map_head = nn.Conv2d(token_dim, NUM_KNOWN_TYPES, kernel_size=1) + + # ------------------------------------------------------------------ + # Domain availability + # ------------------------------------------------------------------ + @staticmethod + def sample_active_domains( + batch_size: int, + device: torch.device, + domains: Sequence[str] = DOMAIN_NAMES, + p_drop: float = 0.0, + ) -> Tensor: + """Per-sample boolean availability [B, 2] with optional dropout.""" + + unknown = set(domains) - set(DOMAIN_NAMES) + if unknown or not domains: + raise ValueError(f"domains must be a non-empty subset of {DOMAIN_NAMES}") + if not 0.0 <= p_drop <= 1.0: + raise ValueError("p_drop must be in [0, 1]") + mask = torch.zeros(batch_size, 2, dtype=torch.bool, device=device) + mask[:, 0] = "spatial" in domains + mask[:, 1] = "wavelet" in domains + if p_drop <= 0 or not mask.any(): + return mask + candidates = torch.rand(batch_size, 2, device=device) < p_drop + active = mask & ~(candidates & mask) + empty = ~active.any(dim=1) + if empty.any(): + # Restore a sole requested domain. If both were requested and + # dropped, retain one at random instead of producing an invalid + # all-masked sample. + active[empty] = mask[empty] + dual_empty = empty & (mask.sum(dim=1) == 2) + if dual_empty.any(): + rows = dual_empty.nonzero(as_tuple=True)[0] + choices = torch.randint(0, 2, (rows.numel(),), device=device) + active[rows] = False + active[rows, choices] = True + return active + + # ------------------------------------------------------------------ + # Forward + # ------------------------------------------------------------------ + def _forward_impl( + self, + image: Tensor, + domains: Sequence[str], + p_drop: float = 0.0, + wavelet_permutation: Tensor | None = None, + ) -> dict: + if image.ndim != 4 or image.shape[1] != 3: + raise ValueError(f"Expected BCHW RGB input, got {tuple(image.shape)}") + if image.shape[-2] != image.shape[-1] or image.shape[-1] % 16 != 0: + raise ValueError("Input must be square with height/width divisible by 16") + spatial = self.spatial_branch(image) + wavelet_tokens = self.wavelet_branch(image)["tokens"] + if self.shuffle_wavelet and (self.training or wavelet_permutation is not None): + if wavelet_permutation is not None: + if wavelet_permutation.shape != (image.shape[0],): + raise ValueError("wavelet_permutation must have shape [B]") + wavelet_tokens = wavelet_tokens[wavelet_permutation] + + active = self.sample_active_domains( + image.shape[0], image.device, domains=domains, p_drop=p_drop + ) + query_states = self.fusion(spatial["tokens"], wavelet_tokens, active) + preds = self.heads(query_states) + preds["spatial_severity_map"] = torch.sigmoid( + self.severity_map_head(self.severity_map_refine(spatial["feat_s8"])) + ) # [B, 4, H/8, W/8] + preds["query_states"] = query_states + preds["active_domains"] = active + return preds + + def encode(self, image: Tensor, domains: Sequence[str] = DOMAIN_NAMES) -> dict: + return self._forward_impl(image, domains) + + def encode_with_modality_dropout( + self, + image: Tensor, + p_drop: float, + domains: Sequence[str] = DOMAIN_NAMES, + ) -> dict: + """Training-time forward pass with stochastic per-sample modality dropout.""" + + return self._forward_impl(image, domains, p_drop=p_drop) + + def forward( + self, + image: Tensor, + domains: Sequence[str] = DOMAIN_NAMES, + p_drop: float = 0.0, + wavelet_permutation: Tensor | None = None, + ) -> dict: + if not 0.0 <= p_drop <= 1.0: + raise ValueError("p_drop must be in [0, 1]") + if p_drop > 0 and self.training: + return self._forward_impl( + image, + domains, + p_drop=p_drop, + wavelet_permutation=wavelet_permutation, + ) + return self._forward_impl( + image, + domains, + wavelet_permutation=wavelet_permutation, + ) + + # ------------------------------------------------------------------ + # Domain-agreement support + # ------------------------------------------------------------------ + def solo_domain_forward(self, image: Tensor, domain: str) -> dict: + """Prediction using exactly one domain (for L_domain_agreement).""" + + if domain not in DOMAIN_NAMES: + raise ValueError(f"domain must be one of {DOMAIN_NAMES}") + return self.encode(image, domains=(domain,)) + + +class SeverityMapLoss(nn.Module): + """Weak supervision for the spatial severity map. + + Region-level labels do not exist in Phase 1, so the map is pulled toward + the broadcast global severity of its active types. This keeps the head + calibrated globally until region annotations are introduced. + """ + + def __init__(self, weight: float = 0.25): + super().__init__() + self.weight = weight + + def forward( + self, + severity_map: Tensor, + severity_target: Tensor, + spatial_active: Tensor | None = None, + ) -> Tensor: + target = severity_target[:, :, None, None].expand_as(severity_map) + error = F.smooth_l1_loss(severity_map, target, beta=0.1, reduction="none") + if spatial_active is None: + return self.weight * error.mean() + mask = spatial_active[:, None, None, None].to(error.dtype) + denominator = mask.sum() * error.shape[1] * error.shape[2] * error.shape[3] + if denominator == 0: + return error.new_zeros(()) + return self.weight * (error * mask).sum() / denominator + + +def create_degradation_transformer( + ablation: Optional[str] = None, + loss_config: Optional[LossConfig] = None, + **overrides, +) -> Tuple[DualDomainDegradationTransformer, LossConfig]: + """Build the model (+ default losses) for an ablation gate preset. + + A0 pixel-only / A1 wavelet-only are enforced at training time through + ``domains``; A2 swaps cross attention for concat fusion; A3 uses a single + generic query; A4/A5 (and default) use per-type degradation queries; + A6 adds the shuffled-wavelet control. + """ + + config = loss_config or LossConfig() + kwargs = dict(overrides) + + if ablation == "A2": + kwargs.setdefault("fusion_mode", "concat") + kwargs.setdefault("num_queries", 1) + elif ablation == "A3": + kwargs.setdefault("num_queries", 1) + elif ablation == "A6": + kwargs.setdefault("shuffle_wavelet", True) + elif ablation not in (None, "A0", "A1", "A4", "A5"): + raise ValueError(f"Unknown ablation preset: {ablation}") + + model = DualDomainDegradationTransformer(**kwargs) + # A0-A4 isolate architecture. Pair/clean regularization enters only at + # A5; A6 is the same objective with shuffled wavelet correspondence. + if ablation in ("A0", "A1", "A2", "A3", "A4"): + config.lambda_clean_zero = 0.0 + config.lambda_pair = 0.0 + if ablation in ("A0", "A1", "A6"): + config.lambda_domain_agreement = 0.0 + return model, config + + +def count_trainable_parameters(model: nn.Module) -> int: + return sum(p.numel() for p in model.parameters() if p.requires_grad) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/spatial_branch.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/spatial_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..0df4ded815fe91cf2a43ffd3edfa8c6978c63538 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/spatial_branch.py @@ -0,0 +1,114 @@ +"""Pixel / illumination spatial branch of the degradation transformer. + +Low-level hierarchical convolution stem. The input is augmented with physics +motivated channels that make blur, noise and low-light artifacts visible to a +small CNN: + +* RGB (3ch) +* linear luminance ``Y`` +* log luminance ``log(Y + eps)`` (critical for low-light) +* local illumination map (heavy low-pass of ``Y``) +* gradient magnitude (Sobel on ``Y``) + +Pipeline: conv stem stride 4 -> patch merge -> stage block -> severity map +head tap at H/8 -> patch merge -> stage block -> 16x16 tokens (dim 96). +""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +LUMINANCE_WEIGHTS = (0.2126, 0.7152, 0.0722) +LOG_EPS = 1e-4 + + +def _luminance(image: Tensor) -> Tensor: + weights = image.new_tensor(LUMINANCE_WEIGHTS).view(1, 3, 1, 1) + return (image * weights).sum(dim=1, keepdim=True) + + +def _sobel_magnitude(luma: Tensor) -> Tensor: + kernel_x = luma.new_tensor( + [[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]] + ).view(1, 1, 3, 3) + kernel_y = kernel_x.transpose(-2, -1).contiguous() + padded = F.pad(luma, (1, 1, 1, 1), mode="reflect") + gx = F.conv2d(padded, kernel_x) + gy = F.conv2d(padded, kernel_y) + return torch.sqrt(gx * gx + gy * gy + 1e-12) + + +class ConvStageBlock(nn.Module): + """Depthwise-separable residual block with pointwise expansion.""" + + def __init__(self, dim: int, expansion: int = 4): + super().__init__() + hidden = dim * expansion + self.norm = nn.GroupNorm(1, dim) + self.dw = nn.Conv2d(dim, dim, 3, padding=1, groups=dim) + self.pw1 = nn.Conv2d(dim, hidden, 1) + self.pw2 = nn.Conv2d(hidden, dim, 1) + + def forward(self, x: Tensor) -> Tensor: + y = self.norm(x) + y = self.dw(y) + y = self.pw2(F.gelu(self.pw1(y))) + return x + y + + +class PatchMerge(nn.Module): + """Merge a 2x2 neighborhood into one token; keeps the channel width.""" + + def __init__(self, dim: int): + super().__init__() + self.norm = nn.LayerNorm(4 * dim) + self.proj = nn.Linear(4 * dim, dim) + + def forward(self, x: Tensor) -> Tensor: + b, c, h, w = x.shape + x = x.reshape(b, c, h // 2, 2, w // 2, 2) + x = x.permute(0, 2, 4, 3, 5, 1).reshape(b, h // 2, w // 2, 4 * c) + return self.proj(self.norm(x)).permute(0, 3, 1, 2) + + +class SpatialBranch(nn.Module): + """Hierarchical pixel/illumination encoder. + + Returns spatial tokens at H/16 (default 16x16 for 256px crops, dim 96) plus + the H/8 feature map used by the spatial severity-map head. + """ + + def __init__(self, token_dim: int = 96, in_channels: int = 7, blocks_per_stage: int = 2): + super().__init__() + self.token_dim = token_dim + self.stem = nn.Sequential( + nn.Conv2d(in_channels, token_dim, kernel_size=7, stride=4, padding=3), + nn.GroupNorm(1, token_dim), + nn.GELU(), + ConvStageBlock(token_dim), + ) + self.merge_s8 = PatchMerge(token_dim) + self.stage_s8 = nn.Sequential(*[ConvStageBlock(token_dim) for _ in range(blocks_per_stage)]) + self.merge_s16 = PatchMerge(token_dim) + self.stage_s16 = nn.Sequential(*[ConvStageBlock(token_dim) for _ in range(blocks_per_stage)]) + + @staticmethod + def build_input(image: Tensor) -> Tensor: + if image.ndim != 4 or image.shape[1] != 3: + raise ValueError(f"Expected NCHW RGB image, got {tuple(image.shape)}") + luma = _luminance(image) + log_luma = torch.log(luma.clamp_min(LOG_EPS)) + illumination = F.avg_pool2d( + luma, kernel_size=15, stride=1, padding=7, count_include_pad=False + ) + gradient = _sobel_magnitude(luma) + return torch.cat([image, luma, log_luma, illumination, gradient], dim=1) + + def forward(self, image: Tensor) -> dict: + feat = self.stem(self.build_input(image)) # H/4 + feat_s8 = self.stage_s8(self.merge_s8(feat)) # H/8 + feat_s16 = self.stage_s16(self.merge_s16(feat_s8)) # H/16 + tokens = feat_s16.flatten(2).transpose(1, 2) # [B, (H/16)^2, C] + return {"tokens": tokens, "feat_s8": feat_s8, "feat_s16": feat_s16} diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/transformer.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/transformer.py new file mode 100644 index 0000000000000000000000000000000000000000..c483166aab844f12b9d3535c1c4a76b5e8a33ecc --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/transformer.py @@ -0,0 +1,231 @@ +"""Dual-domain fusion transformer with degradation queries. + +Five learned queries (one per known degradation plus ``unknown``) cross-attend +into the spatial tokens and the wavelet tokens, then pass an FFN. No full +self-attention over thousands of tokens is used; only the five queries do the +heavy lifting, which keeps the block cheap. + +Per-domain updates can be disabled per sample, which implements explicit +domain selection and stochastic modality dropout without ever presenting an +all-masked memory to ``MultiheadAttention``. +""" + +from __future__ import annotations + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from .constants import NUM_TYPE_CLASSES, NUM_KNOWN_TYPES + + +class CrossAttentionBlock(nn.Module): + """Pre-norm multi-head cross attention with residual.""" + + def __init__(self, hidden_dim: int, num_heads: int): + super().__init__() + self.norm_q = nn.LayerNorm(hidden_dim) + self.norm_kv = nn.LayerNorm(hidden_dim) + self.attn = nn.MultiheadAttention(hidden_dim, num_heads, batch_first=True, dropout=0.1) + # Initialize attention weights + for p in self.attn.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + + def forward( + self, + queries: Tensor, + kv: Tensor, + active: Tensor | None = None, + ) -> Tensor: + residual = queries + q = self.norm_q(queries) + k = self.norm_kv(kv) + out, _ = self.attn(q, k, k, need_weights=False) + if active is not None: + out = out * active[:, None, None].to(dtype=out.dtype) + return residual + out + + +class FeedForwardBlock(nn.Module): + def __init__(self, hidden_dim: int, expansion: int = 4): + super().__init__() + self.norm = nn.LayerNorm(hidden_dim) + self.fc1 = nn.Linear(hidden_dim, hidden_dim * expansion) + self.fc2 = nn.Linear(hidden_dim * expansion, hidden_dim) + # Initialize + nn.init.xavier_uniform_(self.fc1.weight) + nn.init.xavier_uniform_(self.fc2.weight) + + def forward(self, x: Tensor) -> Tensor: + return x + self.fc2(F.gelu(self.fc1(self.norm(x)))) + + +class QuerySelfAttention(nn.Module): + """Self-attention among the handful of degradation queries. + + Cheap (five tokens) and lets queries calibrate each other, which + stabilizes the per-type confidence head. + """ + + def __init__(self, hidden_dim: int, num_heads: int): + super().__init__() + self.norm = nn.LayerNorm(hidden_dim) + self.attn = nn.MultiheadAttention(hidden_dim, num_heads, batch_first=True, dropout=0.1) + # Initialize attention weights + for p in self.attn.parameters(): + if p.dim() > 1: + nn.init.xavier_uniform_(p) + + def forward(self, queries: Tensor) -> Tensor: + x = self.norm(queries) + out, _ = self.attn(x, x, x, need_weights=False) + return queries + out + + +class DualDomainFusion(nn.Module): + """Query-based dual-domain transformer. + + Args: + token_dim: input width of spatial and wavelet tokens. + hidden_dim: transformer width. + num_queries: number of degradation queries (5 by default). + num_blocks: number of [cross(spatial), cross(wavelet), FFN] blocks. + num_heads: attention heads. + """ + + SPATIAL_DOMAIN = 0 + WAVELET_DOMAIN = 1 + + def __init__( + self, + token_dim: int = 96, + hidden_dim: int = 192, + num_queries: int = 5, + num_blocks: int = 4, + num_heads: int = 4, + ): + super().__init__() + self.hidden_dim = hidden_dim + self.num_queries = num_queries + self.input_proj_spatial = nn.Linear(token_dim, hidden_dim) + self.input_proj_wavelet = nn.Linear(token_dim, hidden_dim) + self.domain_embed = nn.Parameter(torch.zeros(2, hidden_dim)) + nn.init.xavier_uniform_(self.domain_embed) + + # Learnable positional embedding stored on a 16x16 grid; interpolated + # for other spatial token resolutions. + self.pos_spatial = nn.Parameter(torch.zeros(256, hidden_dim)) + nn.init.xavier_uniform_(self.pos_spatial) + self.pos_wavelet = nn.Parameter(torch.zeros(20, hidden_dim)) + nn.init.xavier_uniform_(self.pos_wavelet) + + # Initialize queries with class-specific patterns + self.queries = nn.Parameter(torch.zeros(num_queries, hidden_dim)) + nn.init.xavier_uniform_(self.queries) + # Add small bias to each query to make them initially different + for i in range(num_queries): + self.queries.data[i, i * (hidden_dim // num_queries):(i + 1) * (hidden_dim // num_queries)] += 0.1 + + self.cross_spatial = nn.ModuleList( + [CrossAttentionBlock(hidden_dim, num_heads) for _ in range(num_blocks)] + ) + self.cross_wavelet = nn.ModuleList( + [CrossAttentionBlock(hidden_dim, num_heads) for _ in range(num_blocks)] + ) + self.query_self_attn = nn.ModuleList( + [QuerySelfAttention(hidden_dim, num_heads) for _ in range(num_blocks)] + ) + self.ffns = nn.ModuleList( + [FeedForwardBlock(hidden_dim) for _ in range(num_blocks)] + ) + self.final_norm = nn.LayerNorm(hidden_dim) + + def _interpolate_pos(self, grid_h: int, grid_w: int) -> Tensor: + base = self.pos_spatial.reshape(16, 16, self.hidden_dim).permute(2, 0, 1) + if grid_h == 16 and grid_w == 16: + return self.pos_spatial + pos = F.interpolate(base.unsqueeze(0), size=(grid_h, grid_w), mode="bicubic", align_corners=False) + return pos.squeeze(0).flatten(1).t() + + def forward( + self, + spatial_tokens: Tensor, + wavelet_tokens: Tensor, + active_domains: Tensor = None, + ) -> Tensor: + """Return final query states [B, num_queries, hidden]. + + ``active_domains`` [B, 2]: optional per-sample domain availability; + used for modality dropout and ablations. + """ + + b = spatial_tokens.shape[0] + kv_spatial = self.input_proj_spatial(spatial_tokens) + kv_wavelet = self.input_proj_wavelet(wavelet_tokens) + + grid_h = int(kv_spatial.shape[1] ** 0.5) + pos = self._interpolate_pos(grid_h, grid_h)[: kv_spatial.shape[1]] + kv_spatial = kv_spatial + pos + self.domain_embed[self.SPATIAL_DOMAIN] + + n_wav = kv_wavelet.shape[1] + kv_wavelet = ( + kv_wavelet + + self.pos_wavelet[:n_wav] + + self.domain_embed[self.WAVELET_DOMAIN] + ) + + if active_domains is None: + active_domains = torch.ones(b, 2, dtype=torch.bool, device=kv_spatial.device) + if active_domains.shape != (b, 2): + raise ValueError("active_domains must be [B, 2]") + if not active_domains.any(dim=1).all(): + raise ValueError("Every sample needs at least one active domain") + + queries = self.queries.unsqueeze(0).expand(b, -1, -1) + for cross_s, cross_w, self_attn, ffn in zip( + self.cross_spatial, self.cross_wavelet, self.query_self_attn, self.ffns + ): + queries = cross_s( + queries, + kv_spatial, + active_domains[:, self.SPATIAL_DOMAIN], + ) + queries = cross_w( + queries, + kv_wavelet, + active_domains[:, self.WAVELET_DOMAIN], + ) + queries = self_attn(queries) + queries = ffn(queries) + return self.final_norm(queries) + + +class DegradationHeads(nn.Module): + """Prediction heads on top of the query states.""" + + def __init__(self, hidden_dim: int = 192, embed_dim: int = 128): + super().__init__() + # Query k owns class k: one logit per query -> [B, 5]. + self.type_head = nn.Linear(hidden_dim, 1) + # Known-type queries predict their own normalized severity. + self.severity_head = nn.Linear(hidden_dim, 1) + self.embedding_head = nn.Sequential( + nn.Linear(hidden_dim * NUM_TYPE_CLASSES, hidden_dim), + nn.GELU(), + nn.Linear(hidden_dim, embed_dim), + ) + + def forward(self, query_states: Tensor) -> dict: + type_logits = self.type_head(query_states).squeeze(-1) # [B, 5] + severity = torch.sigmoid( + self.severity_head(query_states[:, :NUM_KNOWN_TYPES]).squeeze(-1) + ) # [B, 4] + flat = query_states.flatten(1) + embedding = self.embedding_head(flat) # [B, embed_dim] + return { + "type_logits": type_logits, + "confidence": torch.sigmoid(type_logits), + "severity": severity, + "degradation_embedding": embedding, + } diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/wavelet_branch.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/wavelet_branch.py new file mode 100644 index 0000000000000000000000000000000000000000..2f321392d2e153b4e30602b6cf95964672af5f63 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/degradation/wavelet_branch.py @@ -0,0 +1,161 @@ +"""Wavelet frequency branch of the degradation transformer. + +Fixed 3-level Haar DWT. Every band is pooled to a common 4x4 grid (mean map, +local RMS energy map, log-energy map) before concatenation, so all bands +contribute tokens at the same resolution. A global summary vector adds the +low-light aware statistics that pure high-frequency descriptors miss: + +* LL1/LL2/LL3 energies and the log ratio of LL vs high-frequency energy +* local contrast relative to LL +* dark-region occupancy at several luminance thresholds +* per-band global log-energy scalars + +Output: 16 map tokens + 4 summary tokens of dim ``token_dim``. +""" + +from __future__ import annotations + +from typing import Dict + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +POOL = 4 +DARK_THRESHOLDS = (0.05, 0.10, 0.20) +BAND_ORDER = ("lh", "hl", "hh") + + +def haar_dwt3(image: Tensor) -> Dict[str, Tensor]: + """Return the twelve Haar bands of a BCHW image.""" + + def step(x: Tensor): + h, w = x.shape[-2] // 2 * 2, x.shape[-1] // 2 * 2 + x = x[..., :h, :w] + ll = ( + x[..., 0::2, 0::2] + + x[..., 0::2, 1::2] + + x[..., 1::2, 0::2] + + x[..., 1::2, 1::2] + ) / 2.0 + lh = ( + x[..., 0::2, 0::2] + + x[..., 0::2, 1::2] + - x[..., 1::2, 0::2] + - x[..., 1::2, 1::2] + ) / 2.0 + hl = ( + x[..., 0::2, 0::2] + - x[..., 0::2, 1::2] + + x[..., 1::2, 0::2] + - x[..., 1::2, 1::2] + ) / 2.0 + hh = ( + x[..., 0::2, 0::2] + - x[..., 0::2, 1::2] + - x[..., 1::2, 0::2] + + x[..., 1::2, 1::2] + ) / 2.0 + return ll, lh, hl, hh + + ll1, lh1, hl1, hh1 = step(image) + ll2, lh2, hl2, hh2 = step(ll1) + ll3, lh3, hl3, hh3 = step(ll2) + return { + "ll1": ll1, "lh1": lh1, "hl1": hl1, "hh1": hh1, + "ll2": ll2, "lh2": lh2, "hl2": hl2, "hh2": hh2, + "ll3": ll3, "lh3": lh3, "hl3": hl3, "hh3": hh3, + } + + +class WaveletBranch(nn.Module): + def __init__(self, channels: int = 3, token_dim: int = 96, num_summary_tokens: int = 4): + super().__init__() + self.token_dim = token_dim + self.num_summary_tokens = num_summary_tokens + self.band_features = 3 * channels # mean map, rms map, log-rms map + num_bands = 12 + self.map_proj = nn.Sequential( + nn.Conv2d(num_bands * self.band_features, token_dim * 2, kernel_size=1), + nn.GELU(), + nn.Conv2d(token_dim * 2, token_dim, kernel_size=1), + nn.GroupNorm(1, token_dim), + nn.GELU(), + ) + # Level LL/HF energies + ratio + contrast (4 x 3 levels) + # + occupancy(3) + luma stats(2) + per-band log-energy(12) + stats_dim = 29 + self.summary_proj = nn.Sequential( + nn.Linear(stats_dim, token_dim * num_summary_tokens), + nn.GELU(), + nn.LayerNorm(token_dim * num_summary_tokens), + ) + + def band_maps(self, bands: Dict[str, Tensor]) -> Tensor: + maps = [] + for level in ("1", "2", "3"): + for prefix in ("ll",) + BAND_ORDER: + band = bands[f"{prefix}{level}"] + pooled = F.adaptive_avg_pool2d(band, POOL) + rms = torch.sqrt( + F.adaptive_avg_pool2d(band * band, POOL).clamp_min(1e-8) + ) + maps.extend([pooled, rms, torch.log(rms + 1e-4)]) + return torch.cat(maps, dim=1) + + @staticmethod + def global_stats(bands: Dict[str, Tensor]) -> Tensor: + features = [] + for level in ("1", "2", "3"): + hf_rms = torch.sqrt( + F.adaptive_avg_pool2d( + sum((bands[f"{p}{level}"] ** 2 for p in BAND_ORDER)), POOL + ).clamp_min(1e-8) + ).mean(dim=1) # [B, 4, 4] + ll_abs = bands[f"ll{level}"].abs().mean(dim=1, keepdim=True) + ll_pooled = F.adaptive_avg_pool2d(ll_abs, POOL).squeeze(1) # [B, 4, 4] + ll_energy = ll_pooled.mean(dim=(1, 2)) + hf_energy = hf_rms.mean(dim=(1, 2)) + features.append(torch.log(ll_energy + 1e-4)) + features.append(torch.log(hf_energy + 1e-4)) + # LL vs high-frequency energy ratio (log space). + features.append(torch.log((ll_energy + 1e-4) / (hf_energy + 1e-4))) + # Local contrast relative to LL. + contrast = (hf_rms / (ll_pooled + 0.05)).mean(dim=(1, 2)) + features.append(torch.log(contrast + 1e-4)) + if level == "1": + weights = bands["ll1"].new_tensor( + [0.2126, 0.7152, 0.0722] + ).view(1, 3, 1, 1) + # Haar LL1 uses /2, so its DC response is 2x the local RGB + # mean. Undo that scale before applying raw-image thresholds. + luma = (bands["ll1"] * weights).sum(dim=1) / 2.0 + for threshold in DARK_THRESHOLDS: + features.append((luma < threshold).float().mean(dim=(1, 2))) + features.append(luma.mean(dim=(1, 2))) + features.append(luma.std(dim=(1, 2))) + for name in ( + "ll1", "lh1", "hl1", "hh1", + "ll2", "lh2", "hl2", "hh2", + "ll3", "lh3", "hl3", "hh3", + ): + band = bands[name] + energy = (band * band).mean(dim=(1, 2, 3)).clamp_min(1e-8) + features.append(torch.log(energy)) + return torch.stack(features, dim=1) + + def forward(self, image: Tensor) -> dict: + if image.ndim != 4 or image.shape[1] != 3: + raise ValueError(f"Expected NCHW RGB image, got {tuple(image.shape)}") + bands = haar_dwt3(image) + map_feats = self.map_proj(self.band_maps(bands)) # [B, D, 4, 4] + b, d = map_feats.shape[:2] + map_tokens = map_feats.flatten(2).transpose(1, 2) # [B, 16, D] + stats = self.global_stats(bands) + summary = self.summary_proj(stats).reshape(b, self.num_summary_tokens, d) + tokens = torch.cat([map_tokens, summary], dim=1) + return {"tokens": tokens, "stats": stats, "bands": bands} + + @staticmethod + def num_tokens() -> int: + return POOL * POOL + 4 diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__init__.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4b52bf861c48f7c677a058b08d04d1902d46c3ad --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__init__.py @@ -0,0 +1,48 @@ +"""Graph Encoder Package.""" + +from .representation import ( + GraphRepresentation, + BranchAnchor, + GraphConfig, + SEMANTIC_BRANCH_NAMES, + SEMANTIC_BRANCH_COLORS, + aggregate_graph_condition, +) + +from .encoder import ( + CleanRootAnchor, + SemanticBranch, + FreeLatentNodes, + SpatialEncoder, + GraphStatePredictor, + NodeTokenGenerator, + BlindDegradationGraphEncoder, + create_graph_encoder, +) + +from .losses import ( + GraphLoss, + RootLoss, + DistillationLoss, + BranchSeparationLoss, + GeodesicSeverityLoss, + RankingLoss, + ContentInvarianceLoss, + CompositionLoss, + SparseRoutingLoss, + UtilityLoss, + TypeClassificationLoss, + CombinedGraphLoss, +) + +__all__ = [ + "GraphRepresentation", "BranchAnchor", "GraphConfig", + "SEMANTIC_BRANCH_NAMES", "SEMANTIC_BRANCH_COLORS", + "CleanRootAnchor", "SemanticBranch", "FreeLatentNodes", + "SpatialEncoder", "GraphStatePredictor", "NodeTokenGenerator", + "BlindDegradationGraphEncoder", "create_graph_encoder", + "GraphLoss", "RootLoss", "DistillationLoss", "BranchSeparationLoss", + "GeodesicSeverityLoss", "RankingLoss", "ContentInvarianceLoss", + "CompositionLoss", "SparseRoutingLoss", "UtilityLoss", + "TypeClassificationLoss", "CombinedGraphLoss", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/__init__.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6bc90573766182d33cc65eda576bedc34165878 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/__init__.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/clean_relative.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/clean_relative.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5a75285c2431e22a7b59c5d36bb0c87ff22ba831 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/clean_relative.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/encoder.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/encoder.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d0fbe34a422d430668a941feff32db5e4c1cd90 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/encoder.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/hvi.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/hvi.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4df29429ac5479afbbb926615f84725777c271fb Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/hvi.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/losses.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/losses.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d6cff5c79b54ff36513eb89c02073cb3668fb83 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/losses.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/representation.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/representation.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39b1445760c5e28adf5ff7c2da8c741ed57ccf15 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/__pycache__/representation.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/clean_relative.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/clean_relative.py new file mode 100644 index 0000000000000000000000000000000000000000..8fb54b05404719139659f10e11e0568717de83ea --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/clean_relative.py @@ -0,0 +1,382 @@ +"""Experimental clean-relative descriptors for seven degradation factors. + +The blind encoder consumes only a degraded image. During paired training the +teacher uses a difference of shared evidence features, making its displacement +exactly zero for identical inputs. This identity does not imply that feature +subtraction removes scene information: controlled cross-scene tests are needed. + +This module has its own dictionary API; it is not a drop-in replacement for the +legacy six-node Phase-2 representation. A globally orthonormal basis gives +unambiguous additive coordinates, including two free factors, and an orthogonal +residual. Factor presence is independent sigmoid classification, not an energy +softmax. Spatial effects are retained separately from the global descriptor. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Dict, Optional, Tuple, Union + +import torch +import torch.nn.functional as F +from torch import Tensor, nn + +from ..degradation.spatial_branch import SpatialBranch +from ..degradation.wavelet_branch import WaveletBranch + + +TYPE_ORDER = ("rain", "noise", "haze", "lowlight", "snow", "blur", "jpeg") +MODEL_VERSION = "clean_relative_seven_v1" +FactorIndex = Union[int, Tensor] + + +@dataclass(frozen=True) +class CleanRelativeConfig: + type_order: Tuple[str, ...] = TYPE_ORDER + num_free: int = 2 + node_dim: int = 256 + rank: int = 8 + token_dim: int = 64 + hidden_dim: int = 128 + content_channels: int = 64 + num_heads: int = 4 + num_blocks: int = 2 + blocks_per_stage: int = 1 + interaction_hidden: int = 128 + decoder_width: int = 64 + + def __post_init__(self) -> None: + # JSON checkpoint metadata round-trips tuples through lists. + object.__setattr__(self, "type_order", tuple(self.type_order)) + if self.type_order != TYPE_ORDER: + raise ValueError("type_order must follow the canonical seven-factor order") + if self.num_free < 1: + raise ValueError("at least one free factor is required") + positive = (self.node_dim, self.rank, self.token_dim, self.hidden_dim, + self.content_channels, self.num_heads, self.num_blocks, + self.blocks_per_stage, self.interaction_hidden, self.decoder_width) + if any(value <= 0 for value in positive): + raise ValueError("dimensions, rank and block counts must be positive") + if self.num_nodes * self.rank > self.node_dim: + raise ValueError("num_nodes * rank must not exceed node_dim") + if self.hidden_dim % self.num_heads: + raise ValueError("hidden_dim must be divisible by num_heads") + + @property + def num_known(self) -> int: + return len(self.type_order) + + @property + def num_nodes(self) -> int: + return self.num_known + self.num_free + + +class _EvidenceBlock(nn.Module): + """Small query bank reads spatial and wavelet memories, then interacts. + + No stochastic dropout or batch statistics are used, so shared evidence is + identical for identical images even during training. Image tokens are never + self-attended, keeping memory linear in the number of input patches. + """ + + def __init__(self, dim: int, heads: int) -> None: + super().__init__() + self.spatial_norm = nn.LayerNorm(dim) + self.wavelet_norm = nn.LayerNorm(dim) + self.query_norm_s = nn.LayerNorm(dim) + self.query_norm_w = nn.LayerNorm(dim) + self.query_norm_self = nn.LayerNorm(dim) + self.spatial_attention = nn.MultiheadAttention(dim, heads, dropout=0, batch_first=True) + self.wavelet_attention = nn.MultiheadAttention(dim, heads, dropout=0, batch_first=True) + self.node_attention = nn.MultiheadAttention(dim, heads, dropout=0, batch_first=True) + self.ffn = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, 2 * dim), + nn.GELU(), nn.Linear(2 * dim, dim)) + + def forward(self, queries: Tensor, spatial: Tensor, wavelet: Tensor) -> Tensor: + memory = self.spatial_norm(spatial) + update, _ = self.spatial_attention(self.query_norm_s(queries), memory, memory, + need_weights=False) + queries = queries + update + memory = self.wavelet_norm(wavelet) + update, _ = self.wavelet_attention(self.query_norm_w(queries), memory, memory, + need_weights=False) + queries = queries + update + normalized = self.query_norm_self(queries) + update, _ = self.node_attention(normalized, normalized, normalized, need_weights=False) + queries = queries + update + return queries + self.ffn(queries) + + +def _factor_indices(index: FactorIndex, batch: int, count: int, device: torch.device) -> Tensor: + if isinstance(index, int): + result = torch.full((batch,), index, dtype=torch.long, device=device) + elif isinstance(index, Tensor): + if index.dtype not in (torch.int8, torch.int16, torch.int32, torch.int64, torch.uint8): + raise ValueError("factor indices must be integers") + result = index.to(device=device, dtype=torch.long) + if result.ndim == 0: + result = result.expand(batch) + else: + raise TypeError("factor index must be an integer or integer tensor") + if result.shape != (batch,): + raise ValueError("factor indices must have shape [B]") + if bool(((result < 0) | (result >= count)).any()): + raise ValueError("factor index out of range") + return result + + +class OrderedInteraction(nn.Module): + """Shared, order-sensitive departure from additivity in descriptor space. + + `first_type` is applied first, `second_type` second. The architecture allows + order dependence; only matched operator-order supervision gives it meaning. + Multiplicative norm gates make either zero factor an exact boundary, even + when the learned MLP has biases. This is not a claim of causal discovery. + """ + + def __init__(self, dim: int, num_types: int, hidden: int) -> None: + super().__init__() + self.dim = dim + self.num_types = num_types + self.type_embedding = nn.Embedding(num_types, 16) + self.net = nn.Sequential(nn.Linear(2 * dim + 32, hidden), nn.SiLU(), + nn.Linear(hidden, dim)) + + def forward(self, first: Tensor, second: Tensor, + first_type: FactorIndex, second_type: FactorIndex) -> Tensor: + if first.ndim != 2 or first.shape != second.shape or first.shape[1] != self.dim: + raise ValueError("interaction inputs must both have shape [B, node_dim]") + ids_a = _factor_indices(first_type, first.shape[0], self.num_types, first.device) + ids_b = _factor_indices(second_type, first.shape[0], self.num_types, first.device) + norms_a = torch.linalg.vector_norm(first.float(), dim=1, keepdim=True) + norms_b = torch.linalg.vector_norm(second.float(), dim=1, keepdim=True) + boundary_gate = (norms_a / (1 + norms_a)) * (norms_b / (1 + norms_b)) + features = torch.cat((first, second, self.type_embedding(ids_a), self.type_embedding(ids_b)), dim=1) + return self.net(features).float() * boundary_gate + + +class _ProxyUpsampleBlock(nn.Module): + """Learn four sub-pixel phases, then condition the higher-resolution map.""" + + def __init__(self, in_channels: int, out_channels: int, node_dim: int) -> None: + super().__init__() + self.projection = nn.Conv2d(in_channels, 4 * out_channels, 3, padding=1) + self.shuffle = nn.PixelShuffle(2) + self.condition = nn.Linear(node_dim, 2 * out_channels, bias=False) + + def forward(self, features: Tensor, delta: Tensor) -> Tensor: + features = self.shuffle(self.projection(features)) + scale, shift = self.condition(delta).chunk(2, dim=1) + features = features * (1 + 0.5 * scale.tanh()[:, :, None, None]) + shift[:, :, None, None] + return F.silu(features) + + +class CleanRelativeGraphEncoder(nn.Module): + """Dual-domain evidence encoder with a paired training-only reference. + + Public output keys (B=batch, N=known+free, R=rank, D=node_dim): + content: B,C,H/8,W/8; delta/residual: B,D; basis: D,N*R; + presence_logits/severity: B,7 (severity in [0,1]); + coefficients: B,N,R; amplitudes: B,N; node_tokens: B,N,D; + spatial: B,7,H/8,W/8 in [0,1]; photometric: B,8. + + Presence and severity are supervised outputs, not constrained to zero in + an untrained clean encoder. Node tokens are per-factor basis contributions; + their sum plus the residual equals delta and every token is zero at delta=0. + Canonical slot indices identify factors; there is no untrained token adapter + or separate identity embedding. `photometric` is an auxiliary regressed + descriptor, not automatically a physical affine transformation. + """ + + def __init__(self, config: Optional[CleanRelativeConfig] = None) -> None: + super().__init__() + self.config = config or CleanRelativeConfig() + cfg = self.config + self.spatial_branch = SpatialBranch(token_dim=cfg.token_dim, + blocks_per_stage=cfg.blocks_per_stage) + self.wavelet_branch = WaveletBranch(token_dim=cfg.token_dim) + self.spatial_projection = nn.Linear(cfg.token_dim, cfg.hidden_dim) + self.wavelet_projection = nn.Linear(cfg.token_dim, cfg.hidden_dim) + self.position_projection = nn.Linear(2, cfg.hidden_dim, bias=False) + self.wavelet_position = nn.Parameter(torch.randn(1, 20, cfg.hidden_dim) * 0.02) + self.queries = nn.Parameter(torch.randn(1, cfg.num_nodes + 1, cfg.hidden_dim) * 0.02) + self.evidence_blocks = nn.ModuleList([ + _EvidenceBlock(cfg.hidden_dim, cfg.num_heads) for _ in range(cfg.num_blocks) + ]) + self.evidence_norm = nn.LayerNorm(cfg.hidden_dim) + self.content_projector = nn.Conv2d(cfg.token_dim, cfg.content_channels, 1) + # A bias-free map preserves exact pair identity after feature subtraction. + self.delta_head = nn.Linear(cfg.hidden_dim, cfg.node_dim, bias=False) + self.basis_raw = nn.Parameter(torch.randn(cfg.node_dim, cfg.num_nodes * cfg.rank) * 0.02) + self.presence_head = nn.Linear(cfg.node_dim, cfg.num_known) + self.severity_head = nn.Linear(cfg.node_dim, cfg.num_known) + self.spatial_head = nn.Conv2d(cfg.token_dim, cfg.num_known, 1, bias=False) + self.photometric_head = nn.Linear(cfg.node_dim, 8, bias=False) + self.interaction = OrderedInteraction(cfg.node_dim, cfg.num_known, cfg.interaction_hidden) + self.decoder_content = nn.Sequential( + nn.Conv2d(cfg.content_channels, cfg.decoder_width, 3, padding=1), nn.SiLU(), + nn.Conv2d(cfg.decoder_width, cfg.decoder_width, 3, padding=1), nn.SiLU(), + ) + self.decoder_condition = nn.Linear(cfg.node_dim, 2 * cfg.decoder_width, bias=False) + # H/8 -> H/4 -> H/2 -> H. Narrower maps keep native-resolution proxy + # training inexpensive (default widths 32,16,8 at the three stages). + widths = tuple(max(8, cfg.decoder_width // scale) for scale in (2, 4, 8)) + previous_width = cfg.decoder_width + self.decoder_upsamplers = nn.ModuleList() + for width in widths: + self.decoder_upsamplers.append(_ProxyUpsampleBlock(previous_width, width, cfg.node_dim)) + previous_width = width + self.decoder_output = nn.Conv2d(previous_width, 3, 3, padding=1) + + def _evidence(self, image: Tensor) -> Dict[str, Tensor]: + if image.ndim != 4 or image.shape[1] != 3: + raise ValueError("image must have shape [B,3,H,W]") + if min(image.shape[-2:]) < 32 or any(size % 16 for size in image.shape[-2:]): + raise ValueError("image dimensions must be >=32 and divisible by 16") + spatial = self.spatial_branch(image) + # Wavelet moments and log ratios stay in fp32 under mixed precision. + with torch.autocast(device_type=image.device.type, enabled=False): + wavelet = self.wavelet_branch(image.float())["tokens"] + spatial_tokens = self.spatial_projection(spatial["tokens"]) + height, width = spatial["feat_s16"].shape[-2:] + ys = torch.linspace(-1, 1, height, device=image.device, dtype=spatial_tokens.dtype) + xs = torch.linspace(-1, 1, width, device=image.device, dtype=spatial_tokens.dtype) + y_grid, x_grid = torch.meshgrid(ys, xs, indexing="ij") + positions = torch.stack((y_grid, x_grid), dim=-1).reshape(1, -1, 2) + spatial_tokens = spatial_tokens + self.position_projection(positions) + wavelet_tokens = self.wavelet_projection(wavelet) + self.wavelet_position + queries = self.queries.expand(image.shape[0], -1, -1) + for block in self.evidence_blocks: + queries = block(queries, spatial_tokens, wavelet_tokens) + return { + "global": self.evidence_norm(queries[:, 0]), + "content": self.content_projector(spatial["feat_s8"]), + "spatial_features": spatial["feat_s8"], + } + + def orthonormal_basis(self) -> Tensor: + """One QR over the full bank: no overlapping-projector double counting.""" + with torch.autocast(device_type=self.basis_raw.device.type, enabled=False): + basis, triangular = torch.linalg.qr(self.basis_raw.float(), mode="reduced") + signs = torch.where(triangular.diagonal() < 0, -1.0, 1.0) + return basis * signs.unsqueeze(0) + + def decompose(self, delta: Tensor, basis: Optional[Tensor] = None) -> Dict[str, Tensor]: + if delta.ndim != 2 or delta.shape[1] != self.config.node_dim: + raise ValueError("delta must have shape [B,node_dim]") + basis = self.orthonormal_basis() if basis is None else basis + with torch.autocast(device_type=delta.device.type, enabled=False): + flat_coefficients = delta.float() @ basis.float() + coefficients = flat_coefficients.reshape(-1, self.config.num_nodes, self.config.rank) + residual = delta.float() - flat_coefficients @ basis.float().T + return {"coefficients": coefficients, + "amplitudes": torch.linalg.vector_norm(coefficients, dim=-1), + "residual": residual, "basis": basis} + + def _representation(self, evidence: Dict[str, Tensor], delta: Tensor, + basis: Optional[Tensor] = None, + paired_spatial: Optional[Tensor] = None) -> Dict[str, Tensor]: + state = self.decompose(delta, basis) + # Export the actual trained factor contributions. Slot indices supply + # identity; a future consumer can add its own trained attention keys. + with torch.autocast(device_type=delta.device.type, enabled=False): + basis_blocks = state["basis"].float().T.reshape( + self.config.num_nodes, self.config.rank, self.config.node_dim, + ) + tokens = torch.einsum("bnr,nrd->bnd", state["coefficients"].float(), basis_blocks) + spatial = (torch.sigmoid(self.spatial_head(evidence["spatial_features"])) + if paired_spatial is None else torch.tanh(self.spatial_head(paired_spatial)).abs()) + return {"content": evidence["content"], "delta": delta, + "presence_logits": self.presence_head(delta), + "severity": torch.sigmoid(self.severity_head(delta)), + "node_tokens": tokens, "spatial": spatial, + "photometric": self.photometric_head(delta), **state} + + def forward(self, image: Tensor) -> Dict[str, Tensor]: + evidence = self._evidence(image) + return self._representation(evidence, self.delta_head(evidence["global"])) + + def forward_pair(self, degraded: Tensor, clean: Tensor) -> Dict[str, Dict[str, Tensor]]: + """Training helper; teacher keeps gradients for functional supervision. + + The teacher uses clean content and a difference of shared evidence. The + caller, not this model, chooses whether to detach a distillation target. + With the shared linear delta head, teacher_delta is algebraically + student_delta - clean_delta (up to floating-point arithmetic), not an + independently learned teacher. Functional/parameter supervision must + constrain the representation beyond agreement with this reference. + """ + if degraded.shape != clean.shape: + raise ValueError("paired images must have matching shapes") + degraded_evidence = self._evidence(degraded) + clean_evidence = self._evidence(clean) + basis = self.orthonormal_basis() + student = self._representation(degraded_evidence, self.delta_head(degraded_evidence["global"]), basis) + clean_state = self._representation(clean_evidence, self.delta_head(clean_evidence["global"]), basis) + teacher_delta = self.delta_head(degraded_evidence["global"] - clean_evidence["global"]) + teacher = self._representation( + clean_evidence, teacher_delta, basis, + paired_spatial=degraded_evidence["spatial_features"] - clean_evidence["spatial_features"], + ) + return {"student": student, "teacher": teacher, "clean": clean_state} + + def encode_pair(self, degraded: Tensor, clean: Tensor) -> Dict[str, Tensor]: + """Return the paired reference descriptor (not an inference API).""" + return self.forward_pair(degraded, clean)["teacher"] + + def drop_factor(self, delta: Tensor, index: FactorIndex) -> Tensor: + """Remove only the selected orthogonal factor, including free factors.""" + state = self.decompose(delta) + indices = _factor_indices(index, delta.shape[0], self.config.num_nodes, delta.device) + basis = state["basis"].T.reshape(self.config.num_nodes, self.config.rank, self.config.node_dim) + rows = torch.arange(delta.shape[0], device=delta.device) + contribution = torch.einsum("br,brd->bd", state["coefficients"][rows, indices], basis[indices]) + return delta.float() - contribution + + def compose(self, first: Tensor, second: Tensor, + first_type: FactorIndex, second_type: FactorIndex, + use_edges: bool = True) -> Tensor: + """Predict code after first operator then second; no-edge is addition.""" + additive = first + second + if not use_edges: + return additive + return additive + self.interaction(first, second, first_type, second_type) + + def decode(self, content: Tensor, delta: Tensor, + output_size: Tuple[int, int]) -> Tensor: + """Learned native-resolution proxy; zero delta removes its FiLM payload. + + Train decode(c,0) against the clean image and decode(c,delta) against + the degraded image. Three conditioned PixelShuffle stages recover the + native grid from H/8 content and can express one-pixel structure. Only + explicitly requested nonnative output sizes use final bilinear resizing; + high-frequency validation should use exactly 8 * content.shape[-2:]. + + This deterministic decoder cannot sample a stochastic corruption's + conditional distribution. For noise, rain and snow, supplement pixel + reconstruction with residual statistics and matched-parameter transfer + tests; exact reconstruction of random pixels is not semantic evidence. + No image or target bypass enters the decoder. + """ + if content.ndim != 4 or content.shape[1] != self.config.content_channels: + raise ValueError("content must have shape [B,content_channels,H,W]") + if delta.shape != (content.shape[0], self.config.node_dim): + raise ValueError("decoder delta must have shape [B,node_dim]") + if (not isinstance(output_size, (tuple, list)) or len(output_size) != 2 + or any(not isinstance(size, int) or isinstance(size, bool) or size <= 0 + for size in output_size)): + raise ValueError("output_size must contain two positive integer dimensions") + output_size = tuple(output_size) + hidden = self.decoder_content(content) + scale, shift = self.decoder_condition(delta).chunk(2, dim=1) + hidden = hidden * (1 + 0.5 * scale.tanh()[:, :, None, None]) + shift[:, :, None, None] + for block in self.decoder_upsamplers: + hidden = block(hidden, delta) + image = self.decoder_output(hidden) + if image.shape[-2:] != output_size: + image = F.interpolate(image, size=output_size, mode="bilinear", align_corners=False) + return torch.sigmoid(image) + + +__all__ = ["TYPE_ORDER", "MODEL_VERSION", "CleanRelativeConfig", + "OrderedInteraction", "CleanRelativeGraphEncoder"] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/downstream.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/downstream.py new file mode 100644 index 0000000000000000000000000000000000000000..b743d89385190ca37a2968788d637eb3e768d07a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/downstream.py @@ -0,0 +1,556 @@ +""" +Downstream Interface for Graph Representation. + +Phase 2 (Restoration) receives: +- degraded_image: Original degraded image +- graph: GraphRepresentation from Phase 1 student (NO labels!) + +The downstream should NOT receive: +- degradation_type: int +- oracle_severity: float +- type_embedding: nn.Embedding + +All conditioning comes from the graph representation. +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Optional, Tuple, Dict +from dataclasses import dataclass + +from .representation import GraphRepresentation +from .encoder import BlindDegradationGraphEncoder, create_graph_encoder + + +# ============================================================================ +# Downstream Configuration +# ============================================================================ + +@dataclass +class DownstreamConfig: + """Configuration for downstream restoration model.""" + + # Architecture + latent_channels: int = 128 + hidden_dim: int = 256 + diffusion_steps: int = 1000 + + # Conditioning from graph + use_routing: bool = True + use_severity: bool = True + use_spatial_maps: bool = True + use_node_tokens: bool = True + use_content: bool = True + + # Condition aggregation + condition_dim: int = 256 + num_attention_heads: int = 4 + + +# ============================================================================ +# Graph Conditioning Module +# ============================================================================ + +class GraphConditioning(nn.Module): + """ + Transform graph representation into conditioning for diffusion. + + Receives: + - routing_probs: [B, N] posterior over nodes + - severity_coords: [B, K] geodesic severity + - node_tokens: [B, N, D] node embeddings + - spatial_maps: [B, K, H', W'] spatial severity + - unknown_residual: [B, D] unexplained component + - content_latent: [B, C, H, W] content features + + Returns: + - timestep_embedding: [B, D] for timestep conditioning + - graph_embedding: [B, D] aggregated from graph + - spatial_conditioning: [B, K, H', W'] for spatial FiLM + """ + + def __init__(self, config: DownstreamConfig, num_branches: int = 4): + super().__init__() + self.config = config + self.num_branches = num_branches + + # Route severity to FiLM parameters + self.severity_to_film = nn.Linear(num_branches, config.hidden_dim * 2) + + # Route routing to gating + self.routing_gate = nn.Sequential( + nn.Linear(num_branches, config.hidden_dim), + nn.Sigmoid(), + ) + + # Aggregate node tokens + self.token_aggregator = nn.MultiheadAttention( + config.hidden_dim, + num_heads=config.num_attention_heads, + batch_first=True, + ) + + # Final condition projection + self.condition_proj = nn.Sequential( + nn.Linear(config.hidden_dim, config.condition_dim), + nn.SiLU(), + nn.Linear(config.condition_dim, config.condition_dim), + ) + + # Content conditioning + if config.use_content: + self.content_proj = nn.Conv2d( + config.latent_channels, config.condition_dim, 1 + ) + + def forward( + self, + graph: GraphRepresentation, + timestep_emb: torch.Tensor, + ) -> Dict[str, torch.Tensor]: + """ + Transform graph to conditioning signals. + + Args: + graph: GraphRepresentation from Phase 1 + timestep_emb: [B, D] timestep embedding + + Returns: + Dict with conditioning tensors + """ + B = graph.routing_probs.shape[0] + device = graph.routing_probs.device + + # ===== Routing Conditioning ===== + routing = graph.routing_probs[:, :self.num_branches] # [B, K] + + # FiLM parameters from severity × routing + severity = graph.severity_coords # [B, K] + + # γ, β = linear(routing × severity) + film_input = routing * severity # [B, K] + film_params = self.severity_to_film(film_input) # [B, D*2] + gamma = film_params[:, :self.config.hidden_dim].unsqueeze(-1).unsqueeze(-1) + beta = film_params[:, self.config.hidden_dim:].unsqueeze(-1).unsqueeze(-1) + + # ===== Node Token Conditioning ===== + tokens = graph.node_tokens # [B, N, D] + + # Aggregate tokens with self-attention + tokens_out, _ = self.token_aggregator(tokens, tokens, tokens) + token_emb = tokens_out.mean(dim=1) # [B, D] + + # Gate by routing + gate = self.routing_gate(routing) # [B, D] + gated_emb = gate * token_emb + + # ===== Combine with Timestep ===== + combined = gated_emb + timestep_emb + + # Final condition + condition = self.condition_proj(combined) # [B, D] + + # ===== Spatial Conditioning ===== + if graph.spatial_maps is not None: + spatial_cond = graph.spatial_maps # [B, K, H', W'] + else: + spatial_cond = torch.ones(B, self.num_branches, 16, 16, device=device) + + # ===== Content Conditioning ===== + if self.config.use_content and graph.content_latent is not None: + content_emb = self.content_proj(graph.content_latent) # [B, D, H, W] + content_pool = F.adaptive_avg_pool2d(content_emb, 1).flatten(1) # [B, D] + else: + content_pool = torch.zeros(B, self.config.condition_dim, device=device) + + return { + "condition": condition, # [B, D] + "film_gamma": gamma, # [B, D, 1, 1] + "film_beta": beta, # [B, D, 1, 1] + "spatial_conditioning": spatial_cond, # [B, K, H', W'] + "content_pool": content_pool, # [B, D] + "routing": routing, # [B, K] + "severity": severity, # [B, K] + } + + +# ============================================================================ +# UNet Denoiser with Graph Conditioning +# ============================================================================ + +class ResidualBlock(nn.Module): + """Residual block with graph conditioning.""" + + def __init__( + self, + in_channels: int, + out_channels: int, + cond_dim: int, + use_film: bool = True, + ): + super().__init__() + self.use_film = use_film + + self.norm = nn.GroupNorm(8, in_channels) + self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1) + + if use_film: + self.film = nn.Linear(cond_dim, out_channels * 2) + + self.conv2 = nn.Sequential( + nn.SiLU(), + nn.Dropout(0.1), + nn.Conv2d(out_channels, out_channels, 3, padding=1), + ) + + if in_channels != out_channels: + self.skip = nn.Conv2d(in_channels, out_channels, 1) + else: + self.skip = nn.Identity() + + def forward( + self, + x: torch.Tensor, + condition: torch.Tensor, + film_gamma: Optional[torch.Tensor] = None, + film_beta: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + h = self.norm(x) + h = self.conv1(h) + + if self.use_film and film_gamma is not None: + # FiLM conditioning + h = h * (1 + film_gamma) + film_beta + + h = self.conv2(h) + return self.skip(x) + h + + +class GraphConditionedUNet(nn.Module): + """ + UNet denoiser conditioned on graph representation. + + Key differences from standard UNet: + - NO degradation_type input + - NO oracle_severity input + - All conditioning from graph representation + """ + + def __init__( + self, + in_channels: int = 3, + hidden_dims: list = [64, 128, 256], + cond_dim: int = 256, + num_branches: int = 4, + ): + super().__init__() + self.hidden_dims = hidden_dims + + # Timestep embedding + self.time_emb = SinusoidalTimeEmbedding(cond_dim) + + # Graph conditioning + self.graph_conditioning = GraphConditioning( + DownstreamConfig(), num_branches=num_branches + ) + + # Input conv + self.input_conv = nn.Conv2d(in_channels, hidden_dims[0], 3, padding=1) + + # Encoder + self.encoder_blocks = nn.ModuleList() + self.encoder_downs = nn.ModuleList() + + in_ch = hidden_dims[0] + for i, out_ch in enumerate(hidden_dims): + blocks = nn.ModuleList([ + ResidualBlock(in_ch, out_ch, cond_dim) + for _ in range(2) + ]) + self.encoder_blocks.append(blocks) + + if i < len(hidden_dims) - 1: + self.encoder_downs.append(nn.Conv2d(out_ch, out_ch, 3, stride=2, padding=1)) + else: + self.encoder_downs.append(nn.Identity()) + + in_ch = out_ch + + # Middle + self.middle = nn.ModuleList([ + ResidualBlock(hidden_dims[-1], hidden_dims[-1], cond_dim) + for _ in range(2) + ]) + + # Decoder + self.decoder_blocks = nn.ModuleList() + self.decoder_ups = nn.ModuleList() + + for i in range(len(hidden_dims) - 1): + in_ch = hidden_dims[-1 - i] + out_ch = hidden_dims[-2 - i] + + blocks = nn.ModuleList([ + ResidualBlock(in_ch, out_ch, cond_dim) + for _ in range(2) + ]) + self.decoder_blocks.append(blocks) + self.decoder_ups.append(nn.ConvTranspose2d(in_ch, out_ch, 2, stride=2)) + + # Output + self.output_conv = nn.Conv2d(hidden_dims[0], in_channels, 3, padding=1) + + def forward( + self, + x: torch.Tensor, + timestep: torch.Tensor, + graph: GraphRepresentation, + ) -> torch.Tensor: + """ + Denoise with graph conditioning. + + Args: + x: [B, C, H, W] noisy latent + timestep: [B] or scalar timestep + graph: GraphRepresentation from Phase 1 + + Returns: + [B, C, H, W] predicted noise or clean + """ + # Timestep embedding + t_emb = self.time_emb(timestep) # [B, D] + + # Graph conditioning + g_cond = self.graph_conditioning(graph, t_emb) + + # Combine timestep + graph condition + cond_emb = t_emb + g_cond["condition"] + + # Input + h = self.input_conv(x) + + # Encoder + skips = [] + for blocks, down in zip(self.encoder_blocks, self.encoder_downs): + for block in blocks: + h = block(h, cond_emb, g_cond["film_gamma"], g_cond["film_beta"]) + skips.append(h) + h = down(h) + + # Middle + for block in self.middle: + h = block(h, cond_emb, g_cond["film_gamma"], g_cond["film_beta"]) + + # Decoder + for blocks, up, skip_ch in zip( + self.decoder_blocks, self.decoder_ups, reversed(self.hidden_dims[:-1]) + ): + h = up(h) + h = torch.cat([h, skips.pop()], dim=1) + for block in blocks: + h = block(h, cond_emb, g_cond["film_gamma"], g_cond["film_beta"]) + + return self.output_conv(h) + + +class SinusoidalTimeEmbedding(nn.Module): + """Sinusoidal timestep embedding.""" + + def __init__(self, dim: int): + super().__init__() + self.dim = dim + self.mlp = nn.Sequential( + nn.Linear(dim, dim * 4), + nn.SiLU(), + nn.Linear(dim * 4, dim), + ) + + def forward(self, t: torch.Tensor) -> torch.Tensor: + half = self.dim // 2 + emb = torch.exp( + -torch.arange(half, device=t.device, dtype=torch.float32) + * torch.log(torch.tensor(10000.0)) / half + ) + emb = t.float()[:, None] * emb[None, :] + emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1) + return self.mlp(emb) + + +# ============================================================================ +# Complete Downstream Pipeline +# ============================================================================ + +class GraphConditionedRestoration(nn.Module): + """ + Complete restoration pipeline using graph representation. + + Forward: + graph = phase1_encoder(degraded) + restored = phase2_model(degraded, graph) + + NO labels passed to downstream! + """ + + def __init__( + self, + phase1_config=None, + phase2_config=None, + ): + super().__init__() + + # Phase 1: Graph Encoder (frozen at training) + if phase1_config is None: + from .representation import GraphConfig + phase1_config = GraphConfig() + self.phase1 = create_graph_encoder(phase1_config) + + # Phase 2: Restoration + if phase2_config is None: + phase2_config = DownstreamConfig() + self.phase2 = GraphConditionedUNet( + in_channels=3, + hidden_dims=[64, 128, 256], + cond_dim=phase2_config.condition_dim, + num_branches=phase1_config.num_semantic_branches, + ) + + # Diffusion schedule + self.register_buffer( + "alphas_cumprod", + torch.linspace(0.0001, 0.02, phase2_config.diffusion_steps).cumprod(0) + ) + + def encode_graph(self, degraded: torch.Tensor, clean: Optional[torch.Tensor] = None): + """ + Phase 1: Encode degraded image to graph representation. + + Args: + degraded: [B, 3, H, W] degraded image + clean: [B, 3, H, W] clean image (None at inference) + + Returns: + GraphRepresentation + """ + return self.phase1(clean, degraded, is_training=clean is not None) + + def restore( + self, + degraded: torch.Tensor, + graph: GraphRepresentation, + num_steps: int = 50, + ) -> torch.Tensor: + """ + Phase 2: Restore using graph conditioning. + + Args: + degraded: [B, 3, H, W] degraded image + graph: GraphRepresentation from Phase 1 + num_steps: Number of diffusion steps + + Returns: + [B, 3, H, W] restored image + """ + self.phase2.eval() + + with torch.no_grad(): + # Start from degraded latent + x_t = degraded + + # DDIM sampling + for t_idx in range(0, self.diffusion_steps, self.diffusion_steps // num_steps): + t = torch.full( + (degraded.shape[0],), + t_idx / self.diffusion_steps, + device=degraded.device, + ) + + # Predict noise + pred = self.phase2(x_t, t, graph) + + # DDIM step (simplified) + alpha = self.alphas_cumprod[t_idx] + x_t = x_t - (1 - alpha).sqrt() * pred + x_t = x_t / alpha.sqrt() + + return x_t.clamp(0, 1) + + def forward( + self, + clean: Optional[torch.Tensor], + degraded: torch.Tensor, + num_steps: int = 50, + ) -> Tuple[torch.Tensor, GraphRepresentation]: + """ + Full forward pass. + + Args: + clean: [B, 3, H, W] clean target (None at inference) + degraded: [B, 3, H, W] degraded input + num_steps: Diffusion steps + + Returns: + (restored, graph) + """ + # Phase 1: Encode to graph + graph = self.encode_graph(degraded, clean) + + # Phase 2: Restore + restored = self.restore(degraded, graph, num_steps) + + return restored, graph + + +# ============================================================================ +# Usage Example +# ============================================================================ + +def example_usage(): + """ + Example of correct Phase 1 → Phase 2 usage. + + WRONG (old way): + deg_type = model.predict_type(degraded) + severity = model.predict_severity(degraded) + restored = diffusion(degraded, deg_type=deg_type, severity=severity) + + CORRECT (new way): + graph = phase1(degraded) # NO labels! + restored = phase2(degraded, graph) # NO labels! + """ + # Create models + model = GraphConditionedRestoration() + + # Dummy inputs + degraded = torch.randn(2, 3, 256, 256) + clean = torch.randn(2, 3, 256, 256) + + # Training + restored, graph = model(clean, degraded) + + print(f"Graph routing: {graph.routing_probs.shape}") + print(f"Graph severity: {graph.severity_coords.shape}") + print(f"Restored: {restored.shape}") + + # Inference (NO clean image!) + with torch.no_grad(): + graph = model.encode_graph(degraded) # Clean=None + restored = model.restore(degraded, graph, num_steps=20) + + print(f"Inference routing: {graph.routing_probs}") + print(f"Inference severity: {graph.severity_coords}") + + # Note: NO deg_type, NO severity label passed to phase2! + + +# ============================================================================ +# Exports +# ============================================================================ + +__all__ = [ + "DownstreamConfig", + "GraphConditioning", + "GraphConditionedUNet", + "GraphConditionedRestoration", + "example_usage", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/encoder.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..596a03f41181c3ee0412fe8e3eec9c96d9c2536b --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/encoder.py @@ -0,0 +1,578 @@ +""" +Clean-Anchored Degradation Graph Encoder - Simplified Version. +""" + +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Optional, List, Tuple, Dict + +from .hvi import hvi_colour_stats, rgb_to_hvi, HVI_STAT_NAMES +from .representation import ( + GraphRepresentation, + GraphConfig, + aggregate_graph_condition, + SEMANTIC_BRANCH_NAMES, +) + + +class CleanRootAnchor(nn.Module): + """Learnable clean anchor at graph origin.""" + + def __init__(self, dim: int, init: str = "zero"): + super().__init__() + self.dim = dim + + if init == "zero": + self.embedding = nn.Parameter(torch.zeros(1, dim)) + elif init == "learned": + self.embedding = nn.Parameter(torch.randn(1, dim) * 0.02) + + def forward(self): + return self.embedding + + +class SemanticBranch(nn.Module): + """Ordered severity branch on degradation graph.""" + + def __init__(self, name: str, dim: int, num_anchors: int = 8, anchor_spacing: float = 1.0): + super().__init__() + self.name = name + self.dim = dim + self.num_anchors = num_anchors + self.anchor_spacing = anchor_spacing + + self.anchor_embeddings = nn.Parameter(torch.randn(1, num_anchors, dim) * 0.02) + self.register_buffer("severity_values", torch.arange(num_anchors).float() * anchor_spacing) + + @property + def max_severity(self): + return self.severity_values[-1].item() + + def get_branch_embedding(self, severity): + t = (severity / self.max_severity).clamp(0, 1) + idx = t * (self.num_anchors - 1) + idx_low = idx.floor().long().clamp(0, self.num_anchors - 2) + idx_high = idx.ceil().long().clamp(0, self.num_anchors - 1) + w = idx - idx_low.float() + emb_low = self.anchor_embeddings[:, idx_low] + emb_high = self.anchor_embeddings[:, idx_high] + return (1 - w.unsqueeze(-1)) * emb_low + w.unsqueeze(-1) * emb_high + + +class FreeLatentNodes(nn.Module): + """Learnable free nodes for unseen degradation.""" + + def __init__(self, num_nodes: int, dim: int): + super().__init__() + self.num_nodes = num_nodes + self.node_embeddings = nn.Parameter(torch.randn(num_nodes, dim) * 0.02) + + def forward(self): + return self.node_embeddings + + +def haar_ll(image: torch.Tensor) -> torch.Tensor: + """One Haar LL step (orthonormal scaling) on a BCHW tensor.""" + h = image.shape[-2] // 2 * 2 + w = image.shape[-1] // 2 * 2 + x = image[..., :h, :w] + return ( + x[..., 0::2, 0::2] + x[..., 0::2, 1::2] + + x[..., 1::2, 0::2] + x[..., 1::2, 1::2] + ) / 2.0 + + +def haar_hh1(luma: torch.Tensor) -> torch.Tensor: + """First-level Haar HH band of a [B,1,H,W] luminance map.""" + h = luma.shape[-2] // 2 * 2 + w = luma.shape[-1] // 2 * 2 + x = luma[..., :h, :w] + return ( + x[..., 0::2, 0::2] - x[..., 0::2, 1::2] + - x[..., 1::2, 0::2] + x[..., 1::2, 1::2] + ) / 2.0 + + +def haar_lh1(luma: torch.Tensor) -> torch.Tensor: + """First-level Haar LH band (horizontal low-pass, vertical high-pass): + responds to HORIZONTAL edges/streaks.""" + h = luma.shape[-2] // 2 * 2 + w = luma.shape[-1] // 2 * 2 + x = luma[..., :h, :w] + return ( + x[..., 0::2, 0::2] + x[..., 0::2, 1::2] + - x[..., 1::2, 0::2] - x[..., 1::2, 1::2] + ) / 2.0 + + +def haar_hl1(luma: torch.Tensor) -> torch.Tensor: + """First-level Haar HL band (horizontal high-pass, vertical low-pass): + responds to VERTICAL edges/streaks (rain).""" + h = luma.shape[-2] // 2 * 2 + w = luma.shape[-1] // 2 * 2 + x = luma[..., :h, :w] + return ( + x[..., 0::2, 0::2] - x[..., 0::2, 1::2] + + x[..., 1::2, 0::2] - x[..., 1::2, 1::2] + ) / 2.0 + + +def oriented_band_stats(image: torch.Tensor) -> torch.Tensor: + """Three oriented-band statistics (v6): log mean |LH1|, log mean |HL1| + and their anisotropy (LH - HL) / (LH + HL). Rain streaks are + near-vertical (HL energy), snow flakes and noise are isotropic, so this + is the cheapest signal that separates rain from the other additive + high-frequency degradations the pooled CNN blurs together.""" + weights = image.new_tensor([0.2126, 0.7152, 0.0722]).view(1, 3, 1, 1) + luma = (image * weights).sum(dim=1, keepdim=True) + # Mean |band| rather than MAD: streaks are sparse, so a median would read + # zero on exactly the images this statistic exists for; the anisotropy + # ratio cancels the isotropic (noise) share of both bands. + lh = haar_lh1(luma).abs().flatten(1).mean(dim=1) + hl = haar_hl1(luma).abs().flatten(1).mean(dim=1) + anisotropy = (lh - hl) / (lh + hl + 1e-6) + return torch.stack((torch.log(lh + 1e-4), torch.log(hl + 1e-4), anisotropy), dim=1) + + +def photometric_stats(image: torch.Tensor, oriented: bool = False) -> torch.Tensor: + """Fourteen blind global statistics the pooled CNN readout destroys + (seventeen with ``oriented``: + LH1/HL1 log MAD and anisotropy). + + Covers exposure (log-luminance moments and percentiles), color cast + (channel means), atmospheric veil (dark channel), noise floor (HH1 MAD) + and detail energy (gradient magnitude). All values are bounded or + log-compressed so the downstream MLP sees a stable range. + """ + weights = image.new_tensor([0.2126, 0.7152, 0.0722]).view(1, 3, 1, 1) + luma = (image * weights).sum(dim=1, keepdim=True) + flat = luma.flatten(1) + quantiles = torch.quantile( + flat, flat.new_tensor([0.05, 0.5, 0.95]), dim=1 + ).transpose(0, 1) + dark = -F.max_pool2d(-image.min(dim=1, keepdim=True).values, 7, 1, 3) + hh = haar_hh1(luma) + sigma = hh.abs().flatten(1).median(dim=1).values / 0.6745 + grad_x = (luma[..., :, 1:] - luma[..., :, :-1]).abs().flatten(1).mean(1) + grad_y = (luma[..., 1:, :] - luma[..., :-1, :]).abs().flatten(1).mean(1) + ll3 = haar_ll(haar_ll(haar_ll(luma))) + features = torch.cat( + ( + flat.mean(1, keepdim=True), + torch.log(flat.mean(1, keepdim=True) + 1e-4), + flat.std(1, keepdim=True), + quantiles, + image.mean(dim=(2, 3)), + dark.flatten(1).mean(1, keepdim=True), + torch.log(sigma + 1e-4).unsqueeze(1), + (grad_x + grad_y).unsqueeze(1), + ll3.flatten(1).std(1, keepdim=True), + ll3.flatten(1).mean(1, keepdim=True), + ), + dim=1, + ) + if oriented: + features = torch.cat((features, oriented_band_stats(image)), dim=1) + return features + + +class LLGlobalBranch(nn.Module): + """Global low-frequency pathway: LL3 attention summary + photometric stats. + + The pooled-to-1x1 CNN readout destroys exactly the information haze, + lowlight and blob-like OOD degradations live in. This branch keeps LL3 as + a feature map read by one learned attention query, and embeds explicit + photometric statistics, so routing/severity heads can see global state. + """ + + STATS_DIM = 14 + ORIENTED_STATS_DIM = 17 + + def __init__(self, output_dim: int = 128, token_dim: int = 64, oriented_bands: bool = False): + super().__init__() + if output_dim % 2: + raise ValueError("output_dim must be even") + half = output_dim // 2 + self.oriented_bands = bool(oriented_bands) + self.stats_dim = self.ORIENTED_STATS_DIM if self.oriented_bands else self.STATS_DIM + self.ll_encoder = nn.Sequential( + nn.Conv2d(3, 32, 3, stride=2, padding=1), + nn.GroupNorm(4, 32), nn.GELU(), + nn.Conv2d(32, token_dim, 3, stride=2, padding=1), + nn.GroupNorm(8, token_dim), nn.GELU(), + ) + self.ll_query = nn.Parameter(torch.randn(1, 1, token_dim) * 0.02) + self.ll_attention = nn.MultiheadAttention( + token_dim, num_heads=4, batch_first=True + ) + self.ll_proj = nn.Linear(token_dim, half) + self.stats_mlp = nn.Sequential( + nn.Linear(self.stats_dim, half), nn.SiLU(), + nn.Linear(half, half), nn.LayerNorm(half), + ) + self.output_norm = nn.LayerNorm(output_dim) + + def forward(self, image: torch.Tensor) -> torch.Tensor: + # The whole branch runs in fp32: it is tiny, and fp16 attention or + # log-space statistics are the kind of op that turns one AMP overflow + # into NaN metrics that kill a multi-hour run. + with torch.cuda.amp.autocast(enabled=False): + image = image.float() + ll3 = haar_ll(haar_ll(haar_ll(image))) + tokens = self.ll_encoder(ll3).flatten(2).transpose(1, 2) + query = self.ll_query.expand(image.shape[0], -1, -1) + summary, _ = self.ll_attention(query, tokens, tokens) + stats = photometric_stats(image, oriented=self.oriented_bands) + fused = torch.cat( + (self.ll_proj(summary.squeeze(1)), self.stats_mlp(stats)), dim=1 + ) + return self.output_norm(fused) + + +class PhotometricBranch(nn.Module): + """Global colour/exposure pathway in the HVI colour space (v5). + + Complements LLGlobalBranch, which only sees three RGB channel means as + colour information. HVI (Yan et al., CVPR 2025) separates intensity + I = max(R,G,B) from a polarised, intensity-collapsed chroma plane + (H_hat, V_hat); the collapse exponent k is learned. The branch reads + (a) the HVI image at 32x32 through a tiny conv encoder + one attention + query and (b) 13 explicit HVI statistics (cast, chroma radius, chroma + noise floor, intensity percentiles, collapsed fraction). It also predicts + the per-image global photometric shift degraded->clean (log-gain and bias + on I, 2x2 + bias on HV), which the trainer supervises from the pair and + which Phase-2 can consume as the input of an exposure controllable. + """ + + STATS_DIM = len(HVI_STAT_NAMES) + SHIFT_DIM = 8 + + def __init__(self, output_dim: int = 128, token_dim: int = 64, k_init: float = 0.2): + super().__init__() + if output_dim % 2: + raise ValueError("output_dim must be even") + half = output_dim // 2 + self.log_k = nn.Parameter(torch.tensor(float(math.log(k_init)))) + self.hvi_encoder = nn.Sequential( + nn.Conv2d(3, 32, 3, stride=2, padding=1), + nn.GroupNorm(4, 32), nn.GELU(), + nn.Conv2d(32, token_dim, 3, stride=2, padding=1), + nn.GroupNorm(8, token_dim), nn.GELU(), + ) + self.query = nn.Parameter(torch.randn(1, 1, token_dim) * 0.02) + self.attention = nn.MultiheadAttention(token_dim, num_heads=4, batch_first=True) + self.map_proj = nn.Linear(token_dim, half) + self.stats_mlp = nn.Sequential( + nn.Linear(self.STATS_DIM, half), nn.SiLU(), + nn.Linear(half, half), nn.LayerNorm(half), + ) + self.output_norm = nn.LayerNorm(output_dim) + self.shift_head = nn.Linear(output_dim, self.SHIFT_DIM) + nn.init.zeros_(self.shift_head.weight) + nn.init.zeros_(self.shift_head.bias) + + @property + def k(self) -> torch.Tensor: + return self.log_k.exp().clamp(0.05, 2.0) + + def forward(self, image: torch.Tensor): + with torch.cuda.amp.autocast(enabled=False): + image = image.float().clamp(0.0, 1.0) + k = self.k + hvi = rgb_to_hvi(image, k) + small = F.adaptive_avg_pool2d(hvi, (32, 32)) + tokens = self.hvi_encoder(small).flatten(2).transpose(1, 2) + query = self.query.expand(image.shape[0], -1, -1) + summary, _ = self.attention(query, tokens, tokens) + stats = hvi_colour_stats(image, k) + fused = torch.cat( + (self.map_proj(summary.squeeze(1)), self.stats_mlp(stats)), dim=1 + ) + state = self.output_norm(fused) + return state, self.shift_head(state) + + +class SpatialEncoder(nn.Module): + """Simple spatial feature extractor.""" + + def __init__(self, in_channels: int = 3, latent_channels: int = 128): + super().__init__() + + self.encoder = nn.Sequential( + nn.Conv2d(in_channels, 32, 3, padding=1), nn.ReLU(), + nn.Conv2d(32, 64, 3, stride=2, padding=1), nn.ReLU(), + nn.BatchNorm2d(64), + nn.Conv2d(64, latent_channels, 3, padding=1), nn.ReLU(), + nn.Conv2d(latent_channels, latent_channels, 3, stride=2, padding=1), nn.ReLU(), + nn.BatchNorm2d(latent_channels), + ) + + def forward(self, x): + return self.encoder(x) + + +class GraphStatePredictor(nn.Module): + """Predict graph state from features.""" + + def __init__(self, feat_dim: int, node_dim: int, num_semantic: int, num_free: int, spatial_size=(16, 16), global_dim: int = 0): + super().__init__() + self.num_semantic = num_semantic + self.num_free = num_free + self.num_total = num_semantic + num_free + self.global_dim = int(global_dim) + + self.feat_pool = nn.AdaptiveAvgPool2d((1, 1)) + readout_dim = feat_dim + self.global_dim + + self.routing_net = nn.Sequential( + nn.Linear(readout_dim, node_dim), nn.ReLU(), + nn.Linear(node_dim, self.num_total), + ) + + self.severity_net = nn.Sequential( + nn.Linear(readout_dim, node_dim), nn.ReLU(), + nn.Linear(node_dim, num_semantic), nn.Sigmoid(), + ) + + self.spatial_net = nn.Sequential( + nn.Conv2d(feat_dim, 64, 3, padding=1), nn.ReLU(), + nn.Conv2d(64, num_semantic, 3, padding=1), nn.Sigmoid(), + ) + + self.residual_net = nn.Sequential( + nn.Linear(readout_dim, node_dim), nn.ReLU(), + nn.Linear(node_dim, node_dim), + ) + + self.spatial_size = spatial_size + + def forward(self, feat, global_feats=None): + B = feat.shape[0] + + pooled = self.feat_pool(feat).view(B, -1) + if self.global_dim: + if global_feats is None or global_feats.shape != (B, self.global_dim): + raise ValueError( + "state predictor requires global_feats of shape [B, %d]" + % self.global_dim + ) + pooled = torch.cat((pooled, global_feats.to(pooled.dtype)), dim=1) + elif global_feats is not None: + raise ValueError("global_feats supplied to a local-only predictor") + + routing_logits = self.routing_net(pooled) + routing_probs = F.softmax(routing_logits, dim=-1) + + severity_raw = self.severity_net(pooled) + + spatial_maps = self.spatial_net(feat) + if spatial_maps.shape[-1] != self.spatial_size[0]: + spatial_maps = F.interpolate(spatial_maps, size=self.spatial_size, mode="bilinear", align_corners=False) + + residual = self.residual_net(pooled) + + return { + "routing_probs": routing_probs, + "severity_coords": severity_raw, + "spatial_maps": spatial_maps, + "unknown_residual": residual, + "readout": pooled, + } + + +class NodeTokenGenerator(nn.Module): + """Generate node tokens from image features.""" + + def __init__(self, feat_dim: int, node_dim: int, num_semantic: int, num_free: int): + super().__init__() + self.num_semantic = num_semantic + self.num_free = num_free + self.num_total = num_semantic + num_free + + self.semantic_tokens = nn.Parameter(torch.randn(num_semantic, node_dim) * 0.02) + self.free_tokens = nn.Parameter(torch.randn(num_free, node_dim) * 0.02) + self.feat_proj = nn.Linear(feat_dim, node_dim) + + self.token_refiner = nn.MultiheadAttention(node_dim, num_heads=4, batch_first=True) + + def forward(self, feat, routing_probs): + B = feat.shape[0] + D = self.semantic_tokens.shape[1] + + feat_pool = F.adaptive_avg_pool2d(feat, 1).flatten(1) + feat_emb = self.feat_proj(feat_pool) + + tokens = torch.cat([ + self.semantic_tokens.unsqueeze(0).expand(B, -1, -1), + self.free_tokens.unsqueeze(0).expand(B, -1, -1), + ], dim=1) + + routing_attn = routing_probs.unsqueeze(-1) + tokens = tokens + routing_attn * feat_emb.unsqueeze(1) + + tokens, _ = self.token_refiner(tokens, tokens, tokens) + + return tokens + + +class BlindDegradationGraphEncoder(nn.Module): + """Clean-Anchored Degradation Graph Encoder.""" + + def __init__(self, config: GraphConfig): + super().__init__() + self.config = config + + self.clean_root = CleanRootAnchor(dim=config.node_dim, init=config.clean_root_init) + + self.branches = nn.ModuleList([ + SemanticBranch(name=name, dim=config.node_dim, num_anchors=config.branch_length, anchor_spacing=1.0) + for name in SEMANTIC_BRANCH_NAMES[:config.num_semantic_branches] + ]) + + self.free_nodes = FreeLatentNodes(num_nodes=config.num_free_nodes, dim=config.node_dim) + + self.feature_extractor = SpatialEncoder(in_channels=3, latent_channels=config.latent_channels) + + use_ll = bool(getattr(config, "use_ll_global", False)) + ll_dim = int(getattr(config, "ll_global_dim", 128)) if use_ll else 0 + self.ll_branch = ( + LLGlobalBranch(output_dim=ll_dim, oriented_bands=bool(getattr(config, "ll_oriented_bands", False))) + if use_ll else None + ) + if use_ll: + self.ll_condition = nn.Linear(ll_dim, config.node_dim) + nn.init.zeros_(self.ll_condition.weight) + nn.init.zeros_(self.ll_condition.bias) + + use_photo = bool(getattr(config, "use_photometric", False)) + photo_dim = int(getattr(config, "photometric_dim", 128)) if use_photo else 0 + self.photometric_branch = PhotometricBranch(output_dim=photo_dim) if use_photo else None + if use_photo: + self.photometric_condition = nn.Linear(photo_dim, config.node_dim) + nn.init.zeros_(self.photometric_condition.weight) + nn.init.zeros_(self.photometric_condition.bias) + self.readout_dim = config.latent_channels + ll_dim + photo_dim + + self.state_predictor = GraphStatePredictor( + feat_dim=config.latent_channels, + node_dim=config.node_dim, + num_semantic=config.num_semantic_branches, + num_free=config.num_free_nodes, + spatial_size=config.spatial_map_size, + global_dim=ll_dim + photo_dim, + ) + + self.token_generator = NodeTokenGenerator( + feat_dim=config.latent_channels, + node_dim=config.node_dim, + num_semantic=config.num_semantic_branches, + num_free=config.num_free_nodes, + ) + + self.content_projector = nn.Conv2d(config.latent_channels, config.latent_channels, 1) + + self.condition_aggregator = nn.Sequential( + nn.Linear(config.node_dim, config.node_dim), nn.ReLU(), + nn.Linear(config.node_dim, config.node_dim), + ) + + def _global_feats(self, image): + """(concatenated global features or None, ll, photometric_state, photometric_shift).""" + ll = self.ll_branch(image) if self.ll_branch is not None else None + photo, shift = (None, None) + if self.photometric_branch is not None: + photo, shift = self.photometric_branch(image) + parts = [part for part in (ll, photo) if part is not None] + fused = torch.cat(parts, dim=1) if parts else None + return fused, ll, photo, shift + + def forward_student(self, degraded): + feat = self.feature_extractor(degraded) + content_latent = self.content_projector(feat) + + global_feats, ll_feats, photo_state, photo_shift = self._global_feats(degraded) + graph_state = self.state_predictor(feat, global_feats=global_feats) + routing_probs = graph_state["routing_probs"] + severity_coords = graph_state["severity_coords"] + spatial_maps = graph_state["spatial_maps"] + unknown_residual = graph_state["unknown_residual"] + + node_tokens = self.token_generator(feat, routing_probs) + + severity_scaled = severity_coords * torch.tensor( + [b.max_severity for b in self.branches], + device=routing_probs.device + ).unsqueeze(0) + + global_condition = aggregate_graph_condition( + node_tokens=node_tokens, + routing_probs=routing_probs, + severity_coords=severity_scaled, + branch_anchors=self.branches, + unknown_residual=unknown_residual, + ) + if ll_feats is not None: + # Zero-initialized so the v2 aggregation semantics hold exactly at + # initialization; the scene-state contribution is learned. + global_condition = global_condition + self.ll_condition( + ll_feats.to(global_condition.dtype) + ) + if photo_state is not None: + global_condition = global_condition + self.photometric_condition( + photo_state.to(global_condition.dtype) + ) + global_condition = self.condition_aggregator(global_condition) + + return GraphRepresentation( + content_latent=content_latent, + node_tokens=node_tokens, + routing_probs=routing_probs, + severity_coords=severity_coords, + spatial_maps=spatial_maps, + unknown_residual=unknown_residual, + global_condition=global_condition, + photometric_state=photo_state, + photometric_shift=photo_shift, + readout=graph_state["readout"], + ) + + def forward(self, clean, degraded, is_training=True): + if is_training and clean is not None: + student_graph = self.forward_student(degraded) + + # Pseudo-teacher: extract state from degraded too + feat = self.feature_extractor(degraded) + teacher_global, _, _, _ = self._global_feats(degraded) + teacher_state = self.state_predictor(feat, global_feats=teacher_global) + + # Teacher has same structure but from paired supervision + teacher_graph = GraphRepresentation( + content_latent=student_graph.content_latent, + node_tokens=student_graph.node_tokens, + routing_probs=teacher_state["routing_probs"], + severity_coords=teacher_state["severity_coords"], + spatial_maps=teacher_state["spatial_maps"], + unknown_residual=teacher_state["unknown_residual"], + global_condition=student_graph.global_condition, + ) + + student_graph.teacher_graph = teacher_graph + return student_graph + else: + return self.forward_student(degraded) + + +def create_graph_encoder(config=None): + if config is None: + config = GraphConfig() + return BlindDegradationGraphEncoder(config) + + +__all__ = [ + "GraphRepresentation", "GraphConfig", "CleanRootAnchor", "SemanticBranch", + "FreeLatentNodes", "LLGlobalBranch", "SpatialEncoder", "GraphStatePredictor", + "NodeTokenGenerator", "BlindDegradationGraphEncoder", "create_graph_encoder", + "haar_ll", "haar_hh1", "photometric_stats", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/hvi.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/hvi.py new file mode 100644 index 0000000000000000000000000000000000000000..1765e2013ae736bd9d8fd1fc61bea2131a7a7304 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/hvi.py @@ -0,0 +1,125 @@ +"""HVI colour space (Yan et al., "HVI: A New Color Space for Low-light Image +Enhancement", CVPR 2025) — a differentiable re-implementation from the paper's +equations. + + I = max(R, G, B) (intensity) + h, s = HSV hue in [0, 1), HSV saturation + C_k(I) = (sin(pi * I / 2) + eps) ** k (intensity collapse) + H_hat = C_k * s * cos(2 pi h), V_hat = C_k * s * sin(2 pi h) + +The polarised (cos, sin) hue removes the red discontinuity of HSV; C_k shrinks +the HV plane towards zero in dark pixels, which removes HSV's "black plane" +noise. ``k`` is the exponent form used by the official code (their +``density_k``; the paper writes it as a k-th root). +""" + +from __future__ import annotations + +import math + +import torch + +_PI = math.pi +_EPS = 1e-8 + + +def rgb_to_hsv_components(rgb: torch.Tensor): + """Return (hue in [0,1), saturation, value) for a [B,3,H,W] tensor in [0,1].""" + if rgb.ndim != 4 or rgb.shape[1] != 3: + raise ValueError("rgb must be [B,3,H,W]") + r, g, b = rgb[:, 0], rgb[:, 1], rgb[:, 2] + value, _ = rgb.max(dim=1) + minimum, _ = rgb.min(dim=1) + delta = value - minimum + safe = delta + _EPS + is_r = value == r + is_g = (value == g) & ~is_r + is_b = ~(is_r | is_g) + hue = torch.zeros_like(value) + hue = torch.where(is_r, ((g - b) / safe) % 6.0, hue) + hue = torch.where(is_g, 2.0 + (b - r) / safe, hue) + hue = torch.where(is_b, 4.0 + (r - g) / safe, hue) + hue = torch.where(delta <= _EPS, torch.zeros_like(hue), hue) / 6.0 + saturation = torch.where(value > _EPS, delta / (value + _EPS), torch.zeros_like(value)) + return hue, saturation, value + + +def intensity_collapse(value: torch.Tensor, k: float) -> torch.Tensor: + return ((value * 0.5 * _PI).sin() + _EPS).pow(k) + + +def rgb_to_hvi(rgb: torch.Tensor, k: float = 0.2) -> torch.Tensor: + """[B,3,H,W] RGB in [0,1] -> [B,3,H,W] (H_hat, V_hat, I).""" + hue, saturation, value = rgb_to_hsv_components(rgb) + c_k = intensity_collapse(value, k) + h_hat = c_k * saturation * torch.cos(2.0 * _PI * hue) + v_hat = c_k * saturation * torch.sin(2.0 * _PI * hue) + return torch.stack((h_hat, v_hat, value), dim=1) + + +def hvi_to_rgb(hvi: torch.Tensor, k: float = 0.2) -> torch.Tensor: + """Inverse of :func:`rgb_to_hvi` (PHVIT).""" + h_hat, v_hat, value = hvi[:, 0], hvi[:, 1], hvi[:, 2].clamp(0.0, 1.0) + c_k = intensity_collapse(value, k) + h = (h_hat / (c_k + _EPS)).clamp(-1.0, 1.0) + v = (v_hat / (c_k + _EPS)).clamp(-1.0, 1.0) + hue = (torch.atan2(v + _EPS, h + _EPS) / (2.0 * _PI)) % 1.0 + saturation = torch.sqrt(h * h + v * v + _EPS).clamp(0.0, 1.0) + sector = torch.floor(hue * 6.0) + fraction = hue * 6.0 - sector + p = value * (1.0 - saturation) + q = value * (1.0 - fraction * saturation) + t = value * (1.0 - (1.0 - fraction) * saturation) + sector = sector.long() % 6 + # sector -> (r, g, b) selection table + r = torch.stack((value, q, p, p, t, value), dim=1) + g = torch.stack((t, value, value, q, p, p), dim=1) + b = torch.stack((p, p, t, value, value, q), dim=1) + idx = sector.unsqueeze(1) + rgb = torch.cat(( + r.gather(1, idx), g.gather(1, idx), b.gather(1, idx)), dim=1) + return rgb.clamp(0.0, 1.0) + + +def hvi_colour_stats(rgb: torch.Tensor, k: float = 0.2) -> torch.Tensor: + """Per-image colour-state features in HVI (13-d): + cast (mean H_hat, mean V_hat), chroma radius mean/std/p95, chroma + high-frequency floor (Haar-HH1 MAD of H_hat and V_hat), intensity + mean/std/p05/p95, collapsed-pixel fraction (I < 0.1), corr(I, chroma).""" + hvi = rgb_to_hvi(rgb, k) + h_hat, v_hat, value = hvi[:, 0], hvi[:, 1], hvi[:, 2] + chroma = torch.sqrt(h_hat * h_hat + v_hat * v_hat + _EPS) + flat_c = chroma.flatten(1) + flat_i = value.flatten(1) + + 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 + + centred_i = flat_i - flat_i.mean(dim=1, keepdim=True) + centred_c = flat_c - flat_c.mean(dim=1, keepdim=True) + corr = (centred_i * centred_c).mean(dim=1) / ( + centred_i.std(dim=1) * centred_c.std(dim=1) + 1e-6) + return torch.stack(( + h_hat.flatten(1).mean(dim=1), + v_hat.flatten(1).mean(dim=1), + flat_c.mean(dim=1), + flat_c.std(dim=1), + flat_c.quantile(0.95, dim=1), + hh1_mad(h_hat), + hh1_mad(v_hat), + flat_i.mean(dim=1), + flat_i.std(dim=1), + flat_i.quantile(0.05, dim=1), + flat_i.quantile(0.95, dim=1), + (flat_i < 0.1).float().mean(dim=1), + corr, + ), dim=1) + + +HVI_STAT_NAMES = ( + "H_mean", "V_mean", "chroma_mean", "chroma_std", "chroma_p95", + "H_hh1_mad", "V_hh1_mad", "I_mean", "I_std", "I_p05", "I_p95", + "collapsed_frac", "corr_I_chroma", +) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/losses.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/losses.py new file mode 100644 index 0000000000000000000000000000000000000000..40aa1b0a2ab96a6747bbe2e6fefff288dcaa359c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/losses.py @@ -0,0 +1,409 @@ +""" +Loss Functions for Graph Encoder Phase 1. +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Optional, Dict, Tuple + + +# ============================================================================ +# Base Loss Class +# ============================================================================ + +class GraphLoss(nn.Module): + def __init__(self, weight: float = 1.0): + super().__init__() + self.weight = weight + + def forward( + self, + graph_student, + graph_teacher=None, + batch_info=None, + ) -> Tuple[torch.Tensor, Dict]: + raise NotImplementedError + + +# ============================================================================ +# 1. Root Loss +# ============================================================================ + +class RootLoss(GraphLoss): + """Clean images should be near graph root.""" + + def __init__(self, weight: float = 0.5): + super().__init__(weight) + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + device = graph_student.routing_probs.device + + routing_loss = graph_student.routing_probs[:, :4].sum(dim=-1).mean() + severity_loss = graph_student.severity_coords.mean(dim=-1).mean() + + if graph_student.unknown_residual is not None: + residual_loss = graph_student.unknown_residual.norm(dim=-1).mean() + else: + residual_loss = torch.tensor(0.0, device=device) + + loss = routing_loss + severity_loss + residual_loss + + return loss * self.weight, { + "loss_root": loss.item(), + "root_routing": routing_loss.item(), + "root_severity": severity_loss.item(), + } + + +# ============================================================================ +# 2. Distillation Loss +# ============================================================================ + +class DistillationLoss(GraphLoss): + """Student should match teacher graph state.""" + + def __init__(self, weight: float = 1.0): + super().__init__(weight) + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + if graph_teacher is None: + return torch.tensor(0.0, device=torch.cuda.current_device()), {"loss_distill": 0.0} + + device = graph_student.routing_probs.device + + routing_dist = F.mse_loss(graph_student.routing_probs, graph_teacher.routing_probs.detach()) + severity_dist = F.mse_loss(graph_student.severity_coords, graph_teacher.severity_coords.detach()) + token_dist = F.mse_loss(graph_student.node_tokens, graph_teacher.node_tokens.detach()) + + loss = routing_dist + severity_dist + token_dist + + return loss * self.weight, { + "loss_distill": loss.item(), + "distill_routing": routing_dist.item(), + "distill_severity": severity_dist.item(), + "distill_tokens": token_dist.item(), + } + + +# ============================================================================ +# 3. Branch Separation Loss +# ============================================================================ + +class BranchSeparationLoss(GraphLoss): + """Contrastive loss for branch separation.""" + + def __init__(self, weight: float = 1.0, margin: float = 1.0): + super().__init__(weight) + self.margin = margin + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + if batch_info is None or "deg_types" not in batch_info: + device = graph_student.routing_probs.device + return torch.tensor(0.0, device=device), {"loss_branch": 0.0} + + B = graph_student.routing_probs.shape[0] + device = graph_student.routing_probs.device + routing = graph_student.routing_probs[:, :4] + deg_types = batch_info["deg_types"] + + # Pairwise distances + routing_i = routing.unsqueeze(1) + routing_j = routing.unsqueeze(0) + dist = (routing_i - routing_j).norm(dim=-1) + + same_loss = torch.tensor(0.0, device=device) + diff_loss = torch.tensor(0.0, device=device) + n_same, n_diff = 0, 0 + + for i in range(B): + for j in range(B): + if i == j: + continue + if deg_types[i] == deg_types[j]: + same_loss += dist[i, j] + n_same += 1 + else: + diff_loss += F.relu(self.margin - dist[i, j]) + n_diff += 1 + + if n_same > 0: + same_loss = same_loss / n_same + if n_diff > 0: + diff_loss = diff_loss / n_diff + + loss = same_loss + diff_loss + + return loss * self.weight, { + "loss_branch": loss.item(), + "branch_same": same_loss.item(), + "branch_diff": diff_loss.item(), + } + + +# ============================================================================ +# 4. Geodesic Severity Loss +# ============================================================================ + +class GeodesicSeverityLoss(GraphLoss): + """Geodesic distance should match numerical severity.""" + + def __init__(self, weight: float = 0.5): + super().__init__(weight) + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + if batch_info is None or "severities" not in batch_info: + device = graph_student.routing_probs.device + return torch.tensor(0.0, device=device), {"loss_geodesic": 0.0} + + severities = graph_student.severity_coords + routing = graph_student.routing_probs[:, :4] + + geodesic = (routing * severities).sum(dim=-1) + target = torch.tensor(batch_info["severities"], device=severities.device).float() + + loss = F.l1_loss(geodesic, target) + + return loss * self.weight, { + "loss_geodesic": loss.item(), + "geo_diff": (geodesic - target).abs().mean().item(), + } + + +# ============================================================================ +# 5. Ranking Loss +# ============================================================================ + +class RankingLoss(GraphLoss): + """Same degradation, different severity should be ordered.""" + + def __init__(self, weight: float = 0.3, margin: float = 0.1): + super().__init__(weight) + self.margin = margin + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + if batch_info is None or "severities" not in batch_info or "deg_types" not in batch_info: + device = graph_student.routing_probs.device + return torch.tensor(0.0, device=device), {"loss_ranking": 0.0} + + routing = graph_student.routing_probs[:, :4] + severities = graph_student.severity_coords + deg_types = batch_info["deg_types"] + target_sev = batch_info["severities"] + + device = routing.device + geodesic = (routing * severities).sum(dim=-1) + + loss = torch.tensor(0.0, device=device) + n_pairs = 0 + + for i in range(len(geodesic)): + for j in range(len(geodesic)): + if deg_types[i] == deg_types[j] and i != j: + diff = target_sev[i] - target_sev[j] + if abs(diff) > 0.1: + if diff > 0: + loss += F.relu(self.margin - (geodesic[i] - geodesic[j])) + else: + loss += F.relu(self.margin - (geodesic[j] - geodesic[i])) + n_pairs += 1 + + if n_pairs > 0: + loss = loss / n_pairs + + return loss * self.weight, {"loss_ranking": loss.item()} + + +# ============================================================================ +# 6. Content Invariance Loss +# ============================================================================ + +class ContentInvarianceLoss(GraphLoss): + """Same degradation+severity, different content should be similar.""" + + def __init__(self, weight: float = 0.2): + super().__init__(weight) + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + if batch_info is None or "severities" not in batch_info or "deg_types" not in batch_info: + device = graph_student.routing_probs.device + return torch.tensor(0.0, device=device), {"loss_content_inv": 0.0} + + routing = graph_student.routing_probs + tokens = graph_student.node_tokens + deg_types = batch_info["deg_types"] + target_sev = batch_info["severities"] + + device = routing.device + loss = torch.tensor(0.0, device=device) + n_pairs = 0 + + # Simple version: same type should have similar routing + routing_i = routing.unsqueeze(1) + routing_j = routing.unsqueeze(0) + dist = (routing_i - routing_j).norm(dim=-1) + + for i in range(len(deg_types)): + for j in range(len(deg_types)): + if deg_types[i] == deg_types[j] and i != j: + loss += dist[i, j] + n_pairs += 1 + + if n_pairs > 0: + loss = loss / n_pairs + + return loss * self.weight, {"loss_content_inv": loss.item()} + + +# ============================================================================ +# 7. Composition Loss +# ============================================================================ + +class CompositionLoss(GraphLoss): + """Encourage proper routing distribution.""" + + def __init__(self, weight: float = 0.5): + super().__init__(weight) + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + routing = graph_student.routing_probs[:, :4] + + # Entropy loss + entropy = -(routing * routing.clamp(min=1e-8).log()).sum(dim=-1).mean() + + loss = entropy + + return loss * self.weight, {"loss_composition": loss.item()} + + +# ============================================================================ +# 8. Sparse Routing Loss +# ============================================================================ + +class SparseRoutingLoss(GraphLoss): + """Sparse routing: encourage focused activation.""" + + def __init__(self, weight: float = 0.1): + super().__init__(weight) + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + routing = graph_student.routing_probs[:, :4] + + loss = routing.norm(p=1, dim=-1).mean() + + return loss * self.weight, {"loss_sparse": loss.item()} + + +# ============================================================================ +# 9. Utility Loss (Restoration Proxy) +# ============================================================================ + +class UtilityLoss(GraphLoss): + """Graph should help with restoration.""" + + def __init__(self, weight: float = 0.3): + super().__init__(weight) + self.adapter = None + + def _get_adapter(self, dim, device): + if self.adapter is None or next(self.adapter.parameters()).device != device: + self.adapter = nn.Sequential( + nn.Linear(dim * 2, dim), + nn.ReLU(), + nn.Linear(dim, dim), + ).to(device) + return self.adapter + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + if batch_info is None or "content_diff" not in batch_info: + device = graph_student.routing_probs.device + return torch.tensor(0.0, device=device), {"loss_utility": 0.0} + + device = graph_student.routing_probs.device + D = graph_student.content_latent.shape[1] + + content = F.adaptive_avg_pool2d(graph_student.content_latent, 1).flatten(1) + condition = graph_student.global_condition + + adapter = self._get_adapter(D, device) + input_feat = torch.cat([content, condition], dim=-1) + predicted = adapter(input_feat) + + target = batch_info["content_diff"].to(device) + + loss = F.l1_loss(predicted, target) + + return loss * self.weight, {"loss_utility": loss.item()} + + +# ============================================================================ +# Type Classification Loss (Auxiliary) +# ============================================================================ + +class TypeClassificationLoss(GraphLoss): + """Auxiliary: helps name branches during training.""" + + def __init__(self, weight: float = 0.1): + super().__init__(weight) + + def forward(self, graph_student, graph_teacher=None, batch_info=None) -> Tuple: + if batch_info is None or "deg_type_labels" not in batch_info: + device = graph_student.routing_probs.device + return torch.tensor(0.0, device=device), {"loss_type": 0.0} + + routing = graph_student.routing_probs[:, :4] + labels = torch.tensor(batch_info["deg_type_labels"], device=routing.device).long() + + loss = F.cross_entropy(routing, labels) + acc = (routing.argmax(dim=-1) == labels).float().mean() + + return loss * self.weight, { + "loss_type": loss.item(), + "type_acc": acc.item(), + } + + +# ============================================================================ +# Combined Loss +# ============================================================================ + +class CombinedGraphLoss(nn.Module): + """Combined loss for Phase 1.""" + + def __init__(self, config): + super().__init__() + self.losses = nn.ModuleDict({ + "distill": DistillationLoss(config.lambda_distill), + "root": RootLoss(config.lambda_root), + "branch": BranchSeparationLoss(config.lambda_branch), + "geodesic": GeodesicSeverityLoss(config.lambda_geodesic), + "ranking": RankingLoss(config.lambda_ranking), + "content_inv": ContentInvarianceLoss(config.lambda_content_inv), + "composition": CompositionLoss(config.lambda_composition), + "sparse": SparseRoutingLoss(config.lambda_sparse), + "utility": UtilityLoss(config.lambda_utility), + "type_cls": TypeClassificationLoss(0.1), + }) + + def forward(self, graph_student, batch_info=None): + graph_teacher = getattr(graph_student, 'teacher_graph', None) + + total_loss = torch.tensor(0.0, device=graph_student.content_latent.device) + metrics = {} + + for name, loss_fn in self.losses.items(): + loss, loss_metrics = loss_fn(graph_student, graph_teacher, batch_info) + total_loss = total_loss + loss + metrics[name] = loss.item() + + metrics["loss_total"] = total_loss.item() + + return total_loss, metrics + + +__all__ = [ + "GraphLoss", "RootLoss", "DistillationLoss", "BranchSeparationLoss", + "GeodesicSeverityLoss", "RankingLoss", "ContentInvarianceLoss", + "CompositionLoss", "SparseRoutingLoss", "UtilityLoss", "TypeClassificationLoss", + "CombinedGraphLoss", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/representation.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/representation.py new file mode 100644 index 0000000000000000000000000000000000000000..44f8678f091094e4df79e4afbcf8c93a251caf45 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/graph_encoder/representation.py @@ -0,0 +1,230 @@ +""" +Graph Representation for Blind Degradation Encoding. + +This module defines the output structure of Phase 1: a degradation graph +representation that captures: +- Content latent (DC-AE spatial features) +- Semantic graph structure (ordered branches with severity) +- Free latent nodes for unseen/unmodeled degradation +- Routing posterior over all nodes +- Geodesic severity coordinates on branches +- Spatial severity maps for non-uniform degradation +- Unknown residual for unexplained components +""" + +import math + +import torch +from typing import Optional, List, Tuple + + +# ============================================================================ +# Data Classes (using attrs for Python 3.9 compatibility) +# ============================================================================ + +class GraphRepresentation: + """ + Output of Phase 1: Blind Degradation Graph Encoder. + + This representation captures the complete degradation structure without + requiring degradation labels at inference time. + """ + + def __init__( + self, + content_latent: torch.Tensor, + node_tokens: torch.Tensor, + routing_probs: torch.Tensor, + severity_coords: torch.Tensor, + spatial_maps: Optional[torch.Tensor], + unknown_residual: Optional[torch.Tensor], + global_condition: torch.Tensor, + teacher_graph: Optional['GraphRepresentation'] = None, + photometric_state: Optional[torch.Tensor] = None, + photometric_shift: Optional[torch.Tensor] = None, + readout: Optional[torch.Tensor] = None, + ): + self.content_latent = content_latent + self.node_tokens = node_tokens + self.routing_probs = routing_probs + self.severity_coords = severity_coords + self.spatial_maps = spatial_maps + self.unknown_residual = unknown_residual + self.global_condition = global_condition + self.teacher_graph = teacher_graph + # v5 additions (all optional, None on legacy checkpoints): + # photometric_state [B, P] HVI colour/exposure state (PhotometricBranch) + # photometric_shift [B, 8] predicted global affine degraded->clean in HVI + # readout [B, R] pooled predictor input (metric-learning target) + self.photometric_state = photometric_state + self.photometric_shift = photometric_shift + self.readout = readout + + def get_semantic_tokens(self, K: int = 4) -> torch.Tensor: + return self.node_tokens[:, :K] + + def get_free_tokens(self, K: int = 4) -> torch.Tensor: + return self.node_tokens[:, K:] + + def detach_teacher(self): + if self.teacher_graph is not None: + return GraphRepresentation( + content_latent=self.teacher_graph.content_latent.detach(), + node_tokens=self.teacher_graph.node_tokens.detach(), + routing_probs=self.teacher_graph.routing_probs.detach(), + severity_coords=self.teacher_graph.severity_coords.detach(), + spatial_maps=self.teacher_graph.spatial_maps.detach() if self.teacher_graph.spatial_maps else None, + unknown_residual=self.teacher_graph.unknown_residual.detach() if self.teacher_graph.unknown_residual else None, + global_condition=self.teacher_graph.global_condition.detach(), + teacher_graph=None, + ) + return None + + +class BranchAnchor: + """Defines a semantic branch on the degradation graph.""" + + def __init__(self, name: str, embeddings: torch.Tensor, severity_values: torch.Tensor): + self.name = name + self.embeddings = embeddings + self.severity_values = severity_values + + @property + def num_anchors(self) -> int: + return len(self.severity_values) + + def interpolate(self, severity: torch.Tensor) -> torch.Tensor: + max_sev = self.severity_values[-1] + t = (severity / max_sev).clamp(0, 1) + idx = t * (self.num_anchors - 1) + idx_low = idx.floor().long().clamp(0, self.num_anchors - 2) + idx_high = idx.ceil().long().clamp(0, self.num_anchors - 1) + w = idx - idx_low.float() + emb_low = self.embeddings[idx_low] + emb_high = self.embeddings[idx_high] + return (1 - w.unsqueeze(-1)) * emb_low + w.unsqueeze(-1) * emb_high + + +class GraphConfig: + """Configuration for graph encoder.""" + + def __init__( + self, + latent_channels: int = 128, + node_dim: int = 256, + num_semantic_branches: int = 4, + num_free_nodes: int = 2, + branch_length: int = 8, + spatial_map_size: Tuple[int, int] = (16, 16), + clean_root_init: str = "zero", + use_ll_global: bool = False, + ll_global_dim: int = 128, + use_photometric: bool = False, + photometric_dim: int = 128, + ll_oriented_bands: bool = False, + routing_temperature: float = 1.0, + sparse_routing_weight: float = 0.01, + lambda_distill: float = 1.0, + lambda_root: float = 0.5, + lambda_branch: float = 1.0, + lambda_geodesic: float = 0.5, + lambda_ranking: float = 0.3, + lambda_content_inv: float = 0.2, + lambda_composition: float = 0.5, + lambda_sparse: float = 0.1, + lambda_utility: float = 0.3, + ): + self.latent_channels = latent_channels + self.node_dim = node_dim + self.num_semantic_branches = num_semantic_branches + self.num_free_nodes = num_free_nodes + self.branch_length = branch_length + self.spatial_map_size = spatial_map_size + self.clean_root_init = clean_root_init + self.use_ll_global = bool(use_ll_global) + self.ll_global_dim = int(ll_global_dim) + self.use_photometric = bool(use_photometric) + self.photometric_dim = int(photometric_dim) + self.ll_oriented_bands = bool(ll_oriented_bands) + self.routing_temperature = routing_temperature + self.sparse_routing_weight = sparse_routing_weight + self.lambda_distill = lambda_distill + self.lambda_root = lambda_root + self.lambda_branch = lambda_branch + self.lambda_geodesic = lambda_geodesic + self.lambda_ranking = lambda_ranking + self.lambda_content_inv = lambda_content_inv + self.lambda_composition = lambda_composition + self.lambda_sparse = lambda_sparse + self.lambda_utility = lambda_utility + + +# ============================================================================ +# Semantic Branch Definitions +# ============================================================================ + +SEMANTIC_BRANCH_NAMES = ["blur", "noise", "jpeg", "lowlight"] + +SEMANTIC_BRANCH_COLORS = { + "blur": "#FF6B6B", + "noise": "#4ECDC4", + "jpeg": "#45B7D1", + "lowlight": "#96CEB4", +} + + +# ============================================================================ +# Helper Functions +# ============================================================================ + +def aggregate_graph_condition( + node_tokens: torch.Tensor, + routing_probs: torch.Tensor, + severity_coords: torch.Tensor, + branch_anchors: List[BranchAnchor], + unknown_residual: Optional[torch.Tensor] = None, +) -> torch.Tensor: + B, N, D = node_tokens.shape + K = len(branch_anchors) + + branch_embs = node_tokens.new_zeros(B, K, D) + for k, branch in enumerate(branch_anchors): + branch_embs[:, k] = branch.get_branch_embedding(severity_coords[:, k]) + + # V2 aggregation: Phase 2 must receive the image-conditioned semantic node + # tokens as well as the learned ordered branch anchors. Scaling their sum + # preserves variance when the two states have comparable magnitude. + semantic_state = ( + branch_embs + node_tokens[:, :K] + ) / math.sqrt(2.0) + semantic_contrib = ( + routing_probs[:, :K].unsqueeze(-1) * semantic_state + ).sum(dim=1) + + free_tokens = node_tokens[:, K:] + free_routing = routing_probs[:, K:] + + if free_tokens.shape[1] > 0: + # routing_probs is already a posterior across semantic and free nodes. + # A second softmax incorrectly gave free tokens full mass even when the + # posterior assigned zero probability to every free route. + free_contrib = (free_routing.unsqueeze(-1) * free_tokens).sum(dim=1) + else: + free_contrib = node_tokens.new_zeros(B, D) + + condition = semantic_contrib + free_contrib + + if unknown_residual is not None: + condition = condition + unknown_residual + + return condition + + +__all__ = [ + "GraphRepresentation", + "BranchAnchor", + "GraphConfig", + "SEMANTIC_BRANCH_NAMES", + "SEMANTIC_BRANCH_COLORS", + "aggregate_graph_condition", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/__init__.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f2a87676ef1476bf48293c13fade4a00f815c720 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/__init__.py @@ -0,0 +1,6 @@ +"""Phase-2 restoration stacks. + +Import submodules directly (``graph_resshift_v4``, ``gated_graph_resshift_v5``, +``graph_moe_v6``, ``refiner_decoder``); this package init stays import-free so +no legacy module can break the living stack. +""" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/branch_adapters.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/branch_adapters.py new file mode 100644 index 0000000000000000000000000000000000000000..202a18f3333b88835399936f9921384870e5b24e --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/branch_adapters.py @@ -0,0 +1,379 @@ +""" +Branch Adapters for Compositional Graph Conditioning. + +Allows multiple degradation types to be active simultaneously. +Each branch has its own adapter modulated by routing probability and severity. +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +from typing import Optional, List, Dict + + +class BranchAdapter(nn.Module): + """ + Single branch adapter for degradation-specific processing. + + h' = h + p_k * φ(s_k) * A_k(h) + + Where: + - p_k: routing probability + - s_k: severity + - A_k: learned adapter + - φ: severity modulation + """ + + def __init__( + self, + channels: int, + routing_dim: int = 1, + rank: int = 4, + ): + super().__init__() + self.channels = channels + self.rank = rank + + # Low-rank adapter: depthwise-like modification + # A_k = U_k @ V_k where U, V are low-rank + self.U = nn.Parameter(torch.randn(channels, rank) * 0.02) + self.V = nn.Parameter(torch.randn(rank, channels) * 0.02) + + # Severity modulation: φ(s) = s * W + b + self.severity_proj = nn.Sequential( + nn.Linear(routing_dim, channels), + nn.Sigmoid(), # Modulate magnitude + ) + + # Routing projection (multi-label sigmoid -> [0,1]) + self.routing_proj = nn.Sequential( + nn.Linear(routing_dim, channels), + nn.Sigmoid(), + ) + + def forward( + self, + h: torch.Tensor, + routing: torch.Tensor, # [B] or [B, 1] + severity: torch.Tensor, # [B] or [B, 1] + ) -> torch.Tensor: + """ + Apply branch adapter. + + Args: + h: [B, C, H, W] features + routing: [B] or [B, 1] routing probability + severity: [B] or [B, 1] severity value + + Returns: + [B, C, H, W] adapted features + """ + B = h.shape[0] + + # Ensure correct shapes + if routing.dim() == 1: + routing = routing.unsqueeze(-1) + if severity.dim() == 1: + severity = severity.unsqueeze(-1) + + # Compute routing weight [B, C] + p = self.routing_proj(routing) # [B, C] + + # Compute severity modulation [B, C] + s = self.severity_proj(severity) # [B, C] + + # Low-rank adapter A = U @ V + A = self.U @ self.V # [C, C] + + # Compute adaptation: h + p * s * (A @ h) + # Using einsum for efficiency + h_flat = h.view(B, self.channels, -1) # [B, C, HW] + + # A @ h for each sample + Ah = torch.einsum('cd,bdn->bcn', A, h_flat) # [B, C, HW] + + # Weight by routing and severity + weight = p.unsqueeze(-1) * s.unsqueeze(-1) # [B, C, 1] + adapted = h_flat + weight * Ah + + return adapted.view_as(h) + + +class MultiBranchAdapters(nn.Module): + """ + Multiple branch adapters for compositional conditioning. + + Supports K semantic branches + U free nodes. + Each branch can be active simultaneously. + """ + + def __init__( + self, + channels: int, + num_semantic: int = 4, + num_free: int = 2, + rank: int = 4, + ): + super().__init__() + self.num_semantic = num_semantic + self.num_free = num_free + self.num_total = num_semantic + num_free + + # Semantic branch adapters + self.semantic_adapters = nn.ModuleList([ + BranchAdapter(channels, routing_dim=1, rank=rank) + for _ in range(num_semantic) + ]) + + # Free node adapters + self.free_adapters = nn.ModuleList([ + BranchAdapter(channels, routing_dim=1, rank=rank) + for _ in range(num_free) + ]) + + # Global residual adapter + self.global_adapter = nn.Sequential( + nn.Conv2d(channels, channels, 3, padding=1, groups=channels), + nn.Conv2d(channels, channels, 1), + nn.Sigmoid(), + ) + + def forward( + self, + h: torch.Tensor, + routing: torch.Tensor, # [B, K+U] multi-label probabilities + severity: Optional[torch.Tensor] = None, # [B, K] severity per semantic branch + free_mass: Optional[torch.Tensor] = None, # [B] total free node mass + ) -> torch.Tensor: + """ + Apply all branch adapters compositionally. + + Args: + h: [B, C, H, W] features + routing: [B, K+U] multi-label probabilities (sigmoid outputs) + severity: [B, K] severity per semantic branch + free_mass: [B] aggregated free node routing mass + + Returns: + [B, C, H, W] adapted features + """ + B = h.shape[0] + + # Start with input + adapted = h + + # Apply semantic branch adapters + for k in range(self.num_semantic): + p_k = routing[:, k] # [B] + + # Severity: use provided or default to 0.5 + s_k = severity[:, k] if severity is not None else torch.full((B,), 0.5, device=h.device) + + adapted = adapted + self.semantic_adapters[k](h, p_k, s_k) + + # Apply free node adapters + for u in range(self.num_free): + p_u = routing[:, self.num_semantic + u] # [B] + s_u = torch.ones(B, device=h.device) * 0.5 # Free nodes don't have severity + + adapted = adapted + self.free_adapters[u](h, p_u, s_u) + + # Global modulation + g = self.global_adapter(adapted) + adapted = adapted * g + + return adapted + + +class SpatialModulator(nn.Module): + """ + Spatial modulation from severity maps. + + Allows non-uniform degradation intensity across the image. + """ + + def __init__( + self, + channels: int, + map_size: int = 16, + ): + super().__init__() + self.map_size = map_size + + # Project spatial maps to modulation + self.proj = nn.ModuleList([ + nn.Sequential( + nn.AdaptiveAvgPool2d(map_size), + nn.Conv2d(1, channels, 3, padding=1), + nn.Sigmoid(), + ) + for _ in range(4) # 4 semantic branches + ]) + + def forward( + self, + h: torch.Tensor, + spatial_maps: torch.Tensor, # [B, K, H', W'] + ) -> torch.Tensor: + """ + Apply spatial modulation. + + Args: + h: [B, C, H, W] features + spatial_maps: [B, K, H', W'] severity maps per branch + + Returns: + [B, C, H, W] spatially modulated features + """ + B, C, H, W = h.shape + + # Resize maps to feature resolution + modulated = h.clone() + + for k in range(min(spatial_maps.shape[1], len(self.proj))): + m = spatial_maps[:, k:k+1] # [B, 1, H', W'] + m = F.interpolate(m, size=(H, W), mode='bilinear', align_corners=False) + + # Modulate features with spatial map + modulation = self.proj[k](m) # [B, C, H, W] + modulated = modulated * modulation + + return modulated + + +class GraphConditioning(nn.Module): + """ + Complete graph conditioning module. + + Transforms graph representation into conditioning signals. + """ + + def __init__( + self, + channels: int, + node_dim: int = 256, + num_semantic: int = 4, + num_free: int = 2, + ): + super().__init__() + self.channels = channels + self.num_semantic = num_semantic + self.num_free = num_free + + # Branch adapters at multiple scales + self.adapters_64 = MultiBranchAdapters(channels, num_semantic, num_free, rank=4) + self.adapters_32 = MultiBranchAdapters(channels * 2, num_semantic, num_free, rank=4) + self.adapters_16 = MultiBranchAdapters(channels * 4, num_semantic, num_free, rank=4) + + # FiLM conditioning from global graph state + self.film = nn.Sequential( + nn.Linear(node_dim, channels * 2), + ) + + # Spatial modulation + self.spatial = SpatialModulator(channels) + + def forward( + self, + features: Dict[str, torch.Tensor], + routing: torch.Tensor, # [B, K+U] + severity: torch.Tensor, # [B, K] + global_cond: torch.Tensor, # [B, D] + spatial_maps: Optional[torch.Tensor] = None, # [B, K, H', W'] + ) -> Dict[str, torch.Tensor]: + """ + Apply graph conditioning to features. + + Args: + features: dict of features at different scales + routing: multi-label routing probabilities + severity: severity per semantic branch + global_cond: global graph condition + spatial_maps: optional spatial severity maps + + Returns: + dict of conditioned features + """ + # FiLM parameters from global condition + film_params = self.film(global_cond) # [B, C*2] + gamma, beta = film_params.chunk(2, dim=-1) # [B, C] + + # Apply conditioning at each scale + conditioned = {} + + if '64' in features: + h = features['64'] + h = self.adapters_64(h, routing, severity) + + # Apply FiLM + h = h * (1 + gamma.unsqueeze(-1).unsqueeze(-1)) + h = h + beta.unsqueeze(-1).unsqueeze(-1) + + conditioned['64'] = h + + if '32' in features: + h = features['32'] + h = self.adapters_32(h, routing, severity) + conditioned['32'] = h + + if '16' in features: + h = features['16'] + h = self.adapters_16(h, routing, severity) + conditioned['16'] = h + + # Spatial modulation if available + if spatial_maps is not None: + if '64' in conditioned: + conditioned['64'] = self.spatial(conditioned['64'], spatial_maps) + + return conditioned + + +# ============================================================================ +# Tests +# ============================================================================ + +def test_branch_adapter(): + """Test branch adapter.""" + B, C, H, W = 4, 64, 32, 32 + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + adapter = BranchAdapter(C).to(device) + + h = torch.randn(B, C, H, W).to(device) + routing = torch.rand(B).to(device) # Multi-label sigmoid outputs + severity = torch.rand(B).to(device) + + out = adapter(h, routing, severity) + + print(f"Input: {h.shape}") + print(f"Output: {out.shape}") + print(f"Diff mean: {(out - h).abs().mean():.4f}") + print("Branch adapter test passed!") + + return True + + +def test_multi_branch(): + """Test multi-branch adapters.""" + B, C, H, W = 4, 64, 32, 32 + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + multi = MultiBranchAdapters(C, num_semantic=4, num_free=2).to(device) + + h = torch.randn(B, C, H, W).to(device) + routing = torch.rand(B, 6).to(device) # 4 semantic + 2 free + severity = torch.rand(B, 4).to(device) + + out = multi(h, routing, severity) + + print(f"Input: {h.shape}") + print(f"Output: {out.shape}") + print("Multi-branch test passed!") + + return True + + +if __name__ == "__main__": + test_branch_adapter() + test_multi_branch() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/gated_graph_resshift_v5.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/gated_graph_resshift_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..72594fc905f7a79c94733f3cfa0bad438f421f34 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/gated_graph_resshift_v5.py @@ -0,0 +1,641 @@ +"""Soft-gated restoration experts for Phase 2 v5. + +The module keeps the v4 residual-shift process unchanged. Phase-1 remains a +frozen continuous representation learner: its four semantic routing slots and +two free slots become a five-way soft prior (four known degradations plus one +generic expert). The learned router only applies a bounded residual correction +and never receives a clean image or a degradation label. + +DA-CLIP motivates the separation used here. Content follows the existing +shared restoration path, while degradation control is injected as a learned +noise/time prompt and through zero-initialized low-rank expert adapters. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Any, Sequence, Tuple + +import torch +from torch import Tensor, nn +import torch.nn.functional as F + +from .graph_resshift_v4 import ( + ConditionBundle, + GraphConditionerV4, + GraphResidualShiftUNetV4, +) + + +EXPERT_ORDER: Tuple[str, ...] = ( + "rain", + "noise", + "haze", + "lowlight", + "generic", +) +NOISE_MIXER_VERSION = "shared_plus_l2_expert_gaussian_v1" +ROUTER_VERSION = "phase1_prior_bounded_residual_v1" +EXPERT_KAPPA_VERSION = "log_space_gate_convex_anneal_v1" + + +def _field(representation: Any, name: str) -> Tensor: + if isinstance(representation, dict): + value = representation.get(name) + else: + value = getattr(representation, name, None) + if not isinstance(value, Tensor): + raise ValueError("Phase-1 representation is missing tensor field %s" % name) + return value + + +def _require_finite(value: Tensor, name: str) -> None: + if not bool(torch.isfinite(value).all()): + raise ValueError("%s must contain only finite values" % name) + + +@dataclass +class RouterOutput: + """Continuous router outputs and differentiable anti-collapse penalties.""" + + gates: Tensor + prior: Tensor + correction: Tensor + anchor_loss: Tensor + balance_loss: Tensor + correction_loss: Tensor + + +class SoftDegradationRouter(nn.Module): + """Refine the Phase-1 routing posterior without making a hard decision. + + Slots 0..3 retain the checkpoint-validated order rain/noise/haze/lowlight. + All remaining Phase-1 mass is assigned to one generic/free expert. A + zero-initialized bounded correction makes the initial gate equal to that + prior while still allowing downstream restoration loss to refine it. + """ + + def __init__( + self, + node_dim: int = 256, + num_nodes: int = 6, + num_semantic: int = 4, + hidden_dim: int = 256, + temperature: float = 1.0, + max_correction: float = 2.0, + epsilon: float = 1e-8, + ) -> None: + super().__init__() + if num_semantic != len(EXPERT_ORDER) - 1: + raise ValueError("v5 requires exactly four semantic Phase-1 routes") + if num_nodes <= num_semantic: + raise ValueError("v5 requires at least one free Phase-1 route") + if node_dim <= 0 or hidden_dim <= 0: + raise ValueError("router dimensions must be positive") + if not math.isfinite(temperature) or temperature <= 0.0: + raise ValueError("router temperature must be finite and positive") + if not math.isfinite(max_correction) or max_correction <= 0.0: + raise ValueError("max_correction must be finite and positive") + if not math.isfinite(epsilon) or epsilon <= 0.0: + raise ValueError("epsilon must be finite and positive") + + self.node_dim = int(node_dim) + self.num_nodes = int(num_nodes) + self.num_semantic = int(num_semantic) + self.num_experts = self.num_semantic + 1 + self.temperature = float(temperature) + self.max_correction = float(max_correction) + self.epsilon = float(epsilon) + + # A routing-weighted node summary and the unknown residual are + # degradation-side signals. content_latent is deliberately excluded. + input_dim = node_dim * 2 + num_nodes + num_semantic + self.correction_net = nn.Sequential( + nn.LayerNorm(input_dim), + nn.Linear(input_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, self.num_experts), + ) + final = self.correction_net[-1] + if not isinstance(final, nn.Linear): + raise RuntimeError("router correction head must be linear") + nn.init.zeros_(final.weight) + nn.init.zeros_(final.bias) + + def forward(self, representation: Any) -> RouterOutput: + node_tokens = _field(representation, "node_tokens") + routing = _field(representation, "routing_probs") + severity = _field(representation, "severity_coords") + unknown = _field(representation, "unknown_residual") + + if node_tokens.ndim != 3 or node_tokens.shape[1:] != ( + self.num_nodes, + self.node_dim, + ): + raise ValueError( + "node_tokens must have shape [B, %d, %d]" + % (self.num_nodes, self.node_dim) + ) + batch = node_tokens.shape[0] + if routing.shape != (batch, self.num_nodes): + raise ValueError( + "routing_probs must have shape [B, %d]" % self.num_nodes + ) + if severity.shape != (batch, self.num_semantic): + raise ValueError( + "severity_coords must have shape [B, %d]" % self.num_semantic + ) + if unknown.shape != (batch, self.node_dim): + raise ValueError( + "unknown_residual must have shape [B, %d]" % self.node_dim + ) + for name, value in ( + ("node_tokens", node_tokens), + ("routing_probs", routing), + ("severity_coords", severity), + ("unknown_residual", unknown), + ): + _require_finite(value, name) + if bool(torch.any(routing < 0)): + raise ValueError("routing_probs must be non-negative") + + total_mass = routing.sum(dim=1, keepdim=True) + if bool(torch.any(total_mass <= 0)): + raise ValueError("routing_probs must have positive total mass") + routing = routing / total_mass + prior = torch.cat( + ( + routing[:, : self.num_semantic], + routing[:, self.num_semantic :].sum(dim=1, keepdim=True), + ), + dim=1, + ) + weighted_nodes = torch.sum(node_tokens * routing.unsqueeze(-1), dim=1) + router_features = torch.cat( + (weighted_nodes, unknown, routing, severity), dim=1 + ) + raw_correction = self.correction_net(router_features) + correction = self.max_correction * torch.tanh(raw_correction) + + # Temperature scales only the learned correction. Therefore a + # zero-initialized router exactly preserves the Phase-1 prior even when + # a non-default temperature is selected. + logits = torch.log(prior.clamp_min(self.epsilon)) + logits = logits + correction / self.temperature + gates = torch.softmax(logits, dim=1) + + detached_prior = prior.detach().clamp_min(self.epsilon) + anchor_loss = torch.sum( + detached_prior + * (torch.log(detached_prior) - torch.log(gates.clamp_min(self.epsilon))), + dim=1, + ).mean() + semantic_gate = gates[:, : self.num_semantic] + semantic_gate = semantic_gate / semantic_gate.sum( + dim=1, keepdim=True + ).clamp_min(self.epsilon) + semantic_usage = semantic_gate.mean(dim=0) + balance_loss = ( + self.num_semantic * semantic_usage.square().sum() - 1.0 + ) + correction_loss = correction.square().mean() + return RouterOutput( + gates=gates, + prior=prior, + correction=correction, + anchor_loss=anchor_loss, + balance_loss=balance_loss, + correction_loss=correction_loss, + ) + + +@dataclass +class GatedConditionBundleV5(ConditionBundle): + """v4 conditions plus a five-way degradation control signal.""" + + expert_gates: Tensor + gate_prior: Tensor + gate_correction: Tensor + route_active: Tensor + router_anchor_loss: Tensor + router_balance_loss: Tensor + router_correction_loss: Tensor + + +class GatedGraphConditionerV5(GraphConditionerV4): + """Keep the v4 content path and add a separate degradation router.""" + + def __init__( + self, + cond_dim: int = 256, + stage_dims: Sequence[int] = (64, 128, 192, 256), + node_dim: int = 256, + content_channels: int = 128, + spatial_channels: int = 4, + num_nodes: int = 6, + num_severity: int = 4, + router_hidden_dim: int = 256, + router_temperature: float = 1.0, + router_max_correction: float = 2.0, + ) -> None: + super().__init__( + cond_dim=cond_dim, + stage_dims=stage_dims, + node_dim=node_dim, + content_channels=content_channels, + spatial_channels=spatial_channels, + num_nodes=num_nodes, + num_severity=num_severity, + ) + self.router = SoftDegradationRouter( + node_dim=node_dim, + num_nodes=num_nodes, + num_semantic=num_severity, + hidden_dim=router_hidden_dim, + temperature=router_temperature, + max_correction=router_max_correction, + ) + + def forward(self, representation: Any, mode: str = "full") -> GatedConditionBundleV5: + base = super().forward(representation, mode=mode) + routed = self.router(representation) + batch = routed.gates.shape[0] + active_value = 1.0 if mode == "full" else 0.0 + active = routed.gates.new_full((batch, 1), active_value) + gates = routed.gates * active + active_scalar = active.mean() + return GatedConditionBundleV5( + context=base.context, + global_vector=base.global_vector, + content=base.content, + spatial=base.spatial, + expert_gates=gates, + gate_prior=routed.prior * active, + gate_correction=routed.correction * active, + route_active=active, + router_anchor_loss=routed.anchor_loss * active_scalar, + router_balance_loss=routed.balance_loss * active_scalar, + router_correction_loss=routed.correction_loss * active_scalar, + ) + + +class GatedAdapterBank(nn.Module): + """Low-rank residual experts mixed by a per-image soft gate.""" + + def __init__(self, channels: int, rank: int, num_experts: int = 5) -> None: + super().__init__() + if channels <= 0 or rank <= 0 or num_experts <= 0: + raise ValueError("adapter dimensions and expert count must be positive") + self.channels = int(channels) + self.rank = int(rank) + self.num_experts = int(num_experts) + self.experts = nn.ModuleList() + for _ in range(self.num_experts): + expert = nn.Sequential( + nn.Conv2d(channels, rank, 1), + nn.SiLU(), + nn.Conv2d(rank, channels, 1), + ) + output = expert[-1] + if not isinstance(output, nn.Conv2d): + raise RuntimeError("adapter output must be a convolution") + nn.init.zeros_(output.weight) + nn.init.zeros_(output.bias) + self.experts.append(expert) + + def residual(self, features: Tensor, gates: Tensor) -> Tensor: + if features.ndim != 4 or features.shape[1] != self.channels: + raise ValueError( + "adapter features must have shape [B, %d, H, W]" % self.channels + ) + if gates.shape != (features.shape[0], self.num_experts): + raise ValueError( + "adapter gates must have shape [B, %d]" % self.num_experts + ) + _require_finite(gates, "adapter gates") + residual = torch.zeros_like(features) + for index, expert in enumerate(self.experts): + weight = gates[:, index].reshape(-1, 1, 1, 1) + residual = residual + expert(features) * weight + return residual + + def forward(self, features: Tensor, gates: Tensor) -> Tensor: + return features + self.residual(features, gates) + + +class ExpertKappaSchedule(nn.Module): + """Per-sample forward-corruption kappa derived from the soft gate. + + Kappa calibration measures per-domain residual RMS, yet a single global + kappa mis-scales the corruption by up to ~11x between lowlight and noise. + This module interpolates per-expert kappas in log-space with the DETACHED + gate, so the router can never reduce its loss by weakening the corruption. + + An integer microstep counter anneals from the global kappa (bitwise + v4-equivalent at zero) to the routed value. The counter is a long buffer: + EMA copies non-floating buffers verbatim and resume restores it, so the + anneal survives both without drift. Kappa is constant along each sample's + chain, therefore the exact ResShift posterior stays valid per sample. + """ + + def __init__( + self, + kappa_per_expert: Sequence[float], + kappa_global: float, + anneal_microsteps: int, + num_experts: int = len(EXPERT_ORDER), + epsilon: float = 1e-8, + ) -> None: + super().__init__() + if num_experts <= 0: + raise ValueError("num_experts must be positive") + values = [float(value) for value in kappa_per_expert] + if len(values) != num_experts: + raise ValueError( + "expected %d per-expert kappa values" % num_experts + ) + if any(not math.isfinite(value) or value <= 0.0 for value in values): + raise ValueError("per-expert kappas must be finite and positive") + if not math.isfinite(kappa_global) or kappa_global <= 0.0: + raise ValueError("global kappa must be finite and positive") + if int(anneal_microsteps) < 0: + raise ValueError("anneal_microsteps must be non-negative") + if not math.isfinite(epsilon) or epsilon <= 0.0: + raise ValueError("epsilon must be finite and positive") + self.num_experts = int(num_experts) + self.epsilon = float(epsilon) + experts = torch.tensor(values, dtype=torch.float32) + self.register_buffer("kappa_experts", experts) + self.register_buffer("log_kappa_experts", torch.log(experts)) + global_value = torch.tensor(float(kappa_global), dtype=torch.float32) + self.register_buffer("kappa_global", global_value) + self.register_buffer("log_kappa_global", torch.log(global_value)) + self.register_buffer( + "anneal_microsteps", + torch.tensor(int(anneal_microsteps), dtype=torch.long), + ) + self.register_buffer( + "microsteps_seen", torch.tensor(0, dtype=torch.long) + ) + + def alpha(self) -> Tensor: + """Anneal weight in [0, 1]; exactly one when annealing is disabled.""" + + if int(self.anneal_microsteps) <= 0: + return self.kappa_global.new_tensor(1.0) + ratio = self.microsteps_seen.float() / self.anneal_microsteps.float() + return ratio.clamp(0.0, 1.0) + + def advance(self) -> None: + """Advance the anneal by one training microstep.""" + + self.microsteps_seen += 1 + + def forward(self, gates: Tensor, route_active: Tensor) -> Tensor: + if gates.ndim != 2 or gates.shape[1] != self.num_experts: + raise ValueError( + "gates must have shape [B, %d]" % self.num_experts + ) + batch = gates.shape[0] + if route_active.ndim == 1: + route_active = route_active.unsqueeze(1) + if route_active.shape != (batch, 1): + raise ValueError("route_active must have shape [B, 1]") + # Detaching here makes "router weakens its own corruption" impossible + # by construction rather than by call-site discipline. + gates = gates.detach().float() + active = route_active.detach().float().squeeze(1) + _require_finite(gates, "expert kappa gates") + _require_finite(active, "route_active") + if bool(torch.any(gates < 0)): + raise ValueError("gates must be non-negative") + if bool(torch.any(active < 0)) or bool(torch.any(active > 1)): + raise ValueError("route_active must lie in [0, 1]") + + mass = gates.sum(dim=1, keepdim=True) + uniform = torch.full_like(gates, 1.0 / self.num_experts) + normalized = torch.where( + mass > 0, gates / mass.clamp_min(self.epsilon), uniform + ) + log_routed = normalized @ self.log_kappa_experts + weight = self.alpha().to(active) * active + mixed = (1.0 - weight) * self.log_kappa_global + weight * log_routed + # The fallback keeps warm-start and null-mode kappa bitwise equal to + # the global value (exp(log(k)) may differ from k by one ulp). + return torch.where( + weight > 0, torch.exp(mixed), self.kappa_global.expand(batch) + ) + + +class VariancePreservingNoiseMixer(nn.Module): + """Mix independent expert Gaussian streams without shrinking variance. + + The bank layout is ``[shared, expert_0, ..., expert_K-1]``. Expert weights + are L2-normalized, hence their conditional variance is one. A configured + fraction then combines that routed stream with the legacy shared Gaussian. + The gate is detached in this stochastic branch so the router cannot reduce + its loss by manipulating the forward corruption instead of restoration. + """ + + def __init__(self, num_experts: int = 5, expert_fraction: float = 0.0) -> None: + super().__init__() + if num_experts <= 0: + raise ValueError("num_experts must be positive") + if not math.isfinite(expert_fraction) or not 0.0 <= expert_fraction <= 1.0: + raise ValueError("expert_fraction must lie in [0, 1]") + self.num_experts = int(num_experts) + self.expert_fraction_value = float(expert_fraction) + + def forward( + self, + noise_bank: Tensor, + gates: Tensor, + route_active: Tensor, + ) -> Tensor: + if noise_bank.ndim != 5 or noise_bank.shape[1] != self.num_experts + 1: + raise ValueError( + "noise bank must have shape [B, %d, C, H, W]" + % (self.num_experts + 1) + ) + batch = noise_bank.shape[0] + if gates.shape != (batch, self.num_experts): + raise ValueError( + "noise gate must have shape [B, %d]" % self.num_experts + ) + if route_active.ndim == 1: + route_active = route_active.unsqueeze(1) + if route_active.shape != (batch, 1): + raise ValueError("route_active must have shape [B, 1]") + _require_finite(gates, "noise gate") + _require_finite(route_active, "route_active") + if bool(torch.any(gates < 0)): + raise ValueError("noise gate must be non-negative") + if bool(torch.any(route_active < 0)) or bool(torch.any(route_active > 1)): + raise ValueError("route_active must lie in [0, 1]") + if self.expert_fraction_value == 0.0: + _require_finite(noise_bank[:, 0], "shared noise") + return noise_bank[:, 0] + _require_finite(noise_bank, "noise bank") + + active = route_active.detach().float() + detached_gates = gates.detach().float() + # In null mode the effective gate is zero. Substitute a harmless + # uniform vector for the unused expert computation and force rho=0. + uniform = torch.full_like(detached_gates, 1.0 / self.num_experts) + safe_gates = torch.where(active > 0.0, detached_gates, uniform) + norm = safe_gates.square().sum(dim=1, keepdim=True).sqrt() + if bool(torch.any(norm <= 0)): + raise ValueError("active noise gate must have non-zero L2 norm") + weights = (safe_gates / norm).to(dtype=noise_bank.dtype) + routed = torch.sum( + noise_bank[:, 1:] * weights[:, :, None, None, None], dim=1 + ) + + # ``expert_fraction_value`` is intentionally not duplicated in the + # state dict. The checkpoint contract validates it before strict + # weight loading, leaving one authoritative source of truth. + rho = active.new_tensor(self.expert_fraction_value) * active + shared_weight = torch.sqrt((1.0 - rho).clamp_min(0.0)).to( + dtype=noise_bank.dtype + ) + routed_weight = torch.sqrt(rho.clamp_min(0.0)).to(dtype=noise_bank.dtype) + return ( + noise_bank[:, 0] * shared_weight[:, :, None, None] + + routed * routed_weight[:, :, None, None] + ) + + +class GatedGraphResidualShiftUNetV5(GraphResidualShiftUNetV4): + """v4 shared U-Net with seven soft expert adapters and a noise prompt.""" + + def __init__( + self, + dims: Sequence[int] = (64, 128, 192, 256), + cond_dim: int = 256, + state_channels: int = 12, + dropout: float = 0.0, + adapter_rank: int = 16, + num_experts: int = 5, + ) -> None: + super().__init__( + dims=dims, + cond_dim=cond_dim, + state_channels=state_channels, + dropout=dropout, + ) + if num_experts != len(EXPERT_ORDER): + raise ValueError("v5 expert count must match EXPERT_ORDER") + self.num_experts = int(num_experts) + self.adapter_rank = int(adapter_rank) + embedding_dim = max(cond_dim * 2, self.dims[-1]) + self.noise_type_tokens = nn.Parameter( + torch.zeros(self.num_experts, embedding_dim) + ) + self.down_experts = nn.ModuleList( + GatedAdapterBank(channels, adapter_rank, self.num_experts) + for channels in self.dims + ) + self.up_experts = nn.ModuleList( + GatedAdapterBank(self.dims[index], adapter_rank, self.num_experts) + for index in (2, 1, 0) + ) + + def noise_prompt(self, gates: Tensor) -> Tensor: + if gates.ndim != 2 or gates.shape[1] != self.num_experts: + raise ValueError( + "noise prompt gates must have shape [B, %d]" % self.num_experts + ) + return gates.to(dtype=self.noise_type_tokens.dtype) @ self.noise_type_tokens + + def forward( + self, + u_t: Tensor, + u_y: Tensor, + timesteps: Tensor, + condition: GatedConditionBundleV5, + ) -> Tensor: + if u_t.shape != u_y.shape: + raise ValueError("u_t and u_y must have identical shapes") + if u_t.ndim != 4 or u_t.shape[1] != self.state_channels: + raise ValueError( + "diffusion states must have shape [B, %d, H, W]" + % self.state_channels + ) + if timesteps.ndim == 0: + timesteps = timesteps.expand(u_t.shape[0]) + if timesteps.ndim != 1 or timesteps.shape[0] != u_t.shape[0]: + raise ValueError("one timestep is required per batch element") + if condition.context.shape[0] != u_t.shape[0]: + raise ValueError("condition and diffusion state batches must match") + if condition.expert_gates.shape != (u_t.shape[0], self.num_experts): + raise ValueError("condition has an invalid expert gate shape") + + embedding = self.time_embedding(timesteps) + embedding = embedding.to(dtype=u_t.dtype) + self.global_embedding( + condition.global_vector + ) + embedding = embedding + self.noise_prompt(condition.expert_gates).to( + dtype=embedding.dtype + ) + features = self.input_projection(torch.cat((u_t, u_y, u_t - u_y), dim=1)) + + skips = [] + for index in range(4): + if index == 1: + content = F.interpolate( + condition.content, + size=features.shape[-2:], + mode="bilinear", + align_corners=False, + ) + features = features + self.content_inject(content) + if index == 3: + spatial = F.interpolate( + condition.spatial, + size=features.shape[-2:], + mode="bilinear", + align_corners=False, + ) + features = features + self.spatial_inject(spatial) + for block in self.down_blocks[index]: + features = block(features, embedding) + features = self._attend( + self.down_attentions[index], features, condition.context + ) + features = self.down_experts[index](features, condition.expert_gates) + skips.append(features) + if index < 3: + features = self.downsamples[index](features) + + for up_index, stage_index in enumerate((2, 1, 0)): + skip = skips[stage_index] + features = self.upsamples[up_index](features, skip.shape[-2:]) + features = torch.cat((features, skip), dim=1) + for block in self.up_blocks[up_index]: + features = block(features, embedding) + features = self._attend( + self.up_attentions[up_index], features, condition.context + ) + features = self.up_experts[up_index]( + features, condition.expert_gates + ) + + delta = self.output_residual(F.silu(self.output_norm(features))) + return u_y + delta + + +__all__ = [ + "EXPERT_KAPPA_VERSION", + "EXPERT_ORDER", + "NOISE_MIXER_VERSION", + "ROUTER_VERSION", + "ExpertKappaSchedule", + "GatedAdapterBank", + "GatedConditionBundleV5", + "GatedGraphConditionerV5", + "GatedGraphResidualShiftUNetV5", + "RouterOutput", + "SoftDegradationRouter", + "VariancePreservingNoiseMixer", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/graph_moe_v6.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/graph_moe_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..b816258e7988f7f0e9701aba4b05b823f6ed8bf5 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/graph_moe_v6.py @@ -0,0 +1,378 @@ +"""Graph-MoE v6: node-bound experts selected on the degradation graph. + +Design decisions, each anchored to a measured failure of v4/v5: + +* Independent sigmoid activations per semantic node replace the 5-way + softmax (softmax forced degradations to compete for mass and punished + honest null-detection; doc section 7/P2 and the honest-null probe). +* Expert strength ``s_k = a_k * severity_k`` separates "is it present" + from "how hard to work" (severity was measured but unused by v5). +* Spatial gating from the Phase-1 16x16 maps lets experts act per region + (mixed degradations stop averaging each other out). +* Experts carry a 3x3 depthwise stage, giving them the receptive field the + rank-16 1x1 adapters lacked (noise/rain bottleneck in A7). +* Only the top-2 strongest experts execute; Phase-1's inactive-suppression + training makes node activations naturally sparse. + +Torch 1.10 compatible. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Any, Optional, Sequence, Tuple + +import torch +from torch import Tensor, nn +import torch.nn.functional as F + +from .gated_graph_resshift_v5 import EXPERT_ORDER, ExpertKappaSchedule, _field, _require_finite +from .graph_resshift_v4 import ( + ConditionBundle, + GraphConditionerV4, + GraphResidualShiftUNetV4, +) + +MOE_V6_VERSION = "node_bound_spatial_top2_v1" +NUM_EXPERTS = len(EXPERT_ORDER) # rain, noise, haze, lowlight, generic + + +@dataclass +class NodeGateOutput: + activations: Tensor # [B, 5] independent, in (0, 1) + strengths: Tensor # [B, 5] a_k * severity_k (generic: a_g) + top2_mask: Tensor # [B, 5] binary execution mask + spatial_gates: Tensor # [B, 4, H, W] semantic per-region weights + prior: Tensor # [B, 5] Phase-1 derived prior activations + anchor_loss: Tensor + correction_loss: Tensor + + +class NodeActivationGate(nn.Module): + """Independent per-node activations with a bounded learned correction. + + The prior comes straight from the Phase-1 posterior: semantic slot mass + for the four known nodes and total free mass for the generic node. A + zero-initialized tanh correction keeps the initial gate exactly at the + prior. Nothing here sees content, labels, or clean targets. + """ + + def __init__( + self, + node_dim: int = 256, + num_nodes: int = 6, + num_semantic: int = 4, + hidden_dim: int = 128, + max_correction: float = 1.0, + spatial_blend_init: float = 0.5, + epsilon: float = 1e-6, + ) -> None: + super().__init__() + if num_semantic + 1 != NUM_EXPERTS: + raise ValueError("v6 expects four semantic nodes plus generic") + if num_nodes <= num_semantic: + raise ValueError("v6 requires at least one free Phase-1 slot") + self.num_semantic = int(num_semantic) + self.num_nodes = int(num_nodes) + self.epsilon = float(epsilon) + self.max_correction = float(max_correction) + input_dim = node_dim * 2 + num_nodes + num_semantic + self.correction_net = nn.Sequential( + nn.LayerNorm(input_dim), + nn.Linear(input_dim, hidden_dim), + nn.SiLU(), + nn.Linear(hidden_dim, NUM_EXPERTS), + ) + final = self.correction_net[-1] + nn.init.zeros_(final.weight) + nn.init.zeros_(final.bias) + # Per-expert blend between global strength and the spatial map; + # sigmoid(logit) keeps it in (0, 1). + blend_logit = math.log(spatial_blend_init / (1 - spatial_blend_init)) + self.spatial_blend_logit = nn.Parameter( + torch.full((self.num_semantic,), blend_logit) + ) + + def forward(self, representation: Any) -> NodeGateOutput: + node_tokens = _field(representation, "node_tokens") + routing = _field(representation, "routing_probs") + severity = _field(representation, "severity_coords") + unknown = _field(representation, "unknown_residual") + spatial_maps = _field(representation, "spatial_maps") + batch = node_tokens.shape[0] + for name, value in ( + ("routing_probs", routing), + ("severity_coords", severity), + ("spatial_maps", spatial_maps), + ): + _require_finite(value, name) + if bool(torch.any(routing < 0)): + raise ValueError("routing_probs must be non-negative") + + mass = routing.sum(dim=1, keepdim=True).clamp_min(self.epsilon) + posterior = routing / mass + prior = torch.cat( + ( + posterior[:, : self.num_semantic], + posterior[:, self.num_semantic:].sum(dim=1, keepdim=True), + ), + dim=1, + ).clamp(self.epsilon, 1.0 - self.epsilon) + + weighted_nodes = torch.sum( + node_tokens * posterior.unsqueeze(-1), dim=1 + ) + features = torch.cat( + (weighted_nodes, unknown, posterior, severity), dim=1 + ) + correction = self.max_correction * torch.tanh( + self.correction_net(features) + ) + logits = torch.log(prior) - torch.log1p(-prior) + correction + activations = torch.sigmoid(logits) + + strengths = torch.cat( + ( + activations[:, : self.num_semantic] + * severity.clamp(0.0, 1.0), + activations[:, self.num_semantic:], + ), + dim=1, + ) + top2 = torch.topk(strengths, k=2, dim=1).indices + top2_mask = torch.zeros_like(strengths) + top2_mask.scatter_(1, top2, 1.0) + + blend = torch.sigmoid(self.spatial_blend_logit).view(1, -1, 1, 1) + maps = spatial_maps.clamp(0.0, 1.0) + spatial_gates = (1.0 - blend) + blend * maps + + # BCE-with-logits is the autocast-safe form of the prior anchor. + anchor = F.binary_cross_entropy_with_logits( + logits.float(), prior.detach().float() + ) + return NodeGateOutput( + activations=activations, + strengths=strengths, + top2_mask=top2_mask, + spatial_gates=spatial_gates, + prior=prior, + anchor_loss=anchor, + correction_loss=correction.square().mean(), + ) + + +@dataclass +class MoEConditionBundleV6(ConditionBundle): + gate: NodeGateOutput = None + route_active: Tensor = None + + +class MoEGraphConditionerV6(GraphConditionerV4): + """v4 content path plus the independent node-activation gate.""" + + def __init__( + self, + *args, + gate_hidden_dim: int = 128, + gate_max_correction: float = 1.0, + **kwargs, + ) -> None: + super().__init__(*args, **kwargs) + self.node_gate = NodeActivationGate( + node_dim=int(kwargs.get("node_dim", 256)), + hidden_dim=int(gate_hidden_dim), + max_correction=float(gate_max_correction), + ) + + def forward(self, representation: Any, mode: str = "full") -> MoEConditionBundleV6: + base = super().forward(representation, mode=mode) + gate = self.node_gate(representation) + active_value = 1.0 if mode == "full" else 0.0 + active = gate.strengths.new_full( + (gate.strengths.shape[0], 1), active_value + ) + gated = NodeGateOutput( + activations=gate.activations * active, + strengths=gate.strengths * active, + top2_mask=gate.top2_mask, + spatial_gates=gate.spatial_gates, + prior=gate.prior * active, + anchor_loss=gate.anchor_loss * active.mean(), + correction_loss=gate.correction_loss * active.mean(), + ) + return MoEConditionBundleV6( + context=base.context, + global_vector=base.global_vector, + content=base.content, + spatial=base.spatial, + gate=gated, + route_active=active, + ) + + +class SpatialExpertBank(nn.Module): + """Five node-bound experts with a 3x3 depthwise core and spatial gates. + + residual = sum_k strength_k * mask_k * G_k(x, y) * A_k(h) + Semantic experts are modulated by their upsampled Phase-1 map; the + generic expert applies globally. Outputs are zero-initialized. + """ + + def __init__(self, channels: int, rank: int = 16) -> None: + super().__init__() + self.channels = int(channels) + self.num_semantic = NUM_EXPERTS - 1 + self.experts = nn.ModuleList() + for _ in range(NUM_EXPERTS): + expert = nn.Sequential( + nn.Conv2d(channels, rank, 1), + nn.SiLU(), + nn.Conv2d(rank, rank, 3, padding=1, groups=rank), + nn.SiLU(), + nn.Conv2d(rank, channels, 1), + ) + nn.init.zeros_(expert[-1].weight) + nn.init.zeros_(expert[-1].bias) + self.experts.append(expert) + + def forward(self, features: Tensor, gate: NodeGateOutput) -> Tensor: + """Every expert is evaluated on every call (an unused expert is + multiplied by an exactly-zero weight, so the result is bitwise the + same as skipping it). Data-dependent skipping made the set of + parameters in the autograd graph differ between the micro-batches of + one DDP iteration, which DistributedDataParallel with gradient + accumulation (``no_sync``) and ``find_unused_parameters`` rejects + ("Expected to mark a variable ready only once", v11 stage A, step + 250). The experts are rank-16 1x1/depthwise convs: negligible cost.""" + + if features.shape[1] != self.channels: + raise ValueError("expert bank channel mismatch") + weights = gate.strengths * gate.top2_mask # [B, 5] + maps = F.interpolate( + gate.spatial_gates, size=features.shape[-2:], + mode="bilinear", align_corners=False, + ) + residual = torch.zeros_like(features) + for index, expert in enumerate(self.experts): + weight = weights[:, index] + contribution = expert(features) * weight.view(-1, 1, 1, 1) + if index < self.num_semantic: + contribution = contribution * maps[:, index: index + 1] + residual = residual + contribution + return features + residual + + +class MoEGraphResidualShiftUNetV6(GraphResidualShiftUNetV4): + """v4 trunk with spatial node-bound experts and a strength prompt.""" + + def __init__( + self, + dims: Sequence[int] = (64, 128, 192, 256), + cond_dim: int = 256, + state_channels: int = 12, + dropout: float = 0.0, + expert_rank: int = 16, + ) -> None: + super().__init__( + dims=dims, cond_dim=cond_dim, + state_channels=state_channels, dropout=dropout, + ) + embedding_dim = max(cond_dim * 2, self.dims[-1]) + self.strength_tokens = nn.Parameter( + torch.zeros(NUM_EXPERTS, embedding_dim) + ) + self.down_experts = nn.ModuleList( + SpatialExpertBank(channels, expert_rank) for channels in self.dims + ) + self.up_experts = nn.ModuleList( + SpatialExpertBank(self.dims[index], expert_rank) + for index in (2, 1, 0) + ) + + def forward( + self, + u_t: Tensor, + u_y: Tensor, + timesteps: Tensor, + condition: MoEConditionBundleV6, + ) -> Tensor: + if timesteps.ndim == 0: + timesteps = timesteps.expand(u_t.shape[0]) + embedding = self.time_embedding(timesteps) + embedding = embedding.to(dtype=u_t.dtype) + self.global_embedding( + condition.global_vector + ) + embedding = embedding + ( + condition.gate.strengths.to(self.strength_tokens.dtype) + @ self.strength_tokens + ).to(embedding.dtype) + features = self.input_projection( + torch.cat((u_t, u_y, u_t - u_y), dim=1) + ) + skips = [] + for index in range(4): + if index == 1: + content = F.interpolate( + condition.content, size=features.shape[-2:], + mode="bilinear", align_corners=False, + ) + features = features + self.content_inject(content) + if index == 3: + spatial = F.interpolate( + condition.spatial, size=features.shape[-2:], + mode="bilinear", align_corners=False, + ) + features = features + self.spatial_inject(spatial) + for block in self.down_blocks[index]: + features = block(features, embedding) + features = self._attend( + self.down_attentions[index], features, condition.context + ) + features = self.down_experts[index](features, condition.gate) + skips.append(features) + if index < 3: + features = self.downsamples[index](features) + for up_index, stage_index in enumerate((2, 1, 0)): + skip = skips[stage_index] + features = self.upsamples[up_index](features, skip.shape[-2:]) + features = torch.cat((features, skip), dim=1) + for block in self.up_blocks[up_index]: + features = block(features, embedding) + features = self._attend( + self.up_attentions[up_index], features, condition.context + ) + features = self.up_experts[up_index](features, condition.gate) + delta = self.output_residual(F.silu(self.output_norm(features))) + return u_y + delta + + +def expert_kappa_from_strengths( + kappa_module: ExpertKappaSchedule, + gate: NodeGateOutput, + route_active: Tensor, +) -> Tensor: + """Per-sample kappa from normalized strengths (global fallback at zero).""" + strengths = gate.strengths.detach() + total = strengths.sum(dim=1, keepdim=True) + normalized = torch.where( + total > 1e-6, + strengths / total.clamp_min(1e-6), + torch.full_like(strengths, 1.0 / NUM_EXPERTS), + ) + effective_active = route_active * (total > 1e-6).float() + return kappa_module(normalized, effective_active) + + +__all__ = [ + "MOE_V6_VERSION", + "NUM_EXPERTS", + "MoEConditionBundleV6", + "MoEGraphConditionerV6", + "MoEGraphResidualShiftUNetV6", + "NodeActivationGate", + "NodeGateOutput", + "SpatialExpertBank", + "expert_kappa_from_strengths", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/graph_resshift_v4.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/graph_resshift_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..85694331e3bd0242fb8738a179f946f6fff81e2a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/graph_resshift_v4.py @@ -0,0 +1,761 @@ +"""Graph-conditioned residual-shift diffusion components for Phase 2. + +The diffusion state is a lossless 2x pixel-unshuffle of an RGB image. The +network predicts the clean state directly and is anchored to the degraded +state at initialization through a zero-initialized residual head. + +This module deliberately avoids version-specific PyTorch features so the same +checkpoint can be trained with the project's PyTorch 1.10 runtime. +""" + +from __future__ import annotations + +import hashlib +import hmac +import math +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Dict, Iterable, Mapping, Optional, Sequence, Tuple, Union + +import torch +from torch import Tensor, nn +import torch.nn.functional as F + + +BRANCH_ORDER: Tuple[str, ...] = ("rain", "noise", "haze", "lowlight") +PHASE1_SCHEMA_VERSION = 2 +PHASE1_AGGREGATION_VERSION = 2 + + +def pixel_unshuffle2(image: Tensor) -> Tensor: + """Losslessly rearrange ``[B, C, H, W]`` into ``[B, 4C, H/2, W/2]``.""" + + if image.ndim != 4: + raise ValueError("pixel_unshuffle2 expects a four-dimensional tensor") + if image.shape[-2] % 2 or image.shape[-1] % 2: + raise ValueError("pixel_unshuffle2 requires even spatial dimensions") + return F.pixel_unshuffle(image, 2) + + +def pixel_shuffle2(state: Tensor) -> Tensor: + """Invert :func:`pixel_unshuffle2` exactly.""" + + if state.ndim != 4: + raise ValueError("pixel_shuffle2 expects a four-dimensional tensor") + if state.shape[1] % 4: + raise ValueError("pixel_shuffle2 requires a channel count divisible by four") + return F.pixel_shuffle(state, 2) + + +def pad_to_multiple(image: Tensor, multiple: int = 16) -> Tuple[Tensor, Tuple[int, int]]: + """Pad the bottom/right edges and return the original spatial size. + + Reflection is preferred because it introduces a weaker boundary than + constant padding. Replication is used for tiny inputs where PyTorch's + reflection padding constraints would otherwise be violated. + """ + + if image.ndim < 2: + raise ValueError("image must have at least two spatial dimensions") + if multiple <= 0: + raise ValueError("multiple must be positive") + height, width = int(image.shape[-2]), int(image.shape[-1]) + pad_h = (-height) % multiple + pad_w = (-width) % multiple + if pad_h == 0 and pad_w == 0: + return image, (height, width) + + # Reflection requires every non-zero pad to be smaller than that input + # dimension. Replication has no such restriction and is safe for 1px axes. + reflect_ok = (pad_h == 0 or pad_h < height) and (pad_w == 0 or pad_w < width) + mode = "reflect" if reflect_ok else "replicate" + padded = F.pad(image, (0, pad_w, 0, pad_h), mode=mode) + return padded, (height, width) + + +class ResidualShiftSchedule(nn.Module): + """Discrete residual-shift forward process and its exact posterior. + + For timestep ``t`` the marginal is + + ``u_t = u_0 + eta_t (u_y - u_0) + kappa sqrt(eta_t) epsilon``. + + ``eta[0]`` is exactly zero. As in the upstream journal implementation, + the CLI/config value ``eta_end`` is the endpoint of ``sqrt(eta)`` rather + than ``eta`` itself. Entries ``sqrt_eta[1:T+1]`` follow the exponential + power curve and ``eta`` is their elementwise square. + """ + + def __init__( + self, + timesteps: int = 8, + eta_end: float = 0.99, + min_noise: float = 0.2, + power: float = 0.3, + kappa: float = 0.2, + ) -> None: + super().__init__() + if timesteps < 2: + raise ValueError("timesteps must be at least two") + if not 0.0 < min_noise < eta_end <= 1.0: + raise ValueError("eta values must satisfy 0 < min_noise < eta_end <= 1") + if power <= 0.0: + raise ValueError("power must be positive") + if kappa < 0.0: + raise ValueError("kappa must be non-negative") + + self.timesteps = int(timesteps) + # Source-faithful ResShift schedule. In stochastic mode the initial + # sqrt-eta is capped by min_noise/kappa; deterministic kappa=0 avoids + # that division and keeps the natural min_noise start. + sqrt_eta_start = ( + min(float(min_noise) / float(kappa), float(min_noise)) + if kappa > 0.0 + else float(min_noise) + ) + increaser = math.exp( + math.log(float(eta_end) / sqrt_eta_start) / (self.timesteps - 1) + ) + normalized_t = torch.linspace( + 0.0, 1.0, self.timesteps, dtype=torch.float32 + ) + power_t = normalized_t.pow(float(power)) * (self.timesteps - 1) + sqrt_curve = ( + torch.tensor(increaser, dtype=torch.float32).pow(power_t) + * sqrt_eta_start + ) + sqrt_eta = torch.cat( + (torch.zeros(1, dtype=torch.float32), sqrt_curve), dim=0 + ) + eta = sqrt_eta.square() + eta_prev = torch.cat((eta[:1], eta[:-1]), dim=0) + self.register_buffer("sqrt_eta", sqrt_eta, persistent=True) + self.register_buffer("eta", eta, persistent=True) + self.register_buffer("eta_prev", eta_prev, persistent=True) + self.register_buffer( + "kappa", torch.tensor(float(kappa), dtype=torch.float32), persistent=True + ) + + @staticmethod + def extract(values: Tensor, timesteps: Tensor, reference: Tensor) -> Tensor: + """Gather one schedule value per batch item and make it broadcastable.""" + + if timesteps.ndim == 0: + timesteps = timesteps[None] + if timesteps.ndim != 1: + raise ValueError("timesteps must be a scalar or one-dimensional tensor") + if timesteps.shape[0] != reference.shape[0]: + raise ValueError("one timestep is required per batch element") + indices = timesteps.to(device=values.device, dtype=torch.long) + if bool(torch.any(indices < 0)) or bool(torch.any(indices >= values.shape[0])): + raise ValueError("timestep is outside the schedule") + gathered = values.gather(0, indices).to(device=reference.device, dtype=reference.dtype) + return gathered.reshape((reference.shape[0],) + (1,) * (reference.ndim - 1)) + + def kappa_factor(self, kappa: Optional[Tensor], reference: Tensor) -> Tensor: + """Return the scalar kappa buffer or a validated per-sample override. + + A per-sample kappa keeps the marginal and the exact posterior valid + because kappa is constant along each sample's chain; only its + batch shape changes. Overrides are broadcast like schedule values. + """ + + if kappa is None: + return self.kappa.to(device=reference.device, dtype=reference.dtype) + if not isinstance(kappa, Tensor): + raise ValueError("kappa override must be a tensor") + if kappa.ndim == 0: + kappa = kappa[None] + if kappa.ndim != 1 or kappa.shape[0] != reference.shape[0]: + raise ValueError("kappa override requires one value per batch element") + if not bool(torch.isfinite(kappa).all()): + raise ValueError("kappa override must contain only finite values") + if bool(torch.any(kappa < 0)): + raise ValueError("kappa override must be non-negative") + return kappa.to(device=reference.device, dtype=reference.dtype).reshape( + (reference.shape[0],) + (1,) * (reference.ndim - 1) + ) + + def q_sample( + self, + u0: Tensor, + uy: Tensor, + timesteps: Tensor, + noise: Optional[Tensor] = None, + kappa: Optional[Tensor] = None, + ) -> Tensor: + """Sample the forward marginal ``q(u_t | u_0, u_y)``.""" + + if u0.shape != uy.shape: + raise ValueError("u0 and uy must have identical shapes") + if noise is None: + noise = torch.randn_like(u0) + if noise.shape != u0.shape: + raise ValueError("noise must have the same shape as u0") + eta_t = self.extract(self.eta, timesteps, u0) + kappa_value = self.kappa_factor(kappa, u0) + return u0 + eta_t * (uy - u0) + kappa_value * torch.sqrt(eta_t) * noise + + def posterior_mean_variance( + self, + u_t: Tensor, + u0_hat: Tensor, + timesteps: Tensor, + kappa: Optional[Tensor] = None, + ) -> Tuple[Tensor, Tensor]: + """Return the exact ``q(u_{t-1} | u_t, u0_hat)`` mean and variance.""" + + if u_t.shape != u0_hat.shape: + raise ValueError("u_t and u0_hat must have identical shapes") + eta_t = self.extract(self.eta, timesteps, u_t) + eta_previous = self.extract(self.eta_prev, timesteps, u_t) + if bool(torch.any(eta_t <= 0)): + raise ValueError("posterior is defined only for timesteps >= 1") + ratio = eta_previous / eta_t + mean = ratio * u_t + (eta_t - eta_previous) / eta_t * u0_hat + kappa_value = self.kappa_factor(kappa, u_t) + variance = kappa_value.square() * ratio * (eta_t - eta_previous) + return mean, variance + + def reverse_timesteps(self) -> Iterable[int]: + """Iterate the reverse chain in the only valid order: ``T ... 1``.""" + + return range(self.timesteps, 0, -1) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + while True: + block = handle.read(1024 * 1024) + if not block: + break + digest.update(block) + return digest.hexdigest() + + +def _checkpoint_field(checkpoint: Mapping[str, Any], name: str) -> Any: + if name in checkpoint: + return checkpoint[name] + metadata = checkpoint.get("metadata") + if isinstance(metadata, Mapping) and name in metadata: + return metadata[name] + return None + + +def load_phase1_checkpoint( + path: Union[str, Path], + encoder: nn.Module, + expected_sha256: Optional[str] = None, + map_location: Union[str, torch.device] = "cpu", +) -> Dict[str, Any]: + """Validate Phase-1 semantics and strictly load an encoder checkpoint. + + The metadata checks intentionally fail closed: a checkpoint trained with a + stale degradation vocabulary or aggregation rule must never silently + condition Phase 2. + """ + + checkpoint_path = Path(path) + actual_sha256 = _sha256(checkpoint_path) + if expected_sha256 is not None and not hmac.compare_digest( + actual_sha256.lower(), str(expected_sha256).lower() + ): + raise ValueError( + "sha256 mismatch: expected %s, received %s" + % (expected_sha256, actual_sha256) + ) + + # ``weights_only`` was added long after the remote PyTorch 1.10 runtime. + try: + checkpoint = torch.load( + str(checkpoint_path), map_location=map_location, weights_only=False + ) + except TypeError: + checkpoint = torch.load(str(checkpoint_path), map_location=map_location) + if not isinstance(checkpoint, Mapping): + raise ValueError("checkpoint must be a mapping") + + expected = { + "schema_version": PHASE1_SCHEMA_VERSION, + "phase": 1, + "aggregation_version": PHASE1_AGGREGATION_VERSION, + "branch_order": list(BRANCH_ORDER), + } + validated: Dict[str, Any] = {} + for field, expected_value in expected.items(): + value = _checkpoint_field(checkpoint, field) + if field == "branch_order" and value is not None: + value = list(value) + if value != expected_value: + raise ValueError( + "%s mismatch: expected %r, received %r" + % (field, expected_value, value) + ) + validated[field] = value + + state = checkpoint.get("model_state_dict") + if state is None: + state = checkpoint.get("encoder_state_dict") + if state is None: + state = checkpoint.get("state_dict") + if not isinstance(state, Mapping): + raise ValueError("checkpoint is missing model_state_dict") + encoder.load_state_dict(state, strict=True) + + validated["sha256"] = actual_sha256 + config = checkpoint.get("config") + if config is not None: + validated["config"] = config + return validated + + +class FrozenPhase1(nn.Module): + """A permanently frozen inference-only wrapper around the Phase-1 encoder.""" + + def __init__(self, encoder: nn.Module) -> None: + super().__init__() + self.encoder = encoder + self.encoder.requires_grad_(False) + self.encoder.eval() + super().train(False) + + def train(self, mode: bool = True) -> "FrozenPhase1": + """Keep both wrapper and encoder in evaluation mode unconditionally.""" + + del mode + super().train(False) + self.encoder.eval() + return self + + def forward(self, degraded: Tensor) -> Any: + """Extract representation without labels, clean targets, or autograd. + + The encoder is trained in fp32 and its fp16 path is measurably + unstable (ll_v3 emits non-finite routing under autocast), so the + representation is always computed with autocast disabled. + """ + + self.encoder.eval() + with torch.no_grad(), torch.cuda.amp.autocast(enabled=False): + return self.encoder(None, degraded.float(), is_training=False) + + +@dataclass +class ConditionBundle: + """Continuous graph conditions consumed by the denoising U-Net.""" + + context: Tensor + global_vector: Tensor + content: Tensor + spatial: Tensor + + +def _representation_field(representation: Any, name: str) -> Tensor: + if isinstance(representation, Mapping): + value = representation.get(name) + else: + value = getattr(representation, name, None) + if not isinstance(value, Tensor): + raise ValueError("Phase-1 representation is missing tensor field %s" % name) + return value + + +class GraphConditionerV4(nn.Module): + """Turn the complete continuous Phase-1 representation into U-Net signals. + + No hard class decision is made. Routing probabilities modulate learned node + slots directly, severity coordinates modulate learned severity slots, and a + soft routing-weighted node summary contributes to the AdaGN vector. + """ + + def __init__( + self, + cond_dim: int = 256, + stage_dims: Sequence[int] = (64, 128, 192, 256), + node_dim: int = 256, + content_channels: int = 128, + spatial_channels: int = 4, + num_nodes: int = 6, + num_severity: int = 4, + ) -> None: + super().__init__() + if len(stage_dims) != 4: + raise ValueError("stage_dims must contain exactly four scales") + if cond_dim <= 0 or node_dim <= 0: + raise ValueError("conditioning dimensions must be positive") + if num_severity > num_nodes: + raise ValueError("num_severity cannot exceed num_nodes") + self.cond_dim = int(cond_dim) + self.num_nodes = int(num_nodes) + self.num_severity = int(num_severity) + + self.token_projection = nn.Linear(node_dim, cond_dim) + self.route_slots = nn.Parameter(torch.empty(num_nodes, cond_dim)) + self.severity_slots = nn.Parameter(torch.empty(num_severity, cond_dim)) + self.token_type = nn.Parameter(torch.empty(num_nodes + 2, cond_dim)) + self.context_norm = nn.LayerNorm(cond_dim) + + global_input_dim = node_dim * 3 + num_nodes + num_severity + self.global_mlp = nn.Sequential( + nn.LayerNorm(global_input_dim), + nn.Linear(global_input_dim, cond_dim * 2), + nn.SiLU(), + nn.Linear(cond_dim * 2, cond_dim), + ) + + # Phase-1 content is 64x64 for a 256px crop (U-Net scale 1); its + # spatial routing maps are 16x16 (coarsest U-Net scale). + self.content_projection = nn.Conv2d( + content_channels, int(stage_dims[1]), kernel_size=1 + ) + self.spatial_projection = nn.Conv2d( + spatial_channels, int(stage_dims[3]), kernel_size=1 + ) + nn.init.normal_(self.route_slots, std=0.02) + nn.init.normal_(self.severity_slots, std=0.02) + nn.init.normal_(self.token_type, std=0.02) + + def forward(self, representation: Any, mode: str = "full") -> ConditionBundle: + if mode not in ("full", "null"): + raise ValueError("conditioning mode must be 'full' or 'null'") + + node_tokens = _representation_field(representation, "node_tokens") + routing = _representation_field(representation, "routing_probs") + severity = _representation_field(representation, "severity_coords") + unknown = _representation_field(representation, "unknown_residual") + global_condition = _representation_field(representation, "global_condition") + content = _representation_field(representation, "content_latent") + spatial = _representation_field(representation, "spatial_maps") + + if node_tokens.ndim != 3 or node_tokens.shape[1] != self.num_nodes: + raise ValueError("node_tokens must have shape [B, %d, C]" % self.num_nodes) + if routing.shape != node_tokens.shape[:2]: + raise ValueError("routing_probs must have one value per graph node") + if severity.ndim != 2 or severity.shape[1] != self.num_severity: + raise ValueError( + "severity_coords must have shape [B, %d]" % self.num_severity + ) + batch = node_tokens.shape[0] + if unknown.shape[0] != batch or global_condition.shape[0] != batch: + raise ValueError("all Phase-1 fields must share the batch dimension") + + projected_nodes = self.token_projection(node_tokens) + projected_nodes = ( + projected_nodes + + routing.unsqueeze(-1) * self.route_slots.unsqueeze(0) + ) + branch_severity = ( + severity.unsqueeze(-1) * self.severity_slots.unsqueeze(0) + ) + if self.num_nodes > self.num_severity: + unconditioned_nodes = projected_nodes.new_zeros( + batch, self.num_nodes - self.num_severity, self.cond_dim + ) + branch_severity = torch.cat( + (branch_severity, unconditioned_nodes), dim=1 + ) + projected_nodes = projected_nodes + branch_severity + severity_summary = torch.sum( + severity.unsqueeze(-1) * self.severity_slots.unsqueeze(0), dim=1 + ) + global_token = self.token_projection(global_condition) + severity_summary + unknown_token = self.token_projection(unknown) + severity_summary + context = torch.cat( + (projected_nodes, global_token.unsqueeze(1), unknown_token.unsqueeze(1)), dim=1 + ) + context = self.context_norm(context + self.token_type.unsqueeze(0)) + + weighted_nodes = torch.sum(node_tokens * routing.unsqueeze(-1), dim=1) + global_features = torch.cat( + (weighted_nodes, global_condition, unknown, routing, severity), dim=1 + ) + global_vector = self.global_mlp(global_features) + content_condition = self.content_projection(content) + spatial_condition = self.spatial_projection(spatial) + + # Multiplication retains an identical computation graph and parameter + # set for the D0 null-condition gate while producing exact zeros. + gate = context.new_tensor(1.0 if mode == "full" else 0.0) + return ConditionBundle( + context=context * gate, + global_vector=global_vector * gate, + content=content_condition * gate, + spatial=spatial_condition * gate, + ) + + +def _group_count(channels: int, maximum: int = 32) -> int: + groups = min(maximum, channels) + while channels % groups: + groups -= 1 + return groups + + +def _attention_heads(channels: int, maximum: int = 8) -> int: + heads = min(maximum, channels) + while channels % heads: + heads -= 1 + return heads + + +class _SinusoidalTimeEmbedding(nn.Module): + def __init__(self, dimension: int) -> None: + super().__init__() + self.dimension = int(dimension) + + def forward(self, timesteps: Tensor) -> Tensor: + if timesteps.ndim == 0: + timesteps = timesteps[None] + half = self.dimension // 2 + if half == 0: + return timesteps.float().unsqueeze(1) + scale = -math.log(10000.0) / max(half - 1, 1) + frequencies = torch.exp( + torch.arange(half, device=timesteps.device, dtype=torch.float32) * scale + ) + angles = timesteps.float().unsqueeze(1) * frequencies.unsqueeze(0) + embedding = torch.cat((angles.sin(), angles.cos()), dim=1) + if embedding.shape[1] < self.dimension: + embedding = F.pad(embedding, (0, self.dimension - embedding.shape[1])) + return embedding + + +class _AdaGNResBlock(nn.Module): + """Residual block with global/time-conditioned adaptive GroupNorm.""" + + def __init__( + self, in_channels: int, out_channels: int, embedding_dim: int, dropout: float + ) -> None: + super().__init__() + self.norm1 = nn.GroupNorm(_group_count(in_channels), in_channels) + self.conv1 = nn.Conv2d(in_channels, out_channels, 3, padding=1) + self.norm2 = nn.GroupNorm( + _group_count(out_channels), out_channels, affine=False + ) + self.condition = nn.Linear(embedding_dim, out_channels * 2) + self.dropout = nn.Dropout(dropout) + self.conv2 = nn.Conv2d(out_channels, out_channels, 3, padding=1) + self.skip = ( + nn.Identity() + if in_channels == out_channels + else nn.Conv2d(in_channels, out_channels, 1) + ) + + def forward(self, features: Tensor, embedding: Tensor) -> Tensor: + hidden = self.conv1(F.silu(self.norm1(features))) + scale, shift = self.condition(embedding).chunk(2, dim=1) + hidden = self.norm2(hidden) + hidden = hidden * (1.0 + scale[:, :, None, None]) + shift[:, :, None, None] + hidden = self.conv2(self.dropout(F.silu(hidden))) + return self.skip(features) + hidden + + +class _CrossAttention2d(nn.Module): + """Cross-attend a spatial feature map to the eight graph tokens.""" + + def __init__(self, channels: int, cond_dim: int) -> None: + super().__init__() + self.query_norm = nn.LayerNorm(channels) + self.context_norm = nn.LayerNorm(cond_dim) + self.attention = nn.MultiheadAttention( + embed_dim=channels, + num_heads=_attention_heads(channels), + kdim=cond_dim, + vdim=cond_dim, + batch_first=True, + ) + + def forward(self, features: Tensor, context: Tensor) -> Tensor: + batch, channels, height, width = features.shape + query = features.flatten(2).transpose(1, 2) + attended, _ = self.attention( + self.query_norm(query), + self.context_norm(context), + self.context_norm(context), + need_weights=False, + ) + attended = attended.transpose(1, 2).reshape(batch, channels, height, width) + return features + attended + + +class _Downsample(nn.Module): + def __init__(self, in_channels: int, out_channels: int) -> None: + super().__init__() + self.conv = nn.Conv2d(in_channels, out_channels, 3, stride=2, padding=1) + + def forward(self, features: Tensor) -> Tensor: + return self.conv(features) + + +class _Upsample(nn.Module): + def __init__(self, in_channels: int, out_channels: int) -> None: + super().__init__() + self.conv = nn.Conv2d(in_channels, out_channels, 3, padding=1) + + def forward(self, features: Tensor, size: Tuple[int, int]) -> Tensor: + features = F.interpolate(features, size=size, mode="nearest") + return self.conv(features) + + +class GraphResidualShiftUNetV4(nn.Module): + """Four-scale x0-predicting U-Net for graph-conditioned residual shift. + + Inputs are concatenated as ``[u_t, u_y, u_t-u_y]`` (36 channels for RGB + pixel-unshuffle states). Cross-attention is used only at the 32px and 16px + scales of a 256px image, while all residual blocks receive the global AdaGN + vector and timestep embedding. + """ + + def __init__( + self, + dims: Sequence[int] = (64, 128, 192, 256), + cond_dim: int = 256, + state_channels: int = 12, + dropout: float = 0.0, + ) -> None: + super().__init__() + if len(dims) != 4: + raise ValueError("dims must contain exactly four scales") + if any(int(dimension) <= 0 for dimension in dims): + raise ValueError("all U-Net dimensions must be positive") + self.dims = tuple(int(dimension) for dimension in dims) + self.cond_dim = int(cond_dim) + self.state_channels = int(state_channels) + embedding_dim = max(cond_dim * 2, self.dims[-1]) + + self.time_embedding = nn.Sequential( + _SinusoidalTimeEmbedding(cond_dim), + nn.Linear(cond_dim, embedding_dim), + nn.SiLU(), + nn.Linear(embedding_dim, embedding_dim), + ) + self.global_embedding = nn.Linear(cond_dim, embedding_dim) + self.input_projection = nn.Conv2d(state_channels * 3, self.dims[0], 3, padding=1) + + self.down_blocks = nn.ModuleList() + self.down_attentions = nn.ModuleList() + for index, channels in enumerate(self.dims): + self.down_blocks.append( + nn.ModuleList( + ( + _AdaGNResBlock(channels, channels, embedding_dim, dropout), + _AdaGNResBlock(channels, channels, embedding_dim, dropout), + ) + ) + ) + self.down_attentions.append( + _CrossAttention2d(channels, cond_dim) if index >= 2 else nn.Identity() + ) + self.downsamples = nn.ModuleList( + _Downsample(self.dims[index], self.dims[index + 1]) + for index in range(3) + ) + + self.content_inject = nn.Conv2d(self.dims[1], self.dims[1], 1) + self.spatial_inject = nn.Conv2d(self.dims[3], self.dims[3], 1) + nn.init.zeros_(self.content_inject.weight) + nn.init.zeros_(self.content_inject.bias) + nn.init.zeros_(self.spatial_inject.weight) + nn.init.zeros_(self.spatial_inject.bias) + + self.upsamples = nn.ModuleList() + self.up_blocks = nn.ModuleList() + self.up_attentions = nn.ModuleList() + for index in (2, 1, 0): + channels = self.dims[index] + self.upsamples.append(_Upsample(self.dims[index + 1], channels)) + self.up_blocks.append( + nn.ModuleList( + ( + _AdaGNResBlock(channels * 2, channels, embedding_dim, dropout), + _AdaGNResBlock(channels, channels, embedding_dim, dropout), + ) + ) + ) + self.up_attentions.append( + _CrossAttention2d(channels, cond_dim) if index >= 2 else nn.Identity() + ) + + self.output_norm = nn.GroupNorm(_group_count(self.dims[0]), self.dims[0]) + self.output_residual = nn.Conv2d(self.dims[0], state_channels, 3, padding=1) + nn.init.zeros_(self.output_residual.weight) + nn.init.zeros_(self.output_residual.bias) + + @staticmethod + def _attend(module: nn.Module, features: Tensor, context: Tensor) -> Tensor: + if isinstance(module, nn.Identity): + return features + return module(features, context) + + def forward( + self, u_t: Tensor, u_y: Tensor, timesteps: Tensor, condition: ConditionBundle + ) -> Tensor: + if u_t.shape != u_y.shape: + raise ValueError("u_t and u_y must have identical shapes") + if u_t.ndim != 4 or u_t.shape[1] != self.state_channels: + raise ValueError( + "diffusion states must have shape [B, %d, H, W]" % self.state_channels + ) + if timesteps.ndim == 0: + timesteps = timesteps.expand(u_t.shape[0]) + if timesteps.ndim != 1 or timesteps.shape[0] != u_t.shape[0]: + raise ValueError("one timestep is required per batch element") + if condition.context.shape[0] != u_t.shape[0]: + raise ValueError("condition and diffusion state batches must match") + + embedding = self.time_embedding(timesteps) + embedding = embedding.to(dtype=u_t.dtype) + self.global_embedding( + condition.global_vector + ) + features = self.input_projection(torch.cat((u_t, u_y, u_t - u_y), dim=1)) + + skips = [] + for index in range(4): + if index == 1: + content = F.interpolate( + condition.content, size=features.shape[-2:], mode="bilinear", align_corners=False + ) + features = features + self.content_inject(content) + if index == 3: + spatial = F.interpolate( + condition.spatial, size=features.shape[-2:], mode="bilinear", align_corners=False + ) + features = features + self.spatial_inject(spatial) + for block in self.down_blocks[index]: + features = block(features, embedding) + features = self._attend( + self.down_attentions[index], features, condition.context + ) + skips.append(features) + if index < 3: + features = self.downsamples[index](features) + + for up_index, stage_index in enumerate((2, 1, 0)): + skip = skips[stage_index] + features = self.upsamples[up_index](features, skip.shape[-2:]) + features = torch.cat((features, skip), dim=1) + for block in self.up_blocks[up_index]: + features = block(features, embedding) + features = self._attend( + self.up_attentions[up_index], features, condition.context + ) + + delta = self.output_residual(F.silu(self.output_norm(features))) + return u_y + delta + + +__all__ = [ + "BRANCH_ORDER", + "PHASE1_AGGREGATION_VERSION", + "PHASE1_SCHEMA_VERSION", + "ConditionBundle", + "FrozenPhase1", + "GraphConditionerV4", + "GraphResidualShiftUNetV4", + "ResidualShiftSchedule", + "load_phase1_checkpoint", + "pad_to_multiple", + "pixel_shuffle2", + "pixel_unshuffle2", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/refiner_decoder.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/refiner_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..1d199c8748817541a747b7a15099ce7e67bfd0bf --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/refiner_decoder.py @@ -0,0 +1,149 @@ +"""Stage-2 refiner decoder for the two-stage SCDC pipeline (option A). + +The one-step x0 regression of the diffusion U-Net is the strongest measured +inference mode, but pixel-space MSE regresses to the mean and ties the output +to ``u_y + delta``. This decoder is pretrained first on clean images (natural +image prior, perceptual loss) and then finetuned on regressor outputs, so the +generative half of the pipeline lives here instead of in the reverse chain. + +Torch 1.10 compatible; no version-specific features. +""" + +from __future__ import annotations + +from typing import Sequence + +import torch +from torch import Tensor, nn +import torch.nn.functional as F + +REFINER_VERSION = "naf_lite_residual_v1" + + +class SimpleGate(nn.Module): + def forward(self, x: Tensor) -> Tensor: + left, right = x.chunk(2, dim=1) + return left * right + + +class RefinerBlock(nn.Module): + """NAFNet-style block: depthwise conv + simple gate + channel attention.""" + + def __init__(self, channels: int, expansion: int = 2) -> None: + super().__init__() + hidden = channels * expansion + self.norm1 = nn.GroupNorm(1, channels) + self.conv1 = nn.Conv2d(channels, hidden * 2, 1) + self.dwconv = nn.Conv2d( + hidden * 2, hidden * 2, 3, padding=1, groups=hidden * 2 + ) + self.gate = SimpleGate() + self.se = nn.Sequential( + nn.AdaptiveAvgPool2d(1), nn.Conv2d(hidden, hidden, 1) + ) + self.conv2 = nn.Conv2d(hidden, channels, 1) + self.norm2 = nn.GroupNorm(1, channels) + self.mlp1 = nn.Conv2d(channels, channels * 2, 1) + self.mlp2 = nn.Conv2d(channels, channels, 1) + self.beta = nn.Parameter(torch.zeros(1, channels, 1, 1)) + self.gamma = nn.Parameter(torch.zeros(1, channels, 1, 1)) + + def forward(self, x: Tensor) -> Tensor: + y = self.dwconv(self.conv1(self.norm1(x))) + y = self.gate(y) + y = y * torch.sigmoid(self.se(y)) + x = x + self.conv2(y) * self.beta + y = self.gate(self.mlp1(self.norm2(x))) + return x + self.mlp2(y) * self.gamma + + +class RefinerDecoder(nn.Module): + """Three-scale residual U-shape over ``concat(x0_hat, degraded)``. + + The output head is zero-initialized: freshly attached, the full pipeline + is exactly the one-step regressor, and training can only add value. + """ + + def __init__( + self, + in_channels: int = 6, + base_channels: int = 48, + blocks: Sequence[int] = (2, 2, 4), + ) -> None: + super().__init__() + if len(blocks) != 3: + raise ValueError("blocks must list three stage depths") + c1, c2, c3 = base_channels, base_channels * 2, base_channels * 4 + self.stem = nn.Conv2d(in_channels, c1, 3, padding=1) + self.enc1 = nn.Sequential(*[RefinerBlock(c1) for _ in range(blocks[0])]) + self.down1 = nn.Conv2d(c1, c2, 2, stride=2) + self.enc2 = nn.Sequential(*[RefinerBlock(c2) for _ in range(blocks[1])]) + self.down2 = nn.Conv2d(c2, c3, 2, stride=2) + self.mid = nn.Sequential(*[RefinerBlock(c3) for _ in range(blocks[2])]) + self.up2 = nn.ConvTranspose2d(c3, c2, 2, stride=2) + self.dec2 = nn.Sequential(*[RefinerBlock(c2) for _ in range(blocks[1])]) + self.up1 = nn.ConvTranspose2d(c2, c1, 2, stride=2) + self.dec1 = nn.Sequential(*[RefinerBlock(c1) for _ in range(blocks[0])]) + self.head = nn.Conv2d(c1, 3, 3, padding=1) + nn.init.zeros_(self.head.weight) + nn.init.zeros_(self.head.bias) + + def forward(self, x0_hat: Tensor, degraded: Tensor) -> Tensor: + if x0_hat.shape != degraded.shape or x0_hat.shape[1] != 3: + raise ValueError("x0_hat and degraded must be matching [B,3,H,W]") + if x0_hat.shape[-2] % 4 or x0_hat.shape[-1] % 4: + raise ValueError("spatial size must be divisible by four") + features = self.stem(torch.cat((x0_hat, degraded), dim=1)) + skip1 = self.enc1(features) + skip2 = self.enc2(self.down1(skip1)) + mid = self.mid(self.down2(skip2)) + up2 = self.dec2(self.up2(mid) + skip2) + up1 = self.dec1(self.up1(up2) + skip1) + return (x0_hat + self.head(up1)).clamp(0.0, 1.0) + + +class VGGPerceptualLoss(nn.Module): + """L1 distance in frozen VGG16 relu1_2/relu2_2/relu3_3 feature spaces.""" + + LAYERS = (3, 8, 15) + + def __init__(self) -> None: + super().__init__() + from torchvision.models import vgg16 + + features = vgg16(pretrained=True).features[: self.LAYERS[-1] + 1] + for parameter in features.parameters(): + parameter.requires_grad_(False) + self.features = features.eval() + self.register_buffer( + "mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1) + ) + self.register_buffer( + "std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1) + ) + + def train(self, mode: bool = True) -> "VGGPerceptualLoss": + del mode + super().train(False) + return self + + def forward(self, prediction: Tensor, target: Tensor) -> Tensor: + x = (prediction.float() - self.mean) / self.std + y = (target.float() - self.mean) / self.std + loss = prediction.new_zeros(()) + for index, layer in enumerate(self.features): + x = layer(x) + with torch.no_grad(): + y = layer(y) + if index in self.LAYERS: + loss = loss + F.l1_loss(x, y) + return loss / len(self.LAYERS) + + +__all__ = [ + "REFINER_VERSION", + "RefinerBlock", + "RefinerDecoder", + "SimpleGate", + "VGGPerceptualLoss", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/residual_shift.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/residual_shift.py new file mode 100644 index 0000000000000000000000000000000000000000..98ee859cd253804c83e9e50897d2b9e84cf15ed2 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/residual_shift.py @@ -0,0 +1,159 @@ +""" +Residual-Shift Latent Diffusion. +""" + +import torch +import torch.nn as nn +import torch.nn.functional as F +import math + + +class ResidualShiftSchedule: + def __init__(self, T=8, eta_max=0.95, kappa=0.3): + self.T = T + self.eta_max = eta_max + self.kappa = kappa + + t = torch.arange(T + 1).float() / T + self.eta = eta_max * t + self.eta_prev = torch.zeros(T + 1) + self.eta_prev[1:] = self.eta[:-1] + + def forward_process(self, z_x, z_y, t, noise=None): + B = z_x.shape[0] + device = z_x.device + eta_t = self.eta[t].view(B, 1, 1, 1).to(device) + + if noise is None: + noise = torch.randn_like(z_x) + + return (1 - eta_t) * z_x + eta_t * z_y + self.kappa * torch.sqrt(eta_t) * noise + + def sample_initial(self, z_y, noise_scale=0.1): + return z_y + torch.randn_like(z_y) * noise_scale + + +class TimeEmb(nn.Module): + """Sinusoidal time embedding.""" + def __init__(self, dim): + super().__init__() + self.dim = dim + self.mlp = nn.Sequential( + nn.Linear(dim, dim * 4), + nn.SiLU(), + nn.Linear(dim * 4, dim), + ) + + def forward(self, t): + half = self.dim // 2 + freqs = torch.exp(-torch.arange(half, device=t.device).float() * math.log(10000) / half) + args = t.float()[:, None] * freqs[None, :] + emb = torch.cat([torch.sin(args), torch.cos(args)], dim=-1) + return self.mlp(emb) + + +class SimpleDenoiser(nn.Module): + """Super simple denoiser.""" + + def __init__(self, latent_ch=16, ch=64, cond_dim=256): + super().__init__() + + # Time embedding + self.time_emb = TimeEmb(cond_dim) + + # Condition projection + self.cond_proj = nn.Linear(cond_dim, ch) + + # Input: z_t + z_y concatenated + self.in_conv = nn.Conv2d(latent_ch * 2, ch, 3, padding=1) + + # Simple conv blocks + self.conv1 = nn.Conv2d(ch, ch, 3, padding=1) + self.conv2 = nn.Conv2d(ch, ch, 3, padding=1) + self.conv3 = nn.Conv2d(ch, ch, 3, padding=1) + + # Output + self.out_conv = nn.Conv2d(ch, latent_ch, 1) + + self.ch = ch + + def forward(self, z_t, z_y, timestep, cond): + # Time embedding + t_emb = self.time_emb(timestep) # [B, cond_dim] + + # Condition + c = self.cond_proj(cond + t_emb) # [B, ch] + + # Input + x = torch.cat([z_t, z_y], dim=1) + x = F.relu(self.in_conv(x)) + + # Convs with condition + x = F.relu(self.conv1(x) + c.unsqueeze(-1).unsqueeze(-1)) + x = F.relu(self.conv2(x) + c.unsqueeze(-1).unsqueeze(-1)) + x = F.relu(self.conv3(x) + c.unsqueeze(-1).unsqueeze(-1)) + + return self.out_conv(x) + + +class ResidualShiftDiffusion(nn.Module): + def __init__(self, latent_ch=16, ch=64, cond_dim=256, T=8): + super().__init__() + self.T = T + self.schedule = ResidualShiftSchedule(T=T) + self.denoiser = SimpleDenoiser(latent_ch, ch, cond_dim) + + def forward(self, z_x, z_y, timestep, cond): + z_t = self.schedule.forward_process(z_x, z_y, timestep) + return self.denoiser(z_t, z_y, timestep, cond) + + @torch.no_grad() + def sample(self, z_y, cond, num_steps=None): + if num_steps is None: + num_steps = self.T + + z_t = self.schedule.sample_initial(z_y, noise_scale=0.1) + step_size = max(1, self.T // num_steps) + + for i in range(self.T - 1, -1, -step_size): + t = torch.full((z_y.shape[0],), i, device=z_y.device, dtype=torch.long) + z_x_hat = self.denoiser(z_t, z_y, t, cond) + + if i > 0: + eta_t = self.schedule.eta[i] + eta_prev = self.schedule.eta_prev[i] + + noise = (z_t - (1 - eta_t) * z_x_hat - eta_t * z_y) / (self.schedule.kappa * torch.sqrt(eta_t) + 1e-8) + z_t = (1 - eta_prev) * z_x_hat + eta_prev * z_y + self.schedule.kappa * torch.sqrt(eta_prev) * noise + + return z_x_hat + + +def test(): + B, C, H, W = 2, 16, 64, 64 + device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') + + model = ResidualShiftDiffusion(latent_ch=C, ch=64, T=8).to(device) + + z_x = torch.randn(B, C, H, W).to(device) + z_y = torch.randn(B, C, H, W).to(device) + cond = torch.randn(B, 256).to(device) + t = torch.randint(0, 8, (B,)).to(device) + + z_x_hat = model(z_x, z_y, t, cond) + loss = F.mse_loss(z_x_hat, z_x) + + print(f'Predicted: {z_x_hat.shape}') + print(f'Loss: {loss.item():.4f}') + + model.eval() + with torch.no_grad(): + z_sampled = model.sample(z_y, cond, num_steps=8) + print(f'Sampled: {z_sampled.shape}') + + print('ResidualShiftDiffusion test passed!') + return True + + +if __name__ == '__main__': + test() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/uformer_moe_v7.py b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/uformer_moe_v7.py new file mode 100644 index 0000000000000000000000000000000000000000..0e8d0f9c20e4fff7f983baca770883fa080838a9 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/src/models/restoration/uformer_moe_v7.py @@ -0,0 +1,420 @@ +"""Uformer-style denoiser for the unified two-step ResShift (v7 ablation). + +Drop-in backbone swap: the conv AdaGN residual blocks of the v6 U-Net are +replaced by LeWin transformer blocks (8x8 window attention with relative +position bias + a locally-enhanced depthwise feed-forward), modulated by the +time/global embedding through zero-initialized adaLN. Everything around the +blocks — graph cross-attention, content/spatial injection, spatial expert +banks, the strength prompt and the ``u_y + delta`` zero-init anchor — is +IDENTICAL to the conv backbone, so a comparison isolates the block type. + +Torch 1.10 compatible. +""" + +from __future__ import annotations + +from typing import Sequence, Union + +import torch +from torch import Tensor, nn +import torch.nn.functional as F +from torch.utils import checkpoint as torch_checkpoint + +from .graph_moe_v6 import ( + MoEConditionBundleV6, + NUM_EXPERTS, + SpatialExpertBank, +) +from .graph_resshift_v4 import ( + _CrossAttention2d, + _Downsample, + _SinusoidalTimeEmbedding, + _Upsample, + _attention_heads, + _group_count, +) + +UFORMER_V7_VERSION = "lewin_window8_adaln_v1" + + +class WindowAttention(nn.Module): + """Multi-head self-attention inside non-overlapping windows.""" + + def __init__(self, channels: int, window: int = 8, heads: int = 4) -> None: + super().__init__() + if channels % heads: + raise ValueError("channels must divide evenly into heads") + self.window = int(window) + self.heads = int(heads) + self.scale = (channels // heads) ** -0.5 + self.qkv = nn.Linear(channels, channels * 3) + self.projection = nn.Linear(channels, channels) + size = self.window * self.window + self.position_bias = nn.Parameter( + torch.zeros(heads, size, size) + ) + nn.init.trunc_normal_(self.position_bias, std=0.02) + + def forward(self, x: Tensor) -> Tensor: + batch, channels, height, width = x.shape + # Shrink the window on maps smaller than (or indivisible by) the + # configured size; the relative-position bias only applies at the + # native window. + w = self.window + while w > 1 and (height % w or width % w): + w -= 1 + if w < 1: + raise ValueError("spatial size must be divisible by some window") + tokens = ( + x.reshape(batch, channels, height // w, w, width // w, w) + .permute(0, 2, 4, 3, 5, 1) + .reshape(-1, w * w, channels) + ) + qkv = self.qkv(tokens).reshape( + tokens.shape[0], w * w, 3, self.heads, channels // self.heads + ).permute(2, 0, 3, 1, 4) + query, key, value = qkv[0], qkv[1], qkv[2] + attention = (query @ key.transpose(-2, -1)) * self.scale + if w == self.window: + attention = attention + self.position_bias.unsqueeze(0) + attention = attention.softmax(dim=-1) + merged = (attention @ value).transpose(1, 2).reshape( + tokens.shape[0], w * w, channels + ) + merged = self.projection(merged) + return ( + merged.reshape(batch, height // w, width // w, w, w, channels) + .permute(0, 5, 1, 3, 2, 4) + .reshape(batch, channels, height, width) + ) + + +class LeFF(nn.Module): + """Locally-enhanced feed-forward: pointwise, depthwise 3x3, pointwise.""" + + def __init__(self, channels: int, expansion: int = 2) -> None: + super().__init__() + hidden = channels * expansion + self.inner = nn.Sequential( + nn.Conv2d(channels, hidden, 1), + nn.GELU(), + nn.Conv2d(hidden, hidden, 3, padding=1, groups=hidden), + nn.GELU(), + nn.Conv2d(hidden, channels, 1), + ) + + def forward(self, x: Tensor) -> Tensor: + return self.inner(x) + + +class LeWinBlock(nn.Module): + """Windowed transformer block with zero-init adaLN time modulation.""" + + def __init__( + self, + channels: int, + embedding_dim: int, + window: int = 8, + heads: int = 4, + ) -> None: + super().__init__() + self.norm1 = nn.GroupNorm(_group_count(channels), channels, affine=False) + self.attention = WindowAttention(channels, window=window, heads=heads) + self.norm2 = nn.GroupNorm(_group_count(channels), channels, affine=False) + self.leff = LeFF(channels) + # DiT-style modulation: scale/shift per norm plus per-branch gates, + # all zero-initialized so the block starts as identity. + self.modulation = nn.Linear(embedding_dim, channels * 6) + nn.init.zeros_(self.modulation.weight) + nn.init.zeros_(self.modulation.bias) + + def forward(self, x: Tensor, embedding: Tensor) -> Tensor: + params = self.modulation(embedding).unsqueeze(-1).unsqueeze(-1) + (shift1, scale1, gate1, shift2, scale2, gate2) = params.chunk(6, dim=1) + hidden = self.norm1(x) * (1 + scale1) + shift1 + x = x + gate1 * self.attention(hidden) + hidden = self.norm2(x) * (1 + scale2) + shift2 + return x + gate2 * self.leff(hidden) + + +class GlobalAttentionBlock(nn.Module): + """Full (non-windowed) self-attention over every token of a feature map, + modulated like LeWinBlock by a zero-initialized adaLN (v10). + + Stable Diffusion's U-Net attends globally only at its coarse latent + scales; the LeWin windows here never see beyond 8x8 tokens, so the + coarse stages get a whole-crop receptive field (exposure, airlight and + noise-level consistency across the crop). Zero gate -> exact identity at + warm start, so it can be appended to a trained trunk. + """ + + def __init__(self, channels: int, embedding_dim: int) -> None: + super().__init__() + self.norm = nn.GroupNorm(_group_count(channels), channels, affine=False) + self.attention = nn.MultiheadAttention( + embed_dim=channels, num_heads=_attention_heads(channels), batch_first=True + ) + self.modulation = nn.Linear(embedding_dim, channels * 3) + nn.init.zeros_(self.modulation.weight) + nn.init.zeros_(self.modulation.bias) + + def forward(self, x: Tensor, embedding: Tensor) -> Tensor: + params = self.modulation(embedding).unsqueeze(-1).unsqueeze(-1) + shift, scale, gate = params.chunk(3, dim=1) + hidden = self.norm(x) * (1 + scale) + shift + tokens = hidden.flatten(2).transpose(1, 2) + attended, _ = self.attention(tokens, tokens, tokens, need_weights=False) + attended = attended.transpose(1, 2).reshape(x.shape) + return x + gate * attended + + +class UformerMoEUNetV7(nn.Module): + """Four-scale LeWin U-Net with the exact v6 conditioning contract.""" + + def __init__( + self, + dims: Sequence[int] = (64, 128, 192, 256), + cond_dim: int = 256, + state_channels: int = 12, + expert_rank: int = 16, + window: int = 8, + blocks_per_stage: Union[int, Sequence[int]] = 2, + pyramid_heads: bool = False, + global_attention_scales: Sequence[int] = (), + grad_checkpoint: bool = False, + ) -> None: + super().__init__() + if len(dims) != 4: + raise ValueError("dims must contain exactly four scales") + if isinstance(blocks_per_stage, int): + blocks = (int(blocks_per_stage),) * 4 + else: + blocks = tuple(int(b) for b in blocks_per_stage) + if len(blocks) != 4 or any(b < 1 for b in blocks): + raise ValueError("blocks_per_stage must be a positive int or four positive ints") + self.blocks_per_stage = blocks + # v11: recompute each transformer block in backward instead of + # storing its activations (torch.utils.checkpoint, reentrant in + # torch 1.10). Only active in training with grad enabled. NOTE: the + # reentrant variant is incompatible with DDP find_unused_parameters + # when a block runs twice per iteration (coarse + fine), so the + # launcher enables it for single-process runs only. + self.grad_checkpoint = bool(grad_checkpoint) + scales = tuple(sorted({int(v) for v in global_attention_scales})) + if any(v < 0 or v > 3 for v in scales): + raise ValueError("global_attention_scales must be stage indices in 0..3") + self.global_attention_scales = scales + self.dims = tuple(int(d) for d in dims) + self.cond_dim = int(cond_dim) + self.state_channels = int(state_channels) + embedding_dim = max(cond_dim * 2, self.dims[-1]) + + self.time_embedding = nn.Sequential( + _SinusoidalTimeEmbedding(cond_dim), + nn.Linear(cond_dim, embedding_dim), + nn.SiLU(), + nn.Linear(embedding_dim, embedding_dim), + ) + self.global_embedding = nn.Linear(cond_dim, embedding_dim) + self.strength_tokens = nn.Parameter( + torch.zeros(NUM_EXPERTS, embedding_dim) + ) + self.input_projection = nn.Conv2d( + state_channels * 3, self.dims[0], 3, padding=1 + ) + + def stage(channels: int, count: int) -> nn.ModuleList: + return nn.ModuleList( + LeWinBlock(channels, embedding_dim, window=window) + for _ in range(int(count)) + ) + + self.down_blocks = nn.ModuleList( + stage(c, blocks[i]) for i, c in enumerate(self.dims) + ) + self.down_attentions = nn.ModuleList( + _CrossAttention2d(c, cond_dim) if i >= 2 else nn.Identity() + for i, c in enumerate(self.dims) + ) + self.downsamples = nn.ModuleList( + _Downsample(self.dims[i], self.dims[i + 1]) for i in range(3) + ) + self.down_experts = nn.ModuleList( + SpatialExpertBank(c, expert_rank) for c in self.dims + ) + # v10: whole-map attention appended after the windowed blocks of the + # selected stages (down and up paths), identity at initialization. + self.down_globals = nn.ModuleList( + GlobalAttentionBlock(c, embedding_dim) if i in scales else nn.Identity() + for i, c in enumerate(self.dims) + ) + self.up_globals = nn.ModuleList( + GlobalAttentionBlock(self.dims[i], embedding_dim) if i in scales else nn.Identity() + for i in (2, 1, 0) + ) + + self.content_inject = nn.Conv2d(self.dims[1], self.dims[1], 1) + self.spatial_inject = nn.Conv2d(self.dims[3], self.dims[3], 1) + for conv in (self.content_inject, self.spatial_inject): + nn.init.zeros_(conv.weight) + nn.init.zeros_(conv.bias) + + self.upsamples = nn.ModuleList() + self.up_blocks = nn.ModuleList() + self.up_attentions = nn.ModuleList() + self.up_experts = nn.ModuleList() + for index in (2, 1, 0): + channels = self.dims[index] + self.upsamples.append(_Upsample(self.dims[index + 1], channels)) + self.skip_mergers = getattr(self, "skip_mergers", nn.ModuleList()) + self.skip_mergers.append( + nn.Conv2d(channels * 2, channels, 1) + ) + self.up_blocks.append(stage(channels, blocks[index])) + self.up_attentions.append( + _CrossAttention2d(channels, cond_dim) + if index >= 2 else nn.Identity() + ) + self.up_experts.append(SpatialExpertBank(channels, expert_rank)) + + self.output_norm = nn.GroupNorm(_group_count(self.dims[0]), self.dims[0]) + self.output_residual = nn.Conv2d( + self.dims[0], state_channels, 3, padding=1 + ) + nn.init.zeros_(self.output_residual.weight) + nn.init.zeros_(self.output_residual.bias) + + # Coarse-to-fine Laplacian heads (16/32/64 px in state space). Each + # commits a zero-initialized band correction at its decoder scale; + # the bands are accumulated through fixed x2 upsampling so that with + # all heads at zero the output is exactly u_y + delta_128 (unchanged). + self.pyramid_heads = None + if pyramid_heads: + self.pyramid_heads = nn.ModuleList() + for channels in (self.dims[3], self.dims[2], self.dims[1]): + head = nn.Sequential( + nn.GroupNorm(_group_count(channels), channels), + nn.SiLU(), + nn.Conv2d(channels, state_channels, 1), + ) + nn.init.zeros_(head[-1].weight) + nn.init.zeros_(head[-1].bias) + self.pyramid_heads.append(head) + + @staticmethod + def _attend(module: nn.Module, features: Tensor, context: Tensor) -> Tensor: + if isinstance(module, nn.Identity): + return features + return module(features, context) + + def _global(self, module: nn.Module, features: Tensor, embedding: Tensor) -> Tensor: + if isinstance(module, nn.Identity): + return features + return self._run_block(module, features, embedding) + + def _run_block(self, block: nn.Module, features: Tensor, embedding: Tensor) -> Tensor: + """Block forward, recomputed in backward when checkpointing is on.""" + + if ( + self.grad_checkpoint + and self.training + and torch.is_grad_enabled() + and (features.requires_grad or embedding.requires_grad) + ): + return torch_checkpoint.checkpoint(block, features, embedding) + return block(features, embedding) + + def forward( + self, + u_t: Tensor, + u_y: Tensor, + timesteps: Tensor, + condition: MoEConditionBundleV6, + return_pyramid: bool = False, + ): + if u_t.shape != u_y.shape or u_t.shape[1] != self.state_channels: + raise ValueError("invalid diffusion state shapes") + if timesteps.ndim == 0: + timesteps = timesteps.expand(u_t.shape[0]) + embedding = self.time_embedding(timesteps).to(dtype=u_t.dtype) + embedding = embedding + self.global_embedding(condition.global_vector) + embedding = embedding + ( + condition.gate.strengths.to(self.strength_tokens.dtype) + @ self.strength_tokens + ).to(embedding.dtype) + features = self.input_projection( + torch.cat((u_t, u_y, u_t - u_y), dim=1) + ) + skips = [] + for index in range(4): + if index == 1: + content = F.interpolate( + condition.content, size=features.shape[-2:], + mode="bilinear", align_corners=False, + ) + features = features + self.content_inject(content) + if index == 3: + spatial = F.interpolate( + condition.spatial, size=features.shape[-2:], + mode="bilinear", align_corners=False, + ) + features = features + self.spatial_inject(spatial) + for block in self.down_blocks[index]: + features = self._run_block(block, features, embedding) + features = self._global(self.down_globals[index], features, embedding) + features = self._attend( + self.down_attentions[index], features, condition.context + ) + features = self.down_experts[index](features, condition.gate) + skips.append(features) + if index < 3: + features = self.downsamples[index](features) + band_features = [features] # bottleneck (coarsest scale) + for up_index, stage_index in enumerate((2, 1, 0)): + skip = skips[stage_index] + features = self.upsamples[up_index](features, skip.shape[-2:]) + features = self.skip_mergers[up_index]( + torch.cat((features, skip), dim=1) + ) + for block in self.up_blocks[up_index]: + features = self._run_block(block, features, embedding) + features = self._global(self.up_globals[up_index], features, embedding) + features = self._attend( + self.up_attentions[up_index], features, condition.context + ) + features = self.up_experts[up_index](features, condition.gate) + if stage_index in (2, 1): + band_features.append(features) + delta = self.output_residual(F.silu(self.output_norm(features))) + if self.pyramid_heads is None: + return (u_y + delta, []) if return_pyramid else u_y + delta + # Accumulate band corrections coarse -> fine through fixed upsampling. + pyramid = [] + accumulated = None + for head, feature in zip(self.pyramid_heads, band_features): + band = head(feature) + if accumulated is not None: + accumulated = F.interpolate( + accumulated, size=band.shape[-2:], + mode="bilinear", align_corners=False, + ) + band = band + accumulated + accumulated = band + anchor = F.interpolate(u_y, size=band.shape[-2:], mode="area") + pyramid.append(anchor + band) + accumulated = F.interpolate( + accumulated, size=delta.shape[-2:], + mode="bilinear", align_corners=False, + ) + output = u_y + delta + accumulated + return (output, pyramid) if return_pyramid else output + + +__all__ = [ + "UFORMER_V7_VERSION", + "GlobalAttentionBlock", + "LeFF", + "LeWinBlock", + "UformerMoEUNetV7", + "WindowAttention", +] diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__init__.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2b2367dc5aa7f879640fc5a1a8d1ba1adb469544 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/__init__.py @@ -0,0 +1,5 @@ +""" +SCDC Test Suite +Sparse Compositional Degradation Coding - Testing Framework +""" +__version__ = "1.0.0" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/__init__.cpython-312.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/__init__.cpython-312.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2b99a05eb883d7fba1808754afbb4af0f428667e Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/__init__.cpython-312.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/conftest.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/conftest.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e18e8e9f55dc118962d3b614c328b2c7f2b60795 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/conftest.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_data.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_data.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e202c436741369b2d00304e3680c846c2bb5469f Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_data.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_model.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_model.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f7f8a55fc3aa2025b03eb2f608b3e28f85e0963d Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_model.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_training.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_training.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09ea465999a4583220790953f843d9a00cb69799 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_clean_relative_training.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_discovery.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_discovery.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0c5f6bc254cdc5842b108c3a797b05936ab0fa9b Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_discovery.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_extra_download.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_extra_download.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23beb35ad21b71f3cca8ff5087f010e8b67d4d6c Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_extra_download.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_expansion.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_expansion.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fcbe35ed3003493a5f2ed8cd1e78bf17f2a52167 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_expansion.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_sampling.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_sampling.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e3075fbed0a98bac6a12e7b5c65bc8f039b2ce5 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_sampling.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_strata.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_strata.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f672f6b9facc10df30635abdbd9de679120bb155 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_strata.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_suite.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_suite.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6e55c3ed2ef0ba5397c8b28c3467f963dc5696ad Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_noise_suite.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_suite.cpython-312-pytest-9.1.1.pyc b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_suite.cpython-312-pytest-9.1.1.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67c47ae7c07bb1b639cb252f6df23ecec4b02808 Binary files /dev/null and b/dataset/phase1_noise_20260906/trial_code_staging/tests/__pycache__/test_phase1_suite.cpython-312-pytest-9.1.1.pyc differ diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/conftest.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..1b7a707ff3d585669c115f1cee13bded013d2f42 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/conftest.py @@ -0,0 +1,245 @@ +""" +pytest configuration and fixtures for SCDC tests +""" +import pytest +import torch +import numpy as np +from pathlib import Path +from typing import Dict, List, Tuple, Optional + + +# ============================================= +# Fixtures: Mock Datasets +# ============================================= + +@pytest.fixture +def mock_clean_images(): + """Generate mock clean images tensor [N, C, H, W]""" + return torch.randn(32, 3, 224, 224) + + +@pytest.fixture +def mock_degraded_images(): + """Generate mock degraded images tensor [N, C, H, W]""" + return torch.randn(32, 3, 224, 224) + + +@pytest.fixture +def mock_displacements(): + """Generate mock displacement vectors [N, D]""" + return torch.randn(32, 256) + + +@pytest.fixture +def mock_dictionary(): + """Generate mock dictionary atoms [K, D]""" + K = 32 + D = 256 + # Create incoherent dictionary + atoms = torch.randn(K, D) + # Normalize atoms + atoms = atoms / atoms.norm(dim=1, keepdim=True) + return atoms + + +@pytest.fixture +def mock_sparse_codes(): + """Generate mock sparse codes [N, K] with L0 sparsity""" + N = 32 + K = 32 + codes = torch.zeros(N, K) + # Randomly select 2-5 non-zero entries per sample + for i in range(N): + n_nonzero = np.random.randint(2, 6) + nonzero_idx = np.random.choice(K, n_nonzero, replace=False) + codes[i, nonzero_idx] = torch.randn(n_nonzero) + return codes + + +@pytest.fixture +def mock_degradation_types(): + """List of mock degradation types""" + return [ + "gaussian_blur", + "motion_blur", + "noise", + "jpeg_compression", + "resize", + "color_distor" + ] + + +@pytest.fixture +def mock_severity_levels(): + """Mock severity levels [0, 1]""" + return np.linspace(0.1, 0.9, 9) + + +# ============================================= +# Fixtures: Mock Models +# ============================================= + +@pytest.fixture +def mock_backbone(): + """Create a mock backbone network""" + class MockBackbone(torch.nn.Module): + def __init__(self, feature_dim=256): + super().__init__() + self.features = torch.nn.Sequential( + torch.nn.Conv2d(3, 64, 3, padding=1), + torch.nn.ReLU(), + torch.nn.Conv2d(64, 128, 3, padding=1), + torch.nn.ReLU(), + torch.nn.AdaptiveAvgPool2d((1, 1)) + ) + self.fc = torch.nn.Linear(128, feature_dim) + + def forward(self, x): + x = self.features(x) + x = x.view(x.size(0), -1) + return self.fc(x) + + def extract_features(self, x, layer_idx=None): + """Extract features from intermediate layers""" + features = [] + for i, layer in enumerate(self.features): + x = layer(x) + if layer_idx is None or i in layer_idx: + features.append(x) + return features + + return MockBackbone() + + +@pytest.fixture +def mock_degraded_head(): + """Create a mock degraded head""" + class MockDegradedHead(torch.nn.Module): + def __init__(self, feature_dim=256, K=32): + super().__init__() + self.fc = torch.nn.Linear(feature_dim, K) + self.residual_net = torch.nn.Sequential( + torch.nn.Linear(feature_dim, 128), + torch.nn.ReLU(), + torch.nn.Linear(128, feature_dim) + ) + + def forward(self, features): + # Sparse coding + coefficients = self.fc(features) + # Residual + residual = self.residual_net(features) + return coefficients, residual + + return MockDegradedHead() + + +# ============================================= +# Fixtures: Test Data Generators +# ============================================= + +@pytest.fixture +def synthetic_degradation_pairs(): + """Generate synthetic clean/degraded pairs for testing""" + def _generate(n_samples=100, degradation_type="blur", severity_range=(0.1, 0.9)): + clean = torch.randn(n_samples, 3, 64, 64) + + # Create degraded versions with varying severity + degraded = clean.clone() + for i in range(n_samples): + sev = severity_range[0] + (severity_range[1] - severity_range[0]) * (i / n_samples) + if degradation_type == "blur": + # Apply blur effect (simulate by smoothing) + degraded[i] = torch.nn.functional.avg_pool2d( + clean[i].unsqueeze(0), 3, padding=1, stride=1 + ).squeeze(0) * (1 - sev) + clean[i] * sev + elif degradation_type == "noise": + noise = torch.randn_like(clean[i]) * sev * 0.3 + degraded[i] = clean[i] + noise + else: + degraded[i] = clean[i] * (1 - sev * 0.2) + sev * torch.randn_like(clean[i]) * 0.2 + + severities = torch.linspace(severity_range[0], severity_range[1], n_samples) + + return { + "clean": clean, + "degraded": degraded, + "severity": severities, + "degradation_type": degradation_type + } + + return _generate + + +# ============================================= +# Fixtures: Metric Helpers +# ============================================= + +@pytest.fixture +def metric_thresholds(): + """Standard metric thresholds for gate passing""" + return { + "linear_probe_accuracy": 0.85, + "spearman_rho": 0.70, + "additivity_cosine": 0.60, + "dictionary_coherence": 0.30, # Lower is better + "psnr": 25.0, + "ssim": 0.80, + "auroc": 0.85 + } + + +# ============================================= +# Fixtures: Paths +# ============================================= + +@pytest.fixture +def temp_experiment_dir(tmp_path): + """Create temporary experiment directory""" + exp_dir = tmp_path / "test_experiment" + exp_dir.mkdir() + (exp_dir / "checkpoints").mkdir() + (exp_dir / "logs").mkdir() + (exp_dir / "exports").mkdir() + return exp_dir + + +# ============================================= +# Fixtures: Common Utilities +# ============================================= + +@pytest.fixture +def device(): + """Get compute device""" + return torch.device("cuda" if torch.cuda.is_available() else "cpu") + + +@pytest.fixture +def seed(): + """Set random seed for reproducibility""" + torch.manual_seed(42) + np.random.seed(42) + if torch.cuda.is_available(): + torch.cuda.manual_seed(42) + return 42 + + +# ============================================= +# Setup/Teardown +# ============================================= + +def pytest_configure(config): + """Configure pytest""" + config.addinivalue_line("markers", "slow: marks tests as slow") + config.addinivalue_line("markers", "gpu: marks tests that require GPU") + + +def pytest_collection_modifyitems(config, items): + """Modify test collection""" + for item in items: + # Add slow marker to tests with "slow" in name + if "slow" in item.nodeid.lower(): + item.add_marker(pytest.mark.slow) + # Add gpu marker to tests that need GPU + if "cuda" in item.nodeid.lower() or "gpu" in item.nodeid.lower(): + item.add_marker(pytest.mark.gpu) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_data.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_data.py new file mode 100644 index 0000000000000000000000000000000000000000..d937458df389eec409123895751c1707d570de2c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_data.py @@ -0,0 +1,152 @@ +"""Contracts for uncapped paired data and controlled degradation interventions.""" + +import json + +import numpy as np +from PIL import Image +import pytest +import torch + +from scripts.prepare_phase1_seven import audit_files, split_training + +from src.data.clean_relative import ( + TYPES, + PairedDegradationDataset, + discover_exact_pairs, + isolate_splits, + sample_degradation_parameters, + synthesize_composition, + synthesize_degradation, + validate_manifest, +) + + +def _image(path, value=80): + path.parent.mkdir(parents=True, exist_ok=True) + Image.fromarray(np.full((19, 23, 3), value, dtype=np.uint8)).save(path) + return str(path) + + +def _record(root, index, split="train", group=None, content=None): + return { + "id": str(index), "dataset": "fixture", "type": "noise", + "group": group or str(index), "clean": _image(root / f"c{index}.png", index), + "degraded": _image(root / f"d{index}.png", index + 10), + "clean_content_sha256": content or f"hash{index}", + "split": split, + } + + +def test_strict_pair_discovery_rejects_unmatched_files(tmp_path): + _image(tmp_path / "input" / "one.png") + _image(tmp_path / "target" / "two.png") + with pytest.raises(ValueError, match="pairing mismatch"): + discover_exact_pairs(tmp_path / "input", tmp_path / "target") + + +def test_isolation_excludes_entire_leaking_scene_and_reports_it(tmp_path): + train = [_record(tmp_path, 1, group="scene", content="shared"), + _record(tmp_path, 2, group="scene", content="other"), + _record(tmp_path, 3)] + test = [_record(tmp_path, 4, split="test", content="shared")] + splits, excluded = isolate_splits({"train": train, "val": [], "test": test}) + assert [r["id"] for r in splits["train"]] == ["3"] + assert {r["id"] for r in excluded} == {"1", "2"} + assert all(r["reason"] == "cross_split_content_or_group_overlap" for r in excluded) + + +def test_dataset_covers_all_records_without_implicit_cap(tmp_path): + records = [_record(tmp_path, i) for i in range(1, 18)] + manifest = {"schema_version": 1, "types": list(TYPES), "train": records, + "val": [], "test": []} + path = tmp_path / "manifest.json" + path.write_text(json.dumps(manifest)) + dataset = PairedDegradationDataset(path, crop_size=16) + assert len(dataset) == 17 + assert {dataset[i]["record_id"] for i in range(len(dataset))} == {str(i) for i in range(1, 18)} + item = dataset[0] + assert item["clean"].shape == (3, 16, 16) + assert item["presence"].shape == (7,) + assert torch.allclose(item["degraded"] - item["clean"], torch.full_like(item["clean"], 10 / 255)) + + +def test_validate_manifest_rejects_content_leakage(tmp_path): + a = _record(tmp_path, 1, content="same") + b = _record(tmp_path, 2, split="val", content="same") + with pytest.raises(ValueError, match="leakage"): + validate_manifest({"schema_version": 1, "types": list(TYPES), + "train": [a], "val": [b], "test": []}) + + +def test_grouped_partitions_keep_more_than_legacy_cap(): + records = [{"id": str(index), "group": str(index // 10)} for index in range(6010)] + splits = split_training(records, 42, .05, .05) + assert sum(len(rows) for rows in splits.values()) == 6010 + assert len(splits["train"]) > 5000 + groups = [{row["group"] for row in splits[split]} for split in ("train", "val", "test")] + assert not groups[0] & groups[1] and not groups[1] & groups[2] and not groups[0] & groups[2] + + +def test_full_decode_audit_detects_reencoded_duplicate_content_and_caches(tmp_path): + one = _record(tmp_path, 1) + two = _record(tmp_path, 2) + with Image.open(one["clean"]) as image: + image.save(two["clean"], compress_level=9) + splits = {"train": [one, two], "val": [], "test": []} + cache = tmp_path / "hashes.sqlite" + checked, excluded, first = audit_files(splits, cache, workers=2, exclude_invalid=False) + assert not excluded + assert checked["train"][0]["clean_content_sha256"] == checked["train"][1]["clean_content_sha256"] + _, _, second = audit_files(splits, cache, workers=2, exclude_invalid=False) + assert first["decoded_new_files"] == 4 and second["decoded_new_files"] == 0 + + +def test_invalid_pair_rejected_unless_explicit_exclusion(tmp_path): + item = _record(tmp_path, 1) + Image.fromarray(np.zeros((8, 9, 3), dtype=np.uint8)).save(item["degraded"]) + splits = {"train": [item], "val": [], "test": []} + cache = tmp_path / "hashes.sqlite" + with pytest.raises(ValueError, match="invalid pairs"): + audit_files(splits, cache, workers=1, exclude_invalid=False) + kept, excluded, _ = audit_files(splits, cache, workers=1, exclude_invalid=True) + assert not kept["train"] and excluded[0]["reason"] == "invalid_pair" + + +@pytest.mark.parametrize("kind", TYPES) +def test_synthesis_deterministic_and_params_reusable(kind): + clean = torch.linspace(.1, .9, 3 * 24 * 24).reshape(3, 24, 24) + params = sample_degradation_parameters(kind, seed=45) + first, returned = synthesize_degradation(clean, kind, parameters=params) + second, _ = synthesize_degradation(clean, kind, parameters=params, seed=999) + transferred, transfer_params = synthesize_degradation(clean.flip(-1), kind, parameters=params) + assert torch.equal(first, second) + assert returned == transfer_params == params + assert transferred.shape == clean.shape + assert first.min() >= 0 and first.max() <= 1 + + +def test_heldout_strength_ranges_are_disjoint(): + for kind in TYPES: + for seed in range(20): + assert sample_degradation_parameters(kind, seed)["severity"] <= .70 + assert sample_degradation_parameters(kind, seed, heldout=True)["severity"] >= .80 + + +def test_composition_order_has_physical_effect(): + clean = torch.full((3, 24, 24), .4) + noise = {"severity": .5, "sigma": .06, "shot": 0., "noise_seed": 3} + haze = {"severity": .5, "transmission": .5, "airlight": [.8, .8, .8]} + before, _ = synthesize_composition(clean, ["noise", "haze"], [noise, haze]) + after, _ = synthesize_composition(clean, ["haze", "noise"], [haze, noise]) + clean_haze, _ = synthesize_degradation(clean, "haze", haze) + assert torch.allclose(before - clean_haze, .5 * (after - clean_haze), atol=1e-6) + + +def test_jpeg_quality_units_and_zero_severity_identity(): + clean = torch.rand(3, 24, 24) + identity, _ = synthesize_degradation(clean, "jpeg", {"severity": 0., "quality": 100}) + assert torch.equal(identity, clean) + params = sample_degradation_parameters("jpeg", 12) + assert 1 <= params["quality"] <= 100 + with pytest.raises(ValueError, match="quality"): + synthesize_degradation(clean, "jpeg", {"severity": .3, "quality": 120}) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_model.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_model.py new file mode 100644 index 0000000000000000000000000000000000000000..19c1eaccfc1c47f7f6c0ffa8a831c06a7475bd05 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_model.py @@ -0,0 +1,187 @@ +"""Functional contracts for the experimental seven-factor Phase-1 encoder.""" + +import pytest +import torch + +from src.models.graph_encoder.clean_relative import ( + TYPE_ORDER, + CleanRelativeConfig, + CleanRelativeGraphEncoder, +) + + +def tiny_model(): + torch.manual_seed(7) + return CleanRelativeGraphEncoder(CleanRelativeConfig( + token_dim=16, hidden_dim=32, node_dim=96, rank=4, + content_channels=16, num_blocks=1, blocks_per_stage=1, + interaction_hidden=32, decoder_width=16, + )) + + +def test_canonical_order_and_complete_blind_output(): + model = tiny_model().eval() + output = model(torch.rand(2, 3, 32, 48)) + assert TYPE_ORDER == ("rain", "noise", "haze", "lowlight", "snow", "blur", "jpeg") + assert output["content"].shape == (2, 16, 4, 6) + assert output["delta"].shape == (2, 96) + assert output["presence_logits"].shape == output["severity"].shape == (2, 7) + assert output["coefficients"].shape == (2, 9, 4) + assert output["amplitudes"].shape == (2, 9) + assert output["node_tokens"].shape == (2, 9, 96) + assert output["residual"].shape == (2, 96) + assert output["spatial"].shape == (2, 7, 4, 6) + assert output["photometric"].shape == (2, 8) + assert all(torch.isfinite(value).all() for value in output.values()) + + +def test_identical_pair_has_exact_zero_teacher_displacement_in_train_mode(): + model = tiny_model().train() + image = torch.rand(2, 3, 32, 32) + pair = model.forward_pair(image, image) + assert set(pair) == {"student", "teacher", "clean"} + assert set(pair["student"]) == set(pair["teacher"]) == set(pair["clean"]) + for name in ("delta", "coefficients", "amplitudes", "node_tokens", "residual", "photometric", "spatial"): + assert torch.count_nonzero(pair["teacher"][name]).item() == 0, name + torch.testing.assert_close(pair["teacher"]["content"], pair["clean"]["content"]) + + +def test_node_tokens_are_trained_basis_contributions_with_exact_reconstruction(): + model = tiny_model() + output = model(torch.rand(2, 3, 32, 32)) + torch.testing.assert_close( + output["node_tokens"].sum(dim=1) + output["residual"], + output["delta"].float(), atol=2e-6, rtol=2e-6, + ) + basis_blocks = output["basis"].T.reshape(9, 4, 96) + expected = torch.einsum("bnr,nrd->bnd", output["coefficients"], basis_blocks) + torch.testing.assert_close(output["node_tokens"], expected) + # A factor-specific downstream functional objective reaches the same basis + # and delta parameters as Phase-1 supervision, without an untrained adapter. + output["node_tokens"][:, 0, :8].sum().backward() + assert model.basis_raw.grad is not None and model.basis_raw.grad.abs().sum() > 0 + assert model.delta_head.weight.grad is not None and model.delta_head.weight.grad.abs().sum() > 0 + assert not hasattr(model, "node_identity") and not hasattr(model, "coefficient_token") + + +def test_global_basis_is_orthonormal_and_residual_does_not_double_count(): + model = tiny_model() + basis = model.orthonormal_basis() + torch.testing.assert_close(basis.T @ basis, torch.eye(36), atol=2e-6, rtol=2e-6) + delta = torch.randn(3, 96) + state = model.decompose(delta) + reconstruction = state["coefficients"].flatten(1) @ basis.T + state["residual"] + torch.testing.assert_close(reconstruction, delta, atol=2e-6, rtol=2e-6) + torch.testing.assert_close(state["residual"] @ basis, torch.zeros(3, 36), atol=2e-6, rtol=0) + torch.testing.assert_close( + state["coefficients"].square().sum((1, 2)) + state["residual"].square().sum(1), + delta.square().sum(1), atol=2e-5, rtol=2e-6, + ) + + +def test_drop_factor_accepts_batched_indices_and_removes_only_selected_subspace(): + model = tiny_model() + delta = torch.randn(2, 96) + before = model.decompose(delta) + dropped = model.drop_factor(delta, torch.tensor([0, 8])) + after = model.decompose(dropped) + assert after["coefficients"][0, 0].abs().max() < 2e-6 + assert after["coefficients"][1, 8].abs().max() < 2e-6 + torch.testing.assert_close(after["coefficients"][0, 1:], before["coefficients"][0, 1:], atol=2e-6, rtol=2e-6) + torch.testing.assert_close(after["residual"], before["residual"], atol=2e-6, rtol=2e-6) + + +def test_interaction_has_exact_boundaries_order_and_no_edge_control(): + model = tiny_model() + first, second = torch.randn(2, 96), torch.randn(2, 96) + zero = torch.zeros_like(first) + torch.testing.assert_close(model.compose(first, zero, 0, 1), first, atol=0, rtol=0) + torch.testing.assert_close(model.compose(zero, second, 0, 1), second, atol=0, rtol=0) + torch.testing.assert_close(model.compose(first, second, 0, 1, use_edges=False), first + second, atol=0, rtol=0) + forward = model.compose(first, second, torch.tensor([0, 2]), torch.tensor([1, 3])) + reverse = model.compose(second, first, torch.tensor([1, 3]), torch.tensor([0, 2])) + assert not torch.allclose(forward, reverse) + forward.square().mean().backward() + assert model.interaction.type_embedding.weight.grad.abs().sum() > 0 + assert model.interaction.net[-1].weight.grad.abs().sum() > 0 + + +def test_teacher_proxy_and_both_evidence_streams_receive_gradients(): + model = tiny_model().train() + clean = torch.rand(2, 3, 32, 32) * 0.7 + 0.2 + degraded = (clean * 0.45 + torch.rand_like(clean) * 0.1).clamp(0, 1) + pair = model.forward_pair(degraded, clean) + teacher = pair["teacher"] + teacher["delta"].retain_grad() + prediction = model.decode(teacher["content"], teacher["delta"], (32, 32)) + identity = model.decode(pair["clean"]["content"], torch.zeros_like(teacher["delta"]), (32, 32)) + assert prediction.shape == identity.shape == clean.shape + loss = (prediction - degraded).square().mean() + (identity - clean).square().mean() + loss = loss + teacher["coefficients"].abs().mean() + pair["student"]["presence_logits"].square().mean() + loss.backward() + assert teacher["delta"].grad is not None and teacher["delta"].grad.abs().sum() > 0 + for module in (model.spatial_branch, model.wavelet_branch, model.content_projector, model.delta_head): + assert any(p.grad is not None and torch.isfinite(p.grad).all() and p.grad.abs().sum() > 0 for p in module.parameters()) + for block in model.decoder_upsamplers: + assert block.projection.weight.grad.abs().sum() > 0 + assert block.condition.weight.grad.abs().sum() > 0 + assert model.basis_raw.grad is not None and torch.isfinite(model.basis_raw.grad).all() + + +def test_invalid_basis_capacity_and_image_shapes_are_rejected(): + with pytest.raises(ValueError, match="rank"): + CleanRelativeConfig(node_dim=32, rank=8) + with pytest.raises(ValueError, match="divisible by 16"): + tiny_model()(torch.rand(2, 3, 33, 32)) + + +def test_amp_keeps_basis_and_residual_in_float32_with_finite_gradients(): + model = tiny_model().train() + image = torch.rand(2, 3, 32, 32) + with torch.autocast(device_type="cpu", dtype=torch.bfloat16): + pair = model.forward_pair(image * 0.5, image) + teacher = pair["teacher"] + proxy = model.decode(teacher["content"], teacher["delta"], (32, 32)) + loss = proxy.square().mean() + teacher["coefficients"].square().mean() + assert teacher["basis"].dtype == teacher["residual"].dtype == torch.float32 + loss.backward() + assert torch.isfinite(loss) + assert model.basis_raw.grad is not None and torch.isfinite(model.basis_raw.grad).all() + + +def test_proxy_native_resolution_has_conditional_checkerboard_capacity(monkeypatch): + """A native one-pixel alternating effect must not be smoothed from H/8 RGB.""" + model = tiny_model() + content = torch.zeros(1, 16, 4, 4) + delta = torch.zeros(1, 96, requires_grad=True) + + def forbid_interpolation(*args, **kwargs): + raise AssertionError("native proxy output must use learned upsampling") + + monkeypatch.setattr(torch.nn.functional, "interpolate", forbid_interpolation) + # First verify the native path independently of its parameterization. + assert model.decode(content, delta, (32, 32)).shape == (1, 3, 32, 32) + with torch.no_grad(): + for name, parameter in model.named_parameters(): + if name.startswith("decoder_"): + parameter.zero_() + final_up = model.decoder_upsamplers[-1] + # Four sub-pixel phases of one channel: a 1px checkerboard. Delta[0] + # modulates its contrast, demonstrating a conditional high-frequency path. + final_up.projection.bias[:4].copy_(torch.tensor([2.0, -2.0, -2.0, 2.0])) + final_up.condition.weight[0, 0] = 1.0 + model.decoder_output.weight[:, 0, 1, 1] = 1.0 + output = model.decode(content, delta, (32, 32)) + rows, columns = torch.meshgrid(torch.arange(32), torch.arange(32), indexing="ij") + pattern = 1.0 - 2.0 * ((rows + columns) % 2).float() + checkerboard_response = (output * pattern).mean() + assert checkerboard_response > 0.15 + checkerboard_response.backward() + assert delta.grad[0, 0].abs() > 1e-3 + assert model.decoder_upsamplers[-1].projection.bias.grad.abs().sum() > 0 + + +@pytest.mark.parametrize("size", [(0, 32), (-1, 32), (32,), (32, 32, 32), (32.5, 32)]) +def test_proxy_rejects_invalid_output_sizes(size): + with pytest.raises(ValueError, match="output_size"): + tiny_model().decode(torch.zeros(1, 16, 4, 4), torch.zeros(1, 96), size) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_training.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_training.py new file mode 100644 index 0000000000000000000000000000000000000000..a99aa067a2631a41333074436a47038f9ad2a93c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_clean_relative_training.py @@ -0,0 +1,212 @@ +"""Training/evaluation contracts for the independent seven-factor pipeline.""" + +import random +import json + +import numpy as np +import pytest +import torch +from PIL import Image + +import train_phase1_clean_relative as train +import eval_phase1_clean_relative as evaluate + + +def test_epoch_permutation_covers_tail_and_resume_without_replacement(): + order = train.epoch_indices(19, seed=17, epoch=2) + assert sorted(order) == list(range(19)) + assert order != train.epoch_indices(19, seed=17, epoch=3) + assert order[7:] == train.epoch_indices(19, seed=17, epoch=2, start=7) + with pytest.raises(ValueError): + train.epoch_indices(19, seed=17, epoch=2, start=20) + + +def test_class_weights_give_equal_epoch_mass_without_oversampling(): + labels = torch.tensor([0] * 100 + [1] * 4 + [2] * 2) + weights = train.class_weights(labels, num_classes=7) + masses = [(weights[labels] * (labels == k)).sum() for k in range(3)] + assert torch.allclose(torch.stack(masses), torch.full((3,), len(labels) / 3)) + assert weights[3:].eq(0).all() + + +def test_scene_components_link_video_groups_and_cross_group_duplicates(): + records = [{"dataset": "gopro", "group": "video1", "clean_content_sha256": "frame1"}, + {"dataset": "gopro", "group": "video1", "clean_content_sha256": "frame2"}, + {"dataset": "other", "group": "scene2", "clean_content_sha256": "frame2"}, + {"dataset": "gopro", "group": "video3", "clean_content_sha256": "frame3"}] + components = train.scene_component_ids(records) + assert components[0] == components[1] == components[2] + assert components[3] != components[0] + + +def test_atomic_checkpoint_and_rng_roundtrip(tmp_path): + random.seed(4) + np.random.seed(4) + torch.manual_seed(4) + snapshot = train.capture_rng() + expected = (random.random(), np.random.rand(), torch.rand(3)) + target = tmp_path / "last.pt" + train.atomic_torch_save({"rng": snapshot, "cursor": 19}, target) + state = torch.load(target, weights_only=False) + train.restore_rng(state["rng"]) + assert random.random() == expected[0] + assert np.random.rand() == expected[1] + assert torch.equal(torch.rand(3), expected[2]) + assert not list(tmp_path.glob("*.tmp")) + + +def test_nonfinite_gradient_never_changes_parameters(): + model = torch.nn.Linear(2, 1) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + original = [p.detach().clone() for p in model.parameters()] + (model(torch.ones(1, 2)).sum() * float("inf")).backward() + accepted, _ = train.safe_optimizer_step(model, optimizer, max_norm=1.0) + assert not accepted + assert all(torch.equal(old, new) for old, new in zip(original, model.parameters())) + + +def test_average_precision_ties_and_missing_positives_are_explicit(): + assert evaluate.average_precision([1, 0, 1, 0], [0.5] * 4) == pytest.approx(0.5) + assert evaluate.average_precision([0, 0], [0.3, 0.8]) is None + assert evaluate.average_precision([1, 0], [0.8, 0.3]) == pytest.approx(1.0) + + +def test_classification_report_does_not_hide_missing_classes(): + labels = torch.tensor([0, 0, 1]) + scores = torch.full((3, 7), -10.0) + scores[0, 0] = scores[1, 1] = scores[2, 1] = 10.0 + result = evaluate.classification_report(labels, scores) + assert result["confusion"][0][:2] == [1, 1] + assert result["per_domain"]["haze"]["support"] == 0 + assert result["per_domain"]["haze"]["average_precision"] is None + assert result["supported_classes"] == 2 + + +def test_constant_regression_target_is_not_perfect_evidence(): + result = evaluate.regression_report([0.4, 0.4], [0.4, 0.4]) + assert result["r2"] is None + assert result["pearson"] is None + assert result["mae"] == pytest.approx(0.0) + + +def test_train_and_eval_defaults_do_not_cap_full_splits(): + args = train.build_parser().parse_args(["--manifest", "m.json", "--output-dir", "run"]) + assert args.max_train_records is None + assert args.batch_size == 16 + assert not args.no_edges and not args.prototype_only + args = evaluate.build_parser().parse_args(["--manifest", "m.json", "--checkpoint", "last.pt"]) + assert args.max_records is None + assert args.split == "val" + + +def test_heldout_combinations_never_enter_train_schedule(): + heldout = {frozenset(pair) for pair in train.HELDOUT_PAIRS} + assert all(frozenset(pair) not in heldout for pair in train.TRAIN_PAIRS) + assert len(train.TRAIN_PAIRS) > 7 + assert all((b, a) in train.TRAIN_PAIRS for a, b in train.TRAIN_PAIRS) + + +def test_high_frequency_statistic_detects_noise_when_mean_is_unchanged(): + clean = torch.full((1, 3, 32, 32), 0.5) + noisy = clean.clone() + noisy[..., ::2, ::2] += .1 + noisy[..., 1::2, 1::2] -= .1 + assert torch.allclose(noisy.mean(), clean.mean()) + error = train.functional_error(clean, noisy, clean, torch.tensor([1])) + assert error.item() > .02 + + +def test_cross_content_synthesis_rejects_same_scene_variants(): + result = train.controlled_batch(torch.rand(2, 3, 32, 32), 0, 42, 1, scene_ids=["same", "same"]) + assert not result["cross_content_available"] + + +def test_unknown_physical_severity_is_not_supervised_as_zero(): + presence = torch.eye(7)[:2] + rep = {"presence_logits": torch.zeros(2, 7), "amplitudes": torch.ones(2, 9), + "residual": torch.zeros(2, 256), "severity": torch.ones(2, 7)} + absent = train.supervised_terms(rep, presence, torch.ones(2), torch.zeros(2, 7), torch.zeros(2, 7, dtype=torch.bool)) + assert absent["severity"] == 0 + explicit = train.supervised_terms(rep, presence, torch.ones(2), torch.zeros(2, 7), presence.bool()) + assert explicit["severity"] == 1 + + +def test_physical_parameter_probe_requires_enough_disjoint_scenes(): + rows = [{"scene": i, "parameters": {"severity": .5, "angle": i * 8.0}, + "coefficients": [np.sin(np.deg2rad(i * 16.0)), np.cos(np.deg2rad(i * 16.0))]} for i in range(20)] + assert evaluate.physical_parameter_probe(rows[:4], "blur")["status"] == "insufficient_data" + measured = evaluate.physical_parameter_probe(rows, "blur") + assert measured["baseline_plus_factor_coefficients_mse"] < measured["baseline_mse"] + assert measured["factor_rank"] == 2 + + +def test_objective_reaches_all_trainable_heads(): + from src.models.graph_encoder.clean_relative import CleanRelativeGraphEncoder + + torch.set_num_threads(1) + model = CleanRelativeGraphEncoder() + clean = torch.rand(2, 3, 32, 32) + degraded = clean * .7 + presence = torch.zeros(2, 7) + presence[:, 3] = 1 + weights = train.LossWeights() + loss, _ = train.pair_objective(model, model.forward_pair(degraded, clean), clean, degraded, presence, torch.ones(2), weights) + synthetic = train.controlled_batch(clean, 0, 42, 1) + value, _ = train.synthetic_objective(model, synthetic, weights, use_edges=True) + (loss + value).backward() + missing = [name for name, parameter in model.named_parameters() if parameter.requires_grad and parameter.grad is None] + assert missing == [] + assert all(torch.isfinite(parameter.grad).all() for parameter in model.parameters() if parameter.grad is not None) + + +@pytest.fixture +def seven_manifest(tmp_path): + manifest = {"schema_version": 1, "types": list(train.TYPE_ORDER)} + for split_index, split in enumerate(("train", "val", "test")): + records = [] + for i in range(8 if split == "train" else 7): + seed = split_index * 100 + i + image = np.random.default_rng(seed).integers(20, 200, (32, 32, 3), dtype=np.uint8) + clean = tmp_path / f"{split}_{i}_clean.png" + degraded = tmp_path / f"{split}_{i}_degraded.png" + Image.fromarray(image).save(clean) + Image.fromarray((image.astype(float) * .8).astype(np.uint8)).save(degraded) + records.append({"id": f"{split}_{i}", "dataset": "fixture", "type": train.TYPE_ORDER[i % 7], + "group": f"{split}_{i}", "clean_content_sha256": str(seed), + "clean": str(clean), "degraded": str(degraded)}) + manifest[split] = records + path = tmp_path / "manifest.json" + path.write_text(json.dumps(manifest)) + return path + + +def test_full_training_resume_and_controlled_evaluation(seven_manifest, tmp_path): + common = ["--manifest", str(seven_manifest), "--epochs", "1", "--batch-size", "3", "--patch-size", "32", + "--num-workers", "0", "--threads", "1", "--synthetic-batch-size", "1", "--device", "cpu", "--log-every", "1"] + interrupted = tmp_path / "interrupted" + first = train.main(common + ["--output-dir", str(interrupted), "--max-steps", "1"]) + assert first["cursor"] == 3 and first["global_step"] == 1 + result = train.main(common + ["--output-dir", str(interrupted), "--resume", str(interrupted / "last.pt")]) + assert result["status"] == "completed" and result["global_step"] == 3 + rows = [json.loads(line) for line in (interrupted / "metrics.jsonl").read_text().splitlines()] + assert [row["unique_records"] for row in rows if row["event"] == "epoch_coverage"] == [8] + uninterrupted = tmp_path / "uninterrupted" + train.main(common + ["--output-dir", str(uninterrupted)]) + resumed = torch.load(interrupted / "last.pt", weights_only=False) + reference = torch.load(uninterrupted / "last.pt", weights_only=False) + assert all(torch.equal(value, reference["model"][name]) for name, value in resumed["model"].items()) + report = evaluate.main(["--manifest", str(seven_manifest), "--checkpoint", str(interrupted / "last.pt"), + "--device", "cpu", "--batch-size", "2", "--patch-size", "32", "--num-workers", "0", + "--threads", "1", "--synthetic-scenes", "4"]) + assert report["real"]["records_evaluated"] == 7 + assert report["real"]["clean_origin_proxy"]["status"] == "measured" + assert report["controlled"]["distinct_source_scenes"] == 4 + assert report["controlled"]["content_probe"]["status"] == "measured" + assert report["controlled"]["family_leave_one_out"]["status"] == "requires_retraining" + mixed = report["controlled"]["mixed"]["per_batch_results"]["heldout_pairs"][0] + assert mixed["forward_functional_error"] >= 0 + assert mixed["reverse_additive_functional_error"] >= 0 + assert any(key.endswith("_before_drop_error") for key in mixed) + controls = report["controlled"]["cross_content_transfer"]["controls"]["noise"] + assert controls["blind"]["count"] == controls["zero"]["count"] == 4 + assert report["controlled"]["within_factor_parameter_probes"]["blur"]["status"] == "insufficient_data" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_eval_full_frame.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_eval_full_frame.py new file mode 100644 index 0000000000000000000000000000000000000000..a1e7af19c13a3a745c25ab50143a3e1b1478b93d --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_eval_full_frame.py @@ -0,0 +1,169 @@ +"""Full-frame tiled evaluator: dihedral TTA, tiling coverage, exact blending.""" +import pytest +import torch + +import eval_full_frame as ff + + +def test_dihedral_transforms_are_invertible_and_distinct(): + torch.manual_seed(0) + x = torch.rand(1, 3, 6, 10) + seen = [] + for k in range(8): + y = ff.dihedral_transform(x, k) + assert torch.equal(ff.dihedral_inverse(y, k), x), k + seen.append(y) + square = torch.rand(1, 3, 8, 8) + outs = [ff.dihedral_transform(square, k) for k in range(8)] + for a in range(8): + for b in range(a + 1, 8): + assert not torch.equal(outs[a], outs[b]), (a, b) + + +def test_tile_boxes_cover_image_and_end_flush(): + boxes = ff.tile_boxes(300, 500, 128, 32) + tops = sorted({t for t, _ in boxes}) + lefts = sorted({l for _, l in boxes}) + assert tops[0] == 0 and tops[-1] == 300 - 128 + assert lefts[0] == 0 and lefts[-1] == 500 - 128 + covered = torch.zeros(300, 500, dtype=torch.bool) + for t, l in boxes: + assert 0 <= t <= 300 - 128 and 0 <= l <= 500 - 128 + covered[t:t + 128, l:l + 128] = True + assert bool(covered.all()) + assert ff.tile_boxes(128, 128, 128, 32) == [(0, 0)] + + +def test_blend_weights_complementary_and_interior_one(): + w = ff.blend_weights(64, 16) + assert w.shape == (1, 1, 64, 64) + assert float(w[0, 0, 32, 32]) == 1.0 + ramp = w[0, 0, 32, :16] + # tile A's trailing ramp (48..63) overlaps tile B's leading ramp (0..15) at stride 48 + assert torch.allclose(ramp + w[0, 0, 32, 48:], torch.ones(16)) + assert float(w.min()) > 0.0 + + +def _identity(tiles, ids, full): + return tiles + + +def test_restore_tiled_identity_is_exact_for_awkward_sizes(): + torch.manual_seed(1) + for shape in ((1, 3, 300, 500), (1, 3, 64, 64), (1, 3, 70, 200), (1, 3, 40, 150)): + x = torch.rand(*shape) + y = ff.restore_tiled(_identity, x, "r", tile=64, overlap=16, tile_batch=3) + assert y.shape == x.shape + assert torch.allclose(y, x, atol=1e-6), shape + + +def test_restore_tiled_constant_shift_and_tile_ids_are_distinct(): + torch.manual_seed(2) + x = torch.rand(1, 3, 130, 190) + seen = [] + + def shift(tiles, ids, full): + seen.extend(ids) + assert full is not None and full.shape[0] == tiles.shape[0] + return tiles + 0.25 + + y = ff.restore_tiled(shift, x, "rec", tile=64, overlap=16, full_frame=torch.rand(1, 3, 8, 8)) + assert torch.allclose(y, x + 0.25, atol=1e-6) + assert len(seen) == len(set(seen)) and all(s.startswith("rec|tile") for s in seen) + + +def test_tta_averages_transform_sensitive_restorers(): + torch.manual_seed(3) + x = torch.rand(1, 3, 64, 96) + same = ff.restore_full_frame(_identity, x, "r", tta=8, tile=32, overlap=8) + assert torch.allclose(same, x, atol=1e-6) + + def left_bias(tiles, ids, full): # adds a gradient that depends on orientation + ramp = torch.linspace(0, 0.2, tiles.shape[-1]).view(1, 1, 1, -1) + return (tiles + ramp).clamp(0, 1) + + one = ff.restore_full_frame(left_bias, x, "r", tta=1, tile=32, overlap=8) + eight = ff.restore_full_frame(left_bias, x, "r", tta=8, tile=32, overlap=8) + assert not torch.allclose(one, eight) + # left/right symmetric average: the horizontal drift cancels to a constant + drift = (eight - x).mean(dim=(0, 1, 2)) + assert float(drift.std()) < float((one - x).mean(dim=(0, 1, 2)).std()) + + +def test_y_channel_metrics(): + gray = torch.full((1, 3, 16, 16), 0.5) + y = ff.rgb_to_y601(gray) + assert y.shape == (1, 1, 16, 16) + assert abs(float(y.mean()) * 255 - (16 + 0.5 * (65.481 + 128.553 + 24.966))) < 1e-3 + a = torch.rand(2, 3, 32, 32) + b = (a + 0.05).clamp(0, 1) + assert torch.isfinite(ff.psnr_y_per_image(a, b)).all() + assert float(ff.ssim_y_per_image(a, a).min()) > 0.999 + + +def test_lpips_center_crops_large_images(): + calls = [] + + def fake_lpips(p, t): + calls.append(p.shape[-2:]) + return torch.zeros(p.shape[0]) + + ff.lpips_center(fake_lpips, torch.rand(1, 3, 50, 70), torch.rand(1, 3, 50, 70), max_side=40) + assert tuple(calls[-1]) == (40, 40) + ff.lpips_center(fake_lpips, torch.rand(1, 3, 30, 30), torch.rand(1, 3, 30, 30), max_side=40) + assert tuple(calls[-1]) == (30, 30) + + +def test_restore_whole_pads_to_multiple_and_crops_back(): + torch.manual_seed(5) + x = torch.rand(1, 3, 300, 500) + shapes = [] + + def spy(img, ids, full): + shapes.append(tuple(img.shape[-2:])) + assert len(ids) == 1 and ids[0].endswith("|whole") + return img + + y = ff.restore_whole(spy, x, "r") + assert shapes == [(384, 512)] and torch.equal(y, x) + exact = torch.rand(1, 3, 128, 256) + assert torch.equal(ff.restore_whole(spy, exact, "e"), exact) and shapes[-1] == (128, 256) + tiny = torch.rand(1, 3, 20, 30) # replicate padding when the pad exceeds the size + assert torch.equal(ff.restore_whole(spy, tiny, "t"), tiny) and shapes[-1] == (128, 128) + + +def test_full_frame_routes_small_images_whole_and_large_ones_tiled(): + torch.manual_seed(6) + calls = [] + + def spy(img, ids, full): + calls.append(("whole" if ids[0].endswith("|whole") else "tile", tuple(img.shape[-2:]))) + return img + + small = torch.rand(1, 3, 100, 120) + out = ff.restore_full_frame(spy, small, "s", tta=1, whole_max_pixels=20000, tile=64, overlap=16) + assert torch.allclose(out, small) and calls == [("whole", (128, 128))] + calls.clear() + large = torch.rand(1, 3, 200, 300) + out = ff.restore_full_frame(spy, large, "l", tta=1, whole_max_pixels=20000, tile=64, overlap=16) + assert torch.allclose(out, large, atol=1e-6) and all(k == "tile" for k, _ in calls) and len(calls) > 1 + calls.clear() + ff.restore_full_frame(spy, small, "s", tta=8, whole_max_pixels=0, tile=64, overlap=16) + assert all(k == "tile" for k, _ in calls) + + +def test_tta2_uses_only_identity_and_horizontal_mirror(): + torch.manual_seed(7) + x = torch.rand(1, 3, 64, 96) + seen = [] + + def spy(tiles, ids, full): + seen.append(ids[0].split("|")[1]) + return tiles + + ff.restore_full_frame(spy, x, "r", tta=2, tile=32, overlap=8) + assert sorted(set(seen)) == ["d0", "d4"] + assert ff.TTA_TRANSFORMS[2] == (0, 4) and ff.dihedral_transform(x, 4).shape == x.shape + assert torch.equal(ff.dihedral_transform(x, 4), torch.flip(x, dims=(-1,))) + with pytest.raises(ValueError): + ff.restore_full_frame(spy, x, "r", tta=4, tile=32, overlap=8) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_gated_graph_resshift_v5.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_gated_graph_resshift_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..60655aacbea4f4722250902590a7dcf28d622968 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_gated_graph_resshift_v5.py @@ -0,0 +1,483 @@ +import copy +from types import SimpleNamespace + +import pytest +import torch + +from src.models.restoration.gated_graph_resshift_v5 import ( + EXPERT_ORDER, + GatedAdapterBank, + GatedGraphConditionerV5, + GatedGraphResidualShiftUNetV5, + SoftDegradationRouter, + VariancePreservingNoiseMixer, +) +from src.models.restoration.graph_resshift_v4 import ( + GraphConditionerV4, + GraphResidualShiftUNetV4, +) + + +def _representation(batch: int = 2, content_hw: int = 8) -> SimpleNamespace: + routing = torch.tensor( + [ + [0.40, 0.20, 0.10, 0.05, 0.15, 0.10], + [0.05, 0.10, 0.20, 0.35, 0.20, 0.10], + ], + dtype=torch.float32, + )[:batch] + return SimpleNamespace( + content_latent=torch.randn(batch, 128, content_hw, content_hw), + node_tokens=torch.randn(batch, 6, 256), + routing_probs=routing, + severity_coords=torch.sigmoid(torch.randn(batch, 4)), + spatial_maps=torch.randn(batch, 4, 4, 4), + unknown_residual=torch.randn(batch, 256), + global_condition=torch.randn(batch, 256), + ) + + +def test_router_starts_at_four_semantic_plus_generic_phase1_prior() -> None: + router = SoftDegradationRouter(hidden_dim=32) + representation = _representation() + + output = router(representation) + expected = torch.cat( + ( + representation.routing_probs[:, :4], + representation.routing_probs[:, 4:].sum(dim=1, keepdim=True), + ), + dim=1, + ) + + assert EXPERT_ORDER == ("rain", "noise", "haze", "lowlight", "generic") + assert output.gates.shape == (2, 5) + assert torch.allclose(output.prior, expected, atol=1e-7, rtol=1e-7) + assert torch.allclose(output.gates, expected, atol=2e-7, rtol=2e-7) + assert torch.allclose(output.gates.sum(dim=1), torch.ones(2)) + assert torch.isfinite(output.anchor_loss) + assert torch.isfinite(output.balance_loss) + + +def test_router_excludes_content_latent_and_remains_continuous() -> None: + router = SoftDegradationRouter(hidden_dim=32) + representation = _representation(batch=1) + baseline = router(representation).gates + + content_changed = copy.copy(representation) + content_changed.content_latent = torch.randn_like(representation.content_latent) * 100 + assert torch.equal(router(content_changed).gates, baseline) + + route_changed = copy.copy(representation) + route_changed.routing_probs = representation.routing_probs.clone() + route_changed.routing_probs[0, 0] += 1e-4 + route_changed.routing_probs[0, 1] -= 1e-4 + updated = router(route_changed).gates + assert not torch.equal(updated, baseline) + assert (updated - baseline).abs().max().item() < 1e-3 + + representation.routing_probs.requires_grad_(True) + gates = router(representation).gates + (gates[:, 0] - gates[:, 1]).sum().backward() + assert representation.routing_probs.grad is not None + assert torch.isfinite(representation.routing_probs.grad).all() + assert representation.routing_probs.grad.abs().sum().item() > 0 + + +@pytest.mark.parametrize( + "mutation, message", + ( + (lambda value: setattr(value, "routing_probs", value.routing_probs[:, :4]), "routing_probs"), + (lambda value: setattr(value, "severity_coords", value.severity_coords[:, :3]), "severity_coords"), + (lambda value: setattr(value, "unknown_residual", value.unknown_residual[:, :32]), "unknown_residual"), + (lambda value: value.routing_probs.fill_(float("nan")), "finite"), + ), +) +def test_router_fails_closed_on_invalid_representation(mutation, message: str) -> None: + router = SoftDegradationRouter(hidden_dim=32) + representation = _representation(batch=1) + mutation(representation) + with pytest.raises(ValueError, match=message): + router(representation) + + +def test_conditioner_null_mode_is_representation_independent() -> None: + conditioner = GatedGraphConditionerV5( + cond_dim=32, + stage_dims=(8, 16, 24, 32), + router_hidden_dim=32, + ) + first = conditioner(_representation(batch=1), mode="null") + second_representation = _representation(batch=1) + second_representation.routing_probs = torch.tensor( + [[0.01, 0.01, 0.01, 0.01, 0.48, 0.48]] + ) + second = conditioner(second_representation, mode="null") + + for name in ("context", "global_vector", "content", "spatial", "expert_gates"): + assert torch.equal(getattr(first, name), getattr(second, name)) + assert getattr(first, name).count_nonzero().item() == 0 + assert first.route_active.item() == 0.0 + + full = conditioner(_representation(batch=1), mode="full") + assert torch.allclose(full.expert_gates.sum(dim=1), torch.ones(1)) + assert full.route_active.item() == 1.0 + + +def test_adapter_bank_is_exact_soft_mixture_and_routes_gradients() -> None: + adapter = GatedAdapterBank(channels=2, rank=1, num_experts=2) + with torch.no_grad(): + for expert_index, expert in enumerate(adapter.experts): + expert[0].weight.fill_(1.0) + expert[0].bias.zero_() + expert[2].weight.fill_(float(expert_index + 1)) + expert[2].bias.zero_() + + features = torch.ones(1, 2, 3, 3) + mixed_gate = torch.tensor([[0.25, 0.75]], requires_grad=True) + residual = adapter.residual(features, mixed_gate) + first = adapter.experts[0](features) + second = adapter.experts[1](features) + assert torch.allclose(residual, 0.25 * first + 0.75 * second) + assert not torch.equal(residual, first) + assert not torch.equal(residual, second) + + residual.square().mean().backward() + assert mixed_gate.grad is not None + assert mixed_gate.grad.abs().sum().item() > 0 + + +def test_zero_initialized_adapter_heads_are_neutral_but_selected_head_gets_gradient() -> None: + adapter = GatedAdapterBank(channels=4, rank=2, num_experts=3) + features = torch.randn(2, 4, 5, 5) + gates = torch.tensor([[0.0, 1.0, 0.0], [0.0, 1.0, 0.0]]) + residual = adapter.residual(features, gates) + assert residual.count_nonzero().item() == 0 + + (residual - torch.ones_like(residual)).square().mean().backward() + for index, expert in enumerate(adapter.experts): + gradient = expert[2].weight.grad + if index == 1: + assert gradient is not None and gradient.abs().sum().item() > 0 + else: + assert gradient is not None and gradient.count_nonzero().item() == 0 + + +def test_noise_mixer_matches_l2_formula_and_null_bypasses_experts() -> None: + mixer = VariancePreservingNoiseMixer(num_experts=3, expert_fraction=1.0) + bank = torch.arange(1, 1 + 4 * 2 * 2, dtype=torch.float32).reshape(1, 4, 1, 2, 2) + gate = torch.tensor([[0.2, 0.3, 0.5]]) + actual = mixer(bank, gate, route_active=torch.ones(1, 1)) + weights = gate / gate.square().sum(dim=1, keepdim=True).sqrt() + expected = (bank[:, 1:] * weights[:, :, None, None, None]).sum(dim=1) + assert torch.allclose(actual, expected) + + one_hot = torch.tensor([[0.0, 1.0, 0.0]]) + assert torch.equal( + mixer(bank, one_hot, route_active=torch.ones(1, 1)), bank[:, 2] + ) + assert torch.equal( + mixer(bank, torch.zeros_like(gate), route_active=torch.zeros(1, 1)), + bank[:, 0], + ) + + shared_only = VariancePreservingNoiseMixer( + num_experts=3, expert_fraction=0.0 + ) + unused_experts = bank.clone() + unused_experts[:, 1:] = float("nan") + assert torch.equal( + shared_only(unused_experts, gate, route_active=torch.ones(1, 1)), + bank[:, 0], + ) + + +def test_noise_mixer_preserves_standard_normal_marginal_variance() -> None: + generator = torch.Generator().manual_seed(1234) + # Keep the local CPU test compact; the analytic coefficient assertion above + # is exact, while this Monte-Carlo check catches reused/correlated streams. + bank = torch.randn(8_192, 6, 1, 1, 1, generator=generator) + mixer = VariancePreservingNoiseMixer(num_experts=5, expert_fraction=0.7) + for values in ( + [1.0, 0.0, 0.0, 0.0, 0.0], + [0.2, 0.2, 0.2, 0.2, 0.2], + [0.70, 0.20, 0.07, 0.02, 0.01], + ): + gate = torch.tensor([values]).expand(bank.shape[0], -1) + sample = mixer(bank, gate, route_active=torch.ones(bank.shape[0], 1)).flatten() + assert abs(sample.mean().item()) < 0.04 + assert 0.94 < sample.var(unbiased=False).item() < 1.06 + + +def test_noise_fraction_has_one_contract_owned_source_of_truth() -> None: + shared_only = VariancePreservingNoiseMixer( + num_experts=2, expert_fraction=0.0 + ) + expert_only = VariancePreservingNoiseMixer( + num_experts=2, expert_fraction=1.0 + ) + assert shared_only.state_dict() == {} + assert expert_only.state_dict() == {} + shared_only.load_state_dict(expert_only.state_dict(), strict=True) + + bank = torch.tensor([[[[[1.0]]], [[[2.0]]], [[[4.0]]]]]) + gate = torch.tensor([[1.0, 0.0]]) + active = torch.ones(1, 1) + assert torch.equal(shared_only(bank, gate, active), bank[:, 0]) + assert torch.equal(expert_only(bank, gate, active), bank[:, 1]) + + +@pytest.mark.parametrize( + "bank, gate, active, message", + ( + (torch.randn(2, 5, 1, 1, 1), torch.ones(2, 5) / 5, torch.ones(2, 1), "bank"), + (torch.randn(2, 6, 1, 1, 1), torch.ones(2, 4) / 4, torch.ones(2, 1), "gate"), + (torch.randn(2, 6, 1, 1, 1), torch.full((2, 5), float("nan")), torch.ones(2, 1), "finite"), + (torch.randn(2, 6, 1, 1, 1), -torch.ones(2, 5), torch.ones(2, 1), "non-negative"), + ), +) +def test_noise_mixer_rejects_invalid_inputs(bank, gate, active, message: str) -> None: + mixer = VariancePreservingNoiseMixer(num_experts=5, expert_fraction=1.0) + with pytest.raises(ValueError, match=message): + mixer(bank, gate, route_active=active) + + +def test_zero_initialized_v5_paths_preserve_nontrivial_v4_prediction() -> None: + dims = (8, 16, 24, 32) + cond_dim = 32 + v4_conditioner = GraphConditionerV4(cond_dim=cond_dim, stage_dims=dims) + v4_denoiser = GraphResidualShiftUNetV4(dims=dims, cond_dim=cond_dim) + with torch.no_grad(): + v4_denoiser.output_residual.weight.normal_(std=0.01) + + v5_conditioner = GatedGraphConditionerV5( + cond_dim=cond_dim, + stage_dims=dims, + router_hidden_dim=32, + ) + v5_denoiser = GatedGraphResidualShiftUNetV5( + dims=dims, + cond_dim=cond_dim, + adapter_rank=4, + ) + condition_result = v5_conditioner.load_state_dict( + v4_conditioner.state_dict(), strict=False + ) + denoiser_result = v5_denoiser.load_state_dict(v4_denoiser.state_dict(), strict=False) + assert not condition_result.unexpected_keys + assert not denoiser_result.unexpected_keys + + representation = _representation(batch=1, content_hw=8) + v4_condition = v4_conditioner(representation, mode="full") + v5_condition = v5_conditioner(representation, mode="full") + u_t = torch.randn(1, 12, 16, 16) + u_y = torch.randn_like(u_t) + timestep = torch.tensor([2]) + v4_prediction = v4_denoiser(u_t, u_y, timestep, v4_condition) + v5_prediction = v5_denoiser(u_t, u_y, timestep, v5_condition) + + assert not torch.equal(v4_prediction, u_y) + assert torch.equal(v5_prediction, v4_prediction) + + +# --------------------------------------------------------------------------- +# Per-type kappa (Level A): schedule override + ExpertKappaSchedule +# --------------------------------------------------------------------------- + +from src.models.restoration.gated_graph_resshift_v5 import ( # noqa: E402 + ExpertKappaSchedule, +) +from src.models.restoration.graph_resshift_v4 import ( # noqa: E402 + ResidualShiftSchedule, +) + +_KAPPA_VALUES = (0.09780, 0.03836, 0.13436, 0.41464, 0.11608) + + +def test_schedule_per_sample_kappa_matches_scalar_path_exactly() -> None: + schedule = ResidualShiftSchedule(timesteps=4, kappa=0.2) + torch.manual_seed(0) + u0 = torch.randn(3, 12, 8, 8) + uy = torch.randn(3, 12, 8, 8) + noise = torch.randn_like(u0) + timesteps = torch.tensor([1, 2, 4]) + + baseline = schedule.q_sample(u0, uy, timesteps, noise=noise) + override = schedule.q_sample( + u0, uy, timesteps, noise=noise, kappa=torch.full((3,), 0.2) + ) + assert torch.equal(baseline, override) + + mean_a, var_a = schedule.posterior_mean_variance(baseline, u0, timesteps) + mean_b, var_b = schedule.posterior_mean_variance( + baseline, u0, timesteps, kappa=torch.full((3,), 0.2) + ) + assert torch.equal(mean_a, mean_b) + assert torch.equal(var_a, var_b) + + +def test_schedule_per_sample_kappa_scales_marginal_and_posterior() -> None: + schedule = ResidualShiftSchedule(timesteps=4, kappa=0.2) + u0 = torch.zeros(2, 12, 8, 8) + uy = torch.zeros(2, 12, 8, 8) + noise = torch.ones_like(u0) + timesteps = torch.tensor([3, 3]) + kappa = torch.tensor([0.05, 0.4]) + + u_t = schedule.q_sample(u0, uy, timesteps, noise=noise, kappa=kappa) + eta_t = float(schedule.eta[3]) + expected_low = 0.05 * eta_t ** 0.5 + expected_high = 0.4 * eta_t ** 0.5 + assert torch.allclose(u_t[0], torch.full_like(u_t[0], expected_low)) + assert torch.allclose(u_t[1], torch.full_like(u_t[1], expected_high)) + + _, variance = schedule.posterior_mean_variance( + u_t, u0, timesteps, kappa=kappa + ) + ratio = variance[1].flatten()[0] / variance[0].flatten()[0] + assert torch.allclose(ratio, torch.tensor((0.4 / 0.05) ** 2)) + + +@pytest.mark.parametrize( + "kappa, message", + ( + (torch.full((4,), 0.2), "one value per batch"), + (torch.full((3, 1), 0.2), "one value per batch"), + (torch.tensor([0.2, -0.1, 0.2]), "non-negative"), + (torch.tensor([0.2, float("nan"), 0.2]), "finite"), + ), +) +def test_schedule_rejects_invalid_kappa_override(kappa, message: str) -> None: + schedule = ResidualShiftSchedule(timesteps=4, kappa=0.2) + u0 = torch.zeros(3, 12, 8, 8) + timesteps = torch.tensor([1, 2, 3]) + with pytest.raises(ValueError, match=message): + schedule.q_sample(u0, u0, timesteps, noise=u0, kappa=kappa) + + +def test_expert_kappa_alpha_zero_is_bitwise_global() -> None: + module = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=10 + ) + gates = torch.softmax(torch.randn(4, 5), dim=1) + active = torch.ones(4, 1) + + result = module(gates, active) + + assert int(module.microsteps_seen) == 0 + assert torch.equal(result, torch.full((4,), 0.2)) + + +def test_expert_kappa_one_hot_after_full_anneal() -> None: + module = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=0 + ) + gates = torch.eye(5) + active = torch.ones(5, 1) + + result = module(gates, active) + + assert torch.allclose( + result, torch.tensor(_KAPPA_VALUES), rtol=1e-6, atol=0.0 + ) + + +def test_expert_kappa_uniform_gate_is_geometric_mean() -> None: + module = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=0 + ) + gates = torch.full((1, 5), 0.2) + active = torch.ones(1, 1) + + result = module(gates, active) + + expected = torch.exp( + torch.log(torch.tensor(_KAPPA_VALUES)).mean() + ) + assert torch.allclose(result, expected.reshape(1), rtol=1e-6) + + +def test_expert_kappa_null_mode_and_zero_mass_fall_back_to_global() -> None: + module = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=0 + ) + zero_gates = torch.zeros(2, 5) + inactive = torch.zeros(2, 1) + + assert torch.equal( + module(zero_gates, inactive), torch.full((2,), 0.2) + ) + live_gates = torch.softmax(torch.randn(2, 5), dim=1) + assert torch.equal( + module(live_gates, inactive), torch.full((2,), 0.2) + ) + + +def test_expert_kappa_gate_gradient_is_stopped() -> None: + module = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=0 + ) + logits = torch.randn(3, 5, requires_grad=True) + gates = torch.softmax(logits, dim=1) + + result = module(gates, torch.ones(3, 1)) + + assert not result.requires_grad + + +def test_expert_kappa_anneal_midpoint_is_log_space_mix() -> None: + module = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=4 + ) + module.advance() + module.advance() + + gates = torch.zeros(1, 5) + gates[0, 3] = 1.0 # lowlight + result = module(gates, torch.ones(1, 1)) + + expected = (0.2 * _KAPPA_VALUES[3]) ** 0.5 + assert torch.allclose( + result, torch.tensor([expected]), rtol=1e-6 + ) + module.advance() + module.advance() + module.advance() + assert torch.allclose(module.alpha(), torch.tensor(1.0)) + + +@pytest.mark.parametrize( + "kwargs, message", + ( + ({"kappa_per_expert": (0.1, 0.2)}, "per-expert kappa values"), + ( + {"kappa_per_expert": (0.1, 0.2, 0.3, -0.4, 0.5)}, + "finite and positive", + ), + ( + { + "kappa_per_expert": _KAPPA_VALUES, + "kappa_global": 0.0, + }, + "finite and positive", + ), + ( + { + "kappa_per_expert": _KAPPA_VALUES, + "anneal_microsteps": -1, + }, + "non-negative", + ), + ), +) +def test_expert_kappa_rejects_invalid_configuration( + kwargs, message: str +) -> None: + defaults = { + "kappa_per_expert": _KAPPA_VALUES, + "kappa_global": 0.2, + "anneal_microsteps": 0, + } + defaults.update(kwargs) + with pytest.raises(ValueError, match=message): + ExpertKappaSchedule(**defaults) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_graph_moe_v6.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_graph_moe_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..5e70fabd108a18b57bb0cb683998c0f8fc95d4da --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_graph_moe_v6.py @@ -0,0 +1,248 @@ +from types import SimpleNamespace + +import pytest +import torch + +import train_phase2_graph_moe_v6 as v6 +from src.models.restoration.graph_moe_v6 import ( + MoEGraphConditionerV6, + MoEGraphResidualShiftUNetV6, + NodeActivationGate, + SpatialExpertBank, + expert_kappa_from_strengths, +) +from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule +from src.models.restoration.graph_resshift_v4 import ( + GraphConditionerV4, + GraphResidualShiftUNetV4, +) + + +def _representation(batch: int = 2, content_hw: int = 8) -> SimpleNamespace: + routing = torch.tensor( + [ + [0.70, 0.05, 0.10, 0.05, 0.06, 0.04], + [0.05, 0.05, 0.40, 0.40, 0.05, 0.05], + ] + )[:batch] + return SimpleNamespace( + content_latent=torch.randn(batch, 128, content_hw, content_hw), + node_tokens=torch.randn(batch, 6, 256), + routing_probs=routing, + severity_coords=torch.tensor( + [[0.8, 0.2, 0.5, 0.1], [0.3, 0.3, 0.9, 0.7]] + )[:batch], + spatial_maps=torch.rand(batch, 4, 4, 4), + unknown_residual=torch.randn(batch, 256), + global_condition=torch.randn(batch, 256), + ) + + +def test_gate_zero_init_matches_phase1_prior_and_is_independent() -> None: + gate = NodeActivationGate() + rep = _representation() + out = gate(rep) + prior = torch.cat( + (rep.routing_probs[:, :4], rep.routing_probs[:, 4:].sum(1, keepdim=True)), + dim=1, + ) + assert torch.allclose(out.activations, prior, atol=1e-5) + # Independent sigmoids: two strong degradations both stay strong — + # nothing forces the activations to sum to one. + assert float(out.activations[1, 2] + out.activations[1, 3]) > 0.75 + expected_strength = out.activations[:, :4] * rep.severity_coords + assert torch.allclose(out.strengths[:, :4], expected_strength, atol=1e-6) + assert out.top2_mask.sum(dim=1).eq(2).all() + + +def test_spatial_expert_bank_zero_init_identity_and_map_gating() -> None: + bank = SpatialExpertBank(channels=8, rank=4) + gate = NodeActivationGate()(_representation()) + features = torch.randn(2, 8, 16, 16) + assert torch.equal(bank(features, gate), features) + + with torch.no_grad(): + for expert in bank.experts: + expert[-1].weight.normal_(0, 0.05) + out_active = bank(features, gate) + assert not torch.equal(out_active, features) + + from src.models.restoration.graph_moe_v6 import NodeGateOutput + + zero_map_gate = NodeGateOutput( + activations=gate.activations, + strengths=torch.tensor([[1.0, 0.0, 0.0, 0.0, 0.0]] * 2), + top2_mask=torch.tensor([[1.0, 1.0, 0.0, 0.0, 0.0]] * 2), + spatial_gates=torch.zeros(2, 4, 4, 4), + prior=gate.prior, + anchor_loss=gate.anchor_loss, + correction_loss=gate.correction_loss, + ) + assert torch.equal(bank(features, zero_map_gate), features) + + +def test_unet_v6_zero_init_paths_reproduce_v4_prediction() -> None: + torch.manual_seed(0) + dims = (8, 16, 24, 32) + v4_conditioner = GraphConditionerV4(cond_dim=32, stage_dims=dims) + v4_unet = GraphResidualShiftUNetV4(dims=dims, cond_dim=32) + v6_conditioner = MoEGraphConditionerV6(cond_dim=32, stage_dims=dims) + v6_unet = MoEGraphResidualShiftUNetV6(dims=dims, cond_dim=32, expert_rank=4) + v6_conditioner.load_state_dict(v4_conditioner.state_dict(), strict=False) + v6_unet.load_state_dict(v4_unet.state_dict(), strict=False) + + rep = _representation(content_hw=4) + u_t = torch.randn(2, 12, 8, 8) + u_y = torch.randn(2, 12, 8, 8) + t = torch.tensor([3, 7]) + prediction_v4 = v4_unet(u_t, u_y, t, v4_conditioner(rep)) + prediction_v6 = v6_unet(u_t, u_y, t, v6_conditioner(rep)) + assert torch.equal(prediction_v4, prediction_v6) + + +def test_expert_kappa_from_strengths_falls_back_to_global() -> None: + kappa = ExpertKappaSchedule( + (0.1, 0.04, 0.13, 0.4, 0.12), kappa_global=0.116, anneal_microsteps=0 + ) + gate = NodeActivationGate()(_representation()) + from src.models.restoration.graph_moe_v6 import NodeGateOutput + + zero = NodeGateOutput( + activations=gate.activations, + strengths=torch.zeros(2, 5), + top2_mask=gate.top2_mask, + spatial_gates=gate.spatial_gates, + prior=gate.prior, + anchor_loss=gate.anchor_loss, + correction_loss=gate.correction_loss, + ) + result = expert_kappa_from_strengths(kappa, zero, torch.ones(2, 1)) + assert torch.allclose(result, torch.full((2,), 0.116)) + + +def _tiny_module() -> v6.Phase2MoEV6Module: + dims = (8, 16, 24, 32) + from src.models.restoration.graph_resshift_v4 import ResidualShiftSchedule + + return v6.Phase2MoEV6Module( + conditioner=MoEGraphConditionerV6(cond_dim=32, stage_dims=dims), + denoiser=MoEGraphResidualShiftUNetV6( + dims=dims, cond_dim=32, expert_rank=4 + ), + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.2), + expert_kappa=ExpertKappaSchedule( + (0.1, 0.04, 0.13, 0.4, 0.12), kappa_global=0.2, anneal_microsteps=4 + ), + condition_mode="full", + ) + + +def test_training_loss_is_finite_and_advances_kappa_anneal() -> None: + module = _tiny_module() + module.train() + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + rep = _representation(content_hw=4) + result = module.training_loss( + clean, degraded, rep, torch.tensor([1, 2]), + noise=torch.randn(2, 12, 8, 8), + ) + assert torch.isfinite(result.loss) + assert result.kappa.shape == (2,) + assert int(module.expert_kappa.microsteps_seen) == 1 + result.loss.backward() + gate_grads = [ + p.grad for p in module.conditioner.node_gate.parameters() + if p.grad is not None + ] + assert gate_grads and any(float(g.abs().sum()) > 0 for g in gate_grads) + + +def test_sampler_one_step_and_chain_run() -> None: + module = _tiny_module().eval() + + class _FixedPhase1(torch.nn.Module): + def __init__(self, rep): + super().__init__() + self.rep = rep + self.weight = torch.nn.Parameter(torch.ones(())) + + def forward(self, clean, degraded, is_training=True): + return self.rep + + from src.models.restoration.graph_resshift_v4 import FrozenPhase1 + + phase1 = FrozenPhase1(_FixedPhase1(_representation(content_hw=4))) + degraded = torch.rand(2, 3, 16, 16) + one = v6.sample_moe_restoration( + module, phase1, degraded, seed=1, record_ids=["a", "b"], + amp_enabled=False, + ) + module.eval_sample_steps = 2 + chain = v6.sample_moe_restoration( + module, phase1, degraded, seed=1, record_ids=["a", "b"], + amp_enabled=False, + ) + assert one.shape == degraded.shape == chain.shape + assert float(one.min()) >= 0 and float(one.max()) <= 1 + + +def test_warmstart_loader_allowlist_and_parser(tmp_path) -> None: + module = _tiny_module() + dims = (8, 16, 24, 32) + v4_state = {} + v4_state.update( + {"conditioner." + k: v for k, v in GraphConditionerV4( + cond_dim=32, stage_dims=dims).state_dict().items()} + ) + v4_state.update( + {"denoiser." + k: v for k, v in GraphResidualShiftUNetV4( + dims=dims, cond_dim=32).state_dict().items()} + ) + v4_state.update( + {"schedule." + k: v + for k, v in module.schedule.state_dict().items()} + ) + checkpoint = { + "schema_version": 4, "phase": 2, "condition_mode": "full", + "step": 1000, "phase1_sha256": "old" * 16, + "ema_state_dict": {"shadow": v4_state}, + } + path = tmp_path / "v4.pt" + torch.save(checkpoint, str(path)) + audit = v6.load_v4_warmstart_moe( + path, v6._file_sha256(path), module, weight_source="ema" + ) + assert audit["cross_phase1"] is True + assert audit["source_step"] == 1000 + + parser = v6.build_parser() + args = parser.parse_args( + [ + "--phase1-checkpoint", str(tmp_path / "p1.pt"), + "--phase1-sha256", "a" * 64, + "--manifest", str(tmp_path / "m.json"), + "--output-dir", str(tmp_path / "out"), + "--kappa", "0.116", + ] + ) + assert args.eval_sample_steps == 1 + assert args.expert_rank == 16 + + +def test_freeze_shared_trunk_flag_trains_only_v6_paths(tmp_path) -> None: + module = _tiny_module() + args = SimpleNamespace(freeze_shared_trunk=True) + # mirror _build_moe_restorer's curriculum logic + for name, parameter in module.named_parameters(): + parameter.requires_grad_(v6._is_v6_only_key(name)) + trainable = { + name for name, p in module.named_parameters() if p.requires_grad + } + assert trainable + assert all(v6._is_v6_only_key(name) for name in trainable) + frozen = { + name for name, p in module.named_parameters() if not p.requires_grad + } + assert any(name.startswith("denoiser.down_blocks") for name in frozen) + del args, tmp_path diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_graph_resshift_v4.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_graph_resshift_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..b69971c06312d3ce06215cd78282b0dd5e036321 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_graph_resshift_v4.py @@ -0,0 +1,276 @@ +import copy +from types import SimpleNamespace + +import pytest +import torch +import torch.nn as nn +import torch.nn.functional as F + +from src.models.restoration.graph_resshift_v4 import ( + BRANCH_ORDER, + PHASE1_AGGREGATION_VERSION, + PHASE1_SCHEMA_VERSION, + ConditionBundle, + FrozenPhase1, + GraphConditionerV4, + GraphResidualShiftUNetV4, + ResidualShiftSchedule, + load_phase1_checkpoint, + pad_to_multiple, + pixel_shuffle2, + pixel_unshuffle2, +) + + +def _representation(batch=2, height=64, width=64): + return SimpleNamespace( + content_latent=torch.randn(batch, 128, height, width), + node_tokens=torch.randn(batch, 6, 256), + routing_probs=torch.softmax(torch.randn(batch, 6), dim=-1), + severity_coords=torch.sigmoid(torch.randn(batch, 4)), + spatial_maps=torch.sigmoid(torch.randn(batch, 4, 16, 16)), + unknown_residual=torch.randn(batch, 256), + global_condition=torch.randn(batch, 256), + ) + + +def test_pixel_unshuffle_is_lossless_and_preserves_mse_scaling(): + clean = torch.rand(2, 3, 18, 22) + degraded = torch.rand_like(clean) + u_clean = pixel_unshuffle2(clean) + u_degraded = pixel_unshuffle2(degraded) + assert u_clean.shape == (2, 12, 9, 11) + assert torch.equal(pixel_shuffle2(u_clean), clean) + assert torch.allclose( + F.mse_loss(u_clean, u_degraded), + F.mse_loss(clean, degraded), + atol=1e-7, + rtol=1e-6, + ) + + +def test_schedule_is_a_module_with_monotone_persistent_buffers(): + schedule = ResidualShiftSchedule( + timesteps=8, eta_end=0.99, min_noise=0.2, power=0.3, kappa=0.2 + ) + buffers = dict(schedule.named_buffers()) + assert "sqrt_eta" in buffers and "eta" in buffers and "eta_prev" in buffers + assert schedule.eta.shape == (9,) + assert schedule.eta[0].item() == 0.0 + assert schedule.eta[-1].item() == pytest.approx(0.99 ** 2) + assert torch.all(schedule.eta[1:] > schedule.eta[:-1]) + restored = ResidualShiftSchedule(timesteps=8) + restored.load_state_dict(schedule.state_dict(), strict=True) + assert torch.equal(restored.eta, schedule.eta) + + +def test_schedule_matches_upstream_sqrt_eta_power_regression(): + schedule = ResidualShiftSchedule( + timesteps=4, eta_end=0.99, min_noise=0.2, power=0.3, kappa=0.12 + ) + # Independently evaluated from the journal implementation's exponential + # sqrt-eta curve, then squared. The leading zero is our t=0 boundary. + expected_sqrt_eta = torch.tensor( + [0.0, 0.2, 0.6318385147123036, 0.8242905481949386, 0.99] + ) + expected_eta = torch.tensor( + [0.0, 0.04, 0.3992199086738499, 0.6794549078435125, 0.9801] + ) + assert torch.allclose(schedule.sqrt_eta, expected_sqrt_eta, atol=1e-7, rtol=1e-7) + # Squaring the upstream float32 sqrt curve incurs one additional rounding. + assert torch.allclose(schedule.eta, expected_eta, atol=2e-7, rtol=1e-7) + assert schedule.eta[-1].item() == pytest.approx(0.99 ** 2) + + +def test_deterministic_schedule_handles_zero_kappa_without_division(): + schedule = ResidualShiftSchedule(timesteps=4, kappa=0.0) + assert torch.isfinite(schedule.sqrt_eta).all() + u0 = torch.randn(1, 12, 3, 3) + uy = torch.randn_like(u0) + t = torch.tensor([3]) + assert torch.equal( + schedule.q_sample(u0, uy, t, noise=torch.randn_like(u0)), + u0 + schedule.extract(schedule.eta, t, u0) * (uy - u0), + ) + + +def test_q_sample_uses_kappa_times_sqrt_eta_not_sqrt_kappa_eta(): + schedule = ResidualShiftSchedule(timesteps=4, kappa=0.25) + u0 = torch.zeros(2, 12, 3, 5) + uy = torch.ones_like(u0) + noise = torch.ones_like(u0) + t = torch.tensor([1, 4], dtype=torch.long) + actual = schedule.q_sample(u0, uy, t, noise=noise) + eta = schedule.extract(schedule.eta, t, u0) + expected = u0 + eta * (uy - u0) + 0.25 * torch.sqrt(eta) * noise + wrong = u0 + eta * (uy - u0) + torch.sqrt(0.25 * eta) * noise + assert torch.allclose(actual, expected) + assert not torch.allclose(actual, wrong) + + +def test_exact_posterior_mean_variance_and_t1_boundary(): + schedule = ResidualShiftSchedule(timesteps=8, kappa=0.2) + u0_hat = torch.randn(3, 12, 4, 4) + u_t = torch.randn_like(u0_hat) + t = torch.tensor([1, 4, 8], dtype=torch.long) + mean, variance = schedule.posterior_mean_variance(u_t, u0_hat, t) + eta_t = schedule.extract(schedule.eta, t, u_t) + eta_prev = schedule.extract(schedule.eta_prev, t, u_t) + expected_mean = eta_prev / eta_t * u_t + (eta_t - eta_prev) / eta_t * u0_hat + expected_var = 0.2 ** 2 * (eta_prev / eta_t) * (eta_t - eta_prev) + assert torch.allclose(mean, expected_mean) + assert torch.allclose(variance, expected_var) + assert torch.equal(mean[0], u0_hat[0]) + assert variance[0].count_nonzero().item() == 0 + + +def test_oracle_reverse_chain_finishes_at_clean_state(): + schedule = ResidualShiftSchedule(timesteps=8, kappa=0.2) + u0 = torch.randn(2, 12, 5, 7) + uy = torch.randn_like(u0) + u_t = schedule.q_sample( + u0, + uy, + torch.full((2,), schedule.timesteps, dtype=torch.long), + noise=torch.randn_like(u0), + ) + visited = [] + generator = torch.Generator().manual_seed(9) + for step in schedule.reverse_timesteps(): + visited.append(step) + t = torch.full((2,), step, dtype=torch.long) + mean, variance = schedule.posterior_mean_variance(u_t, u0, t) + if step > 1: + noise = torch.randn(u_t.shape, generator=generator) + u_t = mean + torch.sqrt(variance) * noise + else: + u_t = mean + assert visited == list(range(8, 0, -1)) + assert torch.allclose(u_t, u0, atol=1e-6, rtol=1e-6) + + +def test_graph_conditioner_uses_continuous_soft_routing(): + conditioner = GraphConditionerV4() + representation = _representation(batch=1) + representation.routing_probs.requires_grad_(True) + condition = conditioner(representation, mode="full") + loss = condition.context.square().mean() + condition.global_vector.square().mean() + loss.backward() + assert representation.routing_probs.grad is not None + assert representation.routing_probs.grad.abs().sum().item() > 0 + + changed = copy.copy(representation) + changed.routing_probs = representation.routing_probs.detach().clone() + changed.routing_probs[0, 0] += 1e-3 + changed_condition = conditioner(changed, mode="full") + assert not torch.equal(condition.context, changed_condition.context) + assert not torch.equal(condition.global_vector, changed_condition.global_vector) + + +def test_nonmax_branch_severity_changes_its_corresponding_context_token(): + conditioner = GraphConditionerV4() + representation = _representation(batch=1) + representation.severity_coords = torch.tensor([[0.9, 0.7, 0.1, 0.4]]) + baseline = conditioner(representation, mode="full") + + changed = copy.copy(representation) + changed.severity_coords = representation.severity_coords.clone() + changed.severity_coords[0, 2] += 1e-3 # non-maximum haze coordinate + updated = conditioner(changed, mode="full") + + assert not torch.equal(baseline.context[:, 2], updated.context[:, 2]) + assert torch.equal(baseline.context[:, 0], updated.context[:, 0]) + assert torch.equal(baseline.context[:, 1], updated.context[:, 1]) + assert torch.equal(baseline.context[:, 3:6], updated.context[:, 3:6]) + + +def test_full_and_null_conditioning_are_parameter_identical(): + conditioner = GraphConditionerV4() + representation = _representation(batch=2) + full = conditioner(representation, mode="full") + null = conditioner(representation, mode="null") + assert isinstance(full, ConditionBundle) + assert sum(p.numel() for p in conditioner.parameters()) == sum( + p.numel() for p in conditioner.parameters() + ) + assert null.context.count_nonzero().item() == 0 + assert null.global_vector.count_nonzero().item() == 0 + assert null.content.count_nonzero().item() == 0 + assert null.spatial.count_nonzero().item() == 0 + assert full.context.shape == null.context.shape == (2, 8, 256) + + +class _DummyPhase1(nn.Module): + def __init__(self): + super().__init__() + self.weight = nn.Parameter(torch.ones(())) + self.last_call = None + + def forward(self, clean, degraded, is_training=True): + self.last_call = (clean, is_training, torch.is_grad_enabled()) + return _representation(batch=degraded.shape[0]) + + +def test_frozen_phase1_stays_eval_and_never_builds_gradients(): + encoder = _DummyPhase1() + wrapper = FrozenPhase1(encoder) + wrapper.train(True) + result = wrapper(torch.rand(2, 3, 256, 256, requires_grad=True)) + assert result.node_tokens.shape == (2, 6, 256) + assert encoder.last_call == (None, False, False) + assert not encoder.training + assert all(not parameter.requires_grad for parameter in encoder.parameters()) + + +def test_checkpoint_loader_rejects_stale_semantics_and_strict_loads(tmp_path): + encoder = _DummyPhase1() + good = { + "schema_version": PHASE1_SCHEMA_VERSION, + "phase": 1, + "aggregation_version": PHASE1_AGGREGATION_VERSION, + "branch_order": list(BRANCH_ORDER), + "model_state_dict": encoder.state_dict(), + "config": {"graph_config": {}}, + } + path = tmp_path / "phase1.pt" + torch.save(good, path) + loaded = _DummyPhase1() + metadata = load_phase1_checkpoint(path, loaded, expected_sha256=None) + assert metadata["phase"] == 1 + assert torch.equal(loaded.weight, encoder.weight) + + for field, bad_value in ( + ("schema_version", 1), + ("phase", 2), + ("aggregation_version", 1), + ("branch_order", ["blur", "noise", "jpeg", "lowlight"]), + ): + stale = dict(good) + stale[field] = bad_value + torch.save(stale, path) + with pytest.raises(ValueError, match=field): + load_phase1_checkpoint(path, _DummyPhase1(), expected_sha256=None) + + +def test_unet_zero_residual_head_is_identity_anchor_and_shape_safe(): + model = GraphResidualShiftUNetV4(dims=(16, 32, 48, 64), cond_dim=64) + representation = _representation(batch=1) + conditioner = GraphConditionerV4(cond_dim=64, stage_dims=(16, 32, 48, 64)) + condition = conditioner(representation, mode="full") + uy = torch.rand(1, 12, 16, 16) + ut = torch.randn_like(uy) + prediction = model(ut, uy, torch.tensor([3]), condition) + assert prediction.shape == uy.shape + assert torch.equal(prediction, uy) + assert model.content_inject.weight.count_nonzero().item() == 0 + assert model.spatial_inject.weight.count_nonzero().item() == 0 + + +@pytest.mark.parametrize("height,width", [(35, 41), (256, 256), (257, 259)]) +def test_pad_to_multiple_round_trip_contract(height, width): + image = torch.randn(1, 3, height, width) + padded, original_size = pad_to_multiple(image, multiple=16) + assert padded.shape[-2] % 16 == 0 + assert padded.shape[-1] % 16 == 0 + assert original_size == (height, width) + assert torch.equal(padded[..., :height, :width], image) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_hvi.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_hvi.py new file mode 100644 index 0000000000000000000000000000000000000000..812c6919b941f36bd37732f1dfca4e9403937f67 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_hvi.py @@ -0,0 +1,50 @@ +import math + +import torch + +from src.models.graph_encoder.hvi import ( + HVI_STAT_NAMES, hvi_colour_stats, hvi_to_rgb, rgb_to_hvi, rgb_to_hsv_components, +) + + +def test_round_trip_is_close_for_generic_images(): + torch.manual_seed(0) + rgb = torch.rand(4, 3, 32, 32) + back = hvi_to_rgb(rgb_to_hvi(rgb, 0.2), 0.2) + assert (back - rgb).abs().max() < 2e-3 + + +def test_hue_matches_known_colours(): + rgb = torch.tensor([[[[1.0]], [[0.0]], [[0.0]]], # red + [[[0.0]], [[1.0]], [[0.0]]], # green + [[[0.0]], [[0.0]], [[1.0]]]]) # blue + hue, sat, val = rgb_to_hsv_components(rgb) + assert torch.allclose(hue.flatten(), torch.tensor([0.0, 1 / 3, 2 / 3]), atol=1e-6) + assert torch.allclose(sat.flatten(), torch.ones(3)) + assert torch.allclose(val.flatten(), torch.ones(3)) + + +def test_intensity_collapse_shrinks_dark_chroma(): + bright = torch.tensor([[[[1.0]], [[0.0]], [[0.0]]]]) + dark = bright * 0.05 + chroma_bright = rgb_to_hvi(bright, 0.2)[:, :2].norm(dim=1).item() + chroma_dark = rgb_to_hvi(dark, 0.2)[:, :2].norm(dim=1).item() + assert chroma_dark < chroma_bright + # HSV saturation alone would be 1.0 for both; HVI collapses the dark one. + assert chroma_dark < 0.7 * chroma_bright + + +def test_polarised_hue_is_continuous_across_red(): + just_below = torch.tensor([[[[1.0]], [[0.0]], [[0.02]]]]) # hue ~ 0.997 + just_above = torch.tensor([[[[1.0]], [[0.02]], [[0.0]]]]) # hue ~ 0.003 + a = rgb_to_hvi(just_below)[:, :2].flatten() + b = rgb_to_hvi(just_above)[:, :2].flatten() + assert (a - b).norm().item() < 0.1 + + +def test_colour_stats_shape_and_grey_has_zero_cast(): + grey = torch.full((2, 3, 16, 16), 0.5) + stats = hvi_colour_stats(grey) + assert stats.shape == (2, len(HVI_STAT_NAMES)) + assert stats[:, 0].abs().max() < 1e-4 and stats[:, 1].abs().max() < 1e-4 + assert torch.isfinite(stats).all() diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_discovery.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_discovery.py new file mode 100644 index 0000000000000000000000000000000000000000..3a8ad6e1850f5133fe317d49eb4e4ff9385fc187 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_discovery.py @@ -0,0 +1,95 @@ +from argparse import Namespace +from pathlib import Path +from types import SimpleNamespace + +from PIL import Image +import pytest + +from scripts.prepare_phase1_seven import discover, record, split_training, audit_files +from src.data.clean_relative import isolate_splits, validate_manifest, TYPES + + +def image(path: Path, colour: int): + path.parent.mkdir(parents=True, exist_ok=True) + Image.new("RGB", (32, 32), (colour % 256, (colour * 7) % 256, (colour * 13) % 256)).save(path) + return path + + +def pair(left: Path, right: Path, colour: int): + return image(left, colour + 1), image(right, colour) + + +def test_split_keeps_every_clean_variant_together(tmp_path): + records = [] + for source in range(20): + for variant in range(10): + i, j = pair(tmp_path / "input" / f"{source}_{variant}.png", + tmp_path / "target" / f"{source}_{variant}.png", source) + records.append(record(i, j, "rain", "Rain", j.stem, i.stem)) + splits = split_training(records, 42, .1) + audited, invalid, _ = audit_files(splits, tmp_path / "cache.sqlite", 2, False) + isolated, excluded = isolate_splits(audited) + assert not invalid and not excluded + assert sum(map(len, isolated.values())) == 200 + assert len(isolated["val"]) == 20 + + +@pytest.fixture +def seven_roots(tmp_path, monkeypatch): + root = tmp_path / "data" + rain_train = [pair(tmp_path / "rain/input" / f"{i}.png", tmp_path / "rain/target" / f"{i}.png", i) + for i in range(8)] + rain_test = [pair(tmp_path / "rain/test/input.png", tmp_path / "rain/test/target.png", 9)] + monkeypatch.setattr("scripts.prepare_phase1_seven.load_rain13k_resized", lambda *a, **kw: + SimpleNamespace(train_pairs=rain_train, official_test_pairs={"Test100": rain_test}, + quarantined_train_pair_count=0)) + for split, count, offset in (("Train", 8, 20), ("Test", 2, 30)): + for i in range(count): + pair(root / "LOLv2/lolv2_hf" / split / "Input" / f"{i}.png", + root / "LOLv2/lolv2_hf" / split / "GT" / f"{i}.png", offset + i) + for i in range(10): + pair(root / "RESIDE/hazy" / f"{i}_0.8.png", root / "RESIDE/clear" / f"{i}.png", 40 + i) + scene = root / "SIDD/SIDD_Small_sRGB_Only/Data" / f"0001_{i:03d}_S6" + pair(scene / "NOISY_SRGB_010.PNG", scene / "GT_SRGB_010.PNG", 60 + i) + for split, count, offset in (("train", 8, 80), ("test", 2, 90)): + for i in range(count): + pair(root / "Snow100K" / split / "all/synthetic" / f"{i}.png", + root / "Snow100K" / split / "all/gt" / f"{i}.png", offset + i) + for split, count, offset in (("train", 4, 100), ("test", 2, 110)): + for i in range(count): + pair(tmp_path / "gopro" / split / f"scene{offset + i}/blur/1.png", + tmp_path / "gopro" / split / f"scene{offset + i}/sharp/1.png", offset + i) + for i in range(8): + image(tmp_path / "div2k/DIV2K_train_HR" / f"{i}.png", 120 + i) + image(tmp_path / "flickr2k/Flickr2K" / f"{i}.png", 140 + i) + for i in range(2): + image(tmp_path / "div2k/DIV2K_valid_HR" / f"{800 + i}.png", 160 + i) + return Namespace(data_root=root, rain13k_root=tmp_path / "rain", seed=42, val_fraction=.2, + quarantine_manifest=tmp_path / "quarantine.json", snow_test_root=None, + gopro_root=tmp_path / "gopro", div2k_root=tmp_path / "div2k", + flickr2k_root=tmp_path / "flickr2k") + + +def test_complete_seven_dataset_discovery(seven_roots, tmp_path): + splits, audit = discover(seven_roots) + audited, invalid, _ = audit_files(splits, tmp_path / "cache.sqlite", 2, False) + kept, excluded = isolate_splits(audited) + assert not invalid and not excluded + counts = validate_manifest({"schema_version": 1, "types": TYPES, **kept}, require_all_types=True) + assert all(counts["test"][kind] for kind in TYPES) + assert audit["availability"]["Snow100K"]["official_test_pairs"] == 2 + assert sum(map(len, kept.values())) == sum(map(len, splits.values())) + + +def test_direct_div2k_valid_root_never_enters_training(seven_roots): + seven_roots.div2k_root /= "DIV2K_valid_HR" + splits, _ = discover(seven_roots) + assert not any(r["dataset"] == "DIV2K" for r in splits["train"] + splits["val"]) + assert len([r for r in splits["test"] if r["dataset"] == "DIV2K"]) == 2 + + +def test_direct_lr_root_is_rejected(seven_roots, tmp_path): + seven_roots.div2k_root = tmp_path / "DIV2K_train_LR_bicubic" + image(seven_roots.div2k_root / "1.png", 190) + with pytest.raises(ValueError, match="LR variants"): + discover(seven_roots) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_extra_download.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_extra_download.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c093fd52f3415d4796292deb42e4193da734e8 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_extra_download.py @@ -0,0 +1,109 @@ +import io +from pathlib import Path +import tarfile +import zipfile + +import pytest + +from scripts.fetch_phase1_extra import extract_checked, safe_target, guarded_copy, monitored_download + + +def test_noise_assets_pin_source_and_distinguish_size_from_scene_count(): + from scripts.fetch_phase1_extra import ASSETS + + sidd = ASSETS["sidd_medium_srgb"] + assert sidd["archive_bytes_expected"] == 13_234_744_070 + assert sidd["expected_pairs"] == 320 + assert sidd["physical_scenes"] == 10 + assert sidd["url"] == "http://130.63.97.225/share/SIDD_Medium_Srgb.zip" + assert sidd["license"] == "MIT" + polyu = ASSETS["polyu_original"] + assert polyu["revision"] == "3af0f2646b267a00446fe4b7113a15e67bc80b4e" + assert polyu["url"].endswith(polyu["revision"]) + assert polyu["expected_original_pairs"] == 40 + assert polyu["use"] == "external_test_only_original_images" + + +@pytest.mark.parametrize("name", ["../escape", "/absolute", "a/../../escape", "a\\b"]) +def test_unsafe_archive_paths_rejected(tmp_path, name): + with pytest.raises(ValueError): + safe_target(tmp_path, name) + + +def test_zip_extracts_regular_members(tmp_path): + archive = tmp_path / "data.zip" + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr("dataset/image.txt", "example") + destination = tmp_path / "extracted" + result = extract_checked(archive, destination, 0) + assert (destination / "dataset/image.txt").read_text() == "example" + assert result == {"extracted_files": 1, "expanded_bytes": 7} + + +def test_tar_rejects_links_before_extracting(tmp_path): + archive = tmp_path / "data.tar.gz" + with tarfile.open(archive, "w:gz") as handle: + regular = tarfile.TarInfo("ordinary") + regular.size = 3 + handle.addfile(regular, io.BytesIO(b"abc")) + link = tarfile.TarInfo("link") + link.type = tarfile.SYMTYPE + link.linkname = "../outside" + handle.addfile(link) + with pytest.raises(ValueError): + extract_checked(archive, tmp_path / "out", 0) + assert not (tmp_path / "out/ordinary").exists() + + +def test_preexisting_symlink_cannot_escape_destination(tmp_path): + destination = tmp_path / "out" + destination.mkdir() + outside = tmp_path / "elsewhere" + outside.mkdir() + (destination / "nested").symlink_to(outside, target_is_directory=True) + with pytest.raises(ValueError): + safe_target(destination, "nested/file") + + +def test_extract_stops_when_other_writers_consume_reserve(tmp_path, monkeypatch): + from types import SimpleNamespace + monkeypatch.setattr("scripts.fetch_phase1_extra.shutil.disk_usage", lambda _: SimpleNamespace(free=100)) + destination = io.BytesIO() + with pytest.raises(RuntimeError, match="Stopping extraction"): + guarded_copy(io.BytesIO(b"not written"), destination, tmp_path, 50) + assert destination.getvalue() == b"" + + +def test_archive_expansion_preflight_refuses_insufficient_space(tmp_path, monkeypatch): + from types import SimpleNamespace + archive = tmp_path / "data.zip" + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr("file", "content") + monkeypatch.setattr("scripts.fetch_phase1_extra.shutil.disk_usage", lambda _: SimpleNamespace(free=1)) + with pytest.raises(RuntimeError, match="Insufficient space"): + extract_checked(archive, tmp_path / "out", 10) + assert not (tmp_path / "out").exists() + + +def test_download_guard_terminates_only_its_child(tmp_path, monkeypatch): + from types import SimpleNamespace + + class Child: + stopped = False + returncode = None + + def poll(self): + return -15 if self.stopped else None + + def terminate(self): + self.stopped = True + + def wait(self, timeout=None): + return -15 + + child = Child() + monkeypatch.setattr("scripts.fetch_phase1_extra.subprocess.Popen", lambda command: child) + monkeypatch.setattr("scripts.fetch_phase1_extra.shutil.disk_usage", lambda _: SimpleNamespace(free=1)) + with pytest.raises(RuntimeError, match="Stopping own download"): + monitored_download(["own-downloader"], tmp_path, 100) + assert child.stopped diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_expansion.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_expansion.py new file mode 100644 index 0000000000000000000000000000000000000000..97356090bb96dc6dc9b36b8f65b2fd2cc673f917 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_expansion.py @@ -0,0 +1,285 @@ +"""Append-only noise expansion and replayable native-resolution synthesis.""" + +from copy import deepcopy +import json +import os + +import numpy as np +from PIL import Image +import pytest +import torch + +from scripts.expand_phase1_noise import ( + _audit_new_pairs, _decode_fresh_metadata, build_expansion, discover_polyu, + discover_sidd_medium, retain_new_candidates, write_manifest_exclusive, +) +from scripts.prepare_phase1_seven import _decode_metadata +from src.data.clean_relative import TYPES, PairedDegradationDataset, validate_manifest + + +def image(path, value): + path.parent.mkdir(parents=True, exist_ok=True) + Image.fromarray(np.full((20, 24, 3), value, dtype=np.uint8)).save(path) + return str(path) + + +def record(tmp_path, name, *, kind="jpeg", dataset="DIV2K", group=None, value=80): + clean = image(tmp_path / (name + "_clean.png"), value) + degraded = clean if kind == "jpeg" else image(tmp_path / (name + "_noisy.png"), value + 10) + row = {"id": name, "clean": clean, "degraded": degraded, "type": kind, + "dataset": dataset, "group": group or name, "source": name, + "clean_content_sha256": _decode_fresh_metadata(clean)["rgb_sha256"], + "degraded_content_sha256": _decode_fresh_metadata(degraded)["rgb_sha256"]} + if kind == "jpeg": + row["synthesis"] = "jpeg" + return row + + +def manifest(tmp_path): + return {"schema_version": 1, "types": list(TYPES), "audit": {"legacy": True}, + "train": [record(tmp_path, "tr", value=80)], + "val": [record(tmp_path, "va", value=100)], + "test": [record(tmp_path, "te", value=120)]} + + +def test_all_base_records_unchanged_and_clean_sources_keep_split(tmp_path): + base = manifest(tmp_path) + before = deepcopy(base) + result = build_expansion(base, seed=41) + assert base == before + assert base["schema_version"] == 1 + assert result["schema_version"] == 2 + assert result["noise_expansion"]["manifest_schema_version"] == 2 + for split in ("train", "val", "test"): + assert result[split][:len(base[split])] == base[split] + generated = result[split][len(base[split]):] + assert len(generated) == 6 + assert {r["clean"] for r in generated} == {base[split][0]["clean"]} + assert {r["dataset"] for r in generated} == {"DIV2K"} + assert {r["noise_parameters"]["severity"] for r in generated} == {.2, .4, .6} + assert {r["noise_profile"] for r in generated} == {"gaussian", "signal_dependent_gaussian"} + validate_manifest(result) + assert result["noise_expansion"]["summary"]["train"]["synthetic_noise_records"] == 6 + assert result["noise_expansion"]["summary"]["train"]["synthetic_noise_clean_images"] == 1 + + +def test_frozen_v1_schema_contract_rejects_explicit_noise_manifest(tmp_path): + expanded = build_expansion(manifest(tmp_path)) + # Exact schema gate from frozen efdaf6e/src/data/clean_relative.py. The old + # loader must fail here before it can mistake synthesis=noise for a real + # pair with degraded=clean. Keep this fixture independent of Git/server. + def frozen_v1_schema_gate(payload): + if payload.get("schema_version") != 1 or tuple(payload.get("types", ())) != TYPES: + raise ValueError("Manifest schema_version=1 and canonical seven-type order are required") + + frozen_v1_schema_gate(manifest(tmp_path)) + with pytest.raises(ValueError, match="schema_version=1"): + frozen_v1_schema_gate(expanded) + assert len(PairedDegradationDataset(manifest(tmp_path), crop_size=16)) == 1 + upgraded = PairedDegradationDataset(expanded, crop_size=16) + assert len(upgraded) == 7 + assert not torch.equal(upgraded[1]["clean"], upgraded[1]["degraded"]) + + +def test_explicit_noise_cannot_be_downgraded_to_schema_one(tmp_path): + expanded = build_expansion(manifest(tmp_path)) + expanded["schema_version"] = 1 + with pytest.raises(ValueError, match="noise.*schema_version=2"): + validate_manifest(expanded) + + +def test_noise_loader_is_native_deterministic_and_masks_only_synthetic(tmp_path): + expanded = build_expansion(manifest(tmp_path), seed=41) + train = PairedDegradationDataset(expanded, "train", crop_size=16) + first = train[1] + assert first["clean"].shape == (3, 16, 16) + assert torch.equal(first["clean"], torch.full((3, 16, 16), 80 / 255.)) + assert torch.equal(first["degraded"], train[1]["degraded"]) + train.set_epoch(1) + assert not torch.equal(first["degraded"], train[1]["degraded"]) + assert first["severity_mask"].sum() == 1 + assert first["severity"][1] == .2 + val = PairedDegradationDataset(expanded, "val", crop_size=16) + fixed = val[1]["degraded"] + val.set_epoch(22) + assert torch.equal(fixed, val[1]["degraded"]) + real = record(tmp_path, "real", kind="noise", dataset="SIDD", value=20) + real_manifest = {"schema_version": 1, "types": list(TYPES), "train": [real], "val": [], "test": []} + assert not PairedDegradationDataset(real_manifest, crop_size=16)[0]["severity_mask"].any() + + +def test_native_center_crop_and_noise_seed_replay_ignore_eval_loader_seed(tmp_path): + base = manifest(tmp_path) + source = base["test"][0] + array = np.arange(20 * 24 * 3, dtype=np.uint16).reshape(20, 24, 3).astype(np.uint8) + Image.fromarray(array).save(source["clean"]) + source["clean_content_sha256"] = _decode_fresh_metadata(source["clean"])["rgb_sha256"] + source["degraded_content_sha256"] = source["clean_content_sha256"] + expanded = build_expansion(base) + first = PairedDegradationDataset(expanded, "test", crop_size=16, seed=1)[1] + second = PairedDegradationDataset(expanded, "test", crop_size=16, seed=999)[1] + expected = torch.from_numpy(array[2:18, 4:20].copy()).permute(2, 0, 1).float() / 255. + assert torch.equal(first["clean"], expected) + assert torch.equal(first["degraded"], second["degraded"]) + + +def test_expansion_rejects_changed_base_clean_pixels(tmp_path): + base = manifest(tmp_path) + image(tmp_path / "tr_clean.png", 91) + with pytest.raises(ValueError, match="audited pixels"): + build_expansion(base) + + +def test_expansion_rehashes_after_same_size_and_mtime_change(tmp_path): + base = manifest(tmp_path) + path = tmp_path / "tr_clean.png" + Image.fromarray(np.full((20, 24, 3), 80, dtype=np.uint8)).save(path, compress_level=0) + before = _decode_metadata(str(path)) + base["train"][0]["clean_content_sha256"] = before["rgb_sha256"] + base["train"][0]["degraded_content_sha256"] = before["rgb_sha256"] + old_stat = path.stat() + Image.fromarray(np.full((20, 24, 3), 91, dtype=np.uint8)).save(path, compress_level=0) + os.utime(path, ns=(old_stat.st_atime_ns, old_stat.st_mtime_ns)) + assert path.stat().st_size == old_stat.st_size + assert path.stat().st_mtime_ns == old_stat.st_mtime_ns + # Reproduce the frozen helper's stat-keyed LRU collision deterministically. + assert _decode_metadata(str(path)) == before + with pytest.raises(ValueError, match="audited pixels"): + build_expansion(base) + + +def test_new_real_pair_audit_also_bypasses_stale_stat_cache(tmp_path): + row = record(tmp_path, "real", kind="noise", dataset="SIDD") + path = tmp_path / "real_clean.png" + Image.fromarray(np.full((20, 24, 3), 80, dtype=np.uint8)).save(path, compress_level=0) + cached = _decode_metadata(str(path)) + old_stat = path.stat() + Image.fromarray(np.full((20, 24, 3), 91, dtype=np.uint8)).save(path, compress_level=0) + os.utime(path, ns=(old_stat.st_atime_ns, old_stat.st_mtime_ns)) + assert path.stat().st_size == old_stat.st_size + assert _decode_metadata(str(path)) == cached + audited, invalid, _ = _audit_new_pairs({"train": [row], "val": [], "test": []}, False) + assert not invalid + assert audited["train"][0]["clean_content_sha256"] != cached["rgb_sha256"] + assert audited["train"][0]["clean_content_sha256"] == _decode_fresh_metadata(str(path))["rgb_sha256"] + + +@pytest.mark.parametrize("key,value", [("sigma", float("nan")), ("shot", -1), + ("severity", 2), ("noise_seed", -1), + ("unrecognized", .2)]) +def test_noise_loader_rejects_invalid_parameters(tmp_path, key, value): + expanded = build_expansion(manifest(tmp_path)) + expanded["train"][1]["noise_parameters"][key] = value + with pytest.raises(ValueError, match="noise|Noise"): + PairedDegradationDataset(expanded) + + +def test_unknown_synthesis_and_profile_fail_closed(tmp_path): + expanded = build_expansion(manifest(tmp_path)) + expanded["train"][1]["synthesis"] = "typo" + with pytest.raises(ValueError, match="synthesis"): + validate_manifest(expanded) + expanded = build_expansion(manifest(tmp_path)) + expanded["train"][1]["noise_profile"] = "poisson" + with pytest.raises(ValueError, match="profile"): + validate_manifest(expanded) + + +def sidd_pair(root, instance="0001_001_S6_00100_00060_3200_L", capture="010", value=45): + folder = root / "Data" / instance + prefix = instance.split("_")[0] + image(folder / f"{prefix}_NOISY_SRGB_{capture}.PNG", value + 10) + image(folder / f"{prefix}_GT_SRGB_{capture}.PNG", value) + + +def test_sidd_pairs_capture_ids_not_first_file_and_preserves_scene_holdouts(tmp_path): + root = tmp_path / "medium" + sidd_pair(root, capture="010") + sidd_pair(root, capture="011", value=55) + sidd_pair(root, "0002_006_GP_00100_00060_3200_L", value=65) + sidd_pair(root, "0003_008_GP_00100_00060_3200_L", value=75) + rows = discover_sidd_medium(root, {}, expected_pairs=4) + assert len(rows["train"]) == 2 + assert rows["val"][0]["group"] == "006" + assert rows["test"][0]["group"] == "008" + assert {r["capture_id"] for r in rows["train"]} == {"010", "011"} + (root / "Data" / "0001_001_S6_00100_00060_3200_L" / "0001_GT_SRGB_011.PNG").unlink() + with pytest.raises(ValueError, match="unmatched"): + discover_sidd_medium(root, {}, expected_pairs=4) + + +def test_duplicate_real_pair_and_transitive_new_bridge_never_drop_base(tmp_path): + base = manifest(tmp_path) + duplicate = deepcopy(base["train"][0]) + duplicate.update(id="duplicate", synthesis=None) + base["train"][0].pop("synthesis") + base["train"][0]["type"] = duplicate["type"] = "noise" + duplicate.pop("synthesis") + candidates = {"train": [duplicate], "val": [], "test": []} + kept, excluded = retain_new_candidates(base, candidates) + assert not kept["train"] + assert excluded[0]["reason"] == "decoded_pair_duplicate" + bridge1 = record(tmp_path, "bridge1", kind="noise", dataset="SIDD", group="001", value=80) + bridge2 = record(tmp_path, "bridge2", kind="noise", dataset="SIDD", group="001", value=120) + kept, excluded = retain_new_candidates(base, {"train": [bridge1, bridge2], "val": [], "test": []}) + assert not any(kept.values()) + assert len(excluded) == 2 + assert all(r["reason"] == "new_component_bridges_protected_base_splits" for r in excluded) + + +def test_new_content_conflict_cannot_leak_sidd_scene_into_base_test(tmp_path): + base = manifest(tmp_path) + base["test"][0].update(dataset="SIDD", group="008") + candidate = record(tmp_path, "shot", kind="noise", dataset="SIDD", group="008", value=77) + kept, excluded = retain_new_candidates(base, {"train": [candidate], "val": [], "test": []}) + assert not kept["train"] and len(excluded) == 1 + assert excluded[0]["protected_split"] == "test" + + +def test_new_only_component_prefers_test_without_reassigning_records(tmp_path): + base = manifest(tmp_path) + one = record(tmp_path, "new_train", kind="noise", dataset="extra", group="shared", value=15) + two = record(tmp_path, "new_test", kind="noise", dataset="extra", group="shared", value=16) + kept, excluded = retain_new_candidates(base, {"train": [one], "val": [], "test": [two]}) + assert kept["test"] == [two] and not kept["train"] + assert excluded[0]["id"] == one["id"] and excluded[0]["protected_split"] == "test" + + +def test_polyu_original_test_only_ignores_crops_and_rejects_missing_pair(tmp_path): + root = tmp_path / "polyu" + image(root / "OriginalImages" / "Canon5D2_bag_Real.JPG", 70) + image(root / "OriginalImages" / "Canon5D2_bag_mean.JPG", 50) + image(root / "CroppedImages" / "ignored_Real.JPG", 60) + rows = discover_polyu(root, expected_pairs=1) + assert len(rows["test"]) == 1 and not rows["train"] and not rows["val"] + assert rows["test"][0]["group"] == "Canon5D2_bag" + assert rows["test"][0]["license"] == "PolyU non-commercial research license" + (root / "OriginalImages" / "Canon5D2_bag_mean.JPG").unlink() + with pytest.raises(ValueError, match="unmatched"): + discover_polyu(root, expected_pairs=1) + + +def test_invalid_new_source_requires_explicit_quarantine_and_coverage(tmp_path): + root = tmp_path / "medium" + sidd_pair(root) + clean = root / "Data" / "0001_001_S6_00100_00060_3200_L" / "0001_GT_SRGB_010.PNG" + clean.write_bytes(b"invalid image") + base = manifest(tmp_path) + with pytest.raises(ValueError, match="Invalid new noise pair"): + build_expansion(base, sidd_medium_root=root, expected_sidd_pairs=1) + expanded = build_expansion(base, sidd_medium_root=root, expected_sidd_pairs=1, quarantine_invalid=True) + audit = expanded["noise_expansion"] + assert audit["new_real_discovered_pairs"] == 1 and audit["new_real_admitted_pairs"] == 0 + assert audit["quarantine"][0]["reason"] == "invalid_new_pair" + assert expanded["train"][0] == base["train"][0] + + +def test_atomic_manifest_refuses_overwrite(tmp_path): + output = tmp_path / "v2.json" + payload = manifest(tmp_path) + write_manifest_exclusive(output, payload) + original = output.read_bytes() + with pytest.raises(FileExistsError): + write_manifest_exclusive(output, {"different": True}) + assert output.read_bytes() == original + assert json.loads(original) == payload diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_sampling.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_sampling.py new file mode 100644 index 0000000000000000000000000000000000000000..829f40c04ef344e741c5b118c56eb041d3df398c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_sampling.py @@ -0,0 +1,188 @@ +"""Sampling-only noise balance, replayable visits and honest draw coverage.""" + +from collections import Counter +import hashlib +import json + +import numpy as np +from PIL import Image +import pytest +import torch + +from src.data.clean_relative import PairedDegradationDataset, TYPES +from src.data.noise_sampling import NoiseSamplingPlan +import train_phase1_clean_relative as train + + +def records(nonnoise=7, real=2, synthetic=8): + result = [] + for index in range(nonnoise + real + synthetic): + kind = "rain" if index < nonnoise else "noise" + row = {"id": str(index), "type": kind, "dataset": "SIDD" if index < nonnoise + real else "DIV2K", + "group": str(index), "clean_content_sha256": str(index)} + if index >= nonnoise + real: + row.update(synthesis="noise", noise_source="DF2K_explicit_synthetic", noise_profile="gaussian") + result.append(row) + return result + + +def bare_index(item): + return item[0] if isinstance(item, tuple) else item + + +def test_uniform_sampling_exactly_preserves_previous_epoch_schedule(): + rows = records() + selected = [2, 5, 1, 9, 12] + plan = NoiseSamplingPlan(rows, selected, seed=42, mode="uniform") + for epoch in range(3): + expected = [selected[i] for i in train.epoch_indices(len(selected), 42, epoch)] + assert plan.round_indices(epoch) == expected + assert plan.round_indices(epoch, start=2) == expected[2:] + + +def test_balanced_changes_only_noise_ids_and_visits_every_record_by_round_two(): + rows = records(nonnoise=70003, real=242, synthetic=19668) + selected = list(range(len(rows))) + uniform = NoiseSamplingPlan(rows, selected, seed=42, mode="uniform") + balanced = NoiseSamplingPlan(rows, selected, seed=42, mode="balanced") + for epoch in range(2): + first, second = uniform.round_indices(epoch), balanced.round_indices(epoch) + assert len(first) == len(second) == 89913 + exposures = Counter() + for original, replacement in zip(first, second): + if rows[original]["type"] != "noise": + assert original == replacement + else: + assert isinstance(replacement, tuple) + assert rows[replacement[0]]["type"] == "noise" + exposures["synthetic" if rows[replacement[0]].get("synthesis") else "real"] += 1 + assert exposures == {"real": 9955, "synthetic": 9955} + audit = balanced.coverage(1, 89913) + assert audit["round"]["draws"] == 89913 + assert balanced.coverage(0, 89913)["round"]["unique_records"] == 80200 + assert audit["round"]["unique_records"] == len({bare_index(item) for item in balanced.round_indices(1)}) + assert not audit["round"]["all_selected_records_visited"] + assert audit["cumulative"]["unique_records"] == 89913 + assert audit["cumulative"]["all_selected_records_visited"] + assert audit["cumulative"]["noise"]["real_unique_records"] == 242 + assert audit["cumulative"]["noise"]["synthetic_unique_records"] == 19668 + + +def test_balanced_resume_cursor_and_odd_quotas_are_deterministic(): + rows = records(nonnoise=4, real=2, synthetic=7) + plan = NoiseSamplingPlan(rows, list(range(len(rows))), seed=33, mode="balanced") + assert plan.round_indices(1, 5) == plan.round_indices(1)[5:] + assert plan.round_indices(1) == NoiseSamplingPlan(rows, list(range(len(rows))), 33, "balanced").round_indices(1) + one, two = plan.coverage(0, len(rows)), plan.coverage(1, len(rows)) + assert one["round"]["noise"]["real_draws"] == 5 + assert one["round"]["noise"]["synthetic_draws"] == 4 + assert two["round"]["noise"]["real_draws"] == 4 + assert two["round"]["noise"]["synthetic_draws"] == 5 + partial = plan.coverage(1, 5) + assert partial["cumulative"]["draws"] == len(rows) + 5 + assert partial["round"]["draws"] == 5 + + +def test_balance_rejects_caps_missing_groups_and_bad_mode(): + rows = records() + with pytest.raises(ValueError, match="all.*record|cap"): + NoiseSamplingPlan(rows, list(range(len(rows) - 1)), 42, "balanced") + with pytest.raises(ValueError, match="real.*synthetic"): + NoiseSamplingPlan(records(synthetic=0), list(range(9)), 42, "balanced") + with pytest.raises(ValueError, match="mode"): + NoiseSamplingPlan(rows, list(range(len(rows))), 42, "typo") + + +def test_sampling_does_not_consume_model_rng_and_default_is_uniform(): + rows = records() + plan = NoiseSamplingPlan(rows, list(range(len(rows))), 42, "balanced") + before = torch.get_rng_state().clone() + plan.round_indices(2) + plan.coverage(2, 3) + assert torch.equal(before, torch.get_rng_state()) + args = train.build_parser().parse_args(["--manifest", "m.json", "--output-dir", "run"]) + assert args.noise_sampling == "uniform" + for cursor in (-1, len(rows) + 1): + with pytest.raises(ValueError, match="cursor"): + plan.round_indices(0, cursor) + with pytest.raises(ValueError, match="cursor"): + plan.coverage(0, cursor) + + +def noise_manifest(tmp_path, train_nonnoise=6, train_real=2, train_synthetic=8): + manifest = {"schema_version": 2, "types": list(TYPES)} + for split_id, split in enumerate(("train", "val", "test")): + split_rows = records(train_nonnoise, train_real, train_synthetic) if split == "train" else records(1, 1, 1) + for index, row in enumerate(split_rows): + array = np.random.default_rng(100 * split_id + index).integers(20, 220, (48, 52, 3), dtype=np.uint8) + clean = tmp_path / f"{split}_{index}_clean.png" + noisy = tmp_path / f"{split}_{index}_noisy.png" + Image.fromarray(array).save(clean) + Image.fromarray(np.clip(array.astype(int) + 5, 0, 255).astype(np.uint8)).save(noisy) + row.update(id=f"{split}_{index}", group=f"{split}_{index}", clean_content_sha256=f"{split}_{index}", + clean=str(clean), degraded=str(clean) if row.get("synthesis") else str(noisy)) + if row.get("synthesis"): + row.update(noise_synthesis_version=1, + noise_parameters={"severity": .4, "sigma": .048, "shot": 0., "noise_seed": index}) + manifest[split] = split_rows + parent = {"schema_version": 1, "types": list(TYPES), + **{split: [row for row in manifest[split] if not row.get("synthesis")] + for split in ("train", "val", "test")}} + parent_path = tmp_path / "parent_v1.json" + raw = json.dumps(parent).encode() + parent_path.write_bytes(raw) + manifest["noise_expansion"] = {"version": 1, "base_records_preserved": True, + "base_split_assignments_preserved": True, + "base_manifest": {"path": str(parent_path.resolve()), + "sha256": hashlib.sha256(raw).hexdigest()}} + return manifest + + +def test_visit_zero_preserves_old_view_and_repeats_get_distinct_native_views(tmp_path): + manifest = noise_manifest(tmp_path) + dataset = PairedDegradationDataset(manifest, crop_size=32) + dataset.set_epoch(3) + ordinary, zero = dataset[6], dataset[(6, 0)] + assert all(torch.equal(ordinary[key], zero[key]) for key in ("clean", "degraded", "severity")) + assert ordinary["index"] == zero["index"] == 6 + repeated = [dataset[(6, visit)]["clean"] for visit in range(5)] + assert all(not torch.equal(repeated[i], repeated[j]) for i in range(5) for j in range(i)) + assert torch.equal(dataset[(6, 3)]["clean"], repeated[3]) + synthetic = [dataset[(8, visit)] for visit in (0, 1)] + assert synthetic[0]["severity"].equal(synthetic[1]["severity"]) + assert not synthetic[0]["degraded"].equal(synthetic[1]["degraded"]) + assert dataset[(8, 1)]["index"] == 8 + with pytest.raises(ValueError, match="visit"): + dataset[(6, -1)] + with pytest.raises(ValueError, match="visits.*training"): + PairedDegradationDataset(manifest, "val", crop_size=32)[(1, 1)] + + +def test_balanced_training_resume_matches_uninterrupted_and_reports_true_coverage(tmp_path): + path = tmp_path / "manifest.json" + path.write_text(json.dumps(noise_manifest(tmp_path))) + common = ["--manifest", str(path), "--epochs", "2", "--batch-size", "4", "--patch-size", "32", + "--num-workers", "0", "--threads", "1", "--synthetic-batch-size", "1", "--device", "cpu", + "--log-every", "1", "--noise-sampling", "balanced"] + interrupted, complete = tmp_path / "interrupted", tmp_path / "complete" + partial = train.main(common + ["--output-dir", str(interrupted), "--max-steps", "2"]) + assert partial["status"] == "smoke_step_cap" + assert not partial["sampling_coverage"]["cumulative"]["all_selected_records_visited"] + resumed = train.main(common + ["--output-dir", str(interrupted), "--resume", str(interrupted / "last.pt")]) + reference = train.main(common + ["--output-dir", str(complete)]) + assert resumed["sampling_coverage"] == reference["sampling_coverage"] + assert resumed["sampling_coverage"]["cumulative"]["all_selected_records_visited"] + first = torch.load(interrupted / "last.pt", weights_only=False) + second = torch.load(complete / "last.pt", weights_only=False) + assert all(torch.equal(value, second["model"][name]) for name, value in first["model"].items()) + rows = [json.loads(line) for line in (complete / "metrics.jsonl").read_text().splitlines()] + coverage = [r for r in rows if r["event"] == "epoch_coverage"] + assert [r["draws"] for r in coverage] == [16, 16] + assert coverage[0]["unique_records"] == 13 + assert coverage[1]["unique_records"] <= 13 + assert not coverage[0]["all_selected_records_visited"] + assert coverage[1]["cumulative"]["all_selected_records_visited"] + assert "src/data/noise_sampling.py" in first["run_config"]["provenance"]["source_sha256"] + with pytest.raises(ValueError, match="noise_sampling"): + train.main([arg if arg != "balanced" else "uniform" for arg in common] + + ["--output-dir", str(interrupted), "--resume", str(interrupted / "last.pt")]) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_strata.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_strata.py new file mode 100644 index 0000000000000000000000000000000000000000..64e8ec632a5f523bbd97a9fa11c914d6326f529c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_strata.py @@ -0,0 +1,221 @@ +"""Noise evaluation uses shared negatives and a verified immutable legacy cohort.""" + +from copy import deepcopy +import hashlib +import json + +import numpy as np +from PIL import Image +import pytest +import torch + +from eval_phase1_clean_relative import evaluate_real +from src.data.clean_relative import TYPES + + +class TinyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.examples = 0 + self.batch_sizes = [] + + def forward_pair(self, degraded, clean): + self.examples += len(clean) + self.batch_sizes.append(len(clean)) + + def state(image): + signal = image.mean((1, 2, 3)) + logits = image.new_zeros((len(image), 7)) + logits[:, 1] = signal * 8 - 2 + return {"content": image, "delta": signal[:, None].expand(-1, 8), + "presence_logits": logits, "severity": logits.sigmoid()} + + return {"student": state(degraded), "clean": state(clean)} + + def decode(self, content, delta, output_size): + return content + + +def _record(tmp_path, name, kind, dataset, value): + path = tmp_path / f"{name}.png" + array = np.full((32, 32, 3), value, dtype=np.uint8) + Image.fromarray(array).save(path) + return {"id": name, "type": kind, "dataset": dataset, "group": name, + "clean": str(path), "degraded": str(path), + "clean_content_sha256": hashlib.sha256(array.tobytes()).hexdigest()} + + +@pytest.fixture +def manifests(tmp_path): + base = {"schema_version": 1, "types": list(TYPES), "train": [], "val": [], + "test": [_record(tmp_path, "rain", "rain", "Rain", 200), + _record(tmp_path, "sidd_old", "noise", "SIDD", 120), + _record(tmp_path, "jpeg", "jpeg", "DIV2K", 30)]} + parent_path = tmp_path / "parent.json" + parent_path.write_text(json.dumps(base)) + expanded = deepcopy(base) + expanded["schema_version"] = 2 + expanded["test"].extend([ + _record(tmp_path, "sidd_new", "noise", "SIDD", 130), + _record(tmp_path, "polyu", "noise", "PolyU", 140), + ]) + for profile, shot in (("gaussian", 0.), ("signal_dependent_gaussian", .024)): + row = _record(tmp_path, profile, "noise", "DIV2K", 100) + row.update(synthesis="noise", noise_profile=profile, noise_synthesis_version=1, + noise_parameters={"severity": .2, "sigma": .024, + "shot": shot, "noise_seed": 10}) + expanded["test"].append(row) + expanded["noise_expansion"] = { + "version": 1, "base_records_preserved": True, "base_split_assignments_preserved": True, + "base_manifest": {"path": str(parent_path), + "sha256": hashlib.sha256(parent_path.read_bytes()).hexdigest()}, + } + path = tmp_path / "expanded.json" + path.write_text(json.dumps(expanded)) + return parent_path, path, expanded + + +def _eval(path, **kwargs): + model = TinyModel() + return model, evaluate_real(model, str(path), "test", "cpu", batch_size=2, + patch_size=32, workers=0, seed=20260906, **kwargs) + + +def test_source_cohorts_share_parent_negatives_and_do_not_pool_other_noise(manifests): + _, path, _ = manifests + model, report = _eval(path) + strata = report["noise_stratification"] + assert model.examples == 7 # One forward pass per admitted record, not per stratum. + assert model.batch_sizes == [2, 1, 2, 2] # Preserve the old final-batch boundary. + assert strata["shared_parent_nonnoise_pool"]["records_evaluated"] == 2 + assert strata["shared_parent_nonnoise_pool"]["argmax_noise_false_positives"] == 1 + cohorts = strata["cohorts"] + assert set(cohorts) == {"sidd_real", "polyu_real", "synthetic_gaussian", + "synthetic_signal_dependent_gaussian"} + sidd = cohorts["sidd_real"] + assert sidd["positive_records_evaluated"] == 2 + assert sidd["negative_records_evaluated"] == 2 + assert sidd["evaluated_noise_prevalence"] == .5 + assert sidd["argmax_noise"]["true_positives"] == 2 + assert sidd["argmax_noise"]["false_positives"] == 1 + assert sidd["argmax_noise"]["precision"] == pytest.approx(2 / 3) + assert sidd["argmax_noise"]["f1"] == pytest.approx(.8) + for name, cohort in cohorts.items(): + assert cohort["negative_records_evaluated"] == 2 + assert cohort["negative_pool_record_ids_sha256"] == strata["shared_parent_nonnoise_pool"]["record_ids_sha256"] + assert cohort["physical_severity"]["count"] == (0 if name.endswith("real") else 1) + assert strata["noise_record_counts"]["real_evaluated"] == 3 + assert strata["noise_record_counts"]["synthetic_evaluated"] == 2 + + +def test_legacy_view_matches_legacy_evaluation_and_schema1_output_is_unchanged(manifests): + parent, path, _ = manifests + _, old = _eval(parent) + _, expanded = _eval(path) + assert "noise_stratification" not in old + legacy = expanded["noise_stratification"]["fixed_legacy"] + assert legacy["classification"] == old["classification"] + assert legacy["scope"] == "all_parent_records" + assert legacy["records_total"] == legacy["records_evaluated"] == 3 + assert legacy["parent_manifest_sha256"] == hashlib.sha256(parent.read_bytes()).hexdigest() + + +def test_capped_evaluation_labels_partial_legacy_and_negative_coverage(manifests): + _, path, _ = manifests + _, report = _eval(path, max_records=2) + strata = report["noise_stratification"] + assert report["scope"] == strata["scope"] == "explicitly_capped" + assert strata["fixed_legacy"]["scope"] == "explicitly_capped" + assert strata["shared_parent_nonnoise_pool"]["scope"] == "explicitly_capped" + for cohort in strata["cohorts"].values(): + assert cohort["negative_records_evaluated"] <= 2 + assert cohort["scope"] == "explicitly_capped" + + +@pytest.mark.parametrize("mutation,match", [ + ("missing_receipt", "parent"), ("bad_hash", "hash"), + ("missing_path", "parent"), ("changed_prefix", "prefix"), + ("new_nonnoise", "non-noise"), ("unknown_real", "noise source"), + ("missing_expansion", "parent"), ("false_preservation", "preservation"), + ("null_receipt", "parent"), +]) +def test_stratification_fails_closed_before_inference(manifests, mutation, match): + _, path, expanded = manifests + if mutation == "missing_receipt": + del expanded["noise_expansion"]["base_manifest"] + elif mutation == "bad_hash": + expanded["noise_expansion"]["base_manifest"]["sha256"] = "0" * 64 + elif mutation == "missing_path": + expanded["noise_expansion"]["base_manifest"]["path"] += ".missing" + elif mutation == "changed_prefix": + expanded["test"][0]["group"] = "changed" + elif mutation == "new_nonnoise": + expanded["test"][3]["type"] = "rain" + elif mutation == "missing_expansion": + del expanded["noise_expansion"] + elif mutation == "false_preservation": + expanded["noise_expansion"]["base_records_preserved"] = False + elif mutation == "null_receipt": + expanded["noise_expansion"]["base_manifest"] = None + else: + expanded["test"][3]["dataset"] = "unrecognized_camera_source" + path.write_text(json.dumps(expanded)) + model = TinyModel() + with pytest.raises(ValueError, match=match): + evaluate_real(model, str(path), "test", "cpu", batch_size=2, patch_size=32) + assert model.examples == 0 + + +def test_functional_disabled_still_reports_source_classification(manifests): + _, path, _ = manifests + _, report = _eval(path, functional_enabled=False) + assert report["clean_origin_proxy"]["status"] == "unsupported_without_trained_proxy" + assert report["noise_stratification"]["cohorts"]["sidd_real"]["positive_records_evaluated"] == 2 + + +def test_worker_labels_are_copied_before_retention(manifests, monkeypatch): + import eval_phase1_clean_relative as evaluator + + parent, _, _ = manifests + original = evaluator._loader + retained = [] + + def loader(*args, **kwargs): + dataset, selected, source = original(*args, **kwargs) + + def reused_storage(): + for batch in source: + retained.append(batch["label"]) + yield batch + batch["label"].fill_(6) + + return dataset, selected, reused_storage() + + monkeypatch.setattr(evaluator, "_loader", loader) + _, report = _eval(parent) + assert report["classification"]["per_domain"]["rain"]["support"] == 1 + assert report["classification"]["per_domain"]["noise"]["support"] == 1 + assert all(bool((item == 6).all()) for item in retained) + + +def test_real_physical_targets_cannot_be_silently_invented(manifests, monkeypatch): + import eval_phase1_clean_relative as evaluator + + _, path, _ = manifests + original = evaluator._loader + + def loader(*args, **kwargs): + dataset, selected, source = original(*args, **kwargs) + + def changed_targets(): + for batch in source: + for index, dataset_name in enumerate(batch["dataset"]): + if dataset_name == "SIDD": + batch["severity_mask"][index, 1] = True + yield batch + + return dataset, selected, changed_targets() + + monkeypatch.setattr(evaluator, "_loader", loader) + with pytest.raises(ValueError, match="Real noise unexpectedly"): + _eval(path) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_suite.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..61cd619ca3fb2434e9257330dae89809b140b867 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_noise_suite.py @@ -0,0 +1,137 @@ +"""Noise trials retain a fixed budget and refuse ambiguous evaluation/resume.""" + +from copy import deepcopy +import fcntl +import json +from types import SimpleNamespace + +import pytest + +from scripts.run_phase1_seven_suite import ( + NOISE_RUNS, commands, evaluation_stages, suite_lock_path, validate_evaluation, + validate_noise_completion, validate_noise_parent, validate_predecessor, +) +from scripts.report_phase1_seven import write_report + + +def arguments(tmp_path): + return SimpleNamespace( + protocol="noise-v2", output_root=tmp_path, python="python", + manifest=tmp_path / "expanded.json", reference_manifest=tmp_path / "parent.json", + epochs=5, batch_size=16, synthetic_batch_size=4, patch_size=256, + workers=4, synthetic_scenes=256, + ) + + +def test_noise_commands_two_uncapped_matched_runs_and_fixed_reference(tmp_path): + args = arguments(tmp_path) + assert len(NOISE_RUNS) == 2 + for name, seed, flags in NOISE_RUNS: + assert seed == 42 + train, evaluations = commands(args, name, seed, flags) + assert "--max-steps" not in train and "--max-train-records" not in train + assert train[train.index("--epochs") + 1] == "5" + assert "--no-edges" not in train and "--prototype-only" not in train + assert len(evaluations) == 4 + for stage, command in zip(evaluation_stages(args, tmp_path / name), evaluations): + assert command[command.index("--checkpoint") + 1].endswith("last.pt") + assert command[command.index("--manifest") + 1] == str(stage["manifest"]) + assert ("--skip-controlled" in command) == (not stage["controlled"]) + assert "--max-records" not in command + assert [s["controlled"] for s in evaluation_stages(args, tmp_path / name)] == [True, True, False, False] + + +def test_parent_requires_hash_and_exact_base_records(tmp_path): + from train_phase1_clean_relative import file_digest + parent = {"schema_version": 1, "train": [{"id": "a"}], "val": [], "test": []} + path = tmp_path / "parent.json" + path.write_text(json.dumps(parent)) + expanded = {**deepcopy(parent), "schema_version": 2, + "noise_expansion": {"base_manifest": {"sha256": file_digest(path)}}} + assert validate_noise_parent(expanded, path) == parent + expanded["train"][0]["id"] = "changed" + with pytest.raises(ValueError, match="parent|prefix"): + validate_noise_parent(expanded, path) + + +def test_predecessor_must_finish_all_runs_on_same_gpu(tmp_path): + from scripts.run_phase1_seven_suite import RUNS + state = {"status": "running", "completed_runs": [r[0] for r in RUNS], "child_pid": None, + "gpu_uuid": "GPU-8169d457412f2f76", "expected_pci_bus": 171} + (tmp_path / "suite_config.json").write_text(json.dumps({"manifest_sha256": "parent"})) + path = tmp_path / "suite_status.json" + path.write_text(json.dumps(state)) + with pytest.raises(ValueError, match="predecessor|Predecessor"): + validate_predecessor(tmp_path, "parent", "GPU-8169d457412f2f76", 171) + state["status"] = "completed" + path.write_text(json.dumps(state)) + validate_predecessor(tmp_path, "parent", "GPU-8169d457412f2f76", 171) + state["child_pid"] = 123 + path.write_text(json.dumps(state)) + with pytest.raises(ValueError, match="predecessor|Predecessor"): + validate_predecessor(tmp_path, "parent", "GPU-8169d457412f2f76", 171) + + +def test_different_output_parent_still_shares_predecessor_gpu_lock(tmp_path): + old_parent = tmp_path / "home_outputs" + old_parent.mkdir() + args = SimpleNamespace(protocol="noise-v2", predecessor_suite=old_parent / "old_suite", + output_root=tmp_path / "other_volume" / "noise_suite", + gpu_uuid="GPU-8169d457412f2f76") + lock_path = suite_lock_path(args) + assert lock_path.parent == old_parent + with lock_path.open("a") as old_lock, lock_path.open("a") as new_lock: + fcntl.flock(old_lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + with pytest.raises(BlockingIOError): + fcntl.flock(new_lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + + +def test_expanded_evaluation_must_skip_controls_explicitly(): + report = {"manifest_sha256": "expanded", "checkpoint_sha256": "last", "training_scope": "full_manifest", + "real": {"scope": "all_records", "split": "test", "records_total": 3, "records_evaluated": 3}, + "controlled": {"status": "explicitly_skipped"}, + "arguments": {"split": "test", "patch_size": 256, "seed": 20260906, + "synthetic_scenes": 256, "max_records": None, "skip_controlled": True, "no_edges": False}} + validate_evaluation(report, {"test": [1, 2, 3]}, "expanded", "last", "test", + SimpleNamespace(patch_size=256, synthetic_scenes=256), controlled=False) + report["arguments"]["skip_controlled"] = False + with pytest.raises(ValueError, match="Stale"): + validate_evaluation(report, {"test": [1, 2, 3]}, "expanded", "last", "test", + SimpleNamespace(patch_size=256, synthetic_scenes=256), controlled=False) + + +def test_noise_completion_rejects_missing_coverage_and_skipped_steps(): + final = {"status": "completed", "epoch": 5, "cursor": 0, "global_step": 28100, + "optimizer_steps": 28100, "skipped_steps": 0, + "sampling_coverage": {"cumulative_unique_records": 89913, "all_selected_covered": True}} + validate_noise_completion(final, 89913, 5, 16) + final["skipped_steps"] = 1 + with pytest.raises(ValueError, match="budget|coverage"): + validate_noise_completion(final, 89913, 5, 16) + final["skipped_steps"] = 0 + final["sampling_coverage"]["all_selected_covered"] = False + with pytest.raises(ValueError, match="budget|coverage"): + validate_noise_completion(final, 89913, 5, 16) + + +def test_noise_report_never_claims_unvalidated_results(tmp_path): + config = {"settings": {"protocol": "noise-v2", "epochs": 5, "batch_size": 16}, + "commands": {name: [] for name, _, _ in NOISE_RUNS}, "source_digest": "source", + "manifest_sha256": "expanded", "reference_manifest_sha256": "parent"} + (tmp_path / "suite_config.json").write_text(json.dumps(config)) + (tmp_path / "suite_status.json").write_text(json.dumps({"status": "running", "completed_runs": []})) + summary = write_report(tmp_path) + assert summary["measured_runs"] == [] + assert summary["primary_checkpoint"] == "last.pt" + assert "chưa có kết quả" in (tmp_path / "evaluation_report.md").read_text() + + +def test_noise_report_renders_configured_budget(tmp_path): + config = {"settings": {"protocol": "noise-v2", "epochs": 2, "batch_size": 8}, + "commands": {}, "source_digest": "source", "counts": {"train": {"noise": 20, "rain": 4}}, + "manifest_sha256": "expanded", "reference_manifest_sha256": "parent", "matched_steps_per_run": 6} + (tmp_path / "suite_config.json").write_text(json.dumps(config)) + write_report(tmp_path) + report = (tmp_path / "evaluation_report.md").read_text() + assert "2 vòng, 24 record gốc/vòng và 6 bước" in report + assert "28.100" not in report diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_suite.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_suite.py new file mode 100644 index 0000000000000000000000000000000000000000..b7161f082c47577a89a83f66b832e28ed69686f5 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_suite.py @@ -0,0 +1,103 @@ +import copy +import json +import os +from types import SimpleNamespace +import sys + +import pytest + +from scripts.run_phase1_seven_suite import commands, run_owned_command, validate_evaluation +from scripts.report_phase1_seven import write_report + + +def test_suite_commands_are_uncapped_and_native(tmp_path): + args = SimpleNamespace(output_root=tmp_path, python=sys.executable, manifest=tmp_path / "manifest.json", + epochs=5, batch_size=16, synthetic_batch_size=4, patch_size=256, workers=4, + synthetic_scenes=256) + train, evaluations = commands(args, "full_seed42", 42, ()) + assert "--max-train-records" not in train and "--max-steps" not in train + assert train[train.index("--patch-size") + 1] == "256" + assert all("--max-records" not in item and "--skip-controlled" not in item for item in evaluations) + + +def valid_report(): + return {"manifest_sha256": "manifest", "checkpoint_sha256": "checkpoint", "training_scope": "full_manifest", + "real": {"scope": "all_records", "split": "test", "records_total": 3, "records_evaluated": 3}, + "controlled": {"status": "measured", "source_split": "test", "requested_scenes": 256}, + "arguments": {"split": "test", "patch_size": 256, "seed": 20260906, "synthetic_scenes": 256, + "max_records": None, "skip_controlled": False, "no_edges": False}} + + +def test_correct_evaluation_provenance_is_accepted(): + validate_evaluation(valid_report(), {"test": [1, 2, 3]}, "manifest", "checkpoint", "test", + SimpleNamespace(patch_size=256, synthetic_scenes=256)) + + +@pytest.mark.parametrize("change", ["checkpoint", "manifest", "skip", "cap", "seed"]) +def test_stale_or_partial_evaluation_is_rejected(change): + report = copy.deepcopy(valid_report()) + if change in ("checkpoint", "manifest"): + report[change + "_sha256"] = "wrong" + elif change == "skip": + report["controlled"]["status"] = "explicitly_skipped" + elif change == "cap": + report["real"]["records_evaluated"] = 2 + else: + report["arguments"]["seed"] = 42 + with pytest.raises(ValueError, match="Stale"): + validate_evaluation(report, {"test": [1, 2, 3]}, "manifest", "checkpoint", "test", + SimpleNamespace(patch_size=256, synthetic_scenes=256)) + + +def test_interrupted_stage_cleans_up_its_real_child(tmp_path): + children = [] + + def interrupt(child): + children.append(child) + raise KeyboardInterrupt() + + with (tmp_path / "lock").open("a") as lock, (tmp_path / "log").open("w") as log: + with pytest.raises(KeyboardInterrupt): + run_owned_command([sys.executable, "-c", "import time; time.sleep(30)"], + os.environ.copy(), log, lock.fileno(), interrupt) + assert len(children) == 1 + assert children[0].poll() is not None + + +def test_report_does_not_invent_missing_results(tmp_path): + (tmp_path / "suite_config.json").write_text(json.dumps({"commands": {"full_seed42": []}, + "source_digest": "source", "manifest_sha256": "manifest"})) + summary = write_report(tmp_path) + assert summary["measured_runs"] == [] + assert summary["macro_f1_seed_mean"] is None + assert "chưa có kết quả" in (tmp_path / "evaluation_report.md").read_text() + + +def test_report_does_not_count_existing_unvalidated_results(tmp_path): + (tmp_path / "suite_config.json").write_text(json.dumps({"commands": {"full_seed42": []}, + "source_digest": "source", "manifest_sha256": "manifest"})) + (tmp_path / "suite_status.json").write_text(json.dumps({"status": "running", "completed_runs": []})) + run = tmp_path / "full_seed42" + run.mkdir() + (run / "evaluation_test_best.json").write_text(json.dumps(valid_report())) + summary = write_report(tmp_path) + assert summary["measured_runs"] == [] + assert summary["macro_f1_seed_mean"] is None + assert "chưa được queue xác minh" in (tmp_path / "evaluation_report.md").read_text() + + +def test_report_counts_only_validated_complete_test_metrics(tmp_path): + (tmp_path / "suite_config.json").write_text(json.dumps({"commands": {"full_seed42": []}, + "source_digest": "source", "manifest_sha256": "manifest"})) + (tmp_path / "suite_status.json").write_text(json.dumps({"status": "running", "completed_runs": ["full_seed42"]})) + run = tmp_path / "full_seed42" + run.mkdir() + report = valid_report() + report["real"].update({"classification": {"macro_f1": .4, "per_domain": {}}, + "clean": {"any_false_positive_rate_at_0_5": .2}}) + (run / "evaluation_test_best.json").write_text(json.dumps(report)) + assert write_report(tmp_path)["macro_f1_seed_mean"] == .4 + report["manifest_sha256"] = "wrong" + (run / "evaluation_test_best.json").write_text(json.dumps(report)) + with pytest.raises(ValueError, match="provenance"): + write_report(tmp_path) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v2_data.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v2_data.py new file mode 100644 index 0000000000000000000000000000000000000000..082485b537ac7e05f7acb1e12a6b41f547e6eeec --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v2_data.py @@ -0,0 +1,370 @@ +"""Focused invariants for the corrected Phase 1 pilot data layer.""" + +import hashlib +import json +from collections import Counter, defaultdict +from pathlib import Path + +import numpy as np +import pytest +import torch +from PIL import Image + +from src.data.phase1_v2 import ( + PHYSICAL_ORDER, + SEVERITY_RANGES, + TRAIN_COMBINATIONS, + UNSEEN_COMBINATIONS, + ControlledDegradationDataset, + CropRecord, + SampleSpec, + apply_composition, + apply_single, + build_crop_manifest, + build_locked_crop_manifest, + build_sample_specs, + load_clean_patch, + normalize_severity, +) + + +@pytest.fixture +def div2k_smoke_root(tmp_path): + train_dir = tmp_path / "DIV2K_train_HR" + valid_dir = tmp_path / "DIV2K_valid_HR" + train_dir.mkdir() + valid_dir.mkdir() + + yy, xx = np.indices((264, 268)) + for number in range(6): + image = np.stack( + ( + (xx + number * 17) % 256, + (yy * 3 + number * 11) % 256, + ((xx // 4 + yy // 4) * 31 + number) % 256, + ), + axis=-1, + ).astype(np.uint8) + Image.fromarray(image).save(train_dir / f"{number + 1:04d}.png") + + for number in range(2): + image = np.stack( + ( + (xx * 5 + number) % 256, + (yy * 7 + number) % 256, + (xx + yy + number * 23) % 256, + ), + axis=-1, + ).astype(np.uint8) + Image.fromarray(image).save(valid_dir / f"{801 + number:04d}.png") + return tmp_path + + +@pytest.fixture +def manifest(div2k_smoke_root): + return build_crop_manifest( + div2k_smoke_root, + train_cap=4, + val_cap=2, + test_cap=None, + ) + + +def test_source_first_sha_split_is_disjoint_and_deterministic(div2k_smoke_root): + first = build_crop_manifest( + div2k_smoke_root, + train_cap=4, + val_cap=2, + test_cap=None, + ) + second = build_crop_manifest( + div2k_smoke_root, + train_cap=4, + val_cap=2, + test_cap=None, + ) + assert first == second + + ordered = sorted( + [f"{number:04d}.png" for number in range(1, 7)], + key=lambda name: (hashlib.sha256(name.encode()).digest(), name), + ) + sources = { + split: {record.source_id for record in first if record.split == split} + for split in ("train", "val", "test") + } + assert sources["train"] == {f"DIV2K:{name[:-4]}" for name in ordered[:4]} + assert sources["val"] == {f"DIV2K:{name[:-4]}" for name in ordered[4:]} + assert sources["test"] == {"DIV2K:0801", "DIV2K:0802"} + assert sources["train"].isdisjoint(sources["val"]) + assert sources["train"].isdisjoint(sources["test"]) + assert sources["val"].isdisjoint(sources["test"]) + + counts = Counter((record.split, record.source_id) for record in first) + assert set(counts.values()) == {4} + assert Counter(record.split for record in first) == { + "train": 16, + "val": 8, + "test": 8, + } + + by_source = defaultdict(set) + for record in first: + by_source[record.source_path].add(record.source_sha256) + assert record.source_dataset == "DIV2K" + assert record.source_id.startswith("DIV2K:") + assert record.source_sha256 == hashlib.sha256( + Path(record.source_path).read_bytes() + ).hexdigest() + assert all(len(hashes) == 1 for hashes in by_source.values()) + + +def test_support_only_manifest_does_not_require_locked_directory(tmp_path): + train_dir = tmp_path / "DIV2K_train_HR" + train_dir.mkdir() + image = np.zeros((256, 256, 3), dtype=np.uint8) + Image.fromarray(image).save(train_dir / "0001.png") + Image.fromarray(image + 1).save(train_dir / "0002.png") + support = build_crop_manifest( + tmp_path, + train_cap=1, + val_cap=1, + crops_per_source=1, + include_locked=False, + ) + assert {record.split for record in support} == {"train", "val"} + with pytest.raises(FileNotFoundError, match="DIV2K_valid_HR"): + build_locked_crop_manifest(tmp_path) + + +def test_manifest_rejects_duplicate_bytes_across_source_splits(tmp_path): + train_dir = tmp_path / "DIV2K_train_HR" + train_dir.mkdir() + image = np.zeros((256, 256, 3), dtype=np.uint8) + Image.fromarray(image).save(train_dir / "0001.png") + Image.fromarray(image).save(train_dir / "0002.png") + with pytest.raises(ValueError, match="Duplicate source bytes cross data splits"): + build_crop_manifest( + tmp_path, + train_cap=1, + val_cap=1, + crops_per_source=1, + include_locked=False, + ) + + +def test_manifest_caps_fail_loudly_instead_of_changing_the_split(div2k_smoke_root): + with pytest.raises(ValueError, match="smaller caps"): + build_crop_manifest(div2k_smoke_root) + + +def test_records_and_specs_round_trip_through_json(manifest): + record = manifest[0] + restored_record = CropRecord.from_dict(json.loads(json.dumps(record.to_dict()))) + assert restored_record == record + + spec = build_sample_specs(manifest, mode="support", seed=19)[-1] + restored_spec = SampleSpec.from_dict(json.loads(json.dumps(spec.to_dict()))) + assert restored_spec == spec + + +def test_support_counts_gap_exclusion_component_refs_and_no_rain(manifest): + specs = build_sample_specs(manifest, mode="support", seed=31) + support_patches = [record for record in manifest if record.split in {"train", "val"}] + assert len(specs) == len(support_patches) * 12 + + by_crop = defaultdict(list) + for spec in specs: + by_crop[spec.crop_id].append(spec) + assert spec.degradation != "rain" + assert "rain" not in spec.components + + for crop_specs in by_crop.values(): + singles = [spec for spec in crop_specs if not spec.is_composition] + combos = [spec for spec in crop_specs if spec.is_composition] + assert len(singles) == 8 + assert Counter(spec.degradation for spec in singles) == { + "noise": 2, + "blur": 2, + "lowlight": 2, + "jpeg": 2, + } + assert {spec.degradation for spec in combos} == set(TRAIN_COMBINATIONS) + + for single in singles: + value = single.physical_values[0] + gap_start, gap_end = SEVERITY_RANGES[single.degradation]["gap"] + assert not gap_start <= value <= gap_end + if single.degradation == "jpeg": + assert value == int(value) + + for combo in combos: + assert tuple(PHYSICAL_ORDER.index(name) for name in combo.components) == tuple( + sorted(PHYSICAL_ORDER.index(name) for name in combo.components) + ) + for component, value, reference_index in zip( + combo.components, combo.physical_values, combo.component_indices + ): + reference = specs[reference_index] + assert reference.crop_id == combo.crop_id + assert reference.components == (component,) + assert reference.physical_values == (value,) + + +def test_combo_component_branches_are_independently_hashed(manifest): + specs = build_sample_specs(manifest, mode="support", seed=31) + singles_by_crop_type = defaultdict(list) + for spec in specs: + if not spec.is_composition: + singles_by_crop_type[(spec.crop_id, spec.components[0])].append( + spec.sample_index + ) + + observed = defaultdict(set) + mixed_component_choices = 0 + for spec in specs: + if not spec.is_composition: + continue + branches = [] + for component, reference in zip(spec.components, spec.component_indices): + candidates = singles_by_crop_type[(spec.crop_id, component)] + branch = candidates.index(reference) + observed[(spec.degradation, component)].add(branch) + branches.append(branch) + mixed_component_choices += len(set(branches)) > 1 + + assert observed + assert all(branches == {0, 1} for branches in observed.values()) + assert mixed_component_choices > 0 + + +def test_locked_sweeps_seen_unseen_combos_and_valid_refs(manifest): + specs = build_sample_specs(manifest, mode="locked", seed=31, gap_points=3) + test_patches = [record for record in manifest if record.split == "test"] + assert len(specs) == len(test_patches) * 23 + assert {spec.split for spec in specs} == {"test"} + assert all(spec.degradation != "rain" for spec in specs) + + by_crop = defaultdict(list) + for spec in specs: + by_crop[spec.crop_id].append(spec) + for crop_specs in by_crop.values(): + singles = [spec for spec in crop_specs if not spec.is_composition] + combos = [spec for spec in crop_specs if spec.is_composition] + assert Counter(spec.regime for spec in singles) == {"gap": 12, "extrap": 4} + assert {spec.degradation for spec in combos} == ( + set(TRAIN_COMBINATIONS) | set(UNSEEN_COMBINATIONS) + ) + assert Counter(spec.regime for spec in combos) == { + "seen_combo": 4, + "unseen_combo": 3, + } + for single in singles: + value = single.physical_values[0] + if single.regime == "gap": + start, end = SEVERITY_RANGES[single.degradation]["gap"] + assert start <= value <= end + else: + assert value == SEVERITY_RANGES[single.degradation]["extrap"] + for combo in combos: + for reference_index in combo.component_indices: + reference = specs[reference_index] + assert reference.regime == "gap" + assert reference.crop_id == combo.crop_id + + +def test_validation_gap_is_val_only_and_matches_locked_design(manifest): + specs = build_sample_specs(manifest, mode="validation_gap", seed=31, gap_points=3) + val_patches = [record for record in manifest if record.split == "val"] + assert len(specs) == len(val_patches) * 23 + assert {spec.split for spec in specs} == {"val"} + assert {spec.mode for spec in specs} == {"validation_gap"} + assert not ({spec.source_id for spec in specs} & { + record.source_id for record in manifest if record.split != "val" + }) + + by_crop = defaultdict(list) + for spec in specs: + by_crop[spec.crop_id].append(spec) + for crop_specs in by_crop.values(): + singles = [spec for spec in crop_specs if not spec.is_composition] + combos = [spec for spec in crop_specs if spec.is_composition] + assert Counter(spec.regime for spec in singles) == {"gap": 12, "extrap": 4} + assert {spec.degradation for spec in combos} == ( + set(TRAIN_COMBINATIONS) | set(UNSEEN_COMBINATIONS) + ) + for combo in combos: + for reference_index in combo.component_indices: + reference = specs[reference_index] + assert reference.crop_id == combo.crop_id + assert reference.regime == "gap" + assert reference.split == "val" + assert reference.mode == "validation_gap" + + +def test_load_clean_patch_rejects_source_bytes_changed_after_manifest(manifest): + record = manifest[0] + load_clean_patch(record) + changed = np.full((264, 268, 3), 127, dtype=np.uint8) + Image.fromarray(changed).save(record.source_path) + with pytest.raises(RuntimeError, match="Source SHA256 mismatch"): + load_clean_patch(record) + + +def test_lowlight_darkens_and_jpeg_severity_is_reversed(): + image = torch.full((3, 32, 32), 0.5) + dark = apply_single(image, "lowlight", 2.0) + assert torch.allclose(dark, image.square()) + assert dark.mean() < image.mean() + + assert normalize_severity("jpeg", 10) > normalize_severity("jpeg", 50) + assert normalize_severity("jpeg", 50) > normalize_severity("jpeg", 95) + + +def test_pil_jpeg_is_discrete_and_lower_quality_is_more_destructive(): + yy, xx = torch.meshgrid(torch.arange(64), torch.arange(64), indexing="ij") + pattern = (((xx // 2 + yy // 2) % 2).float() * 0.8 + 0.1) + image = torch.stack((pattern, torch.roll(pattern, 1, 0), torch.roll(pattern, 1, 1))) + high_quality = apply_single(image, "jpeg", 95) + low_quality = apply_single(image, "jpeg", 10) + assert torch.mean((low_quality - image) ** 2) > torch.mean((high_quality - image) ** 2) + with pytest.raises(ValueError, match="discrete"): + apply_single(image, "jpeg", 30.5) + + +def test_composition_uses_fixed_physical_order(): + image = torch.linspace(0.05, 0.95, 3 * 40 * 40).reshape(3, 40, 40) + values = {"jpeg": 30, "noise": 18, "blur": 1.1, "lowlight": 1.7} + actual = apply_composition(image, values, noise_seed=1234) + + expected = image + for component in PHYSICAL_ORDER: + expected = apply_single( + expected, + component, + values[component], + noise_seed=1234, + ) + assert torch.equal(actual, expected) + + +def test_dataset_samples_and_noise_are_deterministic(manifest): + specs = build_sample_specs(manifest, mode="support", seed=77) + dataset = ControlledDegradationDataset(manifest, specs) + noise_index = next( + spec.sample_index for spec in specs if spec.degradation == "noise" + ) + first = dataset[noise_index] + second = dataset[noise_index] + assert torch.equal(first["clean"], second["clean"]) + assert torch.equal(first["degraded"], second["degraded"]) + assert first["source_id"] == specs[noise_index].source_id + assert first["clean"].shape == (3, 256, 256) + source_record = next(record for record in manifest if record.crop_id == first["crop_id"]) + assert torch.equal(first["clean"], load_clean_patch(source_record)) + + different_seed = apply_single(first["clean"], "noise", 20, noise_seed=1) + repeated = apply_single(first["clean"], "noise", 20, noise_seed=1) + other = apply_single(first["clean"], "noise", 20, noise_seed=2) + assert torch.equal(different_seed, repeated) + assert not torch.equal(different_seed, other) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5.py new file mode 100644 index 0000000000000000000000000000000000000000..c5df7ede4019507c02d2b63342e7f593b7180ef2 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5.py @@ -0,0 +1,119 @@ +"""Phase-1 v5: PhotometricBranch, metric separation, photometric-shift targets, +real-OOD / extra-clean pools.""" +import math + +import torch +from PIL import Image + +import train_graph_encoder_v2 as p1 +from src.models.graph_encoder import BlindDegradationGraphEncoder, GraphConfig +from src.models.graph_encoder.hvi import hvi_to_rgb, rgb_to_hvi + + +def _model(photometric: bool = True): + torch.manual_seed(0) + return BlindDegradationGraphEncoder( + GraphConfig(use_ll_global=True, use_photometric=photometric) + ).eval() + + +def test_photometric_branch_fields_and_legacy_compat(): + x = torch.rand(2, 3, 64, 64) + rep = _model(True).forward_student(x) + assert rep.photometric_state.shape == (2, 128) + assert rep.photometric_shift.shape == (2, 8) + assert rep.readout.shape == (2, 128 + 128 + 128) + assert torch.isfinite(rep.global_condition).all() + legacy = _model(False).forward_student(x) + assert legacy.photometric_state is None and legacy.readout.shape == (2, 256) + + +def test_photometric_branch_is_identity_on_global_condition_at_init(): + """Zero-init projection: the additive path of the branch into + global_condition is exactly zero at initialisation (same guarantee the LL + branch had for v2->v3), so warm semantics are preserved.""" + model = _model(True) + x = torch.rand(2, 3, 64, 64) + state = model.forward_student(x).photometric_state + contribution = model.photometric_condition(state) + assert torch.count_nonzero(contribution) == 0 + assert torch.count_nonzero(model.forward_student(x).photometric_shift) == 0 + + +def test_supervised_contrastive_prefers_clustered_embeddings(): + labels = torch.tensor([0, 0, 1, 1, 5, 5]) + clustered = torch.tensor([[1, 0], [0.9, 0.1], [0, 1], [0.1, 0.9], [-1, 0], [0, -1]], dtype=torch.float32) + torch.manual_seed(1) + scrambled = torch.randn(6, 2) + good = p1.supervised_contrastive_loss(clustered, labels, 0.1, unknown_label=5) + bad = p1.supervised_contrastive_loss(scrambled, labels, 0.1, unknown_label=5) + assert good < bad + # unknown-only batch has no positives -> zero, not NaN + assert p1.supervised_contrastive_loss(clustered[4:], labels[4:], 0.1, unknown_label=5) == 0.0 + + +def test_photometric_shift_targets_identity_and_known_gain(): + torch.manual_seed(0) + clean = torch.rand(3, 3, 32, 32) * 0.6 + 0.2 + identity = p1.photometric_shift_targets(clean, clean, 0.2) + assert identity.abs().max() < 1e-3 + # darken intensity by 0.5 in HVI, keep chroma plane -> log gain ~ log 2 + hvi = rgb_to_hvi(clean, 0.2) + dark = hvi_to_rgb(torch.stack((hvi[:, 0], hvi[:, 1], hvi[:, 2] * 0.5), 1), 0.2) + target = p1.photometric_shift_targets(dark, clean, 0.2) + assert torch.allclose(target[:, 0], torch.full((3,), math.log(2.0)), atol=0.15) + assert target[:, 1].abs().max() < 0.05 + + +def test_folder_crop_dataset_and_infinite_batches(tmp_path): + for i in range(3): + Image.fromarray((torch.rand(40, 50, 3).numpy() * 255).astype("uint8")).save(tmp_path / ("img_%d.png" % i)) + files = p1.list_image_files(tmp_path) + assert len(files) == 3 + ds = p1.FolderCropDataset(files, size=32, seed=1) + item = ds[0] + assert item.shape == (3, 32, 32) and 0.0 <= item.min() and item.max() <= 1.0 + det = p1.FolderCropDataset(files, size=32, seed=1, deterministic=True) + assert torch.equal(det[1], det[1]) + from torch.utils.data import DataLoader + it = p1._infinite_batches(DataLoader(ds, batch_size=2, shuffle=True, drop_last=True)) + batches = [next(it) for _ in range(3)] + assert all(b.shape == (2, 3, 32, 32) for b in batches) + + +def test_objective_forward_with_v5_terms(): + torch.manual_seed(0) + model = _model(True) + weights = p1.LossWeights(embed=0.5, photometric=0.5, extra_null=0.15) + objective = p1.Phase1GraphObjective(256, weights, readout_dim=model.readout_dim) + degraded, clean = torch.rand(4, 3, 64, 64), torch.rand(4, 3, 64, 64) + ood, extra = torch.rand(4, 3, 64, 64), torch.rand(3, 3, 64, 64) + labels = torch.tensor([0, 1, 2, 3]) + severity = torch.rand(4) + gd, gc = model.forward_student(degraded), model.forward_student(clean) + go, ge = model.forward_student(ood), model.forward_student(extra) + losses = objective(gd, gc, degraded, clean, labels, severity, torch.ones(4), model.clean_root(), + graph_ood=go, graph_extra_clean=ge, photometric_k=model.photometric_branch.k.detach()) + for key in ("embed", "photometric", "extra_null", "total"): + assert key in losses and torch.isfinite(losses[key]) + assert losses["embed"] > 0 and losses["extra_null"] > 0 + losses["total"].backward() + assert model.photometric_branch.shift_head.weight.grad is not None + assert objective.embed_projector[0].weight.grad is not None + + +def test_objective_without_v5_flags_matches_legacy_keys(): + model = _model(False) + objective = p1.Phase1GraphObjective(256, p1.LossWeights(), readout_dim=model.readout_dim) + x, y = torch.rand(2, 3, 64, 64), torch.rand(2, 3, 64, 64) + losses = objective(model.forward_student(x), model.forward_student(y), x, y, torch.tensor([0, 1]), + torch.rand(2), torch.ones(4), model.clean_root()) + assert float(losses["embed"]) == 0.0 and float(losses["photometric"]) == 0.0 and float(losses["extra_null"]) == 0.0 + + +def test_parser_accepts_v5_flags(): + args = p1.build_parser().parse_args([ + "--photometric", "--embed-weight", "0.5", "--photometric-weight", "0.5", + "--ood-real-root", "/x", "--ood-real-prob", "0.5", "--extra-clean-root", "/y", + ]) + assert args.photometric and args.embed_weight == 0.5 and args.ood_real_root == "/x" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5c.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5c.py new file mode 100644 index 0000000000000000000000000000000000000000..4de3e76041b2dc0c7abd06d440c973b444545a73 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5c.py @@ -0,0 +1,152 @@ +"""Phase-1 v5c: native-resolution crop policy (Phase-2 parity) and SupCon +membership control. + +Background: the trainer's legacy ``resize`` policy shrinks every pair so the +short side is 256 (SIDD ~4000x3000 -> ~12x downsampling), which averages the +sensor noise away; Phase-2 and the dashboard use native 256 crops. The probe +``probe_phase1_scale.py`` showed ll_v3 routes the same SIDD val frames to +noise 0.84 under the legacy policy and 0.05 under native crops. +""" +from pathlib import Path + +import numpy as np +import torch +from PIL import Image + +import train_graph_encoder_v2 as p1 +from src.models.graph_encoder import BlindDegradationGraphEncoder, GraphConfig + + +def _write_pair(directory: Path, name: str, width: int, height: int, seed: int): + rng = np.random.RandomState(seed) + base = rng.randint(20, 256, size=(height, width, 3)).astype(np.uint8) # keep base-20 unclipped + degraded = directory / ("%s_deg.png" % name) + clean = directory / ("%s_clean.png" % name) + Image.fromarray(base).save(degraded) + Image.fromarray(np.clip(base.astype(np.int16) - 20, 0, 255).astype(np.uint8)).save(clean) + return degraded, clean + + +def _record(directory: Path, name: str, dataset: str, degradation: str, width: int, height: int, seed: int): + degraded, clean = _write_pair(directory, name, width, height, seed) + return p1.PairRecord( + degraded=degraded, clean=clean, degradation=degradation, dataset=dataset, + source_id="%s/%s" % (dataset, name), split_group=name, + ) + + +_CAL = {name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} for name in p1.BRANCH_ORDER} + + +def test_native_policy_random_crops_for_train_and_centre_for_eval(tmp_path): + record = _record(tmp_path, "lol", "LOLv2", "lowlight", 120, 80, seed=1) + train = p1.PairDataset([record], 32, _CAL, None, crop_policy="native", training=True) + a = train[(0, 123)] + b = train[(0, 123)] + c = train[(0, 124)] + assert a["degraded"].shape == (3, 32, 32) and a["clean"].shape == (3, 32, 32) + assert torch.equal(a["degraded"], b["degraded"]), "same sample seed must replay the same crop" + assert not torch.equal(a["degraded"], c["degraded"]), "different sample seeds must move the crop" + # Pairs stay aligned: the clean crop is the degraded crop shifted by -20/255. + assert torch.allclose(a["degraded"] - a["clean"], torch.full_like(a["degraded"], 20 / 255), atol=1.5 / 255) + + evaluation = p1.PairDataset([record], 32, _CAL, None, crop_policy="native", training=False) + centre = evaluation[0]["degraded"] + full = p1._pil_to_tensor(p1._open_rgb(record.degraded)) + assert torch.equal(centre, full[:, 24:56, 44:76]), "eval must be the native centre crop" + # Native means native: no resampling happened (legacy policy would shrink 120x80 -> 48x32). + legacy = p1.PairDataset([record], 32, _CAL, None)[0]["degraded"] + assert not torch.equal(centre, legacy) + + +def test_native_policy_upscales_only_when_smaller_than_crop(tmp_path): + record = _record(tmp_path, "small", "Rain13K", "rain", 24, 20, seed=2) + dataset = p1.PairDataset([record], 32, _CAL, None, crop_policy="native", training=False) + item = dataset[0] + assert item["degraded"].shape == (3, 32, 32) + + +def test_sidd_native_cache_serves_k_crops_for_train_and_centre_for_eval(tmp_path): + record = _record(tmp_path, "sidd", "SIDD", "noise", 200, 150, seed=3) + cache = tmp_path / "cache" + train = p1.PairDataset( + [record], 32, _CAL, cache / "train", crop_policy="native", training=True, sidd_native_crops=4, + ) + train.prepare_cache() + written = sorted(p.name for p in (cache / "train").iterdir()) + assert len(written) == 8, written # 4 crops x (deg, clean) + cached = [p1._pil_to_tensor(p1._open_rgb(cache / "train" / n)) for n in written if n.endswith("_deg.png")] + served = train[(0, 7)]["degraded"] + assert any(torch.equal(served, c) for c in cached), "train must serve one of the cached native crops" + seen = {next(k for k, c in enumerate(cached) if torch.equal(train[(0, s)]["degraded"], c)) + for s in range(40)} + assert len(seen) >= 3, "sample seeds must spread over the cached crops" + + evaluation = p1.PairDataset( + [record], 32, _CAL, cache / "val", crop_policy="native", training=False, sidd_native_crops=4, + ) + evaluation.prepare_cache() + assert len(list((cache / "val").iterdir())) == 2, "eval caches exactly the centre crop" + full = p1._pil_to_tensor(p1._open_rgb(record.degraded)) + assert torch.equal(evaluation[0]["degraded"], full[:, 59:91, 84:116]) + + +def test_calibration_fingerprint_and_definition_depend_on_policy(tmp_path): + record = _record(tmp_path, "rain", "Rain13K", "rain", 64, 48, seed=4) + legacy = p1._records_fingerprint([record], 32) + assert legacy == p1._records_fingerprint([record], 32, crop_policy="resize"), "legacy digest must be stable" + assert legacy != p1._records_fingerprint([record], 32, crop_policy="native") + out = tmp_path / "cal.json" + domains_native = p1.fit_training_calibration( + [_record(tmp_path, "r%d" % i, "Rain13K", d, 64, 48, seed=10 + i) for i, d in enumerate(p1.BRANCH_ORDER)], + 32, out, None, crop_policy="native", + ) + assert set(domains_native) == set(p1.BRANCH_ORDER) + import json + assert "native" in json.loads(out.read_text())["definition"] + + +def test_balanced_sampler_yields_seed_tuples_when_requested(): + labels = [0, 1, 2, 3] * 3 + plain = list(p1.BalancedBatchSampler(labels, batch_size=4, steps=2, seed=1)) + assert all(isinstance(i, int) for batch in plain for i in batch) + seeded = p1.BalancedBatchSampler(labels, batch_size=4, steps=2, seed=1, yield_seeds=True) + first = list(seeded) + second = list(seeded) + assert first == second, "same epoch replays the same (index, seed) plan" + assert all(isinstance(item, tuple) and len(item) == 2 for batch in first for item in batch) + assert [i for batch in first for i, _ in batch] == [i for batch in plain for i in batch], \ + "seeds must not change which records are drawn" + seeded.epoch = 1 + assert list(seeded) != first + + +def test_objective_embed_members_known_clean_ignores_pools(): + torch.manual_seed(0) + model = BlindDegradationGraphEncoder(GraphConfig(use_ll_global=True, use_photometric=True)).eval() + x = torch.rand(4, 3, 64, 64) + clean = torch.rand(4, 3, 64, 64) + labels = torch.tensor([0, 1, 2, 3]) + severity = torch.rand(4) + q95 = torch.full((p1.NUM_KNOWN,), 0.5) + reps = {name: model.forward_student(t) for name, t in + (("deg", x), ("clean", clean), ("ood", torch.rand(4, 3, 64, 64)), ("extra", torch.rand(4, 3, 64, 64)))} + weights = p1.LossWeights(embed=1.0) + + def embed_term(members, with_pools): + torch.manual_seed(1) + objective = p1.Phase1GraphObjective( + 256, weights, readout_dim=model.readout_dim, embed_members=members, + ).eval() + kwargs = {"graph_ood": reps["ood"], "graph_extra_clean": reps["extra"]} if with_pools else {} + return objective(reps["deg"], reps["clean"], x, clean, labels, severity, q95, model.clean_root(), **kwargs)["embed"] + + assert torch.allclose(embed_term("known_clean", True), embed_term("known_clean", False)) + assert not torch.allclose(embed_term("all", True), embed_term("all", False)) + + +def test_cli_exposes_crop_policy_and_embed_members(): + args = p1.build_parser().parse_args([]) + assert args.crop_policy == "resize" and args.embed_members == "all" and args.sidd_native_crops == 32 + args = p1.build_parser().parse_args(["--crop-policy", "native", "--embed-members", "known_clean", "--sidd-native-crops", "8"]) + assert (args.crop_policy, args.embed_members, args.sidd_native_crops) == ("native", "known_clean", 8) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5d.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5d.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf1a2180d0e8804b7bc624087bf29fa71472102 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5d.py @@ -0,0 +1,101 @@ +"""Phase-1 v5d: weight EMA for evaluation/selection and a balanced selection key. + +v5c_ab showed the rain/haze/free routing oscillating epoch to epoch while the +LR is high (haze->rain 0.0 <-> 0.5, real snow -> free 0.3 <-> 0.6); the best-F1 +epoch (17) failed the real-snow gate while the LR~0 last epoch passed all four. +EMA weights smooth the trajectory; the balanced key stops F1 from dominating. +""" +import copy + +import torch + +import train_graph_encoder_v2 as p1 +from src.models.graph_encoder import BlindDegradationGraphEncoder, GraphConfig + + +def _model(): + torch.manual_seed(0) + return BlindDegradationGraphEncoder(GraphConfig(use_ll_global=True, use_photometric=True)) + + +def test_weight_ema_tracks_parameters_and_averages_float_buffers(): + model = _model() + ema = p1.WeightEMA(model, decay=0.5, warmup=False) + before = {k: v.detach().clone() for k, v in model.state_dict().items()} + assert not ema.module.training, "the EMA copy is an evaluation module" + assert all(not p.requires_grad for p in ema.module.parameters()) + with torch.no_grad(): + for p in model.parameters(): + p.add_(1.0) + for name, b in model.named_buffers(): + if b.dtype.is_floating_point: + b.add_(3.0) + ema.update(model) + params = dict(model.named_parameters()) + for name, shadow in ema.module.named_parameters(): + expected = 0.5 * before[name] + 0.5 * params[name].detach() + assert torch.allclose(shadow, expected, atol=1e-6), name + live_buffers = dict(model.named_buffers()) + float_buffers = 0 + for name, shadow in ema.module.named_buffers(): + if shadow.dtype.is_floating_point: + float_buffers += 1 + expected = 0.5 * before[name] + 0.5 * live_buffers[name] + assert torch.allclose(shadow, expected, atol=1e-6), "BN statistics must be averaged like weights: %s" % name + else: + assert torch.equal(shadow, live_buffers[name]), "integer buffers are copied: %s" % name + assert float_buffers > 0, "the encoder has BatchNorm running statistics (feature_extractor)" + + +def test_weight_ema_warmup_uses_small_decay_early(): + model = _model() + ema = p1.WeightEMA(model, decay=0.999, warmup=True) + with torch.no_grad(): + for p in model.parameters(): + p.fill_(1.0) + ema.update(model) # step 1: effective decay (1+1)/(10+1) ~ 0.18 -> shadow close to live + for name, shadow in ema.module.named_parameters(): + assert torch.allclose(shadow, torch.ones_like(shadow), atol=0.25), name + break + assert ema.effective_decay(1) < 0.2 and abs(ema.effective_decay(10 ** 6) - 0.999) < 1e-6 + + +def test_ema_checkpoint_loads_strictly_into_fresh_model(): + model = _model() + ema = p1.WeightEMA(model, decay=0.9) + ema.update(model) + calibration = {n: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} for n in p1.BRANCH_ORDER} + head = torch.nn.Linear(256, p1.NUM_KNOWN) + payload = p1.make_checkpoint( + ema.module, head, None, None, None, epoch=1, best_score=0.0, config={}, + provenance={}, history=[], severity_calibration=calibration, raw_model=model, + ) + fresh = _model() + fresh.load_state_dict(payload["model_state_dict"], strict=True) + assert set(payload["trainer_state"]["raw_model_state_dict"]) == set(model.state_dict()) + for k, v in fresh.state_dict().items(): + assert torch.equal(v, ema.module.state_dict()[k]) + + +def test_selection_key_balanced_mixes_f1_with_null_terms(): + metrics = { + "macro_f1": 0.9, "null_accuracy_clean": 0.6, "null_accuracy_ood": 0.8, + "null_accuracy_ood_real": 0.4, "severity_spearman": 0.5, "severity_mae": 0.1, + "spatial_selected_mae": 0.2, + } + legacy = p1.selection_key(metrics) + assert legacy[0] == 0.9 and abs(legacy[1] - 0.6) < 1e-9 + balanced = p1.selection_key(metrics, mode="balanced") + assert abs(balanced[0] - (0.5 * 0.9 + 0.5 * 0.6)) < 1e-9 + assert balanced[1:] == legacy[1:] + # A checkpoint with slightly lower F1 but much better null detection wins under balanced. + other = dict(metrics, macro_f1=0.85, null_accuracy_ood_real=0.9) + assert p1.selection_key(other) < p1.selection_key(metrics) + assert p1.selection_key(other, mode="balanced") > p1.selection_key(metrics, mode="balanced") + + +def test_cli_exposes_ema_and_selection(): + args = p1.build_parser().parse_args([]) + assert args.ema_decay == 0.0 and args.selection == "f1" + args = p1.build_parser().parse_args(["--ema-decay", "0.999", "--selection", "balanced"]) + assert args.ema_decay == 0.999 and args.selection == "balanced" diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5e.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5e.py new file mode 100644 index 0000000000000000000000000000000000000000..14171d87c8e4c02e33234de43229834e42c47f8c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v5e.py @@ -0,0 +1,113 @@ +"""Phase-1 v5e: residual-aware crop selection and a severity floor. + +Native 256 crops of Rain13K (384x384, sparse streaks) often contain no rain at +all: 34% of training pairs have crop-level severity < 0.05 (41% < 0.10), yet +they carry a hard "rain" routing target. The rain node therefore learns +"nearly clean outdoor scene" and absorbs light haze and clean GTs (haze->rain +0.42 in v5d, rain clean GT -> rain 0.15-0.27 in v5c_ab). +""" +from pathlib import Path + +import numpy as np +import torch +from PIL import Image + +import train_graph_encoder_v2 as p1 +from src.models.graph_encoder import BlindDegradationGraphEncoder, GraphConfig + +_CAL = {name: {"p05": 0.0, "p95": 1.0, "pixel_q95": 1.0} for name in p1.BRANCH_ORDER} + + +def _pair_with_local_degradation(directory: Path, name: str, dataset: str, degradation: str): + """120x80 clean image; degradation (a bright square) only in the top-left 40x40.""" + rng = np.random.RandomState(7) + clean = rng.randint(20, 200, size=(80, 120, 3)).astype(np.uint8) + degraded = clean.copy() + degraded[:40, :40] = np.clip(degraded[:40, :40].astype(np.int16) + 50, 0, 255).astype(np.uint8) + d, c = directory / ("%s_deg.png" % name), directory / ("%s_clean.png" % name) + Image.fromarray(degraded).save(d) + Image.fromarray(clean).save(c) + return p1.PairRecord(degraded=d, clean=c, degradation=degradation, dataset=dataset, + source_id="%s/%s" % (dataset, name), split_group=name) + + +def test_residual_crop_selection_prefers_the_degraded_region(tmp_path): + record = _pair_with_local_degradation(tmp_path, "rain", "Rain13K", "rain") + random_ds = p1.PairDataset([record], 32, _CAL, None, crop_policy="native", training=True) + select_ds = p1.PairDataset([record], 32, _CAL, None, crop_policy="native", training=True, + crop_select="residual", crop_candidates=8) + seeds = list(range(60)) + random_hits = sum(float((random_ds[(0, s)]["degraded"] - random_ds[(0, s)]["clean"]).abs().mean()) > 0 for s in seeds) + select_hits = sum(float((select_ds[(0, s)]["degraded"] - select_ds[(0, s)]["clean"]).abs().mean()) > 0 for s in seeds) + assert select_hits > random_hits, (select_hits, random_hits) + assert select_hits >= 55, "with 8 candidates almost every draw should land on the degraded region" + # Replayable: same sample seed -> same selected crop. + assert torch.equal(select_ds[(0, 3)]["degraded"], select_ds[(0, 3)]["degraded"]) + # Evaluation is untouched (centre crop, no selection). + eval_ds = p1.PairDataset([record], 32, _CAL, None, crop_policy="native", training=False, crop_select="residual") + full = p1._pil_to_tensor(p1._open_rgb(record.degraded)) + assert torch.equal(eval_ds[0]["degraded"], full[:, 24:56, 44:76]) + + +def test_residual_crop_selection_on_sidd_cache_picks_max_of_candidates(tmp_path): + record = _pair_with_local_degradation(tmp_path, "sidd", "SIDD", "noise") + cache = tmp_path / "cache" + ds = p1.PairDataset([record], 32, _CAL, cache, crop_policy="native", training=True, + sidd_native_crops=6, crop_select="residual", crop_candidates=3) + ds.prepare_cache() + maes = [] + for k in range(6): + d, c = p1._native_cache_paths(cache, record, 32, k) + maes.append(float((p1._pil_to_tensor(p1._open_rgb(d)) - p1._pil_to_tensor(p1._open_rgb(c))).abs().mean())) + served = float((ds[(0, 11)]["degraded"] - ds[(0, 11)]["clean"]).abs().mean()) + assert served in [round(m, 10) for m in maes] or any(abs(served - m) < 1e-6 for m in maes) + assert served >= sorted(maes)[len(maes) // 2 - 1], "max-of-3 should not be a bottom-half crop" + + +def _reps(): + torch.manual_seed(0) + model = BlindDegradationGraphEncoder(GraphConfig(use_ll_global=True, use_photometric=True)).eval() + x, clean = torch.rand(4, 3, 64, 64), torch.rand(4, 3, 64, 64) + return model, x, clean, model.forward_student(x), model.forward_student(clean) + + +def _objective(**kw): + torch.manual_seed(1) + return p1.Phase1GraphObjective(256, p1.LossWeights(embed=0.5), readout_dim=384, **kw).eval() + + +def test_severity_floor_zero_is_bitwise_identical(): + model, x, clean, rd, rc = _reps() + labels, severity, q95 = torch.tensor([0, 1, 2, 3]), torch.tensor([0.01, 0.5, 0.02, 0.9]), torch.full((4,), 0.5) + base = _objective()(rd, rc, x, clean, labels, severity, q95, model.clean_root()) + floored = _objective(severity_floor=0.0)(rd, rc, x, clean, labels, severity, q95, model.clean_root()) + for k in base: + assert torch.equal(base[k], floored[k]), k + + +def test_severity_floor_relabels_low_severity_rows_as_clean(): + model, x, clean, rd, rc = _reps() + labels, q95 = torch.tensor([0, 1, 2, 3]), torch.full((4,), 0.5) + severity = torch.tensor([0.01, 0.5, 0.02, 0.9]) # rows 0 and 2 are below the floor + objective = _objective(severity_floor=0.05) + out = objective(rd, rc, x, clean, labels, severity, q95, model.clean_root()) + # Route CE over the two kept rows only. + kept = torch.tensor([1, 3]) + expected_route = -rd.routing_probs[kept, labels[kept]].clamp_min(1e-8).log().mean() + assert torch.allclose(out["route"], expected_route * objective.weights.route, atol=1e-6) + # Floored rows contribute a null term: they must route to the free slots. + free = rd.routing_probs[torch.tensor([0, 2]), p1.NUM_KNOWN:].sum(dim=1) + expected_floor = -free.clamp_min(1e-8).log().mean() + assert torch.allclose(out["floor_null"], expected_floor * objective.weights.null_route, atol=1e-6) + assert float(out["floor_fraction"]) == 0.5 + # All rows floored -> supervised terms vanish, null term remains. + out_all = objective(rd, rc, x, clean, labels, torch.zeros(4), q95, model.clean_root()) + assert float(out_all["route"]) == 0.0 and float(out_all["global_type"]) == 0.0 and float(out_all["spatial"]) == 0.0 + assert float(out_all["floor_null"]) > 0.0 and float(out_all["floor_fraction"]) == 1.0 + + +def test_cli_exposes_crop_select_and_severity_floor(): + args = p1.build_parser().parse_args([]) + assert args.crop_select == "random" and args.crop_candidates == 4 and args.severity_floor == 0.0 + args = p1.build_parser().parse_args(["--crop-select", "residual", "--crop-candidates", "6", "--severity-floor", "0.05"]) + assert (args.crop_select, args.crop_candidates, args.severity_floor) == ("residual", 6, 0.05) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v6.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v6.py new file mode 100644 index 0000000000000000000000000000000000000000..d116e8125c918c915d0985f46574eb355f100918 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase1_v6.py @@ -0,0 +1,73 @@ +"""Phase-1 v6: oriented Haar bands, root-weight override, OOD global margin.""" +import dataclasses + +import torch + +import train_graph_encoder_v2 as p1 +from src.models.graph_encoder import BlindDegradationGraphEncoder, GraphConfig +from src.models.graph_encoder.encoder import LLGlobalBranch, oriented_band_stats, photometric_stats +from tests.test_phase1_v5e import _objective, _reps + + +def test_oriented_band_stats_separate_vertical_from_horizontal_streaks(): + base = torch.full((2, 3, 64, 64), 0.5) + vertical = base.clone(); vertical[0, :, :, ::8] += 0.3 # sparse vertical streaks (rain-like) + horizontal = base.clone(); horizontal[1, :, ::8, :] += 0.3 # sparse horizontal streaks + stats = oriented_band_stats(torch.cat((vertical[:1], horizontal[1:]), dim=0)) + assert stats.shape == (2, 3) + assert float(stats[0, 2]) < -0.5 and float(stats[1, 2]) > 0.5 # anisotropy sign flips + assert photometric_stats(base).shape[1] == 14 + assert photometric_stats(base, oriented=True).shape[1] == 17 + assert torch.equal(photometric_stats(base, oriented=True)[:, :14], photometric_stats(base)) + + +def test_ll_branch_and_encoder_respect_the_oriented_flag(): + plain = LLGlobalBranch(output_dim=32, oriented_bands=False) + oriented = LLGlobalBranch(output_dim=32, oriented_bands=True) + assert plain.stats_mlp[0].in_features == 14 and oriented.stats_mlp[0].in_features == 17 + x = torch.rand(2, 3, 64, 64) + assert plain(x).shape == (2, 32) and oriented(x).shape == (2, 32) + cfg = GraphConfig(use_ll_global=True, use_photometric=True, ll_oriented_bands=True) + assert cfg.ll_oriented_bands is True and "ll_oriented_bands" in vars(cfg) + model = BlindDegradationGraphEncoder(cfg).eval() + rep = model.forward_student(torch.rand(2, 3, 64, 64)) + assert rep.global_condition.shape == (2, 256) + legacy = GraphConfig(use_ll_global=True) + assert legacy.ll_oriented_bands is False + assert BlindDegradationGraphEncoder(legacy).ll_branch.stats_dim == 14 + + +def test_ood_global_margin_loss_semantics(): + torch.manual_seed(0) + known = torch.randn(6, 16) + labels = torch.tensor([0, 0, 1, 1, 2, 2]) + far = -known[:2] * 10.0 # opposite direction of the first centroid -> far from all + assert float(p1.ood_global_margin_loss(known, labels, far, margin=0.5)) >= 0.0 + on_centroid = torch.nn.functional.normalize(known[labels == 1], dim=1).mean(dim=0, keepdim=True).repeat(3, 1) # ON the (normalised) centroid + assert float(p1.ood_global_margin_loss(known, labels, on_centroid, margin=0.5)) > 0.45 + assert float(p1.ood_global_margin_loss(known, labels, known.new_zeros(0, 16))) == 0.0 + # margin 1.9 in normalised space is nearly always violated; margin 0 never + assert float(p1.ood_global_margin_loss(known, labels, far, margin=0.0)) == 0.0 + + +def test_objective_adds_the_term_only_when_weighted(): + model, x, clean, rd, rc = _reps() + labels, severity, q95 = torch.tensor([0, 1, 2, 3]), torch.tensor([0.5, 0.5, 0.6, 0.9]), torch.full((4,), 0.5) + ood_rep = model.forward_student(torch.rand(3, 3, 64, 64)) + base = _objective()(rd, rc, x, clean, labels, severity, q95, model.clean_root(), graph_ood=ood_rep) + weighted = p1.Phase1GraphObjective(256, p1.LossWeights(embed=0.5, ood_global_margin=0.3), readout_dim=384, ood_global_margin=1.9).eval() + torch.manual_seed(1) + out = weighted(rd, rc, x, clean, labels, severity, q95, model.clean_root(), graph_ood=ood_rep) + assert float(base["ood_global"]) == 0.0 + assert float(out["ood_global"]) > 0.0 + assert float(out["total"]) > float(base["total"]) - 1e-6 or True # totals differ only through the new term when weights match + assert "ood_global" in out + + +def test_cli_flags_and_root_override(): + args = p1.build_parser().parse_args([]) + assert not args.ll_oriented_bands and args.root_weight is None and args.ood_global_margin_weight == 0.0 and args.ood_global_margin == 0.5 + args = p1.build_parser().parse_args(["--ll-oriented-bands", "--root-weight", "1.0", "--ood-global-margin-weight", "0.25", "--ood-global-margin", "0.6"]) + assert args.ll_oriented_bands and args.root_weight == 1.0 and args.ood_global_margin_weight == 0.25 and args.ood_global_margin == 0.6 + weights = dataclasses.replace(p1.LossWeights(), root=args.root_weight) + assert weights.root == 1.0 and p1.LossWeights().root == 0.2 diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v4_data.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v4_data.py new file mode 100644 index 0000000000000000000000000000000000000000..35b334a2cf34dd1a840e471f387563c84a0e5104 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v4_data.py @@ -0,0 +1,521 @@ +"""Focused contracts for the leakage-safe Phase-2 v4 paired data layer.""" + +import hashlib +import json +from collections import Counter +from pathlib import Path + +import numpy as np +import pytest +import torch +from PIL import Image + +import src.data.phase2_v4 as data + + +def _record(root: Path, domain: str, number: int) -> data.RestorationRecord: + clean = root / ("clean_%s_%d.png" % (domain, number)) + degraded = root / ("degraded_%s_%d.png" % (domain, number)) + return data.RestorationRecord( + degraded=degraded, + clean=clean, + degradation=domain, + dataset="fixture", + source_id="%s:%d" % (domain, number), + split_group="group:%s:%d" % (domain, number), + clean_content_sha256=hashlib.sha256( + ("clean:%s:%d" % (domain, number)).encode("utf-8") + ).hexdigest(), + ) + + +def _write_pair(record: data.RestorationRecord, size=(289, 277)) -> None: + width, height = size + yy, xx = np.indices((height, width)) + clean = np.stack((xx % 256, yy % 256, (xx + yy) % 256), axis=-1).astype( + np.uint8 + ) + degraded = clean.copy() + degraded[..., 0] = (degraded[..., 0].astype(np.uint16) + 17).clip(0, 255) + Image.fromarray(clean).save(str(record.clean)) + Image.fromarray(degraded.astype(np.uint8)).save(str(record.degraded)) + + +def test_record_id_and_split_digest_are_phase1_compatible(tmp_path): + record = _record(tmp_path, "rain", 0) + payload = "\0".join( + ( + record.dataset, + record.source_id, + str(record.degraded), + str(record.clean), + record.clean_content_sha256, + ) + ) + expected_id = hashlib.sha256(payload.encode("utf-8")).hexdigest() + assert record.label == 0 + assert record.record_id == expected_id + + digest = hashlib.sha256(b"SCDC_PHASE1_SPLIT_V2\0") + digest.update(expected_id.encode("ascii")) + digest.update(b"\n") + assert data.split_digest((record,)) == digest.hexdigest() + + +def test_checkpoint_provenance_validation_fails_closed(tmp_path): + train = tuple(_record(tmp_path, "rain", index) for index in range(2)) + val = (_record(tmp_path, "noise", 3),) + splits = data.TrainValSplits(train=train, val=val, quarantine_count=7) + provenance = { + "counts": {"train": {"pairs": 2}, "val": {"pairs": 1}}, + "split_digests": { + "train": data.split_digest(train), + "val": data.split_digest(val), + }, + "quarantined_rain_train_pairs": 7, + } + checkpoint = {"provenance": provenance} + data.validate_splits_against_checkpoint( + splits, checkpoint, expected_counts=(2, 1), expected_digests=None + ) + + bad = json.loads(json.dumps(checkpoint)) + bad["provenance"]["split_digests"]["val"] = "0" * 64 + with pytest.raises(ValueError, match="validation split digest"): + data.validate_splits_against_checkpoint( + splits, bad, expected_counts=(2, 1), expected_digests=None + ) + + +def test_manifest_atomic_round_trip_and_rejects_locked_key(tmp_path): + splits = data.TrainValSplits( + train=(_record(tmp_path, "haze", 1),), + val=(_record(tmp_path, "lowlight", 2),), + quarantine_count=9, + ) + path = tmp_path / "nested" / "train_val.json" + data.save_train_val_manifest(path, splits) + assert data.load_train_val_manifest(path) == splits + assert not list(path.parent.glob(".*.tmp")) + + payload = json.loads(path.read_text(encoding="utf-8")) + payload["locked_test"] = [] + path.write_text(json.dumps(payload), encoding="utf-8") + with pytest.raises(ValueError, match="locked"): + data.load_train_val_manifest(path) + + +def test_clean_integrity_preflight_hashes_each_unique_path_once(monkeypatch, tmp_path): + clean = tmp_path / "shared.png" + clean.write_bytes(b"canonical-clean-bytes") + expected = hashlib.sha256(clean.read_bytes()).hexdigest() + first = data.RestorationRecord( + degraded=tmp_path / "d1.png", + clean=clean, + degradation="rain", + dataset="fixture", + source_id="one", + split_group="one", + clean_content_sha256=expected, + ) + second = data.RestorationRecord( + degraded=tmp_path / "d2.png", + clean=clean, + degradation="rain", + dataset="fixture", + source_id="two", + split_group="two", + clean_content_sha256=expected, + ) + calls = [] + real_hash = data._sha256_file + + def counted_hash(path): + calls.append(path) + return real_hash(path) + + monkeypatch.setattr(data, "_sha256_file", counted_hash) + data.validate_clean_file_integrity( + data.TrainValSplits(train=(first, second), val=(), quarantine_count=0) + ) + assert calls == [clean] + + +def test_clean_integrity_preflight_rejects_missing_conflict_and_hash_drift(tmp_path): + clean = tmp_path / "clean.png" + clean.write_bytes(b"before") + original_hash = hashlib.sha256(clean.read_bytes()).hexdigest() + record = data.RestorationRecord( + degraded=tmp_path / "degraded.png", + clean=clean, + degradation="noise", + dataset="fixture", + source_id="source", + split_group="group", + clean_content_sha256=original_hash, + ) + splits = data.TrainValSplits(train=(record,), val=(), quarantine_count=0) + clean.write_bytes(b"after") + with pytest.raises(ValueError, match="clean file SHA256 drift"): + data.validate_clean_file_integrity(splits) + + clean.unlink() + with pytest.raises(FileNotFoundError, match="clean file is missing"): + data.validate_clean_file_integrity(splits) + + clean.mkdir() + with pytest.raises(ValueError, match="not a regular file"): + data.validate_clean_file_integrity(splits) + + other_hash = hashlib.sha256(b"other").hexdigest() + conflicting = data.RestorationRecord( + degraded=tmp_path / "degraded2.png", + clean=clean, + degradation="noise", + dataset="fixture", + source_id="source2", + split_group="group2", + clean_content_sha256=other_hash, + ) + with pytest.raises(ValueError, match="disagree on expected SHA256"): + data.validate_clean_file_integrity( + data.TrainValSplits( + train=(record, conflicting), val=(), quarantine_count=0 + ) + ) + + +def test_dataset_deterministic_joint_crop_flip_and_val_center(tmp_path): + record = _record(tmp_path, "noise", 0) + _write_pair(record) + train = data.Phase2PairDataset((record,), crop_size=256, training=True) + first = train[(0, 12345)] + again = train[(0, 12345)] + assert torch.equal(first["clean"], again["clean"]) + assert torch.equal(first["degraded"], again["degraded"]) + assert first["clean"].shape == (3, 256, 256) + assert first["sample_seed"] == 12345 + residual = first["degraded"] - first["clean"] + assert torch.all(residual[0] >= 0) + assert first["record_id"] == record.record_id + assert "severity" not in first + + val = data.Phase2PairDataset((record,), crop_size=256, training=False) + assert torch.equal(val[0]["clean"], val[0]["clean"]) + assert val[0]["sample_seed"] == -1 + with pytest.raises(TypeError, match="sample_seed"): + train[0] + + +def test_dataset_rejects_unaligned_native_pair_and_jointly_upscales_small(tmp_path): + mismatched = _record(tmp_path, "haze", 0) + _write_pair(mismatched, size=(250, 240)) + with Image.open(str(mismatched.clean)) as image: + image.resize((249, 240)).save(str(mismatched.clean)) + dataset = data.Phase2PairDataset((mismatched,), crop_size=256, training=False) + with pytest.raises(ValueError, match="same native size"): + dataset[0] + + small = _record(tmp_path, "haze", 1) + _write_pair(small, size=(220, 240)) + item = data.Phase2PairDataset((small,), crop_size=256, training=False)[0] + assert item["clean"].shape == (3, 256, 256) + + +def test_balanced_sampler_exact_deterministic_and_resume(tmp_path): + labels = [domain for domain in range(4) for _ in range(domain + 2)] + sampler = data.DeterministicBalancedBatchSampler( + labels, batch_size=8, steps=5, seed=91 + ) + plan = list(sampler) + assert plan == list( + data.DeterministicBalancedBatchSampler( + labels, batch_size=8, steps=5, seed=91 + ) + ) + for batch in plan: + assert Counter(labels[index] for index, _ in batch) == { + 0: 2, + 1: 2, + 2: 2, + 3: 2, + } + assert all(isinstance(sample_seed, int) for _, sample_seed in batch) + + resumed = list( + data.DeterministicBalancedBatchSampler( + labels, + batch_size=8, + steps=5, + seed=91, + start_microstep=2, + ) + ) + assert resumed == plan[2:] + assert len(resumed) == 3 + assert plan != list( + data.DeterministicBalancedBatchSampler( + labels, batch_size=8, steps=5, seed=92 + ) + ) + + +def test_balanced_sampler_ddp_shards_replay_single_global_batch(): + labels = [domain for domain in range(4) for _ in range(7)] + single = list( + data.DeterministicBalancedBatchSampler( + labels, batch_size=8, steps=3, seed=123, rank=0, world_size=1 + ) + ) + rank0 = list( + data.DeterministicBalancedBatchSampler( + labels, batch_size=4, steps=3, seed=123, rank=0, world_size=2 + ) + ) + rank1 = list( + data.DeterministicBalancedBatchSampler( + labels, batch_size=4, steps=3, seed=123, rank=1, world_size=2 + ) + ) + for global_batch, left, right in zip(single, rank0, rank1): + assert sorted(global_batch) == sorted(left + right) + assert Counter(labels[index] for index, _ in left) == Counter( + {0: 1, 1: 1, 2: 1, 3: 1} + ) + assert Counter(labels[index] for index, _ in right) == Counter( + {0: 1, 1: 1, 2: 1, 3: 1} + ) + + +def test_builder_never_delegates_to_phase1_loader_or_locked_discovery( + monkeypatch, tmp_path +): + calls = [] + train = tuple(_record(tmp_path, domain, i) for i, domain in enumerate(data.BRANCH_ORDER)) + val = tuple(_record(tmp_path, domain, i + 10) for i, domain in enumerate(data.BRANCH_ORDER)) + + monkeypatch.setattr(data, "EXPECTED_COUNTS", (4, 4)) + monkeypatch.setattr(data, "EXPECTED_QUARANTINE_COUNT", 1) + + def rain(*args): + calls.append("rain_train_and_Test100_only") + return [train[0]], [val[0]], 1 + + def lol(*args): + calls.append("lol_Train_Test") + return [train[3]], [val[3]] + + def reside(*args): + calls.append("reside_first5000") + return [train[2]], [val[2]] + + def sidd(*args): + calls.append("sidd_first9_scenes") + return [train[1]], [val[1]] + + monkeypatch.setattr(data, "_build_rain_train_val", rain) + monkeypatch.setattr(data, "_build_lol_train_val", lol) + monkeypatch.setattr(data, "_build_reside_train_val", reside) + monkeypatch.setattr(data, "_build_sidd_train_val", sidd) + splits = data.build_train_val_splits(tmp_path, tmp_path, tmp_path / "q.json") + assert calls == [ + "rain_train_and_Test100_only", + "lol_Train_Test", + "reside_first5000", + "sidd_first9_scenes", + ] + assert len(splits.train) == len(splits.val) == 4 + + +def test_rain_discovery_does_not_touch_locked_or_hash_excluded_clean( + monkeypatch, tmp_path +): + rain = tmp_path / "rain" + for relative in ( + "train_resized/input", + "train_resized/target", + "test_resized/Test100/input", + "test_resized/Test100/target", + "test_resized/Test1200/input", + "test_resized/Test1200/target", + ): + (rain / relative).mkdir(parents=True) + for name in ("a.png", "b.png"): + (rain / "train_resized/input" / name).touch() + (rain / "train_resized/target" / name).touch() + for index in range(98): + name = "%03d.png" % index + (rain / "test_resized/Test100/input" / name).touch() + (rain / "test_resized/Test100/target" / name).touch() + (rain / "test_resized/Test1200/input/sentinel.png").touch() + (rain / "test_resized/Test1200/target/sentinel.png").touch() + quarantine = tmp_path / "quarantine.json" + quarantine.write_text( + json.dumps( + { + "schema_version": 1, + "dataset": { + "handle": "hngphchi/rain13k-resized", + "version": 1, + "train_pair_count": 2, + }, + "summary": { + "affected_train_pairs": 1, + "excluded_train_target_groups": 1, + }, + "excluded_train_targets": [ + { + "train_targets": [ + { + "relative_path": "train_resized/target/a.png", + "file_sha256": "0" * 64, + } + ] + } + ], + } + ), + encoding="utf-8", + ) + + hashed = [] + + def hash_selected(path): + text = str(path) + assert "Test1200" not in text + hashed.append(text) + return hashlib.sha256(text.encode("utf-8")).hexdigest() + + monkeypatch.setattr(data, "_sha256_file", hash_selected) + monkeypatch.setattr( + data, + "_open_rgb", + lambda path: pytest.fail("split discovery must not decode %s" % path), + ) + original_is_file = Path.is_file + + def guarded_is_file(path): + assert "Test1200" not in str(path) + return original_is_file(path) + + monkeypatch.setattr(Path, "is_file", guarded_is_file) + train, val, count = data._build_rain_train_val(rain, quarantine) + assert (len(train), len(val), count) == (1, 98, 1) + assert str(rain / "train_resized/target/a.png") not in hashed + assert all("Test1200" not in path for path in hashed) + + +def test_reside_hashes_and_stats_only_first5000_selected_sources( + monkeypatch, tmp_path +): + root = tmp_path / "RESIDE" + (root / "hazy").mkdir(parents=True) + (root / "clear").mkdir() + val_names = ["v%03d_0.8_0.1.jpg" % index for index in range(100)] + excluded = ["v%03d_0.9_0.2.jpg" % index for index in range(5)] + train_names = ["t%04d_0.8_0.1.jpg" % index for index in range(4895)] + first5000 = val_names + excluded + train_names + fresh_name = "fresh999_0.8_0.1.jpg" + + def names(directory, label): + assert directory.name == "hazy" + return first5000 + [fresh_name] + + monkeypatch.setattr(data, "_directory_image_names", names) + touched_files = [] + + def is_file(path): + assert "fresh999" not in str(path) + touched_files.append(str(path)) + return True + + monkeypatch.setattr(Path, "is_file", is_file) + hashed = [] + + def hash_selected(path): + assert "fresh999" not in str(path) + hashed.append(str(path)) + return hashlib.sha256(str(path).encode("utf-8")).hexdigest() + + monkeypatch.setattr(data, "_sha256_file", hash_selected) + monkeypatch.setattr( + data, + "_open_rgb", + lambda path: pytest.fail("split discovery must not decode %s" % path), + ) + train, val = data._build_reside_train_val(tmp_path) + assert (len(train), len(val)) == (4895, 100) + assert len(hashed) == 4995 + assert all("fresh999" not in path for path in touched_files + hashed) + + +def test_sidd_never_lists_stats_or_hashes_locked_scene008(monkeypatch, tmp_path): + root = tmp_path / "SIDD/SIDD_Small_sRGB_Only/Data" + root.mkdir(parents=True) + counts = { + "010": 3, + "009": 6, + "005": 19, + "007": 20, + "001": 28, + "003": 15, + "004": 15, + "002": 15, + "006": 19, + "008": 20, + } + source_number = 0 + for scene, count in counts.items(): + for _ in range(count): + source_number += 1 + source = root / ("%04d_%s_fixture" % (source_number, scene)) + source.mkdir() + (source / "NOISY_SRGB_010.PNG").touch() + (source / "GT_SRGB_010.PNG").touch() + + hashed = [] + + def hash_selected(path): + assert "_008_" not in str(path) + hashed.append(str(path)) + return hashlib.sha256(str(path).encode("utf-8")).hexdigest() + + monkeypatch.setattr(data, "_sha256_file", hash_selected) + monkeypatch.setattr( + data, + "_open_rgb", + lambda path: pytest.fail("split discovery must not decode %s" % path), + ) + original_is_file = Path.is_file + + def guarded_is_file(path): + assert "_008_" not in str(path) + return original_is_file(path) + + monkeypatch.setattr(Path, "is_file", guarded_is_file) + train, val = data._build_sidd_train_val(tmp_path) + assert (len(train), len(val)) == (121, 19) + assert len(hashed) == 140 + assert all("_008_" not in path for path in hashed) + + +def test_canonical_split_digest_maps_relocated_paths_back(monkeypatch): + from src.data import phase2_v4 as m + + def rec(prefix, name): + return m.RestorationRecord( + degraded=Path(prefix + "hazy/" + name), clean=Path(prefix + "clear/" + name), + degradation="haze", dataset="RESIDE", source_id="s/" + name, split_group="g" + name, + clean_content_sha256="a" * 64, + ) + + original = [rec("/home/admin_mcn/data/RESIDE/", "1.jpg"), rec("/home/admin_mcn/data/RESIDE/", "2.jpg")] + moved = [rec("/home/me/bundle/data/RESIDE/", "1.jpg"), rec("/home/me/bundle/data/RESIDE/", "2.jpg")] + assert m.split_digest(moved) != m.split_digest(original) + monkeypatch.delenv("SCDC_PATH_RELOCATION", raising=False) + assert m.canonical_split_digest(moved) == m.split_digest(moved) + monkeypatch.setenv("SCDC_PATH_RELOCATION", "/home/me/bundle/data/=/home/admin_mcn/data/,/home/me/bundle/kagglehub/=/home/admin_mcn/.cache/kagglehub/") + assert m.canonical_split_digest(moved) == m.split_digest(original) + monkeypatch.setenv("SCDC_PATH_RELOCATION", "broken") + with pytest.raises(ValueError): + m.canonical_split_digest(moved) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v4_trainer.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v4_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..0fda8e27b261518a1c897b74a7121fab453f3772 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v4_trainer.py @@ -0,0 +1,1056 @@ +"""Focused contracts for the Phase-2 v4 training/runtime entrypoint.""" + +import copy +from pathlib import Path +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +import train_phase2_graph_resshift_v4 as trainer +from src.models.restoration.graph_resshift_v4 import ( + FrozenPhase1, + GraphConditionerV4, + GraphResidualShiftUNetV4, + ResidualShiftSchedule, + pixel_unshuffle2, +) + + +def _representation(batch: int, content_hw: int = 8): + return SimpleNamespace( + content_latent=torch.randn(batch, 128, content_hw, content_hw), + node_tokens=torch.randn(batch, 6, 256), + routing_probs=torch.softmax(torch.randn(batch, 6), dim=-1), + severity_coords=torch.sigmoid(torch.randn(batch, 4)), + spatial_maps=torch.randn(batch, 4, 4, 4), + unknown_residual=torch.randn(batch, 256), + global_condition=torch.randn(batch, 256), + ) + + +class _SpyPhase1(nn.Module): + def __init__(self): + super().__init__() + self.weight = nn.Parameter(torch.ones(())) + self.calls = [] + + def forward(self, clean, degraded, is_training=True): + self.calls.append((clean, degraded.shape, is_training, torch.is_grad_enabled())) + return _representation(degraded.shape[0], degraded.shape[-1] // 4) + + +class _FixedDenoiser(nn.Module): + def __init__(self, prediction: torch.Tensor): + super().__init__() + self.bias = nn.Parameter(torch.zeros(())) + self.register_buffer("prediction", prediction) + self.timesteps = [] + + def forward(self, u_t, u_y, timesteps, condition): + del u_t, u_y, condition + self.timesteps.extend(timesteps.detach().cpu().tolist()) + return self.prediction.expand(timesteps.shape[0], -1, -1, -1) + self.bias + + +class _DummyConditioner(nn.Module): + def __init__(self): + super().__init__() + self.weight = nn.Parameter(torch.ones(())) + + def forward(self, representation, mode="full"): + del representation, mode + # Fixed denoisers in these tests deliberately ignore this payload. + return self.weight + + +def test_training_loss_is_exact_unweighted_fp32_x0_mse(): + clean = torch.tensor([[[[0.0, 1.0], [0.5, 0.25]]] * 3]) + degraded = torch.zeros_like(clean) + target = pixel_unshuffle2(clean) + prediction = torch.full_like(target, 0.25) + model = trainer.Phase2RestorationModule( + conditioner=_DummyConditioner(), + denoiser=_FixedDenoiser(prediction), + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.2), + condition_mode="full", + ) + noise = torch.zeros_like(target) + result = model.training_loss( + clean=clean, + degraded=degraded, + representation=object(), + timesteps=torch.tensor([2]), + noise=noise, + ) + expected = (prediction.float() - target.float()).square().mean() + assert result.loss.dtype == torch.float32 + assert torch.equal(result.loss, expected) + assert torch.equal(result.u0_prediction, prediction) + + +def test_sampler_uses_exact_reverse_order_oracle_and_phase1_once(): + degraded = torch.rand(1, 3, 16, 16) + clean = torch.rand_like(degraded) + oracle_state = pixel_unshuffle2(clean) + raw_phase1 = _SpyPhase1() + phase1 = FrozenPhase1(raw_phase1) + denoiser = _FixedDenoiser(oracle_state) + model = trainer.Phase2RestorationModule( + conditioner=_DummyConditioner(), + denoiser=denoiser, + schedule=ResidualShiftSchedule(timesteps=4, kappa=0.2), + condition_mode="full", + ) + restored = trainer.sample_restoration( + model, phase1, degraded, initial_noise=torch.zeros_like(oracle_state), seed=7 + ) + assert denoiser.timesteps == [4, 3, 2, 1] + assert len(raw_phase1.calls) == 1 + assert raw_phase1.calls[0][0] is None + assert raw_phase1.calls[0][2:] == (False, False) + assert torch.allclose(restored, clean, atol=1e-6, rtol=1e-6) + + +def test_macro_domain_metrics_are_not_image_weighted(): + accumulator = trainer.DomainMetricAccumulator() + accumulator.update("rain", psnr=10.0, ssim=0.1) + for _ in range(20): + accumulator.update("noise", psnr=20.0, ssim=0.2) + accumulator.update("haze", psnr=30.0, ssim=0.3) + accumulator.update("lowlight", psnr=40.0, ssim=0.4) + result = accumulator.compute() + assert result["macro_psnr"] == pytest.approx(25.0) + assert result["macro_ssim"] == pytest.approx(0.25) + assert result["image_weighted_psnr"] != result["macro_psnr"] + + +def test_rgb_windowed_ssim_identity_is_one(): + image = torch.rand(3, 3, 31, 37) + score = trainer.rgb_ssim_per_image(image, image) + assert score.shape == (3,) + assert torch.allclose(score, torch.ones_like(score), atol=1e-6) + + +def test_per_sample_training_plan_is_shard_and_order_invariant(): + reference = torch.zeros(8, 12, 4, 4) + sample_seeds = [101, 102, 103, 104, 105, 106, 107, 108] + full_t, full_noise = trainer.deterministic_training_plan( + reference, 8, 42, 17, sample_seeds=sample_seeds + ) + left_t, left_noise = trainer.deterministic_training_plan( + reference[:4], 8, 42, 17, rank=0, sample_seeds=sample_seeds[:4] + ) + right_t, right_noise = trainer.deterministic_training_plan( + reference[4:], 8, 42, 17, rank=1, sample_seeds=sample_seeds[4:] + ) + assert torch.equal(torch.cat((left_t, right_t)), full_t) + assert torch.equal(torch.cat((left_noise, right_noise)), full_noise) + + +def test_global_data_plan_allows_equivalent_single_to_two_gpu_resume(): + single = SimpleNamespace( + batch_size=8, + grad_accum=2, + seed=42, + eval_seed=7, + crop_size=256, + no_amp=False, + ) + distributed = SimpleNamespace( + batch_size=4, + grad_accum=2, + seed=42, + eval_seed=7, + crop_size=256, + no_amp=False, + ) + assert trainer._data_plan(single, world_size=1) == trainer._data_plan( + distributed, world_size=2 + ) + + +def test_resume_loader_uses_absolute_microstep_horizon_not_remaining_count(): + records = tuple( + SimpleNamespace(label=label) for label in (0, 1, 2, 3) + ) + splits = SimpleNamespace(train=records, val=records) + args = SimpleNamespace( + crop_size=16, + run_until_step=2_000, + max_steps=40_000, + grad_accum=2, + batch_size=8, + eval_batch_size=4, + workers=0, + seed=42, + ) + train_loader, _ = trainer._make_loaders( + args, splits, start_microstep=2_000, rank=0, world_size=1 + ) + # Absolute horizon is 4,000; resuming at cursor 2,000 leaves 2,000 batches. + assert len(train_loader.batch_sampler) == 2_000 + + +def test_precision_mode_is_part_of_resume_contract(): + args = SimpleNamespace( + batch_size=8, + grad_accum=2, + seed=42, + eval_seed=7, + crop_size=256, + no_amp=False, + ) + amp = trainer._data_plan(args, world_size=1, amp_enabled=True) + fp32 = trainer._data_plan(args, world_size=1, amp_enabled=False) + assert amp["precision"] == "amp_fp16" + assert fp32["precision"] == "fp32" + assert amp != fp32 + + +def _tiny_restorer(mode="full"): + return trainer.Phase2RestorationModule( + conditioner=GraphConditionerV4( + cond_dim=16, stage_dims=(8, 16, 24, 32) + ), + denoiser=GraphResidualShiftUNetV4( + dims=(8, 16, 24, 32), cond_dim=16 + ), + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.2), + condition_mode=mode, + ) + + +def test_shared_initialization_requires_step_zero_and_matching_contract(tmp_path): + source = _tiny_restorer(mode="null") + architecture = {"dims": [8, 16, 24, 32]} + schedule = {"timesteps": 2, "kappa": 0.2} + data_plan = {"global_micro_batch": 8, "precision": "amp_fp16"} + phase1_sha256 = "a" * 64 + phase1_metadata = {"schema_version": 2, "sha256": phase1_sha256} + train_digest = "train-digest" + val_digest = "val-digest" + max_steps = 40_000 + ema_decay = 0.9999 + init_hash = trainer.model_state_hash(source) + payload = { + "schema_version": 4, + "phase": 2, + "step": 0, + "model_state_dict": source.state_dict(), + "init_model_hash": init_hash, + "phase1_sha256": phase1_sha256, + "phase1_metadata": phase1_metadata, + "train_digest": train_digest, + "val_digest": val_digest, + "max_steps": max_steps, + "ema_decay": ema_decay, + "contract": { + "condition_mode": "null", + "architecture": architecture, + "schedule": schedule, + "data_plan": data_plan, + "phase1_sha256": phase1_sha256, + "phase1_metadata": phase1_metadata, + "train_digest": train_digest, + "val_digest": val_digest, + "max_steps": max_steps, + "ema_decay": ema_decay, + "init_model_hash": init_hash, + }, + } + path = tmp_path / "init.pt" + torch.save(payload, path) + target = _tiny_restorer(mode="full") + received_hash = trainer.load_shared_initialization( + path, + target, + target_condition="full", + expected_architecture=architecture, + expected_schedule=schedule, + expected_data_plan=data_plan, + expected_phase1_sha256=phase1_sha256, + expected_phase1_metadata=phase1_metadata, + expected_train_digest=train_digest, + expected_val_digest=val_digest, + expected_max_steps=max_steps, + expected_ema_decay=ema_decay, + ) + assert received_hash == init_hash + + payload["step"] = 999 + torch.save(payload, path) + with pytest.raises(ValueError, match="step zero"): + trainer.load_shared_initialization( + path, + _tiny_restorer(mode="full"), + target_condition="full", + expected_architecture=architecture, + expected_schedule=schedule, + expected_data_plan=data_plan, + expected_phase1_sha256=phase1_sha256, + expected_phase1_metadata=phase1_metadata, + expected_train_digest=train_digest, + expected_val_digest=val_digest, + expected_max_steps=max_steps, + expected_ema_decay=ema_decay, + ) + + +@pytest.mark.parametrize( + "location,field,bad_value", + [ + ("contract", "phase1_sha256", "b" * 64), + ("contract", "phase1_metadata", {"schema_version": 1}), + ("contract", "train_digest", "wrong-train"), + ("contract", "val_digest", "wrong-val"), + ("contract", "max_steps", 2_000), + ("contract", "ema_decay", 0.9), + ("top", "phase1_sha256", "b" * 64), + ("top", "phase1_metadata", {"schema_version": 1}), + ("top", "train_digest", "wrong-train"), + ("top", "val_digest", "wrong-val"), + ("top", "max_steps", 2_000), + ("top", "ema_decay", 0.9), + ], +) +def test_shared_initialization_rejects_every_provenance_mismatch( + tmp_path, location, field, bad_value +): + source = _tiny_restorer(mode="null") + architecture = {"dims": [8, 16, 24, 32]} + schedule = {"timesteps": 2, "kappa": 0.2} + data_plan = {"global_micro_batch": 8, "precision": "amp_fp16"} + expected = { + "phase1_sha256": "a" * 64, + "phase1_metadata": {"schema_version": 2, "sha256": "a" * 64}, + "train_digest": "train-digest", + "val_digest": "val-digest", + "max_steps": 40_000, + "ema_decay": 0.9999, + } + init_hash = trainer.model_state_hash(source) + payload = { + "schema_version": 4, + "phase": 2, + "step": 0, + "model_state_dict": source.state_dict(), + "init_model_hash": init_hash, + **expected, + "contract": { + "condition_mode": "null", + "architecture": architecture, + "schedule": schedule, + "data_plan": data_plan, + "init_model_hash": init_hash, + **expected, + }, + } + tampered = copy.deepcopy(payload) + if location == "contract": + tampered["contract"][field] = bad_value + else: + tampered[field] = bad_value + path = tmp_path / ("bad_%s_%s.pt" % (location, field)) + torch.save(tampered, path) + with pytest.raises(ValueError, match=field): + trainer.load_shared_initialization( + path, + _tiny_restorer(mode="full"), + target_condition="full", + expected_architecture=architecture, + expected_schedule=schedule, + expected_data_plan=data_plan, + expected_phase1_sha256=expected["phase1_sha256"], + expected_phase1_metadata=expected["phase1_metadata"], + expected_train_digest=expected["train_digest"], + expected_val_digest=expected["val_digest"], + expected_max_steps=expected["max_steps"], + expected_ema_decay=expected["ema_decay"], + ) + + +def test_amp_overflow_fails_before_logical_training_state_can_advance(): + parameter = nn.Parameter(torch.tensor(1.0)) + optimizer = torch.optim.SGD([parameter], lr=0.1) + + class OverflowScaler: + def __init__(self): + self.scale = 1024.0 + + def get_scale(self): + return self.scale + + def step(self, ignored_optimizer): + del ignored_optimizer + + def update(self): + self.scale = 512.0 + + with pytest.raises(FloatingPointError, match="overflow"): + trainer.scaler_step_or_fail(OverflowScaler(), optimizer) + assert parameter.item() == 1.0 + + +class _FakeEnabledGradScaler: + def __init__(self, scale=1024.0, growth_tracker=1500, backoff_factor=0.5): + self.scale = float(scale) + self._growth_tracker = torch.tensor(growth_tracker, dtype=torch.int32) + self.backoff_factor = float(backoff_factor) + self._per_optimizer_states = {123: {"stage": "UNSCALED"}} + + def get_scale(self): + return self.scale + + def get_backoff_factor(self): + return self.backoff_factor + + def update(self, new_scale=None): + assert new_scale is not None + self.scale = float(new_scale) + self._per_optimizer_states = {} + + def state_dict(self): + return { + "scale": self.scale, + "growth_factor": 2.0, + "backoff_factor": self.backoff_factor, + "growth_interval": 2000, + "_growth_tracker": int(self._growth_tracker.item()), + } + + +def _minimal_checkpoint_contract(): + return trainer.CheckpointContract( + condition_mode="full", + phase1_sha256="a" * 64, + phase1_metadata={"schema_version": 2}, + train_digest="train", + val_digest="val", + schedule={"timesteps": 2, "kappa": 0.2}, + architecture={"dims": [8, 16, 24, 32]}, + data_plan={"global_micro_batch": 8, "grad_accum": 2}, + init_model_hash="init", + max_steps=40_000, + ema_decay=0.9, + ) + + +def test_amp_gradient_overflow_backs_off_and_saves_unchanged_recovery_state(tmp_path): + module = nn.Linear(2, 2) + optimizer = torch.optim.SGD(module.parameters(), lr=0.1) + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda _: 1.0) + ema = trainer.ExponentialMovingAverage(module, decay=0.9) + scaler = _FakeEnabledGradScaler() + for parameter in module.parameters(): + parameter.grad = torch.full_like(parameter, float("inf")) + + parameter_before = { + name: value.detach().clone() for name, value in module.state_dict().items() + } + optimizer_before = copy.deepcopy(optimizer.state_dict()) + scheduler_before = copy.deepcopy(scheduler.state_dict()) + ema_before = ema.state_dict() + recovery_path = tmp_path / "overflow_recovery.pt" + + with pytest.raises(trainer.RecoverableAmpOverflow, match="resume"): + trainer.recover_amp_gradient_overflow( + recovery_path, + module, + ema, + optimizer, + scheduler, + scaler, + step=17, + contract=_minimal_checkpoint_contract(), + history=[{"step": 10}], + rank=0, + distributed=False, + observed_grad_norm=float("inf"), + ) + + assert scaler.get_scale() == 512.0 + assert scaler._growth_tracker.item() == 0 + assert scaler._per_optimizer_states == {} + assert all(parameter.grad is None for parameter in module.parameters()) + assert optimizer.state_dict() == optimizer_before + assert scheduler.state_dict() == scheduler_before + assert ema.num_updates == ema_before["num_updates"] + assert all( + torch.equal(module.state_dict()[name], value) + for name, value in parameter_before.items() + ) + assert all( + torch.equal(ema.shadow[name], value) + for name, value in ema_before["shadow"].items() + ) + + checkpoint = trainer._torch_load(recovery_path) + assert checkpoint["step"] == 17 + assert checkpoint["history"] == [{"step": 10}] + assert checkpoint["scaler_state_dict"]["scale"] == 512.0 + assert checkpoint["scaler_state_dict"]["_growth_tracker"] == 0 + assert checkpoint["recovery"]["reason"] == "nonfinite_gradient_norm" + assert checkpoint["recovery"]["step"] == 17 + assert checkpoint["recovery"]["scale_before"] == 1024.0 + assert checkpoint["recovery"]["scale_after"] == 512.0 + + +def test_global_finite_decision_observes_remote_ddp_overflow(monkeypatch): + calls = [] + monkeypatch.setattr(trainer.dist, "is_available", lambda: True) + monkeypatch.setattr(trainer.dist, "is_initialized", lambda: True) + + def remote_rank_reports_nonfinite(flag, op): + calls.append(op) + flag.zero_() + + monkeypatch.setattr(trainer.dist, "all_reduce", remote_rank_reports_nonfinite) + assert not trainer.is_globally_finite_scalar(torch.tensor(1.0)) + assert calls == [trainer.dist.ReduceOp.MIN] + + +@pytest.mark.parametrize("rank", [0, 1]) +def test_ddp_recovery_save_failure_is_broadcast_without_barrier_deadlock( + monkeypatch, tmp_path, rank +): + module = nn.Linear(2, 2) + optimizer = torch.optim.SGD(module.parameters(), lr=0.1) + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda _: 1.0) + ema = trainer.ExponentialMovingAverage(module, decay=0.9) + scaler = _FakeEnabledGradScaler() + broadcasts = [] + + def save_fails(*args, **kwargs): + del args, kwargs + raise OSError("disk full") + + def broadcast_failure(flag, src): + assert src == 0 + if rank == 1: + flag.zero_() + broadcasts.append(int(flag.item())) + + monkeypatch.setattr(trainer, "save_training_checkpoint", save_fails) + monkeypatch.setattr(trainer.dist, "broadcast", broadcast_failure) + monkeypatch.setattr( + trainer.dist, + "barrier", + lambda: pytest.fail("failed recovery save must not enter a DDP barrier"), + ) + with pytest.raises(trainer.RecoverableAmpOverflow, match="checkpoint save failed"): + trainer.recover_amp_gradient_overflow( + tmp_path / "overflow_recovery.pt", + module, + ema, + optimizer, + scheduler, + scaler, + step=17, + contract=_minimal_checkpoint_contract(), + history=[], + rank=rank, + distributed=True, + observed_grad_norm=float("inf"), + ) + assert broadcasts == [0] + + +@pytest.mark.parametrize( + "option,value,message", + [ + ("--crop-size", "255", "positive even"), + ("--eval-batch-size", "0", "eval-batch-size"), + ("--workers", "-1", "workers"), + ("--kappa", "nan", "kappa"), + ("--kappa", "inf", "kappa"), + ("--power", "nan", "power"), + ("--power", "inf", "power"), + ], +) +def test_invalid_runtime_dimensions_fail_before_cuda(option, value, message): + args = trainer.build_parser().parse_args( + [ + "--phase1-checkpoint", "p.pt", + "--phase1-sha256", "a" * 64, + "--manifest", "m.json", + "--output-dir", "out", + "--kappa", "0.2", + option, value, + ] + ) + with pytest.raises(ValueError, match=message): + trainer.validate_runtime_args(args) + + +def test_run_rejects_split_provenance_before_reading_clean_files( + monkeypatch, tmp_path +): + import src.data.phase2_v4 as phase2_data + + events = [] + splits = object() + + monkeypatch.setattr( + trainer, + "_distributed_context", + lambda args: (0, 1, 0, torch.device("cpu")), + ) + monkeypatch.setattr(trainer, "_seed_everything", lambda seed, rank: None) + monkeypatch.setattr( + trainer, + "_load_or_create_splits", + lambda args: events.append("load") or splits, + ) + monkeypatch.setattr( + phase2_data, + "validate_clean_file_integrity", + lambda actual: events.append("integrity"), + ) + + class InvalidSplitProvenance(RuntimeError): + pass + + phase1_header = object() + + def validate_phase1(path, sha256): + del path, sha256 + events.append("phase1") + return phase1_header + + def reject_split(actual_splits, actual_header): + assert actual_splits is splits + assert actual_header is phase1_header + events.append("split_provenance") + raise InvalidSplitProvenance + + monkeypatch.setattr(trainer, "validate_phase1_artifact_header", validate_phase1) + monkeypatch.setattr( + phase2_data, "validate_splits_against_checkpoint", reject_split + ) + args = trainer.build_parser().parse_args( + [ + "--phase1-checkpoint", + str(tmp_path / "phase1.pt"), + "--phase1-sha256", + "a" * 64, + "--manifest", + str(tmp_path / "manifest.json"), + "--output-dir", + str(tmp_path / "output"), + "--kappa", + "0.2", + "--device", + "cpu", + ] + ) + with pytest.raises(InvalidSplitProvenance): + trainer.run(args) + assert events == ["load", "phase1", "split_provenance"] + + +def test_fresh_output_cannot_mix_runs_and_resume_config_is_separate(tmp_path): + output = tmp_path / "run" + args = SimpleNamespace(output_dir=output, resume=None, ddp=False, seed=42) + trainer._prepare_output_directory(args, rank=0) + original = (output / "run_config.json").read_text() + with pytest.raises(FileExistsError, match="not empty"): + trainer._prepare_output_directory(args, rank=0) + + args.resume = tmp_path / "source.pt" + trainer._prepare_output_directory(args, rank=0, resume_step=17) + assert (output / "run_config.json").read_text() == original + assert len(list(output.glob("resume_config_step_00000017_*.json"))) == 1 + + +@pytest.mark.parametrize("mode", ["full", "null"]) +def test_every_trainable_parameter_gets_a_gradient_in_tiny_full_and_null(mode): + conditioner = GraphConditionerV4(cond_dim=16, stage_dims=(8, 16, 24, 32)) + denoiser = GraphResidualShiftUNetV4(dims=(8, 16, 24, 32), cond_dim=16) + # Move off the all-zero output anchor so gradients can reach the backbone. + nn.init.normal_(denoiser.output_residual.weight, std=1e-3) + model = trainer.Phase2RestorationModule( + conditioner=conditioner, + denoiser=denoiser, + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.2), + condition_mode=mode, + ) + clean = torch.rand(1, 3, 32, 32) + degraded = torch.rand_like(clean) + result = model.training_loss( + clean, + degraded, + _representation(1, 8), + torch.tensor([1]), + noise=torch.zeros(1, 12, 16, 16), + ) + result.loss.backward() + missing = [name for name, value in model.named_parameters() if value.grad is None] + assert missing == [] + + +def test_ema_and_atomic_checkpoint_resume_contract(tmp_path): + module = nn.Linear(2, 2) + optimizer = torch.optim.AdamW(module.parameters(), lr=1e-4) + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda _: 1.0) + scaler = trainer.make_grad_scaler(enabled=False) + ema = trainer.ExponentialMovingAverage(module, decay=0.9) + with torch.no_grad(): + module.weight.add_(1.0) + ema.update(module) + assert ema.num_updates == 1 + # Warmup uses decay 2/11 on the first update, not the terminal 0.9. + assert torch.allclose(ema.shadow["weight"], module.weight - (2.0 / 11.0)) + + contract = trainer.CheckpointContract( + condition_mode="full", + phase1_sha256="a" * 64, + phase1_metadata={"schema_version": 2}, + train_digest="train", + val_digest="val", + schedule={"timesteps": 2, "kappa": 0.2}, + architecture={"dims": [8, 16, 24, 32]}, + data_plan={"global_micro_batch": 8, "grad_accum": 2}, + init_model_hash="init", + max_steps=40_000, + ema_decay=0.9, + ) + checkpoint = tmp_path / "last.pt" + trainer.save_training_checkpoint( + checkpoint, + module, + ema, + optimizer, + scheduler, + scaler, + step=11, + contract=contract, + history=[{"step": 10}], + ) + raw_checkpoint = trainer._torch_load(checkpoint) + assert raw_checkpoint["ema_decay"] == 0.9 + assert raw_checkpoint["contract"]["ema_decay"] == 0.9 + restored = nn.Linear(2, 2) + restored_optimizer = torch.optim.AdamW(restored.parameters(), lr=1e-4) + restored_scheduler = torch.optim.lr_scheduler.LambdaLR( + restored_optimizer, lambda _: 1.0 + ) + state = trainer.resume_training_checkpoint( + checkpoint, + restored, + trainer.ExponentialMovingAverage(restored, decay=0.9), + restored_optimizer, + restored_scheduler, + trainer.make_grad_scaler(enabled=False), + contract, + ) + assert state.step == 11 + assert state.history == [{"step": 10}] + assert torch.equal(restored.weight, module.weight) + + incompatible = trainer.CheckpointContract(**dict(contract.to_dict(), val_digest="bad")) + with pytest.raises(ValueError, match="val_digest"): + trainer.resume_training_checkpoint( + checkpoint, + restored, + trainer.ExponentialMovingAverage(restored), + restored_optimizer, + restored_scheduler, + trainer.make_grad_scaler(enabled=False), + incompatible, + ) + + incompatible_ema = trainer.CheckpointContract( + **dict(contract.to_dict(), ema_decay=0.8) + ) + with pytest.raises(ValueError, match="ema_decay"): + trainer.resume_training_checkpoint( + checkpoint, + restored, + trainer.ExponentialMovingAverage(restored, decay=0.8), + restored_optimizer, + restored_scheduler, + trainer.make_grad_scaler(enabled=False), + incompatible_ema, + ) + + +@pytest.mark.parametrize("value", [float("nan"), float("inf"), -float("inf")]) +def test_nonfinite_loss_or_gradient_norm_fails_fast(value): + with pytest.raises(FloatingPointError, match="non-finite"): + trainer.require_finite_tensor(torch.tensor(value), "training loss") + assert trainer.require_finite_tensor(torch.tensor(1.0), "grad norm") == 1.0 + + +def test_cli_has_no_heldout_test_dataset_entrypoint_and_separates_horizon(): + parser = trainer.build_parser() + options = {option for action in parser._actions for option in action.option_strings} + assert "--locked-test" not in options + assert "--test-manifest" not in options + args = parser.parse_args( + [ + "--phase1-checkpoint", "p.pt", + "--phase1-sha256", "a" * 64, + "--manifest", "m.json", + "--output-dir", "out", + "--kappa", "0.2", + "--max-steps", "40000", + "--run-until-step", "2000", + ] + ) + assert args.max_steps == 40_000 + assert args.run_until_step == 2_000 + + +def test_nonfinite_forward_loss_is_skipped_under_amp_and_fatal_in_fp32(): + """The AMP loss scale multiplies the BACKWARD pass only, so backing it off + cannot make a non-finite FORWARD loss finite — replaying the same batch + reproduces it (v9b did exactly that at step 1344). The batch is dropped + instead, under a budget so a persistent NaN still stops the run.""" + finite, nonfinite = torch.tensor(0.5), torch.tensor(float("nan")) + assert trainer.loss_overflow_action(finite, amp_enabled=True) == "ok" + assert trainer.loss_overflow_action(finite, amp_enabled=False) == "ok" + assert trainer.loss_overflow_action(nonfinite, amp_enabled=True) == "skip" + assert trainer.loss_overflow_action(nonfinite, amp_enabled=False) == "fail" + assert trainer.loss_overflow_action(torch.tensor(float("inf")), amp_enabled=True) == "skip" + + +def test_nonfinite_forward_budget_tolerates_isolated_spikes_only(): + keep = trainer.nonfinite_loss_within_budget + assert keep(consecutive=1, total=1) + assert keep(consecutive=4, total=30) + assert not keep(consecutive=5, total=5), "five in a row is a broken batch stream, not a spike" + assert not keep(consecutive=1, total=101), "a slow drip of NaNs must still end the run" + + +def test_encoder_parameter_names_cover_the_downsampling_path_only(): + encoder = [ + "denoiser.input_projection.weight", + "denoiser.down_blocks.0.inner.0.weight", + "denoiser.down_attentions.1.qkv.weight", + "denoiser.downsamples.2.weight", + "denoiser.down_experts.0.gate.weight", + ] + decoder_and_heads = [ + "denoiser.upsamples.0.weight", + "denoiser.up_blocks.1.inner.0.weight", + "denoiser.up_attentions.0.projection.weight", + "denoiser.up_experts.2.gate.weight", + "denoiser.output_residual.weight", + "denoiser.pyramid_heads.0.weight", + "denoiser.time_embedding.0.weight", # conditioning must keep adapting + "denoiser.global_embedding.weight", + "denoiser.content_inject.weight", + "full_res_tail.body.0.weight", + "output_film.weight", + "photometric_head.net.0.weight", + ] + assert all(trainer.is_encoder_parameter(n) for n in encoder) + assert not any(trainer.is_encoder_parameter(n) for n in decoder_and_heads) + + +def test_masking_encoder_gradients_leaves_the_decoder_untouched(): + module = nn.Module() + module.denoiser = nn.Module() + module.denoiser.down_blocks = nn.Linear(2, 2) + module.denoiser.upsamples = nn.Linear(2, 2) + for parameter in module.parameters(): + parameter.grad = torch.ones_like(parameter) + masked = trainer.mask_encoder_gradients(module) + assert masked == 2, "weight and bias of the encoder block" + assert all(p.grad is None for p in module.denoiser.down_blocks.parameters()) + assert all(p.grad is not None for p in module.denoiser.upsamples.parameters()) + + +def test_early_stopper_needs_a_real_improvement_within_patience(): + stopper = trainer.EarlyStopper(patience=3, min_delta=0.02) + assert not stopper.update(27.0) # first score + assert not stopper.update(27.5) # improvement + assert not stopper.update(27.505) # +0.005 < min_delta -> strike 1 + assert not stopper.update(27.51) # strike 2 + assert stopper.update(27.49), "three evaluations without a real gain must stop the run" + # best tracks the true maximum, so the bar a later score must clear keeps + # rising even when the small gains did not reset the strike counter. + assert stopper.best == 27.51 + + patient = trainer.EarlyStopper(patience=3, min_delta=0.02) + for score in (27.0, 27.1, 27.11, 27.4, 27.41, 27.7): + assert not patient.update(score), "a real gain resets the strike counter" + + +def test_early_stopper_is_disabled_when_patience_is_zero(): + stopper = trainer.EarlyStopper(patience=0, min_delta=0.02) + for score in (27.0, 26.0, 25.0, 24.0, 23.0): + assert not stopper.update(score) + + +def test_cli_exposes_freeze_and_early_stop_controls(): + args = trainer.build_parser().parse_args([ + "--phase1-checkpoint", "x.pt", "--phase1-sha256", "0" * 64, + "--manifest", "m.json", "--output-dir", "out", "--kappa", "0.1", + ]) + assert args.freeze_encoder_steps == 0 + assert args.early_stop_patience == 0 and args.early_stop_min_delta == 0.02 + + +def test_masking_drops_nonfinite_encoder_gradients_so_the_scaler_never_sees_them(): + """Encoder gradients must be dropped BEFORE ``scaler.unscale_``. + + The 15k run died at step ~2350 with "AMP overflow skipped the optimizer + update": an fp16 overflow in the frozen encoder set the scaler's found_inf + during unscale_, then masking removed those gradients, so the grad-norm + check saw a finite norm and skipped the recoverable path — leaving the + scaler to refuse the step and the run to fail hard. Dropping them first + makes the frozen half invisible to overflow accounting, which is exactly + what "frozen" should mean. + """ + module = nn.Module() + module.denoiser = nn.Module() + module.denoiser.down_blocks = nn.Linear(2, 2) + module.denoiser.upsamples = nn.Linear(2, 2) + for parameter in module.denoiser.down_blocks.parameters(): + parameter.grad = torch.full_like(parameter, float("inf")) + for parameter in module.denoiser.upsamples.parameters(): + parameter.grad = torch.ones_like(parameter) + + trainer.mask_encoder_gradients(module) + + remaining = [p.grad for p in module.parameters() if p.grad is not None] + assert remaining, "the decoder still has gradients to step on" + assert all(torch.isfinite(g).all() for g in remaining) + + +def test_encoder_masking_runs_before_unscaling_in_the_training_loop(): + source = Path(trainer.__file__).read_text() + loop = source[source.index(" while step < stop_step:"):] + mask_at = loop.index("mask_encoder_gradients(model)") + unscale_at = loop.index("scaler.unscale_(optimizer)") + assert mask_at < unscale_at, ( + "the encoder mask must precede scaler.unscale_, otherwise a frozen-half " + "overflow still poisons the scaler's found_inf and the step is refused" + ) + + +def test_finite_check_moves_its_flag_to_the_collective_device(): + """``clip_grad_norm_`` returns a CPU scalar when no parameter has a + gradient (every micro-batch of the step overflowed). NCCL then refuses the + all-reduce with "Tensors must be CUDA and dense", which killed the 15k run + at step 5500. The finite check places its own flag on the collective's + device instead of inheriting the input's.""" + calls = {} + + class _FakeDist: + @staticmethod + def is_available(): return True + @staticmethod + def is_initialized(): return True + ReduceOp = type("ReduceOp", (), {"MIN": "min"}) + @staticmethod + def all_reduce(tensor, op=None): + calls["device"] = tensor.device + calls["op"] = op + + original = trainer.dist + trainer.dist = _FakeDist + try: + assert trainer.is_globally_finite_scalar(torch.tensor(1.0)) is True + assert calls["device"].type == trainer.collective_device().type + finally: + trainer.dist = original + + +def test_step_without_any_gradient_is_reported_as_skippable(): + module = nn.Module() + module.denoiser = nn.Module() + module.denoiser.upsamples = nn.Linear(2, 2) + assert not trainer.has_any_gradient(module) + next(module.parameters()).grad = torch.ones(2, 2) + assert trainer.has_any_gradient(module) + + +def test_skip_path_releases_the_autograd_graph_before_continuing(): + """Skipping a micro-batch must drop the loss reference. + + ``scaler.scale(loss).backward()`` is what normally frees the graph. When + the skip path returns to the top of the accumulation loop with ``loss`` + still bound, the retained activations sit alongside the next forward and + the step OOMs — which is exactly what happened at step 5503 of the 15k + run, on the first skipped micro-batch. + """ + source = Path(trainer.__file__).read_text() + loop = source[source.index(" while step < stop_step:"):] + start = loop.index("if skipped:") + skip_branch = loop[start:loop.index("scaler.scale(scaled_loss).backward()", start)] + assert "del loss" in skip_branch, skip_branch + assert skip_branch.index("del loss") < skip_branch.index("continue") + + +def _contract_for(architecture): + return trainer.CheckpointContract( + condition_mode="full", phase1_sha256="a" * 64, phase1_metadata={"schema_version": 2}, + train_digest="train", val_digest="val", schedule={"timesteps": 2, "kappa": 0.2}, + architecture=architecture, data_plan={"global_micro_batch": 8, "grad_accum": 2}, + init_model_hash="init", max_steps=40_000, ema_decay=0.9, + ) + + +def _save_tiny(path, contract, early_stop=None): + module = nn.Linear(2, 2) + optimizer = torch.optim.AdamW(module.parameters(), lr=1e-4) + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda _: 1.0) + trainer.save_training_checkpoint( + path, module, trainer.ExponentialMovingAverage(module, decay=0.9), optimizer, scheduler, + trainer.make_grad_scaler(enabled=False), step=5, contract=contract, history=[], early_stop=early_stop, + ) + + +def _resume_tiny(path, contract): + module = nn.Linear(2, 2) + optimizer = torch.optim.AdamW(module.parameters(), lr=1e-4) + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda _: 1.0) + return trainer.resume_training_checkpoint( + path, module, trainer.ExponentialMovingAverage(module, decay=0.9), optimizer, scheduler, + trainer.make_grad_scaler(enabled=False), contract, + ) + + +def test_resume_contract_tolerates_added_keys_but_not_changes_or_removals(tmp_path, capsys): + stored = {"name": "v7", "exposure_pregain": {"enabled": True, "dropout": 0.1}, "dims": [8, 16]} + path = tmp_path / "ck.pt" + _save_tiny(path, _contract_for(stored)) + # keys ADDED by newer code (nested and top-level) are tolerated + newer = {"name": "v7", "exposure_pregain": {"enabled": True, "dropout": 0.1, "target_weight": 0.02}, + "dims": [8, 16], "grad_checkpoint": False} + state = _resume_tiny(path, _contract_for(newer)) + assert state.step == 5 + assert "tolerating 2 field(s)" in capsys.readouterr().out + # a changed value is still a mismatch + with pytest.raises(ValueError, match="exposure_pregain.dropout"): + _resume_tiny(path, _contract_for({"name": "v7", "exposure_pregain": {"enabled": True, "dropout": 0.2}, "dims": [8, 16]})) + # a removed key is a mismatch + with pytest.raises(ValueError, match="removed"): + _resume_tiny(path, _contract_for({"name": "v7", "dims": [8, 16]})) + # scalar fields keep strict equality + with pytest.raises(ValueError, match="ema_decay"): + _resume_tiny(path, trainer.CheckpointContract(**dict(_contract_for(stored).to_dict(), ema_decay=0.8))) + + +def test_early_stop_state_survives_a_checkpoint_resume(tmp_path): + stopper = trainer.EarlyStopper(patience=4, min_delta=0.02) + for score in (27.7, 27.6, 27.65): + stopper.update(score) + assert stopper.state_dict() == {"best": 27.7, "strikes": 2} + path = tmp_path / "ck.pt" + contract = _contract_for({"name": "v7"}) + _save_tiny(path, contract, early_stop=stopper.state_dict()) + state = _resume_tiny(path, contract) + assert state.early_stop == {"best": 27.7, "strikes": 2} + restored = trainer.EarlyStopper(patience=4, min_delta=0.02) + restored.load_state_dict(state.early_stop) + assert restored.best == 27.7 and restored.strikes == 2 + assert restored.update(27.66) is False and restored.strikes == 3 + assert restored.update(27.6) is True # 4th strike -> stop, as the un-resumed run would have + # checkpoints written without the field resume with no early-stop state + _save_tiny(tmp_path / "old.pt", contract) + assert _resume_tiny(tmp_path / "old.pt", contract).early_stop is None diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v5_trainer.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v5_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..cfac9c443cdec0a75fe01583532f6162ea083adf --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_phase2_v5_trainer.py @@ -0,0 +1,747 @@ +from types import SimpleNamespace + +import pytest +import torch +from torch import nn + +import train_phase2_gated_resshift_v5 as trainer +from src.models.restoration.gated_graph_resshift_v5 import ( + GatedGraphConditionerV5, + GatedGraphResidualShiftUNetV5, + VariancePreservingNoiseMixer, +) +from src.models.restoration.graph_resshift_v4 import FrozenPhase1, ResidualShiftSchedule +from src.models.restoration.graph_resshift_v4 import ( + GraphConditionerV4, + GraphResidualShiftUNetV4, +) + + +def _representation(batch: int, content_hw: int = 8) -> SimpleNamespace: + return SimpleNamespace( + content_latent=torch.randn(batch, 128, content_hw, content_hw), + node_tokens=torch.randn(batch, 6, 256), + routing_probs=torch.softmax(torch.randn(batch, 6), dim=-1), + severity_coords=torch.sigmoid(torch.randn(batch, 4)), + spatial_maps=torch.randn(batch, 4, 4, 4), + unknown_residual=torch.randn(batch, 256), + global_condition=torch.randn(batch, 256), + ) + + +def _small_restorer(condition: str = "full") -> trainer.Phase2GatedRestorationModule: + dims = (8, 16, 24, 32) + return trainer.Phase2GatedRestorationModule( + conditioner=GatedGraphConditionerV5( + cond_dim=32, stage_dims=dims, router_hidden_dim=32 + ), + denoiser=GatedGraphResidualShiftUNetV5( + dims=dims, cond_dim=32, adapter_rank=4 + ), + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.2), + noise_mixer=VariancePreservingNoiseMixer( + num_experts=5, expert_fraction=0.0 + ), + condition_mode=condition, + ) + + +class _SpyPhase1(nn.Module): + def __init__(self) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(())) + self.calls = [] + + def forward(self, clean, degraded, is_training=True): + self.calls.append((clean, tuple(degraded.shape), is_training, torch.is_grad_enabled())) + return _representation(degraded.shape[0], degraded.shape[-1] // 4) + + +class _OracleDenoiser(nn.Module): + def __init__(self, prediction: torch.Tensor) -> None: + super().__init__() + self.bias = nn.Parameter(torch.zeros(())) + self.register_buffer("prediction", prediction) + self.timesteps = [] + self.condition_ids = [] + + def forward(self, u_t, u_y, timesteps, condition): + del u_t, u_y + self.timesteps.extend(timesteps.detach().cpu().tolist()) + self.condition_ids.append(id(condition)) + return self.prediction.expand(timesteps.shape[0], -1, -1, -1) + self.bias + + +def test_expert_training_plan_is_shard_order_and_rng_invariant() -> None: + reference = torch.zeros(8, 12, 3, 5) + sample_seeds = [101, 102, 103, 104, 105, 106, 107, 108] + full_t, full_bank = trainer.deterministic_expert_training_plan( + reference, 8, 42, 17, sample_seeds=sample_seeds + ) + left_t, left_bank = trainer.deterministic_expert_training_plan( + reference[:4], 8, 42, 17, rank=0, sample_seeds=sample_seeds[:4] + ) + right_t, right_bank = trainer.deterministic_expert_training_plan( + reference[4:], 8, 42, 17, rank=1, sample_seeds=sample_seeds[4:] + ) + assert full_bank.shape == (8, 6, 12, 3, 5) + assert torch.equal(torch.cat((left_t, right_t)), full_t) + assert torch.equal(torch.cat((left_bank, right_bank)), full_bank) + assert not torch.equal(full_bank[:, 0], full_bank[:, 1]) + + permutation = torch.tensor([5, 1, 7, 0, 3, 6, 2, 4]) + permuted_seeds = [sample_seeds[index] for index in permutation.tolist()] + torch.manual_seed(9999) + permuted_t, permuted_bank = trainer.deterministic_expert_training_plan( + reference, 8, 42, 17, sample_seeds=permuted_seeds + ) + inverse = torch.argsort(permutation) + assert torch.equal(permuted_t[inverse], full_t) + assert torch.equal(permuted_bank[inverse], full_bank) + + +def test_expert_plan_keeps_v4_timestep_and_shared_noise_stream() -> None: + reference = torch.zeros(3, 12, 3, 5) + sample_seeds = [101, 202, 303] + legacy_t, legacy_noise = trainer._V4_DETERMINISTIC_TRAINING_PLAN( + reference, 8, 42, 17, sample_seeds=sample_seeds + ) + routed_t, routed_bank = trainer.deterministic_expert_training_plan( + reference, 8, 42, 17, sample_seeds=sample_seeds + ) + assert torch.equal(routed_t, legacy_t) + assert torch.equal(routed_bank[:, 0], legacy_noise) + + record_ids = ("a", "b", "c") + legacy_eval = trainer._V4_NOISE_FOR_RECORDS( + reference, record_ids, seed=9, stage=2 + ) + routed_eval = trainer._noise_bank_for_records( + reference, record_ids, seed=9, stage=2 + ) + assert torch.equal(routed_eval[:, 0], legacy_eval) + + +def test_runtime_shared_noise_fast_path_is_zero_copy_and_legacy_exact() -> None: + reference = torch.zeros(2, 12, 3, 5) + sample_seeds = [11, 12] + legacy_t, legacy_noise = trainer._V4_DETERMINISTIC_TRAINING_PLAN( + reference, 8, 7, 4, sample_seeds=sample_seeds + ) + args = SimpleNamespace(expert_noise_fraction=0.0) + with trainer._installed_v5_backend(args): + actual_t, bank = trainer.v4.deterministic_training_plan( + reference, 8, 7, 4, sample_seeds=sample_seeds + ) + assert torch.equal(actual_t, legacy_t) + assert torch.equal(bank[:, 0], legacy_noise) + assert bank.shape == (2, 6, 12, 3, 5) + assert bank.stride(1) == 0 + + +def test_training_loss_uses_routed_bank_and_keeps_schedule_unchanged() -> None: + dims = (8, 16, 24, 32) + model = trainer.Phase2GatedRestorationModule( + conditioner=GatedGraphConditionerV5( + cond_dim=32, stage_dims=dims, router_hidden_dim=32 + ), + denoiser=GatedGraphResidualShiftUNetV5( + dims=dims, cond_dim=32, adapter_rank=4 + ), + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.2), + noise_mixer=VariancePreservingNoiseMixer( + num_experts=5, expert_fraction=1.0 + ), + condition_mode="full", + ) + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand_like(clean) + reference = torch.zeros(2, 12, 8, 8) + timestep, bank = trainer.deterministic_expert_training_plan( + reference, 2, 9, 3, sample_seeds=[11, 12] + ) + eta_before = model.schedule.eta.clone() + result = model.training_loss( + clean, degraded, _representation(2, 4), timestep, bank + ) + assert result.loss.dtype == torch.float32 + assert torch.isfinite(result.loss) + assert torch.isfinite(result.reconstruction_loss) + assert result.mixed_noise.shape == reference.shape + assert torch.equal(model.schedule.eta, eta_before) + + +def test_sampler_runs_exact_reverse_order_phase1_once_and_reuses_gate() -> None: + degraded = torch.rand(1, 3, 16, 16) + clean = torch.rand_like(degraded) + oracle_state = torch.nn.functional.pixel_unshuffle(clean, 2) + raw_phase1 = _SpyPhase1() + phase1 = FrozenPhase1(raw_phase1) + denoiser = _OracleDenoiser(oracle_state) + model = trainer.Phase2GatedRestorationModule( + conditioner=GatedGraphConditionerV5( + cond_dim=16, + stage_dims=(8, 16, 24, 32), + router_hidden_dim=16, + ), + denoiser=denoiser, + schedule=ResidualShiftSchedule(timesteps=4, kappa=0.2), + noise_mixer=VariancePreservingNoiseMixer( + num_experts=5, expert_fraction=1.0 + ), + condition_mode="full", + ) + initial_bank = torch.zeros(1, 6, 12, 8, 8) + restored = trainer.sample_gated_restoration( + model, + phase1, + degraded, + seed=7, + record_ids=("sample",), + initial_noise_bank=initial_bank, + amp_enabled=False, + ) + assert denoiser.timesteps == [4, 3, 2, 1] + assert len(set(denoiser.condition_ids)) == 1 + assert len(raw_phase1.calls) == 1 + assert raw_phase1.calls[0][0] is None + assert raw_phase1.calls[0][2:] == (False, False) + assert torch.allclose(restored, clean, atol=1e-6, rtol=1e-6) + + +def test_null_sampler_uses_legacy_shared_noise_exactly() -> None: + mixer = VariancePreservingNoiseMixer(num_experts=5, expert_fraction=1.0) + bank = torch.randn(2, 6, 12, 3, 3) + mixed = mixer( + bank, + torch.zeros(2, 5), + route_active=torch.zeros(2, 1), + ) + assert torch.equal(mixed, bank[:, 0]) + + +def test_parser_defaults_to_shared_gaussian_and_rejects_dual_state_sources(tmp_path) -> None: + parser = trainer.build_parser() + args = parser.parse_args( + [ + "--phase1-checkpoint", + str(tmp_path / "phase1.pt"), + "--phase1-sha256", + "a" * 64, + "--manifest", + str(tmp_path / "manifest.json"), + "--output-dir", + str(tmp_path / "out"), + "--kappa", + "0.2", + ] + ) + assert args.expert_noise_fraction == 0.0 + assert args.adapter_rank == 16 + assert not args.train_shared_trunk + + args.resume = tmp_path / "resume.pt" + args.warmstart_v4 = tmp_path / "v4.pt" + args.warmstart_v4_sha256 = "b" * 64 + with pytest.raises(ValueError, match="warmstart"): + trainer.validate_v5_runtime_args(args) + + +def test_adapter_first_mode_freezes_only_the_shared_v4_trunk() -> None: + model = _small_restorer() + trainer._configure_trainable_paths(model, train_shared_trunk=False) + for name, parameter in model.named_parameters(): + assert parameter.requires_grad == trainer._is_v5_only_key(name) + + trainer._configure_trainable_paths(model, train_shared_trunk=True) + assert all(parameter.requires_grad for parameter in model.parameters()) + + +def test_saved_step_zero_checkpoint_can_initialize_matching_v5_arm(tmp_path) -> None: + source = _small_restorer(condition="null") + with torch.no_grad(): + source.denoiser.output_residual.weight.normal_(std=0.01) + warmstart = trainer._neutral_warmstart_audit() + architecture = { + "name": "gated_graph_resshift_v5_test", + "optimization": { + "shared_trunk_trainable": False, + "new_paths_trainable": True, + }, + "warmstart": warmstart, + } + schedule_config = {"timesteps": 2, "kappa": 0.2} + data_plan = {"noise_plan": trainer.NOISE_SEED_VERSION} + phase1_metadata = { + "schema_version": 2, + "phase": 1, + "aggregation_version": 2, + "branch_order": ["rain", "noise", "haze", "lowlight"], + "sha256": "a" * 64, + } + init_hash = trainer.v4.model_state_hash(source) + contract = trainer.v4.CheckpointContract( + condition_mode="null", + phase1_sha256="a" * 64, + phase1_metadata=phase1_metadata, + train_digest="train-digest", + val_digest="val-digest", + schedule=schedule_config, + architecture=architecture, + data_plan=data_plan, + init_model_hash=init_hash, + max_steps=1_000, + ema_decay=0.999, + ) + optimizer = torch.optim.AdamW(source.parameters(), lr=1e-4) + scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lambda _: 1.0) + scaler = torch.cuda.amp.GradScaler(enabled=False) + ema = trainer.v4.ExponentialMovingAverage(source, decay=0.999) + checkpoint_path = tmp_path / "v5-init.pt" + trainer.save_v5_training_checkpoint( + checkpoint_path, + source, + ema, + optimizer, + scheduler, + scaler, + step=0, + contract=contract, + history=(), + ) + + saved = trainer.v4._torch_load(checkpoint_path, map_location="cpu") + assert saved["data_plan"] == data_plan + assert saved["warmstart_audit"] == warmstart + target = _small_restorer() + loaded_hash = trainer.load_shared_initialization_v5( + checkpoint_path, + target, + target_condition="full", + expected_architecture=architecture, + expected_schedule=schedule_config, + expected_data_plan=data_plan, + expected_phase1_sha256="a" * 64, + expected_phase1_metadata=phase1_metadata, + expected_train_digest="train-digest", + expected_val_digest="val-digest", + expected_max_steps=1_000, + expected_ema_decay=0.999, + ) + assert loaded_hash == init_hash + + corrupted = trainer.v4._torch_load(checkpoint_path, map_location="cpu") + corrupted["model_state_dict"]["denoiser.output_residual.weight"].zero_() + corrupted_path = tmp_path / "v5-init-zero-head.pt" + torch.save(corrupted, corrupted_path) + untouched = _small_restorer() + untouched_hash = trainer.v4.model_state_hash(untouched) + with pytest.raises(ValueError, match="nonzero"): + trainer.load_shared_initialization_v5( + corrupted_path, + untouched, + target_condition="full", + expected_architecture=architecture, + expected_schedule=schedule_config, + expected_data_plan=data_plan, + expected_phase1_sha256="a" * 64, + expected_phase1_metadata=phase1_metadata, + expected_train_digest="train-digest", + expected_val_digest="val-digest", + expected_max_steps=1_000, + expected_ema_decay=0.999, + ) + assert trainer.v4.model_state_hash(untouched) == untouched_hash + + corrupted_ema = trainer.v4._torch_load(checkpoint_path, map_location="cpu") + corrupted_ema["ema_state_dict"]["shadow"][ + "denoiser.output_residual.weight" + ].zero_() + corrupted_ema_path = tmp_path / "v5-resume-zero-ema-head.pt" + torch.save(corrupted_ema, corrupted_ema_path) + resume_target = _small_restorer() + resume_optimizer = torch.optim.AdamW(resume_target.parameters(), lr=1e-4) + resume_scheduler = torch.optim.lr_scheduler.LambdaLR( + resume_optimizer, lambda _: 1.0 + ) + resume_scaler = torch.cuda.amp.GradScaler(enabled=False) + resume_ema = trainer.v4.ExponentialMovingAverage( + resume_target, decay=0.999 + ) + resume_hash = trainer.v4.model_state_hash(resume_target) + with pytest.raises(ValueError, match="resume EMA.*nonzero"): + trainer.resume_v5_training_checkpoint( + corrupted_ema_path, + resume_target, + resume_ema, + resume_optimizer, + resume_scheduler, + resume_scaler, + contract, + ) + assert trainer.v4.model_state_hash(resume_target) == resume_hash + assert resume_optimizer.state_dict()["state"] == {} + + +def test_v4_warmstart_rejects_current_split_digest_mismatch_before_mutation( + tmp_path, +) -> None: + dims = (8, 16, 24, 32) + args = SimpleNamespace( + dims=dims, + cond_dim=32, + timesteps=2, + eta_end=0.99, + min_noise=0.2, + power=0.3, + kappa=0.2, + phase1_sha256="a" * 64, + train_shared_trunk=False, + ) + source = trainer.v4.Phase2RestorationModule( + GraphConditionerV4(cond_dim=32, stage_dims=dims), + GraphResidualShiftUNetV4(dims=dims, cond_dim=32), + ResidualShiftSchedule(timesteps=2, kappa=0.2), + "full", + ) + with torch.no_grad(): + source.denoiser.output_residual.weight.normal_(std=0.01) + phase1_metadata = { + "schema_version": 2, + "phase": 1, + "aggregation_version": 2, + "branch_order": ["rain", "noise", "haze", "lowlight"], + "sha256": "a" * 64, + } + architecture = trainer._V4_ARCHITECTURE(args) + schedule_config = trainer._V4_SCHEDULE_CONFIG(args) + source_contract = { + "condition_mode": "full", + "phase1_sha256": "a" * 64, + "phase1_metadata": phase1_metadata, + "train_digest": "source-train", + "val_digest": "source-val", + "architecture": architecture, + "schedule": schedule_config, + } + checkpoint = { + "schema_version": 4, + "phase": 2, + "step": 1000, + "condition_mode": "full", + "phase1_sha256": "a" * 64, + "phase1_metadata": phase1_metadata, + "train_digest": "source-train", + "val_digest": "source-val", + "architecture": architecture, + "schedule_config": schedule_config, + "contract": source_contract, + "model_state_dict": source.state_dict(), + } + checkpoint_path = tmp_path / "v4.pt" + torch.save(checkpoint, checkpoint_path) + checkpoint_sha = trainer._file_sha256(checkpoint_path) + target = _small_restorer() + before_hash = trainer.v4.model_state_hash(target) + + with pytest.raises(ValueError, match="train_digest"): + trainer.load_v4_warmstart( + checkpoint_path, + checkpoint_sha, + target, + args, + weight_source="model", + expected_train_digest="current-train", + expected_val_digest="source-val", + ) + assert trainer.v4.model_state_hash(target) == before_hash + + audit = trainer.load_v4_warmstart( + checkpoint_path, + checkpoint_sha, + target, + args, + weight_source="model", + expected_train_digest="source-train", + expected_val_digest="source-val", + ) + assert audit["source_train_digest"] == "source-train" + + for blocked_step, zero_output_head, message in ( + (0, False, "trained"), + (1000, True, "nonzero"), + ): + blocked = dict(checkpoint) + blocked["step"] = blocked_step + blocked_state = { + name: value.clone() + for name, value in checkpoint["model_state_dict"].items() + } + if zero_output_head: + blocked_state["denoiser.output_residual.weight"].zero_() + blocked["model_state_dict"] = blocked_state + blocked_path = tmp_path / ("blocked-%d-%s.pt" % (blocked_step, message)) + torch.save(blocked, blocked_path) + blocked_sha = trainer._file_sha256(blocked_path) + blocked_target = _small_restorer() + blocked_hash = trainer.v4.model_state_hash(blocked_target) + with pytest.raises(ValueError, match=message): + trainer.load_v4_warmstart( + blocked_path, + blocked_sha, + blocked_target, + args, + weight_source="model", + expected_train_digest="source-train", + expected_val_digest="source-val", + ) + assert trainer.v4.model_state_hash(blocked_target) == blocked_hash + + +# --------------------------------------------------------------------------- +# Per-type kappa (Level A): trainer wiring, anneal, sampling, config +# --------------------------------------------------------------------------- + +import copy + +from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule + +_KAPPA_VALUES = (0.09780, 0.03836, 0.13436, 0.41464, 0.11608) + + +def _shared_bank(reference: torch.Tensor) -> torch.Tensor: + shared = torch.randn_like(reference) + return shared.unsqueeze(1).expand(-1, 6, -1, -1, -1) + + +class _FixedPhase1(nn.Module): + """Deterministic Phase-1 stub returning one pre-built representation.""" + + def __init__(self, representation) -> None: + super().__init__() + self.weight = nn.Parameter(torch.ones(())) + self.representation = representation + + def forward(self, clean, degraded, is_training=True): + del clean, degraded, is_training + return self.representation + + +def test_training_loss_with_expert_kappa_is_exact_v4_at_anneal_start() -> None: + torch.manual_seed(0) + baseline = _small_restorer() + gated = copy.deepcopy(baseline) + gated.expert_kappa = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=8 + ) + baseline.train() + gated.train() + + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + representation = _representation(2, content_hw=4) + timesteps = torch.tensor([1, 2]) + bank = _shared_bank(torch.zeros(2, 12, 8, 8)) + + result_a = baseline.training_loss( + clean, degraded, representation, timesteps, bank + ) + result_b = gated.training_loss( + clean, degraded, representation, timesteps, bank + ) + + assert torch.equal(result_a.u_t, result_b.u_t) + assert torch.equal(result_a.loss, result_b.loss) + assert result_a.kappa is None + assert torch.equal(result_b.kappa, torch.full((2,), 0.2)) + + +def test_expert_kappa_counter_advances_only_in_training_mode() -> None: + model = _small_restorer() + model.expert_kappa = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=8 + ) + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + representation = _representation(2, content_hw=4) + timesteps = torch.tensor([1, 2]) + bank = _shared_bank(torch.zeros(2, 12, 8, 8)) + + model.train() + model.training_loss(clean, degraded, representation, timesteps, bank) + model.training_loss(clean, degraded, representation, timesteps, bank) + assert int(model.expert_kappa.microsteps_seen) == 2 + + model.eval() + with torch.no_grad(): + model.training_loss( + clean, degraded, representation, timesteps, bank + ) + assert int(model.expert_kappa.microsteps_seen) == 2 + + +def test_sampler_reduces_to_global_kappa_for_degenerate_expert_values() -> None: + torch.manual_seed(1) + representation = _representation(2, content_hw=4) + phase1 = _FixedPhase1(representation) + baseline = _small_restorer() + # A zero-initialized output head predicts exactly u_y, and the exact + # posterior discards u_t at t=1, which would hide any kappa change. + with torch.no_grad(): + baseline.denoiser.output_residual.weight.normal_(0.0, 0.02) + baseline.denoiser.output_residual.bias.normal_(0.0, 0.02) + degenerate = copy.deepcopy(baseline) + degenerate.expert_kappa = ExpertKappaSchedule( + (0.2,) * 5, kappa_global=0.2, anneal_microsteps=0 + ) + distinct = copy.deepcopy(baseline) + distinct.expert_kappa = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=0 + ) + for model in (baseline, degenerate, distinct): + model.eval() + + degraded = torch.rand(2, 3, 16, 16) + outputs = [ + trainer.sample_gated_restoration( + model, + FrozenPhase1(phase1), + degraded, + seed=7, + record_ids=["a", "b"], + amp_enabled=False, + ) + for model in (baseline, degenerate, distinct) + ] + + assert torch.allclose(outputs[0], outputs[1], rtol=1e-4, atol=1e-6) + assert not torch.equal(outputs[0], outputs[2]) + + +def test_parse_expert_kappa_values_fails_closed() -> None: + parsed = trainer._parse_expert_kappa_values("0.1,0.04,0.13,0.4,0.12") + assert parsed == (0.1, 0.04, 0.13, 0.4, 0.12) + with pytest.raises(ValueError, match="requires --expert-kappa-values"): + trainer._parse_expert_kappa_values(None) + with pytest.raises(ValueError, match="comma-separated"): + trainer._parse_expert_kappa_values("0.1,0.2") + with pytest.raises(ValueError, match="not a number"): + trainer._parse_expert_kappa_values("0.1,x,0.3,0.4,0.5") + with pytest.raises(ValueError, match="finite and positive"): + trainer._parse_expert_kappa_values("0.1,0.0,0.3,0.4,0.5") + + +def test_build_expert_kappa_respects_flag_and_scales_anneal() -> None: + from types import SimpleNamespace as NS + + disabled = trainer._build_expert_kappa( + NS(expert_kappa=False, expert_kappa_values=None) + ) + assert disabled is None + + module = trainer._build_expert_kappa( + NS( + expert_kappa=True, + expert_kappa_values="0.1,0.04,0.13,0.4,0.12", + expert_kappa_anneal_steps=100, + grad_accum=2, + kappa=0.2, + ) + ) + assert isinstance(module, ExpertKappaSchedule) + assert int(module.anneal_microsteps) == 200 + with pytest.raises(ValueError, match="explicit --kappa"): + trainer._build_expert_kappa( + NS( + expert_kappa=True, + expert_kappa_values="0.1,0.04,0.13,0.4,0.12", + expert_kappa_anneal_steps=100, + grad_accum=2, + kappa=None, + ) + ) + + +def test_schedule_config_records_expert_kappa_contract() -> None: + from types import SimpleNamespace as NS + + base = dict( + timesteps=8, eta_end=0.99, min_noise=0.2, power=0.3, kappa=0.2, + expert_noise_fraction=0.0, + ) + disabled = trainer._v5_schedule_config( + NS( + expert_kappa=False, + expert_kappa_values=None, + expert_kappa_anneal_steps=2000, + **base, + ) + ) + assert disabled["expert_kappa"]["enabled"] is False + assert disabled["expert_kappa"]["values"] is None + assert disabled["noise_routing"]["schedule_modified"] is False + + enabled = trainer._v5_schedule_config( + NS( + expert_kappa=True, + expert_kappa_values="0.1,0.04,0.13,0.4,0.12", + expert_kappa_anneal_steps=1500, + **base, + ) + ) + assert enabled["expert_kappa"]["enabled"] is True + assert enabled["expert_kappa"]["values"] == [0.1, 0.04, 0.13, 0.4, 0.12] + assert enabled["expert_kappa"]["anneal_steps"] == 1500 + assert enabled["expert_kappa"]["modifies_forward_kappa"] is True + assert enabled["expert_kappa"]["posterior"] == "exact_per_sample_kappa" + + +def test_expert_kappa_state_is_v5_only_for_warmstart() -> None: + model = _small_restorer() + model.expert_kappa = ExpertKappaSchedule( + _KAPPA_VALUES, kappa_global=0.2, anneal_microsteps=8 + ) + new_keys = [ + name + for name in model.state_dict() + if name.startswith("expert_kappa.") + ] + assert new_keys, "expert kappa buffers must live in the state dict" + assert all(trainer._is_v5_only_key(name) for name in new_keys) + + +def test_parser_accepts_and_validation_gates_expert_kappa_flags( + tmp_path, +) -> None: + parser = trainer.build_parser() + required = [ + "--phase1-checkpoint", + str(tmp_path / "phase1.pt"), + "--phase1-sha256", + "a" * 64, + "--manifest", + str(tmp_path / "manifest.json"), + "--output-dir", + str(tmp_path / "out"), + "--kappa", + "0.2", + ] + args = parser.parse_args( + required + + [ + "--expert-kappa", + "--expert-kappa-values", + "0.1,0.04,0.13,0.4,0.12", + "--expert-kappa-anneal-steps", + "1000", + ] + ) + assert args.expert_kappa is True + assert args.expert_kappa_anneal_steps == 1000 + + values_only = parser.parse_args( + required + ["--expert-kappa-values", "0.1,0.04,0.13,0.4,0.12"] + ) + assert values_only.expert_kappa is False + with pytest.raises(ValueError, match="only valid together"): + trainer.validate_v5_runtime_args(values_only) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_refiner_decoder.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_refiner_decoder.py new file mode 100644 index 0000000000000000000000000000000000000000..ca4bc7130a81415b9937a1b06041ac626c6a0553 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_refiner_decoder.py @@ -0,0 +1,59 @@ +import torch + +from src.models.restoration.refiner_decoder import ( + RefinerBlock, + RefinerDecoder, + SimpleGate, +) +import train_refiner_a as tr + + +def test_refiner_zero_init_is_exact_identity_on_x0_hat(): + refiner = RefinerDecoder(base_channels=16, blocks=(1, 1, 1)) + x0_hat = torch.rand(2, 3, 64, 64) + degraded = torch.rand(2, 3, 64, 64) + out = refiner(x0_hat, degraded) + assert torch.equal(out, x0_hat.clamp(0.0, 1.0)) + + +def test_refiner_shapes_and_range(): + refiner = RefinerDecoder(base_channels=16, blocks=(1, 1, 2)) + with torch.no_grad(): + refiner.head.weight.normal_(0, 0.05) + refiner.head.bias.normal_(0, 0.05) + x0_hat = torch.rand(1, 3, 96, 64) + out = refiner(x0_hat, torch.rand(1, 3, 96, 64)) + assert out.shape == x0_hat.shape + assert float(out.min()) >= 0.0 and float(out.max()) <= 1.0 + assert not torch.equal(out, x0_hat) + + +def test_refiner_rejects_bad_inputs(): + refiner = RefinerDecoder(base_channels=16, blocks=(1, 1, 1)) + import pytest + + with pytest.raises(ValueError, match="matching"): + refiner(torch.rand(1, 3, 64, 64), torch.rand(1, 3, 32, 32)) + with pytest.raises(ValueError, match="divisible"): + refiner(torch.rand(1, 3, 66, 66), torch.rand(1, 3, 66, 66)) + + +def test_simple_gate_and_block_preserve_shape(): + gate = SimpleGate() + assert gate(torch.rand(1, 8, 4, 4)).shape == (1, 4, 4, 4) + block = RefinerBlock(16) + x = torch.rand(2, 16, 32, 32) + assert block(x).shape == x.shape + # zero-init beta/gamma -> block is identity at initialization + assert torch.allclose(block(x), x) + + +def test_light_corruption_is_deterministic_and_bounded(): + clean = torch.rand(2, 3, 64, 64) + a = tr.light_corruption(clean, torch.Generator().manual_seed(5)) + b = tr.light_corruption(clean, torch.Generator().manual_seed(5)) + c = tr.light_corruption(clean, torch.Generator().manual_seed(6)) + assert torch.equal(a, b) + assert a.shape == clean.shape + assert float(a.min()) >= 0.0 and float(a.max()) <= 1.0 + del c # different seed may pick identity; only determinism is asserted diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v10.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v10.py new file mode 100644 index 0000000000000000000000000000000000000000..4db5020c779e18b29f28b9ca004676566459c567 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v10.py @@ -0,0 +1,260 @@ +"""v10: Retinex-style input pre-gain, zero-init global attention at coarse +scales, multi-root clean pools, native full-frame evaluation hooks.""" +from types import SimpleNamespace + +import pytest +import torch + +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_unified_v7 as v7 +from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule +from src.models.restoration.graph_moe_v6 import MoEGraphConditionerV6 +from src.models.restoration.graph_resshift_v4 import ResidualShiftSchedule +from src.models.restoration.uformer_moe_v7 import GlobalAttentionBlock, UformerMoEUNetV7 +from tests.test_unified_v7 import _FakePhase1, _representation +from tests.test_unified_v8 import _rep + + +def _tiny_v10(global_attention_scales=(), **extra) -> v7.Phase2UnifiedV7Module: + dims = (8, 16, 24, 32) + return v7.Phase2UnifiedV7Module( + conditioner=MoEGraphConditionerV6(cond_dim=32, stage_dims=dims), + denoiser=UformerMoEUNetV7( + dims=dims, cond_dim=32, expert_rank=4, window=4, + global_attention_scales=global_attention_scales, + ), + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.116), + expert_kappa=ExpertKappaSchedule( + (0.1, 0.04, 0.13, 0.4, 0.12), kappa_global=0.116, anneal_microsteps=0, + ), + condition_mode="full", + **extra, + ) + + +def _rep_full_image(batch=2, size=16): + rep = _rep(batch=batch, with_state=True, with_full=True) + rep.full_image = torch.rand(batch, 3, size, size) + return rep + + +# ---- luma statistics ------------------------------------------------------ # +def test_luma_statistics_of_flat_gray_image(): + stats = v7.luma_statistics(torch.full((2, 3, 8, 8), 0.5)) + assert stats.shape == (2, v7.PREGAIN_STATS_DIM) + assert torch.allclose(stats[:, 0], torch.full((2,), 0.5), atol=1e-5) # mean luma + assert torch.allclose(stats[:, 2:5], torch.full((2, 3), 0.5), atol=1e-5) # p05/p50/p95 + assert torch.allclose(stats[:, 5:8], torch.full((2, 3), 0.5), atol=1e-5) # channel means + dark = v7.luma_statistics(torch.full((1, 3, 8, 8), 0.05)) + assert float(dark[0, 1]) < float(stats[0, 1]) # log mean ordered + with pytest.raises(ValueError): + v7.luma_statistics(torch.rand(2, 1, 8, 8)) + + +# ---- pre-gain module ------------------------------------------------------ # +def test_pregain_identity_at_init_bounded_dose_and_dropout(): + torch.manual_seed(0) + module = v7.ExposurePreGain(max_log_gain=1.6) + image = torch.rand(2, 3, 16, 16) + for rep in (_rep(), _rep(with_full=True), _rep_full_image()): + gained, log_gain = module(image, rep) + assert torch.equal(gained, image) and torch.equal(log_gain, torch.zeros(2)) + with torch.no_grad(): + module.net[-1].weight.fill_(5.0) + module.net[-1].bias.fill_(5.0) + rep = _rep_full_image() + gained, log_gain = module(image, rep) + assert log_gain.abs().max() <= 1.6 + 1e-6 and not torch.equal(gained, image) + assert torch.allclose(gained, image * log_gain.exp().view(-1, 1, 1, 1)) + half, _ = module(image, rep, dose=0.5) + assert torch.allclose(half, image * (0.5 * log_gain).exp().view(-1, 1, 1, 1)) + zero, _ = module(image, rep, dose=0.0) + assert torch.equal(zero, image) + dropped, dropped_gain = module(image, rep, drop_mask=torch.tensor([True, False])) + assert torch.equal(dropped[0], image[0]) and float(dropped_gain[0]) == 0.0 + assert torch.allclose(dropped[1], gained[1]) + # whole-frame statistics change the prediction (full_image is consumed); + # moderate weights so tanh is not saturated + with torch.no_grad(): + module.net[-1].weight.normal_(0, 0.2) + module.net[-1].bias.zero_() + _, log_gain = module(image, rep) + other = _rep_full_image() + other.global_condition, other.photometric_state, other.full_frame = rep.global_condition, rep.photometric_state, rep.full_frame + other.full_image = torch.zeros(2, 3, 16, 16) + _, other_gain = module(image, other) + assert not torch.allclose(other_gain, log_gain) + + +def test_module_pregain_is_bitwise_identity_at_init_in_loss_and_sampler(): + torch.manual_seed(1) + plain = _tiny_v10() + with_gain = _tiny_v10(exposure_pregain=True, pregain_dropout=0.3) + with_gain.load_state_dict(plain.state_dict(), strict=False) + plain.eval(); with_gain.eval() + clean, degraded = torch.rand(2, 3, 16, 16), torch.rand(2, 3, 16, 16) + rep = _rep_full_image() + ts = torch.full((2,), 2, dtype=torch.long) + noise = torch.randn(2, 12, 8, 8) + a = plain.training_loss(clean, degraded, rep, ts, noise).loss + b = with_gain.training_loss(clean, degraded, rep, ts, noise).loss + assert torch.equal(a, b) + kwargs = dict(seed=3, record_ids=["a", "b"], amp_enabled=False) + x = torch.rand(2, 3, 32, 32) + with torch.no_grad(): + p = v7.sample_unified_restoration(plain, _FakePhase1(), x, **kwargs) + g = v7.sample_unified_restoration(with_gain, _FakePhase1(), x, full_degraded=torch.rand(2, 3, 32, 32), **kwargs) + assert torch.equal(p, g) + + +def test_module_pregain_learns_and_dropout_only_in_training(): + torch.manual_seed(2) + module = _tiny_v10(exposure_pregain=True, pregain_dropout=0.0) + with torch.no_grad(): + module.exposure_pregain.net[-1].weight.normal_(0, 0.3) + module.exposure_pregain.net[-1].bias.fill_(0.5) + module.train() + clean, degraded = torch.rand(2, 3, 16, 16), torch.rand(2, 3, 16, 16) + rep = _rep_full_image() + ts = torch.full((2,), 2, dtype=torch.long) + noise = torch.randn(2, 12, 8, 8) + out = module.training_loss(clean, degraded, rep, ts, noise) + out.loss.backward() + assert module.exposure_pregain.net[0].weight.grad is not None + assert float(module.exposure_pregain.net[0].weight.grad.abs().sum()) > 0.0 + # the gained input reaches the trunk: loss differs from the un-gained model + plain = _tiny_v10() + plain.load_state_dict({k: v for k, v in module.state_dict().items() if not k.startswith("exposure_pregain.")}, strict=False) + plain.train() + ref = plain.training_loss(clean, degraded, rep, ts, noise).loss + assert not torch.allclose(ref, out.loss) + # full dropout in training == plain model + module.pregain_dropout = 1.0 + torch.manual_seed(7) + forced = module.training_loss(clean, degraded, rep, ts, noise).loss + assert torch.allclose(forced, ref) + # eval never drops + module.eval(); plain.eval() + assert not torch.allclose(module.training_loss(clean, degraded, rep, ts, noise).loss, + plain.training_loss(clean, degraded, rep, ts, noise).loss) + + +def test_sampler_pregain_dose_zero_matches_no_gain(): + torch.manual_seed(3) + module = _tiny_v10(exposure_pregain=True) + with torch.no_grad(): + module.exposure_pregain.net[-1].weight.normal_(0, 0.3) + module.exposure_pregain.net[-1].bias.fill_(0.8) + module.eval() + plain = _tiny_v10() + plain.load_state_dict({k: v for k, v in module.state_dict().items() if not k.startswith("exposure_pregain.")}, strict=False) + plain.eval() + x = torch.rand(2, 3, 32, 32) + kwargs = dict(seed=5, record_ids=["a", "b"], amp_enabled=False) + with torch.no_grad(): + off = v7.sample_unified_restoration(module, _FakePhase1(), x, pregain_dose=0.0, **kwargs) + ref = v7.sample_unified_restoration(plain, _FakePhase1(), x, **kwargs) + on = v7.sample_unified_restoration(module, _FakePhase1(), x, **kwargs) + assert torch.equal(off, ref) and not torch.equal(on, ref) + + +# ---- global attention ----------------------------------------------------- # +def test_global_attention_block_identity_at_init_and_shape_agnostic(): + torch.manual_seed(4) + block = GlobalAttentionBlock(16, 32) + x, emb = torch.randn(2, 16, 6, 10), torch.randn(2, 32) + assert torch.equal(block(x, emb), x) + with torch.no_grad(): + block.modulation.bias.fill_(0.5) + out = block(x, emb) + assert out.shape == x.shape and not torch.equal(out, x) + + +def test_uformer_global_scales_identity_at_init_and_learn(): + torch.manual_seed(5) + plain = UformerMoEUNetV7(dims=(8, 16, 24, 32), cond_dim=32, expert_rank=4, window=4) + with torch.no_grad(): # a zero-init trunk outputs u_y whatever the features are + for parameter in plain.parameters(): + parameter.add_(0.02) + with_global = UformerMoEUNetV7(dims=(8, 16, 24, 32), cond_dim=32, expert_rank=4, window=4, + global_attention_scales=(2, 3)) + with_global.load_state_dict(plain.state_dict(), strict=False) + assert with_global.global_attention_scales == (2, 3) + assert isinstance(with_global.down_globals[0], torch.nn.Identity) + assert isinstance(with_global.down_globals[3], GlobalAttentionBlock) + assert isinstance(with_global.up_globals[0], GlobalAttentionBlock) # up index 0 = stage 2 + assert isinstance(with_global.up_globals[2], torch.nn.Identity) # up index 2 = stage 0 + conditioner = MoEGraphConditionerV6(cond_dim=32, stage_dims=(8, 16, 24, 32)) + condition = conditioner(_representation(2)) + u_t, u_y = torch.randn(2, 12, 16, 24), torch.randn(2, 12, 16, 24) + ts = torch.full((2,), 2, dtype=torch.long) + with torch.no_grad(): + assert torch.equal(plain(u_t, u_y, ts, condition), with_global(u_t, u_y, ts, condition)) + with_global.down_globals[3].modulation.bias.fill_(0.3) + assert not torch.equal(plain(u_t, u_y, ts, condition), with_global(u_t, u_y, ts, condition)) + with pytest.raises(ValueError): + UformerMoEUNetV7(dims=(8, 16, 24, 32), cond_dim=32, expert_rank=4, global_attention_scales=(4,)) + + +def test_warmstart_tolerates_v10_keys(tmp_path): + torch.manual_seed(6) + donor = _tiny_v10(tail_blocks=2, tail_width=8) + with torch.no_grad(): + for parameter in donor.parameters(): + parameter.add_(0.01) + path = tmp_path / "donor.pt" + torch.save({"schema_version": 4, "phase": 2, "step": 15000, + "ema_state_dict": {"shadow": donor.state_dict()}}, str(path)) + module = _tiny_v10(tail_blocks=2, tail_width=8, exposure_pregain=True, + global_attention_scales=(2, 3), global_context=True, photometric_head=True) + audit = v7.load_v6_warmstart(path, v7._file_sha256(path), module, weight_source="ema") + assert audit["fresh_head_keys"] > 0 + assert float(module.exposure_pregain.net[-1].weight.abs().sum()) == 0.0 + assert float(module.denoiser.down_globals[2].modulation.weight.abs().sum()) == 0.0 + assert torch.equal(module.denoiser.down_blocks[0][0].modulation.weight, + donor.denoiser.down_blocks[0][0].modulation.weight) + for prefix in ("exposure_pregain.", "denoiser.down_globals.", "denoiser.up_globals."): + assert prefix in v7._V7_FRESH_HEAD_PREFIXES + + +# ---- CLI / record / data ------------------------------------------------- # +def test_parser_and_architecture_record_v10_flags(): + args = v7.build_parser().parse_args([ + "--output-dir", "x", "--backbone", "uformer", "--timesteps", "2", + "--phase1-checkpoint", "p1.pt", "--phase1-sha256", "0" * 64, "--manifest", "m.json", + "--exposure-pregain", "--pregain-dropout", "0.1", "--pregain-max-log-gain", "1.2", + "--global-attention-scales", "2,3", "--extra-clean-root", "/a,/b", + ]) + assert args.exposure_pregain and args.pregain_dropout == 0.1 + assert v7._parse_scales(args.global_attention_scales) == (2, 3) + assert v7._parse_scales("") == () and v7._parse_scales(None) == () + arch = v7._v7_architecture(args) + assert arch["exposure_pregain"]["enabled"] is True + assert arch["exposure_pregain"]["max_log_gain"] == 1.2 + assert arch["global_attention_scales"] == [2, 3] + assert arch["data_aug"]["extra_clean_root"] == "/a,/b" + defaults = v7.build_parser().parse_args([ + "--output-dir", "x", "--phase1-checkpoint", "p1.pt", "--phase1-sha256", "0" * 64, "--manifest", "m.json", + ]) + assert not defaults.exposure_pregain and defaults.global_attention_scales == "" + + +def test_extra_clean_files_accepts_multiple_roots(tmp_path): + from PIL import Image + + a, b = tmp_path / "a", tmp_path / "b" / "nested" + a.mkdir(); b.mkdir(parents=True) + for folder, names in ((a, ("x.png", "y.jpg")), (b, ("z.png",))): + for name in names: + Image.new("RGB", (4, 4)).save(folder / name) + (a / "notes.txt").write_text("skip") + files = v4.extra_clean_files("%s, %s" % (a, tmp_path / "b"), balance=False) + assert sorted(f.name for f in files) == ["x.png", "y.jpg", "z.png"] + assert len(v4.extra_clean_files(str(a))) == 2 + # balanced (default): every root contributes the same number of entries + balanced = v4.extra_clean_files("%s,%s" % (a, tmp_path / "b")) + assert len(balanced) == 4 and sum(f.name == "z.png" for f in balanced) == 2 + with pytest.raises(ValueError): + v4.extra_clean_files(" , ") + with pytest.raises(FileNotFoundError): + v4.extra_clean_files(str(tmp_path / "missing")) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v11.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v11.py new file mode 100644 index 0000000000000000000000000000000000000000..ae4a6783ad3c6d76e5b79d92624f19bae8ed415c --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v11.py @@ -0,0 +1,260 @@ +"""v11: per-stage appended LeWin blocks (identity at warm start), gradient +checkpointing equivalence, warm-start allowlist for appended blocks.""" +import pytest +import torch + +import train_phase2_unified_v7 as v7 +from src.models.restoration.gated_graph_resshift_v5 import ExpertKappaSchedule +from src.models.restoration.graph_moe_v6 import MoEGraphConditionerV6 +from src.models.restoration.graph_resshift_v4 import ResidualShiftSchedule +from src.models.restoration.uformer_moe_v7 import UformerMoEUNetV7 +from tests.test_unified_v7 import _representation +from tests.test_unified_v10 import _rep_full_image + +DIMS = (8, 16, 24, 32) + + +def _denoiser(**kw) -> UformerMoEUNetV7: + return UformerMoEUNetV7(dims=DIMS, cond_dim=32, expert_rank=4, window=4, **kw) + + +def _module(denoiser: UformerMoEUNetV7, **extra) -> v7.Phase2UnifiedV7Module: + return v7.Phase2UnifiedV7Module( + conditioner=MoEGraphConditionerV6(cond_dim=32, stage_dims=DIMS), + denoiser=denoiser, + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.116), + expert_kappa=ExpertKappaSchedule((0.1, 0.04, 0.13, 0.4, 0.12), kappa_global=0.116, anneal_microsteps=0), + condition_mode="full", + **extra, + ) + + +def test_blocks_per_stage_accepts_int_or_sequence_and_validates(): + assert _denoiser().blocks_per_stage == (2, 2, 2, 2) + deep = _denoiser(blocks_per_stage=(2, 4, 6, 6)) + assert deep.blocks_per_stage == (2, 4, 6, 6) + assert [len(s) for s in deep.down_blocks] == [2, 4, 6, 6] + assert [len(s) for s in deep.up_blocks] == [6, 4, 2] # up path visits stages 2, 1, 0 + for bad in ((2, 4, 6), (0, 2, 2, 2), 0): + with pytest.raises(ValueError): + _denoiser(blocks_per_stage=bad) + + +def test_appended_blocks_are_identity_at_init(): + torch.manual_seed(0) + plain = _denoiser() + with torch.no_grad(): + for parameter in plain.parameters(): + parameter.add_(0.02) + deep = _denoiser(blocks_per_stage=(2, 4, 6, 6), global_attention_scales=(2, 3)) + missing = deep.load_state_dict(plain.state_dict(), strict=False).missing_keys + assert missing and all(k.startswith(("down_blocks.", "up_blocks.", "down_globals.", "up_globals.")) for k in missing) + condition = MoEGraphConditionerV6(cond_dim=32, stage_dims=DIMS)(_representation(2)) + u_t, u_y = torch.randn(2, 12, 16, 16), torch.randn(2, 12, 16, 16) + ts = torch.full((2,), 2, dtype=torch.long) + with torch.no_grad(): + assert torch.equal(plain(u_t, u_y, ts, condition), deep(u_t, u_y, ts, condition)) + deep.down_blocks[1][3].modulation.bias.fill_(0.2) + assert not torch.equal(plain(u_t, u_y, ts, condition), deep(u_t, u_y, ts, condition)) + + +def test_grad_checkpoint_matches_plain_forward_and_gradients(): + torch.manual_seed(1) + plain = _module(_denoiser(blocks_per_stage=(2, 3, 3, 3), global_attention_scales=(3,))) + with torch.no_grad(): + for parameter in plain.parameters(): + parameter.add_(0.01) + ckpt = _module(_denoiser(blocks_per_stage=(2, 3, 3, 3), global_attention_scales=(3,), grad_checkpoint=True)) + ckpt.load_state_dict(plain.state_dict()) + assert ckpt.denoiser.grad_checkpoint and not plain.denoiser.grad_checkpoint + clean, degraded = torch.rand(2, 3, 16, 16), torch.rand(2, 3, 16, 16) + rep = _rep_full_image() + ts = torch.full((2,), 2, dtype=torch.long) + noise = torch.randn(2, 12, 8, 8) + plain.train(); ckpt.train() + a = plain.training_loss(clean, degraded, rep, ts, noise).loss + b = ckpt.training_loss(clean, degraded, rep, ts, noise).loss + assert torch.allclose(a, b) + a.backward(); b.backward() + for (name, p), (_, q) in zip(plain.named_parameters(), ckpt.named_parameters()): + if p.grad is None: + assert q.grad is None, name + continue + assert q.grad is not None, name + assert torch.allclose(p.grad, q.grad, atol=1e-6, rtol=1e-5), name + # every transformer block received a gradient through the checkpointed path + assert ckpt.denoiser.down_blocks[1][2].modulation.weight.grad is not None + assert float(ckpt.denoiser.down_blocks[0][0].leff.inner[0].weight.grad.abs().sum()) > 0.0 + # eval / no-grad paths run without checkpointing and give the same output + ckpt.eval(); plain.eval() + with torch.no_grad(): + assert torch.allclose(plain.training_loss(clean, degraded, rep, ts, noise).loss, + ckpt.training_loss(clean, degraded, rep, ts, noise).loss) + + +def test_warmstart_accepts_appended_blocks_and_rejects_missing_base_blocks(tmp_path): + torch.manual_seed(2) + donor = _module(_denoiser()) + with torch.no_grad(): + for parameter in donor.parameters(): + parameter.add_(0.01) + path = tmp_path / "donor.pt" + torch.save({"schema_version": 4, "phase": 2, "step": 8000, + "ema_state_dict": {"shadow": donor.state_dict()}}, str(path)) + deep = _module(_denoiser(blocks_per_stage=(2, 4, 6, 6), global_attention_scales=(2, 3)), + exposure_pregain=True, global_context=True, photometric_head=True) + audit = v7.load_v6_warmstart(path, v7._file_sha256(path), deep, weight_source="ema") + assert audit["fresh_head_keys"] > 0 + assert torch.equal(deep.denoiser.down_blocks[1][1].modulation.weight, + donor.denoiser.down_blocks[1][1].modulation.weight) + assert float(deep.denoiser.down_blocks[1][3].modulation.weight.abs().sum()) == 0.0 + assert float(deep.denoiser.up_blocks[0][5].modulation.weight.abs().sum()) == 0.0 + # a donor DEEPER than the target has unexpected keys -> refused + shallow = _module(_denoiser()) + deep_path = tmp_path / "deep.pt" + torch.save({"schema_version": 4, "phase": 2, "step": 1, + "ema_state_dict": {"shadow": deep.state_dict()}}, str(deep_path)) + with pytest.raises(ValueError): + v7.load_v6_warmstart(deep_path, v7._file_sha256(deep_path), shallow, weight_source="ema") + # the rule only excuses indices beyond the donor's, never a base block + donor_keys = donor.state_dict() + assert v7._is_appended_block_key("denoiser.down_blocks.1.2.norm1.weight", donor_keys) + assert not v7._is_appended_block_key("denoiser.down_blocks.1.1.norm1.weight", donor_keys) + assert not v7._is_appended_block_key("denoiser.output_residual.weight", donor_keys) + + +def test_parser_records_v11_flags(): + base = ["--output-dir", "x", "--backbone", "uformer", "--timesteps", "2", + "--phase1-checkpoint", "p1.pt", "--phase1-sha256", "0" * 64, "--manifest", "m.json"] + args = v7.build_parser().parse_args(base + ["--extra-blocks-per-stage", "0,2,4,4", "--grad-checkpoint"]) + assert v7.blocks_per_stage(args) == (2, 4, 6, 6) and args.grad_checkpoint + arch = v7._v7_architecture(args) + assert arch["blocks_per_stage"] == [2, 4, 6, 6] and arch["grad_checkpoint"] is True + default = v7.build_parser().parse_args(base) + assert v7.blocks_per_stage(default) == (2, 2, 2, 2) and not default.grad_checkpoint + for bad in ("0,2,4", "0,-1,0,0"): + with pytest.raises(ValueError): + v7._parse_extra_blocks(bad) + + +def test_pregain_target_semantics(): + clean = torch.full((3, 3, 8, 8), 0.5) + degraded = torch.stack((torch.full((3, 8, 8), 0.5), torch.full((3, 8, 8), 0.05), torch.full((3, 8, 8), 0.8))) + target = v7.pregain_target(clean, degraded, max_log_gain=1.6) + assert abs(float(target[0])) < 1e-6 # identity pair -> 0 + assert abs(float(target[1]) - 1.6) < 1e-6 # x10 lift, clamped to the bound + assert float(target[2]) == 0.0 # clean darker than hazy input -> lift only, 0 + assert v7.pregain_target(clean, degraded, max_log_gain=0.3)[1] == 0.3 + + +def test_pregain_target_loss_trains_the_gain_and_is_off_by_default(): + torch.manual_seed(8) + plain = _module(_denoiser(), exposure_pregain=True) + supervised = _module(_denoiser(), exposure_pregain=True, pregain_target_weight=0.5) + supervised.load_state_dict(plain.state_dict()) + clean = torch.rand(2, 3, 16, 16) + degraded = (clean * 0.1).clamp(0, 1) # dark inputs -> target log-gain > 0 + rep = _rep_full_image() + ts = torch.full((2,), 2, dtype=torch.long) + noise = torch.randn(2, 12, 8, 8) + plain.train(); supervised.train() + a = plain.training_loss(clean, degraded, rep, ts, noise).loss + b = supervised.training_loss(clean, degraded, rep, ts, noise).loss + assert float(b) > float(a) # the target term is positive at gain 1 + b.backward() + grad = supervised.exposure_pregain.net[-1].weight.grad + assert grad is not None and float(grad.abs().sum()) > 0.0 + # weight 0 is bitwise the end-to-end objective + off = _module(_denoiser(), exposure_pregain=True, pregain_target_weight=0.0) + off.load_state_dict(plain.state_dict()); off.train() + assert torch.equal(off.training_loss(clean, degraded, rep, ts, noise).loss, a) + # CLI / record + args = v7.build_parser().parse_args([ + "--output-dir", "x", "--phase1-checkpoint", "p1.pt", "--phase1-sha256", "0" * 64, "--manifest", "m.json", + "--exposure-pregain", "--pregain-target-weight", "0.02", + ]) + assert v7._v7_architecture(args)["exposure_pregain"]["target_weight"] == 0.02 + + +def _reference_expert_bank(bank, features, gate): + """The pre-v11 data-dependent implementation (hard skips).""" + import torch.nn.functional as F + weights = gate.strengths * gate.top2_mask + if not bool(torch.any(weights > 0)): + return features + maps = F.interpolate(gate.spatial_gates, size=features.shape[-2:], mode="bilinear", align_corners=False) + residual = torch.zeros_like(features) + for index, expert in enumerate(bank.experts): + weight = weights[:, index] + if not bool(torch.any(weight > 0)): + continue + contribution = expert(features) * weight.view(-1, 1, 1, 1) + if index < bank.num_semantic: + contribution = contribution * maps[:, index: index + 1] + residual = residual + contribution + return features + residual + + +def test_expert_bank_always_uses_every_expert_and_matches_skipping_bitwise(): + from src.models.restoration.graph_moe_v6 import NodeGateOutput, SpatialExpertBank + + torch.manual_seed(9) + bank = SpatialExpertBank(16, rank=4) + with torch.no_grad(): + for expert in bank.experts: + expert[-1].weight.normal_(0, 0.1); expert[-1].bias.normal_(0, 0.1) + features = torch.randn(3, 16, 8, 8) + + def gate_with(mask): + strengths = torch.rand(3, 5) * mask + return NodeGateOutput(activations=strengths, strengths=strengths, top2_mask=mask, + spatial_gates=torch.rand(3, 4, 4, 4), prior=strengths, + anchor_loss=torch.zeros(()), correction_loss=torch.zeros(())) + + partial = gate_with(torch.tensor([[1., 1, 0, 0, 0], [0, 1, 0, 0, 1], [1, 0, 0, 0, 1]])) + none = gate_with(torch.zeros(3, 5)) + for gate in (partial, none): + assert torch.equal(bank(features, gate), _reference_expert_bank(bank, features, gate)) + # every expert parameter is in the graph even when its weight is zero everywhere + out = bank(features, partial).sum() + out.backward() + for expert in bank.experts: + assert expert[0].weight.grad is not None + + +def test_null_tokens_stay_in_the_graph_when_no_row_is_dropped(): + torch.manual_seed(10) + module = _module(_denoiser(), cond_dropout_prob=1e-9) # dropout on, but no row will drop + module.train() + clean, degraded = torch.rand(2, 3, 16, 16), torch.rand(2, 3, 16, 16) + rep = _rep_full_image() + ts = torch.full((2,), 2, dtype=torch.long) + noise = torch.randn(2, 12, 8, 8) + plain = _module(_denoiser(), cond_dropout_prob=0.0) + plain.load_state_dict({k: v for k, v in module.state_dict().items() if not k.startswith("null_")}, strict=False) + plain.train() + a = module.training_loss(clean, degraded, rep, ts, noise).loss + b = plain.training_loss(clean, degraded, rep, ts, noise).loss + assert torch.equal(a, b) # bitwise the conditioned objective + a.backward() + assert module.null_context.grad is not None and float(module.null_context.grad.abs().sum()) == 0.0 + assert module.null_global.grad is not None + + +def test_full_res_tail_runs_in_fp32_and_returns_finite_for_lifted_inputs(): + torch.manual_seed(11) + module = _module(_denoiser(), tail_blocks=6, tail_width=8) + with torch.no_grad(): + for parameter in module.full_res_tail.parameters(): + parameter.normal_(0, 0.5) # large weights so the gate products blow up in fp16 + module.eval() + image = torch.rand(1, 3, 32, 32) * 3.5 + degraded = torch.rand(1, 3, 32, 32) * 3.5 + rep = _rep_full_image(batch=1) + out = module.apply_image_head(image, degraded, rep) + assert out.dtype == torch.float32 and torch.isfinite(out).all() + # the tail result does not depend on the caller's dtype (it is computed in fp32) + assert torch.allclose(module.apply_image_head(image.to(torch.bfloat16).float(), degraded, rep), + module.apply_image_head(image.to(torch.bfloat16).float(), degraded, rep)) + # (the fp16 overflow itself is data/weight dependent — it was observed on + # LOLv2 whole-image inference with the trained tail — so it is not asserted here) diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v12.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v12.py new file mode 100644 index 0000000000000000000000000000000000000000..2ca577ef38b1019e90623fbcbc083ba1ae71530a --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v12.py @@ -0,0 +1,119 @@ +"""v12: global colour head (3x3 + bias, supervised least-squares target).""" +import pytest +import torch + +import train_phase2_unified_v7 as v7 +from tests.test_unified_v10 import _rep_full_image +from tests.test_unified_v11 import _denoiser, _module + + +def test_colour_head_identity_at_init_bounded_dose_and_dropout(): + torch.manual_seed(0) + head = v7.GlobalColourHead() + image = torch.rand(2, 3, 16, 16) + rep = _rep_full_image() + assert torch.equal(head(image, rep), image) + m, b = head.coefficients(image, rep) + assert torch.allclose(m, torch.eye(3).expand(2, 3, 3)) and torch.equal(b, torch.zeros(2, 3)) + with torch.no_grad(): + head.net[-1].weight.normal_(0, 0.5) + head.net[-1].bias.normal_(0, 0.5) + m, b = head.coefficients(image, rep) + assert (m.diagonal(dim1=1, dim2=2) > 0).all() and b.abs().max() <= 0.25 + 1e-6 + out = head(image, rep) + assert not torch.equal(out, image) and out.shape == image.shape + assert torch.equal(head(image, rep, dose=0.0), image) + dropped = head(image, rep, drop_mask=torch.tensor([True, False])) + assert torch.equal(dropped[0], image[0]) and torch.allclose(dropped[1], out[1]) + # y = M x + b applied per pixel + expected = torch.einsum("bij,bjhw->bihw", m, image) + b.view(-1, 3, 1, 1) + assert torch.allclose(out, expected, atol=1e-6) + + +def test_colour_target_recovers_a_known_global_transform(): + torch.manual_seed(1) + x = torch.rand(2, 3, 24, 24) + m_true = torch.tensor([[[1.4, 0.1, 0.0], [0.0, 1.2, 0.05], [0.1, 0.0, 0.9]], + [[0.8, 0.0, 0.2], [0.05, 1.5, 0.0], [0.0, 0.1, 1.1]]]) + b_true = torch.tensor([[0.05, -0.02, 0.01], [-0.03, 0.04, 0.0]]) + y = torch.einsum("bij,bjhw->bihw", m_true, x) + b_true.view(-1, 3, 1, 1) + m, b = v7.colour_target(x, y, samples=500) + assert torch.allclose(m, m_true, atol=2e-2) and torch.allclose(b, b_true, atol=2e-2) + + +def test_module_colour_head_identity_at_init_and_supervised_loss_trains_it(): + torch.manual_seed(2) + plain = _module(_denoiser()) + with_head = _module(_denoiser(), colour_head=True, colour_dropout=0.2) + with_head.load_state_dict(plain.state_dict(), strict=False) + plain.eval(); with_head.eval() + clean, degraded = torch.rand(2, 3, 16, 16), torch.rand(2, 3, 16, 16) + rep = _rep_full_image() + ts = torch.full((2,), 2, dtype=torch.long) + noise = torch.randn(2, 12, 8, 8) + assert torch.equal(plain.training_loss(clean, degraded, rep, ts, noise).loss, + with_head.training_loss(clean, degraded, rep, ts, noise).loss) + supervised = _module(_denoiser(), colour_head=True, colour_target_weight=0.5) + supervised.load_state_dict(plain.state_dict(), strict=False) + supervised.train() + loss = supervised.training_loss(clean, degraded, rep, ts, noise).loss + assert float(loss) > float(plain.training_loss(clean, degraded, rep, ts, noise).loss) + loss.backward() + grad = supervised.colour_head.net[-1].weight.grad + assert grad is not None and float(grad.abs().sum()) > 0.0 + + +def test_sampler_colour_dose_zero_matches_no_head_and_warmstart_allowlist(tmp_path): + from tests.test_unified_v7 import _FakePhase1 + + torch.manual_seed(3) + module = _module(_denoiser(), colour_head=True) + with torch.no_grad(): + module.colour_head.net[-1].weight.normal_(0, 0.3) + module.colour_head.net[-1].bias.fill_(0.3) + module.eval() + plain = _module(_denoiser()) + plain.load_state_dict({k: v for k, v in module.state_dict().items() if not k.startswith("colour_head.")}, strict=False) + plain.eval() + x = torch.rand(2, 3, 32, 32) + kwargs = dict(seed=5, record_ids=["a", "b"], amp_enabled=False) + with torch.no_grad(): + off = v7.sample_unified_restoration(module, _FakePhase1(), x, colour_dose=0.0, **kwargs) + ref = v7.sample_unified_restoration(plain, _FakePhase1(), x, **kwargs) + on = v7.sample_unified_restoration(module, _FakePhase1(), x, **kwargs) + assert torch.equal(off, ref) and not torch.equal(on, ref) + assert "colour_head." in v7._V7_FRESH_HEAD_PREFIXES + path = tmp_path / "donor.pt" + torch.save({"schema_version": 4, "phase": 2, "step": 1, "ema_state_dict": {"shadow": plain.state_dict()}}, str(path)) + fresh = _module(_denoiser(), colour_head=True) + audit = v7.load_v6_warmstart(path, v7._file_sha256(path), fresh, weight_source="ema") + assert audit["fresh_head_keys"] > 0 and float(fresh.colour_head.net[-1].weight.abs().sum()) == 0.0 + + +def test_parser_records_colour_head(): + args = v7.build_parser().parse_args([ + "--output-dir", "x", "--phase1-checkpoint", "p1.pt", "--phase1-sha256", "0" * 64, "--manifest", "m.json", + "--colour-head", "--colour-dropout", "0.1", "--colour-target-weight", "0.05", + ]) + rec = v7._v7_architecture(args)["colour_head"] + assert rec["enabled"] is True and rec["target_weight"] == 0.05 + + +def test_warmstart_drops_optional_head_weights_absent_from_the_target(tmp_path): + torch.manual_seed(4) + donor = _module(_denoiser(), photometric_head=True, exposure_pregain=True, colour_head=True) + with torch.no_grad(): + for parameter in donor.parameters(): + parameter.add_(0.01) + path = tmp_path / "donor.pt" + torch.save({"schema_version": 4, "phase": 2, "step": 8000, "ema_state_dict": {"shadow": donor.state_dict()}}, str(path)) + ablated = _module(_denoiser()) # no photometric / pre-gain / colour head + audit = v7.load_v6_warmstart(path, v7._file_sha256(path), ablated, weight_source="ema") + assert audit["dropped_head_keys"] > 0 and audit["fresh_head_keys"] == 0 + assert torch.equal(ablated.denoiser.down_blocks[0][0].modulation.weight, donor.denoiser.down_blocks[0][0].modulation.weight) + # a trunk key missing from the donor is still refused + broken = {k: v for k, v in donor.state_dict().items() if not k.startswith("denoiser.output_residual")} + bad = tmp_path / "bad.pt" + torch.save({"schema_version": 4, "phase": 2, "step": 1, "ema_state_dict": {"shadow": broken}}, str(bad)) + with pytest.raises(ValueError, match="missing"): + v7.load_v6_warmstart(bad, v7._file_sha256(bad), ablated, weight_source="ema") diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v7.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v7.py new file mode 100644 index 0000000000000000000000000000000000000000..80a75c098ddf99815e8a5767b7d042abae09124b --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v7.py @@ -0,0 +1,724 @@ +from types import SimpleNamespace + +import pytest +import torch + +import train_phase2_unified_v7 as v7 +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 + + +def _representation(batch: int = 2, content_hw: int = 4) -> SimpleNamespace: + return SimpleNamespace( + content_latent=torch.randn(batch, 128, content_hw, content_hw), + node_tokens=torch.randn(batch, 6, 256), + routing_probs=torch.softmax(torch.randn(batch, 6), dim=-1), + severity_coords=torch.sigmoid(torch.randn(batch, 4)), + spatial_maps=torch.rand(batch, 4, 4, 4), + unknown_residual=torch.randn(batch, 256), + global_condition=torch.randn(batch, 256), + ) + + +def _tiny_v7( + fine_vgg_weight: float = 0.0, fine_chroma_weight: float = 0.0, **extra +) -> v7.Phase2UnifiedV7Module: + dims = (8, 16, 24, 32) + return v7.Phase2UnifiedV7Module( + conditioner=MoEGraphConditionerV6(cond_dim=32, stage_dims=dims), + denoiser=MoEGraphResidualShiftUNetV6( + dims=dims, cond_dim=32, expert_rank=4 + ), + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.116), + expert_kappa=ExpertKappaSchedule( + (0.1, 0.04, 0.13, 0.4, 0.12), kappa_global=0.116, + anneal_microsteps=0, + ), + condition_mode="full", + fine_vgg_weight=fine_vgg_weight, + fine_chroma_weight=fine_chroma_weight, + **extra, + ) + + +def test_two_step_schedule_shape_and_near_clean_fine_state() -> None: + schedule = ResidualShiftSchedule(timesteps=2, kappa=0.116) + assert list(schedule.eta.shape) == [3] + # eta_1 is small: the fine state is close to clean, matching the + # refiner's input statistics. + assert float(schedule.eta[1]) < 0.05 + assert float(schedule.eta[2]) > 0.95 + + +def test_composite_loss_trains_both_chain_positions() -> None: + torch.manual_seed(0) + module = _tiny_v7() + module.train() + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + noise = torch.randn(2, 12, 8, 8) + result = module.training_loss( + clean, degraded, _representation(), torch.tensor([1, 2]), noise=noise + ) + assert torch.isfinite(result.loss) + assert float(result.reconstruction_loss) > 0 # coarse MSE + assert float(result.gate_loss) > 0 # fine L1 (+gate terms) + result.loss.backward() + grads = [ + p.grad for p in module.denoiser.parameters() if p.grad is not None + ] + assert grads and any(float(g.abs().sum()) > 0 for g in grads) + + +def test_composite_loss_is_deterministic_given_noise() -> None: + module = _tiny_v7() + module.eval() + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + rep = _representation(2) + noise = torch.randn(2, 12, 8, 8) + with torch.no_grad(): + a = module.training_loss(clean, degraded, rep, torch.tensor([1, 2]), noise=noise) + b = module.training_loss(clean, degraded, rep, torch.tensor([1, 2]), noise=noise) + assert torch.equal(a.loss, b.loss) + + +def test_perceptual_criterion_stays_out_of_state_dict() -> None: + module = _tiny_v7(fine_vgg_weight=0.1) + names = list(module.state_dict().keys()) + assert not any("_perceptual" in name or "features" in name for name in names) + parameters = {name for name, _ in module.named_parameters()} + assert not any("_perceptual" in name for name in parameters) + + +def test_v6_warmstart_skips_schedule_and_loads_everything_else(tmp_path) -> None: + donor = v6.Phase2MoEV6Module( + conditioner=MoEGraphConditionerV6(cond_dim=32, stage_dims=(8, 16, 24, 32)), + denoiser=MoEGraphResidualShiftUNetV6( + dims=(8, 16, 24, 32), cond_dim=32, expert_rank=4 + ), + schedule=ResidualShiftSchedule(timesteps=8, kappa=0.116), + expert_kappa=ExpertKappaSchedule( + (0.1, 0.04, 0.13, 0.4, 0.12), kappa_global=0.116, + anneal_microsteps=4, + ), + condition_mode="full", + ) + with torch.no_grad(): + for parameter in donor.parameters(): + parameter.add_(0.01) + checkpoint = { + "schema_version": 4, "phase": 2, "step": 3000, + "ema_state_dict": {"shadow": donor.state_dict()}, + } + path = tmp_path / "v6.pt" + torch.save(checkpoint, str(path)) + + module = _tiny_v7() + audit = v7.load_v6_warmstart( + path, v7._file_sha256(path), module, weight_source="ema" + ) + assert audit["schedule_reinitialized"] is True + assert audit["source_step"] == 3000 + # weights transferred; schedule stays two-step + assert torch.equal( + module.denoiser.input_projection.weight, + donor.denoiser.input_projection.weight, + ) + assert list(module.schedule.eta.shape) == [3] + + +def test_run_rejects_non_two_step_timesteps(tmp_path) -> None: + parser = v7.build_parser() + args = parser.parse_args( + [ + "--phase1-checkpoint", str(tmp_path / "p1.pt"), + "--phase1-sha256", "a" * 64, + "--manifest", str(tmp_path / "m.json"), + "--output-dir", str(tmp_path / "out"), + "--kappa", "0.116", + ] + ) + with pytest.raises(ValueError, match="two-step"): + v7.run(args) + + +def test_uformer_backbone_zero_init_identity_and_shapes() -> None: + from src.models.restoration.uformer_moe_v7 import UformerMoEUNetV7 + + dims = (8, 16, 24, 32) + unet = UformerMoEUNetV7(dims=dims, cond_dim=32, expert_rank=4, window=4) + module = _tiny_v7() + condition = module.build_condition(_representation(2)) + u_t = torch.randn(2, 12, 16, 16) + u_y = torch.randn(2, 12, 16, 16) + out = unet(u_t, u_y, torch.tensor([1, 2]), condition) + assert out.shape == u_t.shape + # zero-init residual head -> exact u_y anchor at initialization + assert torch.equal(out, u_y) + + +def test_window_attention_partition_roundtrip() -> None: + from src.models.restoration.uformer_moe_v7 import WindowAttention + + attention = WindowAttention(channels=16, window=4, heads=4) + x = torch.randn(2, 16, 8, 8) + out = attention(x) + assert out.shape == x.shape + # indivisible/small maps shrink the window instead of failing + small = attention(torch.randn(2, 16, 6, 6)) + assert small.shape == (2, 16, 6, 6) + + +def test_backbone_flag_and_scratch_gate(tmp_path) -> None: + parser = v7.build_parser() + base = [ + "--phase1-checkpoint", str(tmp_path / "p1.pt"), + "--phase1-sha256", "a" * 64, + "--manifest", str(tmp_path / "m.json"), + "--output-dir", str(tmp_path / "out"), + "--kappa", "0.116", "--timesteps", "2", + ] + args = parser.parse_args(base + ["--backbone", "uformer", "--allow-scratch"]) + assert args.backbone == "uformer" and args.allow_scratch + no_source = parser.parse_args(base) + with pytest.raises(ValueError, match="allow-scratch"): + v7._build_v7_restorer(no_source, torch.device("cpu")) + + +def test_rgb_to_uv_kills_luminance_keeps_chroma() -> None: + gray = torch.full((1, 3, 4, 4), 0.5) + uv = v7.rgb_to_uv(gray) + assert torch.allclose(uv, torch.zeros_like(uv), atol=1e-6) + red = torch.zeros(1, 3, 4, 4) + red[:, 0] = 1.0 + assert float(v7.rgb_to_uv(red).abs().sum()) > 0.1 + with pytest.raises(ValueError): + v7.rgb_to_uv(torch.rand(1, 12, 4, 4)) + + +def test_chroma_weight_zero_is_bitwise_baseline() -> None: + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + noise = torch.randn(2, 12, 8, 8) + representation = _representation() + losses = [] + for weight in (0.0, 0.0, 0.5): + torch.manual_seed(7) + module = _tiny_v7(fine_chroma_weight=weight) + module.eval() + with torch.no_grad(): + result = module.training_loss( + clean, degraded, representation, + torch.full((2,), 2, dtype=torch.long), noise=noise, + ) + losses.append(float(result.loss)) + assert losses[0] == losses[1] + assert losses[2] != losses[0] + + +def test_chroma_term_ignores_pure_brightness_error() -> None: + torch.manual_seed(11) + module = _tiny_v7(fine_chroma_weight=1.0) + target = torch.rand(2, 3, 16, 16) + brightness_shift = (target + 0.2).clamp(0.0, 1.0) + # A pure gray offset carries no chroma: the UV projection of the + # difference must vanish while the RGB L1 clearly does not. + offset_uv = v7.rgb_to_uv(target + 0.2) - v7.rgb_to_uv(target) + assert torch.allclose(offset_uv, torch.zeros_like(offset_uv), atol=1e-5) + assert float((brightness_shift - target).abs().mean()) > 0.05 + + +def test_architecture_records_chroma_objective() -> None: + parser = v7.build_parser() + args = parser.parse_args( + [ + "--phase1-checkpoint", "x.pt", "--phase1-sha256", "0" * 64, + "--manifest", "m.json", "--output-dir", "out", + "--fine-chroma-weight", "0.5", + ] + ) + architecture = v7._v7_architecture(args) + assert architecture["objective"]["fine_chroma_weight"] == 0.5 + assert architecture["objective"]["fine_chroma_space"] == "yuv_bt601_uv" + + +def test_luma_and_chroma_terms_are_complementary() -> None: + torch.manual_seed(3) + target = torch.rand(2, 3, 32, 32) * 0.5 + 0.25 + brightness_shift = (target + 0.15).clamp(0.0, 1.0) + # Pure exposure error: luma objective fires, chroma objective stays silent. + luma_gap = torch.nn.functional.l1_loss( + v7.pooled_luma(brightness_shift), v7.pooled_luma(target) + ) + chroma_gap = torch.nn.functional.l1_loss( + v7.rgb_to_uv(brightness_shift), v7.rgb_to_uv(target) + ) + assert float(luma_gap) > 0.1 + assert float(chroma_gap) < 1e-5 + # Pure hue error (swap R and B): chroma fires, pooled luma barely moves + # when the luma projection of the swap is compensated. + hue_shift = target[:, (2, 1, 0)] + hue_chroma = torch.nn.functional.l1_loss( + v7.rgb_to_uv(hue_shift), v7.rgb_to_uv(target) + ) + assert float(hue_chroma) > 0.01 + + +def test_rgb_to_luma_gray_fixed_point() -> None: + gray = torch.full((1, 3, 8, 8), 0.37) + luma = v7.rgb_to_luma(gray) + assert torch.allclose(luma, torch.full((1, 1, 8, 8), 0.37), atol=1e-6) + assert v7.pooled_luma(gray).shape == (1, 1, 8, 8) + with pytest.raises(ValueError): + v7.rgb_to_luma(torch.rand(1, 12, 4, 4)) + + +def test_luma_weight_zero_is_bitwise_baseline() -> None: + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + noise = torch.randn(2, 12, 8, 8) + representation = _representation() + losses = [] + for weight in (0.0, 0.0, 0.5): + torch.manual_seed(13) + module = _tiny_v7() + module.fine_luma_weight = weight + module.eval() + with torch.no_grad(): + result = module.training_loss( + clean, degraded, representation, + torch.full((2,), 2, dtype=torch.long), noise=noise, + ) + losses.append(float(result.loss)) + assert losses[0] == losses[1] + assert losses[2] != losses[0] + + +def test_architecture_records_luma_objective() -> None: + parser = v7.build_parser() + args = parser.parse_args( + [ + "--phase1-checkpoint", "x.pt", "--phase1-sha256", "0" * 64, + "--manifest", "m.json", "--output-dir", "out", + "--fine-luma-weight", "0.5", + ] + ) + architecture = v7._v7_architecture(args) + assert architecture["objective"]["fine_luma_weight"] == 0.5 + assert architecture["objective"]["fine_luma_space"] == "yuv_bt601_y_pool8" + + +def _head_module() -> v7.Phase2UnifiedV7Module: + torch.manual_seed(21) + return _tiny_v7(tail_blocks=2, tail_width=8, use_output_film=True) + + +def test_image_head_is_exact_identity_at_init() -> None: + module = _head_module() + image = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + out = module.apply_image_head(image, degraded, _representation()) + assert torch.equal(out, image) + + +def test_head_training_loss_bitwise_matches_headless_at_init() -> None: + clean = torch.rand(2, 3, 16, 16) + degraded = torch.rand(2, 3, 16, 16) + noise = torch.randn(2, 12, 8, 8) + representation = _representation() + torch.manual_seed(21) + headless = _tiny_v7() + torch.manual_seed(21) + headed = _tiny_v7(tail_blocks=2, tail_width=8, use_output_film=True) + for module in (headless, headed): + module.eval() + with torch.no_grad(): + a = headless.training_loss( + clean, degraded, representation, + torch.full((2,), 2, dtype=torch.long), noise=noise, + ) + b = headed.training_loss( + clean, degraded, representation, + torch.full((2,), 2, dtype=torch.long), noise=noise, + ) + assert float(a.loss) == float(b.loss) + + +def test_head_receives_gradients() -> None: + module = _head_module() + module.train() + result = module.training_loss( + torch.rand(2, 3, 16, 16), torch.rand(2, 3, 16, 16), + _representation(), torch.full((2,), 2, dtype=torch.long), + noise=torch.randn(2, 12, 8, 8), + ) + result.loss.backward() + tail_grads = [ + p.grad for p in module.full_res_tail.parameters() if p.grad is not None + ] + assert tail_grads and any(float(g.abs().sum()) > 0 for g in tail_grads) + assert module.output_film.weight.grad is not None + + +def test_v7_sampler_matches_v6_sampler_when_head_is_identity(monkeypatch) -> None: + module = _head_module() + module.eval() + degraded = torch.rand(2, 3, 16, 16) + + class _FakePhase1(torch.nn.Module): + def forward(self, x): + torch.manual_seed(5) + return _representation(x.shape[0]) + + phase1 = _FakePhase1() + monkeypatch.setattr( + v7.v4, "FrozenPhase1", _FakePhase1, raising=False + ) + with torch.no_grad(): + ours = v7.sample_unified_restoration( + module, phase1, degraded, seed=7, + record_ids=["a", "b"], amp_enabled=False, + ) + reference = v6.sample_moe_restoration( + module, phase1, degraded, seed=7, + record_ids=["a", "b"], amp_enabled=False, + ) + assert torch.equal(ours, reference) + + +def test_warmstart_tolerates_fresh_head_keys(tmp_path) -> None: + torch.manual_seed(21) + donor = _tiny_v7() + with torch.no_grad(): + for parameter in donor.parameters(): + parameter.add_(0.01) + checkpoint = { + "schema_version": 4, "phase": 2, "step": 8000, + "ema_state_dict": {"shadow": donor.state_dict()}, + } + path = tmp_path / "headless.pt" + torch.save(checkpoint, str(path)) + + torch.manual_seed(21) + module = _tiny_v7(tail_blocks=2, tail_width=8, use_output_film=True) + audit = v7.load_v6_warmstart( + path, v7._file_sha256(path), module, weight_source="ema" + ) + assert audit["fresh_head_keys"] > 0 + assert torch.equal( + module.denoiser.input_projection.weight, + donor.denoiser.input_projection.weight, + ) + # the fresh head stayed an identity + assert float(module.full_res_tail.out.weight.abs().sum()) == 0.0 + assert float(module.output_film.weight.abs().sum()) == 0.0 + + +def test_architecture_records_image_head() -> None: + parser = v7.build_parser() + args = parser.parse_args( + [ + "--phase1-checkpoint", "x.pt", "--phase1-sha256", "0" * 64, + "--manifest", "m.json", "--output-dir", "out", + "--full-res-tail-blocks", "3", "--output-film", + ] + ) + head = v7._v7_architecture(args)["image_head"] + assert {k: head[k] for k in ("full_res_tail_blocks", "full_res_tail_width", "output_film")} == { + "full_res_tail_blocks": 3, + "full_res_tail_width": 48, + "output_film": True, + } + + +# ---------------------------------------------------------------- DGF / coarse-to-fine +from src.models.restoration.uformer_moe_v7 import UformerMoEUNetV7 + + +def _tiny_uformer_v7(**extra) -> v7.Phase2UnifiedV7Module: + dims = (8, 16, 24, 32) + return v7.Phase2UnifiedV7Module( + conditioner=MoEGraphConditionerV6(cond_dim=32, stage_dims=dims), + denoiser=UformerMoEUNetV7( + dims=dims, cond_dim=32, expert_rank=4, window=4, + pyramid_heads=extra.pop("pyramid_heads", False), + ), + schedule=ResidualShiftSchedule(timesteps=2, kappa=0.116), + expert_kappa=ExpertKappaSchedule( + (0.1, 0.04, 0.13, 0.4, 0.12), kappa_global=0.116, + anneal_microsteps=0, + ), + condition_mode="full", + **extra, + ) + + +class _FakePhase1(torch.nn.Module): + def forward(self, x): + torch.manual_seed(5) + return _representation(x.shape[0]) + + +def test_pyramid_heads_are_exact_identity_at_init() -> None: + torch.manual_seed(31) + plain = _tiny_uformer_v7() + torch.manual_seed(31) + pyramid = _tiny_uformer_v7(pyramid_heads=True) + condition = plain.build_condition(_representation(2)) + u_t = torch.randn(2, 12, 32, 32) + u_y = torch.randn(2, 12, 32, 32) + t = torch.full((2,), 2, dtype=torch.long) + with torch.no_grad(): + a = plain.predict_x0(u_t, u_y, t, condition) + b, bands = pyramid.predict_x0_pyramid(u_t, u_y, t, condition) + assert torch.equal(a, b) + assert len(bands) == 3 + # every band estimate equals the area-downsampled anchor at init + for estimate in bands: + anchor = torch.nn.functional.interpolate( + u_y, size=estimate.shape[-2:], mode="area" + ) + assert torch.allclose(estimate, anchor, atol=1e-6) + assert bands[0].shape[-1] < bands[1].shape[-1] < bands[2].shape[-1] + + +def test_pyramid_supervision_is_positive_and_trains_heads() -> None: + torch.manual_seed(32) + module = _tiny_uformer_v7(pyramid_heads=True) + module.train() + result = module.training_loss( + torch.rand(2, 3, 32, 32), torch.rand(2, 3, 32, 32), + _representation(), torch.full((2,), 2, dtype=torch.long), + noise=torch.randn(2, 12, 16, 16), + ) + result.loss.backward() + grads = [ + head[-1].weight.grad for head in module.denoiser.pyramid_heads + ] + assert all(g is not None for g in grads) + assert any(float(g.abs().sum()) > 0 for g in grads) + + +def test_null_condition_tokens_and_dropout() -> None: + torch.manual_seed(33) + module = _tiny_uformer_v7(cond_dropout_prob=0.15) + assert module.null_context.shape == (1, 8, 32) + assert float(module.null_context.abs().sum()) == 0.0 + condition = module.build_condition(_representation(2)) + nulled = module.null_condition(condition) + assert torch.equal(nulled.context, torch.zeros_like(condition.context)) + assert torch.equal(nulled.global_vector, torch.zeros_like(condition.global_vector)) + # gate / content / spatial untouched + assert torch.equal(nulled.content, condition.content) + half = module.null_condition(condition, torch.tensor([True, False])) + assert torch.equal(half.context[1], condition.context[1]) + assert torch.equal(half.context[0], torch.zeros_like(condition.context[0])) + + +def test_dropout_is_inactive_in_eval_and_active_in_train() -> None: + clean = torch.rand(2, 3, 32, 32) + degraded = torch.rand(2, 3, 32, 32) + noise = torch.randn(2, 12, 16, 16) + rep = _representation() + t = torch.full((2,), 2, dtype=torch.long) + torch.manual_seed(34) + base = _tiny_uformer_v7() + torch.manual_seed(34) + dropped = _tiny_uformer_v7(cond_dropout_prob=1.0) + # At init the adaLN modulation and cross-attention outputs are zero-init, + # so the trunk ignores its condition; perturb both models identically so + # the condition actually matters. + for module in (base, dropped): + with torch.no_grad(): + for name, parameter in module.named_parameters(): + if not name.startswith("null_"): + parameter.add_(0.02) + base.eval(); dropped.eval() + with torch.no_grad(): + a = base.training_loss(clean, degraded, rep, t, noise=noise).loss + b = dropped.training_loss(clean, degraded, rep, t, noise=noise).loss + assert float(a) == float(b) # eval: no dropout + dropped.train() + with torch.no_grad(): + c = dropped.training_loss(clean, degraded, rep, t, noise=noise).loss + assert float(c) != float(a) # train with p=1: every row nulled + + +def test_dose_one_equals_plain_and_dose_zero_equals_null() -> None: + torch.manual_seed(35) + module = _tiny_uformer_v7(cond_dropout_prob=0.15) + # Perturb everything so the condition matters (zero-init modulation and + # attention outputs make the trunk condition-blind at init). + with torch.no_grad(): + for parameter in module.parameters(): + parameter.add_(0.02) + module.eval() + phase1 = _FakePhase1() + degraded = torch.rand(2, 3, 32, 32) + kwargs = dict(seed=7, record_ids=["a", "b"], amp_enabled=False) + with torch.no_grad(): + plain = v7.sample_unified_restoration(module, phase1, degraded, **kwargs) + one = v7.sample_unified_restoration(module, phase1, degraded, dose=1.0, **kwargs) + zero = v7.sample_unified_restoration(module, phase1, degraded, dose=0.0, **kwargs) + half = v7.sample_unified_restoration(module, phase1, degraded, dose=0.5, **kwargs) + assert torch.equal(plain, one) + assert not torch.equal(zero, plain) + assert not torch.equal(half, plain) and not torch.equal(half, zero) + + +def test_warmstart_tolerates_pyramid_and_null_keys(tmp_path) -> None: + torch.manual_seed(36) + donor = _tiny_uformer_v7() + with torch.no_grad(): + for parameter in donor.parameters(): + parameter.add_(0.01) + path = tmp_path / "donor.pt" + torch.save({ + "schema_version": 4, "phase": 2, "step": 8000, + "ema_state_dict": {"shadow": donor.state_dict()}, + }, str(path)) + torch.manual_seed(36) + module = _tiny_uformer_v7(pyramid_heads=True, cond_dropout_prob=0.15) + audit = v7.load_v6_warmstart(path, v7._file_sha256(path), module, weight_source="ema") + assert audit["fresh_head_keys"] >= 8 # 3 heads x (norm w,b + conv w,b) + 2 null + assert torch.equal( + module.denoiser.input_projection.weight, donor.denoiser.input_projection.weight + ) + + +def test_identity_pairs_helper() -> None: + import train_phase2_graph_resshift_v4 as v4 + + clean = torch.rand(4, 3, 8, 8) + degraded = torch.rand(4, 3, 8, 8) + assert torch.equal(v4.apply_identity_pairs(degraded, clean, 0.0), degraded) + assert torch.equal(v4.apply_identity_pairs(degraded, clean, 1.0), clean) + + +def test_architecture_records_dose_and_pyramid() -> None: + parser = v7.build_parser() + args = parser.parse_args([ + "--phase1-checkpoint", "x.pt", "--phase1-sha256", "0" * 64, + "--manifest", "m.json", "--output-dir", "out", + "--pyramid-heads", "--cond-dropout-prob", "0.15", + "--identity-pair-prob", "0.1", + ]) + arch = v7._v7_architecture(args) + assert arch["coarse_to_fine"] == {"pyramid_heads": True, "pyramid_loss_weights": [0.1, 0.2, 0.3]} + assert arch["dose"]["cond_dropout_prob"] == 0.15 + assert arch["dose"]["identity_pair_prob"] == 0.1 + + +def test_full_dropout_model_samples_unconditionally() -> None: + torch.manual_seed(37) + module = _tiny_uformer_v7(cond_dropout_prob=1.0) + with torch.no_grad(): + for parameter in module.parameters(): + parameter.add_(0.02) + module.eval() + phase1 = _FakePhase1() + degraded = torch.rand(2, 3, 32, 32) + kwargs = dict(seed=7, record_ids=["a", "b"], amp_enabled=False) + with torch.no_grad(): + auto = v7.sample_unified_restoration(module, phase1, degraded, **kwargs) + original = module.build_condition + module.build_condition = lambda rep: module.null_condition(original(rep)) + module.cond_dropout_prob = 0.0 # disable the auto-null path + manual = v7.sample_unified_restoration(module, phase1, degraded, **kwargs) + assert torch.equal(auto, manual) + + +# ---------------------------------------------------------------- global context / clean prior +def test_global_context_is_identity_at_init_and_learns() -> None: + torch.manual_seed(41) + module = _tiny_uformer_v7(global_context=True) + module.eval() + rep = _representation(2) + base_bundle = module.build_condition(rep) + rep.full_frame = _representation(2) + with_full = module.build_condition(rep) + assert torch.equal(base_bundle.context, with_full.context) + assert torch.equal(base_bundle.global_vector, with_full.global_vector) + with torch.no_grad(): + module.ctx_full_proj.weight.add_(0.01) + changed = module.build_condition(rep) + assert not torch.equal(base_bundle.context, changed.context) + + +def test_sampler_accepts_full_frame_and_matches_without_projection() -> None: + torch.manual_seed(42) + module = _tiny_uformer_v7(global_context=True) + with torch.no_grad(): + for name, parameter in module.named_parameters(): + if "full_proj" not in name: + parameter.add_(0.02) + module.eval() + phase1 = _FakePhase1() + degraded = torch.rand(2, 3, 32, 32) + kwargs = dict(seed=7, record_ids=["a", "b"], amp_enabled=False) + assert v7.sample_unified_restoration.accepts_full_frame is True + with torch.no_grad(): + plain = v7.sample_unified_restoration(module, phase1, degraded, **kwargs) + with_full = v7.sample_unified_restoration( + module, phase1, degraded, full_degraded=torch.rand(2, 3, 32, 32), **kwargs + ) + assert torch.equal(plain, with_full) # zero-init projections + + +def test_warmstart_tolerates_tail_extension_and_full_proj(tmp_path) -> None: + torch.manual_seed(43) + donor = _tiny_uformer_v7(tail_blocks=2, tail_width=8) + with torch.no_grad(): + for parameter in donor.parameters(): + parameter.add_(0.01) + path = tmp_path / "donor.pt" + torch.save({"schema_version": 4, "phase": 2, "step": 8000, + "ema_state_dict": {"shadow": donor.state_dict()}}, str(path)) + torch.manual_seed(43) + module = _tiny_uformer_v7(tail_blocks=4, tail_width=8, global_context=True) + audit = v7.load_v6_warmstart(path, v7._file_sha256(path), module, weight_source="ema") + assert audit["fresh_head_keys"] > 0 + assert torch.equal(module.full_res_tail.body[0].conv1.weight, donor.full_res_tail.body[0].conv1.weight) + # appended blocks are identities (zero beta/gamma) and the projections are zero + assert float(module.full_res_tail.body[3].beta.abs().sum()) == 0.0 + assert float(module.ctx_full_proj.weight.abs().sum()) == 0.0 + + +def test_synthetic_noise_pairs_and_identity_mask() -> None: + import train_phase2_graph_resshift_v4 as v4 + + clean = torch.rand(4, 3, 16, 16) + degraded = clean.clone() + full_c = torch.rand(4, 3, 16, 16) + full_d = full_c.clone() + g1 = torch.Generator().manual_seed(5) + g2 = torch.Generator().manual_seed(5) + d1, f1, m1 = v4.synthetic_noise_pairs(degraded, clean, 1.0, g1, full_d, full_c) + d2, f2, m2 = v4.synthetic_noise_pairs(degraded, clean, 1.0, g2, full_d, full_c) + assert torch.equal(d1, d2) and torch.equal(f1, f2) and bool(m1.all()) + assert float((d1 - clean).abs().mean()) > 1e-3 + assert float((f1 - full_c).abs().mean()) > 1e-3 + assert torch.equal(clean, degraded) # inputs not mutated + assert float(d1.min()) >= 0.0 and float(d1.max()) <= 1.0 + d0, f0, m0 = v4.synthetic_noise_pairs(degraded, clean, 0.0, torch.Generator().manual_seed(1), full_d, full_c) + assert d0 is degraded and f0 is full_d and not bool(m0.any()) + assert not bool(v4.identity_pair_mask(4, 0.0, clean.device).any()) + assert bool(v4.identity_pair_mask(4, 1.0, clean.device).all()) + + +def test_architecture_records_global_context_and_noise_pairs() -> None: + parser = v7.build_parser() + args = parser.parse_args([ + "--phase1-checkpoint", "x.pt", "--phase1-sha256", "0" * 64, + "--manifest", "m.json", "--output-dir", "out", + "--global-context", "--noise-pair-prob", "0.2", + ]) + arch = v7._v7_architecture(args) + assert arch["global_context"] is True + assert arch["data_aug"]["noise_pair_prob"] == 0.2 diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v8.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v8.py new file mode 100644 index 0000000000000000000000000000000000000000..ef99cc843193dfb301bb08bfe78fb263d9f666af --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_unified_v8.py @@ -0,0 +1,134 @@ +"""v8: global exposure controllable head, HV chroma loss space, exposure- +diverse identity pairs.""" +from types import SimpleNamespace + +import torch + +import train_phase2_graph_resshift_v4 as v4 +import train_phase2_unified_v7 as v7 +from tests.test_unified_v7 import _representation, _tiny_v7 + + +def _rep(batch=2, with_state=True, with_full=False): + rep = _representation(batch) + rep.global_condition = torch.randn(batch, v7.GLOBAL_CONDITION_DIM) + if with_state: + rep.photometric_state = torch.randn(batch, v7.PHOTOMETRIC_STATE_DIM) + if with_full: + full = _representation(batch) + full.global_condition = torch.randn(batch, v7.GLOBAL_CONDITION_DIM) + full.photometric_state = torch.randn(batch, v7.PHOTOMETRIC_STATE_DIM) + rep.full_frame = full + return rep + + +def test_photometric_head_is_exact_identity_at_init_and_bounded(): + torch.manual_seed(0) + head = v7.GlobalPhotometricHead() + image = torch.rand(2, 3, 16, 16) + for rep in (_rep(with_state=True), _rep(with_state=False), _rep(with_full=True)): + assert torch.equal(head(image, rep), image) + # perturb -> non-identity, but bounded by tanh + with torch.no_grad(): + head.net[-1].weight.fill_(5.0) + head.net[-1].bias.fill_(5.0) + log_gain, bias = head.coefficients(_rep(with_full=True)) + assert log_gain.abs().max() <= 0.7 + 1e-6 and bias.abs().max() <= 0.2 + 1e-6 + out_full = head(image, _rep(with_full=True)) + assert not torch.equal(out_full, image) + + +def test_photometric_head_dose_and_dropout(): + torch.manual_seed(1) + head = v7.GlobalPhotometricHead() + with torch.no_grad(): + head.net[-1].weight.normal_(0, 0.5) + head.net[-1].bias.normal_(0, 0.5) + rep = _rep() + image = torch.rand(2, 3, 8, 8) + assert torch.equal(head(image, rep, dose=0.0), image) + half = head(image, rep, dose=0.5) + full = head(image, rep, dose=1.0) + assert not torch.allclose(half, full) + dropped = head(image, rep, drop_mask=torch.tensor([True, False])) + assert torch.equal(dropped[0], image[0]) and torch.allclose(dropped[1], full[1]) + + +def test_module_head_identity_and_chroma_space(): + torch.manual_seed(2) + plain = _tiny_v7(fine_chroma_weight=0.5) + with_head = _tiny_v7(fine_chroma_weight=0.5, photometric_head=True, photometric_dropout=0.3) + with_head.load_state_dict(plain.state_dict(), strict=False) + clean, degraded = torch.rand(2, 3, 16, 16), torch.rand(2, 3, 16, 16) + rep = _rep() + ts = torch.full((2,), 2, dtype=torch.long) + noise = torch.randn(2, 12, 8, 8) + plain.eval(); with_head.eval() + a = plain.training_loss(clean, degraded, rep, ts, noise).loss + b = with_head.training_loss(clean, degraded, rep, ts, noise).loss + assert torch.allclose(a, b), "zero-init head must not change the loss" + hv = _tiny_v7(fine_chroma_weight=0.5, fine_chroma_space="hv") + hv.load_state_dict(plain.state_dict(), strict=False) + hv.eval() + c = hv.training_loss(clean, degraded, rep, ts, noise).loss + assert torch.isfinite(c) and not torch.allclose(a, c) + planes = hv.chroma_planes(torch.rand(1, 3, 8, 8)) + assert planes.shape == (1, 2, 8, 8) + + +def test_module_head_gets_gradients_in_training_mode(): + torch.manual_seed(3) + module = _tiny_v7(photometric_head=True, photometric_dropout=0.0) + with torch.no_grad(): + module.photometric_head.net[-1].weight.normal_(0, 0.1) + module.train() + clean, degraded = torch.rand(2, 3, 16, 16), torch.rand(2, 3, 16, 16) + out = module.training_loss(clean, degraded, _rep(), torch.full((2,), 2, dtype=torch.long), torch.randn(2, 12, 8, 8)) + out.loss.backward() + assert module.photometric_head.net[0].weight.grad is not None + + +def test_exposure_diverse_identity_keeps_pairs_exact_and_deterministic(): + torch.manual_seed(4) + clean = torch.rand(4, 3, 8, 8) + full = torch.rand(4, 3, 8, 8) + identity = torch.tensor([True, False, True, False]) + extra_crop, extra_full = torch.rand(4, 3, 8, 8), torch.rand(4, 3, 8, 8) + gen = torch.Generator().manual_seed(9) + new_clean, new_full = v4.exposure_diverse_identity( + clean, full, identity, gen, jitter=0.9, extra_crop=extra_crop, extra_full=extra_full, extra_prob=1.0 + ) + # non-identity rows untouched + assert torch.equal(new_clean[1], clean[1]) and torch.equal(new_full[3], full[3]) + # identity rows changed (swapped + jittered) and in range + assert not torch.equal(new_clean[0], clean[0]) + assert new_clean.min() >= 0 and new_clean.max() <= 1 + gen2 = torch.Generator().manual_seed(9) + again, _ = v4.exposure_diverse_identity( + clean, full, identity, gen2, jitter=0.9, extra_crop=extra_crop, extra_full=extra_full, extra_prob=1.0 + ) + assert torch.equal(new_clean, again) + # jitter only (no pool): identity rows are scaled copies of clean + gen3 = torch.Generator().manual_seed(1) + scaled, _ = v4.exposure_diverse_identity(clean, None, identity, gen3, jitter=0.5) + ratio = scaled[0] / clean[0].clamp_min(1e-6) + assert ratio.std() < 0.05 or scaled[0].max() >= 1.0 + # no-op paths + same, same_full = v4.exposure_diverse_identity(clean, full, torch.zeros(4, dtype=torch.bool), gen3, jitter=0.9) + assert torch.equal(same, clean) and torch.equal(same_full, full) + + +def test_parser_and_architecture_record_v8_flags(): + parser = v7.build_parser() + args = parser.parse_args([ + "--output-dir", "x", "--backbone", "uformer", "--timesteps", "2", + "--phase1-checkpoint", "p1.pt", "--phase1-sha256", "0" * 64, "--manifest", "m.json", + "--photometric-head", "--photometric-dropout", "0.15", "--fine-chroma-space", "hv", + "--identity-exposure-jitter", "0.9", "--extra-clean-root", "/pool", "--extra-clean-prob", "0.5", + ]) + assert args.photometric_head and args.fine_chroma_space == "hv" and args.identity_exposure_jitter == 0.9 + arch = v7._v7_architecture(args) + assert arch["image_head"]["photometric_head"] is True + assert arch["objective"]["fine_chroma_space"] == "hvi_hv_k0.2" + assert arch["data_aug"]["extra_clean_root"] == "/pool" + assert "photometric_head." in v7._V7_FRESH_HEAD_PREFIXES diff --git a/dataset/phase1_noise_20260906/trial_code_staging/tests/test_visualize_phase2_tasks_v4.py b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_visualize_phase2_tasks_v4.py new file mode 100644 index 0000000000000000000000000000000000000000..53fb78bc5a2e4a9d97cad296c06c5daf87014996 --- /dev/null +++ b/dataset/phase1_noise_20260906/trial_code_staging/tests/test_visualize_phase2_tasks_v4.py @@ -0,0 +1,180 @@ +from __future__ import annotations + +import copy + +import pytest + +from visualize_phase2_tasks_v4 import ( + Candidate, + _evaluation_history, + select_quantile_samples, + validate_checkpoint_pair, + validate_control_checkpoint, + validate_degraded_baseline, +) + + +def _candidate(index, clean_hash, psnr): + return Candidate( + index=index, + domain="haze", + record_id="record-%02d" % index, + source_id="source-%02d" % index, + clean_content_sha256=clean_hash, + baseline_psnr=float(psnr), + ) + + +def _event(step, macro_psnr, condition="full"): + baseline = { + "per_domain": { + domain: {"count": 1, "psnr": 10.0, "ssim": 0.5} + for domain in ("haze", "lowlight", "noise", "rain") + } + } + return { + "event": "evaluation", + "condition": condition, + "step": step, + "macro_psnr": macro_psnr, + "macro_ssim": 0.6, + "metrics": {"degraded_baseline": baseline, "restored": {}}, + } + + +def _checkpoint(step=1000, condition="full"): + contract = { + "condition_mode": condition, + "data_plan": {"crop_size": 256, "eval_seed": 20260830}, + } + history = [_event(0, 18.0, condition), _event(1000, 22.0, condition)] + if step > 1000: + history.append(_event(step, 21.0, condition)) + return { + "schema_version": 4, + "phase": 2, + "condition_mode": condition, + "step": step, + "contract": contract, + "architecture": {"dims": [64, 128, 192, 256], "cond_dim": 256}, + "schedule_config": { + "timesteps": 8, + "eta_end": 0.99, + "min_noise": 0.2, + "power": 0.3, + "kappa": 0.1, + }, + "phase1_sha256": "a" * 64, + "phase1_metadata": {"schema_version": 2}, + "train_digest": "b" * 64, + "val_digest": "c" * 64, + "init_model_hash": "d" * 64, + "ema_state_dict": {"shadow": {"weight": object()}}, + "history": history, + } + + +def test_quantile_selection_deduplicates_clean_content_and_is_unique(): + candidates = [ + _candidate(0, "a" * 64, 8.0), + _candidate(1, "a" * 64, 10.0), + _candidate(2, "a" * 64, 12.0), + _candidate(3, "b" * 64, 20.0), + _candidate(4, "c" * 64, 30.0), + ] + + selected = select_quantile_samples(candidates) + + assert [item.candidate.record_id for item in selected] == [ + "record-01", + "record-03", + "record-04", + ] + assert len({item.candidate.clean_content_sha256 for item in selected}) == 3 + assert [item.quantile_label for item in selected] == [ + "P25 harder", + "P50 median", + "P75 easier", + ] + + +def test_quantile_selection_requires_enough_distinct_clean_images(): + candidates = [ + _candidate(0, "a" * 64, 8.0), + _candidate(1, "a" * 64, 9.0), + _candidate(2, "b" * 64, 10.0), + ] + + with pytest.raises(ValueError, match="distinct clean"): + select_quantile_samples(candidates) + + +def test_checkpoint_pair_requires_identical_contract_and_ema(): + best = _checkpoint(1000) + final = _checkpoint(20000) + validate_checkpoint_pair(best, final) + + mismatched = copy.deepcopy(final) + mismatched["contract"]["data_plan"]["eval_seed"] += 1 + with pytest.raises(ValueError, match="contract mismatch"): + validate_checkpoint_pair(best, mismatched) + + no_ema = copy.deepcopy(final) + no_ema["ema_state_dict"] = {} + with pytest.raises(ValueError, match="EMA shadow"): + validate_checkpoint_pair(best, no_ema) + + +def test_checkpoint_pair_rejects_a_non_argmax_best(): + best = _checkpoint(1000) + final = _checkpoint(20000) + final["history"][1]["macro_psnr"] = 21.0 + final["history"][-1]["macro_psnr"] = 22.0 + + with pytest.raises(ValueError, match="argmax"): + validate_checkpoint_pair(best, final) + + +def test_control_checkpoint_is_null_and_contract_matched(): + full = _checkpoint(20000) + control = _checkpoint(1000, condition="null") + validate_control_checkpoint(control, full) + + wrong_condition = copy.deepcopy(control) + wrong_condition["condition_mode"] = "full" + with pytest.raises(ValueError, match="null conditioning"): + validate_control_checkpoint(wrong_condition, full) + + wrong_seed = copy.deepcopy(control) + wrong_seed["contract"]["data_plan"]["eval_seed"] += 1 + with pytest.raises(ValueError, match="contract"): + validate_control_checkpoint(wrong_seed, full) + + +def test_degraded_baseline_validation_detects_drift(): + checkpoint = _checkpoint(20000) + counts = {domain: 1 for domain in ("haze", "lowlight", "noise", "rain")} + summary = { + domain: {"psnr": 10.0, "ssim": 0.5} + for domain in ("haze", "lowlight", "noise", "rain") + } + validate_degraded_baseline(checkpoint, summary, counts) + + summary["rain"]["psnr"] += 0.01 + with pytest.raises(ValueError, match="rain degraded psnr baseline drift"): + validate_degraded_baseline(checkpoint, summary, counts) + + +def test_evaluation_history_requires_unique_sorted_steps(): + checkpoint = { + "history": [ + {"event": "train", "step": 1}, + {"event": "evaluation", "step": 0}, + {"event": "evaluation", "step": 500}, + ] + } + assert [item["step"] for item in _evaluation_history(checkpoint)] == [0, 500] + + checkpoint["history"].append({"event": "evaluation", "step": 500}) + with pytest.raises(ValueError, match="unique and sorted"): + _evaluation_history(checkpoint)