Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): honour the sampler device in linear illumination (#4546)

rishabha08fd35f1a11
diff --git a/changelog.d/4546.fixed.md b/changelog.d/4546.fixed.md
new file mode 100644
index 000000000..0f9509b30
--- /dev/null
+++ b/changelog.d/4546.fixed.md
@@ -0,0 +1,5 @@
+`RandomLinearIllumination` and `RandomLinearCornerIllumination` build their `gradient` parameter on
+the device and dtype their samplers were moved to, matching `RandomGaussianIllumination`. Moving
+either augmentation to CUDA or MPS, or calling `set_rng_device_and_dtype` on its generator as the
+class docstring describes, used to return a CPU tensor of the default dtype, so a `float64` pipeline
+silently got `float32` parameters and every call copied the gradient across devices. (#4536)
diff --git a/kornia/augmentation/random_generator/_2d/linear_illumination.py b/kornia/augmentation/random_generator/_2d/linear_illumination.py
index 97fb94889..fd13d6ebe 100644
--- a/kornia/augmentation/random_generator/_2d/linear_illumination.py
+++ b/kornia/augmentation/random_generator/_2d/linear_illumination.py
@@ -21,7 +21,6 @@ import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase, UniformDistribution
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
-from kornia.core.utils import _extract_device_dtype
from kornia.enhance.normalize import normalize_min_max
@@ -68,13 +67,19 @@ class LinearIlluminationGenerator(RandomGeneratorBase):
sign = _range_bound(self.sign, "sign", bounds=(-1.0, 1.0), center=0.0).to(device, dtype)
self.sign_sampler = UniformDistribution(sign[0], sign[1], validate_args=False)
- self.directions_sampler = UniformDistribution(0, 4, validate_args=False)
+ # Draw the directions on the sampler device but always in float32: on MPS, half-precision
+ # ``torch.rand`` can return exactly 1.0, which would truncate to the invalid direction 4.
+ self.directions_sampler = UniformDistribution(
+ torch.tensor(0.0, device=device, dtype=torch.float32),
+ torch.tensor(4.0, device=device, dtype=torch.float32),
+ validate_args=False,
+ )
def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
r"""Generate random 2D Gaussian illumination patterns."""
batch_size, channels, height, width = batch_shape
_common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.gain, self.sign])
+ _device, _dtype = self.device, self.dtype
# Random gain and sign
gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_sampler, same_on_batch).to(
@@ -156,13 +161,19 @@ class LinearCornerIlluminationGenerator(RandomGeneratorBase):
sign = _range_bound(self.sign, "sign", bounds=(-1.0, 1.0), center=0.0).to(device, dtype)
self.sign_sampler = UniformDistribution(sign[0], sign[1], validate_args=False)
- self.directions_sampler = UniformDistribution(0, 4, validate_args=False)
+ # Draw the directions on the sampler device but always in float32: on MPS, half-precision
+ # ``torch.rand`` can return exactly 1.0, which would truncate to the invalid direction 4.
+ self.directions_sampler = UniformDistribution(
+ torch.tensor(0.0, device=device, dtype=torch.float32),
+ torch.tensor(4.0, device=device, dtype=torch.float32),
+ validate_args=False,
+ )
def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:
r"""Generate random 2D Gaussian illumination patterns."""
batch_size, channels, height, width = batch_shape
_common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([self.gain, self.sign])
+ _device, _dtype = self.device, self.dtype
gain_factor = _adapted_rsampling((batch_size, 1, 1, 1), self.gain_sampler, same_on_batch).to(
device=_device, dtype=_dtype
diff --git a/tests/augmentation/test_parameter_constants.py b/tests/augmentation/test_parameter_constants.py
index 29cdc644a..5a99be5e8 100644
--- a/tests/augmentation/test_parameter_constants.py
+++ b/tests/augmentation/test_parameter_constants.py
@@ -28,7 +28,8 @@ from kornia.augmentation.utils.helpers import _constant_tensor
from testing.base import BaseTester
-# Numeric constructor inputs deliberately keep the generated parameters on CPU.
+# Numeric constructor inputs deliberately keep the generated parameters on CPU, except for the
+# resize and illumination generators, which follow the device and dtype the generator was moved to.
# Include both branches which construct destination corners in crop generators.
GENERATORS = [
pytest.param(lambda: rg.AffineGenerator(30.0), (4, 3, 16, 19), id="affine"),
@@ -226,13 +227,32 @@ class TestShearSamplerPlacement(BaseTester):
generator((4, 3, 16, 19))
-class TestLinearIlluminationPlacement(BaseTester):
- @pytest.mark.parametrize("generator_type", [rg.LinearIlluminationGenerator, rg.LinearCornerIlluminationGenerator])
- def test_moved_sampler(self, generator_type, device, dtype):
- generator = generator_type((0.1, 0.2), (-1.0, 1.0)).to(device=device, dtype=dtype)
+class TestIlluminationPlacement(BaseTester):
+ @pytest.mark.parametrize(
+ "make_generator",
+ [
+ pytest.param(lambda: rg.LinearIlluminationGenerator((0.1, 0.2), (-1.0, 1.0)), id="linear"),
+ pytest.param(lambda: rg.LinearCornerIlluminationGenerator((0.1, 0.2), (-1.0, 1.0)), id="linear-corner"),
+ pytest.param(
+ lambda: rg.GaussianIlluminationGenerator((0.1, 0.2), (0.1, 0.2), (0.1, 0.2), (-1.0, 1.0)),
+ id="gaussian",
+ ),
+ ],
+ )
+ def test_moved_sampler(self, make_generator, device, dtype):
+ generator = make_generator().to(device=device, dtype=dtype)
params = generator((4, 3, 16, 19))
- assert params["gradient"].device == torch.device("cpu")
- assert params["gradient"].dtype == torch.get_default_dtype()
+ assert params["gradient"].device == device
+ assert params["gradient"].dtype == dtype
+
+ @pytest.mark.parametrize("generator_class", [rg.LinearIlluminationGenerator, rg.LinearCornerIlluminationGenerator])
+ def test_directions_sampler(self, generator_class):
+ # The meta device makes the placement observable without an accelerator. The directions stay
+ # float32 because MPS half-precision ``torch.rand`` can return 1.0, which truncates to direction 4.
+ generator = generator_class((0.1, 0.2), (-1.0, 1.0)).to(device="meta", dtype=torch.float16)
+ assert generator.directions_sampler.low.device.type == "meta"
+ assert generator.directions_sampler.high.device.type == "meta"
+ assert generator.directions_sampler.low.dtype == torch.float32
class TestResizedCropNumpyScale(BaseTester):