Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): keep half-precision crop and PatchMix samplers in float32 (#5050)

rishabh43eb3b237c8d
diff --git a/changelog.d/5050.fixed.md b/changelog.d/5050.fixed.md
new file mode 100644
index 000000000..3e70034cc
--- /dev/null
+++ b/changelog.d/5050.fixed.md
@@ -0,0 +1 @@
+CropGenerator, ResizedCropGenerator, CropGenerator3D and PatchMixGenerator keep their position sampler in float32 when the augmentation is moved to float16 or bfloat16, so a crop or patch start cannot land one past the last valid position. On MPS, half-precision `torch.rand` returns exactly 1.0 for about 1 in 4096 (float16) or 1 in 512 (bfloat16) draws, which made `RandomCrop(cropping_mode="resample")` blend a zero padding line into the crop and put `RandomCrop3D` boxes and `PatchMix` patches one pixel past the edge. float32 and float64 draws are unchanged; for the same seed, float16 and bfloat16 pipelines now draw some different positions than before, and `RandomResizedCrop` also some different crop sizes, because its scale draw comes from the same sampler. (#4553)
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index bb87eb232..fef6d756d 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -66,8 +66,12 @@ class CropGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ # The draw is truncated to a start position, so keep it in float32: half-precision
+ # torch.rand on MPS can return exactly 1.0, which lands one past the last valid start (#4553).
+ sampler_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
self.rand_sampler = Uniform(
- torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ torch.tensor(0.0, device=device, dtype=sampler_dtype),
+ torch.tensor(1.0, device=device, dtype=sampler_dtype),
)
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
@@ -231,8 +235,12 @@ class ResizedCropGenerator(CropGenerator):
ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
_joint_range_check(scale, "scale")
_joint_range_check(ratio, "ratio")
+ # The draw is truncated to a start position, so keep it in float32: half-precision
+ # torch.rand on MPS can return exactly 1.0, which lands one past the last valid start (#4553).
+ sampler_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
self.rand_sampler = Uniform(
- torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ torch.tensor(0.0, device=device, dtype=sampler_dtype),
+ torch.tensor(1.0, device=device, dtype=sampler_dtype),
)
self.log_ratio_sampler = Uniform(torch.log(ratio[0]), torch.log(ratio[1]), validate_args=False)
diff --git a/kornia/augmentation/random_generator/_2d/patchmix.py b/kornia/augmentation/random_generator/_2d/patchmix.py
index b98d176e4..52bff33fc 100644
--- a/kornia/augmentation/random_generator/_2d/patchmix.py
+++ b/kornia/augmentation/random_generator/_2d/patchmix.py
@@ -69,9 +69,12 @@ class PatchMixGenerator(RandomGeneratorBase):
torch.tensor(self.alpha, device=device, dtype=dtype),
torch.tensor(self.alpha, device=device, dtype=dtype),
)
+ # The draw is truncated to a patch start, so keep it in float32: half-precision
+ # torch.rand on MPS can return exactly 1.0, which lands one past the last valid start (#4553).
+ sampler_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
self.rand_sampler = Uniform(
- torch.tensor(0.0, device=device, dtype=dtype),
- torch.tensor(1.0, device=device, dtype=dtype),
+ torch.tensor(0.0, device=device, dtype=sampler_dtype),
+ torch.tensor(1.0, device=device, dtype=sampler_dtype),
)
self.pair_sampler = Uniform(
torch.tensor(0.0, device=device, dtype=dtype),
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index e84c53300..0ca16afb9 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -63,8 +63,12 @@ class CropGenerator3D(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ # The draw is truncated to a start position, so keep it in float32: half-precision
+ # torch.rand on MPS can return exactly 1.0, which lands one past the last valid start (#4553).
+ sampler_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
self.rand_sampler = Uniform(
- torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
+ torch.tensor(0.0, device=device, dtype=sampler_dtype),
+ torch.tensor(1.0, device=device, dtype=sampler_dtype),
)
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index c2474e03c..a8de0a34b 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -28,9 +28,11 @@ from kornia.augmentation.random_generator import (
ColorJiggleGenerator,
ColorJitterGenerator,
CropGenerator,
+ CropGenerator3D,
CutmixGenerator,
MixupGenerator,
MotionBlurGenerator,
+ PatchMixGenerator,
PerspectiveGenerator,
PlainUniformGenerator,
PlanckianJitterGenerator,
@@ -1899,3 +1901,63 @@ class TestPlanckianJitterGenerator:
assert idx.device.type == device.type
assert int(idx.min()) >= 0
assert int(idx.max()) < 25
+
+
+# The four generators that truncate a Uniform(0, 1) draw to a crop or patch start. Each case builds a
+# fresh generator and gives the batch shape of an 8-pixel-wide input that a size-4 crop or patch fits
+# in exactly five ways per axis.
+_POSITION_SAMPLER_CASES = [
+ pytest.param(lambda: CropGenerator((4, 4)), torch.Size([1 << 16, 1, 8, 8]), id="crop"),
+ pytest.param(
+ lambda: ResizedCropGenerator((4, 4), (0.25, 0.25), (1.0, 1.0)),
+ torch.Size([1 << 16, 1, 8, 8]),
+ id="resized_crop",
+ ),
+ pytest.param(lambda: CropGenerator3D((4, 4, 4)), torch.Size([1 << 16, 1, 8, 8, 8]), id="crop3d"),
+ pytest.param(lambda: PatchMixGenerator(patch_size=4), torch.Size([1 << 16, 1, 8, 8]), id="patchmix"),
+]
+
+
+class TestHalfPrecisionPositionSamplers:
+ # The half dtypes are named rather than taken from the fixture so the pins run on the default float32
+ # legs too; the device comes from the fixture so the MPS leg draws on MPS.
+ @pytest.mark.parametrize("make_generator,batch_shape", _POSITION_SAMPLER_CASES)
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_position_sampler_stays_float32_for_half_precision(self, make_generator, batch_shape, device, half_dtype):
+ # The draw is truncated to a start position. Half-precision torch.rand on MPS can return
+ # exactly 1.0, which put the start one past the last valid position (#4553).
+ generator = make_generator()
+ generator.set_rng_device_and_dtype(device, half_dtype)
+ assert generator.rand_sampler.low.dtype == torch.float32
+ assert generator.rand_sampler.high.dtype == torch.float32
+ assert generator.rand_sampler.low.device.type == device.type
+ assert generator.rand_sampler.high.device.type == device.type
+
+ @pytest.mark.parametrize("make_generator,batch_shape", _POSITION_SAMPLER_CASES)
+ @pytest.mark.parametrize("dtype", [torch.float32, torch.float64])
+ def test_position_sampler_follows_full_precision_dtype(self, make_generator, batch_shape, dtype):
+ generator = make_generator()
+ generator.set_rng_device_and_dtype(torch.device("cpu"), dtype)
+ assert generator.rand_sampler.low.dtype == dtype
+ assert generator.rand_sampler.high.dtype == dtype
+
+ # CPU half torch.rand never returns 1.0, so this only discriminates on the MPS leg: there, with a
+ # half-precision sampler, 2**16 draws put about 16 (float16) or 128 (bfloat16) starts per axis one
+ # past the edge.
+ @pytest.mark.parametrize("make_generator,batch_shape", _POSITION_SAMPLER_CASES)
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_half_precision_starts_stay_in_range(self, make_generator, batch_shape, device, half_dtype):
+ generator = make_generator()
+ if isinstance(generator, PatchMixGenerator) and device.type == "cpu":
+ pytest.skip("The PatchMix Beta sampler is not implemented for CPU half precision.")
+ generator.set_rng_device_and_dtype(device, half_dtype)
+ torch.manual_seed(0)
+ params = generator(batch_shape)
+ if isinstance(generator, PatchMixGenerator):
+ # (B, 2) patch starts; the far corner of a size-4 patch is 3 pixels on.
+ last_covered = params["patch_coords"] + 3
+ else:
+ # (B, 4, 2) or (B, 8, 3) crop corners in pixel coordinates.
+ last_covered = params["src"]
+ assert int(last_covered.min()) >= 0
+ assert int(last_covered.max()) < 8