π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): raise one InputRankError for a wrong input rank from every entry point (#6448)
Aditya Malkard090315a0993
diff --git a/changelog.d/6448.fixed.md b/changelog.d/6448.fixed.mdnew file mode 100644index 000000000..f7119c791--- /dev/null+++ b/changelog.d/6448.fixed.md@@ -0,0 +1 @@+A wrong input rank raises `kornia.core.exceptions.InputRankError`, with one message format, from every augmentation entry point: the 2D and 3D classes, `validate_tensor`, `AugmentationSequential`, `ImageSequential`, `PatchSequential` and `VideoSequential`. They used to raise `ValueError`, `RuntimeError` or `AssertionError` with different messages; `InputRankError` is a `ShapeError` (`ValueError`) and also a `RuntimeError` and an `AssertionError`, so existing `except` clauses still catch it. `validate_tensor` now accepts the `(H, W)` and `(C, H, W)` inputs that `forward` accepts (and their 3D counterparts) instead of rejecting them.diff --git a/docs/source/core.rst b/docs/source/core.rstindex 8bba0e502..857d43759 100644--- a/docs/source/core.rst+++ b/docs/source/core.rst@@ -82,7 +82,10 @@ matches its failure: :exc:`TypeCheckError` is also a :exc:`TypeError`, and:exc:`ImageError` are each also a :exc:`ValueError`. :exc:`AsyncCheckError`,the host form of a check that an accelerator runs as ``torch._assert_async``, isa :exc:`ValueCheckError` and also a :exc:`RuntimeError`, the error torch raises-for that check on the device. Many functions validate+for that check on the device. :exc:`InputRankError`, raised by the augmentations+and their containers for an input with an unsupported number of dimensions, is a+:exc:`ShapeError` and also a :exc:`RuntimeError` and an :exc:`AssertionError`, the+types those entry points raised for it before. Many functions validatetheir inputs themselves and raise the built-in :exc:`ValueError` or:exc:`TypeError`, so ``except ValueError`` or ``except TypeError`` catches thoseand the matching kornia errors alike; ``except BaseError`` does not catch those@@ -96,6 +99,9 @@ it... autoexception:: ShapeError:show-inheritance:+.. autoexception:: InputRankError+ :show-inheritance:+.. autoexception:: TypeCheckError:show-inheritance:diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex 42e43d7e2..87f2da21d 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -24,6 +24,7 @@ from torch import float16, float32, float64from kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils import _transform_input, _transform_input_by_shape, _validate_input_dtype+from kornia.augmentation.utils.helpers import _IMAGE_SHAPES, _raise_input_rank_errorfrom kornia.core.ops import eye_likefrom kornia.core.utils import _to_device_nonblocking, is_autocast_enabled, is_compiling, is_exportingfrom kornia.geometry.boxes import Boxes@@ -81,8 +82,11 @@ class AugmentationBase2D(_AugmentationBase):and an ``(H, W)`` input to ``(1, 1, H, W)``; ``keepdim=True`` restores the input rank on the way outand never drops a real batch dimension. The dtype guard accepts ``float16``, ``bfloat16``, ``float32``and ``float64`` and raises ``TypeError`` on an integer tensor. The output keeps the input's device.- - a wrong input rank raises different exception types depending on the entry point that sees it- (`#4424 <https://github.com/kornia/kornia/issues/4424>`_).+ - a wrong input rank raises :class:`~kornia.core.exceptions.InputRankError` with the same message from+ every entry point, the class, :meth:`validate_tensor` and the containers. It is a ``ValueError`` and also a+ ``RuntimeError`` and an ``AssertionError``, the types those entry points raised before+ (`#4424 <https://github.com/kornia/kornia/issues/4424>`_). :meth:`validate_tensor` accepts the ranks+ ``forward`` accepts.- this base samples ``p`` per sample and uses ``p_batch`` as a call-wide gate. ``same_on_batch=True``shares applicable sampled values across the batch. Concrete constructors need not expose ``p_batch``;it can be set as an attribute on any augmentation. A sample the gate skips comes back@@ -118,10 +122,10 @@ class AugmentationBase2D(_AugmentationBase):"""def validate_tensor(self, input: torch.Tensor) -> None:- """Check if the input torch.Tensor is formatted as expected."""+ """Check that the input has a float dtype and one of the ranks ``forward`` accepts: 2, 3 or 4."""_validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, float16, float32, float64])- if len(input.shape) != 4:- raise RuntimeError(f"Expect (B, C, H, W). Got {input.shape}.")+ if len(input.shape) not in (2, 3, 4):+ _raise_input_rank_error(input.shape, _IMAGE_SHAPES)@_input_metadata_onlydef transform_tensor(diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.pyindex d7ae33690..39db17586 100644--- a/kornia/augmentation/_3d/base.py+++ b/kornia/augmentation/_3d/base.py@@ -23,6 +23,7 @@ from torch import float16, float32, float64import korniafrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils import _transform_input3d, _transform_input3d_by_shape, _validate_input_dtype+from kornia.augmentation.utils.helpers import _VOLUME_SHAPES, _raise_input_rank_errorfrom kornia.core.utils import _to_device_nonblockingfrom kornia.geometry.boxes import Boxes3Dfrom kornia.geometry.keypoints import Keypoints3D@@ -63,10 +64,10 @@ class AugmentationBase3D(_AugmentationBase):"""def validate_tensor(self, input: torch.Tensor) -> None:- """Check if the input torch.Tensor is formatted as expected."""+ """Check that the input has a float dtype and one of the ranks ``forward`` accepts: 3, 4 or 5."""_validate_input_dtype(input, accepted_dtypes=[torch.bfloat16, float16, float32, float64])- if len(input.shape) != 5:- raise RuntimeError(f"Expect (B, C, D, H, W). Got {input.shape}.")+ if len(input.shape) not in (3, 4, 5):+ _raise_input_rank_error(input.shape, _VOLUME_SHAPES)def transform_tensor(self, input: torch.Tensor, *, shape: Optional[torch.Tensor] = None, match_channel: bool = Truediff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 4f89909f3..9bf3aa296 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -28,7 +28,7 @@ from kornia.augmentation._2d.geometric.fisheye import RandomFisheyefrom kornia.augmentation._2d.geometric.thin_plate_spline import RandomThinPlateSplinefrom kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmentationBase3Dfrom kornia.augmentation.base import _AugmentationBase-from kornia.augmentation.utils.helpers import _boxes_to_padded_tensor+from kornia.augmentation.utils.helpers import _boxes_to_padded_tensor, _raise_input_rank_errorfrom kornia.constants import DataKey, Resamplefrom kornia.core.check import _check_asyncfrom kornia.core.external import PILImage as Image@@ -76,6 +76,10 @@ def _is_pil_image(arg: Any) -> bool:return pil_module is not None and isinstance(arg, pil_module.Image)+# The inputs AugmentationSequential accepts next to a 3D child; a 4D tensor is ambiguous there.+_VOLUME_BATCH_SHAPES = "either (D, H, W) or (B, C, D, H, W)"++class AugmentationSequential(TransformMatrixMinIn, ImageSequential):r"""AugmentationSequential for handling multiple input types like inputs, masks, keypoints at once.@@ -149,8 +153,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):returned as ``(B, T, 1, H, W)``, and a single ``(1, T, H, W)`` mask is repeated too. Any other mask ranknext to a video, or a 5D mask next to a non-video image, raises ``ValueError`` instead of guessing. Areplay with no image (``params=`` given, no ``INPUT`` key) reads the batch to repeat to from the recorded- params instead. A wrong input rank raises ``RuntimeError`` here rather than the ``ValueError`` of a bare- augmentation (`#4424 <https://github.com/kornia/kornia/issues/4424>`_).+ params instead. A wrong input rank raises :class:`~kornia.core.exceptions.InputRankError` with the message+ a bare augmentation gives; next to a video or 3D child it lists the shapes the container runs, the+ video's 5D layout or ``(D, H, W)`` and ``(B, C, D, H, W)``+ (`#4424 <https://github.com/kornia/kornia/issues/4424>`_).- boxes use the inclusive ``xyxy_plus`` convention of :class:`~kornia.geometry.boxes.Boxes`. Flips map``x' = W - 1 - x`` and ``y' = H - 1 - y`` for every key, as :func:`~kornia.geometry.transform.hflip`does. Labels pass through geometric steps untouched.@@ -756,6 +762,15 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):return out+ def _video_or_volume_shapes(self) -> str:+ """Describe the input shapes this container accepts next to a video or 3D child, for a rejected rank."""+ # A list, not next(generator, None), as in _preproc_mask. Read from the children at error time, so that a+ # module unpickled from an older kornia, which lacks any newer attribute, still runs.+ videos = [c for c in self.children() if isinstance(c, VideoSequential)]+ if videos:+ return "(" + ", ".join(videos[0].data_format) + ")"+ return _VOLUME_BATCH_SHAPES+def forward(self,*args: Union[DataType, Dict[str, DataType]],@@ -803,10 +818,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):if not isinstance(inp, torch.Tensor):raise ValueError(f"`INPUT` should be a torch.Tensor but `{type(inp)}` received.")if self.contains_3d_augmentation and len(inp.shape) == 4:- raise RuntimeError(- f"3D augmentations in AugmentationSequential expect input shape "- f"(D, H, W) or (B, C, D, H, W), but got {inp.shape}."- )+ # A 4D tensor is ambiguous next to 3D augmentations: (C, D, H, W) or a 2D batch.+ _raise_input_rank_error(inp.shape, _VOLUME_BATCH_SHAPES)if params is None:# image data must exist if params is not provided.@@ -814,6 +827,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):inp = in_args[0]# A video input shall be BCDHW while an image input shall be BCHWif self.contains_video_sequential or self.contains_3d_augmentation:+ if len(inp.shape) not in (3, 4, 5):+ _raise_input_rank_error(inp.shape, self._video_or_volume_shapes())_, out_shape = self.autofill_dim(inp, dim_range=(3, 5))else:_, out_shape = self.autofill_dim(inp, dim_range=(2, 4))diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.pyindex 15c9041c0..56fdac526 100644--- a/kornia/augmentation/container/base.py+++ b/kornia/augmentation/container/base.py@@ -24,6 +24,7 @@ from torch import nnimport kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBase+from kornia.augmentation.utils.helpers import _IMAGE_SHAPES, _VOLUME_SHAPES, _raise_input_rank_errorfrom kornia.core.utils import is_exportingfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints@@ -211,11 +212,15 @@ class SequentialBase(BasicSequentialBase):def autofill_dim(self, input: torch.Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:"""Fill torch.Tensor dim to the upper bound of dim_range.- If input torch.Tensor dim is smaller than the lower bound of dim_range, an error will be thrown out.+ A rank outside ``dim_range`` raises :class:`~kornia.core.exceptions.InputRankError` with the message an+ augmentation itself gives for that input (#4424)."""ori_shape = input.shapeif len(ori_shape) < dim_range[0] or len(ori_shape) > dim_range[1]:- raise RuntimeError(f"input shape expected to be in {dim_range} while got {ori_shape}.")+ accepted = {(2, 4): _IMAGE_SHAPES, (3, 5): _VOLUME_SHAPES}.get(+ tuple(dim_range), f"{dim_range[0]} to {dim_range[1]} dimensions"+ )+ _raise_input_rank_error(ori_shape, accepted)while len(input.shape) < dim_range[1]:input = input[None]return ori_shape, input.shapediff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.pyindex f82eb412b..116499b07 100644--- a/kornia/augmentation/container/patch.py+++ b/kornia/augmentation/container/patch.py@@ -25,6 +25,7 @@ from torch import nnimport kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBase+from kornia.augmentation.utils.helpers import _raise_input_rank_errorfrom kornia.contrib.extract_patches import extract_tensor_patchesfrom kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.ops import _device_literal@@ -256,7 +257,7 @@ class PatchSequential(ImageSequential):grid_size = self.grid_sizeself._validate_grid_size(grid_size)if len(batch_shape) != 4:- raise ValueError(f"Expected image shape (B, C, H, W). Got {batch_shape}.")+ _raise_input_rank_error(batch_shape, "(B, C, H, W)")height, width = batch_shape[-2:]if height <= 0 or width <= 0:raise ValueError("PatchSequential requires non-empty spatial dimensions.")@@ -316,7 +317,7 @@ class PatchSequential(ImageSequential):grid_size = self.grid_sizeself._validate_grid_size(grid_size)if input.ndim != 4:- raise ValueError(f"Expected image shape (B, C, H, W). Got {input.shape}.")+ _raise_input_rank_error(input.shape, "(B, C, H, W)")height, width = input.shape[-2:]if pad is not None:height, width = height + pad[2] + pad[3], width + pad[0] + pad[1]@@ -400,7 +401,9 @@ class PatchSequential(ImageSequential):(width + left + right) // self.grid_size[1],))- if len(batch_shape) != 5 or batch_shape[1] != self.grid_size[0] * self.grid_size[1]:+ if len(batch_shape) != 5:+ _raise_input_rank_error(batch_shape, "either (B, C, H, W) or (B, rows * columns, C, h, w)")+ if batch_shape[1] != self.grid_size[0] * self.grid_size[1]:raise ValueError(f"Expected image shape (B, C, H, W) or patch shape (B, rows * columns, C, h, w). Got {batch_shape}.")diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex 8df390ea5..86a299c72 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -24,7 +24,13 @@ import kornia.augmentation as Kfrom kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.container.base import SequentialBasefrom kornia.augmentation.container.image import ImageSequential, _get_new_batch_shape-from kornia.augmentation.utils.helpers import _frame_boxes, _frame_keypoints, _video_boxes, _video_keypoints+from kornia.augmentation.utils.helpers import (+ _frame_boxes,+ _frame_keypoints,+ _raise_input_rank_error,+ _video_boxes,+ _video_keypoints,+)from kornia.geometry.boxes import Boxes, VideoBoxesfrom kornia.geometry.keypoints import Keypoints, VideoKeypoints@@ -572,7 +578,7 @@ class VideoSequential(ImageSequential):) -> torch.Tensor:"""Define the video computation performed."""if len(input.shape) != 5:- raise AssertionError(f"Input must be a 5-dim torch.Tensor. Got {input.shape}.")+ _raise_input_rank_error(input.shape, "(" + ", ".join(self.data_format) + ")")if params is None:self._params = self.forward_parameters(input.shape)diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 6723337c4..49a8a7ec2 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -16,13 +16,14 @@#from functools import wraps-from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union+from typing import Any, Callable, Dict, List, NoReturn, Optional, Sequence, Tuple, Unionimport torchimport torch.nn.functional as Ffrom torch.distributions import Beta, Uniform# Both moved to kornia.core.ops; re-exported so that existing imports from this module keep working.+from kornia.core.exceptions import InputRankErrorfrom kornia.core.ops import _constant_tensor, _flatten_constant # noqa: F401from kornia.core.utils import _extract_device_dtypefrom kornia.geometry.boxes import Boxes, VideoBoxes@@ -260,6 +261,22 @@ def _transform_input3d_by_shape(return input+# The input shapes an augmentation accepts, as listed in the error for any other rank (#4424).+_IMAGE_SHAPES = "either (H, W), (C, H, W) or (*, C, H, W)"+_VOLUME_SHAPES = "either (D, H, W), (C, D, H, W) or (*, C, D, H, W)"+++def _raise_input_rank_error(shape: torch.Size, accepted: str) -> NoReturn:+ """Raise the :class:`~kornia.core.exceptions.InputRankError` every augmentation entry point uses for a bad rank.++ Args:+ shape: the shape of the rejected input.+ accepted: the accepted shapes, such as ``_IMAGE_SHAPES``, completing "must have a shape of ...".++ """+ raise InputRankError(f"Input size must have a shape of {accepted}. Got {shape}", actual_shape=tuple(shape))++def _transform_input(input: torch.Tensor) -> torch.Tensor:r"""Unsqueeze an ``(H, W)`` or ``(C, H, W)`` image tensor to 4 dims, ``(B, C, H, W)``; a 4-dim input is kept.@@ -274,7 +291,7 @@ def _transform_input(input: torch.Tensor) -> torch.Tensor:raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")if len(input.shape) not in [2, 3, 4]:- raise ValueError(f"Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W). Got {input.shape}")+ _raise_input_rank_error(input.shape, _IMAGE_SHAPES)if len(input.shape) == 2:input = input.unsqueeze(0)@@ -299,9 +316,7 @@ def _transform_input3d(input: torch.Tensor) -> torch.Tensor:raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")if len(input.shape) not in [3, 4, 5]:- raise ValueError(- f"Input size must have a shape of either (D, H, W), (C, D, H, W) or (*, C, D, H, W). Got {input.shape}"- )+ _raise_input_rank_error(input.shape, _VOLUME_SHAPES)if len(input.shape) == 3:input = input.unsqueeze(0)diff --git a/kornia/core/exceptions.py b/kornia/core/exceptions.pyindex d0ea6221e..6577fac95 100644--- a/kornia/core/exceptions.py+++ b/kornia/core/exceptions.py@@ -28,6 +28,7 @@ __all__ = ["BaseError","DeviceError","ImageError",+ "InputRankError","ShapeError","TypeCheckError","ValueCheckError",@@ -39,7 +40,8 @@ class BaseError(Exception):A failed ``KORNIA_CHECK`` raises it directly; it is neither a :exc:`ValueError` nor a :exc:`TypeError`. Eachsubclass also derives from the one of those two built-ins that matches its failure, so the matching ``except``- clause catches the subclass as well. :exc:`AsyncCheckError` is also a :exc:`RuntimeError`.+ clause catches the subclass as well. :exc:`AsyncCheckError` is also a :exc:`RuntimeError`, and :exc:`InputRankError`+ also a :exc:`RuntimeError` and an :exc:`AssertionError`."""@@ -63,6 +65,16 @@ class ShapeError(BaseError, ValueError):self.expected_shape = expected_shape+class InputRankError(ShapeError, RuntimeError, AssertionError):+ """Raised when an input has a number of dimensions the operation does not accept. Also a :exc:`ValueError`.++ The augmentation classes and their containers raise it for one user error: an image or a volume with too few or+ too many dimensions. They used to raise :exc:`ValueError`, :exc:`RuntimeError` or :exc:`AssertionError` for it,+ depending on the entry point (`#4424 <https://github.com/kornia/kornia/issues/4424>`_), so this class also+ derives from :exc:`RuntimeError` and :exc:`AssertionError`, and each of those ``except`` clauses still catches it.+ """++class TypeCheckError(BaseError, TypeError):"""Raised when type validation fails. Also a :exc:`TypeError`.diff --git a/tests/api_surface.json b/tests/api_surface.jsonindex f3913efbf..e6f7beb2c 100644--- a/tests/api_surface.json+++ b/tests/api_surface.json@@ -288,6 +288,7 @@"BaseError","DeviceError","ImageError",+ "InputRankError","ShapeError","TypeCheckError","ValueCheckError"diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex d1ae37ac6..95277ea40 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -657,7 +657,7 @@ class TestAugmentationSequential:with pytest.raises(RuntimeError,- match=r"3D augmentations in AugmentationSequential expect input shape",+ match=r"Input size must have a shape of either \(D, H, W\) or \(B, C, D, H, W\)",):aug_list(input)@@ -672,7 +672,7 @@ class TestAugmentationSequential:with pytest.raises(RuntimeError,- match=r"3D augmentations in AugmentationSequential expect input shape",+ match=r"Input size must have a shape of either \(D, H, W\) or \(B, C, D, H, W\)",):aug_list(input_4d, params=params)diff --git a/tests/augmentation/container/test_patch_sequential.py b/tests/augmentation/container/test_patch_sequential.pyindex 204a6b6d1..da4b1c554 100644--- a/tests/augmentation/container/test_patch_sequential.py+++ b/tests/augmentation/container/test_patch_sequential.py@@ -23,6 +23,7 @@ from torch import nnimport kornia.augmentation as Kfrom kornia.color import RgbToBgr+from kornia.core.exceptions import InputRankErrorfrom testing.augmentation.utils import reproducibility_testfrom testing.base import BaseTester@@ -481,15 +482,20 @@ class TestPatchSequentialRegression(BaseTester):def test_three_dimensional_input_raises_value_error(self, method, device, dtype):seq = K.PatchSequential(nn.Identity(), grid_size=(2, 2), patchwise_apply=False)kwargs = {"padding": "same"} if method == "compute_padding" else {}- with pytest.raises(ValueError, match="Expected image shape"):+ with pytest.raises(ValueError, match=r"Input size must have a shape of \(B, C, H, W\)"):getattr(seq, method)(torch.ones(3, 4, 4, device=device, dtype=dtype), **kwargs)- @pytest.mark.parametrize("shape", [(2, 3, 4), (2, 5, 3, 2, 2), (2, 6, 3, 2, 2, 1)])- def test_parameters_reject_invalid_shape(self, shape):+ @pytest.mark.parametrize("shape", [(2, 3, 4), (2, 6, 3, 2, 2, 1)])+ def test_parameters_reject_invalid_rank(self, shape):seq = K.PatchSequential(nn.Identity(), grid_size=(2, 3), patchwise_apply=False)- with pytest.raises(ValueError, match=r"Expected.*shape"):+ with pytest.raises(InputRankError, match=r"must have a shape of either \(B, C, H, W\) or \(B, rows \* columns"):seq.forward_parameters(torch.Size(shape))+ def test_parameters_reject_invalid_patch_count(self):+ seq = K.PatchSequential(nn.Identity(), grid_size=(2, 3), patchwise_apply=False)+ with pytest.raises(ValueError, match=r"Expected.*shape"):+ seq.forward_parameters(torch.Size((2, 5, 3, 2, 2)))+@pytest.mark.parametrize("shape", [(2, 3, 1, 2), (2, 3, 0, 4)])def test_image_shape_parameters_reject_empty_valid_patches(self, shape):seq = K.PatchSequential(nn.Identity(), grid_size=(2, 3), padding="valid", patchwise_apply=False)diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex 626748554..dfff95f44 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -37,6 +37,7 @@ from kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3Dfrom kornia.augmentation.base import _BasicAugmentationBasefrom kornia.core import ImageModulefrom kornia.core._compat import torch_version_lt+from kornia.core.exceptions import InputRankError, ShapeErrorfrom kornia.filters.dissolving import StableDiffusionDissolving, _DissolvingWraper_HFfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints@@ -577,22 +578,64 @@ class TestConventionAugmentationBase2D(BaseTester):with pytest.raises(TypeError, match=expected):K.RandomHorizontalFlip(p=1.0)(torch.zeros(1, 1, 4, 4, device=device, dtype=bad))- def test_wart_wrong_input_rank_has_entry_point_specific_errors_4424(self, device, dtype):- # Wart pin (#4424): one user error can raise different exception types depending on which entry point- # sees it. The class path raises `ValueError` from `transform_tensor`, the container path raises- # `RuntimeError` with a different message, and `validate_tensor`'s own- # `RuntimeError` (which also rejects the legal (C, H, W) rank). `forward` promotes legal unbatched- # inputs before validation.+ def test_convention_wrong_input_rank_raises_one_error_from_every_entry_point_4424(self, device, dtype):+ # Convention pin (#4424): one user error, one exception and one message, whichever entry point sees it.+ # The class, `validate_tensor` and the containers used to raise `ValueError`, `RuntimeError` or+ # `AssertionError` with four different messages; `InputRankError` is all three types, so a caller's+ # existing `except` clause still catches it.x5 = torch.rand(1, 2, 3, 6, 8, device=device, dtype=dtype)- with pytest.raises(ValueError, match="Input size must have a shape of either"):- K.RandomHorizontalFlip(p=1.0)(x5)- with pytest.raises(RuntimeError, match=r"input shape expected to be in \(2, 4\)"):- K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input"])(x5)- with pytest.raises(RuntimeError, match=r"Expect \(B, C, H, W\)"):- K.RandomHorizontalFlip(p=1.0).validate_tensor(x5)- with pytest.raises(RuntimeError, match=r"Expect \(B, C, H, W\)"):- # a rank `forward` accepts, rejected by the validator behind it- K.RandomHorizontalFlip(p=1.0).validate_tensor(torch.rand(3, 6, 8, device=device, dtype=dtype))+ message = r"Input size must have a shape of either \(H, W\), \(C, H, W\) or \(\*, C, H, W\)\. Got"+ entry_points = {+ "class": lambda: K.RandomHorizontalFlip(p=1.0)(x5),+ "validate_tensor": lambda: K.RandomHorizontalFlip(p=1.0).validate_tensor(x5),+ "AugmentationSequential": lambda: K.AugmentationSequential(+ K.RandomHorizontalFlip(p=1.0), data_keys=["input"]+ )(x5),+ "ImageSequential": lambda: K.ImageSequential(K.RandomHorizontalFlip(p=1.0))(x5),+ }+ for name, call in entry_points.items():+ with pytest.raises(InputRankError, match=message) as info:+ call()+ for legacy_type in (ValueError, RuntimeError, AssertionError, ShapeError):+ assert isinstance(info.value, legacy_type), (name, legacy_type)+ assert info.value.actual_shape == tuple(x5.shape), name++ def test_convention_validate_tensor_accepts_the_ranks_forward_accepts_4424(self, device, dtype):+ # `forward` promotes (H, W) and (C, H, W); `validate_tensor` used to reject both (#4424).+ aug = K.RandomHorizontalFlip(p=1.0)+ for shape in ((6, 8), (3, 6, 8), (2, 3, 6, 8)):+ x = torch.rand(*shape, device=device, dtype=dtype)+ aug.validate_tensor(x)+ assert aug(x).shape[-2:] == (6, 8)+ with pytest.raises(InputRankError):+ aug.validate_tensor(torch.rand(8, device=device, dtype=dtype))++ def test_convention_wrong_input_rank_in_patch_video_and_3d_entry_points_4424(self, device, dtype):+ flips = [K.RandomHorizontalFlip(p=1.0) for _ in range(4)]+ with pytest.raises(InputRankError, match=r"must have a shape of \(B, C, H, W\)\. Got"):+ K.PatchSequential(*flips, grid_size=(2, 2))(torch.rand(1, 2, 3, 8, 8, device=device, dtype=dtype))+ with pytest.raises(InputRankError, match=r"must have a shape of \(B, T, C, H, W\)\. Got") as info:+ K.VideoSequential(K.RandomHorizontalFlip(p=1.0))(torch.rand(2, 3, 6, 8, device=device, dtype=dtype))+ assert isinstance(info.value, AssertionError)+ volume_message = r"must have a shape of either \(D, H, W\), \(C, D, H, W\) or \(\*, C, D, H, W\)\. Got"+ x6 = torch.rand(1, 1, 2, 3, 4, 5, device=device, dtype=dtype)+ with pytest.raises(InputRankError, match=volume_message):+ RandomHorizontalFlip3D(p=1.0)(x6)+ with pytest.raises(InputRankError, match=volume_message):+ RandomHorizontalFlip3D(p=1.0).validate_tensor(x6)+ RandomHorizontalFlip3D(p=1.0).validate_tensor(torch.rand(3, 4, 5, device=device, dtype=dtype))++ def test_convention_wrong_input_rank_in_augmentation_sequential_video_and_3d_4424(self, device, dtype):+ # Only the 5D layout is listed: a rank-3 or rank-4 video does not run through the container.+ video = K.AugmentationSequential(K.VideoSequential(K.RandomHorizontalFlip(p=1.0), data_format="BCTHW"))+ with pytest.raises(InputRankError, match=r"must have a shape of \(B, C, T, H, W\)\. Got"):+ video(torch.rand(1, 1, 2, 3, 6, 8, device=device, dtype=dtype))+ # Rank 4 is ambiguous next to a 3D child, so no message lists (C, D, H, W).+ volume = K.AugmentationSequential(RandomHorizontalFlip3D(p=1.0), data_keys=["input"])+ for shape in ((2, 3, 5, 6), (5, 6), (1, 2, 1, 3, 5, 6)):+ with pytest.raises(InputRankError, match=r"either \(D, H, W\) or \(B, C, D, H, W\)\. Got") as info:+ volume(torch.rand(*shape, device=device, dtype=dtype))+ assert isinstance(info.value, RuntimeError)def test_convention_numeric_ranges_return_cpu_parameters_independently_of_input(self, device, dtype):# With numeric ranges and unchanged CPU defaults, returned parameter placement is independent ofdiff --git a/tests/augmentation/test_conventions_transplantation.py b/tests/augmentation/test_conventions_transplantation.pyindex 3b6a1cb71..635695cb7 100644--- a/tests/augmentation/test_conventions_transplantation.py+++ b/tests/augmentation/test_conventions_transplantation.py@@ -450,13 +450,13 @@ class TestTransplantationConventions(BaseTester):image, mask = _labelled_batch(batch=3, spatial=(4, 6))volume, volume_mask = _labelled_batch(batch=3, spatial=(3, 4, 6))# The 2D class on a volume raises.- with pytest.raises(RuntimeError, match="input shape expected to be in"):+ with pytest.raises(RuntimeError, match="Input size must have a shape of either"):K.AugmentationSequential(K.RandomTransplantation(p=1.0), data_keys=["image", "mask"])(volume, volume_mask)# The 3D class on a 2D batch is rejected because the 4D shape is ambiguous.inner = K.RandomTransplantation3D(p=1.0)with pytest.raises(RuntimeError,- match=r"3D augmentations in AugmentationSequential expect input shape",+ match=r"Input size must have a shape of either \(D, H, W\) or \(B, C, D, H, W\)",):K.AugmentationSequential(inner, data_keys=["image", "mask"])(image, mask)