Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fix strict torch.export for the JPEG codec (#5112)

Karnajeet Gosavi8933b042203d
diff --git a/changelog.d/5112.fixed.md b/changelog.d/5112.fixed.md
new file mode 100644
index 000000000..e5d826b36
--- /dev/null
+++ b/changelog.d/5112.fixed.md
@@ -0,0 +1,6 @@
+`JPEGCodecDifferentiable` and `jpeg_codec_differentiable` now build their DCT and IDCT bases with `math.pi` instead of
+the float32 tensor `kornia.constants.pi` (#5107). Strict `torch.export` on torch 2.5.1 and 2.9.1 rejected the codec
+because its forward referenced that module-level tensor, and torch 2.5.1's `torch.export.export` is strict by default.
+The float64 bases were only float32-accurate (the DCT basis was up to 5.65e-7 off the exact cosines), so float64
+outputs change, typically by less than 1e-6 for an image in [0, 1]. float32, float16 and bfloat16 outputs are
+unchanged.
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index 6805df3ae..84444b1cb 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -25,7 +25,6 @@ import torch.nn.functional as F
from torch import nn
from kornia.color import rgb_to_ycbcr, ycbcr_to_rgb
-from kornia.constants import pi
from kornia.core.check import (
KORNIA_CHECK,
KORNIA_CHECK_IS_TENSOR,
@@ -208,7 +207,7 @@ def _idct_8x8(input: torch.Tensor) -> torch.Tensor:
spatial_idx = idx.unsqueeze(0)
freq_idx = idx.unsqueeze(1)
- basis = torch.cos((2.0 * spatial_idx + 1.0) * freq_idx * pi / 16.0)
+ basis = torch.cos((2.0 * spatial_idx + 1.0) * freq_idx * math.pi / 16.0)
alpha = torch.ones(8, dtype=dtype, device=device)
alpha[0] = 1.0 / (2**0.5)
dct_scale = torch.outer(alpha, alpha)
@@ -671,7 +670,7 @@ def _build_dct8_basis_scale(
dtype: Union[torch.dtype, None], device: Union[str, torch.device, None]
) -> tuple[torch.Tensor, torch.Tensor]:
i = torch.arange(8, dtype=dtype, device=device)
- freq = (2.0 * i + 1.0)[:, None] * i[None, :] * (pi / 16.0)
+ freq = (2.0 * i + 1.0)[:, None] * i[None, :] * (math.pi / 16.0)
basis_1d = torch.cos(freq)
dct_tensor = basis_1d[:, None, :, None] * basis_1d[None, :, None, :]
alpha = torch.ones(8, dtype=dtype, device=device)
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index 335b78950..f8fc7d000 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -15,6 +15,8 @@
# limitations under the License.
#
+import math
+
import pytest
import torch
@@ -24,6 +26,55 @@ from testing.base import BaseTester
class TestDiffJPEG(BaseTester):
+ def test_float64_dct_basis_uses_full_precision_pi(self) -> None:
+ from kornia.enhance.jpeg import _get_dct8_basis_scale
+
+ dct_basis, _ = _get_dct8_basis_scale(torch.float64, "cpu")
+ index = torch.arange(8, dtype=torch.float64)
+ basis_1d = torch.cos((2.0 * index + 1.0)[:, None] * index[None, :] * (math.pi / 16.0))
+ expected = basis_1d[:, None, :, None] * basis_1d[None, :, None, :]
+ torch.testing.assert_close(dct_basis, expected, rtol=0.0, atol=0.0)
+
+ def test_float64_idct_uses_full_precision_pi(self) -> None:
+ from kornia.enhance.jpeg import _idct_8x8
+
+ # A non-symmetric block, so a transposed basis fails too.
+ coefficients = (torch.arange(64, dtype=torch.float64) * 37 % 64 - 31.5).view(1, 1, 8, 8)
+ basis = torch.tensor(
+ [[math.cos((2 * s + 1) * f * math.pi / 16) for s in range(8)] for f in range(8)], dtype=torch.float64
+ )
+ alpha = torch.tensor([1.0 / math.sqrt(2.0)] + [1.0] * 7, dtype=torch.float64)
+ expected = 0.25 * basis.T @ (coefficients[0, 0] * alpha[:, None] * alpha[None, :]) @ basis + 128.0
+ # A float32 pi puts the result about 3e-5 off.
+ self.assert_close(_idct_8x8(coefficients)[0, 0], expected, rtol=0.0, atol=1e-10)
+
+ def test_strict_torch_export(self) -> None:
+ from kornia.enhance.jpeg import _DCT8_CACHE, JPEGCodecDifferentiable
+
+ image = torch.rand(1, 3, 16, 16)
+ quality = torch.tensor([50.0])
+ codec = JPEGCodecDifferentiable()
+ cache = _DCT8_CACHE.copy()
+ try:
+ for warm_cache in (False, True):
+ _DCT8_CACHE.clear()
+ if warm_cache:
+ expected = codec(image, quality)
+ try:
+ exported = torch.export.export(codec, (image, quality), strict=True).module()
+ except RuntimeError as e:
+ # torch 2.5.1 routes strict export through Dynamo, which rejects Python 3.13+.
+ if "Python 3.13+ not yet supported for torch.compile" in str(e):
+ pytest.skip(f"strict torch.export is unavailable in this environment: {e}")
+ raise
+ _DCT8_CACHE.clear()
+ if not warm_cache:
+ expected = codec(image, quality)
+ self.assert_close(exported(image, quality), expected)
+ finally:
+ _DCT8_CACHE.clear()
+ _DCT8_CACHE.update(cache)
+
def test_smoke(self, device, dtype) -> None:
"""This test standard usage."""
B, H, W = 2, 32, 32