Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(filters)!: guided_blur subsample accepts sizes not divisible by subsample, validates subsample (#5253)

Dmytro Mishkin2a5c27ad4d8a
diff --git a/changelog.d/5253.breaking.md b/changelog.d/5253.breaking.md
new file mode 100644
index 000000000..948557af2
--- /dev/null
+++ b/changelog.d/5253.breaking.md
@@ -0,0 +1 @@
+`guided_blur` and `GuidedBlur` now raise when `subsample` is not a positive integer, and `GuidedBlur` raises when it is built rather than on its first call: a `BaseError` ("`subsample` must be a positive integer. Got: 0") for `0`, `-1`, `True`, `False` and `numpy.int64(0)`, and a `TypeCheckError` for any other value that is not an integer (`1.0`, `0.5`, `1.5`, `2.0`, a NumPy float or `numpy.bool_`, `"2"`, `None`, a tensor). `TypeCheckError` is a `BaseError`, and since #5233 also a `TypeError`. Before, with 1-channel guidance, `0`, `-1`, `False`, `True`, `1.0`, `0.5`, `numpy.True_`, `numpy.False_` and `numpy.int64(0)` ran as no subsampling, and, on images of 8 x 8 and up, a float above 1 ran as that factor when `floor(floor(H / s) * s)` is `H` and `floor(floor(W / s) * s)` is `W` (`2.0` and `numpy.float64(2.0)` on 8 x 12, `1.5` on 12 x 12, `2.5` on 10 x 10) and failed with a broadcast `RuntimeError` at the final blend otherwise; on a tiny image it failed earlier, in `interpolate` (`1.5` on 1 x 10) or in the reflect `pad` (`2.0` on 2 x 12). With multi-channel guidance, `0`, `-1`, `False`, `numpy.False_` and `numpy.int64(0)` failed in `view` with a `RuntimeError`, every float (`1.0`, `0.5`, `1.5`, `2.0`, `numpy.float64(2.0)`) failed in `view` with a `TypeError` on images of 8 x 8 and up (earlier on a tiny image, as above), and `True` and `numpy.True_` ran as `1`. `"2"` and `None` raised a builtin `TypeError` from `subsample > 1`, and a tensor a `TypeError` from `interpolate`, with either guidance. A call that passed `0`, `-1`, `False`, `True`, `1.0` or `0.5` to mean no subsampling now has to pass `subsample=1`, and one that passed `2.0` has to pass `2`. Positive integers behave as before, NumPy integers included, with one exception: `guided_blur` now continues with `int(subsample)`, so a narrow NumPy integer no longer overflows its own dtype in the arithmetic. On NumPy 2, `numpy.uint8(2)` raised `OverflowError` with `kernel_size=301` (`numpy.int8(2)` from `kernel_size=129`), and with multi-channel guidance failed with an `OverflowError` or a `RuntimeError` from `view` on an image of 256 px or more (128 px for `numpy.int8(2)`); those calls now work.
diff --git a/changelog.d/5253.fixed.md b/changelog.d/5253.fixed.md
new file mode 100644
index 000000000..084a1f7d2
--- /dev/null
+++ b/changelog.d/5253.fixed.md
@@ -0,0 +1 @@
+`guided_blur(..., subsample=s)` and `GuidedBlur(..., subsample=s)` now accept a height or width that is not a multiple of `s`, or is shorter than `s`. They raised a broadcast `RuntimeError` (1-channel guidance) or an `einsum` error (multi-channel guidance) when the height or width was not a multiple of `s`, because the upsampled coefficient maps came out `floor(H / s) * s` pixels tall and wide; an axis shorter than `s` failed earlier, in a zero-sized `interpolate`. The maps are now resized to the input's own size, and an axis shorter than `s` is subsampled to one pixel instead of none. For a size that is not a multiple of `s`, row `i` of the subsampled image is the pixel nearest to `(i + 0.5) * H / rows - s / 2` (a tie rounds up), and likewise for columns: the subsampled grid keeps the alignment with the bilinear upsample it has on a multiple of `s`, so such a size is as close to the `subsample=1` result as a multiple is. Sizes that worked give bit-identical results. The box blur still runs on the subsampled grid, so its padding limit applies there: a call raises the padding `RuntimeError` when the window `(kernel_size - 1) // s + 1` is too wide for that grid to be padded in the chosen `border_type`, as `box_blur` does on it. The default `"reflect"` hits this first, since it cannot pad a one-pixel axis at all, and an axis shorter than `s` is one pixel; `"replicate"` and `"constant"` work at every size.
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index 39e306b74..7b141214e 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -17,24 +17,49 @@
from __future__ import annotations
+from numbers import Integral
+
import torch
from torch import nn
from torch.nn.functional import interpolate
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
from .blur import box_blur
from .kernels import _unpack_2d_ks
+def _check_subsample(subsample: int) -> None:
+ msg = f"`subsample` must be a positive integer. Got: {subsample!r}"
+ KORNIA_CHECK_TYPE(subsample, Integral, f"{msg} ({type(subsample).__name__})")
+ # ``bool`` is an ``int``, and ``subsample=True`` would otherwise run as 1.
+ KORNIA_CHECK(not isinstance(subsample, bool) and subsample >= 1, msg)
+
+
+def _subsample_indices(size: int, subsample: int, device: torch.device) -> torch.Tensor:
+ """Return the pixels an axis of ``size`` pixels keeps when it is subsampled by ``subsample``.
+
+ ``max(size // subsample, 1)`` pixels, never none: an axis shorter than ``subsample`` keeps its first pixel. Pixel
+ ``i`` of the subsampled axis is the one nearest to ``(i + 0.5) * size / rows - subsample / 2``, rounding a tie up:
+ where the bilinear upsample (``align_corners=False``) puts it back, less the ``(subsample - 1) / 2`` offset of
+ taking every ``subsample``-th pixel. On a ``size`` that is a multiple of ``subsample`` that is pixel
+ ``subsample * i`` exactly, and elsewhere the offset stays the same along the axis instead of drifting by up to a
+ pixel, as ``floor(i * size / rows)`` would. Integer arithmetic, so it is exact in every dtype.
+ """
+ rows = max(size // subsample, 1)
+ i = torch.arange(rows, device=device)
+ return ((2 * i + 1) * size + rows * (1 - subsample)).div(2 * rows, rounding_mode="floor").clamp(0, size - 1)
+
+
def _preprocess_fast_guided_blur(
guidance: torch.Tensor, input: torch.Tensor, kernel_size: tuple[int, int] | int, subsample: int = 1
) -> tuple[torch.Tensor, torch.Tensor, tuple[int, int]]:
ky, kx = _unpack_2d_ks(kernel_size)
if subsample > 1:
- s = 1 / subsample
- guidance_sub = interpolate(guidance, scale_factor=s, mode="nearest")
- input_sub = guidance_sub if input is guidance else interpolate(input, scale_factor=s, mode="nearest")
+ rows = _subsample_indices(guidance.shape[-2], subsample, guidance.device)
+ cols = _subsample_indices(guidance.shape[-1], subsample, guidance.device)
+ guidance_sub = guidance.index_select(-2, rows).index_select(-1, cols)
+ input_sub = guidance_sub if input is guidance else input.index_select(-2, rows).index_select(-1, cols)
ky, kx = ((k - 1) // subsample + 1 for k in (ky, kx))
else:
guidance_sub = guidance
@@ -77,8 +102,9 @@ def _guided_blur_grayscale_guidance(
mean_b = box_blur(b, kernel_size, border_type, separable=separable)
if subsample > 1:
- mean_a = interpolate(mean_a, scale_factor=subsample, mode="bilinear")
- mean_b = interpolate(mean_b, scale_factor=subsample, mode="bilinear")
+ # back to the input's own size: it is ``subsample`` times the subsampled one only if it is a multiple of it
+ mean_a = interpolate(mean_a, size=guidance.shape[-2:], mode="bilinear")
+ mean_b = interpolate(mean_b, size=guidance.shape[-2:], mode="bilinear")
return torch.addcmul(mean_b, mean_a, guidance)
@@ -135,9 +161,9 @@ def _guided_blur_multichannel_guidance(
mean_b = box_blur(b.permute(0, 3, 1, 2), kernel_size, border_type, separable=separable)
if subsample > 1:
- mean_a = interpolate(mean_a, scale_factor=subsample, mode="bilinear")
- mean_b = interpolate(mean_b, scale_factor=subsample, mode="bilinear")
- mean_a = mean_a.view(B, C, -1, H * subsample, W * subsample)
+ mean_a = interpolate(mean_a, size=guidance.shape[-2:], mode="bilinear")
+ mean_b = interpolate(mean_b, size=guidance.shape[-2:], mode="bilinear")
+ mean_a = mean_a.view(B, C, -1, *guidance.shape[-2:])
# torch.einsum might not be contiguous, thus mean_b is the first argument
return mean_b + torch.einsum("BCHW,BCcHW->BcHW", guidance, mean_a)
@@ -167,13 +193,24 @@ def guided_blur(
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
- subsample: subsampling factor for Fast Guided filtering. Default: 1 (no subsampling)
+ subsample: subsampling factor for Fast Guided filtering, a positive integer (a ``bool`` is rejected).
+ Guidance and input are subsampled by nearest neighbour to ``max(H // subsample, 1)`` rows and
+ ``max(W // subsample, 1)`` columns: every ``subsample``-th pixel when ``H`` is a multiple of ``subsample``
+ (likewise ``W``), and otherwise, for row ``i``, the pixel nearest to
+ ``(i + 0.5) * H / rows - subsample / 2`` (a tie rounds up), which keeps the subsampled grid aligned with the
+ bilinear upsample of the coefficient maps as it is on a multiple; a single pixel, the first, on an axis
+ shorter than ``subsample``. ``H`` and ``W`` need not be multiples of it: the coefficient maps are resized
+ back to the size of the input. Default: 1 (no subsampling)
separable: use two one-dimensional box-filter passes, reducing work for
large windows. Default: False
Returns:
the blurred torch.Tensor with same shape as `input` :math:`(B, C, H, W)`.
+ Raises:
+ TypeCheckError: if ``subsample`` is not an integer (NumPy integers are accepted).
+ BaseError: if ``subsample`` is not positive, or is a ``bool``.
+
Examples:
>>> guidance = torch.rand(2, 3, 5, 5)
>>> input = torch.rand(2, 4, 5, 5)
@@ -184,6 +221,10 @@ def guided_blur(
"""
KORNIA_CHECK_IS_TENSOR(guidance)
KORNIA_CHECK_SHAPE(guidance, ["B", "C", "H", "W"])
+ _check_subsample(subsample)
+ # A NumPy integer passes the check. Its arithmetic stays in its own dtype, so ``(k - 1) // subsample + 1`` can
+ # overflow it (``numpy.uint8(2)`` with ``kernel_size=301``): continue with a Python ``int``.
+ subsample = int(subsample)
if input is not guidance:
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
@@ -225,13 +266,24 @@ class GuidedBlur(nn.Module):
border_type: the padding mode to be applied before convolving.
The expected modes are: ``'constant'``, ``'reflect'``,
``'replicate'`` or ``'circular'``. Default: ``'reflect'``.
- subsample: subsampling factor for Fast Guided filtering. Default: 1 (no subsampling)
+ subsample: subsampling factor for Fast Guided filtering, a positive integer (a ``bool`` is rejected).
+ Guidance and input are subsampled by nearest neighbour to ``max(H // subsample, 1)`` rows and
+ ``max(W // subsample, 1)`` columns: every ``subsample``-th pixel when ``H`` is a multiple of ``subsample``
+ (likewise ``W``), and otherwise, for row ``i``, the pixel nearest to
+ ``(i + 0.5) * H / rows - subsample / 2`` (a tie rounds up), which keeps the subsampled grid aligned with the
+ bilinear upsample of the coefficient maps as it is on a multiple; a single pixel, the first, on an axis
+ shorter than ``subsample``. ``H`` and ``W`` need not be multiples of it: the coefficient maps are resized
+ back to the size of the input. Default: 1 (no subsampling)
separable: use two one-dimensional box-filter passes, reducing work for
large windows. Default: False
Returns:
the blurred input torch.Tensor.
+ Raises:
+ TypeCheckError: if ``subsample`` is not an integer (NumPy integers are accepted).
+ BaseError: if ``subsample`` is not positive, or is a ``bool``. Both are raised by the constructor.
+
Shape:
- Input: :math:`(B, C, H, W)`, :math:`(B, C, H, W)`
- Output: :math:`(B, C, H, W)`
@@ -255,6 +307,7 @@ class GuidedBlur(nn.Module):
separable: bool = False,
) -> None:
super().__init__()
+ _check_subsample(subsample)
self.kernel_size = kernel_size
self.eps = eps
self.border_type = border_type
diff --git a/tests/filters/test_guided.py b/tests/filters/test_guided.py
index f02c23240..2cfd4cb3b 100644
--- a/tests/filters/test_guided.py
+++ b/tests/filters/test_guided.py
@@ -16,16 +16,103 @@
#
from __future__ import annotations
+import math
+import re
+from fractions import Fraction
from functools import partial
from unittest.mock import patch
+import numpy as np
import pytest
import torch
+import torch.nn.functional as F
from kornia.core._compat import torch_version
+from kornia.core.exceptions import BaseError, TypeCheckError
from kornia.filters import GuidedBlur, box_blur, guided_blur
-
-from testing.base import BaseTester
+from kornia.filters.guided import _preprocess_fast_guided_blur, _subsample_indices
+
+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding
+
+# The guided filter is ill-conditioned in half precision: the window variance is E[g^2] - E[g]^2, a cancellation,
+# and the coefficient cov / (var + eps) amplifies its error by up to 1 / eps. Worst absolute error against float64
+# over 150 seeds: 0.008 (float16) and 0.092 (bfloat16) at eps=0.1, 0.0013 and 0.0102 at eps=1.0, 42 (bfloat16) at
+# eps=0.01; float32 2.4e-7 at eps=1.0. So the half dtypes use eps=1.0 and a tolerance a few times that error on
+# non-divisible sizes, float32 and float64 eps=0.1 and the harness's. bfloat16's 0.05 still catches only gross errors
+# (an align_corners=True mutant slips through most of them); float16's 0.01 catches it.
+_HALF_TOLERANCE = {torch.float16: 0.01, torch.bfloat16: 0.05}
+
+
+def _value_eps(dtype):
+ return 1.0 if dtype in _HALF_TOLERANCE else 0.1
+
+
+def _subsampled_pixels(size, subsample):
+ """The pixels the subsampled grid keeps, in exact rational arithmetic.
+
+ ``max(size // s, 1)`` of them; pixel ``i`` is the one nearest (a tie rounding up) to the centre the bilinear
+ upsample gives it, ``(i + 1/2) * size / rows - 1/2``, less the ``(s - 1) / 2`` offset of every ``s``-th pixel.
+ """
+ rows = max(size // subsample, 1)
+ centres = (Fraction(2 * i + 1, 2) * size / rows - Fraction(1, 2) - Fraction(subsample - 1, 2) for i in range(rows))
+ return [min(max(math.floor(c + Fraction(1, 2)), 0), size - 1) for c in centres]
+
+
+def _fast_guided_filter_reference(guidance, input, kernel_size, eps, subsample, border_type="reflect"):
+ """He and Sun, "Fast Guided Filter" (arXiv:1505.00996), Algorithm 1, per pixel in float64 on the CPU.
+
+ The coefficient maps ``a`` (``C x C_in`` per pixel) and ``b`` are solved on the subsampled grid, window-averaged and
+ resized back to the full ``(H, W)`` of the input, which is the contract for any ``H`` and ``W``.
+ """
+ guidance, input = guidance.cpu().double(), input.cpu().double()
+ (_, C, H, W), C_in = guidance.shape, input.shape[1]
+ rows, cols = _subsampled_pixels(H, subsample), _subsampled_pixels(W, subsample)
+ g = guidance[..., rows, :][..., cols]
+ p = input[..., rows, :][..., cols]
+ kernel_size = (kernel_size, kernel_size) if isinstance(kernel_size, int) else kernel_size
+ window = tuple((k - 1) // subsample + 1 for k in kernel_size)
+
+ def mean(x):
+ return box_blur(x, window, border_type)
+
+ mean_g, mean_p = mean(g), mean(p)
+ corr_gg = mean(torch.einsum("bihw,bjhw->bijhw", g, g).flatten(1, 2)).unflatten(1, (C, C))
+ corr_gp = mean(torch.einsum("bihw,bjhw->bijhw", g, p).flatten(1, 2)).unflatten(1, (C, C_in))
+ var_gg = corr_gg - torch.einsum("bihw,bjhw->bijhw", mean_g, mean_g)
+ cov_gp = corr_gp - torch.einsum("bihw,bjhw->bijhw", mean_g, mean_p)
+ a = torch.linalg.solve(
+ var_gg.permute(0, 3, 4, 1, 2) + eps * torch.eye(C, dtype=g.dtype), cov_gp.permute(0, 3, 4, 1, 2)
+ )
+ b = mean_p.permute(0, 2, 3, 1) - torch.einsum("bhwc,bhwcq->bhwq", mean_g.permute(0, 2, 3, 1), a)
+ mean_a = mean(a.permute(0, 3, 4, 1, 2).flatten(1, 2))
+ mean_b = mean(b.permute(0, 3, 1, 2))
+ mean_a = F.interpolate(mean_a, size=(H, W), mode="bilinear").unflatten(1, (C, C_in))
+ mean_b = F.interpolate(mean_b, size=(H, W), mode="bilinear")
+ return mean_b + torch.einsum("bchw,bcqhw->bqhw", guidance, mean_a)
+
+
+def _scale_factor_interpolate(x, size=None, scale_factor=None, mode=None, **kwargs):
+ """``interpolate`` as the filter called it before ``size=``: with ``scale_factor`` (``1 / s`` down, ``s`` up).
+
+ Stands in for ``kornia.filters.guided.interpolate``. A call that already passes ``scale_factor`` goes through
+ untouched; a ``size=`` call is turned into the call that was made before, for the same integer ratio, so the two can
+ be compared bit for bit: nearest with ``1 / s`` when it shrinks, bilinear with ``s`` when it grows. The mode of the
+ call under test is deliberately not taken over.
+ """
+ if size is None:
+ return F.interpolate(x, scale_factor=scale_factor, mode=mode, **kwargs)
+ assert not kwargs
+ (h, w), (H, W) = x.shape[-2:], size
+ ratio = max(h, H) // min(h, H)
+ assert (
+ ratio > 1
+ and ratio * min(h, H) == max(h, H)
+ and ratio * min(w, W) == max(w, W)
+ and max(w, W) // min(w, W) == ratio
+ )
+ if H < h:
+ return F.interpolate(x, scale_factor=1 / ratio, mode="nearest")
+ return F.interpolate(x, scale_factor=ratio, mode="bilinear")
class TestGuidedBlur(BaseTester):
@@ -358,3 +445,259 @@ class TestGuidedBlur(BaseTester):
self.assert_close(out, expected, rtol=4 * torch.finfo(dtype).eps, atol=4 * torch.finfo(dtype).eps)
else:
self.assert_close(out, expected)
+
+ @staticmethod
+ def _skip_without_padding(device, dtype, border_type):
+ supported = {"reflect": supports_reflect_padding, "replicate": supports_replicate_padding}
+ if border_type in supported and not supported[border_type](device, dtype):
+ pytest.skip(f"this torch build has no {border_type} padding kernel for {dtype} on {device.type}")
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("subsample", [2, 3])
+ @pytest.mark.parametrize("shape", [(7, 10), (9, 11), (8, 13), (13, 8)])
+ @pytest.mark.parametrize("kernel_size", [5, (3, 5)])
+ def test_subsample_size_not_divisible(self, guide_dim, subsample, shape, kernel_size, device, dtype):
+ """Any ``H`` and ``W`` work with ``subsample`` and the output has the input's size.
+
+ Before the fix the upsampled coefficient maps came out ``floor(H / s) * s`` pixels tall and wide, and the final
+ blend died with a raw broadcast error (1-channel guidance) or an ``einsum`` error (multi-channel guidance).
+ The values are checked against the fast guided filter of the paper, resized to the full size.
+ """
+ self._skip_without_padding(device, dtype, "reflect")
+ H, W = shape
+ guide = torch.rand(2, guide_dim, H, W, device=device, dtype=dtype)
+ inp = torch.rand(2, 2, H, W, device=device, dtype=dtype)
+
+ eps = _value_eps(dtype)
+ actual = guided_blur(guide, inp, kernel_size, eps, subsample=subsample)
+
+ assert actual.shape == inp.shape
+ assert actual.dtype == dtype
+ expected = _fast_guided_filter_reference(guide, inp, kernel_size, eps, subsample).to(device=device, dtype=dtype)
+ tolerance = _HALF_TOLERANCE.get(dtype)
+ self.assert_close(actual, expected, rtol=tolerance, atol=tolerance)
+ # the module forwards the same argument
+ self.assert_close(GuidedBlur(kernel_size, eps, subsample=subsample)(guide, inp), actual)
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("subsample", [2, 3])
+ @pytest.mark.parametrize("shape", [(1, 10), (10, 1), (1, 1), (2, 9), (9, 2)])
+ def test_subsample_larger_than_an_axis(self, guide_dim, subsample, shape, device, dtype):
+ """An axis shorter than ``subsample`` is subsampled to one pixel, not to none.
+
+ ``replicate`` padding, because ``reflect`` cannot pad a one-pixel axis with any window larger than one pixel,
+ with or without ``subsample``.
+ """
+ self._skip_without_padding(device, dtype, "replicate")
+ H, W = shape
+ guide = torch.rand(1, guide_dim, H, W, device=device, dtype=dtype)
+ inp = torch.rand(1, 2, H, W, device=device, dtype=dtype)
+
+ eps = _value_eps(dtype)
+ actual = guided_blur(guide, inp, 5, eps, border_type="replicate", subsample=subsample)
+
+ assert actual.shape == inp.shape
+ assert torch.isfinite(actual).all()
+ expected = _fast_guided_filter_reference(guide, inp, 5, eps, subsample, "replicate").to(
+ device=device, dtype=dtype
+ )
+ tolerance = _HALF_TOLERANCE.get(dtype)
+ self.assert_close(actual, expected, rtol=tolerance, atol=tolerance)
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("shape,subsample", [((8, 12), 2), ((12, 8), 2), ((9, 12), 3), ((16, 8), 4), ((6, 6), 6)])
+ @pytest.mark.parametrize("kernel_size", [5, (3, 5)])
+ def test_subsample_divisible_size_is_unchanged(self, guide_dim, shape, subsample, kernel_size, device, dtype):
+ """Sizes that worked before the resize fix give the same bits.
+
+ The subsampled grid is every ``subsample``-th pixel, which is what ``scale_factor=1 / s`` nearest selected, and
+ the upsample by ``size=`` agrees with the one by ``scale_factor=s``.
+ """
+ self._skip_without_padding(device, dtype, "reflect")
+ H, W = shape
+ guide = torch.rand(2, guide_dim, H, W, device=device, dtype=dtype)
+ inp = torch.rand(2, 3, H, W, device=device, dtype=dtype)
+
+ guide_sub, inp_sub, _ = _preprocess_fast_guided_blur(guide, inp, kernel_size, subsample)
+ assert torch.equal(guide_sub, F.interpolate(guide, scale_factor=1 / subsample, mode="nearest"))
+ assert torch.equal(guide_sub, guide[..., ::subsample, ::subsample])
+ assert torch.equal(inp_sub, inp[..., ::subsample, ::subsample])
+
+ actual = guided_blur(guide, inp, kernel_size, 0.01, subsample=subsample)
+ with patch("kornia.filters.guided.interpolate", side_effect=_scale_factor_interpolate) as scale_factor_call:
+ expected = guided_blur(guide, inp, kernel_size, 0.01, subsample=subsample)
+
+ assert scale_factor_call.call_count == 2 # the two coefficient maps up
+ assert torch.equal(actual, expected)
+
+ @pytest.mark.parametrize("size,subsample", [(13, 2), (61, 2), (83, 4), (17, 3), (5, 3), (2, 3)])
+ def test_subsampled_grid_stays_aligned_with_the_upsample(self, size, subsample):
+ """On a size that is not a multiple of ``s`` the grid keeps the offset it has on a multiple.
+
+ The upsample puts subsampled pixel ``i`` at ``(i + 1/2) * size / rows - 1/2``; on a multiple of ``s`` the kept
+ pixel ``s * i`` is ``(s - 1) / 2`` before that. ``floor(i * size / rows)`` drifts from that offset by up to a
+ pixel along the axis, which doubled the error against ``subsample=1`` at ``s = 2``; the kept pixel is within
+ half a pixel of it, and is ``s * i`` on a multiple.
+ """
+ pixels = _subsample_indices(size, subsample, torch.device("cpu")).tolist()
+ assert pixels == _subsampled_pixels(size, subsample)
+ rows = max(size // subsample, 1)
+ for i, pixel in enumerate(pixels):
+ target = Fraction(2 * i + 1, 2) * size / rows - Fraction(subsample, 2)
+ assert abs(pixel - target) <= Fraction(1, 2) or pixel in (0, size - 1)
+ multiple = rows * subsample
+ on_a_multiple = _subsample_indices(multiple, subsample, torch.device("cpu")).tolist()
+ assert on_a_multiple == list(range(0, multiple, subsample))
+
+ def test_subsample_is_closer_to_the_full_filter_on_a_size_not_divisible(self):
+ """A smooth image of 61 x 83 at ``s = 2`` is about as close to ``subsample=1`` as one of 60 x 84.
+
+ Mean absolute difference 0.0079 against 0.0077; a grid that drifts along the axis (``floor(i * H / rows)``)
+ gives 0.0151.
+ """
+ errors = {}
+ for H, W in [(60, 84), (61, 83)]:
+ yy, xx = torch.meshgrid(
+ torch.linspace(0, 3, H, dtype=torch.float64),
+ torch.linspace(0, 4, W, dtype=torch.float64),
+ indexing="ij",
+ )
+ image = (torch.sin(yy * 2) * torch.cos(xx * 1.5) * 0.5 + 0.5)[None, None]
+ full = guided_blur(image, image, 9, 0.01)
+ errors[H, W] = (guided_blur(image, image, 9, 0.01, subsample=2) - full).abs().mean().item()
+ assert errors[61, 83] < 1.25 * errors[60, 84]
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ def test_subsample_divisible_size_keeps_the_values_from_before_size_resize(self, guide_dim, device, dtype):
+ self._skip_without_padding(device, dtype, "replicate")
+ guide = torch.tensor(
+ [[11, 0, 7, 1, 13, 14], [7, 14, 14, 12, 2, 0], [10, 4, 11, 8, 3, 1], [14, 6, 3, 2, 6, 4]],
+ device=device,
+ dtype=dtype,
+ ).view(1, 1, 4, 6)
+ inp = torch.tensor(
+ [[15, 12, 8, 7, 14, 10], [0, 7, 6, 2, 5, 14], [10, 5, 12, 1, 6, 15], [13, 1, 8, 13, 4, 9]],
+ device=device,
+ dtype=dtype,
+ ).view(1, 1, 4, 6)
+ if guide_dim == 3:
+ guide = torch.cat([guide, guide.flip(-1), guide.flip(-2)], dim=1)
+ expected = {
+ # Generated with ``guided_blur(guide / 16, inp / 16, 3, 0.01, border_type="replicate", subsample=2)`` in
+ # float64 on kornia 4df7b3040, which resized by ``scale_factor`` (guide: 11, 0, 7, ... as above).
+ 1: [
+ [0.7266702, 0.3351883, 0.5368115, 0.3295509, 0.6382735, 0.6360668],
+ [0.5934205, 0.7918876, 0.7382599, 0.6238963, 0.3651183, 0.3326832],
+ [0.6852125, 0.4912689, 0.6089832, 0.4800173, 0.3805514, 0.3665639],
+ [0.7858949, 0.5469661, 0.4165676, 0.3695447, 0.3933863, 0.375],
+ ],
+ 3: [
+ [0.7919061, 0.4808834, 0.4991143, 0.3269996, 0.624895, 0.5421822],
+ [0.6066366, 0.6224128, 0.6795592, 0.5507318, 0.3280907, 0.3211122],
+ [0.5977503, 0.6155415, 0.6254567, 0.505276, 0.3778669, 0.354401],
+ [0.6942412, 0.4737252, 0.4527047, 0.3636655, 0.4088435, 0.375],
+ ],
+ }[guide_dim]
+ expected = torch.tensor(expected, device=device, dtype=dtype).view(1, 1, 4, 6)
+
+ actual = guided_blur(guide / 16, inp / 16, 3, 0.01, border_type="replicate", subsample=2)
+
+ # measured against float64 on this fixture: 5e-4 for float16, 1.1e-2 for bfloat16
+ tolerance = {torch.float16: 0.01, torch.bfloat16: 0.05}.get(dtype)
+ self.assert_close(actual, expected, rtol=tolerance, atol=tolerance)
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize(
+ "subsample,error",
+ [
+ (0, BaseError),
+ (-1, BaseError),
+ (True, BaseError),
+ (False, BaseError),
+ (1.0, TypeCheckError),
+ (1.5, TypeCheckError),
+ (2.0, TypeCheckError),
+ (np.float64(2.0), TypeCheckError),
+ (np.True_, TypeCheckError),
+ ("2", TypeCheckError),
+ (None, TypeCheckError),
+ ],
+ )
+ def test_exception_subsample_not_a_positive_int(self, guide_dim, subsample, error):
+ """``subsample`` is a positive ``int``: a value outside the range raises ``BaseError``, a non-integer
+ ``TypeCheckError``, and the message shows the value.
+
+ Before the check, with 1-channel guidance ``0``, ``-1``, ``False``, ``True``, ``1.0`` and ``0.5`` ran as no
+ subsampling, and on images of 8 x 8 and up a float above 1 ran as that factor where the round trip lands on
+ ``H`` and ``W`` (``2.0`` on 8 x 12, ``1.5`` on 12 x 12) and failed at the final blend with a broadcast
+ ``RuntimeError`` otherwise. With multi-channel guidance ``0``, ``-1`` and ``False`` failed in ``view`` with a
+ ``RuntimeError``, ``True`` ran as 1, and on images of 8 x 8 and up every float failed in ``view`` with a
+ ``TypeError``. On a tiny image a float failed earlier, in ``interpolate`` (``1.5`` on 1 x 10) or in the reflect
+ ``pad`` (``2.0`` on 2 x 12). ``"2"`` and ``None`` failed in the comparison ``subsample > 1`` with a
+ ``TypeError``, with either guidance.
+ """
+ guide = torch.rand(1, guide_dim, 8, 12)
+ inp = torch.rand(1, 2, 8, 12)
+ message = rf"`subsample` must be a positive integer\. Got: {re.escape(repr(subsample))}"
+
+ # ``TypeCheckError`` is a ``BaseError``: the exact type tells the type check from the range check
+ with pytest.raises(error, match=message) as excinfo:
+ guided_blur(guide, inp, 5, 0.1, subsample=subsample)
+ assert type(excinfo.value) is error
+ # the module rejects it when it is built, not on the first call
+ with pytest.raises(error, match=message) as excinfo:
+ GuidedBlur(5, 0.1, subsample=subsample)
+ assert type(excinfo.value) is error
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("shape", [(8, 12), (7, 10)])
+ def test_subsample_one_is_no_subsampling(self, guide_dim, shape, device, dtype):
+ self._skip_without_padding(device, dtype, "reflect")
+ guide = torch.rand(1, guide_dim, *shape, device=device, dtype=dtype)
+ inp = torch.rand(1, 2, *shape, device=device, dtype=dtype)
+
+ actual = guided_blur(guide, inp, 5, 0.01, subsample=1)
+
+ assert torch.equal(actual, guided_blur(guide, inp, 5, 0.01))
+ assert torch.equal(GuidedBlur(5, 0.01, subsample=1)(guide, inp), actual)
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize(
+ "subsample,kernel_size",
+ [(np.int64(2), 5), (np.int32(3), 5), (np.uint8(2), 5), (np.uint8(2), 301)],
+ ids=["int64", "int32", "uint8", "uint8-wide-window"],
+ )
+ def test_subsample_accepts_an_integer_that_is_not_a_python_int(
+ self, guide_dim, subsample, kernel_size, device, dtype
+ ):
+ """``numpy`` integers are accepted and give the result of the equal Python ``int``.
+
+ ``guided_blur`` continues with ``int(subsample)``: ``(301 - 1) // numpy.uint8(2)`` is 300, which does not fit
+ the ``uint8`` the window arithmetic would otherwise stay in (``OverflowError``). The size, 66, is a multiple of
+ every ``subsample`` here, so these cases pin the integer types, not the handling of other sizes.
+ """
+ guide = torch.rand(1, guide_dim, 66, 66, device=device, dtype=dtype)
+ inp = torch.rand(1, 2, 66, 66, device=device, dtype=dtype)
+
+ actual = guided_blur(guide, inp, kernel_size, 0.01, border_type="constant", subsample=subsample)
+
+ assert torch.equal(
+ actual, guided_blur(guide, inp, kernel_size, 0.01, border_type="constant", subsample=int(subsample))
+ )
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ def test_gradcheck_subsample_size_not_divisible(self, guide_dim, device) -> None:
+ guide = torch.rand(1, guide_dim, 7, 9, device=device, dtype=torch.float64)
+ img = torch.rand(1, 2, 7, 9, device=device, dtype=torch.float64)
+ self.gradcheck(partial(guided_blur, subsample=2), (guide, img, 5, 0.1), nondet_tol=1e-4)
+
+ @pytest.mark.parametrize("guide_dim", [1, 3])
+ @pytest.mark.parametrize("shape", [(9, 11), (7, 10)])
+ def test_dynamo_subsample_size_not_divisible(self, guide_dim, shape, device, dtype, torch_optimizer) -> None:
+ self._skip_without_padding(device, dtype, "reflect")
+ guide = torch.rand(2, guide_dim, *shape, device=device, dtype=dtype)
+ data = torch.rand(2, 3, *shape, device=device, dtype=dtype)
+ op = GuidedBlur(5, 0.1, subsample=2)
+ op_optimized = torch_optimizer(op)
+
+ self.assert_close(op(guide, data), op_optimized(guide, data))