Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): run the differentiable JPEG codec in float32 for half-precision images (#6100)

Dmytro Mishkindc22bf86d690
diff --git a/changelog.d/6100.fixed.md b/changelog.d/6100.fixed.md
new file mode 100644
index 000000000..0e5bb99a3
--- /dev/null
+++ b/changelog.d/6100.fixed.md
@@ -0,0 +1,9 @@
+`jpeg_codec_differentiable` and `JPEGCodecDifferentiable` now compute `float16` and `bfloat16` images in `float32`,
+quality and quantization tables included, and return the input dtype. The codec ran in the input dtype before, where
+pixels scaled to [0, 255], DCT coefficients of about 1000 and a quality scale of 2500 do not fit an 8-bit or 11-bit
+significand: on random 64x64 images, outputs were 0.15 to 0.25 (`bfloat16`) and 0.11 to 0.18 (`float16`) away from the
+`float64` codec, and image gradients were off by about their own magnitude (relative L2 error 0.5 to 0.9). The output
+is now the `float32` codec's output rounded once to the input dtype. `JPEGCodecDifferentiable` also no longer rounds
+its `float32` tables to the image dtype before passing them to the codec. Inside `torch.autocast`, autocast still runs
+part of the codec in its lower dtype, as before, but the output now keeps the input dtype there too: a `float32` image
+under CPU `bfloat16` autocast used to come back as `bfloat16`.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index 66248e291..428190b22 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -37,8 +37,9 @@ precision, so the table says nothing about those backends.
* - ``kornia.enhance``
- βœ… Yes
- ⚠️ Partial
- - 0 / 2
- - bfloat16: ``DiffJPEG`` and ZCA whitening accuracy.
+ - 0 / 1
+ - bfloat16: ZCA whitening accuracy. ``jpeg_codec_differentiable`` computes float16 and bfloat16 inputs in
+ float32 and returns the input dtype.
* - ``kornia.morphology``
- βœ… Yes
- βœ… Yes
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index c7aa39336..f990dd6fb 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -498,6 +498,9 @@ def jpeg_codec_differentiable(
jpeg_quality is a one-dimensional (1,) shared quality or (N,) per-image quality; a 0-D
scalar is rejected. The codec pads on the bottom and right internally and crops back to
the input shape. See :class:`JPEGCodecDifferentiable` for the reusable-table wrapper.
+ float16 and bfloat16 inputs are computed in float32, quality and tables included, and the
+ output is rounded once to the input dtype. Inside a ``torch.autocast`` region the output keeps
+ the input dtype too, but autocast still runs part of the codec in its own lower dtype.
Based on :cite:`reich2024` :cite:`shin2017`, we perform differentiable JPEG encoding-decoding as follows:
@@ -578,8 +581,13 @@ def jpeg_codec_differentiable(
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_IS_TENSOR(jpeg_quality)
# Get device and dtype
- dtype: Union[torch.dtype, None] = input.dtype
+ out_dtype: torch.dtype = input.dtype
device: Union[str, torch.device, None] = input.device
+ # The codec scales pixels to [0, 255], and its DCT coefficients reach about 1000 and its quality scale 2500, where
+ # bfloat16's 8-bit significand rounds by 1 to 16: coarser than the quantization step of 1 at quality 99. Compute
+ # float16 and bfloat16 inputs in float32 and round once, to the input dtype, at the end.
+ dtype: torch.dtype = torch.float32 if out_dtype in (torch.float16, torch.bfloat16) else out_dtype
+ input = input.to(dtype)
# Use default QT if QT is not given
quantization_table_y = _get_default_qt_y(device, dtype) if quantization_table_y is None else quantization_table_y
quantization_table_c = _get_default_qt_c(device, dtype) if quantization_table_c is None else quantization_table_c
@@ -650,7 +658,7 @@ def jpeg_codec_differentiable(
# Clip coded image
image_rgb_jpeg = _differentiable_clipping(input=image_rgb_jpeg, min_val=0.0, max_val=255.0)
# Crop the image again to the original shape
- return image_rgb_jpeg[..., : H - h_pad, : W - w_pad]
+ return image_rgb_jpeg[..., : H - h_pad, : W - w_pad].to(out_dtype)
def _get_dct8_basis_scale(
@@ -786,8 +794,8 @@ class JPEGCodecDifferentiable(nn.Module):
The method runs an RGB image through the internal JPEG codec pipeline
using the module's quantization tables, then reconstructs an RGB tensor.
- Quantization tables are moved to the input device and dtype before
- encoding/decoding.
+ Quantization tables are moved to the input device and to the dtype
+ the codec computes in before encoding/decoding.
Args:
image_rgb: Input RGB tensor with shape :math:`(*, 3, H, W)`.
@@ -797,17 +805,13 @@ class JPEGCodecDifferentiable(nn.Module):
Reconstructed RGB tensor after differentiable JPEG processing, with
the same shape as ``image_rgb``.
"""
- device = image_rgb.device
- dtype = image_rgb.dtype
- # Move quantization tables to the same device and dtype as input
- # and store it in the local variables created in init
- quantization_table_y = self.quantization_table_y.to(device, dtype)
- quantization_table_c = self.quantization_table_c.to(device, dtype)
- # Perform encoding-decoding
+ # The codec moves the tables to the input device and casts them to the dtype it computes in, float32 for a
+ # half-precision image, in one step. Casting them to the image dtype here would round them, and a device-only
+ # move first would try to put float64 tables on MPS, which has no float64.
image_rgb_jpeg: torch.Tensor = jpeg_codec_differentiable(
image_rgb,
jpeg_quality=jpeg_quality,
- quantization_table_c=quantization_table_c,
- quantization_table_y=quantization_table_y,
+ quantization_table_c=self.quantization_table_c,
+ quantization_table_y=self.quantization_table_y,
)
return image_rgb_jpeg
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 9e7ebf986..c5e16cfab 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -69,7 +69,6 @@ call builtins.AssertionError tests/color/test_luv.py::TestRgbToLuv::test_unit[cp
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_jpeg.py::TestDiffJPEG::test_cardinality[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]
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index 404e3cd0d..d0b2e0829 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -1171,6 +1171,44 @@ class TestDiffJPEG(BaseTester):
# We use a slightly higher tolerance since our implementation varies from the reference implementation
self.assert_close(img_jpeg, img_jpeg_ref, rtol=0.01, atol=0.01)
+ def test_half_precision_rounds_float32_once(self, device, dtype) -> None:
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("only float16 and bfloat16 inputs are computed in float32")
+ # Computed in the input dtype, the codec rounded pixels scaled to [0, 255], DCT coefficients of about 1000 and a
+ # quantization scale of 2500 to an 8-bit (bfloat16) or 11-bit (float16) significand, and its outputs were up to
+ # 0.2 away from float64's on these qualities.
+ img = torch.rand(4, 3, 32, 32, device=device, dtype=dtype)
+ jpeg_quality = torch.tensor([99.0, 90.0, 50.0, 10.0], device=device, dtype=dtype)
+ img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality)
+ wide = kornia.enhance.jpeg_codec_differentiable(img.float(), jpeg_quality.float())
+ assert img_jpeg.dtype == dtype
+ assert torch.equal(img_jpeg, wide.to(dtype))
+ # The module hands its float32 tables to the codec as they are, not rounded to the image dtype first.
+ qt_y = 1.0 + 254.0 * torch.rand(8, 8, device=device)
+ qt_c = 1.0 + 254.0 * torch.rand(8, 8, device=device)
+ img_jpeg = kornia.enhance.JPEGCodecDifferentiable(qt_y, qt_c)(img, jpeg_quality)
+ wide = kornia.enhance.jpeg_codec_differentiable(img.float(), jpeg_quality.float(), qt_y, qt_c)
+ assert img_jpeg.dtype == dtype
+ assert torch.equal(img_jpeg, wide.to(dtype))
+
+ def test_half_precision_backward(self, device, dtype) -> None:
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("float32 and float64 gradients are covered by test_gradcheck")
+ img = torch.rand(4, 3, 32, 32, device=device, dtype=dtype, requires_grad=True)
+ jpeg_quality = torch.tensor([99.0, 90.0, 50.0, 10.0], device=device, dtype=dtype, requires_grad=True)
+ img32 = img.detach().float().requires_grad_(True)
+ jpeg_quality32 = jpeg_quality.detach().float().requires_grad_(True)
+ for x, q in ((img, jpeg_quality), (img32, jpeg_quality32)):
+ kornia.enhance.jpeg_codec_differentiable(x, q).sum().backward()
+ # The half-precision gradients are the float32 ones rounded once. CUDA's interpolation backward accumulates
+ # with atomics, so that rounding may land one step either way: allow one rounding at the largest magnitude.
+ # Computed in the input dtype, the image gradient was off by its own magnitude (relative L2 error 0.5 to 0.9).
+ eps = torch.finfo(dtype).eps
+ for grad, grad32 in ((img.grad, img32.grad), (jpeg_quality.grad, jpeg_quality32.grad)):
+ assert grad.dtype == dtype
+ assert bool(torch.isfinite(grad).all())
+ self.assert_close(grad, grad32.to(dtype), rtol=eps, atol=eps * grad32.abs().max().item())
+
def test_module(self, device, dtype) -> None:
B, H, W = 4, 16, 16
img = torch.rand(B, 3, H, W, device=device, dtype=dtype)
@@ -1182,6 +1220,18 @@ class TestDiffJPEG(BaseTester):
assert img_jpeg is not None
assert img_jpeg.shape == img.shape
+ def test_module_float64_tables_on_cpu(self, device, dtype) -> None:
+ # The tables may stay float64 on the CPU while the image lives on a device without float64 (MPS): the codec
+ # converts them to the image device and its compute dtype in one step.
+ qt_y = 1.0 + 254.0 * torch.rand(8, 8, dtype=torch.float64)
+ qt_c = 1.0 + 254.0 * torch.rand(8, 8, dtype=torch.float64)
+ img = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
+ jpeg_quality = torch.tensor([50.0], device=device, dtype=dtype)
+ img_jpeg = kornia.enhance.JPEGCodecDifferentiable(qt_y, qt_c)(img, jpeg_quality)
+ assert img_jpeg.dtype == dtype
+ assert img_jpeg.device == img.device
+ assert torch.equal(img_jpeg, kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c))
+
def test_module_with_param(self, device, dtype) -> None:
B, H, W = 4, 16, 16
img = torch.rand(B, 3, H, W, device=device, dtype=dtype)