Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(augmentation): Convention blocks (batch 6d: mix, 3D, auto) (#4634)

Dmytro Mishkin5390ec29d652
diff --git a/changelog.d/4634.added.md b/changelog.d/4634.added.md
new file mode 100644
index 000000000..c40d0a9cf
--- /dev/null
+++ b/changelog.d/4634.added.md
@@ -0,0 +1 @@
+Document the conventions of mix and 3D augmentations and automatic augmentation policies, with executable tests for their sampling, coordinate, label, and output contracts.
diff --git a/docs/source/augmentation.auto.rst b/docs/source/augmentation.auto.rst
index be4538137..da6ec6055 100644
--- a/docs/source/augmentation.auto.rst
+++ b/docs/source/augmentation.auto.rst
@@ -41,6 +41,16 @@ This module contains common data augmentation policies that can improve the accu
.. automethod:: inverse
+.. autoclass:: PolicyAugmentBase
+
+.. autoclass:: PolicySequential
+
+.. autoclass:: kornia.augmentation.auto.operations.OperationBase
+
+ .. automethod:: forward_parameters
+
+ .. automethod:: forward
+
Augmentation Search Methods
---------------------------
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index 9470a1c8c..effff29af 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -242,7 +242,9 @@ Several constructors accept ``nn.Parameter`` ranges and can propagate gradients
are not necessarily connected to cached samplers after ``load_state_dict``; reconstruct those configurations
to change their sampling ranges (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).
-The ``kornia.augmentation.auto`` policies cannot be pickled (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).
+A ``kornia.augmentation.auto`` policy can be pickled only when every operation wrapper in it can, so the
+default policies cannot (`#4469 <https://github.com/kornia/kornia/issues/4469>`_); an empty
+``AutoAugment(policy=[[]])`` and a policy holding only ``posterize`` entries can.
The built-in 2D intensity augmentations, flips, ``Resize`` (including ``LongestMaxSize`` and
``SmallestMaxSize``), and slice-mode ``RandomResizedCrop`` compute their transformation matrix
diff --git a/docs/source/augmentation.transforms3d.rst b/docs/source/augmentation.transforms3d.rst
index 6a77e0a82..43fbe24cb 100644
--- a/docs/source/augmentation.transforms3d.rst
+++ b/docs/source/augmentation.transforms3d.rst
@@ -13,6 +13,7 @@ Geometric
.. autoclass:: RandomCrop3D
.. autoclass:: RandomDepthicalFlip3D
.. autoclass:: RandomHorizontalFlip3D
+.. autoclass:: RandomPerspective3D
.. autoclass:: RandomRotation3D
.. autoclass:: RandomVerticalFlip3D
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 6a92e38e0..31db33e99 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -203,7 +203,9 @@ covers a slightly different extent of the source image.
:func:`kornia.geometry.transform.warp_perspective3d` normalize with the corner-aligned
convention whatever flag they pass to ``grid_sample``, and have the same mismatch at
``align_corners=False``: an identity ``warp_perspective3d`` changes a 4x4x4 ``arange``
- volume by up to ``55.1`` there, against exactly ``0`` at ``align_corners=True``. Pass
+ volume by up to ``55.1`` there, against roundoff at ``align_corners=True``: exactly
+ ``0`` in ``float32`` on torch 2.14 and about ``2e-6`` on torch 2.5.1. The grid is built
+ in ``float32``, so a ``float64`` volume is reproduced only to about ``1e-6`` even there. Pass
``align_corners=True`` to the 3-D warps until this is fixed. Tracked in
`#4503 <https://github.com/kornia/kornia/issues/4503>`_.
@@ -434,10 +436,27 @@ Serializing an augmentation
does not update the cached sampling distributions; ``repr`` may or may not
reflect the loaded range. Reconstruct the augmentation to change what it
samples (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).
+- With numeric constructor ranges, the 3D geometric and intensity
+ augmentations and every mix class -- ``RandomCutMixV2``, ``RandomJigsaw``,
+ ``RandomMixUpV2``, ``RandomMosaic``, ``PatchMix``, ``RandomTransplantation``
+ and ``RandomTransplantation3D`` -- have empty ``state_dict()`` objects.
+ Pickle and deepcopy preserve their configuration and recorded parameters
+ after a forward call; passing the restored
+ ``_params`` replays that transform on the same input. An empty
+ ``state_dict()`` cannot save those parameters or reconstruct the constructor
+ configuration. Tensor or ``nn.Parameter`` arguments can have different
+ registration behavior.
- Pickle and deepcopy can retain recorded parameters and transform state,
- but support is configuration-dependent. The ``kornia.augmentation.auto``
- policies cannot currently be pickled
- (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).
+ but support is configuration-dependent. A ``kornia.augmentation.auto``
+ policy can be pickled only when every operation wrapper in it can, so the
+ default policies currently cannot
+ (`#4469 <https://github.com/kornia/kornia/issues/4469>`_). An empty
+ ``AutoAugment(policy=[[]])`` has no wrappers and can be pickled, and so can
+ a policy holding only ``posterize`` entries. ``copy.deepcopy`` raises
+ ``RuntimeError`` once a policy has rebuilt its probability samplers with
+ gradients enabled: after a ``RandAugment`` forward pass, or after
+ ``.train()`` / ``.eval()`` on any of the three policies, even one that was
+ never called (`#4656 <https://github.com/kornia/kornia/issues/4656>`_).
A normal forward draws fresh parameters; replay requires passing the
saved parameters and controlling any application-time randomness.
- Built-in lazy matrices keep only the input's shape, dtype and device
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index a16a17349..acaedc603 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -38,7 +38,8 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
"apply_transform" will need to handle the probabilities internally.
Args:
- p: probability for applying an augmentation. This param controls if to apply the augmentation for the batch.
+ p: probability for applying an augmentation. This param controls the augmentation probabilities
+ element-wise for a batch.
p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wise.
same_on_batch: apply the same transformation across the batch.
@@ -47,6 +48,34 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
data_keys: the input type sequential for applying augmentations.
Accepts "input", "image", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints", "class", "label".
+ Convention:
+ - Sampling, replay, and serialization follow the augmentation-wide randomness and serialization contracts
+ in :doc:`/get-started/conventions`.
+ - Image inputs are floating tensors of shape ``(H, W)``, ``(C, H, W)``, or ``(B, C, H, W)``. They are
+ promoted to ``(B, C, H, W)`` before a mix operation; ``keepdim=True`` restores the rank of an unbatched
+ input. The base accepts ``float16``, ``bfloat16``, ``float32``, and ``float64`` only.
+ :class:`~kornia.augmentation.RandomTransplantation` and
+ :class:`~kornia.augmentation.RandomTransplantation3D` are the exception: they override ``forward``
+ and take a batched ``(B, C, *spatial)`` image with a ``(B, *spatial)`` mask, 2D or 3D alike, so they
+ neither promote an unbatched input nor restore a rank through ``keepdim``. The 3D class also derives
+ from :class:`~kornia.augmentation.AugmentationBase3D`.
+ - A mix operation is not geometric: it has neither a transformation matrix nor an inverse. Its
+ ``transform_matrix`` property raises ``RuntimeError``. ``inverse()`` takes keyword arguments only and
+ raises ``RuntimeError`` as well, so a positional ``inverse(output)`` fails earlier with ``TypeError``.
+ - ``data_keys`` chooses which positional inputs are dispatched. It does not promise that every concrete
+ mix augmentation implements every key: an unsupported mask, box, keypoint, or class key raises
+ ``NotImplementedError`` (or a class-specific error) before anything is sampled, whether or not the gate
+ would select a sample; the two transplantation classes raise it only after their parameters are drawn.
+ The concrete class blocks state the supported non-image keys.
+ - ``batch_prob`` is sampled with the subclass parameters and gates the final image result. A selected
+ image uses the mixed result and an unselected image keeps its input values, except where a concrete
+ class changes the output size (see :class:`~kornia.augmentation.RandomMosaic`). The box
+ handlers use the same gate, and when no sample is selected every transform is skipped. The class
+ handlers of :class:`~kornia.augmentation.RandomMixUpV2` and :class:`~kornia.augmentation.RandomCutMixV2`
+ do not read ``batch_prob``: their sampled gate is batch-wide, so labels and images agree, but a replayed
+ ``params`` whose ``batch_prob`` selects only some rows leaves the unselected images unchanged while
+ still labelling those rows as mixed.
+
"""
def _validate_data_key(self, key: DataKey) -> None:
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index cdbe8c479..0688aec75 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -14,6 +14,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
+
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union
@@ -34,15 +35,15 @@ class RandomCutMixV2(MixAugmentationBaseV2):
Localizable Features` :cite:`yun2019cutmix`.
The function returns (inputs, labels), in which the inputs is the torch.Tensor that contains the mixup images
- while the labels is a :math:`(\text{num_mixes}, B, 3)` torch.Tensor that contains (label_permuted_batch, lambda)
- for each cutmix.
+ while the labels is a :math:`(\text{num_mixes}, B, 3)` torch.Tensor that contains
+ (label_batch, label_permuted_batch, lambda) for each cutmix.
The implementation referred to the following repository: `https://github.com/clovaai/CutMix-PyTorch
<https://github.com/clovaai/CutMix-PyTorch>`_.
+ See the Convention block on :class:`~kornia.augmentation.MixAugmentationBaseV2`.
+
Args:
- height: the width of the input image.
- width: the width of the input image.
p: probability for applying an augmentation to a batch. This param controls the augmentation
probabilities batch-wisely.
num_mix: cut mix times.
@@ -67,7 +68,25 @@ class RandomCutMixV2(MixAugmentationBaseV2):
Returns:
Tuple[torch.Tensor, torch.Tensor]:
- Adjusted image, shape of :math:`(B, C, H, W)`.
- - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, num_mix, 3)`.
+ - Raw labels, permuted labels and lambdas for each mix, shape of :math:`(num_mix, B, 3)`.
+
+ Convention:
+ - With ``data_keys=["input", "class"]``, the class output is ``(num_mix, B, 3)``. Its last axis holds
+ the original label, the label selected by that mix's permutation, and the area fraction returned as
+ lambda. Labels must be one-dimensional and are returned as floating values in the image dtype, except that
+ a ``float16`` or ``bfloat16`` image yields ``float32`` labels so integer class ids up to
+ ``2 ** 24`` stay exact.
+ ``use_correct_lambda=True`` returns ``1 - cut_area / image_area``;
+ the compatibility default returns ``cut_area / image_area`` and emits a deprecation warning.
+ - ``p`` is a batch-wide gate, and the generator applies it a second time per row and mix: inside a selected
+ batch each cut is kept with probability ``p`` and zeroed otherwise. Each cut passes both gates with
+ probability ``p ** 2``; it can still leave the image unchanged through self-pairing or a zero-sized cut.
+ With ``same_on_batch=True`` the inner gate is shared across rows and mixes
+ (`#4649 <https://github.com/kornia/kornia/issues/4649>`_).
+ At ``p=0`` the image is unchanged and each class row contains the original
+ label twice with lambda zero. The current ``cut_size`` interpretation and its rejection of a minimum of
+ ``1`` are described in its argument above; this is the repaired behavior from
+ `#4439 <https://github.com/kornia/kornia/issues/4439>`_.
Note:
This implementation would randomly cutmix images in a batch. Ideally, the larger batch size would be preferred.
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index 29e3d9c17..d5504735e 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -34,19 +34,36 @@ class RandomJigsaw(MixAugmentationBaseV2):
Make Jigsaw puzzles for each image individually. To mix with different images in a
batch, referring to :class:`kornia.augmentation.RandomMosaic`.
+ See the Convention block on :class:`~kornia.augmentation.MixAugmentationBaseV2`.
+
Args:
grid: the Jigsaw puzzle grid. e.g. (2, 2) means
each output will mix image patches in a 2x2 grid.
- ensure_perm: to ensure the nonidentical patch permutation generation against
- the original one.
- data_keys: the input type sequential for applying augmentations.
- Accepts "input", "image", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints",
- "class", "label".
+ ensure_perm: reject the index-identity permutation ``[0, ..., N - 1]`` when drawing. That is the
+ image-preserving permutation only for a single-row or single-column grid; for any other grid the
+ output can still equal the input (`#4703 <https://github.com/kornia/kornia/issues/4703>`_).
+ data_keys: the input type sequential for applying augmentations. Only "input" and "image" are
+ implemented; see the Convention block.
p: probability of applying the transformation to each sample.
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
+ Convention:
+ - ``grid=(rows, columns)`` partitions each image independently. Both image dimensions must be exactly
+ divisible by their corresponding grid entries; any other input raises ``RuntimeError``, whether or not
+ the gate selects a sample. The output preserves the input shape. An entry's position selects the
+ destination cell in column-major order -- for a ``2 x 2`` grid, entries ``[0, 2]`` become the top row
+ and entries ``[1, 3]`` the bottom row -- while the entry's value indexes the source patch in row-major
+ order. The two orders differ unless the grid has a single row or column; where they differ, the
+ identity permutation does not reproduce the image -- on a square grid it transposes the patch grid. The
+ image-preserving permutation is ``arange(N).view(rows, columns).T.flatten()``: ``[0, 2, 1, 3]`` for a
+ ``2 x 2`` grid.
+ - ``p`` is a per-sample gate. With ``same_on_batch=True`` the batch shares one gate draw and one patch
+ permutation; with it false, each sample receives an independent gate and permutation. This class
+ implements image mixing only; requesting another data key raises ``NotImplementedError`` whatever the
+ gate, as described on the base.
+
Examples:
>>> jigsaw = RandomJigsaw((4, 4))
>>> input = torch.randn(8, 3, 256, 256)
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index e4dc61d4c..5a1dca463 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -39,6 +39,8 @@ class RandomMixUpV2(MixAugmentationBaseV2):
`https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py
<https://github.com/hongyi-zhang/mixup/blob/master/cifar/utils.py>`_.
+ See the Convention block on :class:`~kornia.augmentation.MixAugmentationBaseV2`.
+
The loss and accuracy are computed as:
.. code-block:: python
@@ -73,6 +75,21 @@ class RandomMixUpV2(MixAugmentationBaseV2):
- Adjusted image, shape of :math:`(B, C, H, W)`.
- Raw labels, permuted labels and lambdas for each mix, shape of :math:`(B, 3)`.
+ Convention:
+ - With ``data_keys=["input", "class"]``, the class output is ``(B, 3)``: its columns are the original
+ label, the label selected by ``_params["mixup_pairs"]``, and the sampled lambda. The image is
+ ``input * (1 - lambda) + paired_input * lambda``. Labels must be one-dimensional and are returned as
+ floating values in the image dtype, except that a ``float16`` or ``bfloat16`` image yields ``float32``
+ labels so integer class ids up to ``2 ** 24`` stay exact.
+ - ``p`` is a batch-wide gate for this class, and the generator applies it a second time per row: inside a
+ selected batch each row's lambda is kept with probability ``p`` and zeroed otherwise. A row passes both
+ gates with probability ``p ** 2``; its image can still be unchanged if lambda is zero or it is paired
+ with itself. With ``same_on_batch=True`` the inner gate is also shared across rows
+ (`#4649 <https://github.com/kornia/kornia/issues/4649>`_).
+ At ``p=0`` the image is unchanged and the class output holds
+ the original label twice with a zero lambda. ``same_on_batch=True`` shares lambda draws, but it does not
+ constrain the pairing indices: they can differ across rows and can select the original sample.
+
Note:
This implementation would randomly mixup images in a batch. Ideally, the larger batch size would be preferred.
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 9e8101ff0..4785278bc 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -45,15 +45,16 @@ class RandomMosaic(MixAugmentationBaseV2):
1. Concate selected images into a super-image.
2. Crop out the outcome image according to the top-left corner and crop size.
+ See the Convention block on :class:`~kornia.augmentation.MixAugmentationBaseV2`.
+
Args:
- output_size: the output torch.Tensor width and height after mosaicing.
- start_ratio_range: top-left (x, y) position for cropping the mosaic images.
+ output_size: the output ``(height, width)`` after mosaicing.
+ start_ratio_range: the ``(low, high)`` range from which both top-left crop ratios ``(x / W, y / H)`` are drawn.
mosaic_grid: the number of images and image arrangement. e.g. (2, 2) means
each output will mix 4 images in a 2x2 grid.
min_bbox_size: minimum area of bounding boxes. Default to 0.
- data_keys: the input type sequential for applying augmentations.
- Accepts "input", "image", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints",
- "class", "label".
+ data_keys: the input type sequential for applying augmentations. Only "input", "image", "bbox",
+ "bbox_xyxy" and "bbox_xywh" are implemented; see the Convention block.
p: probability of applying the transformation to each sample.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
@@ -76,6 +77,25 @@ class RandomMosaic(MixAugmentationBaseV2):
>>> out[0].shape, out[1].shape
(torch.Size([8, 3, 300, 300]), torch.Size([8, 8, 4]))
+ Convention:
+ - ``output_size`` and the default output shape are ordered ``(height, width)``. With ``output_size=None``
+ and the default ``cropping_mode="slice"`` the output preserves the input's ``(H, W)`` even when they
+ differ; ``cropping_mode="resample"`` needs an explicit ``output_size``; without one it raises ``TypeError``
+ once the gate selects a sample, and a call that selects none returns the input
+ (`#4652 <https://github.com/kornia/kornia/issues/4652>`_). ``start_ratio_range`` draws a pair
+ used as ``(x / W, y / H)`` for the crop's top-left corner. These are the repaired axis conventions from
+ `#4438 <https://github.com/kornia/kornia/issues/4438>`_.
+ - ``p`` is per sample and this class fixes ``same_on_batch=False``. It composes ``mosaic_grid[0]`` tiles
+ along width and ``mosaic_grid[1]`` tiles along height, then crops each result. It supports
+ ``"bbox"``, ``"bbox_xyxy"``, and ``"bbox_xywh"`` in addition to image inputs; it does not support
+ masks, keypoints, or class labels.
+ - With an explicit ``output_size`` an unselected sample is zero-padded or cropped to that size rather than
+ returned unchanged. Boxes are not rescaled or clipped to ``output_size``, and whenever any sample is
+ selected an unselected sample's own boxes are clipped to the input extent, replaced by a
+ ``[0, 0, 1, 1]`` placeholder when smaller than ``min_bbox_size``, and padded with that placeholder to
+ the grid's box count, although that sample is not mixed
+ (`#4652 <https://github.com/kornia/kornia/issues/4652>`_).
+
"""
def _validate_data_key(self, key: DataKey) -> None:
diff --git a/kornia/augmentation/_2d/mix/patchmix.py b/kornia/augmentation/_2d/mix/patchmix.py
index b919cb351..d0a09a399 100644
--- a/kornia/augmentation/_2d/mix/patchmix.py
+++ b/kornia/augmentation/_2d/mix/patchmix.py
@@ -30,7 +30,9 @@ class PatchMix(MixAugmentationBaseV2):
.. image:: _static/img/PatchMix.png
Replaces a random patch in each image of a batch with the corresponding
- region from a randomly chosen different image in the batch.
+ region from a randomly chosen batch image, which can be the same image.
+
+ See the Convention block on :class:`~kornia.augmentation.MixAugmentationBaseV2`.
Implementation for `CutMix: Regularization Strategy to Train Strong
Classifiers with Localizable Features` :cite:`yun2019cutmix`.
@@ -44,6 +46,18 @@ class PatchMix(MixAugmentationBaseV2):
keepdim: Whether to keep the output shape the same as input ``True``
or broadcast it to the batch form ``False``.
+ Convention:
+ - ``patch_size`` is the side length in pixels of a square patch and must not exceed ``min(H, W)``; a larger
+ value, such as the default ``16`` on a smaller image, raises ``ValueError`` when parameters are drawn,
+ whatever the gate. Each output sample copies that square from its paired input, ``_params["mix_pairs"]``,
+ at the same sampled ``(x, y)`` top-left coordinate, ``_params["patch_coords"]``; the output image retains
+ its input shape. The sampled ``lam`` is stored in ``_params`` but is not used to blend the image or
+ produce labels.
+ - ``p`` is a batch-wide gate. ``same_on_batch=True`` shares the patch coordinate across the batch; the
+ pairing is still drawn per call as one permutation of the batch, which may pair a sample with itself.
+ This class implements image input only; requesting a class, mask, box, or keypoint key raises
+ ``NotImplementedError`` whatever the gate, as described on the base.
+
Examples:
>>> aug = PatchMix(alpha=1.0, patch_size=4)
>>> x = torch.rand(2, 3, 32, 32)
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 47c3489fc..3934898b1 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -37,6 +37,25 @@ class AugmentationBase3D(_AugmentationBase):
probabilities batch-wise.
same_on_batch: apply the same transformation across the batch.
+ Convention:
+ - the working layout is ``(B, C, D, H, W)`` float. Inputs of rank three and four are promoted by
+ prepending batch and, for rank three, channel dimensions; ``keepdim=True`` restores that original
+ rank. The dtype guard accepts only ``float16``, ``bfloat16``, ``float32``, and ``float64``.
+ :class:`~kornia.augmentation.RandomTransplantation3D` overrides ``forward`` and takes batched inputs
+ only.
+ - ``p`` gates samples and ``p_batch`` gates a whole call; ``same_on_batch=True`` shares the generated
+ values. Of the concrete 3D constructors only :class:`~kornia.augmentation.RandomTransplantation3D`
+ exposes ``p_batch`` (`#4425 <https://github.com/kornia/kornia/issues/4425>`_); :class:`CenterCrop3D` and
+ :class:`RandomCrop3D` instead map their own ``p`` onto the call-wide gate. Parameters use the common
+ augmentation RNG and ``forward(x, params=...)`` replays a complete generated dictionary. See
+ :doc:`/get-started/conventions` for the canonical sampling, seeding, and serialization contract.
+ - rigid subclasses expose the last sampled ``(B, 4, 4)`` ``transform_matrix``. The 3D bases do not
+ implement ``inverse``: their subclasses have no ``inverse`` method, and a geometric 3D child makes an
+ :class:`~kornia.augmentation.container.AugmentationSequential` inverse raise.
+ :class:`~kornia.augmentation.RandomTransplantation3D` is the exception: it also derives from
+ :class:`~kornia.augmentation.MixAugmentationBaseV2` and so carries that class's ``inverse``, which
+ raises ``RuntimeError``.
+
"""
def validate_tensor(self, input: torch.Tensor) -> None:
@@ -61,11 +80,13 @@ class AugmentationBase3D(_AugmentationBase):
class RigidAffineAugmentationBase3D(AugmentationBase3D):
- r"""AugmentationBase2D base class for rigid/affine augmentation implementations.
+ r"""AugmentationBase3D base class for rigid/affine augmentation implementations.
- RigidAffineAugmentationBase2D enables routined transformation with given transformation matrices
+ RigidAffineAugmentationBase3D enables routined transformation with given transformation matrices
for different data types like masks, boxes, and keypoints.
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase3D`.
+
Args:
p: probability for applying an augmentation. This param controls the augmentation probabilities
element-wise for a batch.
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index 9d0d7ced4..25cd505f5 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -55,7 +55,7 @@ class RandomAffine3D(GeometricAugmentationBase3D):
If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
will be applied.
- If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
+ If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (shear[i, 0], shear[i, 1])
will be applied.
resample: resample mode from "nearest" (0) or "bilinear" (1).
same_on_batch: apply the same transformation across the batch.
@@ -64,13 +64,28 @@ class RandomAffine3D(GeometricAugmentationBase3D):
to the batch form (False). Default: False.
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, D, H, W)`
Note:
Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.Tensor and returned.
+
+ Convention:
+ See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.
+
+ - ``degrees`` is ordered ``(yaw, pitch, roll)`` about the ``(x, y, z)`` voxel-coordinate axes. A
+ positive roll turns a displayed ``H x W`` slice counter-clockwise, as the 2D
+ :class:`~kornia.augmentation.RandomRotation` and :func:`kornia.geometry.transform.rotate` do, and
+ opposite to :class:`RandomRotation3D`, :func:`kornia.geometry.transform.rotate3d`, and the 2D
+ :class:`~kornia.augmentation.RandomAffine`; its recorded rotation block is the transpose of
+ :class:`RandomRotation3D`'s (`#4408 <https://github.com/kornia/kornia/issues/4408>`_).
+ - the default is bilinear resampling with ``align_corners=False``. With zero rotation, zero translation,
+ unit scale, and zero shear, it reproduces the input at that setting up to floating-point roundoff in
+ ``float32`` and ``float64``. In half precision the sampling grid itself is rounded, so the error grows
+ with the volume size (about ``0.5`` for a ``32 x 48 x 96`` volume in ``bfloat16``).
+ - a two-value ``scale=(a, b)`` is documented as isotropic but currently draws the three axes
+ independently, unlike the 2D :class:`~kornia.augmentation.RandomAffine`
+ (`#4704 <https://github.com/kornia/kornia/issues/4704>`_).
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/base.py b/kornia/augmentation/_3d/geometric/base.py
index c6a25e3d0..a036d535a 100644
--- a/kornia/augmentation/_3d/geometric/base.py
+++ b/kornia/augmentation/_3d/geometric/base.py
@@ -19,4 +19,28 @@ from kornia.augmentation._3d.base import RigidAffineAugmentationBase3D
class GeometricAugmentationBase3D(RigidAffineAugmentationBase3D):
- pass
+ r"""Base class for 3D geometric augmentations.
+
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase3D`.
+
+ Args:
+ p: probability for applying an augmentation. This param controls the augmentation probabilities
+ element-wise for a batch.
+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
+ probabilities batch-wise.
+ same_on_batch: apply the same transformation across the batch.
+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
+ form ``False``.
+
+ Convention:
+ - subclasses record a source-to-destination ``(B, 4, 4)`` voxel-coordinate matrix. Coordinates are
+ ordered ``(x, y, z)``, while volume tensor axes are ``(D, H, W)``. For :class:`RandomCrop3D`, the source
+ frame is the padded volume: the matrix omits the translation introduced by pre-crop padding.
+ Resampling follows the matrix in that source frame at ``align_corners=True``; at
+ ``align_corners=False`` normalization can make the applied warp differ from the recorded matrix
+ (`#4503 <https://github.com/kornia/kornia/issues/4503>`_).
+ Matrices use the input dtype, so integer voxel translations are rounded when that dtype cannot represent
+ them exactly (for example, float16 stores the width translation for ``W=2050`` as ``2048``).
+ - the matrix is useful for forward bookkeeping only: this base provides no 3D inverse implementation.
+
+ """
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index 0b0335897..c55918eb5 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -39,13 +39,19 @@ class CenterCrop3D(GeometricAugmentationBase3D):
to the batch form (False).
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, out_d, out_h, out_w)`
Note:
Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.Tensor and returned.
+
+ Convention:
+ See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.
+
+ - ``size`` is ``(D, H, W)``. The crop is shared across the batch; its ``p`` is the call-wide gate, so a
+ valid ``p=0`` request returns the un-cropped input and ``p=1`` returns the requested crop. Size validation
+ still runs when the call is skipped, so an oversized crop raises even at ``p=0``.
+ - defaults are bilinear resampling and ``align_corners=True``.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index 9d275cff9..df5718dc1 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -39,8 +39,8 @@ class RandomCrop3D(GeometricAugmentationBase3D):
size: Desired output size (out_d, out_h, out_w) of the crop.
Must be Tuple[int, int, int], then out_d = size[0], out_h = size[1], out_w = size[2].
padding: Optional padding on each border of the image.
- Default is None, i.e no padding. If a sequence of length 6 is provided, it is used to F.pad
- left, top, right, bottom, front, back borders respectively.
+ Default is None, i.e no padding. If a sequence of length 6 is provided, it is passed to F.pad as
+ left, right, top, bottom, front, back borders respectively.
If a sequence of length 3 is provided, it is used to F.pad left/right,
top/bottom, front/back borders, respectively.
pad_if_needed: It will F.pad the image if smaller than the
@@ -57,13 +57,30 @@ class RandomCrop3D(GeometricAugmentationBase3D):
to the batch form (False).
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
- - Output: :math:`(B, C, , out_d, out_h, out_w)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
+ - Output: :math:`(B, C, out_d, out_h, out_w)`
Note:
Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.Tensor and returned.
+
+ Convention:
+ See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.
+
+ - ``size`` and the output shape are ordered ``(D, H, W)``. A scalar ``padding`` expands to every side;
+ three values expand as ``(left/right, top/bottom, front/back)``, and six are passed to
+ :func:`torch.nn.functional.pad` as ``(left, right, top, bottom, front, back)`` before the crop is drawn.
+ - ``transform_matrix`` maps the padded volume to the crop, not the original input to the crop. Add the
+ left, top, and front padding to an original ``(x, y, z)`` point before applying this matrix. For example,
+ padding a ``3 x 3 x 3`` input by ``1`` and cropping the full ``5 x 5 x 5`` volume records an identity
+ matrix even though the original voxel ``(1, 1, 1)`` moves to ``(2, 2, 2)``.
+ - its ``p`` is a call-wide gate. Size validation uses the padded input even when the call is skipped,
+ but it is off by one: a crop exactly one voxel larger than the padded volume along an axis is accepted
+ and the output gains a slab that is zero up to resampling roundoff, while two or more raise
+ ``ValueError``
+ (`#4688 <https://github.com/kornia/kornia/issues/4688>`_). :class:`CenterCrop3D` rejects the
+ one-voxel case. A valid gated-off call returns the input itself -- unpadded, at the input shape rather
+ than ``size`` -- with an identity ``transform_matrix``.
+ Defaults are bilinear resampling and ``align_corners=True``.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index 8b6ed4fab..3d2435377 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -27,10 +27,6 @@ class RandomDepthicalFlip3D(GeometricAugmentationBase3D):
r"""Apply random flip along the depth axis of 3D volumes (5D tensor).
Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.
- If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
- the corresponding transformation matrix that has been applied to them. In this case the module
- will Depthically flip the tensors and concatenate the corresponding transformation matrix to the
- previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
Args:
p: probability of the image being flipped.
@@ -39,13 +35,17 @@ class RandomDepthicalFlip3D(GeometricAugmentationBase3D):
to the batch form ``False``.
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, D, H, W)`
Note:
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor(:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+
+ Convention:
+ See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.
+
+ - flips the depth ``D`` axis (tensor axis ``-3``, coordinate ``z``). Its matrix maps ``z`` to
+ ``D - 1 - z`` using inclusive voxel coordinates when the input dtype represents that translation exactly.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/horizontal_flip.py b/kornia/augmentation/_3d/geometric/horizontal_flip.py
index 849fcf851..b14a88710 100644
--- a/kornia/augmentation/_3d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_3d/geometric/horizontal_flip.py
@@ -33,13 +33,17 @@ class RandomHorizontalFlip3D(GeometricAugmentationBase3D):
to the batch form ``False``.
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, D, H, W)`
Note:
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor(:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+
+ Convention:
+ See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.
+
+ - flips the width ``W`` axis (tensor axis ``-1``, coordinate ``x``). Its matrix maps ``x`` to
+ ``W - 1 - x`` using inclusive voxel coordinates when the input dtype represents that translation exactly.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index 6dc641ba4..d3f331dfe 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -26,7 +26,7 @@ from kornia.geometry import get_perspective_transform3d, warp_perspective3d
class RandomPerspective3D(GeometricAugmentationBase3D):
- r"""Apply andom perspective transformation to 3D volumes (5D torch.Tensor).
+ r"""Apply random perspective transformation to 3D volumes (5D torch.Tensor).
Args:
p: probability of the image being perspectively transformed.
@@ -38,13 +38,23 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
to the batch form (False).
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, D, H, W)`
Note:
Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.Tensor and returned.
+
+ Convention:
+ See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.
+
+ - ``distortion_scale=0`` generates identical source and destination corners. The default bilinear,
+ ``align_corners=False`` perspective warp nevertheless does not reproduce its input, even a constant one;
+ use ``align_corners=True`` for an identity warp up to float32 grid precision: the sampling grid is
+ built by :func:`kornia.geometry.grid.create_meshgrid3d` in float32, so a ``float64`` volume is
+ reproduced only to that precision -- about ``1e-7`` for a small volume in ``[0, 1]``, growing with
+ its size -- while the affine and rotation paths are exact to ``float64`` roundoff. The false-setting
+ normalization defect is tracked in `#4503 <https://github.com/kornia/kornia/issues/4503>`_.
+ - the default interpolation is bilinear and the default ``align_corners`` is ``False``.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index cf933cc11..5a494469f 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -31,10 +31,6 @@ class RandomRotation3D(GeometricAugmentationBase3D):
r"""Apply random rotations to 3D volumes (5D torch.Tensor).
Input should be a torch.Tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.
- If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
- the corresponding transformation matrix that has been applied to them. In this case the module
- will rotate the tensors and torch.cat the corresponding transformation matrix to the
- previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
Args:
degrees: Range of degrees to select from.
@@ -52,13 +48,24 @@ class RandomRotation3D(GeometricAugmentationBase3D):
to the batch form (False).
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, D, H, W)`
Note:
Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.Tensor and returned.
+
+ Convention:
+ See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.
+
+ - ``degrees`` is ordered ``(yaw, pitch, roll)`` about the ``(x, y, z)`` voxel-coordinate axes. A positive
+ roll turns a displayed ``H x W`` slice clockwise, as :func:`kornia.geometry.transform.rotate3d` and the
+ 2D :class:`~kornia.augmentation.RandomAffine` do. :class:`RandomAffine3D`, the 2D
+ :class:`~kornia.augmentation.RandomRotation`, and :func:`kornia.geometry.transform.rotate` turn it
+ counter-clockwise (`#4408 <https://github.com/kornia/kornia/issues/4408>`_).
+ - the default interpolation is bilinear with ``align_corners=False``; zero angles reproduce the input
+ up to floating-point roundoff in ``float32`` and ``float64``. In half precision the sampling grid
+ itself is rounded, so the error grows with the volume size (about ``0.5`` for a ``32 x 48 x 96``
+ volume in ``bfloat16``).
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/vertical_flip.py b/kornia/augmentation/_3d/geometric/vertical_flip.py
index 0aaa8aa7b..179358c4d 100644
--- a/kornia/augmentation/_3d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_3d/geometric/vertical_flip.py
@@ -27,10 +27,6 @@ class RandomVerticalFlip3D(GeometricAugmentationBase3D):
r"""Apply random vertical flip to 3D volumes (5D tensor).
Input should be a tensor of shape :math:`(C, D, H, W)` or a batch of tensors :math:`(*, C, D, H, W)`.
- If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,
- the corresponding transformation matrix that has been applied to them. In this case the module
- will Vertically flip the tensors and concatenate the corresponding transformation matrix to the
- previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.
Args:
p: probability of the image being flipped.
@@ -39,13 +35,17 @@ class RandomVerticalFlip3D(GeometricAugmentationBase3D):
to the batch form ``False``.
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, D, H, W)`
Note:
Input tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.tensor(:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+
+ Convention:
+ See :class:`~kornia.augmentation.GeometricAugmentationBase3D` for the shared 3D geometry contract.
+
+ - flips the height ``H`` axis (tensor axis ``-2``, coordinate ``y``). Its matrix maps ``y`` to
+ ``H - 1 - y`` using inclusive voxel coordinates when the input dtype represents that translation exactly.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/intensity/base.py b/kornia/augmentation/_3d/intensity/base.py
index fe26ec159..847f2ce43 100644
--- a/kornia/augmentation/_3d/intensity/base.py
+++ b/kornia/augmentation/_3d/intensity/base.py
@@ -19,4 +19,23 @@ from kornia.augmentation._3d.base import RigidAffineAugmentationBase3D
class IntensityAugmentationBase3D(RigidAffineAugmentationBase3D):
- pass
+ r"""Base class for 3D intensity augmentations.
+
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase3D`.
+
+ Args:
+ p: probability for applying an augmentation. This param controls the augmentation probabilities
+ element-wise for a batch.
+ p_batch: probability for applying an augmentation to a batch. This param controls the augmentation
+ probabilities batch-wise.
+ same_on_batch: apply the same transformation across the batch.
+ keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
+ form ``False``.
+
+ Convention:
+ - these augmentations leave voxel coordinates in place and record an identity ``(B, 4, 4)`` matrix.
+ They still have no direct ``inverse`` method; a container skips them on its inverse path.
+ - their image-value requirements are class-specific. In particular, :class:`RandomEqualize3D` documents
+ ``[0, 1]`` as its intended range and qualifies its device-specific validation.
+
+ """
diff --git a/kornia/augmentation/_3d/intensity/equalize.py b/kornia/augmentation/_3d/intensity/equalize.py
index 1922242b2..91ea95be4 100644
--- a/kornia/augmentation/_3d/intensity/equalize.py
+++ b/kornia/augmentation/_3d/intensity/equalize.py
@@ -28,21 +28,29 @@ class RandomEqualize3D(IntensityAugmentationBase3D):
Args:
p: probability of the image being equalized.
- same_on_batch): apply the same transformation across the batch.
+ same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, D, H, W)`
Note:
Input tensor must be float and normalized into [0, 1]: values outside it that the 256-bin lookup
- cannot index raise a ``RuntimeError`` naming the range. This uses :func:`kornia.enhance.equalize3d`,
- which equalizes each channel's whole volume from one 256-bin histogram, so a volume with no more
- than 255 voxels per channel is returned unchanged.
- Additionally, this function accepts another transformation tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation tensor and returned.
+ cannot index raise a ``RuntimeError`` naming the range on CPU and CUDA. MPS skips that check and can
+ raise a raw indexing error instead. This uses :func:`kornia.enhance.equalize3d`, which equalizes each
+ channel's whole volume from one 256-bin histogram, so a volume with no more than 255 voxels per channel
+ is returned unchanged up to floating-point roundoff.
+
+ Convention:
+ See :class:`~kornia.augmentation.IntensityAugmentationBase3D` for the shared 3D intensity contract.
+
+ - values in ``[0, 1]`` are the intended input range. CPU and CUDA reject values the 256-bin lookup cannot
+ index (outside roughly that range) with ``RuntimeError``; the asynchronous check is deliberately skipped
+ on MPS, where an out-of-range value can instead reach a raw indexing error. The whole per-channel volume
+ supplies one 256-bin histogram. A volume with at most 255 voxels per channel can change only by
+ floating-point roundoff; larger volumes can be equalized.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.py
index ff19fc4b4..9725c7896 100644
--- a/kornia/augmentation/_3d/intensity/motion_blur.py
+++ b/kornia/augmentation/_3d/intensity/motion_blur.py
@@ -30,7 +30,7 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
Args:
p: probability of applying the transformation.
- kernel_size: motion kernel size (odd and positive).
+ kernel_size: motion kernel size (odd and at least 3).
If int, the kernel will have a fixed size.
If Tuple[int, int], it will randomly generate the value from the range batch-wisely.
angle: Range of degrees to select from.
@@ -53,18 +53,26 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False).
Shape:
- - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`, Optional: :math:`(B, 4, 4)`
+ - Input: :math:`(C, D, H, W)` or :math:`(B, C, D, H, W)`
- Output: :math:`(B, C, D, H, W)`
Note:
Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
- Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 4, 4)`), then the
- applied transformation will be merged int to the input transformation torch.Tensor and returned.
- A tuple ``kernel_size`` is drawn once per call and shared across the batch, and each odd size inside
- the range is equally likely, bounds included, so ``(3, 5)`` draws ``3`` and ``5`` and ``(3, 20)`` draws
- ``3, 5, ..., 19``. A range holding no odd size is rounded **up** out of the requested range instead, so
- ``(4, 4)`` draws ``5``; a reversed pair such as ``(20, 3)`` raises a ``ValueError`` at construction.
+ Convention:
+ See :class:`~kornia.augmentation.IntensityAugmentationBase3D` for the shared 3D intensity contract.
+
+ - ``angle`` is ordered ``(yaw, pitch, roll)`` about the ``(x, y, z)`` voxel-coordinate axes. A positive
+ roll turns the blur kernel clockwise as displayed, following :class:`RandomRotation3D` and opposite to
+ the 2D :class:`~kornia.augmentation.RandomMotionBlur`, whose positive angle turns it counter-clockwise
+ (`#4408 <https://github.com/kornia/kornia/issues/4408>`_). Its default resampling is
+ nearest-neighbour, unlike the geometric 3D defaults.
+ - an integer ``kernel_size`` is one odd scalar applied to all three spatial axes. A tuple ``kernel_size``
+ is drawn once per call and shared across the batch, and each odd size inside the range is equally
+ likely, bounds included, so ``(3, 5)`` draws ``3`` and ``5`` and ``(3, 20)`` draws ``3, 5, ..., 19``.
+ A range holding no odd size is rounded **up** out of the requested range instead, so ``(4, 4)`` draws
+ ``5``; a reversed pair such as ``(20, 3)`` raises a ``ValueError`` at construction.
+ - this class fixes ``p_batch=1``; its ``p`` remains the per-sample gate.
Examples:
>>> import torch
diff --git a/kornia/augmentation/auto/autoaugment/autoaugment.py b/kornia/augmentation/auto/autoaugment/autoaugment.py
index 74f739c77..212d55d97 100644
--- a/kornia/augmentation/auto/autoaugment/autoaugment.py
+++ b/kornia/augmentation/auto/autoaugment/autoaugment.py
@@ -117,14 +117,26 @@ svhn_policy: List[SUBPOLICY_CONFIG] = [
class AutoAugment(PolicyAugmentBase):
"""Apply AutoAugment :cite:`cubuk2018autoaugment` searched strategies.
+ See the Convention block on :class:`~kornia.augmentation.auto.PolicyAugmentBase`.
+
+ Convention:
+ - selects one sub-policy uniformly for each forward call. A sub-policy is an ordered sequence of
+ ``(name, probability, magnitude_bin)`` entries, so every listed operation is considered in order.
+ - a magnitude bin selects the adjacent interval of that operation's eleven-point scale. Bins ``0``
+ through ``9`` are valid for operations with a magnitude; operations that ignore magnitude accept any
+ value. The wrapped operation samples a value inside its selected interval for every batch row;
+ ``posterize`` then rounds to the nearest integer number of bits (so bin ``1``, spanning ``4.4`` to
+ ``4.8``, produces ``4`` or ``5``), and ``translate_x`` / ``translate_y``
+ multiply it by the image size in pixels.
+
Args:
policy: a customized policy config or presets of "imagenet", "cifar10", and "svhn".
transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix`
attribute.
If `silent`, transformation matrix will be computed silently and the non-rigid
modules will be ignored as identity transformations.
- If `rigid`, transformation matrix will be computed silently and the non-rigid
- modules will trigger errors.
+ If `rigid`, the result is the same for a policy: every operation wrapper
+ contributes a matrix (an intensity operation the identity), so none is rejected.
If `skip`, transformation matrix will be totally ignored.
Examples:
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index 5df4643e8..a6fae65c8 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -35,7 +35,26 @@ SUBPOLICY_CONFIG = List[OP_CONFIG]
class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
- """Policy-based image augmentation."""
+ """Base class for policy-based image augmentations.
+
+ Convention:
+ - a concrete policy selects one or more :class:`PolicySequential` children for each forward call and
+ records that selected path, including every operation parameter dictionary, in ``_params``. Passing
+ that list to ``forward(input, params=...)`` selects the recorded children rather than drawing a new
+ path and reproduces their output.
+ - the selected operations run in the order recorded in ``_params``: the listed order inside a sub-policy,
+ and for :class:`RandAugment` the order in which its sub-policies were drawn. When matrix computation is
+ enabled, their geometric transformation matrices
+ compose in that same execution order; a nonempty policy containing only intensity
+ operations has the identity matrix. An empty selected sub-policy has no matrix.
+ ``inverse`` reverses a geometry-only selected path and raises ``RuntimeError`` when an applied
+ intensity operation cannot be undone.
+ - input normalization, random-number generation, parameter placement, replay, and serialization follow
+ the canonical augmentation contract in :doc:`/get-started/conventions`. This base does not expose a
+ per-instance generator.
+
+ Concrete policies define how they select children and interpret policy magnitudes.
+ """
def __init__(self, policy: List[SUBPOLICY_CONFIG], transformation_matrix_mode: str = "silence") -> None:
policies = self.compose_policy(policy)
@@ -153,8 +172,8 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
Only geometric operations are invertible. A policy draw that contains an intensity operation is
not round-trippable, and inverting it would return a tensor that still carries that operation --
- for a draw with no geometry at all, the input unchanged. This raises instead, as
- :meth:`kornia.augmentation.MixAugmentationBaseV2.inverse` already does for the mix classes.
+ for a draw with no geometry at all, the input unchanged. This raises instead, as ``inverse`` on
+ :class:`~kornia.augmentation.MixAugmentationBaseV2` already does for the mix classes.
Args:
input: Tensor produced by a forward pass.
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index 76a713ccb..4b705ddfe 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -39,6 +39,35 @@ class OperationBase(nn.Module):
is_batch_operation: determine if to obtain the probability from `p` or `p_batch`.
Set to True for most non-shape-persistent operations (e.g. cropping).
+ Convention:
+ - this wrapper owns a probability parameter and, when configured, one learnable magnitude. The
+ ``probability`` property clamps to the closed interval ``[1e-7, 1 - 1e-7]`` and ``magnitude`` clamps to
+ the wrapped generator's configured range. ``forward_parameters`` builds a (relaxed) Bernoulli sampler
+ from that probability, but nothing reads it: the gate is drawn from the wrapped augmentation's own float
+ ``p`` and ``p_batch``, the sampled ``batch_prob`` is a hard ``0`` or ``1``, and the probability parameter
+ receives no gradient (`#4656 <https://github.com/kornia/kornia/issues/4656>`_). It then draws the wrapped
+ augmentation's parameters and substitutes the supplied or learned magnitude.
+ - ``forward`` linearly blends the wrapped augmentation's output with the input using ``batch_prob``.
+ With supplied fractional gates, the wrapped augmentation first keeps rows whose gate is at most ``0.5``
+ unchanged, unless both its ``p`` and ``p_batch`` equal ``1``. Only that unconditional configuration
+ blends every row with the fully transformed image; otherwise rows at or below the threshold stay
+ unchanged even after the outer blend.
+ - a symmetric magnitude first applies the configured magnitude mapping, then chooses an independent sign
+ for every row. Sign selection preserves the mapped magnitude, but the mapping can first quantize it to
+ zero. For example, ``Posterize`` maps ``0.5`` to zero with ``magnitude_range=(0, 8)``.
+ - :class:`~kornia.augmentation.auto.PolicySequential` is a lower-level container. Its own sampler calls
+ ``operation.op.forward_parameters`` directly, bypassing this wrapper's magnitude mapping. This is a
+ distinct direct-use behavior, tracked in `#4441
+ <https://github.com/kornia/kornia/issues/4441>`_.
+ - The concrete operation classes in ``kornia.augmentation.auto.operations.ops`` only configure this
+ wrapper around public 2D augmentations; their input, dtype, RNG, and replay contracts are those of
+ their wrapped augmentation and :doc:`/get-started/conventions`. Serialization is the exception: this
+ wrapper stores its magnitude mapping as a local closure unless the concrete class supplies its own
+ named mapping and ``symmetric_megnitude`` is false, and a local closure does not pickle even though
+ all the wrapped augmentations do. With default arguments only ``Posterize`` pickles;
+ ``ShearX`` and ``ShearY`` also do with ``symmetric_megnitude=False``
+ (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).
+
"""
def __init__(
@@ -187,8 +216,9 @@ class OperationBase(nn.Module):
sampled from ``input.shape``.
Returns:
- Tensor where each sample is either transformed or left unchanged
- according to ``batch_prob``.
+ Tensor blended with the wrapped augmentation's output according to
+ ``batch_prob``. The wrapped augmentation's own gate runs before this
+ blend, as described in the class's Convention block.
"""
if params is None:
params = self.forward_parameters(input.shape)
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index b95cd8f2c..5d4ff1d95 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -33,8 +33,24 @@ from kornia.core.utils import is_exporting
class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
"""Policy tuple for applying multiple operations.
+ Convention:
+ - accepts only :class:`~kornia.augmentation.auto.operations.OperationBase` children. Generated parameters
+ apply every child in construction order. Supplied ``params`` define the execution path instead: their
+ order and membership select the referenced children, so they may replay a reordered or partial path.
+ ``forward`` stores the ``ParamItem`` objects for the path it executed in ``_params``; those parameters can
+ replay the same operations through ``forward(input, params=...)``.
+ - its transformation matrix is the ordered product of its geometric wrapped operations. Intensity
+ operations do not contribute to that matrix.
+ - direct ``forward_parameters`` delegates to each wrapped augmentation rather than to
+ :meth:`~kornia.augmentation.auto.operations.OperationBase.forward_parameters`.
+ It consequently samples the wrapped operation's native
+ magnitude instead of the ``OperationBase`` magnitude mapping; the gate comes from the wrapped
+ augmentation's ``p`` on both paths (`#4656 <https://github.com/kornia/kornia/issues/4656>`_). Tracked
+ in `#4441 <https://github.com/kornia/kornia/issues/4441>`_. Policy augmentations use their own
+ samplers where needed.
+
Args:
- operations: a list of operations to perform.
+ operations: the operations to perform, passed as positional arguments rather than as one list.
"""
diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.py
index 4f7c630d3..14642c27f 100644
--- a/kornia/augmentation/auto/rand_augment/rand_augment.py
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -50,6 +50,22 @@ default_policy: List[SUBPOLICY_CONFIG] = [
class RandAugment(PolicyAugmentBase):
"""Apply RandAugment :cite:`cubuk2020randaugment` augmentation strategies.
+ See the Convention block on :class:`~kornia.augmentation.auto.PolicyAugmentBase`.
+
+ Convention:
+ - selects ``n`` distinct one-operation candidate sub-policies uniformly without replacement, then
+ applies them in the order drawn. ``n`` must be in ``[1, len(policy)]``.
+ - ``m`` must be strictly between ``0`` and ``30``. For every magnitude-bearing selected operation it
+ sets a per-row magnitude to ``low + (high - low) * m / 30`` over that operation's magnitude range. For a
+ symmetric operation that range is ``(0, max)`` and each row independently gets a positive or negative
+ sign, so ``m=15`` on ``("rotate", -30, 30)`` gives ``+15`` or ``-15``. That value then passes through
+ the wrapper's magnitude mapping, which is the identity for every default entry except three:
+ ``shear_x`` / ``shear_y`` multiply it by ``180``, so ``m=15`` on the default ``("shear_x", -0.3, 0.3)``
+ shears by ``27`` degrees and not by ``0.15``; ``posterize`` truncates it to integer bits (``0`` for
+ ``m < 7.5`` with the default entry, an all-black image); and ``translate_x`` / ``translate_y`` take it
+ as pixels, not as a fraction of the image size
+ (`#4655 <https://github.com/kornia/kornia/issues/4655>`_).
+
Args:
n: the number of augmentations to apply sequentially. Must be at least ``1`` and at
most the number of sub-policies in ``policy``, since they are sampled without
@@ -60,8 +76,8 @@ class RandAugment(PolicyAugmentBase):
attribute.
If `silent`, transformation matrix will be computed silently and the non-rigid
modules will be ignored as identity transformations.
- If `rigid`, transformation matrix will be computed silently and the non-rigid
- modules will trigger errors.
+ If `rigid`, the result is the same for a policy: every operation wrapper
+ contributes a matrix (an intensity operation the identity), so none is rejected.
If `skip`, transformation matrix will be totally ignored.
Examples:
diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
index f280e79dd..24984935d 100644
--- a/kornia/augmentation/auto/trivial_augment/trivial_augment.py
+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
@@ -47,14 +47,28 @@ default_policy: List[SUBPOLICY_CONFIG] = [
class TrivialAugment(PolicyAugmentBase):
"""Apply TrivialAugment :cite:`muller2021trivialaugment` augmentation strategies.
+ See the Convention block on :class:`~kornia.augmentation.auto.PolicyAugmentBase`.
+
+ Convention:
+ - selects one candidate sub-policy uniformly for each forward call. Each candidate holds one operation
+ whose probability is fixed at ``1``, so the selected operation is applied to every row and no
+ probability is sampled; a candidate's second and third entries are its magnitude range, not a
+ probability, unlike :class:`~kornia.augmentation.auto.AutoAugment`. Only the magnitude is drawn
+ independently for every batch row.
+ - sampling bypasses the operation wrapper's magnitude mapping. For example, a ``("rotate", -30, 30)``
+ candidate draws angles in ``[0, 30]`` without applying the random sign; for ``shear_x`` / ``shear_y``
+ the same bypass also drops the mapping's factor of ``180``, so those candidates shear by at most
+ ``0.3`` degrees. This follows the :class:`~kornia.augmentation.auto.PolicySequential` limitation
+ tracked in `#4441 <https://github.com/kornia/kornia/issues/4441>`_.
+
Args:
policy: candidate transformations. If None, a default candidate list will be used.
transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix`
attribute.
If `silent`, transformation matrix will be computed silently and the non-rigid
modules will be ignored as identity transformations.
- If `rigid`, transformation matrix will be computed silently and the non-rigid
- modules will trigger errors.
+ If `rigid`, the result is the same for a policy: every operation wrapper
+ contributes a matrix (an intensity operation the identity), so none is rejected.
If `skip`, transformation matrix will be totally ignored.
Examples:
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 1a0a7e82f..b79951404 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -38,6 +38,8 @@ __all__ = ["CutmixGenerator"]
class CutmixGenerator(RandomGeneratorBase):
r"""Generate cutmix indexes and lambdas for a batch of inputs.
+ See the Convention block on :class:`~kornia.augmentation.RandomCutMixV2`.
+
Args:
p (float): probability of applying cutmix.
num_mix (int): number of images to mix with. Default is 1.
@@ -50,8 +52,9 @@ class CutmixGenerator(RandomGeneratorBase):
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (num_mix, B).
- - crop_src (torch.Tensor): element-wise probabilities with a shape of (num_mix, B, 4, 2).
+ - mix_pairs (torch.Tensor): pairing indices with a shape of (num_mix, B).
+ - crop_src (torch.Tensor): cut-box vertices with a shape of (num_mix, B, 4, 2).
+ - image_shape (torch.Tensor): the input ``(H, W)``.
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
diff --git a/kornia/augmentation/random_generator/_2d/jigsaw.py b/kornia/augmentation/random_generator/_2d/jigsaw.py
index 96a4ec12c..c206bf72b 100644
--- a/kornia/augmentation/random_generator/_2d/jigsaw.py
+++ b/kornia/augmentation/random_generator/_2d/jigsaw.py
@@ -29,6 +29,8 @@ __all__ = ["JigsawGenerator"]
class JigsawGenerator(RandomGeneratorBase):
r"""Generate Jigsaw permutation indices for a batch of inputs.
+ See the Convention block on :class:`~kornia.augmentation.RandomJigsaw`.
+
Args:
grid: the Jigsaw puzzle grid. e.g. (2, 2) means
each output will mix image patches in a 2x2 grid.
diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.py
index 949c81491..07b06d4fb 100644
--- a/kornia/augmentation/random_generator/_2d/mixup.py
+++ b/kornia/augmentation/random_generator/_2d/mixup.py
@@ -30,14 +30,16 @@ __all__ = ["MixupGenerator"]
class MixupGenerator(RandomGeneratorBase):
r"""Generate mixup indexes and lambdas for a batch of inputs.
+ See the Convention block on :class:`~kornia.augmentation.RandomMixUpV2`.
+
Args:
lambda_val (torch.Tensor, optional): min-max strength for mixup images, ranged from [0., 1.].
If None, it will be set to tensor([0., 1.]), which means no restrictions.
Returns:
A dict of parameters to be passed for transformation.
- - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (B,).
- - mixup_lambdas (torch.Tensor): element-wise probabilities with a shape of (B,).
+ - mixup_pairs (torch.Tensor): pairing indices with a shape of (B,).
+ - mixup_lambdas (torch.Tensor): the sampled mixing coefficients with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.py
index bc3df18ec..a2468f681 100644
--- a/kornia/augmentation/random_generator/_2d/mosaic.py
+++ b/kornia/augmentation/random_generator/_2d/mosaic.py
@@ -30,17 +30,21 @@ __all__ = ["MosaicGenerator"]
class MosaicGenerator(RandomGeneratorBase):
- r"""Generate mixup indexes and lambdas for a batch of inputs.
+ r"""Generate the tile order and crop boxes of a mosaic for a batch of inputs.
+
+ See the Convention block on :class:`~kornia.augmentation.RandomMosaic`.
Args:
- output_size: the output torch.Tensor width and height after mosaicing.
+ output_size: the output ``(height, width)`` after mosaicing.
mosaic_grid: the number of images and image arrangement. e.g. (2, 2) means
each output will mix 4 images in a 2x2 grid.
- start_ratio_range: top-left (x, y) position for cropping the mosaic images.
+ start_ratio_range: the ``(low, high)`` range from which both top-left crop ratios ``(x / W, y / H)``
+ are drawn.
Returns:
A dict of parameters to be passed for transformation.
- - mosaic_ids (torch.Tensor): a shape of (B, N) torch.tensor, where n is the number of mosaic images.
+ - permutation (torch.Tensor): per-sample tile order with a shape of (B, N), where N is the number
+ of mosaic images.
- src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
- batch_shapes (torch.Tensor): image shapes in the batch with a shape of (B, 3).
diff --git a/kornia/augmentation/random_generator/_2d/patchmix.py b/kornia/augmentation/random_generator/_2d/patchmix.py
index ae35234c3..b26daef88 100644
--- a/kornia/augmentation/random_generator/_2d/patchmix.py
+++ b/kornia/augmentation/random_generator/_2d/patchmix.py
@@ -30,14 +30,17 @@ __all__ = ["PatchMixGenerator"]
class PatchMixGenerator(RandomGeneratorBase):
r"""Generate patchmix indexes and lambdas for a batch of inputs.
+ See the Convention block on :class:`~kornia.augmentation.PatchMix`.
+
Args:
- alpha (float): hyperparameter for generating cut size from beta distribution.
+ alpha (float): parameter of the ``Beta(alpha, alpha)`` draw returned as ``lam``. It does not affect
+ the patch, whose side is always ``patch_size``.
patch_size (int): size of the patch to be swapped.
- p (float): probability of applying patchmix.
+ p (float): stored for ``repr`` only; the augmentation draws the gate itself.
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - mix_pairs (torch.Tensor): element-wise probabilities with a shape of (B).
+ - mix_pairs (torch.Tensor): pairing indices with a shape of (B).
- patch_coords (torch.Tensor): top-left coordinates of the patch (B, 2).
- lam (torch.Tensor): mixing parameter (B).
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index 0b8deb4f6..0ef258dbe 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -33,6 +33,8 @@ from kornia.core.utils import _extract_device_dtype
class AffineGenerator3D(RandomGeneratorBase):
r"""Get parameters for ```3d affine``` transformation random affine transform.
+ See the Convention block on :class:`~kornia.augmentation.RandomAffine3D`.
+
Args:
degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
@@ -57,7 +59,7 @@ class AffineGenerator3D(RandomGeneratorBase):
If shear is a tuple of 2 values, a shear to the 6 facets in the range (shear[0], shear[1]) will be applied.
If shear is a tuple of 6 values, a shear to the i-th facet in the range (-shear[i], shear[i])
will be applied.
- If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (-shear[i, 0], shear[i, 1])
+ If shear is a tuple of 6 tuples, a shear to the i-th facet in the range (shear[i, 0], shear[i, 1])
will be applied.
Returns:
@@ -65,7 +67,7 @@ class AffineGenerator3D(RandomGeneratorBase):
- translations (torch.Tensor): element-wise translations with a shape of (B, 3).
- center (torch.Tensor): element-wise center with a shape of (B, 3).
- scale (torch.Tensor): element-wise scales with a shape of (B, 3).
- - angle (torch.Tensor): element-wise rotation angles with a shape of (B, 3).
+ - angles (torch.Tensor): element-wise rotation angles with a shape of (B, 3).
- sxy (torch.Tensor): element-wise x-y-facet shears with a shape of (B,).
- sxz (torch.Tensor): element-wise x-z-facet shears with a shape of (B,).
- syx (torch.Tensor): element-wise y-x-facet shears with a shape of (B,).
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index db9797fea..fdfa62fc0 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -30,6 +30,8 @@ from kornia.geometry.bbox import bbox_generator3d
class CropGenerator3D(RandomGeneratorBase):
r"""Get parameters for ```crop``` transformation for crop transform.
+ See the Convention block on :class:`~kornia.augmentation.RandomCrop3D`.
+
Args:
size (tuple): Desired size of the crop operation, like (d, h, w).
If torch.Tensor, it must be (B, 3).
@@ -167,6 +169,8 @@ def center_crop_generator3d(
) -> Dict[str, torch.Tensor]:
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
+ See the Convention block on :class:`~kornia.augmentation.CenterCrop3D`.
+
Args:
batch_size (int): the torch.Tensor batch size.
depth (int) : depth of the image.
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index d1d8c296c..065f9c9a0 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -27,11 +27,14 @@ from kornia.core.utils import _extract_device_dtype
class MotionBlurGenerator3D(RandomGeneratorBase):
r"""Get parameters for motion blur.
+ See the Convention block on :class:`~kornia.augmentation.RandomMotionBlur3D`.
+
Args:
- kernel_size: motion kernel size (odd and positive).
+ kernel_size: motion kernel size (odd and at least 3).
If int, the kernel will have a fixed size.
If Tuple[int, int], it will randomly generate one value from the range for the whole batch.
- angle: angle of the motion blur in degrees (anti-clockwise rotation).
+ angle: ``(yaw, pitch, roll)`` of the motion blur in degrees; a positive roll turns the kernel
+ clockwise as displayed, unlike the 2D generator.
If float, it will generate the value from (-angle, angle).
direction: forward/backward direction of the motion blur.
Lower values towards -1.0 will point the motion blur towards the back (with angle provided via angle),
@@ -43,7 +46,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
+ - angle_factor (torch.Tensor): element-wise ``(yaw, pitch, roll)`` angle factors with a shape of (B, 3).
- direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
Note:
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
index 5b77dc612..5ae35073c 100644
--- a/kornia/augmentation/random_generator/_3d/perspective.py
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -29,13 +29,15 @@ from kornia.core.utils import _extract_device_dtype
class PerspectiveGenerator3D(RandomGeneratorBase):
r"""Get parameters for ``perspective`` for a random perspective transform.
+ See the Convention block on :class:`~kornia.augmentation.RandomPerspective3D`.
+
Args:
distortion_scale: controls the degree of distortion and ranges from 0 to 1.
Returns:
A dict of parameters to be passed for transformation.
- - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
+ - start_points (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
+ - end_points (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.py
index bc028f726..96c0f28f1 100644
--- a/kornia/augmentation/random_generator/_3d/rotation.py
+++ b/kornia/augmentation/random_generator/_3d/rotation.py
@@ -27,6 +27,8 @@ from kornia.core.utils import _extract_device_dtype
class RotationGenerator3D(RandomGeneratorBase):
r"""Get parameters for ``rotate`` for a random 3D rotate transform.
+ See the Convention block on :class:`~kornia.augmentation.RandomRotation3D`.
+
Args:
degrees: Range of yaw (x-axis), pitch (y-axis), roll (z-axis) to select from.
If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index c8c216eb0..3f20029ea 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -1095,7 +1095,8 @@ def equalize3d(input: torch.Tensor) -> torch.Tensor:
.. note::
The input is expected in :math:`[0, 1]`, and each channel's whole :math:`(D, H, W)` volume is
equalized from one 256-bin histogram. The lookup step is an integer division by 255, so a volume
- with no more than 255 voxels per channel is returned unchanged; just above that, whether it changes
+ with no more than 255 voxels per channel is returned unchanged up to floating-point roundoff; just
+ above that, whether it changes
depends on the values. Values the 256-bin lookup cannot index (outside roughly :math:`[0, 1]`)
raise a ``RuntimeError`` naming the range. The check runs on CPU and CUDA (via
``torch._assert_async``); on MPS it is skipped.
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
new file mode 100644
index 000000000..51c386fd5
--- /dev/null
+++ b/tests/augmentation/test_conventions_3d.py
@@ -0,0 +1,540 @@
+# 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
+
+import pytest
+import torch
+
+import kornia
+import kornia.augmentation as K
+
+from testing.base import BaseTester, supports_bilinear_3d_grid_sample, supports_nearest_3d_grid_sample
+
+
+class Test3DAugmentationConventions(BaseTester):
+ def test_convention_rank_keepdim_and_dtype_guard(self, device, dtype):
+ # 3D augmentations promote D,H,W and C,D,H,W to B,C,D,H,W. keepdim restores only promoted dimensions.
+ augmentation = K.RandomHorizontalFlip3D(p=1.0, keepdim=True)
+ unchannelled = torch.arange(24, device=device, dtype=dtype).reshape(2, 3, 4)
+ channelled = unchannelled.unsqueeze(0)
+ batch = channelled.unsqueeze(0)
+ assert augmentation(unchannelled).shape == unchannelled.shape
+ assert augmentation(channelled).shape == channelled.shape
+ assert augmentation(batch).shape == batch.shape
+ with pytest.raises(TypeError, match="float16"):
+ augmentation(torch.ones(1, 1, 2, 3, 4, device=device, dtype=torch.int64))
+
+ def test_convention_flip_axes_and_inclusive_matrices(self, device, dtype):
+ volume = torch.zeros(1, 1, 3, 4, 5, device=device, dtype=dtype)
+ volume[..., 0, 2, 3] = 1
+ cases = (
+ (K.RandomHorizontalFlip3D, -1, [[-1, 0, 0, 4], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]),
+ (K.RandomVerticalFlip3D, -2, [[1, 0, 0, 0], [0, -1, 0, 3], [0, 0, 1, 0], [0, 0, 0, 1]]),
+ (K.RandomDepthicalFlip3D, -3, [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, -1, 2], [0, 0, 0, 1]]),
+ )
+ for cls, axis, matrix in cases:
+ augmentation = cls(p=1.0)
+ output = augmentation(volume)
+ self.assert_close(output, torch.flip(volume, (axis,)))
+ self.assert_close(augmentation.transform_matrix, volume.new_tensor(matrix)[None])
+
+ @pytest.mark.device_agnostic
+ def test_convention_flip_matrix_is_rounded_in_float16(self):
+ # Transform matrices keep the input dtype. float16 cannot represent every integer above 2048.
+ volume = torch.zeros(1, 1, 1, 1, 2050, dtype=torch.float16)
+ augmentation = K.RandomHorizontalFlip3D(p=1.0)
+ augmentation(volume)
+ assert augmentation.transform_matrix.dtype is torch.float16
+ assert augmentation.transform_matrix[0, 0, 3] == 2048
+
+ @pytest.mark.device_agnostic
+ def test_convention_degrees_and_motion_angle_follow_xyz_order(self):
+ ranges = ((10.0, 10.0), (20.0, 20.0), (30.0, 30.0))
+ shape = (2, 1, 3, 4, 5)
+ affine = K.RandomAffine3D(ranges, p=1.0).forward_parameters(shape)
+ rotation = K.RandomRotation3D(ranges, p=1.0).forward_parameters(shape)
+ motion = K.RandomMotionBlur3D(3, ranges, (0.0, 0.0), p=1.0).forward_parameters(shape)
+ expected = torch.tensor([10.0, 20.0, 30.0]).expand(2, 3)
+ assert torch.equal(affine["angles"], expected)
+ assert torch.equal(torch.stack((rotation["yaw"], rotation["pitch"], rotation["roll"]), dim=-1), expected)
+ assert torch.equal(motion["angle_factor"], expected)
+ volume = torch.zeros(1, 1, 5, 5, 5)
+ for axis, diagonal in enumerate(((0, 0), (1, 1), (2, 2))):
+ degrees = [(0.0, 0.0)] * 3
+ degrees[axis] = (30.0, 30.0)
+ augmentation = K.RandomRotation3D(tuple(degrees), p=1.0, align_corners=True)
+ augmentation(volume)
+ assert augmentation.transform_matrix[0, diagonal[0], diagonal[1]] == 1
+
+ def test_convention_crop_size_padding_defaults_and_batch_gate(self, device, dtype):
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
+ volume = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6)
+ center = K.CenterCrop3D((2, 3, 4), p=1.0)
+ crop = K.RandomCrop3D((2, 3, 4), p=1.0, same_on_batch=True)
+ assert center.flags["align_corners"] and crop.flags["align_corners"]
+ assert center.flags["resample"].name == crop.flags["resample"].name == "BILINEAR"
+ assert center(volume).shape == crop(volume).shape == (1, 1, 2, 3, 4)
+ self.assert_close(center(volume), volume[..., 1:3, 1:4, 1:5])
+ self.assert_close(K.CenterCrop3D((2, 3, 4), p=0.0)(volume), volume, rtol=0, atol=0)
+ self.assert_close(K.RandomCrop3D((2, 3, 4), p=0.0)(volume), volume, rtol=0, atol=0)
+ padded = K.RandomCrop3D((2, 3, 4), padding=(1, 2, 3, 4, 5, 6), p=1.0).precrop_padding(volume)
+ assert padded.shape[-3:] == (15, 12, 9)
+ self.assert_close(padded[..., 5:9, 3:8, 1:7], volume)
+ padded = K.RandomCrop3D((2, 3, 4), padding=(1, 2, 3), p=1.0).precrop_padding(volume)
+ assert padded.shape[-3:] == (10, 9, 8)
+ self.assert_close(padded[..., 3:7, 2:7, 1:7], volume)
+ padded = K.RandomCrop3D((2, 3, 4), padding=1, p=1.0).precrop_padding(volume)
+ assert padded.shape[-3:] == (6, 7, 8)
+ self.assert_close(padded[..., 1:5, 1:6, 1:7], volume)
+ # The gate is call-wide: it never selects a strict subset of the rows.
+ for augmentation in (K.CenterCrop3D((2, 3, 4), p=0.5), K.RandomCrop3D((2, 3, 4), p=0.5)):
+ for _ in range(20):
+ batch_prob = augmentation.forward_parameters(torch.Size([8, 1, 4, 5, 6]))["batch_prob"]
+ assert batch_prob.numel() == 8
+ assert bool((batch_prob == batch_prob[0]).all())
+
+ def test_convention_random_crop3d_uses_sampled_nonzero_offset(self, device, dtype):
+ if not supports_nearest_3d_grid_sample(device, dtype):
+ pytest.skip("nearest 3D grid_sample is unavailable for this device and dtype")
+ volume = torch.arange(120, device=device, dtype=dtype).reshape(1, 1, 4, 5, 6)
+ augmentation = K.RandomCrop3D((2, 3, 4), resample="nearest", p=1.0)
+ params = augmentation.forward_parameters(volume.shape)
+ # The source cube starts at (x, y, z) = (1, 1, 1), deliberately excluding the top-left crop.
+ params["src"] = torch.tensor(
+ [[[1, 1, 1], [4, 1, 1], [4, 3, 1], [1, 3, 1], [1, 1, 2], [4, 1, 2], [4, 3, 2], [1, 3, 2]]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(augmentation(volume, params=params), volume[..., 1:3, 1:4, 1:5])
+
+ def test_convention_geometric_defaults_and_identity(self, device, dtype):
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
+ volume = torch.arange(60, device=device, dtype=dtype).reshape(1, 1, 3, 4, 5) / 64
+ affine = K.RandomAffine3D((0.0, 0.0, 0.0), p=1.0)
+ rotation = K.RandomRotation3D((0.0, 0.0, 0.0), p=1.0)
+ perspective = K.RandomPerspective3D(0.0, p=1.0)
+ assert not affine.flags["align_corners"] and not rotation.flags["align_corners"]
+ assert not perspective.flags["align_corners"]
+ assert (
+ affine.flags["resample"].name
+ == rotation.flags["resample"].name
+ == perspective.flags["resample"].name
+ == "BILINEAR"
+ )
+ self.assert_close(affine(volume), volume)
+ self.assert_close(rotation(volume), volume)
+
+ def test_wart_random_perspective3d_identity_align_corners_false_4503(self, device, dtype):
+ # #4503: the default false-setting perspective path still mixes coordinate normalizations. A zero
+ # distortion matrix is identity, but a non-constant volume is resampled away from its voxel centres.
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
+ volume = torch.arange(60, device=device, dtype=dtype).reshape(1, 1, 3, 4, 5)
+ default = K.RandomPerspective3D(0.0, p=1.0)
+ aligned = K.RandomPerspective3D(0.0, p=1.0, align_corners=True)
+ assert (default(volume) - volume).abs().max() > 1
+ self.assert_close(aligned(volume), volume)
+
+ @pytest.mark.xfail(strict=True, raises=AssertionError, reason="3D normalization ignores align_corners, #4503")
+ def test_convention_random_perspective3d_identity_align_corners_false(self, device, dtype):
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
+ volume = torch.arange(60, device=device, dtype=dtype).reshape(1, 1, 3, 4, 5)
+ self.assert_close(K.RandomPerspective3D(0.0, p=1.0)(volume), volume)
+
+ @pytest.mark.device_agnostic
+ def test_wart_positive_roll_direction_splits_the_rotation_entry_points_4408(self):
+ # An off-centre marker in a 7 x 7 slice: a counter-clockwise quarter turn sends (row 1, col 4) to (2, 1),
+ # a clockwise one to (4, 5).
+ image = torch.zeros(1, 1, 7, 7)
+ image[0, 0, 1, 4] = 1
+ volume = image[:, :, None].repeat(1, 1, 7, 1, 1)
+ zero, quarter = (0.0, 0.0), (90.0, 90.0)
+
+ def marker(plane):
+ return divmod(int(plane.flatten().argmax()), 7)
+
+ assert marker(kornia.geometry.transform.rotate(image, torch.tensor([90.0]))[0, 0]) == (2, 1)
+ assert marker(K.RandomRotation(quarter, p=1.0)(image)[0, 0]) == (2, 1)
+ assert marker(K.RandomAffine3D((zero, zero, quarter), p=1.0)(volume)[0, 0, 3]) == (2, 1)
+ assert marker(K.RandomAffine(quarter, p=1.0)(image)[0, 0]) == (4, 5)
+ assert marker(K.RandomRotation3D((zero, zero, quarter), p=1.0)(volume)[0, 0, 3]) == (4, 5)
+ angles = [torch.tensor([value]) for value in (0.0, 0.0, 90.0)]
+ assert marker(kornia.geometry.transform.rotate3d(volume, *angles)[0, 0, 3]) == (4, 5)
+
+ def test_wart_random_affine3d_rotation_sign_4408(self, device, dtype):
+ # #4408: the affine composer negates the angle relative to RandomRotation3D; pixel directions are pinned above.
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
+ volume = torch.zeros(1, 1, 5, 5, 5, device=device, dtype=dtype)
+ affine = K.RandomAffine3D(((0.0, 0.0), (0.0, 0.0), (30.0, 30.0)), p=1.0)
+ rotation = K.RandomRotation3D(((0.0, 0.0), (0.0, 0.0), (30.0, 30.0)), p=1.0)
+ affine(volume)
+ rotation(volume)
+ self.assert_close(affine.transform_matrix[:, :3, :3], rotation.transform_matrix[:, :3, :3].transpose(-1, -2))
+
+ @pytest.mark.parametrize(
+ ("axis", "rotation_position", "affine_position"),
+ [(0, (1, 4, 3), (3, 2, 3)), (1, (3, 2, 3), (1, 2, 5)), (2, (1, 2, 5), (1, 4, 3))],
+ )
+ def test_convention_affine_and_rotation3d_move_an_asymmetric_marker(
+ self, axis, rotation_position, affine_position, device, dtype
+ ):
+ if not supports_nearest_3d_grid_sample(device, dtype):
+ pytest.skip("nearest 3D grid_sample is unavailable for this device and dtype")
+ # Odd, unequal D/H/W dimensions put the rotation centre on voxels and make all axes observable.
+ volume = torch.zeros(1, 1, 5, 7, 9, device=device, dtype=dtype)
+ volume[..., 1, 2, 3] = 1
+ degrees = [(0.0, 0.0)] * 3
+ degrees[axis] = (90.0, 90.0)
+ rotation = K.RandomRotation3D(tuple(degrees), resample="nearest", p=1.0, align_corners=True)
+ affine = K.RandomAffine3D(tuple(degrees), resample="nearest", p=1.0, align_corners=True)
+ rotated, affined = rotation(volume), affine(volume)
+ expected_rotation, expected_affine = torch.zeros_like(volume), torch.zeros_like(volume)
+ expected_rotation[(0, 0, *rotation_position)] = 1
+ expected_affine[(0, 0, *affine_position)] = 1
+ self.assert_close(rotated, expected_rotation)
+ self.assert_close(affined, expected_affine)
+
+ def test_convention_equalize_small_volume_roundoff(self, device, dtype):
+ small = torch.linspace(0.1, 0.9, 255, device=device, dtype=dtype).reshape(1, 1, 1, 1, 255)
+ augmentation = K.RandomEqualize3D(p=1.0)
+ self.assert_close(augmentation(small), small, rtol=0, atol=torch.finfo(dtype).eps)
+ self.assert_close(augmentation.transform_matrix, torch.eye(4, device=device, dtype=dtype)[None])
+ # 256 voxels is the smallest volume the lookup can change: 128 zeros and 128 singly occupied bins.
+ ramp = torch.arange(1, 129, device=device, dtype=dtype)
+ large = torch.cat([torch.zeros_like(ramp), ramp / 255]).reshape(1, 1, 1, 1, 256)
+ expected = torch.cat([torch.zeros_like(ramp), (ramp + 127) / 255]).reshape(1, 1, 1, 1, 256)
+ self.assert_close(augmentation(large), expected)
+
+ @pytest.mark.device_agnostic
+ def test_convention_equalize_range_check_on_cpu(self):
+ with pytest.raises(RuntimeError, match="values in \\[0, 1\\]"):
+ K.RandomEqualize3D(p=1.0)(torch.full((1, 1, 1, 1, 2), -0.1))
+
+ @pytest.mark.device_agnostic
+ def test_convention_motion_blur_defaults_and_probability(self):
+ augmentation = K.RandomMotionBlur3D(3, (0.0, 0.0, 0.0), 0.0, p=0.5)
+ assert augmentation.flags["resample"].name == "NEAREST"
+ assert augmentation.p_batch == 1.0
+ assert augmentation.p == 0.5
+
+ def test_convention_motion_blur3d_fixed_kernel_filters_an_impulse(self, device, dtype):
+ volume = torch.zeros(1, 1, 5, 5, 5, device=device, dtype=dtype)
+ volume[..., 2, 2, 2] = 1
+ output = K.RandomMotionBlur3D(3, (0.0, 0.0, 0.0), 0.0, p=1.0)(volume)
+ expected = torch.zeros_like(volume)
+ expected[..., 2, 2, 1:4] = 1 / 3
+ self.assert_close(output, expected)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ ("axis", "line"),
+ [(0, (2, 2, slice(1, 4))), (1, (slice(1, 4), 2, 2)), (2, (2, slice(1, 4), 2))],
+ ids=["yaw-about-x", "pitch-about-y", "roll-about-z"],
+ )
+ def test_convention_motion_blur3d_kernel_uses_the_yaw_pitch_roll_order(self, axis, line):
+ # The zero-angle kernel is a line along x (W). A quarter turn about x leaves it in place, one about y
+ # stands it along D, and one about z lays it along H -- so the three angle slots are distinguishable.
+ volume = torch.zeros(1, 1, 5, 5, 5)
+ volume[..., 2, 2, 2] = 1
+ angle = [(0.0, 0.0)] * 3
+ angle[axis] = (90.0, 90.0)
+ output = K.RandomMotionBlur3D(3, tuple(angle), (0.0, 0.0), p=1.0)(volume)
+ expected = torch.zeros_like(volume)
+ expected[(0, 0, *line)] = 1 / 3
+ self.assert_close(output, expected, atol=1e-4, rtol=0)
+
+ @pytest.mark.device_agnostic
+ def test_convention_3d_augmentations_have_no_direct_inverse(self):
+ augmentations = (
+ K.RandomAffine3D((0.0, 0.0, 0.0)),
+ K.CenterCrop3D((2, 2, 2)),
+ K.RandomCrop3D((2, 2, 2)),
+ K.RandomDepthicalFlip3D(),
+ K.RandomHorizontalFlip3D(),
+ K.RandomPerspective3D(),
+ K.RandomRotation3D((0.0, 0.0, 0.0)),
+ K.RandomVerticalFlip3D(),
+ K.RandomEqualize3D(),
+ K.RandomMotionBlur3D(3, (0.0, 0.0, 0.0), 0.0),
+ )
+ assert all(not hasattr(augmentation, "inverse") for augmentation in augmentations)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("axis", [0, 1, 2])
+ def test_convention_rotation3d_sign_is_literal_and_affine_is_opposite_4408(self, axis):
+ # The matrix literal anchors RandomRotation3D's own direction; #4408 is RandomAffine3D being its transpose.
+ degrees = [(0.0, 0.0)] * 3
+ degrees[axis] = (30.0, 30.0)
+ volume = torch.zeros(1, 1, 5, 5, 5)
+ rotation = K.RandomRotation3D(tuple(degrees), p=1.0, align_corners=True)
+ affine = K.RandomAffine3D(tuple(degrees), p=1.0, align_corners=True)
+ rotation(volume)
+ affine(volume)
+ first, second = [index for index in range(3) if index != axis]
+ matrix = rotation.transform_matrix[0, :3, :3]
+ self.assert_close(matrix[first, second].abs(), torch.tensor(0.5))
+ self.assert_close(matrix[first, second], -matrix[second, first])
+ expected_sign = {0: -1.0, 1: 1.0, 2: -1.0}[axis]
+ assert torch.sign(matrix[first, second]) == expected_sign
+ self.assert_close(affine.transform_matrix[0, :3, :3], matrix.transpose(-1, -2))
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_crop3d_returns_the_unpadded_input_when_gated_off(self):
+ # Fixed by #4667: a gated-off call used to return the padded volume (#4654).
+ volume = torch.rand(1, 1, 4, 5, 6)
+ for kwargs in (
+ {"size": (2, 3, 4), "padding": 2},
+ {"size": (6, 7, 9), "pad_if_needed": True},
+ {"size": (2, 3, 4)},
+ ):
+ augmentation = K.RandomCrop3D(p=0.0, **kwargs)
+ self.assert_close(augmentation(volume), volume, rtol=0, atol=0)
+ self.assert_close(augmentation.transform_matrix, torch.eye(4)[None])
+ assert K.RandomCrop3D((2, 3, 4), padding=2, p=1.0)(volume).shape == (1, 1, 2, 3, 4)
+
+ @pytest.mark.device_agnostic
+ def test_convention_crop3d_validates_size_before_a_disabled_gate(self):
+ volume = torch.rand(1, 1, 4, 5, 6)
+ with pytest.raises(AssertionError, match="Crop size must be smaller"):
+ K.CenterCrop3D((5, 6, 7), p=0.0)(volume)
+ with pytest.raises(ValueError, match="cannot be smaller than crop size"):
+ K.RandomCrop3D((9, 9, 9), padding=1, p=0.0)(volume)
+ # (6, 5, 6) fits the padded (6, 7, 8) volume but not the (4, 5, 6) input: validation sees the padded one.
+ self.assert_close(K.RandomCrop3D((6, 5, 6), padding=1, p=0.0)(volume), volume, rtol=0, atol=0)
+ with pytest.raises(ValueError, match="cannot be smaller than crop size"):
+ K.RandomCrop3D((6, 5, 6), p=0.0)(volume)
+
+ @pytest.mark.parametrize(
+ "padding,size,marker",
+ [(1, (5, 5, 5), (2, 2, 2)), ((1, 2, 3), (9, 7, 5), (4, 3, 2))],
+ )
+ def test_convention_random_crop3d_matrix_uses_the_padded_source_frame(self, padding, size, marker, device, dtype):
+ if not supports_nearest_3d_grid_sample(device, dtype):
+ pytest.skip("nearest 3D grid_sample is unavailable for this device and dtype")
+ volume = torch.zeros(1, 1, 3, 3, 3, device=device, dtype=dtype)
+ volume[..., 1, 1, 1] = 1
+ # Nearest sampling isolates the coordinate frame from half-precision interpolation roundoff.
+ augmentation = K.RandomCrop3D(size, padding=padding, resample="nearest", p=1.0)
+ output = augmentation(volume)
+ expected = torch.zeros_like(output)
+ expected[..., marker[0], marker[1], marker[2]] = 1
+ self.assert_close(output, expected)
+ # Taking the whole padded canvas records identity, despite moving the original marker by the padding.
+ self.assert_close(augmentation.transform_matrix, torch.eye(4, device=device, dtype=dtype)[None])
+
+ @pytest.mark.device_agnostic
+ def test_convention_motion_blur3d_kernel_range_is_drawn_once_per_call_bounds_included(self):
+ # Fixed by #4662 and #4674: the size used to be drawn per sample, which raised for B > 1, and never
+ # reached the upper bound (#4653).
+ volume = torch.rand(6, 1, 4, 5, 6)
+ sizes = set()
+ for seed in range(40):
+ torch.manual_seed(seed)
+ augmentation = K.RandomMotionBlur3D((3, 7), 35.0, 0.5, p=1.0)
+ assert augmentation(volume).shape == volume.shape
+ drawn = augmentation._params["ksize_factor"]
+ assert drawn.shape == (6,) and drawn.unique().numel() == 1
+ sizes.update(drawn.tolist())
+ assert sizes == {3, 5, 7}
+ rounded_up = K.RandomMotionBlur3D((4, 4), 35.0, 0.5, p=1.0)
+ rounded_up(volume)
+ assert rounded_up._params["ksize_factor"].tolist() == [5] * 6
+ with pytest.raises(ValueError, match="smaller than or equal to"):
+ K.RandomMotionBlur3D((7, 3), 35.0, 0.5)
+
+ @pytest.mark.device_agnostic
+ def test_convention_motion_blur3d_positive_roll_is_clockwise(self):
+ # #4408's split reaches motion blur too: the 3D roll mirrors the 2D angle.
+ def tilt(plane):
+ nonzero = (plane.abs() > 1e-4).nonzero().float()
+ centred = nonzero - nonzero.mean(0)
+ return float((centred[:, 0] * centred[:, 1]).sum())
+
+ volume = torch.zeros(1, 1, 3, 15, 15)
+ volume[0, 0, 1, 7, 7] = 1.0
+ image = torch.zeros(1, 1, 15, 15)
+ image[0, 0, 7, 7] = 1.0
+ rolled = K.RandomMotionBlur3D(9, ((0.0, 0.0), (0.0, 0.0), (30.0, 30.0)), 0.0, p=1.0)(volume)[0, 0, 1]
+ flat = K.RandomMotionBlur(9, (30.0, 30.0), 0.0, p=1.0)(image)[0, 0]
+ assert tilt(rolled) > 0 # rows increase with columns: clockwise as displayed
+ assert tilt(flat) < 0 # the 2D class turns the other way
+ assert tilt(rolled) == -tilt(flat)
+
+ @pytest.mark.device_agnostic
+ def test_convention_only_transplantation3d_exposes_p_batch(self):
+ import inspect
+
+ def concrete(cls):
+ for sub in cls.__subclasses__():
+ # Library classes only: other test modules define their own 3D subclasses in the same process.
+ if sub.__module__.startswith("kornia.") and not sub.__name__.endswith("Base3D"):
+ yield sub
+ yield from concrete(sub)
+
+ # Enumerate the subclasses rather than a hand-written list: RandomTransplantation3D is missing from
+ # kornia.augmentation.__all__ and is the one 3D class that does take p_batch.
+ classes = set(concrete(K.AugmentationBase3D))
+ assert {K.RandomAffine3D, K.CenterCrop3D, K.RandomEqualize3D, K.RandomTransplantation3D} <= classes
+ exposing = {cls.__name__ for cls in classes if "p_batch" in inspect.signature(cls.__init__).parameters}
+ assert exposing == {"RandomTransplantation3D"}
+ with pytest.raises(TypeError, match="p_batch"):
+ K.RandomHorizontalFlip3D(p=1.0, p_batch=0.5)
+ volume = torch.rand(4, 1, 3, 4, 5)
+ mask = torch.randint(0, 3, (4, 3, 4, 5))
+ skipped, _ = K.RandomTransplantation3D(p=1.0, p_batch=0.0)(volume, mask, data_keys=["input", "mask"])
+ self.assert_close(skipped, volume, rtol=0, atol=0)
+
+ @pytest.mark.device_agnostic
+ def test_wart_random_crop3d_accepts_a_one_voxel_oversized_crop_4688(self):
+ volume = torch.ones(1, 1, 4, 5, 6)
+ output = K.RandomCrop3D((5, 5, 6), p=1.0)(volume)
+ assert output.shape == (1, 1, 5, 5, 6)
+ # The appended slab carries no input signal. It is compared against a real slice rather than
+ # against zero: torch 2.5.1 and 2.9.1 leave ~1e-6 of grid_sample roundoff there, 2.14 leaves 0.
+ slices = output.sum(dim=(1, 3, 4))[0]
+ assert float(slices[-1]) < 1e-3 * float(slices[0])
+ with pytest.raises(ValueError, match="cannot be smaller than crop size"):
+ K.RandomCrop3D((6, 5, 6), p=1.0)(volume)
+ # CenterCrop3D rejects the same one-voxel request.
+ with pytest.raises(AssertionError, match="Crop size must be smaller"):
+ K.CenterCrop3D((5, 5, 6), p=1.0)(volume)
+
+ @pytest.mark.device_agnostic
+ def test_convention_perspective3d_identity_is_only_float32_grid_precise(self):
+ volume = torch.rand(1, 1, 4, 5, 6, dtype=torch.float64)
+ rotation = float((K.RandomRotation3D(0.0, p=1.0, align_corners=True)(volume) - volume).abs().max())
+ residual = float((K.RandomPerspective3D(0.0, p=1.0, align_corners=True)(volume) - volume).abs().max())
+ # The rotation path is exact to float64 roundoff (0 on torch 2.14, ~2e-16 on 2.5.1 and 2.9.1);
+ # the perspective path is off by ~1e-7 because its sampling grid is built in float32.
+ assert rotation < 1e-12
+ # An absolute window rather than a multiple of `rotation`: where the rotation is exactly 0 a relative
+ # bound collapses to "> 1e-16", under one float64 ULP. 1e-9 has two orders of headroom on either side.
+ assert 1e-9 < residual < 1e-5
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_crop3d_offset_reaches_both_ends(self):
+ # The offset pin overwrites params["src"], so the sampler's inclusive range is never measured.
+ aug = K.RandomCrop3D((2, 3, 4), p=1.0)
+ starts = [set(), set(), set()]
+ for _ in range(20):
+ src = aug.forward_parameters(torch.Size([8, 1, 4, 5, 6]))["src"]
+ for axis in range(3):
+ starts[axis].update(int(value) for value in src[:, 0, axis])
+ # x: 6 - 4, y: 5 - 3, z: 4 - 2 -> the inclusive range [0, 2] on every axis, each with its own bound.
+ assert starts == [{0, 1, 2}] * 3
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_crop3d_fixed_padding_feeds_pad_if_needed(self):
+ # No other pin exercises `padding` and `pad_if_needed` together, which is where the axis
+ # bookkeeping for the second padding pass lives.
+ volume = torch.rand(1, 1, 4, 5, 6)
+ aug = K.RandomCrop3D((12, 3, 3), padding=(0, 0, 0, 0, 3, 3), pad_if_needed=True, p=1.0)
+ assert aug._compute_padding(tuple(volume.shape), aug.flags) == [[0, 0, 0, 0, 3, 3], [0, 0, 0, 0, 2, 2]]
+ assert aug.precrop_padding(volume).shape[-3:] == (14, 5, 6)
+ # Six different paddings and three different deficits, so that each axis has to read its own pair.
+ aug = K.RandomCrop3D((16, 14, 12), padding=(1, 2, 3, 4, 5, 6), pad_if_needed=True, p=1.0)
+ assert aug._compute_padding(tuple(volume.shape), aug.flags) == [
+ [1, 2, 3, 4, 5, 6],
+ [0, 0, 0, 0, 1, 1],
+ [0, 0, 2, 2, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ ]
+ assert aug.precrop_padding(volume).shape[-3:] == (17, 16, 15)
+
+ @pytest.mark.device_agnostic
+ def test_convention_motion_blur3d_rejects_a_mixed_replayed_kernel_size(self):
+ # The kernel-size pin measures the generator; the consumer's rejection of a mixed replay is separate.
+ volume = torch.rand(2, 1, 5, 5, 5)
+ aug = K.RandomMotionBlur3D((3, 7), 35.0, 0.5, p=1.0)
+ params = aug.forward_parameters(volume.shape)
+ params["ksize_factor"] = torch.tensor([3, 7], dtype=torch.int32)
+ with pytest.raises(RuntimeError):
+ aug(volume, params=params)
+
+ @pytest.mark.device_agnostic
+ def test_wart_random_affine3d_two_value_scale_is_not_isotropic_4704(self):
+ # Documented as isotropic; the 2D class draws one value per sample, the 3D class one per axis.
+ flat = K.RandomAffine(0.0, scale=(0.5, 2.0), p=1.0).forward_parameters(torch.Size([64, 1, 6, 7]))["scale"]
+ assert bool((flat[:, 0] == flat[:, 1]).all())
+ aug = K.RandomAffine3D(0.0, scale=(0.5, 2.0), p=1.0)
+ aug(torch.rand(64, 1, 5, 6, 7))
+ scale = aug._params["scale"]
+ assert scale.shape == (64, 3)
+ assert not bool((scale[:, 0] == scale[:, 1]).any()) and not bool((scale[:, 1] == scale[:, 2]).any())
+ self.assert_close(aug.transform_matrix[:, :3, :3].diagonal(dim1=-2, dim2=-1), scale)
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_affine3d_six_pair_shears_keep_their_lower_bound(self):
+ # The Args text used to negate the lower bound of each pair.
+ pairs = ((1, 2), (3, 4), (5, 6), (7, 8), (9, 10), (11, 12))
+ params = K.RandomAffine3D(0.0, shears=pairs, p=1.0).forward_parameters(torch.Size([64, 1, 4, 5, 6]))
+ for key, (low, high) in zip(("sxy", "sxz", "syx", "syz", "szx", "szy"), pairs):
+ assert low <= float(params[key].min()) and float(params[key].max()) <= high
+
+ @pytest.mark.device_agnostic
+ def test_convention_random_crop3d_padding_modes_are_those_of_f_pad(self):
+ volume = torch.rand(2, 1, 4, 5, 6)
+ for mode in ("constant", "reflect", "replicate", "circular"):
+ assert K.RandomCrop3D((5, 6, 7), padding=1, padding_mode=mode, p=1.0)(volume).shape == (2, 1, 5, 6, 7)
+ for mode in ("edge", "symmetric"):
+ with pytest.raises(NotImplementedError, match="Unrecognised padding mode"):
+ K.RandomCrop3D((5, 6, 7), padding=1, padding_mode=mode, p=1.0)(volume)
+
+ @pytest.mark.device_agnostic
+ def test_convention_3d_generator_keys_match_their_returns_sections(self):
+ from kornia.augmentation import random_generator as rg
+
+ shape = torch.Size([3, 1, 4, 5, 6])
+ assert rg.AffineGenerator3D(10.0)(shape)["angles"].shape == (3, 3)
+ perspective = rg.PerspectiveGenerator3D(0.3)(shape)
+ assert set(perspective) == {"start_points", "end_points"}
+ assert perspective["start_points"].shape == perspective["end_points"].shape == (3, 8, 3)
+ blur = rg.MotionBlurGenerator3D(3, 35.0, 0.5)(shape)
+ assert blur["angle_factor"].shape == (3, 3) and blur["ksize_factor"].shape == (3,)
+ # "odd and at least 3": a kernel of one voxel is rejected.
+ with pytest.raises(AssertionError, match="must be odd and greater than 3"):
+ K.RandomMotionBlur3D(1, 35.0, 0.5, p=1.0)(torch.rand(1, 1, 5, 5, 5))
+
+ @pytest.mark.device_agnostic
+ def test_convention_identity_warp_error_grows_with_size_outside_full_precision(self):
+ # "Up to roundoff" is a float32 / float64 statement: in half precision the sampling grid is rounded.
+ large = torch.rand(1, 1, 32, 48, 96)
+ assert float((K.RandomRotation3D(0.0, p=1.0)(large) - large).abs().max()) < 1e-3
+ if supports_bilinear_3d_grid_sample(torch.device("cpu"), torch.bfloat16):
+ half = large.to(torch.bfloat16)
+ for aug in (K.RandomRotation3D(0.0, p=1.0), K.RandomAffine3D(0.0, p=1.0)):
+ assert float((aug(half) - half).abs().max()) > 0.1
+ # The float32 grid of the perspective path shows at float64 too, and also grows with the volume.
+ small64 = torch.rand(1, 1, 4, 5, 6, dtype=torch.float64)
+ large64 = torch.rand(1, 1, 8, 16, 32, dtype=torch.float64)
+ residuals = [
+ float((K.RandomPerspective3D(0.0, p=1.0, align_corners=True)(volume) - volume).abs().max())
+ for volume in (small64, large64)
+ ]
+ assert residuals[0] < residuals[1] < 1e-4
+
+ @pytest.mark.device_agnostic
+ def test_convention_center_crop3d_centres_each_axis_with_its_own_offset(self):
+ # Offsets (z, y, x) = (1, 2, 4), all different: a (1, 1, 1) fixture cannot tell the axes apart.
+ volume = torch.arange(6 * 8 * 12.0).reshape(1, 1, 6, 8, 12)
+ output = K.CenterCrop3D((4, 4, 4), resample="nearest", p=1.0)(volume)
+ self.assert_close(output, volume[..., 1:5, 2:6, 4:8], rtol=0, atol=0)
diff --git a/tests/augmentation/test_conventions_6d_serialization.py b/tests/augmentation/test_conventions_6d_serialization.py
new file mode 100644
index 000000000..6a2e2c1da
--- /dev/null
+++ b/tests/augmentation/test_conventions_6d_serialization.py
@@ -0,0 +1,128 @@
+# 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
+
+import copy
+import pickle
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+import kornia.augmentation.auto as A
+
+from testing.base import BaseTester
+
+_CASES = [
+ ("RandomAffine3D", {"degrees": 15.0}),
+ ("CenterCrop3D", {"size": (3, 4, 5)}),
+ ("RandomCrop3D", {"size": (3, 4, 5)}),
+ ("RandomDepthicalFlip3D", {}),
+ ("RandomHorizontalFlip3D", {}),
+ ("RandomPerspective3D", {"distortion_scale": 0.2}),
+ ("RandomRotation3D", {"degrees": 15.0}),
+ ("RandomVerticalFlip3D", {}),
+ ("RandomEqualize3D", {}),
+ ("RandomMotionBlur3D", {"kernel_size": 3, "angle": 15.0, "direction": 0.3}),
+ ("RandomCutMixV2", {"use_correct_lambda": True}),
+ ("RandomJigsaw", {}),
+ ("RandomMixUpV2", {}),
+ ("RandomMosaic", {}),
+ ("PatchMix", {"patch_size": 2}),
+]
+
+
+class TestConventionMix3DSerialization(BaseTester):
+ @pytest.mark.parametrize("name,kwargs", _CASES, ids=[name for name, _ in _CASES])
+ @pytest.mark.parametrize("batched,keepdim", [(True, False), (False, False), (False, True)])
+ def test_convention_numeric_config_pickle_and_deepcopy_preserve_replay(self, name, kwargs, batched, keepdim):
+ # Numeric configurations have no state_dict entries; pickle/deepcopy also preserve
+ # configuration and last parameters. A state_dict is therefore not a replay checkpoint.
+ torch.manual_seed(17)
+ augmentation = getattr(K, name)(p=1.0, keepdim=keepdim, **kwargs)
+ image = torch.rand((2, 3, 6, 8, 10) if name.endswith("3D") else (2, 3, 8, 12))
+ if not batched:
+ image = image[0]
+ batch_shape = image.shape if batched else torch.Size((1, *image.shape))
+ expected = augmentation(image)
+ assert expected.ndim == image.ndim + int(not batched and not keepdim)
+ assert not augmentation.state_dict()
+ assert not list(augmentation.parameters())
+ assert not list(augmentation.buffers())
+ for restored in (pickle.loads(pickle.dumps(augmentation)), copy.deepcopy(augmentation)): # noqa: S301
+ assert restored._params is not augmentation._params
+ assert restored._params.keys() == augmentation._params.keys()
+ for key in augmentation._params:
+ self.assert_close(restored._params[key], augmentation._params[key], rtol=0, atol=0)
+ self.assert_close(restored(image, params=restored._params), expected, rtol=0, atol=0)
+ # Fresh draws consult constructor ranges/samplers rather than the replay dictionary.
+ torch.manual_seed(31)
+ reference_params = augmentation.forward_parameters(batch_shape)
+ torch.manual_seed(31)
+ restored_params = restored.forward_parameters(batch_shape)
+ assert restored_params.keys() == reference_params.keys()
+ for key in reference_params:
+ self.assert_close(restored_params[key], reference_params[key], rtol=0, atol=0)
+
+ @pytest.mark.parametrize(
+ "name,shape", [("RandomTransplantation", (3, 2, 6, 8)), ("RandomTransplantation3D", (3, 2, 4, 6, 8))]
+ )
+ def test_convention_transplantation_pickle_and_deepcopy_preserve_replay(self, name, shape):
+ # The serialization bullet names both transplantation classes; they take a mask, so they need their own case.
+ torch.manual_seed(17)
+ augmentation = getattr(K, name)(p=1.0)
+ image = torch.rand(shape)
+ mask = torch.randint(0, 3, (shape[0], *shape[2:]))
+ expected, _ = augmentation(image, mask, data_keys=["input", "mask"])
+ assert not torch.equal(expected, image)
+ assert not augmentation.state_dict()
+ for restored in (pickle.loads(pickle.dumps(augmentation)), copy.deepcopy(augmentation)): # noqa: S301
+ assert restored._params is not augmentation._params
+ assert restored._params.keys() == augmentation._params.keys()
+ for key in augmentation._params:
+ self.assert_close(restored._params[key], augmentation._params[key], rtol=0, atol=0)
+ replayed, _ = restored(image, mask, params=restored._params, data_keys=["input", "mask"])
+ self.assert_close(replayed, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("name", ["AutoAugment", "RandAugment", "TrivialAugment"])
+ def test_wart_auto_policies_cannot_be_pickled_4469(self, name):
+ kwargs = {"n": 2, "m": 15} if name == "RandAugment" else {}
+ augmentation = getattr(A, name)(**kwargs)
+ with pytest.raises(AttributeError, match="local object"):
+ pickle.dumps(augmentation)
+
+ @pytest.mark.parametrize("name", ["AutoAugment", "RandAugment", "TrivialAugment"])
+ def test_convention_a_posterize_only_policy_can_be_pickled(self, name):
+ # A policy pickles when every wrapper in it does; Posterize passes a named mapping and no sign flip.
+ entry = ("posterize", 1.0, 3) if name == "AutoAugment" else ("posterize", 0.0, 4)
+ kwargs = {"n": 1, "m": 15} if name == "RandAugment" else {}
+ augmentation = getattr(A, name)(policy=[[entry]], **kwargs)
+ image = torch.rand(2, 3, 4, 4)
+ expected = augmentation(image)
+ restored = pickle.loads(pickle.dumps(augmentation)) # noqa: S301
+ self.assert_close(restored(image, params=restored._params), expected, rtol=0, atol=0)
+
+ def test_convention_empty_autoaugment_policy_can_be_pickled(self):
+ # With no operation wrappers, there is no local magnitude function blocking pickle.
+ augmentation = A.AutoAugment(policy=[[]])
+ image = torch.rand(2, 1, 4, 4)
+ augmentation(image)
+ restored = pickle.loads(pickle.dumps(augmentation)) # noqa: S301
+ self.assert_close(restored(image, params=restored._params), image, rtol=0, atol=0)
+ assert restored.transform_matrix is None
diff --git a/tests/augmentation/test_conventions_auto.py b/tests/augmentation/test_conventions_auto.py
new file mode 100644
index 000000000..9a3d72744
--- /dev/null
+++ b/tests/augmentation/test_conventions_auto.py
@@ -0,0 +1,522 @@
+# 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
+
+import pytest
+import torch
+
+from kornia.augmentation.auto.autoaugment import AutoAugment
+from kornia.augmentation.auto.operations import PolicySequential, ops
+from kornia.augmentation.auto.rand_augment import RandAugment
+from kornia.augmentation.auto.trivial_augment import TrivialAugment
+
+from testing.base import BaseTester, supports_bilinear_2d_grid_sample
+
+
+class TestAutoAugmentConventions(BaseTester):
+ def test_convention_policy_params_record_the_selected_path_and_replay(self, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ image = torch.rand(3, 1, 8, 6, device=device, dtype=dtype)
+ cases = [
+ (AutoAugment(policy=[[("rotate", 1.0, 5)]]), 1),
+ (RandAugment(n=2, m=15, policy=[[("rotate", -30.0, 30.0)], [("translate_x", -0.5, 0.5)]]), 2),
+ (TrivialAugment(policy=[[("rotate", -30.0, 30.0)]]), 1),
+ ]
+ for aug, expected_operations in cases:
+ params = aug.forward_parameters(image.shape)
+ assert len(params) == expected_operations
+ assert all(len(param.data) == 1 for param in params)
+ output = aug(image, params=params)
+ self.assert_close(output, aug(image, params=params))
+
+ @pytest.mark.device_agnostic
+ def test_convention_autoaugment_and_trivialaugment_choose_one_policy(self):
+ torch.manual_seed(17)
+ auto_policy = [[("invert", 1.0, None)], [("solarize", 1.0, 5)]]
+ trivial_policy = [[("rotate", -30.0, 30.0)], [("translate_x", -0.5, 0.5)]]
+ for aug in (AutoAugment(policy=auto_policy), TrivialAugment(policy=trivial_policy)):
+ selected = {aug.forward_parameters(torch.Size([2, 1, 8, 6]))[0].name for _ in range(32)}
+ assert selected == set(dict(aug.named_children()))
+ self.assert_close(aug.rand_selector.probs, torch.full((2,), 0.5))
+
+ @pytest.mark.device_agnostic
+ def test_convention_recorded_params_select_the_recorded_children(self):
+ policy = [[("rotate", -30.0, 30.0)], [("translate_x", -0.5, 0.5)], [("translate_y", -0.5, 0.5)]]
+ auto_policy = [[("rotate", 1.0, 5)], [("translate_x", 1.0, 5)], [("translate_y", 1.0, 5)]]
+ for aug in (
+ AutoAugment(policy=auto_policy),
+ RandAugment(n=2, m=15, policy=policy),
+ TrivialAugment(policy=policy),
+ ):
+ params = aug.forward_parameters(torch.Size([2, 1, 8, 6]))
+ for _ in range(16):
+ assert [name for name, _ in aug.get_forward_sequence(params)] == [param.name for param in params]
+
+ @pytest.mark.device_agnostic
+ def test_convention_autoaugment_magnitude_bins_are_zero_through_nine(self):
+ degrees = AutoAugment(policy=[[("rotate", 1.0, 9)]]).forward_parameters(torch.Size([64, 1, 8, 6]))
+ degrees = degrees[0].data[0].data["degrees"]
+ assert (degrees >= 24.0).all() and (degrees <= 30.0).all()
+ assert degrees.min() < 25.0 and degrees.max() > 29.0 # bounds alone pass for a collapsed interval
+ for magnitude in (-1, 10):
+ with pytest.raises(ValueError, match=r"in \[0, 9\]"):
+ AutoAugment(policy=[[("rotate", 1.0, magnitude)]])
+
+ @pytest.mark.device_agnostic
+ def test_convention_randaugment_selects_distinct_candidates(self):
+ policy = [
+ [("rotate", -30.0, 30.0)],
+ [("translate_x", -0.5, 0.5)],
+ [("translate_y", -0.5, 0.5)],
+ ]
+ aug = RandAugment(n=3, m=15, policy=policy)
+ for _ in range(8):
+ params = aug.forward_parameters(torch.Size([2, 1, 8, 6]))
+ assert len({param.name for param in params}) == 3
+ # The drawn order is the execution order, not the policy-list order: 64 draws of 3 children reach more than
+ # one of the six orders, and each parameter list replays its own order.
+ orders = {tuple(param.name for param in aug.forward_parameters(torch.Size([2, 1, 8, 6]))) for _ in range(64)}
+ assert len(orders) > 1
+ image = torch.rand(2, 1, 8, 6)
+ aug(image)
+ drawn = [param.name for param in aug._params]
+ assert [name for name, _ in aug.get_forward_sequence(aug._params)] == drawn
+
+ @pytest.mark.device_agnostic
+ def test_convention_autoaugment_magnitude_bin_samples_its_adjacent_interval(self):
+ torch.manual_seed(17)
+ aug = AutoAugment(policy=[[("rotate", 1.0, 5)]])
+ degrees = aug.forward_parameters(torch.Size([64, 1, 8, 6]))[0].data[0].data["degrees"]
+ assert (degrees >= 0.0).all()
+ assert (degrees <= 6.0).all()
+ assert degrees.min() < 1.0 and degrees.max() > 5.0
+
+ @pytest.mark.device_agnostic
+ def test_wart_trivialaugment_bypasses_symmetric_magnitude_mapping_4441(self):
+ torch.manual_seed(17)
+ aug = TrivialAugment(policy=[[("rotate", -30.0, 30.0)]])
+ degrees = aug.forward_parameters(torch.Size([64, 1, 8, 6]))[0].data[0].data["degrees"]
+ assert (degrees >= 0.0).all()
+ assert (degrees <= 30.0).all()
+ assert degrees.min() < 5.0 and degrees.max() > 25.0
+
+ @pytest.mark.device_agnostic
+ def test_convention_randaugment_maps_m_and_validates_the_policy_cardinality(self):
+ policy = [[("rotate", -30.0, 30.0)], [("translate_x", -0.5, 0.5)]]
+ torch.manual_seed(17)
+ aug = RandAugment(n=2, m=15, policy=policy)
+ params = aug.forward_parameters(torch.Size([64, 1, 8, 6]))
+ degrees = next(param for param in params if "degrees" in param.data[0].data).data[0].data["degrees"]
+ self.assert_close(degrees.abs(), torch.full_like(degrees, 15.0))
+ assert (degrees < 0).any() and (degrees > 0).any()
+ for m in (0, 30):
+ with pytest.raises(ValueError, match=r"Expect `m` in \(0, 30\)"):
+ RandAugment(n=1, m=m, policy=policy)
+ for n in (0, 3):
+ with pytest.raises(ValueError, match=r"Expect `n` in \[1, 2\]"):
+ RandAugment(n=n, m=15, policy=policy)
+
+ def test_convention_policy_matrix_composes_and_inverse_refuses_intensity(self, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ image = torch.zeros(2, 1, 5, 5, device=device, dtype=dtype)
+ image[..., 2, 2] = 1
+ geometric = AutoAugment(policy=[[("translate_x", 1.0, 5)]])
+ params = geometric.forward_parameters(image.shape)
+ params[0].data[0].data["translate_x"].fill_(1.0)
+ params[0].data[0].data["batch_prob"].fill_(1.0)
+ output = geometric(image, params=params)
+ expected_translation = torch.zeros_like(image)
+ expected_translation[..., 2, 3] = 1
+ self.assert_close(output, expected_translation)
+ expected_translation_matrix = image.new_tensor([[1, 0, 1], [0, 1, 0], [0, 0, 1]]).expand(2, -1, -1)
+ self.assert_close(geometric.transform_matrix, expected_translation_matrix)
+ inverted = geometric.inverse(output, params=params)
+ self.assert_close(inverted, image)
+
+ ordered = AutoAugment(policy=[[("rotate", 1.0, 5), ("translate_x", 1.0, 5)]])
+ marker = torch.zeros(2, 1, 5, 5, device=device, dtype=dtype)
+ marker[..., 1, 2] = 1
+ ordered_params = ordered.forward_parameters(marker.shape)
+ ordered_params[0].data[0].data["degrees"].fill_(90.0)
+ ordered_params[0].data[1].data["translate_x"].fill_(1.0)
+ for item in ordered_params[0].data:
+ item.data["batch_prob"].fill_(1.0)
+ ordered_output = ordered(marker, params=ordered_params)
+ expected_ordered_output = torch.zeros_like(marker)
+ expected_ordered_output[..., 2, 2] = 1
+ self.assert_close(ordered_output, expected_ordered_output)
+ # Rotation about (2, 2), followed by translation: T @ R, not R @ T.
+ expected_matrix = marker.new_tensor([[0, 1, 1], [-1, 0, 4], [0, 0, 1]]).expand(2, -1, -1)
+ self.assert_close(ordered.transform_matrix, expected_matrix)
+ recomputed = ordered[0].get_transformation_matrix(marker, params=ordered_params[0].data, recompute=True)
+ self.assert_close(recomputed, expected_matrix)
+ # The inverse undoes the translation before the rotation. Undoing them in forward order would leave the
+ # marker, which sits on the rotation centre here, at (2, 1) instead.
+ self.assert_close(ordered.inverse(ordered_output, params=ordered_params), marker)
+
+ chained = RandAugment(n=2, m=15, policy=[[("rotate", -30.0, 30.0)], [("translate_x", -0.5, 0.5)]])
+ chained_params = chained.forward_parameters(marker.shape)
+ for item in chained_params:
+ data = item.data[0].data
+ data["batch_prob"].fill_(1.0)
+ if "degrees" in data:
+ data["degrees"].fill_(90.0)
+ else:
+ data["translate_x"].fill_(1.0)
+ for execution_params in (chained_params, list(reversed(chained_params))):
+ rotate_first = "degrees" in execution_params[0].data[0].data
+ chained_output = chained(marker, params=execution_params)
+ # The supplied parameter order selects T @ R, or R @ T when the translation leads.
+ chained_matrix = expected_matrix if rotate_first else marker.new_tensor([[0, 1, 0], [-1, 0, 3], [0, 0, 1]])
+ self.assert_close(chained.transform_matrix, chained_matrix.expand(2, -1, -1))
+ recomputed = chained.get_transformation_matrix(marker, params=execution_params, recompute=True)
+ self.assert_close(recomputed, chained_matrix.expand(2, -1, -1))
+ expected_chained_output = torch.zeros_like(marker)
+ if rotate_first:
+ expected_chained_output[..., 2, 2] = 1
+ else:
+ expected_chained_output[..., 1, 1] = 1
+ self.assert_close(chained_output, expected_chained_output)
+
+ intensity = AutoAugment(policy=[[("solarize", 1.0, 5)]])
+ intensity(image)
+ self.assert_close(intensity.transform_matrix, torch.eye(3, device=device, dtype=dtype).expand(2, -1, -1))
+ with pytest.raises(RuntimeError, match="is not supported"):
+ intensity.inverse(image)
+
+ skipped_intensity = AutoAugment(policy=[[("solarize", 1.0, 5)]])
+ skipped_params = skipped_intensity.forward_parameters(image.shape)
+ skipped_params[0].data[0].data["batch_prob"].zero_()
+ skipped_output = skipped_intensity(image, params=skipped_params)
+ self.assert_close(skipped_output, image)
+ self.assert_close(skipped_intensity.inverse(skipped_output, params=skipped_params), image)
+ # One applied row is enough to make the path non-invertible.
+ skipped_params[0].data[0].data["batch_prob"][0] = 1.0
+ partial_output = skipped_intensity(image, params=skipped_params)
+ with pytest.raises(RuntimeError, match="is not supported"):
+ skipped_intensity.inverse(partial_output, params=skipped_params)
+
+ @pytest.mark.device_agnostic
+ def test_convention_policy_sequential_supplied_params_define_the_execution_path(self):
+ policy = PolicySequential(
+ ops.Invert(initial_probability=1.0), ops.Solarize(initial_magnitude=0.5, initial_probability=1.0)
+ )
+ image = torch.tensor([0.2], dtype=torch.float32).reshape(1, 1, 1, 1)
+ generated = policy.forward_parameters(image.shape)
+ for param in generated:
+ param.data["batch_prob"].fill_(1.0)
+ if "thresholds" in param.data:
+ param.data["thresholds"].fill_(0.5)
+ param.data["additions"].zero_()
+ self.assert_close(policy(image, params=generated), torch.tensor([0.2]).reshape_as(image))
+ reversed_params = list(reversed(generated))
+ self.assert_close(policy(image, params=reversed_params), torch.tensor([0.8]).reshape_as(image))
+ self.assert_close(policy(image, params=generated[:1]), torch.tensor([0.8]).reshape_as(image))
+ assert [param.name for param in policy._params] == [generated[0].name]
+
+ @pytest.mark.device_agnostic
+ def test_convention_intensity_matrix_requires_a_nonempty_selected_policy(self):
+ image = torch.rand(1, 1, 3, 3)
+ intensity = AutoAugment(policy=[[("solarize", 1.0, 5)]])
+ intensity(image)
+ self.assert_close(intensity.transform_matrix, torch.eye(3).unsqueeze(0))
+ empty = AutoAugment(policy=[[]])
+ self.assert_close(empty(image), image)
+ assert empty.transform_matrix is None
+
+ @pytest.mark.device_agnostic
+ def test_convention_symmetric_magnitude_preserves_the_post_mapping_value(self):
+ posterize = ops.Posterize(initial_magnitude=0.5, magnitude_range=(0.0, 8.0), symmetric_megnitude=True)
+ bits = posterize.forward_parameters(torch.Size([32, 1, 1, 1]))["bits_factor"]
+ self.assert_close(bits, torch.zeros_like(bits), rtol=0, atol=0)
+ # A zero is sign-blind, so it cannot show that the mapping runs BEFORE the sign is chosen.
+ nonzero = ops.Posterize(initial_magnitude=5.5, magnitude_range=(0.0, 8.0), symmetric_megnitude=True)
+ signed = nonzero.forward_parameters(torch.Size([64, 1, 1, 1]))["bits_factor"]
+ assert set(signed.tolist()) == {5, -5}
+ # Every built-in mapping is odd (identity, x * 180, truncation), so {5, -5} holds for either order. A
+ # mapping that is not odd separates them: sign after gives {13, -13}, sign before would give {13, 7}.
+ from kornia.augmentation import RandomRotation
+ from kornia.augmentation.auto.operations.base import OperationBase
+
+ shifted = OperationBase(
+ RandomRotation((0.0, 30.0), p=1.0),
+ initial_magnitude=[("degrees", 3.0)],
+ magnitude_fn=lambda magnitude: magnitude + 10.0,
+ symmetric_megnitude=True,
+ )
+ degrees = shifted.forward_parameters(torch.Size([64, 1, 4, 4]))["degrees"]
+ assert set(degrees.tolist()) == {13.0, -13.0}
+
+ @pytest.mark.device_agnostic
+ def test_convention_operation_probability_and_magnitude_clamps(self):
+ operation = ops.Rotate(initial_magnitude=3.0, initial_probability=0.5)
+ operation._probability.data.fill_(2.0)
+ operation._magnitude.data.fill_(100.0)
+ self.assert_close(operation.probability, torch.full_like(operation.probability, 1.0 - 1e-7), rtol=0, atol=0)
+ self.assert_close(operation.magnitude, torch.full_like(operation.magnitude, 30.0))
+ operation._probability.data.fill_(-1.0)
+ self.assert_close(operation.probability, torch.full_like(operation.probability, 1e-7), rtol=0, atol=0)
+
+ @pytest.mark.parametrize(
+ "probability,expected",
+ [(1.0, [0.375, 0.5, 0.375, 0.25]), (0.5, [0.25, 0.25, 0.375, 0.25])],
+ )
+ def test_convention_operation_soft_blend_respects_the_wrapped_gate(self, probability, expected, device, dtype):
+ # The wrapped p=1 path transforms every row. At p<1 it first keeps gates <=0.5 unchanged,
+ # so the outer blend cannot mix those rows with the transformed image.
+ invert = ops.Invert(initial_probability=probability)
+ image = torch.tensor([0.25, 0.25, 0.75, 0.75], device=device, dtype=dtype).view(4, 1, 1, 1)
+ params = invert.op.forward_parameters(image.shape)
+ params["batch_prob"] = torch.tensor([0.25, 0.5, 0.75, 1.0])
+ self.assert_close(invert(image, params=params).flatten(), image.new_tensor(expected))
+
+ @pytest.mark.device_agnostic
+ def test_wart_policy_sequential_bypasses_operation_wrapper_sampling_4441(self):
+ operation = ops.Rotate(initial_magnitude=3.0, initial_probability=0.5)
+ direct_operation = ops.Rotate(initial_magnitude=3.0, initial_probability=0.5)
+ direct_policy = PolicySequential(direct_operation)
+ shape = torch.Size([4, 1, 8, 6])
+
+ operation._probability.data.fill_(1e-7)
+ direct_operation._probability.data.fill_(1e-7)
+ torch.manual_seed(3)
+ wrapped_params = operation.forward_parameters(shape)
+ torch.manual_seed(3)
+ direct_params = direct_policy.forward_parameters(shape)[0].data
+
+ self.assert_close(wrapped_params["degrees"].abs(), torch.full_like(wrapped_params["degrees"], 3.0))
+ assert not torch.equal(direct_params["degrees"], wrapped_params["degrees"])
+ assert not torch.allclose(direct_params["degrees"].abs(), torch.full_like(direct_params["degrees"], 3.0))
+ self.assert_close(operation.probability, torch.tensor([1e-7]))
+ assert direct_operation.op.p == 0.5
+
+ def test_convention_recorded_params_reproduce_the_sampled_forward(self, device, dtype):
+ if not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("bilinear 2D grid_sample is unavailable for this device and dtype")
+ image = torch.rand(3, 3, 8, 8, device=device, dtype=dtype)
+ for aug in (AutoAugment(), RandAugment(n=2, m=15), TrivialAugment()):
+ for seed in range(4):
+ torch.manual_seed(seed)
+ output = aug(image)
+ self.assert_close(aug(image, params=aug._params), output, rtol=0, atol=0)
+
+ @pytest.mark.device_agnostic
+ def test_convention_randaugment_magnitude_formula(self):
+ aug = RandAugment(n=1, m=3, policy=[[("rotate", -30.0, 30.0)]])
+ degrees = aug.forward_parameters(torch.Size([64, 1, 8, 6]))[0].data[0].data["degrees"]
+ self.assert_close(degrees.abs(), torch.full_like(degrees, 3.0))
+ # A range that does not start at zero separates ``low + (high - low) * m / 30`` from ``high * m / 30``.
+ aug = RandAugment(n=1, m=6, policy=[[("brightness", 0.5, 1.5)]])
+ factor = aug.forward_parameters(torch.Size([8, 3, 8, 6]))[0].data[0].data["brightness_factor"]
+ self.assert_close(factor, torch.full_like(factor, 0.7))
+
+ @pytest.mark.device_agnostic
+ def test_convention_autoaugment_posterize_rounds_its_interval(self):
+ torch.manual_seed(17)
+ aug = AutoAugment(policy=[[("posterize", 1.0, 1)]])
+ bits = aug.forward_parameters(torch.Size([256, 3, 8, 8]))[0].data[0].data["bits_factor"]
+ assert not bits.is_floating_point()
+ assert set(bits.tolist()) == {4, 5} # bin 1 is the interval (4.4, 4.8)
+ # Bin 2 is entirely above 4.5 and below 5.5, so every draw rounds to 5; truncation would return 4 or 5.
+ aug = AutoAugment(policy=[[("posterize", 1.0, 2)]])
+ bits = aug.forward_parameters(torch.Size([256, 3, 8, 8]))[0].data[0].data["bits_factor"]
+ self.assert_close(bits, torch.full_like(bits, 5), rtol=0, atol=0)
+
+ @pytest.mark.device_agnostic
+ def test_wart_randaugment_posterize_and_translate_units_4655(self):
+ image = torch.rand(4, 3, 32, 32)
+ posterize = RandAugment(n=1, m=7, policy=[[("posterize", 0.0, 4)]])
+ output = posterize(image)
+ assert posterize._params[0].data[0].data["bits_factor"].tolist() == [0, 0, 0, 0]
+ self.assert_close(output, torch.zeros_like(image))
+ translate = RandAugment(n=1, m=29, policy=[[("translate_x", -0.5, 0.5)]])
+ pixels = translate.forward_parameters(image.shape)[0].data[0].data["translate_x"]
+ self.assert_close(pixels.abs(), torch.full_like(pixels, 0.5 * 29 / 30))
+
+ @pytest.mark.device_agnostic
+ def test_wart_operation_probability_parameter_is_inert_4656(self):
+ import copy
+
+ gates = []
+ for learned in (1e-7, 1.0 - 1e-7):
+ operation = ops.Invert(initial_probability=0.5)
+ operation._probability.data.fill_(learned)
+ torch.manual_seed(17)
+ batch_prob = operation.forward_parameters(torch.Size([4000, 1, 4, 4]))["batch_prob"]
+ assert set(batch_prob.unique().tolist()) == {0.0, 1.0}
+ assert 1700 < batch_prob.sum() < 2300
+ assert not batch_prob.requires_grad
+ gates.append(batch_prob)
+ self.assert_close(gates[0], gates[1], rtol=0, atol=0)
+ operation = ops.Brightness(initial_magnitude=0.3, initial_probability=0.5)
+ operation(torch.rand(8, 3, 4, 4)).sum().backward()
+ assert operation._probability.grad is None
+ assert operation._magnitude.grad is not None
+ policy = RandAugment(n=2, m=15)
+ copy.deepcopy(policy)
+ policy(torch.rand(2, 3, 8, 8))
+ with pytest.raises(RuntimeError, match="graph leaves"):
+ copy.deepcopy(policy)
+ # A forward is not the only trigger: train() / eval() rebuild the samplers on every policy, used or not,
+ # while AutoAugment and TrivialAugment survive a forward because theirs bypasses the wrapper.
+ for unused in (AutoAugment(), TrivialAugment(), RandAugment(n=2, m=15)):
+ copy.deepcopy(unused)
+ with pytest.raises(RuntimeError, match="graph leaves"):
+ copy.deepcopy(unused.eval())
+ for forwarded in (AutoAugment(), TrivialAugment()):
+ forwarded(torch.rand(2, 3, 8, 8))
+ copy.deepcopy(forwarded)
+
+ @pytest.mark.device_agnostic
+ def test_convention_randaugment_shear_passes_through_the_180_mapping(self):
+ # The wrapper's magnitude mapping is the identity for every default entry but shear and posterize.
+ shear = RandAugment(n=1, m=15, policy=[[("shear_x", -0.3, 0.3)]])
+ drawn = shear.forward_parameters(torch.Size([8, 1, 8, 6]))[0].data[0].data["shear_x"]
+ self.assert_close(drawn.abs(), torch.full_like(drawn, 27.0))
+ # 0.15 is low + (high - low) * m / 30, the value before the mapping.
+ assert not torch.allclose(drawn.abs(), torch.full_like(drawn, 0.15))
+ rotate = RandAugment(n=1, m=15, policy=[[("rotate", -30.0, 30.0)]])
+ degrees = rotate.forward_parameters(torch.Size([8, 1, 8, 6]))[0].data[0].data["degrees"]
+ self.assert_close(degrees.abs(), torch.full_like(degrees, 15.0))
+
+ @pytest.mark.device_agnostic
+ def test_convention_trivialaugment_fixes_candidate_probability_at_one(self):
+ aug = TrivialAugment(policy=[[("rotate", -30.0, 30.0)], [("brightness", 0.1, 1.9)]])
+ assert {(module[0].op.p, module[0].op.p_batch) for _, module in aug.named_children()} == {(1.0, 1.0)}
+ # "Each candidate": every entry of the default policy as well, not only the two above.
+ defaults = [(module[0].op.p, module[0].op.p_batch) for _, module in TrivialAugment().named_children()]
+ assert len(defaults) == 12 and set(defaults) == {(1.0, 1.0)}
+ gates = set()
+ for _ in range(16):
+ gates.update(aug.forward_parameters(torch.Size([8, 3, 8, 6]))[0].data[0].data["batch_prob"].tolist())
+ assert gates == {1.0}
+ # Only the magnitude is drawn per row.
+ torch.manual_seed(17)
+ magnitudes = (
+ TrivialAugment(policy=[[("rotate", -30.0, 30.0)]])
+ .forward_parameters(torch.Size([8, 1, 8, 6]))[0]
+ .data[0]
+ .data["degrees"]
+ )
+ assert magnitudes.unique().numel() == 8
+
+ @pytest.mark.device_agnostic
+ def test_wart_trivialaugment_shear_bypass_drops_the_180_factor_4441(self):
+ torch.manual_seed(17)
+ bypassed = (
+ TrivialAugment(policy=[[("shear_x", -0.3, 0.3)]])
+ .forward_parameters(torch.Size([64, 1, 8, 6]))[0]
+ .data[0]
+ .data["shear_x"]
+ )
+ assert bool((bypassed.abs() <= 0.3).all()) and bypassed.abs().max() > 0.05
+ # The same policy entry through RandAugment, which does apply the mapping.
+ mapped = (
+ RandAugment(n=1, m=29, policy=[[("shear_x", -0.3, 0.3)]])
+ .forward_parameters(torch.Size([8, 1, 8, 6]))[0]
+ .data[0]
+ .data["shear_x"]
+ )
+ self.assert_close(mapped.abs(), torch.full_like(mapped, 0.29 * 180))
+
+ @pytest.mark.device_agnostic
+ def test_wart_operation_wrappers_cannot_be_pickled_4469(self):
+ import pickle
+
+ failed = set()
+ for name in ops.__all__:
+ operation = getattr(ops, name)()
+ pickle.loads(pickle.dumps(operation.op)) # noqa: S301 - the wrapped augmentation always pickles
+ try:
+ pickle.loads(pickle.dumps(operation)) # noqa: S301
+ except AttributeError:
+ failed.add(name)
+ # With default arguments only Posterize avoids a local closure: it passes a named mapping and no sign flip.
+ assert failed == set(ops.__all__) - {"Posterize"}
+ # It is the configuration, not the class: ShearX / ShearY pass a named mapping too, and pickle without
+ # the sign flip, while the sign flip makes Posterize unpicklable.
+ for operation in (ops.ShearX(symmetric_megnitude=False), ops.ShearY(symmetric_megnitude=False)):
+ pickle.loads(pickle.dumps(operation)) # noqa: S301
+ with pytest.raises(AttributeError, match="local object"):
+ pickle.dumps(ops.Posterize(symmetric_megnitude=True))
+ with pytest.raises(AttributeError, match="local object"):
+ pickle.dumps(ops.Rotate(symmetric_megnitude=False)) # no named mapping: the identity closure
+
+ @pytest.mark.device_agnostic
+ def test_convention_operation_keeps_its_initial_probability(self):
+ # Every other probability pin overwrites `_probability` before reading it back.
+ operation = ops.Invert(initial_probability=0.25)
+ self.assert_close(operation.probability.detach(), torch.tensor([0.25]), rtol=0, atol=0)
+
+ @pytest.mark.device_agnostic
+ def test_convention_policy_sequential_sequence_follows_supplied_params(self):
+ # The supplied-path pin measures forward outputs, which index by name and so route around
+ # get_forward_sequence; get_transformation_matrix zips against it and does not.
+ policy = PolicySequential(
+ ops.Invert(initial_probability=1.0), ops.Solarize(initial_magnitude=0.5, initial_probability=1.0)
+ )
+ generated = policy.forward_parameters(torch.Size([1, 1, 1, 1]))
+ reversed_names = [name for name, _ in policy.get_forward_sequence(list(reversed(generated)))]
+ assert reversed_names == [param.name for param in reversed(generated)]
+ assert [name for name, _ in policy.get_forward_sequence(generated[:1])] == [generated[0].name]
+
+ @pytest.mark.device_agnostic
+ def test_convention_rigid_matrix_mode_accepts_intensity_operations(self):
+ # "rigid" rejects non-rigid modules in other containers; a policy has none, since every wrapper has a matrix.
+ image = torch.rand(2, 3, 8, 6)
+ for mode in ("silence", "rigid"):
+ intensity = AutoAugment(policy=[[("invert", 1.0, None)]], transformation_matrix_mode=mode)
+ intensity(image)
+ self.assert_close(intensity.transform_matrix, torch.eye(3).expand(2, 3, 3))
+ mixed = AutoAugment(policy=[[("rotate", 1.0, 9), ("invert", 1.0, None)]], transformation_matrix_mode=mode)
+ mixed(image)
+ assert not torch.allclose(mixed.transform_matrix, torch.eye(3).expand(2, 3, 3))
+
+ @pytest.mark.device_agnostic
+ def test_convention_policy_sequential_takes_operations_positionally(self):
+ operations = [ops.Invert(initial_probability=1.0), ops.Solarize(initial_magnitude=0.5, initial_probability=1.0)]
+ assert len(PolicySequential(*operations)) == 2
+ with pytest.raises(ValueError, match="must be Kornia Operations"):
+ PolicySequential(operations)
+
+ @pytest.mark.device_agnostic
+ def test_convention_randaugment_formula_holds_for_every_default_entry(self):
+ # "The identity for every default entry except three": the whole default policy, not a sample of it.
+ import math
+
+ from kornia.augmentation.auto.rand_augment.rand_augment import default_policy
+
+ checked = []
+ for subpolicy in default_policy:
+ name = subpolicy[0][0]
+ aug = RandAugment(n=1, m=10, policy=[subpolicy])
+ operation = aug[0][0]
+ if operation._factor_name is None:
+ continue # auto_contrast, equalize and invert carry no magnitude
+ low, high = (float(bound) for bound in operation.magnitude_range)
+ expected = low + (high - low) * 10 / 30
+ if name in ("shear_x", "shear_y"):
+ expected *= 180
+ elif name == "posterize":
+ expected = math.floor(expected) # 4 * 10 / 30 = 1.33 -> 1 bit: truncation, not rounding
+ drawn = aug.forward_parameters(torch.Size([8, 1, 8, 6]))[0].data[0].data[operation._factor_name]
+ self.assert_close(drawn.abs().float(), torch.full((8,), float(expected)))
+ checked.append(name)
+ assert len(checked) == 12 and {"shear_x", "shear_y", "posterize", "translate_x", "translate_y"} <= set(checked)
diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.py
new file mode 100644
index 000000000..dacdebe19
--- /dev/null
+++ b/tests/augmentation/test_conventions_mix.py
@@ -0,0 +1,601 @@
+# 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
+
+import warnings
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+from kornia.constants import DType
+
+from testing.base import BaseTester
+
+
+def _label_dtype(image_dtype: torch.dtype) -> torch.dtype:
+ # Half-precision images return float32 labels, so that integer class ids are not rounded.
+ return image_dtype if image_dtype in (torch.float32, torch.float64) else torch.float32
+
+
+class TestMixConventions(BaseTester):
+ def test_convention_mix_base_has_no_matrix_or_inverse(self):
+ aug = K.RandomMixUpV2()
+ with pytest.raises(RuntimeError, match="Transformation matrices"):
+ _ = aug.transform_matrix
+ with pytest.raises(RuntimeError, match="Inverse"):
+ aug.inverse()
+
+ @pytest.mark.parametrize(
+ ("factory", "shape"),
+ [
+ (lambda: K.RandomMixUpV2(p=1.0), (2, 3, 8, 12)),
+ (lambda: K.RandomCutMixV2(p=1.0, use_correct_lambda=True), (2, 3, 8, 12)),
+ (lambda: K.PatchMix(p=1.0, patch_size=2), (2, 3, 8, 12)),
+ (lambda: K.RandomJigsaw(p=1.0, grid=(2, 3)), (2, 3, 8, 12)),
+ (lambda: K.RandomMosaic(p=1.0), (2, 3, 8, 12)),
+ ],
+ )
+ def test_convention_image_rank_is_promoted_and_keepdim_restores_it(self, factory, shape, device, dtype):
+ # MixAugmentationBaseV2 accepts CHW images, forwards an NCHW batch to the operation, and the same
+ # operation restores CHW only when keepdim=True. The Jigsaw dimensions divide its 2x3 grid exactly.
+ for input_shape, batch_shape in ((shape[2:], (1, 1, *shape[2:])), (shape[1:], (1, *shape[1:])), (shape, shape)):
+ image = torch.rand(input_shape, device=device, dtype=dtype)
+ torch.manual_seed(7)
+ assert factory()(image).shape == batch_shape
+ aug = factory()
+ aug.keepdim = True
+ torch.manual_seed(7)
+ assert aug(image).shape == input_shape
+
+ def test_convention_mixup_class_rows_describe_the_image_mix(self, device, dtype):
+ image = torch.stack(
+ [torch.full((1, 4, 4), value, device=device, dtype=dtype) for value in (0.0, 1.0, 2.0, 3.0)]
+ )
+ labels = torch.tensor([4, 9, 12, 15], device=device)
+ aug = K.RandomMixUpV2(lambda_val=(0.25, 0.25), p=1.0, data_keys=["input", "class"])
+ aug(image, labels)
+ params = dict(aug._params)
+ # This is neither identity nor a one-row batch roll, so the recorded pairing is observable.
+ params["mixup_pairs"] = torch.tensor([2, 0, 3, 1])
+ output, mixed_labels = aug(image, labels, params=params)
+
+ # Build the oracle from the literal set above, not from aug._params: forward() stores the supplied
+ # dict by reference, so reading it back cannot tell whether the pairing was honoured.
+ pairs = torch.tensor([2, 0, 3, 1], device=device)
+ expected = image * 0.75 + image.index_select(0, pairs) * 0.25
+ self.assert_close(output, expected)
+ assert mixed_labels.shape == (4, 3)
+ label_dtype = _label_dtype(dtype)
+ assert output.dtype == dtype and mixed_labels.dtype == label_dtype
+ self.assert_close(mixed_labels[:, 0], labels.to(label_dtype))
+ self.assert_close(mixed_labels[:, 1], labels.index_select(0, pairs).to(label_dtype))
+ self.assert_close(mixed_labels[:, 2], torch.full((4,), 0.25, device=device, dtype=label_dtype))
+
+ @pytest.mark.parametrize("num_mix", [1, 2])
+ def test_convention_cutmix_class_axis_is_num_mix_then_batch(self, num_mix, device, dtype):
+ image = torch.stack(
+ [torch.arange(42, device=device, dtype=dtype).reshape(1, 6, 7) + 100 * row for row in range(3)]
+ )
+ labels = torch.tensor([2, 5, 7], device=device)
+ aug = K.RandomCutMixV2(num_mix=num_mix, p=1.0, data_keys=["input", "class"], use_correct_lambda=True)
+ aug(image, labels)
+ params = dict(aug._params)
+ params["mix_pairs"] = torch.tensor([[1, 2, 0], [2, 0, 1]])[:num_mix]
+ # The two rectangles have unequal x/y starts and dimensions. They also do not overlap, so num_mix=2
+ # checks both donor/crop stages independently.
+ params["crop_src"] = image.new_tensor(
+ [
+ [[[1, 2], [3, 2], [3, 3], [1, 3]], [[1, 2], [3, 2], [3, 3], [1, 3]], [[1, 2], [3, 2], [3, 3], [1, 3]]],
+ [[[4, 0], [5, 0], [5, 2], [4, 2]], [[4, 0], [5, 0], [5, 2], [4, 2]], [[4, 0], [5, 0], [5, 2], [4, 2]]],
+ ]
+ )[:num_mix]
+ params["image_shape"] = image.new_tensor([6, 7])
+ params["dtype"] = torch.tensor(DType.get(dtype).value)
+ output, mixed_labels = aug(image, labels, params=params)
+
+ expected = image.clone()
+ expected[:, :, 2:4, 1:4] = image[torch.tensor([1, 2, 0], device=device), :, 2:4, 1:4]
+ if num_mix == 2:
+ expected[:, :, 0:3, 4:6] = image[torch.tensor([2, 0, 1], device=device), :, 0:3, 4:6]
+ self.assert_close(output, expected)
+
+ assert mixed_labels.shape == (num_mix, 3, 3)
+ label_dtype = _label_dtype(dtype)
+ assert output.dtype == dtype and mixed_labels.dtype == label_dtype
+ self.assert_close(mixed_labels[:, :, 0], labels.to(label_dtype).expand(num_mix, -1))
+ for mix, pairs in enumerate(aug._params["mix_pairs"].to(device)):
+ self.assert_close(mixed_labels[mix, :, 1], labels.index_select(0, pairs).to(label_dtype))
+ expected_lambdas = torch.tensor([1 - 6 / 42, 1 - 6 / 42], device=device, dtype=label_dtype)[:num_mix]
+ self.assert_close(mixed_labels[:, :, 2], expected_lambdas[:, None].expand(-1, 3))
+
+ @pytest.mark.parametrize(("use_correct_lambda", "expected_lambda"), [(False, 0.25), (True, 0.75)])
+ def test_convention_cutmix_lambda_is_the_configured_area_fraction(
+ self, use_correct_lambda, expected_lambda, device, dtype
+ ):
+ image = torch.zeros(2, 1, 4, 4, device=device, dtype=dtype)
+ labels = torch.tensor([2, 5], device=device)
+ crop = torch.tensor([[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]])
+ params = {
+ "batch_prob": torch.ones(2),
+ "mix_pairs": torch.tensor([[1, 0]]),
+ "crop_src": crop.repeat(1, 2, 1, 1),
+ "image_shape": torch.tensor([4, 4]),
+ "dtype": torch.tensor(DType.get(dtype).value),
+ }
+ aug = K.RandomCutMixV2(data_keys=["input", "class"], use_correct_lambda=use_correct_lambda)
+ _, mixed_labels = aug(image, labels, params=params)
+
+ expected = torch.full((2,), expected_lambda, device=device, dtype=_label_dtype(dtype))
+ self.assert_close(mixed_labels[0, :, 2], expected)
+
+ @pytest.mark.parametrize(
+ ("factory", "label_shape"),
+ [
+ (lambda: K.RandomMixUpV2(p=0.0, data_keys=["input", "class"]), (3, 3)),
+ (lambda: K.RandomCutMixV2(p=0.0, data_keys=["input", "class"], use_correct_lambda=True), (1, 3, 3)),
+ ],
+ )
+ def test_convention_mix_class_batch_gate_returns_identity_labels(self, factory, label_shape, device, dtype):
+ image = torch.rand(3, 1, 8, 8, device=device, dtype=dtype)
+ labels = torch.tensor([2, 5, 7], device=device)
+ output, mixed_labels = factory()(image, labels)
+
+ self.assert_close(output, image)
+ assert mixed_labels.shape == label_shape
+ label_dtype = _label_dtype(dtype)
+ expected_labels = labels.to(label_dtype).expand(label_shape[:-1])
+ self.assert_close(mixed_labels[..., 0], expected_labels)
+ self.assert_close(mixed_labels[..., 1], expected_labels)
+ self.assert_close(mixed_labels[..., 2], torch.zeros(label_shape[:-1], device=device, dtype=label_dtype))
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ "factory",
+ [
+ lambda: K.RandomMixUpV2(p=0.5),
+ lambda: K.RandomCutMixV2(p=0.5, use_correct_lambda=True),
+ lambda: K.PatchMix(p=0.5, patch_size=2),
+ ],
+ )
+ def test_convention_mix_batch_gate_is_all_or_nothing(self, factory):
+ # An invariant, not a statistic: a batch-wide gate never selects a strict subset of the rows.
+ aug = factory()
+ for _ in range(20):
+ batch_prob = aug.forward_parameters(torch.Size([8, 1, 8, 8]))["batch_prob"]
+ assert batch_prob.numel() == 8
+ assert bool((batch_prob == batch_prob[0]).all())
+
+ def test_convention_per_sample_gate_keeps_unselected_rows(self, device, dtype):
+ image = torch.arange(32, device=device, dtype=dtype).reshape(2, 1, 4, 4)
+ params = {"batch_prob": torch.tensor([1.0, 0.0]), "permutation": torch.tensor([[3, 2, 1, 0], [3, 2, 1, 0]])}
+ output = K.RandomJigsaw(grid=(2, 2), p=0.5)(image, params=params)
+ assert not torch.equal(output[0], image[0])
+ self.assert_close(output[1], image[1])
+
+ def test_convention_jigsaw_same_on_batch_shares_the_patch_permutation(self, device, dtype):
+ image = torch.rand(3, 1, 8, 12, device=device, dtype=dtype)
+ aug = K.RandomJigsaw(grid=(2, 3), p=1.0, same_on_batch=True)
+ aug(image)
+
+ permutation = aug._params["permutation"]
+ assert torch.equal(permutation, permutation[0].expand_as(permutation))
+
+ def test_convention_jigsaw_permutation_is_laid_out_by_columns(self, device, dtype):
+ image = torch.zeros(1, 1, 4, 4, device=device, dtype=dtype)
+ image[:, :, :2, :2] = 1
+ image[:, :, :2, 2:] = 2
+ image[:, :, 2:, :2] = 3
+ image[:, :, 2:, 2:] = 4
+ # The second row carries different values and a different permutation: each image is partitioned from
+ # its own pieces, never from another row's.
+ image = torch.cat([image, image + 10])
+ params = {"batch_prob": torch.ones(2), "permutation": torch.tensor([[3, 2, 1, 0], [1, 0, 3, 2]])}
+ output = K.RandomJigsaw(grid=(2, 2), p=1.0)(image, params=params)
+
+ expected = torch.tensor(
+ [
+ [[[4, 4, 2, 2], [4, 4, 2, 2], [3, 3, 1, 1], [3, 3, 1, 1]]],
+ [[[12, 12, 14, 14], [12, 12, 14, 14], [11, 11, 13, 13], [11, 11, 13, 13]]],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(output, expected)
+
+ def test_convention_mosaic_uses_height_width_and_xy_start_ratio(self, device, dtype):
+ image = torch.rand(3, 1, 6, 8, device=device, dtype=dtype)
+ aug = K.RandomMosaic(output_size=(4, 10), start_ratio_range=(0.5, 0.5), p=1.0)
+ output = aug(image)
+
+ assert output.shape == (3, 1, 4, 10)
+ top_left = aug._params["src"][0, 0]
+ self.assert_close(top_left, torch.tensor([4.0, 3.0], device=top_left.device, dtype=top_left.dtype))
+
+ def test_convention_mosaic_grid_first_axis_is_width(self, device, dtype):
+ image = torch.arange(6, device=device, dtype=dtype).view(6, 1, 1, 1).expand(6, 1, 6, 4)
+ aug = K.RandomMosaic(mosaic_grid=(2, 3), start_ratio_range=(0.5, 0.5), p=1.0)
+ params = aug.forward_parameters(image.shape)
+ params["permutation"] = torch.arange(6).expand(6, -1)
+ output = aug(image, params=params)
+
+ # Cropping from (x, y)=(2, 3) crosses the four tiles at the top-left of the 3-row, 2-column grid.
+ expected = image.new_tensor([[0, 0, 3, 3]] * 3 + [[1, 1, 4, 4]] * 3)
+ self.assert_close(output, expected.expand(6, 1, 6, 4))
+
+ def test_convention_mosaic_uses_each_output_row_permutation(self, device, dtype):
+ image = torch.arange(4, device=device, dtype=dtype).reshape(4, 1, 1, 1).expand(4, 1, 4, 4)
+ aug = K.RandomMosaic(start_ratio_range=(0.5, 0.5), p=1.0)
+ params = aug.forward_parameters(image.shape)
+ params["batch_prob"] = torch.ones(4)
+ params["permutation"] = torch.tensor([[0, 1, 2, 3], [1, 0, 3, 2], [2, 3, 0, 1], [3, 2, 1, 0]])
+ output = aug(image, params=params)
+
+ expected = image.new_tensor(
+ [
+ [[0, 0, 2, 2], [0, 0, 2, 2], [1, 1, 3, 3], [1, 1, 3, 3]],
+ [[1, 1, 3, 3], [1, 1, 3, 3], [0, 0, 2, 2], [0, 0, 2, 2]],
+ [[2, 2, 0, 0], [2, 2, 0, 0], [3, 3, 1, 1], [3, 3, 1, 1]],
+ [[3, 3, 1, 1], [3, 3, 1, 1], [2, 2, 0, 0], [2, 2, 0, 0]],
+ ]
+ ).unsqueeze(1)
+ self.assert_close(output, expected)
+
+ @pytest.mark.parametrize("data_key", ["bbox", "bbox_xyxy", "bbox_xywh"])
+ def test_convention_mosaic_supports_each_documented_box_key(self, data_key, device, dtype):
+ image = torch.rand(4, 1, 6, 8, device=device, dtype=dtype)
+ if data_key == "bbox":
+ boxes = image.new_tensor([[[[1, 1], [7, 1], [7, 5], [1, 5]]]] * 4)
+ expected = image.new_tensor(
+ [
+ [[0, 0], [3, 0], [3, 2], [0, 2]],
+ [[0, 4], [3, 4], [3, 6], [0, 6]],
+ [[5, 0], [8, 0], [8, 2], [5, 2]],
+ [[5, 4], [8, 4], [8, 6], [5, 6]],
+ ]
+ )
+ elif data_key == "bbox_xyxy":
+ boxes = image.new_tensor([[[1, 1, 7, 5]]] * 4)
+ expected = image.new_tensor([[0, 0, 3, 2], [0, 4, 3, 6], [5, 0, 8, 2], [5, 4, 8, 6]])
+ else:
+ boxes = image.new_tensor([[[1, 1, 6, 4]]] * 4)
+ expected = image.new_tensor([[0, 0, 3, 2], [0, 4, 3, 2], [5, 0, 3, 2], [5, 4, 3, 2]])
+ # The crop starts at (4, 3); translate each tile's box and clip to the 8x6 output.
+ output, output_boxes = K.RandomMosaic(start_ratio_range=(0.5, 0.5), p=1.0, data_keys=["input", data_key])(
+ image, boxes
+ )
+
+ assert output.shape == image.shape
+ self.assert_close(output_boxes, expected.unsqueeze(0).expand(4, *expected.shape))
+
+ @pytest.mark.parametrize(
+ ("factory", "extra", "error"),
+ [
+ (lambda: K.RandomMixUpV2(p=1.0), "mask", NotImplementedError),
+ (lambda: K.RandomCutMixV2(p=1.0, use_correct_lambda=True), "mask", NotImplementedError),
+ (lambda: K.PatchMix(p=1.0, patch_size=2), "class", NotImplementedError),
+ (lambda: K.RandomJigsaw(p=1.0, grid=(2, 2)), "class", NotImplementedError),
+ (lambda: K.RandomMosaic(p=1.0), "mask", NotImplementedError),
+ ],
+ )
+ def test_convention_unsupported_data_keys_raise(self, factory, extra, error, device, dtype):
+ image = torch.rand(2, 1, 8, 8, device=device, dtype=dtype)
+ annotation = torch.ones_like(image) if extra == "mask" else torch.tensor([0, 1], device=device)
+ with pytest.raises(error):
+ factory()(image, annotation, data_keys=["input", extra])
+
+ def test_convention_patchmix_lam_does_not_weight_the_replacement(self, device, dtype):
+ # The generator records a Beta sample as `lam`, but PatchMix copies a full square patch. The fixed
+ # coordinates and permutation make the written pixels independent of that recorded value.
+ image = torch.stack(
+ [torch.arange(35, device=device, dtype=dtype).reshape(1, 5, 7) + 100 * row for row in range(3)]
+ )
+ aug = K.PatchMix(patch_size=2, p=1.0)
+ params = {
+ "batch_prob": torch.ones(3),
+ "mix_pairs": torch.tensor([2, 0, 1]),
+ "patch_coords": torch.tensor([[0, 2], [3, 0], [1, 1]]),
+ "lam": torch.tensor([0.125, 0.5, 0.875]),
+ "dtype": torch.tensor(DType.get(dtype).value),
+ }
+ output = aug(image, params=params)
+
+ expected = image.clone()
+ expected[0, :, 2:4, 0:2] = image[2, :, 2:4, 0:2]
+ expected[1, :, 0:2, 3:5] = image[0, :, 0:2, 3:5]
+ expected[2, :, 1:3, 1:3] = image[1, :, 1:3, 1:3]
+ self.assert_close(output, expected)
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("dtype", [torch.uint8, torch.int64])
+ def test_convention_mix_rejects_integer_images(self, dtype):
+ with pytest.raises(TypeError, match="float16"):
+ K.RandomMixUpV2(p=1.0)(torch.ones(2, 1, 4, 4, dtype=dtype))
+
+ @pytest.mark.device_agnostic
+ def test_convention_mix_inverse_is_keyword_only(self):
+ with pytest.raises(TypeError, match="positional"):
+ K.RandomMixUpV2().inverse(torch.ones(2, 1, 4, 4))
+
+ @pytest.mark.device_agnostic
+ def test_convention_jigsaw_same_on_batch_shares_the_gate(self):
+ aug = K.RandomJigsaw(grid=(2, 2), p=0.5, same_on_batch=True)
+ for _ in range(20):
+ batch_prob = aug.forward_parameters(torch.Size([8, 1, 4, 4]))["batch_prob"]
+ assert bool((batch_prob == batch_prob[0]).all())
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ @pytest.mark.parametrize(
+ ("factory", "supported", "class_error"),
+ [
+ (lambda p: K.RandomMixUpV2(p=p), {"class"}, NotImplementedError),
+ (lambda p: K.RandomCutMixV2(p=p, use_correct_lambda=True), {"class"}, NotImplementedError),
+ (lambda p: K.RandomJigsaw(grid=(2, 2), p=p), set(), NotImplementedError),
+ (lambda p: K.PatchMix(patch_size=4, p=p), set(), NotImplementedError),
+ (lambda p: K.RandomMosaic(p=p), {"bbox_xyxy"}, RuntimeError),
+ ],
+ )
+ def test_convention_unsupported_key_raises_whatever_the_gate(self, factory, supported, class_error, p):
+ # Fixed by #4676: these used to pass through silently whenever the gate selected no sample (#4651).
+ image = torch.rand(4, 1, 8, 8)
+ annotations = {
+ "bbox_xyxy": torch.tensor([[[1.0, 1.0, 4.0, 4.0]]] * 4),
+ "keypoints": torch.rand(4, 2, 2),
+ "mask": torch.ones_like(image),
+ "class": torch.arange(4),
+ }
+ for key, annotation in annotations.items():
+ if key in supported:
+ factory(p)(image, annotation, data_keys=["input", key])
+ continue
+ # `None` rather than "": MixAugmentationBaseV2._validate_data_key raises a bare
+ # NotImplementedError, so there is no message to match on that half.
+ message = "does not support" if key == "class" and class_error is RuntimeError else None
+ state = torch.get_rng_state().clone()
+ with pytest.raises(class_error if key == "class" else NotImplementedError, match=message):
+ factory(p)(image, annotation, data_keys=["input", key])
+ # "Before anything is sampled": a handler fallback raises the same bare error, but only after the draw.
+ assert torch.equal(state, torch.get_rng_state())
+
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ def test_convention_jigsaw_rejects_a_nondivisible_input_whatever_the_gate(self, p, device, dtype):
+ # Fixed by #4676: (1, 3, 3, 4) with grid=(2, 2) used to come back as (1, 2, 3, 4), and p=0 returned the input.
+ for shape, grid in (((1, 3, 3, 4), (2, 2)), ((2, 1, 9, 13), (2, 3)), ((2, 1, 8, 13), (2, 3))):
+ image = torch.rand(shape, device=device, dtype=dtype)
+ with pytest.raises(RuntimeError, match="must be divisible by grid"):
+ K.RandomJigsaw(grid=grid, p=p)(image)
+
+ @pytest.mark.device_agnostic
+ def test_convention_mix_class_handlers_ignore_a_replayed_partial_gate(self):
+ image = torch.arange(3.0).view(3, 1, 1, 1).expand(3, 1, 4, 4).clone()
+ labels = torch.tensor([10, 20, 30])
+ aug = K.RandomMixUpV2(p=1.0, lambda_val=(0.25, 0.25), data_keys=["input", "class"])
+ aug(image, labels)
+ params = dict(aug._params)
+ params["mixup_pairs"] = torch.tensor([1, 2, 0])
+ params["batch_prob"] = torch.tensor([1.0, 0.0, 1.0])
+ output, mixed = aug(image, labels, params=params)
+ self.assert_close(output[:, 0, 0, 0], torch.tensor([0.25, 1.0, 1.5])) # row 1 keeps its image
+ self.assert_close(mixed, torch.tensor([[10.0, 20.0, 0.25], [20.0, 30.0, 0.25], [30.0, 10.0, 0.25]]))
+
+ @pytest.mark.device_agnostic
+ def test_convention_cutmix_compatibility_lambda_warns(self):
+ with pytest.warns(DeprecationWarning, match="use_correct_lambda"):
+ K.RandomCutMixV2()
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ K.RandomCutMixV2(use_correct_lambda=True)
+
+ @pytest.mark.device_agnostic
+ def test_wart_mixup_and_cutmix_apply_p_to_rows_a_second_time_4649(self):
+ # #4649: inside a selected batch, rows are dropped again with probability 1 - p.
+ mixup = K.RandomMixUpV2(p=0.5, lambda_val=(0.5, 0.5))
+ cutmix = K.RandomCutMixV2(p=0.5, cut_size=(0.5, 0.5), use_correct_lambda=True)
+ image = torch.rand(8, 1, 8, 8)
+ mixup_rows, cutmix_rows = [], []
+ for seed in range(40):
+ torch.manual_seed(seed)
+ params = mixup.forward_parameters(image.shape)
+ if params["batch_prob"].all():
+ mixup_rows.append(params["mixup_lambdas"] > 0)
+ output = cutmix(image)
+ if cutmix._params["batch_prob"].all():
+ cutmix_rows.append((output != image).flatten(1).any(1))
+ for rows in (torch.cat(mixup_rows), torch.cat(cutmix_rows)):
+ assert rows.numel() >= 64
+ assert 0.3 < rows.float().mean() < 0.7
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ def test_convention_patchmix_rejects_a_patch_larger_than_the_image(self, p):
+ # Fixed by #4680: the default patch_size=16 used to draw negative corners on this image (#4650).
+ image = torch.rand(4, 1, 8, 10)
+ for patch_size in (9, 16):
+ with pytest.raises(ValueError, match="`patch_size` to fit the input"):
+ K.PatchMix(patch_size=patch_size, p=p)(image)
+ assert K.PatchMix(patch_size=8, p=p)(image).shape == image.shape # min(H, W) itself is accepted
+
+ @pytest.mark.device_agnostic
+ def test_convention_patchmix_same_on_batch_shares_the_patch_but_not_the_pairing(self):
+ # Fixed by #4680: a shared pairing draw used to argsort to the identity, so every image patched itself.
+ # Each donor's pixel value is its batch index, providing an oracle independent of patch-copy slicing.
+ image = torch.arange(64, dtype=torch.float32).reshape(64, 1, 1, 1).expand(-1, 1, 8, 10).clone()
+ aug = K.PatchMix(patch_size=4, p=1.0, same_on_batch=True)
+ output = aug(image)
+ pairs = aug._params["mix_pairs"]
+ assert torch.equal(pairs.sort().values, torch.arange(64))
+ assert not torch.equal(pairs, torch.arange(64))
+ coords = aug._params["patch_coords"]
+ assert bool((coords == coords[0]).all())
+ x, y = (int(value) for value in coords[0])
+ expected = image.clone()
+ expected[:, :, y : y + 4, x : x + 4] = pairs.to(image)[:, None, None, None]
+ self.assert_close(output, expected, rtol=0, atol=0)
+ # Without same_on_batch the coordinate is per sample as well.
+ independent = K.PatchMix(patch_size=4, p=1.0)
+ independent(image)
+ assert independent._params["patch_coords"].unique(dim=0).shape[0] > 1
+
+ @pytest.mark.device_agnostic
+ def test_wart_mosaic_output_size_boxes_and_resample_default_4652(self):
+ image = torch.rand(4, 1, 6, 8)
+ boxes = torch.tensor([[[1.0, 1.0, 4.0, 4.0]]] * 4)
+ assert K.RandomMosaic(output_size=(4, 10), p=0.0)(image).shape == (4, 1, 4, 10)
+ # Replay one recorded draw under both settings, with a hand-set gate that selects rows 1 and 3 only.
+ reference = K.RandomMosaic(p=1.0, data_keys=["input", "bbox_xyxy"])
+ reference(image, boxes)
+ params = dict(reference._params)
+ params["batch_prob"] = torch.tensor([0.0, 1.0, 0.0, 1.0])
+ selected = params["batch_prob"] > 0
+ results = [
+ K.RandomMosaic(output_size=output_size, p=1.0, data_keys=["input", "bbox_xyxy"])(
+ image, boxes, params=params
+ )
+ for output_size in (None, (4, 10))
+ ]
+ assert results[0][0].shape == (4, 1, 6, 8) and results[1][0].shape == (4, 1, 4, 10)
+ self.assert_close(results[0][1], results[1][1]) # the boxes ignore output_size
+ assert results[1][1][selected][..., 3].max() > 4 # a box bottom below the 4-pixel-high output
+ placeholder = torch.tensor([[1.0, 1.0, 4.0, 4.0]] + [[0.0, 0.0, 1.0, 1.0]] * 3)
+ self.assert_close(results[1][1][~selected], placeholder.expand(2, -1, -1))
+ # An unselected row keeps its image, yet its own boxes are clipped to the input extent and dropped to the
+ # placeholder below min_bbox_size.
+ loose = torch.tensor([[[2.0, 1.0, 30.0, 20.0], [1.0, 1.0, 5.0, 6.0]]] * 4)
+ strict = K.RandomMosaic(p=1.0, min_bbox_size=19.0, data_keys=["input", "bbox_xyxy"])
+ output, filtered = strict(image, loose, params=params)
+ self.assert_close(output[~selected], image[~selected])
+ own = torch.tensor([[2.0, 1.0, 8.0, 6.0], [0.0, 0.0, 1.0, 1.0]]) # clipped to W=8, H=6; the small one dropped
+ self.assert_close(filtered[~selected][:, :2], own.expand(2, -1, -1))
+ with pytest.raises(TypeError, match="NoneType"):
+ K.RandomMosaic(p=1.0, cropping_mode="resample")(image)
+ self.assert_close(K.RandomMosaic(p=0.0, cropping_mode="resample")(image), image) # no selection, no raise
+
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("image_dtype", [torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("p", [0.0, 1.0])
+ def test_convention_mix_labels_stay_exact_for_half_precision_images(self, image_dtype, p):
+ # Fixed by #4661: labels used to be cast to the image dtype, so bfloat16 returned [256, 1000] here (#4657).
+ image = torch.rand(2, 1, 4, 4, dtype=image_dtype)
+ labels = torch.tensor([257, 999])
+ cases = (
+ (K.RandomMixUpV2(p=p), "mixup_pairs", torch.tensor([1, 0])),
+ (K.RandomCutMixV2(p=p, use_correct_lambda=True), "mix_pairs", torch.tensor([[1, 0]])),
+ )
+ for aug, key, swapped in cases:
+ # Supply the swap: with a sampled pairing both columns can legitimately hold [257, 999], and then
+ # nothing shows that the paired label was used, let alone kept exact.
+ aug(image, labels, data_keys=["input", "class"])
+ params = dict(aug._params)
+ params[key] = swapped
+ output, mixed = aug(image, labels, params=params, data_keys=["input", "class"])
+ assert output.dtype == image_dtype and mixed.dtype == torch.float32
+ assert mixed[..., 0].flatten().tolist() == [257.0, 999.0]
+ assert mixed[..., 1].flatten().tolist() == ([999.0, 257.0] if p == 1.0 else [257.0, 999.0])
+
+ def test_convention_jigsaw_identity_permutation_transposes_the_grid(self, device, dtype):
+ # The destination cell is chosen column-major by an entry's position; the entry's value indexes the
+ # source patch row-major. The two orders differ, so the identity permutation is not a no-op.
+ image = torch.tensor([[[[0.0, 1.0], [2.0, 3.0]]]], device=device, dtype=dtype)
+ params = {"batch_prob": torch.ones(1), "permutation": torch.tensor([[0, 1, 2, 3]])}
+ self.assert_close(K.RandomJigsaw(grid=(2, 2), p=1.0)(image, params=params), image.transpose(-1, -2))
+ params["permutation"] = torch.tensor([[0, 2, 1, 3]])
+ self.assert_close(K.RandomJigsaw(grid=(2, 2), p=1.0)(image, params=params), image)
+ # Every permutation above is its own inverse, so "the value indexes the source" and "the value indexes
+ # the destination" agree on all of them. A 3-cycle tells them apart.
+ strip = torch.arange(6, device=device, dtype=dtype).view(1, 1, 2, 3)
+ params["permutation"] = torch.tensor([[1, 2, 0, 3, 4, 5]])
+ cycled = K.RandomJigsaw(grid=(2, 3), p=1.0)(strip, params=params)
+ assert cycled[0, 0].tolist() == [[1.0, 0.0, 4.0], [2.0, 3.0, 5.0]]
+ # "Transposes" is the square case. On any grid the image-preserving permutation is the transposed index
+ # grid, and the identity permutation reproduces the image only when the grid has a single row or column.
+ for grid in ((2, 3), (3, 2), (1, 3), (3, 1)):
+ cells = torch.arange(grid[0] * grid[1], device=device, dtype=dtype).view(grid)
+ picture = cells.repeat_interleave(2, 0).repeat_interleave(2, 1)[None, None]
+ aug = K.RandomJigsaw(grid=grid, p=1.0)
+ params["permutation"] = torch.arange(grid[0] * grid[1])[None]
+ identity_is_a_noop = torch.equal(aug(picture, params=params), picture)
+ assert identity_is_a_noop == (1 in grid)
+ params["permutation"] = torch.arange(grid[0] * grid[1]).view(grid).T.flatten()[None]
+ self.assert_close(aug(picture, params=params), picture)
+
+ @pytest.mark.device_agnostic
+ def test_wart_jigsaw_ensure_perm_rejects_the_wrong_permutation_4703(self):
+ # ensure_perm rejects arange(N), which is a real shuffle on a 2 x 2 grid, and still draws [0, 2, 1, 3],
+ # which is the no-op. 400 draws miss one of the 23 remaining permutations with probability 2e-8.
+ aug = K.RandomJigsaw(grid=(2, 2), p=1.0, ensure_perm=True)
+ drawn = set()
+ for _ in range(50):
+ permutation = aug.forward_parameters(torch.Size([8, 1, 4, 4]))["permutation"]
+ drawn.update(tuple(row) for row in permutation.tolist())
+ assert (0, 1, 2, 3) not in drawn
+ assert (0, 2, 1, 3) in drawn
+
+ def test_convention_transplantation3d_is_a_mix_class_over_volumes(self, device, dtype):
+ # The base block's (B, C, H, W) working layout has one exception: the 3D transplantation class.
+ volume = torch.rand(2, 3, 4, 5, 6, device=device, dtype=dtype)
+ mask = torch.zeros(2, 4, 5, 6, device=device, dtype=torch.long)
+ mask[:, 1:3, 1:3, 1:3] = 1
+ output, _ = K.RandomTransplantation3D(p=1.0)(volume, mask, data_keys=["input", "mask"])
+ assert output.shape == volume.shape
+ # It is still a mix augmentation: no matrix and no inverse.
+ with pytest.raises(RuntimeError, match="Transformation matrices"):
+ _ = K.RandomTransplantation3D(p=1.0).transform_matrix
+ # Both transplantation classes override forward: the spatial rank is free, so the 2D class takes the
+ # same volume, and neither promotes an unbatched image.
+ flat, _ = K.RandomTransplantation(p=1.0)(volume, mask, data_keys=["input", "mask"])
+ assert flat.shape == volume.shape
+ for cls in (K.RandomTransplantation, K.RandomTransplantation3D):
+ with pytest.raises(Exception, match="must match except for the channel"):
+ cls(p=1.0)(volume[0], mask[0], data_keys=["input", "mask"])
+
+ def test_convention_mosaic_start_ratio_range_is_a_sampling_range(self, device, dtype):
+ # Both entries are (low, high) bounds on the SAME ratio draw, not an (x, y) position.
+ image = torch.rand(8, 1, 6, 10, device=device, dtype=dtype)
+ aug = K.RandomMosaic(start_ratio_range=(0.3, 0.7), p=1.0)
+ aug(image)
+ top_left = aug._params["src"][:, 0]
+ ratios = torch.stack([top_left[:, 0] / 10, top_left[:, 1] / 6], dim=-1)
+ assert bool(((ratios >= 0.3 - 1e-5) & (ratios <= 0.7 + 1e-5)).all())
+ # Both entries are bounds on one draw, so both axes vary across the batch.
+ assert ratios[:, 0].unique().numel() > 1 and ratios[:, 1].unique().numel() > 1
+ # "Draws a pair": the two ratios are separate draws, not one value used twice.
+ assert not torch.allclose(ratios[:, 0], ratios[:, 1])
+
+ @pytest.mark.device_agnostic
+ def test_convention_jigsaw_gate_is_drawn_per_sample(self):
+ # The gate pin above supplies `batch_prob`, so nothing measures which of p / p_batch it comes from.
+ aug = K.RandomJigsaw(grid=(2, 2), p=0.5)
+ assert aug.p == 0.5 and aug.p_batch == 1.0
+ subsets = 0
+ for _ in range(20):
+ gate = aug.forward_parameters(torch.Size([8, 1, 4, 4]))["batch_prob"] > 0.5
+ subsets += 0 < int(gate.sum()) < 8
+ assert subsets > 0 # a batch-wide gate can never select a strict subset
+
+ @pytest.mark.device_agnostic
+ def test_convention_patchmix_patch_stays_inside_the_image(self):
+ # The other patch pins supply or read back `patch_coords`, so the sampled range itself is unpinned.
+ aug = K.PatchMix(patch_size=4, p=1.0)
+ xs, ys = set(), set()
+ for _ in range(20):
+ coords = aug.forward_parameters(torch.Size([16, 1, 8, 10]))["patch_coords"]
+ xs.update(coords[:, 0].tolist())
+ ys.update(coords[:, 1].tolist())
+ # Reach as well as containment: every inside corner is drawn, and nothing else.
+ assert xs == set(range(10 - 4 + 1)) and ys == set(range(8 - 4 + 1))