π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(color): branchless hue selection in rgb_to_hsv (8.7x on MPS, byte-identical) (#3915)
Dmytro Mishkinc670e2ab38b4
diff --git a/kornia/color/hsv.py b/kornia/color/hsv.pyindex 8e05e73fd..5e99663cb 100644--- a/kornia/color/hsv.py+++ b/kornia/color/hsv.py@@ -53,8 +53,8 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor: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}")- max_rgb, argmax_rgb = image.max(-3)- min_rgb, _argmin_rgb = image.min(-3)+ max_rgb = image.amax(-3)+ min_rgb = image.amin(-3)deltac = max_rgb - min_rgbv = max_rgb@@ -67,8 +67,12 @@ def rgb_to_hsv(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:h2 = (rc - bc) + 2.0 * deltach3 = (gc - rc) + 4.0 * deltac- h = torch.stack((h1, h2, h3), dim=-3) / deltac.unsqueeze(-3)- h = torch.gather(h, dim=-3, index=argmax_rgb.unsqueeze(-3)).squeeze(-3)+ # select the sextant of the first maximal channel, matching torch.max(dim) tie-breaking;+ # branchless selection avoids max/argmax-with-indices and gather, which are ~100x slower+ # than amax/pointwise ops on MPS and block fusion under torch.compile+ r, g, b = torch.unbind(image, dim=-3)+ h = torch.where((r >= g) & (r >= b), h1, torch.where(g >= b, h2, h3))+ h = h / deltach = (h / 6.0) % 1.0h = 2.0 * math.pi * h # we return 0/2pi outputdiff --git a/tests/color/test_hsv.py b/tests/color/test_hsv.pyindex 0444c4d40..d11027c7e 100644--- a/tests/color/test_hsv.py+++ b/tests/color/test_hsv.py@@ -109,6 +109,24 @@ class TestRgbToHsv(BaseTester):self.assert_close(kornia.color.rgb_to_hsv(data), expected)+ def test_channel_ties(self, device, dtype):+ # Pins the argmax tie-breaking convention (first maximal channel wins) so that+ # implementation changes cannot silently alter the hue of achromatic/boundary pixels.+ # Snippet used to generate expected hues (torch, first-occurrence argmax semantics):+ # gray r=g=b -> h=0; yellow r=g>b -> pi/3; cyan g=b>r -> pi; magenta r=b>g -> 5*pi/3+ data = torch.tensor(+ [+ [[0.5000, 0.5000, 0.3000, 0.6000]],+ [[0.5000, 0.5000, 0.7000, 0.2000]],+ [[0.5000, 0.1000, 0.7000, 0.6000]],+ ],+ device=device,+ dtype=dtype,+ )+ expected_h = torch.tensor([[0.0, math.pi / 3.0, math.pi, 5.0 * math.pi / 3.0]], device=device, dtype=dtype)+ hsv = kornia.color.rgb_to_hsv(data)+ self.assert_close(hsv[..., 0, :, :], expected_h)+def test_nan_rgb_to_hsv(self, device, dtype):if dtype == torch.float16:pytest.skip("not work for half-precision")@@ -136,6 +154,13 @@ class TestRgbToHsv(BaseTester):fcn = kornia.color.rgb_to_hsvself.assert_close(ops(img), fcn(img))+ def test_dynamo(self, device, dtype, torch_optimizer):+ B, C, H, W = 2, 3, 4, 4+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)+ op = kornia.color.rgb_to_hsv+ op_optimized = torch_optimizer(op)+ self.assert_close(op(img), op_optimized(img))+class TestHsvToRgb(BaseTester):def test_smoke(self, device, dtype):@@ -251,3 +276,10 @@ class TestHsvToRgb(BaseTester):ops = kornia.color.HsvToRgb().to(device, dtype)fcn = kornia.color.hsv_to_rgbself.assert_close(ops(img), fcn(img))++ def test_dynamo(self, device, dtype, torch_optimizer):+ B, C, H, W = 2, 3, 4, 4+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)+ op = kornia.color.hsv_to_rgb+ op_optimized = torch_optimizer(op)+ self.assert_close(op(img), op_optimized(img))