Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): keep zero-element tensors out of grid_sample in empty 2D warps (#4354)

Swapnil Gautam62e4f36ebbf2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a51c8f2fb..e09448158 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -364,6 +364,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `warp_affine`, `warp_perspective` and `remap` crashed on MPS for an empty destination -- a `dsize` with a
+ zero dimension, or zero-sized `remap` maps -- with an internal
+ `[srcBuf length] > 0 INTERNAL ASSERT FAILED ... Placeholder tensor is empty!` from PyTorch. The MPS backend
+ rejects *any* zero-element `grid_sample` operand before torch 2.14, including a zero-element grid sampled
+ against a non-empty source, which is what the empty-destination path built. That path now samples a connected
+ 1x1 stand-in and expands the result to the requested empty shape, so `grid_sample` never receives a
+ zero-element operand on any backend and an empty warp costs the same whatever the non-zero side of `dsize` is.
+ The empty path also resolves its output batch the way each operation's non-empty path does, so a singleton
+ transform or map batch broadcasts identically and a mismatched batch is rejected rather than silently
+ returning the wrong cardinality. Outputs, autograd links and the documented empty-source policy are unchanged
+ on CPU and CUDA. (#4032, #4354)
+
* Fixed `unproject_points_z1` depth shape handling for singleton and multi-axis batches,
accepting both trailing-singleton and flat depth tensors. (#4355)
* `solve_quartic` returns finite gradients for a pure biquadratic such as `x^4 - 16`. Its two
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 4f90b25f2..84abfee72 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -103,7 +103,7 @@ def _empty_warp_output_2d(
align_corners: bool,
grid_dtype: torch.dtype,
fill_value: Optional[torch.Tensor] = None,
- expand_transform_batch: bool = False,
+ transform_batch_broadcast: str = "none",
allow_fill: bool = True,
operand: str = "transform",
) -> torch.Tensor:
@@ -111,6 +111,12 @@ def _empty_warp_output_2d(
``operand`` names the second tensor in the error messages. ``remap`` has no ``transform``
parameter β€” it delegates here with its stacked maps β€” so it must not be told about one.
+
+ ``transform_batch_broadcast`` names the caller's singleton-batch rule, so the empty
+ destination broadcasts and rejects exactly as its non-empty path does:
+ ``"none"`` requires equal batches (``warp_perspective``), ``"src_when_larger"`` expands a
+ singleton transform batch only to a source batch above one (``warp_affine``), and ``"src"``
+ expands it to the source batch unconditionally, a zero batch included (``remap``).
"""
if src.device != transform.device:
raise RuntimeError(f"Expected src and {operand} on the same device, got {src.device} and {transform.device}.")
@@ -128,24 +134,45 @@ def _empty_warp_output_2d(
raise RuntimeError(f"Expected src and {operand} with the same dtype, got {src.dtype} and {transform.dtype}.")
if src.dtype != transform.dtype:
transform = transform.to(src.dtype)
+ # Resolve the output batch before any clamping below hides a mismatch: the stand-ins are
+ # clamped away from zero, so a 0/1 or 1/0 batch pairing would otherwise reach ``grid_sample``
+ # as 1/1 and be silently accepted where the non-empty path broadcasts or rejects it.
+ src_batch = src.shape[0]
+ transform_batch = transform.shape[0]
+ broadcasts_singleton = transform_batch_broadcast == "src" or (
+ transform_batch_broadcast == "src_when_larger" and src_batch > 1
+ )
+ if transform_batch == 1 and broadcasts_singleton:
+ transform_batch = src_batch
+ if transform_batch != src_batch:
+ raise RuntimeError(
+ f"Expected src and {operand} with the same batch size, got {src_batch} and {transform.shape[0]}."
+ )
+
+ # ``grid_sample`` must never receive a zero-element operand here. MPS before torch 2.14 raises
+ # ``[srcBuf length] > 0 ... Placeholder tensor is empty!`` for a zero-element grid or batch, even
+ # against a 1x1 source, and kornia supports torch >= 2.0. Sample connected 1x1 stand-ins so the
+ # remaining contracts -- dtype, device, mode and padding_mode -- are still validated by
+ # ``grid_sample`` itself, then expand the sampled result to the empty destination, which keeps
+ # the autograd links to ``src`` and ``transform``. The stand-ins are 1x1 in space rather than
+ # ``dsize``-shaped so the work stays constant: a ``(0, 2_000_000)`` destination must not
+ # materialize two million samples that the empty result then discards.
+ sample_batch = max(src_batch, 1)
+ sample_channels = max(src.shape[1], 1)
grid_zero = transform.reshape(-1)[:1].sum() * 0.0
- grid = grid_zero.reshape(1, 1, 1, 1).expand(transform.shape[0], dsize[0], dsize[1], 2)
- if expand_transform_batch and transform.shape[0] == 1 and src.shape[0] > 1:
- grid = grid.expand(src.shape[0], -1, -1, -1)
+ grid = grid_zero.reshape(1, 1, 1, 1).expand(sample_batch, 1, 1, 2)
- # ``grid_sample`` rejects an empty source even when the destination is also empty. Validate
- # all its other contracts against a connected 1x1 stand-in so the public empty-source policy
- # remains useful without silently accepting invalid batches, dtypes, devices, or modes.
- sample_src = src
- if src.shape[-2] == 0 or src.shape[-1] == 0:
- src_zero = src.reshape(-1)[:1].sum() * 0.0
- sample_src = src_zero.reshape(1, 1, 1, 1).expand(src.shape[0], src.shape[1], 1, 1)
+ src_zero = src.reshape(-1)[:1].sum() * 0.0
+ sample_src = src_zero.reshape(1, 1, 1, 1).expand(sample_batch, sample_channels, 1, 1)
if padding_mode == "fill" and allow_fill:
if fill_value is None:
- fill_value = torch.zeros(src.shape[1], device=src.device, dtype=src.dtype)
- return _fill_and_warp(sample_src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)
- return F.grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+ fill_value = torch.zeros(sample_channels, device=src.device, dtype=src.dtype)
+ sampled = _fill_and_warp(sample_src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)
+ else:
+ sampled = F.grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+ out_zero = sampled.reshape(-1)[:1].sum() * 0.0
+ return out_zero.reshape(1, 1, 1, 1).expand(src_batch, src.shape[1], dsize[0], dsize[1])
def _empty_warp_output_3d(
@@ -376,7 +403,7 @@ def warp_affine(
align_corners,
_matrix_warp_grid_dtype(src, M),
fill_value,
- expand_transform_batch=True,
+ transform_batch_broadcast="src_when_larger",
)
M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)
@@ -843,7 +870,7 @@ def remap(
padding_mode,
align_corners,
_remap_grid_dtype(map_xy, normalized_coordinates),
- expand_transform_batch=True,
+ transform_batch_broadcast="src",
allow_fill=False,
operand="map",
)
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index d422ff7cc..91a5a18a7 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -27,15 +27,15 @@ from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
-def _skip_if_mps_empty_grid_sample(device):
- """Skip when a zero-element sampling grid cannot reach ``grid_sample``.
+def _skip_if_mps_lacks_grid_sample_backward(device):
+ """Skip a warp gradient check that MPS cannot run before torch 2.14.
- PyTorch's MPS backend raises ``[srcBuf length] > 0 INTERNAL ASSERT FAILED ... Placeholder
- tensor is empty!`` for a zero-element ``grid_sample`` argument, so an empty warp destination
- is unreachable there regardless of how kornia builds it.
+ ``aten::grid_sampler_2d_backward`` is unimplemented on MPS until torch 2.14, so no warp can run
+ its backward pass there, empty destination or not. The forward half of the empty-warp contract
+ runs on every backend in ``test_empty_destination_forward_runs_on_every_backend``.
"""
- if device.type == "mps":
- pytest.skip("MPS grid_sample asserts on zero-element tensors")
+ if device.type == "mps" and torch_version_lt(2, 14, 0):
+ pytest.skip("MPS lacks aten::grid_sampler_2d_backward before torch 2.14")
class DummyNNModule(torch.nn.Module):
@@ -48,12 +48,89 @@ class DummyNNModule(torch.nn.Module):
return kornia.geometry.transform.warp_affine(x, y, dsize=(self.h, self.w), align_corners=False)
[email protected]("op_name", ["warp_affine", "warp_perspective"])
[email protected]("dsize", [(0, 4), (3, 0), (0, 0)])
[email protected]("batch", [0, 1, 2])
+def test_empty_destination_forward_runs_on_every_backend(op_name, dsize, batch, device, dtype):
+ """An empty destination must not hand ``grid_sample`` a zero-element operand.
+
+ MPS asserts internally (``[srcBuf length] > 0 ... Placeholder tensor is empty!``) on any
+ zero-element ``grid_sample`` argument before torch 2.14, so the empty destination is built from
+ 1x1 stand-ins instead. Forward-only, so it also covers MPS on older torch, where the backward
+ kernel is missing for unrelated reasons.
+ """
+ src = torch.rand(batch, 3, 3, 4, device=device, dtype=dtype)
+ rows = 2 if op_name == "warp_affine" else 3
+ transform = torch.eye(3, device=device, dtype=dtype)[:rows].expand(batch, rows, 3)
+
+ out = getattr(kornia.geometry.transform, op_name)(src, transform, dsize)
+
+ assert out.shape == (batch, 3, *dsize)
+ assert out.numel() == 0
+ assert out.device.type == device.type and out.dtype == dtype
+
+
[email protected]("op_name", ["warp_affine", "warp_perspective", "remap"])
[email protected](("src_batch", "transform_batch"), [(0, 1), (1, 0), (0, 0), (2, 1), (1, 2), (2, 2)])
+def test_empty_destination_matches_nonempty_batch_semantics(op_name, src_batch, transform_batch, device, dtype):
+ """An empty destination broadcasts and rejects batch pairings exactly as the non-empty path.
+
+ The three operations disagree on purpose -- ``warp_perspective`` requires equal batches,
+ ``warp_affine`` expands a singleton matrix only to a source batch above one, and ``remap``
+ expands a singleton map batch to the image batch unconditionally -- so the empty path is
+ pinned against whatever the non-empty call does rather than against a hardcoded expectation.
+ """
+ if device.type == "mps" and 0 in (src_batch, transform_batch) and torch_version_lt(2, 14, 0):
+ pytest.skip("MPS grid_sample asserts on a zero-element batch before torch 2.14")
+
+ def run(empty: bool) -> torch.Tensor:
+ src = torch.rand(src_batch, 2, 3, 4, device=device, dtype=dtype)
+ if op_name == "remap":
+ maps = torch.zeros(transform_batch, 0 if empty else 3, 4, device=device, dtype=dtype)
+ return kornia.geometry.remap(src, maps, maps)
+ rows = 2 if op_name == "warp_affine" else 3
+ transform = torch.eye(3, device=device, dtype=dtype)[:rows].expand(transform_batch, rows, 3)
+ return getattr(kornia.geometry.transform, op_name)(src, transform, (0, 4) if empty else (3, 4))
+
+ try:
+ expected_batch = run(empty=False).shape[0]
+ except RuntimeError:
+ with pytest.raises(RuntimeError):
+ run(empty=True)
+ return
+
+ assert run(empty=True).shape[0] == expected_batch
+
+
+def test_empty_destination_samples_a_constant_1x1_stand_in(device, dtype, monkeypatch):
+ """The sampled stand-in stays 1x1 however large the non-zero side of the destination is.
+
+ The empty result discards whatever was sampled, so materializing ``dsize``-many samples would
+ make an empty warp cost more than a real one -- unbounded, for a result with no elements.
+ """
+ sampled_grids = []
+ real_grid_sample = torch.nn.functional.grid_sample
+
+ def spy(input, grid, **kwargs):
+ sampled_grids.append(tuple(grid.shape))
+ return real_grid_sample(input, grid, **kwargs)
+
+ monkeypatch.setattr(torch.nn.functional, "grid_sample", spy)
+ src = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ transform = torch.eye(2, 3, device=device, dtype=dtype).unsqueeze(0)
+
+ out = kornia.geometry.transform.warp_affine(src, transform, (0, 2_000_000))
+
+ assert out.shape == (1, 3, 0, 2_000_000)
+ assert sampled_grids and all(shape == (1, 1, 1, 2) for shape in sampled_grids)
+
+
@pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
@pytest.mark.parametrize("dsize", [(0, 4), (3, 0)])
@pytest.mark.parametrize("align_corners", [True, False])
@pytest.mark.parametrize("padding_mode", ["zeros", "fill"])
def test_empty_destination_is_autograd_connected(op_name, dsize, align_corners, padding_mode, device, dtype):
- _skip_if_mps_empty_grid_sample(device)
+ _skip_if_mps_lacks_grid_sample_backward(device)
src = torch.rand(1, 3, 3, 4, device=device, dtype=dtype, requires_grad=True)
if op_name == "warp_affine":
transform = torch.eye(2, 3, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
@@ -79,7 +156,7 @@ def test_empty_destination_is_autograd_connected(op_name, dsize, align_corners,
@pytest.mark.parametrize("op_name", ["warp_affine", "warp_perspective"])
def test_empty_source_policy(op_name, device, dtype):
- _skip_if_mps_empty_grid_sample(device)
+ _skip_if_mps_lacks_grid_sample_backward(device)
src = torch.empty(1, 3, 0, 4, device=device, dtype=dtype, requires_grad=True)
if op_name == "warp_affine":
transform = torch.eye(2, 3, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
@@ -794,7 +871,7 @@ class TestRemap(BaseTester):
@pytest.mark.parametrize("source_empty", [False, True])
def test_empty_maps_return_autograd_connected_output(self, source_empty, device, dtype):
- _skip_if_mps_empty_grid_sample(device)
+ _skip_if_mps_lacks_grid_sample_backward(device)
source_height = 0 if source_empty else 3
image = torch.empty(1, 2, source_height, 5, device=device, dtype=dtype, requires_grad=True)
map_x = torch.empty(1, 0, 5, device=device, dtype=dtype, requires_grad=True)
@@ -808,6 +885,18 @@ class TestRemap(BaseTester):
assert map_x.grad is not None
assert map_y.grad is not None
+ @pytest.mark.parametrize("map_shape", [(1, 0, 5), (1, 3, 0)])
+ def test_empty_maps_forward_runs_on_every_backend(self, map_shape, device, dtype):
+ """Empty maps must not hand ``grid_sample`` a zero-element grid."""
+ image = torch.rand(1, 2, 4, 5, device=device, dtype=dtype)
+ map_x = torch.zeros(*map_shape, device=device, dtype=dtype)
+ map_y = torch.zeros(*map_shape, device=device, dtype=dtype)
+
+ output = kornia.geometry.remap(image, map_x, map_y)
+
+ assert output.shape == (1, 2, map_shape[-2], map_shape[-1])
+ assert output.numel() == 0
+
def test_empty_maps_keep_grid_sample_validation(self, device, dtype):
image = torch.empty(1, 2, 0, 5, device=device, dtype=dtype)
map_x = torch.empty(1, 0, 5, device=device, dtype=dtype)