π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): avoid evaluating skipped image inputs (#5732)
Manu-27174adfb6435a4f
diff --git a/changelog.d/5732.fixed.md b/changelog.d/5732.fixed.mdnew file mode 100644index 000000000..7f31e2f3d--- /dev/null+++ b/changelog.d/5732.fixed.md@@ -0,0 +1 @@+Below `p=1`, `RandomEqualize`, `RandomEqualize3D` and `RandomClahe` no longer raise for an out-of-range image the gate skips, and `RandomGamma` no longer gives a skipped sample a NaN gradient where its value is 0. These classes now run the transform on 0.5 for skipped samples; the selected samples and every other augmentation are unchanged.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 8927dc3c4..893e394ce 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -495,10 +495,16 @@ Randomness in augmentationschild's setting, and ``True`` or ``False`` overwrites it.- Whether a constructor's ``p`` sets the per-sample or the whole-batch gate,and whether it exposes ``p_batch``, depends on the concrete class- (`#4425 <https://github.com/kornia/kornia/issues/4425>`_). The gate selects- after the transform has run on the whole batch, so a skipped sample can still- raise or carry a NaN gradient- (`#4576 <https://github.com/kornia/kornia/issues/4576>`_).+ (`#4425 <https://github.com/kornia/kornia/issues/4425>`_). A sample the gate+ skips comes back with its input values, its values cannot make the call+ raise, and where they are finite its gradient is the identity. Below ``p=1``+ the transform still runs on the whole batch before the gate selects; classes+ whose transform checks input values or has an unbounded derivative+ (``RandomEqualize``, ``RandomEqualize3D``, ``RandomClahe``, ``RandomGamma``)+ run it on the value 0.5 for skipped samples. An augmentation that changes the+ sample shape, such as ``RandomCrop`` or ``Resize``, still raises+ ``ValueError`` when the gate mixes applied and skipped samples+ (`#4497 <https://github.com/kornia/kornia/issues/4497>`_).Serializing an augmentation^^^^^^^^^^^^^^^^^^^^^^^^^^^diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex 37d3be65d..29a7f76d2 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -85,9 +85,11 @@ class AugmentationBase2D(_AugmentationBase):(`#4424 <https://github.com/kornia/kornia/issues/4424>`_).- this base samples ``p`` per sample and uses ``p_batch`` as a call-wide gate. ``same_on_batch=True``shares applicable sampled values across the batch. Concrete constructors need not expose ``p_batch``;- see `#4425 <https://github.com/kornia/kornia/issues/4425>`_. The gate selects after the transform- has been computed for the whole batch, so a sample it skips can still raise or carry a NaN gradient- (`#4576 <https://github.com/kornia/kornia/issues/4576>`_).+ see `#4425 <https://github.com/kornia/kornia/issues/4425>`_. A sample the gate skips comes back+ with its input values, its values cannot make the call raise, and where they are finite its gradient+ is the identity; a class whose transform checks input values or has an unbounded derivative runs it+ on 0.5 for skipped samples. An augmentation that changes the sample shape still raises ``ValueError``+ when the gate mixes applied and skipped samples (`#4497 <https://github.com/kornia/kornia/issues/4497>`_).- parameter sampling normally uses CPU defaults independently of the image device. Moving RNG state orsamplers is incomplete for some generators, and returned parameter placement is a separate concern;see `#4426 <https://github.com/kornia/kornia/issues/4426>`_.diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.pyindex c832ff142..e9c5aaee8 100644--- a/kornia/augmentation/_2d/intensity/base.py+++ b/kornia/augmentation/_2d/intensity/base.py@@ -76,11 +76,10 @@ class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D)::doc:`/get-started/conventions`. The base does not validate it; each class page states what the classdoes 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- check still makes the call raise -- :class:`RandomEqualize` and :class:`RandomClahe` raise for an- out-of-range image even at ``p=0.0`` -- and a skipped sample's gradient can be NaN where the- transform's derivative is infinite (`#4576 <https://github.com/kornia/kornia/issues/4576>`_).+ transforms; every other sample comes back with its input values and, where they are finite, an+ identity gradient. Below ``p=1`` :class:`RandomEqualize`, :class:`RandomClahe` and :class:`RandomGamma`+ run their transform on 0.5 for the skipped samples, so an out-of-range skipped image does not make them+ raise.- the scalar factors a concrete class draws are per sample -- one value, or one per channelper 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`,diff --git a/kornia/augmentation/_2d/intensity/clahe.py b/kornia/augmentation/_2d/intensity/clahe.pyindex 39b613dee..2f700eaa4 100644--- a/kornia/augmentation/_2d/intensity/clahe.py+++ b/kornia/augmentation/_2d/intensity/clahe.py@@ -81,6 +81,8 @@ class RandomClahe(IntensityAugmentationBase2D):"""+ SUBSTITUTE_SKIPPED_SAMPLES = True+def __init__(self,clip_limit: tuple[float, float] = (40.0, 40.0),diff --git a/kornia/augmentation/_2d/intensity/equalize.py b/kornia/augmentation/_2d/intensity/equalize.pyindex ce1ad8e4d..bbd71a312 100644--- a/kornia/augmentation/_2d/intensity/equalize.py+++ b/kornia/augmentation/_2d/intensity/equalize.py@@ -68,6 +68,8 @@ class RandomEqualize(IntensityAugmentationBase2D):"""+ SUBSTITUTE_SKIPPED_SAMPLES = True+def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)diff --git a/kornia/augmentation/_2d/intensity/gamma.py b/kornia/augmentation/_2d/intensity/gamma.pyindex db4081214..c2ccbee3a 100644--- a/kornia/augmentation/_2d/intensity/gamma.py+++ b/kornia/augmentation/_2d/intensity/gamma.py@@ -84,6 +84,8 @@ class RandomGamma(IntensityAugmentationBase2D):"""+ SUBSTITUTE_SKIPPED_SAMPLES = True+def __init__(self,gamma: Tuple[float, float] = (1.0, 1.0),diff --git a/kornia/augmentation/_3d/intensity/equalize.py b/kornia/augmentation/_3d/intensity/equalize.pyindex fbc756bb0..c654dc74c 100644--- a/kornia/augmentation/_3d/intensity/equalize.py+++ b/kornia/augmentation/_3d/intensity/equalize.py@@ -73,6 +73,8 @@ class RandomEqualize3D(IntensityAugmentationBase3D):"""+ SUBSTITUTE_SKIPPED_SAMPLES = True+def __init__(self, p: float = 0.5, same_on_batch: bool = False, keepdim: bool = False) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 63faac748..16a40ac9e 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -368,6 +368,9 @@ class _AugmentationBase(_BasicAugmentationBase):"""+ # Only transforms that reject skipped input values or have unbounded derivatives need substitution.+ SUBSTITUTE_SKIPPED_SAMPLES = False+def apply_transform(self,input: torch.Tensor,@@ -438,8 +441,6 @@ class _AugmentationBase(_BasicAugmentationBase):self.validate_tensor(in_tensor)- output_transformed = self.apply_transform(in_tensor, params, flags, transform=transform)-if self.p == 1.0 and self.p_batch == 1.0:# Always applied (static probabilities): the output is unconditionally the# transformed one. Skip the non-transform branch and the blend entirely β this@@ -447,9 +448,14 @@ class _AugmentationBase(_BasicAugmentationBase):# since the data-dependent shape comparison / `to_apply.any()` fallback is avoided.# (The `to_apply` gate is only needed on the p < 1 path below, so it is not computed# here.)- output = output_transformed+ output = self.apply_transform(in_tensor, params, flags, transform=transform)else:to_apply = torch.atleast_1d(params["batch_prob"] > 0.5)+ transform_input = in_tensor+ if self.SUBSTITUTE_SKIPPED_SAMPLES:+ gate = to_apply.view(-1, *([1] * (in_tensor.ndim - 1))).to(in_tensor.device)+ transform_input = torch.where(gate, in_tensor, 0.5)+ output_transformed = self.apply_transform(transform_input, params, flags, transform=transform)output_not_transformed = self.apply_non_transform(in_tensor, params, flags, transform=transform)output = self._blend_by_prob(output_transformed, output_not_transformed, to_apply)diff --git a/tests/augmentation/test_conventions_intensity_values.py b/tests/augmentation/test_conventions_intensity_values.pyindex d9e021b83..9680019f9 100644--- a/tests/augmentation/test_conventions_intensity_values.py+++ b/tests/augmentation/test_conventions_intensity_values.py@@ -411,36 +411,71 @@ class TestIntensityValueRangeConventions(BaseTester):assert out.shape == image.shapeassert torch.isfinite(out).all()- # Issue #4576: below p=1 the base computes the transform for the whole batch and then selects the- # rows the gate keeps (`_AugmentationBase.transform_inputs`), so a row the gate skips still reaches- # the value check and the backward pass. At p=0.0 RandomEqualize and RandomClahe raise for an image- # they never touch, and RandomGamma returns the input values but a NaN gradient where the discarded- # power's derivative is infinite.- # Snippet used to generate expected:- # g = torch.linspace(0, 1, 1024).reshape(1, 1, 32, 32); x = torch.cat([g, g * 2])- # torch.manual_seed(0); K.RandomEqualize(p=0.0)(x) # and K.RandomClahe(p=0.0)(x)- # v = torch.tensor([0.0, 0.25, 1.0]).reshape(1, 1, 1, 3).repeat(2, 1, 1, 1).requires_grad_()- # torch.manual_seed(0); y = K.RandomGamma((0.5, 0.5), (1.0, 1.0), p=0.0)(v); y.sum().backward()- # print(torch.equal(y, v), v.grad.flatten().tolist()) # -> 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")+ # Issue #4576: a skipped row must not trigger a value check or contribute a NaN gradient.+ def test_convention_p_gate_skipped_sample_has_no_effect_4576(self, device, dtype):ramp = torch.linspace(0, 1, 1024).reshape(1, 1, 32, 32)image = torch.cat([ramp, ramp * 2.0]).to(device=device, dtype=dtype)for cls in (K.RandomEqualize, K.RandomClahe):torch.manual_seed(_FORWARD_SEED)- # It has to be the value check that fires, not merely some RuntimeError: the claim is that- # the transform ran on a sample `p=0.0` was supposed to skip.- with pytest.raises(RuntimeError, match=r"\[0, 1\]"):- _sync(cls(p=0.0)(image).device)+ out = cls(p=0.0)(image)+ assert torch.equal(out, image)+ volume = image.reshape(2, 1, 4, 16, 16)+ assert torch.equal(K.RandomEqualize3D(p=0.0)(volume), volume)values = torch.tensor([0.0, 0.25, 1.0]).reshape(1, 1, 1, 3).repeat(2, 1, 1, 1)values = values.to(device=device, dtype=dtype).requires_grad_()torch.manual_seed(_FORWARD_SEED)out = K.RandomGamma((0.5, 0.5), (1.0, 1.0), p=0.0)(values)assert torch.equal(out, values)out.sum().backward()- assert bool(values.grad[..., 0].isnan().all())- self.assert_close(values.grad[..., 1:], torch.ones_like(values.grad[..., 1:]))+ assert torch.isfinite(values.grad).all()+ self.assert_close(values.grad, torch.ones_like(values.grad))++ @pytest.mark.parametrize("cls", [K.RandomEqualize, K.RandomClahe])+ def test_mixed_p_gate_skips_invalid_image_4576(self, cls, device, dtype):+ ramp = torch.linspace(0, 1, 1024, device=device, dtype=dtype).reshape(1, 1, 32, 32)+ image = torch.cat([ramp, ramp * 2.0])+ aug = cls(p=0.5)+ params = aug.forward_parameters(image.shape)+ params["batch_prob"] = torch.tensor([1.0, 0.0], device=params["batch_prob"].device)+ out = aug(image, params=params)+ expected = cls(p=1.0)(image[:1])+ self.assert_close(out[:1], expected)+ assert torch.equal(out[1:], image[1:])++ def test_mixed_p_gate_skipped_gamma_gradient_is_identity_4576(self, device, dtype):+ image = torch.tensor([[[[0.25, 0.5, 1.0]]], [[[0.0, 0.25, 0.5]]]], device=device, dtype=dtype).requires_grad_()+ aug = K.RandomGamma((0.5, 0.5), (1.0, 1.0), p=0.5)+ params = aug.forward_parameters(image.shape)+ params["batch_prob"] = torch.tensor([1.0, 0.0], device=params["batch_prob"].device)+ out = aug(image, params=params)+ self.assert_close(out[0], image[0].sqrt())+ 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[1], torch.ones_like(image.grad[1]))++ @pytest.mark.parametrize(+ ("factory", "substituted"),+ [(lambda: K.RandomGamma((0.5, 0.5), p=0.5), True), (lambda: K.RandomBrightness((0.9, 1.1), p=0.5), False)],+ )+ def test_p_gate_substitutes_skipped_samples_only_where_needed_4576(self, factory, substituted, device, dtype):+ image = torch.linspace(0, 1, 384, device=device, dtype=dtype).reshape(2, 3, 8, 8)+ aug = factory()+ params = aug.forward_parameters(image.shape)+ params["batch_prob"] = torch.tensor([1.0, 0.0])+ seen = []+ original = aug.apply_transform++ def spy(input, *args, **kwargs):+ seen.append(input)+ return original(input, *args, **kwargs)++ aug.apply_transform = spy+ aug(image, params=params)+ assert torch.equal(seen[0][0], image[0])+ assert torch.equal(seen[0][1], torch.full_like(image[1], 0.5) if substituted else image[1])class TestIntensityColourConventions(BaseTester):