Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): draw ColorJiggle's order and MixUp's pairs as int64 permutations (#6268)

Dmytro Mishkinad9fbaee385e
diff --git a/changelog.d/6268.fixed.md b/changelog.d/6268.fixed.md
new file mode 100644
index 000000000..d85a02d68
--- /dev/null
+++ b/changelog.d/6268.fixed.md
@@ -0,0 +1,7 @@
+`ColorJiggle`'s channel order and `RandomMixUpV2`'s pairs are drawn as an int64 permutation, whatever the dtype the
+parameter generator samples in. A generator set to `bfloat16` used to raise `"randperm_out_cuda" not implemented for
+'BFloat16'` on CUDA. That happened through `set_rng_device_and_dtype`, through `.to(torch.bfloat16)` on the
+augmentation, and, since containers and parent modules now pass `.to()` on to their augmentations, through
+`.to(torch.bfloat16)` on any model that contains one. In `float16`, a MixUp batch above 2048 could not be permuted
+exactly. torch draws the same permutation for every dtype, so the parameters of every call that worked before are
+unchanged.
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index 7733cbcae..8b6474e6a 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -84,7 +84,9 @@ class ColorJiggleGenerator(RandomGeneratorBase):
self.contrast_sampler = UniformDistribution(contrast[0], contrast[1], validate_args=False)
self.hue_sampler = UniformDistribution(hue[0], hue[1], validate_args=False)
self.saturation_sampler = UniformDistribution(saturation[0], saturation[1], validate_args=False)
- self.randperm = partial(torch.randperm, device=device, dtype=dtype)
+ # The order is an index permutation: draw it as int64, whatever the sampling dtype. torch draws the same
+ # permutation for every dtype, and CUDA has no bfloat16 randperm.
+ self.randperm = partial(torch.randperm, device=device, dtype=torch.long)
def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
@@ -99,5 +101,5 @@ class ColorJiggleGenerator(RandomGeneratorBase):
"contrast_factor": contrast_factor.to(device=_device, dtype=_dtype),
"hue_factor": hue_factor.to(device=_device, dtype=_dtype),
"saturation_factor": saturation_factor.to(device=_device, dtype=_dtype),
- "order": self.randperm(4).to(device=_device, dtype=_dtype).long(),
+ "order": self.randperm(4).to(device=_device),
}
diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.py
index 150460eda..7974823b8 100644
--- a/kornia/augmentation/random_generator/_2d/mixup.py
+++ b/kornia/augmentation/random_generator/_2d/mixup.py
@@ -74,7 +74,9 @@ class MixupGenerator(RandomGeneratorBase):
with torch.no_grad():
batch_probs: torch.Tensor = _adapted_sampling((batch_size,), self.prob_sampler, same_on_batch)
- mixup_pairs: torch.Tensor = torch.randperm(batch_size, device=_device, dtype=_dtype).long()
+ # An index permutation: int64 whatever the sampling dtype (CUDA has no bfloat16 randperm, and float16 holds
+ # integers exactly only up to 2048). torch draws the same permutation for every dtype.
+ mixup_pairs: torch.Tensor = torch.randperm(batch_size, device=_device, dtype=torch.long)
mixup_lambdas: torch.Tensor = _adapted_rsampling((batch_size,), self.lambda_sampler, same_on_batch)
mixup_lambdas = mixup_lambdas * batch_probs
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index 02c97e158..d46741812 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -2065,6 +2065,35 @@ class TestHalfPrecisionPositionSamplers:
assert src[:, 0].tolist() == [[4.0] * ndim] * 2
+class TestIndexPermutationsInHalfPrecision:
+ # The ColorJiggle order and the MixUp pairs are index permutations, drawn as int64 whatever the sampling dtype.
+ # CUDA has no bfloat16 randperm, so a generator moved to bfloat16 -- directly, or by a container's or a model's
+ # .to() -- raised there; the CPU legs pin the dtype and the permutation. torch draws the same permutation for
+ # every dtype, so full-precision draws are unchanged.
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_color_jiggle_order_is_an_int64_permutation(self, device, half_dtype):
+ generator = ColorJiggleGenerator(0.1, 0.1, 0.1, 0.1)
+ generator.set_rng_device_and_dtype(device, half_dtype)
+ order = generator(torch.Size([2, 3, 4, 4]))["order"]
+ assert order.dtype == torch.int64
+ assert sorted(order.tolist()) == [0, 1, 2, 3]
+
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_mixup_pairs_are_an_int64_permutation(self, device, half_dtype):
+ generator = MixupGenerator(p=1.0)
+ generator.set_rng_device_and_dtype(device, half_dtype)
+ pairs = generator(torch.Size([5, 3, 4, 4]))["mixup_pairs"]
+ assert pairs.dtype == torch.int64
+ assert sorted(pairs.tolist()) == [0, 1, 2, 3, 4]
+
+ def test_full_precision_orders_are_unchanged(self):
+ # Recorded on CPU float32 with the generator's former float32 randperm: the int64 draw is the same.
+ generator = ColorJiggleGenerator(0.1, 0.1, 0.1, 0.1)
+ torch.manual_seed(0)
+ orders = [generator(torch.Size([2, 3, 4, 4]))["order"].tolist() for _ in range(5)]
+ assert orders == [[1, 0, 3, 2], [1, 3, 0, 2], [1, 0, 3, 2], [3, 2, 0, 1], [1, 2, 3, 0]]
+
+
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.