🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): reject a scalar magnitude past a parameter's upper bound instead of clamping it (#4569)
Dmytro Mishkinecbcad5616c3
diff --git a/benchmarks/augmentation/2d_intensity_test.py b/benchmarks/augmentation/2d_intensity_test.pyindex 48151f263..a5b9dd50a 100644--- a/benchmarks/augmentation/2d_intensity_test.py+++ b/benchmarks/augmentation/2d_intensity_test.py@@ -287,7 +287,9 @@ def test_aug_2d_median_blur(benchmark, device, dtype, torch_optimizer, shape):def test_aug_2d_motion_blur(benchmark, device, dtype, torch_optimizer, shape):data = torch.rand(*shape, device=device, dtype=dtype)- aug = RandomMotionBlur((3, 3), 45.0, 5.5, p=1.0)+ # ``direction`` is bounded by [-1, 1]; 1.0 is the widest admissible magnitude and draws from the+ # same [-1, 1] the out-of-bounds 5.5 used to be clamped to, so the measured op is unchanged.+ aug = RandomMotionBlur((3, 3), 45.0, 1.0, p=1.0)op = torch_optimizer(aug)actual = benchmark(op, input=data)diff --git a/changelog.d/4569.breaking.md b/changelog.d/4569.breaking.mdnew file mode 100644index 000000000..7e4e3c4f7--- /dev/null+++ b/changelog.d/4569.breaking.md@@ -0,0 +1,13 @@+A scalar augmentation magnitude `x` whose implied range `center ± x` reaches past the parameter's upper+bound now raises the same `ValueError: <name> out of bounds. Expected inside (lo, hi), got tensor([...])`+that the explicit range form already raised; it used to be clamped to the bound silently. The lower end is+still floored at the parameter's lower bound, so `RandomContrast(1.5)` still means `[0, 2.5]`,+`RandomSharpness(0.5)` still means `[0, 0.5]`, `RandomJPEG(50.0)` still means `[1, 100]` and+`RandomAffine(degrees=360)` still means `[-360, 360]`. The scalar forms that now raise are+`hue > 0.5` (`RandomHue`, `ColorJiggle`, `ColorJitter`), `brightness > 1` (`RandomBrightness`,+`ColorJiggle`), `thresholds > 0.5` and `additions > 0.5` (`RandomSolarize`), `jpeg_quality > 50`+(`RandomJPEG`), `direction > 1` (`RandomMotionBlur`, `RandomMotionBlur3D`), `angle > 360`+(`RandomMotionBlur`), `degrees > 360` (`RandomRotation`, `RandomAffine`), `shear > 360` (`RandomShear`,+`RandomAffine`), `translate > 1` (`RandomAffine`), `translate_x > 1` and `translate_y > 1`+(`RandomTranslate`) and `times > 3` (`RandomRotation90`). The 3D `degrees`, `shears` and `angle`+arguments go through a different reader and are unchanged. Refs #4563.diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.pyindex 740fe2688..e7a234f86 100644--- a/kornia/augmentation/_2d/geometric/base.py+++ b/kornia/augmentation/_2d/geometric/base.py@@ -50,6 +50,14 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):image dtype guard and therefore reject ``bool`` masks.- a subclass supplies its own :meth:`inverse_transform` -- the base raises ``NotImplementedError`` --while :meth:`compute_inverse_transformation` defaults to inverting the sampled matrix.+ - a scalar magnitude ``x`` means ``center ± x``, as it does for the intensity classes: its lower end+ is floored at the parameter's lower bound, and an upper end past the upper bound raises the same+ error the explicit range does. The bounds are ``(-360, 360)`` for :class:`RandomRotation`'s and+ :class:`RandomAffine`'s ``degrees`` and for :class:`RandomShear`'s and :class:`RandomAffine`'s+ ``shear``, ``(-1, 1)`` for :class:`RandomTranslate`'s ``translate_x`` and ``translate_y``,+ ``(0, 1)`` for :class:`RandomAffine`'s ``translate``, and ``(-3, 3)`` for+ :class:`RandomRotation90`'s ``times``. The 3D classes read their scalar through a helper that+ carries no bound, tracked in `#4617 <https://github.com/kornia/kornia/issues/4617>`_.Note:Masks are resampled with nearest neighbour whatever ``resample`` the augmentation uses for images,diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex 3ba92ace0..e190b5c33 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -100,9 +100,10 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):constant ``3`` (`#4599 <https://github.com/kornia/kornia/issues/4599>`_);and :class:`RandomChannelDropout`'s ``num_drop_channels`` against the input's channel count.:class:`RandomPlanckianJitter`'s ``select_from`` rejects an index past the table at construction- but accepts a negative one, as Python indexing does. A scalar magnitude is a different case: several- classes fit it to the bound instead of raising, tracked in- `#4563 <https://github.com/kornia/kornia/issues/4563>`_.+ 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... warning::Several of these classes return an all-zero image for an input whose values are all negative, with nodiff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.pyindex 134b39287..e16fbc698 100644--- a/kornia/augmentation/_2d/intensity/color_jiggle.py+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py@@ -48,13 +48,14 @@ class ColorJiggle(IntensityAugmentationBase2D):Convention:- this class and :class:`ColorJitter` draw the same factor values and the same random application``order`` from the same seed when their effective sampling bounds match and both modules stay on- the CPU. A scalar ``brightness > 1`` does not match: this class draws from ``[0, 2]`` while- :class:`ColorJitter` draws from ``[0, 1 + brightness]``. Off the CPU the ``order`` diverges,- because this class draws it on the sampler device where :class:`ColorJitter` always draws it on- the CPU; and this class returns its factors in the dtype of its constructor arguments- (``float32`` for Python floats) where :class:`ColorJitter` keeps the sampler dtype. Only- :class:`ColorJitter` takes an ``order`` constructor argument that replaces its sampled order with a- fixed one. The classes use different primitives for three adjustments:+ 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. Only :class:`ColorJitter` takes an ``order`` constructor argument that+ replaces its sampled order with a fixed one. The classes use different primitives for three+ adjustments::func:`kornia.enhance.adjust_brightness` against:func:`kornia.enhance.adjust_brightness_accumulative`,:func:`kornia.enhance.adjust_contrast` against@@ -71,9 +72,10 @@ class ColorJiggle(IntensityAugmentationBase2D):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 channelcount, including the ``C = 1`` and ``C = 4`` on which :class:`ColorJitter` raises.- - the ``[0, 2]`` bound is not only a clamp on a scalar: an explicit ``brightness`` range reaching- above ``2``, such as ``(0.0, 3.0)``, is rejected at construction with- ``brightness out of bounds. Expected inside (0, 2)``, where :class:`ColorJitter` accepts it.+ - 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... warning::The brightness and contrast primitives clip into ``[0, 1]`` by default, so an input whose values arediff --git a/kornia/augmentation/_2d/intensity/color_jitter.py b/kornia/augmentation/_2d/intensity/color_jitter.pyindex 8b8c50cf1..c242d25e8 100644--- a/kornia/augmentation/_2d/intensity/color_jitter.py+++ b/kornia/augmentation/_2d/intensity/color_jitter.py@@ -62,13 +62,13 @@ class ColorJitter(IntensityAugmentationBase2D):Convention:- this class and :class:`ColorJiggle` draw the same factor values and the same random application``order`` from the same seed when their effective sampling bounds match and both modules stay on- the CPU. A scalar ``brightness > 1`` does not match: :class:`ColorJiggle` draws from ``[0, 2]``- while this class draws from ``[0, 1 + brightness]``. Off the CPU the ``order`` diverges, because- this class always draws it on the CPU where :class:`ColorJiggle` draws it on the sampler device;- and this class keeps the sampler dtype for its factors where :class:`ColorJiggle` returns them in- the dtype of its constructor arguments (``float32`` for Python floats). Only this class takes an- ``order`` constructor argument that replaces the sampled order with a fixed one. The classes use different- primitives for three adjustments:+ 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). Only this class takes an ``order`` constructor argument that replaces the+ sampled order with a fixed one. The classes use different primitives for three adjustments::func:`kornia.enhance.adjust_brightness_accumulative` against:func:`kornia.enhance.adjust_brightness`,:func:`kornia.enhance.adjust_contrast_with_mean_subtraction` againstdiff --git a/kornia/augmentation/_2d/intensity/hue.py b/kornia/augmentation/_2d/intensity/hue.pyindex 2eecfed83..521911789 100644--- a/kornia/augmentation/_2d/intensity/hue.py+++ b/kornia/augmentation/_2d/intensity/hue.py@@ -37,9 +37,8 @@ class RandomHue(IntensityAugmentationBase2D):Args:hue: the hue shift, in turns of the hue circle, restricted to the closed ``[-0.5, 0.5]``. If ``hue``- is a single number ``x`` the shift is sampled from ``[-x, x]`` fitted to that bound, so a larger- ``x`` widens the range no further (`#4563 <https://github.com/kornia/kornia/issues/4563>`_); a- tuple gives the range directly, and one outside the bound raises.+ is a single number ``x`` the shift is sampled from ``[-x, x]``, and ``x`` above ``0.5`` raises; a+ tuple gives the range directly, and one outside the bound raises as well.same_on_batch: apply the same transformation across the batch.p: probability of applying the transformation.keepdim: whether to keep the output shape the same as input (True) or broadcast itdiff --git a/kornia/augmentation/_2d/intensity/sharpness.py b/kornia/augmentation/_2d/intensity/sharpness.pyindex 9d7b3f5f6..852296f00 100644--- a/kornia/augmentation/_2d/intensity/sharpness.py+++ b/kornia/augmentation/_2d/intensity/sharpness.py@@ -51,10 +51,9 @@ class RandomSharpness(IntensityAugmentationBase2D):- the factor blends between the fully blurred image at ``0`` and the input at ``1``, and valuesabove ``1`` sharpen. The one-pixel border is copied from the input at every factor, so it is neverblurred or sharpened, although the final clamp into ``[0, 1]`` applies to it as to the rest.- - a scalar argument is the upper bound of ``[0, x]`` -- the centred ``[-x, x]`` fitted to the- non-negative bound (`#4563 <https://github.com/kornia/kornia/issues/4563>`_) -- so the default- ``sharpness=0.5`` never reaches the identity and therefore never sharpens -- it blurs by a random- amount.+ - 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]``... warning::diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.pyindex 4dc6d01d3..1ee6fc76d 100644--- a/kornia/augmentation/utils/param_validation.py+++ b/kornia/augmentation/utils/param_validation.py@@ -70,7 +70,14 @@ def _range_bound(device: Optional[torch.device] = None,dtype: Optional[torch.dtype] = None,) -> torch.Tensor:- r"""Check inputs and compute the corresponding factor bounds."""+ r"""Check inputs and compute the corresponding factor bounds.++ A scalar ``factor`` is a magnitude around ``center``: the range is ``[center - factor, center + factor]``+ with its lower end floored at ``bounds[0]`` (a non-negative parameter reads ``contrast=1.5`` as+ ``[0, 2.5]``, the way torchvision does), and an upper end past ``bounds[1]`` raises the same+ ``ValueError`` the explicit range would. A pair is taken as the range itself and checked against+ ``bounds`` with ``check``.+ """if device is None:device = torch.device("cpu")if dtype is None:@@ -84,11 +91,12 @@ def _range_bound(raise ValueError(f"If {name} is a single number, it must be non negative. Got {factor}.")if center is None or bounds is None:raise ValueError(f"`center` and `bounds` cannot be None for single number. Got {center}, {bounds}.")- # Should be something other than clamp- # Currently, single value factor will not out of scope as long as the user provided it.- # Note: I personally think throw an error will be better than a coarse clamp.factor_bound = factor.repeat(2) * torch.tensor([-1.0, 1.0], device=factor.device, dtype=factor.dtype) + center- factor_bound = factor_bound.clamp(bounds[0], bounds[1]).to(device=device, dtype=dtype)+ # The lower end is floored at the domain floor; the upper end is never clamped, because a+ # magnitude that overshoots the domain is a mistake the explicit range form already rejects.+ if factor_bound[1] > bounds[1]:+ raise ValueError(f"{name} out of bounds. Expected inside {bounds}, got {factor_bound}.")+ factor_bound = factor_bound.clamp(min=bounds[0]).to(device=device, dtype=dtype)else:factor_bound = torch.as_tensor(factor, device=device, dtype=dtype)diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.pyindex cd71cb37d..7357ef6a6 100644--- a/testing/half_precision_eager_rng.py+++ b/testing/half_precision_eager_rng.py@@ -159,7 +159,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(),*_audited("tests/augmentation/test_param_validation.py",- 110,+ 111,"torch.rand",1,("tests/augmentation/test_param_validation.py::TestParamValidation::test_tuple_range_reader_errors",),diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex 0f8ed746b..175351554 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -772,21 +772,24 @@ class TestIntensityColourConventions(BaseTester):@pytest.mark.device_agnosticdef test_convention_color_jiggle_and_jitter_have_different_brightness_bounds(self):- # Scalar brightness=3 is accepted by both, but yields [0, 2] for Jiggle and [0, 4] for Jitter.- # `(jitter > 2).any()` is a `1 - 2 ** -B` event, so it needs a batch wide enough to be certain:- # at the `B = 4` this pin first used it failed on 13 of seeds 0..199, and this literal seed is- # outside the `_FORWARD_SEED` sweep that would have caught it. At `B = 64` the failure- # probability is `2 ** -64`.+ # 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].+ 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)- jiggle_params = K.ColorJiggle(brightness=3.0).forward_parameters((64, 3, 2, 2))- torch.manual_seed(7)- jitter_params = K.ColorJitter(brightness=3.0).forward_parameters((64, 3, 2, 2))- jiggle_brightness = jiggle_params["brightness_factor"]- jitter_brightness = jitter_params["brightness_factor"]- assert bool(((jiggle_brightness >= 0) & (jiggle_brightness <= 2)).all())+ 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())assert bool((jitter_brightness > 2).any())- self.assert_close(jitter_brightness, 2 * jiggle_brightness, atol=0, rtol=0)- for key in jiggle_params.keys() - {"brightness_factor"}:+ # At a scalar within both bounds the two draw the same factors from the same seed.+ torch.manual_seed(7)+ jiggle_params = K.ColorJiggle(brightness=0.5).forward_parameters((4, 3, 2, 2))+ torch.manual_seed(7)+ jitter_params = K.ColorJitter(brightness=0.5).forward_parameters((4, 3, 2, 2))+ for key in jiggle_params:assert torch.equal(jiggle_params[key], jitter_params[key]), key@pytest.mark.parametrize("hue", [0.0, (0.1, 0.1)])@@ -1668,6 +1671,28 @@ class TestIntensityColourConventions(BaseTester):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.+ (+ "hue_scalar_above_half",+ "construction",+ ValueError,+ r"hue out of bounds\. Expected inside \(-0\.5, 0\.5\), got tensor\(\[-0\.6000, 0\.6000\]\)",+ ),+ (+ "brightness_scalar_above_two",+ "construction",+ ValueError,+ r"brightness out of bounds\. Expected inside \(0\.0, 2\.0\), got tensor\(\[-2\., 4\.\]\)",+ ),+ (+ "solarize_scalar_threshold_above_half",+ "construction",+ ValueError,+ r"thresholds out of bounds\. Expected inside \(0\.0, 1\.0\), got tensor\(\[-1\.5000, 2\.5000\]\)",+ ),],)def test_convention_intensity_constructors_reject_out_of_bounds(self, device, dtype, case, stage, error, match):@@ -1687,9 +1712,11 @@ class TestIntensityColourConventions(BaseTester):"brightness_above_two": lambda: K.RandomBrightness((3.0, 3.0), p=1.0),"contrast_negative": lambda: K.RandomContrast((-1.0, -1.0), p=1.0),"saturation_negative": lambda: K.RandomSaturation((-1.0, -1.0), p=1.0),- # A scalar `hue` is silently clamped into the bound instead of rejected, so the pin uses- # the explicit range the audit executed."hue_above_half": lambda: K.RandomHue((0.6, 0.6), p=1.0),+ # The 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),# The construction check is the closed [-0.5, 0.5]; kornia.enhance.solarize rejects the# ends on the forward pass, so this one constructs and raises like the gamma case."solarize_additions_at_half": lambda: K.RandomSolarize((0.5, 0.5), (0.5, 0.5), p=1.0),@@ -1746,28 +1773,56 @@ class TestIntensityColourConventions(BaseTester):K.RandomPlanckianJitter(select_from=[-1], p=1.0).pl, K.RandomPlanckianJitter(select_from=[24], p=1.0).pl)- # Issue #4563: a scalar magnitude whose implied range leaves the documented bounds is fitted to- # them instead of rejected, where the same range written out raises (pinned one test above).- # RandomSharpness is the class that depends on the fit: its scalar form is the centred `[-x, x]`- # clamped to `(0, inf)`, which is what makes `sharpness=0.5` mean `[0, 0.5]`.+ # 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:- # print(K.RandomHue(0.7).hue, K.RandomBrightness(3.0).brightness)- # print(K.ColorJiggle(brightness=3.0).forward_parameters((256, 3, 2, 2))["brightness_factor"].aminmax())+ # 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())- # executed 2026-09-15 (torch 2.14.0, cpu) -> `[-0.5, 0.5]`, `[0, 2]`, brightness in- # `[0.0072, 1.9945]`, sharpness in `[3.87e-05, 0.5]`.+ # 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`.@pytest.mark.device_agnostic- def test_wart_scalar_magnitude_is_fitted_to_the_bound_4563(self):- assert K.RandomHue(0.7, p=1.0).hue.tolist() == [-0.5, 0.5]- assert K.RandomBrightness(3.0, p=1.0).brightness.tolist() == [0.0, 2.0]- torch.manual_seed(_FORWARD_SEED)- brightness = K.ColorJiggle(brightness=3.0, p=1.0).forward_parameters((256, 3, 2, 2))["brightness_factor"]- assert float(brightness.min()) >= 0.0 and float(brightness.max()) <= 2.0- assert float(brightness.max()) > 1.5 # the fit is to [0, 2], not to [0, 1 + 3] or to [0, 1]+ 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.ColorJiggle(brightness=1.5, p=1.0),+ r"brightness out of bounds\. .*got tensor\(\[-0\.5000, 2\.5000\]\)",+ ),+ (+ lambda: K.RandomSolarize(2.0, 0.1, p=1.0),+ r"thresholds out of bounds\. .*got tensor\(\[-1\.5000, 2\.5000\]\)",+ ),+ (+ lambda: K.RandomMotionBlur(3, 45.0, 2.0, p=1.0),+ r"direction out of bounds\. .*got tensor\(\[-2\., 2\.\]\)",+ ),+ (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]+ assert K.RandomBrightness(0.5, p=1.0).brightness.tolist() == [0.5, 1.5]torch.manual_seed(_FORWARD_SEED)sharpness = K.RandomSharpness(0.5, p=1.0).forward_parameters((2000, 1, 4, 4))["sharpness"]assert float(sharpness.min()) >= 0.0 and float(sharpness.max()) <= 0.5- assert float(sharpness.min()) < 0.1 # the lower end is the clamped -x, not a centred x / 2+ assert float(sharpness.min()) < 0.1 # the lower end is the floored -x, not a centred x / 2+ 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)# Issue #4564: RandomClahe rejects an out-of-[0, 1] input with the raw indexing error of the# histogram gather, naming neither the class nor the range RandomEqualize names (#4489). Not on CUDA,diff --git a/tests/augmentation/test_param_validation.py b/tests/augmentation/test_param_validation.pyindex 594b8c521..8c92dd635 100644--- a/tests/augmentation/test_param_validation.py+++ b/tests/augmentation/test_param_validation.py@@ -20,6 +20,7 @@ from typing import castimport pytestimport torch+import kornia.augmentation as Kfrom kornia.augmentation.utils.param_validation import (_common_param_check,_range_bound,@@ -130,6 +131,13 @@ class TestParamValidation:((10, 5), 0, None, "joint", ValueError, "should be smaller than"),("invalid", 0, (-10, 10), "singular", TypeError, None),((-10.0, 10.0), 0, (-5, 5), "singular", ValueError, "param out of bounds"),+ # The scalar rows name the whole message on purpose. The reported tensor is the unclamped+ # `[center - x, center + x]`, which only the scalar branch's own raise produces: with that raise gone+ # the trailing `_joint_range_check` / `_singular_range_check` still rejects the same inputs,+ # but reports the lower end already floored (`[-5., 10.]`, `[-0.5000, 0.6000]`, `[0., 4.]`).+ (10.0, 0, (-5, 5), "singular", ValueError, r"param out of bounds\. .*got tensor\(\[-10\., 10\.\]\)"),+ (0.6, 0, (-0.5, 0.5), "joint", ValueError, r"param out of bounds\. .*got tensor\(\[-0\.6000, 0\.6000\]\)"),+ (3.0, 1.0, (0, 2), "joint", ValueError, r"param out of bounds\. .*got tensor\(\[-2\., 4\.\]\)"),],)def test_range_bound_errors(self, factor, center, bounds, check, expected_exception, match_msg):@@ -145,7 +153,9 @@ class TestParamValidation:"factor, center, bounds, check, expected",[(10.0, 0, (-10, 10), "singular", torch.tensor([-10.0, 10.0], dtype=torch.float32)),- (10.0, 0, (-5, 5), "singular", torch.tensor([-5.0, 5.0], dtype=torch.float32)),+ (1.5, 1.0, (0, float("inf")), "joint", torch.tensor([0.0, 2.5], dtype=torch.float32)),+ (0.5, 0.0, (0, float("inf")), "joint", torch.tensor([0.0, 0.5], dtype=torch.float32)),+ (50.0, 50.0, (1, 100), "joint", torch.tensor([1.0, 100.0], dtype=torch.float32)),(0.2, 1.0, (0, 2), "singular", torch.tensor([0.8, 1.2], dtype=torch.float32)),((5.0, 10.0), 0, None, "singular", torch.tensor([5.0, 10.0], dtype=torch.float32)),([-5.0, 5.0], 0, (-10, 10), "singular", torch.tensor([-5.0, 5.0], dtype=torch.float32)),@@ -153,8 +163,10 @@ class TestParamValidation:((10.0, 5.0), 0, None, "singular", torch.tensor([10.0, 5.0], dtype=torch.float32)),],ids=[- "float-clamp-full",- "float-clamp-partial",+ "float-symmetric-full",+ "float-floored-at-zero",+ "float-floored-at-zero-center-zero",+ "float-floored-at-lower-bound","float-center-offset","tuple-input","list-input",@@ -166,3 +178,30 @@ class TestParamValidation:"""Valid inputs should produce the expected bounded range."""res = _range_bound(factor, "param", center=center, bounds=bounds, check=check)torch.testing.assert_close(res, expected)++ # `_range_bound` is shared, so rejecting a scalar past the upper bound (#4563) reaches the geometric+ # classes as well as the intensity ones, and each reports the unclamped `[center - x, center + x]`.+ # The 3D `degrees`, `shears` and `angle` arguments read their scalar through `_tuple_range_reader`+ # instead, which has no bound of its own, so they are deliberately not covered here.+ # Snippet used to generate expected:+ # for ctor in (lambda: K.RandomRotation(400.0), lambda: K.RandomShear(400.0),+ # lambda: K.RandomTranslate(2.0, 0.1), lambda: K.RandomRotation90(5),+ # lambda: K.RandomAffine(30.0, translate=2.0)):+ # try: ctor()+ # except ValueError as e: print(e)+ # executed 2026-09-16 (torch 2.14.0, cpu) -> the five messages pinned below.+ @pytest.mark.parametrize(+ "ctor, match_msg",+ [+ (lambda: K.RandomRotation(400.0), r"degrees out of bounds\. .*got tensor\(\[-400\., 400\.\]\)"),+ (lambda: K.RandomShear(400.0), r"shear-x out of bounds\. .*got tensor\(\[-400\., 400\.\]\)"),+ (lambda: K.RandomTranslate(2.0, 0.1), r"translate_x out of bounds\. .*got tensor\(\[-2\., 2\.\]\)"),+ (lambda: K.RandomRotation90(5), r"times out of bounds\. .*got tensor\(\[-5\., 5\.\]\)"),+ (lambda: K.RandomAffine(30.0, translate=2.0), r"translate out of bounds\. .*got tensor\(\[-2\., 2\.\]\)"),+ ],+ ids=["rotation-degrees", "shear", "translate", "rotation90-times", "affine-translate"],+ )+ def test_geometric_scalar_magnitude_past_the_upper_bound_raises(self, ctor, match_msg):+ """A scalar that overshoots a geometric parameter's bound is rejected at construction."""+ with pytest.raises(ValueError, match=match_msg):+ ctor()