Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): add bfloat16 support to mix augmentations (#4467) (#4471)

msparsh13956cad88f8b0
diff --git a/README.md b/README.md
index 5511fe1c5..5434a3247 100644
--- a/README.md
+++ b/README.md
@@ -96,7 +96,7 @@ covers CUDA or MPS half precision.
| `kornia.filters` | ⚠️ | ⚠️ | 18 / 9 | Accuracy misses in Canny magnitudes, discrete Gaussian kernels and Otsu; on CPU `fft_conv` runs its FFTs in float32 |
| `kornia.enhance` | ✅ | ⚠️ | 0 / 2 | bfloat16: `DiffJPEG` and ZCA accuracy |
| `kornia.morphology` | ✅ | ✅ | 0 / 0 | |
-| `kornia.augmentation` | ⚠️ | ⚠️ | 205 / 83 | float16: 108 entries are `CutmixGenerator`, whose Dirichlet sampling rejects float16 parameters; bfloat16: `RandomJigsaw`, `RandomCutMixV2`, `RandomMixUpV2` and `RandomMosaic` raise `KeyError: 'BFLOAT16'` ([#4467](https://github.com/kornia/kornia/issues/4467)) |
+| `kornia.augmentation` | ⚠️ | ⚠️ | 200 / 56 | float16: 108 entries are `CutmixGenerator`, whose Dirichlet sampling rejects float16 parameters; bfloat16: mostly 3D-augmentation gradient checks (28 of 56 entries are `RandomMotionBlur3D`/`RandomRotation3D` backward) |
| `kornia.geometry.transform` | ⚠️ | ⚠️ | 43 / 58 | Accuracy misses in rotation matrices, affine/perspective warps, the homography warper and 3D crops |
| `kornia.geometry.camera` | ⚠️ | ⚠️ | 13 / 23 | Pinhole `cam2pixel`/`pixel2cam` consistency, distortion round trips, `StereoCamera` reprojection; 12 bfloat16 entries are a test-side dtype assertion |
| `kornia.geometry.calibration` | ⚠️ | ⚠️ | 13 / 12 | `solve_pnp_dlt` rejects half inputs (float32/float64 only); `undistort_points` misses its OpenCV reference values |
diff --git a/changelog.d/4471.fixed.md b/changelog.d/4471.fixed.md
new file mode 100644
index 000000000..84f2ebc7b
--- /dev/null
+++ b/changelog.d/4471.fixed.md
@@ -0,0 +1 @@
+Add bfloat16 support to mix augmentations and preserve input half-precision dtypes in MixUp and CutMix.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index f6a1578b0..1d6dc54aa 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -47,11 +47,11 @@ precision, so the table says nothing about those backends.
* - ``kornia.augmentation``
- ⚠️ Partial
- ⚠️ Partial
- - 205 / 83
+ - 200 / 56
- float16: 108 entries are ``CutmixGenerator``, whose Dirichlet sampling rejects float16 parameters; most
of the rest are ``VideoSequential`` / ``AugmentationSequential`` and 3D-augmentation gradient checks.
- bfloat16: ``RandomJigsaw``, ``RandomCutMixV2``, ``RandomMixUpV2`` and ``RandomMosaic`` raise
- ``KeyError: 'BFLOAT16'`` (`issue #4467 <https://github.com/kornia/kornia/issues/4467>`_).
+ bfloat16: mostly 3D-augmentation gradient checks (28 of 56 entries are ``RandomMotionBlur3D`` /
+ ``RandomRotation3D`` backward).
* - ``kornia.geometry.transform``
- ⚠️ Partial
- ⚠️ Partial
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index ff3fdbbb0..d29fda88b 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -82,8 +82,7 @@ class AugmentationBase2D(_AugmentationBase):
and an ``(H, W)`` input to ``(1, 1, H, W)``; ``keepdim=True`` restores the input rank on the way out
and never drops a real batch dimension. The dtype guard accepts ``float16``, ``bfloat16``, ``float32``
and ``float64`` and raises ``TypeError`` naming those four on an integer tensor. The output keeps the
- input's device. Individual augmentations may have dtype-specific behavior; see their own docs and
- `#4467 <https://github.com/kornia/kornia/issues/4467>`_.
+ input's device. Individual augmentations may have dtype-specific behavior; see their own docs.
- unsupported ranks and container entry points report validation errors through different paths.
Tracked in `#4424 <https://github.com/kornia/kornia/issues/4424>`_.
- this base samples ``p`` per sample and uses ``p_batch`` as a call-wide gate. ``same_on_batch=True``
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index b38741ded..ec3078314 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -121,11 +121,12 @@ class RandomCutMixV2(MixAugmentationBaseV2):
height, width = params["image_shape"]
out_labels = []
+ calc_dtype = input.dtype if input.dtype in (torch.float32, torch.float64) else torch.float32
for pair, crop in zip(params["mix_pairs"], params["crop_src"]):
labels_permute = input.index_select(dim=0, index=pair.to(input.device))
w, h = infer_bbox_shape(crop)
- lam_val = w.to(input.dtype) * h.to(input.dtype) / (width * height)
+ lam_val = w.to(calc_dtype) * h.to(calc_dtype) / (width * height)
lam = 1 - lam_val if self.use_correct_lambda else lam_val
out_labels.append(
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index 914890dee..d44be0a43 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -110,7 +110,7 @@ class RandomMixUpV2(MixAugmentationBaseV2):
) -> torch.Tensor:
input_permute = input.index_select(dim=0, index=params["mixup_pairs"].to(input.device))
- lam = params["mixup_lambdas"].view(-1, 1, 1, 1).expand_as(input).to(input.device)
+ lam = params["mixup_lambdas"].view(-1, 1, 1, 1).expand_as(input).to(input.device, dtype=input.dtype)
inputs = input * (1 - lam) + input_permute * lam
return inputs
diff --git a/kornia/constants.py b/kornia/constants.py
index 1ced39b1a..afaf39965 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -108,6 +108,7 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):
FLOAT16 = 1
FLOAT32 = 2
FLOAT64 = 3
+ BFLOAT16 = 4
@classmethod
def get(cls, value: Union[str, int, torch.dtype, torch.Tensor, "DType"]) -> "DType":
@@ -144,6 +145,9 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):
elif data == DType.FLOAT64:
return torch.float64
+ elif data == DType.BFLOAT16:
+ return torch.bfloat16
+
raise ValueError
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index eaed77eb4..fda2fe84b 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -26,33 +26,6 @@ call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandom
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomRGBShift::test_random_rgb_shift[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomRGBShift::test_random_rgb_shift_same_batch[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomSaturation::test_sequential[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_partial_batch_passthrough[cpu-bfloat16-0.0]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_partial_batch_passthrough[cpu-bfloat16-0.5]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_random_mixup_beta0[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_random_mixup_num2[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_random_mixup_p0[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_random_mixup_p1[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_random_mixup_same_on_batch[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_numerical[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_p[cpu-bfloat16-False-0.0]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_p[cpu-bfloat16-False-0.5]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_p[cpu-bfloat16-False-1.0]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_p[cpu-bfloat16-True-0.0]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_p[cpu-bfloat16-True-0.5]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_p[cpu-bfloat16-True-1.0]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_partial_batch_passthrough[cpu-bfloat16-0.0]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_partial_batch_passthrough[cpu-bfloat16-0.5]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomJigsaw::test_smoke[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_partial_batch_passthrough[cpu-bfloat16-0.0]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_partial_batch_passthrough[cpu-bfloat16-0.5]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_random_mixup_lam0[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_random_mixup_p0[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_random_mixup_p1[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_random_mixup_same_on_batch[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMosaic::test_numerical[cpu-bfloat16]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMosaic::test_p[cpu-bfloat16-0.0]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMosaic::test_p[cpu-bfloat16-0.5]
-call builtins.KeyError tests/augmentation/test_augmentation_mix.py::TestRandomMosaic::test_p[cpu-bfloat16-1.0]
call builtins.AssertionError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[cpu-bfloat16-False-bilinear-circular-direction0-angle1]
call builtins.AssertionError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[cpu-bfloat16-False-bilinear-circular-direction0-angle2]
call builtins.AssertionError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[cpu-bfloat16-False-bilinear-circular-direction1-angle1]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 7135ab91a..0b9d2f5d5 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -30,6 +30,7 @@ call builtins.RuntimeError tests/augmentation/container/test_patch_sequential.py
call builtins.AssertionError tests/augmentation/container/test_sequential_aug.py::TestSequential::test_forward[cpu-float16-10]
call builtins.AssertionError tests/augmentation/container/test_sequential_aug.py::TestSequential::test_forward[cpu-float16-False]
call builtins.AssertionError tests/augmentation/container/test_sequential_aug.py::TestSequential::test_forward[cpu-float16-True]
+call builtins.AssertionError tests/augmentation/container/test_sequential_aug.py::TestSequential::test_forward[cpu-float16-random_apply3]
call builtins.AssertionError tests/augmentation/container/test_video_sequential.py::TestVideoSequential::test_against_sequential[cpu-float16-BCTHW-augmentations2]
call builtins.AssertionError tests/augmentation/container/test_video_sequential.py::TestVideoSequential::test_against_sequential[cpu-float16-BTCHW-augmentations2]
call builtins.RuntimeError tests/augmentation/container/test_video_sequential.py::TestVideoSequential::test_autocast[cpu-float16-BCTHW]
@@ -62,12 +63,6 @@ call builtins.AssertionError tests/augmentation/test_augmentation.py::TestPlanck
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomGaussianIllumination::test_smoke[cpu-float16]
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomRGBShift::test_random_rgb_shift[cpu-float16]
call builtins.AssertionError tests/augmentation/test_augmentation.py::TestRandomRGBShift::test_random_rgb_shift_same_batch[cpu-float16]
-call builtins.AssertionError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_random_mixup_beta0[cpu-float16]
-call builtins.AssertionError tests/augmentation/test_augmentation_mix.py::TestRandomCutMixV2::test_random_mixup_num2[cpu-float16]
-call builtins.AssertionError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_random_mixup_lam0[cpu-float16]
-call builtins.AssertionError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_random_mixup_p1[cpu-float16]
-call builtins.AssertionError tests/augmentation/test_augmentation_mix.py::TestRandomMixUpV2::test_random_mixup_same_on_batch[cpu-float16]
-call builtins.AssertionError tests/augmentation/test_augmentation_mix.py::TestRandomMosaic::test_numerical[cpu-float16]
call builtins.AssertionError tests/augmentation/test_auto_operation.py::TestAutoAugment::test_reproduce[cpu-float16]
call builtins.AssertionError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[cpu-float16-False-bilinear-circular-direction0-angle1]
call builtins.AssertionError tests/augmentation/test_backward_3d.py::TestRandomMotionBlur3DBackward::test_param[cpu-float16-False-bilinear-circular-direction0-angle2]
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 9fc573a88..808a89e79 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -740,8 +740,6 @@ class TestConventionAugmentationSequential(BaseTester):
# passthrough, so annotations desynchronized from the mixed image. The container now dispatches to
# the child's own handlers: RandomMosaic transforms boxes (container xyxy_plus path), and unsupported
# keys raise NotImplementedError as a direct call does. A class key still raises from the container.
- if dtype == torch.bfloat16:
- pytest.skip("Tracked in #4467: the mix forward path has no bfloat16 DType")
from kornia.geometry.boxes import Boxes
image = torch.rand(2, 3, 16, 16, device=device, dtype=dtype)
diff --git a/tests/augmentation/test_augmentation_mix.py b/tests/augmentation/test_augmentation_mix.py
index eb96b0ed0..fd551907e 100644
--- a/tests/augmentation/test_augmentation_mix.py
+++ b/tests/augmentation/test_augmentation_mix.py
@@ -29,6 +29,7 @@ from kornia.augmentation import (
RandomTransplantation,
RandomTransplantation3D,
)
+from kornia.geometry.bbox import infer_bbox_shape
from testing.base import BaseTester
@@ -58,10 +59,15 @@ class TestRandomMixUpV2(BaseTester):
out_image, out_label = f(input, label)
+ if dtype == torch.float16:
+ rtol, atol = 1e-3, 1e-3
+ else:
+ rtol, atol = 1e-4, 1e-4
+
self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
self.assert_close(out_label[:, 0], label)
self.assert_close(out_label[:, 1], torch.tensor([0, 1], device=device, dtype=dtype))
- self.assert_close(out_label[:, 2], lam, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_label[:, 2], lam, rtol=rtol, atol=atol)
def test_random_mixup_p0(self, device, dtype):
torch.manual_seed(0)
@@ -298,6 +304,28 @@ class TestRandomCutMixV2(BaseTester):
if untouched.any():
self.assert_close(output[untouched], input[untouched])
+ def test_random_cutmix_float64_lambda(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+
+ torch.manual_seed(76)
+ f = RandomCutMixV2(p=1.0, data_keys=["input", "class"])
+
+ input = torch.stack(
+ [
+ torch.ones(1, 15, 17, device=device, dtype=torch.float64),
+ torch.zeros(1, 15, 17, device=device, dtype=torch.float64),
+ ]
+ )
+ label = torch.tensor([1, 0], device=device, dtype=torch.float64)
+
+ _, out_label = f(input, label)
+
+ w, h = infer_bbox_shape(f._params["crop_src"][0])
+ expected_lambda = w.to(torch.float64) * h.to(torch.float64) / (15 * 17)
+
+ self.assert_close(out_label[0, :, 2], expected_lambda, rtol=0.0, atol=0.0)
+
class TestRandomMosaic(BaseTester):
def test_non_square_input_preserves_hw_4438(self):
@@ -413,9 +441,13 @@ class TestRandomMosaic(BaseTester):
device=device,
dtype=dtype,
)
+ if dtype in (torch.float16, torch.bfloat16):
+ rtol, atol = 1e-2, 5e-2
+ else:
+ rtol, atol = 1e-4, 1e-4
self.assert_close(out_image, expected, rtol=1e-4, atol=1e-4)
- self.assert_close(out_box, expected_box, rtol=1e-4, atol=1e-4)
+ self.assert_close(out_box, expected_box, rtol=rtol, atol=atol)
@pytest.mark.parametrize("p", [0.0, 0.5, 1.0])
def test_p(self, p, device, dtype):
diff --git a/tests/augmentation/test_base.py b/tests/augmentation/test_base.py
index cc44fbd45..170722efc 100644
--- a/tests/augmentation/test_base.py
+++ b/tests/augmentation/test_base.py
@@ -404,9 +404,6 @@ class TestDeviceAgnosticAugmentationParameters(BaseTester):
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)