Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(augmentation-intensity): trim convention blocks and pins to kornia scope (#4793)

Dmytro Mishkin4d04d8cb40d8
diff --git a/changelog.d/4793.fixed.md b/changelog.d/4793.fixed.md
new file mode 100644
index 000000000..8b5a91594
--- /dev/null
+++ b/changelog.d/4793.fixed.md
@@ -0,0 +1 @@
+Corrected the 2D intensity augmentation docstrings and the `kornia.enhance` `AdjustHue`, `AdjustContrastWithMeanSubtraction`, `AdjustSaturationWithGraySubtraction` and `AdjustBrightnessAccumulative` summaries: `RandomBrightness`, `RandomContrast` and `RandomSaturation` no longer claim to match PIL and torchvision (their formulas differ, and `ColorJitter` is the class whose steps use torchvision's), `RandomHue`, `RandomGamma` and the `enhance` modules state the mapping they do share with torchvision, the stale MPS and raw-error notes on `RandomEqualize` and `RandomClahe` are gone, and the convention blocks are trimmed to kornia's own behaviour. Newly found defects are linked as known issues: #4781, #4782, #4783, #4784, #4785, #4806, #4807, #4810, #4811 and #4813.
diff --git a/kornia/augmentation/_2d/intensity/auto_contrast.py b/kornia/augmentation/_2d/intensity/auto_contrast.py
index 199d87928..bf922c5ef 100644
--- a/kornia/augmentation/_2d/intensity/auto_contrast.py
+++ b/kornia/augmentation/_2d/intensity/auto_contrast.py
@@ -42,22 +42,10 @@ class RandomAutoContrast(IntensityAugmentationBase2D):
- 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]``.
-
- - non-contiguous input, such as a transposed or permuted image, produces the same
- values as its contiguous copy.
-
- .. 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.
+ - the output is :func:`kornia.enhance.normalize_min_max` of the input: each channel of each sample is
+ rescaled by its own minimum and maximum as ``(x - min) / (max - min + 1e-6)``. This is a rescale, not
+ a clamp, so an input outside ``[0, 1]`` is mapped into range rather than clipped, and a constant
+ channel comes back as zeros.
"""
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
index c2cb160e8..efd967921 100644
--- a/kornia/augmentation/_2d/intensity/base.py
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -40,26 +40,13 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
Convention:
- an intensity augmentation moves no image pixel, so this base supplies ``compute_transformation``
- itself and reports the identity matrix. Its direct mask, box and keypoint handlers pass their inputs
- through, except where a subclass overrides them: :class:`RandomErasing` also erases masks.
- A subclass supplies ``apply_transform`` and, where it draws anything, its ``_param_generator``.
- - the matrix is built lazily, on the first read of ``transform_matrix``.
- - this base adds no ``inverse``. When
- :class:`~kornia.augmentation.container.AugmentationSequential.inverse` can run, it skips 2D intensity
- children and reverses supported geometric children.
- - these classes assume the library-wide ``[0, 1]`` float image value range, 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.
+ itself and reports the identity matrix, built lazily on the first read of ``transform_matrix``. Its
+ mask, box and keypoint handlers pass their inputs through unless a subclass overrides them
+ (:class:`RandomErasing` also erases masks). It adds no ``inverse``:
+ :class:`~kornia.augmentation.container.AugmentationSequential.inverse` skips 2D intensity children.
+ - these classes assume the ``[0, 1]`` float image range stated under "Image tensors" in
+ :doc:`/get-started/conventions`. The base does not validate it; each class page states what the class
+ does outside that range, and a class whose page is silent does not clamp.
- 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
@@ -67,55 +54,24 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
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. :class:`RandomMotionBlur` instead draws
- one kernel size for the whole batch and repeats it in ``_params["ksize_factor"]`` with shape
- ``(B,)``; its angle and direction remain per sample unless ``same_on_batch=True``. :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 with ``same_on_batch=True`` store an
- expanded ``(B, C, H, W)`` view with shared storage for the batch; ``RandomPlasmaShadow`` stores
- ``(B, 1, H, W)``. :class:`ColorJiggle` and :class:`ColorJitter` both draw an application ``order``;
- it is shared by the whole batch. Both take a fixed ``order`` constructor argument. Without one,
- 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`, and
- :class:`RandomGaussianBlur`'s ``sigma`` at ``0`` and even ``kernel_size``, which the constructor
- admits and :func:`kornia.filters.gaussian_blur2d` rejects;
- :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`` -- a range that holds no odd size is rounded up to the next odd size
- rather than rejected, which leaves the requested range, so ``(4, 4)`` draws ``5`` and ``(2, 2)``
- draws ``3``, while ``(0, 2)`` raises because the only odd size it holds is ``1``. Since every
- odd size in the range is now drawn rather than the smallest one almost always, a range that
- straddles ``3`` raises only on the draws below it: ``(0, 3)`` and ``(1, 3)`` raise on about half
- the seeds instead of all of them, and the same applies to the image-size rule above -- the larger
- sizes are live against it for the first time, so ``kernel_size=(3, 5)`` with
- ``border_type="reflect"`` on a ``2 x 2`` image raises for roughly half the draws where the
- constant ``3`` always fit. A reversed pair such as ``(5, 3)`` raises at construction;
- 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 ``x`` means ``center Β± x``:
- its lower end is floored at the parameter's lower bound, so a non-negative parameter reads
- ``contrast=1.5`` as ``[0, 2.5]``, while an upper end past the bound raises the same error the
- explicit range does.
+ per sample where the class's own docstring says so -- and ``same_on_batch=True`` shares one draw.
+ :class:`RandomMotionBlur` draws one kernel size for the whole batch; :class:`Normalize`,
+ :class:`Denormalize` and :class:`RandomDissolving` hard-code ``same_on_batch=True``. A drawn
+ whole-image field (``gaussian_noise``, ``gradient``, ``plasma``, and :class:`RandomSaltAndPepperNoise`'s
+ ``mask_salt`` and ``mask_pepper``) is stored with the batched ``(B, C, H, W)`` input shape, even for a
+ ``(C, H, W)`` input with ``keepdim=True``; :class:`RandomPlasmaShadow`'s single-channel map is
+ ``(B, 1, H, W)``. With ``same_on_batch=True``, ``gaussian_noise`` is stored as
+ ``(1, C, H, W)`` and the plasma classes store an expanded view that shares one map across the batch.
+ - where a class documents bounds for a parameter, a range outside them usually raises at construction;
+ the class page states a bound it does not enforce, or checks only on the forward pass. A scalar
+ magnitude ``x`` usually means ``center Β± x`` around a centre the class fixes -- the neutral value, for a
+ factor such as ``contrast`` -- with its lower end floored at the bound, so ``contrast=1.5`` reads as
+ ``[0, 2.5]``, while an upper end past the bound raises. :class:`RandomSharpness` reads a scalar as
+ ``[0, x]`` and :class:`RandomPosterize` as ``[x, 8]``.
.. 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
+ Several of these classes return an all-zero image, with no warning, for an input whose values are all
+ negative, and :class:`RandomSolarize` does for one whose values are all at least ``1.5``. 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 615d00139..647557b87 100644
--- a/kornia/augmentation/_2d/intensity/box_blur.py
+++ b/kornia/augmentation/_2d/intensity/box_blur.py
@@ -47,28 +47,19 @@ class RandomBoxBlur(IntensityAugmentationBase2D):
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, and ``normalized=True`` matches
- :func:`kornia.filters.box_blur`'s ``separable=True`` default.
- - 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.
+ - ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.box_blur`. An even
+ entry is accepted and shifts the image half a pixel toward the top-left -- for an even extent ``k``, output
+ ``i`` averages inputs ``i - k // 2 + 1`` to ``i + k // 2`` -- where :class:`RandomGaussianBlur` raises.
+ - the output is not clamped. At the default ``border_type="reflect"`` every output value is a mean of
+ input values and stays between the input's extremes, up to the rounding of the kernel weights;
+ ``border_type="constant"`` pads with zeros, which
+ pulls a border pixel toward ``0``.
.. note::
- The padding sets a minimum image size. An even kernel extent ``k`` is padded asymmetrically, with the
- wider ``k // 2`` pad behind, so the bound is stated against that pad rather than the radius: at the default
- ``border_type="reflect"`` each spatial axis must be longer than ``k // 2`` along it (``3`` pixels for a
- ``4``-wide kernel), and ``"circular"`` needs at least ``k // 2``; both raise a ``ValueError`` naming the
- class, the kernel and the input shape. ``"constant"`` and ``"replicate"`` invent their padding and run down
- to a single pixel.
+ The padding sets a minimum image size: at ``border_type="reflect"`` each spatial axis must be longer than
+ ``k // 2`` for a kernel extent ``k`` along it, and at ``"circular"`` at least that long; a smaller image
+ raises a ``ValueError`` naming the class, the kernel and the input shape. ``"constant"`` and
+ ``"replicate"`` run down to a single pixel.
.. 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 0c2e3c6b2..2dc6884ce 100644
--- a/kornia/augmentation/_2d/intensity/brightness.py
+++ b/kornia/augmentation/_2d/intensity/brightness.py
@@ -28,7 +28,9 @@ from kornia.enhance.adjust import adjust_brightness
class RandomBrightness(IntensityAugmentationBase2D):
r"""Apply a random transformation to the brightness of a torch.Tensor image.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ The shift is additive: the output is ``input + (factor - 1)``, before the default clamp. torchvision's and
+ PIL's brightness is multiplicative (``input * factor``); :class:`ColorJitter`'s brightness step is that
+ formula.
.. image:: _static/img/RandomBrightness.png
@@ -46,20 +48,16 @@ class RandomBrightness(IntensityAugmentationBase2D):
- 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.
+ - ``brightness`` is centred on ``1.0``: the drawn factor is re-based to ``factor - 1`` before it reaches
+ :func:`kornia.enhance.adjust_brightness`, whose own identity is ``0.0``, so the same number passed
+ straight to the primitive means something else.
+ - at the default ``clip_output=True`` the result is clamped into ``[0, 1]``; with ``clip_output=False``
+ the raw sum is returned.
.. 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>`_.
+ At the default ``clip_output=True`` an all-negative input comes back as an all-zero image whenever the
+ drawn shift does not lift it above zero, which at the default ``brightness=(1.0, 1.0)`` is always.
+ 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 aaad1972b..bd0a81764 100644
--- a/kornia/augmentation/_2d/intensity/channel_dropout.py
+++ b/kornia/augmentation/_2d/intensity/channel_dropout.py
@@ -44,15 +44,10 @@ class RandomChannelDropout(IntensityAugmentationBase2D):
- 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 an ``int`` or a ``float`` in ``[0, 1]``: this class's own ``__init__`` rejects
- anything outside the bounds, and anything that is not a Python ``int`` or ``float`` on type. As with
- :class:`RandomErasing`'s ``value``, ``0`` and ``1`` are accepted, and so are ``False`` and ``True``.
- ``ChannelDropoutGenerator`` never sees ``fill_value`` -- unlike :class:`RandomErasing`, whose
- ``value`` guard does live in its generator. 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.
+ - the channels named by the drawn ``channel_idx`` are overwritten with the literal ``fill_value``, an
+ ``int`` or ``float`` in ``[0, 1]`` checked at construction. Every other channel is left exactly as it
+ came in, so the input's value range is carried through.
+ - ``num_drop_channels`` is checked against the input's channel count on the forward pass.
- ``fill_value`` is held in a non-persistent buffer, so ``.to(...)`` moves and casts it while
``state_dict()`` gains no key for it.
diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.py
index 866e9c6fd..e6bc9f5f0 100644
--- a/kornia/augmentation/_2d/intensity/clahe.py
+++ b/kornia/augmentation/_2d/intensity/clahe.py
@@ -31,16 +31,14 @@ 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.
+ See the Convention block on :class:`~kornia.augmentation.IntensityAugmentationBase2D`.
Args:
clip_limit: the ``(low, high)`` range the per-sample contrast-limiting threshold is drawn from.
A value is drawn for each image, or once and shared across the batch when ``same_on_batch=True``.
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)``.
+ two-element tuple -- a scalar raises a ``ValueError`` at construction -- and ``(0.0, 0.0)`` disables
+ clipping. A negative bound is not rejected and behaves like ``0.0``.
grid_size: number of tiles to be cropped in each direction (GH, GW).
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
@@ -51,37 +49,19 @@ class RandomClahe(IntensityAugmentationBase2D):
to the batch form (False).
Convention:
- - an input outside ``[0, 1]`` raises a ``RuntimeError`` naming
- :func:`kornia.enhance.equalize_clahe` and that range, the way :class:`RandomEqualize` raises for
- :func:`kornia.enhance.equalize`. As for :class:`RandomEqualize`, 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. The check is ``torch._assert_async``, which
- has an MPS kernel from torch ``2.13``. On an older MPS release the condition is read on the host
- instead, which costs one device sync per call and is skipped under ``torch.compile``.
-
- Convention:
- - ``clip_limit`` is drawn per sample and each image is equalized with its own draw. Both eager and
- compiled execution batch the per-image limits as tensors, so newly sampled limits reuse the same
- graph without converting draws to Python scalars. Batched differentiable histogram arithmetic
- can differ from separate per-image calls by floating-point rounding.
- On MPS, clip limits stored on the device are copied to CPU for float64 threshold arithmetic,
- then thresholds are copied back; this preserves scalar rounding but adds transfer overhead.
+ - an input outside ``[0, 1]`` raises a ``RuntimeError`` naming :func:`kornia.enhance.equalize_clahe` and
+ that range, as :class:`RandomEqualize` does. The check guards a 256-entry lookup indexed with
+ ``(input * 255).long()``, so a value less than one 8-bit code outside ``[0, 1]`` is still admitted, up
+ to the rounding of ``input * 255`` in the input's dtype.
+ - ``grid_size`` tiles the two axes independently, and a grid that does not divide the image pads it, so
+ ``grid_size=(3, 3)`` works on a ``10 x 10`` image. A grid larger than the image raises a ``ValueError``.
.. warning::
- ``grid_size`` is unvalidated past its positivity check. Its two
- entries tile the two axes independently, and a grid that does not tile the image is padded instead, so
- ``grid_size=(3, 3)`` works on a ``10 x 10`` image. Because :func:`kornia.enhance.equalize_clahe` rounds
- the tile up to an even size along each axis, an exactly dividing grid can still pad: ``(4, 5)`` pads 4
- rows and no columns of a ``20 x 20`` image. 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.
+ An image as large as the grid, such as ``8 x 8`` at the default ``grid_size=(8, 8)``, raises a raw padding
+ error instead of the ``ValueError``. Tracked in `#4783 <https://github.com/kornia/kornia/issues/4783>`_.
.. note::
- This function internally uses :func:`kornia.enhance.equalize_clahe`, which expects the input in
- :math:`[0, 1]` and raises a ``RuntimeError`` naming that range for values its 256-bin lookup
- cannot index.
+ This function internally uses :func:`kornia.enhance.equalize_clahe`.
Examples:
>>> img = torch.rand(1, 10, 20)
diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.py
index f03319a46..d21b8934a 100644
--- a/kornia/augmentation/_2d/intensity/color_jiggle.py
+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py
@@ -97,50 +97,26 @@ class ColorJiggle(IntensityAugmentationBase2D):
- 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`` is where they part: this class rejects it, because its
- bound is ``[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. Both classes accept 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` 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.
- - a fixed ``order`` makes a three-channel transform ``torch.compile`` fullgraph-safe while preserving
- lazy neutral-factor skips: eager and compiled calls both dispatch each step through ``torch.cond``,
- and the result is contiguous even for a channels-last input. The default sampled tensor order, and
- neutral one- and four-channel configurations, keep the Python dispatch path, as does a fixed order
- where Dynamo is unavailable (torch ``2.5.1`` on Python ``3.13``). Differentiating a
- compiled fixed-order transform needs torch ``2.7`` or newer with the ``inductor`` backend: on
- ``2.5.1`` and ``2.6.0`` the forward pass compiles but the backward pass raises, while the
- ``aot_eager`` backend works on each.
- - the ``[0, 2]`` bound applies to both argument forms: an explicit ``brightness`` range reaching
- above ``2``, such as ``(0.0, 3.0)``, and a scalar whose implied ``[1 - x, 1 + x]`` does, such as
- ``1.5``, are both rejected at construction with
- ``brightness out of bounds. Expected inside (0, 2)``, where :class:`ColorJitter` accepts either.
+ - the steps use kornia's own primitives: brightness is additive (the drawn factor is re-based to
+ ``factor - 1`` for :func:`kornia.enhance.adjust_brightness`, as :class:`RandomBrightness` does),
+ contrast scales the raw values (:func:`kornia.enhance.adjust_contrast`), saturation scales the HSV
+ saturation (:func:`kornia.enhance.adjust_saturation`) and hue shifts by turns of the hue circle
+ (:func:`kornia.enhance.adjust_hue`). :class:`ColorJitter` uses torchvision's blend formulas for the first
+ three instead, so the two classes give different outputs for the same factors.
+ - with matching effective bounds and the default CPU sampler, this class and :class:`ColorJitter` draw the
+ same factors and the same ``order`` from the same seed. The drawn ``order`` is shared by the whole
+ batch; without a fixed ``order`` argument, an ``order`` tensor passed as a forward keyword or in
+ replayed ``params`` replaces it.
+ - ``brightness`` is bounded to ``[0, 2]`` in both argument forms: ``(0.0, 3.0)`` and the scalar ``1.5``,
+ whose implied range reaches ``2.5``, raise at construction, where :class:`ColorJitter` accepts either.
+ - a step is skipped when every drawn factor in the batch is neutral, so ``ColorJiggle(0, 0, 0, 0)`` is
+ the identity for any input, and the channel count only has to suit the steps that run: saturation and
+ hue need three channels, a brightness- or contrast-only configuration accepts any. The brightness and
+ contrast steps clamp into ``[0, 1]``; saturation and hue do not clamp the RGB result.
.. 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
+ Because the brightness and contrast steps clamp, an all-negative input can come back as an all-zero
+ image, depending on the drawn factors and on which steps run. Tracked in
`#4430 <https://github.com/kornia/kornia/issues/4430>`_.
.. note::
diff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.py
index 51394598f..d5a50516d 100644
--- a/kornia/augmentation/_2d/intensity/color_jitter.py
+++ b/kornia/augmentation/_2d/intensity/color_jitter.py
@@ -34,9 +34,10 @@ from kornia.enhance import (
class ColorJitter(IntensityAugmentationBase2D):
r"""Apply a random transformation to the brightness, contrast, saturation and hue of a torch.Tensor image.
- This implementation aligns PIL. Hence, the output is close to TorchVision. However, it does not
- follow the color theory and is not be actively maintained. Prefer using
- :func:`kornia.augmentation.ColorJiggle`
+ The four steps are torchvision's formulas -- brightness multiplies the image by the factor, contrast blends it
+ with its grayscale mean, saturation with its grayscale, and hue is torchvision's ``adjust_hue`` shift -- so this
+ is the class to port ``torchvision.transforms.ColorJitter`` code to. It is not actively maintained; prefer
+ :class:`ColorJiggle` for new code.
.. image:: _static/img/ColorJitter.png
@@ -61,40 +62,39 @@ class ColorJitter(IntensityAugmentationBase2D):
- 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`` is where they part: :class:`ColorJiggle` rejects it, because
- its bound is ``[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). Both classes accept 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.
+ - see :class:`ColorJiggle` for how the two classes relate. This class takes the brightness factor as
+ drawn, a multiplier whose identity is ``1``, and a scalar ``brightness`` above ``1`` draws from
+ ``[0, 1 + brightness]``, as torchvision does.
+ - a step's result is discarded only when every factor in the batch equals its guard value -- ``1`` for
+ contrast and saturation, ``0`` for hue and, as the #4785 warning below states, for brightness;
+ otherwise the brightness, contrast and (three-channel) saturation steps clamp the whole batch into
+ ``[0, 1]``. A fixed ``order`` without index ``0`` skips the brightness step.
.. 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>`_.
+ Every step in the order is computed even when its factors are neutral, so the hue step rejects any
+ channel count but three and the saturation step any but one or three whatever the factors:
+ ``ColorJitter(brightness=0.2)`` raises on a grayscale image. An eager call also pays for the neutral
+ steps' colour-space round trips. Tracked in `#4813 <https://github.com/kornia/kornia/issues/4813>`_.
+
+ .. warning::
+ The brightness step is skipped for a factor of ``0`` instead of the neutral ``1``: a batch whose factors
+ are all ``0`` comes back unchanged instead of black, and ``ColorJitter(0, 0, 0, 0)`` clamps an
+ out-of-range input. Tracked in
+ `#4785 <https://github.com/kornia/kornia/issues/4785>`_.
+
+ .. warning::
+ On an input that is not three-channel, which only a fixed ``order`` admits, the contrast step blends each
+ sample with the mean of the whole batch rather than its own. Tracked in
+ `#4806 <https://github.com/kornia/kornia/issues/4806>`_.
+
+ .. warning::
+ After this class's own ``.compile()`` the module no longer pickles or passes through ``torch.save``.
+ Tracked in `#4807 <https://github.com/kornia/kornia/issues/4807>`_.
+
+ .. warning::
+ Because the brightness, contrast and saturation steps clamp, an all-negative input can come back as an
+ all-zero image, depending on the draw and the order. Tracked in
+ `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
.. note::
This function internally uses :func:`kornia.enhance.adjust_brightness_accumulative`,
diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.py
index a99168ad6..facd85b51 100644
--- a/kornia/augmentation/_2d/intensity/contrast.py
+++ b/kornia/augmentation/_2d/intensity/contrast.py
@@ -28,7 +28,9 @@ from kornia.enhance.adjust import adjust_contrast
class RandomContrast(IntensityAugmentationBase2D):
r"""Apply a random transformation to the contrast of a torch.Tensor image.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ The factor scales the raw values: the output is ``input * factor``. torchvision's and PIL's contrast blends
+ the image with its grayscale mean instead (``factor * input + (1 - factor) * mean``); :class:`ColorJitter`'s
+ contrast step is that formula.
.. image:: _static/img/RandomContrast.png
@@ -46,16 +48,14 @@ class RandomContrast(IntensityAugmentationBase2D):
- 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.
+ - the drawn factor reaches :func:`kornia.enhance.adjust_contrast` unchanged -- it is not re-based the way
+ :class:`RandomBrightness` re-bases its own -- so ``1.0`` is the identity: for any input with
+ ``clip_output=False``, and for an input in ``[0, 1]`` at the default.
+ - at the default ``clip_output=True`` the result is clamped into ``[0, 1]``; with ``clip_output=False``
+ the raw product is returned.
.. 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
+ At the default ``clip_output=True`` an all-negative input comes back as an all-zero image. Tracked in
`#4430 <https://github.com/kornia/kornia/issues/4430>`_.
.. note::
diff --git a/kornia/augmentation/_2d/intensity/denormalize.py b/kornia/augmentation/_2d/intensity/denormalize.py
index a013f3138..73add3b26 100644
--- a/kornia/augmentation/_2d/intensity/denormalize.py
+++ b/kornia/augmentation/_2d/intensity/denormalize.py
@@ -45,16 +45,10 @@ class Denormalize(IntensityAugmentationBase2D):
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, integer, sequence or tensor ``mean`` and
- ``std``, up to float rounding, when both apply -- each draws its own ``p`` gate.
+ - the ``mean`` and ``std`` forms, the batch-wide ``p`` gate and the storage in ``flags`` are those of
+ :class:`Normalize`.
+ - this class inverts :class:`Normalize` built with the same ``mean`` and ``std``, up to float rounding,
+ when both apply -- each draws its own ``p`` gate.
- the result is not clamped: it is ``input * std + mean`` whatever range the input is in.
.. note::
diff --git a/kornia/augmentation/_2d/intensity/dissolving.py b/kornia/augmentation/_2d/intensity/dissolving.py
index bdb6fc5fc..a44081891 100644
--- a/kornia/augmentation/_2d/intensity/dissolving.py
+++ b/kornia/augmentation/_2d/intensity/dissolving.py
@@ -64,6 +64,10 @@ class RandomDissolving(IntensityAugmentationBase2D):
- Input: :math:`(C, H, W)` or :math:`(B, C, H, W)`.
- Output: :math:`(B, C, H, W)`
+ Convention:
+ - the result is decoded by the Stable Diffusion VAE and clamped into ``[0, 1]``, whatever range the input
+ is in.
+
.. 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,
diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.py
index a6c530727..ce1ad8e4d 100644
--- a/kornia/augmentation/_2d/intensity/equalize.py
+++ b/kornia/augmentation/_2d/intensity/equalize.py
@@ -41,21 +41,13 @@ class RandomEqualize(IntensityAugmentationBase2D):
- 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 message naming
- :func:`kornia.enhance.equalize_clahe` and the range.
- - 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.
+ - an input outside ``[0, 1]`` raises a ``RuntimeError`` naming :func:`kornia.enhance.equalize` and that
+ range, instead of being transformed. The check guards a 256-entry lookup indexed with
+ ``(input * 255).long()``, so a value less than one 8-bit code outside ``[0, 1]`` is still admitted, up
+ to the rounding of ``input * 255`` in the input's dtype.
.. 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. The
- check is ``torch._assert_async``, which has an MPS kernel from torch ``2.13``; on an older MPS
- release the condition is read on the host instead, which costs one device sync per call and is
- skipped under ``torch.compile``.
+ This function internally uses :func:`kornia.enhance.equalize`.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/_2d/intensity/erasing.py b/kornia/augmentation/_2d/intensity/erasing.py
index e40a9114a..da30051b9 100644
--- a/kornia/augmentation/_2d/intensity/erasing.py
+++ b/kornia/augmentation/_2d/intensity/erasing.py
@@ -35,9 +35,7 @@ class RandomErasing(IntensityAugmentationBase2D):
for each of the images in the batch.
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.
+ ``scale``, with an aspect ratio sampled from ``ratio``.
Args:
scale: range of proportion of erased area against input image.
@@ -55,18 +53,13 @@ class RandomErasing(IntensityAugmentationBase2D):
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.
+ to whole pixels and then clamped to ``[1, H] x [1, W]``, so it is never empty and never larger than the
+ image, and the erased area 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.
+ - when ``ratio`` straddles ``1`` the draw is not uniform over the interval: a fair coin picks between
+ ``[ratio[0], 1]`` and ``[1, ratio[1]]``, so at the default ``ratio=(0.3, 3.3)`` half the draws are above
+ ``1``.
- 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
@@ -76,8 +69,7 @@ class RandomErasing(IntensityAugmentationBase2D):
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
+ This function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
applied transformation will be merged int to the input transformation torch.Tensor and returned.
Examples:
diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.py
index a7b9393a1..db4081214 100644
--- a/kornia/augmentation/_2d/intensity/gamma.py
+++ b/kornia/augmentation/_2d/intensity/gamma.py
@@ -27,7 +27,7 @@ from kornia.enhance.adjust import adjust_gamma
class RandomGamma(IntensityAugmentationBase2D):
r"""Apply a random transformation to the gamma of a torch.Tensor image.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ The formula is torchvision's ``adjust_gamma`` for a float image: ``clamp(gain * input ** gamma, 0, 1)``.
.. image:: _static/img/RandomGamma.png
@@ -45,21 +45,16 @@ class RandomGamma(IntensityAugmentationBase2D):
- 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``.
+ - the clamp is not optional: unlike :class:`RandomBrightness` and :class:`RandomContrast` this class has
+ no ``clip_output``.
+ - ``gamma`` and ``gain`` must be non-negative. Neither is checked at construction: the check is in
+ :func:`kornia.enhance.adjust_gamma`, so a negative value raises a ``RuntimeError`` on the forward pass.
+ It is not run for an MPS image, where a negative value goes through the same formula unchecked.
.. 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>`_.
+ On a negative input the power is NaN unless ``gamma`` is an integer, and the clamp keeps the NaN; at the
+ default ``gamma=1.0`` 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 a0d0f2714..61e0b1815 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_blur.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_blur.py
@@ -53,23 +53,25 @@ class RandomGaussianBlur(IntensityAugmentationBase2D):
- 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.
+ - ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.gaussian_blur2d`. An
+ even entry is not rounded up: the forward pass raises that function's odd-size error.
+ - ``sigma`` is drawn once per sample, as a single scalar used for both axes, and a drawn ``0`` raises on
+ the forward pass. 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.
+ mean of input values and stays between the input's extremes, up to the rounding of the kernel weights;
+ ``border_type="constant"`` pads with zeros, which pulls a border pixel toward ``0``.
.. note::
- The padding sets a minimum image size. At the default ``border_type="reflect"`` each spatial axis must be
- longer than the kernel's radius along it, and ``"circular"`` needs at least that radius; both raise a
- ``ValueError`` naming the class, the kernel and the input shape. ``"constant"`` and ``"replicate"`` invent
- their padding and run down to a single pixel.
+ The padding sets a minimum image size: at ``border_type="reflect"`` each spatial axis must be longer than
+ the kernel's radius along it, and at ``"circular"`` at least that long; a smaller image raises a
+ ``ValueError`` naming the class, the kernel and the input shape. ``"constant"`` and ``"replicate"`` run
+ down to a single pixel.
+
+ .. warning::
+ After this class's own ``.compile()`` the module no longer pickles or passes through ``torch.save``.
+ Tracked in `#4807 <https://github.com/kornia/kornia/issues/4807>`_.
.. 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 ff40fbf2b..eb0192af7 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py
@@ -67,30 +67,26 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):
- 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.
+ - the class adds the drawn field ``_params["gradient"]`` 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 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. Every admitted ``sigma`` gives a finite kernel, including the
- ``0`` the constructor's check admits: :func:`kornia.filters.gaussian` measures each sample's
- squared distance from the **nearest sample** rather than from the mean, so that sample always
- weighs ``exp(0) = 1`` and the normalizing sum cannot underflow. At ``sigma=0`` the kernel is the
- unit impulse -- all the weight on the nearest sample, or split evenly between the two that tie
- half a pixel either side of the mean on an even-length axis.
- - 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.
+ narrower kernel on a smaller image. Every admitted ``sigma`` gives a finite kernel, ``0`` included.
.. 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
+ The drawn ``center`` is rounded to a whole pixel, half to even, so on an odd-length axis the peak can sit
+ a pixel past the pixel-centre position ``center * L - 0.5``: ``center=0.5`` lands on column ``4`` of a
+ 7-pixel-wide image. Tracked in `#4811 <https://github.com/kornia/kornia/issues/4811>`_.
+
+ .. warning::
+ After this class's own ``.compile()`` the module no longer pickles or passes through ``torch.save``.
+ Tracked in `#4807 <https://github.com/kornia/kornia/issues/4807>`_.
+
+ .. warning::
+ An all-negative input can come back as an all-zero image, depending on the sampled gradient. Tracked in
`#4430 <https://github.com/kornia/kornia/issues/4430>`_.
.. note::
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
index 9ec786cda..8b6536d83 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -39,12 +39,8 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
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.
+ - the noise is additive and recorded in full: the output is the input plus ``_params["gaussian_noise"]``,
+ so ``mean`` offsets the image rather than naming the mean the output should have.
- nothing is clamped, so an input already inside ``[0, 1]`` can leave it in either direction.
Examples:
diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.py
index ac19f4dec..cf2534307 100644
--- a/kornia/augmentation/_2d/intensity/hue.py
+++ b/kornia/augmentation/_2d/intensity/hue.py
@@ -29,7 +29,8 @@ from kornia.enhance.adjust import adjust_hue
class RandomHue(IntensityAugmentationBase2D):
r"""Apply a random transformation to the hue of a torch.Tensor image.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ The shift is in turns of the hue circle, the unit of torchvision's ``adjust_hue`` ``hue_factor``, so a
+ torchvision hue range carries over unchanged.
.. image:: _static/img/RandomHue.png
@@ -53,9 +54,9 @@ class RandomHue(IntensityAugmentationBase2D):
- 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 in every dtype.
+ - the result is not clamped: a hue rotation keeps each pixel's largest and smallest channel, so a pixel
+ outside ``[0, 1]`` keeps a channel outside it. A pixel whose largest channel is exactly ``0`` comes back
+ as zeros.
.. note::
This function internally uses :func:`kornia.enhance.adjust_hue`
diff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.py
index 623d7d3be..dbc0651d1 100644
--- a/kornia/augmentation/_2d/intensity/linear_illumination.py
+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py
@@ -45,22 +45,15 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):
- 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.
+ - the class adds the drawn field ``_params["gradient"]`` 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
+ An all-negative input can come back as an all-zero image, depending on the sampled gradient. Tracked in
`#4430 <https://github.com/kornia/kornia/issues/4430>`_.
.. note::
@@ -173,22 +166,15 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):
- 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.
+ - the class adds the drawn field ``_params["gradient"]`` 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
+ An all-negative input can come back as an all-zero image, depending on the sampled gradient. Tracked in
`#4430 <https://github.com/kornia/kornia/issues/4430>`_.
.. note::
diff --git a/kornia/augmentation/_2d/intensity/median_blur.py b/kornia/augmentation/_2d/intensity/median_blur.py
index 3d87db9e6..d2db8cc9d 100644
--- a/kornia/augmentation/_2d/intensity/median_blur.py
+++ b/kornia/augmentation/_2d/intensity/median_blur.py
@@ -38,19 +38,15 @@ class RandomMedianBlur(IntensityAugmentationBase2D):
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 by :func:`kornia.filters.median_blur` under
- every implementation it selects -- the ``F.conv2d`` window extraction and the selection network it
- uses instead for a 3x3 or 5x5 inference pass alike -- so a border median is taken over zeros as well
+ - ``kernel_size`` is ``(kH, kW)``: rows, then columns, as in :func:`kornia.filters.median_blur`.
+ - the output is not clamped. The window is zero-padded, 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``.
+ - 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``.
+
+ .. warning::
+ An even entry in ``kernel_size`` is accepted at construction and then fails on the forward pass with a raw
+ torch error rather than a named one. Tracked in `#4781 <https://github.com/kornia/kornia/issues/4781>`_.
.. 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 564dfabea..9b7bec186 100644
--- a/kornia/augmentation/_2d/intensity/motion_blur.py
+++ b/kornia/augmentation/_2d/intensity/motion_blur.py
@@ -63,36 +63,29 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
- ``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.
+ ``"bilinear"`` or ``"bicubic"`` also spread weight off the line.
- the defaults ``border_type="constant"`` and ``resample="nearest"`` are the function's own defaults.
- - a ranged ``kernel_size`` is drawn once per call and repeated into ``_params["ksize_factor"]``
- with shape ``(B,)``. All samples use that size, even with ``same_on_batch=False``; angle and
- direction are sampled per image unless ``same_on_batch=True``. Previously saved parameters
- with differing kernel sizes still select one entry via ``_params["idx"]`` for the whole batch.
- A tuple range draws each odd size inside it with equal probability, bounds included, so
- ``kernel_size=(3, 5)`` draws ``3`` and ``5`` and ``(3, 20)`` draws ``3, 5, ..., 19``. A range that
- holds no odd size is rounded **up** out of the requested range instead, so ``(4, 4)`` draws ``5``;
- a reversed one such as ``(20, 3)`` raises at construction. Because the whole range is drawn, and
- not just its lowest odd size, every size in it is live against the image-size rule below: with
- ``border_type="reflect"`` a ``kernel_size=(3, 5)`` on a ``2 x 2`` image raises on the draws of
- ``5`` -- about half of them -- where a constant ``3`` always fit.
- - 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.
+ - a ranged ``kernel_size`` is drawn once per call and repeated into ``_params["ksize_factor"]`` with
+ shape ``(B,)``, so every sample uses that size even with ``same_on_batch=False``; angle and direction
+ are drawn per sample unless ``same_on_batch=True``. A tuple range draws each odd size inside it with
+ equal probability, bounds included, so ``(3, 20)`` draws ``3, 5, ..., 19``. A range that holds no odd
+ size is rounded up out of the requested range, so ``(4, 4)`` draws ``5``; a reversed one such as
+ ``(20, 3)`` raises at construction, and a drawn size below ``3`` raises on the forward pass.
+ - the output is not clamped. At the default ``border_type="constant"`` the padding is zeros, so a border
+ pixel is pulled toward ``0``. 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 the default
- ``border_type="constant"`` and at ``"replicate"``. ``"reflect"`` raises once a spatial axis is
- no longer than half the kernel size along it, and ``"circular"`` raises a padding error of its
- own once the kernel radius exceeds a spatial axis. Unlike :class:`RandomBoxBlur`,
- :class:`RandomGaussianBlur` and :class:`RandomSharpness`, which name the class and the shape,
- both of these surface as raw torch errors.
+ ``border_type="constant"`` and at ``"replicate"``. ``"reflect"`` needs each spatial axis longer than
+ the kernel radius along it, and ``"circular"`` at least that long.
+
+ .. warning::
+ Under ``"reflect"`` and ``"circular"`` an image too small for the drawn kernel raises a raw torch padding
+ error, where :class:`RandomBoxBlur` and :class:`RandomGaussianBlur` raise a ``ValueError`` naming the
+ class and the shape. Tracked in `#4784 <https://github.com/kornia/kornia/issues/4784>`_.
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
+ This function accepts another transformation torch.Tensor (:math:`(B, 3, 3)`), then the
applied transformation will be merged int to the input transformation torch.Tensor and returned.
Please set ``resample`` to ``'bilinear'`` if more meaningful gradients wanted.
diff --git a/kornia/augmentation/_2d/intensity/normalize.py b/kornia/augmentation/_2d/intensity/normalize.py
index 1900cf1cc..3ee98fd7e 100644
--- a/kornia/augmentation/_2d/intensity/normalize.py
+++ b/kornia/augmentation/_2d/intensity/normalize.py
@@ -49,18 +49,14 @@ class Normalize(IntensityAugmentationBase2D):
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, integer, sequence or tensor ``mean`` and ``std``
- inverts this class, up to float rounding, when both apply -- each draws its own ``p`` gate.
+ - ``p`` gates the whole batch rather than each sample: the constructor hard-codes ``same_on_batch=True``
+ and takes no ``same_on_batch`` argument.
+ - the statistics live in ``flags`` rather than in a buffer: ``state_dict()`` is empty and
+ ``Module.to(...)`` does not move them; they are cast to the input's device and dtype on each call.
+ - :class:`Denormalize` built with the same ``mean`` and ``std`` inverts this class, up to float
+ rounding, when both apply -- each draws its own ``p`` gate.
- the result is not clamped: moving an image out of ``[0, 1]`` is what this class is for.
- - non-contiguous input, such as a transposed or permuted image, produces the same
- values as its contiguous copy.
-
.. 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 c6509f98e..f68dba754 100644
--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py
+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py
@@ -105,7 +105,9 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
Args:
mode: 'blackbody' or 'CIED'.
- select_from: choose a list of jitters to apply from. `blackbody` range [0-24], `CIED` range [0-22]
+ select_from: choose a list of jitters to apply from. `blackbody` range [0-24], `CIED` range [0-22].
+ The entries index the table like a Python sequence: one past the end raises at construction, and a
+ negative one counts from the end.
same_on_batch: apply the same transformation across the batch.
p: probability that the random erasing operation will be performed.
keepdim: whether to keep the output shape the same as input (True) or broadcast it
@@ -118,10 +120,7 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
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``.
+ negative while any value above ``1``, green included, is cut back to ``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.
@@ -130,9 +129,6 @@ class RandomPlanckianJitter(IntensityAugmentationBase2D):
does not load into an instance built with the other. Tracked in
`#4428 <https://github.com/kornia/kornia/issues/4428>`_.
- .. note::
- Input torch.Tensor must be float and normalized into [0, 1].
-
Examples:
To apply planckian jitter based on mode
diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.py
index d37845a0b..7e725598e 100644
--- a/kornia/augmentation/_2d/intensity/plasma.py
+++ b/kornia/augmentation/_2d/intensity/plasma.py
@@ -74,9 +74,8 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):
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 sampled fractal map is recorded as ``_params["plasma"]``, so 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.
@@ -148,9 +147,8 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):
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 sampled fractal map is recorded as ``_params["plasma"]``, so 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.
@@ -219,18 +217,16 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):
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 sampled fractal map is recorded as ``_params["plasma"]`` with a single channel, ``(B, 1, H, W)``: one
+ shade mask is applied to every channel of a sample. 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::
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>`_.
+ an all-zero image. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.py
index d14c4baaa..eb4fd26f6 100644
--- a/kornia/augmentation/_2d/intensity/posterize.py
+++ b/kornia/augmentation/_2d/intensity/posterize.py
@@ -48,22 +48,18 @@ class RandomPosterize(IntensityAugmentationBase2D):
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.
+ 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 round trip is a step function: the output still has ``requires_grad=True``, but its gradient with
+ respect to the input is identically ``0`` below ``bits=8``, and the identity at ``8``.
- 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>`_.
+ Outside ``[0, 1]`` the output is the posterized ``uint8`` conversion of the raw float, not of the clamped
+ input, and that conversion of an out-of-range float is undefined. A
+ sample that draws ``bits=8`` skips the conversion and keeps its out-of-range values. 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 546badcd8..95b8b9001 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -49,28 +49,18 @@ class RandomRain(IntensityAugmentationBase2D):
- 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.
- - every start position that keeps the whole drop inside the image is equally likely, so the last row
- and the last column are reachable. Reachable by a start, not necessarily painted: the gaps inside a
- drop's span described above can still leave a column untouched -- ``drop_height=5`` with
- ``drop_width=9`` on a ``6 x 10`` image has one legal start and never paints column ``8``.
- - the three integer ranges are closed and uniform: every integer from the lower to the upper bound
- is drawn with the same probability, so the default ``drop_height=(5, 20)`` reaches ``20``, the
- default ``drop_width=(-5, 5)`` reaches ``-5`` and ``5``, and ``0`` carries no more weight than
- any other width. Both upper bounds are live against the size rule above, which they were not
- when they were practically never drawn: with the defaults an image 20 pixels tall, or 5 pixels
- wide, now raises on some seeds -- and on every seed once it is 5 pixels tall or shorter, where
- no drawable height is legal. A range that is reversed, fractional or non-finite raises
- ``ValueError`` at construction.
- - ``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.
+ - both sizes must be strictly smaller than the image on their own axis, checked on the forward pass,
+ where the image shape is known; a ``drop_height`` below ``1`` raises there too.
+ - every start position that keeps the whole drop inside the image is equally likely.
+ - the three integer ranges are closed and uniform, so the default ``drop_height=(5, 20)`` reaches ``20``
+ and the default ``drop_width=(-5, 5)`` reaches both ends. With the defaults an image 20 pixels tall, or
+ 5 pixels wide, therefore raises on some draws. A range that is reversed, fractional or non-finite
+ raises ``ValueError`` at construction.
+
+ .. warning::
+ A drop whose larger size ``n`` is at least ``2`` paints ``n`` pixels spread over ``n + 1`` rows or
+ columns, so it has a one-pixel gap: ``drop_height=5`` with ``drop_width=0`` paints rows
+ ``[0, 1, 2, 3, 5]``. Tracked in `#4810 <https://github.com/kornia/kornia/issues/4810>`_.
Examples:
>>> rng = torch.manual_seed(0)
diff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
index 8d0e80517..bdfdf97df 100644
--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py
+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py
@@ -46,20 +46,17 @@ class RandomRGBShift(IntensityAugmentationBase2D):
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.
+ - each ``*_shift_limit`` is a non-negative half-width: that channel's shift is sampled from
+ ``[-limit, limit]``, so a limit of ``0`` adds nothing to the channel, though the clamp still applies. A
+ negative limit raises a ``ValueError`` 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>`_.
+ A tuple limit raises a raw ``TypeError`` at construction rather than being read as a range or rejected
+ by name. Tracked in `#4782 <https://github.com/kornia/kornia/issues/4782>`_.
- Note:
- Input torch.Tensor must be float and normalized into [0, 1].
+ .. 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. Tracked in `#4430 <https://github.com/kornia/kornia/issues/4430>`_.
Examples:
>>> import torch
diff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.py
index 5dd185e5f..7369ffa6c 100644
--- a/kornia/augmentation/_2d/intensity/random_snow.py
+++ b/kornia/augmentation/_2d/intensity/random_snow.py
@@ -48,26 +48,15 @@ class RandomSnow(IntensityAugmentationBase2D):
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. 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.
+ drawn ``snow_coefficient`` -- has its lightness scaled by ``brightness`` and clamped into ``[0, 1]``, so
+ it comes back white once its scaled lightness reaches ``1``. A pixel the snow misses goes through the
+ HLS round trip unclamped, except where the HLS saturation is undefined: a lightness of exactly ``1``
+ with a channel above ``1``, such as ``(1.5, 0.5, 0.5)``, comes back white.
.. 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
+ An input whose values are all negative comes back as an all-zero image, and any pixel whose lightness is
+ zero or negative, such as ``(2.0, -2.0, -2.0)``, comes back black. Tracked in
`#4430 <https://github.com/kornia/kornia/issues/4430>`_.
Examples:
diff --git a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
index bf8b961b7..ca5542491 100644
--- a/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
+++ b/kornia/augmentation/_2d/intensity/salt_pepper_noise.py
@@ -44,9 +44,7 @@ class RandomSaltAndPepperNoise(IntensityAugmentationBase2D):
- 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.
+ - ``amount`` is a per-*pixel* rewrite probability: a chosen pixel is rewritten in every channel.
- ``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``.
diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.py
index d41b54cf6..fd49acefa 100644
--- a/kornia/augmentation/_2d/intensity/saturation.py
+++ b/kornia/augmentation/_2d/intensity/saturation.py
@@ -28,7 +28,9 @@ from kornia.enhance.adjust import adjust_saturation
class RandomSaturation(IntensityAugmentationBase2D):
r"""Apply a random transformation to the saturation of a torch.Tensor image.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ The factor scales the HSV saturation. torchvision's and PIL's saturation blends the image with its
+ grayscale instead (``factor * input + (1 - factor) * gray``); :class:`ColorJitter`'s saturation step is
+ that formula.
.. image:: _static/img/RandomSaturation.png
@@ -47,16 +49,11 @@ class RandomSaturation(IntensityAugmentationBase2D):
Convention:
- the input must have three channels: the scaling is defined on the HSV saturation, 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 divides by the value channel plus a small epsilon,
- and in half precision and integer dtypes it 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.
+ - the drawn factor reaches :func:`kornia.enhance.adjust_saturation` unchanged, and ``1.0`` is the
+ identity, up to rounding, for a pixel with no negative channel.
+ - there is no final RGB clamp, but the HSV saturation is clamped into ``[0, 1]``: at a factor of
+ ``1.0`` a pixel above ``1`` with no negative channel comes back unchanged, while ``(-0.1, 0.5, 0.5)``
+ becomes ``(0.0, 0.5, 0.5)`` and an all-negative pixel becomes gray at its largest channel.
.. 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 5d49fdeb0..d6d9efeb7 100644
--- a/kornia/augmentation/_2d/intensity/sharpness.py
+++ b/kornia/augmentation/_2d/intensity/sharpness.py
@@ -52,10 +52,8 @@ class RandomSharpness(IntensityAugmentationBase2D):
- 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]`` with its lower end
- floored at the non-negative bound -- 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]``.
+ - a scalar argument is the upper bound of ``[0, x]``, so the default ``sharpness=0.5`` never reaches the
+ identity and only blurs.
.. warning::
An input whose values are all negative comes back as an all-zero image. Tracked in
diff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.py
index caad41105..a9b873874 100644
--- a/kornia/augmentation/_2d/intensity/solarize.py
+++ b/kornia/augmentation/_2d/intensity/solarize.py
@@ -54,21 +54,13 @@ class RandomSolarize(IntensityAugmentationBase2D):
- 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, and
- :func:`kornia.enhance.solarize` accepts the same closed interval, so a range that reaches an endpoint,
- or draws one exactly, is applied rather than rejected. Because the two intervals are now the same,
- the function's own forward check cannot fire for this class; it still applies to a direct
- :func:`kornia.enhance.solarize` call, on the device its own ``.. note::`` describes.
+ - an explicit ``additions`` range is checked against the closed ``[-0.5, 0.5]`` at construction, so a
+ range that reaches an endpoint is applied rather than rejected.
.. 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
+ An all-negative input comes back as an all-zero image unless the drawn addition lifts it above zero or
+ the drawn threshold is ``0``, and an input whose values are all at least ``1.5`` comes back as an
+ all-zero image on every draw. Tracked in
`#4430 <https://github.com/kornia/kornia/issues/4430>`_.
.. note::
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 2f6514b26..631ce9fd6 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -1252,7 +1252,7 @@ class AdjustSaturation(nn.Module):
class AdjustSaturationWithGraySubtraction(nn.Module):
r"""Adjust color saturation of an image.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ It blends the image with its grayscale, ``factor * image + (1 - factor) * gray``, as torchvision and PIL do.
The input image is expected to be in the range of [0, 1].
The input image is expected to be an RGB or gray image in the range of [0, 1].
@@ -1313,7 +1313,7 @@ class AdjustSaturationWithGraySubtraction(nn.Module):
class AdjustHue(nn.Module):
r"""Adjust hue of an image.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ ``factor`` is in radians: it matches torchvision's ``adjust_hue`` with ``hue_factor = factor / (2 * pi)``.
The input image is expected to be in the range of [0, 1].
The input image is expected to be an RGB image in the range of [0, 1].
@@ -1467,7 +1467,9 @@ class AdjustContrast(nn.Module):
class AdjustContrastWithMeanSubtraction(nn.Module):
r"""Adjust Contrast of an image.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ For an RGB image it blends the image with its grayscale mean, ``factor * image + (1 - factor) * mean``, as
+ torchvision and PIL do. Any other channel count takes the mean over the whole batch rather than per image
+ (`#4806 <https://github.com/kornia/kornia/issues/4806>`_).
The input image is expected to be in the range of [0, 1].
Args:
@@ -1645,7 +1647,7 @@ class AdjustLog(nn.Module):
class AdjustBrightnessAccumulative(nn.Module):
r"""Adjust Brightness of an image accumulatively.
- This implementation aligns PIL. Hence, the output is close to TorchVision.
+ It multiplies the image by ``factor``, as torchvision's and PIL's brightness does.
The input image is expected to be in the range of [0, 1].
Args:
diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.py
index 6c095331e..0ecbcd9f5 100644
--- a/tests/augmentation/test_conventions_intensity_ops.py
+++ b/tests/augmentation/test_conventions_intensity_ops.py
@@ -18,6 +18,7 @@
from __future__ import annotations
import copy
+import inspect
import io
import itertools
import pickle
@@ -30,7 +31,6 @@ 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
-from kornia.filters.kernels import gaussian
from testing.base import (
DYNAMO_UNAVAILABLE_REASON,
@@ -43,14 +43,11 @@ from testing.base import (
@pytest.fixture(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.
+ # The pins below seed the global RNG; the root fixture (#4446) restores every generator afterwards.
yield
-# The seed drawn immediately before each construct-and-forward, as the audit probe did it.
+# The seed drawn immediately before each construct-and-forward.
_FORWARD_SEED = 0
_FIXTURE_SEED = 1234
@@ -76,19 +73,11 @@ def _impulse(device, dtype, height: int = 7, width: int = 9, row: int = 2, col:
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.
+ # ``kernel_size`` is ``(kH, kW)``, also checked under relabelling (transposed image and kernel).
# 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].
+ # torch.manual_seed(0); y = K.RandomBoxBlur(ks, p=1.0)(x); print(ks, (y[0, 0] > 0).nonzero().T.tolist())
@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):
@@ -99,7 +88,7 @@ class TestBlurConventions(BaseTester):
}
make = factories[name]
- # The audit's own fixture, hot pixel on the 7x9 centre.
+ # 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])
@@ -121,24 +110,12 @@ class TestBlurConventions(BaseTester):
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)
@@ -156,8 +133,6 @@ class TestBlurConventions(BaseTester):
# 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)
@@ -173,6 +148,13 @@ class TestBlurConventions(BaseTester):
assert lit[:, 0].unique().tolist() == rows and lit[:, 1].unique().tolist() == cols
self.assert_close(out.sum(), impulse.sum())
+ # 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.
+ # 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())
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
@@ -193,31 +175,25 @@ class TestBlurConventions(BaseTester):
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).
+
+ # Wart (#4781, https://github.com/kornia/kornia/issues/4781): an even entry is constructed and then fails on
+ # every image size with a raw torch error, not a kornia one. Rejecting it with a kornia error or
+ # supporting it flips this pin.
+ @pytest.mark.parametrize("shape", [(2, 3, 32, 32), (2, 3, 1, 1)])
+ def test_wart_random_median_blur_even_kernel_raises_a_raw_torch_error_4781(self, device, dtype, shape):
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(*shape).to(device=device, dtype=dtype)
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.
+ with pytest.raises(RuntimeError) as raised:
+ _sync(even(image).device)
+ assert type(raised.value) is RuntimeError
+
+ # ``normalized`` is forwarded as box_blur's ``separable``; both branches are means and agree to 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.
+ # print(torch.equal(yt, box_blur(x, (3, 3), "reflect", separable=True)))
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")
@@ -238,15 +214,10 @@ class TestBlurConventions(BaseTester):
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``).
+ # One scalar sigma per sample (a (B,) tensor), and the defaults are gaussian_blur2d's own.
# 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>}`.
+ # torch.manual_seed(0); aug(torch.rand(4, 3, 7, 9)); print(aug._params["sigma"].shape, aug.flags)
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")
@@ -273,43 +244,27 @@ class TestBlurConventions(BaseTester):
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.
+ # An even kernel_size is rejected with gaussian_blur2d's own "odd integer" error, whatever the image
+ # size: a 2x2 image is below the reflect minimum, so a size check that ran first would blame the image.
# 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(0); K.RandomGaussianBlur((4, 4), (0.1, 1.0), p=1.0)(torch.rand(1, 1, 2, 2))
+ @pytest.mark.parametrize(
+ ("kernel_size", "shape"), [((2, 2), (4, 3, 7, 9)), ((4, 4), (1, 1, 2, 2)), ((3, 4), (1, 1, 2, 2))]
+ )
+ def test_convention_random_gaussian_blur_rejects_even_kernel_size(self, device, dtype, kernel_size, shape):
torch.manual_seed(_FIXTURE_SEED)
- image = torch.rand(4, 3, 7, 9).to(device=device, dtype=dtype)
+ image = torch.rand(*shape).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-21b: the even-kernel error does not depend on the image size. 2x2 is below the reflect
- # minimum a 4-extent kernel needs, so a size check that ran first would blame the image instead.
- # Snippet used to generate expected:
- # K.RandomGaussianBlur((4, 4), (0.1, 1.0), p=1.0)(torch.rand(1, 1, 2, 2)) (and a 3x4 kernel)
- # executed 2026-09-22 (torch 2.5.0, cpu) -> `Kernel size must be an odd integer bigger than 0.
- # Gotcha 4 on (4, 4)` and `... Gotcha 4 on (3, 4)`.
- @pytest.mark.parametrize("kernel_size", [(4, 4), (3, 4)])
- def test_convention_random_gaussian_blur_even_kernel_error_is_size_independent(self, device, dtype, kernel_size):
- image = torch.rand(1, 1, 2, 2).to(device=device, dtype=dtype)
- with pytest.raises(Exception, match=r"odd integer bigger than 0\. Gotcha 4"):
+ with pytest.raises(BaseError, match="odd integer"):
_sync(K.RandomGaussianBlur(kernel_size, (0.1, 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.
+ # ``angle`` is counter-clockwise as displayed; the impulse sits off both centre lines, so no literal
+ # is its own transpose.
# 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"),
[
@@ -326,17 +281,12 @@ class TestBlurConventions(BaseTester):
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.
+ # ``direction`` re-weights the kernel along its own axis (-1 start, +1 end, 0 uniform), on two angles.
# 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"),
[
@@ -356,16 +306,13 @@ class TestBlurConventions(BaseTester):
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.
+ # The weighted line is rotated with ``resample``; a "nearest" rotation at 45 degrees keeps three of the
+ # five taps. The impulse response is the kernel, so these are its taps.
# 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 = {}
@@ -376,33 +323,19 @@ class TestBlurConventions(BaseTester):
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>}`.
+ # The class keeps kornia.filters.motion_blur's defaults.
@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: the half-size is drawn on `[lo, hi + 1)` and floored, so every odd size in the requested
- # range is drawn, bounds included, in near-equal shares; the draw used to truncate a float on `[lo, hi)`,
- # which made `(3, 5)` a constant 3. This is the same remedy RandomRain took for #4567. An even upper
- # bound caps at the largest odd size below it, and a range holding no odd size still rounds up (`(4, 4)`
- # draws 5). The kernel size is shared within each batch (#4671), so the pin samples independent calls.
+ # Every odd size in a tuple range is drawn in near-equal shares, bounds included (#4599); an even upper
+ # bound caps at the odd size below it, and a range holding no odd size rounds up (``(4, 4)`` draws 5).
+ # The size is shared within a batch (#4671), so independent calls are sampled.
# Snippet used to generate expected:
- # import collections
- # for ks in ((3, 5), (3, 7), (5, 11), (3, 20), (4, 7), (4, 4)):
- # torch.manual_seed(0)
- # aug = K.RandomMotionBlur(ks, (0., 0.), (0., 0.), p=1.)
- # v = torch.cat([aug.forward_parameters((1, 1, 8, 8))["ksize_factor"] for _ in range(20000)])
- # print(ks, dict(sorted(collections.Counter(v.tolist()).items())))
- # executed 2026-09-21 (torch 2.14.0, cpu) -> `{3: 9984, 5: 10016}`, `{3: 6656, 5: 6675, 7: 6669}`,
- # `{5: 4975, 7: 5009, 9: 5025, 11: 4991}`, `{3: 2189, ..., 19: 2224}` (nine sizes), `{5: 9984, 7: 10016}`,
- # `{5: 20000}`.
+ # torch.manual_seed(0); aug = K.RandomMotionBlur(ks, (0., 0.), (0., 0.), p=1.)
+ # v = torch.cat([aug.forward_parameters((1, 1, 8, 8))["ksize_factor"] for _ in range(20000)])
@pytest.mark.device_agnostic
@pytest.mark.parametrize(
("kernel_size", "drawn"),
@@ -421,8 +354,7 @@ class TestBlurConventions(BaseTester):
factors = torch.cat([aug.forward_parameters((1, 1, 8, 8))["ksize_factor"] for _ in range(20000)])
counts = torch.stack([(factors == k).sum() for k in drawn])
assert sorted(set(factors.tolist())) == drawn
- # Near-equal shares: each size within 10% of 20000 / len(drawn), where the old truncation left the
- # upper bound at a rounding handful.
+ # Near-equal shares: each size within 10% of 20000 / len(drawn).
expected = 20000 / len(drawn)
assert bool(((counts - expected).abs() < 0.1 * expected).all()), counts.tolist()
@@ -442,17 +374,12 @@ class TestBlurConventions(BaseTester):
drawn.update(widths.tolist())
assert len(drawn) > 1
- # 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.
+ # At ``border_type="reflect"`` a "nearest" or "bilinear" kernel rotation stays inside the input's
+ # extremes; "bicubic" gives the kernel negative lobes that overshoot both 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`.
+ # torch.manual_seed(0)
+ # print(K.RandomMotionBlur(5, (80., 80.), (1., 1.), border_type="reflect", resample="bicubic", p=1.)(x).aminmax())
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")
@@ -466,10 +393,8 @@ class TestBlurConventions(BaseTester):
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.
+ # The four filters do not clamp: a 1.1 impulse is attenuated below one, and the output is linear in the
+ # input (for the median blur, a negative plateau stays negative), so no wrapper clamp is hiding in there.
@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):
@@ -490,9 +415,7 @@ class TestBlurConventions(BaseTester):
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.
+ # 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]"
@@ -502,28 +425,17 @@ class TestBlurConventions(BaseTester):
self.assert_close(out, make()(half_impulse) * 2.0)
self.assert_close(make()(-half_impulse), -make()(half_impulse))
- # Issue #4559, fixed: RandomBoxBlur, RandomGaussianBlur and RandomSharpness now raise a kornia
- # `ValueError` naming the class, the kernel and the input shape, where they used to let a raw torch
- # padding error out. The thresholds are unchanged, and they are what the message states: the two
- # blurs reflect-pad, so an axis must be 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 made the
- # split a defect rather than a package-wide rule, and they are unchanged.
+ # Issue #4559: RandomBoxBlur, RandomGaussianBlur and RandomSharpness raise a kornia `ValueError` naming
+ # the class, the kernel and the input shape. The two blurs reflect-pad, so an axis must be 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, at its default constant border, RandomMotionBlur accept
+ # the same degenerate image.
# 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-18 (torch 2.5.0, cpu) -> on (2, 3, 1, 8) the two blurs raise `ValueError:
- # RandomBoxBlur cannot filter an image this small: kernel_size=(3, 3) with border_type='reflect'
- # needs at least 2 pixel(s) along height, but the input is (2, 3, 1, 8)` and RandomSharpness the
- # same shape of message with `border_type='valid'` and 3 pixels; 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_convention_blur_and_sharpness_name_the_size_they_need_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.
+ # Only the legs that reflect-pad are skipped where reflection_pad2d is unavailable.
reflect_ok = supports_reflect_padding(device, dtype)
torch.manual_seed(_FIXTURE_SEED)
thin = torch.rand(2, 3, 1, 8).to(device=device, dtype=dtype)
@@ -543,8 +455,7 @@ class TestBlurConventions(BaseTester):
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).
+ # 2-column image (2 > 3 // 2) and raises on a 3-row one (3 <= 7 // 2), in both classes.
rectangular = {
"RandomBoxBlur": lambda: K.RandomBoxBlur((7, 3), p=1.0),
"RandomGaussianBlur": lambda: K.RandomGaussianBlur((7, 3), (1.0, 1.0), p=1.0),
@@ -573,40 +484,17 @@ class TestBlurConventions(BaseTester):
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
- # still torch's for RandomMotionBlur, which #4559 leaves alone, while the two padding blurs now
- # raise kornia's own error before reaching the pad -- at the same threshold, the radius.
+ # ``border_type="circular"`` needs each axis at least the kernel radius (``k // 2``): the two padding
+ # blurs raise kornia's named error below it, while ``"constant"`` and ``"replicate"`` run there.
# 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(1234); thin = torch.rand(2, 3, 3, 12)
+ # for bt in ("constant", "replicate", "circular"):
# 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_convention_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),
@@ -619,18 +507,39 @@ class TestBlurConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
assert make(border)(thin).shape == thin.shape, f"{name} at {border} should accept a 3-row image"
- # Issue #4559, the case the first cut of the guard missed: RandomBoxBlur accepts EVEN kernel
- # sizes, and `filter2d` pads those asymmetrically -- `(k - 1) // 2` in front, `k // 2` behind.
- # Stating the minima against the radius `(k - 1) // 2` therefore under-reports by one pixel for
- # every even extent, and those inputs walked straight past the guard into the raw torch errors
- # it exists to replace. The constraint is the wider pad, `k // 2`.
+ # Wart (#4784, https://github.com/kornia/kornia/issues/4784): RandomMotionBlur has the same minimum
+ # size under ``"reflect"`` and ``"circular"`` but lets torch's raw padding error out, where RandomBoxBlur
+ # raises a named ValueError. A kornia check flips this pin; the controls below it do not move.
+ @pytest.mark.parametrize(
+ ("border", "kernel_size", "shape"), [("reflect", 3, (2, 3, 1, 8)), ("circular", 5, (2, 3, 1, 1))]
+ )
+ def test_wart_random_motion_blur_small_image_raises_a_raw_padding_error_4784(
+ self, device, dtype, border, kernel_size, shape
+ ):
+ if border == "reflect" and not supports_reflect_padding(device, dtype):
+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")
+ torch.manual_seed(_FIXTURE_SEED)
+ image = torch.rand(*shape).to(device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ aug = K.RandomMotionBlur(kernel_size, (45.0, 45.0), (0.0, 0.0), border_type=border, p=1.0)
+ with pytest.raises(RuntimeError) as raised:
+ _sync(aug(image).device)
+ assert type(raised.value) is RuntimeError
+ # The default constant border runs on the same image, and one radius less runs under circular.
+ torch.manual_seed(_FORWARD_SEED)
+ assert K.RandomMotionBlur(kernel_size, (45.0, 45.0), (0.0, 0.0), p=1.0)(image).shape == image.shape
+ if border == "circular":
+ torch.manual_seed(_FORWARD_SEED)
+ smaller = K.RandomMotionBlur(3, (45.0, 45.0), (0.0, 0.0), border_type=border, p=1.0)
+ assert smaller(image).shape == image.shape
+
+ # An even extent ``k`` is padded asymmetrically, so the minimum size follows the wider pad ``k // 2``:
+ # reflect needs ``k // 2 + 1`` pixels and circular ``k // 2``.
# Snippet used to generate expected:
# for k in range(1, 9):
# front, rear = (k - 1) // 2, k - 1 - (k - 1) // 2
# for mode in ("reflect", "circular"):
# min(s for s in range(1, 12) if F.pad(torch.rand(1, 1, s, s), [front, rear] * 2, mode=mode))
- # executed 2026-09-19 (torch 2.5.0, cpu) -> reflect needs `k // 2 + 1` and circular `k // 2` for
- # every k in 1..8, i.e. 3 and 2 for a 4-wide kernel where the radius said 2 and 1.
@pytest.mark.parametrize(
"kernel, border, too_small, big_enough",
[
@@ -666,14 +575,11 @@ class TestBlurConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
assert K.RandomBoxBlur(kernel, border_type=invented, p=1.0)(small).shape == small.shape
- # 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.
+ # Zero padding pulls a border pixel toward 0: below the minimum of a positive image, above the maximum
+ # of a negative one.
# 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 = {
@@ -692,30 +598,22 @@ class TestBlurConventions(BaseTester):
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.
+ # Toward zero and not another constant ``v``: ``out(+1) + out(-1) = 2 * (1 - s) * v`` vanishes only at 0.
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 `<=`.
+# Twice float32(0.9): the snow coefficient is drawn in float32, so this red channel's HLS lightness equals
+# the drawn coefficient exactly in every dtype, which is what tells the coverage test's `<` 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.
+ # ``scale`` is the target area fraction, ``ratio`` is height / width, the box is the half-open
+ # ``[ys, ys + h) x [xs, xs + w)`` in ``_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
@@ -736,14 +634,11 @@ class TestNoiseAndWeatherConventions(BaseTester):
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
+ # The target box for scale 0.25 and ratio 3 on 10x20 is about 12.2 x 4.1: rounded to 12 x 4, 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.
+ # torch.manual_seed(0); 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"])
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)
@@ -752,16 +647,12 @@ class TestNoiseAndWeatherConventions(BaseTester):
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``.
+ # A ``mask`` data key is erased in the same box, but filled with 0 rather than 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)
@@ -778,16 +669,8 @@ class TestNoiseAndWeatherConventions(BaseTester):
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]`.
+ # The noise is added unclamped and recorded in full under ``_params["gaussian_noise"]``; ``mean`` is
+ # an offset, not a target.
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)
@@ -801,9 +684,7 @@ class TestNoiseAndWeatherConventions(BaseTester):
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.
+ # Parameter fields use the batched BCHW shape even when ``keepdim`` restores a CHW output.
@pytest.mark.parametrize(
"name",
[
@@ -827,9 +708,8 @@ class TestNoiseAndWeatherConventions(BaseTester):
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.
+ # At a partial probability the stored field keeps the full batch length; unselected rows pass through
+ # and the parameter state replays exactly.
@pytest.mark.parametrize(
"name",
[
@@ -845,9 +725,7 @@ class TestNoiseAndWeatherConventions(BaseTester):
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.
+ # B=16 makes an all-or-nothing gate at p=0.5 unlikely (2 * 2 ** -16).
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)
@@ -869,23 +747,9 @@ class TestNoiseAndWeatherConventions(BaseTester):
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.
+ # ``amount`` is a per-pixel fraction (the rewrite mask is the same in every channel) and
+ # ``salt_vs_pepper`` the salt share of the rewritten pixels; both are asserted within five binomial
+ # standard deviations.
@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)
@@ -903,15 +767,10 @@ class TestNoiseAndWeatherConventions(BaseTester):
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.
+ # The poles are the literals 1.0 and 0.0 whatever the input's range.
# 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.
+ # torch.manual_seed(0)
+ # K.RandomSaltAndPepperNoise(amount=(0.3, 0.3), salt_vs_pepper=(1.0, 1.0), p=1.0)(torch.full((2, 3, 12, 20), 2.0))
@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
@@ -927,31 +786,10 @@ class TestNoiseAndWeatherConventions(BaseTester):
# 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.
+ # ``drop_height`` runs down rows and ``drop_width`` along columns, also on the transposed image.
# 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.
+ # torch.manual_seed(0); aug = K.RandomRain(number_of_drops=(1, 1), drop_height=(6, 6), drop_width=(1, 1), p=1.0)
+ # print((aug(torch.zeros(1, 1, 12, 30))[0, 0] > 0).nonzero().tolist())
@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]:
@@ -970,22 +808,14 @@ class TestNoiseAndWeatherConventions(BaseTester):
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.
+ # On a 30x12 image the arguments still mean rows and columns.
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...).
+ # A drop is the literal 200/255, not a function of the image.
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)
@@ -993,21 +823,8 @@ class TestNoiseAndWeatherConventions(BaseTester):
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.`
+ # A drop as tall or as wide as the image is rejected with kornia's error on the forward pass (the
+ # image size is only known there), and one pixel smaller runs.
@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
@@ -1021,7 +838,7 @@ class TestNoiseAndWeatherConventions(BaseTester):
p=1.0,
)
torch.manual_seed(_FORWARD_SEED)
- with pytest.raises(Exception, match=message):
+ with pytest.raises(BaseError, 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)
@@ -1034,53 +851,37 @@ class TestNoiseAndWeatherConventions(BaseTester):
)
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.
+ # Issue #4810: a drop of size n >= 2 paints n pixels over n + 1 rows, skipping one. A fix that paints a
+ # contiguous drop flips it.
# 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):
+ # torch.manual_seed(0)
+ # y = K.RandomRain(number_of_drops=(1, 1), drop_height=(h, h), drop_width=(0, 0), p=1.0)(torch.zeros(1, 1, 6, 10))
+ # print(sorted({r for r, _ in (y[0, 0] != 0).nonzero().tolist()}))
+ @pytest.mark.parametrize(("height", "rows"), [(2, [0, 2]), (5, [0, 1, 2, 3, 5])])
+ def test_wart_random_rain_drop_skips_a_row_4810(self, device, dtype, height, rows):
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
+ out = K.RandomRain(number_of_drops=(1, 1), drop_height=(height, height), drop_width=(0, 0), p=1.0)(image)
+ lit = (out[0, 0] != 0).nonzero()
+ assert (lit[:, 0] - lit[:, 0].min()).tolist() == rows
- # The three integer ranges are closed and uniform (the fix for #4567: the sampler covers
- # ``[lo, hi + 1)``, the draw is floored and then clamped to ``hi``, where a truncating cast of a
- # ``[lo, hi)`` draw used to skip the upper bound and fold ``(-1, 0)`` and ``(0, 1)`` onto ``0``).
+ # The three integer ranges are closed and uniform (#4567), including signed widths that straddle or
+ # end at zero. The 15% band is wide for the 16-bin height at 22000 draws; what it has to separate is
+ # a factor of two (a truncating draw gives ``0`` twice its share).
# 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((22000, 1, 64, 64))
- # for k in ("number_of_drops_factor", "drop_height_factor", "drop_width_factor"):
- # print(k, sorted(collections.Counter(p[k].flatten().tolist()).items()))
- # executed 2026-09-16 (torch 2.14.0, cpu) -> drops 2..4 (7298, 7349, 7353), heights 5..20 (1301 to
- # 1455) and widths -5..5 (1906 to 2090), every count within 6% of the uniform expectation (7333,
- # 1375 and 2000). The pin allows 15%, not 10%: the 16-bin height is the tight one, where 22000
- # draws put 10% at 3.8 sigma and 1 of seeds 0..99 exceeds it (max deviation 10.7%), against 5.7
- # sigma and 0 of 100 at 15%. What the tolerance has to separate is a factor of two, not a few
- # percent -- truncation gave `0` twice its share -- so the wider band loses no mutation.
+ # print(torch.bincount(p.forward_parameters((22000, 1, 64, 64))["drop_width_factor"] + 5))
@pytest.mark.device_agnostic
- def test_convention_random_rain_integer_ranges_are_closed_and_uniform(self):
+ @pytest.mark.parametrize("drop_width", [(-5, 5), (-1, 1), (-5, -1), (-3, 0)])
+ def test_convention_random_rain_integer_ranges_are_closed_and_uniform(self, drop_width):
torch.manual_seed(_FORWARD_SEED)
- aug = K.RandomRain(number_of_drops=(2, 4), drop_height=(5, 20), drop_width=(-5, 5), p=1.0)
+ aug = K.RandomRain(number_of_drops=(2, 4), drop_height=(5, 20), drop_width=drop_width, p=1.0)
params = aug.forward_parameters((22000, 1, 64, 64))
for key, low, high in (
("number_of_drops_factor", 2, 4),
("drop_height_factor", 5, 20),
- ("drop_width_factor", -5, 5),
+ ("drop_width_factor", *drop_width),
):
drawn = params[key].flatten()
assert drawn.dtype == torch.long
@@ -1089,13 +890,8 @@ class TestNoiseAndWeatherConventions(BaseTester):
expected = drawn.numel() / (high - low + 1)
assert bool(((counts > 0.85 * expected) & (counts < 1.15 * expected)).all()), (key, counts.tolist())
- # The excluded end point of the half-open sampler range is clamped back, not drawn: for the largest
- # value `torch.rand` can return, `lo + u * (hi + 1 - lo)` rounds up onto `hi + 1` in float32
- # (`5 + (1 - 2 ** -24) * 16` is exactly `21.0`), which `floor` would keep -- about one draw in 2**24,
- # and a `drop_height` of 21 makes the forward raise on a 21-row image where 20 is legal.
- # Snippet used to generate expected: the same three ranges, with `torch.rand` patched to return
- # `1 - 2 ** -24` everywhere.
- # executed 2026-09-16 (torch 2.14.0, cpu) -> `[4, 20, 5]` with the clamp, `[5, 21, 5]` without it.
+ # The largest ``torch.rand`` value maps onto ``hi + 1`` in float32 (``5 + (1 - 2 ** -24) * 16 == 21.0``);
+ # kornia clamps it back to ``hi``.
@pytest.mark.device_agnostic
def test_convention_random_rain_largest_draw_stays_inside_the_closed_range(self, monkeypatch):
largest = 1 - 2**-24
@@ -1103,62 +899,44 @@ class TestNoiseAndWeatherConventions(BaseTester):
monkeypatch.setattr(torch, "rand", lambda *args, **kwargs: torch.full_like(real_rand(*args, **kwargs), largest))
aug = K.RandomRain(number_of_drops=(2, 4), drop_height=(5, 20), drop_width=(-5, 5), p=1.0)
params = aug.forward_parameters((4, 1, 64, 64))
- # The patch has to reach the generator's own draws, or the pin below is vacuous: the coordinate
- # sampler runs over [0, 1], so under the patch every coordinate is exactly the patched value.
+ # The patch has to reach the generator's own draws, or the pin below is vacuous.
assert float(params["coordinates_factor"].min()) == largest
assert params["number_of_drops_factor"].tolist() == [4, 4, 4, 4]
assert params["drop_height_factor"].tolist() == [20, 20, 20, 20]
assert params["drop_width_factor"].tolist() == [5, 5, 5, 5]
- # A reversed range is rejected at construction, where the samplers are built -- on each of the three
- # parameters, not only the one a single example would name.
- @pytest.mark.device_agnostic
- @pytest.mark.parametrize("name", ["number_of_drops", "drop_height", "drop_width"])
- def test_convention_random_rain_rejects_a_reversed_range(self, name):
- ranges = {"number_of_drops": (1, 1), "drop_height": (1, 1), "drop_width": (1, 1)}
- ranges[name] = (6, 5)
- with pytest.raises(ValueError, match=name):
- K.RandomRain(p=1.0, **ranges)
-
- # The ranges are integer ranges, so a bound that is not a whole number is rejected at construction
- # too -- including `nan` and `inf`, which an ordering test alone does not catch (they are neither
- # greater nor smaller than the other bound, so `drop_height=(nan, 5)` used to reach the sampler and
- # draw a silent `0`), and a fractional pair, which the clamp draws more unevenly than the truncation
- # it replaces: `(0.5, 2.5)` gave `{0: 25%, 1: 50%, 2: 25%}` and would give `{0: 17%, 1: 33%, 2: 50%}`.
+ # Each integer range is validated at construction: reversed, fractional, non-finite or not a pair is
+ # a ValueError naming the argument.
@pytest.mark.device_agnostic
- @pytest.mark.parametrize("bounds", [(0.5, 2.5), (1, 2.5), (float("nan"), 5), (5, float("nan")), (1, float("inf"))])
+ @pytest.mark.parametrize(
+ "bounds",
+ [(6, 5), (0.5, 2.5), (1, 2.5), (float("nan"), 5), (5, float("nan")), (1, float("inf")), (1, 2, 3), (1,), 5],
+ )
@pytest.mark.parametrize("name", ["number_of_drops", "drop_height", "drop_width"])
- def test_convention_random_rain_rejects_a_fractional_or_non_finite_range(self, name, bounds):
+ def test_convention_random_rain_rejects_an_invalid_range(self, name, bounds):
ranges = {"number_of_drops": (1, 1), "drop_height": (1, 1), "drop_width": (1, 1)}
ranges[name] = bounds
with pytest.raises(ValueError, match=name):
K.RandomRain(p=1.0, **ranges)
- # Integral floats are the same range written another way, and stay accepted.
- ranges[name] = (1.0, 2.0)
- K.RandomRain(p=1.0, **ranges)
- # The pair itself is validated: a range that is not two values, whatever its length, is rejected
- # rather than silently indexed, and a tensor range is accepted as the old `_range_bound` accepted it.
+ # Integral floats and a tensor pair are the same closed range written another way.
@pytest.mark.device_agnostic
- def test_convention_random_rain_validates_the_range_pair(self):
- for bad in ((1, 2, 3), (1,), 5):
- with pytest.raises(ValueError, match="drop_height"):
- K.RandomRain(p=1.0, drop_height=bad)
+ def test_convention_random_rain_accepts_integral_float_and_tensor_ranges(self):
+ for name in ("number_of_drops", "drop_height", "drop_width"):
+ ranges = {"number_of_drops": (1, 1), "drop_height": (1, 1), "drop_width": (1, 1)}
+ ranges[name] = (1.0, 2.0)
+ K.RandomRain(p=1.0, **ranges)
torch.manual_seed(_FORWARD_SEED)
aug = K.RandomRain(p=1.0, number_of_drops=(1, 1), drop_height=torch.tensor([2, 4]), drop_width=(1, 1))
drawn = aug.forward_parameters((2000, 1, 64, 64))["drop_height_factor"]
assert sorted(set(drawn.flatten().tolist())) == [2, 3, 4]
- # Issue #4604: a drop starts anywhere that keeps it inside the image, so every row and column is painted,
- # for a single pixel and for drops slanting either way. Literal seeds, as for the other census pins: the
- # claim is over the union of 300 draws, not one. Before the fix the single-pixel case painted rows
- # `[0, 1, 2, 3]` and cols `[0, ..., 8]` on `6 x 10`.
+ # A drop starts anywhere that keeps it inside the image, so over many draws every row and column is
+ # painted, for a single pixel and for drops slanting either way (#4604).
@pytest.mark.parametrize("drop_height, drop_width", [(1, 0), (2, 2), (2, -2)])
def test_convention_random_rain_paints_every_row_and_column_4604(self, device, dtype, drop_height, drop_width):
image = torch.zeros(1, 3, 6, 10, device=device, dtype=dtype)
- # `.to` so the coordinate sampler runs in the test's dtype: left at construction defaults it stays
- # float32 even for a float16 image, and the MPS half `rand` that returns exactly 1.0 (#4553) -- the
- # draw the clamp exists for -- is never reached.
+ # `.to` so the coordinate sampler runs in the test's dtype, where a half `rand` can return 1.0 (#4553).
aug = K.RandomRain(
number_of_drops=(20, 20), drop_height=(drop_height, drop_height), drop_width=(drop_width, drop_width), p=1.0
).to(device=device, dtype=dtype)
@@ -1170,21 +948,8 @@ class TestNoiseAndWeatherConventions(BaseTester):
cols |= set(lit[:, 1].tolist())
assert sorted(rows) == list(range(6)) and sorted(cols) == list(range(10))
- # Issue #4604, the painted extent: a single drop paints a bounding box of exactly ``(h, |w|)`` -- the
- # linspace includes both end points once it has two steps, and is the start alone when it has one -- and
- # that box lands inside the image for every legal start. The union pin above cannot see this: it only
- # records which rows and columns are hit somewhere across 300 draws, so a drop split across opposite
- # edges by a negative-index wrap still covers ``range(10)`` and passes. Swept rather than pinned to
- # literals, because the claim is a bound over the whole legal domain, not a census of one shape.
- # Snippet used to generate expected:
- # for H, W in itertools.product(range(2, 8), repeat=2):
- # for h in range(1, H):
- # for w in range(-(W - 1), W):
- # for seed in range(2):
- # ... print(box, expected, in_bounds)
- # executed 2026-09-18 (torch 2.14.0, cpu) -> 0 violations. With ``+ max(-last_dx, 0)`` deleted, seed 1
- # of ``6 x 10, h=2, w=-2`` starts a drop at ``(2, 0)`` and paints ``(2, 0)`` and ``(4, -2)``, the latter
- # wrapping round to ``(4, 8)``: a box of ``(2, 8)`` against the expected ``(2, 2)``.
+ # A single drop paints a bounding box of exactly ``(h, |w|)`` inside the image for every legal start
+ # (#4604); a drop wrapped across opposite edges by a negative index would still satisfy the union pin.
@pytest.mark.device_agnostic
def test_convention_random_rain_single_drop_box_is_its_size_4604(self):
for height, width in itertools.product(range(2, 8), repeat=2):
@@ -1207,19 +972,12 @@ class TestNoiseAndWeatherConventions(BaseTester):
assert min(rows) >= 0 and max(rows) < height, case
assert min(cols) >= 0 and max(cols) < width, case
- # Issue #4604, the uniformity half of the bullet: every legal start is equally likely, not merely
- # reachable. The union pin is blind to the distribution -- folding the row overflow onto the last row
- # keeps the union at ``range(6)`` while badly skewing where drops land -- so this counts start rows the
- # way the #4567 pin above counts drawn sizes, with the same 15% band and for the same reason. Single
- # pixel drops on a wide image, so each painted cell is one start and collisions are rare (100 drops over
- # 12000 cells, about 0.4 an image), read off the output rather than recomputed from the parameters.
+ # Every legal start row is equally likely, not merely reachable (#4604); single-pixel drops on a wide
+ # image, so each painted cell is one start.
# Snippet used to generate expected:
# torch.manual_seed(0)
# aug = K.RandomRain(number_of_drops=(100, 100), drop_height=(1, 1), drop_width=(0, 0), p=1.0)
- # out = aug(torch.zeros(200, 1, 6, 2000))
- # print(torch.bincount((out[:, 0] != 0).nonzero()[:, 1], minlength=6).tolist())
- # executed 2026-09-18 (torch 2.14.0, cpu) -> every bin within 1% of the uniform expectation. Scaling
- # the row draw by ``cols`` instead of ``rows`` puts every drop on the last row.
+ # print(torch.bincount((aug(torch.zeros(200, 1, 6, 2000))[:, 0] != 0).nonzero()[:, 1], minlength=6))
@pytest.mark.device_agnostic
def test_convention_random_rain_start_row_is_uniform_4604(self):
aug = K.RandomRain(number_of_drops=(100, 100), drop_height=(1, 1), drop_width=(0, 0), p=1.0)
@@ -1229,15 +987,8 @@ class TestNoiseAndWeatherConventions(BaseTester):
expected = int(counts.sum()) / 6
assert bool(((counts > 0.85 * expected) & (counts < 1.15 * expected)).all()), counts.tolist()
- # Issue #4604, the clamp on the start draw: the coordinate sampler runs over ``[0, 1]`` and the MPS half
- # ``rand`` really does return an exact ``1.0`` (#4553), which would put the start one past the last
- # admissible one and index out of the image. Reproduced here by patching the draw rather than left to
- # the MPS leg, so the pin fires on every device; same idiom as the closed-range pin above. Main was
- # safe against this only by accident, its multiplier being one smaller than the true count of starts.
- # Snippet used to generate expected: the config below with `torch.rand` patched to return `1.0`.
- # executed 2026-09-18 (torch 2.14.0, cpu) -> the drop paints `(3, 9)` and `(5, 7)`, the last row and the
- # last column. Clamping to `rows` instead of `rows - 1` raises `index 6 is out of bounds`, and `cols`
- # instead of `cols - 1` raises `index 10 is out of bounds`.
+ # A start draw of exactly 1.0 (possible for a half ``rand``, #4553) is clamped to the last legal start:
+ # the drop reaches the last row and the last column and stays inside (#4604).
@pytest.mark.device_agnostic
def test_convention_random_rain_start_draw_of_one_stays_inside_4604(self, monkeypatch):
real_rand = torch.rand
@@ -1248,21 +999,10 @@ class TestNoiseAndWeatherConventions(BaseTester):
lit = (aug(torch.zeros(1, 1, 6, 10))[0, 0] != 0).nonzero().tolist()
assert sorted(lit) == [[3, 9], [5, 7]]
- # 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-16 (torch 2.14.0, cpu) -> `True [25, 25, 25, 25]` and `False [25, 39, 5, 7]`.
+ # ``same_on_batch=True`` shares the drop count, the drop sizes and the coordinates; without it each
+ # sample draws its own.
def test_convention_random_rain_same_on_batch_draws_one_drop_count(self, device, dtype):
- # B is 16, not 4: `drop_height=(1, 3)` and `drop_width=(1, 3)` each draw from {1, 2, 3}, so
- # "the unshared draw differs across the batch" fails when one of the two factors comes out
- # constant, a `2 * 3 ** -(B - 1)` event -- 16 of seeds 0..199 coincide at B=4, 1 at B=8 and none
- # at B=16.
+ # B=16 makes an accidentally constant unshared draw over {1, 2, 3} unlikely.
batch_size = 16
image = torch.zeros(batch_size, 1, 12, 30, device=device, dtype=dtype)
drawn = {}
@@ -1278,9 +1018,6 @@ class TestNoiseAndWeatherConventions(BaseTester):
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
@@ -1288,32 +1025,15 @@ class TestNoiseAndWeatherConventions(BaseTester):
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)
+ # ``snow_coefficient`` is validated against [0, 1] at construction (the channel-count rule is in the
+ # precondition table below).
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("coefficient", [1.5, -0.5])
+ def test_convention_random_snow_rejects_a_coefficient_outside_unit_range(self, coefficient):
+ with pytest.raises(BaseError, 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.
+ # ``snow_coefficient`` and ``brightness`` are drawn per sample; ``same_on_batch=True`` shares both.
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)
@@ -1327,7 +1047,7 @@ class TestNoiseAndWeatherConventions(BaseTester):
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.
+ # Reach, not only containment.
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)
@@ -1336,30 +1056,14 @@ class TestNoiseAndWeatherConventions(BaseTester):
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. The guarded denominators make both endpoints finite in every supported dtype.
- # 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.
+ # Only a covered pixel (lightness below the coefficient) is scaled and clamped: covered (1.5, 0, 0)
+ # turns white, missed (2, 1.5, 1.5) keeps its values, covered (1.2, -2, -2) turns black. The two
+ # singular lightnesses collapse whether covered or not: exactly 1 comes back white, exactly 0 black.
+ # The last pixel's lightness equals the coefficient, so coverage is strict ``<``.
# 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.9.1, cpu float32/float64/float16/bfloat16) -> 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 finite white and black in every supported dtype.
def test_convention_random_snow_clamps_only_covered_lightness(self, device, dtype):
pixels = torch.tensor(
[
@@ -1382,37 +1086,7 @@ class TestNoiseAndWeatherConventions(BaseTester):
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")
-
- 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
-
- # Every achromatic pixel -- black, gray or white -- stays finite through the HLS round trip.
- # Snippet used to generate expected:
- # for dt in (torch.float16, torch.bfloat16, torch.float32):
- # torch.manual_seed(0); y = K.RandomSnow(p=1.0)(torch.full((1, 3, 2, 2), 0.5, dtype=dt))
- # print(dt, torch.isfinite(y).all())
- # current CPU run -> True for float16, bfloat16 and float32, and the same for constants 0.0 and 1.0.
+ # Every achromatic pixel -- black, gray or white -- stays finite through the HLS round trip (#4571).
@pytest.mark.parametrize("value", [0.0, 0.5, 1.0])
def test_convention_random_snow_achromatic_pixel_is_finite_4571(self, device, dtype, value):
gray = torch.full((1, 3, 2, 2), value, device=device, dtype=dtype)
@@ -1422,17 +1096,10 @@ class TestNoiseAndWeatherConventions(BaseTester):
expected = gray.new_full(gray.shape, value)
self.assert_close(out, expected)
- # 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.
+ # The channel-count precondition, one table: "1 or 3" against "3 only". The type and kornia's own
+ # message are asserted, so an unrelated failure does not satisfy a row.
# 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"),
[
@@ -1449,9 +1116,7 @@ class TestNoiseAndWeatherConventions(BaseTester):
)
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.
+ # The 3-channel baseline call needs the codec's replication padding.
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),
@@ -1478,55 +1143,15 @@ class TestNoiseAndWeatherConventions(BaseTester):
with pytest.raises(error, match=match):
_sync(factories[name]()(image).device)
- # The degenerate signed range `(-1, 1)` is where the old truncation toward zero was total: it mapped
- # the whole interval onto `0`, except an exact `-1.0` draw (#4567). A closed uniform draw gives the
- # three values equal weight, and `0` stops carrying its neighbours' weight one step wider too.
- # Snippet used to generate expected:
- # for bounds in ((-1, 1), (-2, 2)):
- # g = RainGenerator(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=bounds)
- # torch.manual_seed(0)
- # print(bounds, sorted(Counter(g((20000, 3, 64, 64))["drop_width_factor"].flatten().tolist()).items()))
- # executed 2026-09-16 (torch 2.14.0, cpu) -> `{-1: 6688, 0: 6776, 1: 6536}` and, for `(-2, 2)`,
- # `{-2: 3941, -1: 4083, 0: 4075, 1: 3976, 2: 3925}`.
- @pytest.mark.device_agnostic
- def test_convention_random_rain_symmetric_signed_width_range_is_uniform(self):
- # `(-5, -1)` and `(-3, 0)` come from the wart pin this replaces: on a range that never crosses
- # zero, truncation toward zero drops the LOWER bound instead of the upper, so they are the cases
- # where `floor` and the old cast differ and a half-fixed draw would still show.
- for low, high in ((-1, 1), (-2, 2), (-5, -1), (-3, 0)):
- torch.manual_seed(_FORWARD_SEED)
- aug = K.RandomRain(number_of_drops=(5, 6), drop_height=(2, 3), drop_width=(low, high), p=1.0)
- drawn = aug.forward_parameters((20000, 1, 64, 64))["drop_width_factor"].flatten()
- assert sorted(set(drawn.tolist())) == list(range(low, high + 1))
- counts = torch.bincount(drawn - low, minlength=high - low + 1)
- expected = drawn.numel() / (high - low + 1)
- assert bool(((counts > 0.9 * expected) & (counts < 1.1 * expected)).all()), ((low, high), counts.tolist())
-
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.
+ # The three *Illumination classes add a gradient recorded as ``_params["gradient"]`` and clamp the sum
+ # into [0, 1]; ``sign`` is drawn per sample and fixes the direction. At gain 0.8 on a constant 0.5 the
+ # clamp engages on an in-range image.
# 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.
+ # torch.manual_seed(0); a = K.RandomGaussianIllumination(gain=(0.8, 0.8), sign=(1.0, 1.0), p=1.0)
+ # y = a(c); raw = c + a._params["gradient"]; print(torch.equal(y, raw.clamp(0, 1)), torch.equal(y, raw))
@pytest.mark.parametrize(
"name", ["RandomGaussianIllumination", "RandomLinearIllumination", "RandomLinearCornerIllumination"]
)
@@ -1540,9 +1165,7 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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.
+ # -1 can only darken, +1 can only brighten; the output is the clamped sum, 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))
@@ -1557,14 +1180,8 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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.
+ # With the default range one batch holds both directions; same_on_batch=True shares one gradient.
+ # B=16 makes an all-same-sign draw unlikely (2 * 2 ** -16).
batch_size = 16
batch = torch.full((batch_size, 3, 7, 9), 0.5, device=device, dtype=dtype)
torch.manual_seed(_FORWARD_SEED)
@@ -1577,44 +1194,25 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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.
+ # The edge, corner or centre where the gradient is strongest is also drawn per sample.
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))
+ # Issue #4811: ``center`` is rounded to a whole pixel, half to even, so ``center=0.5`` peaks one column
+ # past the middle of a 7-wide image but on it for a 9-wide one. A fix that maps ``center`` to the pixel
+ # centre flips the 7-wide leg.
+ # Snippet used to generate expected:
+ # a = K.RandomGaussianIllumination(gain=(0.5, 0.5), sigma=(0.2, 0.2), center=(0.5, 0.5), sign=(1., 1.), p=1.)
+ # torch.manual_seed(0); a(torch.zeros(1, 1, w, w)); print(int(a._params["gradient"][0, 0].sum(0).argmax()))
+ @pytest.mark.parametrize(("width", "peak"), [(7, 4), (9, 4)])
+ def test_wart_random_gaussian_illumination_center_rounds_half_to_even_4811(self, device, dtype, width, peak):
+ aug = K.RandomGaussianIllumination(gain=(0.5, 0.5), sigma=(0.2, 0.2), center=(0.5, 0.5), sign=(1.0, 1.0), p=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
+ aug(torch.zeros(1, 1, width, width, device=device, dtype=dtype))
+ assert int(aug._params["gradient"][0, 0].float().sum(0).argmax()) == peak
- # 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
+ # The three classes round-trip through pickle, deepcopy and torch.save (#4435), 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"]
)
@@ -1628,8 +1226,6 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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)
@@ -1637,42 +1233,24 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
reloaded = torch.load(buffer, weights_only=False)
assert torch.equal(reloaded(constant), expected)
- # The kernel is finite at every admitted `sigma`, including the `0` the constructor's own check
- # admits (the fix for #4589: `filters.kernels.gaussian` used to normalize by `gauss.sum()`, which
- # underflowed to zero once every sample was far enough from the mean, making the kernel `0 / 0` and
- # the whole output NaN). The fix measures each sample's squared distance from the NEAREST sample
- # rather than from the mean, so the nearest one always weighs `exp(0) = 1` and the sum cannot
- # underflow. This pin covers the three legs the wart pin it replaces used to record as NaN:
- # `sigma=0` at any size, an even axis at a small non-zero sigma (the half-pixel offset leaves no
- # sample at the mean), and a small `sigma * axis` product at any size.
- # 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)
- # print(K.RandomGaussianIllumination(p=1.0, sigma=(sg, sg), center=(0.5, 0.5))(
- # torch.full((1, 3, n, n), 0.5)).isfinite().all())
- # print(gaussian(5, torch.tensor([[0.0]])), gaussian(4, torch.tensor([[0.0]])))
- # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> finite at all five; the limit kernel
- # is `[0, 0, 1, 0, 0]` for an odd window and `[0, 0.5, 0.5, 0]` for an even one, where the two
- # samples either side of the mean tie at half a pixel.
+ # The illumination is finite at every admitted ``sigma``, including ``0`` and a small absolute width
+ # ``sigma * axis`` on an even axis (#4589). The kernel itself is pinned in tests/filters/test_gaussian.py.
@pytest.mark.parametrize("size", [3, 4])
def test_convention_random_gaussian_illumination_is_finite_at_every_sigma(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).isfinite().all())
- # The even axis loses the on-grid sample to the half-pixel offset; it is finite now as well.
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)
assert bool(small.isfinite().all()), (size, sigma)
- # It is the kernel's ABSOLUTE width -- `sigma * axis`, since `sigma` is relative -- that used to
- # underflow, at about 0.034 in the float32 the parameters are drawn in. These five products
- # (0.020, 0.040, 0.016, 0.032, 0.035) straddle that threshold; all five are finite now.
+ # Absolute widths straddling the float32 underflow threshold (about 0.034).
for axis, small_sigma in ((4, 0.005), (8, 0.005), (8, 0.002), (64, 0.0005), (64, 0.00055)):
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.isfinite().all()), (axis, small_sigma)
- # And with the DRAWN centre, which the wart pin recorded as NaN on some seeds at 1 and 3.
+ # And with a drawn centre.
for odd in (1, 3, 5, 7):
for seed in range(16):
torch.manual_seed(seed)
@@ -1681,86 +1259,45 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
odd,
seed,
)
- # The documented default was never affected and must stay unaffected.
torch.manual_seed(_FORWARD_SEED)
assert bool(K.RandomGaussianIllumination(p=1.0)(image).isfinite().all())
- # At `sigma=0` the kernel is the unit impulse: all the weight on the sample nearest the mean, which
- # for an even window is the two samples that tie half a pixel either side of it. This is the limit
- # the `masked_fill` encodes, and it is the part of the #4589 fix that is a NEW contract rather than
- # the removal of a NaN, so it is pinned separately from the finiteness above.
- @pytest.mark.device_agnostic
- def test_convention_gaussian_kernel_at_zero_sigma_is_the_unit_impulse(self):
- odd = gaussian(5, torch.tensor([[0.0]]))
- assert odd.flatten().tolist() == [0.0, 0.0, 1.0, 0.0, 0.0]
- even = gaussian(4, torch.tensor([[0.0]]))
- assert even.flatten().tolist() == [0.0, 0.5, 0.5, 0.0]
- # Every window sums to 1, so the impulse is a normalized kernel and not a degenerate one.
- for window in (1, 2, 3, 4, 5, 8, 9):
- assert float(gaussian(window, torch.tensor([[0.0]])).sum()) == pytest.approx(1.0)
-
- # An ODD window is bit-identical to the pre-fix formula at every ordinary sigma -- the shift cancels
- # exactly, because the nearest sample sits at distance 0 and subtracting 0 is exact. An EVEN window
- # is not: the nearest samples sit at 0.25 (half a pixel squared), the subtraction is inexact, and the
- # kernel moves by up to half a float32 eps. That is a rounding difference and not a behaviour change,
- # but it is the reason an even-window kernel is not byte-comparable across this fix.
- # Snippet used to generate expected:
- # compare gaussian(ws, sigma) against `exp(-x**2 / (2*sigma**2))` normalized, for ws 1..31 and
- # sigma in (0.1, 0.3, 0.5, 0.8, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0)
- # executed 2026-09-16 (torch 2.14.0, cpu) -> odd 160 of 160 bit-identical; even 134 of 150 differ,
- # worst absolute delta 5.96e-08, which is 0.5 * float32 eps.
- @pytest.mark.device_agnostic
- def test_convention_gaussian_odd_window_is_unchanged_by_the_nearest_sample_shift(self):
- for window in (1, 3, 5, 7, 9, 15, 31):
- for sigma in (0.1, 0.5, 1.0, 3.0, 10.0):
- sigma_t = torch.tensor([[sigma]])
- x = (torch.arange(window, dtype=sigma_t.dtype) - window // 2).expand(1, -1)
- reference = torch.exp(-x.pow(2.0) / (2 * sigma_t.pow(2.0)))
- reference = reference / reference.sum(-1, keepdim=True)
- assert torch.equal(gaussian(window, sigma_t), reference), (window, sigma)
-
- # `.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``.
+ # Issue #4807: the classes with their own ``.compile()`` store a compiled callable and then no longer
+ # pickle or pass through torch.save, though they still deep-copy; the linear illumination classes, which
+ # use torch's ``Module.compile``, keep pickling. A fix makes the first three pickle and flips it.
+ # "compile" in the name is load-bearing: conftest deselects it unless KORNIA_TEST_OPTIMIZER is set, which
+ # keeps ``torch.compile``'s process-wide side effects (it disables Distribution argument validation) out
+ # of the ordinary CPU legs.
@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
@pytest.mark.parametrize(
- "name", ["RandomGaussianIllumination", "RandomLinearIllumination", "RandomLinearCornerIllumination"]
+ ("name", "own_compile"),
+ [
+ ("RandomGaussianIllumination", True),
+ ("RandomGaussianBlur", True),
+ ("ColorJitter", True),
+ ("RandomLinearIllumination", False),
+ ("RandomLinearCornerIllumination", False),
+ ],
)
@pytest.mark.device_agnostic
- def test_convention_compiled_illumination_pickling(self, name):
- compiled = _illumination(name)
+ def test_wart_compiled_intensity_augmentation_does_not_pickle_4807(self, name, own_compile):
+ if name == "RandomGaussianBlur":
+ compiled = K.RandomGaussianBlur((3, 3), (1.0, 1.0), p=1.0)
+ elif name == "ColorJitter":
+ compiled = K.ColorJitter(0.1, 0.1, 0.1, 0.1, p=1.0)
+ else:
+ 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":
+ if own_compile:
with pytest.raises(pickle.PicklingError):
pickle.dumps(compiled)
with pytest.raises(pickle.PicklingError):
@@ -1768,38 +1305,17 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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.
+ # The RandomPlasma* classes clamp into [0, 1] and record the fractal as ``_params["plasma"]``, so a
+ # replay with ``params=`` reproduces the output bitwise. The replay runs on a non-constant image,
+ # because a constant 0.5 is a fixed point of the plasma contrast transform.
@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)
@@ -1812,14 +1328,8 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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 and
- # expanded fractal map view, so identical inputs receive identical transformations. #3624 reported this
- # together with RandomGaussianNoise and RandomChannelShuffle, and #3723 fixed only those two.
- # 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]))
- # print(torch.equal(y[0], y[1]))
- # executed 2026-09-16 (torch 2.9.1+cpu, cpu) -> `True` for maps and outputs for all three classes.
+ # With same_on_batch=True the RandomPlasma* classes share their scalar draws and one expanded fractal
+ # map (#4570).
@pytest.mark.parametrize("name", ["RandomPlasmaBrightness", "RandomPlasmaContrast", "RandomPlasmaShadow"])
def test_convention_plasma_same_on_batch_shares_map_4570(self, device, dtype, name):
image = torch.full((4, 3, 8, 8), 0.3, device=device, dtype=dtype)
@@ -1830,18 +1340,11 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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 torch.equal(aug._params["plasma"][0], aug._params["plasma"][1])
- # The map is expanded, not repeated: a batch stride of 0 is the storage promise
- # `IntensityAugmentationBase2D`'s Convention block makes, and `repeat` would satisfy the
- # equality above while quietly allocating (and un-aliasing) one map per sample.
+ # Expanded, not repeated: the stored map has batch stride 0.
assert aug._params["plasma"].stride()[0] == 0
assert 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.
+ # A one-pixel spatial axis is accepted.
@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):
@@ -1849,16 +1352,11 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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.
+ # ``mean`` and ``std`` accept a float, a sequence, a 1- or C-tensor and a per-sample (B, C) tensor, and
+ # each form rescales the image; a (B, C) statistic is applied to its own sample.
# 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.
+ # torch.manual_seed(0); print((K.Normalize(mean=0.5, std=0.25, p=1.0)(x) - x).abs().max())
@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(
@@ -1872,9 +1370,7 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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.
+ # The exact field: the threshold above cannot tell a per-sample application from a row-0 one.
stats = torch.arange(1, 13, device=device, dtype=dtype).reshape(4, 3) / 10.0
field = stats[..., None, None]
torch.manual_seed(_FORWARD_SEED)
@@ -1882,69 +1378,20 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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"])
+ # Denormalize inverts Normalize built with the same statistics, checked on a forward that moved the
+ # tensor, so a no-op cannot satisfy it; integer statistics round-trip too (#4573).
+ @pytest.mark.parametrize("form", ["float", "list3", "tensor1", "tensorB3", "int"])
def test_convention_denormalize_inverts_normalize(self, device, dtype, form):
- mean, std = _statistics(form, device, dtype)
+ mean, std = (0, 4) if form == "int" else _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
+ assert float((normalized - image).abs().max()) > 0.5
torch.manual_seed(_FORWARD_SEED)
self.assert_close(K.Denormalize(mean=mean, std=std, p=1.0)(normalized), image)
- # Issue #4577: normalization preserves image values across contiguous and strided layouts.
- @pytest.mark.parametrize("name", ["Normalize", "RandomAutoContrast"])
- def test_convention_non_contiguous_input_matches_contiguous_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)
- actual = factories[name]()(view)
- torch.manual_seed(_FORWARD_SEED)
- expected = factories[name]()(view.contiguous())
- assert actual.shape == view.shape
- self.assert_close(actual, expected)
-
- # 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.`
+ # A mean or std whose length is neither 1 nor the channel count is rejected.
@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)
@@ -1955,40 +1402,14 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
with pytest.raises(ValueError, match="do not match"):
_sync(cls(mean=mean, std=std, p=1.0)(image).device)
- # Issue #4573: Normalize and Denormalize both accept integer scalar statistics, so the pair
- # built with ``mean=0, std=255`` round-trips.
- # Snippet used to generate expected:
- # x = torch.rand(2, 3, 4, 4); y = K.Normalize(mean=0, std=255, p=1.0)(x)
- # z = K.Denormalize(mean=0, std=255, p=1.0)(y)
- # torch.testing.assert_close(z, x)
- # executed 2026-09-16 (torch 2.5.1, cpu).
- @pytest.mark.device_agnostic
- def test_convention_denormalize_accepts_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)
- self.assert_close(K.Denormalize(mean=0, std=255, p=1.0)(normalized), image)
- 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()``.
+ # Normalize and Denormalize hard-code ``same_on_batch=True`` and take no such argument, so ``p`` gates
+ # the whole batch together.
# 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'`.
+ # torch.manual_seed(seed); aug = K.Normalize(mean=0.5, std=0.25, p=0.5); aug(x); print(aug._params["batch_prob"])
@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)
+ assert "same_on_batch" not in inspect.signature(cls.__init__).parameters
torch.manual_seed(_FIXTURE_SEED)
image = torch.rand(8, 3, 6, 8).to(device=device, dtype=dtype)
applied = 0
@@ -2000,29 +1421,16 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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.
+ # Both outcomes occur over these six seeds.
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.
+ # The statistics live in ``flags``, not in buffers: ``state_dict()`` is empty and ``.to()`` leaves them
+ # alone (the forward casts them to the input).
@pytest.mark.device_agnostic
@pytest.mark.parametrize("cls", [K.Normalize, K.Denormalize])
def test_convention_normalize_keeps_no_state(self, cls):
@@ -2030,47 +1438,14 @@ class TestIlluminationAndNormalizeConventions(BaseTester):
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."""
+ """Point-range constructors for the three *Illumination classes."""
classes = {
"RandomGaussianIllumination": K.RandomGaussianIllumination,
"RandomLinearIllumination": K.RandomLinearIllumination,
@@ -2121,7 +1496,7 @@ def _field_augmentation(name: str, p: float = 1.0, keepdim: bool = False):
def _statistics(form: str, device, dtype):
- """The six ``mean`` / ``std`` forms row 6c-16 records as accepted."""
+ """The six accepted ``mean`` / ``std`` forms."""
if form == "float":
return 0.5, 0.25
if form == "list3":
@@ -2139,8 +1514,7 @@ def _statistics(form: str, device, 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.
+ # Distinct rows, so a per-sample statistic is distinguishable from the scalar form.
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]],
diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.py
index 92e9e0a1f..5ecc6e696 100644
--- a/tests/augmentation/test_conventions_intensity_values.py
+++ b/tests/augmentation/test_conventions_intensity_values.py
@@ -18,18 +18,16 @@
from __future__ import annotations
import math
+import warnings
import pytest
import torch
import kornia.augmentation as K
from kornia.augmentation.random_generator import RectangleEraseGenerator
-from kornia.color import rgb_to_hsv
from kornia.core.exceptions import BaseError, ImageError, ShapeError
from kornia.enhance import (
- AdjustBrightnessAccumulative,
adjust_brightness,
- adjust_brightness_accumulative,
adjust_contrast,
adjust_hue,
adjust_saturation,
@@ -51,11 +49,8 @@ def _restore_global_rng(restore_torch_rng):
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.
+# One constructor per 2D intensity class for the value-range pins below. RandomDissolving (its
+# constructor downloads a checkpoint), RandomClahe and RandomJPEG have pins of their own.
_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),
@@ -84,11 +79,9 @@ _INTENSITY_FACTORIES = {
"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.
+ # A range, not the scalar `bits=3` (the lower bound of [3, 8]): a draw of 8 skips the uint8 round
+ # trip and keeps the fixture's range, as test_wart_random_posterize_eight_bits_skips_the_round_trip_4430
+ # pins.
"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),
@@ -99,10 +92,9 @@ _INTENSITY_FACTORIES = {
"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.
+# The four observed outcomes for these constructor arguments and fixtures (#4430). They are not
+# class-wide policies: a blur can attenuate an out-of-range impulse into [0, 1], and a hue-only
+# ColorJiggle keeps an out-of-range maximum.
_BOUNDED_ON_FIXTURES = (
"ColorJiggle",
"ColorJitter",
@@ -121,7 +113,7 @@ _BOUNDED_ON_FIXTURES = (
"RandomSharpness",
"RandomSolarize",
)
-# Row 6c-04: ``output.clamp(max=1.0)`` only, so a negative input stays negative.
+# ``output.clamp(max=1.0)`` only, so a negative input stays negative.
_UPPER_BOUNDED_ON_FIXTURES = ("RandomPlanckianJitter",)
_OUT_OF_RANGE_ON_FIXTURES = (
"Denormalize",
@@ -142,33 +134,34 @@ _OUT_OF_RANGE_ON_FIXTURES = (
"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",
-)
+# The only factory that rejects these fixtures.
+_REJECTS_OUT_OF_RANGE_FIXTURES = ("RandomEqualize",)
+
+# These factories return zeros for a constant -1 image on every draw (#4430): no admissible draw lifts it
+# above zero. The plasma brightness and contrast maps are unbounded draws, so those two are pinned by replay
+# instead. RandomPosterize is not here: its uint8 conversion of a negative float is platform-dependent
+# (test_wart_random_posterize_out_of_range_wraps_4430).
+_COLLAPSES_ON_CONSTANT_MINUS_ONE = {
+ **{
+ name: _INTENSITY_FACTORIES[name]
+ for name in (
+ "ColorJitter",
+ "RandomBrightness",
+ "RandomContrast",
+ "RandomGaussianIllumination",
+ "RandomLinearIllumination",
+ "RandomLinearCornerIllumination",
+ "RandomPlasmaShadow",
+ "RandomSnow",
+ "RandomSharpness",
+ "RandomSolarize",
+ )
+ },
+ "RandomBrightness-default": lambda: K.RandomBrightness(p=1.0),
+ "ColorJiggle-contrast": lambda: K.ColorJiggle(0.0, 0.3, 0.0, 0.0, p=1.0),
+}
-# 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 for the shared out-of-range images, and the seed drawn before each construct-and-forward.
_FIXTURE_SEED = 1234
_FORWARD_SEED = 0
@@ -197,69 +190,38 @@ def _run(name: str, image: torch.Tensor, seed: int | None = None) -> torch.Tenso
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):
+ # Issue #4430: the four outcomes above, per factory. `clip_output=False` variants of RandomBrightness
+ # and RandomContrast, which pass the range through, are pinned separately below.
+ # Snippet used to generate expected:
# 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`.
+ # for x in (base * 2.0, base - 1.0): torch.manual_seed(0); print(name, factory()(x).aminmax())
@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 kornia checks the same
- # condition (#4600), so the named error is raised there as on the CPU.
+ def test_convention_value_range_on_out_of_range_fixtures(self, device, dtype, name):
+ groups = (
+ _BOUNDED_ON_FIXTURES,
+ _UPPER_BOUNDED_ON_FIXTURES,
+ _OUT_OF_RANGE_ON_FIXTURES,
+ _REJECTS_OUT_OF_RANGE_FIXTURES,
+ )
+ assert set().union(*groups) == set(_INTENSITY_FACTORIES)
+ if name in _REJECTS_OUT_OF_RANGE_FIXTURES and device.type == "cuda":
pytest.skip("CUDA: the value assert is a device-side assert that invalidates the context")
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: its message names the
- # range, on the CPU and on MPS alike (#4600).
+ if name in _REJECTS_OUT_OF_RANGE_FIXTURES:
+ # kornia's own value check, which names the range.
for image in fixtures.values():
with pytest.raises(RuntimeError, match=r"\[0, 1\]"):
_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.
+ # A clamped output is exactly 0.0 or 1.0 and a pass-through one sits near 2.0 or -1.0, so this
+ # tolerance 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.
+ # The fixtures are already out of range, so the pass-through branch would accept the identity:
+ # require the class to change a fixture on some draw (a single draw can be neutral).
moved = False
for seed in range(8):
for image in fixtures.values():
@@ -268,18 +230,14 @@ class TestIntensityValueRangeConventions(BaseTester):
break
if moved:
break
- assert moved, f"{name} returned the audit fixtures unchanged on every seed tried"
+ assert moved, f"{name} returned the out-of-range 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).
+ # Reach: the bound is [0, 1], not a narrower interval. The exceptions are draws that end
+ # inside it: ColorJiggle's hue-only draws, a brightness factor below 1, RandomPosterize's top
+ # level 252/255 and RandomSolarize's inversion.
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"):
@@ -296,17 +254,10 @@ class TestIntensityValueRangeConventions(BaseTester):
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.
+ # `clip_output` is live on both classes: the default clamps, `clip_output=False` returns the raw result.
# 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.
+ # print(cls((1.5, 1.5), p=1.0)(x).max(), cls((1.5, 1.5), clip_output=False, p=1.0)(x).max())
@pytest.mark.parametrize("name", ["RandomBrightness", "RandomContrast"])
def test_convention_brightness_and_contrast_clip_output_is_live(self, device, dtype, name):
cls = getattr(K, name)
@@ -337,132 +288,58 @@ class TestIntensityValueRangeConventions(BaseTester):
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):
- 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.
+ # Issue #4430: these factories silently return an all-zero image for an all-negative input. The pin
+ # asserts the silence as well as the zeros, so a fix that rejects or warns flips it; a fix that instead
+ # rules the clamp to be the policy renames it to a convention pin.
# 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",
+ # x = torch.full((2, 3, 6, 8), -1.0); torch.manual_seed(seed); print(factory()(x).abs().max())
+ @pytest.mark.parametrize("name", sorted(_COLLAPSES_ON_CONSTANT_MINUS_ONE))
+ @pytest.mark.parametrize("seed", [0, 1, 2])
+ def test_wart_intensity_negative_input_collapses_to_zero_4430(self, device, dtype, name, seed):
+ image = torch.full((2, 3, 6, 8), -1.0, device=device, dtype=dtype)
+ torch.manual_seed(seed)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ out = _COLLAPSES_ON_CONSTANT_MINUS_ONE[name]()(image)
+ _sync(image.device)
+ assert float(out.abs().max()) == 0.0
+ assert not caught
+
+ # Issue #4430, the plasma classes: whether a constant -1 image collapses depends on the drawn map.
+ # RandomPlasmaContrast, ``(x - 0.5) * 4 * plasma + 0.5``, zeroes it wherever the map is at least 1/12;
+ # RandomPlasmaBrightness, ``x + (2 * plasma - 1) * intensity``, at intensity 1 zeroes it wherever the map
+ # is at most 1. The draw is pinned by replaying ``params`` with a constant map.
+ @pytest.mark.parametrize(
+ ("name", "level", "collapses"),
+ [
+ ("RandomPlasmaContrast", 0.5, True),
+ ("RandomPlasmaContrast", 0.0, False),
+ ("RandomPlasmaBrightness", 0.5, True),
+ ("RandomPlasmaBrightness", 1.5, False),
+ ],
)
-
- def test_wart_intensity_constant_negative_collapse_census_4430(self, device, dtype):
+ def test_wart_random_plasma_negative_collapse_depends_on_the_map_4430(self, device, dtype, name, level, collapses):
image = torch.full((2, 3, 6, 8), -1.0, device=device, dtype=dtype)
- every, some = [], []
- for name in sorted(_INTENSITY_FACTORIES):
- if name == "RandomEqualize":
- continue
- 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)
- 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.
+ aug = getattr(K, name)(p=1.0)
+ torch.manual_seed(_FORWARD_SEED)
+ aug(image)
+ params = dict(aug._params)
+ params["plasma"] = torch.full_like(params["plasma"], level)
+ if "intensity" in params:
+ params["intensity"] = torch.ones_like(params["intensity"])
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ out = aug(image, params=params)
+ _sync(image.device)
+ assert (float(out.abs().max()) == 0.0) is collapses
+ assert not caught
+
+ # Issue #4430: RandomPosterize posterizes the `uint8` conversion of the raw float, not of the clamped
+ # input. What that conversion does outside [0, 255] is platform-dependent (it wraps or saturates), so
+ # the pin asserts the round-trip identity rather than platform literals.
# 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.
+ # torch.manual_seed(0); y = K.RandomPosterize(bits=(3.0, 3.0), p=1.0)(g * 2.0); print(len(y.unique()), y.max())
@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)
@@ -470,38 +347,22 @@ class TestIntensityValueRangeConventions(BaseTester):
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` reproduces the one `uint8` conversion inside `posterize` that sees the raw value.
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.
+ # A clamp-first fix would return `clamped`; where the running conversion saturates, the two agree.
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.
+ # Issue #4430, the other posterize path: a sample that draws 8 bits is returned unchanged, with no
+ # `uint8` round trip to bound it, so its out-of-range values survive.
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)
@@ -509,79 +370,46 @@ class TestIntensityValueRangeConventions(BaseTester):
_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.
+ # Issue #4430: on a negative input `x ** gamma` is NaN for a non-integer gamma and the clamp keeps it;
+ # an integer gamma stays finite, and the default gamma=1 clamps every negative value to 0.
# 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):
+ # torch.manual_seed(0); print(K.RandomGamma((gamma, gamma), (1.0, 1.0), p=1.0)(neg).isnan().all())
+ @pytest.mark.parametrize(("gamma", "expected"), [(0.5, "nan"), (1.0, "zero"), (2.0, "positive")])
+ def test_wart_random_gamma_negative_input_depends_on_gamma_4430(self, device, dtype, gamma, 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:
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ out = K.RandomGamma((gamma, gamma), (1.0, 1.0), p=1.0)(image)
+ _sync(image.device)
+ assert not caught
+ if expected == "nan":
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.
+ assert (float(out.abs().max()) > 0.0) is (expected == "positive")
+
+ # RandomEqualize rejects an out-of-range input with kornia's error naming the [0, 1] range. The guard
+ # is `input * 255` inside (-1, 256), so less than one 8-bit code outside the range is admitted.
# 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 runs the same check and raises the
- # same message (#4600). 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.
+ # for x in (g, g * 1.0001, g - 0.003, g * 2, g - 1): torch.manual_seed(0); K.RandomEqualize(p=1.0)(x)
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; it runs on MPS as well, so it raises there too.
match = r"\[0, 1\]"
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)
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
@@ -593,10 +421,7 @@ class TestIntensityValueRangeConventions(BaseTester):
# 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`; on mps the
- # named message since #4600), then `True [nan, 1.0, 1.0, nan, 1.0, 1.0]`.
+ # print(torch.equal(y, v), v.grad.flatten().tolist()) # -> 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")
@@ -606,9 +431,7 @@ class TestIntensityValueRangeConventions(BaseTester):
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.
- # MPS runs the value check too since #4600, so only the named error qualifies there.
- gate_rejection = r"\[0, 1\]|out of bounds" if device.type == "cpu" else r"\[0, 1\]"
- with pytest.raises(RuntimeError, match=gate_rejection):
+ with pytest.raises(RuntimeError, match=r"\[0, 1\]"):
_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_()
@@ -621,14 +444,11 @@ class TestIntensityValueRangeConventions(BaseTester):
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.
+ # RandomGamma is `clamp(gain * x ** gamma, 0, 1)` with no `clip_output` to disable the clamp.
# 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.
+ # print((y - gain * g**gamma).abs().max())
@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)
@@ -638,38 +458,29 @@ class TestIntensityColourConventions(BaseTester):
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):
+ def test_convention_random_gamma_negative_exponent_is_unchecked_on_mps(self, device, dtype):
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.
+ # kornia does not run the non-negativity check for an MPS image, so gamma=-1 is evaluated as
+ # clamp(gain / input, 0, 1).
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))
+ out = K.RandomGamma((-1.0, -1.0), (0.1, 0.1), p=1.0)(image)
+ self.assert_close(out, image.new_tensor([0.5, 0.2, 0.125]).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.
+ # Clamping the HSV saturation removes a negative RGB channel even at factor 1 and turns an
+ # all-negative pixel gray at its largest channel; pixels above 1 with no negative channel keep
+ # their values, which a final RGB clamp would remove.
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.
+ # RandomBrightness passes `factor - 1` to 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]`.
+ # c = torch.full((1, 1, 2, 2), 0.4); torch.manual_seed(0); print(K.RandomBrightness((1.5, 1.5), p=1.0)(c))
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)
@@ -689,39 +500,22 @@ class TestIntensityColourConventions(BaseTester):
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`.
+ # Each class's identity factor is 1.0, checked on two distinct samples.
@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"
- )
+ pytest.skip("adjust_saturation's HSV round trip is lossier than the half-precision tolerance")
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.
+ # With matching bounds the two classes draw identical parameters, `order` included, from the same seed;
+ # replaying ColorJitter with ColorJiggle's parameters reproduces ColorJitter's output, so the gap between
+ # the two outputs is the primitives, not the draw.
# 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.
+ # torch.manual_seed(7); b = K.ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0); print((ya - b(x)).abs().max())
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)
@@ -736,8 +530,6 @@ class TestIntensityColourConventions(BaseTester):
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
@@ -745,13 +537,9 @@ class TestIntensityColourConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_color_jiggle_and_jitter_have_different_brightness_bounds(self):
# A scalar brightness above 1 overshoots ColorJiggle's [0, 2] bound and is rejected there, while
- # ColorJitter, bounded by (0, inf), reads it as [0, 1 + brightness].
+ # ColorJitter reads it as [0, 1 + brightness].
with pytest.raises(ValueError, match="brightness out of bounds"):
K.ColorJiggle(brightness=1.5)
- # `(jitter > 2).any()` needs a batch wide enough to be certain: one draw clears 2 with probability
- # 0.2, so at the `B = 4` an earlier revision of this pin 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 = 256`
- # the failure probability is `0.8 ** 256`, about `1e-25`.
torch.manual_seed(7)
jitter_brightness = K.ColorJitter(brightness=1.5).forward_parameters((256, 3, 2, 2))["brightness_factor"]
assert bool(((jitter_brightness >= 0) & (jitter_brightness <= 2.5)).all())
@@ -770,25 +558,14 @@ class TestIntensityColourConventions(BaseTester):
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`.
+ # A chromatic pixel: the rotation keeps its out-of-range maximum.
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.
+ # Both classes are the identity at (0, 0, 0, 0) on an in-range image.
@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)
@@ -796,52 +573,17 @@ class TestIntensityColourConventions(BaseTester):
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):
- 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.
+ # Issue #4785, ColorJitter: the brightness guard tests the factor against 0, not the multiplier's neutral 1,
+ # so the factor 1 drawn by the default ``brightness=0.0`` still runs the clamping step. Run first, it
+ # clamps an all-negative input to zero; a contrast or saturation factor above 1 applied before it lifts
+ # part of the image first. A fix that skips a factor of 1 flips the brightness-first leg; removing the guard
+ # altogether leaves it green, because the clamp is then #4430's. A fixed order without index 0 skips the
+ # step and its clamp.
# 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]`.
+ # print(K.ColorJitter(p=1.0, order=order, contrast=(1.9, 1.9))(neg).aminmax())
@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):
+ def test_wart_color_jitter_default_brightness_step_clamps_4785(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)
@@ -853,23 +595,9 @@ class TestIntensityColourConventions(BaseTester):
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:
- # - on ColorJiggle and ColorJitter, a fixed constructor `order` ignores a forward `order=` tensor;
- # - without a constructor order, a forward `order=` tensor replaces ColorJiggle's 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.`
+ # A fixed constructor `order` ignores a forward `order=` tensor; without one, a forward `order=` replaces
+ # ColorJiggle's drawn order, so leaving the hue step out lets a one-channel image through. ColorJitter's
+ # saturation step rejects four channels, clamps a three-channel image and passes a one-channel image.
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)
@@ -895,29 +623,23 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # Issue #4785: ColorJitter's brightness step multiplies (identity 1) but is guarded as if 0 were
+ # neutral, so a batch whose factors are all 0 comes back unchanged while the same sample in a mixed
+ # batch comes back black. The fix makes the all-zero batch black and flips the first assertion.
+ def test_wart_color_jitter_zero_brightness_factor_is_skipped_4785(self, device, dtype):
+ image = torch.full((2, 3, 2, 2), 0.5, device=device, dtype=dtype)
+ aug = K.ColorJitter(brightness=(0.0, 0.0), p=1.0)
+ assert torch.equal(aug(image), image)
+ params = aug.forward_parameters(image.shape)
+ params["brightness_factor"] = torch.tensor([0.0, 1.0])
+ mixed = aug(image, params=params)
+ assert float(mixed[0].abs().max()) == 0.0
+ self.assert_close(mixed[1], image[1])
+
+ # RandomHue's argument is turns of the hue circle; the class multiplies it by 2*pi for adjust_hue.
# 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)
@@ -925,18 +647,11 @@ class TestIntensityColourConventions(BaseTester):
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, in every dtype since the #4560 guard.
+ # RandomHue has no clamp, and a hue rotation keeps each pixel's largest and smallest channel, so a pixel
+ # outside [0, 1] keeps a channel outside it. A pixel whose largest channel is exactly 0 comes back as zeros.
# 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)
@@ -946,18 +661,10 @@ class TestIntensityColourConventions(BaseTester):
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)
- # Zeros in every dtype since the #4560 guard; float16 used to be NaN here.
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`.
+ # RandomGrayscale keeps the channel count, writes the same value into every channel and uses the BT.601
+ # luma weights by default (pure red -> 0.299); custom weights replace them.
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
@@ -973,14 +680,7 @@ class TestIntensityColourConventions(BaseTester):
# 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`.
+ # The weights are applied as given, not normalized.
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)
@@ -990,13 +690,7 @@ class TestIntensityColourConventions(BaseTester):
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).
+ # A non-RGB channel count is not rejected: every channel becomes the plain mean over channels.
@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)
@@ -1006,17 +700,8 @@ class TestIntensityColourConventions(BaseTester):
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]]`.
+ # Output channel `c` of sample `b` is input channel `channels[b][c]`, drawn per sample unless
+ # same_on_batch; per-sample constant planes 0..11 make the relabelling visible.
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)
@@ -1031,33 +716,13 @@ class TestIntensityColourConventions(BaseTester):
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)
+ # same_on_batch collapses the draw to a single permutation.
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())
+ shared = K.RandomChannelShuffle(p=1.0, same_on_batch=True)
+ shared(image)
+ assert bool((shared._params["channels"] == shared._params["channels"][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]]`.
+ # `fill_value` is written into exactly the channels named by the drawn `channel_idx`, one draw per sample.
@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
@@ -1074,10 +739,7 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # The draw is per sample; two samples can coincide by chance, so distinctness is checked on B=8.
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))
@@ -1093,14 +755,7 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # RandomInvert is `max_val - x` with no clamp.
@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)
@@ -1110,22 +765,11 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # The addition comes first and the sum is clamped into [0, 1]; only then is everything at or above the
+ # threshold inverted.
# 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.
+ # z = (g + a).clamp(0, 1); print((y - torch.where(z < t, z, 1.0 - z)).abs().max())
@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)
@@ -1136,60 +780,46 @@ class TestIntensityColourConventions(BaseTester):
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)
+ # Outside [0, 1] the result depends on the drawn addition and threshold: a positive addition lifts a
+ # negative pixel above zero before the clamp, a negative one brings 1.1 below 1 before the inversion
+ # (1 - 0.7 = 0.3), and a threshold of 0 inverts the clamped zeros to ones.
+ @pytest.mark.parametrize(
+ ("value", "threshold", "addition", "expected"),
+ [
+ (-0.001, 0.5, -0.1, 0.0),
+ (-0.001, 0.5, 0.1, 0.099),
+ (1.1, 0.5, -0.4, 0.3),
+ (1.1, 0.5, 0.0, 0.0),
+ (-0.001, 0.0, 0.0, 1.0),
+ ],
+ )
+ def test_convention_random_solarize_out_of_range_depends_on_the_draw(
+ self, device, dtype, value, threshold, addition, expected
+ ):
+ image = torch.full((1, 3, 6, 8), value, device=device, dtype=dtype)
+ torch.manual_seed(_FORWARD_SEED)
+ out = K.RandomSolarize(thresholds=(threshold, threshold), 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.
+ # Issue #4430, the upper end: `clamp(x + a, 0, 1)` sends every x >= 1.5 to exactly 1.0 for any admissible
+ # addition, which the inversion returns as 0, so such an input is silently all-zero on every draw.
@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.
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ out = K.RandomSolarize(p=1.0)(image)
+ assert bool((out == 0).all())
+ assert not caught
+ # A fixture that straddles the bound does not collapse.
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]`.
+ # A scalar `thresholds` is a half-width around 0.5 and a scalar `additions` one around 0.
@pytest.mark.device_agnostic
def test_convention_random_solarize_scalar_is_a_centred_range(self):
torch.manual_seed(_FORWARD_SEED)
@@ -1202,21 +832,14 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # The draw reaches the documented half-width, not a narrower one.
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])
+ # `bits=(k, k)` leaves exactly 2**k distinct levels on a 256-level ramp.
+ @pytest.mark.parametrize("bits", [0, 3, 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)
@@ -1224,13 +847,7 @@ class TestIntensityColourConventions(BaseTester):
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`.
+ # An `int` argument is the lower bound of [x, 8] -- the opposite of RandomSharpness's scalar.
@pytest.mark.device_agnostic
@pytest.mark.parametrize("bits", [3, 6])
def test_convention_random_posterize_int_argument_is_a_lower_bound(self, bits):
@@ -1240,15 +857,9 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # The factor blends linearly between the blurred image (0) and the input (1); above 1 it sharpens.
# 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`).
+ # torch.manual_seed(0); print((K.RandomSharpness((f, f), p=1.0)(x) - x).abs().max())
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)
@@ -1275,13 +886,7 @@ class TestIntensityColourConventions(BaseTester):
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]`.
+ # A scalar `sharpness` is the upper bound of [0, x], so the default 0.5 never reaches the identity.
@pytest.mark.device_agnostic
def test_convention_random_sharpness_scalar_is_an_upper_bound(self):
torch.manual_seed(_FORWARD_SEED)
@@ -1289,29 +894,12 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # The draw reaches the documented bound, not a shrunk range.
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]]`.
+ # One additive shift per channel per sample, clamped into [0, 1] by shift_rgb; the red shift is replaced
+ # by +1.0 so the clamp is exercised without depending on the draw.
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)
@@ -1319,8 +907,7 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # The two samples draw independently, 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)
@@ -1329,13 +916,7 @@ class TestIntensityColourConventions(BaseTester):
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`.
+ # A limit is the half-width of a symmetric range; a limit of 0 adds nothing but the clamp still applies.
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)
@@ -1347,34 +928,29 @@ class TestIntensityColourConventions(BaseTester):
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`.
+ # Issue #4430, RandomRGBShift: the clamp on the sum makes an image at or below `-limit` silently all-zero
+ # on every draw.
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)`.
+ image = torch.full((2, 3, 6, 8), -0.5, device=device, dtype=dtype)
+ for seed in range(20):
+ torch.manual_seed(seed)
+ with warnings.catch_warnings(record=True) as caught:
+ warnings.simplefilter("always")
+ out = K.RandomRGBShift(p=1.0)(image)
+ assert float(out.abs().max()) == 0.0, seed
+ assert not caught
+
+ # Issue #4782: a tuple limit is neither read as a range nor rejected by name; it dies on the unary
+ # minus that builds `(-limit, limit)`. A fix that accepts the tuple, or raises a kornia error, flips it.
+ @pytest.mark.device_agnostic
+ def test_wart_random_rgb_shift_tuple_limit_raises_a_raw_type_error_4782(self):
+ with pytest.raises(TypeError) as info:
+ K.RandomRGBShift((0.1, 0.5), p=1.0)
+ # A kornia rejection would name the argument; the raw error from the unary minus does not.
+ assert not any(word in str(info.value) for word in ("limit", "shift"))
+
+ # `pl` is a persistent buffer holding the table the mode selects -- 25 rows for blackbody, 23 for CIED --
+ # and `select_from` narrows it.
@pytest.mark.device_agnostic
@pytest.mark.parametrize(
("kwargs", "rows"), [({"mode": "blackbody"}, 25), ({"mode": "CIED"}, 23), ({"select_from": [0, 1]}, 2)]
@@ -1384,14 +960,11 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # The selected row scales red and blue only, then `clamp(max=1.0)` applies to all three channels:
+ # green above 1 is cut back although it is not scaled, 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)
@@ -1399,23 +972,11 @@ class TestIntensityColourConventions(BaseTester):
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)
- # The coefficient table follows the input dtype, so the output is already in it and the
- # comparison needs no cast.
self.assert_close(out, 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 coefficient table follows the input dtype, so half-precision inputs are no
- # longer promoted to float32, and a module cast does not decide the output dtype either.
- # Snippet used to generate expected:
- # for dt in (torch.float16, torch.bfloat16):
- # other = torch.bfloat16 if dt == torch.float16 else torch.float16
- # torch.manual_seed(0); x = torch.rand(2, 3, 4, 4).to(dt)
- # torch.manual_seed(0); a = K.RandomPlanckianJitter(p=1.0)(x).dtype
- # torch.manual_seed(0); b = K.RandomPlanckianJitter(p=1.0).to(dtype=other)(x).dtype
- # print(dt, a, b)
- # executed 2026-09-17 (torch 2.14.0, cpu) -> `float16 float16 float16` and `bfloat16 bfloat16
- # bfloat16`; on `30dfbf711`, this PR's base, both columns were `float32` for both inputs.
+ # Issue #4574: the coefficient table follows the input dtype, so a half-precision input is not promoted.
def test_convention_random_planckian_jitter_preserves_dtype_4574(self, device, dtype):
torch.manual_seed(_FIXTURE_SEED)
image = torch.rand(2, 3, 4, 4).to(device=device, dtype=dtype)
@@ -1426,17 +987,12 @@ class TestIntensityColourConventions(BaseTester):
assert out.device == image.device
if dtype in _HALF:
- # A module cast to the *other* half dtype returned float32 before the fix, because the
- # table's dtype decided the promotion; it now follows the input like every other cast.
+ # A module cast to the other half dtype does not decide the output dtype.
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 == dtype
# Issue #4574, the wider direction: a module cast wider than the input does not widen the output.
- # Snippet used to generate expected:
- # torch.manual_seed(0); x = torch.rand(2, 3, 4, 4)
- # torch.manual_seed(0); print(K.RandomPlanckianJitter(p=1.0).to(dtype=torch.float64)(x).dtype)
- # executed 2026-09-17 (torch 2.14.0, cpu) -> `float32`; on `30dfbf711` it was `float64`.
def test_convention_random_planckian_jitter_wider_module_dtype_4574(self, device):
if device.type == "mps":
pytest.skip("MPS does not support float64")
@@ -1449,52 +1005,28 @@ class TestIntensityColourConventions(BaseTester):
assert out.dtype == torch.float32
assert out.device == image.device
- # 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.`
+ # The illuminant table is an RGB ratio, so a non-RGB input is rejected rather than broadcast.
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]).`
+ # Issue #4428: `pl`'s shape depends on `mode`, so a blackbody state_dict does not load into a CIED
+ # instance.
@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"):
+ with pytest.raises(RuntimeError):
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.
+ # RandomAutoContrast is kornia.enhance.normalize_min_max, a per-sample, per-channel rescale; six channels
+ # with six distinct ranges rule out a per-batch or per-image rescale.
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)
@@ -1507,9 +1039,7 @@ class TestIntensityColourConventions(BaseTester):
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).
+ # The documented `+ 1e-6` in the denominator: a range of 1e-5 peaks at 1e-5 / 1.1e-5.
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
@@ -1517,14 +1047,8 @@ class TestIntensityColourConventions(BaseTester):
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`.
+ # RandomJPEG's decode hard-clamps into [0, 1], so an input far outside it comes back inside, reaching both
+ # ends.
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")
@@ -1551,36 +1075,15 @@ class TestIntensityColourConventions(BaseTester):
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)`, `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.
+ # The documented parameter bounds are enforced, and `stage` records where: at construction, or on the
+ # forward pass for the checks that need the image. `match` pins kornia's message, so a case cannot be
+ # satisfied by a different error of the same class; `bits=9` is the example -- a scalar becomes [9, 8]
+ # and trips the "lo > hi" arm, so the (0, 8] bound needs the explicit range row.
@pytest.mark.parametrize(
("case", "stage", "error", "match"),
[
@@ -1616,7 +1119,6 @@ class TestIntensityColourConventions(BaseTester):
("hue_above_half", "construction", ValueError, r"hue out of bounds\. Expected inside \(-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",
@@ -1643,40 +1145,33 @@ class TestIntensityColourConventions(BaseTester):
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",
- ),
- # The scalar rows name the reported tensor as well as the bound: it is the unclamped
- # `[center - x, center + x]`, which only `_range_bound`'s own scalar raise produces. The
- # trailing `_joint_range_check` rejects the same inputs with the lower end already floored
- # (`[-0.5000, 0.6000]`, `[0., 4.]`, `[0.0000, 2.5000]`), so a bound-only regex passes either way.
+ # torch's indexing error, so only the type is pinned.
+ ("planckian_select_past_the_table", "construction", IndexError, None),
+ # The scalar rows name the unclamped `[center - x, center + x]`, which only the scalar check
+ # reports; the range check behind it reports the floored range, so a bound-only regex passes either way.
(
"hue_scalar_above_half",
"construction",
ValueError,
- r"hue out of bounds\. Expected inside \(-0\.5, 0\.5\), got tensor\(\[-0\.6000, 0\.6000\]\)",
+ r"hue out of bounds\. Expected inside \(-0\.5, 0\.5\), got tensor\(\[-0\.60*,\s*0\.60*\]\)",
),
(
"brightness_scalar_above_two",
"construction",
ValueError,
- r"brightness out of bounds\. Expected inside \(0\.0, 2\.0\), got tensor\(\[-2\., 4\.\]\)",
+ r"brightness out of bounds\. Expected inside \(0\.0, 2\.0\), got tensor\(\[-2\.0*,\s*4\.0*\]\)",
),
(
"solarize_scalar_threshold_above_half",
"construction",
ValueError,
- r"thresholds out of bounds\. Expected inside \(0\.0, 1\.0\), got tensor\(\[-1\.5000, 2\.5000\]\)",
+ r"thresholds out of bounds\. Expected inside \(0\.0, 1\.0\), got tensor\(\[-1\.50*,\s*2\.50*\]\)",
),
],
)
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")
+ pytest.skip("CPU only: on CUDA the value assert is a device-side assert; kornia skips it on MPS")
factories = {
"sharpness_negative": lambda: K.RandomSharpness(-1.0, p=1.0),
"posterize_bits_above_eight": lambda: K.RandomPosterize(bits=9, p=1.0),
@@ -1688,7 +1183,6 @@ class TestIntensityColourConventions(BaseTester):
"contrast_negative": lambda: K.RandomContrast((-1.0, -1.0), p=1.0),
"saturation_negative": lambda: K.RandomSaturation((-1.0, -1.0), p=1.0),
"hue_above_half": lambda: K.RandomHue((0.6, 0.6), p=1.0),
- # The scalar forms overshoot the same bounds and raise the same error since #4563.
"hue_scalar_above_half": lambda: K.RandomHue(0.6, p=1.0),
"brightness_scalar_above_two": lambda: K.RandomBrightness(3.0, p=1.0),
"solarize_scalar_threshold_above_half": lambda: K.RandomSolarize(2.0, 0.1, p=1.0),
@@ -1709,16 +1203,11 @@ class TestIntensityColourConventions(BaseTester):
# 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] in __init__; RandomErasing bounds `value` alike, in its generator.
"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):
@@ -1729,12 +1218,9 @@ class TestIntensityColourConventions(BaseTester):
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)
- # Issue #4605: RandomSolarize admits the closed [-0.5, 0.5] for `additions`, and
- # kornia.enhance.solarize now accepts the same interval, so an endpoint range is applied on the
- # forward pass instead of raising `The addition must be in the open range (-0.5, 0.5)`.
+ # Issue #4605: RandomSolarize admits the closed [-0.5, 0.5] for `additions`, and an endpoint is applied.
@pytest.mark.parametrize("addition", [0.5, -0.5])
def test_convention_random_solarize_applies_an_additions_endpoint_4605(self, device, dtype, addition):
if device.type == "cuda":
@@ -1745,58 +1231,40 @@ class TestIntensityColourConventions(BaseTester):
out = aug(image)
self.assert_close(out, solarize(image, 0.5, addition))
- # 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`.
+ # `select_from` indexes the table like a Python sequence, so a negative entry counts from the end.
@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
)
- # A scalar magnitude is ``center Β± x`` floored at the parameter's lower bound and rejected past its
- # upper bound (the fix for #4563; the upper end used to be clamped silently, so RandomHue(0.7)
- # sampled from [-0.5, 0.5]). RandomSharpness is the class that depends on the floor: its scalar
- # form is the centred `[-x, x]` floored at 0, which is what makes `sharpness=0.5` mean `[0, 0.5]`.
- # Snippet used to generate expected:
- # for ctor in (lambda: K.RandomHue(0.7), lambda: K.RandomBrightness(3.0),
- # lambda: K.ColorJiggle(brightness=1.5), lambda: K.RandomSolarize(2.0, 0.1),
- # lambda: K.RandomMotionBlur(3, 45.0, 2.0), lambda: K.RandomJPEG(90.0)):
- # try: ctor(); print("ok")
- # except ValueError as e: print(e)
- # print(K.RandomContrast(1.5).contrast, K.RandomBrightness(0.5).brightness)
- # print(K.RandomSharpness(0.5).forward_parameters((2000, 1, 4, 4))["sharpness"].aminmax())
- # print(K.RandomJPEG(50.0)._param_generator.jpeg_quality_sampler.low)
- # executed 2026-09-16 (torch 2.14.0, cpu) -> `hue out of bounds. Expected inside (-0.5, 0.5), got
- # tensor([-0.7000, 0.7000]).`, `brightness out of bounds ... (0.0, 2.0), got tensor([-2., 4.])`,
- # `brightness out of bounds ... (0, 2), got tensor([-0.5000, 2.5000])`, `thresholds out of bounds ...
- # (0.0, 1.0), got tensor([-1.5000, 2.5000])`, `direction out of bounds ... (-1, 1), got
- # tensor([-2., 2.])`, `jpeg_quality out of bounds ... (1, 100), got tensor([-40., 140.])`;
- # `[0, 2.5]`, `[0.5, 1.5]`; sharpness in `[3.87e-05, 0.5]`; jpeg low `1`.
+ # A scalar magnitude is `center +- x`, floored at the parameter's lower bound and rejected past its upper
+ # bound. Each regex names the unclamped range, which only the scalar check reports.
@pytest.mark.device_agnostic
def test_convention_scalar_magnitude_floors_low_and_rejects_high(self):
for ctor, message in (
- (lambda: K.RandomHue(0.7, p=1.0), r"hue out of bounds\. .*got tensor\(\[-0\.7000, 0\.7000\]\)"),
- (lambda: K.RandomBrightness(3.0, p=1.0), r"brightness out of bounds\. .*got tensor\(\[-2\., 4\.\]\)"),
+ (lambda: K.RandomHue(0.7, p=1.0), r"hue out of bounds\. .*got tensor\(\[-0\.70*,\s*0\.70*\]\)"),
+ (
+ lambda: K.RandomBrightness(3.0, p=1.0),
+ r"brightness out of bounds\. .*got tensor\(\[-2\.0*,\s*4\.0*\]\)",
+ ),
(
lambda: K.ColorJiggle(brightness=1.5, p=1.0),
- r"brightness out of bounds\. .*got tensor\(\[-0\.5000, 2\.5000\]\)",
+ r"brightness out of bounds\. .*got tensor\(\[-0\.50*,\s*2\.50*\]\)",
),
(
lambda: K.RandomSolarize(2.0, 0.1, p=1.0),
- r"thresholds out of bounds\. .*got tensor\(\[-1\.5000, 2\.5000\]\)",
+ r"thresholds out of bounds\. .*got tensor\(\[-1\.50*,\s*2\.50*\]\)",
),
(
lambda: K.RandomMotionBlur(3, 45.0, 2.0, p=1.0),
- r"direction out of bounds\. .*got tensor\(\[-2\., 2\.\]\)",
+ r"direction out of bounds\. .*got tensor\(\[-2\.0*,\s*2\.0*\]\)",
+ ),
+ (
+ lambda: K.RandomJPEG(90.0, p=1.0),
+ r"jpeg_quality out of bounds\. .*got tensor\(\[-40\.0*,\s*140\.0*\]\)",
),
- (lambda: K.RandomJPEG(90.0, p=1.0), r"jpeg_quality out of bounds\. .*got tensor\(\[-40\., 140\.\]\)"),
):
- # Each regex names the parameter and the unclamped `[center - x, center + x]`, so it can only be
- # satisfied by `_range_bound`'s scalar raise and not by the trailing range check behind it.
with pytest.raises(ValueError, match=message):
ctor()
assert K.RandomContrast(1.5, p=1.0).contrast.tolist() == [0.0, 2.5]
@@ -1808,16 +1276,8 @@ class TestIntensityColourConventions(BaseTester):
jpeg = K.RandomJPEG(50.0, p=1.0)._param_generator
assert (float(jpeg.jpeg_quality_sampler.low), float(jpeg.jpeg_quality_sampler.high)) == (1.0, 100.0)
- # RandomClahe rejects an out-of-[0, 1] input with a message naming `equalize_clahe` and the range
- # (the fix for #4564; the raw indexing error of the histogram gather used to be all a caller got).
- # Not on CUDA, where an out-of-range index is a device-side assert that poisons the context. On MPS
- # `_lookup_value_check` runs the same condition, so the same named error is raised (#4600).
- # 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-16 (torch 2.14.0) -> cpu `RuntimeError: equalize_clahe expects input values in
- # [0, 1]. Scale the image into that range first, ...`; mps the same message since #4600 (before it,
- # `AcceleratorError: gather: index 487 is out of bounds for dimension 5 with size 256`).
+ # Issue #4564: RandomClahe rejects an out-of-[0, 1] input with kornia's error naming `equalize_clahe` and
+ # the range, on MPS as on the CPU.
def test_convention_random_clahe_out_of_range_error_names_the_range_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")
@@ -1826,16 +1286,10 @@ class TestIntensityColourConventions(BaseTester):
torch.manual_seed(_FORWARD_SEED)
with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]") as info:
_sync(K.RandomClahe(p=1.0)(image).device)
- # `match` alone would be satisfied by a message that never mentions how to fix it.
assert "image / 255.0" in str(info.value)
- # The rejection is one 8-bit code wide either side of [0, 1], not exactly at the bound: the guard is
- # the 256-entry lookup indexed with `(input * 255).long()`, so the admitted band is
- # `(-1/255, 1 + 1/255)`. Without this leg a `>=`/`<=` widening of the check survives every other pin.
- # Snippet used to generate expected:
- # for v in (1.0, 0.0, 1 + 0.5/255, 1 + 1.5/255, -0.5/255, -1.5/255):
- # img = torch.full((1, 1, 16, 16), 0.5); img[0, 0, 0, 0] = v; equalize_clahe(img)
- # executed 2026-09-16 (torch 2.14.0, cpu) -> admitted, admitted, admitted, RAISES, admitted, RAISES.
+ # The rejection is one 8-bit code wide either side of [0, 1]: the guard is the 256-entry lookup indexed
+ # with `(input * 255).long()`, so the admitted band is (-1/255, 1 + 1/255).
@pytest.mark.parametrize(
("value", "admitted"),
[
@@ -1848,123 +1302,75 @@ class TestIntensityColourConventions(BaseTester):
],
)
def test_convention_random_clahe_admitted_band_is_one_code_wide(self, device, dtype, value, admitted):
- if device.type in ("cuda", "mps"):
- pytest.skip("the value check runs on the CPU only: CUDA poisons the context, MPS skips it")
+ if device.type == "cuda":
+ pytest.skip("not on CUDA: the value assert is a device-side assert that poisons the context")
image = torch.full((1, 1, 16, 16), 0.5, device=device, dtype=dtype)
image[0, 0, 0, 0] = value
torch.manual_seed(_FORWARD_SEED)
if admitted:
- assert K.RandomClahe(p=1.0)(image).isfinite().all()
+ out = K.RandomClahe(p=1.0)(image)
+ _sync(image.device)
+ assert out.isfinite().all()
else:
with pytest.raises(RuntimeError, match=r"equalize_clahe expects input values in \[0, 1\]"):
- K.RandomClahe(p=1.0)(image)
+ _sync(K.RandomClahe(p=1.0)(image).device)
- # 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):
+ # Issue #2531: each axis of `grid_size` is tiled on its own and padded up to a whole number of tiles,
+ # so a grid works whether or not it divides the image, and an exactly dividing grid can still pad (the
+ # tile is rounded up to an even size). The padding is reflect at the end of each axis, so the
+ # pre-padded image cropped back reproduces the output bitwise.
+ @pytest.mark.parametrize(
+ ("grid_size", "size", "pad"),
+ [
+ ((3, 3), 10, (2, 2)),
+ ((4, 4), 20, (4, 4)),
+ ((5, 5), 20, (0, 0)),
+ ((4, 5), 20, (4, 0)),
+ ((3, 5), 30, (0, 0)),
+ ((1, 2), 10, (0, 2)),
+ ],
+ )
+ def test_convention_random_clahe_grid_pads_each_axis_to_whole_tiles_2531(self, device, dtype, grid_size, size, pad):
+ pad_rows, pad_cols = pad
+ if (pad_rows or pad_cols) 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")
+ if pad_rows or pad_cols:
+ padded = torch.nn.functional.pad(image, [0, pad_cols, 0, pad_rows], 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):
+ # At the default grid (8, 8) an image smaller than the grid gets kornia's named ValueError, and 9 x 9 is
+ # admitted. The 8 x 8 case in between is the #4783 wart below.
+ def test_convention_random_clahe_default_grid_rejects_a_smaller_image(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)
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.
+ with pytest.raises(ValueError, match=r"Cannot compute tiles on the image according to the given grid size"):
+ K.RandomClahe(p=1.0)(torch.rand(1, 1, 7, 7, device=device, dtype=dtype))
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: a NON-square `grid_size` works like a square one, and each axis is tiled on its own.
- # The `(4, 5)` / `20 x 20` row pads 4 rows and no columns although both entries divide the image,
- # `(1, 2)` / `10 x 10` pads 2 columns only, and `(3, 5)` / `30 x 30` pads nothing. As in the square
- # test above, the pre-padded image run through the same call and cropped back reproduces the output
- # bitwise, which pins the padding of each axis separately. Values are checked against an exact
- # reference in `tests/enhance/test_equalization.py`.
- # Snippet used to generate expected:
- # for gs, n, pad in (((4, 5), 20, (4, 0)), ((3, 5), 30, (0, 0)), ((1, 2), 10, (0, 2))):
- # x = torch.linspace(0, 1, n * n).reshape(1, 1, n, n)
- # torch.manual_seed(0); out = K.RandomClahe(grid_size=gs, p=1.0)(x)
- # p = torch.nn.functional.pad(x, [0, pad[1], 0, pad[0]], mode="reflect")
- # torch.manual_seed(0); print(torch.equal(out, K.RandomClahe(grid_size=gs, p=1.0)(p)[..., :n, :n]))
- # executed 2026-09-17 (torch 2.14.0, cpu, all four dtypes) -> `True` for all three rows; before the
- # fix each row raised `IndexError: shape mismatch: indexing tensors could not be broadcast together`.
- @pytest.mark.parametrize(
- ("grid_size", "size", "pad"), [((4, 5), 20, (4, 0)), ((3, 5), 30, (0, 0)), ((1, 2), 10, (0, 2))]
- )
- def test_convention_random_clahe_non_square_grid_works_2531(self, device, dtype, grid_size, size, pad):
- pad_rows, pad_cols = pad
- if (pad_rows or pad_cols) and not supports_reflect_padding(device, dtype):
+ # Issue #4783: an image exactly as large as the grid passes the named size check and then fails in
+ # the reflect padding with torch's raw error. A fix that handles it, or names it, flips this pin.
+ def test_wart_random_clahe_grid_sized_image_raises_a_raw_padding_error_4783(self, device, dtype):
+ if 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())
- assert not torch.equal(out, image)
- if pad_rows or pad_cols:
- padded = torch.nn.functional.pad(image, [0, pad_cols, 0, pad_rows], 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)
+ with pytest.raises(RuntimeError) as info:
+ _sync(K.RandomClahe(p=1.0)(torch.rand(1, 1, 8, 8, device=device, dtype=dtype)).device)
+ # A kornia error would name the grid or its tiles; torch's padding error does not.
+ assert not any(word in str(info.value).lower() for word in ("grid", "tile"))
- # RandomClahe equalizes each image with its OWN `clip_limit_factor` draw (the fix for #4572; the
- # whole batch used to take `float(params["clip_limit_factor"][0])`, the first sample's value).
- # Snippet used to generate expected:
- # torch.manual_seed(1234); x = torch.rand(8, 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([torch.equal(y[i:i+1], equalize_clahe(x[i:i+1], float(c[i]), (2, 2))) for i in range(8)])
- # print([torch.equal(y[i:i+1], equalize_clahe(x[i:i+1], float(c[0]), (2, 2))) for i in range(8)])
- # executed 2026-09-16 (torch 2.14.0, cpu) -> clips `[20.10, 30.84, 4.00, 5.72, 12.64, 25.55, 19.86,
- # 35.91]`; own-clip all True; first-clip True only for row 0.
+ # Issue #4572: each image is equalized with its own `clip_limit_factor` draw, not the first sample's.
@pytest.mark.device_agnostic
def test_convention_random_clahe_applies_each_clip_limit_to_its_own_image_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 the pin this replaces failed on 12 of seeds 0..199. A wide batch also makes the
- # "every row got the FIRST clip limit" arm below a real discriminator rather than a coincidence.
torch.manual_seed(_FIXTURE_SEED)
image = torch.rand(8, 1, 32, 32) ** 3
torch.manual_seed(_FORWARD_SEED)
@@ -1975,22 +1381,13 @@ class TestIntensityColourConventions(BaseTester):
for row in range(image.shape[0]):
own = equalize_clahe(image[row : row + 1], float(clip[row]), (2, 2))
assert torch.equal(out[row : row + 1], own), row
- # ... and not with the first sample's, which is what the defect did. Row 0 is excluded because
- # its own limit IS the first one, so it agrees under both contracts.
+ # ... and not with the first sample's.
first = int((clip - clip[0]).abs().argmax())
assert not torch.equal(out[first : first + 1], equalize_clahe(image[first : first + 1], float(clip[0]), (2, 2)))
- # When every draw is equal the class takes a single `equalize_clahe` call for the batch instead of
- # one per image. `same_on_batch=True` is the way to reach that branch on purpose; the result must be
- # indistinguishable from the per-image path, so this pins equivalence and not merely finiteness.
- # Snippet used to generate expected:
- # torch.manual_seed(0)
- # aug = K.RandomClahe(clip_limit=(0.5, 40.0), grid_size=(2, 2), p=1.0, same_on_batch=True)
- # y = aug(x); c = aug._params["clip_limit_factor"]
- # print((c == c[0]).all(), torch.equal(y, equalize_clahe(x, float(c[0]), (2, 2))))
- # executed 2026-09-16 (torch 2.14.0, cpu) -> `True True`.
+ # With `same_on_batch=True` every image is equalized with the one shared draw.
@pytest.mark.device_agnostic
- def test_convention_random_clahe_equal_clip_limits_take_the_batched_path_4572(self):
+ def test_convention_random_clahe_same_on_batch_shares_one_clip_limit(self):
torch.manual_seed(_FIXTURE_SEED)
image = torch.rand(8, 1, 32, 32) ** 3
torch.manual_seed(_FORWARD_SEED)
@@ -1999,22 +1396,11 @@ class TestIntensityColourConventions(BaseTester):
clip = aug._params["clip_limit_factor"]
assert bool((clip == clip[0]).all())
assert torch.equal(out, equalize_clahe(image, float(clip[0]), (2, 2)))
- # The per-image path must agree with it row by row, so the fast path is an optimization only.
for row in range(image.shape[0]):
assert torch.equal(out[row : row + 1], equalize_clahe(image[row : row + 1], float(clip[0]), (2, 2)))
- # Every class whose path goes through rgb_to_hsv is finite for a black pixel in every dtype,
- # float16 included (the fix for #4560: the saturation divisor was `max_rgb + eps` with `eps=1e-8`,
- # which underflows to `0` in float16, so a black pixel divided `0 / 0`). The guard substitutes a
- # safe divisor through `torch.where` rather than clamping, so it bounds the derivative too and not
- # just the value. Pinned here so the four docstrings that used to cite #4560 have an executable
- # anchor, and so the skip branches this file used to carry stay deleted.
- # Snippet used to generate expected:
- # for dt in (torch.float16, torch.float32, torch.bfloat16, torch.float64):
- # print(dt, K.RandomHue((0.1, 0.1), p=1.0)(torch.zeros(1, 3, 4, 4, dtype=dt)).isnan().any())
- # executed 2026-09-16 (torch 2.14.0, cpu) -> `False` in every dtype, and the same for
- # RandomSaturation((1.5, 1.5)), ColorJiggle(0, 0, 0, (0.1, 0.1)), ColorJiggle(0, 0, (1.5, 1.5), 0)
- # and ColorJitter(0, 0, 0, (0.1, 0.1)), for the black pixel and for (0, -0.5, -0.5) alike.
+ # Issue #4560: every class whose path goes through rgb_to_hsv is finite for a pixel whose largest
+ # channel is 0, in every dtype.
@pytest.mark.parametrize(
"name", ["RandomHue", "RandomSaturation", "ColorJiggle", "ColorJiggleSaturation", "ColorJitter"]
)
@@ -2023,47 +1409,26 @@ class TestIntensityColourConventions(BaseTester):
"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 it reached the
- # NaN without a hue step (ColorJitter's gray-subtraction saturation never did).
+ # ColorJiggle's saturation step is an HSV round trip too.
"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 divided
- # by that zero maximum too, while the saturation step's NaN also needed `max - min` to be 0.
+ # A black pixel, and a pixel whose largest channel is 0 without being black.
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))
assert bool(out.isfinite().all()), (name, dtype, out.tolist())
- # The guard is a `torch.where` and not a clamp, so the BACKWARD pass is finite too. A clamp would
- # bound the value while leaving the unbounded derivative to reach the backward pass -- the trap
- # AGENTS.md documents under #4229 -- and nothing in the forward pins above would notice.
- # Snippet used to generate expected:
- # for dt in (torch.float16, torch.float32):
- # x = torch.zeros(1, 3, 2, 2, dtype=dt, requires_grad=True)
- # rgb_to_hsv(x).sum().backward(); print(dt, x.grad.isfinite().all())
- # executed 2026-09-16 (torch 2.14.0, cpu) -> `True` for both.
- @pytest.mark.device_agnostic
- def test_convention_rgb_to_hsv_black_pixel_gradient_is_finite_4560(self):
- for torch_dtype in (torch.float16, torch.float32, torch.float64):
- image = torch.zeros(1, 3, 2, 2, dtype=torch_dtype, requires_grad=True)
- rgb_to_hsv(image).sum().backward()
- assert bool(image.grad.isfinite().all()), torch_dtype
-
- # 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"])
+ # An unbatched (C, H, W) input is promoted to (1, C, H, W), and `keepdim=True` returns the unbatched
+ # shape, across a colour, a normalization and a weather class.
+ @pytest.mark.parametrize("name", ["RandomBrightness", "Normalize", "RandomRain"])
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),
+ "Normalize": lambda keepdim: K.Normalize(mean=0.5, std=0.25, 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)
@@ -2072,15 +1437,7 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # RandomClahe's default fast path leaves the autograd graph; `slow_and_differentiable=True` keeps it.
@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_()
@@ -2105,12 +1462,7 @@ class TestIntensityColourConventions(BaseTester):
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`.
+ # A non-integral `bits` is accepted and rounded half to even.
@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):
@@ -2119,12 +1471,8 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # ColorJiggle skips a step when every drawn factor is neutral, so the channel count only has to suit the
+ # steps that run.
@pytest.mark.parametrize("channels", [1, 3, 4])
def test_convention_color_jiggle_skips_neutral_steps(self, device, dtype, channels):
torch.manual_seed(_FIXTURE_SEED)
@@ -2140,33 +1488,25 @@ class TestIntensityColourConventions(BaseTester):
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.
+
+ # Issue #4813: ColorJitter computes every step in the order, neutral or not, so the hue and saturation steps
+ # reject a channel count that the configuration never asks them to touch -- where ColorJiggle, above, and
+ # torchvision accept it. A fix that skips neutral steps flips the non-RGB legs; the RGB leg is the control.
+ @pytest.mark.parametrize("channels", [1, 3, 4])
+ def test_wart_color_jitter_computes_neutral_steps_4813(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)
+ if channels == 3:
+ assert K.ColorJitter(*factors, p=1.0)(image).shape == image.shape
+ else:
+ # Which neutral step raises first depends on the drawn order.
+ with pytest.raises((ValueError, ImageError)):
+ K.ColorJitter(*factors, p=1.0)(image)
+
+ # The erasing box is clamped from below as well as above: scale=(0, 0) still erases one pixel and a 1x1
+ # image is always erased in full.
@pytest.mark.device_agnostic
def test_convention_random_erasing_box_is_never_empty(self):
torch.manual_seed(_FORWARD_SEED)
@@ -2179,16 +1519,9 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # A `ratio` straddling 1 is a 50/50 mixture of [ratio[0], 1] and [1, ratio[1]], not uniform over it.
# 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.
+ # torch.manual_seed(0); p = g((200000, 3, 400, 400)); print((p["heights"] > p["widths"]).float().mean())
@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))
@@ -2199,10 +1532,7 @@ class TestIntensityColourConventions(BaseTester):
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.
+ # The realised box follows the draw only while the [1, H] x [1, W] clamp does not bite.
for height, width, expected in ((4, 256, 0.0), (256, 4, 1.0)):
torch.manual_seed(_FORWARD_SEED)
clamped = generator((20000, 3, height, width))
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index 64f98d7ae..e073d7fc4 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -672,6 +672,18 @@ class TestAdjustContrast(BaseTester):
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.enhance.adjust_contrast_with_mean_subtraction, (img, 2.0))
+ # Issue #4806: a non-RGB input blends with the mean of the whole batch, so a sample's result depends on
+ # its batch-mates; an RGB input uses each image's own mean. A per-image fix flips the one-channel leg.
+ @pytest.mark.parametrize(("channels", "contaminated"), [(1, True), (3, False)])
+ def test_wart_mean_subtraction_non_rgb_uses_the_batch_mean_4806(self, device, dtype, channels, contaminated):
+ bright = torch.full((1, channels, 2, 2), 0.8, device=device, dtype=dtype)
+ dark = torch.full((1, channels, 2, 2), 0.2, device=device, dtype=dtype)
+ factor = torch.tensor([0.5, 0.5], device=device, dtype=dtype)
+ alone = kornia.enhance.adjust_contrast_with_mean_subtraction(dark, factor[:1])
+ batched = kornia.enhance.adjust_contrast_with_mean_subtraction(torch.cat([bright, dark]), factor)[1:]
+ self.assert_close(alone, dark)
+ assert (not torch.allclose(batched, alone)) is contaminated
+
def test_dynamo(self, device, dtype, torch_optimizer):
B, C, H, W = 2, 3, 4, 4
img = torch.ones(B, C, H, W, device=device, dtype=dtype)
@@ -757,6 +769,16 @@ class TestAdjustBrightness(BaseTester):
img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
self.gradcheck(kornia.enhance.adjust_brightness_accumulative, (img, 2.0))
+ def test_accumulative_identity_factor_clamps_by_default(self, device, dtype):
+ # The multiplicative identity 1 still clamps into [0, 1] unless clip_output=False, and the module
+ # form always clamps.
+ 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(kornia.enhance.adjust_brightness_accumulative(values, 1.0), expected)
+ self.assert_close(kornia.enhance.AdjustBrightnessAccumulative(1.0)(values), expected)
+ self.assert_close(kornia.enhance.adjust_brightness_accumulative(values, 1.0, clip_output=False), values)
+ self.assert_close(kornia.enhance.adjust_brightness_accumulative(values, 0.0), torch.zeros_like(values))
+
class TestAdjustSigmoid(BaseTester):
@pytest.mark.parametrize("shape", [(3, 4, 4), (2, 3, 4, 4)])