Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix normalization of non-contiguous images (#4580)

Shubham Padkonde0925e5d0198a
diff --git a/changelog.d/4580.fixed.md b/changelog.d/4580.fixed.md
new file mode 100644
index 000000000..3143e6b8d
--- /dev/null
+++ b/changelog.d/4580.fixed.md
@@ -0,0 +1 @@
+`normalize` and `normalize_min_max` now accept non-contiguous images, including through the `Normalize` and `RandomAutoContrast` augmentations.
diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.py
index a7c5bc401..8e41f19a7 100644
--- a/kornia/augmentation/_2d/intensity/auto_contrast.py
+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py
@@ -52,12 +52,8 @@ class RandomAutoContrast(IntensityAugmentationBase2D):
(``inf / inf``) and every other element comes back exactly ``0`` (a finite numerator over ``inf``).
``[-60000, 60000, 0, 1]`` in ``float16`` returns ``[0, nan, 0, 0]``.
- .. warning::
- A non-contiguous input -- anything :meth:`torch.Tensor.view` cannot reshape, such as a
- ``transpose``d or ``permute``d view -- raises a raw ``RuntimeError: view size is not compatible
- with input tensor's size and stride`` from :func:`kornia.enhance.normalize_min_max`, naming neither this
- class nor the fix (``.contiguous()``). Tracked in
- `#4577 <https://github.com/kornia/kornia/issues/4577>`_.
+ - non-contiguous input, such as a ``transpose``d or ``permute``d image, produces the same
+ values as its contiguous copy.
.. note::
This function internally uses :func:`kornia.enhance.normalize_min_max`. A channel with a single value
diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.py
index 8565686ec..ad25a5952 100644
--- a/kornia/augmentation/_2d/intensity/normalize.py
+++ b/kornia/augmentation/_2d/intensity/normalize.py
@@ -58,12 +58,8 @@ class Normalize(IntensityAugmentationBase2D):
inverts this class, up to float rounding, when both apply -- each draws its own ``p`` gate.
- the result is not clamped: moving an image out of ``[0, 1]`` is what this class is for.
- .. warning::
- A non-contiguous input -- anything :meth:`torch.Tensor.view` cannot reshape, such as a
- ``transpose``d or ``permute``d view -- raises a raw ``RuntimeError: view size is not compatible
- with input tensor's size and stride`` from :func:`kornia.enhance.normalize`, naming neither this
- class nor the fix (``.contiguous()``). Tracked in
- `#4577 <https://github.com/kornia/kornia/issues/4577>`_.
+ - non-contiguous input, such as a ``transpose``d or ``permute``d image, produces the same
+ values as its contiguous copy.
.. note::
This function internally uses :func:`kornia.enhance.normalize`.
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 6b0f63722..bf85f40e5 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -179,9 +179,9 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torc
mean = mean[..., None]
std = std[..., None]
- out: torch.Tensor = (data.view(shape[0], shape[1], -1) - mean) / std
+ out: torch.Tensor = (data.reshape(shape[0], shape[1], -1) - mean) / std
- return out.view(shape)
+ return out.reshape(shape)
class Denormalize(nn.Module):
@@ -379,9 +379,9 @@ def normalize_min_max(
shape = input.shape
B, C = shape[0], shape[1]
- x_reshaped = input.view(B, C, -1)
+ x_reshaped = input.reshape(B, C, -1)
x_min = x_reshaped.min(-1, keepdim=True)[0] # Shape: (B, C, 1)
x_max = x_reshaped.max(-1, keepdim=True)[0] # Shape: (B, C, 1)
x_out = (max_val - min_val) * (x_reshaped - x_min) / (x_max - x_min + eps) + min_val
- return x_out.view(shape)
+ return x_out.reshape(shape)
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 33638e0af..4bbcf0b6d 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -4719,6 +4719,11 @@ class TestRandomChannelDropout(BaseTester):
class TestNormalize(BaseTester):
+ def test_noncontiguous(self, device, dtype):
+ data = torch.rand(2, 3, 4, 5, device=device, dtype=dtype).transpose(-1, -2)
+ aug = Normalize(mean=0.5, std=0.25, p=1.0)
+ self.assert_close(aug(data), (data - 0.5) / 0.25)
+
# TODO: improve and implement more meaningful smoke tests e.g check for a consistent
# return values such a Tensor variable.
@pytest.mark.xfail(reason="might fail under windows OS due to printing preicision.")
@@ -5410,6 +5415,11 @@ class TestRandomTranslate(BaseTester):
class TestRandomAutoContrast(BaseTester):
torch.manual_seed(0) # for random reproductibility
+ def test_noncontiguous(self, device, dtype):
+ data = torch.rand(2, 3, 4, 5, device=device, dtype=dtype).transpose(-1, -2)
+ aug = kornia.augmentation.RandomAutoContrast(p=1.0)
+ self.assert_close(aug(data), aug(data.contiguous()))
+
def test_smoke_no_transform(self, device):
x_data = torch.rand(1, 2, 8, 9).to(device)
aug = kornia.augmentation.RandomAutoContrast()
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index cbfd7545e..c27d7195a 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -1777,16 +1777,9 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
self.assert_close(K.Denormalize(mean=mean, std=std, p=1.0)(normalized), image)
- # Issue #4577: `normalize` reshapes with `Tensor.view`, so a non-contiguous input raises a raw torch
- # error naming neither the class nor the fix. `RandomAutoContrast` reaches `normalize_min_max` and
- # fails the same way.
- # Snippet used to generate expected:
- # x = torch.rand(2, 3, 8, 8).transpose(2, 3)
- # torch.manual_seed(0); K.Normalize(mean=torch.tensor([0.5]), std=torch.tensor([0.5]), p=1.0)(x)
- # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> `RuntimeError: view size is not
- # compatible with input tensor's size and stride`; `.contiguous()` on the same view succeeds.
+ # Issue #4577: normalization preserves image values across contiguous and strided layouts.
@pytest.mark.parametrize("name", ["Normalize", "RandomAutoContrast"])
- def test_wart_non_contiguous_input_raises_a_raw_view_error_4577(self, device, dtype, name):
+ def test_convention_non_contiguous_input_matches_contiguous_4577(self, device, dtype, name):
factories = {
"Normalize": lambda: K.Normalize(
mean=torch.tensor([0.5], device=device, dtype=dtype),
@@ -1800,14 +1793,11 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
view = image.transpose(2, 3)
assert not view.is_contiguous()
torch.manual_seed(_FORWARD_SEED)
- with pytest.raises(RuntimeError, match="view size is not compatible") as excinfo:
- _sync(factories[name]()(view).device)
- # The frame that reshapes is `normalize` for Normalize and `normalize_min_max` for
- # RandomAutoContrast, which never calls `normalize`; the class warnings name that function.
- assert excinfo.traceback[-1].name == {"Normalize": "normalize", "RandomAutoContrast": "normalize_min_max"}[name]
- # The same values, made contiguous, go through -- so it is the layout and not the numbers.
+ actual = factories[name]()(view)
torch.manual_seed(_FORWARD_SEED)
- assert factories[name]()(view.contiguous()).shape == view.shape
+ expected = factories[name]()(view.contiguous())
+ assert actual.shape == view.shape
+ self.assert_close(actual, expected)
# Row 6c-16: a ``(B, C)`` statistic is applied per SAMPLE. The pins above use one fixture for all
# six forms, and their thresholds cannot tell a per-sample application from a row-0 or batch-mean
diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.py
index f44c277f0..a1c935c92 100644
--- a/tests/enhance/test_normalize.py
+++ b/tests/enhance/test_normalize.py
@@ -24,6 +24,24 @@ from testing.base import BaseTester
class TestNormalize(BaseTester):
+ @pytest.mark.parametrize("shape", [(2, 3, 4, 5), (2, 3, 2, 4, 5)])
+ def test_noncontiguous(self, shape, device, dtype):
+ data = torch.rand(shape, device=device, dtype=dtype).transpose(-1, -2)
+ mean = torch.tensor([0.25, 0.5, 0.75], device=device, dtype=dtype)
+ std = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype)
+ broadcast_shape = (1, 3) + (1,) * (data.ndim - 2)
+ expected = (data - mean.reshape(broadcast_shape)) / std.reshape(broadcast_shape)
+
+ assert not data.is_contiguous()
+ self.assert_close(kornia.enhance.normalize(data, mean, std), expected)
+ self.assert_close(kornia.enhance.Normalize(mean, std)(data), expected)
+
+ def test_noncontiguous_gradcheck(self, device):
+ data = torch.rand(1, 2, 3, 4, device=device, dtype=torch.float64).transpose(-1, -2)
+ mean = torch.tensor([0.25, 0.5], device=device, dtype=torch.float64)
+ std = torch.tensor([0.5, 2.0], device=device, dtype=torch.float64)
+ self.gradcheck(kornia.enhance.Normalize(mean, std), (data,))
+
def test_smoke(self, device, dtype):
mean = [0.5]
std = [0.1]
@@ -373,6 +391,21 @@ class TestDenormalize(BaseTester):
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):
+ data = torch.rand(shape, device=device, dtype=dtype).transpose(-1, -2)
+ low = data.amin(dim=(-2, -1), keepdim=True)
+ high = data.amax(dim=(-2, -1), keepdim=True)
+ expected = 3.0 * (data - low) / (high - low + 1e-6) - 1.0
+
+ assert not data.is_contiguous()
+ actual = kornia.enhance.normalize_min_max(data, min_val=-1.0, max_val=2.0)
+ self.assert_close(actual, expected)
+
+ def test_noncontiguous_gradcheck(self, device):
+ data = torch.arange(12, device=device, dtype=torch.float64).reshape(1, 1, 3, 4).transpose(-1, -2)
+ self.gradcheck(kornia.enhance.normalize_min_max, (data,))
+
def test_smoke(self, device, dtype):
x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
assert kornia.enhance.normalize_min_max(x) is not None