Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): preserve dictionary metadata and route suffixed keys (#4619)

Shubham Padkonde48044c6bac16
diff --git a/changelog.d/4619.breaking.md b/changelog.d/4619.breaking.md
new file mode 100644
index 000000000..a26aaca43
--- /dev/null
+++ b/changelog.d/4619.breaking.md
@@ -0,0 +1,11 @@
+`AugmentationSequential(data_keys=None)` now matches dictionary data-key names exactly or before an
+underscore/hyphen suffix, preserving coordinate formats for keys such as `bbox_xyxy_2` and leaving the
+caller's dictionary intact. Formerly augmented plural names (`images`, `masks`, `labels`, `bboxes`, `inputs`),
+raw suffixes (`image2`, `keypoints2`), camelCase (`imageLeft`), dot-separated names (`image.2`), and unrelated
+prefixes (`imagenet_id`, `maskrcnn_boxes`, `labelled_image`, `inputsize`) are now returned unchanged as
+metadata without a warning. Rename augmentation inputs to recognized names such as `image`, `mask_2`,
+`label_2`, `bbox_2` or `input_2`. `class` and any key beginning with `class_` or `class-`, for example
+`class_id` or `class_weights`, formerly metadata, now route to labels and can raise for unsupported label-
+changing mix augmentations; rename metadata that must remain untouched. Unrecognized `keypoint` remains
+metadata in dict mode, whereas positional mode rejects it; use `keypoints` for augmentation. A coordinate-box
+suffix still needs `_` or `-`: `bbox_xyxy2` and `bbox_xywh2` match `bbox` and require vertex boxes.
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 47523ac88..6e170e76f 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -299,10 +299,10 @@ Augmentations
even with only rigid children. Do not rely on the outer
``.transform_matrix`` to describe a nested pipeline
(`#4476 <https://github.com/kornia/kornia/issues/4476>`_).
-- Dictionary keys use raw prefix matching with exceptions for coordinate box
- names. Unrecognized metadata is removed from the caller's dictionary before
- being returned in the output. See the container's dictionary guidance and
- `#4483 <https://github.com/kornia/kornia/issues/4483>`_.
+- Dictionary keys match a data-key name exactly or before an ``_``/``-`` suffix,
+ with the longest matching name taking precedence. Unrecognized keys are
+ returned unchanged as metadata, and the caller's dictionary is left intact.
+ See the container's dictionary guidance for recognized names and aliases.
- A positive ``degrees`` turns the displayed image counter-clockwise with
:class:`kornia.augmentation.RandomRotation`, matching
:func:`kornia.geometry.transform.rotate`, and clockwise with
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 6f1f70a8e..6a7f65788 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -108,10 +108,16 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
``image``, ``mask``, ``bbox``, ``bbox_xyxy``, ``bbox_xywh``, ``keypoints``, ``label`` and ``class``
(``input`` is an alias of ``image``, ``class`` of ``label``). Any other spelling -- ``boxes``,
``points``, ``bboxes``, ``keypoint`` -- raises ``KeyError``. With ``data_keys=None`` the call takes a
- dict instead. Dictionary names are matched by raw prefixes and the container removes entries while
- processing them. Prefixes can therefore route unrelated names (for example, ``imagenet_id``) as data
- keys; use positional arguments for reliable key selection. Tracked in
- `#4483 <https://github.com/kornia/kornia/issues/4483>`_.
+ dict instead. Dictionary names match these same names, optionally followed by an underscore or
+ hyphen suffix, with the longest name taking precedence. Unrecognized names (for example,
+ ``imagenet_id``, ``images``, ``masks``, ``labels``, ``bboxes``, ``inputs`` and ``keypoint``) are
+ returned unchanged as metadata, without a warning; unlike positional mode, dict mode does not
+ reject these names. Use recognized names such as ``mask_2`` and ``keypoints`` for augmentation.
+ ``class`` and any key beginning with ``class_`` or ``class-`` (for example, ``class_id`` or
+ ``class_weights``) route to labels and inherit label limitations, including unsupported
+ label-changing mix augmentations. A coordinate-box name must be followed by ``_``
+ or ``-`` to retain its format: ``bbox_xyxy2`` instead matches ``bbox`` and requires vertex boxes.
+ The input dictionary is not modified.
- the layouts are ``(B, C, H, W)`` for images and masks, ``(B, N, 4, 2)`` vertices for ``bbox``,
``(B, N, 4)`` for ``bbox_xyxy`` and ``bbox_xywh``, and ``(B, N, 2)`` in ``(x, y)`` for ``keypoints``.
Feeding a coordinate layout under another coordinate key raises ``ValueError`` naming the expected shape.
@@ -289,12 +295,12 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
>>> [value.shape for value in out]
[torch.Size([2, 3, 32, 32]), torch.Size([2, 3, 32, 32]), torch.Size([2, 2, 32, 32])]
- With ``data_keys=None``, dictionary keys are matched to data-key prefixes. Use the exact keys
- ``bbox_xyxy`` and ``bbox_xywh`` for coordinate boxes: suffixed versions match ``bbox`` and require
- vertices instead. Use ``label`` for labels, since ``class`` and its prefixes are treated as unrelated
- metadata. Unrecognized items are popped from the caller's dictionary and returned without augmentation.
- Raw prefix matching can also misroute unrelated names such as ``imagenet_id``. Tracked in
- `#4483 <https://github.com/kornia/kornia/issues/4483>`_.
+ With ``data_keys=None``, dictionary keys match data-key names case-insensitively, optionally followed
+ by an underscore or hyphen suffix (for example, ``image_2`` or ``bbox_xyxy-left``). The longest matching
+ name wins, so coordinate boxes with an underscore/hyphen suffix retain their coordinate format.
+ Without that separator, ``bbox_xyxy2`` matches ``bbox`` and requires vertex boxes. ``input`` and ``class`` are
+ aliases of ``image`` and ``label``. Unrecognized items are returned without augmentation, and the
+ caller's dictionary is left intact.
>>> import kornia.augmentation as K
>>> img = torch.randn(1, 3, 256, 256)
@@ -663,29 +669,23 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
keys = tuple(data.keys())
data_keys, invalid_keys = self._read_datakeys_from_dict(keys)
- invalid_data = {i: data.pop(i) for i in invalid_keys} if invalid_keys else None
+ invalid_data = {i: data[i] for i in invalid_keys} if invalid_keys else None
keys = tuple(k for k in keys if k not in invalid_keys) if invalid_keys else keys
- data_unpacked = tuple(data.values())
+ data_unpacked = tuple(data[k] for k in keys)
return keys, data_keys, data_unpacked, invalid_data
def _read_datakeys_from_dict(self, keys: Sequence[str]) -> Tuple[List[DataKey], Optional[List[str]]]:
+ # Include aliases and prefer coordinate box names over their BBOX prefix.
+ names = sorted(DataKey.__members__, key=len, reverse=True)
+
def retrieve_key(key: str) -> DataKey:
- """Try to retrieve the datakey value by matching `<datakey>*`."""
- # Alias cases, like INPUT, will not be get by the enum iterator.
- if key.upper().startswith("INPUT"):
- return DataKey.INPUT
-
- for dk in DataKey:
- if key.upper() in {"BBOX_XYXY", "BBOX_XYWH"}:
- return DataKey.get(key.upper())
- if key.upper().startswith(dk.name):
- return DataKey.get(dk.name)
-
- allowed_dk = " | ".join(f"`{d.name}`" for d in DataKey)
- raise ValueError(
- f"Your input data dictionary keys should start with some of datakey values: {allowed_dk}. Got `{key}`"
- )
+ """Match a data-key name exactly or before an underscore/hyphen suffix."""
+ upper_key = key.upper()
+ for name in names:
+ if upper_key == name or upper_key.startswith((name + "_", name + "-")):
+ return DataKey.get(name)
+ raise ValueError(f"Unrecognized data dictionary key: {key}")
valid_data_keys = []
invalid_keys = []
diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.py
index 808a89e79..9d5d81bb1 100644
--- a/tests/augmentation/container/test_augmentation_sequential.py
+++ b/tests/augmentation/container/test_augmentation_sequential.py
@@ -804,21 +804,22 @@ class TestConventionAugmentationSequential(BaseTester):
assert out_first.unique().tolist() == [False, True] # integer labels 2, 3 and 5 are lost
@pytest.mark.parametrize("key", ["bbox_xyxy", "bbox_xywh"])
- def test_wart_suffixed_coordinate_box_dict_keys_expect_vertices_4483(self, key, device, dtype):
+ @pytest.mark.parametrize("suffix", ["", "_2", "-a"])
+ def test_dictionary_coordinate_box_keys_4483(self, key, suffix, device, dtype):
image = torch.arange(20, device=device, dtype=dtype).reshape(1, 1, 4, 5)
boxes = torch.tensor([[[0.0, 0.0, 2.0, 2.0]]], device=device, dtype=dtype)
seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)
- output = seq({"image": image, key: boxes})
+ output = seq({"image": image, key + suffix: boxes})
expected = [2.0, 0.0, 4.0, 2.0] if key == "bbox_xyxy" else [3.0, 0.0, 2.0, 2.0]
- self.assert_close(output[key], torch.tensor([[expected]], device=device, dtype=dtype))
- with pytest.raises(ValueError, match="when vertices_plus mode"):
- seq({"image": image, key + "-a": boxes})
+ self.assert_close(output[key + suffix], torch.tensor([[expected]], device=device, dtype=dtype))
+ restored = seq.inverse(output)
+ self.assert_close(restored[key + suffix], boxes)
- def test_wart_dictionary_class_alias_is_metadata_4483(self):
+ def test_dictionary_class_alias_4483(self):
seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)
keys, metadata = seq._read_datakeys_from_dict(("input", "class", "class-a", "label", "label-a"))
- assert keys == [DataKey.INPUT, DataKey.LABEL, DataKey.LABEL]
- assert metadata == ["class", "class-a"]
+ assert keys == [DataKey.INPUT, DataKey.LABEL, DataKey.LABEL, DataKey.LABEL, DataKey.LABEL]
+ assert metadata == []
@pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
@pytest.mark.parametrize("align_corners", [None, False, True])
@@ -1041,15 +1042,66 @@ class TestConventionAugmentationSequential(BaseTester):
with pytest.raises(IndexError):
seq(image, image.clone())
- def test_wart_dictionary_pops_metadata_and_matches_raw_prefixes_4483(self, device, dtype):
+ def test_dictionary_preserves_metadata_and_input_4483(self, device, dtype):
seq = K.AugmentationSequential(K.RandomHorizontalFlip(p=1.0), data_keys=None)
- keys, metadata = seq._read_datakeys_from_dict(("imagenet_id", "maskrcnn_boxes", "labelled_image", "note"))
- assert keys == [DataKey.INPUT, DataKey.MASK, DataKey.LABEL]
- assert metadata == ["note"]
- data = {"image": torch.ones(1, 1, 2, 2, device=device, dtype=dtype), "note": "retained in output"}
+ metadata = {"imagenet_id": 7, "maskrcnn_boxes": "unchanged", "labelled_image": None, "note": "retained"}
+ image = torch.arange(4, device=device, dtype=dtype).reshape(1, 1, 2, 2)
+ data = {"note": metadata["note"], "image": image, **metadata}
+ original = dict(data)
output = seq(data)
- assert "note" not in data
- assert output["note"] == "retained in output"
+ assert data.keys() == original.keys()
+ for key, value in original.items():
+ assert data[key] is value
+ self.assert_close(output["image"], image.flip(-1))
+ for key, value in metadata.items():
+ assert output[key] is value
+ restored = seq.inverse(output)
+ self.assert_close(restored["image"], image)
+ for key, value in metadata.items():
+ assert restored[key] is value
+ assert output[key] is value
+
+ def test_dictionary_key_boundaries_4483(self):
+ seq = K.AugmentationSequential(data_keys=None)
+ names = ("image", "IMAGE-left", "input_2", "mask_2", "keypoints-right", "bbox_xyxy_2", "bbox_xywh-a", "bbox_2")
+ keys, metadata = seq._read_datakeys_from_dict(names)
+ assert keys == [
+ DataKey.INPUT,
+ DataKey.INPUT,
+ DataKey.INPUT,
+ DataKey.MASK,
+ DataKey.KEYPOINTS,
+ DataKey.BBOX_XYXY,
+ DataKey.BBOX_XYWH,
+ DataKey.BBOX,
+ ]
+ assert metadata == []
+ names = (
+ "imagenet_id",
+ "maskrcnn_boxes",
+ "labelled_image",
+ "keypoint",
+ "classification",
+ "inputsize",
+ "images",
+ "masks",
+ "labels",
+ "bboxes",
+ "inputs",
+ "image2",
+ "imageLeft",
+ "image.2",
+ "keypoints2",
+ )
+ keys, metadata = seq._read_datakeys_from_dict(names)
+ assert keys == []
+ assert metadata == list(names)
+
+ keys, metadata = seq._read_datakeys_from_dict(
+ ("bbox_xyxy2", "bbox_xywh2", "class", "class_id", "class_weights", "class-names")
+ )
+ assert keys == [DataKey.BBOX, DataKey.BBOX, DataKey.LABEL, DataKey.LABEL, DataKey.LABEL, DataKey.LABEL]
+ assert metadata == []
def test_convention_same_on_batch_none_does_not_override_a_child(self, device, dtype):
# Convention pin: `AugmentationSequential(same_on_batch=None)` - the default - keeps whatever each