Release LumaRestore and the LOL-v2 Real benchmark
Browse filesFiles changed (25)
- .gitattributes+1
- .gitignoreAdded+10
- LICENSEAdded+21
- MODEL_CARD.mdAdded+82
- README.mdAdded+82
- checkpoints/cnn/config.jsonAdded+6
- checkpoints/cnn/model.safetensorsAdded+3
- checkpoints/cnn/training.jsonAdded+16
- checkpoints/iterative/config.jsonAdded+6
- checkpoints/iterative/model.safetensorsAdded+3
- checkpoints/iterative/training.jsonAdded+16
- luma_restore/__init__.pyAdded+1
- luma_restore/data.pyAdded+104
- luma_restore/evaluate.pyAdded+185
- luma_restore/infer.pyAdded+68
- luma_restore/metrics.pyAdded+26
- luma_restore/model.pyAdded+143
- luma_restore/train.pyAdded+125
- pyproject.tomlAdded+21
- reports/cnn/history.jsonAdded+82
- reports/iterative/history.jsonAdded+82
- reports/quality-compute.pngAdded
- reports/render_figures.pyAdded+84
- reports/test-results.jsonAdded
- tests/test_model.pyAdded+60
32 unmodified lines33343532 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -textreports/quality-compute.png filter=lfs diff=lfs merge=lfs -text
12345678910.venv/__pycache__/*.py[cod]*.egg-info/.DS_Storedata/runs/.release/runs-*.log/build/123456789101112131415161718192021MIT License
Copyright (c) 2026 LumaRestore contributors
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in allcopies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THESOFTWARE.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182---license: mitpipeline_tag: image-to-imagelibrary_name: pytorchtags:- low-light-image-enhancement- image-restoration- adaptive-inference- safetensors---
# LumaRestore
**Can a compact low-light enhancer use fewer restoration passes on images that have already stabilized?** LumaRestore is a trainable RGB image restoration model with one shared update block and up to three passes. The 18,677-parameter model and a 17,595-parameter CNN control were trained from scratch on a MacBook Pro with an Apple M5 Max.
## Results on 100 official test pairs

| Method | PSNR ↑ (dB) | SSIM ↑ | Mean passes | Median latency (ms) ↓ || :--- | ---: | ---: | ---: | ---: || Low-light input | 9.72 | 0.199 | 0.00 | — || Validation-tuned gamma | 17.56 | 0.624 | 0.00 | 0.18 || Single-pass CNN | 17.88 | **0.689** | 1.00 | 0.62 || Shared block · one pass | **18.40** | 0.664 | 1.00 | 1.21 || Shared block · two passes | 17.26 | 0.642 | 2.00 | 1.62 || Shared block · three passes | 17.53 | 0.643 | 3.00 | 2.04 || Regional adaptive exit | 18.35 | 0.663 | 1.02 | 1.71 || Whole-image adaptive exit | 18.29 | 0.662 | 1.05 | 1.67 |
- **One fixed pass had the highest PSNR at 18.40 dB.** Additional passes reduced mean PSNR on this test split. The single-pass CNN reached the highest SSIM at 0.689 and the lowest learned-model latency at 0.62 ms.- **Regional early exit averaged 1.02 passes.** It stopped after one pass on 98 images and after two on 2. It improved on fixed three-pass PSNR by 0.82 dB (95% paired bootstrap interval +0.64 to +1.00 dB). A fixed one-pass call was faster and slightly better on average.- **The regional and whole-image policies scored similarly.** The paired PSNR difference was +0.06 dB (95% interval −0.07 to +0.18 dB). The selected validation thresholds were 0.295 regional and 0.265 whole-image, with a tuned gamma exponent of 0.250.
[Per-image results, calibration curves, and split manifests](reports/test-results.json) · [Iterative training history](reports/iterative/history.json) · [CNN training history](reports/cnn/history.json) · [Training configuration](checkpoints/iterative/training.json)
## Architecture
LumaRestore starts with a square-root exposure lift and carries two state variables across stages: a spatial log-gain map and an additive RGB detail residual. A small convolutional block operates at half resolution and predicts three updates. A smoothed gain map changes exposure, an RGB residual changes detail, and a learned gate limits the detail update in shadows using a local luminance prior. The same weights are reused at every stage. [Model implementation](luma_restore/model.py)
The early-exit policy measures output change in a 4 × 4 grid. It uses the largest mean absolute RGB change in any cell, so a small active region can keep refinement going. For comparison, a second policy measures whole-image mean change. Both use the same trained weights, leave early only when their statistic is below a threshold, and are calibrated separately under the same validation budget.
The project takes inspiration from the iterative separation of illumination and content in GRUN by Rihan Zhang, Fengyang Xiao, Yuhan Chen, Chunming He, and Sina Farsiu. Here the changes are a shared lightweight update block, an explicit shadow gate, and a validation-calibrated regional exit rule. Adaptive restoration and low-light early exit have prior work. This release evaluates this particular combination. [GRUN](https://arxiv.org/abs/2611.31690) · [Restore, Assess, Repeat](https://openaccess.thecvf.com/content/CVPR2026/papers/Chen_Restore_Assess_Repeat_A_Unified_Framework_for_Iterative_Image_Restoration_CVPR_2026_paper.pdf) · [Adaptive Low Light Enhancement](https://arxiv.org/abs/2504.00400)
## Evaluation protocol
The dataset is LOL-v2 Real, introduced by Wenhan Yang, Haofeng Huang, Wenjing Wang, Shiqi Wang, and Jiaying Liu. We use the pinned mirror revision documented in the code. Of the 689 original training pairs, the first 609 filenames form the training set and the last 80 form the validation set. The 100 official test pairs are evaluated at their native 600 × 400 resolution. The split is by filename, so scene independence within the original training split has not been established. [Dataset authors](https://github.com/flyywh/CVPR-2020-Semi-Low-Light) · [Pinned mirror](https://huggingface.co/datasets/okhater/lolv2-real/tree/db2979107f7c22d372c6e4f1b06fd6203069af0a)
Both networks train from random initialization with the same aligned 128 × 128 crops, seed, AdamW schedule, and image loss. The one-pass CNN learns a residual over the same exposure initialization. The iterative model receives deep supervision at all three exits with loss weights 0.20, 0.30, and 0.50. The checkpoint uses best mean validation PSNR at a 224-pixel long side. The gamma exponent and halt thresholds use full-resolution validation pairs. The thresholds minimize average stage count subject to a 0.15 dB validation PSNR budget relative to three fixed stages.
PSNR uses RGB in [0, 1]. SSIM uses an 11 × 11 Gaussian window and averages over valid windows and RGB channels. Evaluation averages per-image scores and applies no target-dependent exposure correction. Inference medians use batch size one, warmed-up Metal execution, and synchronization before and after the model call. They exclude loading, data transfer, and metric computation. Bootstrap intervals resample test images and represent evaluation variation for these weights.
## Run inference
Python 3.11+ is required. Install the project in a virtual environment and pass an RGB image to the CLI.
```shpython -m venv .venv. .venv/bin/activatepython -m pip install -e .python -m luma_restore.infer --checkpoint checkpoints/iterative --stages 1 input.jpg output.png```
The default runs all three stages. Use `--stages 1` or `--stages 2` for a fixed shorter run; use `--threshold 0.295 --exit-stat regional` to reproduce the regional policy. The CLI accepts `--device cpu`, `mps`, or `cuda`. Safetensors inference preserves image dimensions.
## Reproduce
```shpython -m luma_restore.data data/lolv2-realpython -m luma_restore.train data/lolv2-real runs/reproduce --device auto \ --epochs 16 --batch-size 20 --crop 128 --repeats 2 --seed 42python -m luma_restore.evaluate data/lolv2-real runs/reproduce reports/reproduced.json --device autopython -m unittest discover -s tests -v```
To benchmark the released weights directly, pass `checkpoints` in place of `runs/reproduce` to the evaluation command.
## Scope
This is a one-seed experiment on LOL-v2 Real. It does not establish robustness to other cameras, RAW inputs, or degradations beyond low light. Small output changes can signal a stable but incorrect result. The adaptive policies introduce a host synchronization after each check, so stage savings and wall-clock savings need separate measurement. The CNN and iterative variants differ in computation and structure, so their comparison measures the whole design. The fixed and adaptive exits use identical iterative weights.
Dataset images are obtained separately from the pinned mirror. The benchmark figure can be rebuilt with `python -m pip install -e '.[report]'` and `python reports/render_figures.py`. The code and checkpoints are released under the MIT license.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182---license: mitpipeline_tag: image-to-imagelibrary_name: pytorchtags:- low-light-image-enhancement- image-restoration- adaptive-inference- safetensors---
# LumaRestore
**Can a compact low-light enhancer use fewer restoration passes on images that have already stabilized?** LumaRestore is a trainable RGB image restoration model with one shared update block and up to three passes. The 18,677-parameter model and a 17,595-parameter CNN control were trained from scratch on a MacBook Pro with an Apple M5 Max.
## Results on 100 official test pairs

| Method | PSNR ↑ (dB) | SSIM ↑ | Mean passes | Median latency (ms) ↓ || :--- | ---: | ---: | ---: | ---: || Low-light input | 9.72 | 0.199 | 0.00 | — || Validation-tuned gamma | 17.56 | 0.624 | 0.00 | 0.18 || Single-pass CNN | 17.88 | **0.689** | 1.00 | 0.62 || Shared block · one pass | **18.40** | 0.664 | 1.00 | 1.21 || Shared block · two passes | 17.26 | 0.642 | 2.00 | 1.62 || Shared block · three passes | 17.53 | 0.643 | 3.00 | 2.04 || Regional adaptive exit | 18.35 | 0.663 | 1.02 | 1.71 || Whole-image adaptive exit | 18.29 | 0.662 | 1.05 | 1.67 |
- **One fixed pass had the highest PSNR at 18.40 dB.** Additional passes reduced mean PSNR on this test split. The single-pass CNN reached the highest SSIM at 0.689 and the lowest learned-model latency at 0.62 ms.- **Regional early exit averaged 1.02 passes.** It stopped after one pass on 98 images and after two on 2. It improved on fixed three-pass PSNR by 0.82 dB (95% paired bootstrap interval +0.64 to +1.00 dB). A fixed one-pass call was faster and slightly better on average.- **The regional and whole-image policies scored similarly.** The paired PSNR difference was +0.06 dB (95% interval −0.07 to +0.18 dB). The selected validation thresholds were 0.295 regional and 0.265 whole-image, with a tuned gamma exponent of 0.250.
[Per-image results, calibration curves, and split manifests](reports/test-results.json) · [Iterative training history](reports/iterative/history.json) · [CNN training history](reports/cnn/history.json) · [Training configuration](checkpoints/iterative/training.json)
## Architecture
LumaRestore starts with a square-root exposure lift and carries two state variables across stages: a spatial log-gain map and an additive RGB detail residual. A small convolutional block operates at half resolution and predicts three updates. A smoothed gain map changes exposure, an RGB residual changes detail, and a learned gate limits the detail update in shadows using a local luminance prior. The same weights are reused at every stage. [Model implementation](luma_restore/model.py)
The early-exit policy measures output change in a 4 × 4 grid. It uses the largest mean absolute RGB change in any cell, so a small active region can keep refinement going. For comparison, a second policy measures whole-image mean change. Both use the same trained weights, leave early only when their statistic is below a threshold, and are calibrated separately under the same validation budget.
The project takes inspiration from the iterative separation of illumination and content in GRUN by Rihan Zhang, Fengyang Xiao, Yuhan Chen, Chunming He, and Sina Farsiu. Here the changes are a shared lightweight update block, an explicit shadow gate, and a validation-calibrated regional exit rule. Adaptive restoration and low-light early exit have prior work. This release evaluates this particular combination. [GRUN](https://arxiv.org/abs/2611.31690) · [Restore, Assess, Repeat](https://openaccess.thecvf.com/content/CVPR2026/papers/Chen_Restore_Assess_Repeat_A_Unified_Framework_for_Iterative_Image_Restoration_CVPR_2026_paper.pdf) · [Adaptive Low Light Enhancement](https://arxiv.org/abs/2504.00400)
## Evaluation protocol
The dataset is LOL-v2 Real, introduced by Wenhan Yang, Haofeng Huang, Wenjing Wang, Shiqi Wang, and Jiaying Liu. We use the pinned mirror revision documented in the code. Of the 689 original training pairs, the first 609 filenames form the training set and the last 80 form the validation set. The 100 official test pairs are evaluated at their native 600 × 400 resolution. The split is by filename, so scene independence within the original training split has not been established. [Dataset authors](https://github.com/flyywh/CVPR-2020-Semi-Low-Light) · [Pinned mirror](https://huggingface.co/datasets/okhater/lolv2-real/tree/db2979107f7c22d372c6e4f1b06fd6203069af0a)
Both networks train from random initialization with the same aligned 128 × 128 crops, seed, AdamW schedule, and image loss. The one-pass CNN learns a residual over the same exposure initialization. The iterative model receives deep supervision at all three exits with loss weights 0.20, 0.30, and 0.50. The checkpoint uses best mean validation PSNR at a 224-pixel long side. The gamma exponent and halt thresholds use full-resolution validation pairs. The thresholds minimize average stage count subject to a 0.15 dB validation PSNR budget relative to three fixed stages.
PSNR uses RGB in [0, 1]. SSIM uses an 11 × 11 Gaussian window and averages over valid windows and RGB channels. Evaluation averages per-image scores and applies no target-dependent exposure correction. Inference medians use batch size one, warmed-up Metal execution, and synchronization before and after the model call. They exclude loading, data transfer, and metric computation. Bootstrap intervals resample test images and represent evaluation variation for these weights.
## Run inference
Python 3.11+ is required. Install the project in a virtual environment and pass an RGB image to the CLI.
```shpython -m venv .venv. .venv/bin/activatepython -m pip install -e .python -m luma_restore.infer --checkpoint checkpoints/iterative --stages 1 input.jpg output.png```
The default runs all three stages. Use `--stages 1` or `--stages 2` for a fixed shorter run; use `--threshold 0.295 --exit-stat regional` to reproduce the regional policy. The CLI accepts `--device cpu`, `mps`, or `cuda`. Safetensors inference preserves image dimensions.
## Reproduce
```shpython -m luma_restore.data data/lolv2-realpython -m luma_restore.train data/lolv2-real runs/reproduce --device auto \ --epochs 16 --batch-size 20 --crop 128 --repeats 2 --seed 42python -m luma_restore.evaluate data/lolv2-real runs/reproduce reports/reproduced.json --device autopython -m unittest discover -s tests -v```
To benchmark the released weights directly, pass `checkpoints` in place of `runs/reproduce` to the evaluation command.
## Scope
This is a one-seed experiment on LOL-v2 Real. It does not establish robustness to other cameras, RAW inputs, or degradations beyond low light. Small output changes can signal a stable but incorrect result. The adaptive policies introduce a host synchronization after each check, so stage savings and wall-clock savings need separate measurement. The CNN and iterative variants differ in computation and structure, so their comparison measures the whole design. The fixed and adaptive exits use identical iterative weights.
Dataset images are obtained separately from the pinned mirror. The benchmark figure can be rebuilt with `python -m pip install -e '.[report]'` and `python reports/render_figures.py`. The code and checkpoints are released under the MIT license.123456{ "format": 1, "variant": "cnn", "width": 24, "stages": 1}123version https://git-lfs.github.com/spec/v1oid sha256:a530b3c47387937069b38076ebd9f52f419777ebfa55161d195d5ff4d91841f3size 7117212345678910111213141516{ "epochs": 16, "width": 24, "crop": 128, "repeats": 2, "lr": 0.001, "seed": 42, "batch_size": 20, "validation_count": 80, "parameters": 17595, "device": "mps", "torch_version": "2.13.0", "selected_epoch": 3, "wall_seconds": 39.52420066704508, "checkpoint_selection": "maximum mean validation PSNR, downscaled to 224 px long side"}123456{ "format": 1, "variant": "iterative", "width": 24, "stages": 3}123version https://git-lfs.github.com/spec/v1oid sha256:904363faac5e90b525bbab85a7fd7bb4791bbaaf2f19e5d39e9155680ad5b692size 7549212345678910111213141516{ "epochs": 16, "width": 24, "crop": 128, "repeats": 2, "lr": 0.001, "seed": 42, "batch_size": 20, "validation_count": 80, "parameters": 18677, "device": "mps", "torch_version": "2.13.0", "selected_epoch": 4, "wall_seconds": 18.43127599998843, "checkpoint_selection": "maximum mean validation PSNR, downscaled to 224 px long side"}1"""Compact iterative enhancement for low-light RGB photographs."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104"""Read paired LOL-v2 Real images and take reproducible aligned training crops."""
from dataclasses import dataclassfrom pathlib import Pathimport random
import numpy as npfrom PIL import Image, ImageOpsimport torchfrom torch.utils.data import Dataset
DATASET = "okhater/lolv2-real"REVISION = "db2979107f7c22d372c6e4f1b06fd6203069af0a"
@dataclass(frozen=True)class Pair: name: str low: Path target: Path
def split_pairs(root, split): source, target = Path(root) / split / "Input", Path(root) / split / "GT" low = {path.name: path for path in source.glob("*.png")} normal = {path.name: path for path in target.glob("*.png")} if not low or low.keys() != normal.keys(): raise ValueError(f"Expected matching PNG filenames in {source} and {target}") return [Pair(name, low[name], normal[name]) for name in sorted(low)]
def protocol(root, validation_count=80): original_train = split_pairs(root, "Train") test = split_pairs(root, "Test") if not 1 <= validation_count < len(original_train): raise ValueError("Validation count must leave at least one training pair") if {pair.name for pair in original_train} & {pair.name for pair in test}: raise ValueError("Train and test filenames overlap") return original_train[:-validation_count], original_train[-validation_count:], test
def read_rgb(path): with Image.open(path) as image: return np.array(ImageOps.exif_transpose(image).convert("RGB"), dtype=np.uint8)
def read_pair(pair): low, normal = read_rgb(pair.low), read_rgb(pair.target) if low.shape != normal.shape: raise ValueError(f"Unaligned pair: {pair.name}") return low, normal
def pixels(images): return images.movedim(-1, -3).float() / 255.0
class Crops(Dataset): def __init__(self, pairs, crop_size, repeats, seed): self.images = [read_pair(pair) for pair in pairs] self.crop_size = crop_size self.repeats = repeats self.seed = seed self.epoch = 0 if any(min(low.shape[:2]) < crop_size for low, _ in self.images): raise ValueError("Crop is larger than a training image")
def __len__(self): return len(self.images) * self.repeats
def __getitem__(self, index): low, normal = self.images[index % len(self.images)] rng = random.Random(self.seed + self.epoch * len(self) + index) size = self.crop_size y = rng.randrange(low.shape[0] - size + 1) x = rng.randrange(low.shape[1] - size + 1) flip = rng.getrandbits(1)
def take(image): crop = image[y:y + size, x:x + size] if flip: crop = crop[:, ::-1] return torch.from_numpy(np.ascontiguousarray(crop))
return take(low), take(normal)
def download(root): from huggingface_hub import snapshot_download
return snapshot_download( DATASET, repo_type="dataset", revision=REVISION, token=False, local_dir=root, allow_patterns=["Train/*/*.png", "Test/*/*.png", "LICENSE"], max_workers=12, )
if __name__ == "__main__": import argparse
parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("root", type=Path) args = parser.parse_args() print(download(args.root))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185"""Calibrate adaptive exits on validation and benchmark on the official test split."""
import argparsefrom collections import Counterimport jsonfrom pathlib import Pathimport statisticsimport time
import numpy as npimport torch
from .data import DATASET, REVISION, protocolfrom .infer import device_forfrom .metrics import psnr, ssimfrom .model import activity, initial_image, load_modelfrom .train import tensor_pair
TOLERANCE_DB = 0.15GAMMAS = np.linspace(0.2, 0.85, num=27)THRESHOLDS = np.linspace(0.0, 0.3, num=61)
def select_exit(changes, quality, threshold): selected = np.full(len(changes), changes.shape[1] - 1, dtype=int) for exit_index in range(changes.shape[1] - 2, -1, -1): selected[changes[:, exit_index] <= threshold] = exit_index return float(quality[np.arange(len(quality)), selected].mean()), float((selected + 1).mean())
def choose_exit(changes, quality, fixed_score): curve = [ {"threshold": float(threshold), "psnr": score, "mean_stages": mean} for threshold in THRESHOLDS for score, mean in [select_exit(changes, quality, threshold)] ] eligible = [item for item in curve if item["psnr"] >= fixed_score - TOLERANCE_DB] if not eligible: raise RuntimeError("No validated exit threshold met the PSNR budget") choice = min(eligible, key=lambda item: (item["mean_stages"], -item["psnr"], item["threshold"])) return choice, curve
@torch.inference_mode()def calibrate(model, validation, device): changes = {"regional": [], "global": []} quality, gamma_psnr = [], [] for pair in validation: low, target = tensor_pair(pair, device) outputs = model.trajectory(low) earlier = [initial_image(low), *outputs[:-1]] for statistic, values in changes.items(): values.append(torch.cat([activity(a, b, statistic) for a, b in zip(earlier, outputs)]).tolist()) quality.append(torch.cat([psnr(output, target) for output in outputs]).tolist()) gamma_psnr.append(torch.cat([psnr(low.pow(float(gamma)), target) for gamma in GAMMAS]).tolist()) quality = np.array(quality) fixed_score = float(quality[:, -1].mean()) selected = { name: choose_exit(np.array(values), quality, fixed_score) for name, values in changes.items() } gamma_means = np.array(gamma_psnr).mean(axis=0) gamma_index = gamma_means.argmax().item() return { "tolerance_db": TOLERANCE_DB, "fixed_validation_psnr": fixed_score, "adaptive": {name: choice for name, (choice, _) in selected.items()}, "gamma": float(GAMMAS[gamma_index]), "gamma_validation_psnr": float(gamma_means[gamma_index]), "threshold_curves": {name: curve for name, (_, curve) in selected.items()}, }
def sync(device): if device == "mps": torch.mps.synchronize() elif device.startswith("cuda"): torch.cuda.synchronize(device)
def paired_difference(results, first, second, key): deltas = np.array([row[second][key] - row[first][key] for row in results]) draws = np.random.default_rng(42).choice(deltas, (2_000, len(deltas)), replace=True) return { "mean": float(deltas.mean()), "ci95": np.quantile(draws.mean(axis=1), [0.025, 0.975]).tolist(), }
@torch.inference_mode()def benchmark(model, cnn, test, device, calibration): gamma = calibration["gamma"]
def adaptive(low, statistic): return model.restore(low, calibration["adaptive"][statistic]["threshold"], statistic)
def conditions(low): return { "input": lambda: (low, 0), "gamma": lambda: (low.pow(gamma), 0), "cnn": lambda: (cnn(low), 1), "stage_1": lambda: (model.trajectory(low, 1)[-1], 1), "stage_2": lambda: (model.trajectory(low, 2)[-1], 2), "stage_3": lambda: (model(low), 3), "adaptive_regional": lambda: adaptive(low, "regional"), "adaptive_global": lambda: adaptive(low, "global"), }
warm, _ = tensor_pair(test[0], device) for _ in range(3): for call in conditions(warm).values(): call() sync(device)
results = [] for index, pair in enumerate(test): low, target = tensor_pair(pair, device) calls = list(conditions(low).items()) offset = index % len(calls) result = {"name": pair.name} for name, compute in calls[offset:] + calls[:offset]: sync(device) t0 = time.perf_counter() output, stages = compute() sync(device) latency = 1000 * (time.perf_counter() - t0) result[name] = { "psnr": psnr(output, target).item(), "ssim": ssim(output, target).item(), "stages": stages, "milliseconds": latency, } results.append(result) summary = {} for name in conditions(warm): rows = [row[name] for row in results] median = statistics.median(r["milliseconds"] for r in rows) summary[name] = { "psnr": statistics.mean(r["psnr"] for r in rows), "ssim": statistics.mean(r["ssim"] for r in rows), "median_ms": median, "mean_stages": statistics.mean(r["stages"] for r in rows), "exit_counts": dict(sorted(Counter(r["stages"] for r in rows).items())), } return { "device": device, "images": len(results), "summary": summary, "regional_minus_stage_3_psnr": paired_difference(results, "stage_3", "adaptive_regional", "psnr"), "regional_minus_global_psnr": paired_difference(results, "adaptive_global", "adaptive_regional", "psnr"), "stage_3_minus_cnn_psnr": paired_difference(results, "cnn", "stage_3", "psnr"), "per_image": results, }
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("data", type=Path) parser.add_argument("checkpoints", type=Path) parser.add_argument("output", type=Path) parser.add_argument("--device", default="auto") args = parser.parse_args() torch.set_num_threads(4) device = device_for(args.device) training = json.loads((args.checkpoints / "iterative/training.json").read_text()) train, validation, test = protocol(args.data, training["validation_count"]) model = load_model(args.checkpoints / "iterative", device) cnn = load_model(args.checkpoints / "cnn", device) calibration = calibrate(model, validation, device) print(json.dumps(calibration["adaptive"]), flush=True) report = benchmark(model, cnn, test, device, calibration) report["calibration"] = calibration report["dataset"] = {"repo": DATASET, "revision": REVISION} report["splits"] = { name: [pair.name for pair in pairs] for name, pairs in zip(("train", "validation", "test"), (train, validation, test)) } args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, indent=2) + "\n") print(json.dumps(report["summary"], indent=2), flush=True)
if __name__ == "__main__": main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768"""Enhance an RGB image with a fixed or adaptive number of stages."""
import argparseimport jsonfrom pathlib import Path
from PIL import Imageimport torch
from .data import pixels, read_rgbfrom .model import Iterative, load_model
def device_for(device): if device != "auto": return device if torch.backends.mps.is_available(): return "mps" return "cuda" if torch.cuda.is_available() else "cpu"
def save_image(image, path): array = image[0].detach().cpu().clamp(0, 1).mul(255).round().byte().permute(1, 2, 0).numpy() Image.fromarray(array).save(path)
def main(): parser = argparse.ArgumentParser(description=__doc__) source = parser.add_mutually_exclusive_group(required=True) source.add_argument("--checkpoint", type=Path) source.add_argument("--hub") parser.add_argument("--revision") parser.add_argument("--variant", choices=("iterative", "cnn"), default="iterative") parser.add_argument("--device", default="auto") controls = parser.add_mutually_exclusive_group() controls.add_argument("--threshold", type=float) controls.add_argument("--stages", type=int) parser.add_argument("--exit-stat", choices=("regional", "global"), default="regional") parser.add_argument("input", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args() torch.set_num_threads(4) device = device_for(args.device) checkpoint = args.checkpoint if args.hub: from huggingface_hub import snapshot_download
folder = f"checkpoints/{args.variant}" root = snapshot_download(args.hub, revision=args.revision, allow_patterns=[f"{folder}/*"]) checkpoint = Path(root) / folder model = load_model(checkpoint, device) low = pixels(torch.from_numpy(read_rgb(args.input)))[None].to(device) if not isinstance(model, Iterative) and (args.stages is not None or args.threshold is not None): parser.error("Stage controls require the iterative checkpoint") with torch.inference_mode(): if args.threshold is not None: result, stages = model.restore(low, args.threshold, args.exit_stat) elif isinstance(model, Iterative): outputs = model.trajectory(low, args.stages) result, stages = outputs[-1], len(outputs) else: result, stages = model(low), 1 save_image(result, args.output) print(json.dumps({"output": str(args.output), "device": device, "stages": stages}))
if __name__ == "__main__": main()1234567891011121314151617181920212223242526"""Per-image PSNR and valid-window Gaussian SSIM on unscaled RGB outputs."""
import torchimport torch.nn.functional as F
def psnr(prediction, target): mse = (prediction - target).square().flatten(1).mean(dim=1) return -10 * torch.log10(mse.clamp_min(1e-12))
def ssim(prediction, target): axis = torch.arange(11, device=prediction.device, dtype=prediction.dtype) - 5 weights = (-(axis / 1.5).square() / 2).softmax(dim=0) kernel = (weights[:, None] * weights[None, :]).expand(3, 1, 11, 11).contiguous()
def smooth(image): return F.conv2d(image, kernel, groups=3)
p_mean, t_mean = smooth(prediction), smooth(target) p_var = smooth(prediction.square()) - p_mean.square() t_var = smooth(target.square()) - t_mean.square() cov = smooth(prediction * target) - p_mean * t_mean numerator = (2 * p_mean * t_mean + 0.01**2) * (2 * cov + 0.03**2) denominator = (p_mean.square() + t_mean.square() + 0.01**2) * (p_var + t_var + 0.03**2) return (numerator / denominator).flatten(1).mean(dim=1)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""Shared illumination/detail updates and a single-pass convolutional control."""
from dataclasses import asdict, dataclassimport jsonimport mathfrom pathlib import Path
import torchfrom torch import nnimport torch.nn.functional as Ffrom safetensors.torch import load_file, save_file
@dataclass(frozen=True)class Config: variant: str width: int = 24 stages: int = 3
def __post_init__(self): if self.variant not in {"iterative", "cnn"} or self.width < 4 or self.stages < 1: raise ValueError("Unknown variant or invalid model dimensions")
def initial_image(low): return low.clamp_min(1e-6).sqrt()
def resize_like(tensor, image): return F.interpolate(tensor, size=image.shape[-2:], mode="bilinear", align_corners=False)
def activity(previous, estimate, statistic="regional"): """Measure the output change for a whole image or its most active region.""" change = (estimate - previous).abs().mean(dim=1, keepdim=True) if statistic == "global": return change.flatten(1).mean(dim=1) if statistic != "regional": raise ValueError("Unknown exit statistic") height, width = change.shape[-2:] pad_h, pad_w = (-height) % 4, (-width) % 4 if pad_h or pad_w: change = F.pad(change, (0, pad_w, 0, pad_h), mode="replicate") cells = ((height + pad_h) // 4, (width + pad_w) // 4) return F.avg_pool2d(change, cells).flatten(1).amax(dim=1)
def stack(in_channels, width, out_channels): return nn.Sequential( nn.Conv2d(in_channels, width, 3, stride=2, padding=1), nn.SiLU(), nn.Conv2d(width, width, 3, padding=1), nn.SiLU(), nn.Conv2d(width, width, 3, padding=1), nn.SiLU(), nn.Conv2d(width, width, 3, padding=1), nn.SiLU(), nn.Conv2d(width, out_channels, 3, padding=1), )
class CNN(nn.Module): def __init__(self, config): super().__init__() self.config = config self.predict = stack(6, config.width, 3)
def forward(self, low): base = initial_image(low) residual = resize_like(self.predict(torch.cat((low, base), dim=1)), low) return (base + residual).clamp(0.0, 1.0)
class Iterative(nn.Module): def __init__(self, config): super().__init__() self.config = config self.update = stack(9, config.width, 5) self.register_buffer("luma_weights", torch.tensor([0.2126, 0.7152, 0.0722]).view(1, 3, 1, 1), persistent=False)
def start(self, low): base = initial_image(low) luminance = (low * self.luma_weights).sum(dim=1, keepdim=True) local = F.avg_pool2d(luminance, 5, stride=1, padding=2, count_include_pad=False) darkness = 1 - local.clamp(0, 1).sqrt() detail_input = (luminance - local).abs() zeros = torch.zeros_like(luminance) return (base, darkness, detail_input), (base, zeros, torch.zeros_like(base))
def step(self, low, context, state): base, darkness, detail_input = context estimate, log_gain, detail = state features = self.update(torch.cat((low, estimate, log_gain, darkness, detail_input), dim=1)) raw_gain, raw_detail, raw_gate = features.split((1, 3, 1), dim=1) smooth_gain = F.avg_pool2d(raw_gain, 7, stride=1, padding=3, count_include_pad=False) log_gain = (log_gain + 0.35 * resize_like(smooth_gain.tanh(), low)).clamp(-1.0, 1.2) gate = (resize_like(raw_gate, low) - 1.5 * darkness).sigmoid() detail = detail + 0.25 * gate * resize_like(raw_detail.tanh(), low) estimate = (base * log_gain.exp() + detail).clamp(0.0, 1.0) return estimate, log_gain, detail
def trajectory(self, low, stages=None): count = self.config.stages if stages is None else stages if not 1 <= count <= self.config.stages: raise ValueError("Stage count must be between 1 and the configured maximum") context, state = self.start(low) outputs = [] for _ in range(count): state = self.step(low, context, state) outputs.append(state[0]) return outputs
def forward(self, low): return self.trajectory(low)[-1]
def restore(self, low, threshold, statistic="regional"): if low.shape[0] != 1 or not math.isfinite(threshold) or threshold < 0: raise ValueError("Adaptive inference requires one image and a nonnegative threshold") context, state = self.start(low) for stage in range(1, self.config.stages + 1): previous = state[0] state = self.step(low, context, state) if stage == self.config.stages or activity(previous, state[0], statistic).item() <= threshold: return state[0], stage
def build(config): return Iterative(config) if config.variant == "iterative" else CNN(config)
def save_model(model, folder): folder = Path(folder) folder.mkdir(parents=True, exist_ok=True) state = {key: value.detach().cpu().contiguous() for key, value in model.state_dict().items()} save_file(state, folder / "model.safetensors") (folder / "config.json").write_text(json.dumps({"format": 1, **asdict(model.config)}, indent=2) + "\n")
def load_model(folder, device="cpu"): folder = Path(folder) options = json.loads((folder / "config.json").read_text()) if options.pop("format") != 1: raise ValueError("Unknown checkpoint format") model = build(Config(**options)) model.load_state_dict(load_file(folder / "model.safetensors")) return model.to(device).eval()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""Train both models with the same crops and validation split."""
import argparseimport jsonfrom pathlib import Pathimport time
import torchimport torch.nn.functional as Ffrom torch.utils.data import DataLoader
from .data import Crops, pixels, protocol, read_pairfrom .infer import device_forfrom .metrics import psnrfrom .model import Config, Iterative, build, save_model
def tensor_pair(pair, device="cpu", max_side=None): low, target = (pixels(torch.from_numpy(image))[None] for image in read_pair(pair)) if max_side and max(low.shape[-2:]) > max_side: scale = max_side / max(low.shape[-2:]) shape = tuple(round(dim * scale) for dim in low.shape[-2:]) low, target = [ F.interpolate(image, size=shape, mode="bilinear", align_corners=False, antialias=True) for image in (low, target) ] return low.to(device), target.to(device)
def image_loss(prediction, target): residual = prediction - target content = residual.square().add(1e-6).sqrt().mean() horizontal = residual.diff(dim=-1).abs().mean() vertical = residual.diff(dim=-2).abs().mean() return content + 0.04 * (horizontal + vertical)
def train_model(variant, args, data, validation, device): torch.manual_seed(args.seed) model = build(Config(variant, args.width, 3 if variant == "iterative" else 1)).to(device) optimizer = torch.optim.AdamW(model.parameters(), lr=args.lr, weight_decay=1e-4) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, args.epochs, eta_min=args.lr / 10) batches = DataLoader(data, batch_size=args.batch_size, shuffle=True, generator=torch.Generator().manual_seed(args.seed)) parameters = sum(parameter.numel() for parameter in model.parameters()) history, best = [], -float("inf") destination = args.output / variant start = time.monotonic() print(f"{variant}: {parameters:,} parameters, {device}", flush=True)
for epoch in range(args.epochs): data.epoch = epoch model.train() losses = [] for low, target in batches: low, target = pixels(low.to(device)), pixels(target.to(device)) outputs = model.trajectory(low) if isinstance(model, Iterative) else [model(low)] weights = (0.20, 0.30, 0.50) if len(outputs) == 3 else (1.0,) loss = sum(weight * image_loss(output, target) for weight, output in zip(weights, outputs)) optimizer.zero_grad(set_to_none=True) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) optimizer.step() losses.append(loss.detach()) scheduler.step() model.eval() with torch.inference_mode(): values = [psnr(model(low.to(device)), target.to(device)) for low, target in validation] score = torch.cat(values).mean().item() mean_loss = torch.stack(losses).mean().item() if not torch.isfinite(torch.tensor([score, mean_loss])).all(): raise RuntimeError(f"Nonfinite training run at epoch {epoch + 1}") row = {"epoch": epoch + 1, "loss": mean_loss, "validation_psnr": score} history.append(row) print(json.dumps(row), flush=True) if score > best: best, selected_epoch = score, epoch + 1 save_model(model, destination) (destination / "history.json").write_text(json.dumps(history, indent=2) + "\n") settings = { key: getattr(args, key) for key in ("epochs", "width", "crop", "repeats", "lr", "seed", "batch_size", "validation_count") } report = { **settings, "parameters": parameters, "device": device, "torch_version": str(torch.__version__), "selected_epoch": selected_epoch, "wall_seconds": time.monotonic() - start, "checkpoint_selection": "maximum mean validation PSNR, downscaled to 224 px long side", } (destination / "training.json").write_text(json.dumps(report, indent=2) + "\n")
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("data", type=Path) parser.add_argument("output", type=Path) parser.add_argument("--device", default="auto") parser.add_argument("--mode", choices=("both", "cnn", "iterative"), default="both") parser.add_argument("--crop", type=int, default=128) parser.add_argument("--batch-size", type=int, default=20) parser.add_argument("--epochs", type=int, default=16) parser.add_argument("--repeats", type=int, default=2) parser.add_argument("--width", type=int, default=24) parser.add_argument("--lr", type=float, default=0.001) parser.add_argument("--seed", type=int, default=42) parser.add_argument("--validation-count", type=int, default=80) args = parser.parse_args() if min(args.epochs, args.repeats, args.batch_size) < 1 or args.crop < 16 or args.lr <= 0: parser.error("epochs, repeats, batch size and learning rate must be positive; crop must be at least 16") torch.set_num_threads(4) device = device_for(args.device) training_pairs, validation_pairs, _ = protocol(args.data, args.validation_count) data = Crops(training_pairs, args.crop, args.repeats, args.seed) validation = [tensor_pair(pair, max_side=224) for pair in validation_pairs] print(f"{len(training_pairs)} training pairs and {len(validation_pairs)} validation pairs", flush=True) modes = ("cnn", "iterative") if args.mode == "both" else (args.mode,) for variant in modes: train_model(variant, args, data, validation, device)
if __name__ == "__main__": main()123456789101112131415161718192021[build-system]requires = ["setuptools>=77"]build-backend = "setuptools.build_meta"
[project]name = "luma-restore"version = "0.1.0"description = "Compact low-light restoration with region-aware adaptive inference"readme = "README.md"requires-python = ">=3.11"license = "MIT"dependencies = ["torch>=2.7,<3", "numpy>=1.26,<3", "pillow>=11,<14", "safetensors>=0.5,<1", "huggingface-hub>=1,<3"]
[project.optional-dependencies]report = ["matplotlib>=3.8,<4"]
[project.scripts]luma-restore = "luma_restore.infer:main"
[tool.setuptools.packages.find]include = ["luma_restore*"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182[ { "epoch": 1, "loss": 0.17597948014736176, "validation_psnr": 18.033092498779297 }, { "epoch": 2, "loss": 0.15989252924919128, "validation_psnr": 17.307846069335938 }, { "epoch": 3, "loss": 0.15553513169288635, "validation_psnr": 18.67408561706543 }, { "epoch": 4, "loss": 0.14965762197971344, "validation_psnr": 17.71498680114746 }, { "epoch": 5, "loss": 0.1499001532793045, "validation_psnr": 18.318283081054688 }, { "epoch": 6, "loss": 0.14778389036655426, "validation_psnr": 16.550384521484375 }, { "epoch": 7, "loss": 0.1490267962217331, "validation_psnr": 17.330974578857422 }, { "epoch": 8, "loss": 0.148793026804924, "validation_psnr": 17.83060646057129 }, { "epoch": 9, "loss": 0.14727146923542023, "validation_psnr": 17.89013671875 }, { "epoch": 10, "loss": 0.1471129208803177, "validation_psnr": 17.975929260253906 }, { "epoch": 11, "loss": 0.1466982662677765, "validation_psnr": 18.20313262939453 }, { "epoch": 12, "loss": 0.14618396759033203, "validation_psnr": 18.433696746826172 }, { "epoch": 13, "loss": 0.14611071348190308, "validation_psnr": 17.674680709838867 }, { "epoch": 14, "loss": 0.14391006529331207, "validation_psnr": 17.676959991455078 }, { "epoch": 15, "loss": 0.14630553126335144, "validation_psnr": 18.126985549926758 }, { "epoch": 16, "loss": 0.14447277784347534, "validation_psnr": 17.7352237701416 }]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182[ { "epoch": 1, "loss": 0.18776509165763855, "validation_psnr": 18.429439544677734 }, { "epoch": 2, "loss": 0.1731794774532318, "validation_psnr": 17.402896881103516 }, { "epoch": 3, "loss": 0.17233097553253174, "validation_psnr": 18.657344818115234 }, { "epoch": 4, "loss": 0.1618325412273407, "validation_psnr": 19.053791046142578 }, { "epoch": 5, "loss": 0.1572510153055191, "validation_psnr": 18.936723709106445 }, { "epoch": 6, "loss": 0.1486882120370865, "validation_psnr": 17.929889678955078 }, { "epoch": 7, "loss": 0.1481456756591797, "validation_psnr": 18.1925106048584 }, { "epoch": 8, "loss": 0.14803239703178406, "validation_psnr": 18.368154525756836 }, { "epoch": 9, "loss": 0.14601920545101166, "validation_psnr": 18.9134521484375 }, { "epoch": 10, "loss": 0.14462856948375702, "validation_psnr": 18.362102508544922 }, { "epoch": 11, "loss": 0.1450551450252533, "validation_psnr": 18.72527503967285 }, { "epoch": 12, "loss": 0.14421634376049042, "validation_psnr": 18.89340591430664 }, { "epoch": 13, "loss": 0.1447424590587616, "validation_psnr": 18.498394012451172 }, { "epoch": 14, "loss": 0.14275850355625153, "validation_psnr": 18.316925048828125 }, { "epoch": 15, "loss": 0.14444488286972046, "validation_psnr": 18.519216537475586 }, { "epoch": 16, "loss": 0.14275743067264557, "validation_psnr": 18.4466609954834 }]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Render the quality–compute report from the recorded benchmark."""
import jsonfrom pathlib import Path
import matplotlib
matplotlib.use("Agg")import matplotlib.pyplot as plt
ROOT = Path(__file__).resolve().parentBACKGROUND = "#f6f8fc"INK = "#18263a"
plt.rcParams.update({ "figure.facecolor": BACKGROUND, "axes.facecolor": BACKGROUND, "text.color": INK, "axes.labelcolor": INK, "xtick.color": INK, "ytick.color": INK, "font.family": "DejaVu Sans",})
def format_axis(axis, title, xlabel): for edge in ("top", "right"): axis.spines[edge].set_visible(False) for edge in ("bottom", "left"): axis.spines[edge].set_color("#bdcadb") axis.set_axisbelow(True) axis.grid(alpha=0.35, color="#b1c2d3") axis.set_title(title, loc="left", fontweight="bold") axis.set_xlabel(xlabel) axis.set_ylabel("Mean RGB PSNR (dB)")
def main(): data = json.loads((ROOT / "test-results.json").read_text()) summary = data["summary"] calibration = data["calibration"] fixed_names = ("stage_1", "stage_2", "stage_3") blue, purple, green = "#3462a1", "#7753ad", "#008371"
figure, (validation, test) = plt.subplots(1, 2, figsize=(11.8, 4.7)) figure.subplots_adjust(left=0.09, right=0.97, top=0.74, bottom=0.20, wspace=0.27) figure.text(0.06, 0.91, "What does another restoration pass buy?", fontsize=20, weight="bold") figure.text(0.06, 0.84, "LumaRestore · LOL-v2 Real · Quality versus average update count", fontsize=10.5, color="#43566c")
for name, color, label in ( ("regional", green, "Regional exit"), ("global", purple, "Whole-image exit") ): curve = calibration["threshold_curves"][name] validation.scatter([point["mean_stages"] for point in curve], [point["psnr"] for point in curve], color=color, s=13, alpha=0.55, label=label) selected = calibration["adaptive"][name] validation.scatter(selected["mean_stages"], selected["psnr"], s=95, color=color, edgecolors="white", linewidth=1.3, zorder=5) floor = calibration["fixed_validation_psnr"] - calibration["tolerance_db"] validation.axhline(floor, color=INK, alpha=0.7, linestyle="--", linewidth=1, label="Validation quality floor") validation.legend(frameon=False, fontsize=8, loc="best") format_axis(validation, "Validation threshold sweep", "Mean update count")
test.plot([1, 2, 3], [summary[name]["psnr"] for name in fixed_names], "o-", color=blue, linewidth=2, label="Fixed exits") test.scatter(summary["cnn"]["mean_stages"], summary["cnn"]["psnr"], s=66, marker="s", color="#798296", label="One-pass CNN") for key, color, label in ( ("adaptive_regional", green, "Regional exit"), ("adaptive_global", purple, "Whole-image exit") ): row = summary[key] test.scatter(row["mean_stages"], row["psnr"], s=110, marker="D", color=color, edgecolors="white", linewidth=1.1, label=label, zorder=5) test.legend(frameon=False, fontsize=8, loc="best") test.set_xticks([1, 1.5, 2, 2.5, 3]) format_axis(test, "Official test split", "Mean update count") figure.text(0.06, 0.055, "Validation dots show candidate thresholds. Outlined markers show the selected policies.", fontsize=9.2, color="#43566c") figure.savefig(ROOT / "quality-compute.png", dpi=145)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960import tempfileimport unittest
import numpy as npimport torch
from luma_restore.evaluate import select_exitfrom luma_restore.metrics import psnr, ssimfrom luma_restore.model import Config, activity, build, load_model, save_model
class RestorationTests(unittest.TestCase): def setUp(self): torch.set_num_threads(2) torch.manual_seed(9) self.image = torch.rand(1, 3, 19, 35) * 0.3
def test_iterative_shape_range_and_adaptive_exits(self): model = build(Config("iterative", width=8)) with torch.inference_mode(): stages = model.trajectory(self.image) for stage in stages: self.assertEqual(stage.shape, self.image.shape) self.assertTrue(((0 <= stage) & (stage <= 1)).all()) early, index = model.restore(self.image, 1.0) self.assertEqual(index, 1) torch.testing.assert_close(early, stages[0]) late, index = model.restore(self.image, 0.0, "global") self.assertEqual(index, 3) torch.testing.assert_close(late, stages[-1])
def test_checkpoint_round_trip_and_gradient(self): for variant in ("cnn", "iterative"): with self.subTest(variant=variant), tempfile.TemporaryDirectory() as folder: model = build(Config(variant, width=8)) result = model(self.image) result.mean().backward() self.assertTrue(all(p.grad is not None and torch.isfinite(p.grad).all() for p in model.parameters())) save_model(model, folder) torch.testing.assert_close(load_model(folder)(self.image), result)
def test_regional_exit_detects_localized_change(self): before = torch.zeros(1, 3, 16, 16) after = before.clone() after[..., :4, :4] = 0.5 self.assertAlmostEqual(activity(before, after).item(), 0.5) self.assertAlmostEqual(activity(before, after, "global").item(), 0.5 / 16)
def test_calibration_takes_first_eligible_exit(self): changes = np.array([[0.04, 0.02, 0.01], [0.08, 0.03, 0.02]]) quality = np.array([[21, 22, 23], [24, 25, 26]]) self.assertEqual(select_exit(changes, quality, 0.05), (23.0, 1.5))
def test_identical_images_have_unit_ssim(self): self.assertAlmostEqual(ssim(self.image, self.image).item(), 1.0, places=5) self.assertGreater(psnr(self.image, self.image).item(), psnr(self.image * 0.5, self.image).item())
if __name__ == "__main__": unittest.main().gitattributes+1
.gitignoreAdded+10
LICENSEAdded+21
MODEL_CARD.mdAdded+82
README.mdAdded+82
checkpoints/cnn/config.jsonAdded+6
checkpoints/cnn/model.safetensorsAdded+3
checkpoints/cnn/training.jsonAdded+16
checkpoints/iterative/config.jsonAdded+6
checkpoints/iterative/model.safetensorsAdded+3
checkpoints/iterative/training.jsonAdded+16
luma_restore/__init__.pyAdded+1
luma_restore/data.pyAdded+104
luma_restore/evaluate.pyAdded+185
luma_restore/infer.pyAdded+68
luma_restore/metrics.pyAdded+26
luma_restore/model.pyAdded+143
luma_restore/train.pyAdded+125
pyproject.tomlAdded+21
reports/cnn/history.jsonAdded+82
reports/iterative/history.jsonAdded+82
reports/quality-compute.pngAdded

Large File Pointer Details
- SHA256: d948d3a4b1ef0163b4f3e43fc98b1827888e2cc4d7b280bffa2ce5b2091926bb
- Pointer size: 131 Bytes
- Size of remote file: 122 kB
reports/render_figures.pyAdded+84
reports/test-results.jsonAdded
tests/test_model.pyAdded+60