luma-restore / tests /test_model.py
Kiriti-Ray's picture
Release LumaRestore and the LOL-v2 Real benchmark
c822ccd verified
Raw History Blame Contribute Delete
2.54 kB
import tempfile
import unittest
import numpy as np
import torch
from luma_restore.evaluate import select_exit
from luma_restore.metrics import psnr, ssim
from 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()