Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(augmentation): Convention blocks (batch 6a: shared contract and containers) (#4452)

Dmytro Mishkindc0af1a43084
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1992700e1..5e819e990 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+* Documented the shared 2D contract of `kornia.augmentation` β€” the `(B, C, H, W)` float working layout
+ and `keepdim`, `p` / `p_batch` / `same_on_batch`, where random parameters are drawn and how `torch.manual_seed`
+ and `params=` replay them, what a module serializes, and what `AugmentationSequential` does with each data key
+ (layouts, the inclusive `xyxy_plus` boxes and integer-centre flips, nearest masks, `extra_args`, `inverse`) β€”
+ as Convention blocks on the base classes and containers, with the canonical randomness and serialization
+ statements on the Conventions & Pitfalls page and executable pins. The contracts distinguish sampler and
+ returned-parameter placement, trainable range parameters, application-time replay exceptions, padding labels,
+ information lost by rotated tensor boxes, mask-list gates, mixed mask dtypes, dictionary-key exceptions,
+ and the transplantation constructors. Scope corrections and regression tests cover mix-specific contracts,
+ inverse support, mask erasing/filtering/precision, nested matrices, serialization and sampler limitations;
+ the container, `p_batch`,
+ `set_rng_device_and_dtype`, `state_dict` and `B = 0` defects are tracked in dedicated issues. (#4452)
* Implemented the exported Brown-Conrady, Kannala-Brandt K3, and Orthographic sensor camera models,
including distortion/projection plumbing, intrinsic matrices, and batched project/unproject support. (#4284, #4377)
* New "Camera and world conventions across the ecosystem" page cataloguing the pixel-centre, axis
diff --git a/conftest.py b/conftest.py
index 010305d2e..61303d670 100644
--- a/conftest.py
+++ b/conftest.py
@@ -114,6 +114,23 @@ def device(device_name) -> torch.device:
return TEST_DEVICES[device_name]
+def restore_torch_rng():
+ """Keep explicitly opted-in tests from shifting later CPU/CUDA/MPS random draws (#4446)."""
+ cpu_state = torch.random.get_rng_state()
+ # Initialize available generators before snapshotting: a test can make the first accelerator draw.
+ cuda_states = torch.cuda.get_rng_state_all() if torch.cuda.is_available() else None
+ mps_state = torch.mps.get_rng_state() if torch.backends.mps.is_available() else None
+ try:
+ yield
+ finally:
+ torch.random.set_rng_state(cpu_state)
+ if cuda_states is not None:
+ torch.cuda.set_rng_state_all(cuda_states)
+ if mps_state is not None:
+ torch.mps.set_rng_state(mps_state)
+
+
@pytest.fixture()
def dtype(dtype_name) -> torch.dtype:
"""Return dtype for testing."""
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index 19a5811b3..2bbdbb248 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -26,7 +26,7 @@ The bases form a chain, each layer adding one concern and shared by several subc
β”œβ”€ _AugmentationBase dispatch to image / mask / box / keypoint / class data keys
β”‚ β”œβ”€ AugmentationBase2D 2D tensor validation (subclass for a fully custom 2D op)
β”‚ β”‚ └─ RigidAffineAugmentationBase2D transform-matrix machinery
- β”‚ β”‚ β”œβ”€ IntensityAugmentationBase2D pointwise ops β€” override apply_transform
+ β”‚ β”‚ β”œβ”€ IntensityAugmentationBase2D intensity ops β€” override apply_transform
β”‚ β”‚ └─ GeometricAugmentationBase2D warp ops β€” also override compute_transformation
β”‚ └─ AugmentationBase3D … (the 3D mirror of the 2D chain)
└─ MixAugmentationBaseV2 mix ops (MixUp / CutMix) β€” bypass the per-key dispatch
@@ -38,28 +38,32 @@ For a custom augmentation, subclass ``IntensityAugmentationBase2D`` or ``Geometr
The Predefined Augmentation Routine
-----------------------------------
-Kornia augmentation follows a simple `sample-apply` routine for all augmentations.
+Kornia augmentations generally follow a `sample-apply` routine.
- `sample`: Kornia aims at flexible tensor-level augmentations that augment every image in a batch with
different parameters and probabilities. The sampling step first draws a set of random
parameters. The sampled augmentation state is then stored in the ``_params`` attribute of the augmentation,
- so users can reproduce the same augmentation results.
+ for replay. Application-time draws can require additional RNG control; see the reproducibility notes below.
- `apply`: with the generated (or user-provided) parameters, the augmentation is performed accordingly.
Apart from transforming image tensors, Kornia also supports inverse operations that revert the transform,
and transforms of other data modalities (`data keys` in Kornia) such as masks, keypoints, and bounding boxes.
- Such features are best used through `AugmentationSequential`. Notably, the full pipeline for rigid
- operations is already implemented and needs no further effort. For non-rigid operations, the user may implement
- customized inverse and data-modality operations, e.g. `apply_transform_mask` for transforming mask tensors.
+ These features depend on the concrete operation and its data-key handlers. `AugmentationSequential` dispatches
+ geometric coordinate transforms by the geometric base type; implementing a matrix on a custom rigid base alone
+ does not enable that dispatch (`#4481 <https://github.com/kornia/kornia/issues/4481>`_). Non-rigid coordinate
+ transforms are not supplied automatically (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
Custom Augmentation Classes
---------------------------
-For rigid transformations, `IntensityAugmentationBase2D` and `GeometricAugmentationBase2D` share the exact same logic
-apart from the transformation matrix computation. Namely, an intensity augmentation always results in an
-identity transformation matrix, since it does not change the geometric location of any pixel.
+`IntensityAugmentationBase2D` supplies an identity matrix and default passthrough handlers for most annotations.
+Subclasses can override these defaults: `RandomErasing` zero-fills the erased mask region. Direct intensity
+`transform_boxes` calls currently raise because the base's box-handler names do not match the dispatcher
+(`#4480 <https://github.com/kornia/kornia/issues/4480>`_); the container skips intensity transforms for boxes.
+`GeometricAugmentationBase2D` supplies the dispatch used for geometric coordinate transformations.
-If it is a rigid geometric operation, `compute_transformation` and `apply_transform` need to be implemented, as well as
-`compute_inverse_transformation` and `inverse_transform` to compute its inverse.
+For a geometric operation, implement `compute_transformation` and `apply_transform`. Supporting image inversion
+also requires `inverse_transform`; the base provides matrix inversion. Some configurations, such as slice-mode
+crops, reject inversion.
.. autoclass:: GeometricAugmentationBase2D
@@ -108,15 +112,16 @@ value in `apply_transform`:
aug = RandomAddValue((0.0, 0.2), p=1.0)
out = aug(torch.rand(4, 3, 32, 32)) # a different value per sample
- again = aug(torch.rand(4, 3, 32, 32), params=aug._params) # reproduce with the stored params
+ again = aug(torch.rand(4, 3, 32, 32), params=aug._params) # reuse the recorded draw
Static (non-random) configuration goes in ``self.flags`` (a plain dict), read from the ``flags``
argument of `apply_transform`. A custom augmentation works standalone and inside
`AugmentationSequential` with no extra wiring.
-For a rigid **geometric** augmentation, also implement `compute_transformation` to return the
-``(B, 3, 3)`` transform matrix β€” kornia then applies it, inverts it, and propagates it to masks,
-boxes and keypoints:
+For a rigid **geometric** augmentation, implement `compute_transformation` to return the
+``(B, 3, 3)`` matrix and `apply_transform` to implement the corresponding image operation.
+The geometric base propagates the matrix to boxes and keypoints; mask processing uses its mask handler.
+The following example only illustrates the method signatures, not an invertible geometric warp:
.. code-block:: python
@@ -143,7 +148,7 @@ boxes and keypoints:
def compute_transformation(self, input, params, flags):
# return the (B, 3, 3) transform matrix for this augmentation
- # (identity shown for brevity; kornia applies, inverts and propagates it)
+ # identity shown only to illustrate the required matrix shape
return K.eye_like(3, input)
def apply_transform(
@@ -170,16 +175,47 @@ of the selected elements, so the skipped elements must be resized as well to kee
.. automethod:: apply_transform_class
.. automethod:: apply_non_transform_class
-The same logic applies to 3D augmentations as well.
+`RigidAffineAugmentationBase2D` sits between `AugmentationBase2D` and the two rigid bases. It adds the
+transform-matrix machinery β€” `compute_transformation` and the `transform_matrix` attribute β€” but no `inverse`.
+
+.. autoclass:: RigidAffineAugmentationBase2D
+
+ .. 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.
+
+.. autoclass:: AugmentationBase3D
+
+.. autoclass:: RigidAffineAugmentationBase3D
+
+.. autoclass:: GeometricAugmentationBase3D
+
+.. autoclass:: IntensityAugmentationBase3D
+
+Mix augmentations derive from `MixAugmentationBaseV2` and have their own forward and data-key contracts.
+Some combine different samples; `RandomJigsaw` rearranges patches within each image. Label and box handling
+are class-specific: `RandomMixUpV2` accepts class labels, while `RandomMosaic` accepts boxes but does not
+implement class-label transforms. `RandomTransplantation` and `RandomTransplantation3D` require a segmentation
+mask; a mask-only call needs ``data_keys=["mask"]``. The 3D transplantation class also inherits
+`AugmentationBase3D`.
+
+.. autoclass:: MixAugmentationBaseV2
Some Further Notes
------------------
Probabilities
^^^^^^^^^^^^^
-Kornia supports two types of randomness: element-level randomness `p` and batch-level randomness `p_batch`,
-as defined in `_BasicAugmentationBase`. Under the hood, operations like `crop` and `resize` are implemented with a fixed
-element-level probability of `p=1` and only keep the batch-level randomness.
+`_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.
Random Generators
^^^^^^^^^^^^^^^^^
@@ -190,6 +226,25 @@ generate simple uniform parameters with less boilerplate code.
Random Reproducibility
^^^^^^^^^^^^^^^^^^^^^^
-By default, the random parameters are sampled on the CPU with ``torch.get_default_dtype()``, independently of the
-device of the input, so a seeded run gives the same parameters on CPU and GPU.
-To change this behaviour, use ``set_rng_device_and_dtype``.
+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
+configurations fail during the setter or a later forward
+(`#4415 <https://github.com/kornia/kornia/issues/4415>`_,
+`#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.
+
+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>`_).
+
+Pickle support is configuration-dependent (`#4435 <https://github.com/kornia/kornia/issues/4435>`_), and
+lazy matrix state can retain the last input batch in a pickle or deepcopy
+(`#4482 <https://github.com/kornia/kornia/issues/4482>`_).
+See :doc:`/get-started/conventions` for replay and serialization details.
diff --git a/docs/source/augmentation.container.rst b/docs/source/augmentation.container.rst
index a7aaad25b..5d44b6f2e 100644
--- a/docs/source/augmentation.container.rst
+++ b/docs/source/augmentation.container.rst
@@ -28,8 +28,11 @@ Augmentation Dispatchers
------------------------
Kornia supports two types of augmentation dispatching, namely many-to-many and many-to-one. The former wraps
different augmentations into one group and lets the user pass as many inputs as there are augmentations, applying
-each augmentation to the corresponding input. The latter applies different augmentations to a single input in order
-to obtain a list of differently transformed outputs.
+each augmentation to the corresponding input; a call with a different number of input bundles than
+augmentations raises ``ValueError`` before any augmentation runs. The latter applies different augmentations to a
+single input in order to obtain a list of differently transformed outputs. Its members must be
+``AugmentationSequential`` instances. With the default ``strict=True``, their ``data_keys`` must match;
+``strict=False`` disables that construction check.
.. note::
The class names below keep their historical spelling (``Dispather``) for backward compatibility.
@@ -113,10 +116,10 @@ Example using ``AugmentationSequential`` with synchronized transforms::
img_out, mask_out = aug(img, mask)
# identical random parameters applied to both tensors
-The core distinction: ``AugmentationSequential`` guarantees that random
-augmentation parameters are shared across all specified data keys, maintaining
-geometric consistency. ``ImageSequential`` applies operations independently to
-single image tensors without multi-target awareness.
+``AugmentationSequential`` coordinates supported data-key handlers from one set
+of recorded parameters. Its non-rigid, mask-list and dtype limitations still
+apply; see the class's Convention block. ``ImageSequential`` processes image
+tensors without dispatching auxiliary annotations.
PatchSequential
diff --git a/docs/source/augmentation.geometric.rst b/docs/source/augmentation.geometric.rst
index 21a4390b8..9075dbad2 100644
--- a/docs/source/augmentation.geometric.rst
+++ b/docs/source/augmentation.geometric.rst
@@ -3,8 +3,11 @@
.. currentmodule:: kornia.augmentation
-Transforms that move pixels. Each one exposes its ``(B, 3, 3)`` transformation matrix, can be inverted, and is
-applied consistently to masks, boxes and keypoints by :class:`~kornia.augmentation.AugmentationSequential`.
+Spatial transformations and erasing operations. Matrix, inverse and annotation support depend on the class
+and configuration. Slice-mode crops reject inversion; non-rigid transforms do not carry boxes or keypoints
+along with the image (`#4420 <https://github.com/kornia/kornia/issues/4420>`_). `RandomErasing` changes image
+and mask values without moving coordinates. See
+:class:`~kornia.augmentation.AugmentationSequential` for the supported data-key paths and their limitations.
.. autoclass:: CenterCrop
.. autoclass:: PadTo
diff --git a/docs/source/augmentation.mix.rst b/docs/source/augmentation.mix.rst
index 01e4d4470..1165bbe8e 100644
--- a/docs/source/augmentation.mix.rst
+++ b/docs/source/augmentation.mix.rst
@@ -3,8 +3,10 @@
.. currentmodule:: kornia.augmentation
-Transforms that combine several images of a batch (and their labels) into new samples.
+Transforms that combine samples or rearrange patches within an image. Supported label, box and mask keys
+vary by class; mixing does not imply support for every annotation type.
+.. autoclass:: PatchMix
.. autoclass:: RandomCutMixV2
.. autoclass:: RandomJigsaw
.. autoclass:: RandomMixUpV2
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 98d215618..ef7386a88 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -176,7 +176,7 @@ Bounding boxes
h, w = infer_bbox_shape(boxes)
assert (h.item(), w.item()) == (2.0, 2.0)
-- :class:`kornia.augmentation.AugmentationSequential` accepts three box
+- :class:`kornia.augmentation.container.AugmentationSequential` accepts three box
formats via ``data_keys``: ``"bbox"`` (4-corner), ``"bbox_xyxy"``, and
``"bbox_xywh"``. Keypoints are ``"keypoints"``, ``(B, N, 2)`` in
``(x, y)``.
@@ -200,10 +200,67 @@ Color
Augmentations
-------------
-- One :class:`kornia.augmentation.AugmentationSequential` call applies the
- SAME sampled transform to every registered data type; ``.inverse()``
- undoes the geometric part for all of them. Never augment image and mask
- through two separate calls β€” the random draws will differ.
+- Use one :class:`kornia.augmentation.container.AugmentationSequential` call
+ for an image and its annotations. Geometric children that implement the
+ corresponding data-key handlers share their recorded parameters across
+ those inputs. Non-rigid operations, mask lists and dtype conversion have
+ the limitations below; a transform matrix alone does not establish support
+ for every data key.
+- ``.inverse()`` recovers keypoint coordinates up to numerical precision when
+ every geometric step supports inversion. Slice-mode crops raise; use their
+ ``cropping_mode="resample"`` where inversion is needed. Geometric 3D
+ children raise too. Intensity and non-rigid children are skipped, leaving
+ their effects applied. Resampling cannot recover information lost through
+ cropping, padding or interpolation. Tensor box outputs use axis-aligned
+ enclosures, so a rotation can lose the corners needed to restore a box.
+- Non-rigid children do not carry coordinate annotations along with the
+ image. :class:`kornia.augmentation.RandomElasticTransform` warps masks
+ through its displacement field but leaves keypoints and boxes unchanged.
+ :class:`kornia.augmentation.RandomThinPlateSpline` and
+ :class:`kornia.augmentation.RandomFisheye` leave coordinates unchanged and
+ raise on masks (`#4420 <https://github.com/kornia/kornia/issues/4420>`_).
+ Intensity transformations usually leave masks unchanged, but
+ :class:`kornia.augmentation.RandomErasing` fills the erased mask region with
+ zero.
+- The geometric mask path normally uses nearest interpolation. That avoids
+ interpolating labels only when no other operation changes their values:
+ padding can introduce its fill value, and ``Resize(antialias=True)`` filters
+ masks before sampling, producing fractional labels or changing integer and
+ boolean masks (`#4479 <https://github.com/kornia/kornia/issues/4479>`_).
+- Put the image before masks, including in dictionary insertion order, so
+ conversion uses its working dtype. Earlier masks use the previous image
+ dtype, or ``float32`` on a fresh container. Integer labels outside the
+ working dtype's exact range can change even through a flip; for example,
+ ``2049`` becomes ``2048`` in ``float16``. Every output mask is cast to the
+ last mask argument's dtype (its first element's dtype for a list).
+ A common mask dtype avoids that cross-mask conversion, but does not prevent
+ precision loss during processing. Empty batches with masks can also raise
+ (`#4478 <https://github.com/kornia/kornia/issues/4478>`_). Direct geometric
+ ``transform_masks`` calls require floating tensors; the container converts
+ integer and boolean masks around those calls.
+- Mask lists are not a reliable replacement for separate full-batch tensors.
+ Direct augmentation children use list index ``i`` to select a sample's
+ gate. Full-batch entries can therefore become desynchronized under mixed
+ gates; per-sample entries can fail in warps or reuse the wrong crop window.
+ Prefer separate ``mask`` keys with a common dtype, subject to the precision
+ and filtering limitations above
+ (`#4477 <https://github.com/kornia/kornia/issues/4477>`_).
+- Boxes use the inclusive ``xyxy_plus`` convention of
+ :class:`kornia.geometry.boxes.Boxes` (see *Bounding boxes* above). Flips use
+ integer pixel centres: ``x' = W - 1 - x``.
+- Nested containers can expose missing or stale transformation matrices,
+ even with only rigid children. Do not rely on the outer
+ ``.transform_matrix`` to describe a nested pipeline
+ (`#4476 <https://github.com/kornia/kornia/issues/4476>`_).
+- Dictionary keys use raw prefix matching with exceptions for coordinate box
+ names. Unrecognized metadata is removed from the caller's dictionary before
+ being returned in the output. See the container's dictionary guidance and
+ `#4483 <https://github.com/kornia/kornia/issues/4483>`_.
+- A positive ``degrees`` turns the displayed image counter-clockwise with
+ :class:`kornia.augmentation.RandomRotation`, matching
+ :func:`kornia.geometry.transform.rotate`, and clockwise with
+ :class:`kornia.augmentation.RandomAffine`
+ (`#4408 <https://github.com/kornia/kornia/issues/4408>`_).
.. code-block:: python
@@ -221,6 +278,82 @@ Augmentations
img_back, mask_back, kpts_back = aug.inverse(img_out, mask_out, kpts_out)
assert (kpts_back - kpts).abs().max() < 1e-3
+Randomness in augmentations
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+- Parameter sampling generally starts on the CPU, independently of the image
+ device. Application-time randomness can instead use the input or model
+ device. Sampling precision depends on the generator, constructor ranges
+ and torch defaults; changing the default dtype does not uniformly update
+ cached samplers.
+- ``set_rng_device_and_dtype`` requests a sampling device and dtype. It
+ updates the gate configuration and asks the parameter generator to rebuild
+ its samplers, but some generators retain internal CPU tensors or ignore
+ the requested precision. A move can fail in the setter itself or during
+ a later forward, depending on the configuration
+ (`#4415 <https://github.com/kornia/kornia/issues/4415>`_,
+ `#4426 <https://github.com/kornia/kornia/issues/4426>`_).
+ Returned parameter placement is separate: an affine without shear can
+ sample angles on MPS and return them on CPU. Numeric ranges or tensor-valued
+ constructor ranges can determine the returned device/dtype, so inspecting
+ ``_params`` alone does not establish where or at what precision draws ran.
+- Reproducibility uses the global generators on the sampling devices.
+ ``torch.manual_seed`` reproduces draws for the same configuration, inputs,
+ backend and dtype; matching across devices or PyTorch versions is not
+ promised. There is no general per-instance ``generator=`` interface.
+ The standard :class:`kornia.augmentation.AugmentationBase2D` forward accepts
+ and ignores unknown keywords, while mix forwards can reject them
+ (`#4427 <https://github.com/kornia/kornia/issues/4427>`_).
+- On the standard 2D base forward path, ``params=`` stores the caller's
+ dictionary by reference and inserts an all-true gate if ``batch_prob`` is
+ missing. Mix augmentations use a separate forward contract and can require
+ that key. Prefer complete recorded parameters for replay. The recorded
+ parameters capture every draw, the ``RandomPlasma*`` noise included, except
+ for ``RandomDissolving``, which samples VAE latents during application.
+ Replaying it also needs control of that application-time random state.
+- ``same_on_batch=True`` shares the standard per-sample gate and sampled
+ transform factors. It does not equate batch-pairing indices, and the
+ ``RandomPlasma*`` noise stored in the parameters is drawn independently per
+ sample whatever the flag says.
+ Color adjustment order is one permutation shared across the batch,
+ independently of this flag. On ``AugmentationSequential``, ``None`` keeps
+ each child's setting, while ``True`` and ``False`` overwrite it.
+- A concrete constructor's ``p`` can configure either the base's per-sample
+ gate or its whole-batch gate. Mix augmentations in particular do not share
+ one probability contract. Check the concrete class rather than inferring
+ its gate from the base signature. Exposing ``p_batch`` is also
+ constructor-dependent (`#4425 <https://github.com/kornia/kornia/issues/4425>`_).
+- Under :class:`torch.utils.data.DataLoader`, each worker's global CPU
+ generator is seeded ``base_seed + worker_id``. Reproducibility also depends
+ on worker configuration and consumption order. A ``worker_init_fn`` that
+ reseeds every worker to the same fixed value duplicates their random
+ streams. See `Randomness in multi-process data loading
+ <https://pytorch.org/docs/stable/notes/randomness.html#dataloader>`_.
+- Changing random draw consumption can shift later draws in a seeded
+ pipeline; reordering draws can change which parameter gets each value.
+ The convention tests compare final RNG states to reference operations,
+ so they check consumption, not assignment of values to parameter keys.
+
+Serializing an augmentation
+^^^^^^^^^^^^^^^^^^^^^^^^^^^
+
+- Numeric ranges do not create trainable range parameters. Several
+ constructors, including ``RandomRotation`` and ``RandomAffine``, accept
+ ``nn.Parameter`` ranges that appear in ``named_parameters()`` and
+ ``state_dict()``. Gradients depend on the operation, backend and dtype.
+- Some numeric ranges are copied into buffers, but loading those buffers
+ does not update the cached sampling distributions; ``repr`` may or may not
+ reflect the loaded range. Reconstruct the augmentation to change what it
+ samples (`#4428 <https://github.com/kornia/kornia/issues/4428>`_).
+- Pickle and deepcopy can retain recorded parameters and transform state,
+ but support is configuration-dependent. ``RandomGaussianIllumination``
+ cannot currently be pickled
+ (`#4435 <https://github.com/kornia/kornia/issues/4435>`_). Lazy matrix state
+ can retain the last input batch, increasing serialized size until the
+ matrix is read (`#4482 <https://github.com/kornia/kornia/issues/4482>`_).
+ A normal forward draws fresh parameters; replay requires passing the
+ saved parameters and controlling any application-time randomness.
+
Pitfall checklist
-----------------
@@ -246,8 +379,17 @@ Quick self-review for generated code, most common first:
12. Quaternions constructed in XYZW order β€” Kornia uses WXYZ.
13. Expecting hue in ``[0, 360]`` or ``[0, 1]`` β€” ``rgb_to_hsv`` returns
radians ``[0, 2Ο€)``.
-14. Wrong ``data_keys`` box format β€” ``"bbox"`` means 4-corner ``(B, 4, 2)``;
+14. Wrong ``data_keys`` box format β€” ``"bbox"`` means 4-corner ``(B, N, 4, 2)``;
use ``"bbox_xyxy"``/``"bbox_xywh"`` for coordinate formats.
+15. Assuming one rotation direction across the augmentations β€” a positive
+ ``degrees`` on ``RandomAffine`` turns the image clockwise, on
+ ``RandomRotation`` counter-clockwise.
+16. Expecting a non-rigid augmentation (``RandomElasticTransform``,
+ ``RandomThinPlateSpline``, ``RandomFisheye``) to carry boxes and keypoints
+ along with the image β€” it does not. Only ``RandomElasticTransform`` carries
+ a mask along, and the other two raise on a ``mask`` key.
+17. Inferring the augmentation sampling backend from ``_params`` placement
+ β€” samplers can draw on an accelerator and cast the returned tensors back to CPU.
.. tip::
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index eb65bebea..7e6f2bb85 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -35,6 +35,10 @@ 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.
+
Args:
p: probability for applying an augmentation. This param controls the augmentation probabilities
element-wise for a batch.
@@ -44,6 +48,77 @@ class AugmentationBase2D(_AugmentationBase):
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
form ``False``.
+ Convention:
+ - 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 and
+ `#4467 <https://github.com/kornia/kornia/issues/4467>`_.
+ - unsupported ranks and container entry points report validation errors through different paths.
+ Tracked in `#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>`_.
+ - 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 `#4415 <https://github.com/kornia/kornia/issues/4415>`_ and
+ `#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>`_), some
+ augmentations are not picklable (`#4435 <https://github.com/kornia/kornia/issues/4435>`_), and saved
+ state can retain data from the last call (`#4482 <https://github.com/kornia/kornia/issues/4482>`_).
+ - 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.
+ - 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 and may fail during migration on an
+ accelerator. Tracked in `#4415 <https://github.com/kornia/kornia/issues/4415>`_ and
+ `#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>`_.
+
"""
def validate_tensor(self, input: torch.Tensor) -> None:
@@ -67,8 +142,10 @@ class AugmentationBase2D(_AugmentationBase):
class RigidAffineAugmentationBase2D(AugmentationBase2D):
r"""AugmentationBase2D base class for rigid/affine augmentation implementations.
- RigidAffineAugmentationBase2D enables routined transformation with given transformation matrices
- for different data types like masks, boxes, and keypoints.
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.
+
+ RigidAffineAugmentationBase2D manages transformation matrices. Further subclasses supply the
+ handlers for different data types like masks, boxes, and keypoints.
Args:
p: probability for applying an augmentation. This param controls the augmentation probabilities
@@ -79,6 +156,17 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it to the batch
form ``False``.
+ Convention:
+ - a subclass implements :meth:`compute_transformation`, which returns the ``(B, 3, 3)`` matrix of the
+ sampled transform, and ``apply_transform`` for images. Direct mask, box, and keypoint handlers are
+ incomplete on this base; inherit the geometric base for its matrix-based handlers. Container dispatch
+ 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``; retained state has the serialization limitations in `#4482
+ <https://github.com/kornia/kornia/issues/4482>`_.
+ - this base does not implement an inverse operation.
+
"""
_transform_matrix: Optional[torch.Tensor] = None
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index eef03f80d..5049a8a53 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -29,6 +29,8 @@ from kornia.geometry.keypoints import Keypoints
class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
r"""GeometricAugmentationBase2D base class for customized geometric augmentation implementations.
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.
+
Args:
p: probability for applying an augmentation. This param controls the augmentation probabilities
element-wise for a batch.
@@ -38,6 +40,23 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
+ Convention:
+ - 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
+ interpolation. Tensor-form boxes may lose rotated corners through axis-aligned enclosure.
+ - container mask processing has dtype- and operator-specific limitations; see
+ `#4478 <https://github.com/kornia/kornia/issues/4478>`_ and
+ `#4479 <https://github.com/kornia/kornia/issues/4479>`_. Direct ``transform_masks`` calls use the
+ image dtype guard and therefore reject ``bool`` masks.
+ - a subclass supplies its own :meth:`inverse_transform` -- the base raises ``NotImplementedError`` --
+ while :meth:`compute_inverse_transformation` defaults to inverting the sampled matrix.
+
+ .. warning::
+ The ``resample`` half of an ``extra_args[DataKey.MASK]`` override is discarded here -- masks are
+ always nearest -- while the ``align_corners`` half does reach the sampler. Tracked in
+ `#4419 <https://github.com/kornia/kornia/issues/4419>`_.
+
"""
def inverse_transform(
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
index 9cb4cb70c..e0aa7e526 100644
--- a/kornia/augmentation/_2d/intensity/base.py
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -27,6 +27,8 @@ from kornia.geometry.keypoints import Keypoints
class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
r"""IntensityAugmentationBase2D base class for customized intensity augmentation implementations.
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.
+
Args:
p: probability for applying an augmentation. This param controls the augmentation probabilities
element-wise for a batch.
@@ -36,6 +38,19 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
+ Convention:
+ - an intensity augmentation moves no image pixel, so this base supplies ``compute_transformation``
+ itself and reports the identity matrix. Its direct mask and keypoint handlers pass their inputs through,
+ except where a subclass overrides them: :class:`RandomErasing` also erases masks. Direct box dispatch
+ is currently unsupported despite the similarly named plural helpers below; see
+ `#4480 <https://github.com/kornia/kornia/issues/4480>`_.
+ A subclass supplies ``apply_transform`` and, where it draws anything, its ``_param_generator``.
+ - the matrix is built lazily, on the first read of ``transform_matrix``.
+ - this base adds no ``inverse``. When
+ :class:`~kornia.augmentation.container.AugmentationSequential.inverse` can run, it skips 2D intensity
+ children and reverses supported geometric children.
+ - these classes assume the library-wide ``[0, 1]`` float image value range.
+
"""
# Intensity augmentations are pointwise: apply_transform ignores the transform matrix and
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index ba2f1dd8a..6c2fdf2c0 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -32,7 +32,7 @@ class RandomJigsaw(MixAugmentationBaseV2):
.. image:: _static/img/RandomJigsaw.png
Make Jigsaw puzzles for each image individually. To mix with different images in a
- batch, referring to :class:`kornia.augmentation.RandomMosic`.
+ batch, referring to :class:`kornia.augmentation.RandomMosaic`.
Args:
grid: the Jigsaw puzzle grid. e.g. (2, 2) means
@@ -42,7 +42,7 @@ class RandomJigsaw(MixAugmentationBaseV2):
data_keys: the input type sequential for applying augmentations.
Accepts "input", "image", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints",
"class", "label".
- p: probability of applying the transformation for the whole batch.
+ p: probability of applying the transformation to each sample.
same_on_batch: apply the same transformation across the batch.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index be9bd6123..d3fa20a43 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -54,7 +54,7 @@ class RandomMosaic(MixAugmentationBaseV2):
data_keys: the input type sequential for applying augmentations.
Accepts "input", "image", "mask", "bbox", "bbox_xyxy", "bbox_xywh", "keypoints",
"class", "label".
- p: probability of applying the transformation for the whole batch.
+ p: probability of applying the transformation to each sample.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
padding_mode: Type of padding. Should be: constant, reflect, replicate.
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index f7a6afabb..4be2e5178 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -52,8 +52,13 @@ class _BasicAugmentationBase(nn.Module):
r"""_BasicAugmentationBase base class for customized augmentation implementations.
Plain augmentation base class without the functionality of transformation matrix calculations.
- By default, the random computations will be happened on CPU with ``torch.get_default_dtype()``.
- To change this behaviour, please use ``set_rng_device_and_dtype``.
+
+ 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 `#4415 <https://github.com/kornia/kornia/issues/4415>`_ and
+ `#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
@@ -170,6 +175,13 @@ class _BasicAugmentationBase(nn.Module):
Note:
The generated random numbers are not reproducible across different devices and dtypes.
+ .. warning::
+ This updates both the gate and the parameter generator's samplers, but returned parameters
+ can be cast to a different device/dtype; inspecting ``_params`` alone does not reveal where
+ sampling occurred. Some classes fail after moving their samplers to an accelerator. Tracked in
+ `#4426 <https://github.com/kornia/kornia/issues/4426>`_; the
+ :doc:`/get-started/conventions` page describes placement and the affected classes.
+
"""
self.device = device
self.dtype = dtype
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index ceda528d5..652536a39 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -67,7 +67,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
keepdim: whether to keep the output shape the same as input (True) or broadcast it to the batch form (False).
If None, it will not overwrite the function-wise settings.
- random_apply: randomly select a sublist (order agnostic) of args to apply transformation.
+ random_apply: randomly select children to apply. The selected children run in random order and may repeat
+ when the requested count exceeds the sum of the selection weights.
If int, a fixed number of transformations will be selected.
If (a,), x number of transformations (a <= x <= len(args)) will be selected.
If (a, b), x number of transformations (a <= x <= b) will be selected.
@@ -76,18 +77,124 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
transformation_matrix_mode: computation mode for the chained transformation matrix, via `.transform_matrix`
attribute.
- If `silent`, transformation matrix will be computed silently and the non-rigid
- modules will be ignored as identity transformations.
+ If `silent`, the default, the transformation matrix is computed silently and a
+ direct non-rigid module is skipped rather than treated as an identity. Nested
+ containers are not handled consistently; see the Convention note below.
If `rigid`, transformation matrix will be computed silently and the non-rigid
modules will trigger errors.
If `skip`, transformation matrix will be totally ignored.
-
- extra_args: to control the behaviour for each datakeys. By default, masks are handled by nearest interpolation
- strategies.
+ The validator also accepts `silence`, an alias that behaves
+ like `silent`; any other value raises ``ValueError``.
+
+ extra_args: a dict keyed by ``kornia.constants.DataKey`` that **replaces** the default
+ ``{DataKey.MASK: {'resample': Resample.NEAREST, 'align_corners': None}}`` rather than
+ merging into it, so an override that omits a key drops that key's default. An empty dict
+ is falsy and restores the default. ``DataKey.IMAGE`` honours both entries and
+ ``DataKey.KEYPOINTS`` honours neither. For ``DataKey.MASK`` on a 2D geometric augmentation
+ that uses the base mask path the ``resample`` entry is discarded -- masks are resampled
+ with nearest neighbour whatever it says. ``align_corners`` is handler-dependent: some warps
+ honor it, but resize mask paths replace it as well (see #4419).
+ 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.
+ :class:`~kornia.augmentation.RandomElasticTransform` has its own mask path and honours
+ both entries, but requires a ``kornia.constants.Resample`` member rather than a
+ string.
+
+ 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 are matched by raw prefixes and the container removes entries while
+ processing them. Prefixes can therefore route unrelated names (for example, ``imagenet_id``) as data
+ keys; use positional arguments for reliable key selection. Tracked in
+ `#4483 <https://github.com/kornia/kornia/issues/4483>`_.
+ - 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``.
+ 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.
+ ``Resize(antialias=True)`` filters masks before sampling and can change labels
+ (`#4479 <https://github.com/kornia/kornia/issues/4479>`_); padding can introduce a fill value.
+ Put the image before the masks, including
+ in dictionary insertion order, so mask conversion uses that image's working dtype. Masks preceding
+ the image use the previous call's image dtype, or ``float32`` on a fresh container. The container
+ casts every mask output to the last mask argument's dtype (the first
+ element's dtype if that argument is a list). A single mask or masks with a common dtype therefore
+ keep that dtype, ``bool`` included. Conversion through the image working dtype can round integer
+ labels that dtype cannot represent exactly, and mixed mask dtypes can lose labels, for example when a
+ final boolean mask makes an integer semantic mask boolean too. Tracked in
+ `#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
+ list can become desynchronized from the image when the gate differs across samples. A list longer
+ than the batch raises ``IndexError``. Use separate ``mask`` data keys with a common dtype for
+ separate full-batch masks. 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.
+
+ .. warning::
+ The base 2D geometric mask path discards the ``resample`` half of an ``extra_args[DataKey.MASK]``
+ override. Custom mask paths, including ``RandomElasticTransform``, may honor it instead. Tracked in
+ `#4419 <https://github.com/kornia/kornia/issues/4419>`_.
+
+ .. warning::
+ A non-rigid child silently desynchronizes the coordinate data keys:
+ :class:`~kornia.augmentation.RandomElasticTransform` warps the image **and** a ``mask`` key with it,
+ but returns keypoints and boxes unchanged, and
+ :class:`~kornia.augmentation.RandomThinPlateSpline` and :class:`~kornia.augmentation.RandomFisheye`
+ return keypoints and boxes unchanged and raise a bare ``NotImplementedError`` on a ``mask`` key.
+ Tracked in `#4420 <https://github.com/kornia/kornia/issues/4420>`_.
.. note::
- Mix augmentations (e.g. RandomMixUp, RandomCutMix) can only be working with "input"/"image" data key.
- It is not clear how to deal with the conversions of masks, bounding boxes and keypoints.
+ Inside this container a mix child (e.g. RandomMixUpV2, RandomCutMixV2, RandomMosaic) mixes the image only.
+ A ``class``/``label`` key raises ``NotImplementedError``, and ``mask``, box and ``keypoints`` keys are
+ returned unchanged, silently desynchronized from the mixed image, even where the class transforms that
+ key when called directly (``RandomMosaic`` boxes). Tracked in
+ `#4493 <https://github.com/kornia/kornia/issues/4493>`_.
.. note::
See a working example `here <https://www.kornia.org/tutorials/nbs/data_augmentation_sequential.html>`__.
@@ -173,31 +280,26 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
>>> [o.shape for o in out] # doctest: +ELLIPSIS
[torch.Size([1, 2, 3, 5, 6]), torch.Size([1, 2, 3, 5, 6]), ...([1, 2, 1, 4, 2]), torch.Size([1, 2, 1, 2])]
- This example shows how to use a list of masks and boxes within AugmentationSequential
+ Use separate full-batch mask arguments when their channel counts differ:
>>> import kornia.augmentation as K
- >>> input = torch.randn(2, 3, 256, 256)
- >>> mask = [torch.ones(1, 3, 256, 256), torch.ones(1, 2, 256, 256)]
- >>> bbox = [
- ... torch.tensor([[28.0, 53.0, 143.0, 164.0], [254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]]),
- ... torch.tensor([[254.0, 158.0, 364.0, 290.0], [307.0, 204.0, 413.0, 350.0]])
- ... ]
- >>> bbox = [Boxes.from_tensor(i).data for i in bbox]
-
+ >>> input = torch.randn(2, 3, 32, 32)
+ >>> mask_a = torch.ones(2, 3, 32, 32)
+ >>> mask_b = torch.ones(2, 2, 32, 32)
>>> aug_list = K.AugmentationSequential(
- ... K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0),
- ... K.RandomHorizontalFlip(p=1.0),
- ... K.ImageSequential(K.RandomHorizontalFlip(p=1.0)),
- ... K.ImageSequential(K.ColorJiggle(0.1, 0.1, 0.1, 0.1, p=1.0)),
- ... data_keys=["input", "mask", "bbox"],
- ... same_on_batch=False,
- ... random_apply=10,
+ ... K.RandomHorizontalFlip(p=1.0),
+ ... data_keys=["input", "mask", "mask"],
... )
- >>> out = aug_list(input, mask, bbox)
+ >>> out = aug_list(input, mask_a, mask_b)
+ >>> [value.shape for value in out]
+ [torch.Size([2, 3, 32, 32]), torch.Size([2, 3, 32, 32]), torch.Size([2, 2, 32, 32])]
- How to use a dictionary as input with AugmentationSequential? The dictionary keys that start with
- one of the available datakeys will be augmented accordingly. Otherwise, the dictionary item is passed
- without any augmentation.
+ With ``data_keys=None``, dictionary keys are matched to data-key prefixes. Use the exact keys
+ ``bbox_xyxy`` and ``bbox_xywh`` for coordinate boxes: suffixed versions match ``bbox`` and require
+ vertices instead. Use ``label`` for labels, since ``class`` and its prefixes are treated as unrelated
+ metadata. Unrecognized items are popped from the caller's dictionary and returned without augmentation.
+ Raw prefix matching can also misroute unrelated names such as ``imagenet_id``. Tracked in
+ `#4483 <https://github.com/kornia/kornia/issues/4483>`_.
>>> import kornia.augmentation as K
>>> img = torch.randn(1, 3, 256, 256)
@@ -310,6 +412,8 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
) -> Union[DataType, List[DataType], Dict[str, DataType]]:
"""Reverse the transformation applied.
+ See the Convention block on :class:`~kornia.augmentation.container.AugmentationSequential`.
+
Number of input tensors must align with the number of``data_keys``. If ``data_keys`` is not set, use
``self.data_keys`` by default.
"""
@@ -436,7 +540,10 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
params: Optional[List[ParamItem]] = None,
data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = None,
) -> Union[DataType, List[DataType], Dict[str, DataType]]:
- """Compute multiple tensors simultaneously according to ``self.data_keys``."""
+ """Compute multiple tensors simultaneously according to ``self.data_keys``.
+
+ See the Convention block on :class:`~kornia.augmentation.container.AugmentationSequential`.
+ """
self.clear_state()
# Strip trailing ``None`` positional args. The legacy torch.onnx.export tracer
diff --git a/kornia/augmentation/container/dispatcher.py b/kornia/augmentation/container/dispatcher.py
index aae589272..e6877063d 100644
--- a/kornia/augmentation/container/dispatcher.py
+++ b/kornia/augmentation/container/dispatcher.py
@@ -25,9 +25,18 @@ from .augment import AugmentationSequential
class ManyToManyAugmentationDispather(nn.Module):
r"""Dispatches different augmentations to different inputs element-wisely.
+ See the Convention block on :class:`~kornia.augmentation.container.AugmentationSequential`.
+
Args:
augmentations: a list or a sequence of kornia AugmentationSequential modules.
+ Convention:
+ - every member has to be an :class:`~kornia.augmentation.container.AugmentationSequential`; anything else is
+ rejected at construction with ``ValueError``.
+ - the call takes one input bundle per augmentation and returns a list in that order; a different number
+ of bundles raises ``ValueError`` before any augmentation runs. Each augmentation draws its own
+ parameters, so the members are independent of one another.
+
Examples:
>>> import torch
>>> input_1, input_2 = torch.randn(2, 3, 5, 6), torch.randn(2, 3, 5, 6)
@@ -81,6 +90,8 @@ class ManyToManyAugmentationDispather(nn.Module):
class ManyToOneAugmentationDispather(nn.Module):
r"""Dispatches different augmentations to a single input and returns a list.
+ See the Convention block on :class:`~kornia.augmentation.container.AugmentationSequential`.
+
Same `datakeys` must be applied across different augmentations. By default, with input
(image, mask), the augmentations must not mess it as (mask, image) to avoid unexpected
errors. This check can be cancelled with `strict=False` if needed.
@@ -88,6 +99,12 @@ class ManyToOneAugmentationDispather(nn.Module):
Args:
augmentations: a list or a sequence of kornia AugmentationSequential modules.
+ Convention:
+ - the same input payload is broadcast to every augmentation, so the returned list is always as long
+ as the list of augmentations and no input can be dropped.
+ - with ``strict=True``, the default, the members must all declare the same ``data_keys``; a mismatch
+ raises ``RuntimeError`` at construction.
+
Examples:
>>> import torch
>>> input = torch.randn(2, 3, 5, 6)
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 6ef43bb7f..e4fa18038 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -54,14 +54,16 @@ class ImageModuleForSequentialMixIn(ImageModuleMixIn):
class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
r"""nn.Sequential for creating kornia image processing pipeline.
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.
+
Args:
*args : a list of kornia augmentation and image operation modules.
same_on_batch: apply the same transformation across the batch.
If None, it will not overwrite the function-wise settings.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False). If None, it will not overwrite the function-wise settings.
- random_apply: randomly select a sublist (order agnostic) of args to
- apply transformation. The selection probability aligns to the ``random_apply_weights``.
+ random_apply: randomly select children to apply in random order. The selection probability aligns to the
+ ``random_apply_weights`` and selections may repeat when the requested count is larger than their sum.
If int, a fixed number of transformations will be selected.
If (a,), x number of transformations (a <= x <= len(args)) will be selected.
If (a, b), x number of transformations (a <= x <= b) will be selected.
@@ -69,6 +71,28 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
If False, the whole list of args will be processed as a sequence in original order.
random_apply_weights: a list of selection weights for each operation. The length shall be as
same as the number of operations. By default, operations are sampled uniformly.
+ if_unsupported_ops: intended to choose between raising and skipping an uninvertible plain ``nn.Module``.
+ It is neither validated nor enforced, and the inverse path skips such a module under every value.
+
+ Convention:
+ - this container takes image tensors only. It has no ``data_keys``, so masks, boxes and keypoints go
+ through :class:`~kornia.augmentation.container.AugmentationSequential` instead. It also carries no
+ ``.transform_matrix`` attribute: the chained matrix is reachable through
+ ``get_transformation_matrix``, which needs the recorded ``params=`` handed back to it. To use params
+ from an older call, pass ``recompute=True``.
+ - any ``nn.Module`` may sit in the chain next to the augmentations -- the modules of
+ ``kornia.filters``, ``kornia.color`` and ``kornia.enhance`` among them. ``random_apply``
+ samples ordinary members and mix augmentations through separate paths; a mix member's insertion
+ does not honor its ordinary selection weight. Each selected member is recorded in ``_params``, but
+ a plain module records a ``None`` payload: only augmentation members carry a parameter draw to replay.
+ - ``inverse`` skips uninvertible plain ``nn.Module`` members. Augmentation children can still raise,
+ for example a slice-mode crop or a 3D geometric augmentation, while non-rigid augmentation children
+ are left applied; the round trip is not in general the input.
+
+ .. warning::
+ ``if_unsupported_ops`` never fires: a plain ``nn.Module`` in the chain is skipped on the inverse path
+ under every value of the flag, an invalid value included, and nothing is raised or warned. Tracked in
+ `#4423 <https://github.com/kornia/kornia/issues/4423>`_.
.. note::
Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index c2d7c84b4..e2b3f416e 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -41,6 +41,8 @@ __all__ = ["PatchSequential"]
class PatchSequential(ImageSequential):
r"""Container for performing patch-level image data augmentation.
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.
+
.. image:: _static/img/PatchSequential.png
PatchSequential breaks input images into patches by a given grid size, which will be resembled back
@@ -65,8 +67,8 @@ class PatchSequential(ImageSequential):
patchwise_apply: apply image processing args will be applied patch-wisely.
if ``True`` and ``random_apply=False``, the number of args must equal the number of patches.
if ``False``, the image processing args will be applied as a sequence to all patches.
- random_apply: randomly select a sublist (order agnostic) of args to
- apply transformation.
+ random_apply: randomly select children to apply in random order. Selections may repeat when the requested
+ count is larger than the sum of the selection weights.
If ``int`` (batchwise mode only), a fixed number of transformations will be selected.
If ``(a,)`` (batchwise mode only), x number of transformations (a <= x <= len(args)) will be selected.
If ``(a, b)`` (batchwise mode only), x number of transformations (a <= x <= b) will be selected.
@@ -76,6 +78,8 @@ class PatchSequential(ImageSequential):
location-wisely.
Convention:
+ - like :class:`~kornia.augmentation.container.ImageSequential`, this container takes image tensors only: it has
+ no ``data_keys`` and no ``.transform_matrix`` attribute.
- input images have shape ``(B, C, H, W)``. Each image is split into ``N = rows * columns`` patches,
ordered by row then column. Parameters index the flattened ``B * N`` patch batch.
- with ``patchwise_apply=True`` and ``random_apply=False``, each module processes its grid location
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 8baadc489..c94fb9792 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -35,6 +35,8 @@ __all__ = ["VideoSequential"]
class VideoSequential(ImageSequential):
r"""VideoSequential for processing 5-dim video data like (B, T, C, H, W) and (B, C, T, H, W).
+ See the Convention block on :class:`~kornia.augmentation.AugmentationBase2D`.
+
`VideoSequential` is used to replace `nn.Sequential` for processing video data augmentations.
By default, `VideoSequential` enabled `same_on_frame` to make sure the same augmentations happen
across temporal dimension. Meanwhile, it will not affect other augmentation behaviours like the
@@ -51,6 +53,18 @@ class VideoSequential(ImageSequential):
If (a, b), x number of transformations (a <= x <= b) will be selected.
If None, the whole list of args will be processed as a sequence.
+ Convention:
+ - the input is 5-dimensional and the layout is named by ``data_format``, which accepts ``"BTCHW"``
+ (the default) and ``"BCTHW"``, case-insensitively; any other spelling raises ``AssertionError``.
+ The output keeps the input layout.
+ - ``same_on_frame`` is ``True`` by default, so one draw is shared by every frame of a clip and the
+ clip stays temporally consistent. With ``same_on_frame=False`` each frame is drawn independently.
+ - like :class:`~kornia.augmentation.container.ImageSequential`, this container takes image tensors only: it has
+ no ``data_keys`` and no ``.transform_matrix`` attribute. Register a ``VideoSequential`` as a child of
+ :class:`~kornia.augmentation.container.AugmentationSequential` to augment video masks, boxes and keypoints
+ alongside the clip. For video boxes, use ``bbox`` vertices with shape ``(B, T, N, 4, 2)``;
+ coordinate keys ``bbox_xyxy`` and ``bbox_xywh`` do not accept ``(B, T, N, 4)`` tensors.
+
Note:
Transformation matrix returned only considers the transformation applied in ``kornia.augmentation`` module.
Those transformations in ``kornia.geometry`` will not be taken into account.
diff --git a/testing/base.py b/testing/base.py
index 0d441c620..f1f802b68 100644
--- a/testing/base.py
+++ b/testing/base.py
@@ -197,6 +197,17 @@ def supports_bilinear_2d_grid_sample(device: torch.device, dtype: torch.dtype) -
return _supports_kernel_probe(_bilinear_2d_grid_sample_op, device.type, dtype)
+def _bilinear_2d_grid_sample_backward_op(device_type: str, dtype: torch.dtype) -> None:
+ inp = _probe_zeros(device_type, dtype, 1, 1, 2, 2).requires_grad_()
+ grid = _probe_zeros(device_type, dtype, 1, 1, 1, 2).requires_grad_()
+ F.grid_sample(inp, grid, mode="bilinear", align_corners=True).sum().backward()
+
+
+def supports_bilinear_2d_grid_sample_backward(device: torch.device, dtype: torch.dtype) -> bool:
+ """Whether 2D bilinear grid sampling supports gradients to both input and grid for this device/dtype."""
+ return _supports_kernel_probe(_bilinear_2d_grid_sample_backward_op, device.type, dtype)
+
+
def _bicubic_2d_grid_sample_op(device_type: str, dtype: torch.dtype) -> None:
inp = _probe_zeros(device_type, dtype, 1, 1, 2, 2)
grid = _probe_zeros(device_type, dtype, 1, 1, 1, 2)
@@ -242,6 +253,15 @@ def supports_nearest_3d_grid_sample(device: torch.device, dtype: torch.dtype) ->
return _supports_kernel_probe(_nearest_3d_grid_sample_op, device.type, dtype)
+def _reflect_padding_op(device_type: str, dtype: torch.dtype) -> None:
+ F.pad(_probe_zeros(device_type, dtype, 1, 1, 2, 2), (1, 1, 1, 1), mode="reflect")
+
+
+def supports_reflect_padding(device: torch.device, dtype: torch.dtype) -> bool:
+ """Whether this device supports 2D reflection padding for this dtype, probed once per device/dtype."""
+ return _supports_kernel_probe(_reflect_padding_op, device.type, dtype)
+
+
def _replicate_padding_op(device_type: str, dtype: torch.dtype) -> None:
F.pad(_probe_zeros(device_type, dtype, 1, 1, 2, 2), (1, 1, 1, 1), mode="replicate")
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index e833dcf0b..3fbdc2c8c 100644
--- a/testing/half_precision_eager_rng.py
+++ b/testing/half_precision_eager_rng.py
@@ -149,7 +149,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(
(
*_audited(
"tests/augmentation/container/test_augmentation_sequential.py",
- 47,
+ 48,
"torch.randn",
2,
(
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 6aae5536c..599f53ce5 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -24,12 +24,13 @@ import torch
import kornia
import kornia.augmentation as K
from kornia.augmentation.container.base import ParamItem
-from kornia.constants import BorderType
+from kornia.constants import BorderType, DataKey, Resample
from kornia.core._compat import torch_version_lt
from kornia.geometry.bbox import bbox_to_mask
+from kornia.geometry.boxes import Boxes
from testing.augmentation.utils import reproducibility_test
-from testing.base import assert_close
+from testing.base import BaseTester, assert_close
class TestAugmentationSequential:
@@ -610,3 +611,527 @@ class TestAugmentationSequential:
assert outputs[1].dtype == dtype, "Output mask dtype should match the input dtype"
assert outputs[2].dtype == dtype, "Output box dtype should match the input dtype"
assert outputs[3].dtype == dtype, "Output keypoints dtype should match the input dtype"
+
+
[email protected]("restore_torch_rng")
+class TestConventionAugmentationSequential(BaseTester):
+ """Convention checks and pins for documented `AugmentationSequential` limitations."""
+
+ def test_convention_flip_is_integer_centre_inclusive_for_every_data_key(self, device, dtype):
+ # Convention pin: a horizontal flip maps column x to W - 1 - x, and a vertical flip row y to H - 1 - y,
+ # 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:
+ # 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
+ # box [3, 0, 4, 1].
+ img = torch.zeros(1, 1, 3, 4, device=device, dtype=dtype)
+ img[0, 0, 0, 1] = 1.0
+ kpts = torch.tensor([[[1.0, 2.0]]], device=device, dtype=dtype)
+ boxes = torch.tensor([[[0.0, 0.0, 1.0, 1.0]]], device=device, dtype=dtype)
+ vertices = torch.tensor([[[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]]], device=device, dtype=dtype)
+ keys = ["input", "mask", "keypoints", "bbox_xyxy", "bbox"]
+
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=keys)
+ out_img, out_mask, out_kpts, out_boxes, out_vertices = aug(img, img.clone(), kpts, boxes, vertices)
+ expected_img = torch.zeros(1, 1, 3, 4, device=device, dtype=dtype)
+ expected_img[0, 0, 0, 2] = 1.0
+ self.assert_close(out_img, expected_img)
+ self.assert_close(out_mask, out_img)
+ self.assert_close(out_kpts, torch.tensor([[[2.0, 2.0]]], device=device, dtype=dtype))
+ self.assert_close(out_boxes, torch.tensor([[[2.0, 0.0, 3.0, 1.0]]], device=device, dtype=dtype))
+ self.assert_close(
+ out_vertices,
+ torch.tensor([[[[2.0, 0.0], [3.0, 0.0], [3.0, 1.0], [2.0, 1.0]]]], device=device, dtype=dtype),
+ )
+
+ aug = K.AugmentationSequential(K.RandomVerticalFlip(p=1.0), data_keys=keys[:-1])
+ out_img, out_mask, out_kpts, out_boxes = aug(img, img.clone(), kpts, boxes)
+ expected_img = torch.zeros(1, 1, 3, 4, device=device, dtype=dtype)
+ expected_img[0, 0, 2, 1] = 1.0
+ self.assert_close(out_img, expected_img)
+ self.assert_close(out_mask, out_img)
+ self.assert_close(out_kpts, torch.tensor([[[1.0, 0.0]]], device=device, dtype=dtype))
+ self.assert_close(out_boxes, torch.tensor([[[0.0, 1.0, 1.0, 2.0]]], device=device, dtype=dtype))
+
+ def test_convention_data_key_shapes_are_validated(self, device, dtype):
+ # 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):
+ # "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])."
+ img = torch.rand(1, 1, 3, 4, device=device, dtype=dtype)
+ cases = [
+ ("bbox", torch.rand(1, 1, 4, device=device, dtype=dtype), "must be .N, 4, 2."),
+ ("bbox_xyxy", torch.rand(1, 1, 4, 2, device=device, dtype=dtype), "must be .N, 4."),
+ ("keypoints", torch.rand(1, 2, 3, device=device, dtype=dtype), "Keypoints shape must be"),
+ ]
+ for key, wrong, message in cases:
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", key])
+ with pytest.raises(ValueError, match=message):
+ aug(img, wrong)
+ # the accepted layouts pass, including the degenerate N = 0 case
+ for key, shape in [("bbox", (2, 0, 4, 2)), ("bbox_xyxy", (2, 0, 4)), ("keypoints", (2, 0, 2))]:
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", key])
+ empty = torch.rand(*shape, device=device, dtype=dtype)
+ out = aug(torch.rand(2, 1, 3, 4, device=device, dtype=dtype), empty)
+ assert out[1].shape == shape
+ # `mask` is the one key whose rank changes: (B, H, W) in, (B, 1, H, W) out
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ out = aug(img, torch.rand(1, 3, 4, device=device, dtype=dtype))
+ assert out[1].shape == (1, 1, 3, 4)
+
+ def test_wart_mask_lists_desynchronize_mixed_probability_batches_4477(self, device, dtype):
+ # A list entry selects one sample's gate, even when that entry contains the whole batch.
+ image = torch.arange(24, device=device, dtype=dtype).reshape(2, 1, 3, 4)
+ masks = [image.clone(), image.expand(-1, 2, -1, -1).clone()]
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask"])
+ params = [
+ ParamItem(
+ "RandomHorizontalFlip_0",
+ {"batch_prob": torch.tensor([1.0, 0.0]), "forward_input_shape": torch.tensor(image.shape)},
+ )
+ ]
+ out_image, out_masks = seq(image, masks, params=params)
+ self.assert_close(out_image, torch.stack((image[0].flip(-1), image[1])))
+ self.assert_close(out_masks[0], masks[0].flip(-1))
+ self.assert_close(out_masks[1], masks[1])
+ assert not torch.equal(out_masks[0][1], out_image[1])
+ assert not torch.equal(out_masks[1][0, :1], out_image[0])
+
+ # Separate tensor mask keys preserve the per-sample gates for both channel counts.
+ aligned = K.AugmentationSequential(K.RandomHorizontalFlip(p=0.5), data_keys=["input", "mask", "mask"])
+ out_image, first, second = aligned(image, *masks, params=params)
+ self.assert_close(first, out_image)
+ self.assert_close(second, out_image.expand(-1, 2, -1, -1))
+
+ # 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"):
+ 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"):
+ warp(image, masks)
+ 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(
+ [[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]], [[2.0, 2.0], [3.0, 2.0], [3.0, 3.0], [2.0, 3.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ output, out_masks = crop(image, masks, params=params)
+ self.assert_close(output[0], image[0, :, :2, :2])
+ self.assert_close(output[1], image[1, :, 2:, 2:])
+ self.assert_close(out_masks[0], output[:1])
+ self.assert_close(out_masks[1], output[:1])
+ assert not torch.equal(out_masks[1], output[1:])
+
+ def test_wart_mix_children_pass_annotations_through_4493(self, device, dtype):
+ # Wart pin (#4493): the container's mask, box and keypoint handlers have no branch for a mix child, so
+ # those keys come back unchanged next to a mixed image. Called directly, RandomMosaic transforms boxes
+ # and RandomMixUpV2 raises NotImplementedError on a mask; the container hides both. A class key still
+ # raises. Seed 0 on a 16x16 batch: every listed mix applies (a 6x8 fixture can draw an empty cut box).
+ if dtype == torch.bfloat16:
+ pytest.skip("Tracked in #4467: the mix forward path has no bfloat16 DType")
+ image = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
+ boxes = torch.tensor([[[0.0, 0.0, 2.0, 2.0]], [[1.0, 1.0, 3.0, 3.0]]], device=device, dtype=dtype)
+ 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)
+ torch.manual_seed(0)
+ container = K.AugmentationSequential(
+ K.RandomMosaic(p=1.0), data_keys=["input", "bbox_xyxy", "mask", "keypoints"]
+ )
+ out_image, out_boxes, out_mask, out_keypoints = container(image, boxes, mask, keypoints)
+ assert not torch.equal(out_image, image) # the image was mixed
+ self.assert_close(out_boxes, boxes, rtol=0, atol=0)
+ self.assert_close(out_mask, mask, rtol=0, atol=0)
+ self.assert_close(out_keypoints, keypoints, rtol=0, atol=0)
+ torch.manual_seed(0)
+ direct_boxes = K.RandomMosaic(p=1.0, data_keys=["input", "bbox_xyxy"])(image, boxes)[1]
+ assert not torch.equal(direct_boxes, boxes) # the same draw moves the boxes when called directly
+ with pytest.raises(NotImplementedError):
+ K.RandomMixUpV2(p=1.0)(image, mask, data_keys=["input", "mask"])
+ with pytest.raises(NotImplementedError, match="class labels"):
+ K.AugmentationSequential(K.RandomMixUpV2(p=1.0), data_keys=["input", "class"])(
+ image, torch.tensor([0, 1], device=device)
+ )
+
+ def test_wart_dictionary_mask_before_image_loses_float64_precision_4478(self):
+ # On a fresh container, masks preceding the image fall back to float32 before being cast back.
+ 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)
+ image_first = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)
+ early_output = early_mask({"mask": mask, "image": image})["mask"]
+ expected = mask.flip(-1)
+ self.assert_close(early_output, expected.float().double(), rtol=0, atol=0)
+ assert not torch.equal(early_output, expected)
+ self.assert_close(image_first({"image": image, "mask": mask})["mask"], expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("mask_dtypes", [(torch.int64, torch.bool), (torch.bool, torch.int64)])
+ def test_wart_mask_outputs_use_the_last_mask_dtype_4478(self, mask_dtypes, device, dtype):
+ 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)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask", "mask"])
+ _, out_first, out_second = seq(image, first, second)
+ assert out_first.dtype == out_second.dtype == mask_dtypes[-1]
+ self.assert_close(out_first, first.flip(-1).to(mask_dtypes[-1]))
+ self.assert_close(out_second, second.flip(-1))
+ if mask_dtypes[-1] == torch.bool:
+ assert out_first.unique().tolist() == [False, True] # integer labels 2, 3 and 5 are lost
+
+ @pytest.mark.parametrize("key", ["bbox_xyxy", "bbox_xywh"])
+ def test_wart_suffixed_coordinate_box_dict_keys_expect_vertices_4483(self, key, device, dtype):
+ image = torch.arange(20, device=device, dtype=dtype).reshape(1, 1, 4, 5)
+ boxes = torch.tensor([[[0.0, 0.0, 2.0, 2.0]]], device=device, dtype=dtype)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)
+ output = seq({"image": image, key: boxes})
+ expected = [2.0, 0.0, 4.0, 2.0] if key == "bbox_xyxy" else [3.0, 0.0, 2.0, 2.0]
+ self.assert_close(output[key], torch.tensor([[expected]], device=device, dtype=dtype))
+ with pytest.raises(ValueError, match="when vertices_plus mode"):
+ seq({"image": image, key + "-a": boxes})
+
+ def test_wart_dictionary_class_alias_is_metadata_4483(self):
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)
+ keys, metadata = seq._read_datakeys_from_dict(("input", "class", "class-a", "label", "label-a"))
+ assert keys == [DataKey.INPUT, DataKey.LABEL, DataKey.LABEL]
+ assert metadata == ["class", "class-a"]
+
+ @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(
+ self, cropping_mode, align_corners, device, dtype
+ ):
+ 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(
+ K.RandomResizedCrop((2, 2), scale=(1.0, 1.0), ratio=(1.0, 1.0), cropping_mode=cropping_mode, p=1.0),
+ data_keys=["input", "mask"],
+ 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"):
+ seq(image, mask)
+ else:
+ out_image, out_mask = seq(image, mask)
+ assert out_image.shape == out_mask.shape == (1, 1, 2, 2)
+ assert set(out_mask.unique().tolist()).issubset({0.0, 1.0})
+
+ def test_convention_masks_keep_labels_and_add_padding_fill_through_a_rotation(self, device, dtype):
+ # Convention pin: masks are resampled with nearest interpolation, so a {2, 3} mask still holds those
+ # 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)
+ mask[:, :, 1:4, 2:6] = 3.0
+ out_mask = aug(torch.rand(batch, 3, 6, 8, device=device, dtype=dtype), mask)[1]
+ assert sorted(out_mask.unique().tolist()) == [0.0, 2.0, 3.0]
+ assert out_mask.dtype == dtype
+ assert (out_mask - mask).abs().max().item() == 2.0 # the rotation moved the mask
+ aug = K.AugmentationSequential(K.RandomAffine(degrees=(45.0, 45.0), p=1.0), data_keys=["input", "mask"])
+ bool_mask = torch.zeros(2, 1, 6, 8, device=device, dtype=torch.bool)
+ bool_mask[:, :, 1:4, 2:6] = True
+ assert aug(torch.rand(2, 3, 6, 8, device=device, dtype=dtype), bool_mask)[1].dtype == torch.bool
+
+ def test_wart_resize_antialias_blurs_masks_4479(self, device, dtype):
+ # Resize applies antialiasing before the mask's nearest interpolation, introducing values outside the
+ # input label set. This is a current wart, tracked in #4479.
+ image = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ mask = torch.full((1, 1, 8, 8), 2.0, device=device, dtype=dtype)
+ mask[:, :, :, 4:] = 3.0
+ aug = K.AugmentationSequential(K.Resize((4, 4), antialias=True), data_keys=["input", "mask"])
+ out_mask = aug(image, mask)[1]
+ assert not set(out_mask.unique().tolist()).issubset({2.0, 3.0})
+
+ def test_convention_boxes_follow_the_xyxy_plus_convention(self, device, dtype):
+ # Convention pin: the container's box arithmetic is `Boxes`' inclusive `xyxy_plus` mode, for a scaling
+ # 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
+ # [[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)
+ aug = K.AugmentationSequential(K.Resize((3, 4)), data_keys=["input", "bbox_xyxy"])
+ out_boxes = aug(torch.rand(2, 3, 6, 8, device=device, dtype=dtype), boxes.clone())[1]
+ matrix = aug.transform_matrix
+ inclusive = Boxes.from_tensor(boxes.clone(), mode="xyxy_plus")
+ inclusive.transform_boxes_(matrix)
+ self.assert_close(out_boxes, inclusive.to_tensor(mode="xyxy_plus"))
+ exclusive = Boxes.from_tensor(boxes.clone(), mode="xyxy")
+ exclusive.transform_boxes_(matrix)
+ assert not torch.allclose(out_boxes, exclusive.to_tensor(mode="xyxy"))
+
+ def test_convention_inverse_restores_keypoints_and_loses_rotated_box_corners(self, device, dtype):
+ # 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)
+ kpts = torch.tensor([[[1.0, 2.0]], [[3.0, 4.0]]], device=device, dtype=dtype)
+ out_img, out_kpts = aug(img, kpts)
+ assert (out_kpts - kpts).abs().max().item() > 1.0 # the forward really moved them
+ restored = aug.inverse(out_img, out_kpts)[1]
+ self.assert_close(restored, kpts)
+ boxes_by_key = {
+ "bbox_xyxy": torch.tensor([[[1.0, 2.0, 4.0, 5.0]]], device=device, dtype=dtype),
+ "bbox": torch.tensor([[[[1.0, 2.0], [4.0, 2.0], [4.0, 5.0], [1.0, 5.0]]]], device=device, dtype=dtype),
+ }
+ for key, boxes in boxes_by_key.items():
+ box_aug = K.AugmentationSequential(K.RandomAffine(degrees=(45.0, 45.0), p=1.0), data_keys=["input", key])
+ out_img, out_boxes = box_aug(torch.rand(1, 3, 8, 8, device=device, dtype=dtype), boxes)
+ restored_boxes = box_aug.inverse(out_img, out_boxes)[1]
+ assert torch.isfinite(restored_boxes).all()
+ if key == "bbox":
+ restored_corners = restored_boxes[0, 0]
+ original_corners = boxes[0, 0]
+ else:
+ restored_corners = Boxes.from_tensor(restored_boxes, mode="xyxy_plus").to_tensor(mode="vertices_plus")[
+ 0, 0
+ ]
+ original_corners = Boxes.from_tensor(boxes, mode="xyxy_plus").to_tensor(mode="vertices_plus")[0, 0]
+ assert (restored_corners.min(dim=0).values < original_corners.min(dim=0).values - 1).all()
+ assert (restored_corners.max(dim=0).values > original_corners.max(dim=0).values + 1).all()
+
+ def test_wart_nested_container_matrix_is_order_sensitive_4476(self, device, dtype):
+ # Wart pin (#4476): nesting itself, not a non-rigid child, breaks outer matrix accumulation. A rigid
+ # child followed by a nested rigid sequence raises, while the reverse ordering silently drops the
+ # nested transform. A directly-called nested container can also inject stale state.
+ image = torch.rand(1, 3, 8, 8, device=device, dtype=dtype)
+ nested_rigid = lambda: K.AugmentationSequential( # noqa: E731
+ K.RandomVerticalFlip(p=1.0), data_keys=["input"]
+ )
+ 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'"):
+ _ = rigid_then_nested.transform_matrix
+
+ nested_then_rigid = K.AugmentationSequential(nested_rigid(), K.RandomHorizontalFlip(p=1.0), data_keys=["input"])
+ assert nested_then_rigid(image).shape == image.shape
+ self.assert_close(
+ nested_then_rigid.transform_matrix,
+ torch.tensor([[[-1.0, 0.0, 7.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype),
+ )
+
+ stale_child = K.AugmentationSequential(K.RandomVerticalFlip(p=1.0), data_keys=["input"])
+ stale_child(image)
+ stale_outer = K.AugmentationSequential(stale_child, data_keys=["input"])
+ shorter = image[:, :, :6]
+ stale_outer(shorter)
+ stale = torch.tensor([[[1.0, 0.0, 0.0], [0.0, -1.0, 7.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ self.assert_close(stale_outer.transform_matrix, stale)
+ assert stale_outer.transform_matrix[0, 1, 2].item() != shorter.shape[-2] - 1
+
+ @pytest.mark.parametrize("crop_cls", [K.CenterCrop, K.RandomCrop, K.RandomResizedCrop])
+ def test_convention_slice_crop_inverse_raises(self, crop_cls, device, dtype):
+ seq = K.AugmentationSequential(crop_cls((4, 6), p=1.0), data_keys=["input"])
+ out = seq(torch.rand(1, 3, 6, 8, device=device, dtype=dtype))
+ with pytest.raises(NotImplementedError, match="resample cropping mode"):
+ seq.inverse(out)
+
+ def test_convention_3d_inverse_raises_for_geometry_and_skips_intensity(self, device, dtype):
+ # Enough voxels in two populated histogram bins force an actual equalization in every dtype.
+ image = torch.full((1, 1, 8, 8, 8), 0.2, device=device, dtype=dtype)
+ image[:, :, :4] = 0.7
+ intensity = K.AugmentationSequential(K.RandomEqualize3D(p=1.0), data_keys=["input"])
+ output = intensity(image)
+ assert not torch.equal(output, image)
+ self.assert_close(intensity.inverse(output), output, atol=0, rtol=0)
+ geometric = K.AugmentationSequential(K.RandomHorizontalFlip3D(p=1.0), data_keys=["input"])
+ with pytest.raises(NotImplementedError, match="3d inverse"):
+ geometric.inverse(geometric(image))
+
+ def test_wart_integer_masks_round_through_image_dtype_4478(self, device, dtype):
+ first_inexact = {torch.bfloat16: 257, torch.float16: 2049, torch.float32: 2**24 + 1, torch.float64: 2**53 + 1}
+ label = first_inexact[dtype]
+ image = torch.ones(1, 1, 2, 2, device=device, dtype=dtype)
+ mask = torch.full_like(image, label, dtype=torch.int64)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ output = seq(image, mask)[1]
+ assert output.dtype == torch.int64
+ assert torch.equal(output, torch.full_like(mask, label - 1))
+
+ def test_wart_empty_batch_with_mask_raises_4478(self, device, dtype):
+ image = torch.empty(0, 1, 2, 2, device=device, dtype=dtype)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ with pytest.raises(IndexError):
+ seq(image, image.clone())
+
+ def test_wart_dictionary_pops_metadata_and_matches_raw_prefixes_4483(self, device, dtype):
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)
+ keys, metadata = seq._read_datakeys_from_dict(("imagenet_id", "maskrcnn_boxes", "labelled_image", "note"))
+ assert keys == [DataKey.INPUT, DataKey.MASK, DataKey.LABEL]
+ assert metadata == ["note"]
+ data = {"image": torch.ones(1, 1, 2, 2, device=device, dtype=dtype), "note": "retained in output"}
+ output = seq(data)
+ assert "note" not in data
+ assert output["note"] == "retained in output"
+
+ def test_convention_same_on_batch_none_does_not_override_a_child(self, device, dtype):
+ # 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:
+ # 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).
+ def angles(container_flag, child_flag):
+ torch.manual_seed(0)
+ child = K.RandomAffine(degrees=(10.0, 90.0), p=1.0, same_on_batch=child_flag)
+ seq = K.AugmentationSequential(child, data_keys=["input"], same_on_batch=container_flag)
+ seq(torch.rand(4, 3, 6, 8, device=device, dtype=dtype))
+ return child._params["angle"].unique().numel()
+
+ assert angles(None, True) == 1
+ assert angles(False, True) == 4
+ assert angles(True, False) == 1
+ assert angles(None, False) == 4
+
+ def shape(container_flag, child_flag):
+ seq = K.AugmentationSequential(
+ K.RandomHorizontalFlip(p=1.0, keepdim=child_flag), data_keys=["input"], keepdim=container_flag
+ )
+ return tuple(seq(torch.rand(3, 6, 8, device=device, dtype=dtype)).shape)
+
+ assert shape(None, True) == (3, 6, 8)
+ assert shape(False, True) == (1, 3, 6, 8)
+ assert shape(True, False) == (3, 6, 8)
+
+ def test_wart_extra_args_mask_resample_override_is_discarded_4419(self, device, dtype):
+ # Wart pin (#4419): `extra_args[DataKey.MASK]` is documented as the way to control how masks are
+ # handled, but on every class whose mask path is `RigidAffineAugmentationBase2D.apply_transform_mask`
+ # the `resample` half is overwritten with NEAREST after the override was merged, so asking for
+ # bilinear changes nothing. The `align_corners` half of the same dict IS honoured and reaches the
+ # sampler, and `RandomElasticTransform`, which has its own mask path, honours both halves.
+ # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu), seed 0, a
+ # (1, 1, 6, 8) mask with a 1-block: RandomAffine resample override max|delta| 0.0, RandomPerspective
+ # align_corners override 1.0.
+ # 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.
+ # The fix lands in the repair window and flips the first assertion; do not "correct" it here.
+
+ def mask_of(aug_factory, extra):
+ torch.manual_seed(0)
+ aug = K.AugmentationSequential(aug_factory(), data_keys=["input", "mask"], extra_args=extra)
+ img = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)
+ mask = torch.zeros(1, 1, 6, 8, device=device, dtype=dtype)
+ mask[:, :, 1:4, 2:6] = 1.0
+ return aug(img, mask)[1]
+
+ bilinear = {DataKey.MASK: {"resample": Resample.BILINEAR, "align_corners": None}}
+ align = {DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": True}}
+
+ affine = lambda: K.RandomAffine(degrees=(45.0, 45.0), p=1.0) # noqa: E731
+ assert (mask_of(affine, bilinear) - mask_of(affine, None)).abs().max().item() == 0.0
+
+ perspective = lambda: K.RandomPerspective(0.5, p=1.0) # noqa: E731
+ assert (mask_of(perspective, align) - mask_of(perspective, None)).abs().max().item() == 1.0
+
+ def elastic_mask_of(extra):
+ torch.manual_seed(0)
+ aug = K.AugmentationSequential(
+ K.RandomElasticTransform(alpha=(5.0, 5.0), sigma=(4.0, 4.0), p=1.0),
+ data_keys=["input", "mask"],
+ extra_args=extra,
+ )
+ img = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)
+ yy, xx = torch.meshgrid(torch.arange(6, device=device), torch.arange(8, device=device), indexing="ij")
+ mask = ((yy + xx) % 2).to(dtype).expand(1, 1, 6, 8).clone()
+ return aug(img, mask)[1]
+
+ assert (elastic_mask_of(bilinear) - elastic_mask_of(None)).abs().max().item() > 0.1
+
+ # a user dict replaces the container's default wholesale rather than merging into it
+ default_args = K.AugmentationSequential(affine(), data_keys=["input", "mask"]).extra_args
+ assert default_args == {DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}}
+ replaced = K.AugmentationSequential(
+ affine(), data_keys=["input", "mask"], extra_args={DataKey.MASK: {"align_corners": True}}
+ ).extra_args
+ assert replaced == {DataKey.MASK: {"align_corners": True}}
+
+ @pytest.mark.xfail(strict=True, raises=AssertionError, reason="Tracked in #4419")
+ def test_convention_extra_args_mask_resample_override_is_honoured(self, device, dtype):
+ # Strict xfail (#4419): the intended reading is the one `AugmentationSequential`'s own docstring
+ # states - `extra_args[DataKey.MASK]` controls how masks are handled, so asking for a bilinear
+ # `resample` must reach the sampler and change the mask, exactly as it already does on
+ # `RandomElasticTransform`. Today the 2D geometric mask path overwrites `resample` with NEAREST after
+ # merging the override, so this XFAILs; it turns XPASS when the repair lands, which is the signal to
+ # delete the wart pin above. The affine override currently has no effect.
+ def mask_of(factory, extra):
+ torch.manual_seed(0)
+ aug = K.AugmentationSequential(factory(), data_keys=["input", "mask"], extra_args=extra)
+ img = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)
+ mask = torch.zeros(1, 1, 6, 8, device=device, dtype=dtype)
+ mask[:, :, 1:4, 2:6] = 1.0
+ return aug(img, mask)[1]
+
+ bilinear = {DataKey.MASK: {"resample": Resample.BILINEAR, "align_corners": None}}
+ affine = lambda: K.RandomAffine(degrees=(45.0, 45.0), p=1.0) # noqa: E731
+ assert (mask_of(affine, bilinear) - mask_of(affine, None)).abs().max().item() > 0.0
+
+ def test_wart_non_rigid_augmentation_desynchronizes_the_data_keys_4420(self, device, dtype):
+ # Wart pin (#4420): the container promises that one call applies the same sampled transform to every
+ # registered data type, but a non-rigid augmentation has no transform matrix, so the coordinate keys
+ # pass through untouched instead of raising: `RandomElasticTransform` warps the image *and* the mask
+ # - it carries its own mask path, which resamples the mask through the very same displacement field,
+ # nearest - while the keypoints and the boxes stay exactly where they were, and
+ # `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)),
+ data_keys=["input", "keypoints", "mask", "bbox_xyxy"],
+ )
+ img = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ kpts = torch.tensor([[[1.0, 2.0]], [[3.0, 4.0]]], device=device, dtype=dtype)
+ yy, xx = torch.meshgrid(torch.arange(6, device=device), torch.arange(8, device=device), indexing="ij")
+ mask = ((yy + xx) % 2).to(dtype).expand(2, 1, 6, 8).clone()
+ boxes = torch.tensor([[[0.0, 0.0, 3.0, 2.0]], [[2.0, 1.0, 5.0, 4.0]]], device=device, dtype=dtype)
+ out_img, out_kpts, out_mask, out_boxes = aug(img, kpts, mask, boxes)
+ assert (out_img - img).abs().max().item() > 0.1 # the image really moved
+ assert (out_mask != mask).sum().item() > 0 # and so did the mask, through the same displacement field
+ self.assert_close(out_kpts, kpts) # the wart: the coordinate keys did not follow
+ self.assert_close(out_boxes, boxes)
+ for factory in (
+ lambda: K.RandomThinPlateSpline(p=1.0),
+ lambda: K.RandomFisheye(
+ torch.tensor([-0.3, 0.3], device=device, dtype=dtype),
+ torch.tensor([-0.3, 0.3], device=device, dtype=dtype),
+ torch.tensor([0.9, 1.0], device=device, dtype=dtype),
+ p=1.0,
+ ),
+ ):
+ with pytest.raises(NotImplementedError):
+ K.AugmentationSequential(factory(), data_keys=["input", "mask"])(img, mask)
diff --git a/tests/augmentation/container/test_patch_sequential.py b/tests/augmentation/container/test_patch_sequential.py
index 81a133858..db7376b4b 100644
--- a/tests/augmentation/container/test_patch_sequential.py
+++ b/tests/augmentation/container/test_patch_sequential.py
@@ -435,3 +435,54 @@ class TestPatchSequentialRegression(BaseTester):
seq(x)
params = seq._params
self.gradcheck(lambda value: seq(value, params=params), (x.requires_grad_(),))
+
+
[email protected]("restore_torch_rng")
+class TestConventionPatchSequential(BaseTester):
+ """Convention pins for `PatchSequential` after the #4421 repair (#4460)."""
+
+ def test_convention_random_patch_assignment_allows_fewer_modules_than_patches(self, device, dtype):
+ with pytest.raises(ValueError, match="number of processing modules must be equal with grid size"):
+ K.PatchSequential(K.RandomHorizontalFlip(p=1.0), grid_size=(2, 2), patchwise_apply=True, random_apply=False)
+ seq = K.PatchSequential(
+ K.RandomHorizontalFlip(p=1.0), grid_size=(2, 2), patchwise_apply=True, random_apply=True
+ )
+ image = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4)
+ assert seq(image).shape == image.shape
+
+ @staticmethod
+ def _patch_states(device, dtype, grid, height, width):
+ # Per-patch verdict: was this patch horizontally flipped, left untouched, or neither.
+ torch.manual_seed(0)
+ seq = K.PatchSequential(K.RandomHorizontalFlip(p=1.0), grid_size=grid, patchwise_apply=False)
+ x = torch.rand(2, 3, height, width, device=device, dtype=dtype)
+ out = seq(x)
+ patch_h, patch_w = height // grid[0], width // grid[1]
+ states = []
+ for b in range(2):
+ for row in range(grid[0]):
+ for col in range(grid[1]):
+ rows = slice(row * patch_h, (row + 1) * patch_h)
+ cols = slice(col * patch_w, (col + 1) * patch_w)
+ patch_in, patch_out = x[b, :, rows, cols], out[b, :, rows, cols]
+ if torch.equal(patch_out, patch_in.flip(-1)):
+ states.append("flip")
+ elif torch.equal(patch_out, patch_in):
+ states.append("same")
+ else:
+ states.append("other")
+ return states
+
+ def test_convention_patch_sequential_augments_every_patch_row(self, device, dtype):
+ # Convention pin: the grid splits the image into B x n_patches patch rows and the chain is applied to
+ # all of them, for any channel count. Before #4460 the draw was sized B x C, so on a non-square 8x12
+ # image with a (2, 3) grid only the first 6 of the 12 patches were augmented (#4421).
+ assert self._patch_states(device, dtype, (2, 3), 8, 12) == ["flip"] * 12
+ assert self._patch_states(device, dtype, (2, 2), 8, 8) == ["flip"] * 8
+
+ def test_convention_default_patch_mode_augments_each_sample(self, device, dtype):
+ # Convention pin: the default (patchwise_apply=True, random_apply=False) processes every sample.
+ # Before #4460 the single module flipped sample zero and left sample one unchanged (#4421).
+ seq = K.PatchSequential(K.RandomHorizontalFlip(p=1.0), grid_size=(1, 1))
+ image = torch.arange(128, device=device, dtype=dtype).reshape(2, 1, 8, 8)
+ self.assert_close(seq(image), image.flip(-1))
diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.py
index 2e34d3efe..dd8ba77d7 100644
--- a/tests/augmentation/container/test_sequential_aug.py
+++ b/tests/augmentation/container/test_sequential_aug.py
@@ -20,8 +20,10 @@ import torch
import kornia
import kornia.augmentation as K
+from kornia.core._compat import torch_version_lt
from testing.augmentation.utils import reproducibility_test
+from testing.base import BaseTester
class TestSequential:
@@ -68,3 +70,84 @@ class TestSequential:
assert out.shape == inp.shape
aug.inverse(inp)
reproducibility_test(inp, aug)
+
+
[email protected]("restore_torch_rng")
+class TestConventionImageSequential(BaseTester):
+ """Batch-6 convention pins for `ImageSequential`.
+
+ Literals generated by the body of each pin, executed on this worktree on 2026-09-11 with
+ `.venv/bin/python` (torch 2.14.0, python 3.11, cpu, float32).
+ """
+
+ def test_wart_if_unsupported_ops_is_neither_honoured_nor_validated_4423(self, device, dtype):
+ # Wart pin (#4423): `ImageSequential.if_unsupported_ops` ("raise" by default) never fires. A plain
+ # `nn.Module` in the chain is silently skipped on the inverse path under every value of the flag -
+ # including an invalid one, which is accepted without validation - so `inverse` undoes only the
+ # invertible ops and returns something that is not the input, with no warning.
+ # The deterministic checkerboard ensures the omitted blur visibly changes the output: for every
+ # if_unsupported_ops value in ("raise", "skip", "bogus"), inverse equals hflip(output) exactly
+ # (only the flip was undone) and differs from the input.
+ # The fix lands in the repair window; do not "correct" this pin here.
+ if device.type == "mps" and torch_version_lt(2, 6, 0):
+ pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")
+ yy, xx = torch.meshgrid(torch.arange(6, device=device), torch.arange(8, device=device), indexing="ij")
+ x = ((yy + xx) % 2).to(dtype).expand(2, 3, 6, 8)
+ assert K.ImageSequential(K.RandomHorizontalFlip(p=1.0)).if_unsupported_ops == "raise"
+ for mode in ("raise", "skip", "bogus"):
+ seq = K.ImageSequential(
+ K.RandomHorizontalFlip(p=1.0),
+ kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5)),
+ if_unsupported_ops=mode,
+ )
+ out = seq(x)
+ inverted = seq.inverse(out)
+ self.assert_close(inverted, out.flip(-1)) # only the flip was undone, the blur was skipped
+ assert (inverted - x).abs().max().item() > 0.1 # and the round trip is not the input
+
+ def test_convention_slice_crop_inverse_raises(self, device, dtype):
+ seq = K.ImageSequential(K.CenterCrop((4, 6), p=1.0))
+ out = seq(torch.rand(1, 3, 6, 8, device=device, dtype=dtype))
+ with pytest.raises(NotImplementedError, match="resample cropping mode"):
+ seq.inverse(out)
+
+ def test_convention_get_transformation_matrix_recomputes_older_params(self, device, dtype):
+ # Module matrices hold only the most recent call. Supplying recorded parameters from an earlier call
+ # therefore requires recompute=True.
+ image = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)
+ seq = K.ImageSequential(K.RandomHorizontalFlip(p=0.5), K.RandomVerticalFlip(p=0.5))
+ torch.manual_seed(1)
+ seq(image)
+ old_params = seq._params
+ torch.manual_seed(101)
+ seq(image)
+ current = seq.get_transformation_matrix(image, old_params)
+ recomputed = seq.get_transformation_matrix(image, old_params, recompute=True)
+ assert current is not None and recomputed is not None
+ assert not torch.equal(current, recomputed)
+
+ @pytest.mark.xfail(strict=True, raises=pytest.fail.Exception, reason="Tracked in #4423")
+ def test_convention_if_unsupported_ops_raise_raises_not_implemented(self, device, dtype):
+ # Strict xfail (#4423): the intended reading is the argument's own contract - `if_unsupported_ops`
+ # defaults to "raise", so inverting a chain that holds a non-invertible plain `nn.Module` must raise
+ # `NotImplementedError` rather than silently skip it. This turns XPASS when the repair lands, which
+ # is the signal to delete the wart pin above. Executed 2026-09-11 (torch 2.14.0, cpu): inverse returns
+ # quietly.
+ if device.type == "mps" and torch_version_lt(2, 6, 0):
+ pytest.skip("torch 2.5.1 MPS inverse of expanded matrices can abort the process")
+ x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ seq = K.ImageSequential(
+ K.RandomHorizontalFlip(p=1.0),
+ kornia.filters.GaussianBlur2d((3, 3), (1.5, 1.5)),
+ if_unsupported_ops="raise",
+ )
+ out = seq(x)
+ with pytest.raises(NotImplementedError):
+ seq.inverse(out)
+
+ @pytest.mark.xfail(strict=True, raises=pytest.fail.Exception, reason="Tracked in #4423")
+ def test_convention_if_unsupported_ops_rejects_invalid_value(self):
+ # Strict xfail (#4423): construction accepts only "raise" and "skip". Executed 2026-09-11 (torch
+ # 2.14.0, cpu): "bogus" is accepted without validation.
+ with pytest.raises(ValueError):
+ K.ImageSequential(K.RandomHorizontalFlip(p=1.0), if_unsupported_ops="bogus")
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index 3e46bebce..930a43675 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -15,11 +15,16 @@
# limitations under the License.
#
-from unittest.mock import patch
+import copy
+import pickle
+import re
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
import pytest
import torch
+import kornia.augmentation as K
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.augmentation._2d.geometric.affine import RandomAffine
from kornia.augmentation._2d.geometric.horizontal_flip import RandomHorizontalFlip
@@ -30,9 +35,13 @@ from kornia.augmentation._3d.geometric.affine import RandomAffine3D
from kornia.augmentation._3d.geometric.horizontal_flip import RandomHorizontalFlip3D
from kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3D
from kornia.augmentation.base import _BasicAugmentationBase
+from kornia.core import ImageModule
from kornia.core._compat import torch_version_lt
+from kornia.filters.dissolving import StableDiffusionDissolving, _DissolvingWraper_HF
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_bilinear_2d_grid_sample_backward, supports_reflect_padding
class TestBasicAugmentationBase(BaseTester):
@@ -337,3 +346,679 @@ class TestDeviceAgnosticAugmentationParameters(BaseTester):
expected = torch.stack([input[0] * 0.75 + input[1] * 0.25, input[1]])
assert output.device == input.device
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
+# either seeded inside the test or made deterministic with `p=1.0` plus a point range such as
+# `degrees=(45.0, 45.0)`.
+
+# Representative constructible augmentations for the statelessness pin. Some other augmentations keep their
+# sampling range in a `_param_generator.*` buffer; see `test_wart_param_generator_range_buffers_are_inert_4428`.
+_STATELESS_REPRESENTATIVES = {
+ "RandomHorizontalFlip": lambda: K.RandomHorizontalFlip(p=1.0),
+ "RandomAffine": lambda: K.RandomAffine(degrees=(45.0, 45.0), p=1.0),
+ "ColorJiggle": lambda: K.ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0),
+ "Normalize": lambda: K.Normalize(0.5, 0.5, p=1.0),
+ "AugmentationSequential": lambda: K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0)),
+}
+
+
+def _assert_params_equal(actual, expected) -> None:
+ if isinstance(expected, torch.Tensor):
+ assert isinstance(actual, torch.Tensor)
+ assert torch.equal(actual, expected)
+ elif isinstance(expected, dict):
+ assert isinstance(actual, dict)
+ assert actual.keys() == expected.keys()
+ for key in expected:
+ _assert_params_equal(actual[key], expected[key])
+ elif isinstance(expected, (list, tuple)):
+ assert isinstance(actual, type(expected))
+ assert len(actual) == len(expected)
+ for actual_value, expected_value in zip(actual, expected):
+ _assert_params_equal(actual_value, expected_value)
+ else:
+ assert actual == expected
+
+
+# name -> (constructor, batch shape, reference CPU RNG operations).
+# Compare states against operations on the installed PyTorch rather than version-specific float literals.
+# This pins consumption, not the actual random values or the assignment of values to parameter keys.
+_RNG_FINGERPRINTS = {
+ "RandomHorizontalFlip(p=1.0)": (lambda: K.RandomHorizontalFlip(p=1.0), (4, 3, 6, 8), []),
+ "RandomHorizontalFlip(p=0.0)": (lambda: K.RandomHorizontalFlip(p=0.0), (4, 3, 6, 8), []),
+ "RandomHorizontalFlip(p=0.5)": (lambda: K.RandomHorizontalFlip(p=0.5), (4, 3, 6, 8), [("rand", (4,))]),
+ "CenterCrop": (lambda: K.CenterCrop((4, 6)), (4, 3, 6, 8), []),
+ "Resize": (lambda: K.Resize((8, 12)), (4, 3, 6, 8), []),
+ # The affine draws a gate, angle and two translations. Point ranges still consume random values.
+ "RandomAffine": (
+ lambda: K.RandomAffine(degrees=(30.0, 30.0), translate=(0.1, 0.1)),
+ (4, 3, 6, 8),
+ [("rand", (4,))] * 4,
+ ),
+ "RandomRotation": (lambda: K.RandomRotation(degrees=(30.0, 30.0)), (4, 3, 6, 8), [("rand", (4,))] * 2),
+ "RandomCrop": (lambda: K.RandomCrop((4, 6)), (4, 3, 6, 8), [("rand", (4,))] * 2),
+ "RandomPerspective": (lambda: K.RandomPerspective(0.5), (4, 3, 6, 8), [("rand", (4,)), ("rand", (4, 4, 2))]),
+ "RandomElasticTransform": (K.RandomElasticTransform, (4, 3, 6, 8), [("rand", (4,)), ("rand", (4, 2, 6, 8))]),
+ "ColorJiggle": (
+ lambda: K.ColorJiggle(0.2, 0.2, 0.2, 0.1),
+ (4, 3, 6, 8),
+ [("rand", (4,))] * 4 + [("randperm", (4,))],
+ ),
+ "RandomGaussianNoise": (
+ lambda: K.RandomGaussianNoise(std=0.1),
+ (4, 3, 6, 8),
+ [("rand", (4,)), ("randn", (4, 3, 6, 8))],
+ ),
+ "AugmentationSequential": (
+ lambda: K.AugmentationSequential(K.RandomAffine(degrees=(10.0, 90.0), p=1.0)),
+ (4, 3, 6, 8),
+ [("rand", (4,))],
+ ),
+ "ImageSequential": (
+ lambda: K.ImageSequential(K.RandomAffine(degrees=(10.0, 90.0), p=1.0)),
+ (4, 3, 6, 8),
+ [("rand", (4,))],
+ ),
+ "VideoSequential": (
+ lambda: K.VideoSequential(K.RandomAffine(degrees=(10.0, 90.0), p=1.0)),
+ (4, 2, 3, 6, 8),
+ [("rand", (4,))],
+ ),
+ "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).
+ [("rand", (16,))],
+ ),
+}
+
+
[email protected]("restore_torch_rng")
+class TestConventionAugmentationBase2D(BaseTester):
+ """Pins for the contract every 2D augmentation inherits from ``AugmentationBase2D``."""
+
+ def test_convention_unbatched_input_is_promoted_unless_keepdim(self, device, dtype):
+ # 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)
+ assert K.RandomHorizontalFlip(p=1.0)(torch.rand(6, 8, device=device, dtype=dtype)).shape == (1, 1, 6, 8)
+ batched = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ assert K.RandomHorizontalFlip(p=1.0, keepdim=True)(batched).shape == (2, 3, 6, 8)
+ one_batched = torch.rand(1, 3, 6, 8, device=device, dtype=dtype)
+ assert K.RandomHorizontalFlip(p=1.0, keepdim=True)(one_batched).shape == (1, 3, 6, 8)
+
+ 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):
+ K.RandomHorizontalFlip(p=1.0)(torch.zeros(1, 1, 4, 4, device=device, dtype=bad))
+
+ def test_wart_wrong_input_rank_has_entry_point_specific_errors_4424(self, device, dtype):
+ # Wart pin (#4424): one user error can raise different exception types depending on which entry point
+ # sees it. The class path raises `ValueError` from `transform_tensor`, the container path raises
+ # `RuntimeError` with a different message, and `validate_tensor`'s own
+ # `RuntimeError` (which also rejects the legal (C, H, W) rank). `forward` promotes legal unbatched
+ # inputs before validation.
+ # 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)
+ with pytest.raises(RuntimeError, match=r"input shape expected to be in \(2, 4\)"):
+ K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input"])(x5)
+ with pytest.raises(RuntimeError, match=r"Expect \(B, C, H, W\)"):
+ K.RandomHorizontalFlip(p=1.0).validate_tensor(x5)
+ with pytest.raises(RuntimeError, match=r"Expect \(B, C, H, W\)"):
+ # a rank `forward` accepts, rejected by the validator behind it
+ K.RandomHorizontalFlip(p=1.0).validate_tensor(torch.rand(3, 6, 8, device=device, dtype=dtype))
+
+ 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()
+ assert all(v.device.type == "cpu" for v in aug._params.values())
+ assert aug.transform_matrix.dtype == dtype
+ assert out.dtype == dtype
+
+ def test_convention_p_is_per_sample_and_p_batch_gates_the_whole_batch(self):
+ # 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
+ assert flip(p=1.0, p_batch=1.0).forward_parameters((4, 3, 6, 8))["batch_prob"].tolist() == [1.0] * 4
+ batch_rows = []
+ for seed in range(8):
+ torch.manual_seed(seed)
+ batch_rows.append(flip(p=1.0, p_batch=0.5).forward_parameters((4, 3, 6, 8))["batch_prob"].tolist())
+ assert all(len(set(row)) == 1 for row in batch_rows)
+ assert {row[0] for row in batch_rows} == {0.0, 1.0}
+ # `p=0.5` is per sample: mixed rows exist.
+ sample_rows = []
+ for seed in range(4):
+ torch.manual_seed(seed)
+ sample_rows.append(flip(p=0.5).forward_parameters((4, 3, 6, 8))["batch_prob"].tolist())
+ assert any(len(set(row)) > 1 for row in sample_rows)
+
+ def test_convention_p_batch_draw_precedes_the_per_sample_gate(self):
+ torch.manual_seed(3)
+ actual = K.RandomHorizontalFlip(p=0.5, p_batch=0.5).forward_parameters((4, 3, 6, 8))["batch_prob"]
+ actual_state = torch.random.get_rng_state()
+ torch.manual_seed(3)
+ batch_gate = torch.rand(1) < 0.5
+ per_sample_gate = torch.rand(4) < 0.5
+ expected = (batch_gate * per_sample_gate).to(actual.dtype)
+ assert torch.equal(actual, expected)
+ assert torch.equal(actual_state, torch.random.get_rng_state())
+
+ @pytest.mark.parametrize("augmentation_cls", [K.RandomJigsaw, K.RandomMosaic])
+ def test_convention_jigsaw_and_mosaic_use_p_per_sample(self, augmentation_cls):
+ rows = []
+ for seed in range(4):
+ torch.manual_seed(seed)
+ rows.append(augmentation_cls(p=0.5).forward_parameters((4, 3, 6, 8))["batch_prob"].tolist())
+ assert any(len(set(row)) > 1 for row in rows)
+
+ @pytest.mark.parametrize("augmentation_cls", [K.RandomMixUpV2, K.RandomCutMixV2, K.PatchMix])
+ def test_wart_mixup_cutmix_and_patchmix_map_p_to_a_batch_gate_4425(self, augmentation_cls):
+ # Their constructors map `p` to the mix base's batch-wide probability, unlike Jigsaw and Mosaic.
+ rows = []
+ for seed in range(8):
+ torch.manual_seed(seed)
+ kwargs = {"use_correct_lambda": True} if augmentation_cls is K.RandomCutMixV2 else {}
+ params = augmentation_cls(p=0.5, **kwargs).forward_parameters((4, 3, 6, 8))
+ rows.append(params["batch_prob"].tolist())
+ assert all(len(set(row)) == 1 for row in rows)
+ assert {row[0] for row in rows} == {0.0, 1.0}
+
+ @pytest.mark.parametrize(
+ "augmentation_cls", [K.RandomMixUpV2, K.RandomCutMixV2, K.PatchMix, K.RandomJigsaw, K.RandomMosaic]
+ )
+ def test_convention_mix_replay_requires_batch_prob(self, augmentation_cls):
+ kwargs = {"use_correct_lambda": True} if augmentation_cls is K.RandomCutMixV2 else {}
+ with pytest.raises(KeyError, match="batch_prob"):
+ augmentation_cls(p=1.0, **kwargs)(torch.ones(2, 3, 6, 8), params={})
+
+ @pytest.mark.parametrize(
+ ("augmentation_cls", "shape"),
+ [
+ (K.RandomTransplantation, (4, 3, 6, 8)),
+ (K.RandomTransplantation3D, (4, 3, 6, 8, 10)),
+ ],
+ )
+ def test_convention_transplantation_p_batch_gate(self, augmentation_cls, shape):
+ # Both public transplantation classes expose the base's p_batch gate. A zero gate skips the entire
+ # batch even though p would otherwise apply every sample; one applies every sample.
+ for p_batch, expected in ((0.0, 0.0), (1.0, 1.0)):
+ augmentation = augmentation_cls(p=1.0, p_batch=p_batch)
+ assert augmentation.forward_parameters(shape)["batch_prob"].tolist() == [expected] * shape[0]
+
+ @pytest.mark.parametrize(
+ ("augmentation_cls", "spatial_shape"),
+ [
+ (K.RandomTransplantation, (6, 8)),
+ (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.
+ 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"])
+ 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)
+ rows.append(K.RandomHorizontalFlip(p=0.5, same_on_batch=True).forward_parameters((4, 3, 6, 8)))
+ assert [r["batch_prob"].tolist() for r in rows] == [[1.0] * 4, [0.0] * 4, [0.0] * 4, [1.0] * 4]
+ torch.manual_seed(0)
+ angles = K.RandomAffine(degrees=(10.0, 90.0), same_on_batch=True).forward_parameters((4, 3, 6, 8))["angle"]
+ assert angles.unique().numel() == 1
+ torch.manual_seed(0)
+ angles = K.RandomAffine(degrees=(10.0, 90.0), same_on_batch=False).forward_parameters((4, 3, 6, 8))["angle"]
+ assert angles.unique().numel() == 4
+
+ @pytest.mark.parametrize("augmentation_cls", [K.ColorJiggle, K.ColorJitter])
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ def test_convention_color_adjustment_order_is_shared_across_the_batch(self, augmentation_cls, same_on_batch):
+ # The color adjustments have one random permutation per call, independently of same_on_batch. The
+ # individual factors do honor same_on_batch.
+ params = augmentation_cls(0.2, 0.2, 0.2, 0.1, same_on_batch=same_on_batch).forward_parameters((3, 3, 6, 8))
+ order = params["order"]
+ assert order.shape == (4,)
+ assert torch.equal(order.sort().values, torch.arange(4, device=order.device, dtype=order.dtype))
+ if same_on_batch:
+ for name in ("brightness_factor", "contrast_factor", "saturation_factor", "hue_factor"):
+ assert params[name].unique().numel() == 1
+ else:
+ for name in ("brightness_factor", "contrast_factor", "saturation_factor", "hue_factor"):
+ assert params[name].unique().numel() > 1
+
+ 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)
+ second = K.RandomAffine(degrees=45.0, translate=(0.2, 0.2)).forward_parameters((2, 1, 8, 8))
+ assert set(first) == set(second)
+ assert all(torch.equal(first[k], second[k]) for k in first)
+
+ def test_wart_generator_is_rejected_at_construction_and_swallowed_by_forward_4427(self, device, dtype):
+ # Wart pin (#4427): there is no per-instance RNG. `generator=` raises `TypeError` on a class and on a
+ # 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'"):
+ K.RandomAffine(degrees=45.0, generator=torch.Generator())
+ with pytest.raises(TypeError, match="unexpected keyword argument 'generator'"):
+ K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), generator=torch.Generator())
+ x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ gen = torch.Generator()
+ gen.manual_seed(2718)
+ torch.manual_seed(0)
+ with_generator = K.RandomAffine(degrees=(10.0, 90.0), p=1.0)(x, generator=gen)
+ torch.manual_seed(0)
+ without = K.RandomAffine(degrees=(10.0, 90.0), p=1.0)(x)
+ assert torch.equal(with_generator, without)
+ # any other unknown keyword is swallowed just as silently
+ assert K.RandomAffine(degrees=(10.0, 90.0), p=1.0)(x, nonsense=1).shape == (2, 3, 6, 8)
+
+ 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)
+ params = dict(aug._params)
+ before = {k: v.clone() for k, v in params.items()}
+ second = aug(x, params=params)
+ assert torch.equal(first, second)
+ assert aug._params is params
+ assert set(aug._params) == set(before)
+ assert all(torch.equal(before[k], params[k]) for k in before)
+
+ def test_convention_params_without_batch_prob_are_extended_in_place(self, device, dtype):
+ aug = K.RandomHorizontalFlip(p=0.0)
+ image = torch.arange(16, device=device, dtype=dtype).reshape(1, 1, 4, 4)
+ params = {}
+ output = aug(image, params=params)
+ assert aug._params is params
+ assert set(params) == {"batch_prob"}
+ assert params["batch_prob"].tolist() == [True]
+ self.assert_close(output, image.flip(-1))
+
+ def test_convention_rigid_base_requires_data_key_handlers(self, device, dtype):
+ class Identity(K.RigidAffineAugmentationBase2D):
+ def compute_transformation(self, input, params, flags):
+ return self.identity_matrix(input)
+
+ def apply_transform(self, input, params, flags, transform=None):
+ return input
+
+ aug = Identity(p=1.0)
+ image = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
+ self.assert_close(aug(image), image)
+ boxes = Boxes.from_tensor(torch.tensor([[[0.0, 0.0, 2.0, 2.0]]], device=device, dtype=dtype), mode="xyxy")
+ keypoints = Keypoints(torch.tensor([[[1.0, 1.0]]], device=device, dtype=dtype))
+ for handler, data in (
+ (aug.transform_masks, image),
+ (aug.transform_boxes, boxes),
+ (aug.transform_keypoints, keypoints),
+ ):
+ with pytest.raises(NotImplementedError):
+ handler(data, aug._params, aug.flags, transform=aug.transform_matrix)
+
+ def test_convention_direct_geometric_mask_handler_rejects_bool(self, device, dtype):
+ # The container casts bool masks around geometric dispatch. Calling the geometric handler directly
+ # instead takes the image dtype guard, so float masks work while bool masks raise TypeError.
+ augmentation = K.RandomHorizontalFlip(p=1.0)
+ image = torch.ones(2, 1, 3, 4, device=device, dtype=dtype)
+ augmentation(image)
+ float_mask = torch.tensor(
+ [[[[0.0, 1.0, 2.0, 3.0], [4.0, 5.0, 6.0, 7.0], [8.0, 9.0, 10.0, 11.0]]]],
+ device=device,
+ dtype=dtype,
+ ).repeat(2, 1, 1, 1)
+ transformed = augmentation.transform_masks(
+ float_mask, augmentation._params, augmentation.flags, transform=augmentation.transform_matrix
+ )
+ self.assert_close(transformed, float_mask.flip(-1))
+ with pytest.raises(TypeError, match="Expected input of"):
+ augmentation.transform_masks(
+ float_mask.bool(), augmentation._params, augmentation.flags, transform=augmentation.transform_matrix
+ )
+
+ def test_wart_intensity_container_boxes_passthrough_but_direct_dispatch_raises_4480(self, device, dtype):
+ image = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
+ boxes = Boxes.from_tensor(torch.tensor([[[0.0, 0.0, 2.0, 2.0]]], device=device, dtype=dtype), mode="xyxy")
+ augmentation = K.RandomInvert(p=1.0)
+ augmentation(image)
+ with pytest.raises(NotImplementedError):
+ augmentation.transform_boxes(boxes, augmentation._params, augmentation.flags)
+ container = K.AugmentationSequential(K.RandomInvert(p=1.0), data_keys=["input", "bbox_xyxy"])
+ _, output_boxes = container(image, boxes)
+ self.assert_close(output_boxes.data, boxes.data)
+
+ def test_wart_container_skips_custom_rigid_box_handlers_4481(self, device, dtype):
+ class ShiftBoxes(K.RigidAffineAugmentationBase2D):
+ def compute_transformation(self, input, params, flags):
+ return self.identity_matrix(input)
+
+ def apply_transform(self, input, params, flags, transform=None):
+ return input
+
+ def apply_transform_box(self, input, params, flags, transform=None):
+ return Boxes(input.data + 1, mode=input.mode)
+
+ image = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
+ boxes = Boxes.from_tensor(torch.tensor([[[0.0, 0.0, 2.0, 2.0]]], device=device, dtype=dtype), mode="xyxy")
+ augmentation = ShiftBoxes(p=1.0)
+ direct = augmentation.transform_boxes(boxes, augmentation.forward_parameters(image.shape), augmentation.flags)
+ self.assert_close(direct.data, boxes.data + 1)
+ _, output_boxes = K.AugmentationSequential(augmentation, data_keys=["input", "bbox_xyxy"])(image, boxes)
+ self.assert_close(output_boxes.data, boxes.data)
+
+ def test_convention_random_erasing_also_erases_container_masks(self, device, dtype):
+ image = torch.ones(1, 1, 6, 8, device=device, dtype=dtype)
+ mask = torch.ones_like(image)
+ augmentation = K.AugmentationSequential(
+ K.RandomErasing(scale=(0.5, 0.5), ratio=(1.0, 1.0), value=0.0, p=1.0), data_keys=["input", "mask"]
+ )
+ _, output_mask = augmentation(image, mask)
+ assert torch.count_nonzero(output_mask) < output_mask.numel()
+
+ @pytest.mark.parametrize("plasma_cls", [K.RandomPlasmaBrightness, K.RandomPlasmaContrast, K.RandomPlasmaShadow])
+ def test_convention_random_plasma_replay_is_bitwise(self, plasma_cls, device, dtype):
+ # Convention pin: since #4462 (fixing #4445) the three `RandomPlasma*` classes draw their fractal noise
+ # in `generate_parameters` and store it under `params["plasma"]`, so a `params=` replay is bitwise
+ # without reseeding, while a fresh forward under a different seed draws different noise.
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ aug = plasma_cls(p=1.0)
+ x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ torch.manual_seed(0)
+ first = aug(x)
+ params = aug._params
+ assert "plasma" in params
+ torch.manual_seed(5)
+ assert torch.equal(aug(x, params=params), first)
+ torch.manual_seed(5)
+ assert not torch.equal(aug(x), first)
+
+ def test_convention_random_dissolving_replay_needs_the_latent_rng(self, device, dtype):
+ # Exercise the real augmentation/filter/encoder path with a lightweight VAE distribution.
+ # No diffusion checkpoint is downloaded; only prompt setup and denoising are bypassed.
+ image = torch.ones(1, 3, 4, 4, device=device, dtype=dtype)
+ latent_dist = Mock()
+ latent_dist.sample.side_effect = lambda: torch.rand_like(image)
+ model = SimpleNamespace(
+ device=device,
+ vae=SimpleNamespace(
+ dtype=dtype,
+ encode=Mock(return_value={"latent_dist": latent_dist}),
+ decode=lambda latent: {"sample": latent},
+ ),
+ tokenizer=None,
+ scheduler=SimpleNamespace(set_timesteps=Mock(), timesteps=[0]),
+ )
+ wrapper = _DissolvingWraper_HF(model)
+ with patch.object(StableDiffusionDissolving, "__init__", lambda self, *a, **kw: ImageModule.__init__(self)):
+ aug = K.RandomDissolving(step_range=(1.0, 1.0), p=1.0)
+ aug._dslv.model = wrapper
+ with (
+ patch.object(wrapper, "init_prompt"),
+ patch.object(wrapper, "one_step_dissolve", side_effect=lambda latent, step: latent),
+ ):
+ torch.manual_seed(0)
+ first = aug(image)
+ params = {key: value.clone() for key, value in aug._params.items()}
+ second = aug(image, params=params)
+ assert not torch.equal(first, second)
+ assert set(params) == {"step_range_factor", "batch_prob", "forward_input_shape"}
+ torch.manual_seed(5)
+ replay = aug(image, params=params)
+ torch.manual_seed(5)
+ self.assert_close(aug(image, params=params), replay, rtol=0, atol=0)
+ assert latent_dist.sample.call_count == 4
+
+ @pytest.mark.parametrize("name", list(_STATELESS_REPRESENTATIVES))
+ def test_convention_augmentations_are_stateless_modules(self, name):
+ # These numeric-range configurations have no parameters, buffers or state_dict entries.
+ # 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()) == []
+ assert list(aug.parameters()) == []
+ aug(torch.rand(2, 3, 6, 8))
+ for clone in (pickle.loads(pickle.dumps(aug)), copy.deepcopy(aug)): # noqa: S301
+ assert isinstance(clone, type(aug))
+ _assert_params_equal(clone._params, aug._params)
+
+ def test_convention_parameter_valued_ranges_receive_gradients(self, device, dtype):
+ if not supports_bilinear_2d_grid_sample_backward(device, dtype):
+ pytest.skip("grid_sample backward is unavailable for this device/dtype")
+ degrees = torch.nn.Parameter(torch.tensor([10.0, 20.0], device=device, dtype=dtype))
+ aug = K.RandomRotation(degrees, p=1.0)
+ assert dict(aug.named_parameters()) == {"_param_generator.degrees": degrees}
+ self.assert_close(aug.state_dict()["_param_generator.degrees"], degrees)
+ image = torch.arange(64, device=device, dtype=dtype).reshape(1, 1, 8, 8) / 64
+ torch.manual_seed(0)
+ aug(image).sum().backward()
+ assert degrees.grad is not None
+ assert torch.isfinite(degrees.grad).all()
+ assert torch.count_nonzero(degrees.grad) == 2
+
+ def test_wart_param_generator_range_buffers_are_inert_4428(self):
+ # Wart pin (#4428): classes that keep their sampling range in a `_param_generator.*` buffer
+ # 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"
+ ]
+ source = K.RandomRotation(degrees=(10.0, 11.0))
+ target = K.RandomRotation(degrees=(80.0, 81.0))
+ assert target.state_dict()["_param_generator.degrees"].tolist() == [80.0, 81.0]
+ target.load_state_dict(source.state_dict())
+ assert target.state_dict()["_param_generator.degrees"].tolist() == [10.0, 11.0]
+ torch.manual_seed(0)
+ drawn = target.forward_parameters((4, 3, 6, 8))["degrees"]
+ 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):
+ original_dtype = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(torch.float32)
+ for aug, key, sampler in (
+ (K.RandomAffine(degrees=(10.0, 90.0), p=1.0), "angle", "degree_sampler"),
+ (K.RandomRotation(degrees=(10.0, 90.0), p=1.0), "degrees", None),
+ ):
+
+ def distribution(aug=aug, key=key, sampler=sampler):
+ generator = aug._param_generator
+ return getattr(generator, sampler) if sampler else generator.sampler_dict[key]
+
+ assert distribution().low.dtype == torch.float32
+ torch.set_default_dtype(torch.float64)
+ assert aug.forward_parameters((2, 3, 6, 8))[key].dtype == torch.float64
+ assert distribution().low.dtype == torch.float32
+ aug.set_rng_device_and_dtype(torch.device("cpu"), torch.float64)
+ assert distribution().low.dtype == torch.float64
+ torch.set_default_dtype(torch.float32)
+ params = aug.forward_parameters((2, 3, 6, 8))
+ assert params[key].dtype == torch.float32
+ assert params["batch_prob"].dtype == torch.float64
+ finally:
+ torch.set_default_dtype(original_dtype)
+
+ def test_convention_set_rng_device_moves_sampling_before_casting_parameters_4426(self, device):
+ 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
+ if device.type == "cuda":
+
+ def get_device_state():
+ return torch.cuda.get_rng_state(device)
+
+ elif device.type == "mps":
+ get_device_state = torch.mps.get_rng_state
+ elif device.type == "cpu":
+ get_device_state = torch.random.get_rng_state
+ else:
+ pytest.skip("RNG state assertions cover CPU, CUDA and MPS")
+ cpu_before = torch.random.get_rng_state()
+ device_before = get_device_state()
+ params = aug.forward_parameters((2, 3, 6, 8))
+ assert not torch.equal(device_before, get_device_state())
+ if device.type != "cpu":
+ assert torch.equal(cpu_before, torch.random.get_rng_state())
+ assert params["batch_prob"].device == device
+ assert params["angle"].device.type == "cpu"
+
+ def test_convention_tensor_ranges_determine_returned_parameter_placement(self, device, dtype):
+ degrees = torch.tensor([10.0, 20.0], device=device, dtype=dtype)
+ for aug, key in ((K.RandomAffine(degrees, p=1.0), "angle"), (K.RandomRotation(degrees, p=1.0), "degrees")):
+ aug.set_rng_device_and_dtype(torch.device("cpu"), torch.float32)
+ drawn = aug.forward_parameters((2, 3, 6, 8))[key]
+ assert drawn.device == degrees.device
+ assert drawn.dtype == degrees.dtype
+
+ def test_convention_rng_consumption_fingerprint(self):
+ # Pin CPU float32 consumption relative to this PyTorch build's generator, not its numeric sequence.
+ original_dtype = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(torch.float32)
+ for name, (make, shape, operations) in _RNG_FINGERPRINTS.items():
+ torch.manual_seed(0)
+ make().forward_parameters(shape)
+ actual_state = torch.random.get_rng_state()
+ torch.manual_seed(0)
+ for operation, draw_shape in operations:
+ kwargs = {"device": "cpu"}
+ if operation != "randperm":
+ kwargs["dtype"] = torch.float32
+ getattr(torch, operation)(*draw_shape, **kwargs)
+ assert torch.equal(actual_state, torch.random.get_rng_state()), name
+ finally:
+ torch.set_default_dtype(original_dtype)
+
+ 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)
+ assert K.RandomHorizontalFlip(p=1.0)(empty).shape == (0, 3, 6, 8)
+ assert K.RandomAffine(degrees=(45.0, 45.0), p=1.0)(empty).shape == (0, 3, 6, 8)
+ assert K.ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0)(empty).shape == (0, 3, 6, 8)
+ container = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input"])
+ assert container(empty).shape == (0, 3, 6, 8)
+
+ @pytest.mark.parametrize(
+ "name,error,message",
+ [
+ ("RandomCrop", IndexError, "list index out of range"),
+ ("LongestMaxSize", KeyError, "output_size"),
+ ("RandomAutoContrast", ValueError, "Invalid input tensor, it is empty."),
+ ("Normalize", RuntimeError, "cannot reshape tensor of 0 elements"),
+ ],
+ )
+ def test_wart_zero_batch_raises_in_four_exception_families_4429(self, name, error, message, device, dtype):
+ # 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 others expose implementation details.
+ # Snippet used to generate expected: this body, executed 2026-09-11 (torch 2.14.0, cpu):
+ # RandomCrop IndexError('list index out of range'), LongestMaxSize KeyError('output_size'),
+ # RandomAutoContrast ValueError('Invalid input tensor, it is empty.'),
+ # Normalize RuntimeError('cannot reshape tensor of 0 elements into shape [0, 3, -1] ...').
+ builders = {
+ "RandomCrop": lambda: K.RandomCrop((4, 6), p=1.0),
+ "LongestMaxSize": lambda: K.LongestMaxSize(16, p=1.0),
+ "RandomAutoContrast": lambda: K.RandomAutoContrast(p=1.0),
+ "Normalize": lambda: K.Normalize(0.5, 0.5, p=1.0),
+ }
+ with pytest.raises(error, match=re.escape(message)):
+ builders[name]()(torch.rand(0, 3, 6, 8, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize(
+ ("augmentation", "shape"),
+ [
+ pytest.param(
+ lambda: K.RandomCrop((4, 6), p=1.0),
+ (0, 3, 4, 6),
+ marks=pytest.mark.xfail(strict=True, raises=IndexError, reason="Tracked in #4429"),
+ ),
+ pytest.param(
+ lambda: K.LongestMaxSize(16, p=1.0),
+ (0, 3, 12, 16),
+ marks=pytest.mark.xfail(strict=True, raises=KeyError, reason="Tracked in #4429"),
+ ),
+ pytest.param(
+ lambda: K.RandomAutoContrast(p=1.0),
+ (0, 3, 6, 8),
+ marks=pytest.mark.xfail(strict=True, raises=ValueError, reason="Tracked in #4429"),
+ ),
+ pytest.param(
+ lambda: K.Normalize(0.5, 0.5, p=1.0),
+ (0, 3, 6, 8),
+ marks=pytest.mark.xfail(strict=True, raises=RuntimeError, reason="Tracked in #4429"),
+ ),
+ ],
+ )
+ def test_convention_zero_batch_is_empty_in_empty_out(self, augmentation, shape, device, dtype):
+ # Strict xfail (#4429): each listed augmentation must preserve an empty batch with its intended
+ # output geometry. Per-class markers turn an unrelated repair into a failure rather than an XFAIL.
+ empty = torch.rand(0, 3, 6, 8, device=device, dtype=dtype)
+ assert augmentation()(empty).shape == shape