π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix CUDA compilation with CPU geometric augmentation parameters (#4517)
Dmytro Mishkin60eac42cea5c
diff --git a/changelog.d/4517.fixed.md b/changelog.d/4517.fixed.mdnew file mode 100644index 000000000..6bb738d2e--- /dev/null+++ b/changelog.d/4517.fixed.md@@ -0,0 +1,3 @@+`RandomAffine` and `RandomPerspective` now compile on CUDA with CPU-generated geometry parameters, including numeric and CPU tensor constructor ranges, with or without moving the augmentation. Their parameter placement, returned dtype, and RNG consumption are preserved. This compiler workaround covers these two transforms; other augmentations, including `RandomShear`, `RandomThinPlateSpline`, `RandomErasing`, and `CenterCrop`, may still encounter the upstream CPU-constant transfer defect.++Augmentations and random generators now use standard module migration: dtype-only `.to()` calls preserve the sampler device, device-only calls preserve its dtype, and invalid integer-dtype requests raise before changing samplers. Generator `.to()`, `.cuda()`, `.cpu()`, `.double()`, and parent-module moves now update registered buffers and samplers together. Plain tensor constructor attributes retain their existing placement precedence.diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 4be2e5178..5481d6c28 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -115,17 +115,12 @@ class _BasicAugmentationBase(nn.Module):def to(self, *args: Any, **kwargs: Any) -> "_BasicAugmentationBase":r"""Set the device and dtype for the random number generator."""- device, dtype, _, _ = torch._C._nn._parse_to(*args, **kwargs)- self.set_rng_device_and_dtype(device, dtype)+ # Module.to validates arguments before _apply updates the samplers.return super().to(*args, **kwargs)def _apply(self, fn: Callable[[torch.Tensor], torch.Tensor], *args: Any, **kwargs: Any) -> "_BasicAugmentationBase":- # nn.Module.to/.cuda/.cpu/.half move children by recursing through `_apply`, not `.to`,- # so a container like `AugmentationSequential(...).to("cuda")` never triggers our `to`- # override and leaves parameter sampling on CPU β every forward then generates on the- # host and copies to the device (measured ~5x slower on GPU pipelines). Mirror the device- # and dtype of the moved tensors onto the random generator so container moves behave like- # a direct `.to` on the augmentation.+ # Module migrations recurse through _apply. The generator moves with the children;+ # also update the augmentation's probability samplers, including in containers.out = super()._apply(fn, *args, **kwargs)probe = fn(torch.zeros((), device=self.device, dtype=self.dtype))dtype = probe.dtype if probe.is_floating_point() else self.dtypediff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.pyindex c22e88a9d..56e872278 100644--- a/kornia/augmentation/random_generator/_2d/affine.py+++ b/kornia/augmentation/random_generator/_2d/affine.py@@ -191,7 +191,13 @@ class AffineGenerator(RandomGeneratorBase):else:translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)- center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5+ # Stack scalar factories without indexed fills: those also lift CPU constants+ # that Inductor can reuse in CUDA kernels without copying the parameters.+ # See https://github.com/pytorch/pytorch/issues/196969.+ center = torch.stack(+ [torch.full((), width, device=_device, dtype=_dtype), torch.full((), height, device=_device, dtype=_dtype)]+ ).view(1, 2)+ center = center / 2.0 - 0.5center = center.expand(batch_size, -1)if self.shear_x_sampler is not None and self.shear_y_sampler is not None:@@ -200,8 +206,8 @@ class AffineGenerator(RandomGeneratorBase):sx = sx.to(device=_device, dtype=_dtype)sy = sy.to(device=_device, dtype=_dtype)else:- sx = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)- sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)+ sx = torch.zeros(batch_size, device=_device, dtype=_dtype)+ sy = torch.zeros(batch_size, device=_device, dtype=_dtype)return {"translations": translations,diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.pyindex a6cabf40b..1a78f6670 100644--- a/kornia/augmentation/random_generator/_2d/perspective.py+++ b/kornia/augmentation/random_generator/_2d/perspective.py@@ -80,9 +80,16 @@ class PerspectiveGenerator(RandomGeneratorBase):_check_positive_int_or_traced(height, "height")_check_positive_int_or_traced(width, "width")- start_points: torch.Tensor = torch.tensor(- [[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]], device=_device, dtype=_dtype- ).expand(batch_size, -1, -1)+ # Stack scalar factories without indexed fills: those also lift CPU constants+ # that Inductor can reuse in CUDA kernels without copying the parameters.+ # See https://github.com/pytorch/pytorch/issues/196969.+ zero = torch.zeros((), device=_device, dtype=_dtype)+ x = torch.full((), width - 1, device=_device, dtype=_dtype)+ y = torch.full((), height - 1, device=_device, dtype=_dtype)+ # TL, TR, BR, BL. Subtract before casting: bbox_generator subtracts in the+ # tensor dtype, which changes large half-precision image coordinates.+ start_points = torch.stack([zero, zero, x, zero, x, y, zero, y]).view(1, 4, 2)+ start_points = start_points.expand(batch_size, -1, -1)# generate random offset not larger than half of the imagefx = self._distortion_scale * width / 2@@ -95,7 +102,9 @@ class PerspectiveGenerator(RandomGeneratorBase):device=_device, dtype=_dtype)if self.sampling_method == "basic":- pts_norm = torch.tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)+ one = torch.ones((), device=_device, dtype=_dtype)+ neg_one = -one+ pts_norm = torch.stack([one, one, neg_one, one, neg_one, neg_one, one, neg_one]).view(1, 4, 2)offset = factor * rand_val * pts_normelif self.sampling_method == "area_preserving":offset = 2 * factor * (rand_val - 0.5)diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.pyindex eb2e3147e..6af795887 100644--- a/kornia/augmentation/random_generator/base.py+++ b/kornia/augmentation/random_generator/base.py@@ -65,7 +65,6 @@ class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):self.device = deviceself.dtype = dtype- # TODO: refine the logic with module.to()def to(self, *args: Any, **kwargs: Any) -> "RandomGeneratorBase":"""Update sampler device and dtype using ``torch.nn.Module.to`` semantics.@@ -76,9 +75,16 @@ class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):Returns:This generator instance."""- device, dtype, _, _ = torch._C._nn._parse_to(*args, **kwargs)- self.set_rng_device_and_dtype(device=device, dtype=dtype)- return self+ return super().to(*args, **kwargs)++ def _apply(self, fn: Callable[[torch.Tensor], torch.Tensor], *args: Any, **kwargs: Any) -> "RandomGeneratorBase":+ # Follow registered tensors for direct, convenience, and parent-module moves.+ # Plain tensor constructor attributes keep their existing placement precedence.+ out = super()._apply(fn, *args, **kwargs)+ probe = fn(torch.zeros((), device=self.device, dtype=self.dtype))+ dtype = probe.dtype if probe.is_floating_point() else self.dtype+ self.set_rng_device_and_dtype(probe.device, dtype)+ return outdef make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:"""Create distribution samplers for the given device and dtype.diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex 930a43675..b4cdcd514 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -190,6 +190,77 @@ class TestAugmentationBase2D(BaseTester):self.gradcheck(augmentation, ((input, input_param)))+class TestAugmentationPartialTo(BaseTester):+ @pytest.mark.parametrize("generator_only", [False, True])+ def test_invalid_dtype_preserves_samplers(self, device, dtype, generator_only):+ aug = K.RandomAffine(30.0, p=1.0).to(device=device, dtype=dtype)+ generator = aug._param_generator+ module = generator if generator_only else aug+ sampler = generator.degree_sampler+ with pytest.raises(TypeError, match="only accepts floating point or complex dtypes"):+ module.to(torch.int64)+ assert module.device == device+ assert module.dtype == dtype+ assert generator.degree_sampler is sampler+ assert generator.dtype == dtype+ assert generator((4, 3, 8, 9))["angle"].is_floating_point()++ @pytest.mark.parametrize("generator_only", [False, True])+ def test_move_builds_samplers_once(self, device, generator_only):+ aug = K.RandomAffine(30.0, p=1.0)+ generator = aug._param_generator+ module = generator if generator_only else aug+ # Use the unindexed device spelling to exercise CUDA's canonicalization to cuda:0.+ with patch.object(generator, "make_samplers", wraps=generator.make_samplers) as make_samplers:+ module.to(device.type, dtype=torch.float64 if device.type != "mps" else torch.float16)+ assert make_samplers.call_count == 1++ @pytest.mark.parametrize("move", ["to", "convenience", "container"])+ def test_generator_moves_buffers_and_samplers(self, device, move):+ generator = K.RandomRotation((10.0, 20.0))._param_generator+ target_dtype = torch.float16 if device.type == "mps" else torch.float64+ if move == "to":+ assert generator.to(device=device, dtype=target_dtype) is generator+ elif move == "convenience":+ if device.type in ("cpu", "cuda"):+ getattr(generator, device.type)()+ else:+ generator.to(device)+ generator.half() if target_dtype == torch.float16 else generator.double()+ else:+ torch.nn.Sequential(generator).to(device=device, dtype=target_dtype)+ assert generator.device == device+ assert generator.dtype == target_dtype+ assert generator.degrees.device == device+ assert generator.degrees.dtype == target_dtype+ assert generator.sampler_dict["degrees"].low.device == device+ assert generator.sampler_dict["degrees"].low.dtype == target_dtype++ @pytest.mark.parametrize("generator_only", [False, True])+ def test_dtype_only_to_preserves_device(self, device, dtype, generator_only):+ aug = K.RandomAffine(30.0, p=1.0)+ module = aug._param_generator if generator_only else aug+ module.to(device=device, dtype=torch.float32)+ module.to(dtype=dtype)+ assert module.device == device+ assert module.dtype == dtype+ generator = module if generator_only else module._param_generator+ assert generator.degree_sampler.low.device == device+ assert generator.degree_sampler.low.dtype == dtype++ @pytest.mark.parametrize("generator_only", [False, True])+ def test_device_only_to_preserves_dtype(self, device, dtype, generator_only):+ aug = K.RandomAffine(30.0, p=1.0)+ module = aug._param_generator if generator_only else aug+ module.to(dtype=dtype)+ module.to(device=device)+ assert module.device == device+ assert module.dtype == dtype+ generator = module if generator_only else module._param_generator+ assert generator.degree_sampler.low.device == device+ assert generator.degree_sampler.low.dtype == dtype++class TestGeometricAugmentationBase2D:@pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])def test_autocast(self, batch_prob, device, dtype):diff --git a/tests/augmentation/test_geometric_parameter_device.py b/tests/augmentation/test_geometric_parameter_device.pynew file mode 100644index 000000000..5273759ee--- /dev/null+++ b/tests/augmentation/test_geometric_parameter_device.py@@ -0,0 +1,185 @@+# 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 torch.fx.experimental.proxy_tensor import make_fx++import kornia+from kornia.core._compat import torch_version_lt++from testing.base import BaseTester+++ "make_aug",+ [+ pytest.param(+ lambda tensor_range=False: kornia.augmentation.RandomAffine(+ degrees=torch.tensor(30.0, device="cpu") if tensor_range else 30.0,+ translate=(0.1, 0.1),+ scale=(0.8, 1.2),+ p=1.0,+ ),+ id="affine",+ ),+ pytest.param(+ lambda tensor_range=False: kornia.augmentation.RandomPerspective(+ torch.tensor(0.5, device="cpu") if tensor_range else 0.5, p=1.0+ ),+ id="perspective",+ ),+ pytest.param(+ lambda tensor_range=False: kornia.augmentation.RandomPerspective(+ torch.tensor(0.5, device="cpu") if tensor_range else 0.5, p=1.0, sampling_method="area_preserving"+ ),+ id="perspective-area-preserving",+ ),+ ],+)+class TestGeometricParameterDevice(BaseTester):+ def test_geometry_constants_are_constructed_in_graph(self, make_aug):+ # CPU CI cannot execute the CUDA failure in #4516. Trace the deterministic geometry+ # and reject lifted tensor data, which Inductor may reuse across device transfers.+ generator = make_aug()._param_generator+ key = (+ "center" if isinstance(generator, kornia.augmentation.random_generator.AffineGenerator) else "start_points"+ )+ graph = make_fx(lambda: generator((4, 3, 16, 19))[key].to(torch.float64))().graph+ # Also cover constants used for end_points and indexed scalar fills. Sampler+ # bounds may be captured as attributes, but forward must not lift fresh tensors.+ assert all(node.target != torch.ops.aten.lift_fresh_copy.default for node in graph.nodes)+ output = next(node for node in graph.nodes if node.op == "output")+ pending = list(output.all_input_nodes)+ visited = set()+ while pending:+ node = pending.pop()+ if node in visited:+ continue+ visited.add(node)+ assert node.op != "get_attr", f"Lifted geometry constant: {node.target}"+ pending.extend(node.all_input_nodes)++ @pytest.mark.parametrize("batch_size", [0, 1, 4])+ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_numeric_parameters_keep_default_placement(self, make_aug, batch_size, same_on_batch, device, dtype):+ aug = make_aug().to(device=device, dtype=dtype)+ aug.same_on_batch = same_on_batch+ params = aug.forward_parameters((batch_size, 3, 8, 9))+ for name, value in params.items():+ if name in ("batch_prob", "forward_input_shape"):+ continue+ assert value.device == torch.device("cpu"), name+ # Returned precision remains separate from the sampler's requested precision.+ assert value.dtype == torch.get_default_dtype(), name+ if same_on_batch and batch_size > 1 and name not in ("center", "start_points"):+ self.assert_close(value, value[:1].expand_as(value))++ def test_container_move(self, make_aug, device, dtype):+ aug = make_aug()+ sequence = kornia.augmentation.AugmentationSequential(aug, data_keys=["input"]).to(device=device, dtype=dtype)+ input = torch.rand(2, 3, 8, 9, device=device, dtype=dtype)+ output = sequence(input)+ assert output.device == device+ assert output.dtype == dtype+ for name, value in aug._params.items():+ if name not in ("batch_prob", "forward_input_shape", "data_keys"):+ assert value.device == torch.device("cpu"), name++ @pytest.mark.parametrize("default_dtype", [torch.float32, torch.float64])+ def test_default_dtype_after_sampler_move(self, make_aug, device, default_dtype):+ # A float64 default must not force float64 sampling on MPS.+ aug = make_aug().to(device=device, dtype=torch.float32)+ original_dtype = torch.get_default_dtype()+ try:+ torch.set_default_dtype(default_dtype)+ params = aug.forward_parameters((4, 3, 8, 9))+ generator = aug._param_generator+ assert generator.dtype == torch.float32+ sampler = generator.degree_sampler if hasattr(generator, "degree_sampler") else generator.rand_val_sampler+ assert sampler.low.dtype == torch.float32+ assert sampler.low.device == device+ for name, value in params.items():+ if name not in ("batch_prob", "forward_input_shape"):+ assert value.device == torch.device("cpu"), name+ assert value.dtype == default_dtype, name+ finally:+ torch.set_default_dtype(original_dtype)++ def test_ambient_default_device(self, make_aug, device, dtype):+ # Sampling stays on CPU while numeric returned parameters follow the default device.+ original_modes = torch.overrides._get_current_function_mode_stack()+ with torch.device(device):+ aug = make_aug()+ params = aug.forward_parameters((4, 3, 8, 9))+ assert aug._param_generator.device == torch.device("cpu")+ for name, value in params.items():+ if name not in ("batch_prob", "forward_input_shape"):+ assert value.device == device, name+ assert torch.overrides._get_current_function_mode_stack() == original_modes++ @pytest.mark.parametrize("batch_size", [1, 4])+ @pytest.mark.parametrize(+ "placement",+ ["unmoved", "moved", "cpu_tensor", "cpu_tensor_unmoved", "default_device", "dtype_only", "container"],+ )+ def test_dynamo_parameter_generation(self, make_aug, batch_size, placement, device, dtype, torch_optimizer):+ # #4516: capture fresh parameter generation and CPU-to-image transfers in one graph.+ # Replaying precomputed parameters alone does not reproduce the Inductor defect.+ if device.type not in ("cpu", "cuda"):+ pytest.skip("Inductor regression covers CPU and CUDA")+ if placement == "container" and torch_version_lt(2, 6, 0):+ pytest.skip("PyTorch 2.5 cannot trace the container's isinstance checks with union types")+ with torch.device(device if placement == "default_device" else "cpu"):+ aug = make_aug(tensor_range=placement in ("cpu_tensor", "cpu_tensor_unmoved"))+ if placement in ("moved", "cpu_tensor"):+ aug.to(device=device, dtype=dtype)+ elif placement == "dtype_only":+ aug.to(device).to(dtype)+ module = aug+ if placement == "container":+ module = kornia.augmentation.AugmentationSequential(aug, data_keys=["input"]).to(device, dtype)+ # Fullgraph captures the tensor pipeline; PIL/NumPy conversion uses Python decorators.+ module.disable_features = True+ input = torch.rand(batch_size, 3, 16, 19, device=device, dtype=dtype)++ def apply_with_parameters(input):+ # Capture sampling with application, and return parameters explicitly:+ # older Torch export guards suppress the augmentation's _params side effect.+ params = module.forward_parameters(input.shape)+ output = module(input, params=params)+ return output, params[0].data if placement == "container" else params++ compiled = torch_optimizer(apply_with_parameters, fullgraph=True)+ for _ in range(2):+ actual, params = compiled(input)+ expected = aug(input, params=params)+ self.assert_close(actual, expected)+ parameter_device = device if placement == "default_device" else torch.device("cpu")+ for name, value in params.items():+ if name not in ("batch_prob", "forward_input_shape", "data_keys"):+ assert value.device == parameter_device, name+++class TestGeometricTensorRangeDevice(BaseTester):+ def test_perspective_tensor_range_keeps_placement(self, device, dtype):+ aug = kornia.augmentation.RandomPerspective(torch.tensor(0.5, device="cpu", dtype=dtype), p=1.0)+ aug.set_rng_device_and_dtype(device, torch.float32)+ params = aug.forward_parameters((4, 3, 8, 9))+ for name in ("start_points", "end_points"):+ assert params[name].device == torch.device("cpu")+ assert params[name].dtype == dtypediff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex c9030bd4a..b038b3e63 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -747,6 +747,18 @@ class TestRandomPerspectiveGen(RandomGeneratorBaseTests):class TestRandomAffineGen(RandomGeneratorBaseTests):+ @pytest.mark.parametrize("range_name", ["degrees", "translate", "scale", "shear"])+ def test_tensor_range_keeps_placement(self, range_name, device, dtype):+ ranges = {"degrees": 30.0, "translate": (0.1, 0.1), "scale": (0.8, 1.2), "shear": (0.0, 5.0, 0.0, 5.0)}+ # Any tensor-valued range, including an optional one, controls returned placement.+ ranges[range_name] = torch.tensor(ranges[range_name], device="cpu", dtype=dtype)+ generator = AffineGenerator(**ranges)+ generator.set_rng_device_and_dtype(device, torch.float32)+ params = generator((4, 3, 8, 9))+ for name, value in params.items():+ assert value.device == torch.device("cpu"), name+ assert value.dtype == dtype, name+@pytest.mark.parametrize("batch_size", [0, 1, 4])@pytest.mark.parametrize("height", [200])@pytest.mark.parametrize("width", [300])