Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(augmentation): Convention blocks (batch 6c: 2D intensity) (#4566)

Dmytro Mishkin30dfbf7110bc
diff --git a/changelog.d/4566.added.md b/changelog.d/4566.added.md
new file mode 100644
index 000000000..e83dc3c88
--- /dev/null
+++ b/changelog.d/4566.added.md
@@ -0,0 +1 @@
+Document per-class value-range, parameter-meaning, filter, noise, weather, illumination and normalization conventions for the 2D intensity augmentations, with executable tests for current behavior and issue-linked pins for the known limitations. Rewrite the stale sampler-migration citations in the 2D augmentation bases.
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rst
index 0dcb2f902..9470a1c8c 100644
--- a/docs/source/augmentation.base.rst
+++ b/docs/source/augmentation.base.rst
@@ -227,9 +227,8 @@ Random Reproducibility
^^^^^^^^^^^^^^^^^^^^^^
Parameter sampling generally starts on CPU, independently of the image device. ``set_rng_device_and_dtype``
requests new sampler placement and precision, but not every internal tensor follows that request, and some
-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
+generator/device combinations can still fail during forward
+(`#4426 <https://github.com/kornia/kornia/issues/4426>`_). Returned parameter placement is separate from
sampling placement: constructor ranges and casts can put a sampled tensor on another device or in another dtype.
See :doc:`/get-started/conventions` for global seeding, worker seeds, consumption order, replay and the limits
diff --git a/docs/source/enhance.adjustment.rst b/docs/source/enhance.adjustment.rst
index 3e422bf81..eb81bc872 100644
--- a/docs/source/enhance.adjustment.rst
+++ b/docs/source/enhance.adjustment.rst
@@ -8,24 +8,32 @@ Functions
.. autofunction:: add_weighted
.. autofunction:: adjust_brightness
+.. autofunction:: adjust_brightness_accumulative
.. autofunction:: adjust_contrast
.. autofunction:: adjust_contrast_with_mean_subtraction
.. autofunction:: adjust_gamma
.. autofunction:: adjust_hue
+.. autofunction:: adjust_hue_raw
.. autofunction:: adjust_saturation
+.. autofunction:: adjust_saturation_raw
+.. autofunction:: adjust_saturation_with_gray_subtraction
.. autofunction:: adjust_sigmoid
.. autofunction:: adjust_log
.. autofunction:: invert
.. autofunction:: posterize
.. autofunction:: sharpness
+.. autofunction:: shift_rgb
.. autofunction:: solarize
Modules
-------
.. autoclass:: AdjustBrightness
+.. autoclass:: AdjustBrightnessAccumulative
.. autoclass:: AdjustContrast
+.. autoclass:: AdjustContrastWithMeanSubtraction
.. autoclass:: AdjustSaturation
+.. autoclass:: AdjustSaturationWithGraySubtraction
.. autoclass:: AdjustHue
.. autoclass:: AdjustGamma
.. autoclass:: AdjustSigmoid
diff --git a/docs/source/filters.kernels.rst b/docs/source/filters.kernels.rst
index 4ab606238..7f040caaf 100644
--- a/docs/source/filters.kernels.rst
+++ b/docs/source/filters.kernels.rst
@@ -5,6 +5,7 @@ Kernels
Kernel generators, useful with the :doc:`filters.filtering_api` or to inspect what a filter applies.
+.. autofunction:: gaussian
.. autofunction:: get_gaussian_kernel1d
.. autofunction:: get_gaussian_erf_kernel1d
.. autofunction:: get_gaussian_discrete_kernel1d
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 6794fa28f..b0f7d2133 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -308,6 +308,36 @@ Augmentations
:func:`kornia.geometry.transform.rotate`, and clockwise with
:class:`kornia.augmentation.RandomAffine`
(`#4408 <https://github.com/kornia/kornia/issues/4408>`_).
+- The 2D intensity augmentations assume the ``[0, 1]`` float range, and no
+ base-class check validates it on the way in. Outside that range, individual
+ classes use their documented policy: some clamp, rescale, or convert through
+ ``uint8``; :class:`kornia.augmentation.RandomPlanckianJitter` clamps only the
+ upper end; some do not clamp; and :class:`kornia.augmentation.RandomEqualize`
+ raises where its value check runs (MPS skips the check; torch ``2.14`` raises a
+ raw indexing error instead, and ``2.5.1`` and ``2.9.1`` return silently). The resulting values also depend on the sampled parameters and image
+ contents. Several return an all-zero image for an all-negative input: on a
+ constant ``-1.0`` image most of them do so on every draw, while nearer zero the
+ sampled parameters decide more often, and
+ :class:`kornia.augmentation.RandomSolarize` does the same when every input value
+ is at least ``1.5``. Values between ``1`` and ``1.5`` can instead produce nonzero
+ output after a negative addition (`#4430 <https://github.com/kornia/kornia/issues/4430>`_).
+ These policies are not an exhaustive classification: a further outcome is
+ NaN, which :class:`kornia.augmentation.RandomGamma` produces for a negative
+ input whenever the drawn ``gamma`` is not an integer (``gamma=(1.5, 1.5)`` on a
+ strictly negative image is NaN in every element, while the integral ``(2.0, 2.0)``
+ is finite).
+ See :class:`kornia.augmentation.IntensityAugmentationBase2D` and each class's
+ own documentation. :class:`kornia.augmentation.RandomDissolving` is unmeasured
+ because constructing it needs the optional ``diffusers`` package and, on a cold
+ cache, downloads a Stable Diffusion checkpoint.
+ :class:`kornia.augmentation.RandomClahe` and
+ :class:`kornia.augmentation.RandomJPEG` are importable and documented but absent
+ from ``kornia.augmentation.__all__``, so they are outside the audited set above;
+ ``RandomClahe`` raises out of range with a raw indexing error
+ (`#4564 <https://github.com/kornia/kornia/issues/4564>`_) and ``RandomJPEG``
+ clamps the decoded RGB output into ``[0, 1]``. The decoding can produce intermediate
+ values even when every input value is negative or every input value is above ``1``;
+ such images need not become solid black or white.
.. code-block:: python
@@ -379,6 +409,9 @@ Randomness in augmentations
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>`_).
+ The gate selects after the transform has been computed for the whole batch,
+ so a skipped sample can still raise or carry a NaN gradient
+ (`#4576 <https://github.com/kornia/kornia/issues/4576>`_).
- 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
@@ -451,6 +484,14 @@ Quick self-review for generated code, most common first:
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.
+18. Feeding mean/std-normalized or otherwise out-of-``[0, 1]`` tensors
+ through an intensity augmentation and expecting the values to pass
+ through β€” some rescale, some clamp, ``RandomEqualize`` and ``RandomClahe``
+ raise, and several return zeros for an all-negative image -- on every draw
+ for a constant ``-1.0`` image, on some draws nearer zero -- while
+ ``RandomSolarize`` returns zeros when every
+ input value is at least ``1.5``. Its output for values between ``1`` and ``1.5``
+ depends on the addition.
.. tip::
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index ee739a1bf..ff3fdbbb0 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -88,11 +88,12 @@ class AugmentationBase2D(_AugmentationBase):
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>`_.
+ see `#4425 <https://github.com/kornia/kornia/issues/4425>`_. The gate selects after the transform
+ has been computed for the whole batch, so a sample it skips can still raise or carry a NaN gradient
+ (`#4576 <https://github.com/kornia/kornia/issues/4576>`_).
- 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>`_.
+ see `#4426 <https://github.com/kornia/kornia/issues/4426>`_.
- reproducibility goes through torch's global generators on the devices used for sampling:
``torch.manual_seed`` before the call reproduces the draw for the same backend and dtype.
There is no per-instance generator; ``generator=`` raises at
@@ -130,8 +131,10 @@ class AugmentationBase2D(_AugmentationBase):
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
+ ``set_rng_device_and_dtype`` has incomplete sampler migration. It rebuilds what it can, but some
+ generators retain internal CPU tensors or ignore the requested precision, some generator/device
+ combinations can still fail during forward, and the returned parameters can stay CPU ``float32``
+ while ``batch_prob`` follows the request. Tracked in
`#4426 <https://github.com/kornia/kornia/issues/4426>`_.
.. warning::
diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.py
index 8ba86b89c..a7c5bc401 100644
--- a/kornia/augmentation/_2d/intensity/auto_contrast.py
+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py
@@ -26,12 +26,14 @@ from kornia.enhance import normalize_min_max
class RandomAutoContrast(IntensityAugmentationBase2D):
r"""Apply a random auto-contrast of a torch.Tensor image.
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
clip_output: has no effect on the output. The transform is
:func:`kornia.enhance.normalize_min_max`, which already maps each sample's channels onto ``[0, 1]``,
so clamping to that interval cannot change a value -- including for inputs outside ``[0, 1]``. Kept
- for signature compatibility.
+ for signature compatibility. Tracked in `#4436 <https://github.com/kornia/kornia/issues/4436>`_.
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).
@@ -39,6 +41,24 @@ class RandomAutoContrast(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the output is exactly :func:`kornia.enhance.normalize_min_max` of the input: each channel of
+ each sample is rescaled from its own minimum and maximum as ``(x - min) / (max - min + 1e-6)``,
+ independently of the other channels and the other samples, with the constant channel noted below as
+ the exception. This is a rescale, not a clamp, so an input outside ``[0, 1]`` is mapped into range
+ rather than clipped. The ``1e-6`` keeps a channel whose range is not large next to it short of ``1``
+ (a range of ``1e-5`` peaks at ``0.909``), and in ``float16`` a channel whose span overflows the
+ dtype loses the whole channel: ``max - min`` saturates to ``inf``, so the maximum comes back NaN
+ (``inf / inf``) and every other element comes back exactly ``0`` (a finite numerator over ``inf``).
+ ``[-60000, 60000, 0, 1]`` in ``float16`` returns ``[0, nan, 0, 0]``.
+
+ .. warning::
+ A non-contiguous input -- anything :meth:`torch.Tensor.view` cannot reshape, such as a
+ ``transpose``d or ``permute``d view -- raises a raw ``RuntimeError: view size is not compatible
+ with input tensor's size and stride`` from :func:`kornia.enhance.normalize_min_max`, naming neither this
+ class nor the fix (``.contiguous()``). Tracked in
+ `#4577 <https://github.com/kornia/kornia/issues/4577>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.normalize_min_max`. A channel with a single value
has zero range and is returned as zeros.
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
index 19b071c3a..3ba92ace0 100644
--- a/kornia/augmentation/_2d/intensity/base.py
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -47,7 +47,76 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
- 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.
+ - these classes assume the library-wide ``[0, 1]`` float image value range, stated under
+ "Image tensors" in :doc:`/get-started/conventions`. No base-class check validates it on the way
+ in, so it is a precondition rather than a validated contract.
+ - outside that range, concrete classes apply their documented policy: some clamp, rescale, or use a
+ ``uint8`` conversion; :class:`RandomPlanckianJitter` clamps only the upper end; others do not
+ clamp; and :class:`RandomEqualize` raises a ``RuntimeError`` where its value check runs (on MPS the
+ check is skipped: torch ``2.14`` raises a raw indexing error instead, and ``2.5.1`` and ``2.9.1``
+ return silently). The resulting values also depend on
+ the sampled parameters and image contents, so these policies are not an exhaustive classification
+ of every out-of-range input. :class:`RandomDissolving` is unmeasured because constructing it needs
+ the optional ``diffusers`` package and, on a cold cache, downloads a Stable Diffusion checkpoint.
+ :class:`RandomClahe` and :class:`RandomJPEG` are not in ``kornia.augmentation.__all__`` and document
+ their own behavior on their own pages.
+ - what this block and the class pages say about an output describes the samples the ``p`` gate
+ transforms; every other sample comes back with its input values. Below ``p=1`` the transform is
+ still computed for every sample and the gate then selects, so a skipped sample that fails a value
+ check still makes the call raise -- :class:`RandomEqualize` and :class:`RandomClahe` raise for an
+ out-of-range image even at ``p=0.0`` -- and a skipped sample's gradient can be NaN where the
+ transform's derivative is infinite (`#4576 <https://github.com/kornia/kornia/issues/4576>`_).
+ - the scalar factors a concrete class draws are per sample -- one value, or one per channel
+ per sample where the class's own docstring says so. Two classes draw per sample and then
+ apply one draw to the whole batch. :class:`RandomMotionBlur` fills ``_params["ksize_factor"]`` with
+ one kernel size per sample and blurs the batch with the one at ``_params["idx"]``, an index drawn
+ uniformly over the batch rather than the first sample's; :class:`RandomClahe` draws ``clip_limit``
+ per sample and applies the first sample's
+ (`#4572 <https://github.com/kornia/kornia/issues/4572>`_); and :class:`RandomDissolving`
+ hard-codes ``same_on_batch=True``. Several classes also draw a whole-image field --
+ ``gaussian_noise``, ``gradient``, ``plasma``, and :class:`RandomSaltAndPepperNoise`'s boolean
+ ``mask_salt`` and ``mask_pepper`` -- whose stored shape normally follows the original batched
+ ``(B, C, H, W)`` input shape. A ``(C, H, W)`` input remains batched in those parameters even when
+ ``keepdim=True``. ``gaussian_noise`` instead stores ``(1, C, H, W)`` with ``same_on_batch=True``,
+ then expands it at application time, while the plasma classes keep one map per sample even then
+ (`#4570 <https://github.com/kornia/kornia/issues/4570>`_); ``RandomPlasmaShadow`` stores
+ ``(B, 1, H, W)``. :class:`ColorJiggle` and :class:`ColorJitter` both draw an application ``order``;
+ it is shared by the whole batch. Only :class:`ColorJitter` takes a fixed ``order`` constructor
+ argument. Without one, on either class, an ``order`` tensor passed as a forward keyword, or
+ replayed ``params``, replaces the drawn order for that call; a fixed order ignores both.
+ - where a class documents bounds for a parameter, an explicit range outside them usually raises at
+ construction. These checks run on the forward pass instead: :class:`RandomGamma`'s non-negativity checks
+ on ``gamma`` and ``gain``, which live in :func:`kornia.enhance.adjust_gamma`;
+ :class:`RandomSolarize`'s ``additions`` at the closed bounds ``-0.5`` and ``0.5``
+ (`#4605 <https://github.com/kornia/kornia/issues/4605>`_), and
+ :class:`RandomGaussianBlur`'s ``sigma`` at ``0`` and even ``kernel_size``, which the constructors
+ admit and :func:`kornia.enhance.solarize` and :func:`kornia.filters.gaussian_blur2d` reject;
+ :class:`RandomMedianBlur`'s even ``kernel_size``, which raises a raw torch error the same way;
+ :class:`RandomRain`'s drop-size bounds; a tuple ``kernel_size`` for :class:`RandomMotionBlur` whose
+ drawn odd size is below ``3`` -- an even bound is rounded up to the next odd size rather than
+ rejected, and that rounding can leave the requested range, so ``(4, 4)`` draws ``5`` and ``(2, 2)``
+ draws ``3``, while ``(0, 2)`` raises because the odd size it rounds to is ``1``. That same
+ truncation means the range's upper bound is practically never drawn -- ``kernel_size=(3, 5)`` is a
+ constant ``3`` (`#4599 <https://github.com/kornia/kornia/issues/4599>`_);
+ and :class:`RandomChannelDropout`'s ``num_drop_channels`` against the input's channel count.
+ :class:`RandomPlanckianJitter`'s ``select_from`` rejects an index past the table at construction
+ but accepts a negative one, as Python indexing does. A scalar magnitude is a different case: several
+ classes fit it to the bound instead of raising, tracked in
+ `#4563 <https://github.com/kornia/kornia/issues/4563>`_.
+
+ .. warning::
+ Several of these classes return an all-zero image for an input whose values are all negative, with no
+ warning. On a constant ``-1.0`` image at the audited constructor arguments, 17 classes collapse, 15
+ of them on every one of five seeds, and only :class:`ColorJiggle` and :class:`RandomPlasmaContrast`
+ depend on the draw; two of the 15 are artefacts of the constant image rather than of its sign
+ (:class:`Denormalize` maps ``-1`` to exactly ``0`` at the audited ``mean=std=0.5``, and
+ :class:`RandomAutoContrast` returns zeros for any constant image). Nearer zero the draw decides more
+ often: on the audit fixture drawn from ``[-1, 0)``, 5 of the 12 collapsing classes do so on every
+ one of 100 seeds and the other 7 on some. At the upper end,
+ :class:`RandomSolarize` returns zeros when every input value is at least ``1.5``, for every
+ admissible addition. Values between ``1`` and ``1.5`` can instead produce nonzero output after
+ a negative addition. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
"""
diff --git a/kornia/augmentation/_2d/intensity/box_blur.py b/kornia/augmentation/_2d/intensity/box_blur.py
index 6aa8bcd8a..aa8edb1dc 100644
--- a/kornia/augmentation/_2d/intensity/box_blur.py
+++ b/kornia/augmentation/_2d/intensity/box_blur.py
@@ -28,6 +28,8 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
.. image:: _static/img/RandomBoxBlur.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
kernel_size: the blurring kernel size.
border_type: the padding mode to be applied before convolving.
@@ -39,6 +41,32 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+
+ Convention:
+ - ``kernel_size`` is ``(kH, kW)``: the first entry counts rows and the second counts columns, as in
+ :func:`kornia.filters.box_blur`. An even entry is accepted and centres the window half a pixel toward
+ the top-left rather than raising -- a ``(2, 2)`` window on an impulse spreads it over the impulse's
+ own row and column and the one before each -- where :class:`RandomGaussianBlur` and
+ :class:`RandomMedianBlur` raise on the forward pass.
+ - ``normalized`` reaches that function as its ``separable`` argument, so it selects the implementation
+ rather than a normalization: both settings are L1-normalized means, they agree to float rounding, and
+ a constant image survives either up to the rounding of the kernel weights. ``border_type`` defaults
+ to ``"reflect"``, as the function does, but ``normalized=True`` does **not** match
+ :func:`kornia.filters.box_blur`'s own ``separable=False``, so the default class output differs from
+ the default function output in the last bits -- about ``1.2e-07`` on a ``[0, 1]`` image. Where
+ :class:`RandomGaussianBlur` passes its function's own defaults through, this one does not.
+ - the output is not clamped. At the default ``border_type="reflect"`` every output value is a weighted
+ average of input values and stays between the input's own extremes, up to the rounding of the kernel
+ weights; ``border_type="constant"`` pads with zeros, which pulls a border pixel toward ``0``: below
+ the input's minimum for a positive image, and above its maximum for a negative one.
+
+ .. warning::
+ At the default ``border_type="reflect"``, an image with a spatial axis no longer than half the kernel's extent
+ along that axis raises a raw torch ``RuntimeError`` about the padding rather than a kornia error naming the
+ class or the shape. ``"constant"`` and ``"replicate"`` run on the same image; ``"circular"`` raises a padding
+ error of its own, also raw, once the kernel radius exceeds that axis. Tracked in `#4559
+ <https://github.com/kornia/kornia/issues/4559>`_.
+
.. note::
This function internally uses :func:`kornia.filters.box_blur`.
diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.py
index bd833c025..0c2e3c6b2 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -32,6 +32,8 @@ class RandomBrightness(IntensityAugmentationBase2D):
.. image:: _static/img/RandomBrightness.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
brightness: the brightness factor to apply
clip_output: if true clip output
@@ -43,6 +45,22 @@ class RandomBrightness(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - ``brightness`` is centred on ``1.0``, and the drawn factor is re-based before it is applied:
+ ``factor - 1`` is what reaches :func:`kornia.enhance.adjust_brightness`, whose own identity is
+ ``0.0``. A class factor of ``1.0`` is therefore the identity for an input in ``[0, 1]`` -- the
+ default clamp below still applies to one outside it -- and the same number passed straight to the
+ primitive means something else.
+ - ``clip_output`` is live. Left at its default ``True`` the result is clamped into ``[0, 1]``;
+ with ``clip_output=False`` the raw sum is returned. It can remain outside that interval or
+ move inside it through the brightness shift.
+
+ .. warning::
+ At the default ``clip_output=True`` an input whose values are all negative comes back as an all-zero
+ image whenever the drawn shift does not lift it above zero. At the class default
+ ``brightness=(1.0, 1.0)`` the shift is ``0``, so it always does. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.adjust_brightness`
diff --git a/kornia/augmentation/_2d/intensity/channel_dropout.py b/kornia/augmentation/_2d/intensity/channel_dropout.py
index e8dc768cc..eb1bf8fb4 100644
--- a/kornia/augmentation/_2d/intensity/channel_dropout.py
+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py
@@ -29,6 +29,8 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
.. image:: _static/img/RandomChannelDropout.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
num_drop_channels: Number of channels to drop randomly. Default is 1.
fill_value: Value to fill the dropped channels with. Default is 0.0.
@@ -41,6 +43,19 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(C, H, W)` or :math:`(B, C, H, W)`
+ Convention:
+ - the channels named by the drawn ``channel_idx`` are overwritten with the literal ``fill_value``,
+ which has to be a ``float`` in ``[0, 1]``: this class's own ``__init__`` rejects anything outside
+ the bounds, and an ``int`` such as ``0`` on type. ``ChannelDropoutGenerator`` never sees
+ ``fill_value`` -- unlike :class:`RandomErasing`, whose ``value`` guard does live in its generator,
+ and which accepts an ``int`` ``value`` (`#4606 <https://github.com/kornia/kornia/issues/4606>`_).
+ Every other channel is left exactly as it came in, so the
+ input's value range is carried through.
+ - the dropped channels are drawn independently per sample; ``same_on_batch=True`` collapses the
+ draw to one set of channels for the whole batch.
+ - ``fill_value`` is held in a non-persistent buffer, so ``.to(...)`` moves and casts it while
+ ``state_dict()`` gains no key for it.
+
.. note::
If `num_drop_channels` is set to 1, it means that for each image in the batch,
we will randomly choose one channel to drop.
diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.py
index f6409f91b..82f4720df 100644
--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py
+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py
@@ -28,12 +28,21 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
.. image:: _static/img/RandomChannelShuffle.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
same_on_batch: apply the same transformation across the batch.
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
+ Convention:
+ - the drawn ``channels`` index the source, not the destination: output channel ``c`` of sample
+ ``b`` is input channel ``channels[b][c]``.
+ - the permutation is drawn independently per sample; ``same_on_batch=True`` shares one
+ permutation across the batch.
+ - values are only reordered, never recomputed, so the input's value range is carried through.
+
Examples:
>>> rng = torch.manual_seed(0)
>>> img = torch.arange(1*2*2*2.).view(1,2,2,2)
diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.py
index 69efe2c78..8e4f422b6 100644
--- a/kornia/augmentation/_2d/intensity/clahe.py
+++ b/kornia/augmentation/_2d/intensity/clahe.py
@@ -31,14 +31,54 @@ class RandomClahe(IntensityAugmentationBase2D):
.. image:: _static/img/equalize_clahe.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`. This class raises
+ instead of transforming an out-of-range input, and its error is a raw one.
+
Args:
- clip_limit: threshold value for contrast limiting. If 0 clipping is disabled.
+ clip_limit: the ``(low, high)`` range the per-sample contrast-limiting threshold is drawn from.
+ Unlike :func:`kornia.enhance.equalize_clahe`'s scalar argument of the same name this must be a
+ two-element tuple -- a scalar raises ``ValueError: `center` and `bounds` cannot be None for
+ single number`` at construction -- and ``(0.0, 0.0)`` is what disables clipping. The bound is
+ unvalidated below zero: ``(-1.0, -1.0)`` is accepted and behaves exactly like ``(0.0, 0.0)``.
grid_size: number of tiles to be cropped in each direction (GH, GW).
- slow_and_differentiable: flag to select implementation
+ slow_and_differentiable: selects the implementation. At the default ``False`` the fast path breaks the
+ autograd graph -- the output has ``requires_grad=False`` and no ``grad_fn``, which no other 2D
+ intensity augmentation does -- so set it to ``True`` to keep the class differentiable.
same_on_batch: apply the same transformation across the batch.
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+
+ .. warning::
+ An input outside ``[0, 1]`` reaches :func:`kornia.enhance.equalize_clahe` unchecked and comes
+ back as a raw torch indexing error that names neither this class nor the range it needs. As for
+ :class:`RandomEqualize`, the rejection is not exactly at the boundary: the failing index is the
+ 256-entry lookup indexed with ``(input * 255).long()``, so a value less than one 8-bit code outside
+ ``[0, 1]``, at either end, is still admitted, up to the rounding of ``input * 255`` in the input's
+ dtype. Tracked in
+ `#4564 <https://github.com/kornia/kornia/issues/4564>`_. Unlike :class:`RandomEqualize`, CLAHE has
+ no value check on any device, so the raw error is what every caller gets on the CPU. On MPS the
+ outcome depends on torch: ``2.14`` raises the raw ``gather`` error
+ (`#4600 <https://github.com/kornia/kornia/issues/4600>`_), while ``2.5.1`` leaves the gather
+ unchecked and returns an in-range image as if the input had been valid.
+
+ .. warning::
+ ``clip_limit`` is drawn per sample, but the first sample's value is applied to the whole batch.
+ Tracked in `#4572 <https://github.com/kornia/kornia/issues/4572>`_.
+
+ .. warning::
+ ``grid_size`` is unvalidated past its positivity check in the same way the value range is, and only a
+ **square** grid works. Any ``grid_size`` whose two entries differ raises a raw ``IndexError``
+ (``shape mismatch: indexing tensors could not be broadcast together``) on every image, whether or not
+ the grid tiles it: ``(4, 5)`` fails on a ``20 x 20`` image that both entries divide exactly, and so
+ does ``(1, 2)`` on a ``10 x 10`` one. Reported in
+ `#2531 <https://github.com/kornia/kornia/issues/2531>`_. Divisibility is a separate axis: a square
+ grid that does not tile the image is padded instead, so ``grid_size=(3, 3)`` works on a ``10 x 10``
+ image, and because :func:`kornia.enhance.equalize_clahe` rounds the tile up to an even size an
+ exactly dividing grid can still pad. An image too small for the grid raises a raw ``RuntimeError``
+ from the padding -- at the default ``grid_size=(8, 8)`` the smallest admissible square image is
+ ``9 x 9``, and ``8 x 8`` raises. A grid larger than the image gets the named ``ValueError`` instead.
+
.. note::
This function internally uses :func:`kornia.enhance.equalize_clahe`.
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index 816b3221b..134b39287 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -30,6 +30,8 @@ class ColorJiggle(IntensityAugmentationBase2D):
.. image:: _static/img/ColorJiggle.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
brightness: The brightness factor to apply.
@@ -43,6 +45,50 @@ class ColorJiggle(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - this class and :class:`ColorJitter` draw the same factor values and the same random application
+ ``order`` from the same seed when their effective sampling bounds match and both modules stay on
+ the CPU. A scalar ``brightness > 1`` does not match: this class draws from ``[0, 2]`` while
+ :class:`ColorJitter` draws from ``[0, 1 + brightness]``. Off the CPU the ``order`` diverges,
+ because this class draws it on the sampler device where :class:`ColorJitter` always draws it on
+ the CPU; and this class returns its factors in the dtype of its constructor arguments
+ (``float32`` for Python floats) where :class:`ColorJitter` keeps the sampler dtype. Only
+ :class:`ColorJitter` takes an ``order`` constructor argument that replaces its sampled order with a
+ fixed one. The classes use different primitives for three adjustments:
+ :func:`kornia.enhance.adjust_brightness` against
+ :func:`kornia.enhance.adjust_brightness_accumulative`,
+ :func:`kornia.enhance.adjust_contrast` against
+ :func:`kornia.enhance.adjust_contrast_with_mean_subtraction`, and
+ :func:`kornia.enhance.adjust_saturation` against
+ :func:`kornia.enhance.adjust_saturation_with_gray_subtraction`. Both call
+ :func:`kornia.enhance.adjust_hue`.
+ - the brightness factor is re-based as :class:`RandomBrightness` re-bases it:
+ ``factor - 1`` is what reaches :func:`kornia.enhance.adjust_brightness`.
+ - ``ColorJiggle(0, 0, 0, 0)`` is the identity, including for values outside ``[0, 1]``. A hue-only
+ configuration can also return values outside that interval.
+ - a step whose drawn factor is neutral is skipped rather than computed and discarded, where
+ :class:`ColorJitter` evaluates every step under a ``torch.where``. So the channel count only has to
+ suit the steps that actually run: the saturation and hue steps need three channels, but
+ ``ColorJiggle(0, 0, 0, 0)`` and a brightness- or contrast-only configuration accept any channel
+ count, including the ``C = 1`` and ``C = 4`` on which :class:`ColorJitter` raises.
+ - the ``[0, 2]`` bound is not only a clamp on a scalar: an explicit ``brightness`` range reaching
+ above ``2``, such as ``(0.0, 3.0)``, is rejected at construction with
+ ``brightness out of bounds. Expected inside (0, 2)``, where :class:`ColorJitter` accepts it.
+
+ .. warning::
+ The brightness and contrast primitives clip into ``[0, 1]`` by default, so an input whose values are
+ all negative can come back as an all-zero image, depending on the drawn factors and on which steps
+ run: a contrast-only configuration collapses it for every draw, a brightness-only one or a
+ four-factor one such as ``(0.2, 0.2, 0.2, 0.1)`` for some draws, and a hue-only one never (the
+ all-zero default is the identity). Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
+ .. warning::
+ In ``float16`` a black pixel reaching the saturation or hue step comes back as NaN, because both
+ steps go through ``rgb_to_hsv``, whose ``eps`` underflows there. The hue step does the same for any
+ pixel whose largest channel is ``0``. Tracked in
+ `#4560 <https://github.com/kornia/kornia/issues/4560>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.adjust_brightness`,
:func:`kornia.enhance.adjust_contrast`. :func:`kornia.enhance.adjust_saturation`,
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index 91fe20be5..8b8c50cf1 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -40,6 +40,8 @@ class ColorJitter(IntensityAugmentationBase2D):
.. image:: _static/img/ColorJitter.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
brightness: The brightness factor to apply.
contrast: The contrast factor to apply.
@@ -57,6 +59,47 @@ class ColorJitter(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - this class and :class:`ColorJiggle` draw the same factor values and the same random application
+ ``order`` from the same seed when their effective sampling bounds match and both modules stay on
+ the CPU. A scalar ``brightness > 1`` does not match: :class:`ColorJiggle` draws from ``[0, 2]``
+ while this class draws from ``[0, 1 + brightness]``. Off the CPU the ``order`` diverges, because
+ this class always draws it on the CPU where :class:`ColorJiggle` draws it on the sampler device;
+ and this class keeps the sampler dtype for its factors where :class:`ColorJiggle` returns them in
+ the dtype of its constructor arguments (``float32`` for Python floats). Only this class takes an
+ ``order`` constructor argument that replaces the sampled order with a fixed one. The classes use different
+ primitives for three adjustments:
+ :func:`kornia.enhance.adjust_brightness_accumulative` against
+ :func:`kornia.enhance.adjust_brightness`,
+ :func:`kornia.enhance.adjust_contrast_with_mean_subtraction` against
+ :func:`kornia.enhance.adjust_contrast`, and
+ :func:`kornia.enhance.adjust_saturation_with_gray_subtraction` against
+ :func:`kornia.enhance.adjust_saturation`. Both call :func:`kornia.enhance.adjust_hue`.
+ - the brightness factor is not re-based here: it reaches
+ :func:`kornia.enhance.adjust_brightness_accumulative` as drawn, where :class:`ColorJiggle` and
+ :class:`RandomBrightness` subtract ``1`` first.
+ - with the random ``order``, ``ColorJitter(0, 0, 0, 0)`` is the identity only for a three-channel input in
+ ``[0, 1]``. Every step in the order is computed even when its result is then discarded, so the hue step
+ rejects any channel count but three and the saturation step any but one or three, and the brightness step
+ is applied whenever any drawn brightness factor is not ``0`` -- for every scalar ``brightness``, including
+ the default ``0.0``, which draws ``1``. Its primitive clamps into ``[0, 1]``, as the contrast primitive
+ does and the saturation primitive does for a three-channel image (a one-channel image passes through it
+ unchanged), although there is no final output clamp. The explicit tuple ``brightness=(0.0, 0.0)``, or a
+ fixed ``order`` without index ``0``, skips the brightness step; with the other factors at their defaults,
+ either lets an out-of-range value through.
+
+ .. warning::
+ An input whose values are all negative can come back as an all-zero image: the brightness and contrast steps,
+ and the saturation step on a three-channel image, each clamp into ``[0, 1]``, and a scalar ``brightness``, the
+ default included, runs the brightness step unless a fixed ``order`` leaves it out. The collapse depends on the
+ draw: a contrast or saturation factor above ``1`` applied before the brightness step can lift part of the image
+ above zero first. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
+ .. warning::
+ In ``float16`` a pixel whose largest channel is ``0`` -- for an input in ``[0, 1]``, a black pixel --
+ comes back as NaN when it reaches the hue step, because ``rgb_to_hsv``'s ``eps`` underflows there. Tracked in
+ `#4560 <https://github.com/kornia/kornia/issues/4560>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.adjust_brightness_accumulative`,
:func:`kornia.enhance.adjust_contrast_with_mean_subtraction`,
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index 6020f33a2..a99168ad6 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -32,6 +32,8 @@ class RandomContrast(IntensityAugmentationBase2D):
.. image:: _static/img/RandomContrast.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
contrast: the contrast factor to apply.
clip_output: if true clip output.
@@ -43,6 +45,19 @@ class RandomContrast(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the drawn factor reaches :func:`kornia.enhance.adjust_contrast` unchanged -- it is not re-based
+ the way :class:`RandomBrightness` re-bases its own -- and ``1.0`` is the identity for an input in
+ ``[0, 1]``; the default clamp below still applies to one outside it.
+ - ``clip_output`` is live. Left at its default ``True`` the result is clamped into ``[0, 1]``;
+ with ``clip_output=False`` the raw product is returned. Multiplying an out-of-range input can
+ leave it outside that interval or bring it inside.
+
+ .. warning::
+ At the default ``clip_output=True`` an input whose values are all negative comes back as an all-zero
+ image; with ``clip_output=False`` negative products are not clipped. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.adjust_contrast`
diff --git a/kornia/augmentation/_2d/intensity/denormalize.py b/kornia/augmentation/_2d/intensity/denormalize.py
index ffc03d3a0..3bbc66e3c 100644
--- a/kornia/augmentation/_2d/intensity/denormalize.py
+++ b/kornia/augmentation/_2d/intensity/denormalize.py
@@ -27,6 +27,8 @@ from kornia.enhance import denormalize
class Denormalize(IntensityAugmentationBase2D):
r"""Denormalize tensor images with mean and standard deviation.
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
.. math::
\text{input[channel] = (input[channel] * std[channel]) + mean[channel]}
@@ -35,7 +37,6 @@ class Denormalize(IntensityAugmentationBase2D):
Args:
mean: Mean for each channel.
std: Standard deviations for each channel.
- same_on_batch: apply the same transformation across the batch.
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
@@ -43,6 +44,21 @@ class Denormalize(IntensityAugmentationBase2D):
Return:
Denormalised tensor with same size as input :math:`(*, C, H, W)`.
+ Convention:
+ - ``mean`` and ``std`` accept a float, a per-channel sequence or tensor, or a per-sample ``(B, C)``
+ tensor; a length that is neither ``1`` nor the channel count raises.
+ - ``p`` gates the whole batch rather than each sample: the constructor hard-codes
+ ``same_on_batch=True``, which collapses the per-sample draw to a single one, and it takes no
+ ``same_on_batch`` argument of its own -- the ``Args`` entry that claimed one was part of
+ `#4496 <https://github.com/kornia/kornia/issues/4496>`_ and is removed here.
+ - the statistics live in ``flags`` rather than in a buffer, so ``state_dict()`` is empty and
+ ``Module.to(...)`` leaves their device and dtype alone.
+ - this class inverts :class:`Normalize` built with the same float, sequence or tensor ``mean`` and
+ ``std``, up to float rounding, when both apply -- each draws its own ``p`` gate. An ``int``
+ statistic, which :class:`Normalize` accepts, raises here on the forward pass
+ (`#4573 <https://github.com/kornia/kornia/issues/4573>`_).
+ - the result is not clamped: it is ``input * std + mean`` whatever range the input is in.
+
.. note::
This function internally uses :func:`kornia.enhance.denormalize`.
diff --git a/kornia/augmentation/_2d/intensity/dissolving.py b/kornia/augmentation/_2d/intensity/dissolving.py
index 67104b7fd..bdb6fc5fc 100644
--- a/kornia/augmentation/_2d/intensity/dissolving.py
+++ b/kornia/augmentation/_2d/intensity/dissolving.py
@@ -27,9 +27,18 @@ from kornia.filters import StableDiffusionDissolving
class RandomDissolving(IntensityAugmentationBase2D):
r"""Perform dissolving transformation using StableDiffusion models.
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Based on :cite:`shi2024dissolving`, the dissolving transformation is essentially applying one-step
- reverse diffusion. Our implementation currently supports HuggingFace implementations of SD 1.4, 1.5
- and 2.1. SD 1.X tends to remove more details than SD2.1.
+ reverse diffusion. Our implementation currently supports the HuggingFace implementations of SD 1.4, SD 1.5
+ and SD XL; once ``diffusers`` is importable, any other ``version`` raises a bare ``NotImplementedError``
+ (without it, construction fails on the optional-dependency prompt before the version is looked at).
+
+ .. note::
+ The table below does not render: its cells are missing the ``..`` directive marker, so Sphinx
+ prints ``figure:: https://...`` as text, and the ``SD xl`` column still points at the SD 2.1
+ image because ``dslv-sd-xl.png`` is a 404 in the ``kornia/data`` repository. Tracked in
+ `#4601 <https://github.com/kornia/kornia/issues/4601>`_.
.. list-table:: Title
:widths: 32 32 32
@@ -44,7 +53,7 @@ class RandomDissolving(IntensityAugmentationBase2D):
Args:
p: probability of applying the transformation.
- version: the version of the stable diffusion model.
+ version: the version of the stable diffusion model. Options: ``"1.4"``, ``"1.5"``, ``"xl"``.
step_range: the step range of the diffusion model steps. Higher the step, stronger
the dissolving effects.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
@@ -55,6 +64,12 @@ class RandomDissolving(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`.
- Output: :math:`(B, C, H, W)`
+ .. note::
+ The transform is delegated to ``kornia.filters.StableDiffusionDissolving``, which the constructor
+ builds: instantiating this class needs the optional ``diffusers`` package and, on a cold cache,
+ downloads a Stable Diffusion checkpoint at that point -- the ``from_pretrained`` call is in that
+ class's own constructor, not on the first forward.
+
"""
def __init__(
diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.py
index 8578a643c..b50cad12f 100644
--- a/kornia/augmentation/_2d/intensity/equalize.py
+++ b/kornia/augmentation/_2d/intensity/equalize.py
@@ -28,6 +28,8 @@ class RandomEqualize(IntensityAugmentationBase2D):
.. image:: _static/img/RandomEqualize.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: Probability to equalize an image.
same_on_batch: apply the same transformation across the batch.
@@ -38,9 +40,25 @@ class RandomEqualize(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - this class raises on an out-of-``[0, 1]`` input instead of transforming it. See
+ :class:`~kornia.augmentation.IntensityAugmentationBase2D` for the policies used by the other
+ intensity augmentations. :class:`RandomClahe` also raises out of range, with a raw indexing error
+ that names neither the class nor the range (`#4564 <https://github.com/kornia/kornia/issues/4564>`_).
+ - the rejection is not exactly at the boundary: the check guards the 256-entry lookup indexed with
+ ``(input * 255).long()``, so a value less than one 8-bit code outside ``[0, 1]``, at either end, is
+ still admitted, up to the rounding of ``input * 255`` in the input's dtype: in ``float16``,
+ ``1.00390625`` already raises.
+
.. note::
This function internally uses :func:`kornia.enhance.equalize`, which expects the input in
- :math:`[0, 1]` and raises a ``RuntimeError`` naming that range for values it cannot equalize.
+ :math:`[0, 1]` and raises a ``RuntimeError`` for values it cannot equalize. Where the value check
+ runs, its message names that range; kornia skips the check for an MPS image, and what happens
+ there depends on torch: from ``2.14`` the lookup raises a raw indexing error
+ (``AcceleratorError: gather: index 260 is out of bounds for dimension with size 256``), while
+ ``2.5.1`` and ``2.9.1`` leave the MPS gather unchecked and return an out-of-range image silently.
+ That MPS gap is what `#4431 <https://github.com/kornia/kornia/issues/4431>`_ left behind when it
+ was closed, and is tracked in `#4600 <https://github.com/kornia/kornia/issues/4600>`_.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index 196227edc..50a115142 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -29,12 +29,15 @@ class RandomErasing(IntensityAugmentationBase2D):
.. image:: _static/img/RandomErasing.png
- The operator removes image parts and fills them with zero values at a selected rectangle
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
+ The operator removes image parts and fills them with ``value`` at a selected rectangle
for each of the images in the batch.
- The rectangle will have an area equal to the original image area multiplied by a value uniformly
- sampled between the range [scale[0], scale[1]) and an aspect ratio sampled
- between [ratio[0], ratio[1])
+ The rectangle *targets* an area equal to the original image area multiplied by a value sampled from
+ ``scale``, with an aspect ratio sampled from ``ratio``. The Convention block below records how far the
+ realised box can be from that target: the side lengths are rounded and clamped into ``[1, H] x [1, W]``,
+ and a ``ratio`` straddling ``1`` is not drawn uniformly.
Args:
scale: range of proportion of erased area against input image.
@@ -49,6 +52,29 @@ class RandomErasing(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - ``scale`` is the fraction of the image *area* the rectangle targets and ``ratio`` is its height over
+ its width, so a ratio above ``1`` targets a tall box and below ``1`` a wide one. The box is rounded
+ to whole pixels and then clamped to ``[1, H] x [1, W]`` -- a floor as well as a ceiling, so it is
+ never empty and never larger than the image -- and the erased area and shape can miss the target in
+ either direction: ``scale=(0.25, 0.25)`` with ``ratio=(3.0, 3.0)`` on a ``10 x 20`` image erases
+ ``10 x 4 = 40`` pixels of the 50 asked for, while ``scale=(0.0, 0.0)`` still erases one pixel and a
+ ``1 x 1`` image is always erased in full.
+ - when ``ratio`` straddles ``1`` the draw is not uniform over the interval: the generator builds one
+ sampler for ``[ratio[0], 1]`` and one for ``[1, ratio[1]]`` and picks between them with a fair coin,
+ so a ratio above and below ``1`` are equally likely whatever the two sub-intervals' widths. At the
+ default ``ratio=(0.3, 3.3)`` half the draws are above ``1``, where a uniform draw would give about
+ ``77%``. The realised box follows the drawn ratio only while the ``[1, H] x [1, W]`` clamp above
+ does not bite: on a square image half the boxes come back taller than wide, but on a ``4 x 256``
+ one none of them do. A ``ratio`` that does not straddle ``1`` takes the single-sampler branch.
+ - the erased region is the half-open rectangle ``[ys, ys + h) x [xs, xs + w)`` in pixels, recorded as
+ ``_params["ys"]``, ``["xs"]``, ``["heights"]`` and ``["widths"]``.
+ - the erased pixels carry the literal ``value``, which has to lie in ``[0, 1]`` -- the parameter
+ generator rejects anything else at construction. Every other pixel is carried through unclamped, so
+ every pixel outside the box keeps the input's range.
+ - inside :class:`~kornia.augmentation.container.AugmentationSequential` a ``mask`` data key is erased
+ in the same rectangle, but the mask is filled with ``0`` whatever ``value`` is.
+
Note:
Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
index 46b9299ba..a7b9393a1 100644
--- a/kornia/augmentation/_2d/intensity/gamma.py
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -31,6 +31,8 @@ class RandomGamma(IntensityAugmentationBase2D):
.. image:: _static/img/RandomGamma.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
gamma: the gamma factor to apply.
@@ -42,6 +44,23 @@ class RandomGamma(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the output is ``clamp(gain * input ** gamma, 0, 1)``. The clamp is not optional, so unlike
+ :class:`RandomBrightness` and :class:`RandomContrast` this class has no ``clip_output`` escape
+ hatch for keeping a value the power produced outside ``[0, 1]``.
+ - ``gamma`` and ``gain`` must both be non-negative, and neither is bounded at construction: both
+ checks live inside :func:`kornia.enhance.adjust_gamma` and so run on the forward pass. A negative
+ ``gain`` raises ``Gain must be non-negative``, exactly as a negative ``gamma`` raises
+ ``Gamma must be non-negative``. kornia skips that check for an MPS image, so there
+ a negative ``gamma`` is evaluated using the same power, gain and clamp formula above. Its output
+ depends on both the input and ``gain``.
+
+ .. warning::
+ On an input with negative values the power itself is NaN unless ``gamma`` is an integer, and the
+ clamp does not remove the NaN. At an integer ``gamma`` the output is finite instead, and at the
+ class default ``gamma=1.0`` the clamp floors the negative product, so every negative value comes
+ back as ``0``. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.adjust_gamma`
diff --git a/kornia/augmentation/_2d/intensity/gaussian_blur.py b/kornia/augmentation/_2d/intensity/gaussian_blur.py
index ae5c34a42..5443ef06f 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py
@@ -33,6 +33,8 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
.. image:: _static/img/RandomGaussianBlur.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
kernel_size: the size of the kernel.
sigma: the range for the standard deviation of the kernel.
@@ -48,6 +50,26 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - ``kernel_size`` is ``(kH, kW)``: the first entry counts rows and the second counts columns, as in
+ :func:`kornia.filters.gaussian_blur2d`. An even entry is not rounded up -- the forward pass raises
+ the primitive's own "odd integer" error.
+ - ``sigma`` is drawn once per sample, as a single scalar used for both axes. Both axes get that sigma
+ even when a rectangular ``kernel_size`` gives them different supports, and a support short enough to
+ truncate the Gaussian narrows the blur along its axis.
+ - the defaults ``separable=True`` and ``border_type="reflect"`` are the function's own defaults.
+ - the output is not clamped. At the default ``border_type="reflect"`` every output value is a weighted
+ average of input values and stays between the input's own extremes, up to the rounding of the kernel
+ weights; ``border_type="constant"`` pads with zeros, which pulls a border pixel toward ``0``: below
+ the input's minimum for a positive image, and above its maximum for a negative one.
+
+ .. warning::
+ At the default ``border_type="reflect"``, an image with a spatial axis no longer than half the kernel's extent
+ along that axis raises a raw torch ``RuntimeError`` about the padding rather than a kornia error naming the
+ class or the shape. ``"constant"`` and ``"replicate"`` run on the same image; ``"circular"`` raises a padding
+ error of its own, also raw, once the kernel radius exceeds that axis. Tracked in `#4559
+ <https://github.com/kornia/kornia/issues/4559>`_.
+
.. note::
This function internally uses :func:`kornia.filters.gaussian_blur2d`.
diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
index 1b8a9832b..2da3faa75 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
@@ -47,6 +47,8 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):
.. image:: _static/img/RandomGaussianIllumination.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
gain: Range for the gain factor (intensity) applied to the generated illumination.
center: The center coordinates of the Gaussian distribution are expressed as a
@@ -64,6 +66,46 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the class draws ``_params["gradient"]``, a tensor with the original normalized ``(B, C, H, W)``
+ input shape; a ``(C, H, W)`` input remains batched in stored parameters even when ``keepdim=True``.
+ It adds the field to the image and
+ clamps the sum into ``[0, 1]``, so the output stays inside that range even when the input does not --
+ except where the Gaussian kernel itself is NaN, see the warning below.
+ - ``sign`` is drawn per sample, from ``(-1.0, 1.0)`` by default, and only whether the draw is negative
+ is used: it decides whether that sample's gradient darkens or brightens, so one batch can hold both
+ a darkened and a brightened image. A point range such as ``sign=1.0`` brightens every sample.
+ - the clamp bites on in-range images too: once ``gain`` exceeds the headroom between the image and the
+ bound, the sum is cut there rather than rescaled.
+ - ``sigma`` is a fraction of the axis length, not an absolute width: the generator draws it and
+ multiplies by the image's width and height before building the kernel, so the same ``sigma`` is a
+ narrower kernel on a smaller image.
+ - the module pickles, deep-copies and passes through ``torch.save``, and the copy reproduces the
+ original's output under the same seed. After ``.compile()``, which swaps in a compiled transform,
+ it no longer pickles or passes through ``torch.save``, although it still deep-copies.
+
+ .. warning::
+ An all-negative input can come back as an all-zero image when the sampled gradient does not raise it
+ above zero; a positive sampled gradient can recover values instead. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
+ .. warning::
+ A ``sigma`` at or near ``0``, which the constructor admits, can make the whole output NaN.
+ :func:`kornia.filters.gaussian` normalizes by ``gauss.sum()``, which underflows to zero there, so
+ the kernel is ``0 / 0``. ``sigma=0.0`` does it at any size. Above zero it is the kernel's
+ **absolute** width that decides -- ``sigma`` times the axis length, since ``sigma`` is relative --
+ and not the axis length on its own. With ``center=(0.5, 0.5)`` an even axis puts its nearest sample
+ half a pixel off the mean, so the kernel underflows once ``sigma * axis`` falls below about
+ ``0.034``: a ``4 x 4`` image at ``sigma=(0.005, 0.005)`` is NaN, and so is a ``64 x 64`` one at
+ ``sigma=(0.0005, 0.0005)``, while ``8 x 8`` and larger are finite at ``0.005``. An odd axis whose
+ rounded center lands on the grid keeps a sample at the mean and is finite at every positive
+ ``sigma``; the default ``center=(0.1, 0.9)`` can miss the grid only on a ``1``- or ``3``-pixel axis,
+ which is why a drawn center makes a ``3 x 3`` image NaN on some seeds but never a ``5 x 5`` one.
+ The threshold follows the **parameter** dtype, which is ``float32`` whatever the image dtype, so
+ after ``set_rng_device_and_dtype(device, torch.float64)`` the ``4 x 4`` case at ``sigma=0.005`` is
+ finite and ``0.003`` is not. The default ``sigma=(0.2, 1.0)`` is unaffected. Tracked in
+ `#4589 <https://github.com/kornia/kornia/issues/4589>`_.
+
.. note::
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU. This can be changed by calling
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
index a05bde582..9ec786cda 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -28,6 +28,8 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
.. image:: _static/img/RandomGaussianNoise.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
mean: The mean of the gaussian distribution.
std: The standard deviation of the gaussian distribution.
@@ -36,6 +38,15 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+ Convention:
+ - the noise is additive and recorded in full: the output is the input plus
+ ``_params["gaussian_noise"]``, a tensor with the original normalized ``(B, C, H, W)`` input shape,
+ so ``mean`` offsets the image rather than naming the mean the output should have. A
+ ``(C, H, W)`` input remains batched in the stored parameters even when ``keepdim=True``. With
+ ``same_on_batch=True``, the stored field has shape ``(1, C, H, W)`` and is expanded across the
+ input batch during application.
+ - nothing is clamped, so an input already inside ``[0, 1]`` can leave it in either direction.
+
Examples:
>>> rng = torch.manual_seed(0)
>>> img = torch.ones(1, 1, 2, 2)
diff --git a/kornia/augmentation/_2d/intensity/grayscale.py b/kornia/augmentation/_2d/intensity/grayscale.py
index 5a6376969..6f877289b 100644
--- a/kornia/augmentation/_2d/intensity/grayscale.py
+++ b/kornia/augmentation/_2d/intensity/grayscale.py
@@ -30,6 +30,8 @@ class RandomGrayscale(IntensityAugmentationBase2D):
.. image:: _static/img/RandomGrayscale.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Works for multispectral imagery too (e.g. satellite data with 4-13+ bands): for a non-RGB
channel count the grayscale is the weighted average across *all* channels, broadcast back to
the input channel count. This makes the augmentation usable outside the 3-channel RGB regime.
@@ -37,8 +39,8 @@ class RandomGrayscale(IntensityAugmentationBase2D):
Args:
rgb_weights: Per-channel weights applied when reducing to grayscale β€” one weight per input
channel (three, for the usual RGB case). If ``None``, RGB inputs use the standard
- luminance weights and multispectral inputs weight every band equally. The weights
- should sum to one.
+ luminance weights and multispectral inputs weight every band equally. Weights are applied
+ as given and are not normalized, so weights that do not sum to one rescale the output.
p: probability of the image to be transformed to grayscale.
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
@@ -48,6 +50,15 @@ class RandomGrayscale(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the channel count is preserved: the single weighted average is broadcast back over the input's
+ channels, so every output channel of a sample carries the same value.
+ - a three-channel input uses the RGB luminance weights by default; any other channel count
+ defaults to an equal weight per channel, which makes the output the plain mean over channels.
+ ``rgb_weights`` replaces those defaults.
+ - the result is not clamped; its range follows the weighted channel reduction and the supplied
+ ``rgb_weights``.
+
.. note::
For 3-channel RGB inputs this uses :func:`kornia.color.rgb_to_grayscale`; multispectral
inputs use a weighted channel average.
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index a6262ccb9..2eecfed83 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -33,8 +33,13 @@ class RandomHue(IntensityAugmentationBase2D):
.. image:: _static/img/RandomHue.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
- hue: the saturation factor to apply.
+ hue: the hue shift, in turns of the hue circle, restricted to the closed ``[-0.5, 0.5]``. If ``hue``
+ is a single number ``x`` the shift is sampled from ``[-x, x]`` fitted to that bound, so a larger
+ ``x`` widens the range no further (`#4563 <https://github.com/kornia/kornia/issues/4563>`_); a
+ tuple gives the range directly, and one outside the bound raises.
same_on_batch: apply the same transformation across the batch.
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
@@ -43,6 +48,20 @@ class RandomHue(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the input must have three channels: the shift is computed in HSV, and any other channel count raises
+ a ``ValueError`` on the forward pass.
+ - the drawn shift is in turns of the hue circle, and the class multiplies it by ``2 * pi`` before
+ calling :func:`kornia.enhance.adjust_hue`, which takes radians. Passing the same number
+ straight to that primitive shifts the hue by a different amount.
+ - the result is not clamped, so a pixel outside ``[0, 1]`` keeps a channel outside it, up to the
+ rounding of the HSV round trip. The exception is a pixel whose largest channel is exactly ``0``,
+ which comes back as zeros, or as NaN in ``float16``.
+
+ .. warning::
+ In ``float16`` a pixel whose largest channel is ``0`` -- for an input in ``[0, 1]``, a black pixel --
+ comes back as NaN, because ``rgb_to_hsv``'s ``eps`` underflows there. Tracked in `#4560 <https://github.com/kornia/kornia/issues/4560>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.adjust_hue`
diff --git a/kornia/augmentation/_2d/intensity/invert.py b/kornia/augmentation/_2d/intensity/invert.py
index 26d23d5d6..a92c8ed14 100644
--- a/kornia/augmentation/_2d/intensity/invert.py
+++ b/kornia/augmentation/_2d/intensity/invert.py
@@ -29,6 +29,8 @@ class RandomInvert(IntensityAugmentationBase2D):
.. image:: _static/img/RandomInvert.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
max_val: The expected maximum value in the input tensor. The shape has to
according to the input tensor shape, or at least has to work with broadcasting.
@@ -36,6 +38,12 @@ class RandomInvert(IntensityAugmentationBase2D):
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+
+ Convention:
+ - the output is ``max_val - input``, with no clamp, so an input outside ``[0, max_val]`` comes
+ back outside it rather than clipped. ``max_val`` describes the input's maximum, so it has to be
+ set to match an input that is not in ``[0, 1]``.
+
.. note::
This function internally uses :func:`kornia.enhance.invert`.
diff --git a/kornia/augmentation/_2d/intensity/jpeg.py b/kornia/augmentation/_2d/intensity/jpeg.py
index 7581f4c43..3ccb6a227 100644
--- a/kornia/augmentation/_2d/intensity/jpeg.py
+++ b/kornia/augmentation/_2d/intensity/jpeg.py
@@ -29,6 +29,11 @@ class RandomJPEG(IntensityAugmentationBase2D):
.. image:: _static/img/RandomJPEG.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+ :func:`kornia.color.ycbcr_to_rgb` hard-clamps the decoded RGB values to ``[0, 1]``. The codec's final
+ soft-clipping call uses bounds ``[0, 255]`` and leaves those RGB values unchanged. The input must have
+ three channels: the codec works in YCbCr, and any other channel count raises a ``ShapeError``.
+
Args:
jpeg_quality: The range of compression rates to be applied.
p: probability of applying the transformation.
diff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.py
index 07443c7a5..623d7d3be 100644
--- a/kornia/augmentation/_2d/intensity/linear_illumination.py
+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py
@@ -29,6 +29,8 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
.. image:: _static/img/RandomLinearIllumination.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
gain: Range for the gain factor (intensity) applied to the generated illumination.
sign: Range for the sign of the distribution. If only one sign is needed,
@@ -42,6 +44,25 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the class draws ``_params["gradient"]``, a tensor with the original normalized ``(B, C, H, W)``
+ input shape; a ``(C, H, W)`` input remains batched in stored parameters even when ``keepdim=True``.
+ It adds the field to the image and
+ clamps the sum into ``[0, 1]``, so the output stays inside that range even when the input does not.
+ - ``sign`` is drawn per sample, from ``(-1.0, 1.0)`` by default, and only whether the draw is negative
+ is used: it decides whether that sample's gradient darkens or brightens, so one batch can hold both
+ a darkened and a brightened image. A point range such as ``sign=1.0`` brightens every sample. The
+ edge where the gradient is strongest is drawn separately, per sample.
+ - the clamp bites on in-range images too: once ``gain`` exceeds the headroom between the image and the
+ bound, the sum is cut there rather than rescaled.
+ - the module pickles, deep-copies and passes through ``torch.save``, and the copy reproduces the
+ original's output under the same seed.
+
+ .. warning::
+ An all-negative input can come back as an all-zero image when the sampled gradient does not raise it
+ above zero; a positive sampled gradient can recover values instead. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
.. note::
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU. This can be changed by calling
@@ -136,6 +157,8 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
.. image:: _static/img/RandomLinearCornerIllumination.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
gain: Range for the gain factor (intensity) applied to the generated illumination.
sign: Range for the sign of the distribution. If only one sign is needed,
@@ -149,6 +172,25 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the class draws ``_params["gradient"]``, a tensor with the original normalized ``(B, C, H, W)``
+ input shape; a ``(C, H, W)`` input remains batched in stored parameters even when ``keepdim=True``.
+ It adds the field to the image and
+ clamps the sum into ``[0, 1]``, so the output stays inside that range even when the input does not.
+ - ``sign`` is drawn per sample, from ``(-1.0, 1.0)`` by default, and only whether the draw is negative
+ is used: it decides whether that sample's gradient darkens or brightens, so one batch can hold both
+ a darkened and a brightened image. A point range such as ``sign=1.0`` brightens every sample. The
+ corner where the gradient is strongest is drawn separately, per sample.
+ - the clamp bites on in-range images too: once ``gain`` exceeds the headroom between the image and the
+ bound, the sum is cut there rather than rescaled.
+ - the module pickles, deep-copies and passes through ``torch.save``, and the copy reproduces the
+ original's output under the same seed.
+
+ .. warning::
+ An all-negative input can come back as an all-zero image when the sampled gradient does not raise it
+ above zero; a positive sampled gradient can recover values instead. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
.. note::
The generated random numbers are not reproducible across different devices and dtypes. By default,
the parameters will be generated on CPU. This can be changed by calling
diff --git a/kornia/augmentation/_2d/intensity/median_blur.py b/kornia/augmentation/_2d/intensity/median_blur.py
index 5795da3c1..228581f61 100644
--- a/kornia/augmentation/_2d/intensity/median_blur.py
+++ b/kornia/augmentation/_2d/intensity/median_blur.py
@@ -28,12 +28,30 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
.. image:: _static/img/RandomMedianBlur.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
kernel_size: the blurring kernel size.
same_on_batch: apply the same transformation across the batch.
p: probability of applying the transformation.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+
+ Convention:
+ - ``kernel_size`` is ``(kH, kW)``: the first entry counts rows and the second counts columns, as in
+ :func:`kornia.filters.median_blur`.
+ - the output is not clamped. The window is
+ zero-padded -- :func:`kornia.filters.median_blur` convolves with ``F.conv2d`` -- so a border median
+ is taken over zeros as well as image values, and a border pixel can come back as ``0`` even when no
+ input value is near it.
+ - this class has no ``border_type``, and with an odd ``kernel_size`` an image smaller than the kernel
+ is accepted, down to ``1 x 1``; :class:`RandomBoxBlur` and :class:`RandomGaussianBlur` raise at their
+ default ``border_type="reflect"`` once a spatial axis is no longer than half the kernel's extent along
+ it. An even entry in ``kernel_size`` raises on the forward pass for every image, but not always with
+ the same error: a raw reshape error once the zero-padded image is at least as large as the kernel, and
+ torch's ``Kernel size can't be greater than actual input size`` from ``F.conv2d`` below that -- an even
+ ``4 x 4`` kernel raises the reshape error at ``2 x 2`` and the conv2d error at ``1 x 1``.
+
.. note::
This function internally uses :func:`kornia.filters.median_blur`.
diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.py
index cbd1c9461..2e7fc6e6f 100644
--- a/kornia/augmentation/_2d/intensity/motion_blur.py
+++ b/kornia/augmentation/_2d/intensity/motion_blur.py
@@ -30,6 +30,8 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
.. image:: _static/img/RandomMotionBlur.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
kernel_size: motion kernel size (odd and positive).
@@ -53,6 +55,36 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - a positive ``angle`` turns the blur line counter-clockwise as the image is displayed, as in
+ :func:`kornia.filters.motion_blur` and :func:`kornia.filters.get_motion_kernel2d`.
+ - ``direction`` re-weights the kernel along that line before it is rotated: ``0`` spreads the weight evenly, and
+ ``-1`` and ``+1`` pile it at opposite ends. The rotation then resamples the kernel with ``resample``:
+ ``"nearest"`` can drop or duplicate taps, so the line's length and end weights change with ``angle``, and
+ ``"bilinear"`` or ``"bicubic"`` also spread weight off the line. The ends belong to the rotated line, so which
+ side of the image they fall on turns with ``angle`` and is not read off the image axes.
+ - the defaults ``border_type="constant"`` and ``resample="nearest"`` are the function's own defaults.
+ - ``kernel_size`` is drawn once per sample into ``_params["ksize_factor"]``, and the whole batch is
+ then blurred with the single entry at ``_params["idx"]``, an index drawn uniformly over the batch.
+ The draw truncates a float, so the range's upper bound is practically never reached -- only when
+ the ``float32`` draw rounds onto it, about once in ``2**24`` -- and ``kernel_size=(3, 5)`` is a
+ constant ``3`` while ``(3, 7)`` draws only ``3`` and ``5``. An even bound is separately rounded
+ **up** out of the requested range, so ``(4, 4)`` draws ``5``. Tracked in
+ `#4599 <https://github.com/kornia/kornia/issues/4599>`_.
+ - the output is not clamped. At the default ``border_type="constant"`` the padding is zeros, so a
+ border pixel is blended with ``0`` and pulled toward it: below the input's own minimum for a
+ positive image, and above its maximum for a negative one. With
+ ``border_type="reflect"`` the result stays between the input's extremes, up to rounding, at
+ ``resample="nearest"`` or ``"bilinear"``; a ``"bicubic"`` rotation gives the kernel negative weights,
+ and the result can overshoot both extremes.
+ - an image smaller than the kernel is accepted, down to ``1 x 1``, at ``border_type="constant"``
+ and ``"replicate"``. ``"reflect"`` raises once a spatial axis is no longer than half the kernel
+ size along it, as the two padding blurs do, and ``"circular"`` raises a padding error of its own once the
+ kernel radius exceeds a spatial axis. Both are raw torch errors of the kind
+ `#4559 <https://github.com/kornia/kornia/issues/4559>`_ tracks, although that issue is scoped to the
+ three classes that raise at their *defaults* and names this one as accepting the same images --
+ which it does, at the default ``border_type="constant"``.
+
Note:
Input torch.Tensor must be float and normalized into [0, 1] for the best differentiability support.
Additionally, this function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.py
index 74c41b15b..114cb1f96 100644
--- a/kornia/augmentation/_2d/intensity/normalize.py
+++ b/kornia/augmentation/_2d/intensity/normalize.py
@@ -29,6 +29,8 @@ from kornia.enhance import normalize
class Normalize(IntensityAugmentationBase2D):
r"""Normalize tensor images with mean and standard deviation.
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
.. math::
\text{input[channel] = (input[channel] - mean[channel]) / std[channel]}
@@ -44,6 +46,27 @@ class Normalize(IntensityAugmentationBase2D):
Return:
Normalised tensor with same size as input :math:`(*, C, H, W)`.
+ Convention:
+ - ``mean`` and ``std`` accept a float, a per-channel sequence or tensor, or a per-sample ``(B, C)``
+ tensor; a length that is neither ``1`` nor the channel count raises.
+ - ``p`` gates the whole batch rather than each sample: the constructor hard-codes
+ ``same_on_batch=True``, which collapses the per-sample draw to a single one, and it takes no
+ ``same_on_batch`` argument of its own.
+ - the statistics live in ``flags`` rather than in a buffer, so ``state_dict()`` is empty and
+ ``Module.to(...)`` leaves their device and dtype alone.
+ - :class:`Denormalize` built with the same float, sequence or tensor ``mean`` and ``std`` inverts this
+ class, up to float rounding, when both apply -- each draws its own ``p`` gate. An ``int`` statistic,
+ which this class accepts, makes :class:`Denormalize` raise on the forward pass
+ (`#4573 <https://github.com/kornia/kornia/issues/4573>`_).
+ - the result is not clamped: moving an image out of ``[0, 1]`` is what this class is for.
+
+ .. warning::
+ A non-contiguous input -- anything :meth:`torch.Tensor.view` cannot reshape, such as a
+ ``transpose``d or ``permute``d view -- raises a raw ``RuntimeError: view size is not compatible
+ with input tensor's size and stride`` from :func:`kornia.enhance.normalize`, naming neither this
+ class nor the fix (``.contiguous()``). Tracked in
+ `#4577 <https://github.com/kornia/kornia/issues/4577>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.normalize`.
diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.py
index c6036bff1..983692f3d 100644
--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py
+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py
@@ -95,6 +95,8 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
.. image:: _static/img/RandomPlanckianJitter.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
This is physics based color augmentation, that creates realistic
variations in chromaticity, this can simulate the illumination
changes in the scene.
@@ -113,6 +115,27 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the red and blue channels are scaled by the selected row of the illuminant table and the green
+ channel is not scaled. The result is then clamped at the upper end only, so negative values stay
+ negative while any value the scaling leaves above ``1``, green included, is cut back to ``1``. Every
+ other 2D intensity augmentation whose clamp reaches the whole output bounds both ends;
+ :class:`RandomSnow` clamps only the pixels the snow covers, so it bounds the lower end of an
+ all-negative image and not the upper end of one above ``1``.
+ - ``mode`` selects the illuminant lookup table, held in the persistent buffer ``pl``, and
+ ``select_from`` narrows that table to the listed rows. The input must have three channels.
+
+ .. warning::
+ ``pl``'s shape depends on ``mode``, so a ``state_dict`` saved by an instance built with one mode
+ does not load into an instance built with the other. Tracked in
+ `#4428 <https://github.com/kornia/kornia/issues/4428>`_.
+
+ .. warning::
+ The table is not cast to the input's dtype, so the output takes the promoted dtype of the input and
+ the table. With the table left at ``float32``, a ``float16`` or ``bfloat16`` input comes back as
+ ``float32``; casting the module to the input's own dtype keeps it. Tracked in
+ `#4574 <https://github.com/kornia/kornia/issues/4574>`_.
+
.. note::
Input torch.Tensor must be float and normalized into [0, 1].
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
index 0e09ef097..fbaf92d3a 100644
--- a/kornia/augmentation/_2d/intensity/plasma.py
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -52,6 +52,8 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
.. image:: _static/img/RandomPlasmaBrightness.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals.
See: :cite:`tormentor` for more details.
@@ -66,6 +68,23 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+ Convention:
+ - the sampled fractal map is recorded as ``_params["plasma"]`` with the original normalized
+ ``(B, C, H, W)`` input shape, so a forward replayed with ``params=`` reproduces the first output
+ bitwise. A ``(C, H, W)`` input remains batched in stored parameters even when ``keepdim=True``.
+ - the result is clamped into ``[0, 1]``, so the output stays inside that range even when the input
+ does not.
+ - a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.
+
+ .. warning::
+ With ``same_on_batch=True`` the scalar draws are shared but the fractal map is not: every sample keeps
+ its own ``_params["plasma"]`` slice, so identical inputs can come back different. Tracked in
+ `#4570 <https://github.com/kornia/kornia/issues/4570>`_.
+
+ .. warning::
+ An all-negative input can come back as an all-zero image when the sampled brightness map does not raise
+ it above zero. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
Examples:
>>> rng = torch.manual_seed(0)
>>> img = torch.ones(1, 1, 3, 4)
@@ -113,6 +132,8 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
.. image:: _static/img/RandomPlasmaContrast.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals.
See: :cite:`tormentor` for more details.
@@ -126,6 +147,23 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+ Convention:
+ - the sampled fractal map is recorded as ``_params["plasma"]`` with the original normalized
+ ``(B, C, H, W)`` input shape, so a forward replayed with ``params=`` reproduces the first output
+ bitwise. A ``(C, H, W)`` input remains batched in stored parameters even when ``keepdim=True``.
+ - the result is clamped into ``[0, 1]``, so the output stays inside that range even when the input
+ does not.
+ - a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.
+
+ .. warning::
+ With ``same_on_batch=True`` the scalar draws are shared but the fractal map is not: every sample keeps
+ its own ``_params["plasma"]`` slice, so identical inputs can come back different. Tracked in
+ `#4570 <https://github.com/kornia/kornia/issues/4570>`_.
+
+ .. warning::
+ An all-negative input can come back as an all-zero image, depending on the sampled contrast map.
+ Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
Examples:
>>> rng = torch.manual_seed(0)
>>> img = torch.ones(1, 1, 3, 4)
@@ -168,6 +206,8 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
.. image:: _static/img/RandomPlasmaShadow.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
This is based on the original paper: TorMentor: Deterministic dynamic-path, data augmentations with fractals.
See: :cite:`tormentor` for more details.
@@ -183,6 +223,25 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
keepdim: whether to keep the output shape the same as input (True) or broadcast it
to the batch form (False).
+ Convention:
+ - the sampled fractal map is recorded as ``_params["plasma"]`` with the original normalized
+ ``(B, 1, H, W)`` input shape. Its single channel means one shade mask is applied to every channel
+ of a sample; a ``(C, H, W)`` input remains batched in stored parameters even when ``keepdim=True``.
+ A forward replayed with ``params=`` reproduces the first output bitwise.
+ - the result is clamped into ``[0, 1]``, so the output stays inside that range even when the input
+ does not.
+ - a one-pixel spatial axis is accepted, down to a ``1 x 1`` image.
+
+ .. warning::
+ With ``same_on_batch=True`` the scalar draws are shared but the fractal map is not: every sample keeps
+ its own ``_params["plasma"]`` slice, so identical inputs can come back different. Tracked in
+ `#4570 <https://github.com/kornia/kornia/issues/4570>`_.
+
+ .. warning::
+ At the default non-positive ``shade_intensity``, an input whose values are all negative comes back as
+ an all-zero image; a positive ``shade_intensity``, which the constructor accepts, can lift it. Tracked
+ in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
Examples:
>>> rng = torch.manual_seed(0)
>>> img = torch.ones(1, 1, 3, 4)
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
index b35fe6373..d14c4baaa 100644
--- a/kornia/augmentation/_2d/intensity/posterize.py
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -29,9 +29,13 @@ class RandomPosterize(IntensityAugmentationBase2D):
.. image:: _static/img/RandomPosterize.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
- bits: Integer that ranged from (0, 8], in which 0 gives black image and 8 gives the original.
+ bits: number of high bits to keep, in ``[0, 8]``, in which 0 gives a black image and 8 gives the
+ original. A non-integral argument is accepted; the drawn factor is rounded to an integer, half to
+ even, so ``2.5`` gives ``2`` and ``3.5`` gives ``4``.
If int x, bits will be generated from (x, 8) then convert to int.
If tuple (x, y), bits will be generated from (x, y) then convert to int.
same_on_batch: apply the same transformation across the batch.
@@ -42,6 +46,25 @@ class RandomPosterize(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - ``bits=(k, k)`` with ``k < 8`` leaves at most ``2 ** k`` distinct values, so ``0`` gives a constant
+ image; the reduction is a ``uint8`` round trip inside :func:`kornia.enhance.posterize`. A sample
+ that draws ``8`` is returned unchanged, without the round trip. The drawn factor is integral: a
+ non-integral ``bits`` is rounded half to even.
+ - the round trip is a step function, so a posterized sample carries no gradient. The output still has
+ ``requires_grad=True``, but the gradient with respect to the input is identically ``0`` below
+ ``bits=8``; at ``bits=8``, which skips the round trip, it is the identity.
+ - an ``int`` argument is the lower bound of the sampled range ``[x, 8]`` -- the opposite reading
+ from :class:`RandomSharpness`, whose scalar argument is an upper bound.
+
+ .. warning::
+ Outside ``[0, 1]`` the output is the posterized ``uint8`` conversion of the raw float, which
+ wraps or saturates depending on the platform and torch version, and bears no relation to the
+ clamped input: an input above ``1`` can come back as a full-range posterized image instead of a
+ clipped one, and an all-negative input as an all-zero one. A sample that draws ``bits=8`` skips the
+ conversion and keeps its out-of-range values, and a scalar ``bits`` below ``8`` can draw ``8`` for any
+ sample. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.posterize`.
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index d5c184fb8..6b57d99a1 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -29,6 +29,8 @@ from kornia.core.check import KORNIA_CHECK
class RandomRain(IntensityAugmentationBase2D):
r"""Add Random Rain to the image.
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
number_of_drops: number of drops per image
@@ -40,6 +42,37 @@ class RandomRain(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the input must have one or three channels; any other channel count raises on the forward pass.
+ - ``drop_height`` runs down rows and ``drop_width`` along columns: both name image axes, not
+ drop-local ones, and a negative ``drop_width`` slants the drop the other way across the columns.
+ - a drop is written as the fixed value ``200 / 255``, not as a function of the image, so the rain is
+ darker than every pixel above ``200 / 255`` that it falls on, inside ``[0, 1]`` or not. Every other
+ pixel is carried through unclamped.
+ - both sizes must be strictly smaller than the image on their own axis. Once the larger of the two
+ sizes is at least ``2``, a drop of size ``h`` spans ``h + 1`` rows or columns end to end, so a size
+ one short of the image already reaches from edge to edge; a drop whose sizes are both at most ``1``
+ is a single pixel. ``span`` is an extent, not a count: the drop is a ``linspace`` of
+ ``max(drop_height, abs(drop_width))`` steps truncated to integers, so when the two sizes differ the
+ painted cells have gaps inside that span -- ``drop_height=5`` with ``drop_width=0`` on a ``6 x 10``
+ image paints rows ``[0, 1, 2, 3, 5]``. A size as large as the image's, or a ``drop_height`` below
+ ``1``, raises on the forward pass, where the image shape is known -- constructing it succeeds.
+ - a drop's start coordinate is scaled by ``H - h - 1`` rather than ``H - h``, so the last row and
+ the last column of the image are never painted unless the drop is exactly one short of the image
+ on that axis; a single-pixel drop never reaches the last two rows. Tracked in
+ `#4604 <https://github.com/kornia/kornia/issues/4604>`_.
+ - the drawn sizes and drop count are float draws truncated toward zero, so unless the range is a single
+ point, a positive upper bound is practically never drawn: the default ``drop_height=(5, 20)`` gives
+ heights of ``5`` to ``19`` (an image shorter than 20 pixels raises on some seeds, and on every seed when
+ it is 5 pixels tall or shorter). A negative ``drop_width`` bound rounds toward zero instead: a negative
+ lower bound is practically never drawn while a non-positive upper bound is, and a range from ``-1`` or
+ below to ``1`` or above draws ``0`` twice as often as any other value -- or practically always at
+ ``(-1, 1)`` exactly, where only an exact ``-1.0`` draw, one ``float32`` value in ``2**24``, escapes
+ the truncation to ``0``. Tracked in `#4567
+ <https://github.com/kornia/kornia/issues/4567>`_.
+ - ``same_on_batch=True`` gives every sample of the batch the same drop count, the same drop size and
+ the same coordinates; left at ``False`` each sample draws its own.
+
Examples:
>>> rng = torch.manual_seed(0)
>>> input = torch.rand(1, 1, 5, 5)
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index 571c828d5..8d0e80517 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -27,6 +27,8 @@ from kornia.enhance import shift_rgb
class RandomRGBShift(IntensityAugmentationBase2D):
"""Randomly shift each channel of an image.
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
r_shift_limit: maximum value up to which the shift value can be generated for red channel;
recommended interval - [0, 1], should always be positive
@@ -39,6 +41,23 @@ class RandomRGBShift(IntensityAugmentationBase2D):
keepdim: whether to keep the output shape the same as input ``True`` or broadcast it
to the batch form ``False``.
+ Convention:
+ - the input must have exactly three channels, which :func:`kornia.enhance.shift_rgb` checks; any
+ other channel count raises an ``ImageError``. The class draws three named shifts per sample --
+ ``_params["r_shift"]``, ``["g_shift"]`` and ``["b_shift"]``, each of shape ``(B,)`` -- adds each to
+ its channel, and the sum is clamped into ``[0, 1]`` by :func:`kornia.enhance.shift_rgb`.
+ - each ``*_shift_limit`` is a half-width, not a maximum shift in one direction: that channel's
+ shift is sampled from ``[-limit, limit]``, so a limit of ``0`` adds nothing to the channel. The
+ clamp still applies, so such a channel comes back unchanged only if it was inside ``[0, 1]``. Each
+ limit is a non-negative scalar: a negative one raises a named ``ValueError`` and a tuple raises a raw
+ ``TypeError: bad operand type for unary -: 'tuple'`` at construction.
+
+ .. warning::
+ Because the sum is clamped, an input whose values are all at or below ``-limit`` comes back as an
+ all-zero image on every draw: at the default limits of ``0.5``, a constant ``-0.5`` image is zeros on
+ 100 of 100 seeds, and a constant ``-0.3`` one on 24 of 100, depending on the drawn shifts. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
Note:
Input torch.Tensor must be float and normalized into [0, 1].
diff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.py
index 22892e357..f20f0fcc0 100644
--- a/kornia/augmentation/_2d/intensity/random_snow.py
+++ b/kornia/augmentation/_2d/intensity/random_snow.py
@@ -28,10 +28,12 @@ from kornia.core.check import KORNIA_CHECK
class RandomSnow(IntensityAugmentationBase2D):
r"""Generates snow effect on given torch.Tensor image or a batch torch.Tensor images.
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
snow_coefficient: A tuple of floats (lower and upper bound) between 0 and 1 that control
the amount of snow to add to the image, the larger value corresponds to the more snow.
- brightness: A tuple of floats (lower and upper bound) greater than 1 that controls the
+ brightness: A tuple of floats (lower and upper bound) of ``1`` or greater that controls the
brightness of the snow.
same_on_batch: If True, apply the same transformation to each image in a batch. Default: False.
p: Probability of applying the transformation. Default: 0.5.
@@ -41,6 +43,39 @@ class RandomSnow(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the input must have three channels: the effect is computed in HLS, and any other channel count
+ raises on the forward pass.
+ - ``snow_coefficient`` is checked against ``[0, 1]`` at construction, where ``brightness`` must be
+ ``1`` or greater.
+ - one ``snow_coefficient`` and one ``brightness`` are drawn per sample; ``same_on_batch=True``
+ collapses both to a single value for the batch.
+ - the output as a whole is not clamped. Only a snow-covered pixel -- one whose lightness is below the
+ drawn ``snow_coefficient`` -- has its lightness scaled by ``brightness`` and clamped into ``[0, 1]``.
+ A covered pixel comes back white once its scaled lightness reaches ``1``, and black when its
+ lightness is zero or negative. A pixel the snow misses still goes through the HLS round trip
+ unclamped, so one above ``1`` usually comes back above it. The two exceptions are the pixels where
+ ``rgb_to_hls``'s saturation denominator vanishes, which collapse whether the snow covers them or not:
+ lightness exactly ``1``, where ``2 - max - min`` is zero and ``(1.5, 0.5, 0.5)`` comes back white,
+ and its mirror at lightness exactly ``0``, where ``max + min`` is zero and ``(2.0, -2.0, -2.0)``
+ comes back black. Both are NaN in ``float16`` (see below). The collapse is at the point, not around
+ it: ``(1.4, 0.5, 0.5)`` and a lightness more than about ``1e-7`` off ``1`` come back close to their
+ input. Within ``rgb_to_hls``'s ``eps`` of ``1e-8`` of the point, which only ``float64`` can
+ represent, they do not: a lightness of ``1 + 1e-8`` comes back as ``(2, 0, 0)`` and ``1 + 5e-9`` as
+ values of order ``1e8``. In half precision a value just above ``1`` can round onto the singular point.
+
+ .. warning::
+ An input whose values are all negative comes back as an all-zero image, and a pixel whose lightness is
+ zero or negative comes back black in any image -- including an out-of-range pixel such as
+ ``(2.0, -2.0, -2.0)``, which is neither all-negative nor has a negative lightness. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
+ .. warning::
+ In ``float16`` every achromatic pixel -- black, gray or white -- comes back as NaN, and so does an
+ out-of-range pixel whose lightness is exactly ``0`` or exactly ``1``, because ``rgb_to_hls``'s ``eps``
+ underflows there. Tracked in
+ `#4571 <https://github.com/kornia/kornia/issues/4571>`_.
+
Examples:
>>> inputs = torch.rand(2, 3, 4, 4)
>>> snow = kornia.augmentation.RandomSnow(p=1.0, snow_coefficient=(0.1, 0.6), brightness=(1.0, 5.0))
@@ -60,7 +95,7 @@ class RandomSnow(IntensityAugmentationBase2D):
) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)
KORNIA_CHECK(all(0 <= el <= 1 for el in snow_coefficient), "Snow coefficient values must be between 0 and 1.")
- KORNIA_CHECK(all(1 <= el for el in brightness), "Brightness values must be greater than 1.")
+ KORNIA_CHECK(all(1 <= el for el in brightness), "Brightness values must be 1 or greater.")
self._param_generator = rg.PlainUniformGenerator(
(snow_coefficient, "snow_coefficient", 0.5, (0.0, 1.0)), (brightness, "brightness", None, None)
diff --git a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
index 11ddd2f49..bf8b961b7 100644
--- a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
@@ -29,6 +29,8 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
.. image:: _static/img/RandomSaltAndPepperNoise.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
amount: A float or a tuple representing the range for the amount of noise to apply.
salt_vs_pepper: A float or a tuple representing the range for the ratio of Salt to Pepper noise.
@@ -41,6 +43,16 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - ``amount`` is a per-*pixel* rewrite probability, not a per-scalar one, so it sets the expected
+ fraction of pixels rewritten: a chosen pixel is rewritten in every channel, so the rewrite mask is
+ the same in each one.
+ - ``salt_vs_pepper`` is the probability that a rewritten pixel becomes salt rather than pepper, and
+ the poles are the literals ``1.0`` and ``0.0`` whatever the input's range is -- on an image scaled
+ to ``[0, 2]`` the salt is darker than every pixel above ``1``.
+ - the input must have one or three channels; any other channel count raises.
+ - the pixels the masks do not name are carried through unchanged and unclamped.
+
.. note::
The `amount` parameter controls the intensity of the noise, while `salt_vs_pepper` controls the ratio
of Salt to Pepper noise.
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index 37f1b00a4..960e88271 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -32,6 +32,8 @@ class RandomSaturation(IntensityAugmentationBase2D):
.. image:: _static/img/RandomSaturation.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
saturation: the saturation factor to apply.
@@ -42,6 +44,23 @@ class RandomSaturation(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the input must have three channels: the scaling is computed in HSV, and any other channel count
+ raises a ``ValueError`` on the forward pass.
+ - the drawn factor reaches :func:`kornia.enhance.adjust_saturation` unchanged -- it is not
+ re-based the way :class:`RandomBrightness` re-bases its own -- and ``1.0`` is the identity for a
+ pixel with no negative channel. That primitive round-trips through HSV, so the identity holds only
+ up to floating-point error, and the error is larger in half precision than in ``float32``.
+ - there is no final RGB clamp, but the primitive clamps the HSV saturation component into
+ ``[0, 1]``. An out-of-range RGB input can remain outside that interval or be mapped into it. At a
+ factor of ``1.0`` a pixel above ``1`` with no negative channel comes back unchanged, while a pixel
+ with a negative channel does not: ``(-0.1, 0.5, 0.5)`` becomes ``(0.0, 0.5, 0.5)``, and an
+ all-negative pixel becomes gray at its largest channel.
+
+ .. warning::
+ In ``float16`` a black pixel comes back as NaN, because ``rgb_to_hsv``'s ``eps`` underflows
+ there. Tracked in `#4560 <https://github.com/kornia/kornia/issues/4560>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.adjust_saturation`
diff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.py
index 6a095c191..9d7b3f5f6 100644
--- a/kornia/augmentation/_2d/intensity/sharpness.py
+++ b/kornia/augmentation/_2d/intensity/sharpness.py
@@ -25,13 +25,20 @@ from kornia.enhance import sharpness
class RandomSharpness(IntensityAugmentationBase2D):
- r"""Sharpen given torch.Tensor image or a batch of torch.Tensor images randomly.
+ r"""Blend a random amount of a ``3 x 3`` smoothed copy with the image.
+
+ A drawn factor above ``1`` sharpens and a factor below ``1`` blurs; the default
+ ``sharpness=0.5`` draws from ``[0, 0.5]`` and therefore only ever blurs.
.. image:: _static/img/RandomSharpness.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
- sharpness: factor of sharpness strength. Must be above 0.
+ sharpness: the blend factor between the blurred image and the input. If ``sharpness`` is a single
+ non-negative number ``x``, the factor is sampled from ``[0, x]``; a tuple gives the range
+ directly.
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).
@@ -40,6 +47,25 @@ class RandomSharpness(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the factor blends between the fully blurred image at ``0`` and the input at ``1``, and values
+ above ``1`` sharpen. The one-pixel border is copied from the input at every factor, so it is never
+ blurred or sharpened, although the final clamp into ``[0, 1]`` applies to it as to the rest.
+ - a scalar argument is the upper bound of ``[0, x]`` -- the centred ``[-x, x]`` fitted to the
+ non-negative bound (`#4563 <https://github.com/kornia/kornia/issues/4563>`_) -- so the default
+ ``sharpness=0.5`` never reaches the identity and therefore never sharpens -- it blurs by a random
+ amount.
+ - the result is kept inside ``[0, 1]``.
+
+ .. warning::
+ An input whose values are all negative comes back as an all-zero image. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
+ .. warning::
+ An image with a side smaller than the ``3 x 3`` smoothing kernel raises a raw torch
+ ``RuntimeError`` about the padded input size rather than a kornia error naming the class.
+ Tracked in `#4559 <https://github.com/kornia/kornia/issues/4559>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.sharpness`.
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
index d195f3182..d4d95f38a 100644
--- a/kornia/augmentation/_2d/intensity/solarize.py
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -29,6 +29,8 @@ class RandomSolarize(IntensityAugmentationBase2D):
.. image:: _static/img/RandomSolarize.png
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
+
Args:
p: probability of applying the transformation.
thresholds:
@@ -45,6 +47,31 @@ class RandomSolarize(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`, Optional: :math:`(B, 3, 3)`
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the addition comes first: the drawn ``additions`` value is added to the whole image and the sum
+ is clamped into ``[0, 1]``, and only then is everything at or above the drawn ``thresholds``
+ replaced by ``1 - value``.
+ - the scalar forms are centred, not absolute: a scalar ``thresholds`` is a half-width around
+ ``0.5`` and a scalar ``additions`` a half-width around ``0``, so the class defaults centre on
+ :func:`kornia.enhance.solarize`'s own default threshold rather than equalling it.
+ - an explicit ``additions`` range is checked against the closed ``[-0.5, 0.5]`` at construction, but
+ :func:`kornia.enhance.solarize` rejects the ends of that interval, so ``additions=(0.5, 0.5)``
+ constructs and then raises a ``RuntimeError`` on the forward pass, and a wider range can draw an
+ endpoint exactly, about once in ``2**24`` samples
+ (`#4605 <https://github.com/kornia/kornia/issues/4605>`_). The check runs on the device
+ of the drawn ``additions`` -- the CPU by default -- so it raises for an MPS image too.
+
+ .. warning::
+ An input entirely outside ``[0, 1]`` can collapse at either end. An all-negative input can come back
+ as an all-zero image when the sampled addition does not raise it above zero; a positive sampled
+ addition can recover values instead, and a drawn threshold of ``0`` inverts the clamped zeros into
+ an all-ones image. At the upper end, ``clamp(x + a, 0, 1)``
+ sends every ``x >= 1.5`` to exactly ``1.0`` for any admissible ``a``, and the inversion then returns
+ ``1 - 1.0 == 0``, so an input drawn from ``[1.5, 3.0]`` is an all-zero image on every draw.
+ Values between ``1`` and ``1.5`` can instead produce nonzero output after a negative addition:
+ ``x=1.1``, ``additions=(-0.4, -0.4)`` and ``thresholds=(0.5, 0.5)`` give ``0.3``. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
+
.. note::
This function internally uses :func:`kornia.enhance.solarize`.
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 498e6b58d..890a90c73 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -58,8 +58,7 @@ class _BasicAugmentationBase(nn.Module):
``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>`_.
+ tracked in `#4426 <https://github.com/kornia/kornia/issues/4426>`_.
For automatically generating the corresponding ``__repr__`` with full customized parameters, you may need to
implement ``_param_generator`` by inheriting ``RandomGeneratorBase`` for generating random parameters and
@@ -174,9 +173,10 @@ class _BasicAugmentationBase(nn.Module):
.. 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.
+ sampling occurred. Some generators also retain internal CPU tensors or ignore the requested
+ precision, and some generator/device combinations can still fail during forward. 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
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 4e3856df4..36e9eef9c 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -38,9 +38,10 @@ def _assert_async_value_check(cond: torch.Tensor, msg: str) -> None:
"""Validate a tensor condition without graph breaks or hidden device syncs.
``torch._assert_async`` keeps the check fullgraph-compilable (a Python ``if tensor: raise``
- would break the graph), but ``aten::_assert_async`` has no MPS kernel β€” the CPU fallback
- materializes ``cond`` and drains the queued stream on every call, so on MPS the check is
- skipped instead.
+ would break the graph), but materializing ``cond`` on MPS would drain the queued stream on
+ every call, so kornia skips the check there by design. The skip is this device check, not a
+ missing kernel: torch 2.5.1 had no ``aten::_assert_async`` MPS kernel, torch 2.14 registers
+ one, and the check is skipped on MPS either way.
"""
if cond.device.type == "mps":
return
@@ -275,8 +276,7 @@ def adjust_gamma(
.. note::
The non-negativity check on ``gamma``/``gain`` runs on CPU and CUDA (via ``torch._assert_async``).
- On MPS it is skipped: the op has no MPS kernel and its CPU fallback would synchronize the
- device on every call, so invalid values do not raise there.
+ kornia skips it on MPS by design, so invalid values do not raise there.
Example:
>>> x = torch.ones(1, 1, 2, 2)
@@ -365,8 +365,7 @@ def adjust_contrast(image: torch.Tensor, factor: Union[float, torch.Tensor], cli
.. note::
The non-negativity check on ``factor`` runs on CPU and CUDA (via ``torch._assert_async``).
- On MPS it is skipped: the op has no MPS kernel and its CPU fallback would synchronize the
- device on every call, so invalid values do not raise there.
+ kornia skips it on MPS by design, so invalid values do not raise there.
Example:
>>> import torch
@@ -549,9 +548,9 @@ def adjust_brightness_accumulative(
Args:
image: Image to be adjusted in the shape of :math:`(*, H, W)`.
- factor: Brightness adjust factor per element in the batch. It's recommended to
- bound the factor by [0, 1]. 0 does not modify the input image while any other
- number modify the brightness.
+ factor: Brightness factor per element in the batch. The image is multiplied by it, so ``1``
+ leaves an image in ``[0, 1]`` unchanged, ``0`` gives a black image and a factor above ``1``
+ brightens it.
clip_output: Whether to clip output to be in [0,1].
Return:
@@ -668,7 +667,7 @@ def adjust_log(image: torch.Tensor, gain: float = 1, inv: bool = False, clip_out
def _solarize(input: torch.Tensor, thresholds: Union[float, torch.Tensor] = 0.5) -> torch.Tensor:
r"""For each pixel in the image, select the pixel if the value is less than the threshold.
- Otherwise, subtract 1.0 from the pixel.
+ Otherwise, replace it with ``1.0 - value``.
Args:
input: image or batched images to solarize.
@@ -702,12 +701,15 @@ def solarize(
thresholds: Union[float, torch.Tensor] = 0.5,
additions: Optional[Union[float, torch.Tensor]] = None,
) -> torch.Tensor:
- r"""For each pixel in the image less than threshold.
+ r"""Add an amount to every pixel, clamp, then invert the pixels at or above a threshold.
.. image:: _static/img/solarize.png
- We add 'addition' amount to it and then clip the pixel value to be between 0 and 1.0.
- The value of 'addition' is between -0.5 and 0.5.
+ ``additions`` is added to the **whole** image and the sum is clamped into ``[0, 1]``; only then is each
+ pixel compared against ``thresholds``, and every pixel at or above it is replaced by ``1 - value``.
+ The addition is therefore applied on both sides of the threshold, and it can move a pixel across it:
+ with ``thresholds=0.5`` and ``additions=0.2``, ``[0.1, 0.4, 0.6, 0.9]`` comes back as
+ ``[0.3, 0.4, 0.2, 0.0]``. The value of 'addition' is between -0.5 and 0.5.
Args:
input: image torch.Tensor with shapes like :math:`(*, C, H, W)` to solarize.
@@ -723,9 +725,9 @@ def solarize(
The solarized images with shape :math:`(*, C, H, W)`.
.. note::
- The range check on ``additions`` runs on CPU and CUDA (via ``torch._assert_async``).
- On MPS it is skipped: the op has no MPS kernel and its CPU fallback would synchronize the
- device on every call, so invalid values do not raise there.
+ The range check on ``additions`` runs via ``torch._assert_async`` on the device of ``additions``.
+ kornia skips it for an ``additions`` tensor on MPS, so invalid values do not raise there, but a
+ float, or a CPU tensor, is checked on the CPU and raises for an MPS image too.
Example:
>>> x = torch.rand(1, 4, 3, 3)
@@ -787,7 +789,9 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tens
input: image torch.Tensor with shape :math:`(*, C, H, W)` to posterize.
bits: number of high bits. Must be in range [0, 8].
If int or one element torch.Tensor, input will be posterized by this bits.
- If 1-d torch.Tensor, input will be posterized element-wisely, len(bits) == input.shape[-3].
+ If 1-d torch.Tensor, input will be posterized sample-wise, len(bits) == input.shape[0]
+ -- one value per sample in the batch, not per channel; any other length raises
+ ``Batch size must be equal between bits and input``.
If n-d torch.Tensor, input will be posterized element-channel-wisely,
bits.shape == input.shape[:len(bits.shape)]
@@ -878,7 +882,9 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.
Args:
input: image torch.Tensor with shape :math:`(*, C, H, W)` to sharpen.
- factor: factor of sharpness strength. Must be above 0.
+ factor: blend factor between the smoothed copy and the input. ``0`` returns the smoothed image,
+ ``1`` returns the input, and a factor above ``1`` sharpens. It is not validated: ``0`` and
+ negative factors are accepted and extrapolate past the smoothed image.
If float or one element torch.Tensor, input will be sharpened by the same factor across the whole batch.
If 1-d torch.Tensor, input will be sharpened element-wisely, len(factor) == len(input).
@@ -1591,9 +1597,9 @@ class AdjustBrightnessAccumulative(nn.Module):
The input image is expected to be in the range of [0, 1].
Args:
- brightness_factor: Brightness adjust factor per element
- in the batch. 0 does not modify the input image while any other number modify the
- brightness.
+ brightness_factor: Brightness factor per element in the batch. The image is multiplied by it and
+ clamped into ``[0, 1]``, so ``1`` leaves an image in ``[0, 1]`` unchanged, ``0`` gives a black image
+ and a factor above ``1`` brightens it.
Shape:
- Input: Image/Input to be adjusted in the shape of :math:`(*, N)`.
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 8149e0558..177fc2377 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -86,14 +86,14 @@ def gaussian(
Args:
window_size: the size which drives the filter amount.
- sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`
- mean: Mean of the Gaussian function (center). If not provided, it defaults to window_size // 2.
- If a tensor, should be in a shape :math:`(B, 1)`
+ sigma: gaussian standard deviation. If a tensor, should be in a shape :math:`(B, 1)`.
+ mean: Mean of the Gaussian function (center). If not provided, it defaults to
+ ``window_size // 2``. If a tensor, should be in a shape :math:`(B, 1)`.
device: This value will be used if sigma is a float. Device desired to compute.
dtype: This value will be used if sigma is a float. Dtype desired for compute.
Returns:
- A tensor withshape :math:`(B, \text{kernel_size})`, with Gaussian values.
+ A tensor with shape :math:`(B, \text{kernel_size})`, with Gaussian values.
"""
if isinstance(sigma, float):
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index 35e2f304f..ce0e0261c 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -5338,7 +5338,7 @@ class TestRandomSnow(BaseTester):
def _get_exception_test_data(self, device, dtype):
err_msg_sw_coef = "Snow coefficient values must be between 0 and 1."
- err_msg_brght_coef = "Brightness values must be greater than 1."
+ err_msg_brght_coef = "Brightness values must be 1 or greater."
err_msg_wrong_ch = "Number of color channels should be 3."
err_msg_wrong_sh = "Input size must have a shape of either (H, W), (C, H, W) or (*, C, H, W)."
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
new file mode 100644
index 000000000..e6a7bf2fe
--- /dev/null
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -0,0 +1,1983 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import copy
+import io
+import pickle
+
+import pytest
+import torch
+from torch.distributions import Distribution
+
+import kornia.augmentation as K
+from kornia.constants import BorderType, Resample
+from kornia.core.exceptions import BaseError, ImageError, ShapeError
+from kornia.filters import box_blur, motion_blur
+
+from testing.base import (
+ DYNAMO_UNAVAILABLE_REASON,
+ BaseTester,
+ dynamo_is_available,
+ supports_reflect_padding,
+ supports_replicate_padding,
+)
+
+
[email protected](autouse=True)
+def _restore_global_rng(restore_torch_rng):
+ # Every pin below seeds the global RNG so its draw is reproducible. ``torch.manual_seed`` also
+ # reseeds the CUDA and MPS generators, so the root fixture (#4446) snapshots and restores all of
+ # them; ``fork_rng(devices=[])`` would restore the CPU generator only and shift the draw of an
+ # unseeded later test on an accelerator leg.
+ yield
+
+
+# The seed drawn immediately before each construct-and-forward, as the audit probe did it.
+_FORWARD_SEED = 0
+_FIXTURE_SEED = 1234
+
+
+def _sync(device) -> None:
+ # MPS dispatches asynchronously, so a kernel error raised by the forward under test would
+ # otherwise surface inside an unrelated later test.
+ if device.type == "mps":
+ torch.mps.synchronize()
+
+
+def _lit_extent(plane: torch.Tensor, threshold: float = 1e-3) -> tuple[list[int], list[int]]:
+ """Return the sorted distinct rows and columns of a single ``(H, W)`` plane above ``threshold``."""
+ indices = (plane.float().abs() > threshold).nonzero()
+ return sorted({int(row) for row, _ in indices}), sorted({int(col) for _, col in indices})
+
+
+def _impulse(device, dtype, height: int = 7, width: int = 9, row: int = 2, col: int = 3) -> torch.Tensor:
+ """A non-square zero image with a single 1.0 off both centre lines (7x9 centres are row 3, col 4)."""
+ image = torch.zeros(1, 1, height, width, device=device, dtype=dtype)
+ image[0, 0, row, col] = 1.0
+ return image
+
+
+class TestBlurConventions(BaseTester):
+ # Row 6c-19: ``kernel_size`` is ``(kH, kW)`` -- the first entry counts rows, the second counts
+ # columns -- for RandomBoxBlur and RandomGaussianBlur alike, matching kornia.filters.box_blur
+ # and gaussian_blur2d. The claim is a labelling, so it is also checked under relabelling: the
+ # transposed image blurred with the transposed kernel gives the transposed support.
+ # Snippet used to generate expected:
+ # x = torch.zeros(1, 1, 7, 9); x[0, 0, 3, 4] = 1.0
+ # for ks in ((1, 5), (5, 1)):
+ # torch.manual_seed(0); y = K.RandomBoxBlur(ks, p=1.0)(x)
+ # print(ks, (y[0, 0] > 0).nonzero().T.tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `(1, 5)` lights rows [3] cols [2, 3, 4, 5, 6] and
+ # `(5, 1)` rows [1, 2, 3, 4, 5] col [4], identically for RandomGaussianBlur; with the impulse
+ # moved off the centre lines to (2, 3) the same run gives rows [2] cols [1..5] and rows [0..4]
+ # col [3], and on the transposed 9x7 image rows [1..5] col [2] and row [3] cols [0..4].
+ @pytest.mark.parametrize("name", ["RandomBoxBlur", "RandomGaussianBlur"])
+ def test_convention_blur_kernel_size_is_height_then_width(self, device, dtype, name):
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ factories = {
+ "RandomBoxBlur": lambda ks: K.RandomBoxBlur(ks, p=1.0),
+ "RandomGaussianBlur": lambda ks: K.RandomGaussianBlur(ks, (1.0, 1.0), p=1.0),
+ }
+ make = factories[name]
+
+ # The audit's own fixture, hot pixel on the 7x9 centre.
+ centred = _impulse(device, dtype, row=3, col=4)
+ torch.manual_seed(_FORWARD_SEED)
+ assert _lit_extent(make((1, 5))(centred)[0, 0]) == ([3], [2, 3, 4, 5, 6])
+ torch.manual_seed(_FORWARD_SEED)
+ assert _lit_extent(make((5, 1))(centred)[0, 0]) == ([1, 2, 3, 4, 5], [4])
+
+ # The same claim with the impulse off both centre lines, so no literal is its own transpose.
+ image = _impulse(device, dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ assert _lit_extent(make((1, 5))(image)[0, 0]) == ([2], [1, 2, 3, 4, 5])
+ torch.manual_seed(_FORWARD_SEED)
+ assert _lit_extent(make((5, 1))(image)[0, 0]) == ([0, 1, 2, 3, 4], [3])
+
+ # Relabelling check: transpose the image and the kernel, and the support transposes too.
+ transposed = image.transpose(-1, -2).contiguous()
+ assert transposed.shape[-2:] == (9, 7)
+ torch.manual_seed(_FORWARD_SEED)
+ assert _lit_extent(make((5, 1))(transposed)[0, 0]) == ([1, 2, 3, 4, 5], [2])
+ torch.manual_seed(_FORWARD_SEED)
+ assert _lit_extent(make((1, 5))(transposed)[0, 0]) == ([3], [0, 1, 2, 3, 4])
+
+ # Row 6c-19, the median half: a rank filter cannot be read off an impulse, so the detector is a
+ # one-row bar. A (1, kW) window slides along that row and keeps it; a (kH, 1) window spans five
+ # rows of which four are zero, so the median is zero and the bar is erased. Checked under
+ # relabelling on the transposed bar.
+ # Snippet used to generate expected:
+ # bar = torch.zeros(1, 1, 7, 9); bar[0, 0, 3, :] = 1.0
+ # for ks in ((1, 5), (5, 1)):
+ # torch.manual_seed(0); print(ks, K.RandomMedianBlur(ks, p=1.0)(bar)[0, 0].sum(-1).tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `(1, 5)` keeps row sums
+ # [0, 0, 0, 9, 0, 0, 0] and `(5, 1)` gives [0, 0, 0, 0, 0, 0, 0]; with the bar on row 2 the
+ # surviving sum moves to index 2, and on the transposed 9x7 bar the roles of the two kernels swap.
+ def test_convention_median_blur_border_median_is_over_zero_padding(self, device, dtype):
+ # A constant-ones image: the 3x3 window at a corner holds 5 zeros and 4 ones, so the corner comes
+ # back 0 while an edge pixel (3 zeros, 6 ones) stays 1. Replicate padding would return 1 at both.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); y = K.RandomMedianBlur((3, 3), p=1.0)(torch.ones(1, 1, 4, 4)); print(y[0, 0, 0, :2])
+ # torch.manual_seed(0); print(K.RandomMedianBlur((5, 5), p=1.0)(torch.ones(1, 1, 6, 6))[0, 0, 0])
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> `[0., 1.]`; `[0., 0., 1., 1., 0., 0.]`.
+ ones = torch.ones(1, 1, 4, 4, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomMedianBlur((3, 3), p=1.0)(ones)
+ assert float(out[0, 0, 0, 0]) == 0.0 and float(out[0, 0, 0, 1]) == 1.0
+ assert float(out[0, 0, 1, 1]) == 1.0
+ # 5x5 on a 6x6 image: the top row's window holds 3 image rows, so 15 ones at columns 2 and 3
+ # (median 1) but 12 at columns 1 and 4 and 9 at the corners (median 0).
+ torch.manual_seed(_FORWARD_SEED)
+ wide = K.RandomMedianBlur((5, 5), p=1.0)(torch.ones(1, 1, 6, 6, device=device, dtype=dtype))
+ self.assert_close(wide[0, 0, 0], ones.new_tensor([0.0, 0.0, 1.0, 1.0, 0.0, 0.0]))
+
+ def test_convention_box_blur_even_kernel_is_accepted_and_off_centre(self, device, dtype):
+ # Snippet used to generate expected:
+ # imp = torch.zeros(1, 1, 7, 9); imp[0, 0, 3, 4] = 1.0
+ # for ks in ((2, 2), (4, 4), (3, 4)):
+ # torch.manual_seed(0); nz = K.RandomBoxBlur(ks, p=1.0)(imp)[0, 0].nonzero()
+ # print(ks, nz[:, 0].unique().tolist(), nz[:, 1].unique().tolist())
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> `[2, 3] [3, 4]`, `[1, 2, 3, 4] [2, 3, 4, 5]`,
+ # `[2, 3, 4] [2, 3, 4, 5]`; each output sums to 1.
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ impulse = torch.zeros(1, 1, 7, 9, device=device, dtype=dtype)
+ impulse[0, 0, 3, 4] = 1.0
+ for kernel_size, rows, cols in (
+ ((2, 2), [2, 3], [3, 4]),
+ ((4, 4), [1, 2, 3, 4], [2, 3, 4, 5]),
+ ((3, 4), [2, 3, 4], [2, 3, 4, 5]),
+ ):
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomBoxBlur(kernel_size, p=1.0)(impulse)
+ lit = out[0, 0].nonzero()
+ assert lit[:, 0].unique().tolist() == rows and lit[:, 1].unique().tolist() == cols
+ self.assert_close(out.sum(), impulse.sum())
+
+ def test_convention_median_blur_kernel_size_is_height_then_width(self, device, dtype):
+ bar = torch.zeros(1, 1, 7, 9, device=device, dtype=dtype)
+ bar[0, 0, 3, :] = 1.0
+ torch.manual_seed(_FORWARD_SEED)
+ self.assert_close(K.RandomMedianBlur((1, 5), p=1.0)(bar)[0, 0].sum(-1), bar.new_tensor([0, 0, 0, 9, 0, 0, 0]))
+ torch.manual_seed(_FORWARD_SEED)
+ self.assert_close(K.RandomMedianBlur((5, 1), p=1.0)(bar)[0, 0].sum(-1), bar.new_zeros(7))
+
+ # Off the centre row, and then transposed, so the surviving axis is not a symmetry of the fixture.
+ off_centre = torch.zeros(1, 1, 7, 9, device=device, dtype=dtype)
+ off_centre[0, 0, 2, :] = 1.0
+ torch.manual_seed(_FORWARD_SEED)
+ kept = K.RandomMedianBlur((1, 5), p=1.0)(off_centre)[0, 0].sum(-1)
+ self.assert_close(kept, off_centre.new_tensor([0, 0, 9, 0, 0, 0, 0]))
+ transposed = off_centre.transpose(-1, -2).contiguous()
+ torch.manual_seed(_FORWARD_SEED)
+ kept_t = K.RandomMedianBlur((5, 1), p=1.0)(transposed)[0, 0].sum(-2)
+ self.assert_close(kept_t, transposed.new_tensor([0, 0, 9, 0, 0, 0, 0]))
+ torch.manual_seed(_FORWARD_SEED)
+ self.assert_close(K.RandomMedianBlur((1, 5), p=1.0)(transposed)[0, 0].sum(-2), transposed.new_zeros(7))
+ # An even entry is constructed and then fails on any image size, as a raw reshape error
+ # (`shape '[2, 3, 16, 32, 32]' is invalid`, measured on cpu in all four dtypes and on mps float32).
+ torch.manual_seed(_FORWARD_SEED)
+ even = K.RandomMedianBlur((4, 4), p=1.0)
+ large = torch.rand(2, 3, 32, 32).to(device=device, dtype=dtype)
+ with pytest.raises(RuntimeError, match="is invalid for input of size"):
+ _sync(even(large).device)
+ # Below the kernel the zero-padded image is too small for F.conv2d, which raises before the view:
+ # the claim is "raises for every image", not "raises the same error for every image".
+ small = torch.rand(2, 3, 1, 1).to(device=device, dtype=dtype)
+ with pytest.raises(RuntimeError, match="Kernel size can't be greater than actual input size"):
+ _sync(even(small).device)
+
+ # Row 6c-20 (issue #4433, closed by #4486, which documents the mapping): RandomBoxBlur's
+ # ``normalized`` flag is not a normalization switch -- it is forwarded as box_blur's
+ # ``separable`` argument. Both branches are means, so a constant image survives both and the
+ # two outputs differ only by float rounding.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, 3, 7, 9)
+ # torch.manual_seed(0); yt = K.RandomBoxBlur((3, 3), normalized=True, p=1.0)(x)
+ # torch.manual_seed(0); yf = K.RandomBoxBlur((3, 3), normalized=False, p=1.0)(x)
+ # print(torch.equal(yt, box_blur(x, (3, 3), "reflect", separable=True)),
+ # torch.equal(yf, box_blur(x, (3, 3), "reflect", separable=False)), (yt - yf).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `True True 1.19209e-07`, and
+ # `"normalized" in inspect.signature(box_blur).parameters` is False.
+ def test_convention_random_box_blur_normalized_selects_separable_box_blur(self, device, dtype):
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 7, 9).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ separable = K.RandomBoxBlur((3, 3), normalized=True, p=1.0)(image)
+ torch.manual_seed(_FORWARD_SEED)
+ joint = K.RandomBoxBlur((3, 3), normalized=False, p=1.0)(image)
+ assert torch.equal(separable, box_blur(image, (3, 3), "reflect", separable=True))
+ assert torch.equal(joint, box_blur(image, (3, 3), "reflect", separable=False))
+ assert not torch.equal(separable, box_blur(image, (3, 3), "reflect", separable=False))
+ # Both branches are the same mean, so they agree to float rounding.
+ self.assert_close(separable, joint)
+ # A mean leaves a constant image alone; a sum would multiply it by nine.
+ constant = torch.full((2, 3, 7, 9), 0.375, device=device, dtype=dtype)
+ for normalized in (True, False):
+ torch.manual_seed(_FORWARD_SEED)
+ self.assert_close(K.RandomBoxBlur((3, 3), normalized=normalized, p=1.0)(constant), constant)
+
+ # Row 6c-21: RandomGaussianBlur draws one sigma per sample -- ``_params["sigma"]`` is a (B,)
+ # tensor, not one value for the batch and not a per-axis pair -- and the class defaults repeat
+ # gaussian_blur2d's own (``separable=True``, ``border_type=BorderType.REFLECT``).
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(4, 3, 7, 9)
+ # aug = K.RandomGaussianBlur((3, 3), (0.5, 1.5), p=1.0)
+ # torch.manual_seed(0); aug(x); print(aug._params["sigma"].shape, aug._params["sigma"].tolist(), aug.flags)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `torch.Size([4])`, `[0.996257, 1.268222, 0.588477,
+ # 0.632030]`, `{'kernel_size': (3, 3), 'separable': True, 'border_type': <BorderType.REFLECT: 1>}`.
+ def test_convention_random_gaussian_blur_draws_one_sigma_per_sample(self, device, dtype):
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(4, 3, 7, 9).to(device=device, dtype=dtype)
+ aug = K.RandomGaussianBlur((3, 3), (0.5, 1.5), p=1.0)
+ torch.manual_seed(_FORWARD_SEED)
+ aug(image)
+ sigma = aug._params["sigma"]
+ assert sigma.shape == (4,)
+ assert len(set(sigma.flatten().tolist())) == 4
+ assert float(sigma.min()) >= 0.5 and float(sigma.max()) <= 1.5
+ # Reach, not only containment: a draw shrunk to `[0.5, 0.6]` satisfies the bounds above.
+ torch.manual_seed(_FORWARD_SEED)
+ many = aug.forward_parameters((256, 3, 7, 9))["sigma"]
+ assert float(many.min()) < 0.6 and float(many.max()) > 1.4
+ assert aug.flags["separable"] is True
+ assert aug.flags["border_type"] == BorderType.REFLECT
+ assert aug.flags["kernel_size"] == (3, 3)
+
+ # One parameter away: same_on_batch collapses the same key to a single repeated value.
+ shared = K.RandomGaussianBlur((3, 3), (0.5, 1.5), p=1.0, same_on_batch=True)
+ torch.manual_seed(_FORWARD_SEED)
+ shared(image)
+ assert len(set(shared._params["sigma"].flatten().tolist())) == 1
+
+ # Row 6c-21: an even kernel_size is rejected rather than silently rounded, with the message
+ # gaussian_blur2d's own kernel check raises.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); K.RandomGaussianBlur((2, 2), (1.0, 1.0), p=1.0)(torch.rand(4, 3, 7, 9))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `kornia.core.exceptions.BaseError: Kernel size must
+ # be an odd integer bigger than 0. Gotcha 2 on (2, 2)`.
+ def test_convention_random_gaussian_blur_rejects_even_kernel_size(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(4, 3, 7, 9).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(Exception, match="odd integer"):
+ _sync(K.RandomGaussianBlur((2, 2), (1.0, 1.0), p=1.0)(image).device)
+
+ # Row 6c-22: RandomMotionBlur's ``angle`` is counter-clockwise as the image is displayed. The
+ # fixture is a 7x9 impulse at (row 2, col 3), off both centre lines, so no literal below is its
+ # own transpose: +45 deg carries the blur from (row 3, col 2) up to (row 1, col 4), and -45 deg
+ # down and to the right.
+ # Snippet used to generate expected:
+ # x = torch.zeros(1, 1, 7, 9); x[0, 0, 2, 3] = 1.0
+ # for a in (0.0, 45.0, -45.0, 90.0):
+ # torch.manual_seed(0)
+ # print(a, (K.RandomMotionBlur(5, (a, a), (0.0, 0.0), p=1.0)(x)[0, 0].abs() > 1e-6).nonzero().tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0.0 [[2, 1], [2, 2], [2, 3], [2, 4], [2, 5]]`,
+ # `45.0 [[1, 4], [2, 3], [3, 2]]`, `-45.0 [[1, 2], [2, 3], [3, 4]]`,
+ # `90.0 [[0, 3], [1, 3], [2, 3], [3, 3], [4, 3]]`.
+ @pytest.mark.parametrize(
+ ("angle", "support"),
+ [
+ (0.0, [(2, 1), (2, 2), (2, 3), (2, 4), (2, 5)]),
+ (45.0, [(1, 4), (2, 3), (3, 2)]),
+ (-45.0, [(1, 2), (2, 3), (3, 4)]),
+ (90.0, [(0, 3), (1, 3), (2, 3), (3, 3), (4, 3)]),
+ ],
+ )
+ def test_convention_random_motion_blur_angle_is_counter_clockwise(self, device, dtype, angle, support):
+ image = _impulse(device, dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomMotionBlur(5, (angle, angle), (0.0, 0.0), p=1.0)(image)
+ lit = [(int(row), int(col)) for row, col in (out[0, 0].float().abs() > 1e-6).nonzero()]
+ assert sorted(lit) == support
+
+ # Row 6c-23: ``direction`` re-weights the kernel along the kernel's own axis, whichever axis
+ # ``angle`` selected -- -1 piles the weight at the start of the sweep, +1 at the end, 0 is
+ # uniform. Read on two orientations so the claim is not an artefact of one axis.
+ # Snippet used to generate expected:
+ # x = torch.zeros(1, 1, 7, 9); x[0, 0, 2, 3] = 1.0
+ # for d in (-1.0, 0.0, 1.0):
+ # torch.manual_seed(0); print(K.RandomMotionBlur(5, (0.0, 0.0), (d, d), p=1.0)(x)[0, 0, 2].tolist())
+ # torch.manual_seed(0); print(K.RandomMotionBlur(5, (90.0, 90.0), (d, d), p=1.0)(x)[0, 0, :, 3].tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> angle 0: `[0, .4, .3, .2, .1, 0, 0, 0, 0]`,
+ # `[0, .2, .2, .2, .2, .2, 0, 0, 0]`, `[0, 0, .1, .2, .3, .4, 0, 0, 0]`; angle 90:
+ # `[0, .1, .2, .3, .4, 0, 0]`, `[.2, .2, .2, .2, .2, 0, 0]`, `[.4, .3, .2, .1, 0, 0, 0]`.
+ @pytest.mark.parametrize(
+ ("direction", "along_row", "along_col"),
+ [
+ (-1.0, [0.0, 0.4, 0.3, 0.2, 0.1, 0.0, 0.0, 0.0, 0.0], [0.0, 0.1, 0.2, 0.3, 0.4, 0.0, 0.0]),
+ (0.0, [0.0, 0.2, 0.2, 0.2, 0.2, 0.2, 0.0, 0.0, 0.0], [0.2, 0.2, 0.2, 0.2, 0.2, 0.0, 0.0]),
+ (1.0, [0.0, 0.0, 0.1, 0.2, 0.3, 0.4, 0.0, 0.0, 0.0], [0.4, 0.3, 0.2, 0.1, 0.0, 0.0, 0.0]),
+ ],
+ )
+ def test_convention_random_motion_blur_direction_weights_the_kernel_axis(
+ self, device, dtype, direction, along_row, along_col
+ ):
+ image = _impulse(device, dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ horizontal = K.RandomMotionBlur(5, (0.0, 0.0), (direction, direction), p=1.0)(image)
+ self.assert_close(horizontal[0, 0, 2], image.new_tensor(along_row))
+ torch.manual_seed(_FORWARD_SEED)
+ vertical = K.RandomMotionBlur(5, (90.0, 90.0), (direction, direction), p=1.0)(image)
+ self.assert_close(vertical[0, 0, :, 3], image.new_tensor(along_col))
+
+ # Row 6c-24, the rotation half of `direction`: the weights are laid on a horizontal line and then
+ # rotated with `resample`, and a "nearest" rotation off the axes drops taps, so the line's length and
+ # its end weights change with the angle -- at 45 degrees and direction +1 the five taps become three.
+ # Snippet used to generate expected:
+ # x = torch.zeros(1, 1, 9, 9); x[0, 0, 4, 4] = 1.0
+ # for angle in (0.0, 45.0):
+ # torch.manual_seed(0); y = K.RandomMotionBlur(5, (angle, angle), (1.0, 1.0), p=1.0)(x)
+ # print(angle, sorted(y[y > 0].tolist()))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0.0 [0.1, 0.2, 0.3, 0.4]` (the weight-0 end tap is empty)
+ # and `45.0 [0.1667, 0.3333, 0.5]`; the impulse response is the kernel, so these are its taps.
+ def test_convention_random_motion_blur_nearest_rotation_resamples_the_taps(self, device, dtype):
+ image = _impulse(device, dtype, height=9, width=9, row=4, col=4)
+ taps = {}
+ for angle in (0.0, 45.0):
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomMotionBlur(5, (angle, angle), (1.0, 1.0), p=1.0)(image)
+ taps[angle] = out[out.abs() > 1e-3].sort().values
+ self.assert_close(taps[0.0], image.new_tensor([0.1, 0.2, 0.3, 0.4]))
+ self.assert_close(taps[45.0], image.new_tensor([1.0, 2.0, 3.0]) / 6.0)
+
+ # Row 6c-24: RandomMotionBlur keeps kornia.filters.motion_blur's defaults, so the class does not
+ # quietly change the padding or the interpolation of the kernel rotation.
+ # Snippet used to generate expected:
+ # aug = K.RandomMotionBlur(3, (45.0, 45.0), (0.0, 0.0), p=1.0); print(aug.flags)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `{'border_type': <BorderType.CONSTANT: 0>,
+ # 'resample': <Resample.NEAREST: 0>}`.
+ @pytest.mark.device_agnostic
+ def test_convention_random_motion_blur_defaults_are_constant_and_nearest(self):
+ aug = K.RandomMotionBlur(3, (45.0, 45.0), (0.0, 0.0), p=1.0)
+ assert aug.flags["border_type"] == BorderType.CONSTANT
+ assert aug.flags["resample"] == Resample.NEAREST
+
+ # Issue #4599: `kernel_size` is drawn once per SAMPLE and then one entry -- the one at a uniformly
+ # drawn `_params["idx"]`, not the first -- is applied to the whole batch; and because the draw is
+ # `UniformDistribution(ks[0] // 2, ks[1] // 2)` truncated with `.int()`, the range's upper bound is
+ # practically never reached. `(3, 5)` is therefore a constant 3 -- "practically": as for RandomRain
+ # below, the float32 draw rounds onto the bound about once in 2**24 (seed 204 draws one 5 in 50000),
+ # so the pin is that the bound is vanishingly rare, not impossible.
+ # Snippet used to generate expected:
+ # import collections
+ # for ks in ((3, 5), (3, 7), (5, 11)):
+ # torch.manual_seed(0)
+ # v = K.RandomMotionBlur(ks, (0., 0.), (0., 0.), p=1.).forward_parameters((20000, 1, 8, 8))
+ # print(ks, sorted(collections.Counter(v["ksize_factor"].tolist())))
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `[3]`, `[3, 5]`, `[5, 7, 9]`; `idx` over 400 seeds at
+ # B = 6 lands on every row (`{0: 67, 1: 71, 2: 66, 3: 57, 4: 83, 5: 56}`).
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(("kernel_size", "drawn"), [((3, 5), [3]), ((3, 7), [3, 5]), ((5, 11), [5, 7, 9])])
+ def test_wart_random_motion_blur_upper_bound_is_never_drawn_4599(self, kernel_size, drawn):
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomMotionBlur(kernel_size, (0.0, 0.0), (0.0, 0.0), p=1.0)
+ factors = aug.forward_parameters((20000, 1, 8, 8))["ksize_factor"]
+ assert sorted(set(factors[factors != kernel_size[1]].tolist())) == drawn
+ # The requested upper bound is odd and admissible, and it is practically absent: at most a rounding
+ # handful of 20000 draws, where a uniform draw over the odd sizes would give thousands.
+ assert kernel_size[1] % 2 == 1 and kernel_size[1] not in drawn
+ assert int((factors == kernel_size[1]).sum()) < 5
+
+ # Issue #4599, the other half: the per-sample draw is real, and a random index selects which one
+ # the batch gets -- so `_params["ksize_factor"]` holds B different values while one kernel is used.
+ @pytest.mark.device_agnostic
+ def test_wart_random_motion_blur_applies_one_randomly_indexed_kernel_size_4599(self):
+ picked = set()
+ distinct = 0
+ for seed in range(64):
+ torch.manual_seed(seed)
+ params = K.RandomMotionBlur((3, 21), (0.0, 0.0), (0.0, 0.0), p=1.0).forward_parameters((6, 3, 8, 8))
+ assert params["ksize_factor"].shape == (6,)
+ assert params["idx"].shape == (1,)
+ picked.add(int(params["idx"][0]))
+ distinct += len(set(params["ksize_factor"].tolist())) > 1
+ # Every row of the batch can be the one applied, so it is not "the first sample's".
+ assert picked == set(range(6))
+ # And the draw really is per sample: a constant `ksize_factor` would make `idx` immaterial.
+ assert distinct > 60
+ # The kernel that is applied is the one at `idx`, not the first sample's: `_params` alone cannot
+ # see that (`kernel_size_list[0]` in apply_transform left this pin green), so compare the output
+ # with the functional at `ksize_factor[idx]` on seeds where that differs from `ksize_factor[0]`.
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(6, 3, 8, 8)
+ checked = 0
+ for seed in range(8):
+ torch.manual_seed(seed)
+ aug = K.RandomMotionBlur((3, 21), (-45.0, 45.0), (-1.0, 1.0), p=1.0)
+ out = aug(image)
+ params = aug._params
+ idx = int(params["idx"][0])
+ applied, first = int(params["ksize_factor"][idx]), int(params["ksize_factor"][0])
+ reference = motion_blur(
+ image,
+ applied,
+ params["angle_factor"],
+ params["direction_factor"],
+ border_type="constant",
+ mode="nearest",
+ )
+ assert torch.equal(out, reference)
+ if applied != first:
+ assert not torch.equal(
+ out,
+ motion_blur(
+ image,
+ first,
+ params["angle_factor"],
+ params["direction_factor"],
+ border_type="constant",
+ mode="nearest",
+ ),
+ )
+ checked += 1
+ assert checked >= 3
+
+ # Row 6c-24, the resampling caveat: the kernel's weights are laid on a line and then rotated, so
+ # with ``border_type="reflect"`` a "nearest" or "bilinear" rotation keeps them non-negative and the
+ # output inside the input's extremes, while "bicubic" gives the kernel negative lobes that overshoot
+ # both extremes at an edge.
+ # Snippet used to generate expected:
+ # x = torch.zeros(1, 1, 15, 15); x[..., 7:] = 1.0
+ # for rs in ("nearest", "bilinear", "bicubic"):
+ # torch.manual_seed(0)
+ # aug = K.RandomMotionBlur(5, (80., 80.), (1., 1.), border_type="reflect", resample=rs, p=1.)
+ # print(rs, aug(x).aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu and mps float32) -> `0 / 1`, `0 / 1`, `-0.0573 / 1.0285`.
+ def test_convention_random_motion_blur_reflect_bound_depends_on_resample(self, device, dtype):
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ edge = torch.zeros(1, 1, 15, 15, device=device, dtype=dtype)
+ edge[..., 7:] = 1.0
+ for resample in ("nearest", "bilinear"):
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomMotionBlur(5, (80.0, 80.0), (1.0, 1.0), border_type="reflect", resample=resample, p=1.0)(edge)
+ assert float(out.min()) >= -1e-3 and float(out.max()) <= 1.0 + 1e-3, resample
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomMotionBlur(5, (80.0, 80.0), (1.0, 1.0), border_type="reflect", resample="bicubic", p=1.0)(edge)
+ assert float(out.min()) < -0.02 and float(out.max()) > 1.02
+
+ # The four filters do not clamp their result. A 1.1 impulse is nevertheless attenuated below
+ # one by each supported kernel, while median blur erases this isolated impulse altogether. The
+ # half-amplitude and negative legs make the range observation a property of the filters rather
+ # than an implicit clamp in the augmentation wrapper.
+ @pytest.mark.parametrize("name", ["RandomBoxBlur", "RandomGaussianBlur", "RandomMedianBlur", "RandomMotionBlur"])
+ def test_convention_filters_attenuate_an_out_of_range_impulse_without_clamping(self, device, dtype, name):
+ if name in ("RandomBoxBlur", "RandomGaussianBlur") and not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ factories = {
+ "RandomBoxBlur": lambda: K.RandomBoxBlur((3, 3), p=1.0),
+ "RandomGaussianBlur": lambda: K.RandomGaussianBlur((3, 3), (1.0, 1.0), p=1.0),
+ "RandomMedianBlur": lambda: K.RandomMedianBlur((3, 3), p=1.0),
+ "RandomMotionBlur": lambda: K.RandomMotionBlur(3, (0.0, 0.0), (0.0, 0.0), p=1.0),
+ }
+ make = factories[name]
+
+ impulse = torch.zeros(1, 1, 7, 7, device=device, dtype=dtype)
+ impulse[0, 0, 3, 3] = 1.1
+ out = make()(impulse)
+ assert float(out.min()) >= 0.0
+ assert float(out.max()) <= 1.0
+
+ if name == "RandomMedianBlur":
+ self.assert_close(out, torch.zeros_like(out))
+ # The linearity legs below are unreachable for median blur, so this branch carried no
+ # evidence against a clamp at all: appending `.clamp(0, 1)` to its apply_transform leaves it
+ # green. A negative plateau has a negative median and must come back negative.
+ negative = torch.full((1, 1, 7, 7), -0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ assert float(make()(negative).min()) < -0.4, "the wrapper clamped the median into [0, 1]"
+ return
+
+ half_impulse = impulse * 0.5
+ self.assert_close(out, make()(half_impulse) * 2.0)
+ self.assert_close(make()(-half_impulse), -make()(half_impulse))
+
+ # Issue #4559: RandomBoxBlur, RandomGaussianBlur and RandomSharpness let a raw torch error out
+ # when the image is smaller than the kernel along an axis, instead of raising a kornia error that
+ # names the kernel and the shape. The two blurs reflect-pad, so they fail as soon as an axis is
+ # no longer than the kernel radius (`k // 2`, one pixel for the 3x3 default); RandomSharpness
+ # convolves without padding, so it needs the full 3x3.
+ # RandomMedianBlur and RandomMotionBlur accept the same degenerate image, which is what makes the
+ # split a defect rather than a package-wide rule. #4559 leaves two coherent outcomes open (raise
+ # a named kornia error, or pad and run), so this is a wart pin on today's behavior, not a strict
+ # xfail on a settled contract.
+ # Snippet used to generate expected:
+ # for shape in ((2, 3, 1, 8), (2, 3, 2, 2), (2, 3, 3, 3)):
+ # x = torch.rand(*shape)
+ # torch.manual_seed(0); K.RandomBoxBlur(p=1.0)(x) # and the four other classes
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> on (2, 3, 1, 8) the two blurs raise `RuntimeError:
+ # Argument #6: Padding size should be less than the corresponding input dimension, but got:
+ # padding (1, 1) at dimension 2 of input [2, 3, 1, 8]` and RandomSharpness `RuntimeError:
+ # Calculated padded input size per channel: (1 x 8). Kernel size: (3 x 3). Kernel size can't be
+ # greater than actual input size`; on (2, 3, 2, 2) only RandomSharpness raises; on (2, 3, 3, 3)
+ # all five run; RandomMedianBlur and RandomMotionBlur run on every shape.
+ def test_wart_blur_and_sharpness_reject_images_smaller_than_kernel_4559(self, device, dtype):
+ # The skip is scoped to the legs that actually reflect-pad. RandomSharpness fails through
+ # F.conv2d, and RandomMedianBlur and RandomMotionBlur run on a 1x8 image with no reflect padding
+ # at all, so skipping the whole test where reflection_pad2d is missing -- the torch 2.5.1 float16
+ # leg -- would drop three legs of #4559 for a reason that does not apply to them.
+ reflect_ok = supports_reflect_padding(device, dtype)
+ torch.manual_seed(_FIXTURE_SEED)
+ thin = torch.rand(2, 3, 1, 8).to(device=device, dtype=dtype)
+ small = torch.rand(2, 3, 2, 2).to(device=device, dtype=dtype)
+ square = torch.rand(2, 3, 3, 3).to(device=device, dtype=dtype)
+ blurs = {
+ "RandomBoxBlur": lambda: K.RandomBoxBlur(p=1.0),
+ "RandomGaussianBlur": lambda: K.RandomGaussianBlur((3, 3), (1.0, 1.0), p=1.0),
+ }
+ for name, make in blurs.items():
+ if not reflect_ok:
+ continue
+ torch.manual_seed(_FORWARD_SEED)
+ # The message is torch's reflect-padding guard, identical on cpu and mps and in every
+ # dtype (measured); a kornia-named error would not be a RuntimeError at all, since
+ # BaseError derives straight from Exception.
+ with pytest.raises(RuntimeError, match="Padding size should be less"):
+ _sync(make()(thin).device)
+ torch.manual_seed(_FORWARD_SEED)
+ assert make()(small).shape == small.shape, f"{name} should still accept a 2x2 image"
+ # The threshold is per axis, half the kernel's extent along that axis: a (7, 3) kernel runs on a
+ # 2-column image (2 > 3 // 2) and raises on a 3-row one (3 <= 7 // 2), in both classes (measured on
+ # cpu in all four dtypes and on mps float32).
+ rectangular = {
+ "RandomBoxBlur": lambda: K.RandomBoxBlur((7, 3), p=1.0),
+ "RandomGaussianBlur": lambda: K.RandomGaussianBlur((7, 3), (1.0, 1.0), p=1.0),
+ }
+ narrow = torch.rand(2, 3, 20, 2).to(device=device, dtype=dtype)
+ short = torch.rand(2, 3, 3, 20).to(device=device, dtype=dtype)
+ for make in rectangular.values():
+ if not reflect_ok:
+ continue
+ torch.manual_seed(_FORWARD_SEED)
+ assert make()(narrow).shape == narrow.shape
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(RuntimeError, match="Padding size should be less"):
+ _sync(make()(short).device)
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(RuntimeError, match="Kernel size can't be greater"):
+ _sync(K.RandomSharpness(1.0, p=1.0)(small).device)
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.RandomSharpness(1.0, p=1.0)(square).shape == square.shape
+ # The two rank/kernel-rotation filters accept the same one-row image, so the failure is not
+ # a package-wide "kernel larger than image" rule.
+ for make in (lambda: K.RandomMedianBlur(p=1.0), lambda: K.RandomMotionBlur(3, (45.0, 45.0), (0.0, 0.0), p=1.0)):
+ torch.manual_seed(_FORWARD_SEED)
+ assert make()(thin).shape == thin.shape
+
+ # Issue #4559, the same family one border type over: ``border_type="circular"`` has a padding
+ # failure of its own. torch's circular pad refuses to wrap more than once, so it raises as soon
+ # as the kernel radius (kernel_size // 2) exceeds the axis it pads -- which is a strictly smaller
+ # image than the reflect guard needs, and is why the docstrings cannot say the non-reflect border
+ # types run on every image. ``"constant"`` and ``"replicate"`` do run there. The message is
+ # torch's, not kornia's, so this is the same wart as the pin above and #4559's two outcomes
+ # (raise a named kornia error, or pad and run) leave it a wart pin rather than a strict xfail.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); one = torch.rand(2, 3, 1, 1); thin = torch.rand(2, 3, 3, 12)
+ # for bt in ("constant", "reflect", "replicate", "circular"):
+ # torch.manual_seed(0); K.RandomMotionBlur(k, (45., 45.), (0., 0.), border_type=bt, p=1.)(one)
+ # torch.manual_seed(0); K.RandomBoxBlur((9, 9), border_type=bt, p=1.)(thin)
+ # executed 2026-09-15 (torch 2.14.0, cpu float32/float64/float16/bfloat16 and mps float32, all
+ # identical) -> motion `k=5` on 1x1 and both `(9, 9)` blurs on H=3 raise `RuntimeError: Padding
+ # value causes wrapping around more than once.`, while motion `k=3` on 1x1 (radius 1, axis 1) and
+ # the `"constant"`/`"replicate"` legs return the input shape. The boundary is the radius, not the
+ # kernel: `(9, 9)` circular runs at H=4 and raises at H=3; motion `k=5` runs at 2x2.
+ def test_wart_circular_padding_rejects_images_smaller_than_kernel_radius_4559(self, device, dtype):
+ if not supports_replicate_padding(device, dtype):
+ pytest.skip("replication_pad2d is unavailable for this device/dtype")
+ torch.manual_seed(_FIXTURE_SEED)
+ one = torch.rand(2, 3, 1, 1).to(device=device, dtype=dtype)
+ thin = torch.rand(2, 3, 3, 12).to(device=device, dtype=dtype)
+
+ # Motion blur: radius 2 exceeds a 1-pixel axis and raises; radius 1 does not and runs, so
+ # the failure is the radius rather than "smaller than the kernel".
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(RuntimeError, match="wrapping around"):
+ _sync(K.RandomMotionBlur(5, (45.0, 45.0), (0.0, 0.0), border_type="circular", p=1.0)(one).device)
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.RandomMotionBlur(3, (45.0, 45.0), (0.0, 0.0), border_type="circular", p=1.0)(one).shape == one.shape
+
+ # The two padding blurs, at a kernel whose radius exceeds the short axis: circular raises
+ # where constant and replicate run, which is the pair of legs the #4559 warnings name.
+ blurs = {
+ "RandomBoxBlur": lambda border: K.RandomBoxBlur((9, 9), border_type=border, p=1.0),
+ "RandomGaussianBlur": lambda border: K.RandomGaussianBlur((9, 9), (1.0, 1.0), border_type=border, p=1.0),
+ }
+ for name, make in blurs.items():
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(RuntimeError, match="wrapping around"):
+ _sync(make("circular")(thin).device)
+ for border in ("constant", "replicate"):
+ torch.manual_seed(_FORWARD_SEED)
+ assert make(border)(thin).shape == thin.shape, f"{name} at {border} should accept a 3-row image"
+
+ # The constant-border claim is directional, and a positive fixture cannot tell "pulled toward 0" from
+ # "pulled below the minimum". On an all-negative image zero padding pushes the border ABOVE the
+ # maximum and nothing ever falls below the minimum, so both fixtures are checked.
+ # Snippet used to generate expected:
+ # neg = torch.full((1, 1, 7, 7), -1.0)
+ # torch.manual_seed(0); print(K.RandomBoxBlur((3, 3), border_type="constant", p=1.0)(neg).aminmax())
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> box max -0.4444, gaussian max -0.5270, motion max -0.6667,
+ # each with min -1.0.
+ @pytest.mark.parametrize("name", ["RandomBoxBlur", "RandomGaussianBlur", "RandomMotionBlur"])
+ def test_convention_constant_border_pulls_the_border_toward_zero(self, device, dtype, name):
+ factories = {
+ "RandomBoxBlur": lambda: K.RandomBoxBlur((3, 3), border_type="constant", p=1.0),
+ "RandomGaussianBlur": lambda: K.RandomGaussianBlur((3, 3), (1.0, 1.0), border_type="constant", p=1.0),
+ "RandomMotionBlur": lambda: K.RandomMotionBlur(3, (0.0, 0.0), (0.0, 0.0), border_type="constant", p=1.0),
+ }
+ positive = torch.full((1, 1, 7, 7), 1.0, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ positive_out = factories[name]()(positive)
+ low, high = positive_out.aminmax()
+ assert float(low) < 1.0 and float(high) <= 1.0 + 1e-3, "a positive image is pulled below its minimum"
+ negative = torch.full((1, 1, 7, 7), -1.0, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ negative_out = factories[name]()(negative)
+ low, high = negative_out.aminmax()
+ assert float(high) > -1.0, "a negative image is pulled above its maximum, not below its minimum"
+ assert float(low) >= -1.0 - 1e-3
+ # Toward *zero*, and not toward some other constant: for a kernel whose weights sum to one a
+ # border pixel is `s * x + (1 - s) * v`, so `out(+1) + out(-1)` is `2 * (1 - s) * v` and vanishes
+ # only at `v = 0`. Padding with 0.5 instead satisfies every bound above and is caught only here.
+ self.assert_close(positive_out + negative_out, torch.zeros_like(positive_out), atol=1e-6, rtol=0)
+
+
+# Twice float32(0.9): the snow coefficient is drawn in float32 whatever the image dtype, so this is the
+# red channel whose HLS lightness equals the drawn coefficient exactly in float16, bfloat16, float32 and
+# float64 alike. It is what makes the coverage comparison's `<` distinguishable from `<=`.
+_SNOW_BOUNDARY_RED = 1.7999999523162842
+
+
+class TestNoiseAndWeatherConventions(BaseTester):
+ # Row 6c-25: RandomErasing's ``scale`` is the target area fraction of the erased box -- met exactly
+ # by these two fixtures, which need no rounding -- and ``ratio`` is height / width, so ratio 2.0
+ # gives a tall box and 0.5 a wide one; the box is the half-open
+ # rectangle [ys, ys + h) x [xs, xs + w) named by ``_params``, and ``value`` is the literal fill.
+ # Snippet used to generate expected:
+ # x = torch.ones(1, 1, 10, 20)
+ # torch.manual_seed(0); aug = K.RandomErasing(scale=(0.25, 0.25), ratio=(2.0, 2.0), p=1.0); y = aug(x)
+ # print((y != 1).sum(), {k: v.flatten().tolist() for k, v in aug._params.items()})
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `50` of 200 with
+ # `{'widths': [5.0], 'heights': [10.0], 'xs': [1.0], 'ys': [0.0], 'values': [0.0]}`, and at
+ # ratio 0.5 with value 0.3 `{'widths': [10.0], 'heights': [5.0], 'values': [0.3]}`.
+ @pytest.mark.parametrize(("ratio", "value", "height", "width"), [(2.0, 0.0, 10, 5), (0.5, 0.3, 5, 10)])
+ def test_convention_random_erasing_scale_is_area_and_ratio_is_height_over_width(
+ self, device, dtype, ratio, value, height, width
+ ):
+ image = torch.ones(1, 1, 10, 20, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomErasing(scale=(0.25, 0.25), ratio=(ratio, ratio), value=value, p=1.0)
+ out = aug(image)
+ params = aug._params
+ assert int(params["heights"][0]) == height
+ assert int(params["widths"][0]) == width
+ erased = out != 1.0
+ assert int(erased.sum()) == 50 == int(0.25 * image.numel())
+ # The box is exactly [ys, ys + h) x [xs, xs + w) -- half open, so the extents are h and w.
+ rows, cols = _lit_extent(erased[0, 0].to(dtype))
+ y_start, x_start = int(params["ys"][0]), int(params["xs"][0])
+ assert rows == list(range(y_start, y_start + height))
+ assert cols == list(range(x_start, x_start + width))
+ self.assert_close(out[erased], out.new_full((50,), value))
+
+ # Row 6c-25, the rounding caveat the class block states with these numbers: the target box for
+ # scale 0.25 and ratio 3 on a 10x20 image is about 12.2 x 4.1, which is rounded to 12 x 4 and then
+ # clipped to the 10-row image, so 40 of the 50 requested pixels are erased.
+ # Snippet used to generate expected:
+ # for seed in range(200):
+ # torch.manual_seed(seed); aug = K.RandomErasing(scale=(0.25, 0.25), ratio=(3.0, 3.0), p=1.0)
+ # y = aug(torch.ones(1, 1, 10, 20)); print((y != 1).sum(), aug._params["heights"], aug._params["widths"])
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `40`, `[10.]`, `[4.]` on every one of the 200 seeds.
+ def test_convention_random_erasing_box_is_rounded_and_clipped(self, device, dtype):
+ image = torch.ones(1, 1, 10, 20, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomErasing(scale=(0.25, 0.25), ratio=(3.0, 3.0), p=1.0)
+ out = aug(image)
+ assert (int(aug._params["heights"][0]), int(aug._params["widths"][0])) == (10, 4)
+ assert int((out != 1.0).sum()) == 40
+
+ # Row 6c-25 and the 6a anchor's claim that RandomErasing erases masks: routed through
+ # AugmentationSequential with a ``mask`` data key the mask is erased in the same box, but it is
+ # filled with 0 rather than with the image's ``value``.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0)
+ # seq = K.AugmentationSequential(K.RandomErasing(scale=(0.25, 0.25), ratio=(2.0, 2.0), value=0.3, p=1.0),
+ # data_keys=["input", "mask"])
+ # oi, om = seq(torch.ones(1, 1, 10, 20), torch.ones(1, 1, 10, 20))
+ # print((oi != 1).sum(), (om != 1).sum(), sorted(set(om.flatten().tolist())))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `50 50 [0.0, 1.0]`, with the two erased index sets equal.
+ def test_convention_random_erasing_erases_the_mask_in_the_same_box(self, device, dtype):
+ image = torch.ones(1, 1, 10, 20, device=device, dtype=dtype)
+ mask = torch.ones(1, 1, 10, 20, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ pipeline = K.AugmentationSequential(
+ K.RandomErasing(scale=(0.25, 0.25), ratio=(2.0, 2.0), value=0.3, p=1.0), data_keys=["input", "mask"]
+ )
+ out_image, out_mask = pipeline(image, mask)
+ image_box = (out_image != 1.0)[0, 0]
+ mask_box = (out_mask != 1.0)[0, 0]
+ assert int(image_box.sum()) == 50
+ assert torch.equal(image_box, mask_box)
+ # The image carries `value`, the mask carries 0.
+ self.assert_close(out_image[out_image != 1.0], out_image.new_full((50,), 0.3))
+ self.assert_close(out_mask[mask_box[None, None]], out_mask.new_zeros(50))
+
+ # Row 6c-26: RandomGaussianNoise adds a draw of N(mean, std) to the image and never clamps, so a
+ # constant 0.5 leaves [0, 1] in both directions; the draw is one value per element and is
+ # recorded under ``_params["gaussian_noise"]`` with the input's shape.
+ # Snippet used to generate expected:
+ # c = torch.full((2, 3, 7, 9), 0.5)
+ # torch.manual_seed(0); aug = K.RandomGaussianNoise(mean=0.0, std=1.0, p=1.0); y = aug(c)
+ # print(y.aminmax(), aug._params["gaussian_noise"].shape)
+ # torch.manual_seed(0); print(K.RandomGaussianNoise(mean=2.0, std=0.0, p=1.0)(c).unique())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `min=-2.11332 max=4.60149`, `torch.Size([2, 3, 7, 9])`,
+ # `[2.5]`.
+ def test_convention_random_gaussian_noise_is_additive_and_unclamped(self, device, dtype):
+ constant = torch.full((2, 3, 7, 9), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomGaussianNoise(mean=0.0, std=1.0, p=1.0)
+ noisy = aug(constant)
+ assert float(noisy.min()) < 0.0
+ assert float(noisy.max()) > 1.0
+ assert aug._params["gaussian_noise"].shape == constant.shape
+ self.assert_close(noisy, constant + aug._params["gaussian_noise"].to(device=device, dtype=dtype))
+ # std=0 makes the addition exact, which is what pins `mean` as an offset and not a target.
+ torch.manual_seed(_FORWARD_SEED)
+ self.assert_close(K.RandomGaussianNoise(mean=2.0, std=0.0, p=1.0)(constant), constant + 2.0)
+
+ # Parameter fields use the normalized BCHW shape even when their CHW input is restored by
+ # ``keepdim``. Gaussian noise samples just one such field for ``same_on_batch=True`` and lets
+ # broadcasting share it with every selected sample.
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "RandomGaussianNoise",
+ "RandomGaussianIllumination",
+ "RandomLinearIllumination",
+ "RandomLinearCornerIllumination",
+ "RandomPlasmaBrightness",
+ "RandomPlasmaContrast",
+ "RandomPlasmaShadow",
+ ],
+ )
+ @pytest.mark.parametrize("keepdim", [False, True])
+ def test_convention_intensity_parameter_fields_normalize_chw_shape(self, device, dtype, name, keepdim):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(3, 7, 9).to(device=device, dtype=dtype)
+ aug, field_name, field_channels = _field_augmentation(name, keepdim=keepdim)
+ torch.manual_seed(_FORWARD_SEED)
+ out = aug(image)
+ assert out.shape == (image.shape if keepdim else (1, *image.shape))
+ assert aug._params[field_name].shape == (1, field_channels, *image.shape[-2:])
+ assert torch.equal(out, aug(image, params=aug._params))
+
+ # At a partial probability the stored field keeps the original batch length, rather than being
+ # compacted to the selected rows. ``batch_prob`` identifies which rows were transformed; the
+ # remaining rows pass through unchanged, and the full parameter state still replays exactly.
+ @pytest.mark.parametrize(
+ "name",
+ [
+ "RandomGaussianNoise",
+ "RandomGaussianIllumination",
+ "RandomLinearIllumination",
+ "RandomLinearCornerIllumination",
+ "RandomPlasmaBrightness",
+ "RandomPlasmaContrast",
+ "RandomPlasmaShadow",
+ ],
+ )
+ def test_convention_intensity_parameter_fields_keep_original_batch_for_partial_probability(
+ self, device, dtype, name
+ ):
+ # B is 16, not 4: at p=0.5 an all-or-nothing draw has probability 2 * 2 ** -B, which is 12.5% at
+ # B=4 -- this node failed on 28 of seeds 0..199 and only _FORWARD_SEED kept it green. At B=16 it is
+ # 3e-5.
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(16, 3, 7, 9).to(device=device, dtype=dtype)
+ aug, field_name, field_channels = _field_augmentation(name, p=0.5)
+ torch.manual_seed(_FORWARD_SEED)
+ out = aug(image)
+ selected = aug._params["batch_prob"].bool()
+ assert 0 < int(selected.sum()) < image.shape[0]
+ assert aug._params[field_name].shape == (image.shape[0], field_channels, *image.shape[-2:])
+ assert torch.equal(out[~selected], image[~selected])
+ assert torch.equal(out, aug(image, params=aug._params))
+
+ def test_convention_gaussian_noise_same_on_batch_shares_one_normalized_field(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(4, 3, 7, 9).to(device=device, dtype=dtype)
+ aug = K.RandomGaussianNoise(mean=0.0, std=1.0, p=1.0, same_on_batch=True)
+ torch.manual_seed(_FORWARD_SEED)
+ out = aug(image)
+ noise = aug._params["gaussian_noise"]
+ assert noise.shape == (1, *image.shape[1:])
+ self.assert_close(out, image + noise.to(device=device, dtype=dtype).expand_as(image))
+
+ # Row 6c-27: ``amount`` is the fraction of *pixels* touched, not of scalars -- a chosen pixel is
+ # rewritten in every channel, so the changed mask is identical across channels -- and
+ # ``salt_vs_pepper`` splits those pixels, 0.25 meaning a quarter of them become salt. Both are
+ # per-pixel Bernoulli draws, so each realised fraction is asserted within five binomial standard
+ # deviations of the requested value: at a fixed band the pin held on seed 0 only by luck (the salt
+ # ratio at amount 0.1 left a 0.02 band on 106 of seeds 0..199). The image is large enough that five
+ # deviations is still a tight band (0.0086 for the fraction at amount 0.1).
+ # Snippet used to generate expected:
+ # x = torch.full((2, 3, 96, 160), 0.5)
+ # for amount in (0.1, 0.3, 0.6):
+ # torch.manual_seed(0)
+ # y = K.RandomSaltAndPepperNoise(amount=(amount, amount), salt_vs_pepper=(0.25, 0.25), p=1.0)(x)
+ # changed = (y != 0.5)[:, 0]; salt = (y[:, 0] == 1.0).sum(); pepper = (y[:, 0] == 0.0).sum()
+ # print(amount, changed.float().mean(), salt / (salt + pepper))
+ # executed 2026-09-15 (torch 2.14.0, cpu float16/bfloat16/float32/float64 and mps float32, identical)
+ # -> errors of -0.78 / -1.92 / -1.19 deviations for the fraction and -1.71 / -0.52 / -0.38 for the
+ # salt ratio; over seeds 0..99 and the three amounts no draw leaves the five-deviation band.
+ @pytest.mark.parametrize("amount", [0.1, 0.3, 0.6])
+ def test_convention_random_salt_and_pepper_amount_is_a_pixel_fraction(self, device, dtype, amount):
+ image = torch.full((2, 3, 96, 160), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomSaltAndPepperNoise(amount=(amount, amount), salt_vs_pepper=(0.25, 0.25), p=1.0)(image)
+ changed = out != 0.5
+ assert torch.equal(changed[:, 0], changed[:, 1])
+ assert torch.equal(changed[:, 0], changed[:, 2])
+ pixels = changed[:, 0].numel()
+ fraction = float(changed[:, 0].float().mean())
+ assert abs(fraction - amount) < 5.0 * (amount * (1.0 - amount) / pixels) ** 0.5
+ # salt_vs_pepper splits the touched pixels; 0.25 means a quarter of them go to salt.
+ salt = float((out[:, 0] == 1.0).float().sum())
+ pepper = float((out[:, 0] == 0.0).float().sum())
+ touched = salt + pepper
+ assert abs(salt / touched - 0.25) < 5.0 * (0.25 * 0.75 / touched) ** 0.5
+
+ # Row 6c-27: the two poles are the literals 1.0 and 0.0, written regardless of the input's range,
+ # so on a [0, 2] image the "salt" is darker than the untouched pixels.
+ # Snippet used to generate expected:
+ # x = torch.full((2, 3, 12, 20), 2.0)
+ # for svp in (1.0, 0.0):
+ # torch.manual_seed(0)
+ # print(svp, K.RandomSaltAndPepperNoise(amount=(0.3, 0.3), salt_vs_pepper=(svp, svp), p=1.0)(x).unique())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `1.0 -> [1., 2.]` and `0.0 -> [0., 2.]`, each with
+ # 0.322917 of the pixels changed.
+ @pytest.mark.parametrize(("salt_vs_pepper", "written"), [(1.0, 1.0), (0.0, 0.0)])
+ def test_convention_random_salt_and_pepper_writes_literal_zero_and_one(
+ self, device, dtype, salt_vs_pepper, written
+ ):
+ image = torch.full((2, 3, 12, 20), 2.0, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomSaltAndPepperNoise(amount=(0.3, 0.3), salt_vs_pepper=(salt_vs_pepper, salt_vs_pepper), p=1.0)(
+ image
+ )
+ changed = out != 2.0
+ assert int(changed.sum()) > 0
+ self.assert_close(out[changed], out.new_full((int(changed.sum()),), written))
+ # The other pole is never written at this setting.
+ assert not bool((out == (1.0 - written)).any())
+
+ # Row 6c-27: only 1- and 3-channel images are accepted, so a 2-channel tensor is rejected rather
+ # than silently treated as RGB.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); K.RandomSaltAndPepperNoise(p=1.0)(torch.rand(2, 2, 7, 9))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `kornia.core.exceptions.BaseError: Number of color
+ # channels should be 1 or 3.`
+ def test_convention_random_salt_and_pepper_requires_one_or_three_channels(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 2, 7, 9).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(Exception, match="1 or 3"):
+ _sync(K.RandomSaltAndPepperNoise(p=1.0)(image).device)
+
+ # Row 6c-28: RandomRain's ``drop_height`` runs down rows and ``drop_width`` along columns -- the
+ # names are image axes, not drop-local ones. The claim is a labelling, so it is checked under
+ # relabelling on the transposed 30x12 image with the two arguments swapped.
+ # Snippet used to generate expected:
+ # z = torch.zeros(1, 1, 12, 30)
+ # for dh, dw in ((6, 1), (1, 6)):
+ # torch.manual_seed(0)
+ # y = K.RandomRain(number_of_drops=(1, 1), drop_height=(dh, dh), drop_width=(dw, dw), p=1.0)(z)
+ # print(dh, dw, (y[0, 0] > 0).nonzero().tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `6 1 -> [[0, 8], [1, 8], [2, 8], [3, 8], [4, 8],
+ # [6, 9]]` (six rows, two columns) and `1 6 -> [[1, 7], [1, 8], [1, 9], [1, 10], [1, 11],
+ # [2, 13]]` (two rows, six columns); on the transposed 30x12 image the extents swap.
+ @pytest.mark.parametrize(("drop_height", "drop_width"), [(6, 1), (1, 6)])
+ def test_convention_random_rain_drop_height_runs_down_rows(self, device, dtype, drop_height, drop_width):
+ def extents(image: torch.Tensor) -> tuple[int, int]:
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomRain(
+ number_of_drops=(1, 1),
+ drop_height=(drop_height, drop_height),
+ drop_width=(drop_width, drop_width),
+ p=1.0,
+ )
+ rows, cols = _lit_extent(aug(image)[0, 0])
+ return len(rows), len(cols)
+
+ tall_rows, tall_cols = extents(torch.zeros(1, 1, 12, 30, device=device, dtype=dtype))
+ if drop_height > drop_width:
+ assert tall_rows >= 5 and tall_cols <= 2
+ else:
+ assert tall_cols >= 5 and tall_rows <= 2
+ # Relabelling: on a 30x12 image the same arguments still mean rows and columns, so the
+ # extents do not follow the longer image axis.
+ wide_rows, wide_cols = extents(torch.zeros(1, 1, 30, 12, device=device, dtype=dtype))
+ if drop_height > drop_width:
+ assert wide_rows >= 5 and wide_cols <= 2
+ else:
+ assert wide_cols >= 5 and wide_rows <= 2
+
+ # Row 6c-31: a drop is written as the literal 200/255, not as a function of the image, so on an
+ # image outside [0, 1] the "rain" is a dark smudge rather than a bright one.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0)
+ # y = K.RandomRain(number_of_drops=(5, 5), drop_height=(3, 3), drop_width=(1, 1), p=1.0)(
+ # torch.full((1, 1, 12, 30), 2.0))
+ # print(y.aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `min=0.784314 max=2` (200/255 = 0.7843137...).
+ def test_convention_random_rain_drop_value_is_two_hundred_over_255(self, device, dtype):
+ image = torch.full((1, 1, 12, 30), 2.0, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomRain(number_of_drops=(5, 5), drop_height=(3, 3), drop_width=(1, 1), p=1.0)(image)
+ self.assert_close(out.min(), out.new_tensor(200 / 255))
+ self.assert_close(out.max(), out.new_tensor(2.0))
+
+ # Rows 6c-28 / 6c-29 in the state #4451 left them (it closed #4434): a drop as tall as the image
+ # or as wide as the image is rejected with a kornia error, and one pixel smaller runs. The guard
+ # is `<=` under a message that says "less than", so the rejected case is the equal one. The
+ # check lives in the forward, not the constructor -- the drop size is compared against the image
+ # it is given -- so the construction happens outside the `raises` block, the converse of the
+ # RandomSnow pin below, which pins a constructor-time check.
+ # Snippet used to generate expected:
+ # z = torch.zeros(1, 1, 12, 30)
+ # for dh in (11, 12):
+ # aug = K.RandomRain(number_of_drops=(1, 1), drop_height=(dh, dh), drop_width=(1, 1), p=1.0)
+ # torch.manual_seed(0); aug(z)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> construction succeeds in both cases; the forward
+ # gives `11 ok`, `12 -> BaseError: Height of drop should be greater than zero and less than image
+ # height.`; `drop_width` 29 ok and 30 -> `BaseError: Width of drop should be less than image
+ # width.`
+ @pytest.mark.parametrize(("drop_height", "drop_width", "message"), [(12, 1, "Height of drop"), (1, 30, "Width of")])
+ def test_convention_random_rain_rejects_a_drop_as_large_as_the_image(
+ self, device, dtype, drop_height, drop_width, message
+ ):
+ image = torch.zeros(1, 1, 12, 30, device=device, dtype=dtype)
+ # Constructing an oversized drop is allowed; only the forward, which knows the image, raises.
+ aug = K.RandomRain(
+ number_of_drops=(1, 1),
+ drop_height=(drop_height, drop_height),
+ drop_width=(drop_width, drop_width),
+ p=1.0,
+ )
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(Exception, match=message):
+ _sync(aug(image).device)
+ # One pixel smaller on the same axis runs.
+ inside_height, inside_width = min(drop_height, 11), min(drop_width, 29)
+ torch.manual_seed(_FORWARD_SEED)
+ smaller = K.RandomRain(
+ number_of_drops=(1, 1),
+ drop_height=(inside_height, inside_height),
+ drop_width=(inside_width, inside_width),
+ p=1.0,
+ )
+ assert smaller(image).shape == image.shape
+
+ # Row 6c-29, the painted extent: the drop is sampled along `linspace(0, h, steps=max(h, |w|))`, end point
+ # included, so a drop of size h spans h + 1 rows, and one row short of the image already runs from edge
+ # to edge. With both sizes at most 1 there is a single step, which is the start point alone, so the
+ # drop is one pixel.
+ # Snippet used to generate expected:
+ # x = torch.zeros(1, 1, 6, 10)
+ # for h, w in ((5, 0), (1, 1), (1, 0)):
+ # torch.manual_seed(0)
+ # y = K.RandomRain(number_of_drops=(1, 1), drop_height=(h, h), drop_width=(w, w), p=1.0)(x)
+ # print((h, w), sorted({r for r, _ in (y[0, 0] != 0).nonzero().tolist()}), int((y != 0).sum()))
+ # executed 2026-09-15 (torch 2.14.0, cpu float16/bfloat16/float32/float64 and mps float32) ->
+ # `[0, 1, 2, 3, 5]`, then a single painted pixel for both `(1, 1)` and `(1, 0)`.
+ def test_convention_random_rain_drop_spans_one_row_more_than_its_height(self, device, dtype):
+ image = torch.zeros(1, 1, 6, 10, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomRain(number_of_drops=(1, 1), drop_height=(5, 5), drop_width=(0, 0), p=1.0)(image)
+ rows, _ = _lit_extent(out[0, 0])
+ assert (rows[0], rows[-1]) == (0, 5)
+ for width in (1, 0):
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomRain(number_of_drops=(1, 1), drop_height=(1, 1), drop_width=(width, width), p=1.0)
+ assert int((aug(image) != 0).sum()) == 1
+
+ # Issue #4567: the three integer ranges are float draws truncated to integers, and the generator's
+ # `hi + 1` shift goes through the `bounds` argument that `_range_bound` ignores for a tuple, so the
+ # upper bound is never drawn and a signed `drop_width` truncates both `(-1, 0)` and `(0, 1)` to 0.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0)
+ # p = K.RandomRain(number_of_drops=(2, 4), drop_height=(5, 20), drop_width=(-5, 5), p=1.0)
+ # p = p.forward_parameters((20000, 1, 64, 64))
+ # for k in ("number_of_drops_factor", "drop_height_factor", "drop_width_factor"):
+ # print(k, collections.Counter(p[k].flatten().tolist()))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> drops `{2: 9939, 3: 10061}`, heights `5..19` (about
+ # 1333 each, no 20), widths `-4..4` with `0: 4075` against about 2000 for every other value.
+ @pytest.mark.device_agnostic
+ def test_wart_random_rain_upper_bound_is_never_drawn_4567(self):
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomRain(number_of_drops=(2, 4), drop_height=(5, 20), drop_width=(-5, 5), p=1.0)
+ params = aug.forward_parameters((20000, 1, 64, 64))
+ drops = params["number_of_drops_factor"].flatten()
+ heights = params["drop_height_factor"].flatten()
+ widths = params["drop_width_factor"].flatten()
+ # "Practically never", not never: `lo + (hi - lo) * u` with u = 1 - 2**-24 rounds onto `hi` in
+ # float32 for the top handful of the 2**24 representable draws, so over 20000 draws the bound
+ # appears with probability about 0.2% per seed -- seed 80 draws a 4 here. The pin is that the
+ # bound is vanishingly rare, not that it is impossible; the lower bound is always drawn.
+ assert int(drops.min()) == 2 and int(drops.max()) <= 4 and int((drops == 4).sum()) < 5
+ assert int(heights.min()) == 5 and int(heights.max()) <= 20 and int((heights == 20).sum()) < 5
+ assert int(widths.min()) == -4 and int(widths.max()) <= 5 and int((widths == 5).sum()) < 5
+ zeros, ones = int((widths == 0).sum()), int((widths == 1).sum())
+ assert zeros > 1.5 * ones and ones > 1000
+ # Truncation is toward zero, so on a range below zero it is the lower bound that is not drawn and
+ # the upper bound that is: `(-5, -1)` draws -4..-1 (about 5000 each out of 20000) and `(-3, 0)`
+ # draws -2..0, so 0 is not doubled there.
+ for bounds, expected in (((-5, -1), (-4, -1)), ((-3, 0), (-2, 0))):
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomRain(number_of_drops=(1, 1), drop_height=(1, 1), drop_width=bounds, p=1.0)
+ drawn = aug.forward_parameters((20000, 1, 64, 64))["drop_width_factor"].flatten()
+ assert (int(drawn.min()), int(drawn.max())) == expected
+ counts = torch.stack([(drawn == value).sum() for value in range(expected[0], expected[1] + 1)])
+ assert float(counts.max()) < 1.2 * float(counts.min())
+
+ # Issue #4604: the start coordinate is scaled by `H - h - 1`, so the last row and column are never
+ # painted unless the drop is one short of the image on that axis. Literal seeds, as for the other
+ # census pins: the claim is over the union of 300 draws, not one.
+ # Snippet used to generate expected: the reproduction in #4604.
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> rows `[0, 1, 2, 3]`, cols `[0, ..., 8]` on `6 x 10`;
+ # `drop_height=(5, 5)`, `drop_width=(9, 9)` paints rows 0..5 and cols 0..9.
+ def test_wart_random_rain_never_paints_the_last_row_or_column_4604(self, device, dtype):
+ image = torch.zeros(1, 3, 6, 10, device=device, dtype=dtype)
+ rows, cols = set(), set()
+ for seed in range(300):
+ torch.manual_seed(seed)
+ out = K.RandomRain(number_of_drops=(20, 20), drop_height=(1, 1), drop_width=(0, 0), p=1.0)(image)
+ lit = (out[0, 0] != 0).nonzero()
+ rows |= set(lit[:, 0].tolist())
+ cols |= set(lit[:, 1].tolist())
+ assert sorted(rows) == [0, 1, 2, 3] and sorted(cols) == list(range(9))
+ # One short of the image on both axes is the only case that reaches the far edge.
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomRain(number_of_drops=(1, 1), drop_height=(5, 5), drop_width=(9, 9), p=1.0)(image)
+ lit = (out[0, 0] != 0).nonzero()
+ assert int(lit[:, 0].max()) == 5 and int(lit[:, 1].max()) == 9
+
+ # Row 6c-28 in the state #4453 left it (it closed #4448): with ``same_on_batch=True`` every
+ # sample of the batch gets the same number of drops, the same drop size and the same coordinates;
+ # with the default False each sample draws its own count.
+ # Snippet used to generate expected:
+ # for sob in (True, False):
+ # torch.manual_seed(0)
+ # aug = K.RandomRain(number_of_drops=(1, 50), drop_height=(1, 3), drop_width=(1, 3), p=1.0,
+ # same_on_batch=sob)
+ # aug(torch.zeros(4, 1, 12, 30)); print(sob, aug._params["number_of_drops_factor"].tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `True [25, 25, 25, 25]` and `False [25, 38, 5, 7]`.
+ def test_convention_random_rain_same_on_batch_draws_one_drop_count(self, device, dtype):
+ # B is 16, not 4: `drop_height=(1, 3)` truncates to {1, 2}, so "the unshared draw differs across
+ # the batch" is a `2 * 2 ** -B` event -- 29 of seeds 0..199 coincide at B=4, 3 at B=8 and none
+ # at B=16.
+ batch_size = 16
+ image = torch.zeros(batch_size, 1, 12, 30, device=device, dtype=dtype)
+ drawn = {}
+ shared = {}
+ for same_on_batch in (True, False):
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomRain(
+ number_of_drops=(1, 50), drop_height=(1, 3), drop_width=(1, 3), p=1.0, same_on_batch=same_on_batch
+ )
+ aug(image)
+ drawn[same_on_batch] = aug._params["number_of_drops_factor"].flatten().tolist()
+ shared[same_on_batch] = aug._params
+ assert len(set(drawn[True])) == 1
+ assert len(drawn[True]) == batch_size
+ assert len(set(drawn[False])) > 1
+ # The sentence claims three things, not one: the drop SIZES and the COORDINATES are shared too.
+ # A generator that passed `same_on_batch=False` to the size or coordinate sampler would leave the
+ # drop-count assertions above untouched.
+ for key in ("drop_height_factor", "drop_width_factor"):
+ assert len(set(shared[True][key].flatten().tolist())) == 1, key
+ assert len(set(shared[False][key].flatten().tolist())) > 1, key
+ coordinates = shared[True]["coordinates_factor"]
+ assert all(torch.equal(coordinates[0], coordinates[row]) for row in range(1, batch_size))
+ assert not torch.equal(shared[False]["coordinates_factor"][0], shared[False]["coordinates_factor"][1])
+
+ # Row 6c-32: RandomSnow is an RGB-only operator -- it rejects any other channel count -- and its
+ # ``snow_coefficient`` is validated against [0, 1] at construction rather than at the forward.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); K.RandomSnow(p=1.0)(torch.rand(2, 1, 7, 9))
+ # K.RandomSnow(snow_coefficient=(1.5, 1.5), p=1.0)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `BaseError: Number of color channels should be 3.`
+ # and `BaseError: Snow coefficient values must be between 0 and 1.` (the same for -0.5).
+ def test_convention_random_snow_requires_rgb_and_a_unit_coefficient(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 1, 7, 9).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(Exception, match="should be 3"):
+ _sync(K.RandomSnow(p=1.0)(image).device)
+ for coefficient in (1.5, -0.5):
+ with pytest.raises(Exception, match="between 0 and 1"):
+ K.RandomSnow(snow_coefficient=(coefficient, coefficient), p=1.0)
+
+ # Row 6c-32: ``snow_coefficient`` and ``brightness`` are drawn once per sample, and
+ # ``same_on_batch=True`` collapses both to a single value for the batch.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0)
+ # aug = K.RandomSnow(snow_coefficient=(0.2, 0.8), brightness=(1.5, 3.0), p=1.0)
+ # aug(torch.rand(4, 3, 7, 9)); print({k: v.flatten().tolist() for k, v in aug._params.items()})
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `snow_coefficient [0.370124, 0.726453, 0.375167,
+ # 0.291604]`, `brightness [2.365495, 2.699539, 1.573806, 2.927976]`; with same_on_batch=True both
+ # lists are four copies of one value.
+ def test_convention_random_snow_draws_one_value_per_sample(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(4, 3, 7, 9).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomSnow(snow_coefficient=(0.2, 0.8), brightness=(1.5, 3.0), p=1.0)
+ aug(image)
+ torch.manual_seed(_FORWARD_SEED)
+ many = aug.forward_parameters((256, 3, 7, 9))
+ for key, low, high in (("snow_coefficient", 0.2, 0.8), ("brightness", 1.5, 3.0)):
+ drawn = aug._params[key].flatten()
+ assert drawn.shape == (4,)
+ assert len(set(drawn.tolist())) == 4
+ assert float(drawn.min()) >= low and float(drawn.max()) <= high
+ # Reach, not only containment: a draw shrunk to the lower half of the range satisfies the above.
+ width = high - low
+ assert float(many[key].min()) < low + 0.1 * width and float(many[key].max()) > high - 0.1 * width
+ torch.manual_seed(_FORWARD_SEED)
+ shared = K.RandomSnow(snow_coefficient=(0.2, 0.8), brightness=(1.5, 3.0), p=1.0, same_on_batch=True)
+ shared(image)
+ for key in ("snow_coefficient", "brightness"):
+ assert len(set(shared._params[key].flatten().tolist())) == 1
+
+ # Row 6c-32, the clamp: only a covered pixel -- lightness below the drawn coefficient -- has its
+ # lightness scaled and clamped. At coefficient 0.9 and brightness 2, (1.5, 0, 0) has lightness 0.75, is
+ # covered and turns white; (2, 1.5, 1.5) has lightness 1.75, is missed and keeps its values; and
+ # (1.2, -2, -2) has lightness -0.4 and turns black. A missed pixel still makes the unclamped HLS round
+ # trip, which is not the identity at either singular lightness: (1.5, 0.5, 0.5) has lightness exactly 1,
+ # where `2 - max - min` vanishes, and comes back white; (2, -2, -2) has lightness exactly 0, where
+ # `max + min` vanishes, and comes back black although it is neither all-negative nor negative in
+ # lightness. Both are NaN in float16, where `eps` underflows and the saturation is 0 / 0 (#4571).
+ # The coefficient is 0.9, not 1.0, and (1.8, 0, 0) is the last row: coverage is `lightness < coefficient`
+ # at random_snow.py:118, so the only pixel that can tell `<` from `<=` is one whose lightness equals the
+ # coefficient exactly. At coefficient 1.0 that pixel was (1.5, 0.5, 0.5) -- but it is also the lightness-1
+ # singularity, which comes back white either way, so flipping the comparison left every pin in this file
+ # green. The last row is not singular and sits exactly on the boundary: its red channel is
+ # `2 * float32(0.9)`, not 1.8, because the coefficient is drawn in float32 whatever the image dtype --
+ # with a plain 1.8 a float64 image computes a lightness a hair above the float32 coefficient and the
+ # mutant survives on that leg. Missed it keeps its values; covered it would be scaled by 2 and clamped
+ # to white.
+ # Snippet used to generate expected:
+ # x = torch.tensor([[1.5, 0.0, 0.0], [2.0, 1.5, 1.5], [1.2, -2.0, -2.0], [1.5, 0.5, 0.5],
+ # [2.0, -2.0, -2.0], [1.7999999523162842, 0.0, 0.0]]).T.reshape(1, 3, 1, 6)
+ # torch.manual_seed(0); print(K.RandomSnow(snow_coefficient=(0.9, 0.9), brightness=(2.0, 2.0), p=1.0)(x))
+ # executed 2026-09-16 (torch 2.14.0, cpu float32/float64/float16/bfloat16 and mps float32) -> the pixels
+ # `(1, 1, 1)`, `(2, 1.5, 1.5)`, `(0, 0, 0)`, `(1, 1, 1)`, `(0, 0, 0)` and the boundary pixel unchanged;
+ # rows 3 and 4 are `(nan, nan, nan)` in float16.
+ def test_convention_random_snow_clamps_only_covered_lightness(self, device, dtype):
+ pixels = torch.tensor(
+ [
+ [1.5, 0.0, 0.0],
+ [2.0, 1.5, 1.5],
+ [1.2, -2.0, -2.0],
+ [1.5, 0.5, 0.5],
+ [2.0, -2.0, -2.0],
+ [_SNOW_BOUNDARY_RED, 0.0, 0.0],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomSnow(snow_coefficient=(0.9, 0.9), brightness=(2.0, 2.0), p=1.0)
+ out = aug(pixels.T.reshape(1, 3, 1, 6).contiguous())[0, :, 0].T
+ self.assert_close(out[:3], pixels.new_tensor([[1.0, 1.0, 1.0], [2.0, 1.5, 1.5], [0.0, 0.0, 0.0]]))
+ # Lightness exactly at the coefficient is missed, so the pixel survives the round trip unchanged.
+ self.assert_close(out[5], pixels[5])
+ if dtype == torch.float16:
+ assert bool(out[3].isnan().all())
+ assert bool(out[4].isnan().all())
+ else:
+ self.assert_close(out[3], pixels.new_ones(3))
+ self.assert_close(out[4], pixels.new_zeros(3))
+
+ # The singular region at lightness 1 has the width of rgb_to_hls's eps = 1e-8: a lightness 2e-7 off
+ # comes back close to its input in float32 and float64 (half precision rounds it onto the point), while
+ # 1 + 1e-8 and 1 + 5e-9, which only float64 resolves, come back as (2, 0, 0) and as values of order 1e8.
+ # Snippet used to generate expected:
+ # for L in (1 + 2e-7, 1 + 1e-8, 1 + 5e-9):
+ # x = torch.tensor([2 * L - 0.5, 0.5, 0.5], dtype=torch.float64).reshape(1, 3, 1, 1)
+ # torch.manual_seed(0); print(L, K.RandomSnow(p=1.0)(x).flatten().tolist())
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `[1.5263, 0.4737, 0.4737]` (same at 1e-7), `[2.0, -0.0, -0.0]`,
+ # `[-82271062.5, 82271064.5, 82271064.5]`.
+ def test_convention_random_snow_singularity_has_eps_width(self, device, dtype):
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("half precision: 1.5 + 4e-7 rounds onto the singular point (float16 is NaN there, #4571)")
+
+ def run(lightness: float) -> torch.Tensor:
+ pixel = torch.tensor([2 * lightness - 0.5, 0.5, 0.5], dtype=torch.float64).reshape(1, 3, 1, 1)
+ pixel = pixel.to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ return K.RandomSnow(snow_coefficient=(0.9, 0.9), brightness=(2.0, 2.0), p=1.0)(pixel).flatten()
+
+ near = run(1 + 2e-7)
+ assert float(near[0]) > 1.4 and float((near - near.new_tensor([1.5, 0.5, 0.5])).abs().max()) < 0.1
+ if dtype == torch.float64:
+ self.assert_close(run(1 + 1e-8), near.new_tensor([2.0, 0.0, 0.0]))
+ assert float(run(1 + 5e-9).abs().min()) > 1e6
+
+ # float16, so every achromatic pixel -- black, gray or white -- gets a NaN hue that the HLS round trip
+ # spreads to all three channels. bfloat16 keeps the exponent range of float32 and is finite.
+ # Snippet used to generate expected:
+ # for dt in (torch.float16, torch.bfloat16, torch.float32):
+ # torch.manual_seed(0); print(dt, K.RandomSnow(p=1.0)(torch.full((1, 3, 2, 2), 0.5, dtype=dt)).isnan().any())
+ # executed 2026-09-15 (torch 2.14.0, cpu; mps float16 as well) -> `True`, `False`, `False`, and the
+ # same for the constants 0.0 and 1.0.
+ @pytest.mark.parametrize("value", [0.0, 0.5, 1.0])
+ def test_wart_random_snow_achromatic_pixel_is_nan_in_float16_4571(self, device, dtype, value):
+ gray = torch.full((1, 3, 2, 2), value, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomSnow(p=1.0)(gray)
+ assert bool(out.isnan().any()) == (dtype == torch.float16)
+
+ # The channel-count precondition is a class-by-class contract, so it is pinned as one table rather
+ # than per class: five of these were documented before this batch and five were not, and the split
+ # between "1 or 3" and "3 only" is the part a reader gets wrong.
+ # Snippet used to generate expected:
+ # for c in (1, 2, 4): torch.manual_seed(0); factory()(torch.rand(2, c, 32, 32))
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> RandomRain and RandomSaltAndPepperNoise accept C=1 and
+ # reject C=2/C=4 with `Number of color channels should be 1 or 3.`; ColorJiggle, RandomHue,
+ # RandomSaturation, RandomJPEG, RandomPlanckianJitter, RandomRGBShift and RandomSnow reject all three.
+ # The rejection TYPE and message are part of the contract: with a bare ``pytest.raises(Exception)``
+ # a class that started failing for an unrelated reason would still satisfy this table. The five
+ # message families below were executed on 2026-09-16 (torch 2.14.0, cpu) at C in (1, 2, 4).
+ @pytest.mark.parametrize(
+ ("name", "accepts_one", "error", "match"),
+ [
+ ("ColorJiggle", False, ValueError, r"Input size must have a shape of \(\*, 3, H, W\)"),
+ ("RandomHue", False, ValueError, r"Input size must have a shape of \(\*, 3, H, W\)"),
+ ("RandomSaturation", False, ValueError, r"Input size must have a shape of \(\*, 3, H, W\)"),
+ ("RandomJPEG", False, ShapeError, r"Shape mismatch at dimension 0: expected 3, got"),
+ ("RandomPlanckianJitter", False, ShapeError, r"Shape mismatch at dimension 0: expected 3, got"),
+ ("RandomRGBShift", False, ImageError, r"Not a color tensor"),
+ ("RandomSnow", False, BaseError, r"Number of color channels should be 3\."),
+ ("RandomRain", True, BaseError, r"Number of color channels should be 1 or 3\."),
+ ("RandomSaltAndPepperNoise", True, BaseError, r"Number of color channels should be 1 or 3\."),
+ ],
+ )
+ def test_convention_intensity_channel_count_preconditions(self, device, dtype, name, accepts_one, error, match):
+ if name == "RandomJPEG" and not supports_replicate_padding(device, dtype):
+ # The 3-channel baseline call below needs the codec's replication padding, which torch 2.5.1
+ # has no `Half` kernel for ("replication_pad2d" not implemented for 'Half'). The rejection
+ # this test pins happens before that, but the baseline would fail for an unrelated reason.
+ pytest.skip("replication_pad2d is unavailable for this device/dtype")
+ factories = {
+ "ColorJiggle": lambda: K.ColorJiggle(0.0, 0.0, 0.2, 0.0, p=1.0),
+ "RandomHue": lambda: K.RandomHue((-0.2, 0.2), p=1.0),
+ "RandomSaturation": lambda: K.RandomSaturation((0.7, 1.3), p=1.0),
+ "RandomJPEG": lambda: K.RandomJPEG((50.0, 90.0), p=1.0),
+ "RandomPlanckianJitter": lambda: K.RandomPlanckianJitter(p=1.0),
+ "RandomRGBShift": lambda: K.RandomRGBShift(p=1.0),
+ "RandomSnow": lambda: K.RandomSnow(p=1.0),
+ "RandomRain": lambda: K.RandomRain(number_of_drops=(2, 3), drop_height=(2, 3), drop_width=(1, 2), p=1.0),
+ "RandomSaltAndPepperNoise": lambda: K.RandomSaltAndPepperNoise(p=1.0),
+ }
+ torch.manual_seed(_FIXTURE_SEED)
+ three = torch.rand(2, 3, 32, 32).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ assert factories[name]()(three).shape == three.shape, f"{name} must accept a 3-channel image"
+ for channels in (1, 2, 4):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, channels, 32, 32).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ if channels == 1 and accepts_one:
+ assert factories[name]()(image).shape == image.shape
+ continue
+ with pytest.raises(error, match=match):
+ _sync(factories[name]()(image).device)
+
+ # The degenerate signed range: `(-1, 1)` satisfies the block's "draws 0 twice as often as any other
+ # value" but has no other value to be twice as often as -- truncation toward zero maps the whole
+ # interval onto 0, except an exact -1.0 draw (rand returning 0.0, one float32 value in 2**24, which a
+ # 2**20 batch at seed 1 does produce), so the pin is "practically always", as for the upper bounds.
+ # Snippet used to generate expected:
+ # g = RainGenerator(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=(-1, 1))
+ # torch.manual_seed(0); print(set(g((40000, 3, 64, 64))["drop_width_factor"].flatten().tolist()))
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `{0}`, against `{-1, 0, 1}` for `(-2, 2)`.
+ @pytest.mark.device_agnostic
+ def test_convention_random_rain_symmetric_unit_width_range_is_constant_zero(self):
+ torch.manual_seed(_FORWARD_SEED)
+ degenerate = K.RandomRain(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=(-1, 1), p=1.0)
+ drawn = degenerate.forward_parameters((20000, 1, 64, 64))["drop_width_factor"].flatten()
+ assert set(drawn.tolist()) <= {-1.0, 0.0}
+ assert float((drawn == 0).float().mean()) > 0.999
+ # One step wider and the doubling the block describes is visible again.
+ torch.manual_seed(_FORWARD_SEED)
+ wider = K.RandomRain(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=(-2, 2), p=1.0)
+ widths = wider.forward_parameters((20000, 1, 64, 64))["drop_width_factor"].flatten()
+ assert set(widths.tolist()) == {-1.0, 0.0, 1.0}
+ zeros, ones = int((widths == 0).sum()), int((widths == 1).sum())
+ assert zeros > 1.5 * ones
+
+
+class TestIlluminationAndNormalizeConventions(BaseTester):
+ # Row 6c-42: all three *Illumination classes add a gradient whose direction is the drawn ``sign``
+ # -- one draw per sample, from (-1.0, 1.0) by default -- and clamp the sum into [0, 1]
+ # (`_apply_gaussian_illumination`, and `RandomLinearIllumination.apply_transform` /
+ # `RandomLinearCornerIllumination.apply_transform`). The gradient is recorded under
+ # ``_params["gradient"]`` with the input's shape. The clamp is load-bearing on an *in-range*
+ # image as soon as ``gain`` exceeds the headroom: at gain 0.8 on a constant 0.5 the unclamped sum
+ # reaches 1.3 or -0.3, so deleting ``.clamp_(0, 1)`` fails this pin.
+ # Snippet used to generate expected:
+ # c = torch.full((2, 3, 7, 9), 0.5)
+ # torch.manual_seed(0); aug = K.RandomGaussianIllumination(gain=(0.5, 0.5), p=1.0); y = aug(c)
+ # print(y.aminmax(), aug._params["gradient"].aminmax())
+ # for sign in ((1.0, 1.0), (-1.0, -1.0)):
+ # torch.manual_seed(0); a = K.RandomGaussianIllumination(gain=(0.8, 0.8), sign=sign, p=1.0)
+ # y = a(c); raw = c + a._params["gradient"]
+ # print(sign, y.aminmax(), raw.aminmax(), torch.equal(y, raw.clamp(0, 1)), torch.equal(y, raw))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> default gain 0.5: `min=1.93119e-05 max=0.5`
+ # (Gaussian), `0/0.5` (Linear), `2.38419e-07/0.5` (LinearCorner), gradient in [-0.5, -0] and
+ # `gradient` of shape (2, 3, 7, 9); at gain 0.8, `sign=(1, 1)` -> out `0.5/1` against an unclamped
+ # `0.5/1.3`, `sign=(-1, -1)` -> out `0/0.5` against an unclamped `-0.3/0.5`, with
+ # `out == (c + gradient).clamp(0, 1)` bitwise and `out != c + gradient` in both directions.
+ # NOTE: the negative direction of the default-``sign`` leg is the draw at this seed and batch
+ # size, not a contract -- at B=1 and B=5 the same seed draws sign +1 and the image brightens --
+ # so the darkening claim is asserted only where ``sign`` is a point range.
+ @pytest.mark.parametrize(
+ "name", ["RandomGaussianIllumination", "RandomLinearIllumination", "RandomLinearCornerIllumination"]
+ )
+ def test_convention_illumination_adds_a_signed_gradient_and_clamps_to_unit_range(self, device, dtype, name):
+ aug = _illumination(name)
+ constant = torch.full((2, 3, 7, 9), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = aug(constant)
+ assert float(out.min()) >= 0.0
+ assert float(out.max()) <= 1.0
+ assert aug._params["gradient"].shape == constant.shape
+ assert float(aug._params["gradient"].float().abs().max()) > 0.0
+
+ # `sign` fixes the direction: -1 can only darken, +1 can only brighten. At gain 0.8 the sum
+ # leaves [0, 1] on this in-range image, so the clamp is what brings it back -- and the output
+ # is the clamped sum bitwise, not the raw one.
+ for sign, low, high in ((-1.0, 0.0, 0.5), (1.0, 0.5, 1.0)):
+ torch.manual_seed(_FORWARD_SEED)
+ clamped_aug = _illumination(name, gain=(0.8, 0.8), sign=(sign, sign))
+ clamped = clamped_aug(constant)
+ gradient = clamped_aug._params["gradient"]
+ if sign > 0:
+ assert float(gradient.float().min()) >= 0.0
+ else:
+ assert float(gradient.float().max()) <= 0.0
+ assert float(clamped.min()) >= low - 1e-3 and float(clamped.max()) <= high + 1e-3
+ raw = constant + gradient.to(device=device, dtype=dtype)
+ self.assert_close(clamped, raw.clamp(0.0, 1.0))
+ assert not torch.equal(clamped, raw), "the clamp did not engage, so this leg proves nothing"
+
+ # One parameter away (B=2 -> B=4, and same_on_batch): with the default range the sign is drawn
+ # per sample, so one batch can hold both directions; same_on_batch=True collapses it to one.
+ # Snippet: torch.manual_seed(0); aug(torch.full((4, 3, 7, 9), 0.5));
+ # [float(aug._params["gradient"][b].max()) for b in range(4)]
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `[-0.0, 0.5, -0.0, 0.5]` for RandomLinearIllumination
+ # and `[0.5, 0.5, 0.5, 0.5]` with same_on_batch=True.
+ # B is 16, not 4: "one batch holds both directions" fails when every sample draws the same sign,
+ # which is 2 * 2 ** -B -- 12.5% at B=4, and this leg failed on 29 of seeds 0..199. At B=16 it is 3e-5.
+ batch_size = 16
+ batch = torch.full((batch_size, 3, 7, 9), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ per_sample = _illumination(name)
+ per_sample(batch)
+ directions = [float(per_sample._params["gradient"][b].float().max()) for b in range(batch_size)]
+ assert any(value > 0.0 for value in directions) and any(value <= 0.0 for value in directions)
+ torch.manual_seed(_FORWARD_SEED)
+ shared = _illumination(name, same_on_batch=True)
+ shared(batch)
+ gradients = shared._params["gradient"]
+ assert all(torch.equal(gradients[0], gradients[b]) for b in range(batch_size))
+ # The blocks also say the EDGE (or corner) the gradient is strongest at is drawn per sample.
+ # Nothing above reads it: an implementation that collapsed all four directions to one would
+ # still pass every assertion so far, because the sign and the magnitude would be unchanged.
+ # The brightest cell of each sample's gradient names its direction, so more than one distinct
+ # location across a batch of 16 is the claim. `RandomGaussianIllumination` draws a centre
+ # rather than an edge, and it is covered by the same reading.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); a = _illumination(name); a(torch.full((16, 3, 7, 9), 0.5))
+ # g = a._params["gradient"].flatten(1).abs(); print(len(set(g.argmax(1).tolist())))
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> at least 2 for each of the three.
+ flat = per_sample._params["gradient"].flatten(1).float().abs()
+ assert len(set(flat.argmax(1).tolist())) > 1, "the strongest-gradient location is not drawn per sample"
+
+ # The all-negative collapse documented for these augmentations is conditional on the sampled
+ # gradient. With a fixed positive sign and enough gain, a near-zero negative image retains the
+ # positive portion of that gradient after the unit-range clamp.
+ @pytest.mark.parametrize(
+ "name", ["RandomGaussianIllumination", "RandomLinearIllumination", "RandomLinearCornerIllumination"]
+ )
+ def test_convention_positive_illumination_can_lift_an_all_negative_image(self, device, dtype, name):
+ image = torch.full((2, 3, 7, 9), -0.01, device=device, dtype=dtype)
+ aug = _illumination(name, gain=(0.1, 0.1), sign=(1.0, 1.0))
+ torch.manual_seed(_FORWARD_SEED)
+ out = aug(image)
+ assert float(out.min()) >= 0.0
+ assert float(out.max()) <= 1.0
+ assert float(out.max()) > 0.0
+
+ # Row 6c-41 in the state #4457 left it (it closed #4435): RandomGaussianIllumination used to
+ # define its transform as a closure in __init__, which neither pickle nor torch.save could
+ # serialize. All three classes now round-trip through pickle and deepcopy, and the copy
+ # reproduces the original's output under the same seed.
+ # Snippet used to generate expected:
+ # c = torch.full((2, 3, 7, 9), 0.5)
+ # torch.manual_seed(0); a = K.RandomGaussianIllumination(gain=(0.5, 0.5), p=1.0); y = a(c)
+ # torch.manual_seed(0); b = pickle.loads(pickle.dumps(K.RandomGaussianIllumination(gain=(0.5, 0.5), p=1.0)))
+ # print(torch.equal(y, b(c)))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `True` for pickle, deepcopy and torch.save on all three.
+ @pytest.mark.parametrize(
+ "name", ["RandomGaussianIllumination", "RandomLinearIllumination", "RandomLinearCornerIllumination"]
+ )
+ def test_convention_illumination_augmentations_are_picklable(self, device, dtype, name):
+ constant = torch.full((2, 3, 7, 9), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ expected = _illumination(name)(constant)
+ torch.manual_seed(_FORWARD_SEED)
+ unpickled = pickle.loads(pickle.dumps(_illumination(name))) # noqa: S301
+ assert torch.equal(unpickled(constant), expected)
+ torch.manual_seed(_FORWARD_SEED)
+ cloned = copy.deepcopy(_illumination(name))
+ assert torch.equal(cloned(constant), expected)
+ # torch.save is what #4435 reported: it pickles the module, so it failed for the same reason.
+ # `nbytes > 0` would hold for any object, so the round trip is reloaded and run instead.
+ buffer = io.BytesIO()
+ torch.save(_illumination(name), buffer)
+ buffer.seek(0)
+ torch.manual_seed(_FORWARD_SEED)
+ reloaded = torch.load(buffer, weights_only=False)
+ assert torch.equal(reloaded(constant), expected)
+
+ # Issue #4589: the constructor's own check admits `0 <= sigma <= 1`, but filters.kernels.gaussian
+ # normalizes by `gauss.sum()`, which underflows to zero at sigma 0, so the kernel is 0 / 0 and the
+ # whole output is NaN. An even-length axis carries a half-pixel offset, so no sample sits at the mean
+ # and a small non-zero sigma does it too -- with center 0.5, 4x4 is NaN at sigma 0.005 where 3x3 is not.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); print(K.RandomGaussianIllumination(p=1.0, sigma=0.0)(torch.rand(1, 3, 4, 4)))
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> every element NaN; the default
+ # sigma=(0.2, 1.0) is finite over 200 seeds at sizes 1..4. The even/odd leg needs `center` pinned:
+ # with the drawn centre the odd size is NaN on some draws too, and with centre 0.5 a 4x4 image is NaN
+ # at sigma 0.005 on all 30 seeds tried while 3x3 and 5x5 are finite on all of them.
+ @pytest.mark.parametrize("size", [3, 4])
+ def test_wart_random_gaussian_illumination_zero_sigma_is_nan_4589(self, device, dtype, size):
+ image = torch.full((1, 3, size, size), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ assert bool(K.RandomGaussianIllumination(p=1.0, sigma=0.0)(image).isnan().all())
+ # The even axis loses the on-grid sample to the half-pixel offset, so it is NaN at a small
+ # non-zero sigma that the odd one survives.
+ for sigma in (0.005, 0.01):
+ torch.manual_seed(_FORWARD_SEED)
+ small = K.RandomGaussianIllumination(p=1.0, sigma=(sigma, sigma), center=(0.5, 0.5))(image)
+ if sigma == 0.005 and size % 2 == 0:
+ assert bool(small.isnan().all())
+ else:
+ assert bool(small.isfinite().all())
+ # Evenness is not the variable: `sigma` is relative, so it is `sigma * axis` -- the kernel's
+ # absolute width -- that underflows, at about 0.034 in the float32 the parameters are drawn in.
+ # An `8 x 8` image is finite at the sigma that kills `4 x 4`, and a `64 x 64` one dies at a
+ # proportionally smaller sigma. The even/odd leg above runs only at sizes 3 and 4 and cannot
+ # see either half.
+ # Snippet used to generate expected:
+ # for n, sg in ((4, 0.005), (8, 0.005), (8, 0.002), (64, 0.0005), (64, 0.00055)):
+ # torch.manual_seed(0)
+ # K.RandomGaussianIllumination(p=1.0, sigma=(sg, sg), center=(0.5, 0.5))(
+ # torch.full((1, 3, n, n), 0.5))
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes -- the parameters are float32 in
+ # every one of them) -> NaN, finite, NaN, NaN, finite. `n * sigma` is 0.020, 0.040, 0.016,
+ # 0.032 and 0.035 respectively, so the cut is on the product and not on `n`.
+ for axis, small_sigma, nan_expected in ((4, 0.005, True), (8, 0.005, False), (8, 0.002, True)):
+ square = torch.full((1, 3, axis, axis), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomGaussianIllumination(p=1.0, sigma=(small_sigma, small_sigma), center=(0.5, 0.5))(square)
+ assert bool(out.isnan().all()) is nan_expected, (axis, small_sigma)
+ # The parameter dtype, not the image dtype, sets the threshold: float64 parameters move it.
+ # MPS has no float64, so this leg is CPU/CUDA only.
+ if device.type != "mps":
+ wide = torch.full((1, 3, 4, 4), 0.5, device=device, dtype=dtype)
+ for param_sigma, nan_expected in ((0.005, False), (0.003, True)):
+ aug = K.RandomGaussianIllumination(p=1.0, sigma=(param_sigma, param_sigma), center=(0.5, 0.5))
+ aug.set_rng_device_and_dtype(device, torch.float64)
+ torch.manual_seed(_FORWARD_SEED)
+ assert bool(aug(wide).isnan().all()) is nan_expected, param_sigma
+ # And with the DRAWN centre an odd axis is safe from 5 up, where 1 and 3 are not.
+ for odd, safe in ((3, False), (5, True), (7, True)):
+ hits = 0
+ for seed in range(16):
+ torch.manual_seed(seed)
+ odd_image = torch.full((1, 3, odd, odd), 0.5, device=device, dtype=dtype)
+ hits += bool(K.RandomGaussianIllumination(p=1.0, sigma=(0.005, 0.005))(odd_image).isnan().any())
+ assert (hits == 0) is safe, (odd, hits)
+ # The documented default is unaffected, so the wart is the admitted extreme and not the class.
+ torch.manual_seed(_FORWARD_SEED)
+ assert bool(K.RandomGaussianIllumination(p=1.0)(image).isfinite().all())
+
+ # `.compile()` on RandomGaussianIllumination swaps in a compiled transform that neither pickle nor
+ # torch.save can serialize, while deepcopy still works; the linear classes keep pickling. Measured
+ # on cpu: `PicklingError: Can't pickle <function _apply_gaussian_illumination ...>` for both, and a
+ # deep copy of type RandomGaussianIllumination.
+ #
+ # This leg is separate from the pickle pin above because calling ``torch.compile`` is not free even
+ # when nothing is run through it, so it must not ride along on an ordinary test:
+ # * its first statement raises ``RuntimeError: Dynamo is not supported on Python 3.13+`` on
+ # torch<2.6, i.e. the call fails before any compilation is attempted; and
+ # * where it succeeds, Dynamo's one-time init calls
+ # ``torch.distributions.Distribution.set_default_validate_args(False)`` process-wide and never
+ # restores it, stripping argument validation from every later test in the same process. The
+ # cpu-float16 known-failure manifest records 108
+ # ``TestRandomCutMixGen::test_valid_param_combinations`` nodes that fail only because
+ # ``beta=1e-15`` underflows to 0 in float16 and ``Beta(0, 0)`` rejects it; unvalidated they
+ # XPASS and the strict manifest gate goes red.
+ #
+ # ``compile`` in the test name is load-bearing, not decorative: ``pytest_collection_modifyitems``
+ # drops any test whose name contains "compile" or "dynamo" unless ``KORNIA_TEST_OPTIMIZER`` is set,
+ # which is what confines both hazards to the dynamo job. Renaming it without that substring would
+ # put ``torch.compile`` back into every CPU leg. The skipif and the validate-args restore cover the
+ # dynamo job itself, where conftest's session warm-up is skipped under ``KORNIA_TEST_IN_SUBPROCESS``.
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ @pytest.mark.parametrize(
+ "name", ["RandomGaussianIllumination", "RandomLinearIllumination", "RandomLinearCornerIllumination"]
+ )
+ @pytest.mark.device_agnostic
+ def test_convention_compiled_illumination_pickling(self, name):
+ compiled = _illumination(name)
+ validate_args = Distribution._validate_args
+ try:
+ compiled.compile()
+ finally:
+ Distribution.set_default_validate_args(validate_args)
+ # `isinstance(deepcopy(x), type(x))` holds unless __deepcopy__ is overridden, so the copy is run:
+ # deepcopy survives .compile() where pickle does not, and the copy still transforms.
+ constant = torch.full((2, 3, 7, 9), 0.5)
+ torch.manual_seed(_FORWARD_SEED)
+ cloned = copy.deepcopy(compiled)
+ assert isinstance(cloned, type(compiled))
+ assert cloned(constant).shape == constant.shape
+ if name == "RandomGaussianIllumination":
+ with pytest.raises(pickle.PicklingError):
+ pickle.dumps(compiled)
+ with pytest.raises(pickle.PicklingError):
+ torch.save(compiled, io.BytesIO())
+ else:
+ assert len(pickle.dumps(compiled)) > 0
+
+ # Row 6c-43: the three RandomPlasma* classes clamp into [0, 1], and -- since #4462 closed #4445
+ # by recording the sampled fractal under ``_params["plasma"]`` -- replaying a forward with the
+ # recorded parameters reproduces the first output bitwise.
+ #
+ # The replay leg runs on a *non-constant* image on purpose. A constant 0.5 is a fixed point of
+ # the plasma contrast transform, so on that fixture RandomPlasmaContrast returns 0.5 whether or
+ # not `params` is honoured and the replay assertion would hold with #4462 reverted. The clamp
+ # leg keeps the constant fixture, because that is where audit row 6c-43's literals were read.
+ # Snippet used to generate expected:
+ # c = torch.full((2, 3, 7, 9), 0.5); torch.manual_seed(1234); x = torch.rand(2, 3, 7, 9)
+ # torch.manual_seed(0); aug = K.RandomPlasmaBrightness(p=1.0); print(aug(c).aminmax())
+ # torch.manual_seed(0); aug = K.RandomPlasmaBrightness(p=1.0); y = aug(x)
+ # print(list(aug._params), torch.equal(y, aug(x, params=aug._params)), (y - x).abs().max())
+ # torch.manual_seed(0); b = K.RandomPlasmaBrightness(p=1.0); y2 = b(x)
+ # print("params ignored still equal:", torch.equal(b(x), y2))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> constant fixture `min=0.370964 max=0.589035`
+ # (Brightness), `0.5/0.5` (Contrast), `0/0.5` (Shadow); random fixture `0/0.98835`, `0/1`,
+ # `0/0.994917` with max|out - in| of 0.129036 / 0.327044 / 0.911523, `plasma` present in every key
+ # list, replay `True` for all three, and "params ignored still equal" `False` for all three.
+ @pytest.mark.parametrize("name", ["RandomPlasmaBrightness", "RandomPlasmaContrast", "RandomPlasmaShadow"])
+ def test_convention_plasma_clamps_and_replays_from_params(self, device, dtype, name):
+ # Clamp leg: the audit's own constant fixture and its literals.
+ constant = torch.full((2, 3, 7, 9), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ constant_out = _plasma(name)(constant)
+ assert float(constant_out.min()) >= 0.0
+ assert float(constant_out.max()) <= 1.0
+
+ # Replay leg: a seeded non-constant image, which no plasma transform leaves untouched. The image
+ # is 4x3x32x32, not 2x3x7x9: on the small one the largest deviation fell below the 0.05 floor on 3
+ # of seeds 0..199 (RandomPlasmaShadow twice, RandomPlasmaBrightness once). Over 200 seeds at this
+ # size the smallest deviation observed was 0.0601, against a floor of 0.03.
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(4, 3, 32, 32).to(device=device, dtype=dtype)
+ aug = _plasma(name)
+ torch.manual_seed(_FORWARD_SEED)
+ out = aug(image)
+ assert float(out.min()) >= 0.0
+ assert float(out.max()) <= 1.0
+ assert "plasma" in aug._params
+ # The transform actually moved this fixture, so an identity would not satisfy the replay.
+ assert float((out - image).abs().max()) > 0.03
+ assert torch.equal(aug(image, params=aug._params), out)
+
+ # Issue #4570: with same_on_batch=True the three RandomPlasma* classes share their scalar draws, but
+ # diamond_square draws one fractal map per sample, so identical inputs can come back different. #3624
+ # reported this together with RandomGaussianNoise and RandomChannelShuffle, and #3723 fixed only those two.
+ # The maps differ on every draw; the outputs need not. RandomPlasmaShadow shades a pixel only where its
+ # map is below the shared `shade_quantity`, so a high quantity shades every pixel alike -- on this 0.3
+ # fixture its outputs are identical for 66 of seeds 0..199 (0 for the other two classes) -- and its
+ # output leg is not asserted.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); aug = K.RandomPlasmaBrightness(p=1.0, same_on_batch=True)
+ # y = aug(torch.full((4, 3, 8, 8), 0.3)); print(torch.equal(aug._params["plasma"][0], aug._params["plasma"][1]))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `False` for all three classes, with the outputs differing too.
+ @pytest.mark.parametrize("name", ["RandomPlasmaBrightness", "RandomPlasmaContrast", "RandomPlasmaShadow"])
+ def test_wart_plasma_same_on_batch_draws_one_map_per_sample_4570(self, device, dtype, name):
+ image = torch.full((4, 3, 8, 8), 0.3, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = getattr(K, name)(p=1.0, same_on_batch=True)
+ out = aug(image)
+ for key, value in aug._params.items():
+ if key not in ("plasma", "forward_input_shape"):
+ assert all(torch.equal(value[0], value[b]) for b in range(4)), f"{key} is not shared"
+ assert not torch.equal(aug._params["plasma"][0], aug._params["plasma"][1])
+ if name != "RandomPlasmaShadow":
+ assert not torch.equal(out[0], out[1])
+
+ # Row 6c-43 in its new state: the `math domain error` the audit saw on a one-pixel axis is gone,
+ # so a 1x1 and a 1x8 image now run and keep their shape.
+ # Snippet used to generate expected:
+ # for shape in ((1, 3, 1, 1), (1, 3, 1, 8), (1, 3, 8, 1)):
+ # torch.manual_seed(0); print(shape, K.RandomPlasmaBrightness(p=1.0)(torch.full(shape, 0.5)).shape)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> each shape comes back unchanged for all three classes.
+ @pytest.mark.parametrize("name", ["RandomPlasmaBrightness", "RandomPlasmaContrast", "RandomPlasmaShadow"])
+ @pytest.mark.parametrize("shape", [(1, 3, 1, 1), (1, 3, 1, 8), (1, 3, 8, 1)])
+ def test_convention_plasma_accepts_a_single_pixel_axis(self, device, dtype, name, shape):
+ image = torch.full(shape, 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ assert _plasma(name)(image).shape == shape
+
+ # Row 6c-16: ``mean`` and ``std`` accept a float, a 3-list, a 3-tuple, a 1-tensor, a 3-tensor and
+ # a per-sample (B, C) tensor, and every one of them actually rescales the image.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(4, 3, 6, 8)
+ # for m, s in ((0.5, 0.25), ([0.4, 0.5, 0.6], [0.2, 0.25, 0.3]), ...):
+ # torch.manual_seed(0); print((K.Normalize(mean=m, std=s, p=1.0)(x) - x).abs().max())
+ # torch.manual_seed(0); print((K.Denormalize(mean=m, std=s, p=1.0)(x) - x).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> Normalize moves the tensor by 1.99809 (scalar and
+ # 1-element forms) or 1.99851 (3-element forms); Denormalize, which multiplies by std instead of
+ # dividing, moves it by 0.499522 and 0.599554 respectively.
+ @pytest.mark.parametrize("form", ["float", "list3", "tuple3", "tensor1", "tensor3", "tensorB3"])
+ @pytest.mark.parametrize(("cls", "moved"), [(K.Normalize, 1.0), (K.Denormalize, 0.25)])
+ def test_convention_normalize_accepts_scalar_sequence_and_per_sample_statistics(
+ self, device, dtype, cls, moved, form
+ ):
+ mean, std = _statistics(form, device, dtype)
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(4, 3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = cls(mean=mean, std=std, p=1.0)(image)
+ assert out.shape == image.shape
+ assert float((out - image).abs().max()) > moved
+ if form == "tensorB3":
+ # Even with distinct rows the threshold above cannot tell a per-sample application from a
+ # row-0 one, so assert the exact field: replacing `mean` with `mean[0]` inside
+ # kornia.enhance.normalize (or denormalize) leaves every other assertion here green.
+ stats = torch.arange(1, 13, device=device, dtype=dtype).reshape(4, 3) / 10.0
+ field = stats[..., None, None]
+ torch.manual_seed(_FORWARD_SEED)
+ per_sample = cls(mean=stats, std=stats, p=1.0)(image)
+ expected = image * field + field if cls is K.Denormalize else (image - field) / field
+ self.assert_close(per_sample, expected)
+
+ # Row 6c-16: Denormalize is Normalize's inverse, and the round trip is checked against a forward
+ # that actually moved the tensor (max abs change 1.99809 on this fixture) so the identity cannot
+ # be satisfied by a no-op.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(4, 3, 6, 8)
+ # y = K.Normalize(mean=0.5, std=0.25, p=1.0)(x); z = K.Denormalize(mean=0.5, std=0.25, p=1.0)(y)
+ # print((y - x).abs().max(), (z - x).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `1.99809` and `0` for the scalar form, `1.99851` and
+ # `5.96046e-08` for the 3-element forms.
+ @pytest.mark.parametrize("form", ["float", "list3", "tensor1", "tensorB3"])
+ def test_convention_denormalize_inverts_normalize(self, device, dtype, form):
+ mean, std = _statistics(form, device, dtype)
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(4, 3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ normalized = K.Normalize(mean=mean, std=std, p=1.0)(image)
+ assert float((normalized - image).abs().max()) > 1.0
+ torch.manual_seed(_FORWARD_SEED)
+ self.assert_close(K.Denormalize(mean=mean, std=std, p=1.0)(normalized), image)
+
+ # Issue #4577: `normalize` reshapes with `Tensor.view`, so a non-contiguous input raises a raw torch
+ # error naming neither the class nor the fix. `RandomAutoContrast` reaches `normalize_min_max` and
+ # fails the same way.
+ # Snippet used to generate expected:
+ # x = torch.rand(2, 3, 8, 8).transpose(2, 3)
+ # torch.manual_seed(0); K.Normalize(mean=torch.tensor([0.5]), std=torch.tensor([0.5]), p=1.0)(x)
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> `RuntimeError: view size is not
+ # compatible with input tensor's size and stride`; `.contiguous()` on the same view succeeds.
+ @pytest.mark.parametrize("name", ["Normalize", "RandomAutoContrast"])
+ def test_wart_non_contiguous_input_raises_a_raw_view_error_4577(self, device, dtype, name):
+ factories = {
+ "Normalize": lambda: K.Normalize(
+ mean=torch.tensor([0.5], device=device, dtype=dtype),
+ std=torch.tensor([0.5], device=device, dtype=dtype),
+ p=1.0,
+ ),
+ "RandomAutoContrast": lambda: K.RandomAutoContrast(p=1.0),
+ }
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 8, 8).to(device=device, dtype=dtype)
+ view = image.transpose(2, 3)
+ assert not view.is_contiguous()
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(RuntimeError, match="view size is not compatible") as excinfo:
+ _sync(factories[name]()(view).device)
+ # The frame that reshapes is `normalize` for Normalize and `normalize_min_max` for
+ # RandomAutoContrast, which never calls `normalize`; the class warnings name that function.
+ assert excinfo.traceback[-1].name == {"Normalize": "normalize", "RandomAutoContrast": "normalize_min_max"}[name]
+ # The same values, made contiguous, go through -- so it is the layout and not the numbers.
+ torch.manual_seed(_FORWARD_SEED)
+ assert factories[name]()(view.contiguous()).shape == view.shape
+
+ # Row 6c-16: a ``(B, C)`` statistic is applied per SAMPLE. The pins above use one fixture for all
+ # six forms, and their thresholds cannot tell a per-sample application from a row-0 or batch-mean
+ # one, so this row gives two identical samples different statistics and reads the two results.
+ # Snippet used to generate expected:
+ # x = torch.full((2, 1, 2, 2), 0.5)
+ # m = torch.tensor([[0.0], [0.5]]); s = torch.tensor([[1.0], [0.25]])
+ # torch.manual_seed(0); print(K.Normalize(mean=m, std=s, p=1.0)(x))
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> sample 0 comes back `0.5`
+ # throughout and sample 1 comes back `0.0` throughout.
+ def test_convention_normalize_applies_a_per_sample_statistic_to_its_own_sample(self, device, dtype):
+ image = torch.full((2, 1, 2, 2), 0.5, device=device, dtype=dtype)
+ mean = torch.tensor([[0.0], [0.5]], device=device, dtype=dtype)
+ std = torch.tensor([[1.0], [0.25]], device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.Normalize(mean=mean, std=std, p=1.0)(image)
+ self.assert_close(out[0], torch.full_like(out[0], 0.5))
+ self.assert_close(out[1], torch.zeros_like(out[1]))
+
+ # Row 6c-16: a mean or std whose length is neither 1 nor the channel count is rejected.
+ # Snippet used to generate expected: the last line of the snippet above; executed 2026-09-15
+ # (torch 2.14.0, cpu) -> `ValueError: mean length and number of channels do not match.`
+ @pytest.mark.parametrize("cls", [K.Normalize, K.Denormalize])
+ def test_convention_normalize_rejects_a_statistic_of_the_wrong_length(self, device, dtype, cls):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(4, 3, 6, 8).to(device=device, dtype=dtype)
+ mean = torch.tensor([0.4, 0.5], device=device, dtype=dtype)
+ std = torch.tensor([0.2, 0.25], device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(ValueError, match="do not match"):
+ _sync(cls(mean=mean, std=std, p=1.0)(image).device)
+
+ # Issue #4573: Normalize wraps an `int` mean or std into a tensor, Denormalize wraps only a `float`, so
+ # the pair built with `mean=0, std=255` cannot round-trip: Denormalize reaches kornia.enhance.denormalize
+ # with a bare int and fails there on the forward pass.
+ # Snippet used to generate expected:
+ # x = torch.rand(2, 3, 4, 4); y = K.Normalize(mean=0, std=255, p=1.0)(x); K.Denormalize(mean=0, std=255, p=1.0)(y)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `AttributeError: 'int' object has no attribute 'shape'`.
+ @pytest.mark.device_agnostic
+ def test_wart_denormalize_rejects_the_int_statistics_normalize_accepts_4573(self):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 4, 4)
+ normalized = K.Normalize(mean=0, std=255, p=1.0)(image)
+ self.assert_close(normalized, image / 255)
+ with pytest.raises(AttributeError, match="shape"):
+ K.Denormalize(mean=0, std=255, p=1.0)(normalized)
+ self.assert_close(K.Denormalize(mean=0.0, std=255.0, p=1.0)(normalized), image)
+
+ # Rows 6c-17 and 6c-18: Normalize and Denormalize hard-code ``same_on_batch=True`` (normalize.py
+ # and denormalize.py, `super().__init__(p=p, same_on_batch=True, keepdim=keepdim)`), so the
+ # constructor has no ``same_on_batch`` argument at all and ``p`` gates the whole batch together
+ # rather than sample by sample: ``batch_prob`` is all ones or all zeros, and the number of
+ # unchanged rows is exactly ``(batch_prob == 0).sum()``.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(8, 3, 6, 8)
+ # for seed in range(6):
+ # torch.manual_seed(seed); aug = K.Normalize(mean=0.5, std=0.25, p=0.5); y = aug(x)
+ # print(seed, sum(torch.equal(y[b], x[b]) for b in range(8)), aug._params["batch_prob"].tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> seeds 0 and 3 change all eight rows, seeds 1, 2, 4
+ # and 5 change none, and no seed in range(20) produced a mixed batch_prob for either class;
+ # `K.Normalize(mean=0.5, std=0.25, p=1.0, same_on_batch=True)` raises `TypeError:
+ # Normalize.__init__() got an unexpected keyword argument 'same_on_batch'`.
+ @pytest.mark.parametrize("cls", [K.Normalize, K.Denormalize])
+ def test_convention_normalize_p_gates_the_whole_batch(self, device, dtype, cls):
+ with pytest.raises(TypeError, match="same_on_batch"):
+ cls(mean=0.5, std=0.25, p=1.0, same_on_batch=True)
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(8, 3, 6, 8).to(device=device, dtype=dtype)
+ applied = 0
+ for seed in range(6):
+ torch.manual_seed(seed)
+ aug = cls(mean=0.5, std=0.25, p=0.5)
+ out = aug(image)
+ gate = aug._params["batch_prob"].flatten()
+ assert gate.shape == (8,)
+ unchanged = sum(1 for b in range(8) if torch.equal(out[b], image[b]))
+ assert unchanged == int((gate == 0).sum())
+ # The gate is shared by the batch, which is the visible consequence of same_on_batch=True.
+ assert len(set(gate.tolist())) == 1
+ applied += 8 - unchanged
+ # Both outcomes occur over these six seeds, so the equality above is not read off a
+ # degenerate all-on or all-off run.
+ assert 0 < applied < 48
+ # p=0.0 is the identity.
+ torch.manual_seed(_FORWARD_SEED)
+ assert torch.equal(cls(mean=0.5, std=0.25, p=0.0)(image), image)
+
+ # Row 6c-16: both classes keep their statistics in ``flags`` rather than as buffers, so
+ # ``state_dict()`` is empty and a ``Module.to(...)`` does not reach them -- the statistics are
+ # not carried by the module's own dtype/device machinery and do not survive a checkpoint round
+ # trip. (The 6a pin test_convention_augmentations_are_stateless_modules covers Normalize as one
+ # of five stateless representatives; this one adds Denormalize and names where the statistics
+ # actually live.)
+ # Snippet used to generate expected:
+ # aug = K.Normalize(mean=0.5, std=0.25, p=1.0)
+ # print(list(aug.state_dict()), [n for n, _ in aug.named_buffers()], list(aug.flags))
+ # before = aug.flags["mean"].clone(); aug = aug.to(torch.float64)
+ # print(aug.flags["mean"].dtype, torch.equal(aug.flags["mean"], before))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `[] [] ['mean', 'std']` and, after
+ # `.to(torch.float64)`, `torch.float32 True` -- unchanged -- for both classes.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("cls", [K.Normalize, K.Denormalize])
+ def test_convention_normalize_keeps_no_state(self, cls):
+ aug = cls(mean=0.5, std=0.25, p=1.0)
+ assert list(aug.state_dict()) == []
+ assert [name for name, _ in aug.named_buffers()] == []
+ assert sorted(aug.flags) == ["mean", "std"]
+ # `.to()` walks parameters and buffers; the statistics are in neither, so it leaves them be.
+ before = aug.flags["mean"].clone()
+ moved = aug.to(torch.float64)
+ assert moved.flags["mean"].dtype == torch.float32
+ assert torch.equal(moved.flags["mean"], before)
+
+ # Row 6c-46: an unbatched (C, H, W) input is promoted to (1, C, H, W), and ``keepdim=True``
+ # returns the unbatched shape again. Checked on four classes of this half -- one filter, one
+ # noise, one weather and one normalization -- so the claim is the package convention rather than
+ # one implementation. Every class of this half accepts ``keepdim``.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(3, 6, 8)
+ # torch.manual_seed(0); print(ctor(keepdim=False)(x).shape, ctor(keepdim=True)(x).shape)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `(1, 3, 6, 8)` and `(3, 6, 8)` for Normalize,
+ # RandomSaltAndPepperNoise, RandomGaussianIllumination and RandomRain.
+ @pytest.mark.parametrize(
+ "name", ["Normalize", "RandomSaltAndPepperNoise", "RandomGaussianIllumination", "RandomRain"]
+ )
+ def test_convention_intensity_ops_promote_chw_to_bchw(self, device, dtype, name):
+ factories = {
+ "Normalize": lambda keepdim: K.Normalize(mean=0.5, std=0.25, p=1.0, keepdim=keepdim),
+ "RandomSaltAndPepperNoise": lambda keepdim: K.RandomSaltAndPepperNoise(
+ amount=(0.3, 0.3), p=1.0, keepdim=keepdim
+ ),
+ "RandomGaussianIllumination": lambda keepdim: K.RandomGaussianIllumination(
+ gain=(0.5, 0.5), p=1.0, keepdim=keepdim
+ ),
+ "RandomRain": lambda keepdim: K.RandomRain(
+ number_of_drops=(2, 2), drop_height=(2, 2), drop_width=(1, 1), p=1.0, keepdim=keepdim
+ ),
+ }
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ assert factories[name](False)(image).shape == (1, 3, 6, 8)
+ torch.manual_seed(_FORWARD_SEED)
+ assert factories[name](True)(image).shape == (3, 6, 8)
+
+
+def _illumination(name: str, **kwargs):
+ """Point-range constructors for the three *Illumination classes, as the audit probe used them."""
+ classes = {
+ "RandomGaussianIllumination": K.RandomGaussianIllumination,
+ "RandomLinearIllumination": K.RandomLinearIllumination,
+ "RandomLinearCornerIllumination": K.RandomLinearCornerIllumination,
+ }
+ kwargs.setdefault("gain", (0.5, 0.5))
+ return classes[name](p=1.0, **kwargs)
+
+
+def _plasma(name: str):
+ """Default constructors for the three RandomPlasma* classes."""
+ factories = {
+ "RandomPlasmaBrightness": lambda: K.RandomPlasmaBrightness(p=1.0),
+ "RandomPlasmaContrast": lambda: K.RandomPlasmaContrast(p=1.0),
+ "RandomPlasmaShadow": lambda: K.RandomPlasmaShadow(p=1.0),
+ }
+ return factories[name]()
+
+
+def _field_augmentation(name: str, p: float = 1.0, keepdim: bool = False):
+ """Return a field-producing augmentation, its parameter key, and its field channel count."""
+ factories = {
+ "RandomGaussianNoise": lambda: (
+ K.RandomGaussianNoise(mean=0.0, std=1.0, p=p, keepdim=keepdim),
+ "gaussian_noise",
+ 3,
+ ),
+ "RandomGaussianIllumination": lambda: (
+ K.RandomGaussianIllumination(gain=(0.1, 0.1), p=p, keepdim=keepdim),
+ "gradient",
+ 3,
+ ),
+ "RandomLinearIllumination": lambda: (
+ K.RandomLinearIllumination(gain=(0.1, 0.1), p=p, keepdim=keepdim),
+ "gradient",
+ 3,
+ ),
+ "RandomLinearCornerIllumination": lambda: (
+ K.RandomLinearCornerIllumination(gain=(0.1, 0.1), p=p, keepdim=keepdim),
+ "gradient",
+ 3,
+ ),
+ "RandomPlasmaBrightness": lambda: (K.RandomPlasmaBrightness(p=p, keepdim=keepdim), "plasma", 3),
+ "RandomPlasmaContrast": lambda: (K.RandomPlasmaContrast(p=p, keepdim=keepdim), "plasma", 3),
+ "RandomPlasmaShadow": lambda: (K.RandomPlasmaShadow(p=p, keepdim=keepdim), "plasma", 1),
+ }
+ return factories[name]()
+
+
+def _statistics(form: str, device, dtype):
+ """The six ``mean`` / ``std`` forms row 6c-16 records as accepted."""
+ if form == "float":
+ return 0.5, 0.25
+ if form == "list3":
+ return [0.4, 0.5, 0.6], [0.2, 0.25, 0.3]
+ if form == "tuple3":
+ return (0.4, 0.5, 0.6), (0.2, 0.25, 0.3)
+ if form == "tensor1":
+ return (
+ torch.tensor([0.5], device=device, dtype=dtype),
+ torch.tensor([0.25], device=device, dtype=dtype),
+ )
+ if form == "tensor3":
+ return (
+ torch.tensor([0.4, 0.5, 0.6], device=device, dtype=dtype),
+ torch.tensor([0.2, 0.25, 0.3], device=device, dtype=dtype),
+ )
+ assert form == "tensorB3"
+ # Distinct rows: a per-sample statistic whose rows are all equal is indistinguishable from the
+ # scalar form, so an implementation that read row 0 or the batch mean would pass unnoticed.
+ return (
+ torch.tensor(
+ [[0.40, 0.50, 0.60], [0.45, 0.55, 0.65], [0.35, 0.45, 0.55], [0.50, 0.60, 0.70]],
+ device=device,
+ dtype=dtype,
+ ),
+ torch.tensor(
+ [[0.20, 0.25, 0.30], [0.22, 0.27, 0.32], [0.18, 0.23, 0.28], [0.25, 0.30, 0.35]],
+ device=device,
+ dtype=dtype,
+ ),
+ )
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
new file mode 100644
index 000000000..0f8ed746b
--- /dev/null
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -0,0 +1,2100 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+import math
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+from kornia.augmentation.random_generator import RectangleEraseGenerator
+from kornia.core._compat import torch_version_ge
+from kornia.core.exceptions import BaseError, ImageError, ShapeError
+from kornia.enhance import (
+ AdjustBrightnessAccumulative,
+ adjust_brightness,
+ adjust_brightness_accumulative,
+ adjust_contrast,
+ adjust_hue,
+ adjust_saturation,
+ equalize_clahe,
+ normalize_min_max,
+ posterize,
+)
+
+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
+
+
[email protected](autouse=True)
+def _restore_global_rng(restore_torch_rng):
+ # Every pin below seeds the global RNG so its draw is reproducible. ``torch.manual_seed`` also
+ # reseeds the CUDA and MPS generators, so the root fixture (#4446) snapshots and restores all of
+ # them; ``fork_rng(devices=[])`` would restore the CPU generator only and shift the draw of an
+ # unseeded later test on an accelerator leg.
+ yield
+
+
+# Constructor arguments are verbatim from the 6c audit probe, so the executed literals below are
+# the ones the fact table records. Three classes on the intensity page have no row here:
+# ``RandomDissolving``, because constructing it can prompt for ``diffusers`` and download a
+# Stable-Diffusion checkpoint, and ``RandomClahe`` and ``RandomJPEG``, which are outside
+# ``kornia.augmentation.__all__`` and are pinned by their own tests below.
+_INTENSITY_FACTORIES = {
+ "ColorJiggle": lambda: K.ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0),
+ "ColorJitter": lambda: K.ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0),
+ "Denormalize": lambda: K.Denormalize(mean=torch.tensor([0.5]), std=torch.tensor([0.5]), p=1.0),
+ "Normalize": lambda: K.Normalize(mean=torch.tensor([0.5]), std=torch.tensor([0.5]), p=1.0),
+ "RandomAutoContrast": lambda: K.RandomAutoContrast(p=1.0),
+ "RandomBoxBlur": lambda: K.RandomBoxBlur(p=1.0),
+ "RandomBrightness": lambda: K.RandomBrightness((1.5, 1.5), p=1.0),
+ "RandomChannelDropout": lambda: K.RandomChannelDropout(p=1.0),
+ "RandomChannelShuffle": lambda: K.RandomChannelShuffle(p=1.0),
+ "RandomContrast": lambda: K.RandomContrast((1.5, 1.5), p=1.0),
+ "RandomEqualize": lambda: K.RandomEqualize(p=1.0),
+ "RandomErasing": lambda: K.RandomErasing(p=1.0),
+ "RandomGamma": lambda: K.RandomGamma((2.0, 2.0), (1.0, 1.0), p=1.0),
+ "RandomGaussianBlur": lambda: K.RandomGaussianBlur((3, 3), (1.0, 1.0), p=1.0),
+ "RandomGaussianIllumination": lambda: K.RandomGaussianIllumination(p=1.0),
+ "RandomGaussianNoise": lambda: K.RandomGaussianNoise(mean=0.0, std=0.1, p=1.0),
+ "RandomGrayscale": lambda: K.RandomGrayscale(p=1.0),
+ "RandomHue": lambda: K.RandomHue((0.25, 0.25), p=1.0),
+ "RandomInvert": lambda: K.RandomInvert(p=1.0),
+ "RandomLinearCornerIllumination": lambda: K.RandomLinearCornerIllumination(p=1.0),
+ "RandomLinearIllumination": lambda: K.RandomLinearIllumination(p=1.0),
+ "RandomMedianBlur": lambda: K.RandomMedianBlur(p=1.0),
+ "RandomMotionBlur": lambda: K.RandomMotionBlur(3, (45.0, 45.0), (0.0, 0.0), p=1.0),
+ "RandomPlanckianJitter": lambda: K.RandomPlanckianJitter(p=1.0),
+ "RandomPlasmaBrightness": lambda: K.RandomPlasmaBrightness(p=1.0),
+ "RandomPlasmaContrast": lambda: K.RandomPlasmaContrast(p=1.0),
+ "RandomPlasmaShadow": lambda: K.RandomPlasmaShadow(p=1.0),
+ # A range, not the scalar `bits=3`, which is the LOWER bound of [3, 8]: a draw of 8 skips the
+ # uint8 round trip and keeps the fixture's range, so the scalar form put this factory outside
+ # `_BOUNDED_ON_FIXTURES` on 37 of seeds 0..199 (first at seed 19, `bits_factor [8, 4]`,
+ # max 1.9748). The 8-bit behaviour stays pinned by
+ # test_wart_random_posterize_eight_bits_skips_the_round_trip_4430.
+ "RandomPosterize": lambda: K.RandomPosterize(bits=(3.0, 7.0), p=1.0),
+ "RandomRGBShift": lambda: K.RandomRGBShift(p=1.0),
+ "RandomRain": lambda: K.RandomRain(number_of_drops=(3, 3), drop_height=(1, 2), drop_width=(1, 2), p=1.0),
+ "RandomSaltAndPepperNoise": lambda: K.RandomSaltAndPepperNoise(p=1.0),
+ "RandomSaturation": lambda: K.RandomSaturation((2.0, 2.0), p=1.0),
+ "RandomSharpness": lambda: K.RandomSharpness(1.0, p=1.0),
+ "RandomSnow": lambda: K.RandomSnow(p=1.0),
+ "RandomSolarize": lambda: K.RandomSolarize(0.1, 0.1, p=1.0),
+}
+
+# Row 6c-01: four observed outcomes for these constructor arguments, seeds and fixtures (#4430).
+# These are not class-wide policies: a different input or configuration can change the group.
+# For example, a blur can attenuate an out-of-range impulse into [0, 1], and hue-only ColorJiggle
+# can preserve an out-of-range maximum.
+_BOUNDED_ON_FIXTURES = (
+ "ColorJiggle",
+ "ColorJitter",
+ "RandomAutoContrast",
+ "RandomBrightness",
+ "RandomContrast",
+ "RandomGamma",
+ "RandomGaussianIllumination",
+ "RandomLinearCornerIllumination",
+ "RandomLinearIllumination",
+ "RandomPlasmaBrightness",
+ "RandomPlasmaContrast",
+ "RandomPlasmaShadow",
+ "RandomPosterize",
+ "RandomRGBShift",
+ "RandomSharpness",
+ "RandomSolarize",
+)
+# Row 6c-04: ``output.clamp(max=1.0)`` only, so a negative input stays negative.
+_UPPER_BOUNDED_ON_FIXTURES = ("RandomPlanckianJitter",)
+_OUT_OF_RANGE_ON_FIXTURES = (
+ "Denormalize",
+ "Normalize",
+ "RandomBoxBlur",
+ "RandomChannelDropout",
+ "RandomChannelShuffle",
+ "RandomErasing",
+ "RandomGaussianBlur",
+ "RandomGaussianNoise",
+ "RandomGrayscale",
+ "RandomHue",
+ "RandomInvert",
+ "RandomMedianBlur",
+ "RandomMotionBlur",
+ "RandomRain",
+ "RandomSaltAndPepperNoise",
+ "RandomSaturation",
+ "RandomSnow",
+)
+# Row 6c-02, in the state #4489 left it: the only audited factory that rejects these fixtures.
+_REJECTS_AUDIT_FIXTURES = ("RandomEqualize",)
+
+# Row 6c-03: these nine factories return zeros for the negative fixture at seed 0 (#4430).
+# Positive illumination or solarize additions can instead lift negative inputs above zero, and so can
+# a ColorJitter contrast or saturation factor above 1 drawn ahead of its brightness step.
+# `RandomPosterize` is deliberately not here. It reaches zero on some platforms only: its
+# `(x * 255).to(torch.uint8)` conversion saturates a negative float to code 0 on macOS arm64 with
+# torch 2.14.0 (the vectorised path, from 8 elements up) and on MPS, but wraps modulo 256 on Linux
+# with torch 2.14.0, on torch 2.5.1 in every dtype and on torch 2.9.1 in the half dtypes, where the
+# same input comes back as a full-range posterized image. The collapse is therefore a property of
+# the running conversion kernel, not of kornia; what holds everywhere is pinned by
+# test_wart_random_posterize_out_of_range_wraps_4430 instead.
+_COLLAPSES_ON_NEGATIVE_FIXTURE = (
+ "ColorJitter",
+ "RandomContrast",
+ "RandomGaussianIllumination",
+ "RandomLinearIllumination",
+ "RandomLinearCornerIllumination",
+ "RandomPlasmaShadow",
+ "RandomSnow",
+ "RandomSharpness",
+ "RandomSolarize",
+)
+
+# Fixture seed for the shared out-of-range images, and the seed drawn immediately before each
+# construct-and-forward, exactly as the audit probe did it.
+_FIXTURE_SEED = 1234
+_FORWARD_SEED = 0
+
+_HALF = (torch.float16, torch.bfloat16)
+
+
+def _out_of_range_fixtures(device, dtype) -> dict[str, torch.Tensor]:
+ # One float32 CPU draw cast into the run's device/dtype, so every leg sees the same numbers.
+ torch.manual_seed(_FIXTURE_SEED)
+ base = torch.rand(2, 3, 6, 8).to(device=device, dtype=dtype)
+ return {"[0, 2]": base * 2.0, "[-1, 0]": base - 1.0}
+
+
+def _sync(device) -> None:
+ # MPS dispatches asynchronously, so a kernel error raised by the forward under test would
+ # otherwise surface inside an unrelated later test.
+ if device.type == "mps":
+ torch.mps.synchronize()
+
+
+def _run(name: str, image: torch.Tensor, seed: int | None = None) -> torch.Tensor:
+ torch.manual_seed(_FORWARD_SEED if seed is None else seed)
+ out = _INTENSITY_FACTORIES[name]()(image)
+ _sync(image.device)
+ return out
+
+
+class TestIntensityValueRangeConventions(BaseTester):
+ # Row 6c-01 (issue #4430): preserve the audit observations for these 35 specific factories
+ # and fixtures. Both the group membership and numerical extrema depend on the configuration
+ # and input; the counterexample tests below and in the ops file pin those qualifications.
+ # Additional mechanism caveats (executed 2026-09-15, torch 2.14.0, cpu):
+ # * `RandomBrightness` and `RandomContrast` are bounded only by their default
+ # `clip_output=True`. With `clip_output=False` the range is passed through:
+ # `RandomBrightness((1.5, 1.5), clip_output=False)` on `[0, 2]` gives `max=2.496` and
+ # `RandomContrast((1.5, 1.5), clip_output=False)` gives `max=2.99399` (audit row 6c-35,
+ # `R1 RandomBrightness(clip=False) in=[0,2] -> max=2.496`). The `(clip=False)` variants are
+ # deliberately outside `_INTENSITY_FACTORIES`, as they were outside the audit's count.
+ # * `RandomPosterize`'s `[0, 1]` output is a `uint8` round-trip, not a clamp: the conversion
+ # wraps or saturates depending on the platform and torch version, and the output bears no
+ # relation to the clamped input -- see test_wart_random_posterize_out_of_range_wraps_4430
+ # (audit row 6c-38). The `[0, 1]` bound holds on every platform for a sample that draws fewer
+ # than 8 bits, because a `uint8` code divided by 255 is in `[0, 1]` however the conversion got
+ # there. A sample that draws 8 skips the round trip and keeps its range
+ # (test_wart_random_posterize_eight_bits_skips_the_round_trip_4430), so the group membership
+ # rests on this seed's draw of `bits_factor` `[5, 7]`, not on `bits=3` in general.
+ # * `RandomAutoContrast` is a per-sample, per-channel min-max rescale, not a clamp: its
+ # `clip_output` flag is dead because `normalize_min_max` already returns `[0, 1]`
+ # (audit row 6c-35, #4436; pinned by test_convention_random_auto_contrast_is_normalize_min_max
+ # and, for the dead flag, by TestRandomAutoContrast::test_clip_output_does_not_change_the_output).
+ # Snippet used to generate expected (re-executed on 90650596):
+ # torch.manual_seed(1234); base = torch.rand(2, 3, 6, 8)
+ # for x in (base * 2.0, base - 1.0):
+ # for name, ctor in mk(): torch.manual_seed(0); print(name, ctor()(x).aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu), e.g. `RandomBrightness in=[0,2] -> min=0.501276
+ # max=1`, `RandomSnow in=[0,2] -> min=0.00127578 max=1.996`, `RandomPlanckianJitter
+ # in=[-1,0] -> min=-1.41941 max=-0.00200176`.
+ @pytest.mark.parametrize("name", sorted(_INTENSITY_FACTORIES))
+ def test_convention_value_range_on_audit_fixtures(self, device, dtype, name):
+ groups = (_BOUNDED_ON_FIXTURES, _UPPER_BOUNDED_ON_FIXTURES, _OUT_OF_RANGE_ON_FIXTURES, _REJECTS_AUDIT_FIXTURES)
+ assert tuple(len(group) for group in groups) == (16, 1, 17, 1)
+ assert set().union(*groups) == set(_INTENSITY_FACTORIES) and len(_INTENSITY_FACTORIES) == 35
+ if name in _REJECTS_AUDIT_FIXTURES and device.type == "cuda":
+ # torch._assert_async on a false condition is a device-side assert on CUDA, which poisons
+ # the context for every later test in the process. On MPS the check is skipped by design
+ # and the raw histogram gather raises instead (an AcceleratorError, a RuntimeError subclass).
+ pytest.skip("CUDA: the value assert is a device-side assert that invalidates the context")
+ if dtype == torch.float16 and name in ("ColorJiggle", "ColorJitter"):
+ pytest.skip(
+ "float16 only (#4560): the contrast step collapses the [-1, 0] fixture to exact zeros "
+ "and rgb_to_hsv's eps=1e-8 then underflows for a black pixel, so adjust_hue returns "
+ "NaN (adjust_hue(torch.zeros(1, 3, 2, 2, dtype=torch.float16), 0.1) is already NaN); "
+ "float32, float64 and bfloat16 are finite"
+ )
+ if name in ("RandomBoxBlur", "RandomGaussianBlur") and not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ fixtures = _out_of_range_fixtures(device, dtype)
+ if name in _REJECTS_AUDIT_FIXTURES:
+ # The rejection has to be the VALUE check, not any RuntimeError: on the CPU the message
+ # names the range, and on MPS the check is skipped so the raw gather error surfaces (#4600) --
+ # from torch 2.14; 2.5.1 and 2.9.1 leave the MPS gather unchecked and return silently.
+ if device.type == "mps" and not torch_version_ge(2, 14):
+ for image in fixtures.values():
+ out = _run(name, image)
+ assert bool(torch.isfinite(out).all())
+ return
+ rejection = r"\[0, 1\]" if device.type == "cpu" else "out of bounds"
+ for image in fixtures.values():
+ with pytest.raises(RuntimeError, match=rejection):
+ _run(name, image)
+ return
+ # A clamped output is exactly 0.0 or 1.0, and the pass-through outputs sit near 2.0 or
+ # -1.0, so a tolerance this loose still separates the groups in bfloat16.
+ tol = 1e-3
+ outputs = {tag: _run(name, image) for tag, image in fixtures.items()}
+ ranges = {tag: out.aminmax() for tag, out in outputs.items()}
+ # Both fixtures are already outside [0, 1], so the _OUT_OF_RANGE_ON_FIXTURES branch below is
+ # satisfied by the identity: replacing RandomInvert.apply_transform with `return input` left its
+ # parametrization green. Require the class to actually change a fixture, which is what makes "the
+ # range is passed through" a claim about the transform rather than about the input.
+ # The check is over several draws, not the one _FORWARD_SEED picks, because a neutral draw is
+ # legitimate for some classes: RandomChannelShuffle draws the identity permutation about one time
+ # in six, and RandomSaltAndPepperNoise's mask can select no pixel on a 6x8 image -- each returned
+ # its input on about 11 of seeds 0..199. An implementation that is the identity moves nothing on
+ # any seed, so the weaker claim still catches it.
+ moved = False
+ for seed in range(8):
+ for image in fixtures.values():
+ if not torch.equal(_run(name, image, seed=seed), image):
+ moved = True
+ break
+ if moved:
+ break
+ assert moved, f"{name} returned the audit fixtures unchanged on every seed tried"
+ if name in _BOUNDED_ON_FIXTURES:
+ for tag, (low, high) in ranges.items():
+ assert float(low) >= -tol, f"{name} on {tag} left the lower end unclamped"
+ assert float(high) <= 1 + tol, f"{name} on {tag} left the upper end unclamped"
+ # Reach: the bound is [0, 1], not a narrower interval that would also satisfy the above (a clamp
+ # into [0, 0.5] left every bounded class green). The classes whose draw is fixed by the factory
+ # reach 0 on the negative fixture and 1 on [0, 2]; the exceptions are what the draw can do after
+ # the clamp, measured over seeds 0..199: ColorJiggle's hue-only draws leave the negative minimum
+ # above 0 (24/200) and a brightness factor below 1 pulls the [0, 2] maximum back under 1 for
+ # ColorJiggle (54/200) and ColorJitter (53/200); RandomPosterize tops out at 252/255 after the
+ # uint8 round trip and RandomSolarize inverts everything above its threshold (200/200 each).
+ if name != "ColorJiggle":
+ assert float(ranges["[-1, 0]"][0]) <= tol, f"{name} on [-1, 0] does not reach 0"
+ if name not in ("ColorJiggle", "ColorJitter", "RandomPosterize", "RandomSolarize"):
+ assert float(ranges["[0, 2]"][1]) >= 1 - tol, f"{name} on [0, 2] does not reach 1"
+ elif name in _UPPER_BOUNDED_ON_FIXTURES:
+ for tag, (_, high) in ranges.items():
+ assert float(high) <= 1 + tol, f"{name} on {tag} left the upper end unclamped"
+ # The lower end is checked on the fixture that has one: [0, 2] is non-negative anyway.
+ negative_min = float(ranges["[-1, 0]"][0])
+ assert negative_min < -tol, f"{name} also clamped the lower end (min {negative_min})"
+ else:
+ assert name in _OUT_OF_RANGE_ON_FIXTURES
+ assert any(float(high) > 1 + tol or float(low) < -tol for low, high in ranges.values()), (
+ f"{name} kept the output inside [0, 1] on both out-of-range fixtures"
+ )
+
+ # Row 6c-35, the executable half of the first caveat above: `clip_output` is live on both classes.
+ # Snippet used to generate expected:
+ # x = torch.linspace(0, 1, 48).reshape(1, 1, 6, 8) * 2
+ # for cls in (K.RandomBrightness, K.RandomContrast):
+ # print(cls((1.5, 1.5), p=1.0)(x).max(), cls((1.5, 1.5), clip_output=False, p=1.0)(x).max())
+ # torch.manual_seed(1234); neg = torch.rand(2, 3, 6, 8) - 1
+ # for cls in (K.RandomBrightness, K.RandomContrast):
+ # print(cls((1.5, 1.5), clip_output=False, p=1.0)(neg).aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `1 / 2.5` and `1 / 3`; on the negative input the
+ # brightness shift of +0.5 gives `min=-0.471 max=0.498` and the contrast scale
+ # `min=-1.49904 max=-0.00300264`, both unclamped where the default returns zeros.
+ @pytest.mark.parametrize("name", ["RandomBrightness", "RandomContrast"])
+ def test_convention_brightness_and_contrast_clip_output_is_live(self, device, dtype, name):
+ cls = getattr(K, name)
+ ramp = (torch.linspace(0, 1, 48).reshape(1, 1, 6, 8) * 2).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ clipped = cls((1.5, 1.5), p=1.0)(ramp)
+ torch.manual_seed(_FORWARD_SEED)
+ raw = cls((1.5, 1.5), clip_output=False, p=1.0)(ramp)
+ self.assert_close(clipped.max(), clipped.new_tensor(1.0))
+ self.assert_close(raw.max(), raw.new_tensor(2.5 if name == "RandomBrightness" else 3.0))
+ negative = _out_of_range_fixtures(device, dtype)["[-1, 0]"]
+ torch.manual_seed(_FORWARD_SEED)
+ assert float(cls((1.5, 1.5), p=1.0)(negative).min()) >= 0.0
+ torch.manual_seed(_FORWARD_SEED)
+ assert float(cls((1.5, 1.5), clip_output=False, p=1.0)(negative).min()) < 0.0
+
+ @pytest.mark.parametrize(
+ ("name", "factor", "value", "expected"),
+ [("RandomBrightness", 1.5, -0.1, 0.4), ("RandomContrast", 0.5, 1.5, 0.75)],
+ )
+ def test_convention_unclipped_arithmetic_can_bring_input_into_range(
+ self, device, dtype, name, factor, value, expected
+ ):
+ # No clamp does not imply an out-of-range output: -0.1 + (1.5 - 1) = 0.4;
+ # 1.5 * 0.5 = 0.75. These complement the out-of-range outputs above.
+ image = torch.full((1, 3, 2, 2), value, device=device, dtype=dtype)
+ aug = getattr(K, name)((factor, factor), clip_output=False, p=1.0)
+ out = aug(image)
+ self.assert_close(out, torch.full_like(image, expected))
+
+ # Row 6c-01, the audit exclusions the anchor and conventions.rst name: the factories cover
+ # the classes this file executes, and the classes they leave out are exactly the
+ # three named there. RandomDissolving is excluded by method (constructing it downloads a
+ # Stable-Diffusion checkpoint, so it is never constructed here), and RandomClahe / RandomJPEG
+ # are outside kornia.augmentation.__all__ -- but all three are importable from
+ # kornia.augmentation and the last two are rendered on augmentation.intensity.rst, so a new
+ # intensity class would falsify the anchor sentence silently without this census.
+ # Snippet used to generate expected:
+ # base = K.IntensityAugmentationBase2D
+ # print(sorted(n for n, o in vars(K).items() if isinstance(o, type) and issubclass(o, base)
+ # and o is not base and o.__module__.startswith("kornia.augmentation._2d.intensity")))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> 38 concrete classes, 35 of them the keys of
+ # _INTENSITY_FACTORIES and the other three `['RandomClahe', 'RandomDissolving', 'RandomJPEG']`.
+ @pytest.mark.device_agnostic
+ def test_convention_intensity_split_carve_outs_are_exactly_three(self):
+ base = K.IntensityAugmentationBase2D
+ concrete = {
+ name
+ for name, obj in vars(K).items()
+ if isinstance(obj, type)
+ and issubclass(obj, base)
+ and obj is not base
+ and obj.__module__.startswith("kornia.augmentation._2d.intensity")
+ }
+ assert len(concrete) == 38
+ assert concrete - set(_INTENSITY_FACTORIES) == {"RandomClahe", "RandomDissolving", "RandomJPEG"}
+ assert set(_INTENSITY_FACTORIES) - concrete == set()
+
+ # Row 6c-03 (issue #4430): nine factories return zeros on this negative fixture at seed 0.
+ # This is not a guarantee for other draws, and the seed is therefore pinned as the literal `0`
+ # rather than read from `_FORWARD_SEED`: five of these nine depend on the draw, and overriding
+ # `_FORWARD_SEED` across seeds 0..199 fails on 145 of them for RandomLinearCornerIllumination,
+ # 143 for RandomSolarize and RandomLinearIllumination, 136 for RandomGaussianIllumination and 99
+ # for ColorJitter. The literal keeps the audit record honest -- and keeps a future reseed of the
+ # file from turning this row red for a reason that is not a regression.
+ # #4430 offers two outcomes (clamp, or reject as RandomEqualize now does), so this is a wart pin on
+ # today's behavior, not a strict xfail on a settled contract.
+ # These nine collapse through their own arithmetic, not through a dtype conversion, so the
+ # result is the same on every platform, torch version and dtype (`RandomPosterize`, whose
+ # collapse is a `uint8`-conversion artifact of one platform, is excluded above).
+ # Snippet used to generate expected: the r1 snippet above, reading the `in=[-1,0]` rows;
+ # executed 2026-09-15 on this worktree under torch 2.14.0 and under torch 2.5.1 (macOS arm64,
+ # cpu) -- all nine print `min=0 max=0` in both runs.
+ @pytest.mark.parametrize("name", _COLLAPSES_ON_NEGATIVE_FIXTURE)
+ def test_wart_intensity_negative_input_collapses_to_zero_4430(self, device, dtype, name):
+ if dtype == torch.float16 and name == "ColorJitter":
+ pytest.skip(
+ "float16 only (#4560): the collapsed image reaches adjust_hue, whose rgb_to_hsv gives a "
+ "NaN saturation for a black pixel there (eps=1e-8 underflows in float16)"
+ )
+ image = _out_of_range_fixtures(device, dtype)["[-1, 0]"]
+ assert float(_run(name, image, seed=0).abs().max()) == 0.0
+
+ # The anchor's census (issue #4430): on a constant `-1.0` image at the audited constructor arguments,
+ # 17 factories collapse, 15 of them on every one of seeds 0..4 and only ColorJiggle and
+ # RandomPlasmaContrast on some. Two of the 15 are artefacts of the constant image rather than of
+ # its sign -- Denormalize maps -1 to exactly 0 at mean=std=0.5 and RandomAutoContrast returns zeros
+ # for any constant image -- so neither collapses on the `[-1, 0)` audit fixture, where the draw
+ # decides for 7 of the 12 that do. The seeds are literal so a reseed of the file cannot turn the
+ # census red for a reason that is not a regression.
+ # Snippet used to generate expected:
+ # img = torch.full((2, 3, 6, 8), -1.0)
+ # for name, f in sorted(_INTENSITY_FACTORIES.items()):
+ # n = 0
+ # for s in range(5):
+ # torch.manual_seed(s)
+ # try: n += float(f()(img).abs().max()) == 0.0
+ # except RuntimeError: pass
+ # print(name, n)
+ # executed 2026-09-16 (torch 2.14.0, cpu, float32) -> 5 for the fifteen names below, 2 for
+ # ColorJiggle, 1 for RandomPlasmaContrast, 0 for the rest; RandomEqualize raises.
+ _COLLAPSES_ON_CONSTANT_MINUS_ONE = (
+ "ColorJitter",
+ "Denormalize",
+ "RandomAutoContrast",
+ "RandomBrightness",
+ "RandomContrast",
+ "RandomGaussianIllumination",
+ "RandomLinearCornerIllumination",
+ "RandomLinearIllumination",
+ "RandomPlasmaBrightness",
+ "RandomPlasmaShadow",
+ "RandomPosterize",
+ "RandomRGBShift",
+ "RandomSharpness",
+ "RandomSnow",
+ "RandomSolarize",
+ )
+
+ def test_wart_intensity_constant_negative_collapse_census_4430(self, device, dtype):
+ image = torch.full((2, 3, 6, 8), -1.0, device=device, dtype=dtype)
+ every, some = [], []
+ for name in sorted(_INTENSITY_FACTORIES):
+ if name == "RandomEqualize" or (dtype == torch.float16 and name in ("ColorJitter", "RandomSnow")):
+ continue # raises out of range; float16 ColorJitter (#4560) and RandomSnow (#4571) are NaN there
+ if name in ("RandomBoxBlur", "RandomGaussianBlur") and not supports_reflect_padding(device, dtype):
+ continue # torch 2.5.1 has no half reflection_pad2d on the CPU
+ zeros = sum(float(_run(name, image, seed=seed).abs().max()) == 0.0 for seed in range(5))
+ (every if zeros == 5 else some if zeros else []).append(name)
+ expected = set(self._COLLAPSES_ON_CONSTANT_MINUS_ONE)
+ if dtype == torch.float16:
+ expected -= {"ColorJitter", "RandomSnow"}
+ assert set(every) == expected
+ assert set(some) <= {"ColorJiggle", "RandomPlasmaContrast"}
+ # The two constant-image artefacts do not collapse the non-constant audit fixture on any of 20 seeds.
+ fixture = _out_of_range_fixtures(device, dtype)["[-1, 0]"]
+ for name in ("Denormalize", "RandomAutoContrast"):
+ assert all(float(_run(name, fixture, seed=seed).abs().max()) > 0.0 for seed in range(20))
+ assert float(_run("RandomAutoContrast", torch.full_like(image, 0.5)).abs().max()) == 0.0
+ self.assert_close(_run("Denormalize", torch.full_like(image, -0.5)), torch.full_like(image, 0.25))
+
+ # Row 6c-38 (issue #4430): RandomPosterize does not clamp an out-of-range input. It posterizes
+ # the `uint8` round-trip of the raw float, so the output is the posterization of whatever codes
+ # that conversion produced and bears no relation to the clamped input.
+ # What `(x * 255).to(torch.uint8)` does with a value outside `[0, 255]` is a property of the
+ # running kernel, not of kornia, and the platforms disagree: it wraps modulo 256 on Linux with
+ # torch 2.14.0 and on torch 2.5.1/2.9.1, saturates negatives to code 0 on macOS arm64 with
+ # torch 2.14.0 (the vectorised path, from 8 elements up; measured on
+ # `(torch.linspace(-1, -0.004, n) * 255).to(torch.uint8)`, n = 7 gives 7 distinct codes and
+ # n = 8 gives 1), and saturates both ends on MPS. An earlier revision of this pin asserted the
+ # macOS 2.14 collapse (`len(out.unique()) == 1`) and failed on five CI legs; the round-trip
+ # identity below is what holds on all of them, so the platform-dependent literals are gone.
+ # Snippet used to generate expected:
+ # print((torch.linspace(-1, 0, 48) * 255).to(torch.uint8).unique().numel()) # kernel probe
+ # g = (torch.arange(256, dtype=torch.float32) / 255.0).reshape(1, 1, 8, 32)
+ # for x in (g * 2.0, g - 1.0):
+ # torch.manual_seed(0); y = K.RandomPosterize(bits=(3.0, 3.0), p=1.0)(x)
+ # print(len(y.unique()), y.min().item(), y.max().item())
+ # executed 2026-09-15 on this worktree (macOS arm64, cpu, float32): probe `1`, then
+ # `8 0.0 0.8784313797950745` and `1 0.0 0.0` under torch 2.14.0; probe `48`, then
+ # `8 0.0 0.8784313797950745` and `8 0.0 0.8784313797950745` under torch 2.5.1. The probe tells
+ # a reader which of the two behaviours the kernel in front of them has; only the `[0, 2]`
+ # literals, which agree in both runs, are asserted.
+ @pytest.mark.parametrize("scale", ["[0, 2]", "[-1, 0]"])
+ def test_wart_random_posterize_out_of_range_wraps_4430(self, device, dtype, scale):
+ ramp = (torch.arange(256, dtype=torch.float32) / 255.0).reshape(1, 1, 8, 32).to(device=device, dtype=dtype)
+ image = ramp * 2.0 if scale == "[0, 2]" else ramp - 1.0
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomPosterize(bits=(3.0, 3.0), p=1.0)(image)
+ _sync(image.device)
+ # `bits_factor` is `tensor([3], dtype=torch.int32)` for `bits=(3.0, 3.0)`, and `posterize`
+ # takes the same one-element path for a plain `int`. `codes` reproduces the first of the
+ # two `uint8` conversions inside `posterize` (kornia/enhance/adjust.py::_right_shift) --
+ # the only one that ever sees an out-of-range value, since the second is handed a
+ # non-negative `codes / 2 ** shift <= 255`.
+ codes = (image * 255).to(torch.uint8)
+ expected = posterize(codes.to(dtype) / 255.0, 3)
+ clamped = posterize(image.clamp(0.0, 1.0), 3)
+ assert torch.equal(out, expected)
+ assert float(out.min()) >= 0.0
+ assert float(out.max()) <= 1.0
+ # A clamp-first implementation would return `clamped`; spelled out so the intent survives
+ # an edit to `expected`. The guard is a property of the kernel and the fixture, not of
+ # `expected`: a wrapping conversion sends the out-of-range half of the ramp to codes the
+ # clamped input cannot produce, while a saturating one sends them to exactly the clamped
+ # input's codes, which makes the two implementations numerically identical and leaves
+ # nothing to assert.
+ if not torch.equal(codes, (image.clamp(0.0, 1.0) * 255).to(torch.uint8)):
+ assert not torch.equal(out, clamped)
+ if scale == "[0, 2]":
+ assert len(out.unique()) == 8
+ self.assert_close(out.max(), out.new_tensor(224 / 255))
+
+ # Issue #4430, the other posterize path: kornia.enhance.posterize returns a sample that draws 8 bits
+ # unchanged (`torch.where(bits == 8, input, out)`), with no `uint8` round trip to bound it, so its
+ # out-of-range values survive. The int form draws 8 for part of the batch -- its lower-bound pin,
+ # test_convention_random_posterize_int_argument_is_a_lower_bound, reaches 8.
+ # Snippet used to generate expected:
+ # print(K.RandomPosterize(bits=(8.0, 8.0), p=1.0)(torch.tensor([1.7, -0.4, 2.5, 0.3]).reshape(1, 1, 1, 4)))
+ # torch.manual_seed(0)
+ # print((K.RandomPosterize(bits=3, p=1.0).forward_parameters((100000, 1, 2, 2))["bits_factor"] == 8).sum())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> the input unchanged, and `9986` of the 100000 draws.
+ def test_wart_random_posterize_eight_bits_skips_the_round_trip_4430(self, device, dtype):
+ image = torch.tensor([1.7, -0.4, 2.5, 0.3], device=device, dtype=dtype).reshape(1, 1, 1, 4)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomPosterize(bits=(8.0, 8.0), p=1.0)(image)
+ _sync(image.device)
+ assert torch.equal(out, image)
+
+ # Row 6c-05 (issue #4430), the failure the grouping run cannot see: RandomGamma is in
+ # _BOUNDED_ON_FIXTURES on the strength of `gamma=2.0`, but on a negative input `x ** gamma` is NaN
+ # for every non-integer gamma and the clamp propagates it. Only an integer gamma is finite, and
+ # of those only an even one keeps a non-zero value -- an odd power keeps the sign and the clamp
+ # floors it, which is the all-zero collapse #4430 is about. #4430 leaves two coherent outcomes
+ # open (clamp, or reject), so this is a wart pin on today's behavior, not a strict xfail.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); neg = torch.rand(2, 3, 6, 8) - 1.0
+ # for gamma in (0.5, 1.0, 1.5, 2.0, 3.0):
+ # torch.manual_seed(0); y = K.RandomGamma((gamma, gamma), (1.0, 1.0), p=1.0)(neg)
+ # print(gamma, bool(y.isnan().any()), bool(y.isnan().all()), y.nan_to_num().abs().max())
+ # executed 2026-09-15 (torch 2.14.0) on cpu float32/float64/float16/bfloat16 and mps float32,
+ # identical on every leg -> `0.5` and `1.5` NaN in every element; `1.0`, `2.0` and `3.0` finite,
+ # with max|out| `0` at gamma 1.0 and 3.0 and `0.998725` at gamma 2.0 (`0.999023` in float16,
+ # `1` in bfloat16, so only the inequality is asserted). The fixture has no exact zero
+ # (its maximum is -0.00200176 in float32), so the NaN is every element, not almost every one.
+ @pytest.mark.parametrize(("gamma", "nan_expected"), [(0.5, True), (1.5, True), (2.0, False), (3.0, False)])
+ def test_wart_random_gamma_negative_input_is_nan_4430(self, device, dtype, gamma, nan_expected):
+ image = _out_of_range_fixtures(device, dtype)["[-1, 0]"]
+ assert float(image.max()) < 0.0, "the fixture must be strictly negative for the power to be NaN"
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomGamma((gamma, gamma), (1.0, 1.0), p=1.0)(image)
+ _sync(image.device)
+ if nan_expected:
+ assert bool(out.isnan().all()), f"gamma={gamma} on a negative input should be NaN throughout"
+ else:
+ assert bool(out.isfinite().all()), f"an integer gamma={gamma} should stay finite"
+ # The even power is the control: it is the one integer gamma that survives the clamp,
+ # and it is the value `_INTENSITY_FACTORIES` uses -- which is what hides the NaN there.
+ non_zero = float(out.abs().max()) > 0.0
+ assert non_zero is (gamma == 2.0), f"gamma={gamma} gave max|out| {float(out.abs().max())}"
+
+ # Row 6c-02 in the state #4489 left it (#4431 closed): RandomEqualize is the one 2D intensity
+ # class that rejects an out-of-range input, and its message names the [0, 1] range it needs.
+ # The guard is `input * 255` inside (-1, 256), so `[0, 1.0001]` -- the audit's executed
+ # instance -- is still admitted; only past 256/255 does the histogram index go out of bounds.
+ # Snippet used to generate expected:
+ # g = torch.linspace(0, 1, 64).reshape(1, 1, 8, 8)
+ # for x in (g, g * 1.0001, g * 2, g - 1):
+ # torch.manual_seed(0); K.RandomEqualize(p=1.0)(x)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> the last two raise `RuntimeError: equalize expects
+ # input values in [0, 1]. Scale the image into that range first, for example image / 255.0 for
+ # 8-bit data.`, the first two return a 64-level image. MPS skips the value check, and the same two
+ # inputs raise the raw `gather: index ... is out of bounds` there (an AcceleratorError, which is a
+ # RuntimeError). The guard compares `input * 255` in the input's dtype, so `1.00390625` (1 + 1/256,
+ # under one code above 1) is admitted in float32 and float64 but rounds onto 256 and raises in float16.
+ def test_convention_random_equalize_rejects_out_of_range_with_named_range(self, device, dtype):
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")
+ # Only kornia's own check names the range; MPS skips it and surfaces torch's gather error from
+ # torch 2.14 (2.5.1 and 2.9.1 leave the MPS gather unchecked and return the image silently).
+ match = r"\[0, 1\]" if device.type == "cpu" else "out of bounds"
+ ramp = torch.linspace(0, 1, 64).reshape(1, 1, 8, 8).to(device=device, dtype=dtype)
+ for image in (ramp * 2.0, ramp - 1.0):
+ torch.manual_seed(_FORWARD_SEED)
+ if device.type == "mps" and not torch_version_ge(2, 14):
+ assert bool(torch.isfinite(K.RandomEqualize(p=1.0)(image)).all())
+ continue
+ with pytest.raises(RuntimeError, match=match):
+ _sync(K.RandomEqualize(p=1.0)(image).device)
+ # Less than one 8-bit code outside the range is admitted at either end: `ramp - 0.003` has
+ # `input * 255 > -1` everywhere, so its lookup index truncates to 0.
+ for image in (ramp, ramp * 1.0001, ramp - 0.003):
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomEqualize(p=1.0)(image)
+ assert out.shape == image.shape
+ assert torch.isfinite(out).all()
+ # bfloat16 cannot represent 1 + 1/256 at all, so that dtype has no row.
+ if dtype in (torch.float16, torch.float32, torch.float64):
+ edge = ramp.clone()
+ edge[0, 0, 0, 0] = 1.00390625
+ torch.manual_seed(_FORWARD_SEED)
+ if dtype == torch.float16:
+ with pytest.raises(RuntimeError, match=match):
+ _sync(K.RandomEqualize(p=1.0)(edge).device)
+ else:
+ assert K.RandomEqualize(p=1.0)(edge).shape == edge.shape
+
+ # Issue #4576: below p=1 the base computes the transform for the whole batch and then selects the
+ # rows the gate keeps (`_AugmentationBase.transform_inputs`), so a row the gate skips still reaches
+ # the value check and the backward pass. At p=0.0 RandomEqualize and RandomClahe raise for an image
+ # they never touch, and RandomGamma returns the input values but a NaN gradient where the discarded
+ # power's derivative is infinite.
+ # Snippet used to generate expected:
+ # g = torch.linspace(0, 1, 1024).reshape(1, 1, 32, 32); x = torch.cat([g, g * 2])
+ # torch.manual_seed(0); K.RandomEqualize(p=0.0)(x) # and K.RandomClahe(p=0.0)(x)
+ # v = torch.tensor([0.0, 0.25, 1.0]).reshape(1, 1, 1, 3).repeat(2, 1, 1, 1).requires_grad_()
+ # torch.manual_seed(0); y = K.RandomGamma((0.5, 0.5), (1.0, 1.0), p=0.0)(v); y.sum().backward()
+ # print(torch.equal(y, v), v.grad.flatten().tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu float16/bfloat16/float32/float64 and mps float32) -> both
+ # classes raise (`equalize expects input values in [0, 1]`, `index ... is out of bounds`), then
+ # `True [nan, 1.0, 1.0, nan, 1.0, 1.0]`.
+ def test_wart_p_gate_computes_the_skipped_samples_4576(self, device, dtype):
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the value asserts are device-side asserts that poison the context")
+ ramp = torch.linspace(0, 1, 1024).reshape(1, 1, 32, 32)
+ image = torch.cat([ramp, ramp * 2.0]).to(device=device, dtype=dtype)
+ for cls in (K.RandomEqualize, K.RandomClahe):
+ torch.manual_seed(_FORWARD_SEED)
+ # It has to be the value check that fires, not merely some RuntimeError: the claim is that
+ # the transform ran on a sample `p=0.0` was supposed to skip.
+ gate_rejection = r"\[0, 1\]|out of bounds" if device.type == "cpu" else "out of bounds"
+ if device.type == "mps" and not torch_version_ge(2, 14):
+ # The transform still runs on the skipped samples, but 2.5.1 leaves the MPS gather
+ # unchecked, so the out-of-range rows come back silently instead of raising.
+ assert bool(torch.isfinite(cls(p=0.0)(image)).all())
+ continue
+ with pytest.raises(RuntimeError, match=gate_rejection):
+ _sync(cls(p=0.0)(image).device)
+ values = torch.tensor([0.0, 0.25, 1.0]).reshape(1, 1, 1, 3).repeat(2, 1, 1, 1)
+ values = values.to(device=device, dtype=dtype).requires_grad_()
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomGamma((0.5, 0.5), (1.0, 1.0), p=0.0)(values)
+ assert torch.equal(out, values)
+ out.sum().backward()
+ assert bool(values.grad[..., 0].isnan().all())
+ self.assert_close(values.grad[..., 1:], torch.ones_like(values.grad[..., 1:]))
+
+
+class TestIntensityColourConventions(BaseTester):
+ # Row 6c-05: RandomGamma is `clamp(gain * x ** gamma, 0, 1)`; the clamp is not optional, so the
+ # class has no `clip_output` escape hatch the way RandomBrightness and RandomContrast do.
+ # Snippet used to generate expected:
+ # g = torch.linspace(0, 1, 48).reshape(1, 1, 6, 8)
+ # torch.manual_seed(0); y = K.RandomGamma((gamma, gamma), (gain, gain), p=1.0)(g)
+ # print((y - (gain * g ** gamma).clamp(0, 1)).abs().max(), (y - gain * g ** gamma).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0 / 1` at gamma=1.0 gain=2.0 and
+ # `5.96046e-08 / 0.5` at gamma=0.5 gain=1.5.
+ @pytest.mark.parametrize(("gamma", "gain", "unclamped_gap"), [(1.0, 2.0, 1.0), (0.5, 1.5, 0.5)])
+ def test_convention_random_gamma_is_clamped_gain_times_power(self, device, dtype, gamma, gain, unclamped_gap):
+ ramp = torch.linspace(0, 1, 48).reshape(1, 1, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomGamma((gamma, gamma), (gain, gain), p=1.0)(ramp)
+ raw = gain * ramp**gamma
+ self.assert_close(out, raw.clamp(0.0, 1.0))
+ assert float((out - raw).abs().max()) > unclamped_gap / 2
+
+ @pytest.mark.parametrize(("gain", "expected"), [(1.0, [1.0, 1.0, 1.0]), (0.1, [0.5, 0.2, 0.125])])
+ def test_convention_random_gamma_negative_exponent_on_mps_depends_on_gain(self, device, dtype, gain, expected):
+ if device.type != "mps":
+ pytest.skip("MPS only: CPU rejects negative gamma; CUDA would invalidate the context with a device assert")
+ # MPS skips the value check. At gamma=-1 the output is clamp(gain / input, 0, 1):
+ # gain=1 saturates every pixel here, while gain=0.1 preserves three distinct values.
+ image = torch.tensor([0.2, 0.5, 0.8], device=device, dtype=dtype).reshape(1, 3, 1, 1)
+ out = K.RandomGamma((-1.0, -1.0), (gain, gain), p=1.0)(image)
+ self.assert_close(out, image.new_tensor(expected).reshape_as(image))
+
+ def test_convention_random_saturation_clamps_hsv_without_a_final_rgb_clamp(self, device, dtype):
+ # Clamping HSV saturation removes the first pixel's negative RGB channel even at factor=1, and
+ # turns the all-negative third pixel gray at its largest channel (its saturation is negative).
+ # The second and fourth pixels, above 1 with no negative channel, keep their values, which a final
+ # RGB clamp would remove. The second one's zero hue avoids amplifying half-precision hue
+ # round-trip error at that larger value; the fourth comes back exact in float16 and bfloat16 too.
+ pixels = [[-0.1, 0.5, 0.5], [1.5, 0.0, 0.0], [-0.1, -0.5, -0.9], [2.0, 1.0, 0.5]]
+ image = torch.tensor(pixels, device=device, dtype=dtype).reshape(4, 3, 1, 1)
+ out = K.RandomSaturation((1.0, 1.0), p=1.0)(image)
+ expected = [[0.0, 0.5, 0.5], [1.5, 0.0, 0.0], [-0.1, -0.1, -0.1], [2.0, 1.0, 0.5]]
+ self.assert_close(out, image.new_tensor(expected).reshape_as(image))
+
+ # Rows 6c-06 and 6c-49: RandomBrightness re-bases its factor -- it passes `factor - 1` to
+ # kornia.enhance.adjust_brightness, whose identity is 0.0 -- while RandomContrast and
+ # RandomSaturation pass their factor through unchanged.
+ # Snippet used to generate expected:
+ # c = torch.full((1, 1, 2, 2), 0.4); px = torch.tensor([[0.6], [0.4], [0.2]]).reshape(1, 3, 1, 1)
+ # torch.manual_seed(0); print(K.RandomBrightness((1.5, 1.5), p=1.0)(c).flatten()[0])
+ # print(adjust_brightness(c, 1.5).flatten()[0], adjust_brightness(c, 0.5).flatten()[0])
+ # torch.manual_seed(0); print(K.RandomContrast((1.5, 1.5), p=1.0)(c).flatten()[0])
+ # torch.manual_seed(0); print(K.RandomSaturation((2.0, 2.0), p=1.0)(px).flatten())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0.9 | 1 | 0.9`, `0.6`, `[0.6, 0.3, 0]`.
+ def test_convention_brightness_factor_is_one_centred(self, device, dtype):
+ constant = torch.full((1, 1, 2, 2), 0.4, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ brightened = K.RandomBrightness((1.5, 1.5), p=1.0)(constant)
+ self.assert_close(brightened, adjust_brightness(constant, 0.5))
+ self.assert_close(brightened, torch.full_like(constant, 0.9))
+ assert float((brightened - adjust_brightness(constant, 1.5)).abs().max()) > 0.05
+
+ torch.manual_seed(_FORWARD_SEED)
+ contrasted = K.RandomContrast((1.5, 1.5), p=1.0)(constant)
+ self.assert_close(contrasted, adjust_contrast(constant, 1.5))
+ self.assert_close(contrasted, torch.full_like(constant, 0.6))
+
+ pixel = torch.tensor([[0.6], [0.4], [0.2]], device=device, dtype=dtype).reshape(1, 3, 1, 1)
+ torch.manual_seed(_FORWARD_SEED)
+ saturated = K.RandomSaturation((2.0, 2.0), p=1.0)(pixel)
+ self.assert_close(saturated, adjust_saturation(pixel, 2.0))
+ self.assert_close(saturated, pixel.new_tensor([0.6, 0.3, 0.0]).reshape(1, 3, 1, 1))
+
+ # Rows 6c-06 and 6c-49, the other side of the same claim: each class's identity factor is 1.0,
+ # which is what makes the RandomBrightness offset invisible until it is compared to the
+ # primitive. Checked on an asymmetric batch of two distinct samples.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, 3, 6, 8)
+ # torch.manual_seed(0); print((cls((1.0, 1.0), p=1.0)(x) - x).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0`, `0`, `4.17233e-07`.
+ @pytest.mark.parametrize("cls", [K.RandomBrightness, K.RandomContrast, K.RandomSaturation])
+ def test_convention_point_range_factor_one_is_identity(self, device, dtype, cls):
+ if dtype in _HALF and cls is K.RandomSaturation:
+ pytest.skip(
+ "half precision only: adjust_saturation's RGB -> HSV -> RGB round trip is lossy there, so "
+ "the identity holds only to 2.9e-3 in float16 and 3.1e-2 in bfloat16 (measured), not to "
+ "the dtype tolerance; RandomBrightness and RandomContrast are exact in both"
+ )
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ self.assert_close(cls((1.0, 1.0), p=1.0)(image), image)
+
+ # Rows 6c-07 and 6c-08: with matching effective ranges and default CPU float32 samplers, these
+ # configurations draw byte-identical parameters from the same seed, including the random `order`.
+ # The selected non-identity factors expose the different adjustment primitives.
+ # Replaying ColorJitter with ColorJiggle's own parameters reproduces the same gap, which is
+ # what rules out a sampling-order difference. The gap is fixture-bound (max|diff| 0.124188
+ # here), so only the inequality is asserted.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, 3, 6, 8)
+ # torch.manual_seed(7); a = K.ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0); ya = a(x)
+ # torch.manual_seed(7); b = K.ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0); yb = b(x)
+ # print((ya - yb).abs().max(), (ya - b(x, params=a._params)).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0.124188` twice, with `params equal: True` and
+ # the drawn `order` `[0, 3, 2, 1]` on both.
+ def test_convention_color_jiggle_and_jitter_matching_ranges_draw_identical_params(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(7)
+ jiggle = K.ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0)
+ jiggled = jiggle(image)
+ torch.manual_seed(7)
+ jitter = K.ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0)
+ jittered = jitter(image)
+ assert sorted(jiggle._params) == sorted(jitter._params)
+ assert "order" in jiggle._params
+ for key, value in jiggle._params.items():
+ assert torch.equal(value, jitter._params[key]), f"{key} differs between the two classes"
+ assert float((jiggled - jittered).abs().max()) > 0.05
+ # Replaying ColorJitter with ColorJiggle's own parameters reproduces ColorJitter's output,
+ # so the gap for this configuration is in application, not in the draw.
+ replayed = jitter(image, params=jiggle._params)
+ self.assert_close(replayed, jittered)
+ assert float((jiggled - replayed).abs().max()) > 0.05
+
+ @pytest.mark.device_agnostic
+ def test_convention_color_jiggle_and_jitter_have_different_brightness_bounds(self):
+ # Scalar brightness=3 is accepted by both, but yields [0, 2] for Jiggle and [0, 4] for Jitter.
+ # `(jitter > 2).any()` is a `1 - 2 ** -B` event, so it needs a batch wide enough to be certain:
+ # at the `B = 4` this pin first used it failed on 13 of seeds 0..199, and this literal seed is
+ # outside the `_FORWARD_SEED` sweep that would have caught it. At `B = 64` the failure
+ # probability is `2 ** -64`.
+ torch.manual_seed(7)
+ jiggle_params = K.ColorJiggle(brightness=3.0).forward_parameters((64, 3, 2, 2))
+ torch.manual_seed(7)
+ jitter_params = K.ColorJitter(brightness=3.0).forward_parameters((64, 3, 2, 2))
+ jiggle_brightness = jiggle_params["brightness_factor"]
+ jitter_brightness = jitter_params["brightness_factor"]
+ assert bool(((jiggle_brightness >= 0) & (jiggle_brightness <= 2)).all())
+ assert bool((jitter_brightness > 2).any())
+ self.assert_close(jitter_brightness, 2 * jiggle_brightness, atol=0, rtol=0)
+ for key in jiggle_params.keys() - {"brightness_factor"}:
+ assert torch.equal(jiggle_params[key], jitter_params[key]), key
+
+ @pytest.mark.parametrize("hue", [0.0, (0.1, 0.1)])
+ def test_convention_color_jiggle_can_leave_output_above_unit_range(self, device, dtype, hue):
+ # Disabled brightness/contrast steps do not clamp, and an HSV hue rotation preserves value.
+ image = torch.full((2, 3, 6, 8), 2.0, device=device, dtype=dtype)
+ out = K.ColorJiggle(0.0, 0.0, 0.0, hue, p=1.0)(image)
+ self.assert_close(out, image, atol=0, rtol=0)
+ # The constant fixture is achromatic, so the rotation is the identity on it whatever `hue` is
+ # and only the missing clamp is exercised above. A chromatic pixel makes the second half of
+ # the claim -- that the rotation preserves the out-of-range value -- discriminating.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0)
+ # K.ColorJiggle(0.0, 0.0, 0.0, (0.1, 0.1), p=1.0)(torch.tensor([2.0, 1.5, 0.5]).reshape(1, 3, 1, 1))
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `[1.5999999, 2.0, 0.5]`, whose maximum is the
+ # input's `2.0`.
+ chroma = torch.tensor([2.0, 1.5, 0.5], device=device, dtype=dtype).reshape(1, 3, 1, 1)
+ torch.manual_seed(_FORWARD_SEED)
+ rotated = K.ColorJiggle(0.0, 0.0, 0.0, hue, p=1.0)(chroma)
+ self.assert_close(rotated.amax(1), chroma.amax(1))
+ assert torch.equal(rotated, chroma) is (hue == 0.0)
+
+ # Row 6c-08: both classes are the identity at (0, 0, 0, 0), so the gap above is the primitives
+ # and not a stray factor. Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, 3, 6, 8)
+ # torch.manual_seed(0); print((cls(0, 0, 0, 0, p=1.0)(x) - x).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0` for both.
+ @pytest.mark.parametrize("cls", [K.ColorJiggle, K.ColorJitter])
+ def test_convention_color_jiggle_and_jitter_are_identity_at_zero(self, device, dtype, cls):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ self.assert_close(cls(0.0, 0.0, 0.0, 0.0, p=1.0)(image), image)
+
+ # Issue #4430, the ColorJiggle half: which steps run decides whether the collapse is draw-dependent.
+ # The all-zero default is the identity; contrast-only collapses on every draw; brightness-only and the
+ # audit's four-factor configuration on some; hue-only never. Literal seeds, as for the census above.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); neg = torch.rand(2, 3, 6, 8) - 1.0
+ # for args in ((0, 0.3, 0, 0), (0.3, 0, 0, 0), (0.2, 0.2, 0.2, 0.1), (0, 0, 0, 0.1)):
+ # n = 0
+ # for s in range(20):
+ # torch.manual_seed(s); n += float(K.ColorJiggle(*args, p=1.0)(neg).abs().max()) == 0.0
+ # print(args, n)
+ # executed 2026-09-16 (torch 2.14.0, cpu, float32) -> 20, 7, 7, 0; `ColorJiggle(p=1.0)(neg)` equals `neg`.
+ @pytest.mark.parametrize(
+ ("args", "lo", "hi"),
+ [
+ ((0.0, 0.3, 0.0, 0.0), 20, 20),
+ ((0.3, 0.0, 0.0, 0.0), 1, 19),
+ ((0.2, 0.2, 0.2, 0.1), 1, 19),
+ ((0.0, 0.0, 0.0, 0.1), 0, 0),
+ ],
+ )
+ def test_convention_color_jiggle_negative_collapse_depends_on_which_steps_run(self, device, dtype, args, lo, hi):
+ if dtype == torch.float16 and args[3] > 0.0:
+ pytest.skip("float16 only (#4560): the hue step returns NaN for a black pixel")
+ torch.manual_seed(_FIXTURE_SEED)
+ image = (torch.rand(2, 3, 6, 8) - 1.0).to(device=device, dtype=dtype)
+ assert torch.equal(K.ColorJiggle(p=1.0)(image), image)
+ zeros = 0
+ for seed in range(20):
+ torch.manual_seed(seed)
+ zeros += float(K.ColorJiggle(*args, p=1.0)(image).abs().max()) == 0.0
+ assert lo <= zeros <= hi
+
+ # Issue #4430, the ColorJitter half: the all-negative collapse depends on the drawn order. The
+ # brightness step, which the default scalar brightness runs, clamps what is still negative to zero,
+ # but a contrast or saturation factor above 1 applied before it lifts part of the image first -- with
+ # the random order the audit configuration ColorJitter(0.2, 0.2, 0.2, 0.1) keeps non-zero values for
+ # 18 of seeds 0..39 on the audit fixture. A fixed `order` makes both outcomes deterministic, and one
+ # without index 0 skips the brightness clamp, so the default factors pass an out-of-range value.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); neg = torch.rand(1, 3, 8, 8) - 1.0
+ # for step, kw in ((1, dict(contrast=(1.9, 1.9))), (2, dict(saturation=(1.9, 1.9)))):
+ # for order in ((0, step), (step, 0)):
+ # print(order, K.ColorJitter(p=1.0, order=order, **kw)(neg).aminmax())
+ # print(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0, order=(1, 2, 3))(torch.full((1, 3, 2, 2), 2.0)).unique())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> brightness first `0 / 0` for both; contrast first
+ # `0 / 0.453` and saturation first `0 / 0.669` (0.449 and 0.664 in bfloat16); `[2.0]`.
+ @pytest.mark.parametrize(("step", "kwargs"), [(1, {"contrast": (1.9, 1.9)}), (2, {"saturation": (1.9, 1.9)})])
+ def test_convention_color_jitter_negative_collapse_depends_on_the_order(self, device, dtype, step, kwargs):
+ torch.manual_seed(_FIXTURE_SEED)
+ negative = (torch.rand(1, 3, 8, 8) - 1.0).to(device=device, dtype=dtype)
+ brightness_first = K.ColorJitter(p=1.0, order=(0, step), **kwargs)(negative)
+ assert float(brightness_first.abs().max()) == 0.0
+ step_first = K.ColorJitter(p=1.0, order=(step, 0), **kwargs)(negative)
+ assert float(step_first.min()) >= 0.0
+ assert float(step_first.max()) > 0.25
+ # Leaving index 0 out of a fixed order skips the brightness step and its clamp.
+ above = torch.full((1, 3, 2, 2), 2.0, device=device, dtype=dtype)
+ self.assert_close(K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0, order=(1, 2, 3))(above), above)
+
+ # Row 6c-08, the order and channel-count details:
+ # - a fixed constructor `order` ignores a forward `order=` tensor;
+ # - ColorJiggle has no constructor order, and a forward `order=` tensor replaces the drawn one, so
+ # leaving the hue step out lets a one-channel image through;
+ # - ColorJitter's saturation step (adjust_saturation_with_gray_subtraction) rejects four channels,
+ # clamps a three-channel image, and returns a one-channel image unchanged.
+ # Snippet used to generate expected:
+ # x = torch.rand(2, 3, 4, 4); torch.manual_seed(0)
+ # a = K.ColorJitter(brightness=(0.5, 0.5), order=(1,), p=1.0)
+ # print(torch.equal(a(x, order=torch.tensor([0])), a(x)))
+ # print(K.ColorJiggle(hue=0.1, p=1.0)(torch.rand(2, 1, 4, 4), order=torch.tensor([0, 1, 2])).shape)
+ # s = K.ColorJitter(saturation=(0.5, 0.5), order=(2,), p=1.0)
+ # print(s(torch.full((2, 1, 3, 3), 2.0)).unique(), s(torch.full((2, 3, 3, 3), 2.0)).unique())
+ # s(torch.rand(2, 4, 3, 3))
+ # executed 2026-09-15 (torch 2.14.0, cpu float16/bfloat16/float32/float64 and mps float32) -> `True`,
+ # `(2, 1, 4, 4)` (without `order=`: `ValueError: Input size must have a shape of (*, 3, H, W)`),
+ # `[2.]`, `[1.]`, and `ImageError: Not a color or gray tensor.`
+ def test_convention_color_jitter_order_override_and_channel_counts(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 4, 4).to(device=device, dtype=dtype)
+ fixed = K.ColorJitter(brightness=(0.5, 0.5), order=(1,), p=1.0)
+ torch.manual_seed(_FORWARD_SEED)
+ assert torch.equal(fixed(image, order=torch.tensor([0])), fixed(image))
+ assert float((K.ColorJitter(brightness=(0.5, 0.5), p=1.0, order=(0,))(image) - image).abs().max()) > 0.1
+
+ gray = image[:, :1].contiguous()
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(ValueError, match="shape of"):
+ K.ColorJiggle(hue=0.1, p=1.0)(gray)
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.ColorJiggle(hue=0.1, p=1.0)(gray, order=torch.tensor([0, 1, 2])).shape == gray.shape
+
+ saturation = K.ColorJitter(saturation=(0.5, 0.5), order=(2,), p=1.0)
+ two = torch.full((2, 1, 3, 3), 2.0, device=device, dtype=dtype)
+ self.assert_close(saturation(two), two)
+ self.assert_close(saturation(two.expand(2, 3, 3, 3)), torch.ones_like(two.expand(2, 3, 3, 3)))
+ four_channel = torch.rand(2, 4, 3, 3).to(device=device, dtype=dtype)
+ with pytest.raises(BaseError, match="Not a color or gray tensor"):
+ saturation(four_channel)
+
+ # `adjust_brightness_accumulative`, ColorJitter's brightness primitive, multiplies by the factor and
+ # clamps by default, so its identity factor `1` holds only for an image in [0, 1]; the module form
+ # AdjustBrightnessAccumulative always clamps.
+ # Snippet used to generate expected:
+ # x = torch.tensor([-0.5, 0.5, 2.0]).reshape(1, 3, 1, 1)
+ # print(adjust_brightness_accumulative(x, 1.0).flatten(), AdjustBrightnessAccumulative(1.0)(x).flatten())
+ # executed 2026-09-15 (torch 2.14.0, cpu float16/bfloat16/float32/float64 and mps float32) -> `[0, 0.5, 1]`
+ # twice.
+ def test_convention_adjust_brightness_accumulative_one_is_identity_only_in_range(self, device, dtype):
+ values = torch.tensor([-0.5, 0.5, 2.0], device=device, dtype=dtype).reshape(1, 3, 1, 1)
+ expected = values.clamp(0.0, 1.0)
+ self.assert_close(adjust_brightness_accumulative(values, 1.0), expected)
+ self.assert_close(AdjustBrightnessAccumulative(1.0)(values), expected)
+ self.assert_close(adjust_brightness_accumulative(values, 1.0, clip_output=False), values)
+ self.assert_close(adjust_brightness_accumulative(values, 0.0), torch.zeros_like(values))
+
+ # Row 6c-10: RandomHue's argument is turns of the hue circle, restricted to the closed [-0.5, 0.5];
+ # the class multiplies it by 2*pi before calling kornia.enhance.adjust_hue, which takes radians.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, 3, 6, 8)
+ # torch.manual_seed(0); y = K.RandomHue((0.25, 0.25), p=1.0)(x)
+ # print((y - adjust_hue(x, 0.25 * 2 * math.pi)).abs().max(), (y - adjust_hue(x, 0.25)).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0` and `0.87243`.
+ def test_convention_random_hue_is_turns_of_the_hue_circle(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomHue((0.25, 0.25), p=1.0)(image)
+ self.assert_close(out, adjust_hue(image, 0.25 * 2 * math.pi))
+ assert float((out - adjust_hue(image, 0.25)).abs().max()) > 0.5
+ # The [-0.5, 0.5] bound that goes with those units is pinned from outside in
+ # test_convention_intensity_constructors_reject_out_of_bounds.
+
+ # Row 6c-10, the range half: RandomHue has no clamp, and a hue rotation keeps each pixel's largest and
+ # smallest channel values, so a pixel outside [0, 1] keeps a channel outside it. The exception is a
+ # pixel whose largest channel is exactly 0, whose HSV saturation divides by that zero: the round trip
+ # returns zeros, and NaN in float16 (the #4560 underflow, which reaches a zero-max pixel that is not
+ # black as well).
+ # Snippet used to generate expected:
+ # x = torch.tensor([[1.5, 0.2, 0.3], [0.5, -0.1, 0.2], [-0.2, -0.5, -0.9], [0.0, -0.5, -0.5]])
+ # torch.manual_seed(0); print(K.RandomHue((0.25, 0.25), p=1.0)(x.reshape(4, 3, 1, 1)).reshape(4, 3))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `[[0.95, 1.5, 0.2], [0.5, 0.5, -0.1], [-0.9, -0.2, -0.85],
+ # [-0, 0, -0]]`.
+ def test_convention_random_hue_keeps_out_of_range_extremes(self, device, dtype):
+ pixels = torch.tensor([[1.5, 0.2, 0.3], [0.5, -0.1, 0.2], [-0.2, -0.5, -0.9]], device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomHue((0.25, 0.25), p=1.0)(pixels.reshape(3, 3, 1, 1)).reshape(3, 3)
+ self.assert_close(out.amax(1), pixels.amax(1))
+ self.assert_close(out.amin(1), pixels.amin(1))
+ zero_max = torch.tensor([0.0, -0.5, -0.5], device=device, dtype=dtype).reshape(1, 3, 1, 1)
+ torch.manual_seed(_FORWARD_SEED)
+ collapsed = K.RandomHue((0.25, 0.25), p=1.0)(zero_max)
+ if dtype == torch.float16:
+ assert bool(collapsed.isnan().any())
+ else:
+ self.assert_close(collapsed, torch.zeros_like(collapsed))
+
+ # Row 6c-11: RandomGrayscale keeps the channel count and writes the same value into every
+ # channel; the default weights are the ITU-R BT.601 luma weights, so a pure red pixel becomes
+ # 0.299, and custom weights replace them wholesale.
+ # Snippet used to generate expected:
+ # x = torch.zeros(1, 3, 6, 8); x[0, 0] = 1.0
+ # torch.manual_seed(0); print(K.RandomGrayscale(p=1.0)(x)[0, 0, 0, 0])
+ # torch.manual_seed(0)
+ # print(K.RandomGrayscale(rgb_weights=torch.tensor([1.0, 0.0, 0.0]), p=1.0)(x)[0, 0, 0, 0])
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0.299` and `1`.
+ def test_convention_random_grayscale_keeps_channels_and_weights(self, device, dtype):
+ red = torch.zeros(1, 3, 6, 8, device=device, dtype=dtype)
+ red[0, 0] = 1.0
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomGrayscale(p=1.0)(red)
+ assert out.shape == red.shape
+ self.assert_close(out, out[:, :1].expand_as(out))
+ self.assert_close(out[0, 0, 0, 0], out.new_tensor(0.299))
+ weights = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ weighted = K.RandomGrayscale(rgb_weights=weights, p=1.0)(red)
+ self.assert_close(weighted[0, 0, 0, 0], weighted.new_tensor(1.0))
+ # Channel mixing can put out-of-range input back in range without clamping it.
+ reduced = K.RandomGrayscale(p=1.0)(2 * red)
+ self.assert_close(reduced, torch.full_like(red, 0.598))
+ # The weights are applied AS GIVEN. Every weights vector above sums to one, so an
+ # implementation that normalized them would pass; these two do not sum to one.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); half = torch.full((1, 3, 2, 2), 0.5)
+ # print(K.RandomGrayscale(rgb_weights=torch.ones(3), p=1.0)(half)[0, 0, 0, 0])
+ # torch.manual_seed(0); print(K.RandomGrayscale(p=1.0)(torch.full((1, 4, 2, 2), 0.5))[0, 0, 0, 0])
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> `1.5`; the 4-channel branch
+ # averages instead and gives `0.5`, so `torch.ones(4)` there gives `2.0`.
+ half = torch.full((1, 3, 2, 2), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ unnormalized = K.RandomGrayscale(rgb_weights=torch.ones(3, device=device, dtype=dtype), p=1.0)(half)
+ self.assert_close(unnormalized, torch.full_like(half, 1.5))
+ wide = torch.full((1, 4, 2, 2), 0.5, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ wide_out = K.RandomGrayscale(rgb_weights=torch.ones(4, device=device, dtype=dtype), p=1.0)(wide)
+ self.assert_close(wide_out, torch.full_like(wide, 2.0))
+
+ # Row 6c-11, one parameter away from the pin above: a non-RGB channel count is not rejected --
+ # the channel count is preserved and every channel becomes the plain mean over channels.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(1, C, 6, 8)
+ # torch.manual_seed(0); y = K.RandomGrayscale(p=1.0)(x)
+ # print(y.shape, (y - x.mean(1, keepdim=True)).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `(1, C, 6, 8)` and `0` for C in (1, 2, 4).
+ @pytest.mark.parametrize("channels", [1, 2, 4])
+ def test_convention_random_grayscale_non_rgb_is_the_channel_mean(self, device, dtype, channels):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(1, channels, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomGrayscale(p=1.0)(image)
+ assert out.shape == image.shape
+ self.assert_close(out, image.mean(1, keepdim=True).expand_as(image))
+
+ # Row 6c-14: out channel `c` is in channel `channels[b][c]` -- the drawn index reads the source,
+ # it does not name the destination -- and the permutation is drawn per sample. The claim is a
+ # labelling, so it is checked against the drawn permutation of every sample rather than against
+ # one literal, on per-sample constant planes 0..11 that make the relabelling visible.
+ # Snippet used to generate expected:
+ # x = torch.arange(12, dtype=torch.float32).reshape(4, 3, 1, 1).expand(4, 3, 6, 8)
+ # torch.manual_seed(0); a = K.RandomChannelShuffle(p=1.0); y = a(x.contiguous())
+ # print(a._params["channels"].tolist(), x[:, :, 0, 0].tolist(), y[:, :, 0, 0].tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> channels `[[2, 0, 1], [0, 1, 2], [2, 0, 1],
+ # [1, 2, 0]]` sending `[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]` to
+ # `[[2, 0, 1], [3, 4, 5], [8, 6, 7], [10, 11, 9]]`.
+ def test_convention_random_channel_shuffle_indexes_the_source_channel(self, device, dtype):
+ planes = torch.arange(12, dtype=torch.float32).reshape(4, 3, 1, 1).expand(4, 3, 6, 8)
+ image = planes.contiguous().to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomChannelShuffle(p=1.0)
+ out = aug(image)
+ order = aug._params["channels"]
+ assert order.shape == (4, 3)
+ identity = torch.arange(3, device=order.device)
+ assert not bool((order == identity).all()), "the seeded draw is the identity on every sample"
+ assert not bool((order == order[0]).all()), "the seeded draw is one permutation for every sample"
+ for b in range(4):
+ for c in range(3):
+ self.assert_close(out[b, c], image[b, int(order[b, c])])
+
+ # Row 6c-14, one parameter away: same_on_batch collapses the draw to a single permutation.
+ # Snippet used to generate expected: as above with `same_on_batch=True`; executed 2026-09-15
+ # (torch 2.14.0, cpu) -> `[[2, 0, 1], [2, 0, 1], [2, 0, 1], [2, 0, 1]]`.
+ def test_convention_random_channel_shuffle_same_on_batch(self, device, dtype):
+ planes = torch.arange(12, dtype=torch.float32).reshape(4, 3, 1, 1).expand(4, 3, 6, 8)
+ image = planes.contiguous().to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomChannelShuffle(p=1.0, same_on_batch=True)
+ aug(image)
+ order = aug._params["channels"]
+ assert order.shape == (4, 3)
+ assert bool((order == order[0]).all())
+
+ # Row 6c-15: RandomChannelDropout writes `fill_value` (0 by default) into exactly the channels
+ # named by the drawn `channel_idx`, one independent draw per sample, and leaves the rest alone.
+ # Snippet used to generate expected:
+ # x = torch.ones(2, 3, 6, 8)
+ # torch.manual_seed(0); a = K.RandomChannelDropout(num_drop_channels=n, fill_value=v, p=1.0)
+ # print(a(x).mean((2, 3)).tolist(), a._params["channel_idx"].tolist())
+ # torch.manual_seed(0)
+ # b = K.RandomChannelDropout(num_drop_channels=n, fill_value=v, p=1.0, same_on_batch=True)
+ # b(x); print(b._params["channel_idx"].tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> default: `[[1, 1, 0], [0, 1, 1]]` with idx
+ # `[[2], [0]]`; n=2, v=0.7: `[[0.7, 1, 0.7], [0.7, 0.7, 1]]` with idx `[[2, 0], [0, 1]]`. The
+ # two samples therefore differ; `same_on_batch=True` collapses them to `[[2], [2]]` and
+ # `[[2, 0], [2, 0]]`.
+ @pytest.mark.parametrize(("num_drop_channels", "fill_value"), [(1, 0.0), (2, 0.7)])
+ def test_convention_random_channel_dropout_fills_the_named_channels(
+ self, device, dtype, num_drop_channels, fill_value
+ ):
+ image = torch.ones(2, 3, 6, 8, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomChannelDropout(num_drop_channels=num_drop_channels, fill_value=fill_value, p=1.0)
+ out = aug(image)
+ index = aug._params["channel_idx"]
+ assert index.shape == (2, num_drop_channels)
+ for b in range(2):
+ dropped = {int(c) for c in index[b]}
+ assert len(dropped) == num_drop_channels
+ for c in range(3):
+ expected = fill_value if c in dropped else 1.0
+ self.assert_close(out[b, c], torch.full_like(out[b, c], expected))
+ # The draw is per sample: validating the output against the reported channel_idx alone would
+ # also pass for an implementation that dropped the same channels across the whole batch. Two
+ # samples coincide by chance with probability 1/3 (n=1) or 1/6 (n=2) -- this assertion failed on
+ # 64 of seeds 0..199 at B=2 -- so the distinctness is checked over a wider batch instead.
+ torch.manual_seed(_FORWARD_SEED)
+ wide = K.RandomChannelDropout(num_drop_channels=num_drop_channels, fill_value=fill_value, p=1.0)
+ wide(torch.ones(8, 3, 6, 8, device=device, dtype=dtype))
+ wide_index = wide._params["channel_idx"]
+ assert wide_index.shape == (8, num_drop_channels)
+ assert len({tuple(row) for row in wide_index.tolist()}) > 1, "the seeded per-sample draws coincide"
+ torch.manual_seed(_FORWARD_SEED)
+ batched = K.RandomChannelDropout(
+ num_drop_channels=num_drop_channels, fill_value=fill_value, p=1.0, same_on_batch=True
+ )
+ batched(image)
+ shared = batched._params["channel_idx"]
+ assert shared.shape == (2, num_drop_channels)
+ assert shared[0].tolist() == shared[1].tolist()
+
+ # Row 6c-40: RandomInvert is `max_val - x`, with no clamp, so an input outside [0, 1] comes
+ # back subtracted from `max_val` rather than clipped. That is a reflection about `max_val / 2`,
+ # not about `max_val`: `invert(torch.tensor([2.0]), torch.tensor(1.0))` is `-1.0`, where a
+ # reflection around `max_val` would give `0.0` (executed 2026-09-15, torch 2.14.0, cpu).
+ # Snippet used to generate expected:
+ # g = torch.linspace(0, 2, 48).reshape(1, 1, 6, 8)
+ # torch.manual_seed(0); y = K.RandomInvert(max_val=m, p=1.0)(g); print(y.aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `(-1, 1)` at max_val=1.0 and `(0, 2)` at 2.0.
+ @pytest.mark.parametrize(("max_val", "expected_range"), [(1.0, (-1.0, 1.0)), (2.0, (0.0, 2.0))])
+ def test_convention_random_invert_subtracts_from_max_val(self, device, dtype, max_val, expected_range):
+ ramp = torch.linspace(0, 2, 48).reshape(1, 1, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomInvert(max_val=max_val, p=1.0)(ramp)
+ self.assert_close(out, max_val - ramp)
+ self.assert_close(out.min(), out.new_tensor(expected_range[0]))
+ self.assert_close(out.max(), out.new_tensor(expected_range[1]))
+
+ # Row 6c-39: `additions` is added to the whole image first and the sum is clamped into [0, 1];
+ # only then is everything at or above `thresholds` inverted. The order matters for the pixels
+ # the inversion touches, not for the dark ones: adding after the inversion would give `1 - g + a`
+ # where adding first gives `1 - g - a`, so it is the inverted (bright) pixels that move the other
+ # way, by `2 * addition`. Every pixel more than `addition` below the threshold is identical
+ # under both orders, and only the band `[threshold - addition, threshold)` changes bucket.
+ # Snippet used to generate expected:
+ # g = torch.linspace(0, 1, 48).reshape(1, 1, 6, 8)
+ # torch.manual_seed(0); y = K.RandomSolarize((t, t), (a, a), p=1.0)(g)
+ # z = (g + a).clamp(0, 1); print((y - torch.where(z < t, z, 1.0 - z)).abs().max(), y.aminmax())
+ # w = (torch.where(g < t, g, 1.0 - g) + a).clamp(0, 1); print((y - w).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> formula diff `0` for every pair below, and
+ # threshold=0.5 addition=0.25 sends the input 0.0212766 to 0.271277. Against the other order at
+ # that pair, max|diff| is `0.5` (= 2 * addition), reached on every pixel at or above the
+ # threshold; the two agree exactly below `t - a = 0.25` and the first differing element is
+ # g=0.255319, which is in the band that changes bucket.
+ @pytest.mark.parametrize(("threshold", "addition"), [(0.5, 0.0), (0.5, 0.25), (0.0, 0.0)])
+ def test_convention_random_solarize_adds_before_inverting(self, device, dtype, threshold, addition):
+ ramp = torch.linspace(0, 1, 48).reshape(1, 1, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomSolarize((threshold, threshold), (addition, addition), p=1.0)(ramp)
+ shifted = (ramp + addition).clamp(0.0, 1.0)
+ self.assert_close(out, torch.where(shifted < threshold, shifted, 1.0 - shifted))
+ if (threshold, addition) == (0.5, 0.25):
+ self.assert_close(out.flatten()[1], out.new_tensor(1.0 / 47.0 + 0.25))
+
+ @pytest.mark.parametrize(("addition", "expected"), [(-0.1, 0.0), (0.1, 0.099)])
+ def test_convention_random_solarize_negative_input_depends_on_addition(self, device, dtype, addition, expected):
+ # The seed-0 audit collapse is conditional: a positive addition can lift a negative pixel above zero.
+ image = torch.full((1, 3, 6, 8), -0.001, device=device, dtype=dtype)
+ out = K.RandomSolarize(thresholds=(0.5, 0.5), additions=(addition, addition), p=1.0)(image)
+ self.assert_close(out, torch.full_like(image, expected))
+
+ @pytest.mark.parametrize(("addition", "expected"), [(-0.4, 0.3), (0.0, 0.0)])
+ def test_convention_random_solarize_above_one_depends_on_addition(self, device, dtype, addition, expected):
+ # Being above 1 is insufficient for unconditional collapse: a negative addition can bring
+ # the value below 1 before inversion. At 1.1 - 0.4, the result is 1 - 0.7 = 0.3.
+ image = torch.full((1, 3, 6, 8), 1.1, device=device, dtype=dtype)
+ out = K.RandomSolarize(thresholds=(0.5, 0.5), additions=(addition, addition), p=1.0)(image)
+ self.assert_close(out, torch.full_like(image, expected))
+
+ # The #4430 collapse has an upper-end twin that the audit fixtures cannot see: `[0, 2]` is not
+ # entirely above 1, so `RandomSolarize(p=1.0)` on it returns 151 distinct values. An input drawn
+ # from `[1.5, 3.0]` is all-zero on EVERY draw, because `clamp(x + a, 0, 1)` sends every `x >= 1.5`
+ # to exactly `1.0` for any admissible `a in [-0.5, 0.5]` and `1 - 1.0 == 0`. Swept over the 35
+ # audited factories, `RandomSolarize` is the only one that does this.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.empty(2, 3, 6, 8).uniform_(1.5, 3.0)
+ # for seed in range(5): torch.manual_seed(seed); print((K.RandomSolarize(p=1.0)(x) == 0).all())
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> `True` on all five seeds for
+ # RandomSolarize and on none of the other 34 factories.
+ @pytest.mark.parametrize("seed", [0, 1, 2, 3, 4])
+ def test_wart_random_solarize_at_least_one_point_five_collapses_on_every_draw_4430(self, device, dtype, seed):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.empty(2, 3, 6, 8).uniform_(1.5, 3.0).to(device=device, dtype=dtype)
+ torch.manual_seed(seed)
+ assert bool((K.RandomSolarize(p=1.0)(image) == 0).all())
+ # The audited `[0, 2]` fixture straddles the bound, so it does NOT collapse -- which is why
+ # nothing in the row-6c-01 table sees this.
+ torch.manual_seed(_FIXTURE_SEED)
+ straddling = (torch.rand(2, 3, 6, 8) * 2.0).to(device=device, dtype=dtype)
+ torch.manual_seed(seed)
+ assert K.RandomSolarize(p=1.0)(straddling).unique().numel() > 1
+
+ def test_convention_random_solarize_threshold_zero_inverts_the_clamped_zeros(self, device, dtype):
+ # The other way the #4430 collapse fails: the clamped zeros are "at or above" a drawn threshold of 0,
+ # so they are inverted and the all-negative image comes back as ones.
+ image = torch.full((1, 3, 6, 8), -0.001, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomSolarize(thresholds=(0.0, 0.0), additions=(0.0, 0.0), p=1.0)(image)
+ self.assert_close(out, torch.ones_like(image))
+
+ # Row 6c-50: a scalar `thresholds` is a half-width around the function default 0.5, while a
+ # scalar `additions` is a symmetric range about zero -- the class default centres on
+ # kornia.enhance.solarize's default rather than equalling it.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); p = K.RandomSolarize(0.1, 0.1, p=1.0).forward_parameters((256, 1, 6, 8))
+ # print(p["thresholds"].aminmax(), p["additions"].aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> thresholds in `[0.400247, 0.599413]` and
+ # additions in `[-0.0991148, 0.0999676]`.
+ @pytest.mark.device_agnostic
+ def test_convention_random_solarize_scalar_is_a_centred_range(self):
+ torch.manual_seed(_FORWARD_SEED)
+ params = K.RandomSolarize(0.1, 0.1, p=1.0).forward_parameters((256, 1, 6, 8))
+ assert params["thresholds"].shape == (256,)
+ assert params["additions"].shape == (256,)
+ assert float(params["thresholds"].min()) >= 0.4
+ assert float(params["thresholds"].max()) <= 0.6
+ assert float(params["thresholds"].max()) > 0.5 > float(params["thresholds"].min())
+ assert float(params["additions"].min()) >= -0.1
+ assert float(params["additions"].max()) <= 0.1
+ assert float(params["additions"].max()) > 0.0 > float(params["additions"].min())
+ # A half-width of 0.05 instead of 0.1 satisfies every bound above, so also require the draw to
+ # reach the documented half-width. Over 256 draws each of these fails with probability
+ # 0.9 ** 256 ~ 2e-12 when the half-width is right.
+ assert float(params["thresholds"].max()) > 0.58
+ assert float(params["thresholds"].min()) < 0.42
+ assert float(params["additions"].max()) > 0.09
+ assert float(params["additions"].min()) < -0.09
+
+ # Row 6c-37: `bits=(k, k)` leaves exactly 2**k distinct levels on a 256-level ramp, so k=0 is a
+ # constant image and k=8 is the identity.
+ # Snippet used to generate expected:
+ # g = (torch.arange(256, dtype=torch.float32) / 255.0).reshape(1, 1, 8, 32)
+ # torch.manual_seed(0); print(len(K.RandomPosterize(bits=(k, k), p=1.0)(g).unique()))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> 1, 2, 4, 8, 16, 32, 64, 128, 256 for k = 0..8.
+ @pytest.mark.parametrize("bits", [0, 1, 2, 3, 4, 5, 6, 7, 8])
+ def test_convention_random_posterize_bits_are_levels(self, device, dtype, bits):
+ ramp = (torch.arange(256, dtype=torch.float32) / 255.0).reshape(1, 1, 8, 32)
+ image = ramp.to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomPosterize(bits=(float(bits), float(bits)), p=1.0)(image)
+ assert len(out.unique()) == 2**bits
+
+ # Row 6c-37: an `int` argument is the LOWER bound of [x, 8] and the draw is an int32 -- the
+ # mirror image of RandomSharpness, where a scalar is the upper bound (row 6c-36).
+ # Snippet used to generate expected:
+ # torch.manual_seed(0)
+ # p = K.RandomPosterize(bits=k, p=1.0).forward_parameters((256, 1, 4, 4))["bits_factor"]
+ # print(p.dtype, p.min().item(), p.max().item())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `torch.int32 3 8` and `torch.int32 6 8`.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("bits", [3, 6])
+ def test_convention_random_posterize_int_argument_is_a_lower_bound(self, bits):
+ torch.manual_seed(_FORWARD_SEED)
+ drawn = K.RandomPosterize(bits=bits, p=1.0).forward_parameters((256, 1, 4, 4))["bits_factor"]
+ assert drawn.dtype == torch.int32
+ assert int(drawn.min()) == bits
+ assert int(drawn.max()) == 8
+
+ # Row 6c-36: the sharpness factor blends between the fully blurred image (0.0) and the input
+ # (1.0), so 0.5 moves exactly half as far as 0.0 and values above 1 sharpen. The scale is
+ # linear in the factor, which is what makes "0 = blurred, 1 = identity" checkable.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, 3, 6, 8)
+ # for f in (0.0, 0.5, 1.0, 2.0):
+ # torch.manual_seed(0); print(f, (K.RandomSharpness((f, f), p=1.0)(x) - x).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0.3818`, `0.1909`, `0`, `0.257182`, and the
+ # factor-2.0 output stays inside [0, 1] (`min/max 0 / 1`).
+ def test_convention_random_sharpness_factor_is_identity_at_one(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 6, 8).to(device=device, dtype=dtype)
+ out = {}
+ for factor in (0.0, 0.5, 1.0, 2.0):
+ torch.manual_seed(_FORWARD_SEED)
+ out[factor] = K.RandomSharpness((factor, factor), p=1.0)(image)
+ assert float((out[0.0] - image).abs().max()) > 0.1
+ self.assert_close(out[0.5] - image, 0.5 * (out[0.0] - image))
+ self.assert_close(out[1.0], image)
+ assert float((out[2.0] - image).abs().max()) > 0.1
+ assert float(out[2.0].min()) >= 0.0
+ assert float(out[2.0].max()) <= 1.0
+ # The one-pixel border is copied from the input at every factor: neither blurred nor sharpened.
+ border = torch.ones(image.shape, dtype=torch.bool, device=image.device)
+ border[..., 1:-1, 1:-1] = False
+ for factor in (0.0, 2.0):
+ assert torch.equal(out[factor][border], image[border])
+ # ... but the final clamp into [0, 1] reaches the copied border too.
+ outside = torch.full((2, 1, 4, 4), 0.5, device=device, dtype=dtype)
+ outside[:, :, 0, 0] = 1.5
+ outside[:, :, 0, 1] = -0.25
+ torch.manual_seed(_FORWARD_SEED)
+ corner = K.RandomSharpness((1.0, 1.0), p=1.0)(outside)[:, 0, 0, :2]
+ self.assert_close(corner, outside.new_tensor([[1.0, 0.0], [1.0, 0.0]]))
+
+ # Row 6c-36: a scalar `sharpness` is the UPPER bound of [0, x], so the class default of 0.5
+ # never reaches the identity at 1.0 and therefore never sharpens.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0)
+ # p = K.RandomSharpness(0.5, p=1.0).forward_parameters((256, 1, 6, 8))["sharpness"]
+ # print(p.aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `[0.000618011, 0.498533]`.
+ @pytest.mark.device_agnostic
+ def test_convention_random_sharpness_scalar_is_an_upper_bound(self):
+ torch.manual_seed(_FORWARD_SEED)
+ drawn = K.RandomSharpness(0.5, p=1.0).forward_parameters((256, 1, 6, 8))["sharpness"]
+ assert drawn.shape == (256,)
+ assert float(drawn.min()) >= 0.0
+ assert float(drawn.max()) <= 0.5
+ # Containment alone cannot see a shrunk range: moving the generator's centre from 0.0 to -0.25
+ # makes RandomSharpness(0.5) draw [0, 0.25], which satisfies every bound above. Require the draw
+ # to reach the documented bound. Over 256 draws a true upper bound of 0.5 fails this with
+ # probability 0.9 ** 256 ~ 2e-12.
+ assert float(drawn.max()) > 0.45
+ assert float(drawn.min()) < 0.05
+
+ # Row 6c-34: one additive shift per channel per sample, clamped into [0, 1] by
+ # kornia.enhance.shift_rgb. The shift is replaced by an explicit +1.0 on red so the clamp is
+ # exercised without depending on the draw.
+ # Snippet used to generate expected:
+ # x = torch.full((2, 3, 6, 8), 0.5)
+ # torch.manual_seed(0)
+ # a = K.RandomRGBShift(r_shift_limit=1.0, g_shift_limit=0.0, b_shift_limit=0.0, p=1.0)
+ # p = a.forward_parameters(x.shape)
+ # print(p["r_shift"].tolist(), {k: tuple(v.shape) for k, v in p.items()})
+ # print(a(x, params=p).mean((2, 3)).tolist()) # the natural draw
+ # p["r_shift"] = torch.ones_like(p["r_shift"]) # the injection the pin asserts on
+ # print(a(x, params=p).mean((2, 3)).tolist())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> drawn `r_shift [-0.00748682, 0.536444]` (one per
+ # sample, and `g_shift`/`b_shift` both `[0, 0]`), all three of shape `(2,)`; the natural draw
+ # gives `[[0.492513, 0.5, 0.5], [1, 0.5, 0.5]]` and the injected `+1.0` gives
+ # `[[1, 0.5, 0.5], [1, 0.5, 0.5]]`.
+ def test_convention_random_rgb_shift_is_per_channel_per_sample(self, device, dtype):
+ image = torch.full((2, 3, 6, 8), 0.5, device=device, dtype=dtype)
+ aug = K.RandomRGBShift(r_shift_limit=1.0, g_shift_limit=0.0, b_shift_limit=0.0, p=1.0)
+ torch.manual_seed(_FORWARD_SEED)
+ params = aug.forward_parameters(image.shape)
+ for key in ("r_shift", "g_shift", "b_shift"):
+ assert params[key].shape == (2,), f"{key} is not one shift per sample"
+ # The two samples draw independently, so the shape above is not the whole claim: the seeded
+ # draw is `[-0.00748682, 0.536444]`, and the zero-limit channels stay at exactly 0.
+ assert float(params["r_shift"][0]) != float(params["r_shift"][1])
+ self.assert_close(params["g_shift"], torch.zeros_like(params["g_shift"]), atol=0, rtol=0)
+ self.assert_close(params["b_shift"], torch.zeros_like(params["b_shift"]), atol=0, rtol=0)
+ params["r_shift"] = torch.ones_like(params["r_shift"])
+ out = aug(image, params=params)
+ self.assert_close(out[:, 0], torch.ones_like(out[:, 0]))
+ self.assert_close(out[:, 1:], image[:, 1:])
+
+ # Row 6c-34, the limit itself: a limit is the half-width of a symmetric range, so the draw takes both
+ # signs, and a limit of 0 adds nothing but still leaves the channel to shift_rgb's clamp.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0)
+ # aug = K.RandomRGBShift(r_shift_limit=0.5, g_shift_limit=0.0, b_shift_limit=0.0, p=1.0)
+ # print(aug.forward_parameters((512, 3, 2, 2))["r_shift"].aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `min=-0.4988 max=0.4998`.
+ def test_convention_random_rgb_shift_limit_is_a_half_width(self, device, dtype):
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomRGBShift(r_shift_limit=0.5, g_shift_limit=0.0, b_shift_limit=0.0, p=1.0)
+ shifts = aug.forward_parameters((512, 3, 2, 2))["r_shift"]
+ assert float(shifts.min()) < -0.4 and float(shifts.max()) > 0.4
+ assert float(shifts.abs().max()) <= 0.5
+ image = torch.tensor([1.5, -0.25], device=device, dtype=dtype).reshape(1, 1, 1, 2).expand(1, 3, 1, 2)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomRGBShift(r_shift_limit=0.0, g_shift_limit=0.0, b_shift_limit=0.0, p=1.0)(image.contiguous())
+ self.assert_close(out, image.clamp(0.0, 1.0))
+
+ # Issue #4430, the RandomRGBShift half: the clamp on the sum makes a constant image at or below
+ # `-limit` all-zero on every draw, and one between `-limit` and 0 on the draws whose shift does not
+ # lift it. Literal seeds, as for the census above.
+ # Snippet used to generate expected:
+ # for v in (-0.5, -0.3):
+ # n = 0
+ # for s in range(100):
+ # torch.manual_seed(s)
+ # n += float(K.RandomRGBShift(p=1.0)(torch.full((2, 3, 6, 8), v)).abs().max()) == 0.0
+ # print(v, n)
+ # executed 2026-09-16 (torch 2.14.0, cpu, float32) -> `-0.5 100`, `-0.3 24`.
+ def test_wart_random_rgb_shift_at_or_below_minus_limit_collapses_on_every_draw_4430(self, device, dtype):
+ zeros = {}
+ for value in (-0.5, -0.3):
+ image = torch.full((2, 3, 6, 8), value, device=device, dtype=dtype)
+ zeros[value] = 0
+ for seed in range(100):
+ torch.manual_seed(seed)
+ zeros[value] += float(K.RandomRGBShift(p=1.0)(image).abs().max()) == 0.0
+ assert zeros[-0.5] == 100
+ assert 5 <= zeros[-0.3] <= 50
+
+ # Row 6c-33: `pl` is a persistent buffer holding the illuminant table the mode selects -- 25
+ # rows for blackbody, 23 for CIED -- and `select_from` narrows the table itself.
+ # Snippet used to generate expected:
+ # print(K.RandomPlanckianJitter(mode=m, p=1.0).pl.shape)
+ # print(K.RandomPlanckianJitter(select_from=[0, 1], p=1.0).pl.shape)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `(25, 2)`, `(23, 2)`, `(2, 2)`.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ ("kwargs", "rows"), [({"mode": "blackbody"}, 25), ({"mode": "CIED"}, 23), ({"select_from": [0, 1]}, 2)]
+ )
+ def test_convention_random_planckian_jitter_table_follows_mode(self, kwargs, rows):
+ aug = K.RandomPlanckianJitter(p=1.0, **kwargs)
+ assert tuple(aug.pl.shape) == (rows, 2)
+ assert [name for name, _ in aug.named_buffers()] == ["pl"]
+
+ # Row 6c-04 and 6c-33, per channel: the selected row scales red and blue only, and the clamp that
+ # follows is `clamp(max=1.0)` on all three channels -- green above 1 is cut back although it is not
+ # scaled, a scaled value is cut only if it is still above 1, and negatives stay negative.
+ # Snippet used to generate expected:
+ # x = torch.tensor([[1.5, -0.5], [1.7, -0.5], [1.5, -0.5]]).reshape(1, 3, 1, 2)
+ # aug = K.RandomPlanckianJitter(mode="blackbody", select_from=[0], p=1.0); print(aug.pl[0], aug(x))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> row `(1.6736, 0.0032)`; red `[1.0, -0.8368]`, green
+ # `[1.0, -0.5]`, blue `[0.0048, -0.0016]`.
+ def test_convention_random_planckian_jitter_scales_red_and_blue_then_clamps_above(self, device, dtype):
+ image = torch.tensor([[1.5, -0.5], [1.7, -0.5], [1.5, -0.5]], device=device, dtype=dtype).reshape(1, 3, 1, 2)
+ aug = K.RandomPlanckianJitter(mode="blackbody", select_from=[0], p=1.0)
+ torch.manual_seed(_FORWARD_SEED)
+ out = aug(image)
+ red_gain, blue_gain = (float(value) for value in aug.pl[0])
+ scaled = torch.stack([image[:, 0] * red_gain, image[:, 1], image[:, 2] * blue_gain], dim=1)
+ # Compared in the input's dtype: the output is float32 for a half input (#4574, pinned below).
+ self.assert_close(out.to(dtype), scaled.clamp(max=1.0))
+ assert float(out[0, 1, 0, 0]) == 1.0 and float(out[0, 2, 0, 0]) < 0.01
+ assert bool((out[..., 1] < 0).all())
+
+ # Issue #4574: the `pl` table is float32 unless the module is cast, and apply_transform multiplies the
+ # red and blue channels by it without casting, so a half-precision input comes back float32; a float64
+ # input keeps its dtype, and so does a half input once the module is cast with `.half()`.
+ # Snippet used to generate expected:
+ # for dt in (torch.float16, torch.bfloat16, torch.float64):
+ # torch.manual_seed(0); print(dt, K.RandomPlanckianJitter(p=1.0)(torch.rand(2, 3, 4, 4).to(dt)).dtype)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `float32`, `float32`, `float64`.
+ def test_wart_random_planckian_jitter_half_input_comes_back_float32_4574(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 4, 4).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomPlanckianJitter(p=1.0)(image)
+ assert out.dtype == (torch.float32 if dtype in _HALF else dtype)
+ # The output is the promoted dtype of input and table, so casting the module to the input's own
+ # dtype restores it, and a wider cast widens the output.
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.RandomPlanckianJitter(p=1.0).to(device=device, dtype=dtype)(image).dtype == dtype
+ if dtype in _HALF:
+ other = torch.bfloat16 if dtype == torch.float16 else torch.float16
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.RandomPlanckianJitter(p=1.0).to(device=device, dtype=other)(image).dtype == torch.float32
+
+ # Row 6c-32/6c-33: the illuminant table is an RGB ratio, so a non-RGB input is rejected rather
+ # than broadcast. Snippet used to generate expected:
+ # torch.manual_seed(0); K.RandomPlanckianJitter(p=1.0)(torch.rand(1, 1, 6, 8))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `ShapeError: Shape mismatch at dimension 0:
+ # expected 3, got 1.`
+ def test_convention_random_planckian_jitter_requires_three_channels(self, device, dtype):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(1, 1, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ # `match` is part of the pin: requiring any other channel count raises the same ShapeError, so
+ # without it `KORNIA_CHECK_SHAPE(input, ["*", "4", "H", "W"])` leaves this node green.
+ with pytest.raises(ShapeError, match=r"expected 3, got 1"):
+ # The sync is what surfaces an MPS kernel error inside this block rather than later.
+ _sync(K.RandomPlanckianJitter(p=1.0)(image).device)
+
+ # Row 6c-48 (issue #4428): because `pl` is a persistent buffer whose shape depends on `mode`, a
+ # state_dict is mode-specific -- a blackbody checkpoint cannot be loaded into a CIED instance.
+ # The other eleven 6c range buffers at least load; they are simply inert (6a pins that half of
+ # #4428 on RandomBrightness).
+ # Snippet used to generate expected:
+ # K.RandomPlanckianJitter(mode="CIED").load_state_dict(
+ # K.RandomPlanckianJitter(mode="blackbody").state_dict())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `RuntimeError: Error(s) in loading state_dict for
+ # RandomPlanckianJitter: size mismatch for pl: copying a param with shape torch.Size([25, 2])
+ # from checkpoint, the shape in current model is torch.Size([23, 2]).`
+ @pytest.mark.device_agnostic
+ def test_wart_random_planckian_jitter_state_dict_is_mode_specific_4428(self):
+ blackbody = K.RandomPlanckianJitter(mode="blackbody")
+ cied = K.RandomPlanckianJitter(mode="CIED")
+ assert "pl" in blackbody.state_dict()
+ with pytest.raises(RuntimeError, match="size mismatch for pl"):
+ cied.load_state_dict(blackbody.state_dict())
+ # The same-mode round trip is fine, so the defect is the shape and not the buffer.
+ K.RandomPlanckianJitter(mode="blackbody").load_state_dict(blackbody.state_dict())
+
+ # Row 6c-35: RandomAutoContrast is exactly kornia.enhance.normalize_min_max -- a per-sample,
+ # per-channel rescale onto [0, 1] -- checked on a fixture whose six channels have six distinct
+ # ranges so a per-batch or per-image rescale would not reproduce it.
+ # Snippet used to generate expected:
+ # torch.manual_seed(5)
+ # x = torch.rand(2, 3, 6, 8) * torch.tensor([0.2, 0.5, 1.0]).reshape(1, 3, 1, 1) \
+ # + torch.tensor([0.1, 0.3]).reshape(2, 1, 1, 1)
+ # torch.manual_seed(0)
+ # print((K.RandomAutoContrast(p=1.0)(x) - kornia.enhance.normalize_min_max(x)).abs().max())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `0`, from per-channel input ranges
+ # `[(0.106653, 0.298837), (0.164935, 0.586581), (0.118316, 1.08595)]` on the first sample.
+ def test_convention_random_auto_contrast_is_normalize_min_max(self, device, dtype):
+ torch.manual_seed(5)
+ scale = torch.tensor([0.2, 0.5, 1.0]).reshape(1, 3, 1, 1)
+ offset = torch.tensor([0.1, 0.3]).reshape(2, 1, 1, 1)
+ image = (torch.rand(2, 3, 6, 8) * scale + offset).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomAutoContrast(p=1.0)(image)
+ self.assert_close(out, normalize_min_max(image))
+ for b in range(2):
+ for c in range(3):
+ self.assert_close(out[b, c].min(), out.new_tensor(0.0))
+ self.assert_close(out[b, c].max(), out.new_tensor(1.0))
+ # The denominator is `max - min + 1e-6`, so a channel whose range is not large next to 1e-6 stops
+ # short of 1: a range of 1e-5 peaks at 1e-5 / 1.1e-5 = 0.90908 (float32/float64 only; the half
+ # dtypes cannot hold 0.2 + 1e-5 apart from 0.2).
+ if dtype in (torch.float32, torch.float64):
+ narrow = torch.full((1, 1, 2, 2), 0.2, device=device, dtype=dtype)
+ narrow[0, 0, 0, 0] += 1e-5
+ torch.manual_seed(_FORWARD_SEED)
+ peak = K.RandomAutoContrast(p=1.0)(narrow).max()
+ assert abs(float(peak) - 1e-5 / 1.1e-5) < 1e-3
+
+ # RandomJPEG, outside `kornia.augmentation.__all__`, carries one range sentence: `ycbcr_to_rgb`
+ # hard-clamps the decoded RGB into [0, 1], and the codec's final soft clip, with bounds [0, 255], leaves
+ # those values alone. So an input far outside [0, 1] comes back inside it, and reaches both ends.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, 3, 32, 32) * 3 - 1
+ # torch.manual_seed(0); y = K.RandomJPEG(p=1.0)(x); print(y.aminmax(), y.isnan().any())
+ # executed 2026-09-15 (torch 2.14.0, cpu float16/bfloat16/float32/float64 and mps float32) ->
+ # `min=0, max=1`, `False`.
+ def test_convention_random_jpeg_output_is_clamped_to_unit_range(self, device, dtype):
+ if not supports_replicate_padding(device, dtype):
+ pytest.skip("replication_pad2d is unavailable for this device/dtype")
+ torch.manual_seed(_FIXTURE_SEED)
+ image = (torch.rand(2, 3, 32, 32) * 3.0 - 1.0).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomJPEG(p=1.0)(image)
+ assert out.dtype == dtype
+ assert not bool(out.isnan().any())
+ assert float(out.min()) == 0.0
+ assert float(out.max()) == 1.0
+
+ @pytest.mark.parametrize("negative", [True, False])
+ def test_convention_random_jpeg_out_of_range_input_need_not_be_solid(self, device, dtype, negative):
+ if not supports_replicate_padding(device, dtype):
+ pytest.skip("replication_pad2d is unavailable for this device/dtype")
+ # A nonconstant grayscale field distinguishes clamping the decoded image from clamping
+ # the input. Keep its values away from the endpoints even after conversion to bfloat16.
+ torch.manual_seed(_FIXTURE_SEED)
+ field = (torch.rand(1, 1, 32, 32) * 2.0 + 0.03125).expand(1, 3, -1, -1).contiguous()
+ image = (-field if negative else 1.0 + field).to(device=device, dtype=dtype)
+ assert bool((image < 0.0).all()) if negative else bool((image > 1.0).all())
+ aug = K.RandomJPEG(jpeg_quality=(50.0, 50.0), p=1.0)
+ out = aug(image)
+ assert bool(torch.isfinite(out).all())
+ assert float(out.min()) >= 0.0 and float(out.max()) <= 1.0
+ # CPU/MPS float32 at quality 50: negative input peaks near 0.04625; positive input bottoms
+ # near 0.95154. The half dtypes differ, but each keeps values strictly inside the range.
+ assert bool(((out > 0.0) & (out < 1.0)).any())
+ # Quantization can also give a constant black input small positive values, so the range
+ # assertion alone would not catch a misplaced input clamp.
+ assert not torch.equal(out, aug(image.clamp(0.0, 1.0)))
+
+ # Row 6c-45: the documented parameter bounds are enforced, and where: `stage` records whether the
+ # constructor raises or constructs and the forward pass raises, since the anchor's list of forward-time
+ # checks is part of the contract. Beyond the audit rows, RandomGaussianBlur's even kernel, a
+ # RandomMotionBlur kernel range whose drawn odd size is 1, RandomChannelDropout dropping more channels
+ # than the image has and a RandomPlanckianJitter row past the table are pinned here too.
+ # The exception type is what the audit recorded, so the type is the pin and the message is not.
+ # Snippet used to generate expected:
+ # ctor()(torch.rand(2, 3, 6, 8)) # for each case below
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `ValueError: If sharpness is a single number, it
+ # must be non negative.`, `ValueError: bits[0] should be smaller than bits[1]`, `ValueError:
+ # bits out of bounds. Expected inside (0, 8)`, `RuntimeError: Gamma must be non-negative.`,
+ # `ValueError: brightness out of bounds. Expected inside (0.0, 2.0)`, `ValueError: contrast out
+ # of bounds. Expected inside (0, inf)`, `ValueError: saturation out of bounds. Expected inside
+ # (0, inf)`, `ValueError: hue out of bounds. Expected inside (-0.5, 0.5)`, `RuntimeError: The addition
+ # must be in the open range (-0.5, 0.5).` (for 0.5 and -0.5; #4605), `BaseError: sigma must be positive` and
+ # `BaseError: Height of drop should be greater than zero and less than image height.`; then
+ # `BaseError: Kernel size must be an odd integer bigger than 0` (Gaussian (4, 4)), `... bigger than 2`
+ # (motion (1, 1)), `BaseError: Invalid value in num_drop_channels` and `IndexError: index 25 is out
+ # of bounds for dimension 0 with size 25`; the last one at construction, the three before it on the
+ # forward pass.
+ # `match` is part of the pin, not decoration: without it a case can be satisfied by a different
+ # error of the same class. `bits=9` is the example -- a scalar becomes the range [9, 8], so it trips
+ # the "lo > hi" arm and says nothing about the documented (0, 8] upper bound; widening that bound to
+ # (0, 16) left every pin in this file green until `posterize_bits_range_above_eight` was added.
+ @pytest.mark.parametrize(
+ ("case", "stage", "error", "match"),
+ [
+ (
+ "sharpness_negative",
+ "construction",
+ ValueError,
+ r"If sharpness is a single number, it must be non negative",
+ ),
+ ("posterize_bits_above_eight", "construction", ValueError, r"bits\[0\] should be smaller than bits\[1\]"),
+ (
+ "posterize_bits_range_above_eight",
+ "construction",
+ ValueError,
+ r"bits out of bounds\. Expected inside \(0, 8\)",
+ ),
+ ("posterize_bits_negative", "construction", ValueError, r"bits out of bounds\. Expected inside \(0, 8\)"),
+ ("gamma_negative", "forward", RuntimeError, r"Gamma must be non-negative"),
+ ("gain_negative", "forward", RuntimeError, r"Gain must be non-negative"),
+ (
+ "brightness_above_two",
+ "construction",
+ ValueError,
+ r"brightness out of bounds\. Expected inside \(0\.0, 2\.0\)",
+ ),
+ ("contrast_negative", "construction", ValueError, r"contrast out of bounds\. Expected inside \(0, inf\)"),
+ (
+ "saturation_negative",
+ "construction",
+ ValueError,
+ r"saturation out of bounds\. Expected inside \(0, inf\)",
+ ),
+ ("hue_above_half", "construction", ValueError, r"hue out of bounds\. Expected inside \(-0\.5, 0\.5\)"),
+ (
+ "solarize_additions_at_half",
+ "forward",
+ RuntimeError,
+ r"The addition must be in the open range \(-0\.5, 0\.5\)",
+ ),
+ (
+ "solarize_additions_at_minus_half",
+ "forward",
+ RuntimeError,
+ r"The addition must be in the open range \(-0\.5, 0\.5\)",
+ ),
+ ("gaussian_blur_sigma_zero", "forward", BaseError, r"sigma must be positive"),
+ ("gaussian_blur_even_kernel", "forward", BaseError, r"Kernel size must be an odd integer bigger than 0"),
+ ("median_blur_even_kernel", "forward", RuntimeError, r"is invalid for input of size"),
+ ("rain_drop_height_zero", "forward", BaseError, r"Height of drop should be greater than zero"),
+ (
+ "motion_blur_kernel_range_draws_one",
+ "forward",
+ BaseError,
+ r"Kernel size must be an odd integer bigger than 2",
+ ),
+ (
+ "motion_blur_even_bound_rounds_up",
+ "forward",
+ BaseError,
+ r"Kernel size must be an odd integer bigger than 2",
+ ),
+ ("channel_dropout_more_than_the_channels", "forward", BaseError, r"Invalid value in .num_drop_channels."),
+ (
+ "channel_dropout_fill_value_above_one",
+ "construction",
+ BaseError,
+ r"Invalid value in .fill_value.\. Must be a float between 0 and 1",
+ ),
+ (
+ "color_jiggle_brightness_range_above_two",
+ "construction",
+ ValueError,
+ r"brightness out of bounds\. Expected inside \(0, 2\)",
+ ),
+ ("rgb_shift_tuple_limit", "construction", TypeError, r"bad operand type for unary -: 'tuple'"),
+ (
+ "planckian_select_past_the_table",
+ "construction",
+ IndexError,
+ r"index 25 is out of bounds for dimension 0 with size 25",
+ ),
+ ],
+ )
+ def test_convention_intensity_constructors_reject_out_of_bounds(self, device, dtype, case, stage, error, match):
+ if case in ("gamma_negative", "gain_negative") and device.type != "cpu":
+ pytest.skip("CPU only: on CUDA the value assert is a device-side assert; MPS skips the check")
+ # The solarize check runs on the CPU-drawn additions, so unlike the gamma check it raises for an
+ # MPS image as well; CUDA stays out, like every value assert here.
+ if case.startswith("solarize_additions") and device.type == "cuda":
+ pytest.skip("not on CUDA: value asserts are kept out of the shared CUDA process")
+ factories = {
+ "sharpness_negative": lambda: K.RandomSharpness(-1.0, p=1.0),
+ "posterize_bits_above_eight": lambda: K.RandomPosterize(bits=9, p=1.0),
+ "posterize_bits_negative": lambda: K.RandomPosterize(bits=-1, p=1.0),
+ "gamma_negative": lambda: K.RandomGamma((-1.0, -1.0), (1.0, 1.0), p=1.0),
+ # `gain` has the identical forward-time check and no construction bound of its own.
+ "gain_negative": lambda: K.RandomGamma((1.0, 1.0), (-1.0, -1.0), p=1.0),
+ "brightness_above_two": lambda: K.RandomBrightness((3.0, 3.0), p=1.0),
+ "contrast_negative": lambda: K.RandomContrast((-1.0, -1.0), p=1.0),
+ "saturation_negative": lambda: K.RandomSaturation((-1.0, -1.0), p=1.0),
+ # A scalar `hue` is silently clamped into the bound instead of rejected, so the pin uses
+ # the explicit range the audit executed.
+ "hue_above_half": lambda: K.RandomHue((0.6, 0.6), p=1.0),
+ # The construction check is the closed [-0.5, 0.5]; kornia.enhance.solarize rejects the
+ # ends on the forward pass, so this one constructs and raises like the gamma case.
+ "solarize_additions_at_half": lambda: K.RandomSolarize((0.5, 0.5), (0.5, 0.5), p=1.0),
+ "solarize_additions_at_minus_half": lambda: K.RandomSolarize((0.5, 0.5), (-0.5, -0.5), p=1.0),
+ # The constructor admits sigma 0; gaussian_blur2d rejects it on the forward pass.
+ "gaussian_blur_sigma_zero": lambda: K.RandomGaussianBlur((3, 3), (0.0, 0.0), p=1.0),
+ # The documented "greater than zero" is checked against the image on the forward pass.
+ "rain_drop_height_zero": lambda: K.RandomRain(
+ number_of_drops=(1, 1), drop_height=(0, 0), drop_width=(1, 1), p=1.0
+ ),
+ # The constructor admits an even entry; gaussian_blur2d rejects it on the forward pass.
+ "gaussian_blur_even_kernel": lambda: K.RandomGaussianBlur((4, 4), (1.0, 1.0), p=1.0),
+ # Only odd sizes are drawn, so (1, 1) draws 1, which the motion kernel rejects.
+ "motion_blur_kernel_range_draws_one": lambda: K.RandomMotionBlur((1, 1), 35.0, 0.5, p=1.0),
+ # The bound is the input's channel count, which only the forward pass knows.
+ "channel_dropout_more_than_the_channels": lambda: K.RandomChannelDropout(num_drop_channels=4, p=1.0),
+ # `select_from` indexes the 25-row blackbody table at construction.
+ "planckian_select_past_the_table": lambda: K.RandomPlanckianJitter(select_from=[25], p=1.0),
+ # A scalar `bits=9` becomes the range [9, 8] and trips the "lo > hi" arm, so the documented
+ # (0, 8] upper bound needs an explicit range to be pinned at all.
+ "posterize_bits_range_above_eight": lambda: K.RandomPosterize(bits=(3.0, 9.0), p=1.0),
+ # An even entry raises a raw reshape error from median_blur's view, not a kornia check.
+ "median_blur_even_kernel": lambda: K.RandomMedianBlur((4, 4), p=1.0),
+ # An even bound is rounded up to the next odd size, so (0, 2) draws 1 and the kernel rejects it.
+ "motion_blur_even_bound_rounds_up": lambda: K.RandomMotionBlur((0, 2), 35.0, 0.5, p=1.0),
+ # `fill_value` is bounded to [0, 1] at construction, unlike RandomErasing's `value` type check.
+ "channel_dropout_fill_value_above_one": lambda: K.RandomChannelDropout(fill_value=2.0, p=1.0),
+ # ColorJiggle's brightness bound is (0, 2); ColorJitter accepts the same range.
+ "color_jiggle_brightness_range_above_two": lambda: K.ColorJiggle(brightness=(0.0, 3.0), p=1.0),
+ # Each *_shift_limit must be a scalar; a tuple dies on the unary minus that builds the range.
+ "rgb_shift_tuple_limit": lambda: K.RandomRGBShift((0.1, 0.5), p=1.0),
+ }
+ if stage == "construction":
+ with pytest.raises(error, match=match):
+ factories[case]()
+ return
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, 3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = factories[case]()
+ with pytest.raises(error, match=match):
+ # The sync is what surfaces an MPS kernel error inside this block rather than later.
+ _sync(aug(image).device)
+
+ # Row 6c-45, the bound that never raises: RandomPlanckianJitter's `select_from` is used as a Python
+ # index into its table, so a negative entry down to -25 selects a row from the end instead of being
+ # rejected against the documented `[0-24]`.
+ # Snippet used to generate expected:
+ # print(torch.equal(K.RandomPlanckianJitter(select_from=[-1]).pl, K.RandomPlanckianJitter(select_from=[24]).pl))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `True`.
+ @pytest.mark.device_agnostic
+ def test_convention_random_planckian_jitter_select_from_is_a_python_index(self):
+ assert torch.equal(
+ K.RandomPlanckianJitter(select_from=[-1], p=1.0).pl, K.RandomPlanckianJitter(select_from=[24], p=1.0).pl
+ )
+
+ # Issue #4563: a scalar magnitude whose implied range leaves the documented bounds is fitted to
+ # them instead of rejected, where the same range written out raises (pinned one test above).
+ # RandomSharpness is the class that depends on the fit: its scalar form is the centred `[-x, x]`
+ # clamped to `(0, inf)`, which is what makes `sharpness=0.5` mean `[0, 0.5]`.
+ # Snippet used to generate expected:
+ # print(K.RandomHue(0.7).hue, K.RandomBrightness(3.0).brightness)
+ # print(K.ColorJiggle(brightness=3.0).forward_parameters((256, 3, 2, 2))["brightness_factor"].aminmax())
+ # print(K.RandomSharpness(0.5).forward_parameters((2000, 1, 4, 4))["sharpness"].aminmax())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `[-0.5, 0.5]`, `[0, 2]`, brightness in
+ # `[0.0072, 1.9945]`, sharpness in `[3.87e-05, 0.5]`.
+ @pytest.mark.device_agnostic
+ def test_wart_scalar_magnitude_is_fitted_to_the_bound_4563(self):
+ assert K.RandomHue(0.7, p=1.0).hue.tolist() == [-0.5, 0.5]
+ assert K.RandomBrightness(3.0, p=1.0).brightness.tolist() == [0.0, 2.0]
+ torch.manual_seed(_FORWARD_SEED)
+ brightness = K.ColorJiggle(brightness=3.0, p=1.0).forward_parameters((256, 3, 2, 2))["brightness_factor"]
+ assert float(brightness.min()) >= 0.0 and float(brightness.max()) <= 2.0
+ assert float(brightness.max()) > 1.5 # the fit is to [0, 2], not to [0, 1 + 3] or to [0, 1]
+ torch.manual_seed(_FORWARD_SEED)
+ sharpness = K.RandomSharpness(0.5, p=1.0).forward_parameters((2000, 1, 4, 4))["sharpness"]
+ assert float(sharpness.min()) >= 0.0 and float(sharpness.max()) <= 0.5
+ assert float(sharpness.min()) < 0.1 # the lower end is the clamped -x, not a centred x / 2
+
+ # Issue #4564: RandomClahe rejects an out-of-[0, 1] input with the raw indexing error of the
+ # histogram gather, naming neither the class nor the range RandomEqualize names (#4489). Not on CUDA,
+ # where the out-of-range index is a device-side assert that poisons the context; on MPS the error is
+ # an AcceleratorError, a RuntimeError subclass, reading `gather: index ... is out of bounds`.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(1, 3, 16, 16) * 2
+ # torch.manual_seed(0); K.RandomClahe(p=1.0)(x)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `RuntimeError: index 430 is out of bounds for
+ # dimension 5 with size 256`.
+ def test_wart_random_clahe_out_of_range_error_is_raw_4564(self, device, dtype):
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the index error is a device-side assert that poisons the context")
+ torch.manual_seed(_FIXTURE_SEED)
+ image = (torch.rand(1, 3, 16, 16) * 2).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ if device.type == "mps" and not torch_version_ge(2, 14):
+ # 2.5.1 leaves the MPS gather unchecked: the call returns an in-range image as if valid.
+ out = K.RandomClahe(p=1.0)(image)
+ assert float(out.min()) >= 0.0 and float(out.max()) <= 1.0
+ return
+ with pytest.raises(RuntimeError, match="out of bounds") as info:
+ _sync(K.RandomClahe(p=1.0)(image).device)
+ assert "RandomClahe" not in str(info.value) and "[0, 1]" not in str(info.value)
+
+ # Divisibility is not the axis that decides whether `grid_size` works: a SQUARE grid is padded up to
+ # a whole number of tiles, so it works whether or not it divides the image. `_compute_tiles` is
+ # called with `even_tile_size=True`, so an exactly dividing grid can still pad -- `(4, 5)` on
+ # `20 x 20` pads 4 rows -- which is why the rectangular leg below carries the padding guard too.
+ # Snippet used to generate expected:
+ # for gs, n in (((3, 3), 10), ((4, 4), 20), ((5, 5), 20), ((8, 8), 9)):
+ # torch.manual_seed(0); K.RandomClahe(grid_size=gs, p=1.0)(torch.rand(1, 1, n, n))
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> no raise for any of them.
+ @pytest.mark.parametrize(("grid_size", "size", "pad"), [((3, 3), 10, 2), ((4, 4), 20, 4), ((5, 5), 20, 0)])
+ def test_convention_random_clahe_square_grid_works_whether_or_not_it_tiles(
+ self, device, dtype, grid_size, size, pad
+ ):
+ if pad and not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ image = torch.linspace(0, 1, size * size, device=device, dtype=dtype).reshape(1, 1, size, size)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomClahe(grid_size=grid_size, p=1.0)(image)
+ assert out.shape == image.shape
+ assert bool(out.isfinite().all())
+ # A pass-through would satisfy the two assertions above, so the transform has to have moved it.
+ assert not torch.equal(out, image)
+ if pad:
+ # Shape, finiteness and "not the input" say nothing about HOW the image is padded, and the
+ # inequality is satisfied by CLAHE itself: switching `_compute_tiles`' pad from "reflect" to
+ # "constant" leaves all three green. The padding is reflect and sits at the END of each axis,
+ # so running the pre-padded image through the same call and cropping back reproduces this
+ # output bitwise.
+ padded = torch.nn.functional.pad(image, [0, pad, 0, pad], mode="reflect")
+ torch.manual_seed(_FORWARD_SEED)
+ reference = K.RandomClahe(grid_size=grid_size, p=1.0)(padded)[..., :size, :size]
+ assert torch.equal(out, reference)
+
+ # The other documented `grid_size` boundary, which nothing exercised: at the default `(8, 8)` the
+ # smallest admissible square image is `9 x 9`. `8 x 8` needs 8 rows of reflect padding on an
+ # 8-row image, which torch refuses, and anything smaller than the grid gets the named ValueError.
+ # Snippet used to generate expected:
+ # for n in (7, 8, 9): torch.manual_seed(0); K.RandomClahe(p=1.0)(torch.rand(1, 1, n, n))
+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> ValueError("Cannot compute tiles on
+ # the image according to the given grid size"), RuntimeError("Padding size should be less than the
+ # corresponding input dimension"), and a `(1, 1, 9, 9)` output.
+ @pytest.mark.parametrize(
+ ("size", "error", "match"),
+ [
+ (7, ValueError, r"Cannot compute tiles on the image according to the given grid size"),
+ (8, RuntimeError, r"Padding size should be less than the corresponding input dimension"),
+ ],
+ )
+ def test_convention_random_clahe_default_grid_needs_nine_pixels(self, device, dtype, size, error, match):
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ torch.manual_seed(_FIXTURE_SEED)
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(error, match=match):
+ K.RandomClahe(p=1.0)(torch.rand(1, 1, size, size, device=device, dtype=dtype))
+ # One pixel more on each axis is admitted, so the boundary is exactly where the block says.
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.RandomClahe(p=1.0)(torch.rand(1, 1, 9, 9, device=device, dtype=dtype)).shape == (1, 1, 9, 9)
+
+ # Issue #2531: every NON-square `grid_size` raises, on every image, whether or not it tiles. The
+ # `(4, 5)` / `20 x 20` row is the exactly dividing case, `(1, 2)` / `10 x 10` the one that pads, and
+ # `(3, 5)` / `30 x 30` rules out a mismatch between odd and even grid entries as the cause.
+ # Snippet used to generate expected:
+ # import itertools
+ # for gh, gw in itertools.product(range(1, 7), repeat=2):
+ # for h, w in ((24, 24), (30, 30), (24, 30), (35, 42), (60, 60)):
+ # torch.manual_seed(0); K.RandomClahe(grid_size=(gh, gw), p=1.0)(torch.rand(1, 1, h, w))
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> all 150 rows follow `raises == (gh != gw)`; a further
+ # 40 random non-square grids from {1,2,3,4,5,7,8,9,12,16}^2 over three image shapes raised in
+ # 120/120 cases and the 30 square controls all passed.
+ @pytest.mark.parametrize(
+ ("grid_size", "size", "pads"), [((4, 5), 20, True), ((3, 5), 30, False), ((1, 2), 10, True)]
+ )
+ def test_wart_random_clahe_non_square_grid_always_raises_2531(self, device, dtype, grid_size, size, pads):
+ if pads and not supports_reflect_padding(device, dtype):
+ # A padding row would die of "reflection_pad2d not implemented for 'Half'" on the torch 2.5.1
+ # floor before reaching the lookup; the `(3, 5)` row pads nothing, so it keeps the pin alive
+ # on every dtype.
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ if device.type == "cuda":
+ # The broadcast of the lookup indices is computed on the host, so this should raise before
+ # any kernel launches -- but that is untested on CUDA, and being wrong here poisons the
+ # context for every later test, exactly as the #4564 pin above guards against.
+ pytest.skip("not on CUDA: the raise site ahead of the device-side lookup is unverified there")
+ image = torch.linspace(0, 1, size * size, device=device, dtype=dtype).reshape(1, 1, size, size)
+ torch.manual_seed(_FORWARD_SEED)
+ with pytest.raises(IndexError, match="shape mismatch: indexing tensors could not be broadcast together"):
+ K.RandomClahe(grid_size=grid_size, p=1.0)(image)
+
+ # Issue #4572: RandomClahe draws `clip_limit_factor` per sample but equalizes the whole batch with
+ # the first sample's value (`float(params["clip_limit_factor"][0])`).
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, 1, 32, 32) ** 3
+ # torch.manual_seed(0); aug = K.RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), p=1.0); y = aug(x)
+ # c = aug._params["clip_limit_factor"]; print(c)
+ # for i in (1, 0):
+ # print(torch.equal(y[1:], equalize_clahe(x[1:], float(c[i]), (2, 2))))
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `[20.1021, 30.8448]`, `False True`.
+ @pytest.mark.device_agnostic
+ def test_wart_random_clahe_applies_the_first_clip_limit_to_the_batch_4572(self):
+ # B is 8, not 2: two draws from (0.5, 40.0) land within 1.0 of each other about 5% of the time,
+ # and at B=2 this node failed on 12 of seeds 0..199. Over 8 draws the spread was at least 9.4 on
+ # every one of those seeds, and the sample farthest from the first is the one that shows the wart.
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(8, 1, 32, 32) ** 3
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), p=1.0)
+ out = aug(image)
+ clip = aug._params["clip_limit_factor"]
+ far = int((clip - clip[0]).abs().argmax())
+ assert abs(float(clip[far]) - float(clip[0])) > 1.0
+ # The whole batch is equalized with the first sample's clip limit, not with its own.
+ assert torch.equal(out[far : far + 1], equalize_clahe(image[far : far + 1], float(clip[0]), (2, 2)))
+ assert not torch.equal(out[far : far + 1], equalize_clahe(image[far : far + 1], float(clip[far]), (2, 2)))
+
+ # Issue #4560: every class whose path goes through rgb_to_hsv returns NaN for a black pixel in
+ # float16, because the conversion's `eps=1e-8` underflows to 0 there; bfloat16 keeps the exponent
+ # range of float32 and is finite. Pinned here so the four warnings that cite #4560 have an
+ # executable anchor, and so the skip reasons above stay honest if the NaN ever disappears.
+ # Snippet used to generate expected:
+ # for dt in (torch.float16, torch.float32, torch.bfloat16):
+ # print(dt, K.RandomHue((0.1, 0.1), p=1.0)(torch.zeros(1, 3, 4, 4, dtype=dt)).isnan().any())
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `True`, `False`, `False`; the same for
+ # RandomSaturation((1.5, 1.5)), ColorJiggle(0, 0, 0, (0.1, 0.1)) and ColorJitter(0, 0, 0, (0.1, 0.1)).
+ # The pixel (0, -0.5, -0.5) is NaN in float16 through the three hue-step configurations and finite
+ # through the two saturation-only ones (measured on cpu in all four dtypes and on mps float32).
+ @pytest.mark.parametrize(
+ "name", ["RandomHue", "RandomSaturation", "ColorJiggle", "ColorJiggleSaturation", "ColorJitter"]
+ )
+ def test_wart_hsv_path_black_pixel_is_nan_in_float16_4560(self, device, dtype, name):
+ factories = {
+ "RandomHue": lambda: K.RandomHue((0.1, 0.1), p=1.0),
+ "RandomSaturation": lambda: K.RandomSaturation((1.5, 1.5), p=1.0),
+ "ColorJiggle": lambda: K.ColorJiggle(0.0, 0.0, 0.0, (0.1, 0.1), p=1.0),
+ # ColorJiggle's saturation step is adjust_saturation, an HSV round trip too, so the NaN needs
+ # no hue step (ColorJitter's gray-subtraction saturation does not have it).
+ "ColorJiggleSaturation": lambda: K.ColorJiggle(0.0, 0.0, (1.5, 1.5), 0.0, p=1.0),
+ "ColorJitter": lambda: K.ColorJitter(0.0, 0.0, 0.0, (0.1, 0.1), p=1.0),
+ }
+ # A black pixel, and a pixel whose largest channel is 0 without being black: the hue step divides
+ # by that zero maximum too, while the saturation step's NaN needs `max - min` to be 0 as well.
+ pixels = torch.tensor([[0.0, 0.0, 0.0], [0.0, -0.5, -0.5]], device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = factories[name]()(pixels.T.reshape(1, 3, 1, 2))
+ half = dtype == torch.float16
+ hue_path = name not in ("RandomSaturation", "ColorJiggleSaturation")
+ assert out.isnan().any(1)[0, 0].tolist() == [half, half and hue_path]
+
+ # Row 6c-46: an unbatched (C, H, W) input is promoted to (1, C, H, W), and `keepdim=True`
+ # returns the unbatched shape again. Checked across four classes of the sub-batch so the claim
+ # is the package convention rather than one implementation.
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(3, 6, 8)
+ # torch.manual_seed(0); print(ctor(keepdim=False)(x).shape, ctor(keepdim=True)(x).shape)
+ # executed 2026-09-15 (torch 2.14.0, cpu) -> `(1, 3, 6, 8)` and `(3, 6, 8)` for all four.
+ @pytest.mark.parametrize("name", ["RandomBrightness", "RandomGrayscale", "RandomSolarize", "RandomPlanckianJitter"])
+ def test_convention_intensity_promotes_chw_to_bchw(self, device, dtype, name):
+ factories = {
+ "RandomBrightness": lambda keepdim: K.RandomBrightness((1.5, 1.5), p=1.0, keepdim=keepdim),
+ "RandomGrayscale": lambda keepdim: K.RandomGrayscale(p=1.0, keepdim=keepdim),
+ "RandomSolarize": lambda keepdim: K.RandomSolarize(0.1, 0.1, p=1.0, keepdim=keepdim),
+ "RandomPlanckianJitter": lambda keepdim: K.RandomPlanckianJitter(p=1.0, keepdim=keepdim),
+ }
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(3, 6, 8).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ assert factories[name](False)(image).shape == (1, 3, 6, 8)
+ torch.manual_seed(_FORWARD_SEED)
+ assert factories[name](True)(image).shape == (3, 6, 8)
+
+ # Differentiability is a family-wide property, so it is pinned as one sweep: RandomClahe is the only
+ # class of the 35 whose default output leaves the autograd graph, and RandomPosterize the only one
+ # whose gradient is identically zero while still reporting requires_grad.
+ # Snippet used to generate expected:
+ # x = (torch.rand(2, 3, 16, 16) * 0.8 + 0.1).requires_grad_()
+ # o = K.RandomClahe(p=1.0)(x); print(o.requires_grad, o.grad_fn)
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `False None`, and `True` with
+ # slow_and_differentiable=True; RandomPosterize gives requires_grad True with x.grad.abs().sum() 0.0
+ # below bits=8 and 1536.0 (= 2*3*16*16, the identity) at bits=8.
+ @pytest.mark.device_agnostic
+ def test_convention_random_clahe_is_differentiable_only_when_asked(self):
+ image = (torch.rand(2, 3, 16, 16) * 0.8 + 0.1).requires_grad_()
+ torch.manual_seed(_FORWARD_SEED)
+ fast = K.RandomClahe(p=1.0)(image)
+ assert not fast.requires_grad and fast.grad_fn is None
+ torch.manual_seed(_FORWARD_SEED)
+ slow = K.RandomClahe(p=1.0, slow_and_differentiable=True)(image)
+ assert slow.requires_grad
+ slow.sum().backward()
+ assert image.grad is not None and float(image.grad.abs().sum()) > 0.0
+
+ # The uint8 round trip is a step function, so the gradient below bits=8 is structurally zero even
+ # though requires_grad stays True; bits=8 skips the round trip and is the identity.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(("bits", "expected"), [(0, 0.0), (3, 0.0), (7, 0.0), (8, 1536.0)])
+ def test_convention_random_posterize_gradient_is_zero_below_eight_bits(self, bits, expected):
+ image = (torch.rand(2, 3, 16, 16) * 0.8 + 0.1).requires_grad_()
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomPosterize((bits, bits), p=1.0)(image)
+ assert out.requires_grad, "the output keeps requires_grad whatever the gradient is"
+ out.sum().backward()
+ assert float(image.grad.abs().sum()) == expected
+
+ # A non-integral `bits` is accepted and rounded half to even, which the "Integer" wording hid.
+ # Snippet used to generate expected:
+ # for b in (2.5, 3.5, 0.4, 0.6):
+ # torch.manual_seed(0); a = K.RandomPosterize((b, b), p=1.0); a(torch.rand(1, 3, 16, 16))
+ # print(b, a._params["bits_factor"].tolist())
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `2`, `4`, `0`, `1`.
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(("bits", "drawn"), [(2.5, 2), (3.5, 4), (0.4, 0), (0.6, 1)])
+ def test_convention_random_posterize_rounds_a_float_bits_half_to_even(self, bits, drawn):
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomPosterize((bits, bits), p=1.0)
+ aug(torch.rand(1, 3, 16, 16))
+ assert [int(v) for v in aug._params["bits_factor"].tolist()] == [drawn]
+
+ # ColorJiggle skips a step whose drawn factor is neutral, where ColorJitter evaluates every step
+ # under a torch.where. So the channel count only has to suit the steps that actually run.
+ # Snippet used to generate expected:
+ # for c in (1, 3, 4): torch.manual_seed(0); K.ColorJiggle(0, 0, 0, 0, p=1.0)(torch.rand(2, c, 5, 5))
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> all three accepted on ColorJiggle, C=1 and C=4 rejected
+ # on ColorJitter; a saturation- or hue-only ColorJiggle rejects C=1 and C=4 as well.
+ @pytest.mark.parametrize("channels", [1, 3, 4])
+ def test_convention_color_jiggle_skips_neutral_steps(self, device, dtype, channels):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(2, channels, 5, 5).to(device=device, dtype=dtype)
+ for factors in ((0.0, 0.0, 0.0, 0.0), (0.2, 0.0, 0.0, 0.0), (0.0, 0.2, 0.0, 0.0)):
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.ColorJiggle(*factors, p=1.0)(image).shape == image.shape
+ # The steps that do run still need three channels.
+ for factors in ((0.0, 0.0, 0.2, 0.0), (0.0, 0.0, 0.0, 0.1)):
+ torch.manual_seed(_FORWARD_SEED)
+ if channels == 3:
+ assert K.ColorJiggle(*factors, p=1.0)(image).shape == image.shape
+ else:
+ with pytest.raises(ValueError, match="shape of"):
+ K.ColorJiggle(*factors, p=1.0)(image)
+ # ColorJitter computes every step, so the neutral configuration raises where ColorJiggle does not.
+ torch.manual_seed(_FORWARD_SEED)
+ if channels == 3:
+ assert K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0)(image).shape == image.shape
+ else:
+ # WHICH step raises depends on the drawn `order`, so the message is not fixed. At C=4 the
+ # saturation primitive raises `ImageError: Not a color or gray tensor` when it comes first
+ # and the hue step raises `ValueError: Input size must have a shape of (*, 3, H, W)` when it
+ # does -- 102 against 98 over seeds 0..199, so pinning either one alone is a coin flip. At
+ # C=1 the saturation step passes a one-channel image through, so only the hue message occurs
+ # (200/200).
+ # Snippet used to generate expected:
+ # torch.manual_seed(1234); x = torch.rand(2, c, 5, 5)
+ # for s in range(200): torch.manual_seed(s); K.ColorJitter(0, 0, 0, 0, p=1.0)(x)
+ # executed 2026-09-16 (torch 2.14.0, cpu).
+ expected = r"Input size must have a shape of \(\*, 3, H, W\)"
+ if channels != 1:
+ expected = r"Not a color or gray tensor|" + expected
+ with pytest.raises((ValueError, ImageError), match=expected):
+ K.ColorJitter(0.0, 0.0, 0.0, 0.0, p=1.0)(image)
+
+ # The erasing box is clamped from BELOW as well as above, so it is never empty: scale=(0, 0) still
+ # erases one pixel and a 1x1 image is always erased in full.
+ # Snippet used to generate expected:
+ # torch.manual_seed(0); a = K.RandomErasing(scale=(0.0, 0.0), ratio=(1.0, 1.0), p=1.0)
+ # o = a(torch.ones(1, 1, 10, 10)); print(int((o == 0).sum()), a._params["heights"].tolist())
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `1 [1.0]`, and `1 [1.0]` for a 1x1 image.
+ @pytest.mark.device_agnostic
+ def test_convention_random_erasing_box_is_never_empty(self):
+ torch.manual_seed(_FORWARD_SEED)
+ degenerate = K.RandomErasing(scale=(0.0, 0.0), ratio=(1.0, 1.0), p=1.0)
+ out = degenerate(torch.ones(1, 1, 10, 10))
+ assert int((out == 0).sum()) == 1
+ assert degenerate._params["heights"].tolist() == [1.0]
+ assert degenerate._params["widths"].tolist() == [1.0]
+ torch.manual_seed(_FORWARD_SEED)
+ single = K.RandomErasing(p=1.0)(torch.ones(1, 1, 1, 1))
+ assert float(single.sum()) == 0.0
+
+ # When `ratio` straddles 1 the draw is a 50/50 mixture of [ratio[0], 1] and [1, ratio[1]], not uniform
+ # over the interval, so tall and wide boxes are equally likely whatever the sub-intervals' widths.
+ # A single-point range cannot see this -- it needs the ratio of the two branch populations.
+ # Snippet used to generate expected:
+ # g = RectangleEraseGenerator(scale=(0.25, 0.25), ratio=(0.3, 3.3))
+ # g.set_rng_device_and_dtype(torch.device("cpu"), torch.float32)
+ # torch.manual_seed(0); p = g((200000, 3, 400, 400))
+ # print((p["heights"] > p["widths"]).float().mean())
+ # executed 2026-09-16 (torch 2.14.0, cpu) -> `0.4987`, against `(3.3 - 1) / (3.3 - 0.3) = 0.7667` for a
+ # uniform draw; ratio=(1.0, 3.3) takes the single-sampler branch and gives 0.998.
+ @pytest.mark.device_agnostic
+ def test_convention_random_erasing_straddling_ratio_is_a_fair_mixture(self):
+ generator = RectangleEraseGenerator(scale=(0.25, 0.25), ratio=(0.3, 3.3))
+ generator.set_rng_device_and_dtype(torch.device("cpu"), torch.float32)
+ torch.manual_seed(_FORWARD_SEED)
+ params = generator((200000, 3, 400, 400))
+ tall = float((params["heights"] > params["widths"]).float().mean())
+ assert abs(tall - 0.5) < 0.01, "the straddling draw is a fair coin between the two sub-intervals"
+ uniform = (3.3 - 1.0) / (3.3 - 0.3)
+ assert abs(tall - uniform) > 0.2, "a uniform draw over the interval would be far from a fair coin"
+ # The fair coin is a property of the DRAW. The realised box only follows it while the
+ # `[1, H] x [1, W]` clamp does not bite, and on a strongly non-square image it always does.
+ # Snippet used to generate expected: this body with the shape replaced; executed 2026-09-16
+ # (torch 2.14.0, cpu) -> tall fraction 0.4987 at 400 x 400, 0.0 at 4 x 256 and 1.0 at 256 x 4.
+ for height, width, expected in ((4, 256, 0.0), (256, 4, 1.0)):
+ torch.manual_seed(_FORWARD_SEED)
+ clamped = generator((20000, 3, height, width))
+ realised = float((clamped["heights"] > clamped["widths"]).float().mean())
+ assert realised == expected, (height, width, realised)