π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(contrib): cache the super-resolution weights in the torch hub; fall back to params (#6131)
Dmytro Mishkin63e4c2341255
diff --git a/.github/download-models-weights.py b/.github/download-models-weights.pyindex 1158e95a0..ff4535aab 100644--- a/.github/download-models-weights.py+++ b/.github/download-models-weights.py@@ -192,6 +192,9 @@ MODELS: dict[str, "str | list[str]"] = {# DeFMO(True): smoke and jit tests instantiate both halves."encoder_best.pt": "https://huggingface.co/kornia/defmo/resolve/main/encoder_best.pt","rendering_best.pt": "https://huggingface.co/kornia/defmo/resolve/main/rendering_best.pt",+ # -- super-resolution ----------------------------------------------------+ # SmallSRNet(pretrained=True): about 240 KB; its two slow tests skip unless it is cached.+ "superres_epoch100-44c6958e.pth": "https://s3.amazonaws.com/pytorch/test_data/export/superres_epoch100-44c6958e.pth",}diff --git a/changelog.d/6131.fixed.md b/changelog.d/6131.fixed.mdnew file mode 100644index 000000000..d6f95b144--- /dev/null+++ b/changelog.d/6131.fixed.md@@ -0,0 +1,5 @@+Super-resolution weight loading in `kornia.contrib` and `kornia.models`:++- The pretrained Real-ESRGAN weights of `RRDBNetBuilder` (also reached through `SuperResolution.from_config`) and the `SmallSRNet` weights behind `SmallSRBuilder` are cached in the torch hub directory through `kornia.core.download.load_state_dict_from_url`, as kornia's other checkpoints are. They were cached under `kornia_config.hub_onnx_dir` (`.kornia_hub/onnx_models`, relative to the working directory), so each new working directory downloaded them again; existing users download them once more. A copy kept for offline use goes to `<torch.hub.get_dir()>/checkpoints/` under the URL's file name: `small_sr.pth` becomes `superres_epoch100-44c6958e.pth`, and the Real-ESRGAN files keep their names.+- A Real-ESRGAN checkpoint without `params_ema` loads its `params`, the fallback of Real-ESRGAN's own loader; it raised `KeyError: 'params_ema'`.+- `SmallSRNet.load_from_file` reads a local checkpoint file, as its docstring said; a path raised `ValueError: URL must start with 'http:' or 'https:'`. A path that names no file raises `FileNotFoundError`.diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.pyindex dd43e5266..b83328f11 100644--- a/kornia/contrib/super_resolution.py+++ b/kornia/contrib/super_resolution.py@@ -21,7 +21,7 @@ from typing import Any, List, Optional, Tuple, Unionimport torchfrom torch import nn-from kornia.config import kornia_config+from kornia.core.download import load_state_dict_from_urlfrom kornia.core.external import PILImage as Imagefrom kornia.core.external import onnxfrom kornia.core.mixin.onnx import ONNXExportMixin@@ -29,7 +29,6 @@ from kornia.models.base import ModelBasefrom kornia.models.processors import OutputRangePostProcessor, ResizePreProcessorfrom kornia.models.rrdbnet import RRDBNetfrom kornia.models.small_sr import SmallSRNetWrapper-from kornia.onnx.download import CachedDownloader__all__ = ["RRDBNetBuilder", "SmallSRBuilder", "SuperResolution", "SuperResolutionConfig"]@@ -291,14 +290,11 @@ class RRDBNetBuilder:"'RealESRGAN_x4plus', 'RealESRNet_x4plus', 'RealESRGAN_x4plus_anime_6B', 'RealESRGAN_x2plus'.")- model_path = Noneif pretrained:- url = _URLs[model_name]- model_path = CachedDownloader.download_to_cache(- url, model_name, download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir- )- state_dict = torch.load(model_path, map_location=torch.device("cpu"), weights_only=True)- model.load_state_dict(state_dict["params_ema"], strict=True)+ # The torch hub cache, as for every other kornia checkpoint. Real-ESRGAN's RealESRGANer prefers the EMA+ # weights and falls back to the plain ones.+ checkpoint = load_state_dict_from_url(_URLs[model_name], map_location=torch.device("cpu"))+ model.load_state_dict(checkpoint["params_ema" if "params_ema" in checkpoint else "params"], strict=True)model.eval()return SuperResolution(diff --git a/kornia/models/small_sr.py b/kornia/models/small_sr.pyindex 12052ee9a..38cda27ee 100644--- a/kornia/models/small_sr.py+++ b/kornia/models/small_sr.py@@ -15,12 +15,13 @@# limitations under the License.#+import os+import torchfrom torch import nnfrom kornia.color.ycbcr import RgbToYcbcr, YcbcrToRgb-from kornia.config import kornia_config-from kornia.onnx.download import CachedDownloader+from kornia.core.download import load_state_dict_from_urlurl = "https://s3.amazonaws.com/pytorch/test_data/export/superres_epoch100-44c6958e.pth"@@ -55,18 +56,26 @@ class SmallSRNet(nn.Module):weight_init(self)def load_from_file(self, path_file: str) -> None:- """Load pretrained super-resolution weights from the model cache.+ """Load pretrained super-resolution weights and switch the module to evaluation mode.Args:- path_file: Checkpoint URL or path passed to the cached downloader.- The downloaded state dictionary is loaded strictly and the- module is switched to evaluation mode.+ path_file: path of a local checkpoint file, or a URL accepted by+ :func:`kornia.core.download.load_state_dict_from_url`. A string naming an existing file (a leading+ ``~`` is expanded) is read with :func:`torch.load` and ``weights_only=True``; a URL (a string with+ ``://``) goes through the torch hub cache. The state dictionary is loaded strictly.++ Raises:+ FileNotFoundError: If ``path_file`` is neither an existing file nor a URL."""- # use torch.hub to load pretrained model- model_path = CachedDownloader.download_to_cache(- path_file, "small_sr.pth", download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir- )- pretrained_dict = torch.load(model_path, map_location=torch.device("cpu"), weights_only=True)+ local = os.path.expanduser(path_file)+ if os.path.isfile(local):+ with open(local, "rb") as f:+ pretrained_dict = torch.load(f, map_location=torch.device("cpu"), weights_only=True)+ elif "://" not in str(path_file):+ # Not a URL either: name the missing file instead of load_state_dict_from_url's "not a URL" error.+ raise FileNotFoundError(f"No checkpoint file at {local!r}.")+ else:+ pretrained_dict = load_state_dict_from_url(path_file, map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)self.eval()diff --git a/tests/contrib/test_super_resolution.py b/tests/contrib/test_super_resolution.pyindex 2480e91db..7b721ba09 100644--- a/tests/contrib/test_super_resolution.py+++ b/tests/contrib/test_super_resolution.py@@ -189,3 +189,42 @@ class TestSuperResolutionBuilders(BaseTester):inferred = onnx.shape_inference.infer_shapes(exported, data_prop=True)out_dim = inferred.graph.output[0].type.tensor_type.shape.dim[-1]assert out_dim.dim_value == model.output_image_size+++class TestRRDBNetBuilderWeights:+ """Pretrained Real-ESRGAN weights load like every other kornia checkpoint, with no download here."""++ @staticmethod+ def _fake_loader(monkeypatch, checkpoint):+ import kornia.contrib.super_resolution as sr++ calls = []++ def _load(url, **kwargs):+ calls.append((url, kwargs))+ return checkpoint++ monkeypatch.setattr(sr, "load_state_dict_from_url", _load)+ return calls++ @pytest.mark.parametrize("keys", [("params_ema",), ("params",), ("params", "params_ema")])+ def test_loads_the_ema_weights_and_falls_back_to_params(self, monkeypatch, tmp_path, keys):+ # Real-ESRGAN's RealESRGANer prefers ``params_ema`` and falls back to ``params``; kornia read ``params_ema``+ # only, so a checkpoint without it raised ``KeyError``.+ monkeypatch.chdir(tmp_path)+ reference = RRDBNetBuilder.build("RealESRGAN_x4plus_anime_6B", pretrained=False).model.state_dict()+ checkpoint = {key: {k: torch.full_like(v, i + 1.0) for k, v in reference.items()} for i, key in enumerate(keys)}+ calls = self._fake_loader(monkeypatch, checkpoint)++ model = RRDBNetBuilder.build("RealESRGAN_x4plus_anime_6B", pretrained=True).model++ expected = checkpoint["params_ema" if "params_ema" in keys else "params"]+ assert all(torch.equal(v, expected[k]) for k, v in model.state_dict().items())+ assert [url for url, _ in calls] == [+ "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.2.4/RealESRGAN_x4plus_anime_6B.pth"+ ]+ # The weights go to the torch hub cache, as every other kornia checkpoint does, not under the working+ # directory, where each new one downloaded them again: no ``model_dir`` overrides the hub's.+ assert calls[0][1].get("model_dir") is None+ assert calls[0][1].get("file_name") is None+ assert not any(tmp_path.iterdir())diff --git a/tests/core/test_weights_prefetch.py b/tests/core/test_weights_prefetch.pyindex 81b158590..65e52ddf4 100644--- a/tests/core/test_weights_prefetch.py+++ b/tests/core/test_weights_prefetch.py@@ -38,9 +38,8 @@ enumerated in :data:`WEIGHT_REGISTRIES`). Two other download paths live inas the vision-language builders (``kornia/models/{kimi_vl,siglip2}/builder.py``)call it, to fetch a ``model.safetensors``, and as ``kornia/feature/lightglue_onnx/utils/download.py``calls it, to fetch the LightGlue ONNX models -- and ``CachedDownloader`` into-``.kornia_hub/`` (``kornia/models/small_sr.py``, ``kornia/contrib/super_resolution.py``,-``kornia/onnx/utils.py``, ``kornia/models/_hf_models/hf_onnx_community.py``). Nothing in the PR matrix-downloads through either today; a test that did would fetch live from every+``.kornia_hub/`` (``kornia/onnx/utils.py``, ``kornia/models/_hf_models/hf_onnx_community.py``). Nothing in the PR+matrix downloads through either today; a test that did would fetch live from everymatrix cell with this file still green.Those builders' checkpoints could in principle be prefetched as the reference@@ -72,6 +71,7 @@ from urllib.parse import urlparseimport pytest+from kornia.contrib import super_resolutionfrom kornia.feature import affine_shape, defmo, hardnet, hynet, keynet, mkd, orientation, sosnet, tfeat, xfeatfrom kornia.feature import lightglue as lightglue_modfrom kornia.feature.aliked import aliked@@ -83,7 +83,7 @@ from kornia.feature.loftr import loftrfrom kornia.feature.sold2 import sold2, sold2_detectorfrom kornia.filters import dexinedfrom kornia.models import dexined as dexined_model-from kornia.models import tiny_vit, vit+from kornia.models import small_sr, tiny_vit, vitfrom kornia.models.efficient_vit import model as efficient_vitfrom kornia.models.rt_detr import model as rt_detrfrom kornia.models.sam import model as sam@@ -145,6 +145,8 @@ WEIGHT_REGISTRIES: dict[str, tuple[ModuleType, dict[str, Any]]] = {"rt_detr": (rt_detr, rt_detr.URLs),"keynet": (keynet, {"keynet": keynet.KeyNet_URL}),"yunet": (yunet, {"yunet": yunet._url}),+ "small_sr": (small_sr, {"small_sr": small_sr.url}),+ "super_resolution": (super_resolution, super_resolution._URLs),# kornia.filters.dexined re-exports kornia.models.dexined, so both entries# read one list; the filters entry keeps the old import path's ``url`` alias,# which testing/reference_data.py reads, under the same guard.@@ -289,6 +291,11 @@ NOT_PREFETCHED: dict[str, str] = {"vit_s-16.pth": "no test or doctest selects this ViT variant","vit_ti-16.pth": "no test or doctest selects this ViT variant","vit_b-32.pth": "no test or doctest selects this ViT variant",+ # Real-ESRGAN: the tests build RRDBNetBuilder random or monkeypatch its loader, and models.rst only shows the call.+ "RealESRGAN_x4plus.pth": "no test, doctest or docs build loads pretrained Real-ESRGAN weights",+ "RealESRNet_x4plus.pth": "no test, doctest or docs build loads pretrained Real-ESRGAN weights",+ "RealESRGAN_x4plus_anime_6B.pth": "no test, doctest or docs build loads pretrained Real-ESRGAN weights",+ "RealESRGAN_x2plus.pth": "no test, doctest or docs build loads pretrained Real-ESRGAN weights",}diff --git a/tests/models/test_small_sr.py b/tests/models/test_small_sr.pyindex aa089fd80..b48c6638e 100644--- a/tests/models/test_small_sr.py+++ b/tests/models/test_small_sr.py@@ -20,8 +20,8 @@ import osimport pytestimport torch-from kornia.config import kornia_configfrom kornia.models.small_sr import SmallSRNet, SmallSRNetWrapper+from kornia.models.small_sr import url as small_sr_urlfrom testing.base import BaseTester@@ -98,7 +98,7 @@ class TestSmallSRNet(BaseTester):"""Test that pretrained weights can be loaded (only upscale_factor=3 has pretrained weights)."""if upscale_factor == 3:# Check if pretrained weights are cached to avoid network download attempts in offline CI- cache_path = os.path.join(kornia_config.hub_onnx_dir, "small_sr.pth")+ cache_path = os.path.join(torch.hub.get_dir(), "checkpoints", os.path.basename(small_sr_url))if not os.path.exists(cache_path):pytest.skip(f"Pretrained weights not cached at {cache_path}. Skipping to avoid network download.")@@ -210,7 +210,7 @@ class TestSmallSRNetWrapper(BaseTester):def test_feature_pretrained_upscale_3x(self, device, dtype):"""Test upscaling with pretrained weights (only available for upscale_factor=3)."""# Check if pretrained weights are cached to avoid network download attempts in offline CI- cache_path = os.path.join(kornia_config.hub_onnx_dir, "small_sr.pth")+ cache_path = os.path.join(torch.hub.get_dir(), "checkpoints", os.path.basename(small_sr_url))if not os.path.exists(cache_path):pytest.skip(f"Pretrained weights not cached at {cache_path}. Skipping to avoid network download.")@@ -293,3 +293,45 @@ class TestSmallSRNetWrapper(BaseTester):# Individual processing should match batch processingself.assert_close(output1, output_batch[0:1], rtol=1e-4, atol=1e-4)self.assert_close(output2, output_batch[1:2], rtol=1e-4, atol=1e-4)+++class TestSmallSRNetWeights:+ """``load_from_file`` reads a local checkpoint itself and sends a URL through the hub cache."""++ @pytest.mark.parametrize("spelling", ["absolute", "home"])+ def test_a_local_checkpoint_is_read(self, monkeypatch, tmp_path, spelling):+ source = SmallSRNet(upscale_factor=3, pretrained=False)+ path = tmp_path / "weights.pth"+ torch.save(source.state_dict(), path)+ monkeypatch.setenv("HOME", str(tmp_path))+ monkeypatch.setenv("USERPROFILE", str(tmp_path))+ loads = []+ real_load = torch.load+ monkeypatch.setattr(torch, "load", lambda *a, **kw: loads.append(kw.get("weights_only")) or real_load(*a, **kw))+ model = SmallSRNet(upscale_factor=3, pretrained=False).train()+ model.load_from_file(str(path) if spelling == "absolute" else "~/weights.pth")+ assert all(torch.equal(v, source.state_dict()[k]) for k, v in model.state_dict().items())+ assert not model.training+ # A local checkpoint is unpickled with weights_only=True, as the hub path does.+ assert loads == [True]++ def test_a_url_goes_through_the_hub_cache(self, monkeypatch, tmp_path):+ from kornia.models import small_sr++ monkeypatch.chdir(tmp_path)+ source = SmallSRNet(upscale_factor=3, pretrained=False)+ calls = []++ def _load(url, **kwargs):+ # No model_dir and no file_name: the torch hub cache, under the URL's base name, which is the key+ # .github/download-models-weights.py prefetches it by.+ calls.append((url, kwargs.get("model_dir"), kwargs.get("file_name")))+ return source.state_dict()++ monkeypatch.setattr(small_sr, "load_state_dict_from_url", _load)+ model = SmallSRNet(upscale_factor=3, pretrained=True)+ # The torch hub cache: no ``model_dir`` overrides it.+ assert calls == [(small_sr.url, None, None)]+ assert all(torch.equal(v, source.state_dict()[k]) for k, v in model.state_dict().items())+ # Not cached under the working directory, where each new one downloaded the weights again.+ assert not any(tmp_path.iterdir())