Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): preserve empty-batch shape history for inverse replay (#5620)

renta04264b4becd73e7c
diff --git a/changelog.d/5620.breaking.md b/changelog.d/5620.breaking.md
new file mode 100644
index 000000000..f23f75145
--- /dev/null
+++ b/changelog.d/5620.breaking.md
@@ -0,0 +1,11 @@
+On an empty batch, the inverse of a shape-changing 2D geometric augmentation now returns the input height and width
+recorded in its parameters, keeping the channels, dtype, device and autograd graph of the tensor it inverts. It used
+to return the transformed size: for a `(0, 3, 6, 8)` forward, `Resize((5, 7)).inverse` gave `(0, 3, 5, 7)` and now
+gives `(0, 3, 6, 8)`. This covers `Resize`, `LongestMaxSize`, `SmallestMaxSize`, `CenterCrop`, `RandomResizedCrop`
+and resample-mode `RandomCrop`, directly and through `AugmentationSequential.inverse`. Two empty-batch parameters
+change with it. `RandomCrop` now records the unpadded input as `forward_input_shape`; it used to record the padded
+canvas, which an empty batch cannot undo because its `padding_size` has no rows. In a container, a stage after an
+always-applied (`p=1`) `RandomCrop` or `Resize` (including `LongestMaxSize` and `SmallestMaxSize`) now records its
+own input size; it used to record the size before that crop or resize. Empty `RandomCrop` parameters saved before
+this change still replay but restore the padded canvas, for example `(0, 1, 12, 12)` instead of `(0, 1, 6, 8)` with
+`padding=(1, 2, 3, 4)`: regenerate them. Non-empty batches are unchanged. Part of #4429.
diff --git a/changelog.d/5620.fixed.md b/changelog.d/5620.fixed.md
new file mode 100644
index 000000000..b5c6a7cee
--- /dev/null
+++ b/changelog.d/5620.fixed.md
@@ -0,0 +1,4 @@
+`AugmentationSequential.inverse` of an empty-batch mask no longer raises `IndexError` (from `padding_size[0]`) when it
+replays `RandomCrop` parameters other than the dict the last forward call used, such as a copy. `VideoSequential` no
+longer raises `IndexError` on an empty batch when it contains a `Resize`, `LongestMaxSize` or `SmallestMaxSize`.
+Part of #4429.
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 0317599be..8b71684bc 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -56,6 +56,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
call depends on its implementation and configuration: slice-mode crops, for example, do not support it.
Inverse resampling cannot recover image or mask information lost through cropping, padding, or
interpolation. Tensor-form boxes may lose rotated corners through axis-aligned enclosure.
+ For an empty batch, image and mask inverse restore the spatial dimensions recorded in the parameters.
- container mask processing has dtype- and operator-specific limitations; see
`#4478 <https://github.com/kornia/kornia/issues/4478>`_. Direct ``transform_masks`` calls use the
image dtype guard and therefore reject ``bool`` masks.
@@ -228,6 +229,11 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
transform: Optional[torch.Tensor] = None,
**kwargs: Any,
) -> torch.Tensor:
+ """Inverse image inputs.
+
+ For an empty batch with recorded input-shape metadata, image and mask inverses
+ restore the recorded spatial size while preserving the inverse input's channel count.
+ """
in_tensor = self.transform_tensor(input)
output = in_tensor.clone()
batch_prob = params["batch_prob"]
@@ -243,8 +249,11 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
_size = params["forward_input_shape"].tolist()
size = (_size[-2], _size[-1])
+ # An empty batch has no applied rows, but still needs its recorded spatial shape restored.
+ if in_tensor.shape[0] == 0 and size is not None:
+ output = in_tensor.reshape(*in_tensor.shape[:-2], *size)
# if no augmentation needed
- if not to_apply.any():
+ elif not to_apply.any():
output = in_tensor
# if all data needs to be augmented
elif to_apply.all():
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index e879f91bd..90a81a0dc 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -100,6 +100,7 @@ class RandomCrop(GeometricAugmentationBase2D):
``align_corners`` and maps constant, replicate and reflect pre-padding to zero, border and reflection
sampler padding. Only resample mode supports :meth:`inverse`, which removes the pre-crop padding but cannot
restore cropped or interpolated content.
+ For an empty batch, ``forward_input_shape`` records the original, unpadded canvas for inverse replay.
Note:
Compiled slice-mode interpolation matches eager execution to floating-point tolerance,
@@ -455,6 +456,7 @@ class RandomCrop(GeometricAugmentationBase2D):
)
)
padding_size = _constant_tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
- _params = super().forward_parameters(batch_shape_new)
+ # An empty batch has no padding rows and no pixels to pad. Keep its original canvas for inverse replay.
+ _params = super().forward_parameters(batch_shape if batch_shape[0] == 0 else batch_shape_new)
_params.update({"padding_size": padding_size})
return _params
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index d8c504704..b185040b0 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -27,6 +27,7 @@ from kornia.core import ImageModule
from kornia.core.mixin.image_module import ImageModuleMixIn
from kornia.core.ops import eye_like
from kornia.core.utils import is_exporting
+from kornia.geometry.transform.affwarp import _side_to_image_size
from .base import ImageSequentialBase
from .params import ParamItem, PatchParamItem
@@ -472,6 +473,8 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Opti
Note:
Augmentations that change the image size must provide the parameter `output_size`.
+ Empty crops and resizes have no sampled output-size rows, so their configured size is used
+ only when the image forward path always applies the transform.
"""
data = param.data
@@ -503,6 +506,18 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Opti
batch_shape = _get_new_batch_shape(p, batch_shape, children.get(p.name))
return batch_shape
+ if batch_shape[0] == 0 and isinstance(module, (K.RandomCrop, K.Resize)):
+ # Match the image forward's unconditional path. An empty gate selects the original
+ # canvas in the other probability branches, including Resize's p_batch setting (#4429).
+ if module.p != 1.0 or module.p_batch != 1.0:
+ return batch_shape
+ size = module.flags["size"]
+ if isinstance(module, K.Resize) and isinstance(size, int):
+ size = _side_to_image_size(size, batch_shape[-1] / batch_shape[-2], module.flags["side"])
+ new_batch_shape = list(batch_shape)
+ new_batch_shape[-2:] = size
+ return torch.Size(new_batch_shape)
+
# Carefully avoid evaluating expression multiple times; batch_prob is often a 1-element torch.Tensor
if "output_size" in data:
if is_exporting():
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 41667b49b..dd23f5502 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -85,7 +85,12 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
dtype = reference.dtype if reference is not None and torch.is_floating_point(reference) else torch.float32
input_shape = tuple(forward_input_shape.tolist())
padding_size = params.get("padding_size")
- if not is_exporting() and isinstance(padding_size, torch.Tensor) and len(input_shape) >= 2:
+ if (
+ not is_exporting()
+ and isinstance(padding_size, torch.Tensor)
+ and padding_size.shape[0] > 0
+ and len(input_shape) >= 2
+ ):
left, right, top, bottom = padding_size[0].tolist()
input_shape = (*input_shape[:-2], input_shape[-2] - top - bottom, input_shape[-1] - left - right)
matrix_input = torch.empty((), device=device, dtype=dtype).expand(input_shape)
diff --git a/tests/augmentation/test_empty_inverse.py b/tests/augmentation/test_empty_inverse.py
new file mode 100644
index 000000000..b012a8cbc
--- /dev/null
+++ b/tests/augmentation/test_empty_inverse.py
@@ -0,0 +1,430 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+from copy import deepcopy
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+
+from testing.base import BaseTester, supports_bilinear_2d_grid_sample_backward
+
+
+class TestEmptyGeometricInverse(BaseTester):
+ @pytest.mark.parametrize("method", ["inverse_inputs", "inverse_masks"])
+ @pytest.mark.parametrize(
+ "make_aug",
+ [
+ lambda: K.Resize((4, 5)),
+ lambda: K.Resize(4, side="long"),
+ lambda: K.LongestMaxSize(4),
+ lambda: K.SmallestMaxSize(4),
+ lambda: K.CenterCrop((4, 5), cropping_mode="resample"),
+ lambda: K.RandomResizedCrop((4, 5), cropping_mode="resample"),
+ ],
+ ids=["resize-tuple", "resize-int", "longest", "smallest", "center-crop", "resized-crop"],
+ )
+ def test_restores_spatial_shape_4429(self, make_aug, method, device, dtype):
+ aug = make_aug()
+ params = aug.forward_parameters((0, 3, 6, 8))
+ # A mask can have fewer channels than the image whose parameters it replays.
+ channels = 1 if method == "inverse_masks" else 3
+ cropped = torch.empty(0, channels, 4, 5, device=device, dtype=dtype, requires_grad=True)
+ restored = getattr(aug, method)(cropped, params, aug.flags)
+ assert restored.shape == (0, channels, 6, 8)
+ assert restored.device == device
+ assert restored.dtype == dtype
+ restored.sum().backward()
+ self.assert_close(cropped.grad, torch.empty_like(cropped))
+
+ @pytest.mark.parametrize("method", ["inverse_inputs", "inverse_masks"])
+ def test_without_shape_metadata_preserves_input(self, method, device, dtype):
+ aug = K.RandomHorizontalFlip()
+ image = torch.empty(0, 3, 4, 5, device=device, dtype=dtype)
+ output = getattr(aug, method)(image, {"batch_prob": torch.empty(0)}, aug.flags)
+ self.assert_close(output, image)
+
+ @pytest.mark.parametrize(
+ "padding,pad_if_needed,size",
+ [
+ (None, False, (4, 5)),
+ (2, False, (4, 5)),
+ ((1, 2, 3, 4), False, (4, 5)),
+ ((0, 1, 2, 3), True, (10, 12)),
+ ],
+ )
+ @pytest.mark.parametrize("method", ["inverse_inputs", "inverse_masks", "inverse"])
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ def test_crop_replays_padding_history_4429(self, padding, pad_if_needed, size, method, p, device, dtype):
+ aug = K.RandomCrop(size, padding=padding, pad_if_needed=pad_if_needed, cropping_mode="resample", p=p)
+ params = deepcopy(aug.forward_parameters((0, 3, 6, 8)))
+ assert params["padding_size"].shape == (0, 4)
+ assert params["forward_input_shape"].tolist() == [0, 3, 6, 8]
+ channels = 1 if method == "inverse_masks" else 3
+ cropped = torch.empty(0, channels, *size, device=device, dtype=dtype, requires_grad=True)
+ # Replay must use the original padding history, including after module flags change.
+ aug.flags.update(padding=7, pad_if_needed=False, size=(2, 3))
+ if method == "inverse":
+ restored = aug.inverse(cropped, params=params)
+ else:
+ restored = getattr(aug, method)(cropped, params, aug.flags)
+ assert restored.shape == (0, channels, 6, 8)
+ assert restored.device == device
+ assert restored.dtype == dtype
+ restored.sum().backward()
+ self.assert_close(cropped.grad, torch.empty_like(cropped))
+
+ @pytest.mark.parametrize(
+ "make_aug",
+ [
+ lambda: K.Resize((4, 5), p=0.0),
+ lambda: K.RandomCrop((4, 5), padding=(1, 2, 3, 4), p=0.0, cropping_mode="resample"),
+ ],
+ ids=["resize", "crop"],
+ )
+ @pytest.mark.parametrize("method", ["inverse_inputs", "inverse_masks"])
+ def test_nonempty_skipped_batch_is_unchanged(self, make_aug, method, device, dtype):
+ aug = make_aug()
+ image = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ params = aug.forward_parameters(image.shape)
+ output = getattr(aug, method)(image, params, aug.flags)
+ self.assert_close(output, image, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
+ @pytest.mark.parametrize("height,width", [(6, 8), (9, 13)])
+ def test_sequential_round_trip_4429(self, p, height, width, device, dtype):
+ if not supports_bilinear_2d_grid_sample_backward(device, dtype):
+ pytest.skip("The forward resampling kernel does not support this device/dtype's backward pass.")
+ aug = K.AugmentationSequential(
+ K.RandomCrop((4, 5), padding=(1, 2, 3, 4), cropping_mode="resample", p=p),
+ K.Resize((2, 3)),
+ data_keys=["input"],
+ )
+ image = torch.empty(0, 3, height, width, device=device, dtype=dtype, requires_grad=True)
+ output = aug(image)
+ mask = torch.empty(0, 1, *output.shape[-2:], device=device, dtype=dtype, requires_grad=True)
+ restored_image, restored_mask = aug.inverse(output, mask, data_keys=["input", "mask"])
+ assert restored_image.shape == image.shape
+ assert restored_mask.shape == (0, 1, height, width)
+ for restored, original in ((restored_image, image), (restored_mask, mask)):
+ assert restored.device == original.device
+ assert restored.dtype == original.dtype
+ restored.sum().backward()
+ self.assert_close(original.grad, torch.empty_like(original))
+
+ @pytest.mark.parametrize(
+ "crop_p,resize_p",
+ [
+ (0.0, 0.0),
+ (0.0, 0.5),
+ (0.0, 1.0),
+ (0.5, 0.0),
+ (0.5, 0.5),
+ (0.5, 1.0),
+ (1.0, 0.0),
+ (1.0, 0.5),
+ (1.0, 1.0),
+ ],
+ )
+ @pytest.mark.parametrize("height,width", [(6, 8), (9, 13)])
+ def test_empty_stage_shape_history_4429(self, crop_p, resize_p, height, width, device, dtype):
+ crop = K.RandomCrop((4, 5), cropping_mode="resample", p=crop_p)
+ resize = K.Resize((3, 4), p=resize_p)
+ sequence = K.AugmentationSequential(crop, resize, data_keys=["input"])
+ image = torch.empty(0, 3, height, width, device=device, dtype=dtype)
+ output = sequence(image)
+ saved_params = deepcopy(sequence._params)
+
+ # With p < 1 an empty batch keeps its input size, because the blend falls back to the skipped
+ # branch (tracked in #4429). This pins the current forward, which the tracked shapes must follow.
+ crop_size = (4, 5) if crop_p == 1.0 else (height, width)
+ output_size = (3, 4) if resize_p == 1.0 else crop_size
+ assert saved_params[0].data["forward_input_shape"].tolist() == [0, 3, height, width]
+ assert saved_params[1].data["forward_input_shape"].tolist() == [0, 3, *crop_size]
+ assert output.shape == (0, 3, *output_size)
+ assert output.dtype == image.dtype
+ assert output.device == image.device
+
+ @pytest.mark.parametrize(
+ "height,width,intermediate_size",
+ [(6, 8, (7, 9)), (9, 13, (7, 10))],
+ )
+ def test_empty_integer_resize_shape_history_4429(self, height, width, intermediate_size, device, dtype):
+ first_resize = K.Resize(7, side="short")
+ second_resize = K.Resize((3, 4))
+ sequence = K.AugmentationSequential(first_resize, second_resize, data_keys=["input"])
+ image = torch.empty(0, 3, height, width, device=device, dtype=dtype)
+ direct_output = first_resize(image)
+ assert direct_output.shape == (0, 3, *intermediate_size)
+ assert direct_output.dtype == image.dtype
+ assert direct_output.device == image.device
+
+ output = sequence(image)
+ saved_params = deepcopy(sequence._params)
+ assert output.shape == (0, 3, 3, 4)
+ assert output.dtype == image.dtype
+ assert output.device == image.device
+ assert saved_params[0].data["forward_input_shape"].tolist() == [0, 3, height, width]
+ assert saved_params[1].data["forward_input_shape"].tolist() == [0, 3, *intermediate_size]
+
+ for replay_state in ("immediate", "after-forward"):
+ if replay_state == "after-forward":
+ next_height, next_width = (9, 13) if (height, width) == (6, 8) else (6, 8)
+ nonempty = torch.arange(
+ 2 * 3 * next_height * next_width,
+ device=device,
+ dtype=dtype,
+ ).reshape(2, 3, next_height, next_width)
+ sequence(nonempty)
+
+ mask = torch.empty(0, 1, *output.shape[-2:], device=device, dtype=dtype, requires_grad=True)
+ intermediate = second_resize.inverse(mask, params=saved_params[1].data)
+ assert intermediate.shape == (0, 1, *intermediate_size)
+ restored = first_resize.inverse(intermediate, params=saved_params[0].data)
+ assert restored.shape == (0, 1, height, width)
+
+ replayed = sequence.inverse(mask, params=saved_params, data_keys=["mask"])
+ assert replayed.shape == (0, 1, height, width)
+ assert replayed.dtype == mask.dtype
+ assert replayed.device == mask.device
+ replayed.sum().backward()
+ assert mask.grad is not None
+ assert mask.grad.shape == mask.shape
+
+ @pytest.mark.parametrize("height,width", [(6, 8), (9, 13)])
+ def test_empty_nested_shape_history_4429(self, height, width, device, dtype):
+ crop = K.RandomCrop((4, 5), padding=(1, 2, 3, 4), cropping_mode="resample", p=1.0)
+ inner_resize = K.Resize((3, 4))
+ inner = K.ImageSequential(crop, inner_resize)
+ outer_resize = K.Resize((2, 3))
+ sequence = K.AugmentationSequential(inner, outer_resize, data_keys=["input"])
+ image = torch.empty(0, 3, height, width, device=device, dtype=dtype)
+ output = sequence(image)
+ saved_params = deepcopy(sequence._params)
+ inner_params = saved_params[0].data
+ assert output.shape == (0, 3, 2, 3)
+ assert output.dtype == image.dtype
+ assert output.device == image.device
+ assert inner_params[0].data["forward_input_shape"].tolist() == [0, 3, height, width]
+ assert inner_params[1].data["forward_input_shape"].tolist() == [0, 3, 4, 5]
+ assert saved_params[1].data["forward_input_shape"].tolist() == [0, 3, 3, 4]
+
+ mask = torch.empty(0, 1, *output.shape[-2:], device=device, dtype=dtype, requires_grad=True)
+ outer_restored = outer_resize.inverse(mask, params=saved_params[1].data)
+ assert outer_restored.shape == (0, 1, 3, 4)
+ inner_restored = inner_resize.inverse(outer_restored, params=inner_params[1].data)
+ assert inner_restored.shape == (0, 1, 4, 5)
+ restored = crop.inverse(inner_restored, params=inner_params[0].data)
+ assert restored.shape == (0, 1, height, width)
+
+ replayed = sequence.inverse(mask, params=deepcopy(saved_params), data_keys=["mask"])
+ assert replayed.shape == (0, 1, height, width)
+ assert replayed.dtype == mask.dtype
+ assert replayed.device == mask.device
+ replayed.sum().backward()
+ assert mask.grad is not None
+ assert mask.grad.shape == mask.shape
+
+ @pytest.mark.parametrize("height,width", [(6, 8), (9, 13)])
+ @pytest.mark.parametrize("replay_state", ["immediate", "after-forward", "fresh-instance"])
+ def test_mask_only_saved_params_replay_4429(self, height, width, replay_state, device, dtype):
+ if not supports_bilinear_2d_grid_sample_backward(device, dtype):
+ pytest.skip("The forward resampling kernel does not support this device/dtype's backward pass.")
+
+ def make_sequence():
+ return K.AugmentationSequential(
+ K.RandomCrop(
+ (4, 5),
+ padding=(1, 2, 3, 4),
+ cropping_mode="resample",
+ p=1.0,
+ ),
+ data_keys=["input"],
+ )
+
+ sequence = make_sequence()
+ output = sequence(torch.empty(0, 3, height, width, device=device, dtype=dtype))
+ saved_params = deepcopy(sequence._params)
+ assert output.shape == (0, 3, 4, 5)
+ assert saved_params[0].data["forward_input_shape"].tolist() == [0, 3, height, width]
+
+ if replay_state == "after-forward":
+ next_height, next_width = (9, 13) if (height, width) == (6, 8) else (6, 8)
+ nonempty = torch.arange(
+ 2 * 3 * next_height * next_width,
+ device=device,
+ dtype=dtype,
+ ).reshape(2, 3, next_height, next_width)
+ sequence(nonempty)
+ elif replay_state == "fresh-instance":
+ sequence = make_sequence()
+
+ mask = torch.empty(0, 1, *output.shape[-2:], device=device, dtype=dtype, requires_grad=True)
+ restored = sequence.inverse(mask, params=saved_params, data_keys=["mask"])
+ assert restored.shape == (0, 1, height, width)
+ assert restored.device == device
+ assert restored.dtype == dtype
+ restored.sum().backward()
+ assert mask.grad is not None
+ assert mask.grad.shape == mask.shape
+
+ @pytest.mark.parametrize("height,width", [(6, 8), (9, 13)])
+ def test_two_stage_mask_saved_params_replay_4429(self, height, width, device, dtype):
+ if not supports_bilinear_2d_grid_sample_backward(device, dtype):
+ pytest.skip("The forward resampling kernel does not support this device/dtype's backward pass.")
+ crop = K.RandomCrop(
+ (4, 5),
+ padding=(1, 2, 3, 4),
+ cropping_mode="resample",
+ p=1.0,
+ )
+ resize = K.Resize((3, 4))
+ sequence = K.AugmentationSequential(crop, resize, data_keys=["input"])
+ output = sequence(torch.empty(0, 3, height, width, device=device, dtype=dtype))
+ saved_params = deepcopy(sequence._params)
+ mask = torch.empty(0, 1, *output.shape[-2:], device=device, dtype=dtype, requires_grad=True)
+
+ intermediate = resize.inverse(mask, params=saved_params[1].data)
+ assert intermediate.shape == (0, 1, 4, 5)
+ restored = crop.inverse(intermediate, params=saved_params[0].data)
+ assert restored.shape == (0, 1, height, width)
+
+ replayed = sequence.inverse(mask, params=deepcopy(saved_params), data_keys=["mask"])
+ assert replayed.shape == (0, 1, height, width)
+ assert replayed.device == device
+ assert replayed.dtype == dtype
+ replayed.sum().backward()
+ assert mask.grad is not None
+ assert mask.grad.shape == mask.shape
+
+ @pytest.mark.parametrize(
+ "make_sequence",
+ [
+ lambda: K.AugmentationSequential(
+ K.RandomCrop(
+ (4, 5),
+ padding=(1, 2, 3, 4),
+ cropping_mode="resample",
+ p=1.0,
+ ),
+ data_keys=["input"],
+ ),
+ lambda: K.AugmentationSequential(K.Resize((4, 5)), data_keys=["input"]),
+ ],
+ ids=["random-crop", "resize"],
+ )
+ def test_dynamo_mask_only_saved_params_replay_4429(
+ self,
+ make_sequence,
+ torch_optimizer,
+ device,
+ dtype,
+ ):
+ sequence = make_sequence()
+ output = sequence(torch.empty(0, 3, 9, 13, device=device, dtype=dtype))
+ saved_params = deepcopy(sequence._params)
+ mask = torch.empty(0, 1, *output.shape[-2:], device=device, dtype=dtype)
+
+ def replay(saved_mask):
+ return sequence.inverse(saved_mask, params=saved_params, data_keys=["mask"])
+
+ eager = replay(mask)
+ compiled = torch_optimizer(replay)
+ actual = compiled(mask)
+ self.assert_close(actual, eager)
+ assert actual.shape == (0, 1, 9, 13)
+ assert actual.device == device
+ assert actual.dtype == dtype
+
+ @pytest.mark.parametrize(
+ "make_aug,output_size",
+ [
+ (lambda p: K.Resize((4, 5), p=p), (4, 5)),
+ (lambda p: K.Resize(4, side="long", p=p), (3, 4)),
+ (lambda p: K.LongestMaxSize(4, p=p), (3, 4)),
+ (lambda p: K.SmallestMaxSize(4, p=p), (4, 5)),
+ (lambda p: K.CenterCrop((4, 5), cropping_mode="resample", p=p), (4, 5)),
+ (lambda p: K.RandomResizedCrop((4, 5), cropping_mode="resample", p=p), (4, 5)),
+ (lambda p: K.RandomCrop((4, 5), padding=(1, 2, 3, 4), cropping_mode="resample", p=p), (4, 5)),
+ ],
+ ids=["resize-tuple", "resize-int", "longest", "smallest", "center-crop", "resized-crop", "crop"],
+ )
+ @pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
+ def test_public_round_trip_4429(self, make_aug, output_size, p, device, dtype):
+ aug = make_aug(p)
+ if not isinstance(aug, K.Resize) and not supports_bilinear_2d_grid_sample_backward(device, dtype):
+ pytest.skip("The forward resampling kernel does not support this device/dtype's backward pass.")
+ image = torch.empty(0, 3, 6, 8, device=device, dtype=dtype, requires_grad=True)
+ output = aug(image)
+ # With p < 1 an empty batch keeps its input size (blend fallback, tracked in #4429); the inverse
+ # must undo whichever size the forward produced.
+ expected_size = output_size if p == 1.0 else (6, 8)
+ assert output.shape == (0, 3, *expected_size)
+ restored = aug.inverse(output)
+ assert restored.shape == image.shape
+ assert restored.device == image.device
+ assert restored.dtype == image.dtype
+ restored.sum().backward()
+ self.assert_close(image.grad, torch.empty_like(image))
+
+ def test_empty_slice_crop_inverse_is_unsupported(self, device, dtype):
+ aug = K.RandomCrop((4, 5), cropping_mode="slice")
+ image = torch.empty(0, 3, 6, 8, device=device, dtype=dtype)
+ output = aug(image)
+ with pytest.raises(NotImplementedError, match="only applicable for resample cropping mode"):
+ aug.inverse(output)
+
+ @pytest.mark.parametrize(
+ "make_first,intermediate_size",
+ [
+ (lambda: K.LongestMaxSize(12), (9, 12)),
+ (lambda: K.Resize(12, side="long"), (9, 12)),
+ (lambda: K.SmallestMaxSize(12), (12, 14)),
+ ],
+ ids=["longest", "resize-long", "smallest"],
+ )
+ def test_empty_max_size_shape_history_4429(self, make_first, intermediate_size, device, dtype):
+ # The container must size an integer resize on the side the module selects, as the module does.
+ first = make_first()
+ second = K.Resize((3, 4))
+ sequence = K.AugmentationSequential(first, second, data_keys=["input"])
+ image = torch.empty(0, 3, 9, 11, device=device, dtype=dtype)
+ assert first(image).shape == (0, 3, *intermediate_size)
+ output = sequence(image)
+ assert output.shape == (0, 3, 3, 4)
+ params = sequence._params
+ assert params[1].data["forward_input_shape"].tolist() == [0, 3, *intermediate_size]
+ mask = torch.empty(0, 1, 3, 4, device=device, dtype=dtype)
+ assert second.inverse(mask, params=params[1].data).shape == (0, 1, *intermediate_size)
+ assert sequence.inverse(mask, params=params, data_keys=["mask"]).shape == (0, 1, 9, 11)
+
+ @pytest.mark.parametrize("same_on_frame", [False, True])
+ def test_empty_video_resize_4429(self, same_on_frame, device, dtype):
+ # VideoSequential tracks shapes with the same helper; an empty batch used to raise IndexError there.
+ sequence = K.VideoSequential(
+ K.RandomCrop((6, 7), cropping_mode="resample"),
+ K.LongestMaxSize(10),
+ data_format="BTCHW",
+ same_on_frame=same_on_frame,
+ )
+ video = torch.empty(0, 2, 3, 9, 11, device=device, dtype=dtype)
+ output = sequence(video)
+ assert output.shape == (0, 2, 3, 8, 10)
+ assert sequence.inverse(output).shape == video.shape