Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): keep inference and traced tensors out of the JPEG DCT basis cache (#5098)

Manuel Beardo Campoaaaf418e9770
diff --git a/changelog.d/5098.fixed.md b/changelog.d/5098.fixed.md
new file mode 100644
index 000000000..db5f02dd9
--- /dev/null
+++ b/changelog.d/5098.fixed.md
@@ -0,0 +1 @@
+`jpeg_codec_differentiable`, `JPEGCodecDifferentiable` and `RandomJPEG` now keep the DCT basis cache out of `torch.compile`, `torch.export` and dynamo ONNX tracing, and build eager cache entries outside inference mode. A first inference-mode call no longer breaks later image-gradient computations. Exporting the codec no longer leaves cached fake or functional tensors that break subsequent eager calls. Eager calls still reuse the basis per dtype and device.
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index eb228d4b8..6805df3ae 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -31,7 +31,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 is_compiling, is_exporting
from kornia.geometry.transform.affwarp import rescale
from kornia.image.utils import perform_keep_shape_image
@@ -653,19 +653,33 @@ def jpeg_codec_differentiable(
def _get_dct8_basis_scale(
dtype: Union[torch.dtype, None], device: Union[str, torch.device, None]
) -> tuple[torch.Tensor, torch.Tensor]:
+ # ``torch.compile``, ``torch.export`` and the dynamo ONNX exporter trace the forward: build the basis inside the
+ # graph and leave the cache alone, so that no traced tensor leaks into later eager calls and the captured graph
+ # does not depend on earlier calls.
+ if is_compiling():
+ return _build_dct8_basis_scale(dtype, device)
key = (dtype, device)
if key not in _DCT8_CACHE:
- i = torch.arange(8, dtype=dtype, device=device)
- freq = (2.0 * i + 1.0)[:, None] * i[None, :] * (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)
- alpha[0] = 1.0 / (2**0.5)
- dct_scale = torch.outer(alpha, alpha) * 0.25
- _DCT8_CACHE[key] = (dct_tensor, dct_scale)
+ # Build outside inference mode: an inference tensor in the cache would make later calls in which autograd
+ # tracks the input fail, since autograd cannot save it for backward.
+ with torch.inference_mode(False):
+ _DCT8_CACHE[key] = _build_dct8_basis_scale(dtype, device)
return _DCT8_CACHE[key]
+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)
+ basis_1d = torch.cos(freq)
+ dct_tensor = basis_1d[:, None, :, None] * basis_1d[None, :, None, :]
+ alpha = torch.ones(8, dtype=dtype, device=device)
+ alpha[0] = 1.0 / (2**0.5)
+ dct_scale = torch.outer(alpha, alpha) * 0.25
+ return dct_tensor, dct_scale
+
+
class JPEGCodecDifferentiable(nn.Module):
r"""Differentiable JPEG encoding-decoding module.
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index 80609dfd3..335b78950 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -1157,3 +1157,55 @@ class TestDiffJPEG(BaseTester):
# We use a slightly higher tolerance since our implementation varies from the reference implementation
self.assert_close(img.grad.mean().view(-1), img_jpeg_mean_grad_ref, rtol=0.01, atol=0.01)
self.assert_close(jpeg_quality.grad, jpeg_quality_grad_ref, rtol=0.01, atol=0.01)
+
+ def test_basis_cache_after_inference_mode(self, device, dtype, monkeypatch) -> None:
+ """A first call under ``torch.inference_mode()`` must not break later calls that track gradients.
+
+ The DCT basis is memoized per dtype and device. Caching the inference tensors built by that first call made
+ later calls in which autograd tracks the image fail in the forward with "Inference tensors cannot be saved
+ for backward".
+ """
+ monkeypatch.setattr("kornia.enhance.jpeg._DCT8_CACHE", {})
+ torch.manual_seed(0)
+ img = torch.rand(2, 3, 16, 16).to(device=device, dtype=dtype)
+ jpeg_quality = torch.tensor([30.0, 90.0], device=device, dtype=dtype)
+ with torch.inference_mode():
+ expected = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality)
+ img = img.clone().requires_grad_(True)
+ img_jpeg = kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality)
+ img_jpeg.sum().backward()
+ self.assert_close(img_jpeg.detach(), expected)
+ assert img.grad is not None
+ assert torch.isfinite(img.grad).all()
+
+ def test_basis_cache_after_compile_in_inference_mode(self, device, dtype, torch_optimizer, monkeypatch) -> None:
+ """A compiled first call under ``torch.inference_mode()`` must not break later calls that track gradients."""
+ monkeypatch.setattr("kornia.enhance.jpeg._DCT8_CACHE", {})
+ torch.manual_seed(0)
+ img = torch.rand(2, 3, 16, 16).to(device=device, dtype=dtype)
+ jpeg_quality = torch.tensor([30.0, 90.0], device=device, dtype=dtype)
+ op_optimized = torch_optimizer(kornia.enhance.jpeg_codec_differentiable)
+ with torch.inference_mode():
+ op_optimized(img, jpeg_quality)
+ img = img.clone().requires_grad_(True)
+ kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality).sum().backward()
+ assert img.grad is not None
+ assert torch.isfinite(img.grad).all()
+
+ @pytest.mark.device_agnostic
+ def test_basis_cache_after_export(self, monkeypatch) -> None:
+ """Tracing with ``torch.export`` must not leave fake tensors in the DCT basis cache.
+
+ The trace runs the forward on fake tensors. Caching the basis built there made later eager calls in the same
+ process return fake tensors without data: ``.item()`` gave a symbol and ``.numpy()`` raised.
+ """
+ monkeypatch.setattr("kornia.enhance.jpeg._DCT8_CACHE", {})
+ torch.manual_seed(0)
+ img = torch.rand(1, 3, 16, 16)
+ jpeg_quality = torch.tensor([50.0])
+ module = kornia.enhance.JPEGCodecDifferentiable()
+ torch.export.export(module, (img, jpeg_quality), strict=False)
+ img_jpeg = module(img, jpeg_quality)
+ assert type(img_jpeg) is torch.Tensor
+ kornia.enhance.jpeg._DCT8_CACHE.clear()
+ self.assert_close(img_jpeg, module(img, jpeg_quality))