Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): preserve patch coverage and batch shape in PatchSequential (#4460)

Zhenhuan Wange7110004eb30
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 49cf7182f..f3afbaadb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -160,6 +160,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
in-tree MPS workarounds stay. (#4202)
### Breaking changes
+* `PatchSequential` now preserves the batch size in both padding modes. `same` preserves the input
+ spatial size and `valid` keeps only the complete, centred grid region. Previously, a `(2,3,8,8)`
+ input on a `(3,3)` grid produced `(2,3,7,7)` with `same` (now `(2,3,8,8)`) and `(2,3,8,8)` with
+ `valid` (now `(2,3,6,6)`). With `valid`, a `(2,3,6,8)` input on a `(4,4)` grid changed the batch
+ size to produce `(3,3,6,6)`; it now produces `(2,3,4,8)`. Geometric children may move temporarily
+ padded zeroes into the retained image. `restore_from_patches` now defaults to `self.grid_size`
+ instead of `(4,4)` and raises `ValueError` for a mismatched patch count instead of inferring a
+ different batch size or failing later in reshape. `forward_parameters` accepts both image
+ `(B,C,H,W)` and patch `(B,N,C,h,w)` shapes; parameter generation now covers `B*N` patch rows rather
+ than `B*C`, so fixed-seed outputs and RNG consumption can change. Refs #4421. (#4460)
+
* Removed the unused `preprocess_boxes` helper, which had no public export or caller. (#4181, #4321)
* `kornia_rs>=0.1.14` is required; the floor used to be 0.1.9. kornia_rs 0.1.11 relocated its image I/O
@@ -381,6 +392,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `PatchSequential` now augments every patch of every image and runs the complete selected sequence.
+ The padding, reconstruction and parameter-generation behaviour changes are listed under
+ *Breaking changes*. Refs #4421. (#4460)
* `RandomMosaic` now preserves `(H, W)` for non-square inputs when `output_size=None`; it previously
returned `(W, H)`. `start_ratio_range` now scales x by width and y by height; it previously scaled
x by height and y by width. (#4459)
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index c7ce4d2c7..c2d7c84b4 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -15,7 +15,8 @@
# limitations under the License.
#
-from itertools import cycle, islice
+from __future__ import annotations
+
from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
import torch
@@ -25,6 +26,7 @@ from torch import nn
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.contrib.extract_patches import extract_tensor_patches
+from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -49,15 +51,19 @@ class PatchSequential(ImageSequential):
Args:
*args: a list of processing modules.
- grid_size: controls the grid board separation.
- padding: same or valid padding. If same padding, it will F.pad to include all pixels if the input
- torch.Tensor cannot be divisible by grid_size. If valid padding, the redundant border will be removed.
+ grid_size: positive ``(rows, columns)`` of patches in each image.
+ padding: ``"same"`` temporarily zero-pads to a multiple of ``grid_size`` and removes the added
+ border after augmentation, preserving the input spatial size. ``"valid"`` crops the remainder
+ before augmentation and keeps the cropped spatial size. Padding and cropping are centred;
+ an odd extra pixel is placed on the right or bottom. Both modes preserve the batch size.
+ Geometric transforms can move the temporary zero border into the retained image; removing
+ the added border does not undo that movement.
same_on_batch: apply the same transformation across the batch.
If None, it will not overwrite the function-wise settings.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). If None, it will not overwrite the function-wise settings.
patchwise_apply: apply image processing args will be applied patch-wisely.
- if ``True``, the number of args must be equal to grid number.
+ if ``True`` and ``random_apply=False``, the number of args must equal the number of patches.
if ``False``, the image processing args will be applied as a sequence to all patches.
random_apply: randomly select a sublist (order agnostic) of args to
apply transformation.
@@ -69,6 +75,16 @@ class PatchSequential(ImageSequential):
If ``False`` and ``patchwise_apply``, the whole list of args will be processed in original order
location-wisely.
+ Convention:
+ - input images have shape ``(B, C, H, W)``. Each image is split into ``N = rows * columns`` patches,
+ ordered by row then column. Parameters index the flattened ``B * N`` patch batch.
+ - 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.
+ - ``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.
+
.. note::
Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
Those transformations in ``kornia.geometry`` will not be taken into account.
@@ -140,6 +156,8 @@ class PatchSequential(ImageSequential):
) -> None:
_random_apply: Optional[Union[int, Tuple[int, int]]]
+ self._validate_grid_size(grid_size)
+
if patchwise_apply and random_apply is True:
# will only apply [1, 4] augmentations per patch
_random_apply = (1, 4)
@@ -169,6 +187,15 @@ class PatchSequential(ImageSequential):
self.patchwise_apply = patchwise_apply
self._params: Optional[List[PatchParamItem]] # type: ignore[assignment]
+ @staticmethod
+ def _validate_grid_size(grid_size: Tuple[int, int]) -> None:
+ if (
+ not isinstance(grid_size, (tuple, list))
+ or len(grid_size) != 2
+ or any(not isinstance(size, int) or isinstance(size, bool) or size <= 0 for size in grid_size)
+ ):
+ raise ValueError(f"grid_size must contain two positive integers. Got {grid_size}.")
+
def compute_padding(
self, input: torch.Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None
) -> Tuple[int, int, int, int]:
@@ -180,19 +207,34 @@ class PatchSequential(ImageSequential):
grid_size: Optional grid override. Uses ``self.grid_size`` when omitted.
Returns:
- Padding tuple ``(left, right, top, bottom)``.
+ Padding tuple ``(left, right, top, bottom)``. Negative values crop the border.
Raises:
+ ValueError: The input is not four-dimensional, has an empty spatial dimension, or the
+ grid cannot produce non-empty patches in ``"valid"`` mode.
NotImplementedError: ``padding`` is neither ``"same"`` nor ``"valid"``.
"""
+ return self._compute_padding(input.shape, padding, grid_size)
+
+ def _compute_padding(
+ self, batch_shape: torch.Size, padding: str, grid_size: Optional[Tuple[int, int]] = None
+ ) -> Tuple[int, int, int, int]:
+ """Compute padding from an image shape without allocating a tensor."""
if grid_size is None:
grid_size = self.grid_size
+ self._validate_grid_size(grid_size)
+ if len(batch_shape) != 4:
+ raise ValueError(f"Expected image shape (B, C, H, W). Got {batch_shape}.")
+ height, width = batch_shape[-2:]
+ if height <= 0 or width <= 0:
+ raise ValueError("PatchSequential requires non-empty spatial dimensions.")
if padding == "valid":
- ph, pw = input.size(-2) // grid_size[0], input.size(-1) // grid_size[1]
- return (-pw // 2, pw // 2 - pw, -ph // 2, ph // 2 - ph)
+ if height < grid_size[0] or width < grid_size[1]:
+ raise ValueError("grid_size must produce non-empty patches with padding='valid'.")
+ ph, pw = height % grid_size[0], width % grid_size[1]
+ return (-(pw // 2), -(pw - pw // 2), -(ph // 2), -(ph - ph // 2))
if padding == "same":
- ph = input.size(-2) - input.size(-2) // grid_size[0] * grid_size[0]
- pw = input.size(-1) - input.size(-1) // grid_size[1] * grid_size[1]
+ ph, pw = -height % grid_size[0], -width % grid_size[1]
return (pw // 2, pw - pw // 2, ph // 2, ph - ph // 2)
raise NotImplementedError(f"Expect `padding` as either 'valid' or 'same'. Got {padding}.")
@@ -202,7 +244,10 @@ class PatchSequential(ImageSequential):
grid_size: Optional[Tuple[int, int]] = None,
pad: Optional[Tuple[int, int, int, int]] = None,
) -> torch.Tensor:
- """Extract patches from torch.Tensor.
+ """Extract ``(B, rows * columns, C, h, w)`` patches from an image batch.
+
+ The spatial size after applying ``pad`` must be positive and divisible by ``grid_size``.
+ Use :meth:`compute_padding` to determine the padding or cropping for a given mode.
Example:
>>> import kornia.augmentation as K
@@ -222,7 +267,7 @@ class PatchSequential(ImageSequential):
<BLANKLINE>
[[[10, 11],
[14, 15]]]]])
- >>> pas.extract_patches(torch.arange(54).view(1, 1, 6, 9), grid_size=(2, 2), pad=(-1, -1, -2, -2))
+ >>> pas.extract_patches(torch.arange(54).view(1, 1, 6, 9), grid_size=(2, 2), pad=(-1, -2, -2, -2))
tensor([[[[[19, 20, 21]]],
<BLANKLINE>
<BLANKLINE>
@@ -235,10 +280,20 @@ class PatchSequential(ImageSequential):
[[[31, 32, 33]]]]])
"""
- if pad is not None:
- input = F.pad(input, list(pad))
if grid_size is None:
grid_size = self.grid_size
+ self._validate_grid_size(grid_size)
+ if input.ndim != 4:
+ raise ValueError(f"Expected image shape (B, C, H, W). Got {input.shape}.")
+ height, width = input.shape[-2:]
+ if pad is not None:
+ height, width = height + pad[2] + pad[3], width + pad[0] + pad[1]
+ if height <= 0 or width <= 0 or height % grid_size[0] or width % grid_size[1]:
+ raise ValueError(
+ f"Padded image size {(height, width)} must be positive and divisible by grid_size {grid_size}."
+ )
+ if pad is not None:
+ input = F.pad(input, list(pad))
window_size = (input.size(-2) // grid_size[-2], input.size(-1) // grid_size[-1])
stride = window_size
return extract_tensor_patches(input, window_size, stride)
@@ -246,10 +301,13 @@ class PatchSequential(ImageSequential):
def restore_from_patches(
self,
patches: torch.Tensor,
- grid_size: Tuple[int, int] = (4, 4),
+ grid_size: Optional[Tuple[int, int]] = None,
pad: Optional[Tuple[int, int, int, int]] = None,
) -> torch.Tensor:
- """Restore input from patches.
+ """Restore images from ``(B, rows * columns, C, h, w)`` patches.
+
+ Uses ``self.grid_size`` unless overridden. Only positive entries in ``pad`` are removed:
+ pixels cropped during extraction cannot be recovered and are not replaced with zeroes.
Example:
>>> import kornia.augmentation as K
@@ -264,39 +322,69 @@ class PatchSequential(ImageSequential):
"""
if grid_size is None:
grid_size = self.grid_size
- patches_tensor = patches.view(-1, grid_size[0], grid_size[1], *patches.shape[-3:])
- restored_tensor = torch.cat(torch.chunk(patches_tensor, grid_size[0], 1), -2).squeeze(1)
- restored_tensor = torch.cat(torch.chunk(restored_tensor, grid_size[1], 1), -1).squeeze(1)
+ self._validate_grid_size(grid_size)
+ KORNIA_CHECK_SHAPE(patches, ["B", "N", "C", "H", "W"])
+ batch, count, channels, height, width = patches.shape
+ if count != grid_size[0] * grid_size[1]:
+ raise ValueError(f"The patch count {count} must equal grid_size[0] * grid_size[1] for {grid_size}.")
+ patches_tensor = patches.reshape(batch, grid_size[0], grid_size[1], channels, height, width)
+ restored_tensor = patches_tensor.permute(0, 3, 1, 4, 2, 5).reshape(
+ batch, channels, grid_size[0] * height, grid_size[1] * width
+ )
if pad is not None:
- restored_tensor = F.pad(restored_tensor, [-i for i in pad])
+ restored_tensor = F.pad(restored_tensor, [-max(i, 0) for i in pad])
return restored_tensor
def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]: # type: ignore[override]
"""Generate patch-level parameters for a forward pass.
Args:
- batch_shape: Shape of the extracted patch batch.
+ batch_shape: Image shape ``(B, C, H, W)`` or extracted patch shape ``(B, N, C, h, w)``,
+ with ``N = grid_size[0] * grid_size[1]``. Image shapes are converted to patch shapes
+ using this container's ``grid_size`` and ``padding`` without allocating an image.
Returns:
List of :class:`PatchParamItem` entries, including patch indices and
operation params.
+
+ Example:
+ >>> seq = PatchSequential(K.RandomHorizontalFlip(p=1), grid_size=(2, 3), patchwise_apply=False)
+ >>> image = torch.rand(2, 3, 5, 7)
+ >>> params = seq.forward_parameters(image.shape)
+ >>> output = seq(image, params=params)
+ >>> torch.equal(output, seq(image, params=params))
+ True
"""
+ if len(batch_shape) == 4:
+ left, right, top, bottom = self._compute_padding(batch_shape, self.padding)
+ batch, channels, height, width = batch_shape
+ batch_shape = torch.Size(
+ (
+ batch,
+ self.grid_size[0] * self.grid_size[1],
+ channels,
+ (height + top + bottom) // self.grid_size[0],
+ (width + left + right) // self.grid_size[1],
+ )
+ )
+ if len(batch_shape) != 5 or batch_shape[1] != self.grid_size[0] * self.grid_size[1]:
+ raise ValueError(
+ f"Expected image shape (B, C, H, W) or patch shape (B, rows * columns, C, h, w). Got {batch_shape}."
+ )
out_param: List[PatchParamItem] = []
if not self.patchwise_apply:
params = self.generate_parameters(torch.Size([1, batch_shape[0] * batch_shape[1], *batch_shape[2:]]))
indices = torch.arange(0, batch_shape[0] * batch_shape[1])
out_param = [PatchParamItem(indices.tolist(), p) for p, _ in params]
- # "append" of "list" does not return a value
- elif not self.same_on_batch:
+ elif not self.same_on_batch and self.random_apply:
params = self.generate_parameters(torch.Size([batch_shape[0] * batch_shape[1], 1, *batch_shape[2:]]))
out_param = [PatchParamItem([i], p) for p, i in params]
- # "append" of "list" does not return a value
else:
+ # Fixed locations draw B parameters together, respecting the child's same_on_batch setting.
params = self.generate_parameters(torch.Size([batch_shape[1], batch_shape[0], *batch_shape[2:]]))
indices = torch.arange(0, batch_shape[0] * batch_shape[1], step=batch_shape[1])
out_param = [PatchParamItem((indices + i).tolist(), p) for p, i in params]
- # "append" of "list" does not return a value
return out_param
def generate_parameters(self, batch_shape: torch.Size) -> Iterator[Tuple[ParamItem, int]]:
@@ -307,8 +395,7 @@ class PatchSequential(ImageSequential):
the number of sequence.
"""
- if not self.same_on_batch and self.random_apply:
- # diff_on_batch and random_apply => patch-wise augmentation
+ if self.random_apply:
with_mix = False
for i in range(batch_shape[0]):
seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)
@@ -318,30 +405,12 @@ class PatchSequential(ImageSequential):
yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), i
else:
yield ParamItem(s[0], None), i
- elif not self.same_on_batch and not self.random_apply:
+ else:
for i, nchild in enumerate(self.named_children()):
if isinstance(nchild[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), i
else:
yield ParamItem(nchild[0], None), i
- elif not self.random_apply:
- # same_on_batch + not random_apply => location-wise augmentation
- for i, nchild in enumerate(islice(cycle(self.named_children()), batch_shape[0])):
- if isinstance(nchild[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
- yield ParamItem(nchild[0], nchild[1].forward_parameters(torch.Size(batch_shape[1:]))), i
- else:
- yield ParamItem(nchild[0], None), i
- else:
- # same_on_batch + random_apply => location-wise augmentation
- with_mix = False
- for i in range(batch_shape[0]):
- seq, mix_added = self.get_random_forward_sequence(with_mix=with_mix)
- with_mix = mix_added
- for s in seq:
- if isinstance(s[1], (_AugmentationBase, SequentialBase, K.MixAugmentationBaseV2)):
- yield ParamItem(s[0], s[1].forward_parameters(torch.Size(batch_shape[1:]))), i
- else:
- yield ParamItem(s[0], None), i
def forward_by_params(self, input: torch.Tensor, params: List[PatchParamItem]) -> torch.Tensor:
"""Apply module parameters to selected patch indices.
@@ -361,18 +430,19 @@ class PatchSequential(ImageSequential):
module = self.get_submodule(patch_param.param.name)
_input = input[patch_param.indices]
output = InputSequentialOps.transform(_input, module, patch_param.param, extra_args={})
- input[patch_param.indices] = output
+ # Mix operations may promote to their parameter dtype; the patch buffer retains the image dtype.
+ input[patch_param.indices] = output.to(input)
return input.reshape(in_shape)
def transform_inputs( # type: ignore[override]
- self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
+ self, input: torch.Tensor, params: Optional[List[PatchParamItem]], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
"""Apply patch-wise augmentation to an input tensor.
Args:
input: Input image tensor.
- params: Patch-level parameters from :meth:`forward_parameters`.
+ params: Patch-level parameters from :meth:`forward_parameters`, or ``None`` to generate them.
extra_args: Optional runtime overrides (unused in this implementation).
Returns:
@@ -380,8 +450,11 @@ class PatchSequential(ImageSequential):
"""
pad = self.compute_padding(input, self.padding)
input = self.extract_patches(input, self.grid_size, pad)
+ if params is None:
+ params = self.forward_parameters(input.shape)
input = self.forward_by_params(input, params)
input = self.restore_from_patches(input, self.grid_size, pad=pad)
+ self._params = params
return input
@@ -550,16 +623,8 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
def forward(self, input: torch.Tensor, params: Optional[List[PatchParamItem]] = None) -> torch.Tensor: # type: ignore[override]
- """Input transformation will be returned if input is a tuple."""
- # BCHW -> B(patch)CHW
+ """Augment an image batch, optionally replaying previously generated patch parameters."""
if isinstance(input, (tuple,)):
raise ValueError("tuple input is not currently supported.")
- if params is None:
- params = self.forward_parameters(input.shape)
-
- output = self.transform_inputs(input, params=params)
-
- self._params = params
-
- return output
+ return self.transform_inputs(input, params=params)
diff --git a/tests/augmentation/container/test_patch_sequential.py b/tests/augmentation/container/test_patch_sequential.py
index 411cf1728..81a133858 100644
--- a/tests/augmentation/container/test_patch_sequential.py
+++ b/tests/augmentation/container/test_patch_sequential.py
@@ -17,10 +17,20 @@
import pytest
import torch
+from torch import nn
import kornia.augmentation as K
+from kornia.color import RgbToBgr
from testing.augmentation.utils import reproducibility_test
+from testing.base import BaseTester
+
+
[email protected](autouse=True)
+def _restore_global_rng():
+ # The restored legacy test now draws parameters; keep it from shifting unrelated tests' RNG state.
+ with torch.random.fork_rng(devices=[]):
+ yield
class TestPatchSequential:
@@ -50,38 +60,40 @@ class TestPatchSequential:
**error_param,
)
- @pytest.mark.parametrize("shape", [(2, 3, 24, 24)])
+ @pytest.mark.parametrize("shape", [(2, 3, 24, 24), (2, 3, 23, 25)])
@pytest.mark.parametrize("padding", ["same", "valid"])
@pytest.mark.parametrize("patchwise_apply", [True, False])
@pytest.mark.parametrize("same_on_batch", [True, False, None])
@pytest.mark.parametrize("keepdim", [True, False, None])
@pytest.mark.parametrize("random_apply", [1, (2, 2), (1, 2), (2,), 10, True, False])
def test_forward(self, shape, padding, patchwise_apply, same_on_batch, keepdim, random_apply, device, dtype):
+ if patchwise_apply and not isinstance(random_apply, bool):
+ pytest.skip("patchwise_apply=True only supports boolean random_apply")
torch.manual_seed(11)
- try: # skip wrong param settings.
- seq = K.PatchSequential(
- K.color.RgbToBgr(),
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1),
- K.ImageSequential(
- K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=0.5),
- K.RandomPerspective(0.2, p=0.5),
- K.RandomSolarize(0.1, 0.1, p=0.5),
- ),
- K.RandomMixUpV2(p=1.0),
- grid_size=(2, 2),
- padding=padding,
- patchwise_apply=patchwise_apply,
- same_on_batch=same_on_batch,
- keepdim=keepdim,
- random_apply=random_apply,
- )
- # TODO: improve me and remove the exception.
- except Exception:
- return
+ # Exercise nested colour/geometric/mix operations without the unrelated HSV float16
+ # zero-pixel path: perspective padding can introduce black pixels before another colour draw.
+ seq = K.PatchSequential(
+ RgbToBgr(),
+ K.ColorJiggle(0.1, 0.1),
+ K.ImageSequential(
+ K.ColorJiggle(0.1, 0.1, p=0.5),
+ K.RandomPerspective(0.2, p=0.5),
+ K.RandomSolarize(0.1, 0.1, p=0.5),
+ ),
+ K.RandomMixUpV2(p=1.0),
+ grid_size=(2, 2),
+ padding=padding,
+ patchwise_apply=patchwise_apply,
+ same_on_batch=same_on_batch,
+ keepdim=keepdim,
+ random_apply=random_apply,
+ )
- input = torch.randn(*shape, device=device, dtype=dtype)
+ # Colour transforms expect RGB values in [0, 1], not a normally distributed image.
+ input = torch.rand(*shape, device=device, dtype=dtype)
out = seq(input)
- assert out.shape[-3:] == input.shape[-3:]
+ expected_shape = shape if padding == "same" else (*shape[:2], shape[2] // 2 * 2, shape[3] // 2 * 2)
+ assert out.shape == expected_shape
reproducibility_test(input, seq)
@@ -124,3 +136,302 @@ class TestPatchSequential:
output = aug(imgs)
assert output.dtype == dtype, "Output image dtype should match the input dtype"
+
+
+class _ScaleShift(nn.Module):
+ def __init__(self, scale=1, shift=0):
+ super().__init__()
+ self.scale = scale
+ self.shift = shift
+
+ def forward(self, input):
+ return input * self.scale + self.shift
+
+
+class TestPatchSequentialRegression(BaseTester):
+ """Numerical regressions for the patch layout and padding defects in #4421."""
+
+ @pytest.fixture(autouse=True)
+ def _seed_rng(self, _restore_global_rng):
+ torch.manual_seed(42)
+
+ @pytest.mark.parametrize("channels", [1, 3, 7])
+ @pytest.mark.parametrize("grid", [(1, 1), (2, 2), (2, 3)])
+ def test_augments_every_patch_row_4421(self, channels, grid, device, dtype):
+ # Manual spatial slices are the oracle, independent of the extraction/restoration helpers.
+ x = (torch.arange(2 * channels * 8 * 12, device=device) % 251).to(dtype).reshape(2, channels, 8, 12)
+ seq = K.PatchSequential(K.RandomHorizontalFlip(p=1), grid_size=grid, patchwise_apply=False)
+ expected = x.clone()
+ h, w = 8 // grid[0], 12 // grid[1]
+ for row in range(grid[0]):
+ for col in range(grid[1]):
+ rows, cols = slice(row * h, (row + 1) * h), slice(col * w, (col + 1) * w)
+ expected[..., rows, cols] = x[..., rows, cols].flip(-1)
+ self.assert_close(seq(x), expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("same_on_batch", [True, False, None])
+ def test_location_wise_modules_cover_every_sample(self, same_on_batch, device, dtype):
+ seq = K.PatchSequential(
+ *[_ScaleShift(shift=i) for i in range(1, 7)], grid_size=(2, 3), same_on_batch=same_on_batch
+ )
+ x = torch.zeros(2, 3, 4, 6, device=device, dtype=dtype)
+ x[1] = 10
+ expected = x.clone()
+ for row in range(2):
+ for col in range(3):
+ expected[..., row * 2 : row * 2 + 2, col * 2 : col * 2 + 2] += row * 3 + col + 1
+ self.assert_close(seq(x), expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("same_on_batch", [True, False, None])
+ def test_applies_complete_sequence_in_order(self, same_on_batch, device, dtype):
+ seq = K.PatchSequential(
+ _ScaleShift(shift=1),
+ _ScaleShift(scale=2),
+ grid_size=(2, 3),
+ patchwise_apply=False,
+ same_on_batch=same_on_batch,
+ )
+ x = torch.ones(2, 3, 4, 6, device=device, dtype=dtype)
+ self.assert_close(seq(x), (x + 1) * 2, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("same_on_batch", [True, False, None])
+ @pytest.mark.parametrize("child_same_on_batch", [True, False])
+ def test_location_wise_parameter_batch(self, same_on_batch, child_same_on_batch):
+ # Each location draws a batch of parameters, allowing both sharing and per-sample draws.
+ seq = K.PatchSequential(
+ *[K.RandomBrightness((0.8, 1.2), p=1, same_on_batch=child_same_on_batch) for _ in range(6)],
+ grid_size=(2, 3),
+ same_on_batch=same_on_batch,
+ )
+ params = seq.forward_parameters(torch.Size((2, 6, 3, 2, 2)))
+ assert len(params) == 6
+ for location, item in enumerate(params):
+ assert item.indices == [location, location + 6]
+ assert item.param.data["brightness_factor"].shape == (2,)
+ expected_same = child_same_on_batch if same_on_batch is None else same_on_batch
+ assert seq.get_submodule(item.param.name).same_on_batch is expected_same
+ if expected_same:
+ self.assert_close(item.param.data["brightness_factor"][0], item.param.data["brightness_factor"][1])
+
+ @pytest.mark.parametrize("same_on_batch", [True, False, None])
+ def test_random_patch_schedule_and_replay(self, same_on_batch, device, dtype, monkeypatch):
+ seq = K.PatchSequential(
+ _ScaleShift(shift=1),
+ _ScaleShift(scale=2),
+ grid_size=(2, 3),
+ random_apply=True,
+ same_on_batch=same_on_batch,
+ )
+ # Supply alternating sequences so sharing is tested without relying on random inequality.
+ calls = []
+ modules = list(seq.named_children())
+
+ def select(with_mix=True):
+ order = modules if len(calls) % 4 < 2 else modules[::-1]
+ calls.append(order)
+ return iter(order), False
+
+ monkeypatch.setattr(seq, "get_random_forward_sequence", select)
+ x = torch.ones(2, 3, 4, 6, device=device, dtype=dtype)
+ out = seq(x)
+ assert len(calls) == (6 if same_on_batch else 12)
+ expected = x.clone()
+ for batch in range(2):
+ for location in range(6):
+ call = location if same_on_batch else batch * 6 + location
+ row, col = divmod(location, 3)
+ expected[batch, :, row * 2 : row * 2 + 2, col * 2 : col * 2 + 2] = 4 if call % 4 < 2 else 3
+ self.assert_close(out, expected, rtol=0, atol=0)
+ params = seq._params
+ monkeypatch.setattr(seq, "forward_parameters", lambda _: pytest.fail("Replay must not draw parameters"))
+ self.assert_close(seq(x, params=params), out, rtol=0, atol=0)
+ assert len(calls) == (6 if same_on_batch else 12)
+
+ @pytest.mark.parametrize("patchwise_apply", [True, False])
+ @pytest.mark.parametrize("same_on_batch", [True, False, None])
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_random_parameter_replay(self, patchwise_apply, same_on_batch, padding, device, dtype, monkeypatch):
+ seq = K.PatchSequential(
+ K.RandomBrightness((0.8, 1.2), p=1),
+ K.RandomHorizontalFlip(p=0.5),
+ grid_size=(2, 3),
+ patchwise_apply=patchwise_apply,
+ random_apply=True,
+ same_on_batch=same_on_batch,
+ padding=padding,
+ )
+ x = torch.full((2, 3, 5, 7), 0.5, device=device, dtype=dtype)
+ out = seq(x)
+ params = seq._params
+ monkeypatch.setattr(seq, "forward_parameters", lambda _: pytest.fail("Replay must not draw parameters"))
+ self.assert_close(seq(x, params=params), out, rtol=0, atol=0)
+ assert out.shape == ((2, 3, 5, 7) if padding == "same" else (2, 3, 4, 6))
+
+ @pytest.mark.parametrize(
+ "height,width,grid,crop",
+ [
+ (8, 8, (2, 2), (0, 8, 0, 8)),
+ (8, 8, (3, 3), (1, 7, 1, 7)),
+ (7, 10, (3, 4), (0, 6, 1, 9)),
+ (6, 8, (4, 4), (1, 5, 0, 8)),
+ ],
+ )
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_padding_preserves_batch_and_pixels_4421(self, height, width, grid, crop, padding, device, dtype):
+ x = (torch.arange(2 * height * width, device=device) % 251).to(dtype).reshape(2, 1, height, width)
+ seq = K.PatchSequential(nn.Identity(), grid_size=grid, padding=padding, patchwise_apply=False)
+ top, bottom, left, right = crop
+ expected = x if padding == "same" else x[..., top:bottom, left:right]
+ self.assert_close(seq(x), expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_padding_with_flip(self, padding, device, dtype):
+ x = torch.arange(1, 16, device=device, dtype=dtype).reshape(1, 1, 3, 5)
+ seq = K.PatchSequential(K.RandomHorizontalFlip(p=1), grid_size=(2, 2), padding=padding, patchwise_apply=False)
+ # same: pad on right/bottom to 4x6, flip each 2x3 patch, remove that padding.
+ # valid: crop right/bottom to 2x4, then flip each 1x2 patch.
+ values = (
+ [[3, 2, 1, 0, 5], [8, 7, 6, 0, 10], [13, 12, 11, 0, 15]]
+ if padding == "same"
+ else [[2, 1, 4, 3], [7, 6, 9, 8]]
+ )
+ expected = torch.tensor(values, device=device, dtype=dtype)[None, None]
+ self.assert_close(seq(x), expected, rtol=0, atol=0)
+
+ def test_same_padding_with_grid_larger_than_image(self, device, dtype):
+ x = torch.arange(6, device=device, dtype=dtype).reshape(1, 1, 2, 3)
+ seq = K.PatchSequential(nn.Identity(), grid_size=(4, 5), patchwise_apply=False)
+ self.assert_close(seq(x), x, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("grid", [(0, 2), (-1, 2), (2,), (2, 3, 4), (2.5, 2), (True, 2)])
+ def test_invalid_grid(self, grid):
+ with pytest.raises(ValueError, match=r"grid_size.*two positive integers"):
+ K.PatchSequential(nn.Identity(), grid_size=grid, patchwise_apply=False)
+
+ def test_valid_padding_rejects_empty_patches(self, device, dtype):
+ seq = K.PatchSequential(nn.Identity(), grid_size=(3, 4), padding="valid", patchwise_apply=False)
+ with pytest.raises(ValueError, match="non-empty patches"):
+ seq(torch.ones(2, 1, 2, 3, device=device, dtype=dtype))
+
+ def test_extract_rejects_incompatible_grid(self, device, dtype):
+ seq = K.PatchSequential(nn.Identity(), patchwise_apply=False)
+ with pytest.raises(ValueError, match="divisible by grid_size"):
+ seq.extract_patches(torch.ones(2, 1, 7, 10, device=device, dtype=dtype), grid_size=(3, 4))
+
+ def test_restore_rejects_wrong_patch_count(self, device, dtype):
+ seq = K.PatchSequential(nn.Identity(), patchwise_apply=False)
+ with pytest.raises(ValueError, match="patch count"):
+ seq.restore_from_patches(torch.ones(2, 9, 1, 2, 2, device=device, dtype=dtype), grid_size=(2, 3))
+
+ @pytest.mark.parametrize("padding,patch_shape", [("same", (24, 3, 3, 3)), ("valid", (24, 3, 2, 2))])
+ def test_parameters_use_patch_spatial_size(self, padding, patch_shape, device, dtype):
+ seq = K.PatchSequential(K.RandomHorizontalFlip(p=1), grid_size=(3, 4), padding=padding, patchwise_apply=False)
+ seq(torch.ones(2, 3, 7, 10, device=device, dtype=dtype))
+ assert tuple(seq._params[0].param.data["forward_input_shape"].tolist()) == patch_shape
+
+ @pytest.mark.parametrize("padding,patch_size", [("same", 3), ("valid", 2)])
+ @pytest.mark.parametrize("patchwise_apply", [True, False])
+ @pytest.mark.parametrize("same_on_batch", [True, False, None])
+ @pytest.mark.parametrize("random_apply", [True, False])
+ def test_image_shape_parameter_replay(
+ self, padding, patch_size, patchwise_apply, same_on_batch, random_apply, device, dtype, monkeypatch
+ ):
+ seq = K.PatchSequential(
+ *[K.RandomAffine(degrees=20, translate=(0.1, 0.2), p=1) for _ in range(6)],
+ grid_size=(2, 3),
+ padding=padding,
+ patchwise_apply=patchwise_apply,
+ same_on_batch=same_on_batch,
+ random_apply=random_apply,
+ )
+ x = torch.arange(210, device=device, dtype=dtype).reshape(2, 3, 5, 7) / 210
+ rng = torch.get_rng_state()
+ image_params = seq.forward_parameters(x.shape)
+ sampled_rng = torch.get_rng_state()
+ torch.set_rng_state(rng)
+ # Independently specified dimensions: 5x7 pads to 6x9 or crops to 4x6 on a 2x3 grid.
+ patch_params = seq.forward_parameters(torch.Size((2, 6, 3, patch_size, patch_size)))
+ assert torch.equal(torch.get_rng_state(), sampled_rng)
+ assert len(image_params) == len(patch_params)
+ for image_item, patch_item in zip(image_params, patch_params):
+ assert image_item.indices == patch_item.indices
+ assert image_item.param.name == patch_item.param.name
+ assert image_item.param.data.keys() == patch_item.param.data.keys()
+ for key in image_item.param.data:
+ self.assert_close(image_item.param.data[key], patch_item.param.data[key], rtol=0, atol=0)
+
+ monkeypatch.setattr(seq, "forward_parameters", lambda _: pytest.fail("Replay must not draw parameters"))
+ out = seq(x, params=image_params)
+ self.assert_close(out, seq(x, params=patch_params), rtol=0, atol=0)
+ assert torch.equal(torch.get_rng_state(), sampled_rng)
+ assert out.shape == ((2, 3, 5, 7) if padding == "same" else (2, 3, 4, 6))
+
+ @pytest.mark.parametrize("grid", [(1, 1), (4, 5)])
+ def test_image_shape_parameters_with_small_image(self, grid, device, dtype):
+ seq = K.PatchSequential(K.RandomHorizontalFlip(p=1), grid_size=grid, patchwise_apply=False)
+ x = torch.arange(12, device=device, dtype=dtype).reshape(2, 1, 2, 3)
+ params = seq.forward_parameters(x.shape)
+ expected = x.flip(-1) if grid == (1, 1) else x
+ self.assert_close(seq(x, params=params), expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("method", ["forward", "compute_padding", "extract_patches"])
+ def test_three_dimensional_input_raises_value_error(self, method, device, dtype):
+ seq = K.PatchSequential(nn.Identity(), grid_size=(2, 2), patchwise_apply=False)
+ kwargs = {"padding": "same"} if method == "compute_padding" else {}
+ with pytest.raises(ValueError, match="Expected image shape"):
+ getattr(seq, method)(torch.ones(3, 4, 4, device=device, dtype=dtype), **kwargs)
+
+ @pytest.mark.parametrize("shape", [(2, 3, 4), (2, 5, 3, 2, 2), (2, 6, 3, 2, 2, 1)])
+ def test_parameters_reject_invalid_shape(self, shape):
+ seq = K.PatchSequential(nn.Identity(), grid_size=(2, 3), patchwise_apply=False)
+ with pytest.raises(ValueError, match=r"Expected.*shape"):
+ seq.forward_parameters(torch.Size(shape))
+
+ @pytest.mark.parametrize("shape", [(2, 3, 1, 2), (2, 3, 0, 4)])
+ def test_image_shape_parameters_reject_empty_valid_patches(self, shape):
+ seq = K.PatchSequential(nn.Identity(), grid_size=(2, 3), padding="valid", patchwise_apply=False)
+ with pytest.raises(ValueError, match="non-empty"):
+ seq.forward_parameters(torch.Size(shape))
+
+ def test_noncontiguous_input_is_not_modified(self, device, dtype):
+ x = torch.arange(96, device=device, dtype=dtype).reshape(2, 1, 12, 4).transpose(-1, -2)
+ original = x.clone()
+ seq = K.PatchSequential(_ScaleShift(shift=1), grid_size=(2, 3), patchwise_apply=False)
+ self.assert_close(seq(x), original + 1, rtol=0, atol=0)
+ self.assert_close(x, original, rtol=0, atol=0)
+
+ def test_mix_parameter_dtype_preserves_image_dtype(self, device, dtype):
+ seq = K.PatchSequential(K.RandomMixUpV2(p=1), grid_size=(1, 1), patchwise_apply=False)
+ params = seq.forward_parameters(torch.Size((2, 1, 3, 2, 2)))
+ # MixUp's parameter generator can produce float32 lambdas for a half-precision image.
+ params[0].param.data["mixup_pairs"] = torch.tensor([1, 0])
+ params[0].param.data["mixup_lambdas"] = torch.full((2,), 0.25, dtype=torch.float32)
+ x = torch.zeros(2, 3, 2, 2, device=device, dtype=dtype)
+ x[1] = 1
+ self.assert_close(seq(x, params=params), x * 0.75 + x.flip(0) * 0.25, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_gradient_support(self, padding, device, dtype):
+ x = torch.ones(2, 1, 3, 5, device=device, dtype=dtype, requires_grad=True)
+ seq = K.PatchSequential(_ScaleShift(scale=2), grid_size=(2, 2), padding=padding, patchwise_apply=False)
+ grad = torch.autograd.grad(seq(x).sum(), x)[0]
+ expected = torch.full_like(x, 2)
+ if padding == "valid":
+ expected[..., -1, :] = 0
+ expected[..., :, -1] = 0
+ self.assert_close(grad, expected, rtol=0, atol=0)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize("padding", ["same", "valid"])
+ def test_gradcheck(self, padding, device):
+ x = torch.arange(1, 16, device=device, dtype=torch.float64).reshape(1, 1, 3, 5) / 16
+ seq = K.PatchSequential(
+ K.RandomHorizontalFlip(p=1),
+ _ScaleShift(scale=2),
+ grid_size=(2, 2),
+ padding=padding,
+ patchwise_apply=False,
+ )
+ seq(x)
+ params = seq._params
+ self.gradcheck(lambda value: seq(value, params=params), (x.requires_grad_(),))