Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): accept empty affine volume batches (#5892)

peng xiang4058ff0db098
diff --git a/changelog.d/5892.fixed.md b/changelog.d/5892.fixed.md
new file mode 100644
index 000000000..79e16fc42
--- /dev/null
+++ b/changelog.d/5892.fixed.md
@@ -0,0 +1 @@
+`warp_affine3d` raised `ValueError: Expected non-zero, positive output size` for an empty `(0, C, D, H, W)` batch, and so did everything built on it: `affine3d`, `rotate3d`, `crop_by_transform_mat3d`, `RandomAffine3D`, `RandomRotation3D`, `CenterCrop3D` and `RandomCrop3D`. They now return an empty batch of the requested output size, connected to both inputs for backward.
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 750fdc8d4..e617466a9 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -1308,8 +1308,11 @@ def warp_affine3d(
- ``M`` is the source→destination **pixel** affine matrix :math:`(B, 3, 4)`
- align_corners: ``True`` by default
- padding_mode: ``'zeros'`` by default
+ - an empty batch returns shape :math:`(0, C, d, h, w)` with gradients connected to both inputs
+ even when a source spatial dimension is zero
- a zero output dimension returns an autograd-connected empty tensor;
negative output dimensions raise ``ValueError``
+ - a nonempty batch requires positive source spatial dimensions for a nonempty output
Args:
src : input torch.Tensor of shape :math:`(B, C, D, H, W)`.
@@ -1338,7 +1341,9 @@ def warp_affine3d(
B, C, D, H, W = src.size()
if dsize[0] < 0 or dsize[1] < 0 or dsize[2] < 0:
raise ValueError(f"Output size must be non-negative. Got {dsize}.")
- if dsize[0] == 0 or dsize[1] == 0 or dsize[2] == 0:
+ # affine_grid rejects a zero batch: an empty batch takes the empty-output path, which keeps the
+ # sampling-option, dtype, device and batch checks and the autograd links to both inputs.
+ if B == 0 or dsize[0] == 0 or dsize[1] == 0 or dsize[2] == 0:
return _empty_warp_output_3d(src, M, dsize, flags, padding_mode, align_corners)
out_dtype = src.dtype
if _runs_in_float32(src, M):
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index 5e9a7074a..c1fc620e2 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -25,6 +25,89 @@ from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
+class TestWarpAffine3dEmptyBatch(BaseTester):
+ """Empty volume batches retain affine-warp geometry and gradient connections."""
+
+ @pytest.mark.parametrize("dsize", [(3, 4, 5), (2, 6, 7)])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("mode,padding", [("bilinear", "zeros"), ("nearest", "reflection")])
+ def test_empty_batch_4429(self, dsize, align_corners, mode, padding, device, dtype):
+ """Keep the requested canvas, dtype, device and gradients for both empty operands."""
+ src = torch.empty(0, 2, 3, 4, 5, device=device, dtype=dtype, requires_grad=True)
+ matrix = torch.empty(0, 3, 4, device=device, dtype=dtype, requires_grad=True)
+ out = proj.warp_affine3d(src, matrix, dsize, mode, padding, align_corners)
+ assert out.shape == (0, 2, *dsize)
+ assert out.dtype == dtype
+ assert out.device == device
+ out.sum().backward()
+ assert src.grad is not None
+ assert src.grad.shape == src.shape
+ assert matrix.grad is not None
+ assert matrix.grad.shape == matrix.shape
+
+ @pytest.mark.parametrize("spatial", [(3, 4, 5), (0, 4, 5), (3, 0, 5), (3, 4, 0)])
+ def test_empty_batch_validation_4429(self, spatial, device, dtype):
+ """An empty batch still rejects invalid sampling options and incompatible matrices."""
+ src = torch.empty(0, 2, *spatial, device=device, dtype=dtype)
+ matrix = torch.empty(0, 3, 4, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="expected mode"):
+ proj.warp_affine3d(src, matrix, (3, 4, 5), flags="invalid")
+ with pytest.raises(ValueError, match="expected padding_mode"):
+ proj.warp_affine3d(src, matrix, (3, 4, 5), padding_mode="invalid")
+ with pytest.raises(RuntimeError):
+ proj.warp_affine3d(src, torch.eye(3, 4, device=device, dtype=dtype)[None], (3, 4, 5))
+ # A non-empty batch rejects a matrix of another dtype, so an empty one must too.
+ other = torch.float16 if dtype != torch.float16 else torch.float32
+ with pytest.raises(RuntimeError, match="same dtype"):
+ proj.warp_affine3d(src, matrix.to(other), (3, 4, 5))
+
+ @pytest.mark.parametrize("spatial", [(0, 4, 5), (3, 0, 5), (3, 4, 0)])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("mode,padding", [("bilinear", "zeros"), ("nearest", "reflection")])
+ def test_empty_spatial_batch_4429(self, spatial, align_corners, mode, padding, device, dtype):
+ """An empty batch needs no source voxels to retain its output shape and gradients."""
+ src = torch.empty(0, 2, *spatial, device=device, dtype=dtype, requires_grad=True)
+ matrix = torch.empty(0, 3, 4, device=device, dtype=dtype, requires_grad=True)
+ out = proj.warp_affine3d(src, matrix, (2, 6, 7), mode, padding, align_corners)
+ assert out.shape == (0, 2, 2, 6, 7)
+ assert out.dtype == dtype
+ assert out.device == device
+ out.sum().backward()
+ assert src.grad is not None
+ assert src.grad.shape == src.shape
+ assert matrix.grad is not None
+ assert matrix.grad.shape == matrix.shape
+
+ @pytest.mark.parametrize("augmentation", ["RandomAffine3D", "RandomRotation3D"])
+ @pytest.mark.parametrize("container", [False, True])
+ def test_empty_augmentation_4429(self, augmentation, container, device, dtype):
+ """Both direct and sequential 3D augmentations retain empty image batches."""
+ op = getattr(kornia.augmentation, augmentation)(20.0, p=1.0)
+ if container:
+ op = kornia.augmentation.AugmentationSequential(op, data_keys=["input"])
+ image = torch.empty(0, 2, 3, 4, 5, device=device, dtype=dtype, requires_grad=True)
+ out = op(image)
+ assert out.shape == image.shape
+ assert out.dtype == dtype
+ assert out.device == device
+ assert op.transform_matrix.shape == (0, 4, 4)
+ out.sum().backward()
+ assert image.grad is not None
+ assert image.grad.shape == image.shape
+
+ @pytest.mark.parametrize("spatial", [(3, 4, 5), (0, 4, 5), (3, 0, 5), (3, 4, 0)])
+ def test_dynamo_empty_batch_4429(self, spatial, device, dtype, torch_optimizer):
+ """Fullgraph capture keeps the empty affine warp and its backward pass."""
+ src = torch.empty(0, 2, *spatial, device=device, dtype=dtype, requires_grad=True)
+ matrix = torch.empty(0, 3, 4, device=device, dtype=dtype, requires_grad=True)
+ compiled = torch_optimizer(proj.warp_affine3d, fullgraph=True)
+ out = compiled(src, matrix, (2, 6, 7))
+ assert out.shape == (0, 2, 2, 6, 7)
+ out.sum().backward()
+ assert src.grad is not None
+ assert matrix.grad is not None
+
+
@pytest.mark.parametrize("op_name", ["warp_affine3d", "warp_perspective3d"])
@pytest.mark.parametrize("dsize", [(0, 4, 5), (3, 0, 5), (3, 4, 0)])
@pytest.mark.parametrize("align_corners", [True, False])
@@ -47,8 +130,10 @@ def test_empty_destination_is_autograd_connected(op_name, dsize, align_corners,
@pytest.mark.parametrize("op_name", ["warp_affine3d", "warp_perspective3d"])
-def test_empty_source_policy(op_name, device, dtype):
- src = torch.empty(1, 2, 0, 4, 5, device=device, dtype=dtype, requires_grad=True)
[email protected]("spatial", [(0, 4, 5), (3, 0, 5), (3, 4, 0)])
+def test_empty_source_policy(op_name, spatial, device, dtype):
+ """A nonempty batch with no source voxels only permits an empty destination."""
+ src = torch.empty(1, 2, *spatial, device=device, dtype=dtype, requires_grad=True)
if op_name == "warp_affine3d":
transform = torch.eye(3, 4, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
op = proj.warp_affine3d
@@ -56,8 +141,8 @@ def test_empty_source_policy(op_name, device, dtype):
transform = torch.eye(4, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
op = proj.warp_perspective3d
- empty = op(src, transform, (0, 4, 5))
- assert empty.shape == (1, 2, 0, 4, 5)
+ empty = op(src, transform, spatial)
+ assert empty.shape == (1, 2, *spatial)
empty.sum().backward()
assert src.grad is not None
assert transform.grad is not None