Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters): stabilize discrete Gaussian kernels across dtypes (#5238)

Ge Li8c240ab50f84
diff --git a/README.md b/README.md
index 2a7ca3cb0..f1c1b17cf 100644
--- a/README.md
+++ b/README.md
@@ -93,7 +93,7 @@ covers CUDA or MPS half precision.
| Module | float16 | bfloat16 | Known failures (fp16 / bf16) | Notes |
|--------|:-------:|:--------:|:----------------------------:|-------|
| `kornia.color` | ⚠️ | ⚠️ | 3 / 9 | float16: HLS JIT/module and RGB255 round-trip accuracy; bfloat16: Lab, Luv and RGB255 accuracy |
-| `kornia.filters` | ⚠️ | ⚠️ | 18 / 9 | Accuracy misses in Canny magnitudes, discrete Gaussian kernels and Otsu; on CPU `fft_conv` runs its FFTs in float32 |
+| `kornia.filters` | ⚠️ | ⚠️ | 6 / 8 | Accuracy misses in Canny magnitudes, the sampled Gaussian kernel and separable blur; on CPU `fft_conv` runs its FFTs in float32 |
| `kornia.enhance` | ✅ | ⚠️ | 0 / 2 | bfloat16: `DiffJPEG` and ZCA accuracy |
| `kornia.morphology` | ✅ | ✅ | 0 / 0 | |
| `kornia.augmentation` | ⚠️ | ⚠️ | 200 / 56 | float16: 108 entries are `CutmixGenerator`, whose Dirichlet sampling rejects float16 parameters; bfloat16: mostly 3D-augmentation gradient checks (28 of 56 entries are `RandomMotionBlur3D`/`RandomRotation3D` backward) |
diff --git a/changelog.d/5238.fixed.md b/changelog.d/5238.fixed.md
new file mode 100644
index 000000000..e9a6fc873
--- /dev/null
+++ b/changelog.d/5238.fixed.md
@@ -0,0 +1,7 @@
+`get_gaussian_discrete_kernel1d` computes the exponentially scaled Bessel terms
+`exp(-sigma**2) I_n(sigma**2)` directly, using float32 intermediates for float16 and bfloat16
+inputs and returning the input dtype. This fixes NaN kernels at large sigma values and, for
+float16 with kernel sizes of at least 5, at ordinary positive sigma values as well.
+Finite float64 outputs also change for sigma values from about 7 to 19: previously inaccurate
+kernels now agree with the normalized reference. For `kernel_size=7, sigma=18`, the maximum
+absolute error per tap decreases from about 0.021 to 4.9e-8.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index f5f38e973..71609f4e3 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -610,9 +610,7 @@ The kernel builders against their references:
``cv2.getGaussianKernel(k, sigma)`` and the weights ``scipy.ndimage.gaussian_filter1d`` applies with
``radius=k // 2``. :func:`~kornia.filters.get_gaussian_erf_kernel1d` is the pixel-integrated Gaussian and
:func:`~kornia.filters.get_gaussian_discrete_kernel1d` is Lindeberg's discrete Gaussian,
- ``scipy.special.ive(abs(n), sigma**2)`` normalized, except for a large ``sigma`` (in float16, any ``sigma`` once
- ``kernel_size`` is 5 or more), where its Bessel terms drift or overflow
- (`#5227 <https://github.com/kornia/kornia/issues/5227>`_).
+ ``scipy.special.ive(abs(n), sigma**2)`` normalized.
- :func:`~kornia.filters.get_hanning_kernel1d` is the symmetric window of ``numpy.hanning(k)``,
``scipy.signal.windows.hann(k)`` and ``torch.hann_window(k, periodic=False)``; torch's default periodic window
differs.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index 3000b35e8..6bf5f2ed4 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -31,9 +31,9 @@ precision, so the table says nothing about those backends.
* - ``kornia.filters``
- ⚠️ Partial
- ⚠️ Partial
- - 14 / 8
- - Accuracy misses in Canny magnitudes and discrete Gaussian kernels. On CPU, ``fft_conv`` computes its FFTs
- in float32 and returns the input dtype.
+ - 6 / 8
+ - Accuracy misses in Canny magnitudes, the sampled Gaussian kernel and separable blur. On CPU, ``fft_conv``
+ computes its FFTs in float32 and returns the input dtype.
* - ``kornia.enhance``
- ✅ Yes
- ⚠️ Partial
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index e9857482f..10394a183 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -222,7 +222,7 @@ def gaussian_discrete_erf(
return gauss / gauss.sum(-1, keepdim=True)
-def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:
+def _modified_bessel_0(x: torch.Tensor, scaled: bool = False) -> torch.Tensor:
"""Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
Both polynomial branches are evaluated on the full tensor and merged with ``torch.where`` (instead
@@ -232,7 +232,8 @@ def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:
idx_a = ax < 3.75
# small-argument branch (|x| < 3.75)
- y = (x / 3.75) * (x / 3.75)
+ x_a = torch.where(idx_a, x, torch.zeros_like(x))
+ y = (x_a / 3.75) * (x_a / 3.75)
out_a = 1.0 + y * (
3.5156229 + y * (3.0899424 + y * (1.2067492 + y * (0.2659732 + y * (0.360768e-1 + y * 0.45813e-2))))
)
@@ -242,12 +243,14 @@ def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:
y = 3.75 / ax_b
ans = 0.916281e-2 + y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1 + y * 0.392377e-2)))
coef = 0.39894228 + y * (0.1328592e-1 + y * (0.225319e-2 + y * (-0.157565e-2 + y * ans)))
- out_b = (ax_b.exp() / ax_b.sqrt()) * coef
+ out_b = coef / ax_b.sqrt() if scaled else (ax_b.exp() / ax_b.sqrt()) * coef
+ if scaled:
+ out_a = out_a * (-x_a.abs()).exp()
return torch.where(idx_a, out_a, out_b)
-def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor:
+def _modified_bessel_1(x: torch.Tensor, scaled: bool = False) -> torch.Tensor:
"""Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
Branch-free like :func:`_modified_bessel_0`.
@@ -256,29 +259,35 @@ def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor:
idx_a = ax < 3.75
# small-argument branch (|x| < 3.75)
- y = (x / 3.75) * (x / 3.75)
+ x_a = torch.where(idx_a, x, torch.zeros_like(x))
+ y = (x_a / 3.75) * (x_a / 3.75)
ans = 0.51498869 + y * (0.15084934 + y * (0.2658733e-1 + y * (0.301532e-2 + y * 0.32411e-3)))
- out_a = ax * (0.5 + y * (0.87890594 + y * ans))
+ out_a = x_a.abs() * (0.5 + y * (0.87890594 + y * ans))
# large-argument branch; clamp keeps the unused lanes finite (|x| = 0 would divide by zero)
ax_b = torch.where(idx_a, torch.full_like(ax, 3.75), ax)
y = 3.75 / ax_b
ans = 0.2282967e-1 + y * (-0.2895312e-1 + y * (0.1787654e-1 - y * 0.420059e-2))
ans = 0.39894228 + y * (-0.3988024e-1 + y * (-0.362018e-2 + y * (0.163801e-2 + y * (-0.1031555e-1 + y * ans))))
- ans = ans * ax_b.exp() / ax_b.sqrt()
+ ans = ans / ax_b.sqrt() if scaled else ans * ax_b.exp() / ax_b.sqrt()
+ if scaled:
+ out_a = out_a * (-x_a.abs()).exp()
out_b = torch.where(x < 0, -ans, ans)
return torch.where(idx_a, out_a, out_b)
-def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:
+def _modified_bessel_i(n: int, x: torch.Tensor, scaled: bool = False, max_order: Optional[int] = None) -> torch.Tensor:
"""Adapted from: https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py."""
KORNIA_CHECK(n >= 2, "n must be greater than 1.99")
# I_n(0) = 0 for n >= 1. The zero lanes are computed on a safe placeholder and masked out at the
# end instead of being compacted away, so the recurrence has no data-dependent control flow.
is_zero_mask = torch.isclose(x, torch.tensor(0.0, device=x.device, dtype=x.dtype))
- x_nz = torch.where(is_zero_mask, torch.ones_like(x), x)
+ order = n if max_order is None else max_order
+ # A ~1e-7 approximation mismatch here can make finite-difference gradcheck fail exactly at the branch switch.
+ use_forward = x.abs() > order * order / 4 if scaled else torch.zeros_like(x, dtype=torch.bool)
+ x_nz = torch.where(is_zero_mask | use_forward, torch.ones_like(x), x)
tox = 2.0 / x_nz.abs()
@@ -286,7 +295,7 @@ def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:
bip = torch.zeros_like(x)
bi = torch.ones_like(x)
- m = int(2 * (n + int(math.sqrt(40.0 * n))))
+ m = int(2 * (order + int(math.sqrt(40.0 * order))))
for j in range(m, 0, -1):
bim = torch.addcmul(bip, tox, bi, value=j)
bip, bi = bi, bim
@@ -300,10 +309,21 @@ def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:
if j == n:
ans = bip
- out = ans * _modified_bessel_0(x_nz) / bi
+ out = ans * _modified_bessel_0(x_nz, scaled=scaled) / bi
if (n % 2) == 1:
out = torch.where(x_nz < 0.0, -out, out)
+ if scaled:
+ # Upward recurrence is stable when all requested orders are small relative to sqrt(x).
+ x_up = torch.where(use_forward, x.abs(), torch.full_like(x, order * order / 4))
+ previous = _modified_bessel_0(x_up, scaled=True)
+ current = _modified_bessel_1(x_up, scaled=True)
+ for k in range(1, n):
+ previous, current = current, previous - (2.0 * k / x_up) * current
+ if (n % 2) == 1:
+ current = torch.where(x < 0, -current, current)
+ out = torch.where(use_forward, current, out)
+
return torch.where(is_zero_mask, torch.zeros_like(x), out)
@@ -333,18 +353,20 @@ def gaussian_discrete(
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
+ output_dtype = sigma.dtype
+ if sigma.dtype in (torch.float16, torch.bfloat16):
+ sigma = sigma.float()
sigma2 = sigma * sigma
tail = int(window_size // 2) + 1
bessels = [
- _modified_bessel_0(sigma2),
- _modified_bessel_1(sigma2),
- *(_modified_bessel_i(k, sigma2) for k in range(2, tail)),
+ _modified_bessel_0(sigma2, scaled=True),
+ _modified_bessel_1(sigma2, scaled=True),
+ *(_modified_bessel_i(k, sigma2, scaled=True, max_order=tail) for k in range(2, tail)),
]
- # NOTE: on monain is exp(-sig)
- # https://github.com/Project-MONAI/MONAI/blob/dev/monai/networks/layers/convutils.py#L128
- out = torch.cat(bessels[:0:-1] + bessels, -1) * sigma2.exp()
+ # The exp(-sigma²) factor is already included in the scaled Bessel terms.
+ out = torch.cat(bessels[:0:-1] + bessels, -1)
- return out / out.sum(-1, keepdim=True)
+ return (out / out.sum(-1, keepdim=True)).to(output_dtype)
def laplacian_1d(
@@ -784,15 +806,10 @@ def get_gaussian_discrete_kernel1d(
- See the Convention block on :func:`~kornia.filters.get_gaussian_kernel1d`. In a floating ``dtype`` this
kernel is Lindeberg's discrete Gaussian :math:`e^{-\sigma^2} I_{|n|}(\sigma^2)`, with :math:`I_n` the
modified Bessel function of the first kind, normalized over the window: the smoothing kernel of discrete
- scale space.
- - Known defects:
-
- - the tap count is not always ``kernel_size``: ``kernel_size=1`` gives 3 taps, and an even size with
- ``force_even=True`` gives one more than asked (`#5158 <https://github.com/kornia/kornia/issues/5158>`_).
- - the Bessel terms are computed unscaled and overflow, so the kernel is all NaN for a large ``sigma``
- (from about 7 in float32) and, in float16, for any ``sigma > 0`` once ``kernel_size`` is 5 or more. In
- float64, before it overflows at a ``sigma`` of about 19, it drifts from the discrete Gaussian from about
- 9 and is no longer unimodal from about 14 (`#5227 <https://github.com/kornia/kornia/issues/5227>`_).
+ scale space. A float16 or bfloat16 kernel is computed in float32 and rounded to its ``dtype``.
+ - Known defect: the tap count is not always ``kernel_size``. ``kernel_size=1`` gives 3 taps, and an even
+ size with ``force_even=True`` gives one more than asked
+ (`#5158 <https://github.com/kornia/kornia/issues/5158>`_).
Args:
kernel_size: filter size. It should be odd and positive.
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index f394b199a..ad4dbf4e2 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -185,14 +185,6 @@ call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnit
call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_threshold[cpu-float16]
call builtins.AssertionError tests/filters/test_gaussian.py::TestGaussianBlur2d::test_separable_vs_non_separable_small_kernel[cpu-float16]
call builtins.AssertionError tests/filters/test_gaussian.py::test_gaussian[cpu-float16-11-11.0-3.0-expected3]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_float[cpu-float16-1.5-11]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_float[cpu-float16-1.5-5]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_float[cpu-float16-5.0-11]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_float[cpu-float16-5.0-5]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma0-11]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma0-5]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma1-11]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_get_gaussian_discrete_kernel1d_tensor[cpu-float16-sigma1-5]
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[cpu-float16-20]
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[cpu-float16-6]
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam_weighted[cpu-float16-16]
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 7fd1457cc..8621e15a7 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -1819,10 +1819,8 @@ _UNIT_SUM_KERNELS = [
]
-def _kernel_guard(name: str, device: torch.device, dtype: torch.dtype, values: bool = True) -> None:
- """Skip a builder whose kernel cannot be built, or whose ``values`` are not usable, on this device/dtype."""
- if values and name == "get_gaussian_discrete_kernel1d" and dtype == torch.float16:
- pytest.skip("get_gaussian_discrete_kernel1d overflows to NaN in float16 (#5227)")
+def _kernel_guard(name: str, device: torch.device, dtype: torch.dtype) -> None:
+ """Skip a builder whose kernel cannot be built on this device/dtype."""
if name == "get_motion_kernel2d" and not _supports_nearest_2d_grid_sample(device, dtype):
pytest.skip("2D grid_sample (nearest) is unavailable for this device/dtype")
if name == "get_motion_kernel3d" and not supports_nearest_3d_grid_sample(device, dtype):
@@ -1845,7 +1843,7 @@ def _correlate_at(kernel: torch.Tensor, field: torch.Tensor, centre: tuple[int,
class TestConventionsKernels(BaseTester):
@pytest.mark.parametrize("name, factory, shape", _KERNEL_SHAPES, ids=[case[0] for case in _KERNEL_SHAPES])
def test_convention_kernel_builder_output_shapes(self, name, factory, shape, device, dtype):
- _kernel_guard(name, device, dtype, values=False)
+ _kernel_guard(name, device, dtype)
kernel = factory(device, dtype)
assert kernel.shape == shape
assert kernel.dtype == dtype
@@ -2114,21 +2112,32 @@ class TestConventionsKernels(BaseTester):
assert int(kernel.float().argmax()) == 2
assert kernel[2] > kernel[1]
- def test_wart_gaussian_discrete_kernel1d_overflows_to_nan_5227(self, device, dtype):
- """get_gaussian_discrete_kernel1d computes its Bessel terms unscaled and overflows to NaN (#5227)."""
- # the smallest failing sigma depends on the dtype: about 6.8 in float32 and bfloat16, about 19 in float64;
- # in float16 every sigma > 0 fails once kernel_size is 5 or more
- sigma = {torch.float16: 1.0, torch.bfloat16: 7.0, torch.float32: 7.0, torch.float64: 20.0}[dtype]
+ @pytest.mark.parametrize(
+ "sigma, expected",
+ [
+ (1.0, [0.05088223571, 0.2118383232, 0.4745588821, 0.2118383232, 0.05088223571]),
+ (7.0, [0.1958895744, 0.2020423257, 0.2041361999, 0.2020423257, 0.1958895744]),
+ (20.0, [0.1994995631, 0.2002500302, 0.2005008133, 0.2002500302, 0.1994995631]),
+ ],
+ )
+ def test_convention_gaussian_discrete_kernel1d_is_finite_for_a_large_sigma_5227(
+ self, sigma, expected, device, dtype
+ ):
+ """get_gaussian_discrete_kernel1d scales its Bessel terms by exp(-sigma**2), so it does not overflow (#5227)."""
+ # Unscaled terms overflow to an all-NaN kernel from sigma about 6.8 in float32 and bfloat16 and about 19 in
+ # float64, and in float16 for every sigma > 0 once kernel_size is 5 or more. Reference (scipy 1.17.1):
+ # scipy.special.ive(abs(n), sigma**2) for n = arange(-2, 3), normalized.
kernel = get_gaussian_discrete_kernel1d(5, sigma, device=device, dtype=dtype)
- assert bool(torch.isnan(kernel).all())
+ self.assert_close(kernel, torch.tensor([expected], device=device, dtype=dtype))
- def test_wart_gaussian_discrete_kernel1d_drifts_in_float64_for_a_large_sigma_5227(self, device, dtype):
- """Before it overflows, the float64 discrete kernel drifts from the discrete Gaussian (#5227)."""
- if dtype != torch.float64:
- pytest.skip("the drift shows in float64; the other dtypes overflow first (#5227)")
+ def test_convention_gaussian_discrete_kernel1d_is_unimodal_for_a_large_sigma_5227(self, device, dtype):
+ """The discrete kernel follows the discrete Gaussian at sigma 14, where float64 used to drift (#5227)."""
kernel = get_gaussian_discrete_kernel1d(85, 14.0, device=device, dtype=dtype)[0]
- # scipy.special.ive(abs(n), 14.0**2) is unimodal; here tap 39 (n = -3) dips below tap 38 (n = -4)
- assert kernel[39] < kernel[38]
+ # scipy.special.ive(abs(n), 14.0**2) normalized (scipy 1.17.1) at taps 38, 39, 42 (n = -4, -3, 0). A Miller
+ # recurrence started too low for sigma**2 makes tap 39 dip below tap 38 in float64.
+ expected = torch.tensor([0.02743744108, 0.02793304819, 0.02858345732], device=device, dtype=dtype)
+ self.assert_close(kernel[[38, 39, 42]], expected)
+ assert kernel[39] > kernel[38]
@pytest.mark.parametrize(
"builder", [get_gaussian_kernel1d, get_gaussian_erf_kernel1d, get_gaussian_discrete_kernel1d]
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index 4c0844ff7..ffaa61c4f 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -233,6 +233,71 @@ def test_get_gaussian_discrete_kernel1d_tensor(window_size, sigma, device, dtype
assert_close(actual.sum(), expected.sum())
+class TestGaussianDiscreteStability(BaseTester):
+ @pytest.mark.parametrize("window_size,sigma", [(19, 3.0), (43, 7.0), (121, 20.0), (5, 100.0)])
+ def test_finite_normalized(self, window_size, sigma, device, dtype):
+ actual = get_gaussian_discrete_kernel1d(window_size, sigma, device=device, dtype=dtype)
+ assert actual.shape == (1, window_size)
+ assert actual.device == device
+ assert actual.dtype == dtype
+ assert torch.isfinite(actual).all()
+ assert (actual >= 0).all()
+ self.assert_close(actual, actual.flip(-1))
+ self.assert_close(actual.sum(-1), torch.ones(1, device=device, dtype=dtype))
+
+ @pytest.mark.parametrize(
+ "sigma,expected",
+ [
+ (1.0, [0.00817354616137807, 0.050050459106933266, 0.208375382589111, 0.4668012242851553]),
+ (7.0, [0.1355957850107771, 0.14276597314552686, 0.14725015016551396, 0.1487761833563642]),
+ (20.0, [0.1419646295228945, 0.1428557999903338, 0.14339318752279784, 0.14357276592794782]),
+ ],
+ )
+ def test_reference(self, sigma, expected, device, dtype):
+ # scipy.special.ive(abs(arange(-3, 4)), sigma**2), divided by its sum.
+ expected = torch.tensor([expected + expected[-2::-1]], device=device, dtype=dtype)
+ actual = get_gaussian_discrete_kernel1d(7, sigma, device=device, dtype=dtype)
+ self.assert_close(actual, expected, atol=1e-6, rtol=1e-5)
+
+ @pytest.mark.parametrize(
+ "window_size,sigma,offsets,expected",
+ [
+ (11, 0.5, [0, 1, 5], [0.7910171688007969, 0.09811262952356505, 1.985756382484167e-07]),
+ (
+ 121,
+ 20.0,
+ [0, 3, 30, 60],
+ [0.02000335778883414, 0.01977930326376025, 0.006488429408783234, 0.00022284111702319516],
+ ),
+ ],
+ )
+ def test_reference_taps(self, window_size, sigma, offsets, expected, device, dtype):
+ # Reference: scipy.special.ive(abs(arange(window_size) - window_size // 2), sigma**2),
+ # normalized by its sum, then indexed at window_size // 2 + offsets.
+ actual = get_gaussian_discrete_kernel1d(window_size, sigma, device=device, dtype=dtype)
+ taps = actual[0, [window_size // 2 + offset for offset in offsets]]
+ self.assert_close(taps, torch.tensor(expected, device=device, dtype=dtype))
+
+ def test_backward_finite_large_sigma(self, device, dtype):
+ sigma = torch.tensor([[100.0]], device=device, dtype=dtype, requires_grad=True)
+ kernel = get_gaussian_discrete_kernel1d(5, sigma)
+ (kernel * torch.arange(5, device=device, dtype=dtype)).sum().backward()
+ assert torch.isfinite(sigma.grad).all()
+
+ @pytest.mark.parametrize("window_size, sigma", [(5, 0.0), (121, 0.5)])
+ def test_backward_finite_small_sigma(self, window_size, sigma, device, dtype):
+ # The upward-recurrence lanes are computed and discarded here; they must run on a safe placeholder
+ # argument, or their division by sigma**2 (zero, or tiny next to the order) puts NaN in the gradient.
+ sigma = torch.tensor([[sigma]], device=device, dtype=dtype, requires_grad=True)
+ kernel = get_gaussian_discrete_kernel1d(window_size, sigma)
+ (kernel * torch.arange(window_size, device=device, dtype=dtype)).sum().backward()
+ assert torch.isfinite(sigma.grad).all()
+
+ def test_gradcheck(self, device):
+ sigma = torch.tensor([[1.5], [7.0], [20.0]], device=device, dtype=torch.float64)
+ self.gradcheck(get_gaussian_discrete_kernel1d, (7, sigma))
+
+
@pytest.mark.parametrize("ksize_x", [5, 11])
@pytest.mark.parametrize("ksize_y", [3, 7])
@pytest.mark.parametrize("sigma", [(1.5, 1.5), (2.1, 2.1)])