π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(filters): keep the gaussian kernel finite when every sample underflows (#4592)
Dipak Chaudharid68950e2f4ac
diff --git a/changelog.d/4592.fixed.md b/changelog.d/4592.fixed.mdnew file mode 100644index 000000000..cb9d40edc--- /dev/null+++ b/changelog.d/4592.fixed.md@@ -0,0 +1 @@+`kornia.filters.kernels.gaussian` no longer returns NaN when every sample underflows, which a small `sigma` (or `sigma = 0`) on a short window caused. It returns the unit-impulse limit instead, so `RandomGaussianIllumination` produces a finite image for every `sigma` its constructor accepts. Kernels with an odd window are bit-identical to before; an even window can differ in the last bit (half a float32 epsilon at worst over window sizes 1 to 31), because the nearest sample now sits a quarter-pixel away and that subtraction rounds. The impulse limit is differentiable: the gradient with respect to a tensor `sigma` is 0 there, the value of the continuous `sigma -> 0` limit, rather than NaN. An empty window still returns an empty kernel.diff --git a/kornia/augmentation/_2d/intensity/gaussian_illumination.py b/kornia/augmentation/_2d/intensity/gaussian_illumination.pyindex 2da3faa75..ff40fbf2b 100644--- a/kornia/augmentation/_2d/intensity/gaussian_illumination.py+++ b/kornia/augmentation/_2d/intensity/gaussian_illumination.py@@ -70,8 +70,7 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):- the class draws ``_params["gradient"]``, a tensor with the original normalized ``(B, C, H, W)``input shape; a ``(C, H, W)`` input remains batched in stored parameters even when ``keepdim=True``.It adds the field to the image and- clamps the sum into ``[0, 1]``, so the output stays inside that range even when the input does not --- except where the Gaussian kernel itself is NaN, see the warning below.+ clamps the sum into ``[0, 1]``, so the output stays inside that range even when the input does not.- ``sign`` is drawn per sample, from ``(-1.0, 1.0)`` by default, and only whether the draw is negativeis used: it decides whether that sample's gradient darkens or brightens, so one batch can hold botha darkened and a brightened image. A point range such as ``sign=1.0`` brightens every sample.@@ -79,7 +78,12 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):bound, the sum is cut there rather than rescaled.- ``sigma`` is a fraction of the axis length, not an absolute width: the generator draws it andmultiplies by the image's width and height before building the kernel, so the same ``sigma`` is a- narrower kernel on a smaller image.+ narrower kernel on a smaller image. Every admitted ``sigma`` gives a finite kernel, including the+ ``0`` the constructor's check admits: :func:`kornia.filters.gaussian` measures each sample's+ squared distance from the **nearest sample** rather than from the mean, so that sample always+ weighs ``exp(0) = 1`` and the normalizing sum cannot underflow. At ``sigma=0`` the kernel is the+ unit impulse -- all the weight on the nearest sample, or split evenly between the two that tie+ half a pixel either side of the mean on an even-length axis.- the module pickles, deep-copies and passes through ``torch.save``, and the copy reproduces theoriginal's output under the same seed. After ``.compile()``, which swaps in a compiled transform,it no longer pickles or passes through ``torch.save``, although it still deep-copies.@@ -89,23 +93,6 @@ class RandomGaussianIllumination(IntensityAugmentationBase2D):above zero; a positive sampled gradient can recover values instead. Tracked in`#4430 <https://github.com/kornia/kornia/issues/4430>`_.- .. warning::- A ``sigma`` at or near ``0``, which the constructor admits, can make the whole output NaN.- :func:`kornia.filters.gaussian` normalizes by ``gauss.sum()``, which underflows to zero there, so- the kernel is ``0 / 0``. ``sigma=0.0`` does it at any size. Above zero it is the kernel's- **absolute** width that decides -- ``sigma`` times the axis length, since ``sigma`` is relative --- and not the axis length on its own. With ``center=(0.5, 0.5)`` an even axis puts its nearest sample- half a pixel off the mean, so the kernel underflows once ``sigma * axis`` falls below about- ``0.034``: a ``4 x 4`` image at ``sigma=(0.005, 0.005)`` is NaN, and so is a ``64 x 64`` one at- ``sigma=(0.0005, 0.0005)``, while ``8 x 8`` and larger are finite at ``0.005``. An odd axis whose- rounded center lands on the grid keeps a sample at the mean and is finite at every positive- ``sigma``; the default ``center=(0.1, 0.9)`` can miss the grid only on a ``1``- or ``3``-pixel axis,- which is why a drawn center makes a ``3 x 3`` image NaN on some seeds but never a ``5 x 5`` one.- The threshold follows the **parameter** dtype, which is ``float32`` whatever the image dtype, so- after ``set_rng_device_and_dtype(device, torch.float64)`` the ``4 x 4`` case at ``sigma=0.005`` is- finite and ``0.003`` is not. The default ``sigma=(0.2, 1.0)`` is unaffected. Tracked in- `#4589 <https://github.com/kornia/kornia/issues/4589>`_.-.. note::The generated random numbers are not reproducible across different devices and dtypes. By default,the parameters will be generated on CPU. This can be changed by callingdiff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 177fc2377..de0392706 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -95,6 +95,12 @@ def gaussian(Returns:A tensor with shape :math:`(B, \text{kernel_size})`, with Gaussian values.+ .. note::+ A ``sigma`` of zero -- and any ``sigma`` too small for the window to hold a representable+ weight -- returns the unit-impulse limit of the kernel: all the mass on the sample nearest+ the mean, split evenly between the two centre taps when ``window_size`` is even. The+ gradient with respect to ``sigma`` is zero there, matching the continuous limit.+"""if isinstance(sigma, float):sigma = torch.tensor([[sigma]], device=device, dtype=dtype)@@ -115,7 +121,24 @@ def gaussian(if window_size % 2 == 0:x = x + 0.5- gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0)))+ # Measure the squared distance from the nearest sample rather than from the mean. The shift+ # cancels in the normalization, but the nearest sample now always weighs exp(0) = 1, so a+ # small sigma (or a mean far off the grid) cannot underflow every sample to 0 and divide 0 / 0.+ dist = x.pow(2.0)+ if window_size > 0:+ dist = dist - dist.min(-1, keepdim=True)[0]++ # A zero denominator is the unit-impulse limit of the kernel: sigma == 0 exactly, or a sigma+ # whose square underflows the dtype (float16 below ~1e-4). Either way the nearest samples+ # divide 0 / 0. Repairing that after the fact leaves the division on the graph and the sigma+ # gradient still comes back NaN, so divide by a stand-in and select the impulse out of that+ # finite arm instead. The gradient is then the 0 of the continuous sigma -> 0 limit. A NaN+ # sigma is not caught by the comparison and still propagates, as it did before.+ denominator = 2 * sigma.pow(2.0)+ is_impulse = denominator == 0+ safe_denominator = torch.where(is_impulse, torch.ones_like(denominator), denominator)+ gauss = torch.exp(-dist / safe_denominator)+ gauss = torch.where(is_impulse, (dist == 0).to(dist.dtype), gauss)return gauss / gauss.sum(-1, keepdim=True)@@ -576,6 +599,14 @@ def get_gaussian_kernel1d(tensor([[0.1201, 0.2339, 0.2921, 0.2339, 0.1201],[0.0096, 0.2054, 0.5699, 0.2054, 0.0096]])+ A ``sigma`` of zero, or one too small for the window to hold a representable weight,+ returns the unit impulse rather than a kernel of NaN:++ >>> get_gaussian_kernel1d(5, 0.0)+ tensor([[0., 0., 1., 0., 0.]])+ >>> get_gaussian_kernel1d(4, 0.0, force_even=True)+ tensor([[0.0000, 0.5000, 0.5000, 0.0000]])+"""_check_kernel_size(kernel_size, allow_even=force_even)diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 4016ae57f..e264720e6 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -4385,6 +4385,14 @@ class TestRandomSaltAndPepperNoise(BaseTester):class TestRandomGaussianIllumination(BaseTester):+ @pytest.mark.parametrize("sigma", [0.0, 0.001, 0.02])+ @pytest.mark.parametrize("size", [1, 2, 3, 4, 8, 32])+ def test_a_small_sigma_it_admits_returns_a_finite_image_4589(self, sigma, size, device, dtype):+ torch.manual_seed(0)+ img = torch.rand(4, 3, size, size, device=device, dtype=dtype)+ out = RandomGaussianIllumination(sigma=sigma, p=1.0)(img)+ assert torch.isfinite(out).all()+def _roundtrip(self, aug, serializer):if serializer == "pickle":return pickle.loads(pickle.dumps(aug)) # noqa: S301diff --git a/tests/augmentation/test_conventions_intensity_ops.py b/tests/augmentation/test_conventions_intensity_ops.pyindex 0b8c8df27..4823a1298 100644--- a/tests/augmentation/test_conventions_intensity_ops.py+++ b/tests/augmentation/test_conventions_intensity_ops.py@@ -30,6 +30,7 @@ import kornia.augmentation as Kfrom kornia.constants import BorderType, Resamplefrom kornia.core.exceptions import BaseError, ImageError, ShapeErrorfrom kornia.filters import box_blur, motion_blur+from kornia.filters.kernels import gaussianfrom testing.base import (DYNAMO_UNAVAILABLE_REASON,@@ -1606,69 +1607,88 @@ class TestIlluminationAndNormalizeConventions(BaseTester):reloaded = torch.load(buffer, weights_only=False)assert torch.equal(reloaded(constant), expected)- # Issue #4589: the constructor's own check admits `0 <= sigma <= 1`, but filters.kernels.gaussian- # normalizes by `gauss.sum()`, which underflows to zero at sigma 0, so the kernel is 0 / 0 and the- # whole output is NaN. An even-length axis carries a half-pixel offset, so no sample sits at the mean- # and a small non-zero sigma does it too -- with center 0.5, 4x4 is NaN at sigma 0.005 where 3x3 is not.+ # The kernel is finite at every admitted `sigma`, including the `0` the constructor's own check+ # admits (the fix for #4589: `filters.kernels.gaussian` used to normalize by `gauss.sum()`, which+ # underflowed to zero once every sample was far enough from the mean, making the kernel `0 / 0` and+ # the whole output NaN). The fix measures each sample's squared distance from the NEAREST sample+ # rather than from the mean, so the nearest one always weighs `exp(0) = 1` and the sum cannot+ # underflow. This pin covers the three legs the wart pin it replaces used to record as NaN:+ # `sigma=0` at any size, an even axis at a small non-zero sigma (the half-pixel offset leaves no+ # sample at the mean), and a small `sigma * axis` product at any size.# Snippet used to generate expected:- # torch.manual_seed(0); print(K.RandomGaussianIllumination(p=1.0, sigma=0.0)(torch.rand(1, 3, 4, 4)))- # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> every element NaN; the default- # sigma=(0.2, 1.0) is finite over 200 seeds at sizes 1..4. The even/odd leg needs `center` pinned:- # with the drawn centre the odd size is NaN on some draws too, and with centre 0.5 a 4x4 image is NaN- # at sigma 0.005 on all 30 seeds tried while 3x3 and 5x5 are finite on all of them.+ # for n, sg in ((4, 0.005), (8, 0.005), (8, 0.002), (64, 0.0005), (64, 0.00055)):+ # torch.manual_seed(0)+ # print(K.RandomGaussianIllumination(p=1.0, sigma=(sg, sg), center=(0.5, 0.5))(+ # torch.full((1, 3, n, n), 0.5)).isfinite().all())+ # print(gaussian(5, torch.tensor([[0.0]])), gaussian(4, torch.tensor([[0.0]])))+ # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes) -> finite at all five; the limit kernel+ # is `[0, 0, 1, 0, 0]` for an odd window and `[0, 0.5, 0.5, 0]` for an even one, where the two+ # samples either side of the mean tie at half a pixel.@pytest.mark.parametrize("size", [3, 4])- def test_wart_random_gaussian_illumination_zero_sigma_is_nan_4589(self, device, dtype, size):+ def test_convention_random_gaussian_illumination_is_finite_at_every_sigma(self, device, dtype, size):image = torch.full((1, 3, size, size), 0.5, device=device, dtype=dtype)torch.manual_seed(_FORWARD_SEED)- assert bool(K.RandomGaussianIllumination(p=1.0, sigma=0.0)(image).isnan().all())- # The even axis loses the on-grid sample to the half-pixel offset, so it is NaN at a small- # non-zero sigma that the odd one survives.+ assert bool(K.RandomGaussianIllumination(p=1.0, sigma=0.0)(image).isfinite().all())+ # The even axis loses the on-grid sample to the half-pixel offset; it is finite now as well.for sigma in (0.005, 0.01):torch.manual_seed(_FORWARD_SEED)small = K.RandomGaussianIllumination(p=1.0, sigma=(sigma, sigma), center=(0.5, 0.5))(image)- if sigma == 0.005 and size % 2 == 0:- assert bool(small.isnan().all())- else:- assert bool(small.isfinite().all())- # Evenness is not the variable: `sigma` is relative, so it is `sigma * axis` -- the kernel's- # absolute width -- that underflows, at about 0.034 in the float32 the parameters are drawn in.- # An `8 x 8` image is finite at the sigma that kills `4 x 4`, and a `64 x 64` one dies at a- # proportionally smaller sigma. The even/odd leg above runs only at sizes 3 and 4 and cannot- # see either half.- # Snippet used to generate expected:- # for n, sg in ((4, 0.005), (8, 0.005), (8, 0.002), (64, 0.0005), (64, 0.00055)):- # torch.manual_seed(0)- # K.RandomGaussianIllumination(p=1.0, sigma=(sg, sg), center=(0.5, 0.5))(- # torch.full((1, 3, n, n), 0.5))- # executed 2026-09-16 (torch 2.14.0, cpu, all four dtypes -- the parameters are float32 in- # every one of them) -> NaN, finite, NaN, NaN, finite. `n * sigma` is 0.020, 0.040, 0.016,- # 0.032 and 0.035 respectively, so the cut is on the product and not on `n`.- for axis, small_sigma, nan_expected in ((4, 0.005, True), (8, 0.005, False), (8, 0.002, True)):+ assert bool(small.isfinite().all()), (size, sigma)+ # It is the kernel's ABSOLUTE width -- `sigma * axis`, since `sigma` is relative -- that used to+ # underflow, at about 0.034 in the float32 the parameters are drawn in. These five products+ # (0.020, 0.040, 0.016, 0.032, 0.035) straddle that threshold; all five are finite now.+ for axis, small_sigma in ((4, 0.005), (8, 0.005), (8, 0.002), (64, 0.0005), (64, 0.00055)):square = torch.full((1, 3, axis, axis), 0.5, device=device, dtype=dtype)torch.manual_seed(_FORWARD_SEED)out = K.RandomGaussianIllumination(p=1.0, sigma=(small_sigma, small_sigma), center=(0.5, 0.5))(square)- assert bool(out.isnan().all()) is nan_expected, (axis, small_sigma)- # The parameter dtype, not the image dtype, sets the threshold: float64 parameters move it.- # MPS has no float64, so this leg is CPU/CUDA only.- if device.type != "mps":- wide = torch.full((1, 3, 4, 4), 0.5, device=device, dtype=dtype)- for param_sigma, nan_expected in ((0.005, False), (0.003, True)):- aug = K.RandomGaussianIllumination(p=1.0, sigma=(param_sigma, param_sigma), center=(0.5, 0.5))- aug.set_rng_device_and_dtype(device, torch.float64)- torch.manual_seed(_FORWARD_SEED)- assert bool(aug(wide).isnan().all()) is nan_expected, param_sigma- # And with the DRAWN centre an odd axis is safe from 5 up, where 1 and 3 are not.- for odd, safe in ((3, False), (5, True), (7, True)):- hits = 0+ assert bool(out.isfinite().all()), (axis, small_sigma)+ # And with the DRAWN centre, which the wart pin recorded as NaN on some seeds at 1 and 3.+ for odd in (1, 3, 5, 7):for seed in range(16):torch.manual_seed(seed)odd_image = torch.full((1, 3, odd, odd), 0.5, device=device, dtype=dtype)- hits += bool(K.RandomGaussianIllumination(p=1.0, sigma=(0.005, 0.005))(odd_image).isnan().any())- assert (hits == 0) is safe, (odd, hits)- # The documented default is unaffected, so the wart is the admitted extreme and not the class.+ assert bool(K.RandomGaussianIllumination(p=1.0, sigma=(0.005, 0.005))(odd_image).isfinite().all()), (+ odd,+ seed,+ )+ # The documented default was never affected and must stay unaffected.torch.manual_seed(_FORWARD_SEED)assert bool(K.RandomGaussianIllumination(p=1.0)(image).isfinite().all())+ # At `sigma=0` the kernel is the unit impulse: all the weight on the sample nearest the mean, which+ # for an even window is the two samples that tie half a pixel either side of it. This is the limit+ # the `masked_fill` encodes, and it is the part of the #4589 fix that is a NEW contract rather than+ # the removal of a NaN, so it is pinned separately from the finiteness above.+ @pytest.mark.device_agnostic+ def test_convention_gaussian_kernel_at_zero_sigma_is_the_unit_impulse(self):+ odd = gaussian(5, torch.tensor([[0.0]]))+ assert odd.flatten().tolist() == [0.0, 0.0, 1.0, 0.0, 0.0]+ even = gaussian(4, torch.tensor([[0.0]]))+ assert even.flatten().tolist() == [0.0, 0.5, 0.5, 0.0]+ # Every window sums to 1, so the impulse is a normalized kernel and not a degenerate one.+ for window in (1, 2, 3, 4, 5, 8, 9):+ assert float(gaussian(window, torch.tensor([[0.0]])).sum()) == pytest.approx(1.0)++ # An ODD window is bit-identical to the pre-fix formula at every ordinary sigma -- the shift cancels+ # exactly, because the nearest sample sits at distance 0 and subtracting 0 is exact. An EVEN window+ # is not: the nearest samples sit at 0.25 (half a pixel squared), the subtraction is inexact, and the+ # kernel moves by up to half a float32 eps. That is a rounding difference and not a behaviour change,+ # but it is the reason an even-window kernel is not byte-comparable across this fix.+ # Snippet used to generate expected:+ # compare gaussian(ws, sigma) against `exp(-x**2 / (2*sigma**2))` normalized, for ws 1..31 and+ # sigma in (0.1, 0.3, 0.5, 0.8, 1.0, 1.5, 2.0, 3.0, 5.0, 10.0)+ # executed 2026-09-16 (torch 2.14.0, cpu) -> odd 160 of 160 bit-identical; even 134 of 150 differ,+ # worst absolute delta 5.96e-08, which is 0.5 * float32 eps.+ @pytest.mark.device_agnostic+ def test_convention_gaussian_odd_window_is_unchanged_by_the_nearest_sample_shift(self):+ for window in (1, 3, 5, 7, 9, 15, 31):+ for sigma in (0.1, 0.5, 1.0, 3.0, 10.0):+ sigma_t = torch.tensor([[sigma]])+ x = (torch.arange(window, dtype=sigma_t.dtype) - window // 2).expand(1, -1)+ reference = torch.exp(-x.pow(2.0) / (2 * sigma_t.pow(2.0)))+ reference = reference / reference.sum(-1, keepdim=True)+ assert torch.equal(gaussian(window, sigma_t), reference), (window, sigma)+# `.compile()` on RandomGaussianIllumination swaps in a compiled transform that neither pickle nor# torch.save can serialize, while deepcopy still works; the linear classes keep pickling. Measured# on cpu: `PicklingError: Can't pickle <function _apply_gaussian_illumination ...>` for both, and adiff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.pyindex 119ca157a..960876af6 100644--- a/tests/filters/test_gaussian.py+++ b/tests/filters/test_gaussian.py@@ -69,6 +69,47 @@ def test_gaussian(window_size, sigma, mean, expected, device, dtype):assert_close(result, expected, atol=1e-4, rtol=1e-4)+ "window_size, sigma, mean, expected",+ [+ # Every sample used to underflow to 0 here, and the normalization divided 0 / 0 (#4589).+ (4, 0.02, None, [0.0, 0.5, 0.5, 0.0]),+ (8, 1e-4, None, [0.0, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0]),+ (5, 0.05, 0.0, [1.0, 0.0, 0.0, 0.0, 0.0]),+ (4, 1.0, 40.0, [0.0, 0.0, 0.0, 1.0]),+ # At sigma == 0 the kernel is the unit-impulse limit instead of nan.+ (5, 0.0, None, [0.0, 0.0, 1.0, 0.0, 0.0]),+ (4, 0.0, None, [0.0, 0.5, 0.5, 0.0]),+ (1, 0.0, None, [1.0]),+ ],+)+def test_gaussian_does_not_underflow_to_nan_4589(window_size, sigma, mean, expected, device, dtype):+ result = gaussian(window_size, sigma, mean=mean, device=device, dtype=dtype)+ assert_close(result, torch.tensor([expected], device=device, dtype=dtype), atol=1e-4, rtol=1e-4)++[email protected]("window_size", [4, 5])+def test_gaussian_sigma_gradient_is_finite_at_zero_4589(window_size, device, dtype):+ # The impulse limit is reachable with a tensor sigma, so it has to be differentiable too.+ # Dividing by sigma ** 2 first and repairing the result afterwards left the 0 / 0 on the+ # graph, and the sigma gradient came back nan even though the forward value was finite.+ sigma = torch.zeros(1, 1, device=device, dtype=dtype, requires_grad=True)++ out = gaussian(window_size, sigma)+ (out * torch.arange(window_size, device=device, dtype=dtype)).sum().backward()++ assert torch.isfinite(out).all()+ assert torch.isfinite(sigma.grad).all()+ # The continuous limit is flat at sigma == 0: the impulse does not move as sigma grows.+ assert_close(sigma.grad, torch.zeros_like(sigma.grad))+++def test_gaussian_empty_window_stays_empty_4589(device, dtype):+ # kornia's convention for a degenerate shape is empty in, empty out. Subtracting the nearest+ # sample means reducing over the window, which has no identity when the window is empty.+ assert gaussian(0, 1.0, device=device, dtype=dtype).shape == (1, 0)++@pytest.mark.parametrize("window_size", [5, 11])@pytest.mark.parametrize("sigma", [1.5, 5.0])def test_get_gaussian_kernel1d_float(window_size, sigma, device, dtype):