π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(color): stop RgbToHls exporting an all-zero ONNX graph (#5790)
NIKHIL8729d753cd05
diff --git a/changelog.d/5790.fixed.md b/changelog.d/5790.fixed.mdnew file mode 100644index 000000000..e8da995a8--- /dev/null+++ b/changelog.d/5790.fixed.md@@ -0,0 +1,6 @@+`rgb_to_hls` and `RgbToHls` now export to ONNX with the TorchScript exporter and compile with+`torch.compile(fullgraph=True)`. For an input that does not require grad they used to write the H, L and S channels+with `out=` into views of one preallocated tensor. The TorchScript exporter (the `torch.onnx.export` default before+torch 2.9, and `dynamo=False` from it) did not record those writes, so the exported graph ignored its input and returned+zeros, and `torch.compile(fullgraph=True)` raised on the non-contiguous `out=` tensor. The channels are now computed as+separate tensors and stacked; eager results are bit-identical.diff --git a/kornia/color/hls.py b/kornia/color/hls.pyindex 7ad29f1f1..a79d37224 100644--- a/kornia/color/hls.py+++ b/kornia/color/hls.py@@ -64,25 +64,11 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:imax = _img_max[1]minc: torch.Tensor = image.min(-3)[0]- if image.requires_grad:- l_ = maxc + minc- s = maxc - minc- # weird behaviour with undefined vars in JIT...- # scripting requires image_hls be defined even if it is not used :S- h = l_ # assign to any torch.Tensor...- image_hls = l_ # assign to any torch.Tensor...- else:- # define the resulting image to avoid the torch.stack([h, l, s])- # so, h, l and s require inplace operations- # NOTE: torch.stack() increases in a 10% the cost in colab- image_hls = torch.empty_like(image)- h, l_, s = (- image_hls[..., 0, :, :],- image_hls[..., 1, :, :],- image_hls[..., 2, :, :],- )- torch.add(maxc, minc, out=l_) # l = max + min- torch.sub(maxc, minc, out=s) # s = max - min+ # Compute the channels as separate tensors and stack them. Writing them with `out=` into channel views of a+ # preallocated output is not traced by the TorchScript ONNX exporter, which then exports a graph that ignores+ # the input, and torch.compile(fullgraph=True) rejects an `out=` tensor that is not contiguous.+ l_ = maxc + minc+ s = maxc - minc# Use unit divisors when chroma or the lightness denominator is zero.# Preserve the epsilon-adjusted calculation for nonzero denominators.@@ -102,23 +88,14 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:# h[imax == 1] = (((b - r) / (max - min)) + 2)[imax == 1]# h[imax == 2] = (((r - g) / (max - min)) + 4)[imax == 2]cond = imax[..., None, :, :] == _RGB2HSL_IDX- if image.requires_grad:- h = ((g - b) % 6) * cond[..., 0, :, :]- else:- # replacing `torch.mul` with `out=h` with python * operator gives wrong results- torch.mul((g - b) % 6, cond[..., 0, :, :], out=h)+ h = ((g - b) % 6) * cond[..., 0, :, :]h += (b - r + 2) * cond[..., 1, :, :]h += (r - g + 4) * cond[..., 2, :, :]# h = 2.0 * math.pi * (60.0 * h) / 360.0h *= math.pi / 3.0 # hue [0, 2*pi]- if image.requires_grad:- h = h.masked_fill(h >= 2.0 * math.pi, 0.0)- else:- h.masked_fill_(h >= 2.0 * math.pi, 0.0)-- if image.requires_grad:- return torch.stack([h, l_, s], -3)- return image_hls+ h = h.masked_fill(h >= 2.0 * math.pi, 0.0)++ return torch.stack([h, l_, s], -3)def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:diff --git a/tests/color/test_hls.py b/tests/color/test_hls.pyindex 4c040daf6..548196160 100644--- a/tests/color/test_hls.py+++ b/tests/color/test_hls.py@@ -15,7 +15,9 @@# limitations under the License.#+import ioimport math+import warningsimport pytestimport torch@@ -224,6 +226,41 @@ class TestRgbToHls(BaseTester):fcn = kornia.color.rgb_to_hlsself.assert_close(ops(img), fcn(img))+ def test_dynamo_fullgraph(self, device, dtype, torch_optimizer):+ # Without grad the channels used to be written with `out=` into views of one output tensor, and Dynamo+ # rejects an `out=` tensor that is not contiguous.+ img = torch.rand(2, 3, 4, 5, device=device, dtype=dtype)+ compiled = torch_optimizer(kornia.color.rgb_to_hls, fullgraph=True)+ self.assert_close(compiled(img), kornia.color.rgb_to_hls(img))++ @pytest.mark.device_agnostic+ def test_onnx_export_legacy_matches_eager(self, dtype):+ # The TorchScript exporter (the torch.onnx.export default before torch 2.9) did not trace the `out=` writes+ # into views of the output, so the exported graph ignored its input and returned zeros.+ if dtype != torch.float32:+ pytest.skip("the exported graph is checked once, in float32")+ pytest.importorskip("onnx")+ ort = pytest.importorskip("onnxruntime")++ traced = torch.rand(1, 3, 4, 5, dtype=dtype)+ image = torch.rand(2, 3, 6, 7, dtype=dtype)+ buffer = io.BytesIO()+ with warnings.catch_warnings():+ warnings.simplefilter("ignore")+ torch.onnx.export(+ kornia.color.RgbToHls(),+ (traced,),+ buffer,+ input_names=["image"],+ output_names=["hls"],+ dynamic_axes={"image": {0: "B", 2: "H", 3: "W"}, "hls": {0: "B", 2: "H", 3: "W"}},+ opset_version=17,+ dynamo=False,+ )+ session = ort.InferenceSession(buffer.getvalue(), providers=["CPUExecutionProvider"])+ exported = torch.from_numpy(session.run(None, {"image": image.numpy()})[0])+ self.assert_close(exported, kornia.color.rgb_to_hls(image))+class TestHlsToRgb(BaseTester):def test_smoke(self, device, dtype):