π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): promote integer input to float in normalize/denormalize (#5403) (#5407)
Muhammad Talha8eaf69292dbf
diff --git a/changelog.d/5407.breaking.md b/changelog.d/5407.breaking.mdnew file mode 100644index 000000000..c4be63fd4--- /dev/null+++ b/changelog.d/5407.breaking.md@@ -0,0 +1 @@+`kornia.enhance.denormalize` and `Denormalize` return torch's default floating dtype (float32 unless changed with `torch.set_default_dtype`) for an integer or bool input, as `normalize` already did. They used to compute in and return the input's integer dtype, which was exact for integral statistics that did not overflow: `denormalize` of a uint8 `[0, 50, 100]` with `mean=10.0, std=2.0` returned uint8 `[10, 110, 210]` and now returns float32 `[10.0, 110.0, 210.0]`. Both functions now convert an integer input before applying `mean` and `std`, so under the default float32 an integer value above 2**24 is rounded first. Cast the result back, for example with `.round().clamp(0, 255).to(torch.uint8)`, where integer output is needed.diff --git a/changelog.d/5407.fixed.md b/changelog.d/5407.fixed.mdnew file mode 100644index 000000000..73c17dbae--- /dev/null+++ b/changelog.d/5407.fixed.md@@ -0,0 +1 @@+`kornia.enhance.normalize`, `denormalize` and the `Normalize`/`Denormalize` modules no longer cast `mean` and `std` to an integer input's dtype. For a uint8 image a fractional statistic truncated to 0, so `normalize(x, 0.5, 0.5)` returned `nan`/`inf`, and the arithmetic wrapped around in the integer dtype: `normalize([0, 128, 255], 100.0, 50.0)` returned `[3.12, 0.56, 3.10]` instead of `[-2.0, 0.56, 3.1]`, and `denormalize([0, 128, 255], 10.0, 2.0)` returned `[10, 10, 8]` instead of `[10, 266, 520]`. An integer or bool input is now converted to torch's default floating dtype first; a bool input, which used to raise `NotImplementedError`, is accepted. Floating and complex inputs are unchanged, and pixel values are not rescaled: give `mean` and `std` in the 0-255 scale for a uint8 image.diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 26d9ffaea..d06025ffd 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -27,6 +27,19 @@ from kornia.image.utils import perform_keep_shape_image__all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_min_max"]+def _promote_integer_data(data: torch.Tensor) -> torch.Tensor:+ r"""Return ``data`` in torch's default floating dtype if it is an integer or bool tensor.++ :func:`normalize` and :func:`denormalize` cast ``mean`` and ``std`` to the dtype of ``data``. For an integer+ tensor that truncates a fractional statistic to an integer (``0.5`` becomes ``0``) and runs the subtraction and+ ``addcmul`` in the integer dtype, where the result wraps. Promoting the data first, as ``data * 0.5`` does, keeps+ a fractional statistic and computes in floating point. Floating and complex tensors are returned untouched.+ """+ if data.is_floating_point() or data.is_complex():+ return data+ return data.to(torch.get_default_dtype())++class Normalize(nn.Module):r"""Normalize a torch.Tensor image with mean and standard deviation.@@ -48,6 +61,9 @@ class Normalize(nn.Module):- Input: Image torch.Tensor of size :math:`(B, C, *)`.- Output: Normalised torch.Tensor with same size as input :math:`(B, C, *)`.+ Note:+ An integer or bool input is converted to torch's default floating dtype first; see :func:`normalize`.+Examples:>>> x = torch.rand(1, 4, 3, 3)>>> out = Normalize(0.0, 255.)(x)@@ -95,6 +111,10 @@ class Normalize(nn.Module):A tensor with the same shape as ``input`` whose channel values arenormalized by ``(x - mean) / std``."""+ # Promote before the statistics are built in the input dtype: for an integer input a fractional Python+ # statistic would otherwise truncate here, before `normalize` sees it.+ input = _promote_integer_data(input)+# 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@@ -130,12 +150,22 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torcReturn:Normalised torch.Tensor with same size as input :math:`(B, C, *)`.+ Note:+ An integer or bool ``data`` is converted to torch's default floating dtype (float32 unless changed) before+ ``mean`` and ``std`` are applied, so a fractional statistic is not truncated and the result is floating.+ Floating and complex inputs keep their dtype. Pixel values are not rescaled: give ``mean`` and ``std`` in the+ 0-255 scale for a uint8 image.+Examples:>>> x = torch.rand(1, 4, 3, 3)>>> out = normalize(x, torch.tensor([0.0]), torch.tensor([255.]))>>> out.shapetorch.Size([1, 4, 3, 3])+ >>> x = torch.tensor([[[[0, 255]]]], dtype=torch.uint8)+ >>> normalize(x, 127.5, 127.5)+ tensor([[[[-1., 1.]]]])+>>> x = torch.rand(1, 4, 3, 3)>>> mean = torch.zeros(4)>>> std = 255. * torch.ones(4)@@ -144,6 +174,7 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torctorch.Size([1, 4, 3, 3])"""+ data = _promote_integer_data(data)shape = data.shapeif torch.onnx.is_in_onnx_export():@@ -211,6 +242,9 @@ class Denormalize(nn.Module):- Input: Image torch.Tensor of size :math:`(B, C, *)`.- Output: Denormalised torch.Tensor with same size as input :math:`(B, C, *)`.+ Note:+ An integer or bool input is converted to torch's default floating dtype first; see :func:`denormalize`.+Examples:>>> x = torch.rand(1, 4, 3, 3)>>> out = Denormalize(0.0, 255.)(x)@@ -253,6 +287,9 @@ class Denormalize(nn.Module):A tensor with the same shape as ``input`` where each channel istransformed by ``x * std + mean``."""+ # Promote before the statistics are built in the input dtype, as in `Normalize.forward`.+ input = _promote_integer_data(input)+# 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@@ -295,12 +332,21 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: UnionReturn:Denormalised torch.Tensor with same size as input :math:`(B, C, *)`.+ Note:+ An integer or bool ``data`` is converted to torch's default floating dtype (float32 unless changed) before+ ``mean`` and ``std`` are applied, so the result is floating and cannot wrap. Floating and complex inputs keep+ their dtype.+Examples:>>> x = torch.rand(1, 4, 3, 3)>>> out = denormalize(x, 0.0, 255.)>>> out.shapetorch.Size([1, 4, 3, 3])+ >>> x = torch.tensor([[[[0, 255]]]], dtype=torch.uint8)+ >>> denormalize(x, 10., 2.)+ tensor([[[[ 10., 520.]]]])+>>> x = torch.rand(1, 4, 3, 3, 3)>>> mean = torch.zeros(1, 4)>>> std = 255. * torch.ones(1, 4)@@ -309,6 +355,7 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Uniontorch.Size([1, 4, 3, 3, 3])"""+ data = _promote_integer_data(data)shape = data.shapeif torch.onnx.is_in_onnx_export():diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.pyindex 86a1739f4..2d2d9b156 100644--- a/tests/enhance/test_normalize.py+++ b/tests/enhance/test_normalize.py@@ -459,6 +459,121 @@ class TestDenormalize(BaseTester):pass+class TestNormalizeIntegerInput(BaseTester):+ """`normalize` and `denormalize` used to cast mean and std to an integer input's dtype (#5403).++ A fractional statistic then truncated to an integer (0.5 -> 0) and the arithmetic ran in the integer dtype, so+ `normalize` divided by zero and `denormalize` wrapped. Integer and bool inputs are now promoted to torch's+ default floating dtype first, as `x * 0.5` does, and both functions return that dtype.+ """++ INTEGER_DTYPES = (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64, torch.bool)++ @staticmethod+ def _image(device, input_dtype):+ g = torch.Generator().manual_seed(0)+ values = torch.randint(0, 2 if input_dtype is torch.bool else 128, (2, 3, 4, 5), generator=g)+ return values.to(device, input_dtype)++ @pytest.mark.parametrize("input_dtype", INTEGER_DTYPES)+ @pytest.mark.parametrize("fn", ["normalize", "denormalize"])+ @pytest.mark.parametrize("stats", ["float", "tensor"])+ def test_integer_input_matches_the_float_path_5403(self, device, input_dtype, fn, stats):+ # The same values held as float32 are the reference: nothing is truncated, wrapped or non-finite.+ op = getattr(kornia.enhance, fn)+ img = self._image(device, input_dtype)+ if stats == "float":+ mean, std = 0.5, 0.25+ else:+ mean = torch.tensor([0.5, 0.25, 0.75], device=device)+ std = torch.tensor([0.25, 0.5, 2.0], device=device)++ out = op(img, mean, std)++ assert out.dtype == torch.get_default_dtype()+ assert out.shape == img.shape+ assert torch.isfinite(out).all()+ self.assert_close(out, op(img.to(torch.get_default_dtype()), mean, std))++ def test_issue_values_5403(self, device):+ x = torch.tensor([[[[0, 128, 255]]]], device=device, dtype=torch.uint8)++ # 0.5 used to truncate to 0: [nan, inf, inf]+ self.assert_close(+ kornia.enhance.normalize(x, 0.5, 0.5),+ torch.tensor([[[[-1.0, 255.0, 509.0]]]], device=device),+ )+ # 0 - 100 used to wrap to 156 in uint8: [3.12, 0.56, 3.10]+ self.assert_close(+ kornia.enhance.normalize(x, 100.0, 50.0),+ torch.tensor([[[[-2.0, 0.56, 3.1]]]], device=device),+ )+ # used to return [0, 0, 0] uint8+ self.assert_close(+ kornia.enhance.denormalize(x, 0.5, 0.5),+ torch.tensor([[[[0.5, 64.5, 128.0]]]], device=device),+ )+ # 128 * 2 + 10 and 255 * 2 + 10 used to wrap in uint8: [10, 10, 8]+ self.assert_close(+ kornia.enhance.denormalize(x, 10.0, 2.0),+ torch.tensor([[[[10.0, 266.0, 520.0]]]], device=device),+ )++ @pytest.mark.parametrize("module", ["Normalize", "Denormalize"])+ def test_modules_promote_integer_input_5403(self, device, module):+ img = self._image(device, torch.uint8)+ op = getattr(kornia.enhance, module)(0.5, 0.25).to(device)++ out = op(img)++ assert out.dtype == torch.get_default_dtype()+ assert torch.isfinite(out).all()+ self.assert_close(out, op(img.to(torch.get_default_dtype())))++ def test_uint8_pixel_scale_round_trip_5403(self, device):+ # Statistics in the 0-255 pixel scale are what a caller holding a uint8 image passes.+ mean = torch.tensor([123.675, 116.28, 103.53], device=device)+ std = torch.tensor([58.395, 57.12, 57.375], device=device)+ img = torch.randint(0, 256, (2, 3, 6, 7), device=device, dtype=torch.uint8)++ normalized = kornia.enhance.normalize(img, mean, std)++ assert normalized.dtype == torch.get_default_dtype()+ assert normalized.abs().max() < 3.0+ self.assert_close(kornia.enhance.denormalize(normalized, mean, std), img.to(normalized.dtype))++ def test_integer_input_follows_the_default_dtype_5403(self, device):+ # The promotion target is torch's default floating dtype, the same as `x * 0.5`, not a hardcoded float32.+ if device.type == "mps":+ pytest.skip("MPS does not support float64")+ img = self._image(device, torch.uint8)+ previous = torch.get_default_dtype()+ torch.set_default_dtype(torch.float64)+ try:+ assert (img * 0.5).dtype == torch.float64+ assert kornia.enhance.normalize(img, 0.5, 0.25).dtype == torch.float64+ assert kornia.enhance.denormalize(img, 0.5, 0.25).dtype == torch.float64+ finally:+ torch.set_default_dtype(previous)++ def test_float_input_keeps_its_dtype_5403(self, device, dtype):+ # Only integer and bool inputs are promoted; a floating input is returned in its own dtype.+ img = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)+ assert kornia.enhance.normalize(img, 0.5, 0.25).dtype == dtype+ assert kornia.enhance.denormalize(img, 0.5, 0.25).dtype == dtype++ @pytest.mark.parametrize("fn", ["normalize", "denormalize"])+ def test_complex_input_is_not_cast_5403(self, device, fn):+ # Promoting a complex tensor to a real dtype would drop its imaginary part, so it must stay complex.+ op = getattr(kornia.enhance, fn)+ img = torch.complex(torch.rand(1, 3, 2, 2), torch.rand(1, 3, 2, 2)).to(device)++ out = op(img, 0.5, 0.25)++ assert out.dtype == img.dtype+ assert out.imag.abs().sum() > 0++class TestNormalizeMinMax(BaseTester):@pytest.mark.parametrize("shape", [(4, 5), (3, 4, 5), (2, 3, 4, 5), (2, 2, 3, 4, 5)])def test_noncontiguous(self, shape, device, dtype):