Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(augmentation): trim convention blocks and pins to kornia scope (#4791)

Dmytro Mishkinf9129bcea25b
diff --git a/changelog.d/4791.fixed.md b/changelog.d/4791.fixed.md
new file mode 100644
index 000000000..4b049da59
--- /dev/null
+++ b/changelog.d/4791.fixed.md
@@ -0,0 +1 @@
+The `kornia.augmentation` Convention blocks outside the 2D intensity classes are shorter and state each rule once. `RandomEqualize3D` now documents its out-of-range check as raising on every backend; the old text said MPS skipped it. Each known defect is stated with its tracking issue, including the new #4775, #4776, #4777, #4787, #4801, #4802, #4804, #4805, #4809, #4814 and #4815.
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index effff29af..627a27928 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -181,9 +181,8 @@ transform-matrix machinery β€” `compute_transformation` and the `transform_matri
.. automethod:: compute_transformation
-The 3D bases provide analogous shape, matrix and data-key machinery, but do not implement a standalone
-geometric inverse. In `AugmentationSequential`, geometric 3D children raise during inversion while intensity
-3D children are skipped, leaving their effects applied.
+The 3D bases provide analogous shape, matrix and data-key machinery; see :class:`AugmentationBase3D` for their
+contract, including the missing inverse.
.. autoclass:: AugmentationBase3D
@@ -207,14 +206,10 @@ Some Further Notes
Probabilities
^^^^^^^^^^^^^
-`_BasicAugmentationBase` has a per-sample `p` and a whole-batch `p_batch` gate. A concrete constructor can
-map its public ``p`` to either gate, so consult that class's contract. For example, `RandomMixUpV2` gates the
-batch, while `RandomJigsaw` gates individual samples. Mixing classes do not inherit all of the
-`AugmentationBase2D` forward conventions.
-
-When ``0 < p_batch < 1``, the base draws a batch Bernoulli before the per-sample gate; endpoints skip the
-Bernoulli draw. With ``p=1.0, p_batch=0.0`` no sample is selected. Only some concrete constructors expose
-``p_batch`` directly; `#4425 <https://github.com/kornia/kornia/issues/4425>`_ tracks that limitation.
+:class:`AugmentationBase2D` states the ``p`` / ``p_batch`` model. A concrete constructor can map its public ``p``
+to either gate: `RandomMixUpV2` gates the batch and `RandomJigsaw` individual samples
+(`#4425 <https://github.com/kornia/kornia/issues/4425>`_). When ``0 < p_batch < 1``, the base draws the batch
+Bernoulli before the per-sample gate; endpoints skip that draw, and ``p=1.0, p_batch=0.0`` selects no sample.
Random Generators
^^^^^^^^^^^^^^^^^
@@ -225,39 +220,13 @@ generate simple uniform parameters with less boilerplate code.
Random Reproducibility
^^^^^^^^^^^^^^^^^^^^^^
-Parameter sampling generally starts on CPU, independently of the image device. ``set_rng_device_and_dtype``
-requests new sampler placement and precision, but not every internal tensor follows that request, and some
-generator/device combinations can still fail during forward
-(`#4426 <https://github.com/kornia/kornia/issues/4426>`_). Returned parameter placement is separate from
-sampling placement: constructor ranges and casts can put a sampled tensor on another device or in another dtype.
-
-See :doc:`/get-started/conventions` for global seeding, worker seeds, consumption order, replay and the limits
-of sampler configuration. Application-time randomness is not always recorded: the dissolving VAE latents
-require controlling their random state for replay. The base's keyword and incomplete-parameter handling do not
-apply uniformly to mix augmentations.
+See :class:`AugmentationBase2D` for where parameters are sampled and what ``params=`` replays, and
+:doc:`/get-started/conventions` for seeding, worker seeds and consumption order.
Serialization
^^^^^^^^^^^^^
-Several constructors accept ``nn.Parameter`` ranges and can propagate gradients to them. Numeric range buffers
-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>`_).
-
-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
-only when it is requested. Their pending matrix state keeps the input's shape, dtype and device
-alongside the transformation parameters, without retaining the image tensor itself. Consequently,
-``pickle``, ``copy.deepcopy`` and ``torch.save`` of these modules do not carry the last image batch
-merely because its matrix has not yet been read. Parameters remain available for replay, including
-their existing gradient connections.
-
-Custom lazy subclasses may use pixel values in ``transform_tensor``, ``generate_transformation_matrix``,
-``compute_transformation`` or ``identity_matrix``. Overriding any of these four methods keeps the
-original input-based lazy behavior, retaining the input until the matrix is read or another forward
-replaces the pending state. Inheriting unchanged built-in implementations preserves their compact
-metadata state; an override does not implicitly promise that it can operate without pixel data.
-
-See :doc:`/get-started/conventions` for replay and serialization details.
+- Several constructors that accept ``nn.Parameter`` ranges propagate gradients to them.
+- The default ``kornia.augmentation.auto`` policies cannot be pickled
+ (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).
+- :class:`AugmentationBase2D` covers the range buffers in ``state_dict()``, and
+ :class:`RigidAffineAugmentationBase2D` what a lazily built matrix keeps.
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 32f282884..2b446a6c1 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -64,9 +64,8 @@ class AugmentationBase2D(_AugmentationBase):
If the subclass contains routined matrix-based transformations, `RigidAffineAugmentationBase2D`
might be a better fit.
- This class is the anchor for the contract the 2D augmentations of ``kornia.augmentation`` inherit;
- they point here instead of restating it. Mix and 3D augmentation bases have their own public contracts;
- do not infer this class's probability, RNG, replay, or serialization behavior from their common internals.
+ This class is the anchor for the contract the 2D augmentations of ``kornia.augmentation`` inherit.
+ Mix and 3D augmentations have their own bases and contracts.
Args:
p: probability for applying an augmentation. This param controls the augmentation probabilities
@@ -81,10 +80,9 @@ class AugmentationBase2D(_AugmentationBase):
- the working layout is ``(B, C, H, W)`` float. A ``(C, H, W)`` input is promoted to ``(1, C, H, W)``
and an ``(H, W)`` input to ``(1, 1, H, W)``; ``keepdim=True`` restores the input rank on the way out
and never drops a real batch dimension. The dtype guard accepts ``float16``, ``bfloat16``, ``float32``
- and ``float64`` and raises ``TypeError`` naming those four on an integer tensor. The output keeps the
- input's device. Individual augmentations may have dtype-specific behavior; see their own docs.
- - unsupported ranks and container entry points report validation errors through different paths.
- Tracked in `#4424 <https://github.com/kornia/kornia/issues/4424>`_.
+ and ``float64`` and raises ``TypeError`` on an integer tensor. The output keeps the input's device.
+ - a wrong input rank raises different exception types depending on the entry point that sees it
+ (`#4424 <https://github.com/kornia/kornia/issues/4424>`_).
- this base samples ``p`` per sample and uses ``p_batch`` as a call-wide gate. ``same_on_batch=True``
shares applicable sampled values across the batch. Concrete constructors need not expose ``p_batch``;
see `#4425 <https://github.com/kornia/kornia/issues/4425>`_. The gate selects after the transform
@@ -93,64 +91,23 @@ class AugmentationBase2D(_AugmentationBase):
- parameter sampling normally uses CPU defaults independently of the image device. Moving RNG state or
samplers is incomplete for some generators, and returned parameter placement is a separate concern;
see `#4426 <https://github.com/kornia/kornia/issues/4426>`_.
- - reproducibility goes through torch's global generators on the devices used for sampling:
- ``torch.manual_seed`` before the call reproduces the draw for the same backend and dtype.
- There is no per-instance generator; ``generator=`` raises at
- construction and is silently dropped by ``forward``, as any other unknown keyword is.
- - :doc:`/get-started/conventions` is the canonical statement of all of this: the seeding,
- ``DataLoader``-worker and consumption-order rules, sampling versus returned parameter placement,
- the ``set_rng_device_and_dtype`` limitations, and what a serialization round trip carries.
- - the last draw is kept in ``_params``; ``forward(x, params=...)`` replaces that dict wholesale rather
- than merging into it and stores the caller's dict by reference. A complete generated dictionary
- is not extended; if ``batch_prob`` is absent, ``forward`` inserts an all-true gate into that same
- dictionary. Replaying parameters reproduces the output bitwise, the ``RandomPlasma*`` noise included
- since it is drawn into ``_params``, except for :class:`RandomDissolving`, which samples VAE latents
- during application; that draw is not stored and requires controlling the global seed too.
- - range configuration and serialization behavior vary by generator. Some range buffers are inert after
- ``load_state_dict`` (tracked in `#4428 <https://github.com/kornia/kornia/issues/4428>`_). Built-in lazy
- matrix state keeps only the input's shape, dtype and device alongside the transformation parameters.
- Lazy subclasses overriding ``transform_tensor``, ``generate_transformation_matrix``,
- ``compute_transformation`` or ``identity_matrix`` retain the input until the matrix is read or another
- forward replaces the state.
- - an empty batch is an empty output on the classes that accept one, but it is not a package-wide
- guarantee: a minority of the classes raise on ``B = 0``, in several unrelated exception families.
+ - reproducibility goes through torch's global generators; there is no per-instance generator.
+ ``generator=`` raises at construction, and ``forward`` silently drops it like any other unknown keyword
+ (`#4427 <https://github.com/kornia/kornia/issues/4427>`_). :doc:`/get-started/conventions` states the
+ seeding, ``DataLoader``-worker, parameter-placement and serialization rules.
+ - the last draw is kept in ``_params``; ``forward(x, params=...)`` replaces that dict wholesale, stores the
+ caller's dict by reference and, if ``batch_prob`` is absent, inserts an all-true gate into it. Replaying
+ parameters reproduces the output, except for :class:`RandomDissolving`, whose VAE latents are drawn
+ during application and are not stored.
+ - some ``_param_generator.*`` range buffers in ``state_dict()`` do not update the samplers when loaded
+ (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).
+ - an empty batch gives an empty output, except on a minority of classes that raise on ``B = 0``
+ (`#4429 <https://github.com/kornia/kornia/issues/4429>`_).
- rotation-like parameters are in degrees, and a positive angle turns the image counter-clockwise as
- displayed (top-left origin, y pointing down), as :func:`~kornia.geometry.transform.rotate` documents.
- The ``*Affine*`` classes deviate and turn clockwise -- see :class:`RandomAffine` (tracked in
- `#4408 <https://github.com/kornia/kornia/issues/4408>`_).
- - ``torch.jit.script`` does not support these modules. ``torch.compile`` commonly works in its default,
- graph-break-tolerant mode, while ``fullgraph=True`` depends on the augmentation, flags, and input.
-
- .. warning::
- One wrong input rank can raise different exception types depending on the entry point that sees it.
- Tracked in `#4424 <https://github.com/kornia/kornia/issues/4424>`_.
-
- .. warning::
- Concrete constructors expose ``p_batch`` inconsistently, so the base probability model is not a
- universal constructor contract. Tracked in `#4425 <https://github.com/kornia/kornia/issues/4425>`_.
-
- .. warning::
- ``set_rng_device_and_dtype`` has incomplete sampler migration. It rebuilds what it can, but some
- generators retain internal CPU tensors or ignore the requested precision, some generator/device
- combinations can still fail during forward, and the returned parameters can stay CPU ``float32``
- while ``batch_prob`` follows the request. Tracked in
- `#4426 <https://github.com/kornia/kornia/issues/4426>`_.
-
- .. warning::
- ``forward`` swallows ``generator=`` -- and every other unknown keyword -- without a warning, so a
- per-instance generator looks accepted and is ignored. Tracked in
- `#4427 <https://github.com/kornia/kornia/issues/4427>`_.
-
- .. warning::
- With numeric constructor ranges, the copied ``_param_generator.*`` range buffers in ``state_dict()``
- do not update the samplers when loaded. Tracked in
- `#4428 <https://github.com/kornia/kornia/issues/4428>`_.
-
- .. warning::
- ``B = 0`` raises on a minority of the concrete classes instead of returning an empty batch, which
- contradicts the library-wide empty-in/empty-out convention of
- `#4115 <https://github.com/kornia/kornia/issues/4115>`_. Tracked in
- `#4429 <https://github.com/kornia/kornia/issues/4429>`_.
+ displayed (top-left origin, y pointing down), as :func:`~kornia.geometry.transform.rotate` documents;
+ :class:`RandomAffine` turns clockwise (`#4408 <https://github.com/kornia/kornia/issues/4408>`_).
+ - ``torch.jit.script`` is not supported; ``torch.compile(fullgraph=True)`` works for some augmentations
+ and flags only.
"""
@@ -197,11 +154,9 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
recognizes geometric children, so custom rigid subclasses need integration work of their own. See
`#4481 <https://github.com/kornia/kornia/issues/4481>`_.
- the matrix of the last call is readable as ``transform_matrix``. Subclasses opt into lazy construction
- with ``_compute_matrix_lazily``. Built-in lazy matrices keep only the input's shape, dtype and device
- alongside the transformation parameters. Lazy subclasses overriding ``transform_tensor``,
- ``generate_transformation_matrix``, ``compute_transformation`` or ``identity_matrix`` keep the input
- until the matrix is read or another forward replaces the state; unchanged inherited implementations
- keep the compact metadata state.
+ with ``_compute_matrix_lazily``; a lazy matrix keeps only the input's shape, dtype and device, unless the
+ subclass overrides ``transform_tensor``, ``generate_transformation_matrix``, ``compute_transformation``
+ or ``identity_matrix``, in which case the input is kept until the matrix is read or replaced.
- this base does not implement an inverse operation.
"""
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 8fb4b6f14..9cbcccbe7 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -64,19 +64,11 @@ class RandomAffine(GeometricAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Convention:
- - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- Pixel coordinates are ``(x, y)`` with inclusive image corners
- ``(0, 0)`` and ``(W - 1, H - 1)``; the affine center is ``((W - 1) / 2, (H - 1) / 2)``.
- - ``degrees``, scale, and shear are sampled independently per selected sample unless ``same_on_batch=True``.
- ``translate=(a, b)``
- samples pixel offsets from ``[-a W, a W]`` and ``[-b H, b H]``; positive offsets move content right
- and down. A positive ``degrees`` value instead rotates the displayed image clockwise, unlike
- :class:`RandomRotation`; this inherited affine-composer convention is tracked in `#4408
- <https://github.com/kornia/kornia/issues/4408>`_.
- - The defaults are bilinear resampling, zero padding, and ``align_corners=False``. The matrix maps input
- pixel coordinates to output pixel coordinates and is available as :attr:`transform_matrix`.
+ - See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ - ``translate=(a, b)`` samples pixel offsets from ``[-a W, a W]`` and ``[-b H, b H]``; positive offsets
+ move content right and down.
+ - a positive ``degrees`` rotates the displayed image clockwise, unlike :class:`RandomRotation`
+ (:doc:`/get-started/conventions`, `#4408 <https://github.com/kornia/kornia/issues/4408>`_).
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index e7a234f86..7e0949482 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -41,6 +41,21 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
to the batch form ``False``.
Convention:
+ - pixel coordinates are ``(x, y)`` at integer pixel centres, with corners ``(0, 0)`` and
+ ``(W - 1, H - 1)`` (see :doc:`/get-started/conventions`); rotations, shears and affine maps are centred
+ at ``((W - 1) / 2, (H - 1) / 2)``, and ``transform_matrix`` maps input pixel coordinates to output pixel
+ coordinates. Two exceptions: with pre-crop padding (``padding`` or ``pad_if_needed``), the matrix of
+ :class:`RandomCrop` starts from the padded canvas
+ (`#4801 <https://github.com/kornia/kornia/issues/4801>`_); at ``align_corners=False``, the bilinear and
+ bicubic interpolation of :class:`Resize`, :class:`LongestMaxSize`, :class:`SmallestMaxSize` and
+ slice-mode :class:`RandomResizedCrop` samples on a half-pixel grid that the matrix does not follow
+ (`#4804 <https://github.com/kornia/kornia/issues/4804>`_).
+ - the resampling classes, including the non-rigid :class:`RandomElasticTransform` and
+ :class:`RandomThinPlateSpline`, default to bilinear interpolation with zero sampler padding. The
+ ``align_corners`` default is ``True`` for :class:`RandomRotation`, :class:`RandomRotation90` and the crop
+ and resize classes, and ``False`` for :class:`RandomAffine`, :class:`RandomShear`,
+ :class:`RandomTranslate`, :class:`RandomPerspective`, :class:`RandomElasticTransform` and
+ :class:`RandomThinPlateSpline` (`#4412 <https://github.com/kornia/kornia/issues/4412>`_).
- this base provides a matrix-based ``inverse`` interface. Whether a concrete augmentation can invert a
call depends on its implementation and configuration: slice-mode crops, for example, do not support it.
Inverse resampling cannot recover image or mask information lost through cropping, padding, or
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index b79fadd0b..6bd2d17eb 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -53,18 +53,14 @@ class CenterCrop(GeometricAugmentationBase2D):
This function internally uses :func:`kornia.geometry.transform.crop_by_boxes`.
Convention:
- See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- ``size`` accepts an integer for a square crop or an
- ``(height, width)`` tuple. The fixed centre crop is shared by every selected image in a batch.
-
- When the crop is selected, ``cropping_mode="slice"`` indexes the input directly and returns a copy of the
- indexed region, so writing to the result leaves the input unchanged. ``cropping_mode="resample"`` uses
- ``crop_by_transform_mat`` with the configured ``resample`` (bilinear by default), ``align_corners`` (``True``
- by default), and zero padding. Only resample mode supports
- :meth:`inverse`; it resamples onto the original canvas with zero padding by default and cannot restore discarded
- data. The inverse call can override ``padding_mode``, for example with ``padding_mode="border"``.
+ See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ ``size`` accepts an integer for a square crop or an ``(height, width)`` tuple, unlike
+ :class:`RandomCrop` and :class:`RandomResizedCrop` (`#4417 <https://github.com/kornia/kornia/issues/4417>`_).
+
+ ``cropping_mode="slice"`` indexes the input and returns a copy, so writing to the result leaves the input
+ unchanged. ``cropping_mode="resample"`` warps with the configured ``resample`` and ``align_corners``. Only
+ resample mode supports :meth:`inverse`, which resamples onto the original canvas (zero padding unless the
+ call passes ``padding_mode``) and cannot restore discarded data.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index ff39c60fe..3da8e85c6 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -74,43 +74,30 @@ class RandomCrop(GeometricAugmentationBase2D):
applied transformation will be merged int to the input transformation torch.Tensor and returned.
Convention:
- See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- ``size`` is an ``(height, width)`` tuple; unlike
- :class:`CenterCrop`, a bare integer raises ``AssertionError`` by default, or ``TypeError`` during padding
- computation with ``pad_if_needed=True``. The split is tracked in
- `#4417 <https://github.com/kornia/kornia/issues/4417>`_. Here ``p`` selects or skips the whole batch together.
- Within a selected batch, each image samples a crop independently unless ``same_on_batch=True``.
- When skipped, images, masks, keypoints, and boxes remain unchanged, even with padding configured.
+ See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ ``size`` is an ``(height, width)`` tuple; a bare integer raises, unlike :class:`CenterCrop`
+ (`#4417 <https://github.com/kornia/kornia/issues/4417>`_). ``p`` selects or skips the whole batch
+ together; a skipped batch is returned unchanged and unpadded. With ``padding`` or ``pad_if_needed``,
+ ``transform_matrix`` maps the padded canvas, not the input, to the crop
+ (`#4801 <https://github.com/kornia/kornia/issues/4801>`_).
Explicit ``padding`` is applied before sampling, in ``(left, top, right, bottom)`` order after its scalar
- or two-value shorthand is expanded. ``pad_if_needed=True`` takes the per-side maximum of that padding and
- the positive crop-minus-input size difference on each axis. Without explicit padding this is symmetric;
- asymmetric explicit padding can remain asymmetric after the merge.
- In :class:`~kornia.augmentation.container.AugmentationSequential`, a per-channel ``fill`` applies to the
- image while mask padding defaults to zero because the mask can have a different channel count. Set a mask
- ``fill`` through ``extra_args[DataKey.MASK]`` to override that default. A scalar ``fill`` retains the
- previous behavior and applies to both the image and mask.
-
- With ``pad_if_needed=False``, an oversized request does not raise. Slice mode resizes the available slice
- to the requested size. Resample mode instead uses a mis-scaled warp that can blend in zero padding; when
- either axis is oversized, both matrix axes are rescaled, including an axis that would fit. This wart is
- tracked in `#4414 <https://github.com/kornia/kornia/issues/4414>`_. With explicit padding, the transform
- dimensions include the pre-crop padded canvas, so a crop that fits after padding avoids a spurious scale
- correction while retaining its sampled translation. The no-padding oversized behavior tracked in #4414 remains
- unchanged. With explicit padding, ``RandomCrop((10, 10), padding=1)`` on a 3-by-3 input scales against the
- padded canvas, changing ``10/3`` to ``10/5``.
-
- Slice mode calls ``crop_by_indices`` with that
- function's bilinear/``align_corners=None`` defaults, ignoring this class's ``resample`` and
- ``align_corners`` flags. Under ``torch.compile``, tensor indexing and interpolation keep newly sampled
- crop coordinates from triggering recompilation. Resample mode uses ``crop_by_transform_mat`` with the configured
- interpolation and
- ``align_corners``; it maps constant, replicate, and reflect pre-padding to zero, border, and reflection
- sampler padding respectively. Only
- resample mode supports :meth:`inverse`; inverse removes pre-crop padding but cannot restore cropped or
- interpolated content.
+ or two-value shorthand is expanded. ``pad_if_needed=True`` pads each side by the maximum of that padding
+ and the crop-minus-input size on its axis, so asymmetric explicit padding can stay asymmetric. In
+ :class:`~kornia.augmentation.container.AugmentationSequential`, a per-channel ``fill`` pads only the image
+ and the mask is padded with zero unless ``extra_args[DataKey.MASK]`` sets its ``fill``; a scalar ``fill``
+ applies to both.
+
+ With ``pad_if_needed=False``, an oversized request does not raise: slice mode resizes the available slice,
+ and resample mode uses a mis-scaled warp that rescales both matrix axes and can blend in zero padding
+ (`#4414 <https://github.com/kornia/kornia/issues/4414>`_). The scale is computed against the padded canvas,
+ so a crop that fits after explicit padding gets no scale correction.
+
+ Slice mode uses :func:`~kornia.geometry.transform.crop_by_indices` with its own defaults and ignores this
+ class's ``resample`` and ``align_corners``. Resample mode uses the configured interpolation and
+ ``align_corners`` and maps constant, replicate and reflect pre-padding to zero, border and reflection
+ sampler padding. Only resample mode supports :meth:`inverse`, which removes the pre-crop padding but cannot
+ restore cropped or interpolated content.
Note:
Compiled slice-mode interpolation matches eager execution to floating-point tolerance,
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index 49d79c339..448714c63 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -31,15 +31,14 @@ class RandomElasticTransform(AugmentationBase2D):
.. image:: _static/img/RandomElasticTransform.png
Convention:
- See the shared contract on :class:`~kornia.augmentation.AugmentationBase2D`.
- This is a dense backward sampling field, with no ``transform_matrix`` or ``inverse`` interface.
+ This is a dense backward sampling field with no ``transform_matrix`` or ``inverse``; spatial labels in
+ containers have limitations (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Noise has shape ``(B, 2, H, W)`` with channels ``(x, y)``; ``alpha`` scales displacement in
normalized sampling coordinates, whereas ``kernel_size`` and ``sigma`` use ``(y, x)`` order.
- The default sampler is bilinear with zero padding and ``align_corners=False``. The displaced
- grid is clamped to ``[-1, 1]`` before sampling. Zero ``alpha`` preserves the image up to
- interpolation rounding for either ``align_corners`` value.
- Spatial labels in containers have additional limitations; see
- `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
+ The displaced grid is clamped to ``[-1, 1]`` before sampling. Zero ``alpha`` is an identity warp up to
+ interpolation roundoff for either ``align_corners``. Its defaults and the ``align_corners`` split across
+ classes (`#4412 <https://github.com/kornia/kornia/issues/4412>`_) are listed on
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D`.
Args:
kernel_size: the size of the Gaussian kernel, in the y and x directions, respectively.
diff --git a/kornia/augmentation/_2d/geometric/fisheye.py b/kornia/augmentation/_2d/geometric/fisheye.py
index 1bf215d52..aad218235 100644
--- a/kornia/augmentation/_2d/geometric/fisheye.py
+++ b/kornia/augmentation/_2d/geometric/fisheye.py
@@ -31,15 +31,13 @@ class RandomFisheye(AugmentationBase2D):
.. image:: _static/img/RandomFisheye.png
Convention:
- See the shared contract on :class:`~kornia.augmentation.AugmentationBase2D`.
Coordinates are normalized to ``[-1, 1]`` with corner pixel centres at the endpoints.
At output coordinate ``(x, y)``, let ``r`` be its distance from the sampled centre.
The input sampling coordinate is ``(x * (1 + r**gamma), y * (1 + r**gamma))``:
the centre changes the distance, but scaling is about the coordinate origin.
Sampling is bilinear with zero padding and ``align_corners=True``; these settings are fixed.
- Output spatial size is unchanged. This non-rigid class has no ``transform_matrix`` or
- ``inverse`` interface. For spatial labels in containers, see
- `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
+ There is no ``transform_matrix`` or ``inverse``; spatial labels in containers have limitations
+ (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Args:
center_x: Ranges to sample respect to x-coordinate center with shape (2,).
diff --git a/kornia/augmentation/_2d/geometric/horizontal_flip.py b/kornia/augmentation/_2d/geometric/horizontal_flip.py
index 98ea24652..8ed8b31f5 100644
--- a/kornia/augmentation/_2d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_2d/geometric/horizontal_flip.py
@@ -49,12 +49,9 @@ class RandomHorizontalFlip(GeometricAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Convention:
- - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- Coordinates are inclusive pixel centers: a selected flip maps
- ``(x, y)`` to ``(W - 1 - x, y)`` and applies the exact discrete :func:`~kornia.geometry.transform.hflip`
- operation, without resampling.
+ A selected flip maps ``(x, y)`` to ``(W - 1 - x, y)`` with the exact discrete
+ :func:`~kornia.geometry.transform.hflip`, without resampling; see
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for the shared contract.
.. note::
This function internally uses :func:`kornia.geometry.transform.hflip`.
diff --git a/kornia/augmentation/_2d/geometric/pad.py b/kornia/augmentation/_2d/geometric/pad.py
index 7629a2b33..062320dbb 100644
--- a/kornia/augmentation/_2d/geometric/pad.py
+++ b/kornia/augmentation/_2d/geometric/pad.py
@@ -45,20 +45,14 @@ class PadTo(GeometricAugmentationBase2D):
This function internally uses :func:`torch.nn.functional.pad`.
Convention:
- See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- This operation always runs and applies its padding on the
- right and bottom, using ``pad_mode`` and ``pad_value``. A target smaller than the input supplies negative
- padding to :func:`torch.nn.functional.pad`, which crops those axes instead; a target can consequently pad
- one axis while cropping the other. This wart is tracked in
- `#4410 <https://github.com/kornia/kornia/issues/4410>`_.
+ See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ This operation always runs and pads on the right and bottom, using ``pad_mode`` and ``pad_value``. A
+ target smaller than the input crops that axis instead, so a target can pad one axis while cropping the
+ other (`#4410 <https://github.com/kornia/kornia/issues/4410>`_).
:meth:`inverse` slices to the prior input size. It exactly removes right/bottom padding, but after a crop it
returns the cropped result unchanged rather than restoring discarded pixels. The transformation matrix is
- identity, leaving coordinates unchanged. Keypoints and boxes are not clipped or removed when cropping
- puts them outside the output canvas. Canvas extents are carried separately in the input metadata used by
- :meth:`inverse`.
+ identity, so keypoints and boxes are neither moved nor clipped when cropping puts them outside the canvas.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_2d/geometric/perspective.py b/kornia/augmentation/_2d/geometric/perspective.py
index 18be85b9e..99450d982 100644
--- a/kornia/augmentation/_2d/geometric/perspective.py
+++ b/kornia/augmentation/_2d/geometric/perspective.py
@@ -48,24 +48,19 @@ class RandomPerspective(GeometricAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Convention:
- - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- The source corners are the inclusive pixel coordinates ``(0, 0)``,
- ``(W - 1, 0)``, ``(W - 1, H - 1)``, and ``(0, H - 1)``; :attr:`transform_matrix` maps those source
- coordinates to the sampled destination corners.
+ - See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ The source corners are ``(0, 0)``, ``(W - 1, 0)``, ``(W - 1, H - 1)`` and ``(0, H - 1)``;
+ :attr:`transform_matrix` maps them to the sampled destination corners.
- ``basic`` samples each corner inward by at most ``distortion_scale * (W, H) / 2``. ``area_preserving``
- samples each coordinate in both directions over the same extent. Defaults are bilinear resampling, zero
- padding, and ``align_corners=False``. ``same_on_batch=True`` reuses the sampled destination corners for
- every selected sample.
-
- - With ``distortion_scale=0`` and ``H > 1``, ``W > 1``, the image warp is identity up to numerical
- precision for either ``align_corners`` setting. If either spatial dimension is 1, coincident source
- corners instead produce a NaN transformation matrix and output even at zero distortion. This limitation
- is recorded in `#4538 <https://github.com/kornia/kornia/pull/4538#pullrequestreview-5209122169>`_.
+ samples each coordinate in both directions over the same extent.
+ - with ``distortion_scale=0`` and ``H > 1``, ``W > 1``, the warp is an identity up to numerical precision
+ for either ``align_corners``. A ``float64`` image is warped through a ``float32`` grid, so it is
+ reproduced only to float32 precision (`#4776 <https://github.com/kornia/kornia/issues/4776>`_). If either
+ spatial dimension is 1, the coincident source corners give a NaN matrix and output even at zero
+ distortion (`#4787 <https://github.com/kornia/kornia/issues/4787>`_).
.. note::
- This function internally uses :func:`kornia.geometry.transform.warp_pespective`.
+ This function internally uses :func:`kornia.geometry.transform.warp_perspective`.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/_2d/geometric/resize.py b/kornia/augmentation/_2d/geometric/resize.py
index 92d4a50da..2402dcbb8 100644
--- a/kornia/augmentation/_2d/geometric/resize.py
+++ b/kornia/augmentation/_2d/geometric/resize.py
@@ -42,21 +42,16 @@ class Resize(GeometricAugmentationBase2D):
to the batch form (False).
Convention:
- See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
+ See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
A tuple ``size`` is the exact ``(height, width)`` output.
With an integer, ``side`` selects which input side is set to that value while preserving aspect ratio:
``"short"`` (the default) selects the shortest side, ``"long"`` the longest, ``"vert"`` the height, and
``"horz"`` the width. The derived side is truncated toward zero; if it becomes zero, the resize raises
``AssertionError`` (for example, ``Resize(4, side="long")`` or ``LongestMaxSize(4)`` on a 1-by-10 image).
- This class uses
- :func:`kornia.geometry.transform.resize`; ``align_corners`` is forwarded for bilinear and bicubic sampling,
- and ``antialias`` affects downscaling only. The operation has a fixed, whole-batch resize whenever it is
- selected.
-
- :meth:`inverse` resamples to the prior canvas with zero padding through ``crop_by_transform_mat``. It
- restores the shape but cannot recover values discarded by a resize.
+ This class uses :func:`kornia.geometry.transform.resize`; ``align_corners`` is forwarded for bilinear and
+ bicubic sampling, and at ``align_corners=False`` the image does not follow ``transform_matrix``
+ (`#4804 <https://github.com/kornia/kornia/issues/4804>`_). :meth:`inverse` resamples to the prior canvas
+ and cannot recover values discarded by a resize.
"""
diff --git a/kornia/augmentation/_2d/geometric/resized_crop.py b/kornia/augmentation/_2d/geometric/resized_crop.py
index 198ff2da3..23b3f66f1 100644
--- a/kornia/augmentation/_2d/geometric/resized_crop.py
+++ b/kornia/augmentation/_2d/geometric/resized_crop.py
@@ -61,26 +61,22 @@ class RandomResizedCrop(GeometricAugmentationBase2D):
applied transformation will be merged int to the input transformation torch.Tensor and returned.
Convention:
- See :class:`~kornia.augmentation.AugmentationBase2D` for input, dtype, probability, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- ``size`` is an ``(height, width)`` tuple. A bare integer
- is rejected, unlike :class:`CenterCrop`; the sibling split is tracked in
- `#4417 <https://github.com/kornia/kornia/issues/4417>`_. Here ``p`` selects or skips the whole batch together.
+ See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ ``size`` is an ``(height, width)`` tuple; a bare integer raises, unlike :class:`CenterCrop`
+ (`#4417 <https://github.com/kornia/kornia/issues/4417>`_). ``p`` selects or skips the whole batch together.
Within a selected batch, the generator tries ten candidate crops per image, sampling area fractions from
- ``scale`` and width/height ratios from ``ratio`` (shared with ``same_on_batch=True``). Rounded candidate
- dimensions must be positive and strictly smaller than the input on both axes. If no candidate fits,
- a fallback chooses dimensions by comparing input height/width with ``min(ratio)``, then clamps them to
- the input size. This fallback can violate both requested ranges: on an 8x6 input, ``scale=(1.0, 1.0)``
- with the default ratio produces a 4x6 crop, with half the input area and width/height ratio 1.5.
- The selected crop is resized to the requested output size.
-
- Slice mode calls index cropping with the configured interpolation and ``align_corners``; resample mode
- calls ``crop_by_transform_mat`` with zero padding. Both default to bilinear sampling and
- ``align_corners=True``. Under ``torch.compile``, slice mode uses tensor indexing and
- interpolation so newly sampled crop coordinates do not trigger recompilation.
- Only resample mode supports :meth:`inverse`; its inverse
- resamples onto the original canvas and cannot recover information discarded by cropping or interpolation.
+ ``scale`` and width/height ratios from ``ratio`` (shared with ``same_on_batch=True``), and resizes the first
+ that fits to the requested output size. A candidate must be strictly smaller than the input on both axes,
+ and the fallback compares height/width, not width/height, with ``min(ratio)``, so ``scale=(1.0, 1.0)``
+ never keeps a square or portrait image and can leave both ranges: an 8x6 input gives a 4x6 crop where
+ torchvision keeps 8x6 (`#4814 <https://github.com/kornia/kornia/issues/4814>`_).
+
+ Both cropping modes use the configured interpolation and ``align_corners``, so slice mode raises for
+ ``resample="nearest"`` unless ``align_corners=None``
+ (`#4802 <https://github.com/kornia/kornia/issues/4802>`_). At ``align_corners=False`` the two modes give
+ different images, and slice mode does not follow ``transform_matrix``
+ (`#4804 <https://github.com/kornia/kornia/issues/4804>`_). Only resample mode supports :meth:`inverse`,
+ which resamples onto the original canvas and cannot recover discarded information.
Note:
Compiled slice-mode interpolation matches eager execution to floating-point tolerance,
diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.py
index 40b0562a7..5f7dc3658 100644
--- a/kornia/augmentation/_2d/geometric/rotation.py
+++ b/kornia/augmentation/_2d/geometric/rotation.py
@@ -47,14 +47,10 @@ class RandomRotation(GeometricAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Convention:
- - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- Coordinates are inclusive pixel centers, and rotation is about
- ``((W - 1) / 2, (H - 1) / 2)``.
- - A positive sampled angle rotates the displayed image counter-clockwise. The default is bilinear
- resampling with zero padding and ``align_corners=True``; this default differs from several 2D geometric
- augmentations and is tracked in `#4412 <https://github.com/kornia/kornia/issues/4412>`_.
+ - See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ - a positive sampled angle rotates the displayed image counter-clockwise, as
+ :func:`~kornia.geometry.transform.rotate` does and unlike :class:`RandomAffine`
+ (:doc:`/get-started/conventions`, `#4408 <https://github.com/kornia/kornia/issues/4408>`_).
.. note::
This function internally uses :func:`kornia.geometry.transform.affine`.
@@ -164,15 +160,10 @@ class RandomRotation90(GeometricAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Convention:
- - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- Coordinates are inclusive pixel centers and positive rounded ``times`` values rotate the displayed image
- counter-clockwise by ``times * 90`` degrees.
- - ``times`` is sampled from the supplied uniform range and rounded before multiplication by 90. The output
- retains the input ``(H, W)`` shape, including for non-square images; both behaviors are tracked in
- `#4409 <https://github.com/kornia/kornia/issues/4409>`_. Its defaults match :class:`RandomRotation`:
- bilinear resampling, zero padding, and ``align_corners=True``.
+ - See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ - a positive rounded ``times`` rotates the displayed image counter-clockwise by ``times * 90`` degrees.
+ - ``times`` is sampled from a continuous uniform range and rounded, and a non-square image keeps its
+ ``(H, W)`` shape (`#4409 <https://github.com/kornia/kornia/issues/4409>`_).
.. note::
This function internally uses :func:`kornia.geometry.transform.affine`. This version is relatively
diff --git a/kornia/augmentation/_2d/geometric/shear.py b/kornia/augmentation/_2d/geometric/shear.py
index 49ac981e4..53bfd8d29 100644
--- a/kornia/augmentation/_2d/geometric/shear.py
+++ b/kornia/augmentation/_2d/geometric/shear.py
@@ -51,14 +51,9 @@ class RandomShear(GeometricAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Convention:
- - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- Pixel coordinates are inclusive, and the shear is centered at
- ``((W - 1) / 2, (H - 1) / 2)``. Positive ``shear_x`` and ``shear_y`` use the same signs as
- :class:`RandomAffine`'s shear parameters.
+ - See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
- ``shear`` supplies one or two degree ranges for the x and y shears; a scalar or pair supplies only x
- shear. Defaults are bilinear resampling, zero padding, and ``align_corners=False``.
+ shear. The signs are those of :class:`RandomAffine`'s ``shear``.
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index e67aa6c97..c3e27ceb1 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -32,17 +32,15 @@ class RandomThinPlateSpline(AugmentationBase2D):
.. image:: _static/img/RandomThinPlateSpline.png
Convention:
- See the shared contract on :class:`~kornia.augmentation.AugmentationBase2D`.
Five control points use normalized ``(x, y)`` coordinates: ``(-1, -1)``, ``(-1, 1)``,
``(1, -1)``, ``(1, 1)``, and ``(0, 0)``. Each destination coordinate receives uniform
noise between ``-scale`` and ``scale``; zero scale leaves these points unchanged.
- Sampling is bilinear with zero padding and ``align_corners=False`` by default; no
- interpolation-mode argument is exposed. Output spatial size is unchanged, and there is
- no ``transform_matrix`` or ``inverse`` interface. Spatial labels in containers have
- additional limitations; see `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
-
- With zero scale, the image warp is identity up to numerical precision for either ``align_corners``
- setting with float16, float32, float64, and bfloat16 inputs.
+ Sampling is bilinear, with no interpolation-mode argument. Zero scale is an identity warp up to
+ interpolation roundoff for either ``align_corners``. There is no ``transform_matrix`` or ``inverse``;
+ spatial labels in containers have limitations (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
+ Its defaults and the ``align_corners`` split across classes
+ (`#4412 <https://github.com/kornia/kornia/issues/4412>`_) are listed on
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D`.
Args:
scale: the non-negative scale factor to apply to the destination points.
diff --git a/kornia/augmentation/_2d/geometric/translate.py b/kornia/augmentation/_2d/geometric/translate.py
index 95738c04c..a143f827d 100644
--- a/kornia/augmentation/_2d/geometric/translate.py
+++ b/kornia/augmentation/_2d/geometric/translate.py
@@ -47,14 +47,9 @@ class RandomTranslate(GeometricAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Convention:
- - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- Coordinates are inclusive pixel centers. ``translate_x`` and
- ``translate_y`` are independently sampled fractions and multiplied by ``W`` and ``H`` respectively;
- positive values move content right and down. Omitting either range fixes that axis at zero.
- - The defaults are bilinear resampling, zero padding, and ``align_corners=False``. The matrix maps input
- pixel coordinates to output pixel coordinates.
+ - See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.
+ - ``translate_x`` and ``translate_y`` are independently sampled fractions of ``W`` and ``H``; positive
+ values move content right and down. Omitting either range fixes that axis at zero.
.. note::
This function internally uses :func:`kornia.geometry.transform.warp_affine`.
diff --git a/kornia/augmentation/_2d/geometric/vertical_flip.py b/kornia/augmentation/_2d/geometric/vertical_flip.py
index 3c6405413..1a802f349 100644
--- a/kornia/augmentation/_2d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_2d/geometric/vertical_flip.py
@@ -40,12 +40,9 @@ class RandomVerticalFlip(GeometricAugmentationBase2D):
- Output: :math:`(B, C, H, W)`
Convention:
- - See :class:`~kornia.augmentation.AugmentationBase2D` for input, sampling, and replay,
- :class:`~kornia.augmentation.RigidAffineAugmentationBase2D` for transformation matrices, and
- :class:`~kornia.augmentation.GeometricAugmentationBase2D` for inverse behavior.
- Coordinates are inclusive pixel centers: a selected flip maps
- ``(x, y)`` to ``(x, H - 1 - y)`` and applies the exact discrete :func:`~kornia.geometry.transform.vflip`
- operation, without resampling.
+ A selected flip maps ``(x, y)`` to ``(x, H - 1 - y)`` with the exact discrete
+ :func:`~kornia.geometry.transform.vflip`, without resampling; see
+ :class:`~kornia.augmentation.GeometricAugmentationBase2D` for the shared contract.
.. note::
This function internally uses :func:`kornia.geometry.transform.vflip`.
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 99b97455a..ed1da7112 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -49,32 +49,26 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
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.
+ - Sampling, replay, and serialization follow the augmentation-wide contracts in
+ :doc:`/get-started/conventions`.
+ - Image inputs are floating tensors of shape ``(H, W)``, ``(C, H, W)``, or ``(B, C, H, W)`` in
+ ``float16``, ``bfloat16``, ``float32`` or ``float64``, promoted to ``(B, C, H, W)``; ``keepdim=True``
+ restores the rank of an unbatched input. :class:`~kornia.augmentation.RandomTransplantation` and
+ :class:`~kornia.augmentation.RandomTransplantation3D` override ``forward`` and take batched inputs only.
+ - A mix operation is not geometric: ``transform_matrix`` and ``inverse()`` raise ``RuntimeError``.
+ - ``data_keys`` chooses which positional inputs are dispatched. Called directly, a key the concrete class
+ does not implement raises ``NotImplementedError`` (or a class-specific error) before anything is
+ sampled; the two transplantation classes, and any mix child of
+ :class:`~kornia.augmentation.container.AugmentationSequential`, raise it after the 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
+ - ``batch_prob`` gates the result: a selected image is mixed and an unselected image keeps its input
+ values, except where a concrete class changes the output size (see
+ :class:`~kornia.augmentation.RandomMosaic`); the transplantation classes read ``acceptor_indices``
+ instead. The box handlers use the same gate. The class-label
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.
+ ignore ``batch_prob``; their sampled gate is batch-wide, but a ``params`` whose ``batch_prob`` selects
+ only some rows labels the unselected, unchanged rows as mixed
+ (`#4775 <https://github.com/kornia/kornia/issues/4775>`_).
"""
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 0102f444e..219553c54 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -78,15 +78,14 @@ class RandomCutMixV2(MixAugmentationBaseV2):
``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 is applied once: one draw per call selects the whole batch with probability
- ``p``, so ``_params["batch_prob"]`` is all ones or all zeros. Every row and mix of a selected batch receives
- a cut and none is dropped again. With ``same_on_batch=False`` each row and mix draws its own cut size and
- its own placement; ``same_on_batch=True`` shares both, so all rows and mixes receive one geometry. A cut
- can still leave the image unchanged through self-pairing or a zero-sized cut.
- 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>`_.
+ - ``p`` is a batch-wide gate applied once, unlike the per-sample ``p`` of :class:`RandomJigsaw`
+ (`#4425 <https://github.com/kornia/kornia/issues/4425>`_): ``_params["batch_prob"]`` is all ones or all zeros,
+ and every row and mix of a selected batch receives a cut, though self-pairing or a zero-sized cut can
+ leave a row unchanged. With ``same_on_batch=False`` each row and mix draws its own cut size and placement;
+ ``same_on_batch=True`` shares one geometry, and with ``num_mix > 1`` one pairing too, so every mix
+ repeats the first cut while the labels credit the donor once per mix
+ (`#4805 <https://github.com/kornia/kornia/issues/4805>`_). At ``p=0`` the image is unchanged and each
+ class row contains the original label twice with lambda zero.
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 adf6c295b..45fb2d93f 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -51,19 +51,14 @@ class RandomJigsaw(MixAugmentationBaseV2):
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.
+ - ``grid=(rows, columns)`` partitions each image independently. Both image dimensions must be divisible by
+ their grid entries, otherwise ``RuntimeError`` is raised whatever the gate. An entry's position selects
+ the destination cell in column-major order, while its value indexes the source patch in row-major order,
+ so the identity permutation reproduces the image only on a single-row or single-column grid (on a square
+ grid it transposes the patches). 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; ``same_on_batch=True`` shares one gate draw and one permutation. Only image
+ input is implemented.
Examples:
>>> jigsaw = RandomJigsaw((4, 4))
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index 1ab1bd28e..65a253ad2 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -81,13 +81,11 @@ class RandomMixUpV2(MixAugmentationBaseV2):
``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 is applied once: one draw per call selects the whole batch
- with probability ``p``, so ``_params["batch_prob"]`` is all ones or all zeros. Every row of a selected
- batch draws its lambda from ``lambda_val`` and none is dropped again; a row's image can still be unchanged
- if its lambda is zero or it is paired with itself.
- 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.
+ - ``p`` is a batch-wide gate applied once, unlike the per-sample ``p`` of :class:`RandomJigsaw`
+ (`#4425 <https://github.com/kornia/kornia/issues/4425>`_): ``_params["batch_prob"]`` is all ones or all zeros,
+ and every row of a selected batch draws its lambda from ``lambda_val``. 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
+ the lambda draw but not the pairing, which may pair a sample with itself.
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/patchmix.py b/kornia/augmentation/_2d/mix/patchmix.py
index d0a09a399..9b9bbb775 100644
--- a/kornia/augmentation/_2d/mix/patchmix.py
+++ b/kornia/augmentation/_2d/mix/patchmix.py
@@ -50,13 +50,11 @@ class PatchMix(MixAugmentationBaseV2):
- ``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.
+ at the same sampled ``(x, y)`` top-left corner, ``_params["patch_coords"]``. The sampled ``lam`` is
+ stored but blends nothing.
+ - ``p`` is a batch-wide gate (`#4425 <https://github.com/kornia/kornia/issues/4425>`_).
+ ``same_on_batch=True`` shares the patch corner, not the pairing, which may pair a sample with itself.
+ Only image input is implemented.
Examples:
>>> aug = PatchMix(alpha=1.0, patch_size=4)
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index 3f00d0f6a..d1d915b72 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -85,37 +85,28 @@ class RandomTransplantation(MixAugmentationBaseV2):
(`DataKey.MASK`).
Convention:
- - the transplant is driven by the first ``"mask"`` input. Every input keeps its own rank: an image is
- ``(B, C, *spatial)`` and a mask ``(B, *spatial)``, for any number of spatial dimensions, including
- none -- a ``(B,)`` mask is one label per image and moves the whole image. The first axis is always
- the batch and there is no unbatched form. This class overrides ``forward`` wholesale, so the
- ``(B, C, H, W)`` working layout and the rank promotion on
- :class:`~kornia.augmentation.MixAugmentationBaseV2` do not apply to it, and its inherited
- ``keepdim`` is inert.
- - ``p`` gates samples and ``p_batch`` gates the whole call. Each selected image is an acceptor and its
- donor is the previous image of the **full** batch, ``(i - 1) mod B``, so a donor need not itself be
- an acceptor, and one that is gives its original content rather than what it received. At ``B = 1``
- an image is its own donor and the call is an exact identity.
- - one label is drawn uniformly from the donor's distinct labels, minus ``excluded_labels``, with
- ``torch.randperm`` on the global CPU generator whatever the mask's device; the draw is over labels,
- not over area. A donor with no eligible label has nothing to give, so its acceptor is dropped from
- ``acceptor_indices``, its ``batch_prob`` entry is cleared and it receives nothing, while the rest of
- the batch is transplanted.
- - ``_params`` holds ``batch_prob``, ``forward_input_shape`` (the mask's shape in a direct call, the image's
- inside a container), ``acceptor_indices``, ``donor_indices``, ``selected_labels`` and ``selection``.
- ``selection`` is what the transform reads: row ``d`` marks the positions moved from ``donor_indices[d]``
- into ``acceptor_indices[d]``, and a drawn ``selected_labels`` has one entry per row. A recorded ``_params``
- passed back is used as given and completed in place, so it replays the same positions on any input of the
- same shape. Labels are drawn only when ``selected_labels`` and ``selection`` are both missing. A missing
- ``selection`` alone is rebuilt from the given labels against the current mask, without consulting
- ``excluded_labels``, and a label list shorter than the acceptors leaves the trailing acceptors untouched.
- - image inputs accept ``float16``, ``bfloat16``, ``float32`` and ``float64`` only, checked whatever the
- gate; a mask keeps its own dtype, which may be ``bool``, ``uint8``, a signed integer or one of those
- four floating dtypes. Only ``"input"`` / ``"image"`` and ``"mask"`` are implemented -- any other data
- key raises a bare ``NotImplementedError`` whatever the gate. A ``"mask"`` is needed only to derive the
- parameters, where its absence raises ``ValueError``; a call with a complete ``_params`` accepts any
- subset of the inputs, which is how :class:`~kornia.augmentation.container.AugmentationSequential`
- applies the transplant, one input at a time. Outputs come back in input order, a single one as a bare
+ - the transplant is driven by the first ``"mask"`` input. An image is ``(B, C, *spatial)`` and a mask
+ ``(B, *spatial)`` for any number of spatial dimensions, including none (a ``(B,)`` mask moves whole
+ images). There is no unbatched form, and the inherited ``keepdim`` is inert.
+ - ``p`` gates samples and ``p_batch`` the whole call. The donor of acceptor ``i`` is image ``(i - 1) mod B``
+ of the full batch, with its original content, whether or not it is an acceptor itself; at ``B = 1`` the
+ call is an identity.
+ - one label is drawn uniformly from the donor's distinct labels minus ``excluded_labels`` (over labels, not
+ area), on the global CPU generator whatever the mask's device. An acceptor whose donor has no eligible
+ label is dropped from ``acceptor_indices`` and its ``batch_prob`` is cleared.
+ - ``selection`` in ``_params`` is what the transform reads: row ``d`` marks the positions moved from
+ ``donor_indices[d]`` into ``acceptor_indices[d]``. A ``params`` passed back is used as given and completed
+ in place. Labels are drawn only when ``selected_labels`` and ``selection`` are both missing; a missing
+ ``selection`` alone is rebuilt from the given labels as they are (by design, ``excluded_labels`` filters
+ only drawn labels), and a label list shorter than the acceptors leaves the trailing ones untouched.
+ - images are ``float16``, ``bfloat16``, ``float32`` or ``float64``; a mask keeps its own dtype (``bool``,
+ integer or floating). Only ``"input"`` / ``"image"`` and ``"mask"`` keys are implemented; any other key
+ raises ``NotImplementedError``. A mask is needed only to draw the parameters, and a call without one
+ fails with Python's ``IndexError`` or ``ValueError``, or a generic key-count error, rather than a kornia
+ error naming the mask (`#4777 <https://github.com/kornia/kornia/issues/4777>`_). With a complete
+ ``params`` any subset of the inputs is accepted, which is how
+ :class:`~kornia.augmentation.container.AugmentationSequential` applies the transplant, one input at a
+ time. Outputs come back in input order, a single one as a bare
tensor.
- like every mix augmentation it is not geometric: ``transform_matrix`` and ``inverse()`` both raise
``RuntimeError``, and the ``inverse()`` of a
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index ca19249c2..8ee6dd59c 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -73,16 +73,10 @@ class RandomAffine3D(GeometricAugmentationBase3D):
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
+ - ``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, and the 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``).
+ - the default is bilinear resampling with ``align_corners=False``.
- a two-value ``scale=(a, b)`` is isotropic: one factor per sample is drawn from ``[a, b]`` and applied
to all three axes, as the 2D :class:`~kornia.augmentation.RandomAffine` does. The three-pair form
``((a, b), (c, d), (e, f))`` draws each axis independently.
diff --git a/kornia/augmentation/_3d/geometric/base.py b/kornia/augmentation/_3d/geometric/base.py
index a036d535a..4cdcd05d7 100644
--- a/kornia/augmentation/_3d/geometric/base.py
+++ b/kornia/augmentation/_3d/geometric/base.py
@@ -34,13 +34,16 @@ class GeometricAugmentationBase3D(RigidAffineAugmentationBase3D):
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
+ ordered ``(x, y, z)``, while volume tensor axes are ``(D, H, W)``. For :class:`RandomCrop3D`
+ (`#4801 <https://github.com/kornia/kornia/issues/4801>`_), 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.
+ them exactly.
+ - a zero-parameter :class:`RandomAffine3D` or :class:`RandomRotation3D` warp reproduces its input up to
+ roundoff in ``float32`` and ``float64``. In half precision the sampling grid is itself rounded, so the
+ error grows with the volume size.
"""
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index 62f6c720b..2b835ea42 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -51,7 +51,9 @@ class CenterCrop3D(GeometricAugmentationBase3D):
- ``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``.
+ still runs when the call is skipped, so an oversized crop raises even at ``p=0``. The exception types
+ differ from :class:`RandomCrop3D`'s, and a two-element ``size`` fails with ``IndexError``
+ (`#4417 <https://github.com/kornia/kornia/issues/4417>`_).
- defaults are bilinear resampling and ``align_corners=True``.
Examples:
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index 84f8dd9d3..28af97926 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -81,14 +81,16 @@ class RandomCrop3D(GeometricAugmentationBase3D):
- ``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)``.
+ - ``transform_matrix`` maps the padded volume to the crop, not the original input to the crop
+ (`#4801 <https://github.com/kornia/kornia/issues/4801>`_). Add the left, top, and front padding to an
+ original ``(x, y, z)`` point before applying this matrix: padding a ``3 x 3 x 3`` input by ``1`` and
+ cropping the full ``5 x 5 x 5`` volume records an identity matrix although 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: a
- crop larger than the padded volume along any axis, even by one voxel, raises ``ValueError``
- (:class:`CenterCrop3D` rejects the same request with ``AssertionError``); a crop equal to it is valid.
- A valid gated-off call returns the input itself -- unpadded, at the input shape rather than ``size`` --
+ crop larger than the padded volume along any axis, even by one voxel, raises; a crop equal to it is
+ valid. The exception types differ from :class:`CenterCrop3D`'s, and an ``int`` ``size`` is rejected
+ (`#4417 <https://github.com/kornia/kornia/issues/4417>`_).
+ A valid gated-off call returns the input unchanged -- unpadded, at the input shape rather than ``size`` --
with an identity ``transform_matrix``.
Defaults are bilinear resampling and ``align_corners=True``.
diff --git a/kornia/augmentation/_3d/geometric/depthical_flip.py b/kornia/augmentation/_3d/geometric/depthical_flip.py
index 3d2435377..2e894690a 100644
--- a/kornia/augmentation/_3d/geometric/depthical_flip.py
+++ b/kornia/augmentation/_3d/geometric/depthical_flip.py
@@ -45,7 +45,8 @@ class RandomDepthicalFlip3D(GeometricAugmentationBase3D):
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.
+ ``D - 1 - z`` in inclusive voxel coordinates, rounded where the dtype cannot
+ represent it (see the base).
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/horizontal_flip.py b/kornia/augmentation/_3d/geometric/horizontal_flip.py
index b14a88710..37cc4d8af 100644
--- a/kornia/augmentation/_3d/geometric/horizontal_flip.py
+++ b/kornia/augmentation/_3d/geometric/horizontal_flip.py
@@ -43,7 +43,8 @@ class RandomHorizontalFlip3D(GeometricAugmentationBase3D):
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.
+ ``W - 1 - x`` in inclusive voxel coordinates, rounded where the dtype cannot
+ represent it (see the base).
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/perspective.py b/kornia/augmentation/_3d/geometric/perspective.py
index d3f331dfe..40abb2fbf 100644
--- a/kornia/augmentation/_3d/geometric/perspective.py
+++ b/kornia/augmentation/_3d/geometric/perspective.py
@@ -55,6 +55,8 @@ class RandomPerspective3D(GeometricAugmentationBase3D):
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``.
+ - a ``float64`` volume is warped through a float32 sampling grid, so it keeps only float32 precision
+ (`#4776 <https://github.com/kornia/kornia/issues/4776>`_).
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/rotation.py b/kornia/augmentation/_3d/geometric/rotation.py
index 5a494469f..28dc38d64 100644
--- a/kornia/augmentation/_3d/geometric/rotation.py
+++ b/kornia/augmentation/_3d/geometric/rotation.py
@@ -58,14 +58,11 @@ class RandomRotation3D(GeometricAugmentationBase3D):
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``).
+ roll turns a displayed ``H x W`` slice clockwise, as :func:`kornia.geometry.transform.rotate3d` does;
+ :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``.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/geometric/vertical_flip.py b/kornia/augmentation/_3d/geometric/vertical_flip.py
index 179358c4d..a379286cf 100644
--- a/kornia/augmentation/_3d/geometric/vertical_flip.py
+++ b/kornia/augmentation/_3d/geometric/vertical_flip.py
@@ -45,7 +45,8 @@ class RandomVerticalFlip3D(GeometricAugmentationBase3D):
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.
+ ``H - 1 - y`` in inclusive voxel coordinates, rounded where the dtype cannot
+ represent it (see the base).
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/intensity/base.py b/kornia/augmentation/_3d/intensity/base.py
index 847f2ce43..91ef6de46 100644
--- a/kornia/augmentation/_3d/intensity/base.py
+++ b/kornia/augmentation/_3d/intensity/base.py
@@ -33,9 +33,7 @@ class IntensityAugmentationBase3D(RigidAffineAugmentationBase3D):
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.
+ - these augmentations leave voxel coordinates in place: they record an identity ``(B, 4, 4)`` matrix,
+ and a container skips them on its inverse path.
"""
diff --git a/kornia/augmentation/_3d/intensity/equalize.py b/kornia/augmentation/_3d/intensity/equalize.py
index 91ea95be4..fbc756bb0 100644
--- a/kornia/augmentation/_3d/intensity/equalize.py
+++ b/kornia/augmentation/_3d/intensity/equalize.py
@@ -37,20 +37,15 @@ class RandomEqualize3D(IntensityAugmentationBase3D):
- 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 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.
+ Input tensor must be float and normalized into [0, 1].
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.
+ - values the 256-bin lookup cannot index (outside roughly ``[0, 1]``) raise a ``RuntimeError`` naming
+ the range. Each channel's whole volume supplies one 256-bin histogram
+ (:func:`kornia.enhance.equalize3d`), so a volume with at most 255 voxels per channel is returned
+ unchanged up to roundoff.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_3d/intensity/motion_blur.py b/kornia/augmentation/_3d/intensity/motion_blur.py
index 9725c7896..ede28128e 100644
--- a/kornia/augmentation/_3d/intensity/motion_blur.py
+++ b/kornia/augmentation/_3d/intensity/motion_blur.py
@@ -63,8 +63,8 @@ class RandomMotionBlur3D(IntensityAugmentationBase3D):
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
+ roll turns the blur kernel clockwise as displayed, as :class:`RandomRotation3D` does and
+ opposite to the 2D :class:`~kornia.augmentation.RandomMotionBlur`
(`#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``
diff --git a/kornia/augmentation/_3d/mix/transplantation.py b/kornia/augmentation/_3d/mix/transplantation.py
index 7975062a8..8abd677eb 100644
--- a/kornia/augmentation/_3d/mix/transplantation.py
+++ b/kornia/augmentation/_3d/mix/transplantation.py
@@ -30,14 +30,8 @@ class RandomTransplantation3D(RandomTransplantation, AugmentationBase3D): # typ
See the Convention block on :class:`~kornia.augmentation.RandomTransplantation`.
Convention:
- - this subclass changes no behaviour. It exists so that
- :class:`~kornia.augmentation.container.AugmentationSequential` dispatches it as a 3D augmentation;
- called directly, it is byte-identical to the 2D class at every rank, volumes included.
- - inside a container, use this class for ``(B, C, D, H, W)`` volumes and
- :class:`~kornia.augmentation.RandomTransplantation` for ``(B, C, H, W)`` images. The container
- rejects ambiguous 4D input for this 3D class and rejects 5D input for the 2D class.
- - it derives from both :class:`~kornia.augmentation.MixAugmentationBaseV2` and
- :class:`~kornia.augmentation.AugmentationBase3D`, so it is the one 3D augmentation that carries a
- mix ``inverse`` -- which raises ``RuntimeError`` -- and the one mix augmentation a container accepts
- on five-dimensional volumes.
+ - called directly it behaves exactly like the 2D class; it exists so that
+ :class:`~kornia.augmentation.container.AugmentationSequential` dispatches it as a 3D augmentation. Inside a
+ container use it for ``(B, C, D, H, W)`` volumes and :class:`~kornia.augmentation.RandomTransplantation`
+ for ``(B, C, H, W)`` images; the container rejects 4D input for this class and 5D input for the 2D one.
"""
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index fb57a8ac9..8ea9a6069 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -39,35 +39,22 @@ class OperationBase(nn.Module):
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. The probability parameter is initialized from the wrapped
- augmentation's ``p`` (``p_batch`` for a batch operation) and kept in ``state_dict()`` for API and
- checkpoint compatibility; it does not take part in sampling. 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, while the magnitude does. ``forward_parameters`` draws
- the wrapped augmentation's parameters and substitutes the supplied or learned magnitude. The wrapper
- builds no probability sampler, on itself or on the wrapped augmentation, which keeps its own parameter
- samplers; ``copy.deepcopy`` therefore works before and after a forward pass or a ``train()`` / ``eval()``
- call.
- - ``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` samples each operation through
- ``forward_parameters``, so the magnitude mapping applies under every policy container.
- - 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>`_).
+ - ``probability`` is initialized from the wrapped augmentation's ``p`` (``p_batch`` for a batch operation),
+ clamped to ``[1e-7, 1 - 1e-7]`` and kept in ``state_dict()`` for checkpoint compatibility, but it takes
+ no part in sampling and receives no gradient: the gate is drawn from the wrapped augmentation's own
+ ``p`` and ``p_batch`` as a hard ``0`` or ``1``. ``magnitude``, where the operation has one, is clamped to
+ the wrapped generator's range and receives a gradient where the wrapped augmentation is differentiable
+ in it; ``forward_parameters`` substitutes it into the wrapped augmentation's draw.
+ - ``forward`` linearly blends the wrapped output with the input using ``batch_prob``. Unless the wrapped
+ ``p`` and ``p_batch`` are both ``1``, the wrapped augmentation first keeps rows whose gate is at most
+ ``0.5`` unchanged, so the same supplied fractional gates replay differently depending on ``p``
+ (`#4809 <https://github.com/kornia/kornia/issues/4809>`_).
+ - a symmetric magnitude applies the magnitude mapping first and then a random sign per row, so a mapping
+ that quantizes to zero stays zero (``Posterize`` maps ``0.5`` to ``0`` bits with ``magnitude_range=(0, 8)``).
+ - the concrete classes in ``kornia.augmentation.auto.operations.ops`` wrap public 2D augmentations and
+ inherit their input, dtype, RNG and replay contracts. A wrapper pickles only with a named magnitude
+ mapping and ``symmetric_megnitude=False`` (with default arguments, only ``Posterize``); otherwise its
+ local closure blocks pickling (`#4469 <https://github.com/kornia/kornia/issues/4469>`_).
"""
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index d9717c473..ecc074f8e 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -42,10 +42,9 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
- its transformation matrix is the ordered product of its geometric wrapped operations. Intensity
operations do not contribute to that matrix.
- ``forward_parameters`` samples each child through
- :meth:`~kornia.augmentation.auto.operations.OperationBase.forward_parameters`, so a policy entry gets
- the operation's magnitude and magnitude mapping, including the random sign of a symmetric magnitude,
- as it does under :class:`~kornia.augmentation.auto.RandAugment`. The gate comes from the wrapped
- augmentation's ``p``. Policy augmentations use their own samplers where needed.
+ :meth:`~kornia.augmentation.auto.operations.OperationBase.forward_parameters`, so the operation's
+ magnitude, magnitude mapping and symmetric sign apply; the gate comes from the wrapped augmentation's
+ ``p``.
Args:
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 c3bc3d0a8..e24a711f3 100644
--- a/kornia/augmentation/auto/rand_augment/rand_augment.py
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -55,18 +55,15 @@ class RandAugment(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``. Two kinds of entry depart from
- that formula. ``posterize`` runs its range backwards, ``high - (high - low) * m / 30``, so a larger ``m``
- keeps fewer bits. A ``translate_x`` / ``translate_y`` range is a fraction of the image width / height
- and the value is multiplied by that size, so ``m=15`` on the default ``("translate_x", -0.1, 0.1)`` shifts
- a 32-pixel-wide image by ``1.6`` pixels either way. The 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``, and ``posterize`` truncates it to integer bits, so the default ``("posterize", 4.0, 8.0)``
- keeps ``7`` bits at ``m=7``, ``6`` at ``m=15`` and ``4`` at ``m=29``.
+ - ``m`` must be strictly between ``0`` and ``30`` and sets the magnitude of every selected operation that
+ has one to ``low + (high - low) * m / 30`` over its magnitude range. A symmetric operation's range is
+ ``(0, max)`` with a random sign per row: ``m=15`` on ``("rotate", -30, 30)`` gives ``+15`` or ``-15``. A
+ ``translate_x`` / ``translate_y`` value is a fraction of the image width / height, applied in pixels.
+ The operation's magnitude mapping is the identity for every default entry except ``shear_x`` /
+ ``shear_y``, which multiply by ``180`` (``27`` degrees at ``m=15`` for the default range), and
+ ``posterize``, which truncates to integer bits. ``posterize`` also runs its range backwards,
+ ``high - (high - low) * m / 30``, so a larger ``m`` keeps fewer bits (``7``, ``6`` and ``4`` at ``m=7``,
+ ``15`` and ``29``).
Args:
n: the number of augmentations to apply sequentially. Must be at least ``1`` and at
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 9ae7d48f4..ce342bd86 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -59,10 +59,6 @@ class _BasicAugmentationBase(nn.Module):
See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.
- ``set_rng_device_and_dtype`` updates RNG-related state, but sampler migration and returned parameter
- placement are not uniform across generators. See :doc:`/get-started/conventions` and the limitations
- tracked in `#4426 <https://github.com/kornia/kornia/issues/4426>`_.
-
For automatically generating the corresponding ``__repr__`` with full customized parameters, you may need to
implement ``_param_generator`` by inheriting ``RandomGeneratorBase`` for generating random parameters and
put all static parameters inside ``self.flags``. You may take the advantage of ``PlainUniformGenerator`` to
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 7f5b44550..f22296ca5 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -96,50 +96,35 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
handler-dependent: some warps honor it, but resize mask paths replace it.
With :class:`~kornia.augmentation.RandomResizedCrop`,
boolean ``align_corners`` overrides raise ``ValueError`` in the default ``cropping_mode='slice'``
- mask path; ``cropping_mode='resample'`` accepts them. ``None`` works in both modes.
+ mask path (`#4802 <https://github.com/kornia/kornia/issues/4802>`_); ``cropping_mode='resample'``
+ accepts them. ``None`` works in both modes.
:class:`~kornia.augmentation.RandomElasticTransform` has its own mask path and honours
- both entries, but requires a ``kornia.constants.Resample`` member rather than a
- string.
+ both entries. Unlike the constructors, the override is not normalized: a string ``resample``
+ raises ``AttributeError`` wherever the mask is resampled, so pass a
+ ``kornia.constants.Resample`` member (`#4815 <https://github.com/kornia/kornia/issues/4815>`_).
Convention:
- - consult each child's base and concrete class for its contract; mix and 3D children do not inherit
- every :class:`~kornia.augmentation.AugmentationBase2D` convention.
- - ``data_keys`` names one entry per positional argument, case-insensitively, out of ``input``,
- ``image``, ``mask``, ``bbox``, ``bbox_xyxy``, ``bbox_xywh``, ``keypoints``, ``label`` and ``class``
- (``input`` is an alias of ``image``, ``class`` of ``label``). Any other spelling -- ``boxes``,
- ``points``, ``bboxes``, ``keypoint`` -- raises ``KeyError``. With ``data_keys=None`` the call takes a
- dict instead. Dictionary names match these same names, optionally followed by an underscore or
- hyphen suffix, with the longest name taking precedence. Unrecognized names (for example,
- ``imagenet_id``, ``images``, ``masks``, ``labels``, ``bboxes``, ``inputs`` and ``keypoint``) are
- returned unchanged as metadata, without a warning; unlike positional mode, dict mode does not
- reject these names. Use recognized names such as ``mask_2`` and ``keypoints`` for augmentation.
- ``class`` and any key beginning with ``class_`` or ``class-`` (for example, ``class_id`` or
- ``class_weights``) route to labels and inherit label limitations, including unsupported
- label-changing mix augmentations. A coordinate-box name must be followed by ``_``
- or ``-`` to retain its format: ``bbox_xyxy2`` instead matches ``bbox`` and requires vertex boxes.
- The input dictionary is not modified.
+ - each child keeps the contract of its own base and class; mix and 3D children do not inherit every
+ :class:`~kornia.augmentation.AugmentationBase2D` convention.
+ - ``data_keys`` names one entry per positional argument, case-insensitively: ``input`` (alias
+ ``image``), ``mask``, ``bbox``, ``bbox_xyxy``, ``bbox_xywh``, ``keypoints`` and ``label`` (alias
+ ``class``); any other name raises ``KeyError``. With ``data_keys=None`` the call takes a dict whose
+ keys are these names, optionally followed by a ``_`` or ``-`` suffix (``mask_2``, ``class_id``). The
+ longest matching name wins and a suffix needs its separator: ``bbox_xyxy2`` is a ``bbox`` key and must
+ hold vertices. Unrecognized keys (``images``, ``masks``, ``labels``) are returned unchanged, without a
+ warning. The input dict is not modified.
- the layouts are ``(B, C, H, W)`` for images and masks, ``(B, N, 4, 2)`` vertices for ``bbox``,
- ``(B, N, 4)`` for ``bbox_xyxy`` and ``bbox_xywh``, and ``(B, N, 2)`` in ``(x, y)`` for ``keypoints``.
- For 3D augmentations, inputs must be ``(D, H, W)`` or ``(B, C, D, H, W)``; rank-4 input is rejected
- because ``(C, D, H, W)`` and ``(B, C, H, W)`` are ambiguous. Feeding a coordinate layout under another
- coordinate key raises ``ValueError`` naming the expected shape. ``N = 0`` is
- accepted on every one of them. A ``mask`` is the one key whose rank changes: a ``(B, H, W)`` mask is
- accepted and returned as ``(B, 1, H, W)``. A wrong input *rank* raises ``RuntimeError`` here rather than
- the ``ValueError`` a bare augmentation raises.
- - boxes are read and written in the inclusive ``xyxy_plus`` convention of
- :class:`~kornia.geometry.boxes.Boxes`, which is one unit wider per axis than the exclusive ``xyxy``
- of torchvision and COCO. Flips follow the same inclusive, integer-centre rule as
- :func:`~kornia.geometry.transform.hflip`: ``x' = W - 1 - x`` and ``y' = H - 1 - y``, for the image,
- the mask, the keypoints and all three box spellings alike, and ``bbox_xywh`` keeps its ``w`` and
- ``h``. Labels are passed through untouched by a geometric step.
- - mask resampling normally uses nearest interpolation, but this does not guarantee label preservation:
- padding can introduce a fill value. Masks are converted to the image working dtype: that of the most
- recent image argument before the mask, or of the call's first image when none precedes it, which can
- happen in dictionary insertion order (a list ``data_keys`` must start with the image). Each mask output
- comes back in the dtype of its own argument (per element for a list), ``bool`` included, so masks of
- different dtypes do not affect each other. The conversion through the image working dtype can still
- round integer labels that dtype cannot represent exactly, for example ``2049`` through ``float16``.
- Tracked in `#4478 <https://github.com/kornia/kornia/issues/4478>`_.
+ ``(B, N, 4)`` for ``bbox_xyxy`` and ``bbox_xywh``, and ``(B, N, 2)`` in ``(x, y)`` for ``keypoints``;
+ ``N = 0`` is accepted. 3D inputs are ``(D, H, W)`` or ``(B, C, D, H, W)``; rank 4 is rejected as
+ ambiguous. A ``(B, H, W)`` mask is returned as ``(B, 1, H, W)``, or as ``(B, H, W)`` under
+ ``keepdim=True``. A wrong input rank raises ``RuntimeError`` here rather than the ``ValueError`` of a
+ bare augmentation (`#4424 <https://github.com/kornia/kornia/issues/4424>`_).
+ - boxes use the inclusive ``xyxy_plus`` convention of :class:`~kornia.geometry.boxes.Boxes`. Flips map
+ ``x' = W - 1 - x`` and ``y' = H - 1 - y`` for every key, as :func:`~kornia.geometry.transform.hflip`
+ does. Labels pass through geometric steps untouched.
+ - masks are resampled with nearest interpolation by default (see ``extra_args``; padding can still add the
+ fill value) in the image's working dtype and come back in their own dtype; integer labels that the
+ working dtype cannot represent are rounded (`#4478 <https://github.com/kornia/kornia/issues/4478>`_).
- a ``mask`` argument can be a list of tensors with different channel counts, but its batch handling
has limitations. Each list entry uses only ``batch_prob[i]`` as its gate, including for intensity
children. Per-sample list tensors are unsupported by warp operations, and full-batch tensors in that
@@ -148,36 +133,16 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.
- supported geometric data-key handlers share the recorded transform, subject to the mask limitations
above. Custom rigid subclasses are not dispatched solely because they supply a matrix
- (`#4481 <https://github.com/kornia/kornia/issues/4481>`_). A non-rigid child has no transform matrix,
- so the coordinate
- keys drop out of that draw: :class:`~kornia.augmentation.RandomElasticTransform` warps the image and
- a ``mask`` key through the same displacement field, while the keypoints and the boxes come
- back unchanged; :class:`~kornia.augmentation.RandomThinPlateSpline` and
- :class:`~kornia.augmentation.RandomFisheye` leave keypoints and boxes unchanged too and raise
- ``NotImplementedError`` on a ``mask`` key (see the warning below).
- - ``.inverse()`` undoes applicable 2D geometric steps and leaves intensity and non-rigid steps applied.
- Slice-mode crop inverses raise ``NotImplementedError``; resample-mode crops can be inverted. Tensor box
- outputs take axis-aligned enclosures, so a non-axis-aligned rotation can lose the corners needed
- to recover the original boxes. Retaining a ``Boxes`` object preserves its transformed corners.
- Inverse resampling cannot recover image or mask information lost through cropping, padding or
- interpolation. A 3D geometric child has no inverse and raises ``NotImplementedError``; 3D intensity
- children are skipped.
- - ``same_on_batch`` and ``keepdim`` are three-state here: ``None``, the default, keeps whatever each
- child was built with, while ``True`` and ``False`` overwrite the child's own setting in both
- directions.
- - ``random_apply`` selects children per call in random order, with replacement when necessary.
- Mix children use a separate selection path inherited from ``ImageSequential``;
- ``transformation_matrix_mode`` decides
- what ``.transform_matrix`` does with a non-rigid child. ``silent``, the default (and its
- alias ``silence``), skips a direct non-rigid child and keeps accumulating the rigid
- ones, so a chain with no rigid child at all leaves ``.transform_matrix`` at ``None``. A nested
- container is an order-sensitive exception even when it contains only rigid children: a rigid
- child followed by a nested container can raise ``TypeError``, while the reverse order can omit the
- nested transform. A nested container called previously may also contribute a stale matrix. Do not
- rely on a nested container's matrix. Tracked in `#4476 <https://github.com/kornia/kornia/issues/4476>`_.
- ``rigid`` raises ``RuntimeError`` during forward after a direct non-rigid child runs; it does not
- inspect nested children. ``skip`` leaves
- ``.transform_matrix`` at ``None`` whatever the chain.
+ (`#4481 <https://github.com/kornia/kornia/issues/4481>`_). A non-rigid warp child has no matrix, so
+ the coordinate keys are left unchanged; see the warning below.
+ - ``.inverse()`` undoes the 2D geometric steps and leaves intensity and non-rigid steps applied. Slice-mode
+ crops and 3D geometric children raise ``NotImplementedError``, mix children ``RuntimeError``. Tensor
+ boxes come back as axis-aligned enclosures; pass :class:`~kornia.geometry.boxes.Boxes` to keep rotated
+ corners. Content lost to cropping, padding or interpolation is not recovered.
+ - ``same_on_batch`` and ``keepdim`` default to ``None``, which keeps each child's own setting;
+ ``True`` or ``False`` overrides it.
+ - ``.transform_matrix`` of a chain holding a nested container is unreliable: it can raise, omit the
+ nested transform or return a stale one (`#4476 <https://github.com/kornia/kornia/issues/4476>`_).
.. warning::
A non-rigid child silently desynchronizes the coordinate data keys:
@@ -188,12 +153,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
Tracked in `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
.. note::
- Inside this container a mix child (e.g. RandomMixUpV2, RandomCutMixV2, RandomMosaic) dispatches
- ``mask``, box and ``keypoints`` keys to the child's own handlers, using the same parameters as the
- mixed image. Keys the child does not implement raise ``NotImplementedError``, matching a direct call
- (for example ``RandomMosaic`` transforms boxes and refuses masks/keypoints). A ``class``/``label`` key
- still raises ``NotImplementedError`` from the container. Fixed in
- `#4493 <https://github.com/kornia/kornia/issues/4493>`_.
+ A mix child (e.g. RandomMixUpV2, RandomCutMixV2, RandomMosaic) receives ``mask``, box and ``keypoints``
+ keys with the image's parameters; keys it does not implement raise ``NotImplementedError``, as in a
+ direct call. A ``class``/``label`` key raises ``NotImplementedError`` from the container.
.. note::
See a working example `here <https://www.kornia.org/tutorials/nbs/data_augmentation_sequential.html>`__.
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 1b55e5324..3bb4a5f87 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -660,7 +660,7 @@ class TestConventionAugmentationSequential(BaseTester):
# for the image, the mask, keypoints and boxes alike - inclusive pixel coordinates about the integer
# centre, the same rule `kornia.geometry.transform.hflip` / `vflip` follow.
# H = 3, W = 4 (asymmetric); hot pixel (row 0, col 1), off both centre lines; keypoint (x=1, y=2).
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu). hflip:
+ # Snippet used to generate expected: this body. hflip:
# pixel -> (row 0, col 2), keypoint -> (2, 2), bbox_xyxy [0,0,1,1] -> [2, 0, 3, 1], bbox vertices ->
# [[2,0],[3,0],[3,1],[2,1]]. vflip: pixel -> (row 2, col 1), keypoint -> (1, 0),
# bbox_xyxy -> [0, 1, 1, 2]. An exclusive reading (x' = W - x) would give keypoint (3, 2) and
@@ -698,7 +698,7 @@ class TestConventionAugmentationSequential(BaseTester):
# Convention pin: each data key has one accepted layout - `bbox` is (B, N, 4, 2) vertices, `bbox_xyxy`
# is (B, N, 4) corners, `keypoints` is (B, N, 2) - and feeding one layout under the other key raises
# `ValueError` naming the expected shape and the box mode.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu):
+ # Snippet used to generate expected: this body:
# "Boxes shape must be (N, 4, 2) or (B, N, 4, 2) when vertices_plus mode. Got torch.Size([1, 1, 4])."
# "Boxes shape must be (N, 4) or (B, N, 4) when xyxy_plus mode. Got torch.Size([1, 1, 4, 2])."
# "Keypoints shape must be (N, 2) or (B, N, 2). Got torch.Size([1, 2, 3])."
@@ -749,15 +749,17 @@ class TestConventionAugmentationSequential(BaseTester):
# Keep a deliberate invalid-index probe on CPU to avoid accelerator context poisoning.
cpu_image = image.cpu()
- with pytest.raises(IndexError, match="index 2 is out of bounds for dimension 0 with size 2"):
+ with pytest.raises(IndexError):
seq(cpu_image, [cpu_image.clone() for _ in range(3)], params=params)
def test_wart_per_sample_mask_lists_fail_warps_and_reuse_crop_window_4477(self, device, dtype):
image = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4).repeat(2, 1, 1, 1)
masks = [image[:1].clone(), image[1:].clone()]
warp = K.AugmentationSequential(K.RandomAffine((30.0, 30.0), p=1.0), data_keys=["input", "mask"])
- with pytest.raises(RuntimeError, match="batch size"):
+ with pytest.raises(RuntimeError):
warp(image, masks)
+ # Control: full-batch list entries warp, so the failure above is the per-sample entries.
+ assert [mask.shape for mask in warp(image, [image.clone(), image.clone()])[1]] == [(2, 1, 4, 4)] * 2
crop = K.AugmentationSequential(K.RandomCrop((2, 2), p=1.0), data_keys=["input", "mask"])
params = crop.forward_parameters(image.shape)
params[0].data["src"] = torch.tensor(
@@ -813,10 +815,9 @@ class TestConventionAugmentationSequential(BaseTester):
seq.inverse(*output)
def test_mix_children_dispatch_annotation_keys_4493(self, device, dtype):
- # Regression (#4493): mix children used to fall through Mask/Box/KeypointSequentialOps to a silent
- # passthrough, so annotations desynchronized from the mixed image. The container now dispatches to
- # the child's own handlers: RandomMosaic transforms boxes (container xyxy_plus path), and unsupported
- # keys raise NotImplementedError as a direct call does. A class key still raises from the container.
+ # #4493: the container dispatches a mix child's annotation keys to the child's own handlers: RandomMosaic
+ # transforms boxes (container xyxy_plus path), and unsupported keys raise NotImplementedError as a direct
+ # call does. A class key raises from the container.
from kornia.geometry.boxes import Boxes
image = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
@@ -824,7 +825,7 @@ class TestConventionAugmentationSequential(BaseTester):
mask = torch.arange(2, device=device, dtype=dtype).reshape(2, 1, 1, 1).expand(2, 1, 16, 16).clone()
keypoints = torch.tensor([[[1.0, 1.0]], [[2.0, 2.0]]], device=device, dtype=dtype)
- # RandomMosaic boxes are transformed inside the container (no longer passthrough).
+ # RandomMosaic boxes are transformed inside the container.
seq = K.AugmentationSequential(K.RandomMosaic(p=1.0), data_keys=["input", "bbox_xyxy"])
torch.manual_seed(0)
out_image, out_boxes = seq(image, boxes)
@@ -857,9 +858,8 @@ class TestConventionAugmentationSequential(BaseTester):
def test_convention_dictionary_mask_before_image_keeps_float64_precision_4478(self):
# Convention pin for kornia#4478: a mask is converted with this call's image dtype wherever it sits in the
- # dictionary. Until the fix, a mask inserted before the image was converted with the previous call's image
- # dtype, or float32 on a fresh container, so these float64 values, which float32 cannot hold, came back
- # rounded even though the image was float64. Both insertion orders now return the mask bit for bit.
+ # dictionary, so these float64 values, which float32 cannot hold, come back bit for bit in both insertion
+ # orders.
image = torch.zeros(1, 1, 1, 2, dtype=torch.float64)
mask = torch.tensor([1.0 + 2**-30, 2.0 + 2**-29], dtype=torch.float64).reshape_as(image)
early_mask = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)
@@ -872,10 +872,8 @@ class TestConventionAugmentationSequential(BaseTester):
@pytest.mark.parametrize("mask_dtypes", [(torch.int64, torch.bool), (torch.bool, torch.int64)])
def test_convention_each_mask_keeps_its_own_dtype_4478(self, mask_dtypes, device, dtype):
- # Convention pin for kornia#4478: each mask output comes back in the dtype of its own argument. Until the
- # fix every mask output was cast to the dtype of the LAST mask argument, so an integer semantic mask
- # followed by a boolean one came back boolean and labels 2, 3 and 5 collapsed to True. Both orders are
- # covered, so the pin fails whichever mask used to win.
+ # Convention pin for kornia#4478: each mask output comes back in the dtype of its own argument, so labels
+ # 2, 3 and 5 survive next to a boolean mask. Both argument orders are covered.
image = torch.arange(24, device=device, dtype=dtype).reshape(2, 1, 3, 4)
labels = torch.tensor([0, 2, 3, 5], device=device).reshape(1, 1, 1, 4).expand(2, 1, 3, 4)
first, second = (labels.to(mask_dtype) for mask_dtype in mask_dtypes)
@@ -890,9 +888,8 @@ class TestConventionAugmentationSequential(BaseTester):
@pytest.mark.parametrize("mask_dtypes", [(torch.int64, torch.bool), (torch.bool, torch.int64)])
def test_convention_each_list_mask_element_keeps_its_own_dtype_4478(self, mask_dtypes, device, dtype):
- # Convention pin for kornia#4478: a list mask comes back per element in each entry's own dtype. Until the
- # fix every element was cast to the list's first dtype, so a boolean entry after an integer one came back
- # int64 as [1, 1, 1, 0]. Both orders are covered, so the pin fails whichever element used to win.
+ # Convention pin for kornia#4478: a list mask comes back per element in each entry's own dtype. Both
+ # element orders are covered.
image = torch.arange(16, device=device, dtype=dtype).reshape(2, 1, 2, 4)
labels = torch.tensor([0, 2, 3, 5], device=device).reshape(1, 1, 1, 4).expand(1, 1, 2, 4)
entries = [labels.to(mask_dtype) for mask_dtype in mask_dtypes]
@@ -923,9 +920,10 @@ class TestConventionAugmentationSequential(BaseTester):
@pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
@pytest.mark.parametrize("align_corners", [None, False, True])
- def test_convention_resized_crop_mask_align_corners_depends_on_mode(
+ def test_wart_resized_crop_mask_align_corners_depends_on_mode_4802(
self, cropping_mode, align_corners, device, dtype
):
+ # #4802: the slice-mode raise flips when slice mode drops `align_corners` for nearest resampling.
image = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4) / 16
mask = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4).remainder(2)
seq = K.AugmentationSequential(
@@ -934,7 +932,7 @@ class TestConventionAugmentationSequential(BaseTester):
extra_args={DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": align_corners}},
)
if cropping_mode == "slice" and align_corners is not None:
- with pytest.raises(ValueError, match="align_corners option can only be set with the interpolating modes"):
+ with pytest.raises(ValueError):
seq(image, mask)
else:
out_image, out_mask = seq(image, mask)
@@ -946,9 +944,6 @@ class TestConventionAugmentationSequential(BaseTester):
# labels after a 45 degree affine without intermediate values. The zero padding fill is also present,
# and the mask dtype is preserved, `bool` included.
# The claim is checked one parameter away from the pin's fixture: B = 2 and B = 1 both hold.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): value set
- # [0.0, 2.0, 3.0], dtype torch.float32 preserved, bool mask stays torch.bool, max|mask - input mask|
- # 2.0 (the rotation really moved it).
for batch in (2, 1):
aug = K.AugmentationSequential(K.RandomAffine(degrees=(45.0, 45.0), p=1.0), data_keys=["input", "mask"])
mask = torch.full((batch, 1, 6, 8), 2.0, device=device, dtype=dtype)
@@ -1030,7 +1025,7 @@ class TestConventionAugmentationSequential(BaseTester):
# op as well as for a flip - `Boxes.from_tensor(..., mode="xyxy_plus").transform_boxes_(M)` reproduces
# the container's output exactly, while `mode="xyxy"` (exclusive) does not.
# Two asymmetric boxes on a 6x8 image, resized to (3, 4) => M = diag(3/7, 2/5) in xyxy_plus space.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): container
+ # Snippet used to generate expected: this body. Container
# [[0.0, 0.0, 1.2857143, 0.8]], [[0.85714293, 0.4, 2.1428573, 1.6]] == xyxy_plus;
# xyxy gives [[0.0, 0.0, 1.8571429, 1.4]], [[0.85714293, 0.4, 2.7142859, 2.2]].
boxes = torch.tensor([[[0.0, 0.0, 3.0, 2.0]], [[2.0, 1.0, 5.0, 4.0]]], device=device, dtype=dtype)
@@ -1048,8 +1043,6 @@ class TestConventionAugmentationSequential(BaseTester):
# Convention pin: `.inverse()` restores keypoints moved by the geometric chain, while non-axis-aligned
# rotations cannot restore tensor boxes. Forward turns both `bbox_xyxy` and vertex `bbox` formats into
# axis-aligned enclosures, losing the original corners before inverse is called.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): forward
- # max|move| 1.6213202476501465, inverse max|error| 7.152557373046875e-07.
torch.manual_seed(0)
aug = K.AugmentationSequential(K.RandomAffine(degrees=(45.0, 45.0), p=1.0), data_keys=["input", "keypoints"])
img = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
@@ -1088,7 +1081,7 @@ class TestConventionAugmentationSequential(BaseTester):
)
rigid_then_nested = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), nested_rigid(), data_keys=["input"])
assert rigid_then_nested(image).shape == image.shape
- with pytest.raises(TypeError, match=r"unsupported operand type\(s\) for @: 'NoneType' and 'Tensor'"):
+ with pytest.raises(TypeError):
_ = rigid_then_nested.transform_matrix
nested_then_rigid = K.AugmentationSequential(nested_rigid(), K.RandomHorizontalFlip(p=1.0), data_keys=["input"])
@@ -1139,9 +1132,7 @@ class TestConventionAugmentationSequential(BaseTester):
@pytest.mark.parametrize("mask_dtype", [None, torch.int64, torch.bool])
def test_convention_empty_batch_with_mask_4478(self, mask_dtype, device, dtype):
# Convention pin for kornia#4478: an empty batch with a mask returns an empty mask, forward and inverse,
- # in the mask's own dtype. Until the fix it raised IndexError before any op ran: the dtype read tested
- # ``isinstance(inp, list)`` on the accumulator, which is always a list, and so indexed the tensor mask at
- # ``arg[0]``.
+ # in the mask's own dtype.
image = torch.empty(0, 1, 2, 2, device=device, dtype=dtype)
mask = image.clone() if mask_dtype is None else torch.empty(0, 1, 2, 2, device=device, dtype=mask_dtype)
seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
@@ -1217,7 +1208,7 @@ class TestConventionAugmentationSequential(BaseTester):
# Convention pin: `AugmentationSequential(same_on_batch=None)` - the default - keeps whatever each
# child was built with, while `True` and `False` overwrite the child's own setting in both directions.
# `keepdim` follows the same three-state rule.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu), seed 0, B = 4:
+ # Snippet used to generate expected: this body, seed 0, B = 4:
# None over a same_on_batch=True child -> one distinct angle (36.5752067565918 four times);
# False over the same child -> four distinct angles; True over a same_on_batch=False child -> one.
# keepdim: None over a keepdim=True child -> (3, 6, 8), False -> (1, 3, 6, 8), True over False -> (3, 6, 8).
@@ -1243,39 +1234,26 @@ class TestConventionAugmentationSequential(BaseTester):
assert shape(False, True) == (1, 3, 6, 8)
assert shape(True, False) == (3, 6, 8)
+ @pytest.mark.parametrize("factory", [lambda: K.RandomAffine(30.0, p=1.0), lambda: K.RandomElasticTransform(p=1.0)])
+ def test_wart_extra_args_mask_resample_must_be_a_resample_member_4815(self, factory, device, dtype):
+ # #4815: flips when the container normalizes a string override as the constructors do, or rejects it with
+ # a kornia error.
+ image = torch.rand(1, 1, 6, 8, device=device, dtype=dtype)
+ for resample, raises in ((Resample.NEAREST, False), ("nearest", True)):
+ seq = K.AugmentationSequential(
+ factory(), data_keys=["input", "mask"], extra_args={DataKey.MASK: {"resample": resample}}
+ )
+ if raises:
+ with pytest.raises(AttributeError):
+ seq(image, image.clone())
+ else:
+ assert seq(image, image.clone())[1].shape == image.shape
+
def test_extra_args_mask_override_reaches_the_sampler_4419(self, device, dtype):
- # #4419: `extra_args[DataKey.MASK]` is the documented way to control how masks are handled, and both
- # halves of it reach the sampler. The base 2D geometric mask path used to overwrite `resample` with
- # NEAREST after merging the override, so asking for bilinear changed nothing on `RandomAffine`, while
- # the `align_corners` half of the same dict was honoured. `RandomElasticTransform`, which has its own
- # mask path, honours both halves.
- # Snippet used to generate expected: this body, executed 2026-09-14 (torch 2.9.1, cpu), seed 0, a
- # (1, 1, 6, 8) mask with a 1-block: RandomAffine with padding_mode="reflection" align_corners
- # override 1.0.
- # The align_corners fixture was `RandomPerspective(0.5, p=1.0)` with zero padding until #3945. That
- # delta was 1.0 only because the two conventions disagreed on in-bounds samples: the sampling grid
- # was built corner-aligned whatever flag reached grid_sample, so align_corners=True vs False shifted
- # the mask by half a pixel. #3945 makes the grid follow the flag, so the two now agree wherever the
- # sample lands inside the image and that delta collapsed to 0.0 (float32, float64, float16 and
- # bfloat16 alike). They still differ out of bounds, because +/-1 spans a different extent under each
- # convention, so the fixture moves to a transform that samples outside the frame and a padding_mode
- # that makes those samples observable. Sweep, seeds 0-9: delta is exactly 1.0 at every seed on cpu
- # float32, float64, float16 and bfloat16.
- # The elastic half uses its own fixture, reusing the #4420 pin's style below: `RandomElasticTransform
- # (alpha=(5.0, 5.0), sigma=(4.0, 4.0), p=1.0)` on a checkerboard mask, same (1, 1, 6, 8), H != W frame,
- # instead of the default alpha/sigma with a solid block. #4382 ("fix: respect align_corners in elastic
- # transform grid"), now in this branch's rebased base, shrank the displacement at the default fixture
- # until the bilinear-vs-nearest mask delta collapsed - 0.0093 (float32) / 0.0076 (float64) at seed 0,
- # both under the old > 0.1 threshold - and a solid block mask can also map onto itself under a small
- # warp regardless of alpha/sigma, so a checkerboard is used instead.
- # Sweep, seeds 0-9, this elastic fixture: min/max delta 0.461683/0.739558 on cpu float32, 0.292913/
- # 0.716883 on cpu float64, 0.462891/0.740234 on cpu float16, 0.472656/0.742188 on cpu bfloat16, and
- # 0.401424/0.749953 on mps float32 - never near the old default-fixture value at any seed or dtype
- # checked, so `> 0.1` stays a safe threshold. Seed-0 delta: 0.739558 (cpu float32), 0.588690 (cpu
- # float64), 0.740234 (cpu float16), 0.742188 (cpu bfloat16), 0.749953 (mps float32). The half-dtype
- # skip that used to guard this pin is dropped: affine and perspective are exact on float16/bfloat16
- # (0.0 and 1.0, matching float32/float64) and the elastic delta stays far above the threshold there
- # too.
+ # #4419: both halves of `extra_args[DataKey.MASK]` reach the sampler; `RandomElasticTransform`, which has
+ # its own mask path, honours both too. The align_corners fixture samples outside the frame with
+ # padding_mode="reflection", where the two conventions differ (delta 1.0). The elastic fixture uses a
+ # checkerboard mask and a displacement large enough to keep the bilinear-vs-nearest delta well above 0.1.
def mask_of(aug_factory, extra):
torch.manual_seed(0)
@@ -1376,7 +1354,6 @@ class TestConventionAugmentationSequential(BaseTester):
# `RandomThinPlateSpline` / `RandomFisheye` raise a bare `NotImplementedError` (no message) on a mask
# key.
# Seed zero and a checkerboard with a stronger displacement expose both the image and mask warp.
- # The observed displacement depends on dtype/backend; this fixture does not assert a sweep over seeds.
torch.manual_seed(0)
aug = K.AugmentationSequential(
K.RandomElasticTransform(p=1.0, alpha=(5.0, 5.0), sigma=(4.0, 4.0)),
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 87072fde9..8848ed2ee 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -416,10 +416,8 @@ class TestDeviceAgnosticAugmentationParameters(BaseTester):
self.assert_close(output, expected)
-# Batch-6 convention pins for the `kornia.augmentation` shared contract (anchor 1: `AugmentationBase2D`).
-# Every literal below was generated by the body of the pin that carries it, executed on this worktree on
-# 2026-09-11 with `.venv/bin/python` (torch 2.14.0, python 3.11, cpu, float32) unless the comment says
-# otherwise. Fixtures are asymmetric (H != W, a hot pixel off both centre lines) and every random draw is
+# Pins for the shared `AugmentationBase2D` contract. Every literal below was generated by the body of the pin
+# that carries it. Fixtures are asymmetric (H != W, a hot pixel off both centre lines) and every random draw is
# either seeded inside the test or made deterministic with `p=1.0` plus a point range such as
# `degrees=(45.0, 45.0)`.
@@ -499,7 +497,7 @@ _RNG_FINGERPRINTS = {
"PatchSequential": (
lambda: K.PatchSequential(K.RandomAffine(degrees=(10.0, 90.0), p=1.0), grid_size=(2, 2), patchwise_apply=False),
(4, 3, 6, 8),
- # One draw per patch row: B * rows * columns = 4 * 2 * 2 (B * C = 12 before #4460 fixed #4421).
+ # One draw per patch row: B * rows * columns = 4 * 2 * 2 (#4421).
[("rand", (16,))],
),
}
@@ -513,8 +511,6 @@ class TestConventionAugmentationBase2D(BaseTester):
# Convention pin: an augmentation always works on (B, C, H, W). A (C, H, W) input is promoted to
# (1, C, H, W) and a bare (H, W) to (1, 1, H, W); `keepdim=True` restores the input rank on the way
# out and never drops a real batch dimension.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu):
- # (1, 3, 6, 8) / (3, 6, 8) / (1, 1, 6, 8) / (2, 3, 6, 8).
x = torch.rand(3, 6, 8, device=device, dtype=dtype)
assert K.RandomHorizontalFlip(p=1.0)(x).shape == (1, 3, 6, 8)
assert K.RandomHorizontalFlip(p=1.0, keepdim=True)(x).shape == (3, 6, 8)
@@ -527,8 +523,6 @@ class TestConventionAugmentationBase2D(BaseTester):
def test_convention_integer_input_is_rejected(self, device):
# Convention pin: the dtype policy is enforced - an integer image raises `TypeError` naming the four
# accepted float dtypes, for `uint8` and `int64` alike.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu):
- # "Expected input of [torch.bfloat16, torch.float16, torch.float32, torch.float64]. Got torch.uint8".
expected = r"Expected input of \[torch.bfloat16, torch.float16, torch.float32, torch.float64\]"
for bad in (torch.uint8, torch.int64):
with pytest.raises(TypeError, match=expected):
@@ -540,8 +534,6 @@ class TestConventionAugmentationBase2D(BaseTester):
# `RuntimeError` with a different message, and `validate_tensor`'s own
# `RuntimeError` (which also rejects the legal (C, H, W) rank). `forward` promotes legal unbatched
# inputs before validation.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu).
- # The repair window picks one exception type; do not "correct" this pin here.
x5 = torch.rand(1, 2, 3, 6, 8, device=device, dtype=dtype)
with pytest.raises(ValueError, match="Input size must have a shape of either"):
K.RandomHorizontalFlip(p=1.0)(x5)
@@ -556,10 +548,6 @@ class TestConventionAugmentationBase2D(BaseTester):
def test_convention_numeric_ranges_return_cpu_parameters_independently_of_input(self, device, dtype):
# With numeric ranges and unchanged CPU defaults, returned parameter placement is independent of
# the image. This pin checks returned tensors, not the sampling backend/precision (covered below).
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0) for a float64
- # input: every `_params` entry `cpu`, the float entries `torch.float32`, output and matrix float64.
- # Only the `--dtype=float64` leg separates the two dtypes; on a float32 leg (and on mps, which has no
- # float64) the dtype half is a tautology and the device half is what bites.
aug = K.RandomAffine(degrees=(45.0, 45.0), translate=(0.2, 0.2), p=1.0)
out = aug(torch.rand(2, 3, 6, 8, device=device, dtype=dtype))
assert aug._params["angle"].dtype == torch.get_default_dtype()
@@ -571,7 +559,6 @@ class TestConventionAugmentationBase2D(BaseTester):
# Convention pin: `p` is a per-sample Bernoulli and `p_batch` a single Bernoulli that gates the whole
# batch; a sample is augmented only when both fire. Drawn on the cpu generator, so no device/dtype
# fixture is involved; seeded inside the test.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu).
flip = K.RandomHorizontalFlip
assert flip(p=1.0, p_batch=0.0).forward_parameters((4, 3, 6, 8))["batch_prob"].tolist() == [0.0] * 4
assert flip(p=0.0, p_batch=1.0).forward_parameters((4, 3, 6, 8))["batch_prob"].tolist() == [0.0] * 4
@@ -652,25 +639,19 @@ class TestConventionAugmentationBase2D(BaseTester):
(K.RandomTransplantation3D, (3, 6, 8)),
],
)
- def test_convention_transplantation_requires_masks_and_supports_mask_only(
- self, augmentation_cls, spatial_shape, device
- ):
- # A mask is required to choose the transplant, but images are optional. Three donors make the cyclic
- # donor direction observable: p=1 replaces every acceptor with its preceding donor.
+ def test_convention_transplantation_supports_a_mask_only_call(self, augmentation_cls, spatial_shape, device):
+ # Images are optional (a missing mask is #4777). Three donors make the cyclic donor direction observable:
+ # p=1 replaces every acceptor with its preceding donor.
mask = torch.arange(3, device=device, dtype=torch.int64).reshape(3, *((1,) * len(spatial_shape)))
mask = mask.expand(3, *spatial_shape)
augmentation = augmentation_cls(p=1.0)
output = augmentation(mask, data_keys=["mask"])
+ assert isinstance(output, torch.Tensor) # a single output is a bare tensor
self.assert_close(output, torch.roll(mask, 1, dims=0))
- image = torch.zeros((3, 3, *spatial_shape), device=device)
- with pytest.raises(IndexError, match="tuple index out of range"):
- augmentation(image)
def test_convention_same_on_batch_collapses_the_draw_to_one_sample(self):
# Convention pin: `same_on_batch=True` collapses every per-sample draw - the `p` gate included - to a
# single value broadcast over the batch. Same seeds as the pin above, whose `p=0.5` rows are mixed.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): seeds 0..3
- # give [1,1,1,1], [0,0,0,0], [0,0,0,0], [1,1,1,1], and the angles are constant across the batch.
rows = []
for seed in range(4):
torch.manual_seed(seed)
@@ -702,7 +683,6 @@ class TestConventionAugmentationBase2D(BaseTester):
def test_convention_global_seed_reproduces_the_draw(self):
# Convention pin: reproducibility goes through the global torch CPU generator - `torch.manual_seed`
# before the draw reproduces `forward_parameters` key for key, bitwise.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): True.
torch.manual_seed(1)
first = K.RandomAffine(degrees=45.0, translate=(0.2, 0.2)).forward_parameters((2, 1, 8, 8))
torch.manual_seed(1)
@@ -715,11 +695,9 @@ class TestConventionAugmentationBase2D(BaseTester):
# container, and `forward` silently accepts and drops it - together with any other unknown keyword -
# because `forward` funnels its `**kwargs` into `override_parameters`. The passed generator is never
# consumed, so the output still follows the global seed.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): TypeError,
- # TypeError, output shape (2, 3, 6, 8), and the two seeded outputs bitwise equal.
- with pytest.raises(TypeError, match="unexpected keyword argument 'generator'"):
+ with pytest.raises(TypeError):
K.RandomAffine(degrees=45.0, generator=torch.Generator())
- with pytest.raises(TypeError, match="unexpected keyword argument 'generator'"):
+ with pytest.raises(TypeError):
K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), generator=torch.Generator())
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
gen = torch.Generator()
@@ -735,8 +713,6 @@ class TestConventionAugmentationBase2D(BaseTester):
def test_convention_params_replay_is_bitwise_and_the_dict_is_stored_by_reference(self, device, dtype):
# Convention pin for a complete generated dictionary: `params=` replaces the previous draw,
# stores the dictionary by reference and replays this affine bitwise without changing its entries.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): bitwise True,
- # `aug._params is params` True, no key added, no value mutated.
aug = K.RandomAffine(degrees=(45.0, 45.0), translate=(0.2, 0.2), p=1.0)
x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
first = aug(x)
@@ -900,8 +876,6 @@ class TestConventionAugmentationBase2D(BaseTester):
# Parameter-valued ranges are covered separately below. They survive pickle and deepcopy while
# carrying the last `_params`. Other classes register range buffers; that distinction is pinned in
# `test_wart_param_generator_range_buffers_are_inert_4428`.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): 0 state_dict
- # entries, no buffers, no parameters, pickle and deepcopy OK for each representative.
aug = _STATELESS_REPRESENTATIVES[name]()
assert len(aug.state_dict()) == 0
assert list(aug.buffers()) == []
@@ -930,10 +904,6 @@ class TestConventionAugmentationBase2D(BaseTester):
# expose it in `state_dict()` (and, inside a container, under a prefixed key), but the buffer is a
# dead copy: `load_state_dict` from an instance with a different range changes the buffer and changes
# neither the draw nor the `repr`, so a `state_dict` round trip is a silent no-op.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): the buffer
- # moves [80.0, 81.0] -> [10.0, 11.0] while the draw stays in [80, 81]
- # ([80.30742645263672, 80.63407897949219, 80.49009704589844, 80.89644622802734]) and the repr still
- # says degrees=(80.0, 81.0).
assert list(K.RandomRotation(degrees=(80.0, 81.0)).state_dict()) == ["_param_generator.degrees"]
assert list(K.AugmentationSequential(K.RandomRotation(degrees=(10.0, 90.0))).state_dict()) == [
"RandomRotation_0._param_generator.degrees"
@@ -948,7 +918,8 @@ class TestConventionAugmentationBase2D(BaseTester):
assert bool(((drawn >= 80.0) & (drawn <= 81.0)).all())
assert "degrees=(80.0, 81.0)" in repr(target)
- def test_convention_sampler_precision_is_separate_from_returned_dtype_4426(self):
+ def test_wart_sampler_precision_is_separate_from_returned_dtype_4426(self):
+ # #4426: flips when the returned parameters follow the requested dtype like `batch_prob` does.
original_dtype = torch.get_default_dtype()
try:
torch.set_default_dtype(torch.float32)
@@ -974,7 +945,9 @@ class TestConventionAugmentationBase2D(BaseTester):
finally:
torch.set_default_dtype(original_dtype)
- def test_convention_set_rng_device_moves_sampling_before_casting_parameters_4426(self, device):
+ def test_wart_set_rng_device_moves_sampling_but_not_returned_parameters_4426(self, device):
+ # #4426: flips when the returned angle follows the requested device like `batch_prob` does; only an
+ # accelerator leg can see that, since on CPU both devices are the same.
aug = K.RandomAffine(degrees=(10.0, 90.0), p=1.0)
aug.set_rng_device_and_dtype(device, torch.float32)
assert aug._param_generator.degree_sampler.low.device == device
@@ -1028,8 +1001,6 @@ class TestConventionAugmentationBase2D(BaseTester):
def test_convention_zero_batch_passes_through(self, device, dtype):
# Convention pin (#4115 family, empty in -> empty out): a `B = 0` batch survives the flip, the affine
# and an intensity op, and survives `AugmentationSequential`, keeping the (0, C, H, W) shape.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu): (0, 3, 6, 8)
- # from all four.
if device.type == "mps" and torch_version_lt(2, 6, 0):
pytest.skip("torch 2.5.1 MPS asserts on an empty placeholder tensor inside grid_sample")
empty = torch.rand(0, 3, 6, 8, device=device, dtype=dtype)
@@ -1050,11 +1021,6 @@ class TestConventionAugmentationBase2D(BaseTester):
# Wart pin (#4429): `B = 0` is not uniformly "empty in, empty out". These representative
# augmentations raise through distinct failure paths; RandomAutoContrast is a deliberate validation
# error and the other exposes an implementation detail.
- # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu):
- # LongestMaxSize KeyError('output_size'), RandomAutoContrast ValueError('Invalid input tensor, it is
- # empty.').
- # Normalize used to be a further family, fixed by #4681; RandomCrop's IndexError from
- # crop_by_indices was another.
builders = {
"LongestMaxSize": lambda: K.LongestMaxSize(16, p=1.0),
"RandomAutoContrast": lambda: K.RandomAutoContrast(p=1.0),
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index a52fc6285..cb325c7bd 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -58,14 +58,10 @@ class Test3DAugmentationConventions(BaseTester):
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)
+ def test_convention_flip_matrix_keeps_the_input_dtype(self, device, dtype):
augmentation = K.RandomHorizontalFlip3D(p=1.0)
- augmentation(volume)
- assert augmentation.transform_matrix.dtype is torch.float16
- assert augmentation.transform_matrix[0, 0, 3] == 2048
+ augmentation(torch.zeros(1, 1, 2, 3, 4, device=device, dtype=dtype))
+ assert augmentation.transform_matrix.dtype == dtype
@pytest.mark.device_agnostic
def test_convention_degrees_and_motion_angle_follow_xyz_order(self):
@@ -198,24 +194,27 @@ class Test3DAugmentationConventions(BaseTester):
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))
+ # The motion-blur kernels split the same way: the 3D roll follows RandomRotation3D, the 2D angle does not.
+ def tilt(plane):
+ nonzero = (plane.abs() > 1e-4).nonzero().float()
+ centred = nonzero - nonzero.mean(0)
+ return float((centred[:, 0] * centred[:, 1]).sum())
+
+ impulse = torch.zeros(1, 1, 3, 15, 15)
+ impulse[0, 0, 1, 7, 7] = 1.0
+ rolled = K.RandomMotionBlur3D(9, (zero, zero, (30.0, 30.0)), 0.0, p=1.0)(impulse)[0, 0, 1]
+ flat = K.RandomMotionBlur(9, (30.0, 30.0), 0.0, p=1.0)(impulse[:, :, 1])[0, 0]
+ assert tilt(rolled) > 0 # rows increase with columns: clockwise as displayed
+ assert tilt(flat) == -tilt(rolled)
@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(
+ def test_wart_affine_and_rotation3d_move_an_asymmetric_marker_opposite_ways_4408(
self, axis, rotation_position, affine_position, device, dtype
):
+ # #4408: RandomAffine3D turns the other way from RandomRotation3D; flips when either follows the other.
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.
@@ -297,20 +296,21 @@ class Test3DAugmentationConventions(BaseTester):
)
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):
+ def test_wart_random_affine3d_rotation_is_the_rotation3d_transpose_4408(self, axis, device, dtype):
# The matrix literal anchors RandomRotation3D's own direction; #4408 is RandomAffine3D being its transpose.
+ if not supports_bilinear_3d_grid_sample(device, dtype):
+ pytest.skip("bilinear 3D grid_sample is unavailable for this device and dtype")
degrees = [(0.0, 0.0)] * 3
degrees[axis] = (30.0, 30.0)
- volume = torch.zeros(1, 1, 5, 5, 5)
+ volume = torch.zeros(1, 1, 5, 5, 5, device=device, dtype=dtype)
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].abs(), matrix.new_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
@@ -318,7 +318,7 @@ class Test3DAugmentationConventions(BaseTester):
@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).
+ # #4654: a gated-off call returns the input, not the padded volume.
volume = torch.rand(1, 1, 4, 5, 6)
for kwargs in (
{"size": (2, 3, 4), "padding": 2},
@@ -332,21 +332,38 @@ class Test3DAugmentationConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_crop3d_validates_size_before_a_disabled_gate(self):
+ # The exception types are split between the two classes (#4417); this pin is about the order only.
volume = torch.rand(1, 1, 4, 5, 6)
- with pytest.raises(AssertionError, match="Crop size must be smaller"):
+ with pytest.raises((AssertionError, ValueError)):
K.CenterCrop3D((5, 6, 7), p=0.0)(volume)
- with pytest.raises(ValueError, match="cannot be smaller than crop size"):
+ with pytest.raises((AssertionError, ValueError)):
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"):
+ with pytest.raises((AssertionError, ValueError)):
K.RandomCrop3D((6, 5, 6), p=0.0)(volume)
+ @pytest.mark.device_agnostic
+ def test_wart_crop3d_siblings_disagree_on_size_errors_4417(self):
+ # #4417: flips when the two classes validate `size` the same way; which assertion fails depends on the
+ # direction of the fix.
+ volume = torch.rand(1, 1, 4, 5, 6)
+ with pytest.raises(AssertionError):
+ K.CenterCrop3D((5, 5, 6), p=1.0)(volume)
+ with pytest.raises(ValueError):
+ K.RandomCrop3D((5, 5, 6), p=1.0)(volume)
+ assert K.CenterCrop3D(2, p=1.0)(volume).shape == (1, 1, 2, 2, 2)
+ with pytest.raises(AssertionError):
+ K.RandomCrop3D(2, p=1.0)(volume)
+ with pytest.raises(IndexError):
+ K.CenterCrop3D((2, 2), p=1.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):
+ def test_wart_random_crop3d_matrix_uses_the_padded_source_frame_4801(self, padding, size, marker, device, dtype):
+ # #4801: flips when the recorded matrix includes the padding offset.
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)
@@ -362,8 +379,7 @@ class Test3DAugmentationConventions(BaseTester):
@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).
+ # #4653: one size per call, both bounds reachable.
volume = torch.rand(6, 1, 4, 5, 6)
sizes = set()
for seed in range(40):
@@ -380,24 +396,6 @@ class Test3DAugmentationConventions(BaseTester):
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
@@ -409,13 +407,12 @@ class Test3DAugmentationConventions(BaseTester):
yield sub
yield from concrete(sub)
- # Enumerate the subclasses rather than a hand-written list or `__all__`: RandomTransplantation3D was
- # missing from kornia.augmentation.__all__ until #4695, and is the one 3D class that does take p_batch.
+ # Enumerate the subclasses rather than a hand-written list or `__all__`.
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"):
+ with pytest.raises(TypeError):
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))
@@ -424,28 +421,25 @@ class Test3DAugmentationConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_random_crop3d_rejects_a_one_voxel_oversized_crop_4688(self):
- # Fixed by #4691: a crop one voxel larger than the input used to pass the guard and append an empty slab
- # (#4688). It now raises like any larger request, on every axis, matching CenterCrop3D.
+ # #4688: a crop one voxel larger than the input raises on every axis; the whole volume is a valid crop.
volume = torch.ones(1, 1, 4, 5, 6)
for size in ((5, 5, 6), (4, 6, 6), (4, 5, 7), (6, 5, 6)):
- with pytest.raises(ValueError, match="cannot be smaller than crop size"):
+ with pytest.raises((AssertionError, ValueError)):
K.RandomCrop3D(size, p=1.0)(volume)
- # The whole volume is still a valid crop.
self.assert_close(K.RandomCrop3D((4, 5, 6), p=1.0)(volume), volume)
- 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):
+ def test_wart_perspective3d_float64_identity_uses_a_float32_grid_4776(self):
+ # #4776: flips to `residual < 1e-12` once the grid is built in float64; the rotation path already is.
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
+ # The float32-grid error grows with the volume size.
+ large = torch.rand(1, 1, 8, 16, 32, dtype=torch.float64)
+ large_residual = float((K.RandomPerspective3D(0.0, p=1.0, align_corners=True)(large) - large).abs().max())
+ assert residual < large_residual < 1e-4
@pytest.mark.device_agnostic
def test_convention_random_crop3d_offset_reaches_both_ends(self):
@@ -461,8 +455,7 @@ class Test3DAugmentationConventions(BaseTester):
@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.
+ # `padding` and `pad_if_needed` together: the second padding pass keeps per-axis bookkeeping.
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]]
@@ -479,7 +472,6 @@ class Test3DAugmentationConventions(BaseTester):
@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)
@@ -490,7 +482,7 @@ class Test3DAugmentationConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_random_affine3d_two_value_scale_is_isotropic_4704(self):
# A two-value scale draws one factor per sample for all three axes, as the 2D class does; the
- # three-pair form keeps one independent draw per axis.
+ # three-pair form draws each axis independently.
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)
@@ -508,13 +500,12 @@ class Test3DAugmentationConventions(BaseTester):
axes = per_axis.forward_parameters(torch.Size([64, 1, 5, 6, 7]))["scale"]
assert axes.shape == (64, 3)
assert not bool((axes[:, 0] == axes[:, 1]).any()) and not bool((axes[:, 1] == axes[:, 2]).any())
- # The two-value form is range-checked once under its own name; main reported it as "scale-x".
+ # The two-value form is range-checked under its own name.
with pytest.raises(ValueError, match="scale out of bounds"):
K.RandomAffine3D(0.0, scale=(-0.5, 2.0), p=1.0)
@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):
@@ -525,9 +516,6 @@ class Test3DAugmentationConventions(BaseTester):
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):
@@ -545,22 +533,14 @@ class Test3DAugmentationConventions(BaseTester):
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.
+ def test_convention_identity_warp_is_roundoff_exact_only_in_full_precision(self):
+ # In half precision the sampling grid is itself rounded, so a large volume moves far beyond roundoff.
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):
diff --git a/tests/augmentation/test_conventions_6d_serialization.py b/tests/augmentation/test_conventions_6d_serialization.py
index 6a2e2c1da..bf34ecade 100644
--- a/tests/augmentation/test_conventions_6d_serialization.py
+++ b/tests/augmentation/test_conventions_6d_serialization.py
@@ -100,29 +100,25 @@ class TestConventionMix3DSerialization(BaseTester):
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)
+ @pytest.mark.parametrize(
+ "name,policy",
+ [
+ ("AutoAugment", [[("posterize", 1.0, 3)]]),
+ ("RandAugment", [[("posterize", 0.0, 4)]]),
+ ("TrivialAugment", [[("posterize", 0.0, 4)]]),
+ ("AutoAugment", [[]]),
+ ],
+ ids=["autoaugment-posterize", "randaugment-posterize", "trivialaugment-posterize", "autoaugment-empty"],
+ )
+ def test_convention_a_closure_free_policy_can_be_pickled(self, name, policy):
+ # A policy pickles when every wrapper in it does: Posterize has a named mapping and no sign flip, and an
+ # empty sub-policy has no wrapper at all.
kwargs = {"n": 1, "m": 15} if name == "RandAugment" else {}
- augmentation = getattr(A, name)(policy=[[entry]], **kwargs)
+ augmentation = getattr(A, name)(policy=policy, **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
+ if policy == [[]]:
+ self.assert_close(expected, 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
index 18756f2ba..45c446257 100644
--- a/tests/augmentation/test_conventions_auto.py
+++ b/tests/augmentation/test_conventions_auto.py
@@ -69,11 +69,16 @@ class TestAutoAugmentConventions(BaseTester):
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):
+ def test_convention_autoaugment_magnitude_bins_select_adjacent_intervals(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
+ torch.manual_seed(17)
+ degrees = AutoAugment(policy=[[("rotate", 1.0, 5)]]).forward_parameters(torch.Size([64, 1, 8, 6]))
+ degrees = degrees[0].data[0].data["degrees"]
+ assert (degrees >= 0.0).all() and (degrees <= 6.0).all() # bin 5 of linspace(-30, 30, 11) is [0, 6]
+ assert degrees.min() < 1.0 and degrees.max() > 5.0
for magnitude in (-1, 10):
with pytest.raises(ValueError, match=r"in \[0, 9\]"):
AutoAugment(policy=[[("rotate", 1.0, magnitude)]])
@@ -98,19 +103,9 @@ class TestAutoAugmentConventions(BaseTester):
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_convention_trivialaugment_applies_the_symmetric_magnitude_mapping_4441(self):
- # #4441: TrivialAugment used to sample the wrapped augmentation directly, which skipped the random sign,
- # so a symmetric op such as rotate only ever drew non-negative magnitudes.
+ # #4441: TrivialAugment samples through the wrapper, so a symmetric op such as rotate draws both signs.
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"]
@@ -232,6 +227,10 @@ class TestAutoAugmentConventions(BaseTester):
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]
+ # get_forward_sequence, which get_transformation_matrix zips against, follows the supplied order too.
+ reversed_names = [name for name, _ in policy.get_forward_sequence(reversed_params)]
+ assert reversed_names == [param.name for param in reversed_params]
+ assert [name for name, _ in policy.get_forward_sequence(generated[:1])] == [generated[0].name]
@pytest.mark.device_agnostic
def test_convention_intensity_matrix_requires_a_nonempty_selected_policy(self):
@@ -268,6 +267,8 @@ class TestAutoAugmentConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_operation_probability_and_magnitude_clamps(self):
+ initial = ops.Invert(initial_probability=0.25)
+ self.assert_close(initial.probability.detach(), torch.tensor([0.25]), rtol=0, atol=0)
operation = ops.Rotate(initial_magnitude=3.0, initial_probability=0.5)
operation._probability.data.fill_(2.0)
operation._magnitude.data.fill_(100.0)
@@ -280,9 +281,9 @@ class TestAutoAugmentConventions(BaseTester):
"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.
+ def test_wart_operation_soft_blend_depends_on_the_wrapped_p_4809(self, probability, expected, device, dtype):
+ # #4809: 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. One of the two cases flips when the blend stops depending on p.
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)
@@ -291,9 +292,8 @@ class TestAutoAugmentConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_policy_sequential_samples_through_the_operation_wrapper_4441(self):
- # #4441: PolicySequential used to call the wrapped augmentation's forward_parameters, so it ignored the
- # wrapper's magnitude and magnitude mapping. The gate still comes from the wrapped augmentation's p, and
- # the wrapper's probability parameter is still not consulted on either path.
+ # #4441: PolicySequential samples through the wrapper's magnitude and magnitude mapping. The gate comes
+ # from the wrapped augmentation's p, and the wrapper's probability parameter is not consulted.
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)
@@ -387,24 +387,11 @@ class TestAutoAugmentConventions(BaseTester):
# So a policy deep-copies after a forward and after train() / eval(), and the copy replays the original.
image = torch.rand(2, 3, 8, 8)
for policy in (AutoAugment(), TrivialAugment(), RandAugment(n=2, m=15)):
- copy.deepcopy(policy)
copy.deepcopy(policy.eval())
copy.deepcopy(policy.train())
output = policy(image)
self.assert_close(copy.deepcopy(policy)(image, params=policy._params), output, rtol=0, atol=0)
- @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)]])
@@ -428,8 +415,7 @@ class TestAutoAugmentConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_policy_shear_entries_are_mapped_to_degrees_4441(self):
- # #4441: TrivialAugment used to drop ShearX's 180 factor, so ("shear_x", -0.3, 0.3) sheared by at most
- # 0.3 degrees, where RandAugment sheared by up to 54 degrees for the same entry.
+ # #4441: every policy applies ShearX's 180 factor, so ("shear_x", -0.3, 0.3) shears by up to 54 degrees.
torch.manual_seed(17)
trivial = (
TrivialAugment(policy=[[("shear_x", -0.3, 0.3)]])
@@ -453,7 +439,7 @@ class TestAutoAugmentConventions(BaseTester):
)
assert bool((auto >= low - 1e-3).all()) and bool((auto <= high + 1e-3).all()), (name, magnitude_bin)
assert auto.min() < low + 1.0 and auto.max() > high - 1.0, (name, magnitude_bin)
- # The same policy entry through RandAugment, which always applied the mapping.
+ # The same policy entry through RandAugment.
mapped = (
RandAugment(n=1, m=29, policy=[[("shear_x", -0.3, 0.3)]])
.forward_parameters(torch.Size([8, 1, 8, 6]))[0]
@@ -466,13 +452,15 @@ class TestAutoAugmentConventions(BaseTester):
def test_wart_operation_wrappers_cannot_be_pickled_4469(self):
import pickle
+ # Python 3.14 raises PicklingError for a local object where earlier versions raise AttributeError.
+ local_object_error = (AttributeError, pickle.PicklingError)
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:
+ except local_object_error:
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"}
@@ -480,28 +468,14 @@ class TestAutoAugmentConventions(BaseTester):
# 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"):
+ with pytest.raises(local_object_error):
pickle.dumps(ops.Posterize(symmetric_megnitude=True))
- with pytest.raises(AttributeError, match="local object"):
+ with pytest.raises(local_object_error):
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]
+ # So the default policies, which hold such wrappers, do not pickle either.
+ for policy in (AutoAugment(), RandAugment(n=2, m=15), TrivialAugment()):
+ with pytest.raises(local_object_error):
+ pickle.dumps(policy)
@pytest.mark.device_agnostic
def test_convention_rigid_matrix_mode_accepts_intensity_operations(self):
@@ -524,7 +498,7 @@ class TestAutoAugmentConventions(BaseTester):
@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.
+ # The magnitude mapping over the whole default policy, not a sample of it.
import math
from kornia.augmentation.auto.rand_augment.rand_augment import default_policy
diff --git a/tests/augmentation/test_conventions_geometric_crop.py b/tests/augmentation/test_conventions_geometric_crop.py
index ec88684ad..0ffd69e1f 100644
--- a/tests/augmentation/test_conventions_geometric_crop.py
+++ b/tests/augmentation/test_conventions_geometric_crop.py
@@ -62,7 +62,7 @@ class TestGeometricCropConventions(BaseTester):
@pytest.mark.parametrize("size", [(4, 4), (4, 8), (6, 8)])
def test_convention_center_crop_slice_returns_a_copy_4413(self, device, dtype, size):
- # #4413: default slice mode used to return a view, so writing to the output changed the input.
+ # #4413: default slice mode returns a copy, so writing to the output leaves the input unchanged.
# (4, 8) keeps whole rows and (6, 8) is the full image: both slices are already contiguous.
x = torch.arange(48, device=device, dtype=dtype).reshape(1, 1, 6, 8)
original = x.clone()
@@ -145,6 +145,7 @@ class TestGeometricCropConventions(BaseTester):
points = image.new_tensor([[[2, 2]]])
boxes = image.new_tensor([[[[1, 1], [2, 1], [2, 2], [1, 2]]]])
output, out_points, out_boxes = seq(image, points, boxes, params=params)
+ # The matrix starts from the padded canvas (#4801); the keypoint and box handlers add the padding.
self.assert_close(crop.transform_matrix, image.new_tensor([[[1, 0, 0], [0, 1, 0], [0, 0, 1]]]))
self.assert_close(out_points, image.new_tensor([[[3, 3]]]))
self.assert_close(out_boxes, boxes + 1)
@@ -238,19 +239,10 @@ class TestGeometricCropConventions(BaseTester):
[0.0, 0.0, 0.0, 0.0],
],
}
- if dtype == torch.float16 and mode == "resample":
- # Captured from the published corrected implementation on CPU/PyTorch 2.9.1; the matrix remains
- # independently pinned.
- expected_rows["resample"] = [
- [0.0, 0.0, 0.0, 0.0],
- [0.0, 0.0260009765625, 0.15625, 0.051605224609375],
- [0.0, 0.281005859375, 0.4375, 0.1239013671875],
- [0.0, 0.59375, 0.75, 0.2015380859375],
- [0.0, 0.5205078125, 0.62451171875, 0.1651611328125],
- [0.0, 0.0, 0.0, 0.0],
- ]
expected = image.new_tensor(expected_rows[mode]).reshape(1, 1, 6, 4)
- self.assert_close(output, expected)
+ # float16 resampling also rounds its grid, so this is a bound; the matrix is pinned exactly above.
+ tolerance = {"rtol": 0.0, "atol": 3e-3} if dtype == torch.float16 and mode == "resample" else {}
+ self.assert_close(output, expected, **tolerance)
self.assert_close(output[0, 0, 0], image.new_tensor([0, 0, 0, 0]))
assert output.shape == (1, 1, 6, 4)
@@ -307,27 +299,79 @@ class TestGeometricCropConventions(BaseTester):
self.assert_close(nearest(x, params=params), x)
@pytest.mark.device_agnostic
- def test_convention_random_resized_crop_fallback_can_escape_scale_and_ratio(self):
- params = K.RandomResizedCrop((4, 4), scale=(1.0, 1.0), p=1.0).forward_parameters((1, 1, 8, 6))
-
- src = params["src"]
- crop_height = (src[0, 2, 1] - src[0, 1, 1]).item() + 1
- crop_width = (src[0, 1, 0] - src[0, 0, 0]).item() + 1
- assert (crop_height, crop_width) == (4, 6)
- assert crop_height * crop_width / (8 * 6) != 1.0
- assert crop_width / crop_height > 4 / 3
+ def test_wart_random_resized_crop_fallback_leaves_scale_and_ratio_4814(self):
+ # #4814: no candidate may equal the input and the fallback compares H / W with min(ratio), so scale=(1, 1)
+ # crops a portrait or square image; torchvision's get_params keeps 8 x 6 and 8 x 8. Flips on either fix.
+ torch.manual_seed(0)
+ for shape, crop in (((8, 6), (4, 6)), ((8, 8), (6, 8))):
+ src = K.RandomResizedCrop((4, 4), scale=(1.0, 1.0), p=1.0).forward_parameters((1, 1, *shape))["src"]
+ assert ((src[0, 2, 1] - src[0, 1, 1]).item() + 1, (src[0, 1, 0] - src[0, 0, 0]).item() + 1) == crop
@pytest.mark.device_agnostic
def test_wart_crop_siblings_disagree_on_integer_size_4417(self):
- # #4417: CenterCrop accepts an int while its random siblings reject it through implementation details.
+ # #4417: CenterCrop accepts an int while its random siblings reject it.
assert K.CenterCrop(4).size == (4, 4)
with pytest.raises(AssertionError):
K.RandomCrop(4)(torch.ones(1, 1, 6, 8)) # type: ignore[arg-type]
- with pytest.raises(TypeError, match="not subscriptable"):
+ with pytest.raises(TypeError):
K.RandomCrop(4, pad_if_needed=True)(torch.ones(1, 1, 6, 8)) # type: ignore[arg-type]
with pytest.raises(TypeError):
K.RandomResizedCrop(4) # type: ignore[arg-type]
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ def test_wart_random_crop_matrix_starts_from_the_padded_canvas_4801(self, device, dtype, mode):
+ # #4801: flips when the recorded matrix includes the padding offset and maps (2, 1) to (3, 2).
+ image = torch.zeros(1, 1, 3, 4, device=device, dtype=dtype)
+ image[0, 0, 1, 2] = 1 # pixel (x=2, y=1); cropping the whole padded canvas has one placement
+ seq = K.AugmentationSequential(
+ K.RandomCrop((5, 6), padding=1, cropping_mode=mode, p=1.0), data_keys=["input", "keypoints"]
+ )
+ output, points = seq(image, image.new_tensor([[[2.0, 1.0]]]))
+ assert output[0, 0].argmax().item() == 2 * 6 + 3
+ self.assert_close(points, image.new_tensor([[[3.0, 2.0]]]))
+ self.assert_close(seq.transform_matrix, torch.eye(3, device=device, dtype=dtype)[None])
+
+ @pytest.mark.parametrize("mode", ["slice", "resample"])
+ def test_wart_random_crop_pad_if_needed_matrix_omits_the_padding_4801(self, device, dtype, mode):
+ # #4801: flips when the matrix includes the `pad_if_needed` offset, (2, 1) for a 6 x 9 crop of 5 x 7.
+ image = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)
+ image[0, 0, 2, 1] = 1 # pixel (x=1, y=2)
+ torch.manual_seed(0)
+ seq = K.AugmentationSequential(
+ K.RandomCrop((6, 9), pad_if_needed=True, cropping_mode=mode, p=1.0), data_keys=["input", "keypoints"]
+ )
+ output, points = seq(image, image.new_tensor([[[1.0, 2.0]]]))
+ row, col = divmod(output[0, 0].argmax().item(), 9)
+ self.assert_close(points, image.new_tensor([[[col, row]]])) # the keypoint follows the pixel
+ via_matrix = seq.transform_matrix[0] @ image.new_tensor([1.0, 2.0, 1.0])
+ self.assert_close(points[0, 0] - via_matrix[:2], image.new_tensor([2.0, 1.0]))
+
+ @pytest.mark.device_agnostic
+ def test_wart_interpolate_paths_record_a_corner_aligned_matrix_4804(self):
+ # #4804: at align_corners=False the image is resized on the half-pixel grid, the matrix corner to corner.
+ # A ramp's value is the source x each output pixel sampled; flips when the two agree.
+ ramp = torch.arange(7.0, dtype=torch.float64).expand(1, 1, 5, 7).contiguous()
+ for align_corners, disagree in ((True, False), (False, True)):
+ aug = K.Resize((10, 14), align_corners=align_corners, p=1.0)
+ sampled = aug(ramp)[0, 0, 2, 1]
+ inverse = torch.linalg.inv(aug.transform_matrix[0])
+ assert bool((sampled - (inverse[0, 0] + inverse[0, 2])).abs() > 0.1) == disagree # output column 1
+ torch.manual_seed(1)
+ image = torch.rand(1, 1, 20, 24)
+ sliced = K.RandomResizedCrop((9, 13), align_corners=align_corners, p=1.0)
+ first = sliced(image)
+ resampled = K.RandomResizedCrop((9, 13), align_corners=align_corners, p=1.0, cropping_mode="resample")
+ assert bool((first - resampled(image, params=sliced._params)).abs().max() > 0.1) == disagree
+
+ @pytest.mark.device_agnostic
+ def test_wart_random_resized_crop_slice_mode_rejects_nearest_4802(self):
+ # #4802: flips when slice mode drops the default align_corners for nearest resampling.
+ image = torch.rand(1, 1, 8, 8)
+ for kwargs in ({"cropping_mode": "resample"}, {"align_corners": None}):
+ assert K.RandomResizedCrop((4, 4), resample="nearest", p=1.0, **kwargs)(image).shape == (1, 1, 4, 4)
+ with pytest.raises(ValueError):
+ K.RandomResizedCrop((4, 4), resample="nearest", p=1.0)(image)
+
def test_convention_resize_side_policies_and_inverse(self, device, dtype):
x = torch.arange(70, device=device, dtype=dtype).reshape(1, 1, 7, 10)
exact = K.Resize((3, 5), p=1.0)
diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.py
index 0efe35a9d..eb87f43d6 100644
--- a/tests/augmentation/test_conventions_geometric_matrix.py
+++ b/tests/augmentation/test_conventions_geometric_matrix.py
@@ -27,23 +27,15 @@ from testing.base import BaseTester
class TestConventionGeometricMatrices(BaseTester):
- @pytest.mark.device_agnostic
- def test_convention_flips_use_inclusive_pixel_coordinates(self):
- x = torch.zeros(1, 1, 5, 7)
- x[..., 1, 2] = 1
- horizontal = K.RandomHorizontalFlip(p=1.0)(x)
- vertical = K.RandomVerticalFlip(p=1.0)(x)
-
- assert horizontal[0, 0].argmax().item() == 1 * 7 + 4
- assert vertical[0, 0].argmax().item() == 3 * 7 + 2
-
- def test_convention_flips_expose_their_discrete_coordinate_matrices(self, device, dtype):
+ def test_convention_flips_use_inclusive_pixel_coordinates(self, device, dtype):
x = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype)
+ x[..., 1, 2] = 1
horizontal = K.RandomHorizontalFlip(p=1.0)
vertical = K.RandomVerticalFlip(p=1.0)
- horizontal(x)
- vertical(x)
+ # x' = W - 1 - x and y' = H - 1 - y, in the image and in the matrix alike.
+ assert horizontal(x)[0, 0].argmax().item() == 1 * 7 + 4
+ assert vertical(x)[0, 0].argmax().item() == 3 * 7 + 2
self.assert_close(
horizontal.transform_matrix,
torch.tensor([[[-1.0, 0.0, 6.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),
@@ -142,9 +134,19 @@ class TestConventionGeometricMatrices(BaseTester):
K.RandomPerspective(0.0, align_corners=align_corners, p=1.0)(image), image, low_tolerance=True
)
+ @pytest.mark.parametrize("align_corners", [False, True])
+ def test_wart_random_perspective_float64_identity_goes_through_a_float32_grid_4776(self, device, align_corners):
+ # #4776: warp_perspective builds its grid in float32, so a float64 identity warp keeps only float32
+ # precision (RandomAffine's warp_affine is exact on the same input). Flips when the grid follows the dtype.
+ if device.type == "mps":
+ pytest.skip("MPS has no float64")
+ image = torch.arange(35, device=device, dtype=torch.float64).reshape(1, 1, 5, 7) / 35
+ output = K.RandomPerspective(0.0, align_corners=align_corners, p=1.0)(image)
+ assert (output - image).abs().max() > 1e-12
+
@pytest.mark.parametrize("size", [(1, 7), (5, 1), (1, 1)])
@pytest.mark.parametrize("align_corners", [False, True])
- def test_wart_random_perspective_singleton_dimensions_4538(self, device, dtype, size, align_corners):
+ def test_wart_random_perspective_singleton_dimensions_4787(self, device, dtype, size, align_corners):
height, width = size
image = torch.arange(height * width, device=device, dtype=dtype).reshape(1, 1, height, width)
augmentation = K.RandomPerspective(0.0, align_corners=align_corners, p=1.0)
diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.py
index ef5dd8871..3a754f305 100644
--- a/tests/augmentation/test_conventions_mix.py
+++ b/tests/augmentation/test_conventions_mix.py
@@ -34,8 +34,21 @@ def _label_dtype(image_dtype: torch.dtype) -> torch.dtype:
class TestMixConventions(BaseTester):
- def test_convention_mix_base_has_no_matrix_or_inverse(self):
- aug = K.RandomMixUpV2()
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ "factory",
+ [
+ K.RandomMixUpV2,
+ lambda: K.RandomCutMixV2(use_correct_lambda=True),
+ K.PatchMix,
+ K.RandomJigsaw,
+ K.RandomMosaic,
+ K.RandomTransplantation,
+ K.RandomTransplantation3D,
+ ],
+ )
+ def test_convention_mix_has_no_matrix_or_inverse(self, factory):
+ aug = factory()
with pytest.raises(RuntimeError, match="Transformation matrices"):
_ = aug.transform_matrix
with pytest.raises(RuntimeError, match="Inverse"):
@@ -166,20 +179,24 @@ class TestMixConventions(BaseTester):
@pytest.mark.device_agnostic
@pytest.mark.parametrize(
- "factory",
+ ("factory", "per_sample"),
[
- 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),
+ (lambda: K.RandomJigsaw(grid=(2, 2), p=0.5, same_on_batch=True), False),
+ (lambda: K.RandomTransplantation(p=0.5), True),
],
)
- 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.
+ def test_convention_mix_gate_is_per_sample_or_batch_wide(self, factory, per_sample):
+ # A batch-wide gate never selects a strict subset of the rows; a per-sample one misses doing so in 20
+ # draws of 8 rows with probability (2 / 256) ** 20. Jigsaw and Mosaic's per-sample `p` and the batch-wide
+ # `p` of MixUp, CutMix and PatchMix (#4425) are pinned in test_base.py.
aug = factory()
+ shape = torch.Size([8, 8, 8]) if isinstance(aug, K.RandomTransplantation) else torch.Size([8, 1, 8, 8])
+ subsets = 0
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())
+ gate = aug.forward_parameters(shape)["batch_prob"] > 0.5
+ assert gate.numel() == 8
+ subsets += 0 < int(gate.sum()) < 8
+ assert (subsets > 0) == per_sample
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)
@@ -321,24 +338,6 @@ class TestMixConventions(BaseTester):
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(
@@ -352,7 +351,7 @@ class TestMixConventions(BaseTester):
],
)
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).
+ # #4651 / #4676: the key is validated before the gate is consulted.
image = torch.rand(4, 1, 8, 8)
annotations = {
"bbox_xyxy": torch.tensor([[[1.0, 1.0, 4.0, 4.0]]] * 4),
@@ -375,14 +374,15 @@ class TestMixConventions(BaseTester):
@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.
+ # #4676: the divisibility check runs whatever the gate.
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):
+ def test_wart_mix_class_handlers_ignore_a_replayed_partial_gate_4775(self):
+ # #4775: flips when the class handler honours batch_prob, i.e. row 1 is labelled [20, 20, 0].
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"])
@@ -393,6 +393,16 @@ class TestMixConventions(BaseTester):
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]]))
+ # RandomCutMixV2 has the same handler split: a 2 x 2 cut, and row 1 is gated off.
+ aug = K.RandomCutMixV2(p=1.0, use_correct_lambda=True, data_keys=["input", "class"])
+ aug(image, labels)
+ params = dict(aug._params)
+ params["mix_pairs"] = torch.tensor([[1, 2, 0]])
+ params["crop_src"] = torch.tensor([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]).expand(1, 3, 4, 2).clone()
+ params["batch_prob"] = torch.tensor([1.0, 0.0, 1.0])
+ output, mixed = aug(image, labels, params=params)
+ self.assert_close(output[1], image[1])
+ self.assert_close(mixed[0], torch.tensor([[10.0, 20.0, 0.75], [20.0, 30.0, 0.75], [30.0, 10.0, 0.75]]))
@pytest.mark.device_agnostic
def test_convention_cutmix_compatibility_lambda_warns(self):
@@ -446,12 +456,26 @@ class TestMixConventions(BaseTester):
heights, widths = infer_bbox_shape(independent.forward_parameters(shape)["crop_src"].flatten(0, 1))
assert heights.unique().numel() > 1 and widths.unique().numel() > 1
+ @pytest.mark.device_agnostic
+ def test_wart_cutmix_same_on_batch_repeats_one_cut_per_mix_4805(self):
+ # #4805: with same_on_batch=True every mix repeats the first cut from the same donor, yet each mix is
+ # labelled. Flips when the mixes differ or collapse to one, i.e. when the labels match the pixels.
+ torch.manual_seed(0)
+ image = torch.arange(4.0).view(4, 1, 1, 1).expand(4, 1, 8, 8).clone() # row i is filled with i
+ aug = K.RandomCutMixV2(
+ num_mix=2, same_on_batch=True, p=1.0, use_correct_lambda=True, data_keys=["input", "class"]
+ )
+ output, mixed = aug(image, torch.tensor([0, 1, 2, 3]))
+ assert mixed.shape[0] == 2 and torch.equal(mixed[0], mixed[1])
+ replaced = (output[:, 0] != image[:, 0]).float().mean((-2, -1))
+ self.assert_close(replaced, 1 - mixed[0, :, 2]) # one cut's area, while two mixes credit the donor
+
@pytest.mark.device_agnostic
def test_convention_cutmix_placement_is_drawn_per_cut_4712(self):
from kornia.geometry.bbox import infer_bbox_shape
- # #4712: one uniform draw per axis used to place every cut of the batch. With the size fixed, only the
- # placement can differ, so equal boxes here would mean the placement is shared again.
+ # #4712: every cut draws its own placement. With the size fixed, only the placement can differ, so equal
+ # boxes here would mean the placement is shared.
shape = torch.Size([8, 1, 64, 48])
for seed in range(10):
torch.manual_seed(seed)
@@ -473,7 +497,7 @@ class TestMixConventions(BaseTester):
@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).
+ # #4650 / #4680: checked whatever the gate.
image = torch.rand(4, 1, 8, 10)
for patch_size in (9, 16):
with pytest.raises(ValueError, match="`patch_size` to fit the input"):
@@ -482,8 +506,7 @@ class TestMixConventions(BaseTester):
@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.
+ # #4680. Each donor's pixel value is its batch index, 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)
@@ -539,7 +562,7 @@ class TestMixConventions(BaseTester):
@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).
+ # #4657: a half-precision image gives float32 labels, so class ids such as 257 and 999 stay exact.
image = torch.rand(2, 1, 4, 4, dtype=image_dtype)
labels = torch.tensor([257, 999])
cases = (
@@ -586,13 +609,15 @@ class TestMixConventions(BaseTester):
_, mixed = aug(image.double(), labels, params=params, data_keys=["input", "class"])
assert mixed.dtype == torch.float64
- @pytest.mark.parametrize("image_dtype", [torch.uint8, torch.int32, torch.bool])
- def test_convention_mix_replay_rejects_an_unsupported_dtype_with_type_error(self, image_dtype):
- # The replayed dictionary goes through the same dtype check as a fresh draw, so the error stays a TypeError.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("replay", [False, True])
+ @pytest.mark.parametrize("image_dtype", [torch.uint8, torch.int32, torch.int64, torch.bool])
+ def test_convention_mix_rejects_a_non_floating_image(self, image_dtype, replay):
+ # A fresh draw and a replayed dictionary go through the same dtype guard.
image = torch.rand(2, 1, 4, 4)
for aug_cls in (K.RandomMixUpV2, K.RandomCutMixV2, K.RandomJigsaw, K.RandomMosaic):
aug = aug_cls(p=1.0)
- params = aug.forward_parameters(image.shape)
+ params = aug.forward_parameters(image.shape) if replay else None
with pytest.raises(TypeError, match="Expected input of"):
aug((image * 255).to(image_dtype), params=params)
@@ -645,24 +670,6 @@ class TestMixConventions(BaseTester):
output = aug(picture)
assert not (output == picture).flatten(1).all(1).any()
- 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)
@@ -676,17 +683,6 @@ class TestMixConventions(BaseTester):
# "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.
diff --git a/tests/augmentation/test_conventions_transplantation.py b/tests/augmentation/test_conventions_transplantation.py
index fb82974a4..5f1d86256 100644
--- a/tests/augmentation/test_conventions_transplantation.py
+++ b/tests/augmentation/test_conventions_transplantation.py
@@ -88,43 +88,28 @@ class TestTransplantationConventions(BaseTester):
assert on_device._params["selected_labels"].cpu().tolist() == on_cpu._params["selected_labels"].tolist()
@pytest.mark.device_agnostic
- def test_convention_first_axis_is_always_the_batch(self):
+ @pytest.mark.parametrize("cls", [K.RandomTransplantation, K.RandomTransplantation3D])
+ def test_convention_image_rank_is_mask_rank_plus_one_and_batched(self, cls):
# There is no (C, H, W) form: the leading axis is read as the batch, so the ranks disagree.
with pytest.raises(BaseError, match="must match except for the channel dimension"):
- K.RandomTransplantation(p=1.0)(torch.rand(2, 4, 5), torch.randint(0, 3, (4, 5)))
-
- @pytest.mark.device_agnostic
- def test_convention_image_rank_must_be_mask_rank_plus_one(self):
+ cls(p=1.0)(torch.rand(2, 4, 5), torch.randint(0, 3, (4, 5)))
mask = torch.randint(0, 3, (3, 4, 5))
- with pytest.raises(BaseError, match="one additional dimension"):
- K.RandomTransplantation(p=1.0)(torch.rand(3, 4, 5), mask)
- with pytest.raises(BaseError, match="one additional dimension"):
- K.RandomTransplantation(p=1.0)(torch.rand(3, 2, 4, 5, 6), mask)
-
- @pytest.mark.device_agnostic
- def test_convention_gate_is_per_sample_and_p_batch_is_call_wide(self):
- aug = K.RandomTransplantation(p=0.5)
- subsets = 0
- for _ in range(40):
- gate = aug.forward_parameters(torch.Size([8, 4, 5]))["batch_prob"] > 0.5
- subsets += 0 < int(gate.sum()) < 8
- assert subsets > 0 # a batch-wide gate can never select a strict subset
- closed = K.RandomTransplantation(p=1.0, p_batch=0.0)
- for _ in range(8):
- assert not bool((closed.forward_parameters(torch.Size([8, 4, 5]))["batch_prob"] > 0.5).any())
+ for image in (torch.rand(3, 4, 5), torch.rand(3, 2, 4, 5, 6)):
+ with pytest.raises(BaseError, match="one additional dimension"):
+ cls(p=1.0)(image, mask)
@pytest.mark.device_agnostic
- def test_convention_donor_is_the_previous_image_of_the_full_batch(self):
- image, mask = _labelled_batch(batch=5)
- torch.manual_seed(0)
+ @pytest.mark.parametrize("batch", [1, 5])
+ def test_convention_donor_is_the_previous_image_with_its_original_content(self, batch):
+ # Image i is 10 * i + c in channel c. A transplant chained through already-written acceptors would hand
+ # image 0's content down the batch; at B = 1 the image is its own donor and the call is an identity.
+ _, mask = _labelled_batch(batch=batch)
+ image = torch.stack([torch.stack([torch.full((4, 6), 10.0 * i + c) for c in range(3)]) for i in range(batch)])
aug = K.RandomTransplantation(p=1.0)
- _, out_mask = aug(image, mask)
- # Every image is one label, so the whole mask row takes the donor's label.
- observed = [int(out_mask[i].flatten()[0]) for i in range(5)]
- assert observed == [(i - 1) % 5 + 1 for i in range(5)]
- assert observed != [(i + 1) % 5 + 1 for i in range(5)] # not the next image
- assert observed != [i + 1 for i in range(5)] # not the identity
- assert aug._params["donor_indices"].tolist() == [4, 0, 1, 2, 3]
+ out_image, out_mask = aug(image, mask)
+ assert aug._params["donor_indices"].tolist() == [(i - 1) % batch for i in range(batch)]
+ self.assert_close(out_image, image.roll(1, dims=0), rtol=0, atol=0)
+ assert torch.equal(out_mask, mask.roll(1, dims=0))
@pytest.mark.device_agnostic
def test_convention_donor_need_not_be_an_acceptor(self):
@@ -139,26 +124,6 @@ class TestTransplantationConventions(BaseTester):
self.assert_close(out_image[1], image[0], rtol=0, atol=0)
self.assert_close(out_image[3], image[2], rtol=0, atol=0)
- @pytest.mark.device_agnostic
- def test_convention_a_donor_gives_its_original_content_and_every_channel_moves(self):
- # Image i is its own index in every position, offset per channel. With every image an acceptor, a
- # transplant chained through already-written acceptors would hand image 0's content down the batch.
- _, mask = _labelled_batch(batch=4)
- image = torch.stack([torch.stack([torch.full((4, 6), 10.0 * i + c) for c in range(3)]) for i in range(4)])
- out_image, _ = K.RandomTransplantation(p=1.0)(image, mask)
- self.assert_close(out_image, image.roll(1, dims=0), rtol=0, atol=0)
-
- @pytest.mark.device_agnostic
- def test_convention_single_image_batch_is_its_own_donor_and_an_identity(self):
- image, mask = _labelled_batch(batch=1)
- for seed in range(4):
- torch.manual_seed(seed)
- aug = K.RandomTransplantation(p=1.0)
- out_image, out_mask = aug(image, mask)
- assert aug._params["donor_indices"].tolist() == aug._params["acceptor_indices"].tolist() == [0]
- self.assert_close(out_image, image, rtol=0, atol=0)
- assert torch.equal(out_mask, mask)
-
@pytest.mark.device_agnostic
def test_convention_label_draw_is_uniform_over_distinct_labels_not_area(self):
# The donor holds label 1 on a single position and label 2 on the rest: area-weighted sampling
@@ -377,14 +342,12 @@ class TestTransplantationConventions(BaseTester):
aug = K.RandomTransplantation(p=p, excluded_labels=[0])
_, out_mask = aug(torch.rand(2, 1, 4, 5), mask.to(dtype))
assert out_mask.dtype is dtype and aug._params["selected_labels"].dtype is dtype
-
- @pytest.mark.device_agnostic
- @pytest.mark.parametrize("image_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
- def test_convention_each_floating_image_dtype_is_accepted_and_kept(self, image_dtype):
image, mask = _labelled_batch(batch=3)
- out_image, _ = K.RandomTransplantation(p=1.0)(image.to(image_dtype), mask)
- assert out_image.dtype is image_dtype
- assert torch.equal(out_image, image.to(image_dtype).roll(1, dims=0))
+ for image_dtype in floating:
+ out_image, _ = K.RandomTransplantation(p=p)(image.to(image_dtype), mask)
+ assert out_image.dtype is image_dtype
+ expected = image.roll(1, dims=0) if p == 1.0 else image
+ assert torch.equal(out_image, expected.to(image_dtype))
@pytest.mark.device_agnostic
@pytest.mark.parametrize("p", [0.0, 1.0])
@@ -402,9 +365,17 @@ class TestTransplantationConventions(BaseTester):
K.RandomTransplantation(p=p)(image, mask, annotations[key], data_keys=["input", "mask", key])
@pytest.mark.device_agnostic
- def test_convention_a_mask_key_is_required_only_to_derive_the_parameters(self):
- with pytest.raises(ValueError, match="MASK"):
- K.RandomTransplantation(p=1.0)(torch.rand(2, 1, 4, 5), data_keys=["input"])
+ @pytest.mark.parametrize("cls", [K.RandomTransplantation, K.RandomTransplantation3D])
+ def test_wart_a_missing_mask_raises_a_python_lookup_error_4777(self, cls):
+ # #4777: flips when kornia checks for the mask itself instead of failing in tuple / list lookups.
+ image = torch.rand(2, 1, 4, 5)
+ with pytest.raises(IndexError):
+ cls(p=1.0)(image) # the default data_keys name a mask that was not passed
+ with pytest.raises(ValueError, match="not in list"): # Python 3.14 reworded list.index's message
+ cls(p=1.0)(image, data_keys=["input"])
+
+ @pytest.mark.device_agnostic
+ def test_convention_a_mask_is_required_only_to_derive_the_parameters(self):
# With complete parameters no mask is looked up: this is the call AugmentationSequential makes per input.
image, mask = _multi_label_batch()
torch.manual_seed(0)
@@ -417,21 +388,6 @@ class TestTransplantationConventions(BaseTester):
swapped = K.RandomTransplantation(p=1.0)(mask, image, params=recorded, data_keys=["mask", "input"])
assert torch.equal(swapped[0], expected_mask) and torch.equal(swapped[1], expected_image)
- @pytest.mark.device_agnostic
- def test_convention_mask_only_call_returns_a_bare_tensor(self):
- _, mask = _labelled_batch(batch=3)
- out = K.RandomTransplantation(p=1.0)(mask, data_keys=["mask"])
- assert isinstance(out, torch.Tensor) and out.shape == mask.shape
-
- @pytest.mark.device_agnostic
- def test_convention_no_matrix_and_no_inverse(self):
- for cls in (K.RandomTransplantation, K.RandomTransplantation3D):
- aug = cls(p=1.0)
- with pytest.raises(RuntimeError, match="Transformation matrices"):
- _ = aug.transform_matrix
- with pytest.raises(RuntimeError, match="Inverse"):
- aug.inverse()
-
@pytest.mark.device_agnostic
def test_convention_selected_labels_length_is_validated(self):
image, mask = _labelled_batch(batch=2)