π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): keep the derivative at exact 0 and 1 in the [0, 1] intensity clamps (#6594)
Dmytro Mishkin7200ba929f6a
diff --git a/changelog.d/6594.fixed.md b/changelog.d/6594.fixed.mdnew file mode 100644index 000000000..3605bd0a3--- /dev/null+++ b/changelog.d/6594.fixed.md@@ -0,0 +1 @@+The `[0, 1]` clamp of the `kornia.enhance` intensity ops, of the augmentations built on them, and of the linear and Gaussian illumination, plasma and snow augmentations now uses the one-sided derivative from inside the range at a result exactly on `0` or `1`, on every torch version. That derivative was 0 on torch 2.14 and later and nonzero on earlier releases: `adjust_brightness(x, 0.0)`, for example, returned its input with a zero gradient at black and white pixels. Plain `torch.clamp` still gives 0 on torch 2.14 and later; this is a Kornia convention, and a graph captured by `torch.jit.trace` or `torch.export` keeps the plain clamp. Values are unchanged, and forward-mode `adjust_gamma` now gives 0 at a black pixel for a gamma between 0 and 1 on every release.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 7440396e0..294cb5f3e 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -474,6 +474,10 @@ Enhancementadjusts contrast around an image mean. torchvision and PIL brightness, contrast and saturationcorrespond to the ``_accumulative``, ``_with_mean_subtraction`` and ``_with_gray_subtraction``variants.+- A result of these intensity ops exactly on ``0`` or ``1`` has no unique derivative. These ops use the+ one-sided derivative from inside the range on every torch version; plain ``torch.clamp`` gives 0 there+ from torch 2.14. A result outside the range gets the bound and a zero gradient. A graph captured by+ ``torch.jit.trace`` or ``torch.export`` keeps the plain clamp.- :func:`kornia.enhance.adjust_hue` and :func:`kornia.enhance.adjust_hue_raw` take radians(torchvision's ``hue_factor`` is ``factor / (2 * pi)``); the raw hue and saturation helpersoperate on HSV data.diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex c9d5eab02..047e70955 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -17,7 +17,6 @@from typing import Any, Dict, Optional, Sequence-import torchfrom torch import Tensorfrom kornia.augmentation._2d.base import RigidAffineAugmentationBase2D, _input_metadata_only@@ -25,29 +24,6 @@ from kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints-def _clamp_unit_range(input: Tensor) -> Tensor:- """Clamp ``input`` into ``[0, 1]`` with an identity gradient on the closed range.-- ``torch.clamp``'s derivative at a bound is ``1`` on torch 2.5.1 and 2.9.1 and ``0`` on 2.14.0, and valid images- often hold exact ``0`` and ``1`` pixels. The values inside ``[0, 1]`` are therefore taken from ``input`` itself,- so they keep their gradient on every torch version; values outside get the bound and a zero gradient.-- The values always equal ``input.clamp(0, 1)``, ``NaN`` included, so a call that records no gradient and- carries no forward-mode tangent is that single clamp. Otherwise, select ``input`` where the clamp left it- unchanged: one comparison against the clamped copy instead of two bound comparisons and their conjunction.- Forward-mode tangents must keep the identity derivative even inside ``torch.no_grad()``. The sign of a zero is- not part of the contract: ``clamp`` returns ``+0.0`` for ``-0.0`` on MPS and under Inductor (CPU and CUDA),- while eager CPU and CUDA keep ``-0.0``.- """- clamped = input.clamp(0.0, 1.0)- if (- not (torch.is_grad_enabled() and input.requires_grad)- and torch.autograd.forward_ad.unpack_dual(input).tangent is None- ):- return clamped- return torch.where(clamped == input, input, clamped)--class _PicklableCompileMixin:"""Keep a module picklable after its own ``compile()`` replaced callables with ``torch.compile``d ones.diff --git a/kornia/augmentation/_2d/intensity/brightness.py b/kornia/augmentation/_2d/intensity/brightness.pyindex 3e4b5dde2..cf4c14bcc 100644--- a/kornia/augmentation/_2d/intensity/brightness.py+++ b/kornia/augmentation/_2d/intensity/brightness.py@@ -20,9 +20,9 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.augmentation.utils.param_validation import _learnable_range_bound, _load_unowned_learnable_range-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingfrom kornia.enhance.adjust import adjust_brightnessdiff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.pyindex 2171f3dca..f009adf6b 100644--- a/kornia/augmentation/_2d/intensity/clahe.py+++ b/kornia/augmentation/_2d/intensity/clahe.py@@ -22,7 +22,8 @@ from typing import Any, Optionalimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_rangefrom kornia.enhance.equalization import _equalize_clahediff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.pyindex 9b54489a5..05b07bb92 100644--- a/kornia/augmentation/_2d/intensity/color_jiggle.py+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py@@ -22,8 +22,8 @@ from typing import Any, Callable, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range-from kornia.core.utils import _to_device_nonblocking+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingfrom kornia.enhance import adjust_brightness, adjust_contrast, adjust_hue, adjust_saturationdiff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex 15729b573..dfd804c10 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -22,11 +22,7 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import (- IntensityAugmentationBase2D,- _clamp_unit_range,- _PicklableCompileMixin,-)+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _PicklableCompileMixinfrom kornia.augmentation._2d.intensity.color_jiggle import (_adjust_hue,_apply_order_cond,@@ -34,6 +30,7 @@ from kornia.augmentation._2d.intensity.color_jiggle import (_dispatch_color_steps,_Steps,)+from kornia.core.utils import _clamp_unit_rangefrom kornia.enhance import (adjust_brightness_accumulative,adjust_contrast_with_mean_subtraction,diff --git a/kornia/augmentation/_2d/intensity/contrast.py b/kornia/augmentation/_2d/intensity/contrast.pyindex 35db46f16..c994e3127 100644--- a/kornia/augmentation/_2d/intensity/contrast.py+++ b/kornia/augmentation/_2d/intensity/contrast.py@@ -20,9 +20,9 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.augmentation.utils.param_validation import _learnable_range_bound, _load_unowned_learnable_range-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingfrom kornia.enhance.adjust import adjust_contrastdiff --git a/kornia/augmentation/_2d/intensity/dissolving.py b/kornia/augmentation/_2d/intensity/dissolving.pyindex 70d43cedd..b5df1d785 100644--- a/kornia/augmentation/_2d/intensity/dissolving.py+++ b/kornia/augmentation/_2d/intensity/dissolving.py@@ -20,7 +20,8 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_rangefrom kornia.filters import StableDiffusionDissolvingdiff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.pyindex 156174a2f..bb0484226 100644--- a/kornia/augmentation/_2d/intensity/equalize.py+++ b/kornia/augmentation/_2d/intensity/equalize.py@@ -19,7 +19,8 @@ from typing import Any, Dict, Optionalfrom torch import Tensor-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_rangefrom kornia.enhance import equalizediff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.pyindex 5bf503e16..3f40e34d2 100644--- a/kornia/augmentation/_2d/intensity/gamma.py+++ b/kornia/augmentation/_2d/intensity/gamma.py@@ -20,8 +20,8 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range-from kornia.core.utils import _to_device_nonblocking+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingfrom kornia.enhance.adjust import adjust_gammadiff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.pyindex c72f9f5d4..fbf751063 100644--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py@@ -21,14 +21,11 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torch-from kornia.augmentation._2d.intensity.base import (- IntensityAugmentationBase2D,- _clamp_unit_range,- _PicklableCompileMixin,-)+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _PicklableCompileMixinfrom kornia.augmentation.random_generator._2d import GaussianIlluminationGeneratorfrom kornia.core.check import KORNIA_CHECK-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblocking+from kornia.enhance.adjust import _clip_unit_freshdef _apply_gaussian_illumination(@@ -44,7 +41,7 @@ def _apply_gaussian_illumination(# Out-of-place add: in-place would mutate the caller's tensor and corrupt# the non-transformed branch, which shares the same input.- return input.add(gradient).clamp_(0, 1)+ return _clip_unit_fresh(input.add(gradient))class RandomGaussianIllumination(_PicklableCompileMixin, IntensityAugmentationBase2D):diff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.pyindex cb045ff96..0eff9a6e8 100644--- a/kornia/augmentation/_2d/intensity/hue.py+++ b/kornia/augmentation/_2d/intensity/hue.py@@ -21,9 +21,9 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.augmentation.utils.param_validation import _learnable_range_bound, _load_unowned_learnable_range-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingfrom kornia.enhance.adjust import adjust_huediff --git a/kornia/augmentation/_2d/intensity/jpeg.py b/kornia/augmentation/_2d/intensity/jpeg.pyindex b838c8414..d3e3fdb0f 100644--- a/kornia/augmentation/_2d/intensity/jpeg.py+++ b/kornia/augmentation/_2d/intensity/jpeg.py@@ -20,7 +20,8 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_rangefrom kornia.enhance import jpeg_codec_differentiablediff --git a/kornia/augmentation/_2d/intensity/linear_illumination.py b/kornia/augmentation/_2d/intensity/linear_illumination.pyindex 58f8524e7..dd7401317 100644--- a/kornia/augmentation/_2d/intensity/linear_illumination.py+++ b/kornia/augmentation/_2d/intensity/linear_illumination.py@@ -19,10 +19,10 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torch-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.augmentation.random_generator._2d import LinearCornerIlluminationGenerator, LinearIlluminationGeneratorfrom kornia.core.check import KORNIA_CHECK-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingclass RandomLinearIllumination(IntensityAugmentationBase2D):@@ -142,7 +142,7 @@ class RandomLinearIllumination(IntensityAugmentationBase2D):) -> torch.Tensor:r"""Apply random gaussian gradient illumination to the input image."""input = _clamp_unit_range(input)- return input.add(_to_device_nonblocking(params["gradient"], input.device, input.dtype)).clamp(0, 1)+ return _clamp_unit_range(input.add(_to_device_nonblocking(params["gradient"], input.device, input.dtype)))class RandomLinearCornerIllumination(IntensityAugmentationBase2D):@@ -262,4 +262,4 @@ class RandomLinearCornerIllumination(IntensityAugmentationBase2D):) -> torch.Tensor:r"""Apply random gaussian gradient illumination to the input image."""input = _clamp_unit_range(input)- return input.add(_to_device_nonblocking(params["gradient"], input.device, input.dtype)).clamp(0, 1)+ return _clamp_unit_range(input.add(_to_device_nonblocking(params["gradient"], input.device, input.dtype)))diff --git a/kornia/augmentation/_2d/intensity/planckian_jitter.py b/kornia/augmentation/_2d/intensity/planckian_jitter.pyindex b01563f0e..5d45ba056 100644--- a/kornia/augmentation/_2d/intensity/planckian_jitter.py+++ b/kornia/augmentation/_2d/intensity/planckian_jitter.py@@ -20,9 +20,9 @@ from typing import Any, Dict, List, Optional, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingdef get_planckian_coeffs(mode: str) -> torch.Tensor:diff --git a/kornia/augmentation/_2d/intensity/plasma.py b/kornia/augmentation/_2d/intensity/plasma.pyindex 4930f1ba1..f7bc7c6dc 100644--- a/kornia/augmentation/_2d/intensity/plasma.py+++ b/kornia/augmentation/_2d/intensity/plasma.py@@ -20,9 +20,10 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.contrib import diamond_square-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblocking+from kornia.enhance.adjust import _clip_unit_freshdef _generate_plasma(@@ -123,7 +124,7 @@ class RandomPlasmaBrightness(IntensityAugmentationBase2D):intensity = _to_device_nonblocking(params["intensity"], image.device, image.dtype).view(-1, 1, 1, 1)brightness_map = 2 * _plasma_for_input(params["plasma"], image) - 1brightness_map = brightness_map * intensity- return (image + brightness_map).clamp_(0, 1)+ return _clip_unit_fresh(image + brightness_map)class RandomPlasmaContrast(IntensityAugmentationBase2D):@@ -190,7 +191,7 @@ class RandomPlasmaContrast(IntensityAugmentationBase2D):) -> torch.Tensor:image = _clamp_unit_range(image)contrast_map = 4 * _plasma_for_input(params["plasma"], image)- return ((image - 0.5) * contrast_map + 0.5).clamp_(0, 1)+ return _clip_unit_fresh((image - 0.5) * contrast_map + 0.5)class RandomPlasmaShadow(IntensityAugmentationBase2D):@@ -271,4 +272,4 @@ class RandomPlasmaShadow(IntensityAugmentationBase2D):shade_quantity = _to_device_nonblocking(params["shade_quantity"], image.device, image.dtype).view(-1, 1, 1, 1)shade_map = _plasma_for_input(params["plasma"], image)shade_map = (shade_map < shade_quantity).to(image.dtype) * shade_intensity- return (image + shade_map).clamp_(0, 1)+ return _clip_unit_fresh(image + shade_map)diff --git a/kornia/augmentation/_2d/intensity/posterize.py b/kornia/augmentation/_2d/intensity/posterize.pyindex 7656eb46c..1c276a234 100644--- a/kornia/augmentation/_2d/intensity/posterize.py+++ b/kornia/augmentation/_2d/intensity/posterize.py@@ -20,8 +20,8 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range-from kornia.core.utils import _to_device_nonblocking+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingfrom kornia.enhance import posterizediff --git a/kornia/augmentation/_2d/intensity/random_rgb_shift.py b/kornia/augmentation/_2d/intensity/random_rgb_shift.pyindex aec537d0f..e25fd989c 100644--- a/kornia/augmentation/_2d/intensity/random_rgb_shift.py+++ b/kornia/augmentation/_2d/intensity/random_rgb_shift.py@@ -20,7 +20,8 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_rangefrom kornia.enhance import shift_rgbdiff --git a/kornia/augmentation/_2d/intensity/random_snow.py b/kornia/augmentation/_2d/intensity/random_snow.pyindex 2143edbf7..44cdb2911 100644--- a/kornia/augmentation/_2d/intensity/random_snow.py+++ b/kornia/augmentation/_2d/intensity/random_snow.py@@ -20,10 +20,10 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.color import hls_to_rgb, rgb_to_hlsfrom kornia.core.check import KORNIA_CHECK-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingclass RandomSnow(IntensityAugmentationBase2D):@@ -104,7 +104,7 @@ class RandomSnow(IntensityAugmentationBase2D):mask[:, 1, :, :] = torch.where(input_HLS[:, 1, :, :] < snow_coefficient[:, 0, :, :], 1, 0)# Increase Light channel of the image by given brightness for areas based on snow coefficient.- new_light = (input_HLS * mask * brightness).clamp(min=0.0, max=1.0)+ new_light = _clamp_unit_range(input_HLS * mask * brightness)input_HLS = input_HLS * (1 - mask) + new_lightreturn _clamp_unit_range(hls_to_rgb(input_HLS))diff --git a/kornia/augmentation/_2d/intensity/saturation.py b/kornia/augmentation/_2d/intensity/saturation.pyindex 39263c206..5555aeb8b 100644--- a/kornia/augmentation/_2d/intensity/saturation.py+++ b/kornia/augmentation/_2d/intensity/saturation.py@@ -20,9 +20,9 @@ from typing import Any, Dict, Optional, Tupleimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.augmentation.utils.param_validation import _learnable_range_bound, _load_unowned_learnable_range-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingfrom kornia.enhance.adjust import adjust_saturationdiff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.pyindex f07c51430..e43ea780b 100644--- a/kornia/augmentation/_2d/intensity/sharpness.py+++ b/kornia/augmentation/_2d/intensity/sharpness.py@@ -20,8 +20,9 @@ from typing import Any, Dict, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2Dfrom kornia.augmentation.utils import _check_filter_min_size+from kornia.core.utils import _clamp_unit_rangefrom kornia.enhance import sharpnessdiff --git a/kornia/augmentation/_2d/intensity/solarize.py b/kornia/augmentation/_2d/intensity/solarize.pyindex add8cd774..98628353b 100644--- a/kornia/augmentation/_2d/intensity/solarize.py+++ b/kornia/augmentation/_2d/intensity/solarize.py@@ -20,7 +20,8 @@ from typing import Any, Dict, List, Optional, Tuple, Unionimport torchfrom kornia.augmentation import random_generator as rg-from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D, _clamp_unit_range+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D+from kornia.core.utils import _clamp_unit_rangefrom kornia.enhance import solarizediff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.pyindex b9d25620d..272193c7f 100644--- a/kornia/augmentation/auto/operations/ops.py+++ b/kornia/augmentation/auto/operations/ops.py@@ -20,12 +20,11 @@ from typing import Any, Dict, Optional, Tupleimport torchimport kornia.augmentation as K-from kornia.augmentation._2d.intensity.base import _clamp_unit_rangefrom kornia.augmentation._2d.intensity.brightness import RandomBrightnessfrom kornia.augmentation._2d.intensity.contrast import RandomContrastfrom kornia.augmentation._2d.intensity.saturation import RandomSaturationfrom kornia.augmentation.auto.operations.base import OperationBase-from kornia.core.utils import _to_device_nonblocking+from kornia.core.utils import _clamp_unit_range, _to_device_nonblockingfrom kornia.enhance import (adjust_brightness_accumulative,adjust_contrast_with_mean_subtraction,diff --git a/kornia/core/utils.py b/kornia/core/utils.pyindex acd0f342c..42575fc2a 100644--- a/kornia/core/utils.py+++ b/kornia/core/utils.py@@ -522,13 +522,44 @@ def _needs_derivatives(input: torch.Tensor) -> bool:"""Return whether autograd can ask for a derivative through ``input``.Reverse mode needs grad mode and an ``input`` that requires grad; forward mode (``torch.func.jvp``, ``jacfwd``,- ``torch.autograd.forward_ad``) gives ``input`` a tangent instead, whatever the grad mode.+ ``torch.autograd.forward_ad``) gives ``input`` a tangent instead, whatever the grad mode. TorchScript has no forward+ mode and cannot compile the query."""if torch.is_grad_enabled() and input.requires_grad:return True+ if torch.jit.is_scripting():+ return Falsereturn torch.autograd.forward_ad.unpack_dual(input).tangent is not None+def _clamp_unit_range(input: torch.Tensor) -> torch.Tensor:+ """Clamp ``input`` into ``[0, 1]`` with an identity gradient on the closed range.++ A clamp has no derivative at a bound: its one-sided derivatives are 0 and 1. torch returned 1 up to 2.13 and returns+ 0 from 2.14, its documented minimum-norm rule (pytorch/pytorch#191142). Kornia uses the derivative from inside the+ range on every version: at an identity factor it is the only one on the documented input domain, and it lets a pixel+ on a bound move back. Values outside the range get the bound and a zero gradient.++ The values always equal ``input.clamp(0, 1)``, ``NaN`` included, so a call that records no gradient and+ carries no forward-mode tangent is that single clamp. Otherwise, select ``input`` where the clamp left it+ unchanged: one comparison against the clamped copy instead of two bound comparisons and their conjunction.+ Forward-mode tangents must keep the identity derivative even inside ``torch.no_grad()``. The sign of a zero is+ not part of the contract: ``clamp`` returns ``+0.0`` for ``-0.0`` on MPS, under Inductor (CPU and CUDA) and in the+ SIMD lanes of eager arm64 CPU, while eager x86 CPU and CUDA keep ``-0.0``.+ """+ # A captured graph keeps the plain clamp: ``torch.jit.trace``'s check reruns under ``no_grad``, and an inference+ # graph has no use for the selection. The gradient through a traced module then follows ``torch.clamp``.+ # Selecting without a derivative costs 5 times a plain clamp or more on the CPU and about 3 to 4 times on CUDA+ # (i7-14700K, RTX 4090).+ if _is_tracing_or_exporting() or not _needs_derivatives(input):+ return input.clamp(0.0, 1.0)+ # The clamp records nothing: ``where`` takes it only outside the range, where the gradient is zero anyway, and the+ # backward of a recorded clamp made a forward and backward pass 1.7 to 2.5 times as slow on the CPU and 1.2 to 1.7+ # times on CUDA.+ clamped = input.detach().clamp(0.0, 1.0)+ return torch.where(clamped == input, input, clamped)++def _symmetric_eigenvector(input: torch.Tensor, eigenvalues: torch.Tensor, eigenvectors: torch.Tensor, index: Union[int, torch.Tensor]) -> torch.Tensor:diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 3d439c173..b9b17bff8 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -35,16 +35,25 @@ from kornia.core.check import ()from kornia.core.exceptions import TypeCheckErrorfrom kornia.core.ops import _device_literal-from kornia.core.utils import _normalize_to_float32_or_float64, _to_device_nonblocking, is_compiling+from kornia.core.utils import (+ _clamp_unit_range,+ _is_tracing_or_exporting,+ _needs_derivatives,+ _normalize_to_float32_or_float64,+ _to_device_nonblocking,+ is_compiling,+)from kornia.image.utils import _to_bcdhw, _to_bchwdef _clip_unit_fresh(image: torch.Tensor) -> torch.Tensor:- """Clamp a tensor this module just allocated into ``[0, 1]``, in place when no gradient is recorded.+ """Clamp a tensor this module just allocated into ``[0, 1]``, in place when no derivative can be asked for.- The values equal ``image.clamp(0, 1)``. Without a recorded gradient the clamp reuses the fresh buffer instead of- allocating another image-sized one: at batch 32 that third 25 MB temporary per call made glibc trim and re-fault- the heap on every call. Only call it on a tensor no caller can see.+ The values equal ``image.clamp(0, 1)``. Without a recorded gradient or a forward-mode tangent the clamp reuses the+ fresh buffer instead of allocating another image-sized one: at batch 32 that third 25 MB temporary per call made+ glibc trim and re-fault the heap on every call. With one it is ``_clamp_unit_range``, whose derivative at a bound+ does not depend on the torch version. A captured graph takes the same path whatever the grad mode, so that+ ``torch.jit.trace``'s check under ``no_grad`` records the same clamp. Only call it on a tensor no caller can see.An integer tensor, which reaches here only with checks disabled, keeps the out-of-place clamp: the float boundspromote its result to the default float dtype, which an in-place clamp cannot do. So does a tensor under a function@@ -54,11 +63,12 @@ def _clip_unit_fresh(image: torch.Tensor) -> torch.Tensor:if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guardif (image.is_floating_point()- and not (torch.is_grad_enabled() and image.requires_grad)+ and not _is_tracing_or_exporting()+ and not _needs_derivatives(image)and not torch._C._are_functorch_transforms_active()):return image.clamp_(min=0.0, max=1.0)- return image.clamp(min=0.0, max=1.0)+ return _clamp_unit_range(image)def _check_floating_image(image: torch.Tensor, op: str) -> None:@@ -154,7 +164,9 @@ def adjust_saturation_raw(image: torch.Tensor, factor: Union[float, torch.Tensorh, s, v = torch.chunk(image, chunks=3, dim=-3)# transform the hue value and appl module- s_out: torch.Tensor = torch.clamp(s * factor, min=0, max=1)+ s_out: torch.Tensor = s * factor+ # Integer bounds keep the dtype of an integer image, which this HSV primitive does not reject.+ s_out = _clamp_unit_range(s_out) if s_out.is_floating_point() else s_out.clamp(min=0, max=1)# pack back back the corrected hueout: torch.Tensor = torch.cat([h, s_out, v], dim=-3)@@ -217,7 +229,7 @@ def adjust_saturation_with_gray_subtraction(image: torch.Tensor, factor: Union[fx_adjusted: torch.Tensor = (1 - factor) * x_other + factor * image# clamp the output- out: torch.Tensor = torch.clamp(x_adjusted, 0.0, 1.0)+ out: torch.Tensor = _clamp_unit_range(x_adjusted)return out@@ -287,7 +299,7 @@ def adjust_saturation(image: torch.Tensor, factor: Union[float, torch.Tensor]) -delta = max_rgb - min_rgbvalue_divisor = torch.where(max_rgb == 0, torch.ones_like(max_rgb), max_rgb + 1e-8)saturation = delta / value_divisor- saturation = torch.clamp(saturation * factor, min=0, max=1)+ saturation = _clamp_unit_range(saturation * factor)adjusted_delta = max_rgb * saturationdelta_divisor = torch.where(delta == 0, torch.ones_like(delta), delta)@@ -454,7 +466,7 @@ def adjust_gamma(if input.dtype == torch.float32:gamma = struct.unpack("f", struct.pack("f", gamma))[0]gain = struct.unpack("f", struct.pack("f", gain))[0]- if torch.is_grad_enabled() and input.requires_grad and 0.0 < gamma < 1.0:+ if 0.0 < gamma < 1.0 and _needs_derivatives(input):# As in the tensor path below.black = input == 0power = torch.where(@@ -462,7 +474,7 @@ def adjust_gamma()else:power = input.pow(gamma)- return (power * gain).clamp(0.0, 1.0)+ return _clamp_unit_range(power * gain)if isinstance(gamma, float):gamma = torch.tensor([gamma], device=input.device, dtype=input.dtype)@@ -486,10 +498,10 @@ def adjust_gamma(gain = _make_factor_broadcastable(gain, input)# Apply the gamma correction. For 0 < gamma < 1, x ** gamma has an infinite derivative at x = 0, which the clamp- # below turns into NaN (inf before torch 2.14). Black pixels then take the power of a safe base, keep their value- # 0 ** gamma = 0 and get a zero gradient; gamma = 0 keeps 0 ** 0 = 1. The values are the same either way, so the- # masking only runs when autograd records a gradient for the input.- if torch.is_grad_enabled() and input.requires_grad:+ # below would pass on. Black pixels then take the power of a safe base, keep their value 0 ** gamma = 0 and get a+ # zero gradient; gamma = 0 keeps 0 ** 0 = 1. The values are the same either way, so the masking only runs when+ # autograd can ask for a derivative through the input. The mask costs 5 times or more without a derivative.+ if _needs_derivatives(input):black = (input == 0) & (gamma > 0) & (gamma < 1)power = torch.where(black, torch.zeros_like(input), torch.pow(torch.where(black, torch.ones_like(input), input), gamma)@@ -499,7 +511,7 @@ def adjust_gamma(x_adjust: torch.Tensor = gain * power# Truncate between pixel values- out: torch.Tensor = torch.clamp(x_adjust, 0.0, 1.0)+ out: torch.Tensor = _clamp_unit_range(x_adjust)return out@@ -633,7 +645,7 @@ def adjust_contrast_with_mean_subtraction(image: torch.Tensor, factor: Union[flo# Apply contrast factor subtracting the meanimg_adjust: torch.Tensor = image * factor + img_mean * (1 - factor)- return img_adjust.clamp(min=0.0, max=1.0)+ return _clamp_unit_range(img_adjust)def adjust_brightness(@@ -761,7 +773,7 @@ def adjust_brightness_accumulative(# truncate between pixel valuesif clip_output:- img_adjust = img_adjust.clamp(min=0.0, max=1.0)+ img_adjust = _clamp_unit_range(img_adjust)return img_adjust@@ -849,7 +861,7 @@ def adjust_log(image: torch.Tensor, gain: float = 1, inv: bool = False, clip_out# truncate between pixel valuesif clip_output:- img_adjust = img_adjust.clamp(min=0.0, max=1.0)+ img_adjust = _clamp_unit_range(img_adjust)return img_adjust@@ -984,8 +996,7 @@ def solarize(# tensor (`for x in additions` breaks the graph); numerically identical.additions = _to_device_nonblocking(additions, input.device).to(input.dtype)additions = additions.view([-1] + [1] * (input.ndim - 1))- input = input + additions- input = input.clamp(0.0, 1.0)+ input = _clamp_unit_range(input + additions)return _solarize(input, thresholds)@@ -1173,7 +1184,7 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.# This shall be equivalent to depthwise conv2d:# Ref: https://discuss.pytorch.org/t/depthwise-and-separable-convolutions-in-pytorch/7315/2degenerate = torch.nn.functional.conv2d(input, kernel, bias=None, stride=1, groups=input.size(1))- degenerate = torch.clamp(degenerate, 0.0, 1.0)+ degenerate = _clamp_unit_range(degenerate)# For the borders of the resulting image, fill in the values of the original image.mask = torch.ones_like(degenerate)@@ -1188,7 +1199,7 @@ def sharpness(input: torch.Tensor, factor: Union[float, torch.Tensor]) -> torch.# bites for extrapolation, matching the previous behavior.if len(factor.size()) != 0:factor = factor.view(-1, *([1] * (result.dim() - 1)))- return torch.clamp(result + (input - result) * factor, 0.0, 1.0).reshape(input_shape)+ return _clamp_unit_range(result + (input - result) * factor).reshape(input_shape)def _scale_channel_batched(input: torch.Tensor) -> torch.Tensor:diff --git a/kornia/enhance/shift_rgb.py b/kornia/enhance/shift_rgb.pyindex e91b3d79a..14682348a 100644--- a/kornia/enhance/shift_rgb.py+++ b/kornia/enhance/shift_rgb.py@@ -20,7 +20,7 @@ import torchfrom kornia.core.check import KORNIA_CHECK_IS_COLOR, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.core.utils import _to_device_nonblocking-from kornia.enhance.adjust import _check_floating_image+from kornia.enhance.adjust import _check_floating_image, _clip_unit_freshdef shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor, b_shift: torch.Tensor) -> torch.Tensor:@@ -41,4 +41,6 @@ def shift_rgb(image: torch.Tensor, r_shift: torch.Tensor, g_shift: torch.Tensor,shifts = [r_shift, g_shift, b_shift]shift = _to_device_nonblocking(torch.stack(shifts, dim=1).view(-1, 3, 1, 1), image.device, image.dtype)- return (image + shift).clamp_(min=0, max=1)+ shifted = image + shift+ # An integer image reaches here only with checks disabled, and integer bounds keep its dtype.+ return _clip_unit_fresh(shifted) if shifted.is_floating_point() else shifted.clamp_(min=0, max=1)diff --git a/tests/augmentation/test_auto_operation.py b/tests/augmentation/test_auto_operation.pyindex 0c153b2ea..c520022cb 100644--- a/tests/augmentation/test_auto_operation.py+++ b/tests/augmentation/test_auto_operation.py@@ -564,6 +564,18 @@ def test_auto_enhancer_keeps_magnitude_gradient_6253(operation, device, dtype):assert aug.op.p_batch == 1.0[email protected]("operation", [ops.Brightness, ops.Contrast, ops.Saturate])+def test_auto_enhancer_keeps_the_identity_gradient_at_exact_0_and_1_6296(operation, device, dtype):+ """Return the input at the neutral magnitude with an identity gradient on black and white pixels too."""+ row = torch.tensor([0.0, 0.25, 0.5, 1.0], device=device, dtype=dtype).view(1, 1, 1, 4)+ image = row.expand(1, 3, 4, 4).contiguous().requires_grad_()+ aug = operation(initial_magnitude=1.0, initial_probability=1.0).to(dtype=dtype)+ out = aug(image)+ (gradient,) = torch.autograd.grad(out.sum(), image)+ assert_close(out, image)+ assert_close(gradient, torch.ones_like(image))++@pytest.mark.parametrize("policy", ["auto", "rand", "trivial"])def test_policy_brightness_uses_multiplicative_factor_6253(policy, device, dtype):"""Use multiplicative brightness through all three policy containers."""diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex 661d32d03..e5bebcd71 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -24,10 +24,10 @@ import pytestimport torchimport kornia.augmentation as K-from kornia.augmentation._2d.intensity.base import _clamp_unit_rangefrom kornia.augmentation.random_generator import PosterizeGenerator, RectangleEraseGeneratorfrom kornia.core._compat import torch_version_gefrom kornia.core.exceptions import AsyncCheckError, BaseError, ShapeError+from kornia.core.utils import _clamp_unit_rangefrom kornia.enhance import (adjust_brightness,adjust_contrast,@@ -367,8 +367,7 @@ class TestIntensityValueRangeConventions(BaseTester):assert torch.equal(out[1], image[1])out.sum().backward()assert torch.isfinite(image.grad).all()- # Exclude x=1, where adjust_gamma's clamp derivative differs across torch releases.- self.assert_close(image.grad[0, ..., :2], 0.5 / image[0, ..., :2].detach().sqrt())+ self.assert_close(image.grad[0], 0.5 / image[0].detach().sqrt())self.assert_close(image.grad[1], torch.ones_like(image.grad[1]))@pytest.mark.parametrize(@@ -1625,6 +1624,74 @@ class TestIntensityInputClamping(BaseTester):out.sum().backward()self.assert_close(image.grad, torch.ones_like(image))+ # The kernels of these classes clamp their result with the same helper as the input clamp (#6296), so a neutral+ # factor leaves the identity gradient at exact 0 and 1 on every torch version.+ @pytest.mark.parametrize(+ "factory",+ [+ lambda: K.RandomBrightness((1.0, 1.0), p=1.0),+ lambda: K.RandomContrast((1.0, 1.0), p=1.0),+ lambda: K.RandomGamma((1.0, 1.0), (1.0, 1.0), p=1.0),+ lambda: K.RandomSharpness((1.0, 1.0), p=1.0),+ lambda: K.RandomRGBShift(0.0, 0.0, 0.0, p=1.0),+ lambda: K.RandomLinearIllumination(gain=(0.0, 0.0), sign=(1.0, 1.0), p=1.0),+ lambda: K.RandomLinearCornerIllumination(gain=(0.0, 0.0), sign=(1.0, 1.0), p=1.0),+ lambda: K.RandomGaussianIllumination(gain=(0.0, 0.0), sign=(1.0, 1.0), p=1.0),+ lambda: K.RandomPlasmaBrightness(intensity=(0.0, 0.0), p=1.0),+ lambda: K.RandomPlasmaShadow(shade_intensity=(0.0, 0.0), p=1.0),+ ],+ ids=[+ "RandomBrightness",+ "RandomContrast",+ "RandomGamma",+ "RandomSharpness",+ "RandomRGBShift",+ "RandomLinearIllumination",+ "RandomLinearCornerIllumination",+ "RandomGaussianIllumination",+ "RandomPlasmaBrightness",+ "RandomPlasmaShadow",+ ],+ )+ def test_convention_kernel_clamp_keeps_gradient_at_unit_range_bounds_6296(self, device, dtype, factory):+ row = torch.tensor([0.0, 0.25, 0.75, 1.0], device=device, dtype=dtype).view(1, 1, 1, 4)+ image = row.expand(1, 3, 4, 4).contiguous().requires_grad_()+ out = factory()(image)+ self.assert_close(out, image.detach())+ (grad,) = torch.autograd.grad(out.sum(), image)+ self.assert_close(grad, torch.ones_like(image))++ # RandomPlasmaContrast has no neutral factor, but a replayed flat map of 0.25 gives a contrast of 1, which returns+ # the input with its exact 0 and 1 pixels on the bounds of the clamp.+ def test_plasma_contrast_clamp_keeps_gradient_at_unit_range_bounds_6296(self, device, dtype):+ row = torch.tensor([0.0, 0.25, 0.5, 1.0], device=device, dtype=dtype).view(1, 1, 1, 4)+ image = row.expand(1, 3, 4, 4).contiguous().requires_grad_()+ aug = K.RandomPlasmaContrast(p=1.0)+ params = aug.forward_parameters(image.shape)+ params["plasma"] = torch.full_like(params["plasma"], 0.25)+ out = aug(image, params=params)+ self.assert_close(out, image.detach())+ (grad,) = torch.autograd.grad(out.sum(), image)+ self.assert_close(grad, torch.ones_like(image))++ # RandomSnow at brightness 1 returns its input, and a black pixel's lightness stays on the bound of the clamp. At a+ # grey pixel the max/min tie of the HLS round trip sends the gradient to one channel, so compare the sum.+ def test_snow_clamp_keeps_gradient_at_unit_range_bounds_6296(self, device, dtype):+ row = torch.tensor([0.0, 0.25, 0.5, 1.0], device=device, dtype=dtype).view(1, 1, 1, 4)+ image = row.expand(1, 3, 4, 4).contiguous().requires_grad_()+ out = K.RandomSnow(snow_coefficient=(0.5, 0.5), brightness=(1.0, 1.0), p=1.0)(image)+ self.assert_close(out, image.detach())+ (grad,) = torch.autograd.grad(out.sum(), image)+ self.assert_close(grad.sum(1), torch.full_like(grad[:, 0], 3.0))++ # ColorJitter's brightness multiplies: black stays on its bound and keeps the factor, white leaves the range.+ def test_color_jitter_keeps_the_factor_at_a_black_pixel_6296(self, device, dtype):+ row = torch.tensor([0.0, 0.25, 0.5, 1.0], device=device, dtype=dtype).view(1, 1, 1, 4)+ image = row.expand(1, 3, 4, 4).contiguous().requires_grad_()+ (grad,) = torch.autograd.grad(K.ColorJitter(brightness=(1.5, 1.5), p=1.0)(image).sum(), image)+ expected = image.new_tensor([1.5, 1.5, 1.5, 0.0]).view(1, 1, 1, 4).expand_as(image)+ self.assert_close(grad, expected)+# Without a recorded gradient the input clamp is a single torch.clamp; with one it selects the input where the# clamp left it unchanged. Both must return the same values, and the recorded gradient is 1 inside [0, 1]# and 0 outside.diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex 7565f4253..0317ef361 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -15,7 +15,7 @@# limitations under the License.#-from math import exp, prod+from math import exp, log, prodimport pytestimport torch@@ -27,6 +27,7 @@ from kornia.constants import pifrom kornia.core._compat import torch_version_gefrom kornia.core.check import are_checks_enabled, disable_checks, enable_checksfrom kornia.core.exceptions import AsyncCheckError+from kornia.enhance.adjust import _clip_unit_freshfrom testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available@@ -365,8 +366,8 @@ class TestAdjustGamma(BaseTester):@pytest.mark.parametrize("scalar", [True, False])def test_black_pixel_gradient(self, device, dtype, gamma, scalar):# For 0 < gamma < 1, x ** gamma has an infinite derivative at x = 0; the gradient there is 0, as for the other- # exponents. x = 1 is left out: the derivative of the output clamp at its bound differs across torch releases.- image = torch.tensor([0.0, 0.25, 0.5], device=device, dtype=dtype).reshape(1, 1, 3).requires_grad_()+ # exponents. x = 1 lands on the output clamp's bound and keeps the derivative of the power.+ image = torch.tensor([0.0, 0.25, 0.5, 1.0], device=device, dtype=dtype).reshape(1, 1, 4).requires_grad_()param = gamma if scalar else torch.tensor([gamma], device=device, dtype=dtype)out = kornia.enhance.adjust_gamma(image, param)(grad,) = torch.autograd.grad(out.sum(), image)@@ -379,6 +380,24 @@ class TestAdjustGamma(BaseTester):assert torch.isfinite(grad).all()self.assert_close(grad, expected_grad)+ @pytest.mark.parametrize("scalar", [True, False])+ @pytest.mark.parametrize("forward_mode", ["jvp", "dual"])+ @pytest.mark.parametrize("grad_enabled", [False, True])+ def test_black_pixel_tangent(self, device, dtype, scalar, forward_mode, grad_enabled):+ # Forward mode meets the same infinite derivative; the output clamp no longer hides it on any torch version.+ image = torch.tensor([0.0, 0.25, 0.5, 1.0], device=device, dtype=dtype).reshape(1, 1, 4)+ tangent = torch.ones_like(image)+ param = 0.5 if scalar else torch.tensor([0.5], device=device, dtype=dtype)+ with torch.set_grad_enabled(grad_enabled):+ if forward_mode == "jvp":+ _, actual = torch.func.jvp(lambda x: kornia.enhance.adjust_gamma(x, param), (image,), (tangent,))+ else:+ with torch.autograd.forward_ad.dual_level():+ dual = torch.autograd.forward_ad.make_dual(image, tangent)+ actual = torch.autograd.forward_ad.unpack_dual(kornia.enhance.adjust_gamma(dual, param)).tangent+ expected = image.new_tensor([0.0, 1.0, 0.5**0.5, 0.5]).reshape(1, 1, 4)+ self.assert_close(actual, expected)+@pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)def test_scalar_export(self, device, dtype):image = torch.full((1, 2, 2), 0.4, device=device, dtype=dtype)@@ -2103,7 +2122,7 @@ class TestEmptyIntensity(BaseTester):class TestClipUnitFreshBuffer(BaseTester):# adjust_brightness and adjust_contrast clamp their own fresh result in place when no gradient is recorded, so a# batch-32 call allocates one image-sized temporary fewer. The caller's tensor is never modified, and the values- # and gradients equal the out-of-place clamp.+ # equal the out-of-place clamp, as do the gradients away from a bound (TestUnitRangeClampGradient has those on it)._REFERENCE = {"adjust_brightness": lambda image, factor: torch.clamp(image + factor.view(-1, 1, 1, 1), 0.0, 1.0),"adjust_contrast": lambda image, factor: torch.clamp(image * factor.view(-1, 1, 1, 1), 0.0, 1.0),@@ -2132,6 +2151,25 @@ class TestClipUnitFreshBuffer(BaseTester):assert leaf.grad is not Noneself.assert_close(leaf.grad, ref_leaf.grad)+ def test_reuses_the_buffer_only_when_no_derivative_can_be_asked_for(self, device, dtype):+ fresh = torch.linspace(-0.5, 1.5, 8, device=device, dtype=dtype)+ expected = fresh.clamp(0.0, 1.0)+ unrecorded = fresh.clone()+ out = _clip_unit_fresh(unrecorded)+ assert out is unrecorded+ assert torch.equal(out, expected)+ recorded = fresh.clone().requires_grad_()+ out = _clip_unit_fresh(recorded)+ assert out is not recorded+ assert torch.equal(out, expected)+ with torch.no_grad():+ detached = recorded.clone()+ assert _clip_unit_fresh(detached) is detached+ with torch.autograd.forward_ad.dual_level():+ dual = torch.autograd.forward_ad.make_dual(fresh.clone(), torch.ones_like(fresh))+ assert _clip_unit_fresh(dual) is not dual+ assert torch.equal(dual, fresh)+@pytest.mark.parametrize("op", sorted(_REFERENCE))@pytest.mark.parametrize("batch", [0, 3])def test_vmap_keeps_the_batching_rule(self, device, dtype, op, batch):@@ -2179,3 +2217,241 @@ class TestClipUnitFreshBuffer(BaseTester):assert torch.equal(image, original)assert out.dtype == torch.float32self.assert_close(out, self._REFERENCE[op](image, factor.to(torch.uint8)))+++def _black_grey_white(device, dtype) -> Tensor:+ row = torch.tensor([0.0, 0.25, 0.5, 1.0], device=device, dtype=dtype)+ return row.view(1, 1, 1, 4).expand(1, 3, 4, 4).contiguous()+++def _no_shift(image: Tensor) -> tuple[Tensor, Tensor, Tensor]:+ return (image.new_zeros(image.shape[0]),) * 3+++class TestUnitRangeClampGradient(BaseTester):+ # Valid images hold exact 0 and 1 pixels, and torch.clamp's derivative at a bound is 1 on torch 2.5.1 and 2.9.1 and+ # 0 on 2.14 (#6296). These ops clamp with _clamp_unit_range, so a result on the closed range [0, 1] keeps the+ # derivative of the arithmetic on every torch version, and a result outside it gets the bound and a zero gradient.+ # These pins fail with a plain clamp only on a recent torch; the 2.5.1 leg shows that the two sides agree.+ _AT_IDENTITY = {+ "adjust_brightness": lambda x: enhance.adjust_brightness(x, 0.0),+ "adjust_contrast": lambda x: enhance.adjust_contrast(x, 1.0),+ "adjust_brightness_accumulative": lambda x: enhance.adjust_brightness_accumulative(x, 1.0),+ "adjust_contrast_with_mean_subtraction": lambda x: enhance.adjust_contrast_with_mean_subtraction(x, 1.0),+ "adjust_saturation_with_gray_subtraction": lambda x: enhance.adjust_saturation_with_gray_subtraction(x, 1.0),+ "adjust_gamma_scalar": lambda x: enhance.adjust_gamma(x, 1.0),+ "adjust_gamma_tensor": lambda x: enhance.adjust_gamma(x, x.new_tensor([1.0])),+ "sharpness": lambda x: enhance.sharpness(x, 1.0),+ "shift_rgb": lambda x: enhance.shift_rgb(x, *_no_shift(x)),+ "solarize": lambda x: enhance.solarize(x, 2.0, 0.0),+ }++ # The gradient at the pixels 0, 0.25, 0.5, 1.+ _AWAY_FROM_IDENTITY = {+ "adjust_brightness_lands_on_1": (lambda x: enhance.adjust_brightness(x, 0.5), [1.0, 1.0, 1.0, 0.0]),+ "adjust_brightness_lands_on_0": (lambda x: enhance.adjust_brightness(x, -0.25), [0.0, 1.0, 1.0, 1.0]),+ "adjust_contrast": (lambda x: enhance.adjust_contrast(x, 1.5), [1.5, 1.5, 1.5, 0.0]),+ "adjust_brightness_accumulative": (+ lambda x: enhance.adjust_brightness_accumulative(x, 1.5),+ [1.5, 1.5, 1.5, 0.0],+ ),+ "adjust_gamma_root": (lambda x: enhance.adjust_gamma(x, 0.5), [0.0, 1.0, 0.5**0.5, 0.5]),+ "adjust_gamma_root_tensor": (lambda x: enhance.adjust_gamma(x, x.new_tensor([0.5])), [0.0, 1.0, 0.5**0.5, 0.5]),+ "adjust_gamma_square": (lambda x: enhance.adjust_gamma(x, 2.0), [0.0, 0.5, 1.0, 2.0]),+ "adjust_log": (enhance.adjust_log, [1 / (v * log(2.0)) for v in (1.0, 1.25, 1.5, 2.0)]),+ "adjust_log_inv": (lambda x: enhance.adjust_log(x, inv=True), [log(2.0) * 2**v for v in (0.0, 0.25, 0.5, 1.0)]),+ "solarize_additions_0": (lambda x: enhance.solarize(x, 0.6, 0.0), [1.0, 1.0, 1.0, -1.0]),+ "solarize_lands_on_0": (lambda x: enhance.solarize(x, 0.6, -0.25), [0.0, 1.0, 1.0, -1.0]),+ "shift_rgb": (lambda x: enhance.shift_rgb(x, *(s + 0.5 for s in _no_shift(x))), [1.0, 1.0, 1.0, 0.0]),+ }++ # A pixel with a zero channel has a saturation of exactly 1 in float32, and a grey or black pixel one of exactly 0.+ # No two smallest channels tie: the half-precision path goes through HSV, where the hue of such a pixel moves the+ # gradient between them on every torch version.+ _COLOURED = (+ (1.0, 0.5, 0.0),+ (0.5, 0.25, 0.0),+ (0.5, 0.25, 0.125),+ (1.0, 1.0, 1.0),+ (0.0, 0.0, 0.0),+ (1.0, 0.5, 0.25),+ )++ @pytest.mark.parametrize("op", sorted(_AT_IDENTITY))+ def test_convention_identity_factor_keeps_the_identity_gradient(self, device, dtype, op):+ image = _black_grey_white(device, dtype).requires_grad_()+ out = self._AT_IDENTITY[op](image)+ (grad,) = torch.autograd.grad(out.sum(), image)+ self.assert_close(out, image)+ self.assert_close(grad, torch.ones_like(image))++ @pytest.mark.parametrize("op", sorted(_AWAY_FROM_IDENTITY))+ def test_convention_result_on_a_bound_keeps_the_derivative_of_the_arithmetic(self, device, dtype, op):+ call, expected = self._AWAY_FROM_IDENTITY[op]+ image = _black_grey_white(device, dtype).requires_grad_()+ (grad,) = torch.autograd.grad(call(image).sum(), image)+ expected = image.new_tensor(expected).view(1, 1, 1, 4).expand_as(image)+ self.assert_close(grad, expected)++ @pytest.mark.parametrize("factor", [0.0, 0.5])+ def test_sharpness_keeps_the_smoothed_gradient_on_a_black_image(self, device, dtype, factor):+ # Both clamps sit on their bound. The smoothed copy reads the 3 x 3 around each pixel of the inner 3 x 3 and the+ # border keeps the input, so the expected gradient is the kernel summed over the pixels that read each position.+ image = torch.zeros(1, 1, 5, 5, device=device, dtype=dtype, requires_grad=True)+ (grad,) = torch.autograd.grad(enhance.sharpness(image, factor).sum(), image)+ kernel = image.new_tensor([[1.0, 1.0, 1.0], [1.0, 5.0, 1.0], [1.0, 1.0, 1.0]]).view(1, 1, 3, 3) / 13+ reads = torch.nn.functional.conv2d(torch.ones(1, 1, 3, 3, device=device, dtype=dtype), kernel, padding=2)+ blended = torch.full_like(image, 1.0)+ blended[..., 1:4, 1:4] = factor+ self.assert_close(grad, blended + (1.0 - factor) * reads)++ def test_saturation_keeps_the_identity_gradient_of_a_coloured_image(self, device, dtype):+ image = torch.tensor(self._COLOURED, device=device, dtype=dtype).T.view(1, 3, 1, 6).requires_grad_()+ out = enhance.adjust_saturation(image, 1.0)+ (grad,) = torch.autograd.grad(out.sum(), image)+ self.assert_close(out, image)+ self.assert_close(grad, torch.ones_like(image))++ def test_saturation_raw_keeps_the_gradient_of_the_saturation_channel(self, device, dtype):+ # Saturation 0, 0.5 and 1 at factor 1 pass through; hue and value are not clamped.+ image = torch.tensor(+ [[[[3.0, 3.0, 3.0]], [[0.0, 0.5, 1.0]], [[1.0, 1.0, 1.0]]]], device=device, dtype=dtype+ ).requires_grad_()+ (grad,) = torch.autograd.grad(enhance.adjust_saturation_raw(image, 1.0).sum(), image)+ self.assert_close(grad, torch.ones_like(image))++ @pytest.mark.parametrize("op", ["adjust_brightness", "adjust_contrast"])+ def test_factor_gradient_follows_the_image_gradient_at_a_bound(self, device, dtype, op):+ # The clamp is one selection for the whole result, so a factor on a pixel that lands on a bound keeps its+ # derivative too: 1 for the additive brightness, the pixel for the multiplicative contrast.+ image = _black_grey_white(device, dtype)+ neutral = 0.0 if op == "adjust_brightness" else 1.0+ factor = torch.tensor([neutral], device=device, dtype=dtype, requires_grad=True)+ (grad,) = torch.autograd.grad(getattr(enhance, op)(image, factor).sum(), factor)+ expected = image.numel() if op == "adjust_brightness" else image.sum().item()+ self.assert_close(grad, torch.tensor([expected], device=device, dtype=dtype))++ @pytest.mark.parametrize("op", ["adjust_brightness", "adjust_contrast", "adjust_brightness_accumulative"])+ def test_no_clamp_means_no_selection(self, device, dtype, op):+ # clip_output=False has no bound, so a value outside [0, 1] keeps its gradient.+ image = torch.tensor([-0.5, 0.0, 1.0, 1.5], device=device, dtype=dtype).view(1, 1, 1, 4).requires_grad_()+ factor = 0.0 if op == "adjust_brightness" else 1.0+ out = getattr(enhance, op)(image, factor, clip_output=False)+ (grad,) = torch.autograd.grad(out.sum(), image)+ self.assert_close(out, image)+ self.assert_close(grad, torch.ones_like(image))++ @pytest.mark.parametrize("op", sorted(_AT_IDENTITY))+ def test_values_outside_the_range_get_the_bound_and_a_zero_gradient(self, device, dtype, op):+ # The first row is on the border, which sharpness leaves to the input; only the other rows mix neighbours.+ row = torch.tensor([-0.5, -2.0, 1.5, 3.0], device=device, dtype=dtype)+ image = row.view(1, 1, 1, 4).expand(1, 3, 3, 4).contiguous()+ leaf = image.clone().requires_grad_()+ out = self._AT_IDENTITY[op](leaf)+ with torch.no_grad():+ no_grad = self._AT_IDENTITY[op](image)+ assert torch.equal(out[..., 0, :], no_grad[..., 0, :])+ assert torch.equal(out[..., 0, :], image[..., 0, :].clamp(0.0, 1.0))+ (grad,) = torch.autograd.grad(out[..., 0, :].sum(), leaf)+ assert torch.equal(grad[..., 0, :], torch.zeros_like(grad[..., 0, :]))++ @pytest.mark.parametrize("forward_mode", ["jvp", "dual"])+ @pytest.mark.parametrize("grad_enabled", [False, True])+ @pytest.mark.parametrize("op", sorted(_AT_IDENTITY))+ def test_forward_mode_keeps_the_tangent_at_the_bounds(self, device, dtype, op, forward_mode, grad_enabled):+ image = _black_grey_white(device, dtype)+ tangent = torch.full_like(image, 3.0)+ call = self._AT_IDENTITY[op]+ with torch.set_grad_enabled(grad_enabled):+ if forward_mode == "jvp":+ values, actual = torch.func.jvp(call, (image,), (tangent,))+ else:+ with torch.autograd.forward_ad.dual_level():+ dual = torch.autograd.forward_ad.make_dual(image, tangent)+ values, actual = torch.autograd.forward_ad.unpack_dual(call(dual))+ self.assert_close(values, image)+ self.assert_close(actual, tangent)++ @pytest.mark.parametrize(+ "name", ["adjust_brightness", "adjust_contrast", "adjust_gamma", "adjust_log", "shift_rgb"]+ )+ def test_scripted_call_keeps_the_gradient_at_the_bounds(self, device, dtype, name):+ scripted = torch.jit.script(getattr(enhance, name))+ image = _black_grey_white(device, dtype).requires_grad_()+ if name == "shift_rgb":+ out = scripted(image, *_no_shift(image))+ elif name == "adjust_log":+ out = scripted(image)+ else:+ out = scripted(image, 0.0 if name == "adjust_brightness" else 1.0)+ (grad,) = torch.autograd.grad(out.sum(), image)+ expected = 1 / ((1 + image.detach()) * log(2.0)) if name == "adjust_log" else torch.ones_like(image)+ self.assert_close(grad, expected)++ # adjust_brightness and adjust_contrast raised on the base as well: they reach _clip_unit_fresh, which took the+ # in-place clamp only in the check under no_grad. The other nine traced on the base.+ _CAPTURED = {+ "adjust_brightness": lambda x: enhance.adjust_brightness(x, 0.1),+ "adjust_contrast": lambda x: enhance.adjust_contrast(x, 1.2),+ "adjust_brightness_accumulative": lambda x: enhance.adjust_brightness_accumulative(x, 1.2),+ "adjust_contrast_with_mean_subtraction": lambda x: enhance.adjust_contrast_with_mean_subtraction(x, 1.2),+ "adjust_saturation_with_gray_subtraction": lambda x: enhance.adjust_saturation_with_gray_subtraction(x, 1.2),+ "adjust_saturation": lambda x: enhance.adjust_saturation(x, 1.2),+ "adjust_saturation_raw": lambda x: enhance.adjust_saturation_raw(x, 1.2),+ "adjust_log": enhance.adjust_log,+ "sharpness": lambda x: enhance.sharpness(x, 1.0),+ "shift_rgb": lambda x: enhance.shift_rgb(x, *_no_shift(x)),+ "solarize": lambda x: enhance.solarize(x, 0.5, 0.1),+ }++ @pytest.mark.parametrize("op", sorted(_CAPTURED))+ def test_trace_of_a_module_with_parameters_passes_its_check(self, device, dtype, op):+ # A parameter gives the op an input that requires grad, and torch.jit.trace checks its graph again under+ # no_grad: a clamp that follows the grad mode records two different graphs, and the trace raises+ # TracingCheckError.+ call = self._CAPTURED[op]++ class ConvThenOp(torch.nn.Module):+ def __init__(self) -> None:+ super().__init__()+ self.conv = torch.nn.Conv2d(3, 3, 1, bias=False)+ torch.nn.init.dirac_(self.conv.weight)++ def forward(self, x: Tensor) -> Tensor:+ return call(self.conv(x))++ module = ConvThenOp().to(device, dtype)+ image = _black_grey_white(device, dtype)+ traced = torch.jit.trace(module, (image,))+ self.assert_close(traced(image), call(image))++ @pytest.mark.parametrize("op", sorted(_AT_IDENTITY))+ def test_vmap_of_grad_keeps_the_identity_gradient(self, device, dtype, op):+ image = _black_grey_white(device, dtype)[0]+ grads = torch.vmap(torch.func.grad(lambda x: self._AT_IDENTITY[op](x[None]).sum()))(image[None])+ self.assert_close(grads, torch.ones_like(grads))++ def test_integer_image_with_checks_disabled_keeps_the_integer_bounds(self, device):+ # shift_rgb and adjust_saturation_raw clamp an integer result with integer bounds, which keep its dtype.+ image = torch.randint(0, 256, (2, 3, 4, 4), device=device, dtype=torch.uint8)+ shift = torch.ones(2, device=device)+ was_enabled = are_checks_enabled()+ disable_checks()+ try:+ shifted = enhance.shift_rgb(image, shift, shift, shift)+ finally:+ if was_enabled:+ enable_checks()+ saturated = enhance.adjust_saturation_raw(image, 2.0)+ assert shifted.dtype == torch.uint8+ assert torch.equal(shifted, (image + 1).clamp(0, 1))+ assert saturated.dtype == torch.uint8+ assert torch.equal(saturated[:, 1], (image[:, 1] * 2).clamp(0, 1))++ @pytest.mark.parametrize("op", sorted(_AT_IDENTITY))+ def test_dynamo_gradient_at_the_bounds(self, device, dtype, op, torch_optimizer):+ image = _black_grey_white(device, dtype).requires_grad_()+ out = torch_optimizer(self._AT_IDENTITY[op], fullgraph=True)(image)+ (grad,) = torch.autograd.grad(out.sum(), image)+ self.assert_close(out, image)+ self.assert_close(grad, torch.ones_like(image))