Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix half-precision Pascal kernel normalization (#5271)

hoobnnd09c10d70b6d
diff --git a/changelog.d/5271.fixed.md b/changelog.d/5271.fixed.md
new file mode 100644
index 000000000..7d9d4a305
--- /dev/null
+++ b/changelog.d/5271.fixed.md
@@ -0,0 +1,6 @@
+In float16, the normalized Pascal kernels no longer overflow. `get_pascal_kernel_2d` returned an all-zero kernel for
+`kernel_size` 9 to 11 and NaN from 12, and `get_pascal_kernel_1d(..., norm=True)` returned zeros from 17 and NaN from
+20, so `blur_pool2d` and `max_blur_pool2d` on float16 input returned zero or NaN images from `kernel_size=9` and
+`edge_aware_blur_pool2d` blended in the same broken blur. Each row is now normalized before it is converted to the
+requested dtype, and the 2-D kernel is the outer product of the normalized rows. float32 and float64 kernels are
+unchanged up to `kernel_size=58`.
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index ae4f069b1..e9857482f 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -1127,13 +1127,10 @@ def get_pascal_kernel_2d(
"""
ky, kx = _unpack_2d_ks(kernel_size)
- ax = get_pascal_kernel_1d(kx, device=device, dtype=dtype)
- ay = get_pascal_kernel_1d(ky, device=device, dtype=dtype)
+ ax = get_pascal_kernel_1d(kx, norm=norm, device=device, dtype=dtype)
+ ay = get_pascal_kernel_1d(ky, norm=norm, device=device, dtype=dtype)
- filt = ay[:, None] * ax[None, :]
- if norm:
- filt = filt / torch.sum(filt)
- return filt
+ return ay[:, None] * ax[None, :]
def get_pascal_kernel_1d(
@@ -1177,6 +1174,11 @@ def get_pascal_kernel_1d(
cur[-j - 1] = value
pre = cur
+ if norm and (dtype is None or dtype.is_floating_point or dtype.is_complex):
+ # Normalize before casting: even the row sum can overflow in the requested dtype.
+ total = sum(cur)
+ return torch.tensor([value / total for value in cur], device=device, dtype=dtype)
+
out = torch.tensor(cur, device=device, dtype=dtype)
if norm:
diff --git a/tests/filters/test_blur_pool.py b/tests/filters/test_blur_pool.py
index 9cb576254..8f7de4171 100644
--- a/tests/filters/test_blur_pool.py
+++ b/tests/filters/test_blur_pool.py
@@ -137,6 +137,13 @@ class TestMaxBlurPool(BaseTester):
class TestBlurPool(BaseTester):
+ @pytest.mark.parametrize("kernel_size", [5, 7, 9, 11, 17])
+ @pytest.mark.parametrize("op", [blur_pool2d, max_blur_pool2d, edge_aware_blur_pool2d])
+ def test_large_kernel_matches_float32(self, kernel_size, op, device, dtype):
+ data = torch.ones(1, 2, 32, 32, device=device, dtype=dtype)
+ expected = op(data.float(), kernel_size).to(dtype)
+ self.assert_close(op(data, kernel_size), expected)
+
@pytest.mark.parametrize("kernel_size", [3, (5, 5)])
@pytest.mark.parametrize("stride", [1, 2])
def test_smoke(self, kernel_size, stride, device, dtype):
diff --git a/tests/filters/test_pascal.py b/tests/filters/test_pascal.py
new file mode 100644
index 000000000..eb28eb974
--- /dev/null
+++ b/tests/filters/test_pascal.py
@@ -0,0 +1,78 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import math
+
+import pytest
+import torch
+
+from kornia.filters.kernels import get_pascal_kernel_1d, get_pascal_kernel_2d
+
+from testing.base import BaseTester
+
+
+class TestPascalKernel2d(BaseTester):
+ @pytest.mark.parametrize("kernel_size", [5, 7, 9, 11, 17, 33, (9, 11), (3, 17)])
+ def test_normalized_binomial_coefficients(self, kernel_size, device, dtype):
+ ky, kx = (kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
+ # Pascal rows sum to 2**(size - 1), so the reference needs no tensor reduction.
+ expected = torch.tensor(
+ [[math.comb(ky - 1, y) * math.comb(kx - 1, x) / 2 ** (ky + kx - 2) for x in range(kx)] for y in range(ky)],
+ device=device,
+ dtype=dtype,
+ )
+ actual = get_pascal_kernel_2d(kernel_size, device=device, dtype=dtype)
+
+ self.assert_close(actual, expected)
+ self.assert_close(actual.sum(), actual.new_tensor(1.0))
+
+ def test_unnormalized(self, device, dtype):
+ actual = get_pascal_kernel_2d((3, 4), norm=False, device=device, dtype=dtype)
+ expected = torch.tensor([[1, 3, 3, 1], [2, 6, 6, 2], [1, 3, 3, 1]], device=device, dtype=dtype)
+ self.assert_close(actual, expected, atol=0, rtol=0)
+
+
+class TestPascalKernel1d(BaseTester):
+ @pytest.mark.parametrize("kernel_size", [9, 17, 33])
+ def test_normalized_binomial_coefficients(self, kernel_size, device, dtype):
+ expected = torch.tensor(
+ [math.comb(kernel_size - 1, x) / 2 ** (kernel_size - 1) for x in range(kernel_size)],
+ device=device,
+ dtype=dtype,
+ )
+ actual = get_pascal_kernel_1d(kernel_size, norm=True, device=device, dtype=dtype)
+ self.assert_close(actual, expected)
+ self.assert_close(actual.sum(), actual.new_tensor(1.0))
+
+ @pytest.mark.parametrize("dtype", [torch.int64, torch.bool])
+ def test_normalized_nonfloating_dtype(self, device, dtype):
+ row = get_pascal_kernel_1d(5, device=device, dtype=dtype)
+ expected = row / row.sum()
+ self.assert_close(get_pascal_kernel_1d(5, norm=True, device=device, dtype=dtype), expected)
+ raw = row[:, None] * row
+ self.assert_close(get_pascal_kernel_2d(5, device=device, dtype=dtype), raw / raw.sum())
+
+ def test_default_float16(self, device):
+ previous_dtype = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(torch.float16)
+ actual = get_pascal_kernel_2d(17, device=device)
+ expected = get_pascal_kernel_2d(17, device=device, dtype=torch.float32).half()
+ self.assert_close(actual, expected)
+ self.assert_close(actual.sum(), actual.new_tensor(1.0))
+ finally:
+ torch.set_default_dtype(previous_dtype)