π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): handle empty normalize batches (#4681)
NiteeshGowda72e2ec102a16a4
diff --git a/changelog.d/4681.fixed.md b/changelog.d/4681.fixed.mdnew file mode 100644index 000000000..b64a07251--- /dev/null+++ b/changelog.d/4681.fixed.md@@ -0,0 +1 @@+`kornia.enhance.normalize` and the `Normalize` augmentation now preserve empty batches instead of raising a reshape error for `B=0`. Existing `mean` and `std` validation remains unchanged.diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.pyindex bf85f40e5..9cedb79ef 100644--- a/kornia/enhance/normalize.py+++ b/kornia/enhance/normalize.py@@ -179,7 +179,11 @@ def normalize(data: torch.Tensor, mean: torch.Tensor, std: torch.Tensor) -> torcmean = mean[..., None]std = std[..., None]- out: torch.Tensor = (data.reshape(shape[0], shape[1], -1) - mean) / std+ numel = 1+ for dim in shape[2:]:+ numel *= dim++ out: torch.Tensor = (data.reshape(shape[0], shape[1], numel) - mean) / stdreturn out.reshape(shape)diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex 50ef4574b..9f8618671 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -1045,22 +1045,20 @@ class TestConventionAugmentationBase2D(BaseTester):("RandomCrop", IndexError, "list index out of range"),("LongestMaxSize", KeyError, "output_size"),("RandomAutoContrast", ValueError, "Invalid input tensor, it is empty."),- ("Normalize", RuntimeError, "cannot reshape tensor of 0 elements"),],)- def test_wart_zero_batch_raises_in_four_exception_families_4429(self, name, error, message, device, dtype):+ def test_wart_zero_batch_raises_in_three_exception_families_4429(self, name, error, message, device, dtype):# Wart pin (#4429): `B = 0` is not uniformly "empty in, empty out". These representative# augmentations raise through distinct failure paths; RandomAutoContrast is a deliberate validation# error and the others expose implementation details.# Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu):# RandomCrop IndexError('list index out of range'), LongestMaxSize KeyError('output_size'),- # RandomAutoContrast ValueError('Invalid input tensor, it is empty.'),- # Normalize RuntimeError('cannot reshape tensor of 0 elements into shape [0, 3, -1] ...').+ # RandomAutoContrast ValueError('Invalid input tensor, it is empty.').+ # Normalize used to be a fourth family; #4681 fixed it.builders = {"RandomCrop": lambda: K.RandomCrop((4, 6), p=1.0),"LongestMaxSize": lambda: K.LongestMaxSize(16, p=1.0),"RandomAutoContrast": lambda: K.RandomAutoContrast(p=1.0),- "Normalize": lambda: K.Normalize(0.5, 0.5, p=1.0),}with pytest.raises(error, match=re.escape(message)):builders[name]()(torch.rand(0, 3, 6, 8, device=device, dtype=dtype))@@ -1083,11 +1081,6 @@ class TestConventionAugmentationBase2D(BaseTester):(0, 3, 6, 8),marks=pytest.mark.xfail(strict=True, raises=ValueError, reason="Tracked in #4429"),),- pytest.param(- lambda: K.Normalize(0.5, 0.5, p=1.0),- (0, 3, 6, 8),- marks=pytest.mark.xfail(strict=True, raises=RuntimeError, reason="Tracked in #4429"),- ),],)def test_convention_zero_batch_is_empty_in_empty_out(self, augmentation, shape, device, dtype):diff --git a/tests/enhance/test_normalize.py b/tests/enhance/test_normalize.pyindex a1c935c92..effd6fe94 100644--- a/tests/enhance/test_normalize.py+++ b/tests/enhance/test_normalize.py@@ -60,6 +60,47 @@ class TestNormalize(BaseTester):f = kornia.enhance.Normalize(mean, std)self.assert_close(f(data), expected)+ def test_empty_batch(self, device, dtype):+ data = torch.rand(0, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)+ mean = torch.tensor([0.5], device=device, dtype=dtype, requires_grad=True)+ std = torch.tensor([0.5], device=device, dtype=dtype, requires_grad=True)++ output = kornia.enhance.normalize(data, mean, std)+ augmentation_output = kornia.augmentation.Normalize(mean, std, p=1.0)(data)++ assert output.shape == data.shape+ assert output.device == data.device+ assert output.dtype == data.dtype+ assert augmentation_output.shape == data.shape++ output.sum().backward()++ assert data.grad is not None+ assert mean.grad is not None+ assert std.grad is not None+ assert data.grad.abs().sum() == 0+ assert mean.grad.abs().sum() == 0+ assert std.grad.abs().sum() == 0++ def test_rank2_normalize(self, device, dtype):+ data = torch.ones(2, 3, device=device, dtype=dtype)+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype)+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype)++ expected = (data - mean) / std++ self.assert_close(kornia.enhance.normalize(data, mean, std), expected)++ def test_empty_rank2_normalize(self, device, dtype):+ data = torch.empty(0, 3, device=device, dtype=dtype)+ mean = torch.tensor([0.5, 1.0, 2.0], device=device, dtype=dtype)+ std = torch.tensor([2.0, 2.0, 2.0], device=device, dtype=dtype)++ output = kornia.enhance.normalize(data, mean, std)++ assert output.shape == data.shape+ self.assert_close(output, data)+def test_broadcast_normalize(self, device, dtype):# prepare input datadata = torch.ones(2, 3, 1, 1, device=device, dtype=dtype)