Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): register Normalize/Denormalize/Rescale constants as buffers (#4330)

Dipak Chaudharid8fc98b697d5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e09448158..f297b6986 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -411,6 +411,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
read as the vertices: an out-of-bounds error with one box, and three `(1, 3)` tensors -- one value
per coordinate rather than per box -- with eight. (#4248, #4351)
+* `Normalize`, `Denormalize` and `Rescale` register their constants (`mean`, `std`, `factor`) as
+ non-persistent buffers instead of plain attributes, so `.to(device)` moves them with the module.
+ Previously they stayed on the CPU: eager tolerates the mix, but `torch.export` traces with fake
+ tensors and refused it, so exporting a preprocessing pipeline from an accelerator failed while
+ the same pipeline exported fine from the CPU. `Denormalize` now coerces a scalar `mean`/`std` to
+ a 1-D tensor, as `Normalize` already did, which changes its `__repr__` to match `Normalize`'s and
+ lets a scalar `Denormalize` reach the ONNX export branch instead of raising `IndexError` there.
+ The buffers are non-persistent, so `state_dict()` is unchanged and existing checkpoints still
+ load. (#4323, #4330)
+
* `RenderingDeFMO` (used by `DeFMO`) no longer crashes on a half-precision forward pass. Its rendering
time-steps (`times`) were a plain Python attribute, not a registered buffer, so `nn.Module.to()` never
moved it; `forward` re-derived `times`'s device from the input on every call but never its dtype, so
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 74068d576..6b0f63722 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -77,8 +77,17 @@ class Normalize(nn.Module):
if isinstance(std, (tuple, list)):
std = torch.tensor(std)[None]
- self.mean = mean
- self.std = std
+ # Buffers, not plain attributes: `.to(device)` has to move them, or a
+ # module living on an accelerator keeps CPU constants. Eager tolerates
+ # the mix (a broadcastable CPU tensor combines with a CUDA/MPS one),
+ # which is why this went unnoticed, but `torch.export` traces with fake
+ # tensors and refuses it.
+ #
+ # persistent=False: these are constructor arguments, not learned state.
+ # Putting them in `state_dict()` would make every existing checkpoint
+ # report unexpected keys, for values the constructor already supplies.
+ self.register_buffer("mean", mean, persistent=False)
+ self.register_buffer("std", std, persistent=False)
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""Normalize an input tensor channel-wise with this module's statistics.
@@ -209,8 +218,24 @@ class Denormalize(nn.Module):
def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
super().__init__()
- self.mean = mean
- self.std = std
+ # A float has to become a tensor before it can be a buffer. Wrap a
+ # scalar in a list so it becomes 1-D, exactly as `Normalize` does: the
+ # ONNX export branch indexes `mean.shape[0]`, which a 0-d tensor would
+ # turn into `IndexError: tuple index out of range`.
+ if isinstance(mean, (int, float)):
+ mean = torch.tensor([mean])
+ elif not isinstance(mean, torch.Tensor):
+ mean = torch.tensor(mean)
+
+ if isinstance(std, (int, float)):
+ std = torch.tensor([std])
+ elif not isinstance(std, torch.Tensor):
+ std = torch.tensor(std)
+
+ # See Normalize: buffers so `.to(device)` moves them; non-persistent so
+ # they stay out of `state_dict()`.
+ self.register_buffer("mean", mean, persistent=False)
+ self.register_buffer("std", std, persistent=False)
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""Restore scale/offset from a tensor normalized by mean and std.
diff --git a/kornia/enhance/rescale.py b/kornia/enhance/rescale.py
index a21f85424..7c945b441 100644
--- a/kornia/enhance/rescale.py
+++ b/kornia/enhance/rescale.py
@@ -32,11 +32,14 @@ class Rescale(nn.Module):
def __init__(self, factor: Union[float, torch.Tensor]) -> None:
super().__init__()
if isinstance(factor, float):
- self.factor = torch.tensor(factor)
- else:
- if not isinstance(factor, torch.Tensor) or factor.ndim != 0:
- raise TypeError(f"Expected factor to be a float or a 0-d torch.Tensor, got {factor}.")
- self.factor = factor
+ factor = torch.tensor(factor)
+ elif not isinstance(factor, torch.Tensor) or factor.ndim != 0:
+ raise TypeError(f"Expected factor to be a float or a 0-d torch.Tensor, got {factor}.")
+
+ # A buffer, so `.to(device)` moves it with the module. Non-persistent:
+ # the factor is a constructor argument, not learned state, and adding
+ # it to `state_dict()` would break existing checkpoints.
+ self.register_buffer("factor", factor, persistent=False)
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""Multiply the input tensor by the configured scaling factor.
diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.py
index 5af2a745c..f44c277f0 100644
--- a/tests/enhance/test_normalize.py
+++ b/tests/enhance/test_normalize.py
@@ -166,11 +166,105 @@ class TestNormalize(BaseTester):
pass
+class TestNormalizeConstantsAreBuffers(BaseTester):
+ """`mean`/`std`/`factor` must move with the module.
+
+ They were plain tensor attributes, so `.to(device)` left them behind. Eager
+ tolerates the mix -- a broadcastable CPU tensor combines with a CUDA/MPS one
+ -- which is why it went unnoticed, but `torch.export` traces with fake
+ tensors and refuses it, so exporting from an accelerator failed.
+ """
+
+ @staticmethod
+ def _modules():
+ return {
+ "Normalize": kornia.enhance.Normalize(torch.zeros(3), torch.ones(3)),
+ "Denormalize": kornia.enhance.Denormalize(torch.zeros(3), torch.ones(3)),
+ "Denormalize-float": kornia.enhance.Denormalize(0.0, 255.0),
+ "Rescale": kornia.enhance.Rescale(2.0),
+ }
+
+ def test_constants_are_registered_buffers(self, device, dtype):
+ for name, module in self._modules().items():
+ assert list(module.buffers()), f"{name} registered no buffers"
+
+ @pytest.mark.parametrize(
+ "name,attrs",
+ [
+ ("Normalize", ("mean", "std")),
+ ("Denormalize", ("mean", "std")),
+ ("Denormalize-float", ("mean", "std")),
+ ("Rescale", ("factor",)),
+ ],
+ )
+ def test_to_moves_the_constants(self, name, attrs, device, dtype):
+ """dtype stands in for device, so the check runs on CPU-only CI.
+
+ Asserted on the attributes by name rather than by iterating buffers:
+ iterating would pass vacuously on a module that registered none, which
+ is exactly the bug.
+ """
+ moved = self._modules()[name].to(torch.float64)
+ for attr in attrs:
+ value = getattr(moved, attr)
+ assert isinstance(value, torch.Tensor), f"{name}.{attr} is not a tensor"
+ assert value.dtype == torch.float64, f"{name}.{attr} stayed {value.dtype} after .to(float64)"
+
+ def test_the_constants_stay_out_of_the_state_dict(self, device, dtype):
+ """They are constructor arguments, not learned state.
+
+ Registering them persistently would make every existing checkpoint
+ report unexpected keys, so they are non-persistent buffers.
+ """
+ for name, module in self._modules().items():
+ assert module.state_dict() == {}, f"{name} state_dict is not empty"
+
+ def test_denormalize_coerces_scalars(self, device, dtype):
+ """A float cannot be a buffer, and Normalize already coerced its own."""
+ module = kornia.enhance.Denormalize(0.0, 255.0)
+ assert isinstance(module.mean, torch.Tensor)
+ assert isinstance(module.std, torch.Tensor)
+
+ def test_forward_is_unchanged(self, device, dtype):
+ x = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+ mean = torch.zeros(3, device=device, dtype=dtype)
+ std = 2.0 * torch.ones(3, device=device, dtype=dtype)
+ self.assert_close(
+ kornia.enhance.Normalize(mean, std)(x),
+ kornia.enhance.normalize(x, mean, std),
+ )
+ self.assert_close(
+ kornia.enhance.Denormalize(mean, std)(x),
+ kornia.enhance.denormalize(x, mean, std),
+ )
+ self.assert_close(kornia.enhance.Rescale(2.0)(x), x * 2.0)
+
+ def test_smoke(self, device, dtype):
+ pass
+
+ def test_cardinality(self, device, dtype):
+ pass
+
+ def test_exception(self, device, dtype):
+ pass
+
+ def test_gradcheck(self, device):
+ pass
+
+ def test_module(self, device, dtype):
+ pass
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ pass
+
+
class TestDenormalize(BaseTester):
def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
- repr = "Denormalize(mean=[0.5], std=[0.1])"
+ # Tensors, matching TestNormalize above: Denormalize now coerces its
+ # arguments so they can be registered as buffers and move with `.to()`.
+ repr = "Denormalize(mean=tensor([0.5000]), std=tensor([0.1000]))"
assert str(kornia.enhance.Denormalize(mean, std)) == repr
def test_denormalize(self, device, dtype):
diff --git a/tests/models/test_segmentation_models.py b/tests/models/test_segmentation_models.py
index 2eb0f1032..19d5a1b60 100644
--- a/tests/models/test_segmentation_models.py
+++ b/tests/models/test_segmentation_models.py
@@ -189,10 +189,6 @@ class TestSemanticSegmentation(BaseTester):
pytest.importorskip("onnx")
ort = pytest.importorskip("onnxruntime")
pytest.importorskip("onnxscript")
- if device.type != "cpu":
- # `Normalize` keeps mean/std as plain tensor attributes that `.to(device)` does not move, so
- # exporting an accelerator-resident pipeline fails on a device mismatch (pre-existing).
- pytest.skip("export of a non-CPU pipeline is blocked by Normalize's tensor attributes")
params = {**IMAGENET_PARAMS, "input_space": "BGR", "input_range": [0, 255]}
pipeline = SegmentationModelsBuilder.get_preprocessing_pipeline(params).to(device).eval()
# Export tensor operations without the convenience I/O cache: torch.export in PyTorch 2.9