Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): run the differentiable JPEG codec outside a caller's autocast (#6109)

Dmytro Mishkin557e57909816
diff --git a/changelog.d/6100.fixed.md b/changelog.d/6100.fixed.md
index 0e5bb99a3..9f36e4249 100644
--- a/changelog.d/6100.fixed.md
+++ b/changelog.d/6100.fixed.md
@@ -4,6 +4,5 @@ pixels scaled to [0, 255], DCT coefficients of about 1000 and a quality scale of
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`.
+its `float32` tables to the image dtype before passing them to the codec. Inside `torch.autocast` the output now keeps
+the input dtype too: a `float32` image under CPU `bfloat16` autocast used to come back as `bfloat16`.
diff --git a/changelog.d/6109.fixed.md b/changelog.d/6109.fixed.md
new file mode 100644
index 000000000..3fd8f634e
--- /dev/null
+++ b/changelog.d/6109.fixed.md
@@ -0,0 +1,9 @@
+`jpeg_codec_differentiable` and `JPEGCodecDifferentiable`, and so `RandomJPEG`, run with autocast disabled, so a
+caller's `torch.autocast` region no longer changes their output, or their gradients when the backward pass runs after
+the region (on CUDA, up to the run-to-run spread of its atomic accumulation unless deterministic algorithms are
+enabled). Autocast ran the codec's matrix products and convolutions in its lower dtype, which rounds pixels scaled to
+[0, 255], DCT coefficients and the quality scale too coarsely: on random 64x64 `float32` images at qualities 99, 90, 50
+and 10, outputs were up to 0.109 (CPU `bfloat16` autocast), 0.014 (MPS `float16`) and 0.088 (MPS `bfloat16`) away from
+the `float64` codec on an Apple M1, and up to 0.03 (`float16`) and 0.12 (`bfloat16`) under CUDA autocast. They now
+equal the call outside autocast, 8.4e-7 from the `float64` codec on the CPU and MPS and 6.9e-7 on CUDA. A backward pass
+inside the region, which `torch.compile` assumes by default, still computes part of the gradient in the autocast dtype.
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index f8fb99235..4bfb47034 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -27,7 +27,7 @@ from torch import nn
from kornia.color import rgb_to_ycbcr, ycbcr_to_rgb
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_compiling, is_exporting
+from kornia.core.utils import _autocast_disabled, _to_device_nonblocking, is_compiling, is_exporting
from kornia.enhance.adjust import _check_floating_image
from kornia.geometry.transform.affwarp import rescale
from kornia.image.utils import perform_keep_shape_image
@@ -531,8 +531,11 @@ def jpeg_codec_differentiable(
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.
+ output is rounded once to the input dtype. The codec runs with autocast disabled, so inside a
+ ``torch.autocast`` region it gives the same output as outside it, and the same gradients when the
+ backward pass runs after the region (on CUDA, up to the run-to-run spread of its atomic accumulation
+ unless deterministic algorithms are enabled). A backward pass inside the region, which
+ ``torch.compile`` assumes by default, still computes part of the gradient in the autocast dtype.
Based on :cite:`reich2024` :cite:`shin2017`, we perform differentiable JPEG encoding-decoding as follows:
@@ -672,25 +675,29 @@ def jpeg_codec_differentiable(
# Quantization tables to same device and dtype as input image
quantization_table_y = _to_device_nonblocking(quantization_table_y, device, dtype)
quantization_table_c = _to_device_nonblocking(quantization_table_c, device, dtype)
- # Perform encoding
- y_encoded, cb_encoded, cr_encoded = _jpeg_encode(
- image_rgb=input,
- jpeg_quality=jpeg_quality,
- quantization_table_c=quantization_table_c,
- quantization_table_y=quantization_table_y,
- )
- image_rgb_jpeg: torch.Tensor = _jpeg_decode(
- input_y=y_encoded,
- input_cb=cb_encoded,
- input_cr=cr_encoded,
- jpeg_quality=jpeg_quality,
- H=H,
- W=W,
- quantization_table_c=quantization_table_c,
- quantization_table_y=quantization_table_y,
- )
- # Clip coded image
- image_rgb_jpeg = _differentiable_clipping(input=image_rgb_jpeg, min_val=0.0, max_val=255.0)
+ # A caller's autocast would run the codec's matrix products and convolutions in its lower dtype, which rounds the
+ # [0, 255] pixels, DCT coefficients and quality scale as coarsely as computing them in half precision would:
+ # compute it in dtype.
+ with _autocast_disabled(input.device.type):
+ # Perform encoding
+ y_encoded, cb_encoded, cr_encoded = _jpeg_encode(
+ image_rgb=input,
+ jpeg_quality=jpeg_quality,
+ quantization_table_c=quantization_table_c,
+ quantization_table_y=quantization_table_y,
+ )
+ image_rgb_jpeg: torch.Tensor = _jpeg_decode(
+ input_y=y_encoded,
+ input_cb=cb_encoded,
+ input_cr=cr_encoded,
+ jpeg_quality=jpeg_quality,
+ H=H,
+ W=W,
+ quantization_table_c=quantization_table_c,
+ quantization_table_y=quantization_table_y,
+ )
+ # 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].to(out_dtype)
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index 43a0ceb1c..ab7f1030c 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -1191,6 +1191,34 @@ class TestDiffJPEG(BaseTester):
assert img_jpeg.dtype == dtype
assert torch.equal(img_jpeg, wide.to(dtype))
+ def test_a_mixed_precision_region_does_not_reach_the_codec(self, device) -> None:
+ # A caller's autocast ran the codec's matrix products and convolutions in its lower dtype: a float32 image under
+ # CPU bfloat16 autocast came out about 0.1 away from the same call outside autocast. MPS autocasts to float16;
+ # the test has no "autocast" in its name, which conftest would skip on MPS.
+ if device.type not in ("cpu", "cuda", "mps"):
+ pytest.skip("CPU, CUDA and MPS autocast")
+ # MPS autocasts to float16, and so does a CUDA device without bfloat16, where bfloat16 autocast raises.
+ bfloat16_ok = device.type == "cpu" or (device.type == "cuda" and torch.cuda.is_bf16_supported())
+ autocast_dtype = torch.bfloat16 if bfloat16_ok else torch.float16
+ img = torch.rand(4, 3, 32, 32, device=device, requires_grad=True)
+ jpeg_quality = torch.tensor([99.0, 90.0, 50.0, 10.0], device=device, requires_grad=True)
+ qt_y = 1.0 + 254.0 * torch.rand(8, 8, device=device)
+ qt_c = 1.0 + 254.0 * torch.rand(8, 8, device=device)
+ for codec in (kornia.enhance.jpeg_codec_differentiable, kornia.enhance.JPEGCodecDifferentiable(qt_y, qt_c)):
+ expected = codec(img, jpeg_quality)
+ expected_grads = torch.autograd.grad(expected.sum(), (img, jpeg_quality))
+ with torch.autocast(device.type, dtype=autocast_dtype):
+ actual = codec(img, jpeg_quality)
+ actual_grads = torch.autograd.grad(actual.sum(), (img, jpeg_quality))
+ assert actual.dtype == torch.float32
+ assert torch.equal(actual, expected)
+ for grad, expected_grad in zip(actual_grads, expected_grads):
+ if device.type == "cuda":
+ # CUDA's interpolation backward accumulates with atomics, so two backward passes may round apart.
+ self.assert_close(grad, expected_grad)
+ else:
+ assert torch.equal(grad, expected_grad)
+
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")