π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): keep each container mask in its own dtype (#4665)
abhijeet sharma626707fe140e
diff --git a/changelog.d/4665.breaking.md b/changelog.d/4665.breaking.mdnew file mode 100644index 000000000..cec3e14ba--- /dev/null+++ b/changelog.d/4665.breaking.md@@ -0,0 +1,5 @@+`AugmentationSequential` no longer converts every mask output to one shared dtype. Previously all mask outputs of a+call were cast to the dtype of the last mask argument, so a boolean mask passed before a `float32` mask came back as+`float32`; it now comes back as `bool`, like every other mask that keeps its own argument's dtype. Code that did+arithmetic on such an output (for example `1 - mask`, which raises for `bool` tensors) must convert it explicitly,+e.g. `mask.float()`.diff --git a/changelog.d/4665.fixed.md b/changelog.d/4665.fixed.mdnew file mode 100644index 000000000..1baba45b4--- /dev/null+++ b/changelog.d/4665.fixed.md@@ -0,0 +1,6 @@+`AugmentationSequential` returns each mask in the dtype of its own argument. It used to cast every mask output to the+dtype of the last mask argument, so an integer semantic mask followed by a boolean one came back boolean and lost its+labels. An empty batch with a mask no longer raises `IndexError`, and a mask placed before the image in dictionary+insertion order is now converted with that call's image dtype instead of the previous call's, so a float64 mask keeps+its precision. The same holds under `torch.export`, which used to convert masks through `float32` or a dtype left+behind by an earlier eager call and bake the rounding into the exported graph.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex f40bb6508..0dfc26b51 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -276,23 +276,23 @@ Augmentationszero.- The geometric mask path normally uses nearest interpolation. That avoidsinterpolating labels, but padding can still introduce its fill value.-- Put the image before masks, including in dictionary insertion order, so- conversion uses its working dtype. Earlier masks use the previous image- dtype, or ``float32`` on a fresh container. Integer labels outside the- working dtype's exact range can change even through a flip; for example,- ``2049`` becomes ``2048`` in ``float16``. Every output mask is cast to the- last mask argument's dtype (its first element's dtype for a list).- A common mask dtype avoids that cross-mask conversion, but does not prevent- precision loss during processing. Empty batches with masks can also raise- (`#4478 <https://github.com/kornia/kornia/issues/4478>`_). Direct geometric- ``transform_masks`` calls require floating tensors; the container converts- integer and boolean masks around those calls.+- Masks are processed in the image working dtype: that of the most recent+ image argument before the mask, or of the call's first image when none+ precedes it, which can happen in dictionary insertion order. Integer labels+ outside the working dtype's exact range can change even through a flip; for+ example, ``2049`` becomes ``2048`` in ``float16``+ (`#4478 <https://github.com/kornia/kornia/issues/4478>`_). Each output mask+ comes back in the dtype of its own argument, per element for a list,+ ``bool`` included, so masks of different dtypes do not affect each other.+ An empty batch with a mask is accepted. Direct geometric ``transform_masks``+ calls require floating tensors; the container converts integer and boolean+ masks around those calls.- Mask lists are not a reliable replacement for separate full-batch tensors.Direct augmentation children use list index ``i`` to select a sample'sgate. Full-batch entries can therefore become desynchronized under mixedgates; per-sample entries can fail in warps or reuse the wrong crop window.- Prefer separate ``mask`` keys with a common dtype, subject to the precision- and filtering limitations above+ Prefer separate ``mask`` keys, subject to the precision and filtering+ limitations above(`#4477 <https://github.com/kornia/kornia/issues/4477>`_).- Boxes use the inclusive ``xyxy_plus`` convention of:class:`kornia.geometry.boxes.Boxes` (see *Bounding boxes* above). Flips usediff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 475f5b06c..1ff298603 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -132,22 +132,19 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):the mask, the keypoints and all three box spellings alike, and ``bbox_xywh`` keeps its ``w`` and``h``. Labels are passed through untouched by a geometric step.- mask resampling normally uses nearest interpolation, but this does not guarantee label preservation:- padding can introduce a fill value.- Put the image before the masks, including- in dictionary insertion order, so mask conversion uses that image's working dtype. Masks preceding- the image use the previous call's image dtype, or ``float32`` on a fresh container. The container- casts every mask output to the last mask argument's dtype (the first- element's dtype if that argument is a list). A single mask or masks with a common dtype therefore- keep that dtype, ``bool`` included. Conversion through the image working dtype can round integer- labels that dtype cannot represent exactly, and mixed mask dtypes can lose labels, for example when a- final boolean mask makes an integer semantic mask boolean too. Tracked in- `#4478 <https://github.com/kornia/kornia/issues/4478>`_.+ padding can introduce a fill value. Masks are converted to the image working dtype: that of the most+ recent image argument before the mask, or of the call's first image when none precedes it, which can+ happen in dictionary insertion order (a list ``data_keys`` must start with the image). Each mask output+ comes back in the dtype of its own argument (per element for a list), ``bool`` included, so masks of+ different dtypes do not affect each other. The conversion through the image working dtype can still+ round integer labels that dtype cannot represent exactly, for example ``2049`` through ``float16``.+ Tracked in `#4478 <https://github.com/kornia/kornia/issues/4478>`_.- a ``mask`` argument can be a list of tensors with different channel counts, but its batch handlinghas limitations. Each list entry uses only ``batch_prob[i]`` as its gate, including for intensitychildren. Per-sample list tensors are unsupported by warp operations, and full-batch tensors in thatlist 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 with a common dtype for- separate full-batch masks. Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.+ than the batch raises ``IndexError``. Use separate ``mask`` data keys for separate full-batch masks.+ Tracked in `#4477 <https://github.com/kornia/kornia/issues/4477>`_.- supported geometric data-key handlers share the recorded transform, subject to the mask limitationsabove. Custom rigid subclasses are not dispatched solely because they supply a matrix(`#4481 <https://github.com/kornia/kornia/issues/4481>`_). A non-rigid child has no transform matrix,@@ -471,21 +468,37 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):# TODO: validate args batching, and its consistencydef _arguments_preproc(self, *args: DataType, data_keys: List[DataKey]) -> List[DataType]:+ # Resolve this call's image dtype before any mask is converted, so a mask that precedes the image in+ # dictionary insertion order uses it too, rather than the previous call's image dtype (or ``float32`` on+ # a fresh container). It is kept in a local rather than read back from ``self.input_dtype``, so the same+ # conversion happens under ``torch.export``, where that attribute is deliberately left untouched. Masks+ # after an image use the most recent image, as before; a call with no image falls back to the attribute.+ working_dtype = self.input_dtype+ for arg, dcate in zip(args, data_keys):+ if DataKey.get(dcate) in _IMG_OPTIONS:+ working_dtype = cast(torch.Tensor, arg).dtype+ breakinp: List[DataType] = []for arg, dcate in zip(args, data_keys):if DataKey.get(dcate) in _IMG_OPTIONS:arg = cast(torch.Tensor, arg)+ working_dtype = arg.dtypeif not is_exporting():self.input_dtype = arg.dtypeinp.append(arg)elif DataKey.get(dcate) in _MSK_OPTIONS:- if isinstance(inp, list):- arg = cast(List[torch.Tensor], arg)- self.mask_dtype = arg[0].dtype- else:- arg = cast(torch.Tensor, arg)- self.mask_dtype = arg.dtype- inp.append(self._preproc_mask(arg))+ # Output dtypes are read back per argument in ``_arguments_postproc``; ``mask_dtype`` only records+ # the last mask's dtype for callers that read the attribute. The test is on ``arg``: it used to be+ # on the accumulator ``inp``, which is always a list, so a tensor mask was indexed at ``arg[0]``+ # and an empty batch raised ``IndexError``. Like ``input_dtype``, the attribute is not written under+ # ``torch.export``: creating an instance attribute during capture fails the export on torch 2.9.+ if not is_exporting():+ if isinstance(arg, list):+ if len(arg) > 0:+ self.mask_dtype = arg[0].dtype+ else:+ self.mask_dtype = cast(torch.Tensor, arg).dtype+ inp.append(self._preproc_mask(arg, working_dtype))elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:inp.append(self._preproc_keypoints(arg, dcate))elif DataKey.get(dcate) in _BOXES_OPTIONS:@@ -506,7 +519,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):out.append(out_arg)# TODO: may add the float to integer (for masks), etc.elif DataKey.get(dcate) in _MSK_OPTIONS:- _out_m = self._postproc_mask(cast(MaskDataType, out_arg))+ _out_m = self._postproc_mask(cast(MaskDataType, out_arg), cast(MaskDataType, in_arg))out.append(_out_m)elif DataKey.get(dcate) in _KEYPOINTS_OPTIONS:@@ -697,25 +710,23 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):return valid_data_keys, invalid_keys- def _preproc_mask(self, arg: MaskDataType) -> MaskDataType:+ def _preproc_mask(self, arg: MaskDataType, dtype: Optional[torch.dtype]) -> MaskDataType:+ # ``dtype`` is the calling image's working dtype, resolved by ``_arguments_preproc``; ``float32`` when the+ # call has no image and no earlier call recorded one.+ working = dtype if dtype is not None else torch.floatif isinstance(arg, list):- new_arg = []- for a in arg:- a_new = a.to(self.input_dtype) if self.input_dtype else a.to(torch.float)- new_arg.append(a_new)- return new_arg-- return arg.to(self.input_dtype) if self.input_dtype else arg.to(torch.float)+ return [a.to(working) for a in arg]+ return arg.to(working)- def _postproc_mask(self, arg: MaskDataType) -> MaskDataType:+ def _postproc_mask(self, arg: MaskDataType, like: MaskDataType) -> MaskDataType:+ # Each mask output goes back to the dtype of its own argument, per element for a list. A single shared+ # dtype would cast every mask to whichever mask came last: an integer semantic mask followed by a boolean+ # one came back boolean, and its labels collapsed to ``True``.if isinstance(arg, list):- new_arg = []- for a in arg:- a_new = a.to(self.mask_dtype) if self.mask_dtype else a.to(torch.float)- new_arg.append(a_new)- return new_arg-- return arg.to(self.mask_dtype) if self.mask_dtype else arg.to(torch.float)+ likes = like if isinstance(like, list) else [like] * len(arg)+ return [a.to(ref.dtype) for a, ref in zip(arg, likes)]+ ref = like[0] if isinstance(like, list) else like+ return arg.to(ref.dtype)def _preproc_boxes(self, arg: DataType, dcate: DataKey) -> Boxes:if DataKey.get(dcate) in [DataKey.BBOX]:diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 78ed3e035..34c45822b 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -830,30 +830,53 @@ class TestConventionAugmentationSequential(BaseTester):image, torch.tensor([0, 1], device=device))- def test_wart_dictionary_mask_before_image_loses_float64_precision_4478(self):- # On a fresh container, masks preceding the image fall back to float32 before being cast back.+ def test_convention_dictionary_mask_before_image_keeps_float64_precision_4478(self):+ # Convention pin for kornia#4478: a mask is converted with this call's image dtype wherever it sits in the+ # dictionary. Until the fix, a mask inserted before the image was converted with the previous call's image+ # dtype, or float32 on a fresh container, so these float64 values, which float32 cannot hold, came back+ # rounded even though the image was float64. Both insertion orders now return the mask bit for bit.image = torch.zeros(1, 1, 1, 2, dtype=torch.float64)mask = torch.tensor([1.0 + 2**-30, 2.0 + 2**-29], dtype=torch.float64).reshape_as(image)early_mask = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)image_first = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)- early_output = early_mask({"mask": mask, "image": image})["mask"]expected = mask.flip(-1)- self.assert_close(early_output, expected.float().double(), rtol=0, atol=0)- assert not torch.equal(early_output, expected)- self.assert_close(image_first({"image": image, "mask": mask})["mask"], expected, rtol=0, atol=0)+ early_output = early_mask({"mask": mask, "image": image})["mask"]+ assert early_output.dtype == torch.float64+ assert torch.equal(early_output, expected)+ assert torch.equal(image_first({"image": image, "mask": mask})["mask"], expected)@pytest.mark.parametrize("mask_dtypes", [(torch.int64, torch.bool), (torch.bool, torch.int64)])- def test_wart_mask_outputs_use_the_last_mask_dtype_4478(self, mask_dtypes, device, dtype):+ def test_convention_each_mask_keeps_its_own_dtype_4478(self, mask_dtypes, device, dtype):+ # Convention pin for kornia#4478: each mask output comes back in the dtype of its own argument. Until the+ # fix every mask output was cast to the dtype of the LAST mask argument, so an integer semantic mask+ # followed by a boolean one came back boolean and labels 2, 3 and 5 collapsed to True. Both orders are+ # covered, so the pin fails whichever mask used to win.image = torch.arange(24, device=device, dtype=dtype).reshape(2, 1, 3, 4)labels = torch.tensor([0, 2, 3, 5], device=device).reshape(1, 1, 1, 4).expand(2, 1, 3, 4)first, second = (labels.to(mask_dtype) for mask_dtype in mask_dtypes)seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask", "mask"])_, out_first, out_second = seq(image, first, second)- assert out_first.dtype == out_second.dtype == mask_dtypes[-1]- self.assert_close(out_first, first.flip(-1).to(mask_dtypes[-1]))- self.assert_close(out_second, second.flip(-1))- if mask_dtypes[-1] == torch.bool:- assert out_first.unique().tolist() == [False, True] # integer labels 2, 3 and 5 are lost+ assert (out_first.dtype, out_second.dtype) == mask_dtypes+ assert torch.equal(out_first, first.flip(-1))+ assert torch.equal(out_second, second.flip(-1))+ integer_output = out_first if mask_dtypes[0] == torch.int64 else out_second+ assert integer_output.unique().tolist() == [0, 2, 3, 5] # the labels survive next to a boolean mask+ assert seq.mask_dtype == mask_dtypes[1] # the attribute still records the last mask argument's dtype++ @pytest.mark.parametrize("mask_dtypes", [(torch.int64, torch.bool), (torch.bool, torch.int64)])+ def test_convention_each_list_mask_element_keeps_its_own_dtype_4478(self, mask_dtypes, device, dtype):+ # Convention pin for kornia#4478: a list mask comes back per element in each entry's own dtype. Until the+ # fix every element was cast to the list's first dtype, so a boolean entry after an integer one came back+ # int64 as [1, 1, 1, 0]. Both orders are covered, so the pin fails whichever element used to win.+ image = torch.arange(16, device=device, dtype=dtype).reshape(2, 1, 2, 4)+ labels = torch.tensor([0, 2, 3, 5], device=device).reshape(1, 1, 1, 4).expand(1, 1, 2, 4)+ entries = [labels.to(mask_dtype) for mask_dtype in mask_dtypes]+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])+ _, out = seq(image, entries)+ assert [m.dtype for m in out] == list(mask_dtypes)+ for out_entry, entry in zip(out, entries):+ assert torch.equal(out_entry, entry.flip(-1))+ assert seq.mask_dtype == mask_dtypes[0] # the attribute records the first element of the last list mask@pytest.mark.parametrize("key", ["bbox_xyxy", "bbox_xywh"])@pytest.mark.parametrize("suffix", ["", "_2", "-a"])@@ -1088,11 +1111,21 @@ class TestConventionAugmentationSequential(BaseTester):assert output.dtype == torch.int64assert torch.equal(output, torch.full_like(mask, label - 1))- def test_wart_empty_batch_with_mask_raises_4478(self, device, dtype):+ @pytest.mark.parametrize("mask_dtype", [None, torch.int64, torch.bool])+ def test_convention_empty_batch_with_mask_4478(self, mask_dtype, device, dtype):+ # Convention pin for kornia#4478: an empty batch with a mask returns an empty mask, forward and inverse,+ # in the mask's own dtype. Until the fix it raised IndexError before any op ran: the dtype read tested+ # ``isinstance(inp, list)`` on the accumulator, which is always a list, and so indexed the tensor mask at+ # ``arg[0]``.image = torch.empty(0, 1, 2, 2, device=device, dtype=dtype)+ mask = image.clone() if mask_dtype is None else torch.empty(0, 1, 2, 2, device=device, dtype=mask_dtype)seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])- with pytest.raises(IndexError):- seq(image, image.clone())+ out_image, out_mask = seq(image, mask)+ assert out_image.shape == out_mask.shape == (0, 1, 2, 2)+ assert out_mask.dtype == mask.dtype+ restored_image, restored_mask = seq.inverse(out_image, out_mask)+ assert restored_image.shape == restored_mask.shape == (0, 1, 2, 2)+ assert restored_mask.dtype == mask.dtypedef test_dictionary_preserves_metadata_and_input_4483(self, device, dtype):seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)diff --git a/tests/augmentation/test_torch_export.py b/tests/augmentation/test_torch_export.pyindex e1fcdf0a3..daf731515 100644--- a/tests/augmentation/test_torch_export.py+++ b/tests/augmentation/test_torch_export.py@@ -136,3 +136,44 @@ def test_torch_export_container(name: str, factory: Callable[[], torch.nn.Moduleout = exported.module()(x)assert out.shape == eager.shape, f"{name}: shape {out.shape} vs {eager.shape}"torch.testing.assert_close(out, eager, atol=1e-5, rtol=1e-5)+++def _mask_export_case(case: str) -> Tuple[torch.nn.Module, tuple, Callable[[object], torch.Tensor], torch.Tensor]:+ """Build a float64 image/mask pipeline for ``case``: the module, its arguments, a mask getter, the expected mask."""+ image = torch.zeros(1, 1, 1, 2, dtype=torch.float64)+ # float32 cannot hold either value, so any conversion through a narrower dtype rounds them+ mask = torch.tensor([1.0 + 2**-30, 2.0 + 2**-29], dtype=torch.float64).reshape_as(image)+ if case == "dict_mask_first":+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)+ return seq, ({"mask": mask, "image": image},), lambda out: out["mask"], mask.flip(-1)+ seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=["input", "mask"])+ if case == "after_float16_call":+ # an earlier eager call with a float16 image leaves float16 behind in the container's state+ seq(torch.zeros(1, 1, 1, 2, dtype=torch.float16), torch.zeros(1, 1, 1, 2))+ return seq, (image, mask), lambda out: out[1], mask.flip(-1)++[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]("case", ["fresh", "after_float16_call", "dict_mask_first"])[email protected]_agnostic+def test_torch_export_mask_uses_the_call_image_dtype_4478(case: str) -> None:+ """A mask is converted with this call's image dtype under ``torch.export``, exactly as in eager (#4478).++ The call's image dtype used to be resolved only outside export, because the attribute that holds it is not+ written during capture. Mask conversion read that attribute anyway, so an exported pipeline converted a+ float64 mask through float32 on a fresh container, or through whatever dtype an earlier eager call had left+ behind, and baked the rounding into the graph. The mask now comes back bit for bit in all three setups.+ """+ seq, args, get_mask, expected = _mask_export_case(case)+ # ``input_dtype`` and ``mask_dtype`` are class attributes until the first eager call writes them. Export must+ # not create or change them: torch 2.9 rejects an attribute created during capture, and torch 2.14 lets it+ # through silently, so the state is pinned here as well as by the export itself.+ state_before = {k: vars(seq).get(k, "<unset>") for k in ("input_dtype", "mask_dtype")}+ exported = torch.export.export(seq, args)+ state_after = {k: vars(seq).get(k, "<unset>") for k in ("input_dtype", "mask_dtype")}+ assert state_after == state_before, f"{case}: export changed the container state {state_before} -> {state_after}"+ 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()}"