Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(enhance): support dynamic torch.export JPEG shapes (#6538)

Muhammad Talha868a5f10e2ed
diff --git a/changelog.d/6538.fixed.md b/changelog.d/6538.fixed.md
new file mode 100644
index 000000000..6b8771681
--- /dev/null
+++ b/changelog.d/6538.fixed.md
@@ -0,0 +1 @@
+`torch.export.export` of `JPEGCodecDifferentiable` with a dynamic height and width now succeeds, and the exported program is correct at every image size. It used to raise `ConstraintViolationError` for named dims, and with `Dim.AUTO` the exported program held only at the traced height and width.
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index c806b7411..550bcdfb5 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -199,6 +199,74 @@ def _unpatchify_8x8(input: torch.Tensor, H: int, W: int) -> torch.Tensor:
return output
+def _patchify_chroma(input_cb: torch.Tensor, input_cr: torch.Tensor) -> torch.Tensor:
+ """Patchify the Cb and Cr planes together into one tensor of 8 x 8 patches.
+
+ ``patches = _patchify_chroma(input_cb, input_cr)`` takes the Cb and Cr planes of the shape ``(B, H, W)``, with
+ ``H`` and ``W`` multiples of 8, and returns their non-overlapping 8 x 8 patches, the Cb ones followed by the Cr
+ ones, with the values and the order of ``_patchify_8x8`` on each plane. The planes are stacked along the height
+ and their rows of 8 pixels read with one ``torch.index_select``: no intermediate tensor has an axis of the patch
+ rows or columns of one plane, either of which can be 1, so ``torch.export`` keeps the image size dynamic.
+
+ Args:
+ input_cb: Cb plane of the shape ``(B, H, W)``.
+ input_cr: Cr plane of the shape ``(B, H, W)``.
+
+ Returns:
+ The Cb patches followed by the Cr patches, of the shape ``(B, 2N, 8, 8)`` with ``N = (H // 8) * (W // 8)``.
+
+ See Also:
+ - :func:`jpeg_codec_differentiable`: the public codec, whose encoder calls this helper.
+
+ """
+ B, H, W = input_cb.shape
+ n_cols = W // 8
+ n_patches = 2 * (H // 8) * n_cols
+ # Rows of 8 pixels of the stacked planes. Flattened first: splitting the width alone would compare the patch
+ # columns with 1.
+ rows = torch.cat((input_cb, input_cr), dim=1).flatten(1).view(B, n_patches * 8, 8)
+ # Row ``r`` of patch ``p`` is row ``(p // n_cols * 8 + r) * n_cols + p % n_cols``. ``p % n_cols`` is spelled
+ # ``p - p // n_cols * n_cols``: the ONNX exporter cannot translate ``torch.remainder`` by a symbolic size.
+ patch = torch.arange(n_patches, device=input_cb.device)
+ block_row = torch.div(patch, n_cols, rounding_mode="floor")
+ first_row = block_row * (8 * n_cols) + (patch - block_row * n_cols)
+ src = first_row[:, None] + torch.arange(8, device=input_cb.device) * n_cols
+ return rows.index_select(1, src.view(-1)).view(B, n_patches, 8, 8)
+
+
+def _unpatchify_chroma(input: torch.Tensor, H: int, W: int) -> tuple[torch.Tensor, torch.Tensor]:
+ """Unpatchify the joint Cb and Cr patches back into two planes.
+
+ ``cb, cr = _unpatchify_chroma(input, H, W)`` takes the Cb patches followed by the Cr patches, of the shape
+ ``(B, 2N, 8, 8)``, and returns the Cb and the Cr plane, each of the shape ``(B, H, W)``. It undoes
+ ``_patchify_chroma`` and gives the values of ``_unpatchify_8x8`` on each half, read as rows of 8 pixels with one
+ ``torch.index_select``.
+
+ Args:
+ input: Cb patches followed by Cr patches, of the shape ``(B, 2N, 8, 8)``.
+ H: height of each plane, a multiple of 8.
+ W: width of each plane, a multiple of 8.
+
+ Returns:
+ The Cb and the Cr plane, each of the shape ``(B, H, W)``.
+
+ See Also:
+ - :func:`jpeg_codec_differentiable`: the public codec, whose decoder calls this helper.
+
+ """
+ B = input.shape[0]
+ n_cols = W // 8
+ n_rows = 2 * H * n_cols
+ # Row ``k`` of 8 pixels of the stacked planes is row ``k // n_cols % 8`` of patch
+ # ``k // n_cols // 8 * n_cols + k % n_cols``.
+ k = torch.arange(n_rows, device=input.device)
+ plane_row = torch.div(k, n_cols, rounding_mode="floor")
+ block_row = torch.div(plane_row, 8, rounding_mode="floor")
+ src = (block_row * n_cols + (k - plane_row * n_cols)) * 8 + (plane_row - block_row * 8)
+ planes = input.reshape(B, n_rows, 8).index_select(1, src).flatten(1).view(B, 2, H, W)
+ return planes[:, 0], planes[:, 1]
+
+
def _dct_8x8(input: torch.Tensor) -> torch.Tensor:
"""Perform an 8 x 8 discrete cosine transform.
@@ -395,21 +463,12 @@ def _chroma_upsampling(input_c: torch.Tensor) -> torch.Tensor:
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 ``(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,
quantization_table_y: torch.Tensor,
quantization_table_c: torch.Tensor,
-) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+) -> tuple[torch.Tensor, torch.Tensor]:
"""Perform JPEG encoding.
Args:
@@ -420,8 +479,9 @@ def _jpeg_encode(
Returns:
y_encoded (torch.Tensor): Encoded Y component of the shape ``(B, N, 8, 8)``.
- cb_encoded (torch.Tensor): Encoded Cb component of the shape ``(B, N, 8, 8)``.
- cr_encoded (torch.Tensor): Encoded Cr component of the shape ``(B, N, 8, 8)``.
+ cb_cr_encoded (torch.Tensor): Encoded Cb component followed by the encoded Cr component, of the shape
+ ``(B, 2N_c, 8, 8)``. They stay together between encoding and decoding: a ``(B, N_c, 8, 8)`` half of them
+ can have a single patch, which ``torch.export`` cannot trace for a dynamic image size.
"""
# Convert RGB image to YCbCr.
@@ -431,33 +491,26 @@ def _jpeg_encode(
# Perform chroma subsampling
input_y, input_cb, input_cr = _chroma_subsampling(image_ycbcr)
# Patchify, DCT, and rounding
- input_y, input_cb, input_cr = (
- _patchify_8x8(input_y),
- _patchify_8x8(input_cb),
- _patchify_8x8(input_cr),
- )
+ input_y = _patchify_8x8(input_y)
+ input_cb_cr = _patchify_chroma(input_cb, input_cr)
dct_y = _dct_8x8(input_y)
- dct_cb_cr = _dct_8x8(torch.cat((input_cb, input_cr), dim=1))
+ dct_cb_cr = _dct_8x8(input_cb_cr)
y_encoded: torch.Tensor = _quantize(
dct_y,
jpeg_quality,
quantization_table_y,
)
- cb_encoded, cr_encoded = _split_cb_cr(
- _quantize(
- dct_cb_cr,
- jpeg_quality,
- quantization_table_c,
- ),
- input_cb.shape[1],
+ cb_cr_encoded: torch.Tensor = _quantize(
+ dct_cb_cr,
+ jpeg_quality,
+ quantization_table_c,
)
- return y_encoded, cb_encoded, cr_encoded
+ return y_encoded, cb_cr_encoded
def _jpeg_decode(
input_y: torch.Tensor,
- input_cb: torch.Tensor,
- input_cr: torch.Tensor,
+ input_cb_cr: torch.Tensor,
jpeg_quality: torch.Tensor,
H: int,
W: int,
@@ -468,8 +521,8 @@ def _jpeg_decode(
Args:
input_y (torch.Tensor): Compressed Y component of the shape ``(B, N, 8, 8)``.
- input_cb (torch.Tensor): Compressed Cb component of the shape ``(B, N, 8, 8)``.
- input_cr (torch.Tensor): Compressed Cr component of the shape ``(B, N, 8, 8)``.
+ input_cb_cr (torch.Tensor): Compressed Cb component followed by the compressed Cr component, of the shape
+ ``(B, 2N_c, 8, 8)``.
jpeg_quality (torch.Tensor): Compression strength of the shape ``(B)``.
H (int): Original image height.
W (int): Original image width.
@@ -487,17 +540,16 @@ def _jpeg_decode(
quantization_table_y,
)
input_cb_cr = _dequantize(
- torch.cat((input_cb, input_cr), dim=1),
+ input_cb_cr,
jpeg_quality,
quantization_table_c,
)
# Perform inverse DCT
idct_y: torch.Tensor = _idct_8x8(input_y)
- idct_cb, idct_cr = _split_cb_cr(_idct_8x8(input_cb_cr), input_cb.shape[1])
+ idct_cb_cr: torch.Tensor = _idct_8x8(input_cb_cr)
# Reverse patching
image_y: torch.Tensor = _unpatchify_8x8(idct_y, H, W)
- image_cb: torch.Tensor = _unpatchify_8x8(idct_cb, H // 2, W // 2)
- image_cr: torch.Tensor = _unpatchify_8x8(idct_cr, H // 2, W // 2)
+ image_cb, image_cr = _unpatchify_chroma(idct_cb_cr, H // 2, W // 2)
# Perform chroma upsampling
image_cb = _chroma_upsampling(image_cb)
image_cr = _chroma_upsampling(image_cr)
@@ -531,6 +583,30 @@ def _perform_padding(image: torch.Tensor) -> tuple[torch.Tensor, int, int]:
return image_padded, h_pad, w_pad
+def _crop_padding(image: torch.Tensor, H: int, W: int) -> torch.Tensor:
+ """Crop the bottom and right padding off an image padded to a multiple of 16.
+
+ ``cropped = _crop_padding(image, H, W)`` takes an image of the shape ``(*, C, H_new, W_new)`` that
+ ``_perform_padding`` padded from ``H`` x ``W``, and returns its top-left ``(*, C, H, W)`` part, as a copy.
+
+ Args:
+ image: Padded image of the shape ``(*, C, H_new, W_new)``.
+ H: height of the image before the padding.
+ W: width of the image before the padding.
+
+ Returns:
+ The top-left part of ``image``, of the shape ``(*, C, H, W)``.
+
+ See Also:
+ - :func:`jpeg_codec_differentiable`: the public codec, whose last step is this crop.
+
+ """
+ # ``image[..., :H, :W]`` would make ``torch.export`` guard that ``H`` is at most the padded height, which it cannot
+ # show for every ``H``. A negative pad crops without that guard, and gives the same values.
+ h_pad, w_pad = image.shape[-2] - H, image.shape[-1] - W
+ return F.pad(image, (0, -w_pad, 0, -h_pad))
+
+
@perform_keep_shape_image
def jpeg_codec_differentiable(
input: torch.Tensor,
@@ -698,7 +774,7 @@ def jpeg_codec_differentiable(
# compute it in dtype.
with _autocast_disabled(input.device.type):
# Perform encoding
- y_encoded, cb_encoded, cr_encoded = _jpeg_encode(
+ y_encoded, cb_cr_encoded = _jpeg_encode(
image_rgb=input,
jpeg_quality=jpeg_quality,
quantization_table_c=quantization_table_c,
@@ -706,8 +782,7 @@ def jpeg_codec_differentiable(
)
image_rgb_jpeg: torch.Tensor = _jpeg_decode(
input_y=y_encoded,
- input_cb=cb_encoded,
- input_cr=cr_encoded,
+ input_cb_cr=cb_cr_encoded,
jpeg_quality=jpeg_quality,
H=H,
W=W,
@@ -717,7 +792,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_in, :W_in].to(out_dtype)
+ return _crop_padding(image_rgb_jpeg, H_in, W_in).to(out_dtype)
def _get_dct8_basis_scale(
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index fbc6afc1b..af7456dfe 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -75,6 +75,67 @@ class TestDiffJPEG(BaseTester):
_DCT8_CACHE.clear()
_DCT8_CACHE.update(cache)
+ @pytest.mark.parametrize("grid", [(1, 1), (1, 3), (3, 1), (2, 5), (4, 6), (7, 2)])
+ @pytest.mark.parametrize("batch", [0, 1, 3])
+ def test_chroma_patches_match_per_plane_views(self, device, dtype, grid, batch) -> None:
+ """The joint chroma patches hold the values and the order of the per-plane views, and invert to the planes."""
+ from kornia.enhance.jpeg import _patchify_8x8, _patchify_chroma, _unpatchify_8x8, _unpatchify_chroma
+
+ generator = torch.Generator().manual_seed(0)
+ height, width = 8 * grid[0], 8 * grid[1]
+ cb = torch.randn(batch, height, width, generator=generator).to(device=device, dtype=dtype)
+ cr = torch.randn(batch, height, width, generator=generator).to(device=device, dtype=dtype)
+
+ # Both only move values, so they must agree to the last bit in every dtype.
+ patches = _patchify_chroma(cb, cr)
+ self.assert_close(patches, torch.cat((_patchify_8x8(cb), _patchify_8x8(cr)), dim=1), rtol=0.0, atol=0.0)
+
+ n = grid[0] * grid[1]
+ cb_back, cr_back = _unpatchify_chroma(patches, height, width)
+ self.assert_close(cb_back, _unpatchify_8x8(patches[:, :n], height, width), rtol=0.0, atol=0.0)
+ self.assert_close(cr_back, _unpatchify_8x8(patches[:, n:], height, width), rtol=0.0, atol=0.0)
+ self.assert_close(cb_back, cb, rtol=0.0, atol=0.0)
+ self.assert_close(cr_back, cr, rtol=0.0, atol=0.0)
+
+ @pytest.mark.parametrize(
+ "shape", [(1, 3, 16, 16), (2, 3, 32, 48), (1, 3, 41, 70), (2, 3, 17, 33), (1, 3, 1, 1), (0, 3, 24, 24)]
+ )
+ def test_values_and_gradients_match_per_plane_views(self, device, dtype, shape, monkeypatch) -> None:
+ """The codec gives, to the last bit, the values and gradients of per-plane views and a slicing crop."""
+ from kornia.enhance import jpeg
+
+ def patchify_views(cb: torch.Tensor, cr: torch.Tensor) -> torch.Tensor:
+ return torch.cat((jpeg._patchify_8x8(cb), jpeg._patchify_8x8(cr)), dim=1)
+
+ def unpatchify_views(patches: torch.Tensor, H: int, W: int) -> tuple[torch.Tensor, torch.Tensor]:
+ n = patches.shape[1] // 2
+ return jpeg._unpatchify_8x8(patches[:, :n], H, W), jpeg._unpatchify_8x8(patches[:, n:], H, W)
+
+ generator = torch.Generator().manual_seed(0)
+ image = torch.rand(*shape, generator=generator).to(device=device, dtype=dtype)
+ quality = (torch.rand(max(shape[0], 1), generator=generator) * 90.0 + 5.0).to(device=device, dtype=dtype)
+ weights = torch.rand(*shape, generator=generator).to(device=device, dtype=dtype)
+ codec = kornia.enhance.JPEGCodecDifferentiable()
+
+ def run() -> tuple[torch.Tensor, torch.Tensor]:
+ x = image.clone().requires_grad_(True)
+ out = codec(x, quality)
+ (out * weights).sum().backward()
+ return out.detach(), x.grad
+
+ actual, actual_grad = run()
+ monkeypatch.setattr(jpeg, "_patchify_chroma", patchify_views)
+ monkeypatch.setattr(jpeg, "_unpatchify_chroma", unpatchify_views)
+ monkeypatch.setattr(jpeg, "_crop_padding", lambda image, H, W: image[..., :H, :W])
+ expected, expected_grad = run()
+
+ assert actual.shape == expected.shape
+ self.assert_close(actual, expected, rtol=0.0, atol=0.0)
+ # The CUDA backward of the bilinear chroma upsampling adds atomically, in no fixed order: compare the gradients
+ # to the last bit on CPU only.
+ exact = {"rtol": 0.0, "atol": 0.0} if device.type == "cpu" else {}
+ self.assert_close(actual_grad, expected_grad, **exact)
+
def test_smoke(self, device, dtype) -> None:
"""This test standard usage."""
B, H, W = 2, 32, 32
diff --git a/tests/enhance/test_jpeg_onnx.py b/tests/enhance/test_jpeg_onnx.py
index d819a6552..260fd7584 100644
--- a/tests/enhance/test_jpeg_onnx.py
+++ b/tests/enhance/test_jpeg_onnx.py
@@ -138,3 +138,57 @@ def test_chroma_resampling_matches_rescale(size):
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)
+
+
+# Sizes the exported programs and routes below are checked at: the padded block grid is a single block (16 x 16, 1 x 1,
+# 5 x 9), a row or a column of blocks, and several; the padding is zero, partial and one short of a block; and an empty
+# batch.
+_EXPORT_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),
+ (2, 3, 16, 40),
+ (1, 3, 33, 16),
+ (1, 3, 5, 9),
+ (1, 3, 1, 1),
+ (1, 3, 100, 131),
+ (0, 3, 24, 40),
+]
+
+
+ torch_version_lt(2, 14, 0), reason="torch.export keeps the codec's height and width dynamic on 2.14"
+)
[email protected]("dim_min", [None, 1], ids=["default_range", "min_1"])
+def test_jpeg_codec_torch_export_matches_eager_at_other_shapes(dim_min):
+ """``torch.export`` with a dynamic height and width gives a program that holds at every size, not at the traced one.
+
+ The program used to raise ``ConstraintViolationError`` for named dims (#6294), and with ``Dim.AUTO`` it asserted
+ outside the traced padding class and at a size of 16 pixels.
+ """
+ from torch.export import Dim, export
+
+ model = JPEGCodecDifferentiable().eval()
+ example = (torch.rand(2, 3, 32, 48), torch.tensor([50.0, 80.0]))
+ options = {} if dim_min is None else {"min": dim_min}
+ batch, height, width = Dim("batch", **options), Dim("height", **options), Dim("width", **options)
+ program = export(
+ model, example, dynamic_shapes={"image_rgb": {0: batch, 2: height, 3: width}, "jpeg_quality": {0: batch}}
+ )
+ exported = program.module()
+
+ generator = torch.Generator().manual_seed(0)
+ for shape in _EXPORT_SHAPES:
+ image = torch.rand(*shape, generator=generator)
+ quality = torch.rand(shape[0], generator=generator) * 90.0 + 5.0
+ with torch.no_grad():
+ actual = exported(image, quality)
+ expected = model(image, quality)
+ assert actual.shape == expected.shape, f"traced at (32, 48), run at {shape}"
+ # The program runs the eager operations on the same values.
+ assert_close(actual, expected, rtol=0.0, atol=0.0)