Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): keep JPEGCodecDifferentiable ONNX graphs dynamic in height and width (#6300)

Muhammad Talha30b54361ea9a
diff --git a/changelog.d/6300.fixed.md b/changelog.d/6300.fixed.md
new file mode 100644
index 000000000..4e38352fe
--- /dev/null
+++ b/changelog.d/6300.fixed.md
@@ -0,0 +1 @@
+`JPEGCodecDifferentiable` exported to ONNX with a dynamic height and width now follows the input size. The TorchScript exporter (`dynamo=False`) used to give a graph that, at any size but the traced one, returned an image of the traced size or wrong values, without an error. The dynamo exporter's graph used to fail in onnxruntime at any other padded size; on torch 2.14 it now follows the input size as well.
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index b225cb903..5842cc9a0 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -29,7 +29,7 @@ from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK
from kornia.core.ops import _device_literal
from kornia.core.utils import _autocast_disabled, _to_device_nonblocking, is_compiling
from kornia.enhance.adjust import _check_floating_image
-from kornia.geometry.transform.affwarp import rescale
+from kornia.filters import gaussian_blur2d
from kornia.image.utils import perform_keep_shape_image
_DCT8_CACHE: dict[
@@ -354,20 +354,22 @@ def _chroma_subsampling(input_ycbcr: torch.Tensor) -> tuple[torch.Tensor, torch.
output_y: torch.Tensor = input_ycbcr[:, 0]
output_cb: torch.Tensor = input_ycbcr[:, 1]
output_cr: torch.Tensor = input_ycbcr[:, 2]
- # Perform average pooling of Cb and Cr channels
- output_cb = rescale(
- output_cb[:, None],
- factor=0.5,
- interpolation="bilinear",
+ # Halve Cb and Cr. The codec pads the image to a multiple of 16, so the factor is exactly 2: ``rescale`` with
+ # ``antialias=True`` smooths with a 3 x 3 Gaussian of sigma 0.5 and then interpolates to ``(H // 2, W // 2)``.
+ # Both steps are spelled out here because ``rescale`` takes the output size from float arithmetic and the
+ # antialias kernel from the size ratio, which freezes the traced size of an exported graph (ONNX, torch.export).
+ h_half, w_half = input_ycbcr.shape[-2] // 2, input_ycbcr.shape[-1] // 2
+ output_cb = F.interpolate(
+ gaussian_blur2d(output_cb[:, None], (3, 3), (0.5, 0.5)),
+ size=(h_half, w_half),
+ mode="bilinear",
align_corners=False,
- antialias=True,
)
- output_cr = rescale(
- output_cr[:, None],
- factor=0.5,
- interpolation="bilinear",
+ output_cr = F.interpolate(
+ gaussian_blur2d(output_cr[:, None], (3, 3), (0.5, 0.5)),
+ size=(h_half, w_half),
+ mode="bilinear",
align_corners=False,
- antialias=True,
)
return output_y, output_cb[:, 0], output_cr[:, 0]
@@ -382,17 +384,26 @@ def _chroma_upsampling(input_c: torch.Tensor) -> torch.Tensor:
output_c (torch.Tensor): Upsampled C(b or r) component of the shape :math:`(B, H * 2, W * 2)`.
"""
- # Upsample component
- output_c: torch.Tensor = rescale(
+ # Upsample component. The size is explicit: ``rescale`` computes it with float arithmetic, which freezes the
+ # traced size of an exported graph.
+ output_c: torch.Tensor = F.interpolate(
input_c[:, None],
- factor=2.0,
- interpolation="bilinear",
+ size=(input_c.shape[-2] * 2, input_c.shape[-1] * 2),
+ mode="bilinear",
align_corners=False,
- antialias=False,
)
return output_c[:, 0]
+def _split_cb_cr(input_cb_cr: torch.Tensor, n_patches: int) -> tuple[torch.Tensor, torch.Tensor]:
+ """Split the concatenated Cb and Cr patches of the shape :math:`(B, 2N, 8, 8)` into two :math:`(B, N, 8, 8)`.
+
+ This is ``chunk(2, dim=1)`` with the half size passed in: ``chunk`` exports as a ``SplitToSequence`` with a
+ symbolic size, which the ONNX optimizer cannot fold when the image size is dynamic.
+ """
+ return input_cb_cr[:, :n_patches], input_cb_cr[:, n_patches:]
+
+
def _jpeg_encode(
image_rgb: torch.Tensor,
jpeg_quality: torch.Tensor,
@@ -432,11 +443,14 @@ def _jpeg_encode(
jpeg_quality,
quantization_table_y,
)
- cb_encoded, cr_encoded = _quantize(
- dct_cb_cr,
- jpeg_quality,
- quantization_table_c,
- ).chunk(2, dim=1)
+ cb_encoded, cr_encoded = _split_cb_cr(
+ _quantize(
+ dct_cb_cr,
+ jpeg_quality,
+ quantization_table_c,
+ ),
+ input_cb.shape[1],
+ )
return y_encoded, cb_encoded, cr_encoded
@@ -479,7 +493,7 @@ def _jpeg_decode(
)
# Perform inverse DCT
idct_y: torch.Tensor = _idct_8x8(input_y)
- idct_cb, idct_cr = _idct_8x8(input_cb_cr).chunk(2, dim=1)
+ idct_cb, idct_cr = _split_cb_cr(_idct_8x8(input_cb_cr), input_cb.shape[1])
# Reverse patching
image_y: torch.Tensor = _unpatchify_8x8(idct_y, H, W)
image_cb: torch.Tensor = _unpatchify_8x8(idct_cb, H // 2, W // 2)
@@ -508,9 +522,10 @@ def _perform_padding(image: torch.Tensor) -> tuple[torch.Tensor, int, int]:
"""
# Get spatial dimensions of the image
H, W = image.shape[-2:]
- # Compute horizontal and vertical padding
- h_pad: int = math.ceil(H / 16) * 16 - H
- w_pad: int = math.ceil(W / 16) * 16 - W
+ # Compute horizontal and vertical padding. This is integer arithmetic on the shape, not ``math.ceil(H / 16)``:
+ # an exporter records it, where a float ``ceil`` would fix the pads to the traced size.
+ h_pad: int = (H + 15) // 16 * 16 - H
+ w_pad: int = (W + 15) // 16 * 16 - W
# Perform padding (we follow JPEG and F.pad only the bottom and right side of the image)
image_padded: torch.Tensor = F.pad(image, (0, w_pad, 0, h_pad), "replicate")
return image_padded, h_pad, w_pad
@@ -653,7 +668,8 @@ def jpeg_codec_differentiable(
),
)
# Pad the image to a shape dividable by 16
- input, h_pad, w_pad = _perform_padding(input)
+ H_in, W_in = input.shape[-2:]
+ input, _, _ = _perform_padding(input)
# Get height and shape
H, W = input.shape[-2:]
# Check matching batch dimensions
@@ -701,7 +717,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].to(out_dtype)
+ return image_rgb_jpeg[..., :H_in, :W_in].to(out_dtype)
def _get_dct8_basis_scale(
diff --git a/tests/enhance/test_jpeg_onnx.py b/tests/enhance/test_jpeg_onnx.py
new file mode 100644
index 000000000..d819a6552
--- /dev/null
+++ b/tests/enhance/test_jpeg_onnx.py
@@ -0,0 +1,140 @@
+# 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 io
+
+import pytest
+import torch
+
+from kornia.core._compat import torch_version_lt
+from kornia.enhance import JPEGCodecDifferentiable
+from kornia.enhance.jpeg import _chroma_subsampling, _chroma_upsampling, _perform_padding
+from kornia.geometry.transform import rescale
+
+from testing.base import DYNAMO_UNAVAILABLE_REASON, assert_close, dynamo_is_available
+
+# Every test in this module must stay device-free: the mark deselects the whole file on non-CPU devices.
+pytestmark = pytest.mark.device_agnostic
+
+
+def _export_codec(model: JPEGCodecDifferentiable, example: tuple[torch.Tensor, torch.Tensor], dynamo: bool) -> bytes:
+ """Export ``model`` to ONNX with a dynamic batch, height and width."""
+ buffer = io.BytesIO()
+ if dynamo:
+ from torch.export import Dim
+
+ batch, height, width = Dim("batch"), Dim("height"), Dim("width")
+ torch.onnx.export(
+ model,
+ example,
+ buffer,
+ dynamo=True,
+ dynamic_shapes={"image_rgb": {0: batch, 2: height, 3: width}, "jpeg_quality": {0: batch}},
+ )
+ else:
+ torch.onnx.export(
+ model,
+ example,
+ buffer,
+ dynamo=False,
+ opset_version=17,
+ input_names=["image", "quality"],
+ output_names=["out"],
+ dynamic_axes={
+ "image": {0: "B", 2: "H", 3: "W"},
+ "quality": {0: "B"},
+ "out": {0: "B", 2: "H", 3: "W"},
+ },
+ )
+ return buffer.getvalue()
+
+
+# One exporter per ID, on every torch version. conftest.py deselects IDs that contain "dynamo" unless
+# KORNIA_TEST_OPTIMIZER is set, hence ``torch_export``.
+ "dynamo",
+ [
+ pytest.param(False, id="torchscript"),
+ pytest.param(
+ True,
+ id="torch_export",
+ marks=[
+ pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON),
+ # Below torch 2.14 the exporter does not keep the codec's height and width dynamic. On 2.9.1 it
+ # applies torch.export's suggested fix, which restricts both to multiples of 16, so the padding of
+ # the traced 32 x 48 example is frozen at zero. On 2.5.1 torch.export rejects the batch constraint.
+ pytest.mark.skipif(torch_version_lt(2, 14, 0), reason="the dynamo ONNX exporter needs torch 2.14 here"),
+ ],
+ ),
+ ],
+)
+def test_jpeg_codec_onnx_matches_eager_at_other_shapes(dynamo):
+ """Traced once, the graph follows the batch, height and width, including sizes that are not multiples of 16."""
+ pytest.importorskip("onnx")
+ ort = pytest.importorskip("onnxruntime")
+ if dynamo:
+ pytest.importorskip("onnxscript")
+
+ model = JPEGCodecDifferentiable().eval()
+ example = (torch.rand(2, 3, 32, 48), torch.tensor([50.0, 80.0]))
+ session = ort.InferenceSession(_export_codec(model, example, dynamo), providers=["CPUExecutionProvider"])
+ input_names = [i.name for i in session.get_inputs()]
+
+ generator = torch.Generator().manual_seed(0)
+ # The traced size, other batches, other multiples of 16, odd sizes, and the smallest padded image.
+ shapes = [
+ (2, 3, 32, 48),
+ (1, 3, 32, 48),
+ (3, 3, 48, 64),
+ (2, 3, 64, 32),
+ (1, 3, 41, 70),
+ (2, 3, 17, 17),
+ (1, 3, 16, 16),
+ ]
+ for shape in shapes:
+ image = torch.rand(*shape, generator=generator)
+ quality = torch.rand(shape[0], generator=generator) * 90.0 + 5.0
+ (actual,) = session.run(None, {input_names[0]: image.numpy(), input_names[1]: quality.numpy()})
+ with torch.no_grad():
+ expected = model(image, quality)
+ assert actual.shape == tuple(expected.shape), f"traced at (32, 48), run at {shape}"
+ assert_close(torch.from_numpy(actual), expected, rtol=1e-4, atol=1e-3)
+
+
[email protected]("size", [(1, 1), (5, 7), (16, 16), (17, 33), (41, 70)])
+def test_perform_padding_makes_the_size_a_multiple_of_16(size):
+ image = torch.rand(1, 3, *size)
+ padded, h_pad, w_pad = _perform_padding(image)
+ assert padded.shape[-2:] == (size[0] + h_pad, size[1] + w_pad)
+ assert padded.shape[-2] % 16 == 0
+ assert padded.shape[-1] % 16 == 0
+ assert 0 <= h_pad < 16
+ assert 0 <= w_pad < 16
+ assert_close(padded[..., : size[0], : size[1]], image, rtol=0.0, atol=0.0)
+
+
[email protected]("size", [(16, 16), (32, 48), (64, 32)])
+def test_chroma_resampling_matches_rescale(size):
+ """The codec spells out its chroma resampling with explicit sizes; it must keep the values ``rescale`` gave."""
+ ycbcr = torch.rand(2, 3, *size, generator=torch.Generator().manual_seed(0)) * 255.0
+ _, cb, cr = _chroma_subsampling(ycbcr)
+ for actual, channel in ((cb, ycbcr[:, 1]), (cr, ycbcr[:, 2])):
+ expected = rescale(channel[:, None], factor=0.5, interpolation="bilinear", align_corners=False, antialias=True)
+ assert_close(actual, expected[:, 0], rtol=0.0, atol=0.0)
+ up = rescale(actual[:, None], factor=2.0, interpolation="bilinear", align_corners=False, antialias=False)
+ assert_close(_chroma_upsampling(actual), up[:, 0], rtol=0.0, atol=0.0)