π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): keep torch.distributions validation on after ColorJiggle's eager torch.cond (#4725)
Dmytro Mishkind0b8328e2960
diff --git a/changelog.d/4725.fixed.md b/changelog.d/4725.fixed.mdnew file mode 100644index 000000000..4b52aa8ca--- /dev/null+++ b/changelog.d/4725.fixed.md@@ -0,0 +1 @@+`ColorJiggle(order=...)` no longer turns off `torch.distributions` argument validation for the rest of the process. Its eager `torch.cond` dispatch entered Dynamo, whose one-time setup disables that validation globally; the caller's setting is now restored. A fixed `order` also no longer raises `torch.cond requires dynamo support` where Dynamo is unavailable (torch 2.5.1 on Python 3.13); it uses the Python dispatch there.diff --git a/kornia/augmentation/_2d/intensity/color_jiggle.py b/kornia/augmentation/_2d/intensity/color_jiggle.pyindex b29228f61..3e82fcd29 100644--- a/kornia/augmentation/_2d/intensity/color_jiggle.py+++ b/kornia/augmentation/_2d/intensity/color_jiggle.py@@ -19,6 +19,7 @@ from collections.abc import Sequencefrom typing import Any, Dict, List, Optional, Tuple, Unionimport torch+from torch.distributions import Distributionfrom kornia.augmentation import random_generator as rgfrom kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D@@ -123,7 +124,8 @@ class ColorJiggle(IntensityAugmentationBase2D):- a fixed ``order`` makes a three-channel transform ``torch.compile`` fullgraph-safe while preservinglazy neutral-factor skips: eager and compiled calls both dispatch each step through ``torch.cond``,and the result is contiguous even for a channels-last input. The default sampled tensor order, and- neutral one- and four-channel configurations, keep the Python dispatch path. Differentiating a+ neutral one- and four-channel configurations, keep the Python dispatch path, as does a fixed order+ where Dynamo is unavailable (torch ``2.5.1`` on Python ``3.13``). Differentiating acompiled fixed-order transform needs torch ``2.7`` or newer with the ``inductor`` backend: on``2.5.1`` and ``2.6.0`` the forward pass compiles but the backward pass raises, while the``aot_eager`` backend works on each.@@ -194,6 +196,9 @@ class ColorJiggle(IntensityAugmentationBase2D):f"`order` entries must be in 0..3 (brightness, contrast, saturation, hue). Got {order}")self._fixed_order: Optional[Tuple[int, ...]] = order+ # torch.cond raises where Dynamo is unavailable (torch 2.5.1 on Python 3.13), so a fixed order keeps+ # the Python dispatch there. Checked here because Dynamo cannot trace the check inside forward.+ self._cond_dispatch = order is not None and torch._dynamo.is_dynamo_supported()def apply_transform(self,@@ -206,17 +211,24 @@ class ColorJiggle(IntensityAugmentationBase2D):# branch is traced, including branches that are not selected at runtime, so the dispatcher is# restricted to RGB inputs: tracing the hue/saturation branches would otherwise reject the neutral# one- and four-channel configurations accepted by the Python dispatch below.- if self._fixed_order is not None and input.shape[-3] == 3:- jittered = input- for idx in self._fixed_order:- jittered = _apply_transform_cond(- idx,- jittered,- params["brightness_factor"],- params["contrast_factor"],- params["saturation_factor"],- params["hue_factor"],- )+ if self._cond_dispatch and input.shape[-3] == 3:+ # An eager torch.cond enters Dynamo, whose one-time setup calls+ # ``Distribution.set_default_validate_args(False)`` process-wide; restore the caller's setting.+ validate_args = Distribution._validate_args+ try:+ jittered = input+ for idx in self._fixed_order:+ jittered = _apply_transform_cond(+ idx,+ jittered,+ params["brightness_factor"],+ params["contrast_factor"],+ params["saturation_factor"],+ params["hue_factor"],+ )+ finally:+ if Distribution._validate_args != validate_args:+ Distribution.set_default_validate_args(validate_args)return jitteredtransforms = [diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 8f73a4740..51364493b 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -19,6 +19,7 @@ import copyimport ioimport osimport pickle+import subprocessimport sysfrom typing import Any, Dict, Optional, Tuple, Typefrom unittest.mock import patch@@ -1347,6 +1348,40 @@ class TestColorJiggle(BaseTester):with pytest.raises(ValueError, match=r"entries must be in 0\.\.3"):ColorJiggle(order=(0, 1, 9))+ @pytest.mark.device_agnostic+ def test_fixed_order_keeps_distribution_validation(self):+ # The eager torch.cond dispatch enters Dynamo, whose one-time setup turns off+ # torch.distributions argument validation process-wide. A fresh interpreter is needed because that+ # setup runs once per process, so an earlier Dynamo entry in this one would hide the leak.+ script = (+ "import torch\n"+ "from torch.distributions import Distribution\n"+ "from kornia.augmentation import ColorJiggle\n"+ "Distribution.set_default_validate_args(True)\n"+ "ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(0, 1, 2, 3))(torch.rand(2, 3, 8, 8))\n"+ "assert Distribution._validate_args, 'ColorJiggle disabled Distribution validation'\n"+ )+ # Trusted, fixed command (the current interpreter running a literal script); no external input.+ result = subprocess.run( # noqa: S603+ [sys.executable, "-c", script],+ capture_output=True,+ text=True,+ check=False,+ timeout=300,+ )+ assert result.returncode == 0, result.stderr++ def test_fixed_order_falls_back_without_cond(self, device, dtype, monkeypatch):+ # torch.cond raises "requires dynamo support" where Dynamo is unavailable (torch 2.5.1 on Python+ # 3.13), so a fixed order must fall back to the Python dispatch there.+ image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype)+ op = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))+ params = op.forward_parameters(image.shape)+ expected = op(image, params=params)+ monkeypatch.setattr(torch._dynamo, "is_dynamo_supported", lambda: False)+ fallback = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))+ assert torch.equal(fallback(image, params=params), expected)+def test_dynamo_fixed_order(self, device, dtype):image = torch.rand(2, 3, 8, 8, device=device, dtype=dtype, requires_grad=True)op = ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0, order=(2, 3, 1, 0))