π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(contrib): make the super_resolution builders constructible again (#4335)
Aditya Malkar05578ef74262
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 76bb0827d..c604c597b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -513,6 +513,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0now built in `float32` and `float16`/`bfloat16` results are byte-identical to `float32`/`float64`.`RandomErasing` and `RandomCutMixV2` build their masks through it. (#4336)+* `kornia.contrib.super_resolution` builders construct again. `SuperResolution` never implemented+ `ModelBase`'s abstract `from_config` and defined no `__init__`, so `SmallSRBuilder.build()` and+ `RRDBNetBuilder.build()` both raised `TypeError` at construction β the whole public+ super-resolution entry point had been unreachable since the models refactor made `from_config`+ abstract. It now has a `SuperResolutionConfig` and a `from_config` that dispatches to either+ builder family, and both builders are covered by tests. Fixes #4291. (#4335)+* `kornia.io.load_image` and `write_image` work on the kornia_rs that a plain `pip install kornia`resolves. kornia_rs 0.1.11 moved its image readers and writers from the package root into`kornia_rs.io`, and kornia kept calling the root, so on 0.1.11 and newer `load_image` raiseddiff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.pyindex 5d5de0e7b..44f3105ce 100644--- a/docs/export_support/cases_models.py+++ b/docs/export_support/cases_models.py@@ -672,7 +672,6 @@ A(model=torch.nn.Identity(), pre_processor=torch.nn.Identity(), post_processor=torch.nn.Identity(), name="x"),[IMG],- note="KORNIA BUG: abstract (ModelBase.from_config not implemented, no __init__) -> TypeError",))A(@@ -681,7 +680,6 @@ A("contrib",lambda x: K.contrib.SmallSRBuilder.build("small_sr", pretrained=False),[IMG],- note="KORNIA BUG: builder instantiates abstract SuperResolution -> TypeError at super_resolution.py:262",))A(@@ -690,7 +688,7 @@ A("contrib",None,[],- skip="builds a 17M-parameter Real-ESRGAN generator and would hit the same abstract SuperResolution TypeError",+ skip="builds a 17M-parameter Real-ESRGAN generator; too heavy for the survey",))diff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex ed9cc776f..1a79bcf97 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -195,3 +195,18 @@ KMeans.. autoclass:: KMeans:members:++Super Resolution+----------------++.. autoclass:: SuperResolution+ :members:++.. autoclass:: SuperResolutionConfig+ :members:++.. autoclass:: SmallSRBuilder+ :members:++.. autoclass:: RRDBNetBuilder+ :members:diff --git a/docs/source/models.rst b/docs/source/models.rstindex 638d6b838..801a230cc 100644--- a/docs/source/models.rst+++ b/docs/source/models.rst@@ -80,10 +80,13 @@ The `RRDBNet` class is the Residual-in-Residual Dense Block generator behind ESRIt is a plain ``nn.Module`` that upsamples a batched ``(B, 3, H, W)`` image by a factor of 1, 2 or 4,and its module and parameter names match the reference implementation, so the published Real-ESRGANcheckpoints load with ``strict=True``. ``kornia.contrib.super_resolution.RRDBNetBuilder`` configures-it for the released Real-ESRGAN variants and downloads their weights, but it currently raises-``TypeError`` because the ``SuperResolution`` wrapper it returns never implements the abstract-``from_config`` method it inherits (`kornia#4291 <https://github.com/kornia/kornia/issues/4291>`_);-until that is fixed, construct ``RRDBNet`` directly and load the checkpoint with ``load_state_dict``.+it for the released Real-ESRGAN variants and downloads their weights, and returns a+``SuperResolution`` wrapper ready for inference::++ from kornia.contrib.super_resolution import RRDBNetBuilder++ model = RRDBNetBuilder.build("RealESRNet_x4plus")+ upscaled = model(images) # (B, 3, H, W) -> (B, 3, 4H, 4W)The architecture is vendored from `BasicSR <https://github.com/XPixelGroup/BasicSR>`_ (Apache-2.0,Copyright 2018-2022 BasicSR Authors); no extra package is required to use it.diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.pyindex 7571da41d..86fb6bc20 100644--- a/kornia/contrib/__init__.py+++ b/kornia/contrib/__init__.py@@ -39,7 +39,7 @@ from .image_stitching import ImageStitcherfrom .kmeans import KMeansfrom .lambda_module import Lambdafrom .object_detection import ObjectDetector, RTDETRDetectorBuilder-from .super_resolution import RRDBNetBuilder, SmallSRBuilder, SuperResolution+from .super_resolution import RRDBNetBuilder, SmallSRBuilder, SuperResolution, SuperResolutionConfig__all__ = ["CombineTensorPatches",@@ -55,6 +55,7 @@ __all__ = ["RTDETRDetectorBuilder","SmallSRBuilder","SuperResolution",+ "SuperResolutionConfig","TinyViT","combine_tensor_patches","compute_padding",diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.pyindex ff0fd300f..28db938dd 100644--- a/kornia/contrib/super_resolution.py+++ b/kornia/contrib/super_resolution.py@@ -15,6 +15,7 @@# limitations under the License.#+from dataclasses import dataclassfrom typing import Any, List, Optional, Tuple, Unionimport torch@@ -30,7 +31,11 @@ from kornia.models.rrdbnet import RRDBNetfrom kornia.models.small_sr import SmallSRNetWrapperfrom kornia.onnx.download import CachedDownloader-__all__ = ["RRDBNetBuilder", "SmallSRBuilder", "SuperResolution"]+__all__ = ["RRDBNetBuilder", "SmallSRBuilder", "SuperResolution", "SuperResolutionConfig"]++# `SmallSRBuilder`'s wrapper resizes every input to this before the network, so the+# pipeline's output side is always this times `upscale_factor`, whatever `image_size` is.+_SMALL_SR_INPUT_SIZE = 224_URLs = {"RealESRGAN_x4plus": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",@@ -41,7 +46,34 @@ _URLs = {# TODO: support patching -> SR -> unpatching pipeline-class SuperResolution(ModelBase, ONNXExportMixin):+@dataclass+class SuperResolutionConfig:+ """Configuration to construct a :class:`SuperResolution` model.++ The fields mirror the arguments accepted by :class:`RRDBNetBuilder` and+ :class:`SmallSRBuilder`, so a config can drive either builder.++ Args:+ model_name: Name of the model variant to build. RRDB variants are+ ``"RealESRGAN_x4plus"``, ``"RealESRNet_x4plus"``,+ ``"RealESRGAN_x4plus_anime_6B"`` and ``"RealESRGAN_x2plus"``;+ the lightweight variant is ``"small_sr"``.+ pretrained: If ``True``, load pretrained weights for the selected variant.+ upscale_factor: Integer scale used by the lightweight variant. Ignored by+ the RRDB variants, whose scale is fixed by ``model_name``.+ image_size: Optional fixed input size for the lightweight variant. It declares+ the size fed to the wrapper; it does not change the pre-processor, which+ always resizes to 224, so the output side stays ``224 * upscale_factor``.++ """++ model_name: str = "small_sr"+ pretrained: bool = True+ upscale_factor: int = 3+ image_size: Optional[int] = None+++class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):"""SuperResolution is a module that wraps an super resolution model."""name: str = "super_resolution"@@ -49,6 +81,67 @@ class SuperResolution(ModelBase, ONNXExportMixin):output_image_size: Optional[int]pseudo_image_size: Optional[int]+ def __init__(+ self,+ model: nn.Module,+ pre_processor: nn.Module,+ post_processor: nn.Module,+ name: Optional[str] = None,+ ) -> None:+ """Initialize SuperResolution.++ Args:+ model: The super-resolution network.+ pre_processor: Pre-processing module applied to the input images.+ post_processor: Post-processing module applied to the network output.+ name: Optional name, used by :meth:`save` for file names.++ """+ super().__init__()+ self.model = model.eval()+ self.pre_processor = pre_processor+ self.post_processor = post_processor+ if name is not None:+ self.name = name+ # `to_onnx` reads these three; builders overwrite the ones they know.+ # Without defaults they are annotations only, and export raises+ # AttributeError.+ self.input_image_size = None+ self.output_image_size = None+ self.pseudo_image_size = None++ @staticmethod+ def from_config(config: SuperResolutionConfig) -> "SuperResolution":+ """Build a super-resolution model from a configuration object.++ Dispatches to :class:`SmallSRBuilder` for the lightweight variant and to+ :class:`RRDBNetBuilder` for the RRDB variants.++ Args:+ config: Super-resolution configuration. See :class:`SuperResolutionConfig`.++ Returns:+ A :class:`SuperResolution` wrapper ready for inference.++ Raises:+ ValueError: If ``config.model_name`` is not a supported variant.++ """+ if config.model_name.lower() == "small_sr":+ return SmallSRBuilder.build(+ model_name=config.model_name,+ pretrained=config.pretrained,+ upscale_factor=config.upscale_factor,+ image_size=config.image_size,+ )+ if config.model_name not in _URLs:+ raise ValueError(+ f"Model {config.model_name} not found. Please choose from 'small_sr', "+ "'RealESRGAN_x4plus', 'RealESRNet_x4plus', 'RealESRGAN_x4plus_anime_6B', "+ "'RealESRGAN_x2plus'."+ )+ return RRDBNetBuilder.build(model_name=config.model_name, pretrained=config.pretrained)+@torch.inference_mode()def forward(self, images: Union[torch.Tensor, List[torch.Tensor]]) -> Union[torch.Tensor, List[torch.Tensor]]:"""Forward pass of the super resolution model.@@ -237,8 +330,9 @@ class SmallSRBuilder:upscale_factor: Integer scale used by ``SmallSRNetWrapper``.For example, ``3`` maps an input image of size ``H x W`` to anoutput image of approximately ``3H x 3W``.- image_size: Optional fixed input size. When provided, output metadata is- configured as ``image_size * upscale_factor``.+ image_size: Optional fixed input size. It declares the size fed to the+ wrapper and does not change the pre-processor, which always resizes to+ 224; the output side is therefore ``224 * upscale_factor``.Returns:A :class:`SuperResolution` instance configured with resizing pre-processing@@ -254,14 +348,16 @@ class SmallSRBuilder:sr = SuperResolution(model,- pre_processor=ResizePreProcessor(224, 224),+ pre_processor=ResizePreProcessor(_SMALL_SR_INPUT_SIZE, _SMALL_SR_INPUT_SIZE),post_processor=nn.Identity(),name=model_name,)+ # The pre-processor resizes to `_SMALL_SR_INPUT_SIZE` regardless of `image_size`,+ # so the wrapper's output side does not depend on the input size.+ sr.output_image_size = _SMALL_SR_INPUT_SIZE * upscale_factorif image_size is None:- sr.pseudo_image_size = 224+ sr.pseudo_image_size = _SMALL_SR_INPUT_SIZEelse:sr.input_image_size = image_size- sr.output_image_size = image_size * 3sr.pseudo_image_size = image_sizereturn srdiff --git a/tests/contrib/test_super_resolution.py b/tests/contrib/test_super_resolution.pynew file mode 100644index 000000000..848bd64e9--- /dev/null+++ b/tests/contrib/test_super_resolution.py@@ -0,0 +1,113 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++import pytest+import torch++from kornia.contrib.super_resolution import (+ RRDBNetBuilder,+ SmallSRBuilder,+ SuperResolution,+ SuperResolutionConfig,+)++from testing.base import BaseTester+++class TestSuperResolutionBuilders(BaseTester):+ """Pin the public super-resolution entry points.++ Regression test for #4291: ``SuperResolution`` did not implement ``ModelBase``'s+ abstract ``from_config`` and defined no ``__init__``, so every builder raised at+ construction. Nothing in ``tests/`` called the builders, which is why CI never+ noticed.+ """++ def test_small_sr_builder_builds_and_runs(self, device, dtype):+ model = SmallSRBuilder.build(pretrained=False).to(device, dtype)+ out = model(torch.rand(1, 3, 16, 16, device=device, dtype=dtype))+ assert out.shape[0] == 1+ assert out.shape[1] == 3++ def test_rrdbnet_builder_builds_and_runs(self, device, dtype):+ model = RRDBNetBuilder.build(pretrained=False).to(device, dtype)+ out = model(torch.rand(1, 3, 16, 16, device=device, dtype=dtype))+ assert out.shape[0] == 1+ assert out.shape[1] == 3++ @pytest.mark.parametrize("model_name", ["small_sr", "RealESRNet_x4plus"])+ def test_from_config_dispatches_to_both_families(self, device, dtype, model_name):+ config = SuperResolutionConfig(model_name=model_name, pretrained=False)+ model = SuperResolution.from_config(config).to(device, dtype)+ out = model(torch.rand(1, 3, 16, 16, device=device, dtype=dtype))+ assert out.shape[0] == 1+ assert out.shape[1] == 3++ def test_from_config_rejects_unknown_model_name(self):+ with pytest.raises(ValueError, match="small_sr"):+ SuperResolution.from_config(SuperResolutionConfig(model_name="not_a_model", pretrained=False))++ @pytest.mark.parametrize("builder", [SmallSRBuilder, RRDBNetBuilder])+ def test_onnx_metadata_is_initialised(self, builder):+ """``to_onnx`` reads these three; without defaults they are annotations only.++ Regression test for the review of #4335: an ``__init__`` that does not set them+ leaves export raising ``AttributeError``.+ """+ model = builder.build(pretrained=False)+ assert model.pseudo_image_size is None or isinstance(model.pseudo_image_size, int)+ assert model.input_image_size is None or isinstance(model.input_image_size, int)+ assert model.output_image_size is None or isinstance(model.output_image_size, int)++ def test_rrdbnet_onnx_metadata_defaults_to_none(self):+ """``RRDBNetBuilder`` sets none of the three, so they must default to ``None``."""+ model = RRDBNetBuilder.build(pretrained=False)+ assert model.input_image_size is None+ assert model.output_image_size is None+ assert model.pseudo_image_size is None++ @pytest.mark.parametrize("builder", [SmallSRBuilder, RRDBNetBuilder])+ def test_to_onnx_exports(self, builder):+ """Both families export; this fails with ``AttributeError`` if the metadata is unset."""+ pytest.importorskip("onnx")+ pytest.importorskip("onnxscript")+ builder.build(pretrained=False).to_onnx(save=False)++ @pytest.mark.parametrize(("upscale_factor", "image_size"), [(2, 32), (3, None), (4, 64)])+ def test_output_image_size_matches_the_real_forward(self, device, dtype, upscale_factor, image_size):+ """``output_image_size`` must equal what a forward actually returns.++ The pre-processor resizes every input to 224 before the network, so the output+ side is ``224 * upscale_factor`` and does not depend on ``image_size``. Pinning+ the attribute alone let it disagree with the model it describes.+ """+ model = SmallSRBuilder.build(pretrained=False, upscale_factor=upscale_factor, image_size=image_size).to(+ device, dtype+ )+ out = model(torch.rand(1, 3, 32, 32, device=device, dtype=dtype))+ assert out.shape[-1] == model.output_image_size+ assert out.shape[-2] == model.output_image_size+ assert model.output_image_size == 224 * upscale_factor++ def test_onnx_export_shape_matches_the_real_forward(self):+ """The static size handed to ``to_onnx`` must be the one the graph produces."""+ pytest.importorskip("onnx")+ pytest.importorskip("onnxscript")+ model = SmallSRBuilder.build(pretrained=False, upscale_factor=2, image_size=32)+ exported = model.to_onnx(save=False)+ out_dim = exported.graph.output[0].type.tensor_type.shape.dim[-1]+ assert out_dim.dim_value == model.output_image_sizediff --git a/tests/models/test_rrdbnet.py b/tests/models/test_rrdbnet.pyindex d69d11c21..aaea0fd2e 100644--- a/tests/models/test_rrdbnet.py+++ b/tests/models/test_rrdbnet.py@@ -318,35 +318,22 @@ class TestRRDBNetBuilder:("RealESRGAN_x2plus", 2, 23),],)- def test_build_selects_the_vendored_rrdbnet(self, monkeypatch, model_name, scale, num_block):- # `SuperResolution` cannot be instantiated today (`ModelBase.from_config` is abstract --- # kornia#4291, a pre-existing defect that also skips this builder in the export survey), so- # the wrapper is stubbed out to reach the model the builder constructs. Once #4291 is fixed,- # drop the stub and assert on the returned `SuperResolution` directly.- captured = {}-- def record(model, **kwargs):- captured["model"] = model- captured["kwargs"] = kwargs- return model-- monkeypatch.setattr(super_resolution_module, "SuperResolution", record)-+ def test_build_selects_the_vendored_rrdbnet(self, model_name, scale, num_block):returned = RRDBNetBuilder.build(model_name, pretrained=False)+ assert isinstance(returned, super_resolution_module.SuperResolution)- model = captured["model"]- assert model is returned+ model = returned.modelassert isinstance(model, RRDBNet)assert model.scale == scaleassert len(model.body) == num_blockassert model.conv_first.out_channels == 64 # num_feat=64assert model.body[0].rdb1.conv1.out_channels == 32 # num_grow_ch=32assert not model.training- assert captured["kwargs"]["name"] == model_name+ assert returned.name == model_name# the rest of `build`'s contract: no pre-processing, outputs clamped back into [0, 1]- assert isinstance(captured["kwargs"]["pre_processor"], nn.Identity)- post_processor = captured["kwargs"]["post_processor"]+ assert isinstance(returned.pre_processor, nn.Identity)+ post_processor = returned.post_processorassert isinstance(post_processor, OutputRangePostProcessor)assert (post_processor.min_val, post_processor.max_val) == (0.0, 1.0)