Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): RandomRotation90 raises on a non-square image that may turn oddly (#6305)

Aryan Kumar3c76ee96aa5a
diff --git a/changelog.d/6305.breaking.md b/changelog.d/6305.breaking.md
new file mode 100644
index 000000000..c75586f63
--- /dev/null
+++ b/changelog.d/6305.breaking.md
@@ -0,0 +1 @@
+`RandomRotation90` now raises `ValueError` on a non-square input when the `times` range allows an odd number of quarter turns, such as `times=(1, 1)` or `times=(-1, 1)`, even if a given call would draw an even one. An odd number of turns swaps the height and the width, but the class keeps the input's `(H, W)`, so it used to return an image of the same shape with the part that did not fit cut off and a strip of zeros in its place (a 6 x 8 image lost two of its eight columns), with no warning (#4409). Square images, and ranges of even numbers only such as `times=(2, 2)`, behave as before. The error names `RandomRotation` with a fixed angle of 90 degrees, to rotate and crop, and `torch.rot90`, to turn a whole batch exactly. `AdaptiveDiscriminatorAugmentation` is affected through its default stack, which contains `RandomRotation90(times=(0, 3))`: it now raises on a non-square image, on the first call, before it selects any sample, so the default preset needs square images.
diff --git a/docs/export_support/cases_aug.py b/docs/export_support/cases_aug.py
index 52cd63ff3..7edc6a914 100644
--- a/docs/export_support/cases_aug.py
+++ b/docs/export_support/cases_aug.py
@@ -40,6 +40,7 @@ torch.manual_seed(0)
IMG = torch.rand(2, 3, 32, 40)
IMG1 = torch.rand(1, 3, 32, 40)
+IMG_SQUARE = IMG[..., :32] # RandomRotation90 raises on a non-square image when it may turn it oddly
VOL = torch.rand(2, 1, 8, 16, 16)
LABEL = torch.tensor([0, 1])
MASK = (torch.rand(2, 1, 32, 40) > 0.5).float()
@@ -317,7 +318,7 @@ build(
note="pad_mode=reflect",
rand=False,
)
-build("RandomRotation90", G2, lambda: KA.RandomRotation90(times=(1, 3), p=1.0), [IMG])
+build("RandomRotation90", G2, lambda: KA.RandomRotation90(times=(1, 3), p=1.0), [IMG_SQUARE])
build("RandomShear", G2, lambda: KA.RandomShear(shear=10.0, p=1.0), [IMG])
build("RandomTranslate", G2, lambda: KA.RandomTranslate((0.1, 0.2), (0.1, 0.2), p=1.0), [IMG])
build("RandomChannelDropout[b1]", G2, lambda: KA.RandomChannelDropout(p=1.0), [IMG1], rand=False, note="batch 1")
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 22a947fa6..562be4df1 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -149,6 +149,16 @@ class RandomRotation(GeometricAugmentationBase2D):
)
+def _range_allows_odd_turns(low: float, high: float) -> bool:
+ """Whether a ``times`` draw from ``[low, high]`` can round to an odd number of quarter turns.
+
+ The bounds are rounded the way ``compute_transformation`` rounds a draw. Two different whole numbers always include
+ an odd one, and a single whole number is either odd or even.
+ """
+ low, high = round(low), round(high)
+ return high > low or low % 2 != 0
+
+
class RandomRotation90(GeometricAugmentationBase2D):
r"""Rotate images by a random multiple of 90 degrees, applied per sample with probability ``p`` (default 0.5).
@@ -172,7 +182,12 @@ class RandomRotation90(GeometricAugmentationBase2D):
- a range of whole numbers for ``times`` is closed and uniform: ``times=(-1, 1)`` gives a clockwise quarter
turn, no turn and a counter-clockwise quarter turn with the same probability. A range with a fractional
bound is still drawn continuously and rounded.
- - a non-square image keeps its ``(H, W)`` shape (`#4409 <https://github.com/kornia/kornia/issues/4409>`_).
+ - an odd number of quarter turns swaps the height and the width, but the output keeps the ``(H, W)`` of the
+ input, so part of a non-square image would be cut off. A non-square input therefore raises ``ValueError``
+ when the ``times`` range allows an odd number of quarter turns, even if a given call would draw an even one.
+ Square images, and ranges of even numbers only such as ``times=(2, 2)``, are unaffected. Use
+ :class:`~kornia.augmentation.RandomRotation` with a fixed angle of 90 degrees to rotate and crop, or
+ :func:`torch.rot90` to turn a whole batch exactly.
.. note::
This function internally uses :func:`kornia.geometry.transform.affine`. This version is relatively
@@ -216,9 +231,29 @@ class RandomRotation90(GeometricAugmentationBase2D):
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
self._param_generator = rg.Rotation90Generator(times)
+ low, high = self._param_generator.times.tolist()
+ self._allows_odd_turns = _range_allows_odd_turns(low, high)
self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}
+ def __setstate__(self, state: Dict[str, Any]) -> None:
+ super().__setstate__(state)
+ if "_allows_odd_turns" not in self.__dict__:
+ # A RandomRotation90 pickled before the non-square check existed has no cached answer.
+ low, high = self._param_generator.times.tolist()
+ self._allows_odd_turns = _range_allows_odd_turns(low, high)
+
+ def validate_tensor(self, input: torch.Tensor) -> None:
+ super().validate_tensor(input)
+ height, width = input.shape[-2:]
+ if self._allows_odd_turns and height != width:
+ raise ValueError(
+ f"`RandomRotation90` keeps the (H, W) shape, so an odd number of quarter turns of a non-square "
+ f"{height}x{width} image would cut off part of it, and `times` allows one. Use a square image, "
+ "`RandomRotation` with a fixed angle of 90 degrees to rotate and crop, or `torch.rot90` to turn "
+ "the whole batch exactly."
+ )
+
def compute_transformation(
self, input: torch.Tensor, params: dict[str, torch.Tensor], flags: dict[str, Any]
) -> torch.Tensor:
diff --git a/kornia/augmentation/presets/ada.py b/kornia/augmentation/presets/ada.py
index fa90b1962..1f67e1b21 100644
--- a/kornia/augmentation/presets/ada.py
+++ b/kornia/augmentation/presets/ada.py
@@ -78,6 +78,14 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
**kwargs: Additional keyword arguments passed to `AugmentationSequential`
+ .. note::
+ The default augmentation stack contains ``RandomRotation90(times=(0, 3))``, which raises ``ValueError`` on a
+ non-square image, so the default needs square images. ADA checks the image against it on every call, before
+ it selects samples, so a non-square image raises on the first call. In a custom stack, a
+ :class:`~kornia.augmentation.RandomRotation90` that may turn an image by an odd number of quarter turns needs
+ the image it receives to be square, after any earlier resize, crop or patch split, and raises when ADA first
+ selects a sample.
+
Examples:
>>> from kornia.augmentation.presets.ada import AdaptiveDiscriminatorAugmentation
>>> original = torch.randn(2, 3, 16, 16)
@@ -89,7 +97,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
>>> import kornia.augmentation as K
>>> from kornia.augmentation.presets.ada import AdaptiveDiscriminatorAugmentation
- >>> originals = torch.randn(2, 3, 5, 6)
+ >>> originals = torch.randn(2, 3, 6, 6)
>>> aug_list = [
... K.RandomRotation90(times=(0, 3), p=1),
... K.RandomAffine(degrees=10, translate=(.1, .1), scale=(.9, 1.1), p=1),
@@ -97,7 +105,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
... ]
>>> ada = AdaptiveDiscriminatorAugmentation(*aug_list)
- >>> augmented = ada(original)
+ >>> augmented = ada(originals)
This example demonstrates using custom augmentations with AdaptiveDiscriminatorAugmentation.
"""
@@ -118,7 +126,8 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
same_on_batch: Optional[bool] = False,
**kwargs: Any,
) -> None:
- if not args:
+ default_stack = not args
+ if default_stack:
args = self.default_ada_transfroms(erasing_scale, erasing_ratio, erasing_fill_value)
super().__init__(
@@ -132,6 +141,9 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
**kwargs,
)
+ # ADA built the default stack, so it knows the stack's RandomRotation90 receives the input's (H, W).
+ self._default_stack = default_stack
+
if adjustment_speed <= 0:
raise ValueError(f"Invalid `adjustment_speed` ({adjustment_speed}) β€” must be greater than 0")
@@ -241,6 +253,26 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
order = sorted(range(len(keys)), key=lambda i: dict_data_keys[i] != DataKey.INPUT)
return [keys[i] for i in order]
+ def _validate_rotation90_inputs(self, inputs: _inputs_type, data_keys: Optional[_data_keys_type]) -> None:
+ # Only the default stack: in a custom one an earlier module can resize the image, or a container can cut it into
+ # patches or frames, so the input's (H, W) is not the one its RandomRotation90 receives. There the rotation
+ # checks the tensor it receives, when ADA first selects a sample. An ADA pickled before this check has no flag.
+ if not getattr(self, "_default_stack", False):
+ return
+ if isinstance(inputs, dict):
+ keys, dict_data_keys, _, _ = self._preproc_dict_data(cast(Dict[str, DataType], inputs))
+ images = [inputs[key] for key, data_key in zip(keys, dict_data_keys) if data_key == DataKey.INPUT]
+ else:
+ # A tensor is an image unless ``data_keys`` name it otherwise; a mask-only call is not checked here.
+ if data_keys is None:
+ data_keys = [k.name for k in self.data_keys] if self.data_keys is not None else ["input"]
+ images = [inputs] if DataKey.get(data_keys[0]) == DataKey.INPUT else []
+ rotations = [module for module in self.modules() if isinstance(module, RandomRotation90)]
+ for image in images:
+ if image.dim() == 4:
+ for rotation in rotations:
+ rotation.validate_tensor(image)
+
def _get_inputs_metadata(
self, inputs: _inputs_type, data_keys: _data_keys_type
) -> Tuple[int, Optional[Union[str, torch.device]]]:
@@ -310,6 +342,11 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
if real_acc is not None:
self.update(real_acc)
+ # ADA only calls its augmentations for the samples its probability selects, which at a small `p` can be many
+ # calls in. Check the input here, on every call, so a shape the default `RandomRotation90` rejects fails on the
+ # first one.
+ self._validate_rotation90_inputs(inputs, data_keys)
+
if self.p == 0:
return inputs
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 7e04f396f..ef43375e2 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -125,6 +125,10 @@ class CommonTests(BaseTester):
############################################################################################################
_augmentation_cls: Optional[Type[AugmentationBase2D]] = None
_default_param_set: Dict["str", Any] = {}
+ # input shapes the shared tests use; override for an augmentation that needs square images
+ _batch_shape = (4, 3, 5, 6)
+ _p0_shape = (2, 3, 4, 5)
+ _inverse_shape = (1, 3, 50, 100)
############################################################################################################
# Fixtures
@@ -208,7 +212,7 @@ class CommonTests(BaseTester):
)
# generate_parameters can be called and returns the correct amount of parameters
- batch_shape = (4, 3, 5, 6)
+ batch_shape = self._batch_shape
generated_params = augmentation.forward_parameters(batch_shape)
assert isinstance(generated_params, dict)
@@ -229,7 +233,7 @@ class CommonTests(BaseTester):
assert output.shape[0] == batch_shape[0]
def _test_smoke_call_implementation(self, params):
- batch_shape = (4, 3, 5, 6)
+ batch_shape = self._batch_shape
expected_transformation_shape = torch.Size((batch_shape[0], 3, 3))
test_input = torch.ones(batch_shape, device=self.device, dtype=self.dtype)
augmentation = self._create_augmentation_from_params(**params)
@@ -266,7 +270,7 @@ class CommonTests(BaseTester):
def _test_random_p_0_implementation(self, params):
augmentation = self._create_augmentation_from_params(**params, p=0.0)
- test_input = torch.rand((2, 3, 4, 5), device=self.device, dtype=self.dtype)
+ test_input = torch.rand(self._p0_shape, device=self.device, dtype=self.dtype)
output = augmentation(test_input)
self.assert_close(output, test_input)
@@ -318,7 +322,7 @@ class CommonTests(BaseTester):
def _test_inverse_coordinate_check_implementation(self, params):
torch.manual_seed(42)
- input_tensor = torch.zeros((1, 3, 50, 100), device=self.device, dtype=self.dtype)
+ input_tensor = torch.zeros(self._inverse_shape, device=self.device, dtype=self.dtype)
input_tensor[:, :, 20:30, 40:60] = 1.0
augmentation = self._create_augmentation_from_params(**params, p=1.0)
@@ -756,6 +760,10 @@ class TestRandomRotation90(CommonTests):
"align_corners": (False, True),
}
_augmentation_cls = RandomRotation90
+ # an odd number of quarter turns of a non-square image raises (#4409), so use square images
+ _batch_shape = (4, 3, 5, 5)
+ _p0_shape = (2, 3, 5, 5)
+ _inverse_shape = (1, 3, 50, 50)
_default_param_set: dict["str", Any] = {
"times": (-3, 3),
"align_corners": True,
@@ -770,7 +778,7 @@ class TestRandomRotation90(CommonTests):
@pytest.mark.parametrize(
"input_shape,expected_output_shape",
- [((3, 4, 5), (1, 3, 4, 5)), ((2, 3, 4, 5), (2, 3, 4, 5))],
+ [((3, 5, 5), (1, 3, 5, 5)), ((2, 3, 5, 5), (2, 3, 5, 5))],
)
def test_cardinality(self, input_shape, expected_output_shape):
self._test_cardinality_implementation(
diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.py
index 7a3ef9af4..260002089 100644
--- a/tests/augmentation/test_conventions_geometric_matrix.py
+++ b/tests/augmentation/test_conventions_geometric_matrix.py
@@ -17,10 +17,13 @@
from __future__ import annotations
+import pickle
+
import pytest
import torch
import kornia.augmentation as K
+from kornia.augmentation._2d.geometric.rotation import _range_allows_odd_turns
from kornia.constants import Resample, SamplePadding
from testing.base import BaseTester
@@ -350,10 +353,111 @@ class TestConventionGeometricMatrices(BaseTester):
assert output[0, 0].argmax().item() == 2 * 7 + 1
assert output[1, 0].argmax().item() == 1 * 7 + 4
+ # A quarter turn swaps the height and the width, but the class keeps the input's `(H, W)`, so on a non-square image
+ # the turned picture did not fit: part of it was cut off and a strip of zeros appeared, with no warning (#4409).
+ # A `times` range that allows an odd number of turns now raises on a non-square input, whatever a given call
+ # would draw. A range with a fractional bound is judged by the whole numbers its draws round to.
+ # Snippet used to generate expected:
+ # x = torch.arange(48.0).reshape(1, 1, 6, 8)
+ # K.RandomRotation90((1, 1), p=1.0)(x)
+ # executed 2026-10-24 (torch 2.14.0, cpu) -> before: shape `(1, 1, 6, 8)` with columns 0 and 7 of `x` missing
+ # and an all-zero first and last column; now: `ValueError`.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("shape", [(6, 8), (8, 6), (1, 5)])
+ @pytest.mark.parametrize("times", [(1, 1), (-1, 1), (0, 2), (2, 3), (0, 3), 1, (0.5, 2.5), (1.4, 1.6)])
+ def test_convention_random_rotation90_raises_on_a_non_square_image_that_may_turn_oddly_4409(self, times, shape):
+ x = torch.zeros(1, 1, *shape)
+ with pytest.raises(ValueError, match=r"`RandomRotation` with a fixed angle of 90 degrees.*`torch\.rot90`"):
+ K.RandomRotation90(times, p=1.0)(x)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("times", [(2, 2), (0, 0), (-2, -2), 0, (0.2, 0.4), (2.2, 2.4), (-0.4, 0.4)])
+ def test_convention_random_rotation90_keeps_a_non_square_image_when_every_turn_is_even_4409(self, times):
+ x = torch.rand(2, 1, 6, 8)
+ assert K.RandomRotation90(times, p=1.0)(x).shape == x.shape
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("times", [(1, 1), (-1, 1), (0, 3), 1])
+ def test_convention_random_rotation90_keeps_working_on_a_square_image_4409(self, times):
+ x = torch.rand(2, 1, 6, 6)
+ assert K.RandomRotation90(times, p=1.0)(x).shape == x.shape
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_rotation90_square_quarter_turn_matches_rot90_4409(self):
+ x = torch.arange(36.0).reshape(1, 1, 6, 6)
+ output = K.RandomRotation90((1, 1), p=1.0)(x)
+ # The warp leaves float32 noise around 1e-5, so the integer-valued result is rounded before it is compared.
+ assert torch.equal(output.round(), torch.rot90(x, 1, (-2, -1)))
+
+ # The check runs in `validate_tensor`, so it depends on the input shape and the range only: not on `p` (a call
+ # with `p=0.5` may select no image), not on how the input is batched, not on a `params` argument and not on the
+ # container that calls the augmentation.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
+ def test_convention_random_rotation90_raise_does_not_depend_on_p_4409(self, p):
+ for _ in range(5):
+ with pytest.raises(ValueError, match="non-square"):
+ K.RandomRotation90((1, 1), p=p)(torch.zeros(4, 1, 6, 8))
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("shape", [(1, 6, 8), (6, 8)])
+ def test_convention_random_rotation90_raises_on_an_unbatched_non_square_input_4409(self, shape):
+ with pytest.raises(ValueError, match="non-square"):
+ K.RandomRotation90((1, 1), p=1.0)(torch.zeros(*shape))
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_rotation90_raises_when_params_are_passed_4409(self):
+ x = torch.zeros(1, 1, 6, 8)
+ augmentation = K.RandomRotation90((1, 1), p=1.0)
+ with pytest.raises(ValueError, match="non-square"):
+ augmentation(x, params=augmentation.forward_parameters(x.shape))
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_rotation90_raises_inside_a_container_4409(self):
+ sequential = K.AugmentationSequential(K.RandomRotation90((1, 1), p=1.0), data_keys=["input", "mask"])
+ with pytest.raises(ValueError, match="non-square"):
+ sequential(torch.zeros(1, 1, 6, 8), torch.zeros(1, 1, 6, 8))
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("times", [(1, 1), (2, 2)])
+ def test_convention_random_rotation90_unpickled_from_before_the_check_4409(self, times):
+ # A RandomRotation90 pickled before the check existed has no cached `_allows_odd_turns`; it still runs.
+ augmentation = K.RandomRotation90(times, p=1.0)
+ del augmentation._allows_odd_turns
+ restored = pickle.loads(pickle.dumps(augmentation)) # noqa: S301
+ assert restored(torch.rand(1, 1, 6, 6)).shape == (1, 1, 6, 6)
+ if times == (1, 1):
+ with pytest.raises(ValueError, match="non-square"):
+ restored(torch.zeros(1, 1, 6, 8))
+ else:
+ assert restored(torch.rand(1, 1, 6, 8)).shape == (1, 1, 6, 8)
+
+ # The bounds are rounded the way `compute_transformation` rounds a draw, so the rule is about the whole numbers
+ # a draw can become: `(0.2, 0.4)` only ever becomes 0, while `(0.5, 2.5)` can become 1.
@pytest.mark.device_agnostic
- def test_wart_random_rotation90_keeps_non_square_shape_4409(self):
- x = torch.zeros(1, 1, 5, 7)
- assert K.RandomRotation90((1, 1), p=1.0)(x).shape == x.shape
+ @pytest.mark.parametrize(
+ "low,high,expected",
+ [
+ (2, 2, False),
+ (0, 0, False),
+ (-2, -2, False),
+ (1, 1, True),
+ (-1, -1, True),
+ (-3, -3, True),
+ (0, 2, True),
+ (2, 4, True),
+ (-1, 1, True),
+ (0, 3, True),
+ (0.2, 0.4, False),
+ (2.2, 2.4, False),
+ (-0.4, 0.4, False),
+ (0.5, 2.5, True),
+ (1.4, 1.6, True),
+ (2.4, 2.6, True),
+ ],
+ )
+ def test_convention_random_rotation90_range_allows_odd_turns_4409(self, low, high, expected):
+ assert _range_allows_odd_turns(low, high) is expected
@pytest.mark.device_agnostic
def test_wart_align_corners_defaults_split_geometric_augmentations_4412(self):
@@ -388,6 +492,5 @@ class TestConventionGeometricMatrices(BaseTester):
}
perspective_output = K.RandomPerspective(0.5, p=1.0)(x, params=perspective_params)
rotation_output = K.RandomRotation((45.0, 45.0), p=1.0)(x)
- rotation90_output = K.RandomRotation90((1, 1), p=1.0)(x)
- for border in (perspective_output[..., 0, :], rotation_output[..., 0, 0], rotation90_output[..., :, 0]):
+ for border in (perspective_output[..., 0, :], rotation_output[..., 0, 0]):
self.assert_close(border, torch.zeros_like(border))
diff --git a/tests/augmentation/test_presets.py b/tests/augmentation/test_presets.py
index cb32fb50c..73bd68afa 100644
--- a/tests/augmentation/test_presets.py
+++ b/tests/augmentation/test_presets.py
@@ -19,7 +19,7 @@
import pytest
import torch
-from kornia.augmentation import RandomHorizontalFlip
+from kornia.augmentation import PatchSequential, RandomHorizontalFlip, RandomRotation90, Resize
from kornia.augmentation.presets.ada import AdaptiveDiscriminatorAugmentation
from testing.base import BaseTester
@@ -89,6 +89,42 @@ class TestAdaptiveDiscriminatorAugmentation(PresetTests):
for t, et in zip(transforms, expected_transforms):
assert et == str(t.__class__.__name__)
+ @pytest.mark.parametrize("initial_p", [1e-5, 0.0, 0.5])
+ def test_default_stack_raises_on_a_non_square_image_at_the_first_call(self, device, dtype, initial_p):
+ ada = AdaptiveDiscriminatorAugmentation(initial_p=initial_p).to(device)
+ inputs = torch.rand(8, 3, 16, 24, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="RandomRotation90"):
+ ada(inputs)
+
+ def test_default_stack_checks_the_image_entries_of_a_dict(self, device, dtype):
+ ada = AdaptiveDiscriminatorAugmentation(initial_p=1e-5).to(device)
+ square = torch.rand(4, 3, 16, 16, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="RandomRotation90"):
+ ada({"input": square, "input_wide": torch.rand(4, 3, 16, 24, device=device, dtype=dtype)})
+ # A mask is not an image: an integer mask passes through as it did before the check.
+ mask = torch.zeros(4, 1, 16, 16, device=device, dtype=torch.long)
+ assert AdaptiveDiscriminatorAugmentation(initial_p=0.0)({"mask": mask})["mask"] is mask
+ assert AdaptiveDiscriminatorAugmentation(initial_p=0.0)(mask, data_keys=["mask"]) is mask
+
+ @pytest.mark.parametrize(
+ "stack",
+ [
+ lambda: [Resize((16, 16)), RandomRotation90((0, 3), p=1.0), Resize((16, 24))],
+ lambda: [PatchSequential(RandomRotation90((0, 3), p=1.0), grid_size=(2, 3), patchwise_apply=False)],
+ ],
+ )
+ def test_custom_stack_rotation_checks_the_tensor_it_receives(self, device, dtype, stack):
+ # The rotation receives square 16x16 images or 8x8 patches of the 16x24 input, so nothing is cut off.
+ ada = AdaptiveDiscriminatorAugmentation(*stack(), initial_p=0.8).to(device)
+ inputs = torch.rand(4, 3, 16, 24, device=device, dtype=dtype)
+ assert ada(inputs).shape == inputs.shape
+
+ @pytest.mark.parametrize("rotation", [RandomRotation90((2, 2), p=1.0), RandomHorizontalFlip(p=1.0)])
+ def test_non_square_image_is_fine_when_no_rotation_may_turn_oddly(self, device, dtype, rotation):
+ ada = AdaptiveDiscriminatorAugmentation(rotation, initial_p=0.5).to(device)
+ inputs = torch.rand(4, 3, 16, 24, device=device, dtype=dtype)
+ assert ada(inputs).shape == inputs.shape
+
def test_transforms_behaviour(self, device, dtype):
ada_preset = AdaptiveDiscriminatorAugmentation().to(device)
inputs = torch.randn(2, 3, 32, 32).to(device)
diff --git a/tests/core/test_onnx_mixin.py b/tests/core/test_onnx_mixin.py
index 1a8e60e1b..71c87e9a1 100644
--- a/tests/core/test_onnx_mixin.py
+++ b/tests/core/test_onnx_mixin.py
@@ -111,6 +111,10 @@ _NOT_CALL_STATE = {
"RandomGaussianIllumination.compile": (("_fn",), "the compiled kernel"),
"_PicklableCompileMixin._record_compile": (("_compile_kwargs", "_uncompiled_fns"), "compile() records its options"),
"_PicklableCompileMixin.__setstate__": (("_uncompiled_fns",), "unpickling"),
+ "RandomRotation90.__setstate__": (
+ ("_allows_odd_turns",),
+ "unpickling an instance saved before the attribute existed",
+ ),
"AugmentationSequentialOps.data_keys": (
("_data_keys",),
"a property setter, which the container calls to set its data keys back before each call returns",