Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): prevent integer mask label rounding (#5711)

peng xiangc5e5da9e6c08
diff --git a/changelog.d/5711.breaking.md b/changelog.d/5711.breaking.md
new file mode 100644
index 000000000..dfa9d04b3
--- /dev/null
+++ b/changelog.d/5711.breaking.md
@@ -0,0 +1 @@
+`AugmentationSequential` processed a mask in its image's dtype, so integer labels above that dtype's exact range were silently rounded: `2049` became `2048` next to a float16 image. It now processes integer and boolean masks in at least float32 (float64 next to a float64 image), so their labels come back intact. A label that is not exactly representable even there (for example `2**24 + 1` next to a float32 or half-precision image) now raises `RuntimeError` instead of being rounded; remap the labels to smaller integers or use a float64 image where supported. Next to a float16 or bfloat16 image, a warped integer or boolean mask (rotation, affine, perspective, ...) is now resampled on a float32 grid, so it can differ from before at individual pixels; the half-precision resampling on CPU also picked wrong source pixels, including labels the mask does not contain. Floating masks keep the image's working dtype.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 7a15eabe1..bcc4c47a0 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -397,12 +397,14 @@ Augmentations
the image.
- Geometric children normally resample masks with nearest interpolation, so
labels are not blended, but padding can introduce its fill value. The container
- processes a mask in the dtype of the image it is working on (the most recent
+ processes a floating mask in the dtype of the image it is working on (the most recent
image argument before the mask, or the call's first image when the mask
- comes first) and returns it in the mask's own dtype, so
- integer labels outside that dtype's exact range change even through a flip:
- ``2049`` becomes ``2048`` in ``float16``
- (`#4478 <https://github.com/kornia/kornia/issues/4478>`_). A direct
+ comes first) and returns it in the mask's own dtype. Integer masks use at least
+ float32, or float64 with a float64 image, so half-precision images do not round
+ their class labels. Labels not exactly representable in that working dtype raise
+ ``RuntimeError``; remap them to smaller integers or use a float64 image where
+ supported. On accelerators the asynchronous assertion may report at the next
+ synchronization; MPS before torch 2.13 checks on the host. A direct
geometric ``transform_masks`` call requires a floating tensor.
- A list of masks is not a substitute for separate full-batch tensors: list
index ``i`` selects sample ``i``'s gate, so full-batch entries desynchronize
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 7ffdd39e3..b3fd30b6f 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -58,9 +58,9 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
Inverse resampling cannot recover image or mask information lost through cropping, padding, or
interpolation. Tensor-form boxes may lose rotated corners through axis-aligned enclosure.
For an empty batch, image and mask inverse restore the spatial dimensions recorded in the parameters.
- - container mask processing has dtype- and operator-specific limitations; see
- `#4478 <https://github.com/kornia/kornia/issues/4478>`_. Direct ``transform_masks`` calls use the
- image dtype guard and therefore reject ``bool`` masks.
+ - containers process integer masks in at least float32 and reject labels that cannot be represented
+ exactly in the working dtype. Direct ``transform_masks`` calls use the image dtype guard and therefore
+ reject ``bool`` masks.
- a subclass supplies its own :meth:`inverse_transform` -- the base raises ``NotImplementedError`` --
while :meth:`compute_inverse_transformation` defaults to inverting the sampled matrix.
- a scalar magnitude ``x`` means ``center Β± x``, as it does for the intensity classes: its lower end
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 90a81a0dc..93cc96ba4 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -306,7 +306,7 @@ class RandomCrop(GeometricAugmentationBase2D):
padding_size = params["padding_size"].unique(dim=0).cpu().squeeze().tolist()
if flags["cropping_mode"] == "resample" and isinstance(transform, torch.Tensor):
# Pixels are padded below; sample with the padded-canvas crop matrix.
- offset = self._padding_offset(input, params)
+ offset = self._padding_offset(input, params).to(transform)
if not (self.p == 1.0 and self.p_batch == 1.0):
# Only selected matrices include padding. Keep skipped rows as identity.
applied = torch.atleast_1d(params["batch_prob"] > 0.5).to(offset)
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index d91dc5f99..3355dfc14 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -27,10 +27,11 @@ from kornia.augmentation._3d.base import AugmentationBase3D, RigidAffineAugmenta
from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.utils.helpers import _boxes_to_padded_tensor
from kornia.constants import DataKey, Resample
+from kornia.core._compat import torch_version_lt
from kornia.core.external import PILImage as Image
from kornia.core.external import numpy as np
from kornia.core.ops import eye_like
-from kornia.core.utils import is_autocast_enabled, is_exporting
+from kornia.core.utils import _normalize_to_float32_or_float64, is_autocast_enabled, is_exporting
from kornia.geometry.boxes import Boxes, VideoBoxes
from kornia.geometry.keypoints import Keypoints, VideoKeypoints
from kornia.image.utils import image_to_tensor
@@ -147,15 +148,17 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
``x' = W - 1 - x`` and ``y' = H - 1 - y`` for every key, as :func:`~kornia.geometry.transform.hflip`
does. Labels pass through geometric steps untouched.
- masks are resampled with nearest interpolation by default (see ``extra_args``; padding can still add the
- fill value) in the image's working dtype and come back in their own dtype; integer labels that the
- working dtype cannot represent are rounded (`#4478 <https://github.com/kornia/kornia/issues/4478>`_).
+ fill value) and come back in their own dtype. Floating masks use the image's working dtype; integer
+ masks use at least float32 (float64 with a float64 image). Integer labels not exactly representable
+ in that working dtype raise ``RuntimeError`` instead of being rounded. On accelerators an asynchronous
+ assertion may report at the next synchronization; MPS before torch 2.13 checks on the host.
- a ``mask`` argument can be a list of tensors with different channel counts, but its batch handling
has limitations. Each list entry uses only ``batch_prob[i]`` as its gate, including for intensity
children. Per-sample list tensors are unsupported by warp operations, and full-batch tensors in that
list can become desynchronized from the image when the gate differs across samples. A list longer
than the batch raises ``IndexError``. Use separate ``mask`` data keys for separate full-batch masks.
``.inverse()`` takes the list the forward pass returned and inverts it element by element with the
- same per-entry gate. A flip round-trips each entry, subject to the working-dtype rounding above; other
+ same per-entry gate. A flip round-trips each entry, subject to the working-dtype requirements above; other
warps lose the pixels they move out of the frame and, when they resample, restore the rest only
approximately. Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.
- the ``mask``, box and ``keypoints`` handlers of a geometric child, or of a custom
@@ -909,8 +912,36 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
working = dtype if dtype is not None else torch.float
if isinstance(arg, list):
# A list keeps its per-entry gate semantics (see the class docstring); it is not broadcast.
- return [a.to(working) for a in arg]
- return self._broadcast_single_mask(arg.to(working), image_batch)
+ return [self._cast_mask(a, working) for a in arg]
+ return self._broadcast_single_mask(self._cast_mask(arg, working), image_batch)
+
+ @staticmethod
+ def _cast_mask(mask: torch.Tensor, dtype: torch.dtype) -> torch.Tensor:
+ """Convert masks without silently rounding integer class labels."""
+ if not mask.is_floating_point():
+ dtype = _normalize_to_float32_or_float64(dtype)
+ converted = mask.to(dtype)
+ # Smaller integer types (and bool) are exactly representable in float32. For wider types, even float64
+ # cannot represent every int64 label, so check the actual round trip instead of a conservative bound.
+ if mask.dtype in (torch.int32, torch.int64, torch.uint32, torch.uint64):
+ limits = torch.iinfo(mask.dtype)
+ # The exclusive upper bound is an exact power of two. limits.max itself can round up to that bound.
+ # The minimum is exact too, so integer-to-float conversion cannot round below it. Replace overflow
+ # with zero before casting back: an overflowing positive label cannot equal zero, and casting an
+ # out-of-range float to an integer has undefined behavior even when it happens to match the input.
+ safe = torch.where(converted < float(limits.max + 1), converted, 0.0)
+ exact = (safe.to(mask.dtype) == mask).all()
+ message = (
+ f"Integer mask labels must be exactly representable in {dtype}. "
+ "Use a float64 image where supported or remap labels to smaller integers."
+ )
+ if mask.device.type == "mps" and torch_version_lt(2, 13, 0):
+ # Older MPS has no asynchronous assertion kernel. Do not skip a correctness check there.
+ if not bool(exact):
+ raise RuntimeError(message)
+ else:
+ torch._assert_async(exact, message)
+ return converted
@staticmethod
def _broadcast_single_mask(mask: torch.Tensor, image_batch: Optional[int]) -> torch.Tensor:
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 791b8616a..01f49bc7e 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -32,7 +32,7 @@ from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import resize
from testing.augmentation.utils import reproducibility_test
-from testing.base import BaseTester, assert_close
+from testing.base import BaseTester, assert_close, supports_bilinear_2d_grid_sample
class TestAugmentationSequential:
@@ -1849,15 +1849,120 @@ class TestConventionAugmentationSequential(BaseTester):
with pytest.raises(NotImplementedError, match="3d inverse"):
geometric.inverse(geometric(image))
- def test_wart_integer_masks_round_through_image_dtype_4478(self, device, dtype):
- first_inexact = {torch.bfloat16: 257, torch.float16: 2049, torch.float32: 2**24 + 1, torch.float64: 2**53 + 1}
- label = first_inexact[dtype]
- image = torch.ones(1, 1, 2, 2, device=device, dtype=dtype)
+ @pytest.mark.parametrize("as_list", [False, True])
+ @pytest.mark.parametrize("operation", ["flip", "resize", "affine"])
+ def test_convention_integer_mask_labels_survive_4478(self, as_list, operation, device, dtype):
+ if operation == "affine" and not supports_bilinear_2d_grid_sample(device, dtype):
+ pytest.skip("The image path requires bilinear grid_sample for the selected dtype.")
+ image = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)
+ mask = torch.tensor([0, 257, 2049, 26001, -2049, 65535], device=device).reshape(1, 1, 2, 3)
+ children = {
+ "flip": K.RandomHorizontalFlip(p=1.0),
+ "resize": K.Resize((4, 6)),
+ "affine": K.RandomAffine(degrees=(0.0, 0.0), p=1.0),
+ }
+ seq = K.AugmentationSequential(children[operation], data_keys=["input", "mask"])
+ expected = mask.flip(-1) if operation == "flip" else mask
+ if operation == "resize":
+ expected = mask.repeat_interleave(2, -2).repeat_interleave(2, -1)
+ output = seq(image, [mask] if as_list else mask)[1]
+ output = output[0] if as_list else output
+ assert output.dtype == mask.dtype
+ assert torch.equal(output, expected)
+ if operation == "flip":
+ inverse = seq.inverse(*seq(image, [mask] if as_list else mask))[1]
+ inverse = inverse[0] if as_list else inverse
+ assert torch.equal(inverse, mask)
+
+ def test_convention_inexact_integer_mask_labels_raise_4478(self, dtype):
+ # CPU assertions report immediately; invalid asynchronous accelerator assertions can poison the stream.
+ working = torch.float64 if dtype == torch.float64 else torch.float32
+ label = 2**53 + 1 if working == torch.float64 else 2**24 + 1
+ image = torch.ones(1, 1, 2, 2, dtype=dtype)
mask = torch.full_like(image, label, dtype=torch.int64)
seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
- output = seq(image, mask)[1]
- assert output.dtype == torch.int64
- assert torch.equal(output, torch.full_like(mask, label - 1))
+ with pytest.raises(RuntimeError, match=r"Integer mask labels.*exactly representable"):
+ seq(image, mask)
+
+ @pytest.mark.parametrize("mask_dtype", [torch.int32, torch.uint32, torch.int64, torch.uint64])
+ def test_integer_mask_boundary_labels_4478(self, dtype, mask_dtype):
+ # Keep invalid assertions on CPU: accelerator assertion failures can poison the stream.
+ limits = torch.iinfo(mask_dtype)
+ precision = 53 if dtype == torch.float64 else 24
+ exponent = limits.bits - int(limits.min < 0)
+ # The largest representable integer below 2**exponent has spacing 2**(exponent - precision).
+ last_exact = limits.max if exponent <= precision else 2**exponent - 2 ** (exponent - precision)
+ image = torch.ones(1, 1, 2, 2, dtype=dtype)
+ mask = torch.tensor([limits.min, last_exact, 0, limits.min], dtype=mask_dtype).reshape_as(image)
+ expected = torch.tensor([last_exact, limits.min, limits.min, 0], dtype=mask_dtype).reshape_as(image)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ assert torch.equal(seq(image, mask)[1], expected)
+ if exponent > precision:
+ with pytest.raises(RuntimeError, match=r"Integer mask labels.*exactly representable"):
+ seq(image, torch.full_like(mask, limits.max))
+
+ @pytest.mark.parametrize("mask_dtype", [torch.bool, torch.uint8, torch.int16, torch.int32, torch.int64])
+ def test_integer_mask_partial_gate_and_replay_4478(self, mask_dtype, device, dtype):
+ labels = [0, 1, 2] if mask_dtype in (torch.bool, torch.uint8) else [257, -2049, 26001]
+ mask = torch.tensor(labels, device=device, dtype=mask_dtype).reshape(1, 1, 1, 3).repeat(2, 1, 2, 1)
+ image = torch.ones(2, 1, 2, 3, device=device, dtype=dtype)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ seq(image, mask)
+ params = seq._params
+ params[0].data["batch_prob"] = torch.tensor([1.0, 0.0], device=device, dtype=dtype)
+ expected = mask.clone()
+ expected[0] = mask[0].flip(-1)
+ output = seq(image, mask, params=params)[1]
+ assert output.dtype == mask_dtype
+ assert torch.equal(output, expected)
+ replay = seq(mask, params=params, data_keys=["mask"])
+ assert torch.equal(replay, expected)
+
+ def test_integer_masks_keep_labels_under_autocast_4478(self):
+ image = torch.ones(1, 1, 2, 3)
+ mask = torch.tensor([0, 257, 2049, 26001, -2049, 65535]).reshape(1, 1, 2, 3)
+ seq = K.AugmentationSequential(K.RandomAffine(degrees=(0.0, 0.0), p=1.0), data_keys=["input", "mask"])
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ output = seq(image, mask)[1]
+ assert torch.equal(output, mask)
+
+ def test_integer_mask_cast_dynamo_4478(self, device, dtype, torch_optimizer):
+ # Exercise the dtype conversion and validation with a real fullgraph compiler, without RNG capture.
+ mask = torch.tensor([0, 257, 2049, 26001], device=device).reshape(1, 1, 2, 2)
+ op = partial(K.AugmentationSequential._cast_mask, dtype=dtype)
+ compiled = torch_optimizer(op, fullgraph=True)
+ self.assert_close(compiled(mask), op(mask), atol=0, rtol=0)
+ if device.type == "cpu":
+ label = 2**53 + 1 if dtype == torch.float64 else 2**24 + 1
+ for invalid in (label, torch.iinfo(torch.int64).max):
+ with pytest.raises(RuntimeError, match="Integer mask labels"):
+ compiled(torch.full_like(mask, invalid))
+
+ def test_integer_mask_float64_accepts_larger_exact_labels_4478(self):
+ image = torch.ones(1, 1, 2, 2, dtype=torch.float64)
+ mask = torch.tensor([2**24 + 1, -(2**24 + 1), 2**53, -(2**53)]).reshape(1, 1, 2, 2)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ assert torch.equal(seq(image, mask)[1], mask.flip(-1))
+
+ @pytest.mark.parametrize("padding", [0, 2])
+ @pytest.mark.parametrize("half", [torch.float16, torch.bfloat16])
+ def test_integer_mask_resample_crop_next_to_a_half_image_4478(self, half, padding, device):
+ # The integer mask works in float32 and the crop matrix comes from the half-precision image: the resample
+ # crop must combine them in one dtype and still cut the labels out exactly.
+ if not supports_bilinear_2d_grid_sample(device, half):
+ pytest.skip("The image path requires bilinear grid_sample for the selected dtype.")
+ image = torch.ones(2, 1, 8, 10, device=device, dtype=half)
+ mask = (torch.arange(160, device=device) * 9 + 2049).reshape(2, 1, 8, 10)
+ crop = K.RandomCrop((5, 6), padding=padding, cropping_mode="resample", p=1.0)
+ seq = K.AugmentationSequential(crop, data_keys=["input", "mask"])
+
+ out_image, out_mask = seq(image, mask)
+
+ padded = torch.nn.functional.pad(mask, [padding] * 4)
+ for sample, corner in zip(range(2), seq._params[0].data["src"][:, 0].long().tolist()):
+ x0, y0 = corner
+ assert torch.equal(out_mask[sample], padded[sample, :, y0 : y0 + 5, x0 : x0 + 6])
+ assert seq.inverse(out_image, out_mask)[1].dtype == mask.dtype
@pytest.mark.parametrize("mask_dtype", [None, torch.int64, torch.bool])
def test_convention_empty_batch_with_mask_4478(self, mask_dtype, device, dtype):
diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.py
index b5690e875..157da5119 100644
--- a/tests/augmentation/test_torch_export.py
+++ b/tests/augmentation/test_torch_export.py
@@ -186,3 +186,23 @@ def test_torch_export_mask_uses_the_call_image_dtype_4478(case: str) -> None:
mask = get_mask(exported.module()(*args))
assert mask.dtype == torch.float64
assert torch.equal(mask, expected), f"{case}: {mask.flatten().tolist()} vs {expected.flatten().tolist()}"
+
+
[email protected](not hasattr(torch, "export"), reason="torch.export requires torch>=2.1")
[email protected](not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
[email protected](not _HAS_TORCH_EXPORT_TRACKING, reason=_TORCH_EXPORT_TRACKING_REASON)
[email protected]("image_dtype", [torch.float16, torch.bfloat16, torch.float32, torch.float64])
+def test_torch_export_integer_mask_labels_4478(image_dtype: torch.dtype) -> None:
+ """Export retains both the integer label precision and the exact-representability assertion."""
+ image = torch.ones(1, 1, 2, 2, dtype=image_dtype)
+ mask = torch.tensor([257, 2049, 26001, -2049]).reshape(1, 1, 2, 2)
+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])
+ exported = torch.export.export(seq, (image, mask)).module()
+ output = exported(image, mask)[1]
+ assert output.dtype == mask.dtype
+ assert torch.equal(output, mask.flip(-1))
+ label = 2**53 + 1 if image_dtype == torch.float64 else 2**24 + 1
+ for invalid in (label, torch.iinfo(torch.int64).max):
+ with pytest.raises(RuntimeError, match="Integer mask labels"):
+ exported(image, torch.full_like(mask, invalid))