Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

perf: vectorize xyz conversions (5.6x speedup) with safety checks (#3482)

Aditya Kumar Sethiaf6339e01e0ce
diff --git a/benchmarks/color/xyz_test.py b/benchmarks/color/xyz_test.py
new file mode 100644
index 000000000..5a9188c54
--- /dev/null
+++ b/benchmarks/color/xyz_test.py
@@ -0,0 +1,49 @@
+# 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 pytest
+import torch
+
+from kornia.color import rgb_to_xyz, xyz_to_rgb
+
+
[email protected]("B", [1, 8, 32])
[email protected]("H", [128, 256, 512])
[email protected]("W", [128, 256, 512])
+def test_rgb_to_xyz_benchmark(benchmark, device, dtype, torch_optimizer, B, C, H, W):
+ """Benchmark the rgb_to_xyz function."""
+
+ data = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ op = torch_optimizer(rgb_to_xyz)
+ actual = benchmark(op, data)
+
+ assert actual.shape == (B, 3, H, W)
+
+
[email protected]("B", [1, 8, 32])
[email protected]("H", [128, 256, 512])
[email protected]("W", [128, 256, 512])
+def test_xyz_to_rgb_benchmark(benchmark, device, dtype, torch_optimizer, B, C, H, W):
+ """Benchmark the xyz_to_rgb function."""
+
+ data = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ op = torch_optimizer(xyz_to_rgb)
+ actual = benchmark(op, image=data)
+
+ assert actual.shape == (B, 3, H, W)
diff --git a/kornia/color/xyz.py b/kornia/color/xyz.py
index d15e74a31..df0e4fd85 100644
--- a/kornia/color/xyz.py
+++ b/kornia/color/xyz.py
@@ -20,8 +20,11 @@ from __future__ import annotations
from typing import ClassVar
import torch
+import torch.nn.functional as F
from torch import nn
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+
def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:
r"""Convert a RGB image to XYZ.
@@ -39,23 +42,22 @@ def rgb_to_xyz(image: torch.Tensor) -> torch.Tensor:
>>> output = rgb_to_xyz(input) # 2x3x4x5
"""
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
-
- if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
-
- r: torch.Tensor = image[..., 0, :, :]
- g: torch.Tensor = image[..., 1, :, :]
- b: torch.Tensor = image[..., 2, :, :]
+ KORNIA_CHECK_IS_TENSOR(image)
+ KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])
- x: torch.Tensor = 0.412453 * r + 0.357580 * g + 0.180423 * b
- y: torch.Tensor = 0.212671 * r + 0.715160 * g + 0.072169 * b
- z: torch.Tensor = 0.019334 * r + 0.119193 * g + 0.950227 * b
+ # CIE RGB to XYZ Matrix (D65 White Point)
+ kernel = torch.tensor(
+ [
+ [0.412453, 0.357580, 0.180423],
+ [0.212671, 0.715160, 0.072169],
+ [0.019334, 0.119193, 0.950227],
+ ],
+ device=image.device,
+ dtype=torch.float32,
+ )
- out: torch.Tensor = torch.stack([x, y, z], -3)
-
- return out
+ # Apply Optimized Linear Transformation
+ return _apply_linear_transformation(image, kernel)
def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:
@@ -72,21 +74,67 @@ def xyz_to_rgb(image: torch.Tensor) -> torch.Tensor:
>>> output = xyz_to_rgb(input) # 2x3x4x5
"""
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")
+ KORNIA_CHECK_IS_TENSOR(image)
+ KORNIA_CHECK_SHAPE(image, ["*", "3", "H", "W"])
- if len(image.shape) < 3 or image.shape[-3] != 3:
- raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")
+ # CIE XYZ to RGB Matrix (D65 White Point)
+ kernel = torch.tensor(
+ [
+ [3.2404813432005266, -1.5371515162713185, -0.4985363261688878],
+ [-0.9692549499965682, 1.8759900014898907, 0.0415559265582928],
+ [0.0556466391351772, -0.2040413383665112, 1.0573110696453443],
+ ],
+ device=image.device,
+ dtype=torch.float32,
+ )
- x: torch.Tensor = image[..., 0, :, :]
- y: torch.Tensor = image[..., 1, :, :]
- z: torch.Tensor = image[..., 2, :, :]
+ # Apply Optimized Linear Transformation
+ return _apply_linear_transformation(image, kernel)
- r: torch.Tensor = 3.2404813432005266 * x + -1.5371515162713185 * y + -0.4985363261688878 * z
- g: torch.Tensor = -0.9692549499965682 * x + 1.8759900014898907 * y + 0.0415559265582928 * z
- b: torch.Tensor = 0.0556466391351772 * x + -0.2040413383665112 * y + 1.0573110696453443 * z
- out: torch.Tensor = torch.stack([r, g, b], dim=-3)
+def _apply_linear_transformation(image: torch.Tensor, kernel: torch.Tensor) -> torch.Tensor:
+ """Apply a 3x3 linear color transformation with device-aware optimization.
+
+ Args:
+ image: Input image tensor with shape :math:`(*, 3, H, W)`.
+ kernel: Transformation matrix with shape :math:`(3, 3)` applied along the channel
+ dimension.
+
+ Returns:
+ Tensor with the same shape as ``image`` containing the transformed values.
+ """
+ # Handle Integer inputs by casting to float safely
+ # If it's already floating point (e.g. float64 from gradcheck), we preserve it
+ if image.is_floating_point():
+ image_compute = image
+ else:
+ image_compute = image.float()
+
+ # Match kernel dtype to the image (propagates float64 if needed)
+ kernel_compute = kernel.to(dtype=image_compute.dtype, device=image_compute.device)
+
+ input_shape = image_compute.shape
+
+ # Empirical benchmarks show that einsum is faster on CPU for this specific pattern,
+ # while conv2d offers significant speedups on GPU/CUDA.
+ # We branch to ensure optimal performance on both devices.
+ # BRANCH 1: CPU (Einsum)
+ if image_compute.device.type == "cpu":
+ out = torch.einsum("...chw,oc->...ohw", image_compute, kernel_compute)
+ out = out.contiguous()
+
+ # BRANCH 2: GPU/Accelerators (Conv2d)
+ else:
+ # Reshape for conv2d: (B*..., C, H, W)
+ input_flat = image_compute.reshape(-1, 3, input_shape[-2], input_shape[-1])
+
+ # Reshape kernel: (3, 3) -> (3, 3, 1, 1)
+ weight = kernel_compute.view(3, 3, 1, 1)
+
+ out_flat = F.conv2d(input_flat, weight)
+
+ # Unflatten back to original shape
+ out = out_flat.reshape(input_shape)
return out
diff --git a/tests/color/test_xyz.py b/tests/color/test_xyz.py
index 84134d642..ea4703588 100644
--- a/tests/color/test_xyz.py
+++ b/tests/color/test_xyz.py
@@ -36,14 +36,16 @@ class TestRgbToXyz(BaseTester):
assert kornia.color.rgb_to_xyz(img).shape == shape
def test_exception(self, device, dtype):
- with pytest.raises(TypeError):
+ from kornia.core.exceptions import ShapeError, TypeCheckError
+
+ with pytest.raises(TypeCheckError):
assert kornia.color.rgb_to_xyz([0.0])
- with pytest.raises(ValueError):
+ with pytest.raises(ShapeError):
img = torch.ones(1, 1, device=device, dtype=dtype)
assert kornia.color.rgb_to_xyz(img)
- with pytest.raises(ValueError):
+ with pytest.raises(ShapeError):
img = torch.ones(2, 1, 1, device=device, dtype=dtype)
assert kornia.color.rgb_to_xyz(img)
@@ -147,14 +149,16 @@ class TestXyzToRgb(BaseTester):
assert kornia.color.xyz_to_rgb(img).shape == shape
def test_exception(self, device, dtype):
- with pytest.raises(TypeError):
+ from kornia.core.check import ShapeError, TypeCheckError
+
+ with pytest.raises(TypeCheckError):
assert kornia.color.xyz_to_rgb([0.0])
- with pytest.raises(ValueError):
+ with pytest.raises(ShapeError):
img = torch.ones(1, 1, device=device, dtype=dtype)
assert kornia.color.xyz_to_rgb(img)
- with pytest.raises(ValueError):
+ with pytest.raises(ShapeError):
img = torch.ones(2, 1, 1, device=device, dtype=dtype)
assert kornia.color.xyz_to_rgb(img)