π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): align probability masks with input devices (#4164)
Dmytro Mishkin8f8287ff71c3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0d7a98852..9f6841a78 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -129,6 +129,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* Fix 2-D, 3-D, and mix augmentations raising a cross-device `RuntimeError` when their random parameters are generated+ on the default CPU device and their input is on MPS or CUDA (#4164). Since #3722, four branchless `torch.where`+ blends used the CPU `batch_prob` mask directly with accelerator outputs or transformation matrices. The selection+ mask now moves to the output device at each blend boundary, preserving CPU random-number generation and the+ ONNX/fullgraph-friendly blend. Calling `augmentation(x_accelerator)` therefore works again without first moving the+ augmentation module or its RNG to the accelerator (#4151).+* Keep `extract_patches_simple` and `extract_patches_from_pyramid` off a broken reduced-precision CPU kernel: for a`float16`/`bfloat16` CPU image, the `grid_sample` kernels in torch <= 2.9 read out of bounds when a rotated patchstraddles the image border and return NaN or garbage values far outside the image's range. Both extractors nowdiff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex 0eea067dc..eb65bebea 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -135,7 +135,9 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):# If batch sizes line up, do the where-blend. Otherwise (e.g. VideoSequential# passes B-sized batch_prob into a B*T-sized input) fall back to all-or-nothing.if trans_matrix_applied.shape[0] == to_apply.shape[0] == trans_matrix_identity.shape[0]:- to_apply_expanded = to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1)))+ to_apply_expanded = to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1))).to(+ trans_matrix_applied.device+ )trans_matrix = torch.where(to_apply_expanded, trans_matrix_applied, trans_matrix_identity)else:trans_matrix = trans_matrix_applied if bool(to_apply.any()) else trans_matrix_identitydiff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.pyindex 8e40be7dd..96f052b5d 100644--- a/kornia/augmentation/_2d/mix/base.py+++ b/kornia/augmentation/_2d/mix/base.py@@ -109,7 +109,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):applied_post = self.apply_non_transform(applied, params, flags)if applied_post.shape == non_applied.shape and applied_post.shape[0] == to_apply.shape[0]:- to_apply_expanded = to_apply.view(-1, *([1] * (applied_post.dim() - 1)))+ to_apply_expanded = to_apply.view(-1, *([1] * (applied_post.dim() - 1))).to(applied_post.device)output = torch.where(to_apply_expanded, applied_post, non_applied)else:# Shape-changing mix augmentations (e.g. RandomMosaic when ``output_size``diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.pyindex c251bd331..718a6c843 100644--- a/kornia/augmentation/_3d/base.py+++ b/kornia/augmentation/_3d/base.py@@ -101,7 +101,9 @@ class RigidAffineAugmentationBase3D(AugmentationBase3D):trans_matrix_identity = self.identity_matrix(in_tensor)if trans_matrix_applied.shape[0] == to_apply.shape[0] == trans_matrix_identity.shape[0]:- to_apply_expanded = to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1)))+ to_apply_expanded = to_apply.view(-1, *([1] * (trans_matrix_applied.dim() - 1))).to(+ trans_matrix_applied.device+ )trans_matrix = torch.where(to_apply_expanded, trans_matrix_applied, trans_matrix_identity)else:trans_matrix = trans_matrix_applied if bool(to_apply.any()) else trans_matrix_identitydiff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 533dab746..f7a6afabb 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -356,7 +356,7 @@ class _AugmentationBase(_BasicAugmentationBase):not onnx-exportable."""if transformed.shape == not_transformed.shape and transformed.shape[0] == to_apply.shape[0]:- to_apply_expanded = to_apply.view(-1, *([1] * (len(transformed.shape) - 1)))+ to_apply_expanded = to_apply.view(-1, *([1] * (len(transformed.shape) - 1))).to(transformed.device)return torch.where(to_apply_expanded, transformed, not_transformed)return transformed if bool(to_apply.any()) else not_transformeddiff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.pyindex ca94744d8..3e46bebce 100644--- a/tests/augmentation/test_base.py+++ b/tests/augmentation/test_base.py@@ -22,8 +22,12 @@ import torchfrom kornia.augmentation._2d.base import AugmentationBase2Dfrom kornia.augmentation._2d.geometric.affine import RandomAffine+from kornia.augmentation._2d.geometric.horizontal_flip import RandomHorizontalFlipfrom kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlur+from kornia.augmentation._2d.intensity.invert import RandomInvert+from kornia.augmentation._2d.mix.mixup import RandomMixUpV2from kornia.augmentation._3d.geometric.affine import RandomAffine3D+from kornia.augmentation._3d.geometric.horizontal_flip import RandomHorizontalFlip3Dfrom kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3Dfrom kornia.augmentation.base import _BasicAugmentationBasefrom kornia.core._compat import torch_version_lt@@ -263,3 +267,73 @@ class TestGeometricAugmentationBase3D:res = aug(x, params)assert res.dtype == dtype, "The output dtype should match the input dtype"+++class TestDeviceAgnosticAugmentationParameters(BaseTester):+ """Augmentations keep RNG/params on CPU while accepting accelerator inputs.++ CPU cases provide smoke coverage; the cross-device regression is exercised on CUDA and MPS.+ """++ @staticmethod+ def _cpu_partial_batch_params(augmentation: _BasicAugmentationBase, input: torch.Tensor) -> dict[str, torch.Tensor]:+ params = augmentation.forward_parameters(input.shape)+ assert params["batch_prob"].device.type == "cpu"+ params["batch_prob"] = torch.tensor([True, False])+ return params++ def test_2d_augmentation_blends_cpu_params_with_accelerator_input(self, device, dtype):+ input = torch.arange(12, device=device, dtype=dtype).reshape(2, 1, 2, 3) / 12+ augmentation = RandomInvert(p=0.5)+ params = self._cpu_partial_batch_params(augmentation, input)++ output = augmentation(input, params=params)++ expected = torch.stack([1 - input[0], input[1]])+ assert output.device == input.device+ self.assert_close(output, expected)++ def test_2d_geometric_matrix_blends_cpu_params_with_accelerator_input(self, device, dtype):+ input = torch.arange(12, device=device, dtype=dtype).reshape(2, 1, 2, 3)+ augmentation = RandomHorizontalFlip(p=0.5)+ params = self._cpu_partial_batch_params(augmentation, input)++ output = augmentation(input, params=params)+ matrix = augmentation.transform_matrix++ expected = torch.stack([input[0].flip(-1), input[1]])+ assert output.device == input.device+ assert matrix is not None+ assert matrix.device == input.device+ self.assert_close(output, expected)+ self.assert_close(matrix[1], torch.eye(3, device=device, dtype=dtype))++ def test_3d_geometric_matrix_blends_cpu_params_with_accelerator_input(self, device, dtype):+ input = torch.arange(24, device=device, dtype=dtype).reshape(2, 1, 2, 2, 3)+ augmentation = RandomHorizontalFlip3D(p=0.5)+ params = self._cpu_partial_batch_params(augmentation, input)++ output = augmentation(input, params=params)+ matrix = augmentation.transform_matrix++ expected = torch.stack([input[0].flip(-1), input[1]])+ assert output.device == input.device+ assert matrix is not None+ assert matrix.device == input.device+ self.assert_close(output, expected)+ self.assert_close(matrix[1], torch.eye(4, device=device, dtype=dtype))++ def test_mix_augmentation_blends_cpu_params_with_accelerator_input(self, device, dtype):+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("RandomMixUpV2 promotes half inputs because mixup_lambdas are float32")++ input = torch.arange(24, device=device, dtype=dtype).reshape(2, 3, 2, 2)+ augmentation = RandomMixUpV2(lambda_val=(0.25, 0.25), p=1.0, data_keys=["input"])+ params = self._cpu_partial_batch_params(augmentation, input)+ params["mixup_pairs"] = torch.tensor([1, 0])++ output = augmentation(input, params=params)++ expected = torch.stack([input[0] * 0.75 + input[1] * 0.25, input[1]])+ assert output.device == input.device+ self.assert_close(output, expected)