Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): preserve precision of Python scalar parameters (#5380)

Karnajeet Gosavi0facf537fd5b
diff --git a/changelog.d/5380.fixed.md b/changelog.d/5380.fixed.md
new file mode 100644
index 000000000..2a94b699c
--- /dev/null
+++ b/changelog.d/5380.fixed.md
@@ -0,0 +1 @@
+`Normalize`, `Denormalize` and `Rescale` keep Python-number `mean`, `std` and `factor` arguments as Python numbers and apply them in the input's dtype and device, so a float64 input no longer gets a float32-rounded constant. Such arguments are no longer registered as buffers and `repr` shows them as given; tensor arguments are still non-persistent buffers that move with `.to()`.
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 543923978..26d9ffaea 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -70,29 +70,15 @@ class Normalize(nn.Module):
) -> None:
super().__init__()
- if isinstance(mean, (int, float)):
- mean = torch.tensor([mean])
-
- if isinstance(std, (int, float)):
- std = torch.tensor([std])
-
- if isinstance(mean, (tuple, list)):
- mean = torch.tensor(mean)[None]
-
- if isinstance(std, (tuple, list)):
- std = torch.tensor(std)[None]
-
- # 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)
+ if isinstance(mean, torch.Tensor):
+ self.register_buffer("mean", mean, persistent=False)
+ else:
+ self.mean = mean
+
+ if isinstance(std, torch.Tensor):
+ self.register_buffer("std", std, persistent=False)
+ else:
+ self.std = std
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""Normalize an input tensor channel-wise with this module's statistics.
@@ -109,7 +95,15 @@ class Normalize(nn.Module):
A tensor with the same shape as ``input`` whose channel values are
normalized by ``(x - mean) / std``.
"""
- return normalize(input, self.mean, self.std)
+ # A Python number becomes (1,) and a sequence (1, *shape), the shapes the
+ # constructor used to store, built in the input dtype so float64 keeps its bits.
+ mean = self.mean
+ std = self.std
+ if not isinstance(mean, torch.Tensor):
+ mean = torch.as_tensor(mean, device=input.device, dtype=input.dtype)[None]
+ if not isinstance(std, torch.Tensor):
+ std = torch.as_tensor(std, device=input.device, dtype=input.dtype)[None]
+ return normalize(input, mean, std)
def __repr__(self) -> str:
repr = f"(mean={self.mean}, std={self.std})"
@@ -235,24 +229,15 @@ class Denormalize(nn.Module):
def __init__(self, mean: Union[torch.Tensor, float], std: Union[torch.Tensor, float]) -> None:
super().__init__()
- # 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)
+ if isinstance(mean, torch.Tensor):
+ self.register_buffer("mean", mean, persistent=False)
+ else:
+ self.mean = mean
+
+ if isinstance(std, torch.Tensor):
+ self.register_buffer("std", std, persistent=False)
+ else:
+ self.std = std
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""Restore scale/offset from a tensor normalized by mean and std.
@@ -268,7 +253,17 @@ class Denormalize(nn.Module):
A tensor with the same shape as ``input`` where each channel is
transformed by ``x * std + mean``.
"""
- return denormalize(input, self.mean, self.std)
+ # A Python number becomes (1,) and a sequence keeps its own shape, as the
+ # constructor used to store them: a (C,) list is still checked against the
+ # channel count, a (B, C) list still gives per-sample statistics, and the
+ # ONNX branch, which indexes ``mean.shape[0]``, never sees a 0-d tensor.
+ mean = self.mean
+ std = self.std
+ if not isinstance(mean, torch.Tensor):
+ mean = torch.atleast_1d(torch.as_tensor(mean, device=input.device, dtype=input.dtype))
+ if not isinstance(std, torch.Tensor):
+ std = torch.atleast_1d(torch.as_tensor(std, device=input.device, dtype=input.dtype))
+ return denormalize(input, mean, std)
def __repr__(self) -> str:
repr = f"(mean={self.mean}, std={self.std})"
diff --git a/kornia/enhance/rescale.py b/kornia/enhance/rescale.py
index f3682f52c..f3d3b8ae8 100644
--- a/kornia/enhance/rescale.py
+++ b/kornia/enhance/rescale.py
@@ -25,8 +25,10 @@ class Rescale(nn.Module):
r"""Initialize the Rescale operator.
Convention:
- factor is a scalar float or 0-D tensor and multiplies every element;
- it is stored as a module buffer, so ``.to()`` device and dtype moves apply to it.
+ factor is a scalar float or 0-D tensor and multiplies every element.
+ A float is kept as a Python number and applied like one: a float64 input keeps
+ its precision and an integer input promotes to the default float dtype. A tensor
+ is stored as a non-persistent buffer, so ``.to()`` moves apply to it.
Args:
factor: The scaling factor. Could be a float or a 0-d torch.Tensor.
@@ -36,15 +38,12 @@ class Rescale(nn.Module):
def __init__(self, factor: Union[float, torch.Tensor]) -> None:
super().__init__()
if isinstance(factor, float):
- factor = torch.tensor(factor)
- elif not isinstance(factor, torch.Tensor) or factor.ndim != 0:
+ self.factor = factor
+ elif isinstance(factor, torch.Tensor) and factor.ndim == 0:
+ self.register_buffer("factor", factor, persistent=False)
+ else:
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.
@@ -58,4 +57,6 @@ class Rescale(nn.Module):
A tensor with the same shape as ``input``, where each element is
multiplied by ``self.factor``.
"""
+ # A float factor multiplies as a Python number: float64 keeps its bits, half
+ # inputs are scaled in float32 arithmetic, and integer inputs promote to float.
return input * self.factor
diff --git a/kornia/models/segmentation/segmentation_models.py b/kornia/models/segmentation/segmentation_models.py
index 85d550e09..90736c9c9 100644
--- a/kornia/models/segmentation/segmentation_models.py
+++ b/kornia/models/segmentation/segmentation_models.py
@@ -132,8 +132,8 @@ class SegmentationModelsBuilder:
# Rescale the [0, 1] input to [0, 255] if the network expects it. Multiply by 255, which every
# dtype stores exactly, rather than divide by the reciprocal: bfloat16 rounds 1/255 to 0.0039368,
- # a ~254.0 multiplier that maps 0.5 to 127.0 instead of 127.5. `Rescale` holds the factor as a
- # 0-d tensor and exports to ONNX from any device.
+ # a ~254.0 multiplier that maps 0.5 to 127.0 instead of 127.5. `Rescale` keeps a float factor as a
+ # Python number, so it exports to ONNX from any device.
input_range = preproc_params["input_range"]
if input_range[1] == 255:
proc_sequence.append(kornia.enhance.Rescale(255.0))
diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.py
index effd6fe94..86a1739f4 100644
--- a/tests/enhance/test_normalize.py
+++ b/tests/enhance/test_normalize.py
@@ -45,7 +45,7 @@ class TestNormalize(BaseTester):
def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
- repr = "Normalize(mean=tensor([[0.5000]]), std=tensor([[0.1000]]))"
+ repr = "Normalize(mean=[0.5], std=[0.1])"
assert str(kornia.enhance.Normalize(mean, std)) == repr
def test_normalize(self, device, dtype):
@@ -226,21 +226,14 @@ class TestNormalize(BaseTester):
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.
- """
+ """Tensor arguments move with the module; Python constants follow the input."""
@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),
+ "Rescale": kornia.enhance.Rescale(torch.tensor(2.0)),
}
def test_constants_are_registered_buffers(self, device, dtype):
@@ -252,7 +245,6 @@ class TestNormalizeConstantsAreBuffers(BaseTester):
[
("Normalize", ("mean", "std")),
("Denormalize", ("mean", "std")),
- ("Denormalize-float", ("mean", "std")),
("Rescale", ("factor",)),
],
)
@@ -279,10 +271,48 @@ class TestNormalizeConstantsAreBuffers(BaseTester):
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."""
+ """Scalar arguments stay as Python values and are materialized per input."""
module = kornia.enhance.Denormalize(0.0, 255.0)
- assert isinstance(module.mean, torch.Tensor)
- assert isinstance(module.std, torch.Tensor)
+ assert module.mean == 0.0
+ assert module.std == 255.0
+ assert not list(module.buffers())
+
+ def test_python_constants_preserve_float64_precision(self):
+ x = torch.full((1, 3, 1, 1), 0.3, dtype=torch.float64)
+ normalize = kornia.enhance.Normalize(0.1, 0.3).double()
+ denormalize = kornia.enhance.Denormalize(0.1, 0.3).double()
+ rescale = kornia.enhance.Rescale(0.1).double()
+
+ assert torch.equal(normalize(x), (x - 0.1) / 0.3)
+ assert torch.equal(denormalize(x), x * 0.3 + 0.1)
+ assert torch.equal(rescale(x), x * 0.1)
+
+ def test_normalize_sequence_constants_preserve_float64_precision(self):
+ x = torch.full((1, 2, 1, 1), 0.3, dtype=torch.float64)
+ module = kornia.enhance.Normalize((0.1, 0.2), (0.3, 0.4))
+ mean = torch.tensor([[0.1, 0.2]], dtype=torch.float64)
+ std = torch.tensor([[0.3, 0.4]], dtype=torch.float64)
+
+ assert torch.equal(module(x), (x - mean.reshape(1, 2, 1, 1)) / std.reshape(1, 2, 1, 1))
+
+ def test_denormalize_sequence_is_checked_against_the_channels(self):
+ """A (C,) list must not broadcast a 1-channel input to C channels."""
+ module = kornia.enhance.Denormalize([0.1, 0.2, 0.3], [1.0, 1.0, 1.0])
+ with pytest.raises(ValueError):
+ module(torch.ones(2, 1, 4, 4))
+
+ def test_denormalize_nested_sequence_gives_per_sample_statistics(self):
+ x = torch.ones(2, 3, 1, 1)
+ out = kornia.enhance.Denormalize([[0.0] * 3, [1.0] * 3], [[1.0] * 3, [2.0] * 3])(x)
+ expected = torch.tensor([1.0, 3.0]).view(2, 1, 1, 1).expand(2, 3, 1, 1)
+ assert torch.equal(out, expected)
+
+ def test_python_constants_take_the_onnx_branch(self, monkeypatch):
+ """The ONNX branch indexes ``mean.shape[0]``, so a 0-d constant would raise IndexError."""
+ monkeypatch.setattr(torch.onnx, "is_in_onnx_export", lambda: True)
+ x = torch.full((1, 3, 2, 2), 0.5)
+ self.assert_close(kornia.enhance.Normalize(0.1, 0.4)(x), torch.full_like(x, 1.0))
+ self.assert_close(kornia.enhance.Denormalize(0.1, 0.4)(x), torch.full_like(x, 0.3))
def test_forward_is_unchanged(self, device, dtype):
x = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
@@ -321,9 +351,7 @@ class TestDenormalize(BaseTester):
def test_smoke(self, device, dtype):
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]))"
+ repr = "Denormalize(mean=[0.5], std=[0.1])"
assert str(kornia.enhance.Denormalize(mean, std)) == repr
def test_denormalize(self, device, dtype):
diff --git a/tests/enhance/test_rescale.py b/tests/enhance/test_rescale.py
index 78989a31e..0df4e9901 100644
--- a/tests/enhance/test_rescale.py
+++ b/tests/enhance/test_rescale.py
@@ -76,3 +76,15 @@ class TestRescale(BaseTester):
x = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
op = torch_optimizer(r)
self.assert_close(op(x), r(x))
+
+ def test_float_factor_promotes_integer_input(self, device):
+ x = torch.arange(256, device=device, dtype=torch.uint8)
+ out = Rescale(1 / 255.0)(x)
+ assert out.dtype == torch.float32
+ self.assert_close(out, torch.arange(256, device=device, dtype=torch.float32) / 255.0)
+
+ def test_float_factor_is_not_rounded_to_a_half_input(self, device):
+ """bfloat16 rounds 1/255 to 0.0039368; the product must use the float factor and round once."""
+ x = torch.arange(256, device=device, dtype=torch.float32).to(torch.bfloat16)
+ expected = (x.float() * (1 / 255.0)).to(torch.bfloat16)
+ assert torch.equal(Rescale(1 / 255.0)(x), expected)