Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(contrib): support empty patch batches (#5674)

renta0426904c3238aa7f
diff --git a/changelog.d/5674.fixed.md b/changelog.d/5674.fixed.md
new file mode 100644
index 000000000..3a1328b17
--- /dev/null
+++ b/changelog.d/5674.fixed.md
@@ -0,0 +1,6 @@
+`extract_tensor_patches` and `combine_tensor_patches`, including their module wrappers,
+now handle empty image batches without ambiguous reshape errors. Patch counts, spatial
+sizes, dtype, device and autograd connections are preserved. `PatchSequential` also
+supports empty batches when its children do, preserving the existing `same` padding
+and `valid` cropping behavior. Geometric patch inverses and mask transforms remain
+unsupported. Part of #4429.
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index e2b3f416e..d2004c1fe 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -85,6 +85,8 @@ class PatchSequential(ImageSequential):
- with ``patchwise_apply=True`` and ``random_apply=False``, each module processes its grid location
across all images. ``same_on_batch`` controls parameter sharing, not which images are processed.
- with ``patchwise_apply=False``, the selected sequence is applied to every patch.
+ - an empty image batch retains the grid's patch count and spatial sizes. Children must themselves
+ support empty inputs; geometric patch inverses and mask transforms remain unsupported.
- ``padding="valid"`` requires at least one pixel per patch in each spatial dimension. For example,
an ``8 x 8`` image on a ``(3, 3)`` grid remains ``8 x 8`` with ``"same"`` and becomes ``6 x 6``
with ``"valid"``. The batch size, channel count, device and dtype are preserved.
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index ad6e6e368..cde3cb137 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -130,6 +130,9 @@ class ExtractTensorPatches(nn.Module):
defined in the function signature.
left-right and top-bottom order.
+ An empty batch (:math:`B = 0`) gives an empty output with the same :math:`N`, :math:`C`, :math:`H_{out}` and
+ :math:`W_{out}` as a non-empty one. :math:`C` must be non-zero and the window sizes positive.
+
* :attr:`window_size` is the size of the sliding window and controls the
shape of the output torch.Tensor and defines the shape of the output patch.
* :attr:`stride` controls the stride to apply to the sliding window and
@@ -231,6 +234,7 @@ class CombineTensorPatches(nn.Module):
defined in the function signature.
left-right and top-bottom order.
+ An empty batch (:math:`B = 0`) is reconstructed with the same spatial size and unpadding as a non-empty one.
* :attr:`original_size` is the size of the original image prior to
extracting torch.Tensor patches and defines the shape of the output patch.
@@ -417,7 +421,7 @@ def combine_tensor_patches(
restored_size = ones_tensor.shape[2:]
patches = patches.permute(0, 2, 3, 4, 1)
- patches = patches.reshape(patches.shape[0], -1, patches.shape[-1])
+ patches = patches.flatten(1, 3)
int_flag = 0
if not torch.is_floating_point(patches):
int_flag = 1
@@ -446,12 +450,11 @@ def combine_tensor_patches(
def _extract_tensor_patchesnd(
input: torch.Tensor, window_sizes: Tuple[int, ...], strides: Tuple[int, ...]
) -> torch.Tensor:
- batch_size, num_channels = input.size()[:2]
dims = range(2, input.dim())
for dim, patch_size, stride in zip(dims, window_sizes, strides):
input = input.unfold(dim, patch_size, stride)
input = input.permute(0, *dims, 1, *(dim + len(dims) for dim in dims)).contiguous()
- return input.view(batch_size, -1, num_channels, *window_sizes)
+ return input.flatten(1, len(dims))
def extract_tensor_patches(
@@ -497,6 +500,10 @@ def extract_tensor_patches(
# torch's unfold drops the final patches that don't fit
window_size = cast(Tuple[int, int], _pair(window_size))
stride = cast(Tuple[int, int], _pair(stride))
+ if input.shape[1] == 0:
+ raise ValueError("extract_tensor_patches requires a non-empty channel dimension.")
+ if any(size <= 0 for size in window_size):
+ raise ValueError(f"window_size must contain positive values. Got {window_size}.")
original_size = (input.shape[-2], input.shape[-1])
# if padding is specified, we leave it up to the user to ensure it fits
diff --git a/tests/augmentation/container/test_patch_sequential.py b/tests/augmentation/container/test_patch_sequential.py
index 2371e3eb0..6da30678e 100644
--- a/tests/augmentation/container/test_patch_sequential.py
+++ b/tests/augmentation/container/test_patch_sequential.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+from copy import deepcopy
+
import pytest
import torch
from torch import nn
@@ -574,3 +576,168 @@ class TestConventionPatchSequential(BaseTester):
seq = K.PatchSequential(K.RandomHorizontalFlip(p=1.0), grid_size=(1, 1))
image = torch.arange(128, device=device, dtype=dtype).reshape(2, 1, 8, 8)
self.assert_close(seq(image), image.flip(-1))
+
+
+class TestEmptyPatchSequential(BaseTester):
+ """Empty image batches keep patch geometry and the existing container contracts (#4429)."""
+
+ @staticmethod
+ def _sequence(padding, patchwise=False, random_apply=False, same_on_batch=None, children=2):
+ modules = [K.RandomHorizontalFlip(p=0.5) if i % 2 else K.RandomVerticalFlip(p=1) for i in range(children)]
+ return K.PatchSequential(
+ *modules,
+ grid_size=(2, 3),
+ padding=padding,
+ patchwise_apply=patchwise,
+ random_apply=random_apply,
+ same_on_batch=same_on_batch,
+ )
+
+ def _assert_params_equal(self, actual, expected):
+ assert len(actual) == len(expected)
+ for actual_item, expected_item in zip(actual, expected):
+ assert actual_item.indices == expected_item.indices
+ assert actual_item.param.name == expected_item.param.name
+ assert actual_item.param.data.keys() == expected_item.param.data.keys()
+ for key in actual_item.param.data:
+ self.assert_close(actual_item.param.data[key], expected_item.param.data[key], rtol=0, atol=0)
+
+ @pytest.mark.parametrize("padding,patch_size,output_size", [("same", 5, (9, 13)), ("valid", 4, (8, 12))])
+ @pytest.mark.parametrize(
+ "patchwise,random_apply,same_on_batch,children",
+ [
+ (False, False, None, 2),
+ (False, True, None, 2),
+ (False, 2, None, 2),
+ (False, (1, 2), None, 2),
+ (True, False, None, 6),
+ (True, True, False, 2),
+ (True, True, True, 2),
+ (False, False, None, 0),
+ ],
+ )
+ def test_empty_patch_pipeline_4429(
+ self, padding, patch_size, output_size, patchwise, random_apply, same_on_batch, children, device, dtype
+ ):
+ sequence = self._sequence(padding, patchwise, random_apply, same_on_batch, children)
+ image = torch.empty(0, 3, 9, 13, device=device, dtype=dtype, requires_grad=True)
+ pad = sequence.compute_padding(image, padding)
+ patches = sequence.extract_patches(image, pad=pad)
+ assert patches.shape == (0, 6, 3, patch_size, patch_size)
+ assert patches.dtype == dtype
+ assert patches.device == device
+ rng = torch.get_rng_state()
+ params = sequence.forward_parameters(image.shape)
+ sampled_rng = torch.get_rng_state()
+ torch.set_rng_state(rng)
+ patch_params = sequence.forward_parameters(patches.shape)
+ self._assert_params_equal(params, patch_params)
+ assert torch.equal(torch.get_rng_state(), sampled_rng)
+ for item in params:
+ assert item.indices == []
+ assert item.param.data["forward_input_shape"].tolist() == [0, 3, patch_size, patch_size]
+ transformed = sequence.forward_by_params(patches, params)
+ assert transformed.shape == patches.shape
+ restored = sequence.restore_from_patches(transformed, pad=pad)
+ assert restored.shape == (0, 3, *output_size)
+ output = sequence(image, params=params)
+ assert output.shape == restored.shape
+ assert output.dtype == dtype
+ assert output.device == device
+ assert output.numel() == 0
+ output.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("padding,output_size", [("same", (9, 13)), ("valid", (8, 12))])
+ @pytest.mark.parametrize("patchwise", [False, True])
+ @pytest.mark.parametrize("replay_state", ["same_params", "after_forward", "fresh_instance"])
+ def test_empty_saved_patch_params_4429(
+ self, padding, output_size, patchwise, replay_state, device, dtype, monkeypatch
+ ):
+ children = 6 if patchwise else 2
+ sequence = self._sequence(padding, patchwise, children=children)
+ image = torch.empty(0, 3, 9, 13, device=device, dtype=dtype, requires_grad=True)
+ sequence(image)
+ params = sequence._params if replay_state == "same_params" else deepcopy(sequence._params)
+ snapshot = deepcopy(params)
+ if replay_state == "after_forward":
+ sequence(torch.zeros(2, 3, 7, 11, device=device, dtype=dtype))
+ elif replay_state == "fresh_instance":
+ sequence = self._sequence(padding, patchwise, children=children)
+ monkeypatch.setattr(sequence, "forward_parameters", lambda _: pytest.fail("Replay must not draw parameters"))
+ rng = torch.get_rng_state()
+ output = sequence(image, params=params)
+ assert output.shape == (0, 3, *output_size)
+ assert output.dtype == dtype
+ assert output.device == device
+ assert torch.equal(torch.get_rng_state(), rng)
+ self._assert_params_equal(params, snapshot)
+ output.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
+ @pytest.mark.parametrize("padding,tracked_size", [("same", (9, 13)), ("valid", (8, 12))])
+ @pytest.mark.parametrize("children", [0, 2])
+ def test_empty_nested_patch_shape_history_4429(self, container, padding, tracked_size, children, device, dtype):
+ sequence = container(K.ImageSequential(self._sequence(padding, children=children)), K.Resize((3, 4)))
+ image = torch.empty(0, 3, 9, 13, device=device, dtype=dtype, requires_grad=True)
+ params = sequence.forward_parameters(image.shape)
+ assert params[1].data["forward_input_shape"][-2:].tolist() == list(tracked_size)
+ received = []
+ handle = sequence[1].register_forward_pre_hook(lambda _, args: received.append(args[0].shape))
+ try:
+ output = sequence(image, params=params)
+ finally:
+ handle.remove()
+ assert received == [torch.Size((0, 3, *tracked_size))]
+ assert output.shape == (0, 3, 3, 4)
+ assert output.dtype == dtype
+ assert output.device == device
+ output.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("layout", ["BTCHW", "BCTHW"])
+ @pytest.mark.parametrize("padding,tracked_size", [("same", (9, 13)), ("valid", (8, 12))])
+ def test_empty_video_patch_shape_history_4429(self, layout, padding, tracked_size, device, dtype):
+ # Nested containers currently support same_on_frame=False only; do not change that contract.
+ sequence = K.VideoSequential(self._sequence(padding), K.Resize((3, 4)), data_format=layout, same_on_frame=False)
+ shape = (0, 2, 3, 9, 13) if layout == "BTCHW" else (0, 3, 2, 9, 13)
+ expected_shape = (0, 2, 3, 3, 4) if layout == "BTCHW" else (0, 3, 2, 3, 4)
+ image = torch.empty(*shape, device=device, dtype=dtype, requires_grad=True)
+ params = sequence.forward_parameters(image.shape)
+ assert params[1].data["forward_input_shape"][-2:].tolist() == list(tracked_size)
+ output = sequence(image, params=params)
+ assert output.shape == expected_shape
+ assert output.dtype == dtype
+ assert output.device == device
+ output.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ def test_empty_patch_validation_and_unsupported_ops_4429(self, device, dtype):
+ sequence = self._sequence("valid")
+ with pytest.raises(ValueError, match="non-empty patches"):
+ sequence(torch.empty(0, 3, 1, 2, device=device, dtype=dtype))
+ with pytest.raises(ValueError, match="non-empty spatial"):
+ sequence(torch.empty(0, 3, 0, 13, device=device, dtype=dtype))
+ with pytest.raises(ValueError, match="patch count"):
+ sequence.restore_from_patches(torch.empty(0, 5, 3, 4, 4, device=device, dtype=dtype))
+ image = torch.empty(0, 3, 9, 13, device=device, dtype=dtype)
+ output = sequence(image)
+ with pytest.raises(NotImplementedError, match="geometric transformations"):
+ sequence.inverse(output)
+ with pytest.raises(NotImplementedError, match="geometric transformations"):
+ sequence.transform_masks(torch.empty(0, 1, 8, 12, device=device, dtype=dtype), sequence._params)
+
+ @pytest.mark.parametrize("padding,output_size", [("same", (9, 13)), ("valid", (8, 12))])
+ def test_dynamo_empty_patch_pipeline_4429(self, padding, output_size, device, dtype, torch_optimizer):
+ sequence = self._sequence(padding)
+ image = torch.empty(0, 3, 9, 13, device=device, dtype=dtype)
+ params = sequence.forward_parameters(image.shape)
+ actual = torch_optimizer(sequence)(image, params=params)
+ assert actual.shape == (0, 3, *output_size)
+ assert actual.dtype == dtype
+ assert actual.device == device
diff --git a/tests/contrib/test_combine_tensor_patch.py b/tests/contrib/test_combine_tensor_patch.py
index 5b3abd69d..4f824338f 100644
--- a/tests/contrib/test_combine_tensor_patch.py
+++ b/tests/contrib/test_combine_tensor_patch.py
@@ -131,3 +131,78 @@ class TestCombineTensorPatches(BaseTester):
torch.arange(16.0, device=device, dtype=torch.float64).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2)
)
self.gradcheck(kornia.contrib.combine_tensor_patches, (patches, (4, 4), (2, 2), (2, 2)))
+
+ @pytest.mark.parametrize("batch_size", [0, 1, 2])
+ @pytest.mark.parametrize(
+ "image_size,window,stride,unpadding,auto_unpadding,pad,grid",
+ [
+ ((8, 12), (4, 4), (4, 4), 0, False, (0, 0, 0, 0), (2, 3)),
+ ((7, 11), (3, 5), (2, 3), 0, False, (0, 0, 0, 0), (3, 3)),
+ ((7, 11), (3, 5), (2, 3), (1, 1, 2, 1), False, (2, 1, 1, 1), (4, 4)),
+ ((9, 13), (4, 5), (4, 5), 0, True, (1, 1, 1, 2), (3, 3)),
+ ],
+ )
+ def test_patch_reconstruction_and_empty_batch_4429(
+ self, batch_size, image_size, window, stride, unpadding, auto_unpadding, pad, grid, device, dtype
+ ):
+ image = (torch.arange(batch_size * 3 * image_size[0] * image_size[1], device=device) % 251).to(dtype)
+ image = image.reshape(batch_size, 3, *image_size)
+ padded = torch.nn.functional.pad(image, pad)
+ # Construct patches without the extraction API so paired layout mistakes cannot cancel out.
+ patches = (
+ torch.stack(
+ [
+ padded[
+ ...,
+ row * stride[0] : row * stride[0] + window[0],
+ col * stride[1] : col * stride[1] + window[1],
+ ]
+ for row in range(grid[0])
+ for col in range(grid[1])
+ ],
+ dim=1,
+ )
+ .detach()
+ .requires_grad_()
+ )
+ module = kornia.contrib.CombineTensorPatches(image_size, window, stride, unpadding, auto_unpadding)
+ actual = module(patches)
+ functional = kornia.contrib.combine_tensor_patches(
+ patches, image_size, window, stride, auto_unpadding, unpadding
+ )
+ accumulated = torch.zeros_like(padded)
+ counts = torch.zeros_like(padded)
+ for row in range(grid[0]):
+ for col in range(grid[1]):
+ rows = slice(row * stride[0], row * stride[0] + window[0])
+ cols = slice(col * stride[1], col * stride[1] + window[1])
+ accumulated[..., rows, cols] += patches[:, row * grid[1] + col]
+ counts[..., rows, cols] += 1
+ expected = torch.nn.functional.pad(accumulated / (counts + 1e-8), tuple(-value for value in pad))
+ assert actual.shape == (batch_size, 3, *image_size)
+ assert actual.dtype == dtype
+ assert actual.device == device
+ self.assert_close(actual, expected)
+ self.assert_close(functional, expected)
+ self.assert_close(actual, image)
+ weights = (torch.arange(actual.numel(), device=device) % 7 + 1).to(dtype).reshape(actual.shape)
+ actual_grad = torch.autograd.grad((actual * weights).sum(), patches)[0]
+ expected_grad = torch.autograd.grad((expected * weights).sum(), patches)[0]
+ assert actual_grad.shape == patches.shape
+ self.assert_close(actual_grad, expected_grad)
+
+ def test_invalid_empty_patch_metadata_4429(self, device, dtype):
+ patches = torch.empty(0, 6, 3, 4, 4, device=device, dtype=dtype)
+ with pytest.raises(AssertionError, match=r"Stride=.*Window size"):
+ kornia.contrib.combine_tensor_patches(patches, (8, 12), (4, 4), (5, 4))
+ with pytest.raises(RuntimeError, match="sliding blocks"):
+ kornia.contrib.combine_tensor_patches(patches[:, :5], (8, 12), (4, 4), (4, 4))
+
+ @pytest.mark.parametrize("batch_size", [0, 2])
+ def test_dynamo_patch_reconstruction_4429(self, batch_size, device, dtype, torch_optimizer):
+ patches = (torch.arange(batch_size * 6 * 3 * 4 * 4, device=device) % 251).to(dtype)
+ patches = patches.reshape(batch_size, 6, 3, 4, 4)
+ module = kornia.contrib.CombineTensorPatches((8, 12), (4, 4), (4, 4))
+ actual = torch_optimizer(module)(patches)
+ assert actual.shape == (batch_size, 3, 8, 12)
+ self.assert_close(actual, module(patches))
diff --git a/tests/contrib/test_extract_tensor_patch.py b/tests/contrib/test_extract_tensor_patch.py
index 5f4d6ce3c..174875f52 100644
--- a/tests/contrib/test_extract_tensor_patch.py
+++ b/tests/contrib/test_extract_tensor_patch.py
@@ -161,3 +161,73 @@ class TestExtractTensorPatches(BaseTester):
warnings.simplefilter("always")
kornia.contrib.extract_tensor_patches(img, window_size=2, stride=2)
assert any("will not fit" in str(w.message) for w in caught) is not fits
+
+ @pytest.mark.parametrize("batch_size", [0, 1, 2])
+ @pytest.mark.parametrize("noncontiguous", [False, True])
+ @pytest.mark.parametrize(
+ "image_size,window,stride,padding,auto_padding,pad,grid",
+ [
+ ((8, 12), (4, 4), (4, 4), 0, False, (0, 0, 0, 0), (2, 3)),
+ ((7, 11), (3, 5), (2, 3), 0, False, (0, 0, 0, 0), (3, 3)),
+ ((7, 11), (3, 5), (2, 3), (1, 1, 2, 1), False, (2, 1, 1, 1), (4, 4)),
+ ((9, 13), (4, 5), (4, 5), 0, True, (1, 1, 1, 2), (3, 3)),
+ ],
+ )
+ def test_patch_layout_and_empty_batch_4429(
+ self, batch_size, noncontiguous, image_size, window, stride, padding, auto_padding, pad, grid, device, dtype
+ ):
+ height, width = image_size
+ storage_size = (width, height) if noncontiguous else image_size
+ image = (torch.arange(batch_size * 3 * height * width, device=device) % 251).to(dtype)
+ image = image.reshape(batch_size, 3, *storage_size)
+ if noncontiguous:
+ image = image.transpose(-2, -1)
+ image = image.detach().requires_grad_()
+ original = image.detach().clone()
+ module = kornia.contrib.ExtractTensorPatches(window, stride, padding, auto_padding)
+ patches = module(image)
+ functional = kornia.contrib.extract_tensor_patches(image, window, stride, padding, auto_padding)
+ # Independent spatial slices pin both the window count and row-major ordering.
+ padded = torch.nn.functional.pad(image, pad)
+ expected = torch.stack(
+ [
+ padded[
+ ..., row * stride[0] : row * stride[0] + window[0], col * stride[1] : col * stride[1] + window[1]
+ ]
+ for row in range(grid[0])
+ for col in range(grid[1])
+ ],
+ dim=1,
+ )
+ assert patches.shape == (batch_size, grid[0] * grid[1], 3, *window)
+ assert patches.dtype == dtype
+ assert patches.device == device
+ self.assert_close(patches, expected, rtol=0, atol=0)
+ self.assert_close(functional, expected, rtol=0, atol=0)
+ self.assert_close(image, original, rtol=0, atol=0)
+ weights = (torch.arange(patches.numel(), device=device) % 7 + 1).to(dtype).reshape(patches.shape)
+ actual_grad = torch.autograd.grad((patches * weights).sum(), image)[0]
+ expected_grad = torch.autograd.grad((expected * weights).sum(), image)[0]
+ assert actual_grad.shape == image.shape
+ self.assert_close(actual_grad, expected_grad, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("batch_size", [0, 1])
+ def test_invalid_empty_planes_and_window_4429(self, batch_size, device, dtype):
+ with pytest.raises(ValueError, match="non-empty channel"):
+ kornia.contrib.extract_tensor_patches(torch.empty(batch_size, 0, 8, 12, device=device, dtype=dtype), 4, 4)
+ with pytest.raises(ValueError, match=r"window_size.*positive"):
+ kornia.contrib.extract_tensor_patches(
+ torch.empty(batch_size, 3, 8, 12, device=device, dtype=dtype), (0, 4), (4, 4)
+ )
+ with pytest.raises(RuntimeError, match=r"step.*> 0"):
+ kornia.contrib.extract_tensor_patches(
+ torch.empty(batch_size, 3, 8, 12, device=device, dtype=dtype), 4, 0, padding=(0, 0, 0, 0)
+ )
+
+ @pytest.mark.parametrize("batch_size", [0, 2])
+ def test_dynamo_patch_extraction_4429(self, batch_size, device, dtype, torch_optimizer):
+ image = torch.arange(batch_size * 3 * 8 * 12, device=device).to(dtype).reshape(batch_size, 3, 8, 12)
+ module = kornia.contrib.ExtractTensorPatches((4, 4), (4, 4))
+ actual = torch_optimizer(module)(image)
+ assert actual.shape == (batch_size, 6, 3, 4, 4)
+ self.assert_close(actual, module(image), rtol=0, atol=0)