π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): draw the CutMix and PatchMix Beta coefficient in float32 for half precision (#6277)
Dmytro Mishkine079f719dcaf
diff --git a/changelog.d/6277.fixed.md b/changelog.d/6277.fixed.mdnew file mode 100644index 000000000..6c0963598--- /dev/null+++ b/changelog.d/6277.fixed.md@@ -0,0 +1,7 @@+`RandomCutMixV2` and the PatchMix generator draw their Beta mixing coefficient in float32 when their parameter+generator is set to float16 or bfloat16, as the position samplers already do (#4553). torch draws Beta through+Dirichlet, which has no CPU half-precision kernel. A CPU generator in half precision used to raise `"dirichlet" not+implemented for 'Half'` on every call. That happened after `set_rng_device_and_dtype`, after `.to(torch.float16)` on+the augmentation (in 0.8.3 too), or, since containers and parent modules now pass `.to()` on to their augmentations,+after `.to(torch.float16)` on any model that holds one. CutMix builds the concentration from `beta` directly in+float32, so a `beta` outside the float16 range keeps its value. Float32 and float64 draws are unchanged.diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.pyindex 6469ef928..1deaaf8a0 100644--- a/kornia/augmentation/random_generator/_2d/cutmix.py+++ b/kornia/augmentation/random_generator/_2d/cutmix.py@@ -83,10 +83,15 @@ class CutmixGenerator(RandomGeneratorBase):return f"cut_size={self.cut_size}, beta={self.beta}, num_mix={self.num_mix}"def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ # torch draws Beta through Dirichlet, which has no CPU half-precision kernel: a generator moved to float16 by+ # .to() raised on every draw. Draw in float32 for half precision, as the position samplers do (#4553). Build+ # the concentration from the supplied beta directly in that dtype: a float16 round trip turns a large beta+ # into inf and a small one into 0.+ beta_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtypeif self.beta is None:- self._beta = torch.tensor(1.0, device=device, dtype=dtype)+ self._beta = torch.tensor(1.0, device=device, dtype=beta_dtype)else:- self._beta = torch.as_tensor(self.beta, device=device, dtype=dtype)+ self._beta = torch.as_tensor(self.beta, device=device, dtype=beta_dtype)if self.cut_size is None:self._cut_size = torch.tensor([0.0, 1.0], device=device, dtype=dtype)else:diff --git a/kornia/augmentation/random_generator/_2d/patchmix.py b/kornia/augmentation/random_generator/_2d/patchmix.pyindex 52bff33fc..37cecd48a 100644--- a/kornia/augmentation/random_generator/_2d/patchmix.py+++ b/kornia/augmentation/random_generator/_2d/patchmix.py@@ -65,9 +65,11 @@ class PatchMixGenerator(RandomGeneratorBase):return f"alpha={self.alpha}, patch_size={self.patch_size}, p={self.p}"def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ # Beta draws through Dirichlet, which has no CPU half-precision kernel: draw in float32 for half precision.+ beta_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtypeself.beta_sampler = Beta(- torch.tensor(self.alpha, device=device, dtype=dtype),- torch.tensor(self.alpha, device=device, dtype=dtype),+ torch.tensor(self.alpha, device=device, dtype=beta_dtype),+ torch.tensor(self.alpha, device=device, dtype=beta_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).diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.pyindex 9cbb96b76..cf40fe041 100644--- a/tests/augmentation/test_augmentation_mix.py+++ b/tests/augmentation/test_augmentation_mix.py@@ -295,6 +295,18 @@ class TestRandomMixUpV2(BaseTester):class TestRandomCutMixV2(BaseTester):+ # A model moved to half precision moves its augmentations too. CutMix's Beta draw used to raise there on CPU+ # ("dirichlet" has no Half kernel), on 0.8.3 as well for a direct .to(); it now draws in float32.+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])+ def test_module_moved_to_half_precision(self, device, half_dtype):+ torch.manual_seed(0)+ aug = RandomCutMixV2(p=1.0, data_keys=["input", "class"]).to(device=device, dtype=half_dtype)+ image = torch.rand(2, 3, 8, 8, device=device, dtype=half_dtype)+ out_image, out_labels = aug(image, torch.tensor([0, 1], device=device))+ assert out_image.dtype == half_dtype+ assert torch.isfinite(out_image).all()+ assert torch.isfinite(out_labels).all()+def test_smoke(self):f = RandomCutMixV2(data_keys=["input", "class"], use_correct_lambda=True)expected_repr = "RandomCutMixV2(cut_size=None, beta=None, num_mix=1, p=1.0, p_batch=1.0, same_on_batch=False)"diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex d46741812..4cf3d7170 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -2023,8 +2023,6 @@ class TestHalfPrecisionPositionSamplers:@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)@@ -2094,6 +2092,52 @@ class TestIndexPermutationsInHalfPrecision:assert orders == [[1, 0, 3, 2], [1, 3, 0, 2], [1, 0, 3, 2], [3, 2, 0, 1], [1, 2, 3, 0]]+class TestBetaSamplersInHalfPrecision:+ # torch draws Beta through Dirichlet, which has no CPU half-precision kernel, so a CutMix or PatchMix generator+ # moved to float16 or bfloat16 -- set_rng_device_and_dtype, or .to() on the augmentation or on a module holding it+ # -- raised "dirichlet not implemented for 'Half'" on every draw. The Beta sampler now draws in float32 for half+ # precision, as the position samplers do (#4553).+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])+ @pytest.mark.parametrize(+ "make_generator,batch_shape",+ [+ (lambda: CutmixGenerator(p=1.0), torch.Size([4, 3, 16, 16])),+ (lambda: PatchMixGenerator(patch_size=4), torch.Size([4, 3, 16, 16])),+ ],+ ids=["CutmixGenerator", "PatchMixGenerator"],+ )+ def test_beta_draws_in_half_precision(self, device, half_dtype, make_generator, batch_shape):+ generator = make_generator()+ generator.set_rng_device_and_dtype(device, half_dtype)+ assert generator.beta_sampler.concentration1.dtype == torch.float32+ torch.manual_seed(0)+ params = generator(batch_shape)+ for value in params.values():+ if value.is_floating_point():+ assert torch.isfinite(value).all()++ # 1e5 overflows float16 and 1e-8 underflows it. A float16 round trip turned the first into an inf concentration,+ # whose draws are all ~0 (a full-image cut instead of a lambda near 0.5), and the second into 0, which Beta rejects.+ @pytest.mark.parametrize("beta", [1e5, 1e-8])+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])+ def test_cutmix_beta_outside_half_range_keeps_its_value(self, device, half_dtype, beta):+ generator = CutmixGenerator(beta=beta, p=1.0)+ generator.set_rng_device_and_dtype(device, half_dtype)+ expected = torch.tensor(beta, device=device, dtype=torch.float32)+ assert torch.equal(generator.beta_sampler.concentration1, expected)+ assert torch.equal(generator.beta_sampler.concentration0, expected)+ if beta > 1:+ torch.manual_seed(0)+ draws = generator.beta_sampler.sample((64,))+ assert ((draws - 0.5).abs() < 0.02).all()++ @pytest.mark.parametrize("dtype_", [torch.float32, torch.float64])+ def test_beta_sampler_follows_full_precision(self, dtype_):+ generator = CutmixGenerator(p=1.0)+ generator.set_rng_device_and_dtype(torch.device("cpu"), dtype_)+ assert generator.beta_sampler.concentration1.dtype == dtype_++class TestTruncateToStart:# The largest float32 below 1 rounds to 1.0 in float16 and in bfloat16, the largest float64 below 1 rounds to# 1.0 in float32. The start has to stay at the last valid position and come back in the extent's dtype.