Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: improve half precision in color, filters and ZCA (#6212)

Dmytro Mishkin190d61244301
diff --git a/README.md b/README.md
index 4bf5232e4..8b78ec3dd 100644
--- a/README.md
+++ b/README.md
@@ -86,15 +86,15 @@ Leverage pre-trained AI models optimized for a variety of vision tasks, all with
The module table below counts entries in the Linux CPU known-failure manifests
([`cpu_float16.txt`](testing/half_precision_xfails/cpu_float16.txt),
[`cpu_bfloat16.txt`](testing/half_precision_xfails/cpu_bfloat16.txt)), pinned to Python 3.11 and PyTorch 2.14.0.
-There are **250 float16 and 274 bfloat16 recorded failures**. These are parametrized test cases, not counts of
+There are **243 float16 and 256 bfloat16 recorded failures**. These are parametrized test cases, not counts of
unsupported functions. The remaining work is tracked in [#4153](https://github.com/kornia/kornia/issues/4153).
No CI job covers CUDA or MPS half precision; CPU results do not establish support on those backends.
| Module | float16 | bfloat16 | Known failures (fp16 / bf16) | Notes |
|--------|:-------:|:--------:|:----------------------------:|-------|
-| `kornia.color` | ⚠️ | ⚠️ | 1 / 9 | float16: RGB255 round-trip accuracy; bfloat16: Lab, Luv and RGB255 accuracy |
-| `kornia.filters` | ⚠️ | ⚠️ | 6 / 8 | Canny and Gaussian kernel/blur accuracy; CPU FFT convolution computes in float32 |
-| `kornia.enhance` | βœ… | ⚠️ | 0 / 1 | bfloat16: ZCA accuracy; JPEG computes half inputs in float32 and returns the input dtype |
+| `kornia.color` | βœ… | βœ… | 0 / 0 | Lab/Luv conversions and `rgb255_to_normals` compute half inputs in float32 and return the input dtype |
+| `kornia.filters` | βœ… | βœ… | 0 / 0 | Canny, Gaussian kernels/blur and CPU FFT convolution compute half inputs in float32 and return the input dtype |
+| `kornia.enhance` | βœ… | βœ… | 0 / 0 | ZCA keeps half-input fitted state in float32; whitening and JPEG return the input dtype after float32 computation |
| `kornia.morphology` | βœ… | βœ… | 0 / 0 | |
| `kornia.augmentation` | ⚠️ | ⚠️ | 59 / 48 | float16: container autocast/runtime errors and accuracy; both dtypes: 3D backward and random-generator accuracy |
| `kornia.geometry.transform` | ⚠️ | ⚠️ | 31 / 31 | Rotation matrices, affine/perspective warps and homography-warper accuracy |
diff --git a/changelog.d/5721.fixed.md b/changelog.d/5721.fixed.md
index 9363f9d8a..582c79888 100644
--- a/changelog.d/5721.fixed.md
+++ b/changelog.d/5721.fixed.md
@@ -1,5 +1,5 @@
-`zca_mean`, `zca_whiten` and `ZCAWhitening` fit float16 and bfloat16 data in float32 and return the mean and transforms
-in the input dtype. In float16 the unnormalized scatter overflowed, so eight samples of 0 and 255 gave NaN transforms.
+`zca_mean`, `zca_whiten` and `ZCAWhitening` fit float16 and bfloat16 data in float32. In float16 the unnormalized
+scatter overflowed, so eight samples of 0 and 255 gave NaN transforms.
Eager fitting also runs with autocast disabled: under `torch.autocast` a float32 input used to give transforms in the
autocast dtype (NaN for pixel-range data under float16 autocast), and now gives the float32 transforms it gets outside
autocast. TorchScript fitting does not disable an enclosing autocast region.
diff --git a/changelog.d/6212.breaking.md b/changelog.d/6212.breaking.md
new file mode 100644
index 000000000..60c1a0529
--- /dev/null
+++ b/changelog.d/6212.breaking.md
@@ -0,0 +1 @@
+`zca_mean` returns, and `ZCAWhitening.fit` stores, the mean and transforms in float32 for float16 and bfloat16 inputs; previously they were in the input dtype, whose rounding could corrupt rank-deficient whitening. `linear_transform`, `zca_whiten`, and `ZCAWhitening` still return the input dtype, computing half-input transforms in float32. Callers applying `zca_mean` results directly must promote half inputs to float32 or use `linear_transform`. Explicitly casting fitted buffers to half precision still discards their accuracy.
diff --git a/changelog.d/6212.fixed.md b/changelog.d/6212.fixed.md
new file mode 100644
index 000000000..8b687f013
--- /dev/null
+++ b/changelog.d/6212.fixed.md
@@ -0,0 +1 @@
+Improve float16 and bfloat16 accuracy in Lab/Luv conversions, `rgb255_to_normals` visualization, Gaussian kernels and blur, and Canny by computing intermediates in float32 and returning the input dtype. Canny no longer overflows when squaring gradients of common 255-level float16 inputs, and decoding a zero float16 normal remains finite.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index 975119d06..c66f3e99b 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -7,7 +7,7 @@ CUDA, float16 and bfloat16 support
The module table below counts entries in the Linux CPU known-failure manifests
(`cpu_float16.txt <https://github.com/kornia/kornia/blob/main/testing/half_precision_xfails/cpu_float16.txt>`_,
`cpu_bfloat16.txt <https://github.com/kornia/kornia/blob/main/testing/half_precision_xfails/cpu_bfloat16.txt>`_), pinned to Python 3.11 and PyTorch 2.14.0.
-There are **250 float16 and 274 bfloat16 recorded failures**. These are parametrized test cases, not counts of
+There are **243 float16 and 256 bfloat16 recorded failures**. These are parametrized test cases, not counts of
unsupported functions. The remaining work is tracked in `#4153 <https://github.com/kornia/kornia/issues/4153>`_.
No CI job covers CUDA or MPS half precision; CPU results do not establish support on those backends.
@@ -21,20 +21,21 @@ No CI job covers CUDA or MPS half precision; CPU results do not establish suppor
- Known failures
- Notes
* - ``kornia.color``
- - ⚠️
- - ⚠️
- - 1 / 9
- - float16: RGB255 round-trip accuracy; bfloat16: Lab, Luv and RGB255 accuracy
+ - βœ…
+ - βœ…
+ - 0 / 0
+ - Lab/Luv conversions and ``rgb255_to_normals`` compute half inputs in float32 and return the input dtype
* - ``kornia.filters``
- - ⚠️
- - ⚠️
- - 6 / 8
- - Canny and Gaussian kernel/blur accuracy; CPU FFT convolution computes in float32
+ - βœ…
+ - βœ…
+ - 0 / 0
+ - Canny, Gaussian kernels/blur and CPU FFT convolution compute half inputs in float32 and return the input dtype
* - ``kornia.enhance``
- βœ…
- - ⚠️
- - 0 / 1
- - bfloat16: ZCA accuracy; JPEG computes half inputs in float32 and returns the input dtype
+ - βœ…
+ - 0 / 0
+ - ZCA keeps half-input fitted state in float32; whitening and JPEG return the input dtype after float32
+ computation
* - ``kornia.morphology``
- βœ…
- βœ…
diff --git a/kornia/color/lab.py b/kornia/color/lab.py
index a807e017b..8744058d9 100644
--- a/kornia/color/lab.py
+++ b/kornia/color/lab.py
@@ -27,6 +27,8 @@ from typing import ClassVar
import torch
from torch import nn
+from kornia.core.utils import _autocast_disabled
+
from .rgb import linear_rgb_to_rgb, rgb_to_linear_rgb
from .xyz import rgb_to_xyz, xyz_to_rgb
@@ -40,6 +42,7 @@ def rgb_to_lab(image: torch.Tensor) -> torch.Tensor:
color is computed using the D65 illuminant and Observer 2.
Convention:
+ Float16 and bfloat16 inputs are computed in float32 and rounded to the input dtype at return.
Input is nonlinear sRGB in RGB channel order at axis -3; this function first converts
it to linear RGB. Output channels are L*, a*, b* using D65 / 2Β° reference white.
@@ -61,6 +64,17 @@ def rgb_to_lab(image: torch.Tensor) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
+ if image.dtype in (torch.float16, torch.bfloat16):
+ if torch.jit.is_scripting():
+ return _rgb_to_lab(image.float()).to(image.dtype)
+ # Color matrices use einsum/convolution, which an enclosing autocast would downcast again.
+ with _autocast_disabled(image.device.type):
+ return _rgb_to_lab(image.float()).to(image.dtype)
+ return _rgb_to_lab(image)
+
+
+def _rgb_to_lab(image: torch.Tensor) -> torch.Tensor:
+ """Compute the conversion in the working dtype."""
# Convert from sRGB to Linear RGB
lin_rgb = rgb_to_linear_rgb(image)
@@ -95,6 +109,7 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:
a and b channels are in the range of :math:`[-128, 127]`.
Convention:
+ Float16 and bfloat16 inputs are computed in float32 and rounded to the input dtype at return.
Input channels are L*, a*, b* at axis -3 using D65 / 2Β° reference white. Set clip to
false to skip the final [0, 1] clamp of the sRGB output.
@@ -116,6 +131,17 @@ def lab_to_rgb(image: torch.Tensor, clip: bool = True) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
+ if image.dtype in (torch.float16, torch.bfloat16):
+ if torch.jit.is_scripting():
+ return _lab_to_rgb(image.float(), clip).to(image.dtype)
+ # Color matrices use einsum/convolution, which an enclosing autocast would downcast again.
+ with _autocast_disabled(image.device.type):
+ return _lab_to_rgb(image.float(), clip).to(image.dtype)
+ return _lab_to_rgb(image, clip)
+
+
+def _lab_to_rgb(image: torch.Tensor, clip: bool) -> torch.Tensor:
+ """Compute the conversion in the working dtype."""
L: torch.Tensor = image[..., 0, :, :]
a: torch.Tensor = image[..., 1, :, :]
_b: torch.Tensor = image[..., 2, :, :]
diff --git a/kornia/color/luv.py b/kornia/color/luv.py
index 487e86477..96c0843b2 100644
--- a/kornia/color/luv.py
+++ b/kornia/color/luv.py
@@ -27,6 +27,8 @@ from typing import ClassVar
import torch
from torch import nn
+from kornia.core.utils import _autocast_disabled
+
from .rgb import linear_rgb_to_rgb, rgb_to_linear_rgb
from .xyz import rgb_to_xyz, xyz_to_rgb
@@ -40,14 +42,14 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
color is computed using the D65 illuminant and Observer 2.
Convention:
+ Float16 and bfloat16 inputs are computed in float32 and rounded to the input dtype at return.
Input is nonlinear sRGB in RGB order at axis -3. Output is CIE L*u*v* with D65 / 2Β°
reference white.
Args:
image: RGB Image to be converted to Luv with shape :math:`(*, 3, H, W)`.
- eps: for numerically stability when dividing. For float16 input a positive ``eps`` below
- :math:`2^{-14}`, the smallest normal float16 value, is raised to it: smaller values underflow to
- zero or overflow the backward pass.
+ eps: For numerical stability when dividing. Half inputs use float32 arithmetic, so the default
+ epsilon remains representable without a dtype-dependent floor.
Returns:
Luv version of the image with shape :math:`(*, 3, H, W)`.
@@ -63,10 +65,17 @@ def rgb_to_luv(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- # float16 cannot represent the default eps, and a too-small eps can overflow its backward.
- if image.dtype == torch.float16 and eps > 0.0:
- eps = max(eps, 6.103515625e-05)
+ if image.dtype in (torch.float16, torch.bfloat16):
+ if torch.jit.is_scripting():
+ return _rgb_to_luv(image.float(), eps).to(image.dtype)
+ # Color matrices use einsum/convolution, which an enclosing autocast would downcast again.
+ with _autocast_disabled(image.device.type):
+ return _rgb_to_luv(image.float(), eps).to(image.dtype)
+ return _rgb_to_luv(image, eps)
+
+def _rgb_to_luv(image: torch.Tensor, eps: float) -> torch.Tensor:
+ """Compute the conversion in the working dtype."""
# Convert from sRGB to Linear RGB
lin_rgb = rgb_to_linear_rgb(image)
@@ -101,14 +110,14 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
r"""Convert a Luv image to RGB.
Convention:
+ Float16 and bfloat16 inputs are computed in float32 and rounded to the input dtype at return.
Input channels are CIE L*, u*, v* at axis -3 with D65 / 2Β° reference white. The result
is nonlinear sRGB.
Args:
image: Luv image to be converted to RGB with shape :math:`(*, 3, H, W)`.
- eps: for numerically stability when dividing. For float16 input a positive ``eps`` below
- :math:`2^{-14}`, the smallest normal float16 value, is raised to it: smaller values underflow to
- zero or overflow the backward pass.
+ eps: For numerical stability when dividing. Half inputs use float32 arithmetic, so the default
+ epsilon remains representable without a dtype-dependent floor.
Returns:
Luv version of the image with shape :math:`(*, 3, H, W)`.
@@ -124,10 +133,17 @@ def luv_to_rgb(image: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
if len(image.shape) < 3 or image.shape[-3] != 3:
raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
- # float16 cannot represent the default eps, and a too-small eps can overflow its backward.
- if image.dtype == torch.float16 and eps > 0.0:
- eps = max(eps, 6.103515625e-05)
+ if image.dtype in (torch.float16, torch.bfloat16):
+ if torch.jit.is_scripting():
+ return _luv_to_rgb(image.float(), eps).to(image.dtype)
+ # Color matrices use einsum/convolution, which an enclosing autocast would downcast again.
+ with _autocast_disabled(image.device.type):
+ return _luv_to_rgb(image.float(), eps).to(image.dtype)
+ return _luv_to_rgb(image, eps)
+
+def _luv_to_rgb(image: torch.Tensor, eps: float) -> torch.Tensor:
+ """Compute the conversion in the working dtype."""
L: torch.Tensor = image[..., 0, :, :]
u: torch.Tensor = image[..., 1, :, :]
v: torch.Tensor = image[..., 2, :, :]
diff --git a/kornia/color/rgb.py b/kornia/color/rgb.py
index c163cfe4b..a5f83ec5d 100644
--- a/kornia/color/rgb.py
+++ b/kornia/color/rgb.py
@@ -384,6 +384,7 @@ def rgb255_to_normals(image: torch.Tensor) -> torch.Tensor:
Convention:
Maps RGB255 channels to [-1, 1], then normalizes each three-channel vector at axis -3.
+ Half inputs are computed in float32 and rounded to the input dtype once at return.
Args:
image: RGB Image to be converted to surface normals of shape :math:`(*,3,H,W)`.
@@ -397,7 +398,11 @@ def rgb255_to_normals(image: torch.Tensor) -> torch.Tensor:
"""
KORNIA_CHECK_IS_COLOR(image)
- return F.normalize((image / 255.0) * 2.0 - 1.0, dim=-3, p=2.0)
+ dtype = image.dtype
+ if dtype in (torch.float16, torch.bfloat16):
+ image = image.float()
+ output = F.normalize((image / 255.0) * 2.0 - 1.0, dim=-3, p=2.0)
+ return output.to(dtype) if dtype in (torch.float16, torch.bfloat16) else output
class BgrToRgb(nn.Module):
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index 85a57f42b..e4e80c6fa 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -20,7 +20,7 @@ from typing import List, Optional, Tuple
import torch
from torch import nn
-from kornia.core.utils import _torch_svd_cast
+from kornia.core.utils import _autocast_disabled, _torch_svd_cast
__all__ = ["ZCAWhitening", "linear_transform", "zca_mean", "zca_whiten"]
@@ -48,6 +48,10 @@ class ZCAWhitening(nn.Module):
where :math:`U` are the eigenvectors of :math:`\Sigma` and :math:`S` contain the corresponding
eigenvalues of :math:`\Sigma`. After the transform is applied, the output is reshaped to same shape.
+ Float16 and bfloat16 inputs are fitted and transformed in float32, with only the transformed output rounded
+ to the input dtype. The fitted buffers stay float32; explicitly casting the module to half precision discards
+ that accuracy.
+
The fitted mean and transforms are buffers: ``state_dict`` saves them, ``.to()`` moves and casts them, and
loading a fitted state into an unfitted module fits it. An unfitted module holds no tensors, so the loaded
ones keep the device and dtype they were saved with; move the module after loading. A checkpoint saved
@@ -220,7 +224,12 @@ class ZCAWhitening(nn.Module):
if self.transform_inv is None:
raise TypeError("The transform inverse should be a torch.Tensor. Got None.")
- mean_inv: torch.Tensor = -self.mean_vector.mm(self.transform_matrix)
+ if x.dtype in (torch.float16, torch.bfloat16) and not torch.jit.is_scripting():
+ # The transformed mean is part of the fit too: autocasting it loses accuracy before linear_transform.
+ with _autocast_disabled(x.device.type):
+ mean_inv = -self.mean_vector.float().mm(self.transform_matrix.float())
+ else:
+ mean_inv = -self.mean_vector.mm(self.transform_matrix)
return linear_transform(x, self.transform_inv, mean_inv, self.dim)
@@ -233,7 +242,7 @@ def zca_mean(
Convention:
See :class:`ZCAWhitening`: dim selects samples and all other axes form features.
Fitting runs with autocast disabled (not under TorchScript). Float16 and bfloat16 fitting uses float32
- arithmetic; the mean and transforms keep the input dtype.
+ arithmetic and returns float32 mean and transforms to avoid cancellation when applying a rank-deficient fit.
The output can be used with :func:`linear_transform`. See :class:`ZCAWhitening` for details.
@@ -324,10 +333,6 @@ def zca_mean(
with torch.autocast(device_type=inp.device.type, enabled=False):
T, mean, T_inv = _zca_mean(inp_permute, num_features, unbiased, eps, return_inverse)
- dtype = inp.dtype
- if dtype in (torch.float16, torch.bfloat16):
- # The unnormalised scatter can overflow half precision even when the covariance and transform fit.
- return T.to(dtype), mean.to(dtype), T_inv.to(dtype) if T_inv is not None else None
return T, mean, T_inv
@@ -431,7 +436,8 @@ def linear_transform(
Convention:
dim selects rows (samples); all other dimensions form a feature row.
The result is (X - mean) @ transform_matrix with the original layout
- restored.
+ restored. Half inputs are centered and multiplied in float32 with autocast disabled (outside TorchScript),
+ then rounded to the input dtype. Keep the fitted transform and mean in float32 to preserve their accuracy.
.. math::
@@ -493,8 +499,18 @@ def linear_transform(
inp_permute = inp.permute(new_order)
inp_flat = inp_permute.reshape((-1, num_features))
- inp_center = inp_flat - mean_vector
- inp_transformed = inp_center.mm(transform_matrix)
+ output_dtype = inp.dtype
+ if output_dtype in (torch.float16, torch.bfloat16):
+ inp_center = inp_flat.float() - mean_vector.float()
+ if torch.jit.is_scripting():
+ inp_transformed = inp_center.mm(transform_matrix.float())
+ else:
+ with _autocast_disabled(inp.device.type):
+ inp_transformed = inp_center.mm(transform_matrix.float())
+ inp_transformed = inp_transformed.to(output_dtype)
+ else:
+ inp_center = inp_flat - mean_vector
+ inp_transformed = inp_center.mm(transform_matrix)
inp_transformed = inp_transformed.reshape(inp_permute.size())
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index 769812992..a71f77183 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -33,7 +33,7 @@ from kornia.core.check import (
KORNIA_CHECK_IS_TENSOR,
KORNIA_CHECK_SHAPE,
)
-from kornia.core.utils import is_exporting
+from kornia.core.utils import _autocast_disabled, is_exporting
from .filter import _to_floating
from .gaussian import gaussian_blur2d
@@ -138,8 +138,8 @@ def canny(
:math:`\sqrt{(8 s)^2 + \epsilon}` at an interior pixel, about ``8 * abs(s)``. This is about eight times
what :func:`~kornia.filters.sobel` returns by default, up to the ``eps`` inside the square root. On an
image in :math:`[0, 1]` it is not bounded by 1: a unit step reaches 4 without the blur and about 2.59 with
- the default one. In float16 the squared gradient overflows past 65504, which a step of 64 already reaches
- without the blur, so keep a float16 image in :math:`[0, 1]` rather than scaling it and the thresholds up.
+ the default one. Float16 and bfloat16 inputs are computed in float32, with enclosing autocast disabled;
+ only the final magnitude and edges are rounded to the input dtype.
- The thresholds compare against that magnitude and are strict: a pixel is weak above ``low_threshold`` and
strong above ``high_threshold``. :ref:`Filtering <filtering-conventions>` maps them onto OpenCV and
scikit-image.
@@ -200,19 +200,19 @@ def canny(
# conversion keeps the fractional grey a uint8 conversion would round away
input = _to_floating(input)
- # To Grayscale
- if input.shape[1] == 3:
- input = rgb_to_grayscale(input)
-
+ output_dtype = input.dtype
+ if output_dtype in (torch.float16, torch.bfloat16):
+ input = input.float()
+ if torch.jit.is_scripting():
+ gradients = _canny_gradients(input, kernel_size, sigma)
+ else:
+ with _autocast_disabled(input.device.type):
+ gradients = _canny_gradients(input, kernel_size, sigma)
+ else:
+ gradients = _canny_gradients(input, kernel_size, sigma)
device = input.device
dtype = input.dtype
- # Gaussian filter
- blurred: torch.Tensor = gaussian_blur2d(input, kernel_size, sigma)
-
- # Compute the gradients
- gradients: torch.Tensor = spatial_gradient(blurred, normalized=False)
-
# Unpack the edges
gx: torch.Tensor = gradients[:, :, 0]
gy: torch.Tensor = gradients[:, :, 1]
@@ -275,7 +275,7 @@ def canny(
high: torch.Tensor = magnitude > high_threshold
# Cast before scaling: a boolean times a Python float exports as aten.mul.Scalar, which onnxscript < 0.7.2 cannot
- # translate. The result is 0, 0.5 or 1, exact in every floating dtype; the last cast keeps an integer input's dtype.
+ # translate. The result is 0, 0.5 or 1, exact in every floating dtype.
edges = ((low.to(dtype) + high.to(dtype)) * 0.5).to(dtype)
# Hysteresis
@@ -305,7 +305,19 @@ def canny(
# The weak pixels left touch no strong pixel.
edges = (edges == 1).to(dtype)
- return magnitude, edges
+ return magnitude.to(output_dtype), edges.to(output_dtype)
+
+
+def _canny_gradients(
+ input: torch.Tensor,
+ kernel_size: tuple[int, int] | int,
+ sigma: tuple[float, float] | torch.Tensor,
+) -> torch.Tensor:
+ """Convert to grayscale, blur and differentiate in the working dtype."""
+ if input.shape[1] == 3:
+ input = rgb_to_grayscale(input)
+ blurred = gaussian_blur2d(input, kernel_size, sigma)
+ return spatial_gradient(blurred, normalized=False)
class Canny(nn.Module):
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index c022f6e6e..95c764844 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -23,7 +23,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
from kornia.core.ops import _device_literal
-from kornia.core.utils import _to_device_nonblocking, is_autocast_enabled, is_compiling
+from kornia.core.utils import _autocast_disabled, _to_device_nonblocking, is_autocast_enabled, is_compiling
from .filter import _to_floating, filter2d, filter2d_separable
from .kernels import _check_kernel_size, _unpack_2d_ks, get_gaussian_kernel1d, get_gaussian_kernel2d
@@ -102,6 +102,8 @@ def gaussian_blur2d(
first, so ``sigma[0]`` blurs along ``H`` and ``sigma[1]`` along ``W``.
:ref:`Filtering <filtering-conventions>` maps both pairs onto OpenCV and scipy.
- The border modes are :func:`~kornia.filters.filter2d`'s; see its Convention block.
+ - Float16 and bfloat16 inputs use float32 kernels and convolution, including both separable passes,
+ and are rounded to the input dtype once at return. Enclosing autocast is disabled for this computation.
- An integer or bool input is blurred in float32 and the output is float32, as in
:func:`~kornia.filters.filter2d`; ``sigma`` is cast to float32 as well.
@@ -159,6 +161,22 @@ def gaussian_blur2d(
# promote before casting sigma and the kernel to the input's dtype, where an integer dtype truncates them (#5155)
input = _to_floating(input)
+ if input.dtype in (torch.float16, torch.bfloat16):
+ if torch.jit.is_scripting():
+ return _gaussian_blur2d(input.float(), kernel_size, sigma, border_type, separable).to(input.dtype)
+ with _autocast_disabled(input.device.type):
+ return _gaussian_blur2d(input.float(), kernel_size, sigma, border_type, separable).to(input.dtype)
+ return _gaussian_blur2d(input, kernel_size, sigma, border_type, separable)
+
+
+def _gaussian_blur2d(
+ input: torch.Tensor,
+ kernel_size: tuple[int, int] | int,
+ sigma: tuple[float, float] | torch.Tensor,
+ border_type: str,
+ separable: bool,
+) -> torch.Tensor:
+ """Construct and apply the kernels in the working dtype."""
# The positivity check below reads ``host_sigma``: the Python numbers, or ``sigma`` in the input dtype on the
# device it came on, so that a CPU sigma, as the augmentations pass it, is checked without reading the GPU.
host_sigma: tuple[float, float] | torch.Tensor
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index ccdd705f5..91a07465a 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -165,21 +165,29 @@ def gaussian(
A tensor with shape :math:`(B, \text{kernel_size})`, with Gaussian values.
.. note::
+ Float16 and bfloat16 kernels are computed in float32 and rounded once at return.
+
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.
"""
+ output_dtype = sigma.dtype if isinstance(sigma, torch.Tensor) else dtype or torch.get_default_dtype()
if isinstance(sigma, (int, float)):
_check_kernel_dtype(dtype, "A Gaussian kernel")
- sigma = torch.tensor([[float(sigma)]], device=device, dtype=dtype)
+ compute_dtype = torch.float32 if output_dtype in (torch.float16, torch.bfloat16) else output_dtype
+ sigma = torch.tensor([[float(sigma)]], device=device, dtype=compute_dtype)
KORNIA_CHECK_IS_TENSOR(sigma)
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
if not (sigma.dtype.is_floating_point or sigma.dtype.is_complex):
# as in `gaussian_discrete`: in a uint8 sigma's dtype the offsets below the mean would wrap (#5155)
sigma = sigma.to(torch.get_default_dtype())
+ if output_dtype in (torch.float16, torch.bfloat16):
+ sigma = sigma.float()
+ if isinstance(mean, torch.Tensor):
+ mean = mean.float()
batch_size = sigma.shape[0]
mean = float(window_size // 2) if mean is None else mean
@@ -203,7 +211,7 @@ def gaussian(
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
+ # whose square underflows the working dtype. 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
@@ -214,7 +222,8 @@ def gaussian(
gauss = torch.exp(-dist / safe_denominator)
gauss = torch.where(is_impulse, (dist == 0).to(dist.dtype), gauss)
- return gauss / gauss.sum(-1, keepdim=True)
+ kernel = gauss / gauss.sum(-1, keepdim=True)
+ return kernel.to(output_dtype) if output_dtype in (torch.float16, torch.bfloat16) else kernel
def gaussian_discrete_erf(
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index fc8fe013a..c9785049f 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -57,26 +57,8 @@ call builtins.AssertionError tests/augmentation/test_random_generator.py::TestRa
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomAffineGen3D::test_random_gen[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomPerspectiveGen3D::test_random_gen[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomPerspectiveGen3D::test_same_on_batch[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_lab.py::TestLabToRgb::test_forth_and_back[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_lab.py::TestLabToRgb::test_unit[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_lab.py::TestRgbToLab::test_forth_and_back[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_lab.py::TestRgbToLab::test_unit[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_luv.py::TestLuvToRgb::test_forth_and_back[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_luv.py::TestLuvToRgb::test_unit[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_luv.py::TestRgbToLuv::test_forth_and_back[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_luv.py::TestRgbToLuv::test_unit[cpu-bfloat16]
-call builtins.AssertionError tests/color/test_rgb.py::TestRgb255Normals::test_back_and_forth[cpu-bfloat16]
call builtins.AssertionError tests/contrib/test_hist_match.py::TestHistMatch::test_histmatch[cpu-bfloat16]
call builtins.AssertionError tests/core/test_helpers.py::TestSvdCast::test_smoke[cpu-bfloat16]
-call builtins.AssertionError tests/enhance/test_zca.py::TestZCA::test_dim_args[cpu-bfloat16-1]
-call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst[cpu-bfloat16]
-call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst_false[cpu-bfloat16]
-call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_threshold[cpu-bfloat16]
-call builtins.AssertionError tests/filters/test_gaussian.py::TestGaussianBlur2d::test_separable_vs_non_separable_small_kernel[cpu-bfloat16]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_gaussian[cpu-bfloat16-11-11.0-3.0-expected3]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_gaussian[cpu-bfloat16-11-5.0-8.0-expected2]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_gaussian[cpu-bfloat16-11-5.0-None-expected1]
-call builtins.AssertionError tests/filters/test_gaussian.py::test_gaussian[cpu-bfloat16-5-1.0-None-expected0]
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[cpu-bfloat16-20]
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam[cpu-bfloat16-6]
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_pred_world_to_cam_weighted[cpu-bfloat16-16]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 828f187de..bc1e0a1e7 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -69,13 +69,6 @@ call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::Tes
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomAffineGen3D::test_same_on_batch[cpu-float16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomPerspectiveGen3D::test_random_gen[cpu-float16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomPerspectiveGen3D::test_same_on_batch[cpu-float16]
-call builtins.AssertionError tests/color/test_rgb.py::TestRgb255Normals::test_back_and_forth[cpu-float16]
-call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude[cpu-float16]
-call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst[cpu-float16]
-call builtins.AssertionError tests/filters/test_canny.py::TestCanny::test_magnitude_hyst_false[cpu-float16]
-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 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/color/test_lab.py b/tests/color/test_lab.py
index 228bccd46..db7efc3a5 100644
--- a/tests/color/test_lab.py
+++ b/tests/color/test_lab.py
@@ -48,9 +48,6 @@ class TestRgbToLab(BaseTester):
assert kornia.color.rgb_to_lab(img)
def test_unit(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
-
data = torch.tensor(
[
[
@@ -102,18 +99,26 @@ class TestRgbToLab(BaseTester):
dtype=dtype,
)
+ if dtype in (torch.float16, torch.bfloat16):
+ # The literal reference above predates input quantization; isolate arithmetic error on half inputs.
+ expected = kornia.color.rgb_to_lab(data.to(device="cpu", dtype=torch.float64)).to(
+ device=device, dtype=dtype
+ )
self.assert_close(kornia.color.rgb_to_lab(data), expected, low_tolerance=True)
def test_forth_and_back(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
-
data = torch.rand(3, 4, 5, device=device, dtype=dtype)
lab = kornia.color.rgb_to_lab
rgb = kornia.color.lab_to_rgb
data_out = lab(rgb(data, clip=False))
- self.assert_close(data_out, data)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Quantize the intermediate representation too: its loss cannot be undone by the inverse.
+ wide = data.to(device="cpu", dtype=torch.float64)
+ reference = lab(rgb(wide, clip=False).to(dtype).double()).to(device=device, dtype=dtype)
+ self.assert_close(data_out, reference)
+ else:
+ self.assert_close(data_out, data)
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
@@ -159,9 +164,6 @@ class TestLabToRgb(BaseTester):
assert kornia.color.lab_to_rgb(img)
def test_unit(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
-
data = torch.tensor(
[
[
@@ -244,19 +246,30 @@ class TestLabToRgb(BaseTester):
dtype=dtype,
)
+ if dtype in (torch.float16, torch.bfloat16):
+ expected = kornia.color.lab_to_rgb(data.to(device="cpu", dtype=torch.float64)).to(
+ device=device, dtype=dtype
+ )
self.assert_close(kornia.color.lab_to_rgb(data), expected)
+ if dtype in (torch.float16, torch.bfloat16):
+ expected_unclipped = kornia.color.lab_to_rgb(data.to(device="cpu", dtype=torch.float64), clip=False).to(
+ device=device, dtype=dtype
+ )
self.assert_close(kornia.color.lab_to_rgb(data, clip=False), expected_unclipped)
def test_forth_and_back(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
-
data = torch.rand(3, 4, 5, device=device, dtype=dtype)
lab = kornia.color.rgb_to_lab
rgb = kornia.color.lab_to_rgb
unclipped_data_out = rgb(lab(data), clip=False)
- self.assert_close(unclipped_data_out, data)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Quantize the intermediate representation too: its loss cannot be undone by the inverse.
+ wide = data.to(device="cpu", dtype=torch.float64)
+ reference = rgb(lab(wide).to(dtype).double(), clip=False).to(device=device, dtype=dtype)
+ self.assert_close(unclipped_data_out, reference)
+ else:
+ self.assert_close(unclipped_data_out, data)
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
diff --git a/tests/color/test_luv.py b/tests/color/test_luv.py
index 4160ede40..79a4c5e33 100644
--- a/tests/color/test_luv.py
+++ b/tests/color/test_luv.py
@@ -48,9 +48,6 @@ class TestRgbToLuv(BaseTester):
assert kornia.color.rgb_to_luv(img)
def test_unit(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
-
data = torch.tensor(
[
[
@@ -102,12 +99,14 @@ class TestRgbToLuv(BaseTester):
dtype=dtype,
)
+ if dtype in (torch.float16, torch.bfloat16):
+ # The literal reference above predates input quantization; isolate arithmetic error on half inputs.
+ expected = kornia.color.rgb_to_luv(data.to(device="cpu", dtype=torch.float64)).to(
+ device=device, dtype=dtype
+ )
self.assert_close(kornia.color.rgb_to_luv(data), expected, low_tolerance=True)
def test_forth_and_back(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
-
# Generate on CPU with a fixed seed so the test is order-independent.
torch.manual_seed(0)
data = torch.rand(3, 4, 5).to(device=device, dtype=dtype)
@@ -115,7 +114,13 @@ class TestRgbToLuv(BaseTester):
rgb = kornia.color.luv_to_rgb
data_out = luv(rgb(data))
- self.assert_close(data_out, data)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Quantize the intermediate representation too: its loss cannot be undone by the inverse.
+ wide = data.to(device="cpu", dtype=torch.float64)
+ reference = luv(rgb(wide).to(dtype).double()).to(device=device, dtype=dtype)
+ self.assert_close(data_out, reference)
+ else:
+ self.assert_close(data_out, data)
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
@@ -161,8 +166,6 @@ class TestLuvToRgb(BaseTester):
assert kornia.color.luv_to_rgb(img)
def test_unit(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
data = torch.tensor(
[
[
@@ -219,12 +222,13 @@ class TestLuvToRgb(BaseTester):
dtype=dtype,
)
+ if dtype in (torch.float16, torch.bfloat16):
+ expected = kornia.color.luv_to_rgb(data.to(device="cpu", dtype=torch.float64)).to(
+ device=device, dtype=dtype
+ )
self.assert_close(kornia.color.luv_to_rgb(data), expected)
def test_forth_and_back(self, device, dtype):
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
-
# Generate on CPU with a fixed seed so the test is order-independent.
torch.manual_seed(0)
data = torch.rand(3, 4, 5).to(device=device, dtype=dtype)
@@ -232,7 +236,13 @@ class TestLuvToRgb(BaseTester):
rgb = kornia.color.luv_to_rgb
data_out = rgb(luv(data))
- self.assert_close(data_out, data)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Quantize the intermediate representation too: its loss cannot be undone by the inverse.
+ wide = data.to(device="cpu", dtype=torch.float64)
+ reference = rgb(luv(wide).to(dtype).double()).to(device=device, dtype=dtype)
+ self.assert_close(data_out, reference)
+ else:
+ self.assert_close(data_out, data)
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
@@ -269,13 +279,12 @@ def test_luv_converters_float16_black_are_finite(function):
@pytest.mark.parametrize(
"half_dtype, scale, luv_atol, rgb_atol",
[
- # A subnormal float16 eps overflows the backward of rgb_to_luv (1e-5) and luv_to_rgb (1e-8).
- (torch.float16, 1e-5, 5e-2, 2e-5),
- (torch.float16, 1e-8, 5e-2, 2e-5),
- # A float16 eps floor much larger than the smallest normal moves these values.
- (torch.float16, 1e-3, 5e-2, 2e-5),
- # bfloat16 represents the default eps and must keep it.
- (torch.bfloat16, 1e-4, 2e-3, 2e-5),
+ # Half inputs are converted in float32 with the caller's eps, so dark pixels match the float32 conversion up to
+ # the rounding of the output. In float16, 1e-5 is subnormal and 1e-8 rounds to black.
+ (torch.float16, 1e-5, 1e-4, 2e-5),
+ (torch.float16, 1e-8, 1e-4, 2e-5),
+ (torch.float16, 1e-3, 1e-4, 2e-5),
+ (torch.bfloat16, 1e-4, 1e-4, 2e-5),
],
)
def test_luv_converters_half_dark_pixels_match_float32(half_dtype, scale, luv_atol, rgb_atol):
diff --git a/tests/color/test_rgb.py b/tests/color/test_rgb.py
index cca638461..1ba353884 100644
--- a/tests/color/test_rgb.py
+++ b/tests/color/test_rgb.py
@@ -491,6 +491,17 @@ class TestLinearRgb(BaseTester):
class TestRgb255Normals(BaseTester):
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize("op", [kornia.color.normals_to_rgb255, kornia.color.rgb255_to_normals])
+ def test_integer_preserves_default_floating_dtype(self, op):
+ previous = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(torch.float64)
+ data = torch.zeros(3, 1, 1, dtype=torch.int64)
+ assert op(data).dtype == torch.float64
+ finally:
+ torch.set_default_dtype(previous)
+
# Smoke tests: check if the functions execute and return a tensor
def test_smoke(self, device, dtype):
C, H, W = 3, 4, 5
@@ -514,12 +525,13 @@ class TestRgb255Normals(BaseTester):
data_rgb = torch.rand(1, 3, 3, 2, device=device, dtype=dtype)
rgb255 = kornia.color.rgb_to_rgb255(data_rgb)
rgb_restored = kornia.color.rgb255_to_rgb(rgb255)
- torch.testing.assert_close(data_rgb, rgb_restored, atol=1e-4, rtol=1e-4)
+ self.assert_close(data_rgb, rgb_restored)
+ def test_normals_back_and_forth(self, device, dtype):
data_normals = torch.nn.functional.normalize(torch.rand(1, 3, 3, 2, device=device, dtype=dtype), p=2, dim=1)
rgb255_normals = kornia.color.normals_to_rgb255(data_normals)
normals_restored = kornia.color.rgb255_to_normals(rgb255_normals)
- torch.testing.assert_close(data_normals, normals_restored, atol=1e-4, rtol=1e-4)
+ self.assert_close(data_normals, normals_restored)
def test_gradcheck(self, device, dtype):
B, C, H, W = 2, 3, 4, 4
diff --git a/tests/enhance/test_zca.py b/tests/enhance/test_zca.py
index cb19d386a..73a06dd8c 100644
--- a/tests/enhance/test_zca.py
+++ b/tests/enhance/test_zca.py
@@ -37,15 +37,16 @@ class TestZCA(BaseTester):
divisor = sample_count - 1 if unbiased else sample_count
# The two features have zero cross covariance and variances N * scale**2 / divisor and a quarter of it.
std = [math.sqrt(sample_count * s**2 / divisor + 1e-6) for s in (scale, scale / 2)]
- expected_transform = torch.diag(torch.tensor([1 / s for s in std], device=device, dtype=dtype))
- expected_inverse = torch.diag(torch.tensor(std, device=device, dtype=dtype))
+ compute_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ expected_transform = torch.diag(torch.tensor([1 / s for s in std], device=device, dtype=compute_dtype))
+ expected_inverse = torch.diag(torch.tensor(std, device=device, dtype=compute_dtype))
expected = (data - mean) * torch.tensor([1 / s for s in std], device=device, dtype=dtype)
if dim != 0:
data, expected = data.t(), expected.t()
transform, actual_mean, inverse = kornia.enhance.zca_mean(data, dim=dim, unbiased=unbiased, return_inverse=True)
self.assert_close(transform, expected_transform)
- self.assert_close(actual_mean, mean)
+ self.assert_close(actual_mean, mean.to(actual_mean.dtype))
self.assert_close(inverse, expected_inverse)
self.assert_close(kornia.enhance.zca_whiten(data, dim=dim, unbiased=unbiased), expected)
model = kornia.enhance.ZCAWhitening(dim=dim, unbiased=unbiased)
@@ -74,7 +75,12 @@ class TestZCA(BaseTester):
data = torch.tensor([[-300.0], [300.0]], device=device, dtype=dtype).repeat(2, 1)
std = math.sqrt(4 * 300.0**2 / (3 if unbiased else 4) + 1e-6)
transform, mean, inverse = kornia.enhance.zca_mean(data, unbiased=unbiased, return_inverse=True)
- assert transform.dtype == mean.dtype == inverse.dtype == dtype
+ assert (
+ transform.dtype
+ == mean.dtype
+ == inverse.dtype
+ == (torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype)
+ )
# Compare dimensionless values so an absolute tolerance cannot accept a zero transform.
self.assert_close(transform * std, torch.ones_like(transform))
self.assert_close(mean, torch.zeros_like(mean))
@@ -93,7 +99,12 @@ class TestZCA(BaseTester):
with torch.autocast(device_type=device.type, dtype=torch.float16):
transform, mean, inverse = kornia.enhance.zca_mean(data, unbiased=unbiased, return_inverse=True)
assert torch.is_autocast_enabled(device.type)
- assert transform.dtype == mean.dtype == inverse.dtype == input_dtype
+ assert (
+ transform.dtype
+ == mean.dtype
+ == inverse.dtype
+ == (torch.float32 if input_dtype in (torch.float16, torch.bfloat16) else input_dtype)
+ )
self.assert_close(transform * std, torch.ones_like(transform))
self.assert_close(mean, torch.zeros_like(mean))
self.assert_close(inverse / std, torch.ones_like(inverse))
@@ -131,7 +142,7 @@ class TestZCA(BaseTester):
assert transform.shape == inverse.shape == (2, 2)
assert mean.shape == (1, 2)
assert transform.device == mean.device == inverse.device == data.device
- assert transform.dtype == mean.dtype == inverse.dtype == half_dtype
+ assert transform.dtype == mean.dtype == inverse.dtype == torch.float32
@pytest.mark.parametrize("unbiased", [True, False])
def test_covariance_accumulation_bfloat16_range(self, device, dtype, unbiased):
@@ -143,7 +154,12 @@ class TestZCA(BaseTester):
divisor = data.shape[0] - 1 if unbiased else data.shape[0]
normalized_std = math.sqrt(data.shape[0] / divisor)
transform, mean, inverse = kornia.enhance.zca_mean(data, unbiased=unbiased, return_inverse=True)
- assert transform.dtype == mean.dtype == inverse.dtype == dtype
+ assert (
+ transform.dtype
+ == mean.dtype
+ == inverse.dtype
+ == (torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype)
+ )
assert transform.device == mean.device == inverse.device == device
# Compare dimensionless values so an absolute tolerance cannot accept a zero transform.
self.assert_close(transform * scale, torch.full_like(transform, 1 / normalized_std))
@@ -223,9 +239,6 @@ class TestZCA(BaseTester):
if "xla" in device.type:
pytest.skip("buggy with XLA devices.")
- if dtype == torch.float16:
- pytest.skip("not work for half-precision")
-
data = torch.tensor([[0, 1], [1, 0], [-1, 0], [0, -1]], device=device, dtype=dtype)
if dim == 1:
@@ -314,9 +327,10 @@ class TestZCA(BaseTester):
assert "transform_inv" in state_dict
assert state_dict["mean_vector"].shape == zca.mean_vector.shape
assert state_dict["transform_matrix"].shape == zca.transform_matrix.shape
- # Without compute_inv the inverse is an empty placeholder, made on the data's device and dtype.
+ # Without compute_inv the inverse is an empty placeholder in the fit's working dtype.
assert state_dict["transform_inv"].shape == (0,)
- assert all(tensor.device == device and tensor.dtype == dtype for tensor in state_dict.values())
+ compute_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ assert all(tensor.device == device and tensor.dtype == compute_dtype for tensor in state_dict.values())
def test_unfitted_state_is_empty(self):
zca = kornia.enhance.ZCAWhitening()
diff --git a/tests/filters/test_canny.py b/tests/filters/test_canny.py
index d9210cc4c..c3f1839f9 100644
--- a/tests/filters/test_canny.py
+++ b/tests/filters/test_canny.py
@@ -173,8 +173,14 @@ class TestCanny(BaseTester):
)
magnitude, edges = canny(inp)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Magnitude literals describe unquantized inputs; the edge mask is checked independently below.
+ expected_magnitude = canny(inp.to(device="cpu", dtype=torch.float64))[0].to(device=device, dtype=dtype)
- self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
+ if dtype in (torch.float16, torch.bfloat16):
+ self.assert_close(magnitude, expected_magnitude)
+ else:
+ self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
self.assert_close(edges, expected_edges, atol=1e-4, rtol=1e-4)
def test_magnitude_hyst(self, device, dtype):
@@ -227,8 +233,16 @@ class TestCanny(BaseTester):
)
magnitude, edges = canny(inp, hysteresis=True)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Magnitude literals describe unquantized inputs; the edge mask is checked independently below.
+ expected_magnitude = canny(inp.to(device="cpu", dtype=torch.float64), hysteresis=True)[0].to(
+ device=device, dtype=dtype
+ )
- self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
+ if dtype in (torch.float16, torch.bfloat16):
+ self.assert_close(magnitude, expected_magnitude)
+ else:
+ self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
self.assert_close(edges, expected_edges, atol=1e-4, rtol=1e-4)
def test_magnitude_hyst_false(self, device, dtype):
@@ -281,8 +295,16 @@ class TestCanny(BaseTester):
)
magnitude, edges = canny(inp, hysteresis=False)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Magnitude literals describe unquantized inputs; the edge mask is checked independently below.
+ expected_magnitude = canny(inp.to(device="cpu", dtype=torch.float64), hysteresis=False)[0].to(
+ device=device, dtype=dtype
+ )
- self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
+ if dtype in (torch.float16, torch.bfloat16):
+ self.assert_close(magnitude, expected_magnitude)
+ else:
+ self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
self.assert_close(edges, expected_edges, atol=1e-4, rtol=1e-4)
def test_magnitude_threshold(self, device, dtype):
@@ -335,8 +357,16 @@ class TestCanny(BaseTester):
)
magnitude, edges = canny(inp, low_threshold=0.3, high_threshold=0.9)
+ if dtype in (torch.float16, torch.bfloat16):
+ # Magnitude literals describe unquantized inputs; the edge mask is checked independently below.
+ expected_magnitude = canny(
+ inp.to(device="cpu", dtype=torch.float64), low_threshold=0.3, high_threshold=0.9
+ )[0].to(device=device, dtype=dtype)
- self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
+ if dtype in (torch.float16, torch.bfloat16):
+ self.assert_close(magnitude, expected_magnitude)
+ else:
+ self.assert_close(magnitude, expected_magnitude, atol=1e-4, rtol=1e-4)
self.assert_close(edges, expected_edges, atol=1e-4, rtol=1e-4)
def test_gradcheck(self, device):
@@ -777,9 +807,11 @@ class TestConventionsCanny(BaseTester):
rgb = torch.rand(2, 3, 11, 13, generator=generator).to(device=device, dtype=dtype)
magnitude, edges = canny(rgb)
assert magnitude.shape == edges.shape == (2, 1, 11, 13)
- magnitude_grey, edges_grey = canny(rgb_to_grayscale(rgb))
- self.assert_close(magnitude, magnitude_grey)
- self.assert_close(edges, edges_grey)
+ # Canny promotes before grayscale conversion; rounding grayscale first can change suppression ties.
+ working_rgb = rgb.float() if dtype in (torch.float16, torch.bfloat16) else rgb
+ magnitude_grey, edges_grey = canny(rgb_to_grayscale(working_rgb))
+ self.assert_close(magnitude, magnitude_grey.to(dtype))
+ self.assert_close(edges, edges_grey.to(dtype))
# channel 0 is read as red: the same data in BGR order gives other edges
_, edges_bgr = canny(rgb.flip(1))
assert not torch.equal(edges_bgr, edges)
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index 6df01855e..c8cff4f7f 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -49,34 +49,98 @@ from testing.base import (
)
+# Generated with Python math: w = [exp(-(i - mean)**2 / (2 * sigma**2)) for i in range(size)];
+# expected = [v / sum(w) for v in w], with mean = size // 2 when unspecified.
@pytest.mark.parametrize(
"window_size, sigma, mean, expected",
[
- (5, 1.0, None, torch.tensor([[0.0545, 0.2442, 0.4026, 0.2442, 0.0545]])),
+ (5, 1.0, None, [0.05448868455, 0.244201342003, 0.402619946894, 0.244201342003, 0.05448868455]),
(
11,
5.0,
None,
- torch.tensor([[0.0663, 0.0794, 0.0914, 0.1010, 0.1072, 0.1094, 0.1072, 0.1010, 0.0914, 0.0794, 0.0663]]),
+ [
+ 0.06634166574,
+ 0.079425394123,
+ 0.091360949823,
+ 0.100969464792,
+ 0.107213067802,
+ 0.10937891544,
+ 0.107213067802,
+ 0.100969464792,
+ 0.091360949823,
+ 0.079425394123,
+ 0.06634166574,
+ ],
),
(
11,
5.0,
8.0,
- torch.tensor([[0.0343, 0.0463, 0.0600, 0.0747, 0.0895, 0.1029, 0.1138, 0.1208, 0.1232, 0.1208, 0.1138]]),
+ [
+ 0.034263492805,
+ 0.046250877542,
+ 0.059984154618,
+ 0.074744859274,
+ 0.089485843327,
+ 0.102933220947,
+ 0.113758802295,
+ 0.120793253768,
+ 0.12323343936,
+ 0.120793253768,
+ 0.113758802295,
+ ],
),
(
11,
11.0,
3.0,
- torch.tensor([[0.0926, 0.0946, 0.0957, 0.0961, 0.0957, 0.0946, 0.0926, 0.0900, 0.0867, 0.0828, 0.0785]]),
+ [
+ 0.092623025915,
+ 0.094556631274,
+ 0.095736116673,
+ 0.096132538951,
+ 0.095736116673,
+ 0.094556631274,
+ 0.092623025915,
+ 0.089982225006,
+ 0.086697241637,
+ 0.082844679454,
+ 0.078511767227,
+ ],
),
],
)
def test_gaussian(window_size, sigma, mean, expected, device, dtype):
- expected = expected.to(device=device, dtype=dtype)
+ expected = torch.tensor([expected], device=device, dtype=dtype)
result = gaussian(window_size, sigma, mean=mean, device=device, dtype=dtype)
- assert_close(result, expected, atol=1e-4, rtol=1e-4)
+ assert_close(result, expected)
+
+
+def test_gaussian_mixed_native_precision_mean(device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ sigma = torch.tensor([[1.3]], device=device, dtype=torch.float32)
+ mean = torch.tensor([[2.123456789]], device=device, dtype=torch.float64)
+ actual = gaussian(5, sigma, mean=mean)
+ expected = gaussian(5, sigma.double(), mean=mean)
+ assert actual.dtype == torch.float64
+ # Sigma's native float32 arithmetic precedes promotion by the float64 mean.
+ assert_close(actual, expected, rtol=1e-7, atol=1e-8)
+
+
[email protected]("half_dtype", [torch.float16, torch.bfloat16])
+def test_gaussian_half_default_dtype(half_dtype):
+ expected = gaussian(11, 1.3, mean=3.0, dtype=torch.float64).to(half_dtype)
+ previous = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(half_dtype)
+ actual = gaussian(11, 1.3, mean=3.0)
+ assert actual.dtype == half_dtype
+ assert_close(actual, expected, rtol=0, atol=0)
+ finally:
+ torch.set_default_dtype(previous)
@pytest.mark.parametrize(
@@ -756,7 +820,7 @@ class TestGaussianBlur2d(BaseTester):
sigma = (1.5, 1.5)
output_sep = gaussian_blur2d(sample, (3, 3), sigma, separable=True)
output_non_sep = gaussian_blur2d(sample, (3, 3), sigma, separable=False)
- assert_close(output_sep, output_non_sep, atol=1e-4, rtol=1e-4)
+ assert_close(output_sep, output_non_sep)
def test_different_kernel_sizes(self, device, dtype):
"""Test with various kernel sizes."""
diff --git a/tests/test_half_precision_accuracy.py b/tests/test_half_precision_accuracy.py
new file mode 100644
index 000000000..a8c2f6009
--- /dev/null
+++ b/tests/test_half_precision_accuracy.py
@@ -0,0 +1,181 @@
+# 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 pytest
+import torch
+
+import kornia
+
+from testing.base import BaseTester
+
+
+class TestHalfPrecisionAccuracy(BaseTester):
+ @pytest.fixture(autouse=True)
+ def half_only(self, dtype):
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("half-precision numerical regressions")
+
+ @pytest.mark.parametrize("space", ["lab", "luv"])
+ @pytest.mark.parametrize("inverse", [False, True])
+ def test_color(self, device, dtype, space, inverse):
+ # Fixed representable RGB samples include black, white, and colors near neutral.
+ rgb = torch.tensor(
+ [[0, 1, 0.5, 0.25, 0.75], [0, 1, 0.5, 0.75, 0.25], [0, 1, 0.5, 0.5, 0.5]],
+ device=device,
+ dtype=dtype,
+ ).reshape(3, 1, 5)
+ forward = getattr(kornia.color, "rgb_to_" + space)
+ op = getattr(kornia.color, space + "_to_rgb") if inverse else forward
+ data = forward(rgb.float()).to(dtype) if inverse else rgb
+ reference = op(data.to(device="cpu", dtype=torch.float64)).to(device=device, dtype=dtype)
+ actual = op(data)
+ assert actual.dtype == dtype
+ self.assert_close(actual, reference, rtol=torch.finfo(dtype).eps, atol=2e-4)
+
+ def test_normals_to_rgb255(self, device, dtype):
+ # Half inputs are mapped in their own dtype, which rounds twice: within one unit in the last place of the
+ # correctly rounded result for every representable component in [-1, 1]. The check runs in float64, so it
+ # does not round itself.
+ values = torch.arange(-(2**15), 2**15, dtype=torch.int32).to(torch.int16).view(dtype)
+ values = values[torch.isfinite(values) & (values.abs() <= 1)]
+ data = values[: values.numel() // 3 * 3].reshape(3, 1, -1).to(device)
+ reference = kornia.color.normals_to_rgb255(data.to(device="cpu", dtype=torch.float64)).to(dtype)
+ actual = kornia.color.normals_to_rgb255(data)
+ assert actual.dtype == dtype
+ self.assert_close(actual.double(), reference.to(device).double(), rtol=torch.finfo(dtype).eps, atol=0)
+
+ def test_rgb255_to_normals(self, device, dtype):
+ data = torch.tensor([[-0.75, 0, 0.75], [0.5, 0, -0.5], [0.25, 0, -0.25]], device=device, dtype=dtype).reshape(
+ 3, 1, 3
+ )
+ data = ((data.float() + 1) * 127.5).to(dtype)
+ reference = kornia.color.rgb255_to_normals(data.to(device="cpu", dtype=torch.float64)).to(
+ device=device, dtype=dtype
+ )
+ actual = kornia.color.rgb255_to_normals(data)
+ assert torch.isfinite(actual).all()
+ self.assert_close(actual, reference, rtol=torch.finfo(dtype).eps / 2, atol=1e-5)
+
+ @pytest.mark.parametrize("sigma", [1.3, 11.0])
+ def test_gaussian(self, device, dtype, sigma):
+ reference = kornia.filters.gaussian(11, sigma, mean=3.0, dtype=torch.float64).to(device=device, dtype=dtype)
+ actual = kornia.filters.gaussian(11, sigma, mean=3.0, device=device, dtype=dtype)
+ self.assert_close(actual, reference, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("separable", [True, False])
+ def test_blur(self, device, dtype, separable):
+ data = (torch.arange(3 * 8 * 8, device=device).reshape(1, 3, 8, 8) % 17).to(dtype) / 16
+ reference = kornia.filters.gaussian_blur2d(
+ data.to(device="cpu", dtype=torch.float64), 5, (1.25, 1.5), separable=separable
+ ).to(device=device, dtype=dtype)
+ actual = kornia.filters.gaussian_blur2d(data, 5, (1.25, 1.5), separable=separable)
+ self.assert_close(actual, reference, rtol=0, atol=0)
+
+ def test_canny_large_step(self, device, dtype):
+ # Squaring the unnormalized Sobel gradient of a 255-level step overflows float16.
+ data = torch.zeros(1, 1, 8, 8, device=device, dtype=dtype)
+ data[..., 4:] = 255
+ actual = kornia.filters.canny(data, kernel_size=1, low_threshold=100, high_threshold=200)
+ reference = kornia.filters.canny(
+ data.to(device="cpu", dtype=torch.float64), kernel_size=1, low_threshold=100, high_threshold=200
+ )
+ for result, expected in zip(actual, reference):
+ assert torch.isfinite(result).all()
+ self.assert_close(result, expected.to(device=device, dtype=dtype), rtol=0, atol=0)
+
+ @pytest.mark.parametrize("dim", [0, 1, -1])
+ def test_rank_deficient_zca(self, device, dtype, dim):
+ data = torch.tensor([[0, 1], [1, 0], [-1, 0], [0, -1]], device=device, dtype=dtype)
+ if dim == 0:
+ data = data.t()
+ # Each centered sample lies on (1, -1, 1, -1); covariance has one eigenvalue of 2.
+ expected = (
+ data.to(device="cpu", dtype=torch.float64)
+ - data.to(device="cpu", dtype=torch.float64).mean(dim, keepdim=True)
+ ) / (2 + 1e-6) ** 0.5
+ model = kornia.enhance.ZCAWhitening(dim=dim).fit(data)
+ self.assert_close(model(data), expected.to(device=device, dtype=dtype))
+ self.assert_close(kornia.enhance.zca_whiten(data, dim=dim), expected.to(device=device, dtype=dtype))
+ assert model.transform_matrix.dtype == torch.float32
+ assert model.mean_vector.dtype == torch.float32
+
+ @pytest.mark.parametrize(
+ "op",
+ [
+ kornia.filters.gaussian_blur2d,
+ kornia.enhance.zca_whiten,
+ kornia.color.rgb_to_lab,
+ kornia.color.lab_to_rgb,
+ kornia.color.rgb_to_luv,
+ kornia.color.luv_to_rgb,
+ kornia.filters.canny,
+ ],
+ )
+ def test_enclosing_autocast(self, device, dtype, op):
+ if device.type != "cpu":
+ pytest.skip("CPU autocast regression")
+ data = (torch.arange(192, device=device).reshape(4, 3, 4, 4) % 13).to(dtype) / 16
+ args = (3, (1.25, 1.5)) if op is kornia.filters.gaussian_blur2d else ()
+ expected = op(data, *args)
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ actual = op(data, *args)
+ if isinstance(actual, tuple):
+ for result, reference in zip(actual, expected):
+ self.assert_close(result, reference, rtol=0, atol=0)
+ else:
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ def test_inverse_enclosing_autocast(self, device, dtype):
+ if device.type != "cpu":
+ pytest.skip("CPU autocast regression")
+ data = torch.tensor([[0, 2], [1, 3], [-1, 4], [0.5, 1]], device=device, dtype=dtype)
+ model = kornia.enhance.ZCAWhitening(compute_inv=True).fit(data)
+ whitened = model(data)
+ expected = model.inverse_transform(whitened)
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ actual = model.inverse_transform(whitened)
+ self.assert_close(actual, expected, rtol=0, atol=0)
+
+ @pytest.mark.parametrize("name", ["rgb_to_lab", "lab_to_rgb", "rgb_to_luv", "luv_to_rgb", "blur", "zca"])
+ def test_backward(self, device, dtype, name):
+ data = ((torch.arange(3 * 6 * 6, device=device).reshape(1, 3, 6, 6) % 17).to(dtype) / 16).requires_grad_()
+ if name == "blur":
+ op = kornia.filters.GaussianBlur2d(3, (1.25, 1.5))
+ elif name == "zca":
+ # Distinct covariance eigenvalues keep the SVD derivative well-defined.
+ data = torch.tensor([[0, 2], [1, 3], [-1, 4], [0.5, 1]], device=device, dtype=dtype, requires_grad=True)
+ op = kornia.enhance.zca_whiten
+ else:
+ op = getattr(kornia.color, name)
+ wide = data.detach().float().requires_grad_()
+ gradient = torch.autograd.grad(op(data).sum(), data)[0]
+ reference = torch.autograd.grad(op(wide).sum(), wide)[0]
+ assert torch.isfinite(gradient).all()
+ assert gradient.dtype == dtype
+ self.assert_close(gradient, reference.to(dtype))
+
+ @pytest.mark.parametrize("name", ["rgb_to_lab", "lab_to_rgb", "rgb_to_luv", "luv_to_rgb", "blur", "zca"])
+ def test_dynamo(self, device, dtype, name, torch_optimizer):
+ data = (torch.arange(4 * 3 * 6 * 6, device=device).reshape(4, 3, 6, 6) % 17).to(dtype) / 16
+ if name == "blur":
+ op = kornia.filters.GaussianBlur2d(3, (1.25, 1.5))
+ elif name == "zca":
+ data = data[:, :, :1, :1]
+ op = kornia.enhance.zca_whiten
+ else:
+ op = getattr(kornia.color, name)
+ self.assert_close(torch_optimizer(op)(data), op(data))