Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): reject a one-voxel oversized 3D crop and honour a per-channel `fill` (#4691)

Dmytro Mishkin0e8cf3b57ba6
diff --git a/changelog.d/4691.fixed.md b/changelog.d/4691.fixed.md
new file mode 100644
index 000000000..a97572d74
--- /dev/null
+++ b/changelog.d/4691.fixed.md
@@ -0,0 +1 @@
+`RandomCrop3D` no longer accepts a crop exactly one voxel larger than the (padded) input along an axis. It used to pass the size guard, crop past the edge and return a volume with an empty slab; it now raises the same `ValueError` that a larger crop already did. `RandomCrop` and `RandomCrop3D` also honour a `fill` sequence holding one value per channel, which both have always documented but which raised `TypeError: pad(): argument 'value' must be float, not tuple`; a sequence must match the channel count and requires `padding_mode="constant"`. In `AugmentationSequential`, a per-channel image fill defaults mask padding to zero unless `extra_args[DataKey.MASK]["fill"]` overrides it, so masks with a different channel count remain supported.
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index a50475be2..275624859 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -17,15 +17,14 @@
from __future__ import annotations
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import torch
-import torch.nn.functional as F
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.augmentation.utils._crop import _compiled_slice_resize
-from kornia.augmentation.utils.helpers import _constant_tensor
+from kornia.augmentation.utils.helpers import _constant_tensor, _pad_with_fill
from kornia.constants import Resample
from kornia.core.utils import is_compiling, is_exporting
from kornia.geometry.boxes import Boxes
@@ -49,8 +48,9 @@ class RandomCrop(GeometricAugmentationBase2D):
pad_if_needed: It will F.pad the image if smaller than the
desired size to avoid raising an exception. Since cropping is done
after padding, the padding seems to be done at a random offset.
- fill: Pixel fill value for constant fill. Default is 0.
- This value is only used when the padding_mode is constant.
+ fill: Pixel fill value for constant fill. Default is 0. A sequence gives one value per channel,
+ so it must be as long as the input's channel dimension. This value is only used when the
+ padding_mode is constant, and a sequence requires it.
padding_mode: Type of padding. Should be: constant, reflect, replicate.
resample: the interpolation mode.
same_on_batch: apply the same transformation across the batch.
@@ -87,6 +87,10 @@ class RandomCrop(GeometricAugmentationBase2D):
or two-value shorthand is expanded. ``pad_if_needed=True`` takes the per-side maximum of that padding and
the positive crop-minus-input size difference on each axis. Without explicit padding this is symmetric;
asymmetric explicit padding can remain asymmetric after the merge.
+ In :class:`~kornia.augmentation.container.AugmentationSequential`, a per-channel ``fill`` applies to the
+ image while mask padding defaults to zero because the mask can have a different channel count. Set a mask
+ ``fill`` through ``extra_args[DataKey.MASK]`` to override that default. A scalar ``fill`` retains the
+ previous behavior and applies to both the image and mask.
With ``pad_if_needed=False``, an oversized request does not raise. Slice mode resizes the available slice
to the requested size. Resample mode instead uses a mis-scaled warp that can blend in zero padding; when
@@ -139,7 +143,7 @@ class RandomCrop(GeometricAugmentationBase2D):
size: Tuple[int, int],
padding: Optional[Union[int, Tuple[int, int], Tuple[int, int, int, int]]] = None,
pad_if_needed: Optional[bool] = False,
- fill: int = 0,
+ fill: Union[float, Sequence[float]] = 0,
padding_mode: str = "constant",
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
@@ -199,7 +203,7 @@ class RandomCrop(GeometricAugmentationBase2D):
padding = self.compute_padding(input.shape)
if any(padding):
- input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ input = _pad_with_fill(input, padding, flags["fill"], flags["padding_mode"])
return input
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index 445265527..b8f83eb40 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -17,13 +17,13 @@
from __future__ import annotations
-from typing import Any, Dict, List, Optional, Tuple, Union
+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import torch
-import torch.nn.functional as F
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
+from kornia.augmentation.utils.helpers import _pad_with_fill
from kornia.constants import Resample
from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
@@ -46,9 +46,11 @@ class RandomCrop3D(GeometricAugmentationBase3D):
pad_if_needed: It will F.pad the image if smaller than the
desired size to avoid raising an exception. Since cropping is done
after padding, the padding seems to be done at a random offset.
- fill: Pixel fill value for constant fill. Default is 0.
- This value is only used when the padding_mode is constant.
- padding_mode: Type of padding. Should be: constant, edge, reflect or symmetric. Default is constant.
+ fill: Voxel fill value for constant fill. Default is 0. A sequence gives one value per channel,
+ so it must be as long as the input's channel dimension. This value is only used when the
+ padding_mode is constant, and a sequence requires it.
+ padding_mode: Type of padding, passed to F.pad. Should be: constant, reflect, replicate or circular.
+ Default is constant.
resample: resample mode from "nearest" (0) or "bilinear" (1).
same_on_batch: apply the same transformation across the batch.
align_corners: interpolation flag.
@@ -72,13 +74,11 @@ class RandomCrop3D(GeometricAugmentationBase3D):
left, top, and front padding to an original ``(x, y, z)`` point before applying this matrix. For example,
padding a ``3 x 3 x 3`` input by ``1`` and cropping the full ``5 x 5 x 5`` volume records an identity
matrix even though the original voxel ``(1, 1, 1)`` moves to ``(2, 2, 2)``.
- - its ``p`` is a call-wide gate. Size validation uses the padded input even when the call is skipped,
- but it is off by one: a crop exactly one voxel larger than the padded volume along an axis is accepted
- and the output gains a slab that is zero up to resampling roundoff, while two or more raise
- ``ValueError``
- (`#4688 <https://github.com/kornia/kornia/issues/4688>`_). :class:`CenterCrop3D` rejects the
- one-voxel case. A valid gated-off call returns the input itself -- unpadded, at the input shape rather
- than ``size`` -- with an identity ``transform_matrix``.
+ - its ``p`` is a call-wide gate. Size validation uses the padded input even when the call is skipped: a
+ crop larger than the padded volume along any axis, even by one voxel, raises ``ValueError``
+ (:class:`CenterCrop3D` rejects the same request with ``AssertionError``); a crop equal to it is valid.
+ A valid gated-off call returns the input itself -- unpadded, at the input shape rather than ``size`` --
+ with an identity ``transform_matrix``.
Defaults are bilinear resampling and ``align_corners=True``.
Examples:
@@ -106,7 +106,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
size: Tuple[int, int, int],
padding: Optional[Union[int, Tuple[int, int, int], Tuple[int, int, int, int, int, int]]] = None,
pad_if_needed: Optional[bool] = False,
- fill: int = 0,
+ fill: Union[float, Sequence[float]] = 0,
padding_mode: str = "constant",
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
@@ -161,7 +161,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
flags = self.flags if flags is None else flags
# Keep fixed and automatic padding separate to preserve non-constant boundary values.
for padding in self._compute_padding(tuple(input.shape), flags):
- input = F.pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
+ input = _pad_with_fill(input, padding, flags["fill"], flags["padding_mode"])
return input
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 9996554b2..5dea048b6 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -395,6 +395,18 @@ class ClassSequentialOps(SequentialOpsInterface[torch.Tensor]):
class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
"""Apply and inverse transformations for mask tensors."""
+ @staticmethod
+ def _mask_extra_args(module: Any, extra_args: Optional[Dict[str, Any]]) -> Dict[str, Any]:
+ extra_args = {} if extra_args is None else extra_args
+ # A per-channel image fill has no unambiguous meaning for a semantic mask, whose channel count
+ # commonly differs from the image. Default mask padding to background while preserving an explicit
+ # per-mask override and the legacy behavior of scalar fills.
+ fill = module.flags.get("fill")
+ if fill is not None and not isinstance(fill, (int, float)):
+ extra_args = dict(extra_args)
+ extra_args.setdefault("fill", 0.0)
+ return extra_args
+
@classmethod
def transform(
cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
@@ -412,6 +424,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
extra_args = {}
if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ extra_args = cls._mask_extra_args(module, extra_args)
input = module.transform_masks(
input,
params=cls.get_instance_module_param(param),
@@ -466,6 +479,7 @@ class MaskSequentialOps(SequentialOpsInterface[torch.Tensor]):
if extra_args is None:
extra_args = {}
if isinstance(module, (K.GeometricAugmentationBase2D,)):
+ extra_args = cls._mask_extra_args(module, extra_args)
tfm_input = []
params = cls.get_instance_module_param(param)
params_i = copy.deepcopy(params)
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index fdfa62fc0..e84c53300 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -95,8 +95,10 @@ class CropGenerator3D(RandomGeneratorBase):
y_diff = height - size[:, 1] + 1
z_diff = depth - size[:, 0] + 1
+ # ``*_diff`` is the number of valid start offsets, so it is 1 when the crop covers the whole
+ # axis and 0 when the crop is one voxel too large. The guard has to reject that zero as well.
# The size check reads the data, which graph capture cannot do; skip it under export.
- if not is_exporting() and ((x_diff < 0).any() or (y_diff < 0).any() or (z_diff < 0).any()):
+ if not is_exporting() and ((x_diff <= 0).any() or (y_diff <= 0).any() or (z_diff <= 0).any()):
raise ValueError(
f"input_size {(depth, height, width)} cannot be smaller than crop size {size!s} in any dimension."
)
diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.py
index 3dd8172d4..04c66ff0d 100644
--- a/kornia/augmentation/utils/__init__.py
+++ b/kornia/augmentation/utils/__init__.py
@@ -27,6 +27,7 @@ from kornia.augmentation.utils.helpers import (
_adapted_uniform,
_infer_batch_shape,
_infer_batch_shape3d,
+ _pad_with_fill,
_shape_validation,
_transform_input,
_transform_input3d,
@@ -61,6 +62,7 @@ __all__ = [
"_infer_batch_shape",
"_infer_batch_shape3d",
"_joint_range_check",
+ "_pad_with_fill",
"_range_bound",
"_shape_validation",
"_shear_bound",
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 9086daea2..b3346740a 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -17,15 +17,46 @@
import math
from functools import wraps
-from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import torch
+import torch.nn.functional as F
from torch.distributions import Beta, Uniform
from kornia.core.utils import _extract_device_dtype
from kornia.geometry.keypoints import Keypoints
+def _pad_with_fill(
+ input: torch.Tensor, padding: List[int], fill: Union[float, Sequence[float]], mode: str
+) -> torch.Tensor:
+ """Pad ``input`` with a scalar or with one constant per channel.
+
+ ``torch.nn.functional.pad`` only accepts a scalar ``value``, so a sequence ``fill`` is applied by padding
+ with zeros and writing the per-channel constants into the region the padding added. A sequence is only
+ meaningful for ``mode="constant"``.
+ """
+ if isinstance(fill, (int, float)):
+ return F.pad(input, padding, value=float(fill), mode=mode)
+
+ if mode != "constant":
+ raise ValueError(f"A sequence `fill` needs `padding_mode='constant'`, got '{mode}'.")
+
+ channels = input.shape[1]
+ # Built in-graph rather than lifted from a host list, so a compiled CUDA call issues no host-device copy.
+ if isinstance(fill, (list, tuple)):
+ values = _constant_tensor(fill, device=input.device, dtype=input.dtype).flatten()
+ else:
+ values = torch.as_tensor(fill, device=input.device, dtype=input.dtype).flatten()
+ if values.numel() != channels:
+ raise ValueError(f"`fill` must hold one value per channel: got {values.numel()} for {channels} channels.")
+
+ padded = F.pad(input, padding, value=0.0, mode=mode)
+ # 1 where a voxel came from the input, 0 where the padding added one. Negative padding crops both alike.
+ inside = F.pad(torch.ones_like(input[:, :1]), padding, value=0.0, mode=mode)
+ return torch.where(inside.bool(), padded, values.view(1, channels, *([1] * (padded.ndim - 2))))
+
+
def _flatten_constant(data: Any, shape: List[int], leaves: List[Any], depth: int = 0) -> None:
if isinstance(data, (list, tuple)):
if depth == len(shape):
diff --git a/tests/augmentation/_3d/test_random_crop_3d.py b/tests/augmentation/_3d/test_random_crop_3d.py
index 7ded05a4c..af64bfb95 100644
--- a/tests/augmentation/_3d/test_random_crop_3d.py
+++ b/tests/augmentation/_3d/test_random_crop_3d.py
@@ -261,3 +261,42 @@ class TestRandomCrop3D(BaseTester):
actual = op_trace(img)
expected = op(img)
self.assert_close(actual, expected)
+
+ @pytest.mark.parametrize("axis", [0, 1, 2])
+ def test_rejects_a_crop_one_voxel_larger_than_the_input(self, axis, device, dtype):
+ # The size guard counted valid start offsets and rejected only a negative count, so a crop exactly
+ # one voxel too large passed and the output gained an empty slab.
+ volume = torch.ones(1, 1, 4, 5, 6, device=device, dtype=dtype)
+ size = [4, 5, 6]
+ size[axis] += 1
+ with pytest.raises(ValueError, match="cannot be smaller than crop size"):
+ RandomCrop3D(tuple(size), p=1.0)(volume)
+ # The whole volume is still a valid crop.
+ assert RandomCrop3D((4, 5, 6), p=1.0)(volume).shape == (1, 1, 4, 5, 6)
+ # Padding is counted in, so the same size fits once the axis is padded.
+ padding = [0, 0, 0, 0, 0, 0]
+ padding[2 * (2 - axis)] = 1
+ assert RandomCrop3D(tuple(size), padding=tuple(padding), p=1.0)(volume).shape == (1, 1, *size)
+
+ def test_fill_accepts_one_value_per_channel(self, device, dtype):
+ volume = torch.zeros(1, 3, 2, 2, 2, device=device, dtype=dtype)
+ fill = (0.25, 0.5, 0.75)
+ padded = RandomCrop3D((4, 4, 4), padding=1, fill=fill, p=1.0).precrop_padding(volume)
+ assert padded.shape == (1, 3, 4, 4, 4)
+ expected = volume.new_tensor(fill).view(1, 3, 1, 1, 1)
+ self.assert_close(padded[:, :, 0, 0, 0], expected[:, :, 0, 0, 0])
+ self.assert_close(padded[:, :, -1, -1, -1], expected[:, :, 0, 0, 0])
+ self.assert_close(padded[:, :, 1:3, 1:3, 1:3], volume) # the interior is untouched
+ # A scalar keeps the old behaviour.
+ scalar = RandomCrop3D((4, 4, 4), padding=1, fill=7.0, p=1.0).precrop_padding(volume)
+ self.assert_close(scalar[:, :, 0, 0, 0], torch.full((1, 3), 7.0, device=device, dtype=dtype))
+
+ @pytest.mark.device_agnostic
+ def test_fill_sequence_is_validated(self):
+ volume = torch.zeros(1, 3, 2, 2, 2)
+ with pytest.raises(ValueError, match="one value per channel"):
+ RandomCrop3D((4, 4, 4), padding=1, fill=(1.0, 0.0), p=1.0).precrop_padding(volume)
+ with pytest.raises(ValueError, match="padding_mode='constant'"):
+ RandomCrop3D((4, 4, 4), padding=1, fill=(1.0, 0.0, 0.0), padding_mode="replicate", p=1.0).precrop_padding(
+ volume
+ )
diff --git a/tests/augmentation/container/test_random_crop.py b/tests/augmentation/container/test_random_crop.py
index 44c130a29..27a980a14 100644
--- a/tests/augmentation/container/test_random_crop.py
+++ b/tests/augmentation/container/test_random_crop.py
@@ -23,6 +23,7 @@ import pytest
import torch
import kornia.augmentation as K
+from kornia.constants import DataKey
from kornia.geometry.boxes import Boxes
from kornia.geometry.keypoints import Keypoints
@@ -57,6 +58,39 @@ class TestRandomCropAnnotations(BaseTester):
params[0].data["src"] = src[: shape[0]].to(params[0].data["src"])
return params
+ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
+ def test_per_channel_image_fill_defaults_masks_to_background(self, cropping_mode, device, dtype):
+ image = torch.zeros(1, 3, 2, 2, device=device, dtype=dtype)
+ mask = torch.ones(1, 1, 2, 2, device=device, dtype=dtype)
+ fill = (0.25, 0.5, 0.75)
+
+ def apply(mask_input, mask_fill=None):
+ extra_args = None if mask_fill is None else {DataKey.MASK: {"fill": mask_fill}}
+ seq = K.AugmentationSequential(
+ K.RandomCrop((4, 4), padding=1, fill=fill, p=1.0, cropping_mode=cropping_mode),
+ data_keys=["input", "mask"],
+ extra_args=extra_args,
+ )
+ return seq(image, mask_input)
+
+ padded_image, padded_mask = apply(mask)
+ expected_image = image.new_tensor(fill).view(1, 3, 1, 1).expand(1, 3, 4, 4).clone()
+ expected_image[:, :, 1:3, 1:3] = image
+ expected_mask = mask.new_zeros(1, 1, 4, 4)
+ expected_mask[:, :, 1:3, 1:3] = mask
+ self.assert_close(padded_image, expected_image)
+ self.assert_close(padded_mask, expected_mask)
+
+ _, overridden_mask = apply(mask, 9.0)
+ expected_override = mask.new_full((1, 1, 4, 4), 9.0)
+ expected_override[:, :, 1:3, 1:3] = mask
+ self.assert_close(overridden_mask, expected_override)
+
+ _, padded_mask_list = apply([mask])
+ self.assert_close(padded_mask_list[0], expected_mask)
+ _, overridden_mask_list = apply([mask], 9.0)
+ self.assert_close(overridden_mask_list[0], expected_override)
+
@pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
@pytest.mark.parametrize("p,batch_size", [(0.0, 1), (0.5, 2)])
@pytest.mark.parametrize(
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 51364493b..35da0506f 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -3474,6 +3474,24 @@ class TestRandomRotation(BaseTester):
class TestRandomCrop(BaseTester):
+ def test_fill_accepts_one_value_per_channel(self, device, dtype):
+ image = torch.zeros(1, 3, 2, 2, device=device, dtype=dtype)
+ fill = (0.25, 0.5, 0.75)
+ padded = RandomCrop((4, 4), padding=1, fill=fill, p=1.0).precrop_padding(image)
+ assert padded.shape == (1, 3, 4, 4)
+ expected = image.new_tensor(fill).view(1, 3, 1, 1)
+ self.assert_close(padded[:, :, 0, 0], expected[:, :, 0, 0])
+ self.assert_close(padded[:, :, -1, -1], expected[:, :, 0, 0])
+ self.assert_close(padded[:, :, 1:3, 1:3], image)
+ scalar = RandomCrop((4, 4), padding=1, fill=7.0, p=1.0).precrop_padding(image)
+ self.assert_close(scalar[:, :, 0, 0], torch.full((1, 3), 7.0, device=device, dtype=dtype))
+
+ @pytest.mark.device_agnostic
+ def test_fill_sequence_is_validated(self):
+ image = torch.zeros(1, 3, 2, 2)
+ with pytest.raises(ValueError, match="one value per channel"):
+ RandomCrop((4, 4), padding=1, fill=(1.0, 0.0), p=1.0).precrop_padding(image)
+
# 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.")
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index 902011d63..51a524313 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -404,17 +404,15 @@ class Test3DAugmentationConventions(BaseTester):
self.assert_close(skipped, volume, rtol=0, atol=0)
@pytest.mark.device_agnostic
- def test_wart_random_crop3d_accepts_a_one_voxel_oversized_crop_4688(self):
+ def test_convention_random_crop3d_rejects_a_one_voxel_oversized_crop_4688(self):
+ # Fixed by #4691: a crop one voxel larger than the input used to pass the guard and append an empty slab
+ # (#4688). It now raises like any larger request, on every axis, matching CenterCrop3D.
volume = torch.ones(1, 1, 4, 5, 6)
- output = K.RandomCrop3D((5, 5, 6), p=1.0)(volume)
- assert output.shape == (1, 1, 5, 5, 6)
- # The appended slab carries no input signal. It is compared against a real slice rather than
- # against zero: torch 2.5.1 and 2.9.1 leave ~1e-6 of grid_sample roundoff there, 2.14 leaves 0.
- slices = output.sum(dim=(1, 3, 4))[0]
- assert float(slices[-1]) < 1e-3 * float(slices[0])
- with pytest.raises(ValueError, match="cannot be smaller than crop size"):
- K.RandomCrop3D((6, 5, 6), p=1.0)(volume)
- # CenterCrop3D rejects the same one-voxel request.
+ for size in ((5, 5, 6), (4, 6, 6), (4, 5, 7), (6, 5, 6)):
+ with pytest.raises(ValueError, match="cannot be smaller than crop size"):
+ K.RandomCrop3D(size, p=1.0)(volume)
+ # The whole volume is still a valid crop.
+ self.assert_close(K.RandomCrop3D((4, 5, 6), p=1.0)(volume), volume)
with pytest.raises(AssertionError, match="Crop size must be smaller"):
K.CenterCrop3D((5, 5, 6), p=1.0)(volume)