π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): preserve empty batches in normalize_min_max (#5605)
renta0426eefcd78d4880
diff --git a/changelog.d/5605.breaking.md b/changelog.d/5605.breaking.mdnew file mode 100644index 000000000..5e9a011cc--- /dev/null+++ b/changelog.d/5605.breaking.md@@ -0,0 +1,5 @@+`torch.jit.script(normalize_min_max)` now normalises every `(H, W)` plane of a `(*, C, H, W)` input, as the eager+function does. Previously scripting compiled only the body written for `(B, C, H, W)`, so a scripted call normalised+each row of each channel of a `(C, H, W)` input separately, returned an `(H, W)` input filled with `min_val`, and+normalised an input with more than four dimensions jointly over all but its first two dimensions. Scripted+`(B, C, H, W)` calls and eager results for non-empty inputs are unchanged.diff --git a/changelog.d/5605.fixed.md b/changelog.d/5605.fixed.mdnew file mode 100644index 000000000..cc9fc4b57--- /dev/null+++ b/changelog.d/5605.fixed.md@@ -0,0 +1,5 @@+`normalize_min_max` now returns an empty tensor with the input's shape, dtype and device for an empty batch, and keeps+the empty leading dimensions of a higher-rank input; it used to raise `ValueError: Invalid input tensor, it is empty.`+for any empty input. `RandomAutoContrast`, `RandomGaussianIllumination` and `RandomLinearCornerIllumination`, which call+it, now preserve an empty batch instead of raising that error. Inputs that stay invalid (an empty channel or spatial+dimension, fewer than two dimensions, a non-tensor) raise the same exception types as before, with new messages.diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.pyindex bf922c5ef..530e7e287 100644--- a/kornia/augmentation/_2d/intensity/auto_contrast.py+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py@@ -45,7 +45,7 @@ class RandomAutoContrast(IntensityAugmentationBase2D):- the output is :func:`kornia.enhance.normalize_min_max` of the input: each channel of each sample isrescaled by its own minimum and maximum as ``(x - min) / (max - min + 1e-6)``. This is a rescale, nota clamp, so an input outside ``[0, 1]`` is mapped into range rather than clipped, and a constant- channel comes back as zeros.+ channel comes back as zeros. Empty batches preserve their shape, dtype and device."""diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex 4c91b6d2b..8370800c3 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -22,8 +22,6 @@ from typing import List, Tuple, Unionimport torchfrom torch import nn-from kornia.image.utils import perform_keep_shape_image-__all__ = ["Denormalize", "Normalize", "denormalize", "normalize", "normalize_min_max"]@@ -395,7 +393,6 @@ def denormalize(data: torch.Tensor, mean: Union[torch.Tensor, float], std: Unionreturn torch.addcmul(mean, data, std)-@perform_keep_shape_imagedef normalize_min_max(input: torch.Tensor, min_val: float = 0.0, max_val: float = 1.0, eps: float = 1e-6) -> torch.Tensor:@@ -403,7 +400,8 @@ def normalize_min_max(Convention:Input is ``(*, C, H, W)``: minima and maxima are taken over H and W separately for every- leading index and channel. Constant planes map to min_val.+ leading index and channel. Constant planes map to min_val. Empty leading dimensions are+ preserved; channel and spatial dimensions must be nonzero.The data is normalised using the following formulation:@@ -433,6 +431,12 @@ def normalize_min_max(if not isinstance(input, torch.Tensor):raise TypeError(f"data should be a torch.Tensor. Got: {type(input)}.")+ if input.ndim < 2:+ raise ValueError(f"Input tensor must have at least two dimensions. Got {input.shape}")++ if 0 in input.shape[-3:]:+ raise ValueError("Invalid input tensor, channel and spatial dimensions must be nonzero.")+if not isinstance(min_val, float):raise TypeError(f"'min_val' should be a float. Got: {type(min_val)}.")@@ -440,11 +444,9 @@ def normalize_min_max(raise TypeError(f"'max_val' should be a float. Got: {type(max_val)}.")shape = input.shape- B, C = shape[0], shape[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_reshaped = input.flatten(start_dim=-2)+ x_min = x_reshaped.min(-1, keepdim=True)[0]+ x_max = x_reshaped.max(-1, keepdim=True)[0]x_out = (max_val - min_val) * (x_reshaped - x_min) / (x_max - x_min + eps) + min_valreturn x_out.reshape(shape)diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex 8aaa23853..521c02859 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -17,7 +17,6 @@import copyimport pickle-import refrom types import SimpleNamespacefrom unittest.mock import Mock, patch@@ -1158,11 +1157,34 @@ class TestConventionAugmentationBase2D(BaseTester):container = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input"])assert container(empty).shape == (0, 3, 6, 8)- def test_wart_zero_batch_raises_a_validation_error_4429(self, device, dtype):- # Wart pin (#4429): `B = 0` is not uniformly "empty in, empty out". RandomAutoContrast raises its- # deliberate validation error; the int-size resizes are pinned in the convention test below.- with pytest.raises(ValueError, match=re.escape("Invalid input tensor, it is empty.")):- K.RandomAutoContrast(p=1.0)(torch.rand(0, 3, 6, 8, device=device, dtype=dtype))+ @pytest.mark.parametrize("augmentation", [K.RandomGaussianIllumination, K.RandomLinearCornerIllumination])+ @pytest.mark.parametrize("probability", [0.0, 0.5, 1.0])+ def test_minmax_illumination_empty_batch_4429(self, augmentation, probability, device, dtype):+ data = torch.empty(0, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)+ output = augmentation(p=probability)(data)+ assert output.shape == data.shape+ assert output.dtype == dtype+ assert output.device == device+ output.sum().backward()+ assert data.grad is not None+ assert data.grad.shape == data.shape++ @pytest.mark.parametrize("probability", [0.0, 0.5, 1.0])+ @pytest.mark.parametrize("clip_output", [False, True])+ def test_autocontrast_empty_batch_4429(self, probability, clip_output, device, dtype):+ data = torch.empty(0, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)+ augmentation = K.RandomAutoContrast(p=probability, clip_output=clip_output)+ output = augmentation(data)+ replay = augmentation(data, params=augmentation._params)+ for actual in (output, replay):+ assert actual.shape == data.shape+ assert actual.dtype == dtype+ assert actual.device == device+ output.sum().backward()+ assert data.grad is not None+ assert data.grad.shape == data.shape+ sequence = K.AugmentationSequential(augmentation, data_keys=["input"])+ assert sequence(data).shape == data.shape@pytest.mark.parametrize(("augmentation", "shape"),@@ -1177,12 +1199,11 @@ class TestConventionAugmentationBase2D(BaseTester):pytest.param(lambda: K.RandomAutoContrast(p=1.0),(0, 3, 6, 8),- marks=pytest.mark.xfail(strict=True, raises=ValueError, reason="Tracked in #4429"),),],)def test_convention_zero_batch_is_empty_in_empty_out(self, augmentation, shape, device, dtype):- # Strict xfail (#4429): each listed augmentation must preserve an empty batch with its intended- # output geometry. Per-class markers turn an unrelated repair into a failure rather than an XFAIL.+ # Convention pin (#4429): each listed augmentation preserves an empty batch with its intended+ # output geometry. Other empty-batch configurations remain tracked by the umbrella issue.empty = torch.rand(0, 3, 6, 8, device=device, dtype=dtype)assert augmentation()(empty).shape == shapediff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.pyindex 2d2d9b156..2911d3008 100644--- a/tests/enhance/test_normalize.py+++ b/tests/enhance/test_normalize.py@@ -575,6 +575,56 @@ class TestNormalizeIntegerInput(BaseTester):class TestNormalizeMinMax(BaseTester):+ @pytest.mark.parametrize("shape", [(2, 3, 6, 8), (0, 3, 6, 8), (2, 0, 3, 6, 8)])+ def test_dynamo(self, shape, device, dtype, torch_optimizer):+ data = torch.rand(shape, device=device, dtype=dtype)+ op = kornia.enhance.normalize_min_max+ self.assert_close(torch_optimizer(op)(data), op(data))++ @pytest.mark.parametrize("shape", [(0, 3, 6, 8), (2, 0, 3, 6, 8), (0, 2, 3, 6, 8), (2, 1, 0, 3, 6, 8)])+ def test_empty_leading_dimensions(self, shape, device, dtype):+ data = torch.empty(shape, device=device, dtype=dtype, requires_grad=True)+ actual = kornia.enhance.normalize_min_max(input=data, min_val=-2.0, max_val=3.0)+ assert actual.shape == data.shape+ assert actual.dtype == data.dtype+ assert actual.device == data.device+ assert actual.numel() == 0+ actual.sum().backward()+ assert data.grad is not None+ assert data.grad.shape == data.shape++ @pytest.mark.parametrize("shape", [(0, 8), (3, 0, 8), (0, 6, 8), (2, 0, 6, 8), (0, 3, 0, 8), (0, 3, 6, 0)])+ def test_empty_image_planes_rejected(self, shape, device, dtype):+ with pytest.raises(ValueError):+ kornia.enhance.normalize_min_max(torch.empty(shape, device=device, dtype=dtype))++ @pytest.mark.parametrize("shape", [(), (3,), (0,)])+ def test_invalid_rank(self, shape, device, dtype):+ with pytest.raises(ValueError, match="at least two dimensions"):+ kornia.enhance.normalize_min_max(torch.empty(shape, device=device, dtype=dtype))++ @pytest.mark.parametrize("kwargs", [{"min_val": 0}, {"max_val": 1}])+ def test_empty_batch_validates_range_types(self, kwargs, device, dtype):+ with pytest.raises(TypeError):+ kornia.enhance.normalize_min_max(torch.empty(0, 3, 6, 8, device=device, dtype=dtype), **kwargs)++ @pytest.mark.parametrize("shape", [(2, 3), (2, 2, 3), (2, 2, 2, 3), (2, 2, 2, 2, 3)])+ def test_tied_extrema_gradients(self, shape, device, dtype):+ # Indexed extrema must retain the first-tie gradient behavior of the BCHW implementation.+ data = torch.tensor([0.0, 0.0, 1.0, 2.0, 2.0, 1.0], device=device, dtype=dtype)+ data = data.repeat(torch.Size(shape).numel() // 6).reshape(shape).requires_grad_()+ reference = data.detach().clone().requires_grad_()+ planes = reference.reshape(-1, 6)+ low = planes.min(-1, keepdim=True)[0]+ high = planes.max(-1, keepdim=True)[0]+ expected = (3.0 * (planes - low) / (high - low + 1e-6) - 1.0).reshape(shape)+ actual = kornia.enhance.normalize_min_max(data, min_val=-1.0, max_val=2.0)+ self.assert_close(actual, expected)+ weights = torch.arange(data.numel(), device=device, dtype=dtype).reshape(shape)+ (actual * weights).sum().backward()+ (expected * weights).sum().backward()+ self.assert_close(data.grad, reference.grad)+@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)@@ -628,9 +678,12 @@ class TestNormalizeMinMax(BaseTester):actual = kornia.enhance.normalize_min_max(x, min_val=-1.0, max_val=1.0)self.assert_close(actual, expected, low_tolerance=True)- @pytest.mark.skip(reason="args and kwargs in decorator")- def test_jit(self, device, dtype):- x = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)+ @pytest.mark.parametrize(+ "shape", [(1, 1, 1, 1), (6, 8), (3, 6, 8), (2, 3, 6, 8), (2, 2, 3, 6, 8), (0, 3, 6, 8), (2, 0, 3, 6, 8)]+ )+ def test_jit(self, shape, device, dtype):+ # Non-constant planes of every rank: the scripted function must normalise the same (*, C, H, W) planes as eager.+ x = torch.arange(torch.Size(shape).numel(), device=device, dtype=dtype).reshape(shape)op = kornia.enhance.normalize_min_maxop_jit = torch.jit.script(op)self.assert_close(op(x), op_jit(x))@@ -688,9 +741,7 @@ class TestNormalizeMinMax(BaseTester):assert out.shape == input_shapedef test_keyword_argument(self, device, dtype):- # Regression test for #3745: the perform_keep_shape_image wrapper binds the- # first argument as `input`, so passing the image by keyword must use `input=`- # and match the documented signature.+ # Regression test for #3745: the image keyword must match the documented `input` signature.x = torch.rand(1, 2, 4, 5, device=device, dtype=dtype)out_kwarg = kornia.enhance.normalize_min_max(input=x, min_val=-1.0, max_val=1.0)out_positional = kornia.enhance.normalize_min_max(x, min_val=-1.0, max_val=1.0)