π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): accept dictionary input in AdaptiveDiscriminatorAugmentation (#5882)
Saksham Sharmae91037957864
diff --git a/changelog.d/5882.fixed.md b/changelog.d/5882.fixed.mdnew file mode 100644index 000000000..6f4d18ebc--- /dev/null+++ b/changelog.d/5882.fixed.md@@ -0,0 +1,7 @@+`AdaptiveDiscriminatorAugmentation` accepts the dictionary input its signature allows. No dictionary reached+the augmentations: a plain call raised `ValueError` because the preset always sets `data_keys`,+`forward(..., data_keys=...)` with the dictionary's own keys raised the same error whenever a sample was drawn,+and `forward` without `data_keys` raised `KeyError: 'IMAGE'` unless `p` was 0. The dictionary's keys now name+the data, the same samples are augmented in every entry, and an entry that names no data key is returned+unchanged. When `p` is above 0, `data_keys` passed with a dictionary must name the same data keys, in any+order, or a `ValueError` is raised.diff --git a/kornia/augmentation/presets/ada.py b/kornia/augmentation/presets/ada.pyindex 3a064c7ad..01339b129 100644--- a/kornia/augmentation/presets/ada.py+++ b/kornia/augmentation/presets/ada.py@@ -20,6 +20,8 @@ from typing import Any, Dict, List, Optional, Tuple, Union, castimport torch+from kornia.constants import DataKey+from .. import ( # noqa: TID252AugmentationSequential,ColorJitter,@@ -31,6 +33,7 @@ from .. import ( # noqa: TID252RandomRotation90,)from ..base import _AugmentationBase # noqa: TID252+from ..container.ops import DataType # noqa: TID252from ..container.params import ParamItem # noqa: TID252_data_keys_type = List[str]@@ -211,6 +214,33 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):else:self.p = min(self.p + self.adjustment_speed, self.max_p)+ def _preproc_dict_data(+ self, data: Dict[str, DataType]+ ) -> Tuple[Tuple[str, ...], List[DataKey], Tuple[DataType, ...], Optional[Dict[str, Any]]]:+ # ``data_keys`` describe a tensor input, and ADA always sets them, so the parent's rule that a dictionary needs+ # ``data_keys=None`` would reject every dictionary. A dictionary names its own entries instead.+ keys = tuple(data.keys())+ data_keys, invalid_keys = self._read_datakeys_from_dict(keys)+ invalid_data = {k: data[k] for k 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+ return keys, data_keys, tuple(data[k] for k in keys), invalid_data++ def _dict_keys(self, inputs: Dict[str, torch.Tensor], data_keys: Optional[_data_keys_type]) -> _data_keys_type:+ """Return the augmentable keys of a dictionary input, the image key first."""+ keys, dict_data_keys, _, _ = self._preproc_dict_data(cast(Dict[str, DataType], inputs))+ if not keys:+ raise ValueError(f"No key of the dictionary input names a data key. Got {list(inputs)}.")+ # The dictionary sets the order, so only the data keys themselves have to agree.+ if data_keys is not None and sorted(DataKey.get(k).value for k in data_keys) != sorted(+ k.value for k in dict_data_keys+ ):+ raise ValueError(+ f"A dictionary input names its own data keys, so `data_keys` must match them, in any order, or be "+ f"None. Got {data_keys} for the keys {list(keys)}."+ )+ order = sorted(range(len(keys)), key=lambda i: dict_data_keys[i] != DataKey.INPUT)+ return [keys[i] for i in order]+def _get_inputs_metadata(self, inputs: _inputs_type, data_keys: _data_keys_type) -> Tuple[int, Optional[Union[str, torch.device]]]:@@ -238,8 +268,9 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):) -> _inputs_type:merged: _inputs_typeif isinstance(original, dict) and isinstance(augmented, dict):- merged = {}- for key in original:+ # Entries that name no data key were not augmented and pass through unchanged.+ merged = dict(original)+ for key in augmented:merged_tensor = original[key].clone()merged_tensor[p_tensor] = augmented[key]merged[key] = merged_tensor@@ -268,6 +299,11 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):if `real_acc` is provided, the internal probability `p` is updated via the `update` method.Non-augmented samples retain their original values, and the output matches the input structure.+ A dictionary input names its own data keys, as with :class:`~kornia.augmentation.AugmentationSequential`,+ whatever ``data_keys`` the preset was built with; ``data_keys`` passed here must match them, in any order, or+ be None. The same samples are augmented in every entry, and an entry whose key names no data key is returned+ unchanged.+`real_acc` is the Discriminator's accuracy on real images; for example,`(real_logits > 0).float().mean().item()` if using logits andn assuming real labels are positive."""@@ -277,14 +313,14 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):if self.p == 0:return inputs- if data_keys is None:- data_keys = (- [k.name for k in self.data_keys]- if self.data_keys is not None- else [- "input",- ]- )+ if isinstance(inputs, dict):+ # Each entry is row-selected and merged by its own key; the parent reads the data keys from the names.+ data_keys = self._dict_keys(inputs, data_keys)+ forward_data_keys = None+ else:+ if data_keys is None:+ data_keys = [k.name for k in self.data_keys] if self.data_keys is not None else ["input"]+ forward_data_keys = data_keysbatch_size, device = self._get_inputs_metadata(inputs, data_keys=data_keys)@@ -304,7 +340,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):super().forward(selected_inputs, # type: ignore[arg-type]params=params,- data_keys=data_keys,+ data_keys=forward_data_keys,),)diff --git a/tests/augmentation/test_presets.py b/tests/augmentation/test_presets.pyindex 501c8a8d1..cb32fb50c 100644--- a/tests/augmentation/test_presets.py+++ b/tests/augmentation/test_presets.py@@ -138,3 +138,53 @@ class TestAdaptiveDiscriminatorAugmentation(PresetTests):for _ in range(ada.update_every):ada(inputs, real_acc=ada.target_real_acc + 0.1)self.assert_close(ada.p, ada.max_p)++ @pytest.mark.parametrize("route", ["call", "forward_data_keys", "init_data_keys"])+ def test_dict_input(self, device, dtype, route):+ # Every dictionary route raised: ADA always set `data_keys`, which the parent rejects with a dictionary, and+ # the default keys were the enum names ("IMAGE"), not the dictionary's. Each row is augmented with its mask,+ # and an entry that names no data key passes through.+ torch.manual_seed(0)+ x = torch.rand(16, 1, 4, 4, device=device, dtype=dtype)+ m = (torch.rand(16, 1, 4, 4, device=device) > 0.5).to(dtype)+ sample_id = torch.arange(16, device=device)+ data_keys = ["input", "mask"] if route == "init_data_keys" else None+ ada = AdaptiveDiscriminatorAugmentation(+ RandomHorizontalFlip(p=1.0), initial_p=0.5, max_p=1.0, data_keys=data_keys+ )+ inputs = {"input": x, "mask": m, "sample_id": sample_id}+ if route == "call":+ out = ada(inputs)+ elif route == "forward_data_keys":+ out = ada.forward(inputs, data_keys=["input", "mask"])+ else:+ out = ada.forward(inputs)++ assert set(out) == {"input", "mask", "sample_id"}+ flipped = (out["input"] != x).flatten(1).any(1)+ self.assert_close(out["input"][flipped], x[flipped].flip(-1))+ self.assert_close(out["input"][~flipped], x[~flipped])+ self.assert_close(out["mask"][flipped], m[flipped].flip(-1))+ self.assert_close(out["mask"][~flipped], m[~flipped])+ assert torch.equal(out["sample_id"], sample_id)++ def test_dict_input_data_keys_mismatch(self, device, dtype):+ ada = AdaptiveDiscriminatorAugmentation(RandomHorizontalFlip(p=1.0), initial_p=0.5)+ x = torch.rand(4, 1, 4, 4, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="must match them, in any order"):+ ada.forward({"input": x, "mask": x}, data_keys=["input"])++ def test_dict_input_without_data_key(self, device, dtype):+ ada = AdaptiveDiscriminatorAugmentation(RandomHorizontalFlip(p=1.0), initial_p=0.5)+ x = torch.rand(4, 1, 4, 4, device=device, dtype=dtype)+ with pytest.raises(ValueError, match="No key of the dictionary input names a data key"):+ ada({"img": x})++ def test_dict_input_data_keys_any_order(self, device, dtype):+ # The dictionary sets the order, so `data_keys` naming the same keys in another order are accepted.+ ada = AdaptiveDiscriminatorAugmentation(RandomHorizontalFlip(p=1.0), initial_p=1.0, max_p=1.0)+ x = torch.rand(4, 1, 4, 4, device=device, dtype=dtype)+ m = (x > 0.5).to(dtype)+ out = ada.forward({"mask": m, "input": x}, data_keys=["input", "mask"])+ self.assert_close(out["input"], x.flip(-1))+ self.assert_close(out["mask"], m.flip(-1))