π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(enhance): make posterize torch.compile fullgraph-safe (#3789)
Edgar Riba07c639d8ceaa
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.pyindex 77e915e48..a171bb79f 100644--- a/kornia/enhance/adjust.py+++ b/kornia/enhance/adjust.py@@ -794,13 +794,13 @@ def posterize(input: torch.Tensor, bits: Union[int, torch.Tensor]) -> torch.Tensreturn (input * 255).to(torch.uint8) / (2**shift).to(input.dtype) / 255.0def _posterize_one(input: torch.Tensor, bits: torch.Tensor) -> torch.Tensor:- # Single bits value condition- if bits == 0:- return torch.zeros_like(input)- if bits == 8:- return input.clone()- bits = 8 - bits- return _left_shift(_right_shift(input, bits), bits)+ # Branchless for torch.compile: the bits==0 / bits==8 special cases guard a uint8+ # overflow in the shift math, so compute the shift unconditionally and select with+ # torch.where (verified numerically identical to the branched version for bits 0..8).+ shift = 8 - bits+ shifted = _left_shift(_right_shift(input, shift), shift)+ out = torch.where(bits == 0, torch.zeros_like(input), shifted)+ return torch.where(bits == 8, input, out)if len(bits.shape) == 0 or (len(bits.shape) == 1 and len(bits) == 1):return _posterize_one(input, bits)diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.pyindex 2baf17a54..c10aa8d21 100644--- a/tests/enhance/test_adjust.py+++ b/tests/enhance/test_adjust.py@@ -1207,3 +1207,9 @@ class TestPosterize(BaseTester):expected = op(img, 8)actual = op_script(img, 8)self.assert_close(actual, expected)++ def test_dynamo(self, device, dtype, torch_optimizer):+ img = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)+ op = kornia.enhance.posterize+ op_optimized = torch_optimizer(op)+ self.assert_close(op(img, 3), op_optimized(img, 3))