Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): accept integer and tensor random_apply_weights (#6050)

Saksham Sharmab09be3b262e4
diff --git a/changelog.d/6050.fixed.md b/changelog.d/6050.fixed.md
new file mode 100644
index 000000000..bb50d7c1e
--- /dev/null
+++ b/changelog.d/6050.fixed.md
@@ -0,0 +1 @@
+`ImageSequential` and `AugmentationSequential` accept integer, boolean and tensor `random_apply_weights`. Previously integer or boolean weights raised `RuntimeError: multinomial only supports floating-point dtypes` on every call, and a tensor of weights raised `RuntimeError: Boolean value of Tensor with more than one value is ambiguous` in the constructor. Non-floating weights are converted to the default floating dtype, and float weights keep their dtype, so existing selections are unchanged. Weights that are not one-dimensional now raise a `ValueError`; a nested float list used to be accepted and drew a selection per row, so `random_apply=1` applied more than one transformation.
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index dfab7a639..6c8969f54 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -334,7 +334,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
same_on_batch: Optional[bool] = None,
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
- random_apply_weights: Optional[List[float]] = None,
+ random_apply_weights: Optional[Union[Sequence[float], torch.Tensor]] = None,
transformation_matrix_mode: str = "silent",
extra_args: Optional[Dict[DataKey, Dict[str, Any]]] = None,
) -> None:
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 21a45dd00..3a777e09f 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -16,7 +16,7 @@
#
import operator
-from typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union, cast
+from typing import Any, Dict, Iterator, List, Literal, Optional, Sequence, Tuple, Union, cast
import torch
from torch import nn
@@ -73,8 +73,9 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
If (a, b), x number of transformations (a <= x <= b) will be selected.
If True, the whole list of args will be processed as a sequence in a random order.
If False, the whole list of args will be processed as a sequence in original order.
- random_apply_weights: a list of selection weights for each operation. The length shall be as
- same as the number of operations. By default, operations are sampled uniformly.
+ random_apply_weights: a one-dimensional sequence or tensor of selection weights for each operation. The
+ length shall be as same as the number of operations. Integer and boolean weights are converted to floating
+ point. By default, operations are sampled uniformly.
if_unsupported_ops: what ``inverse`` does on reaching a plain ``nn.Module``, which has no inverse:
``'raise'`` raises ``NotImplementedError`` naming it, before anything is inverted, and ``'skip'``
leaves it applied and inverts the other members. Any other value raises ``ValueError``.
@@ -150,7 +151,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
same_on_batch: Optional[bool] = None,
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
- random_apply_weights: Optional[List[float]] = None,
+ random_apply_weights: Optional[Union[Sequence[float], torch.Tensor]] = None,
if_unsupported_ops: str = "raise",
disable_item_features: bool = True,
disable_sequential_features: bool = False,
@@ -169,7 +170,14 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
"The length of `random_apply_weights` must be as same as the number of operations."
f"Got {len(random_apply_weights)} and {len(self)}."
)
- self.random_apply_weights = torch.as_tensor(random_apply_weights or torch.ones((len(self),)))
+ # ``torch.multinomial`` samples floating-point weights only, so integer or boolean weights are converted; a
+ # tensor argument is tested against ``None`` rather than for its truth value, which is ambiguous.
+ weights = torch.as_tensor(random_apply_weights) if random_apply_weights is not None else torch.ones(len(self))
+ if weights.dim() != 1:
+ raise ValueError(f"`random_apply_weights` must be one-dimensional. Got shape {tuple(weights.shape)}.")
+ if not weights.is_floating_point():
+ weights = weights.to(torch.get_default_dtype())
+ self.random_apply_weights = weights
self.if_unsupported_ops = if_unsupported_ops
self._output_image = None
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index eece7a79f..c5fe14f89 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -17,7 +17,7 @@
from __future__ import annotations
-from typing import Any, Dict, Iterator, List, Optional, Tuple, Union
+from typing import Any, Dict, Iterator, List, Optional, Sequence, Tuple, Union
import torch
import torch.nn.functional as F
@@ -158,7 +158,7 @@ class PatchSequential(ImageSequential):
keepdim: Optional[bool] = None,
patchwise_apply: bool = True,
random_apply: Union[int, bool, Tuple[int, int]] = False,
- random_apply_weights: Optional[List[float]] = None,
+ random_apply_weights: Optional[Union[Sequence[float], torch.Tensor]] = None,
) -> None:
_random_apply: Optional[Union[int, Tuple[int, int]]]
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 10ca7e911..817bb29bf 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -15,7 +15,7 @@
# limitations under the License.
#
-from typing import Any, Dict, List, Optional, Tuple, Union, cast
+from typing import Any, Dict, List, Optional, Sequence, Tuple, Union, cast
import torch
from torch import nn
@@ -138,7 +138,7 @@ class VideoSequential(ImageSequential):
data_format: str = "BTCHW",
same_on_frame: bool = True,
random_apply: Union[int, bool, Tuple[int, int]] = False,
- random_apply_weights: Optional[List[float]] = None,
+ random_apply_weights: Optional[Union[Sequence[float], torch.Tensor]] = None,
if_unsupported_ops: str = "raise",
) -> None:
super().__init__(
diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.py
index dc6246eb3..c1d84300a 100644
--- a/tests/augmentation/container/test_sequential_aug.py
+++ b/tests/augmentation/container/test_sequential_aug.py
@@ -261,6 +261,72 @@ class TestConventionImageSequential(BaseTester):
assert [p.name for p in seq._params] == ["RandomHorizontalFlip_0"]
self.assert_close(seq.inverse(out), out.flip(-1))
+ @pytest.mark.parametrize(
+ "weights",
+ [
+ [1, 0],
+ (1, 0),
+ [True, False],
+ torch.tensor([1, 0]),
+ torch.tensor([True, False]),
+ torch.tensor([1.0, 0.0]),
+ torch.tensor([1.0, 0.0], dtype=torch.float64),
+ ],
+ )
+ @pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
+ def test_random_apply_weights_accept_integer_and_tensor_weights_6049(self, weights, container, device, dtype):
+ # Integer and boolean weights used to reach torch.multinomial as an int64/bool tensor, and a tensor of weights
+ # was tested for its truth value; both raised. Any of them now selects in proportion, like float weights.
+ x = torch.rand(2, 3, 6, 8, device=device, dtype=dtype)
+ seq = container(
+ K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), random_apply=1, random_apply_weights=weights
+ )
+
+ assert seq.random_apply_weights.is_floating_point()
+ for seed in range(5):
+ torch.manual_seed(seed)
+ out = seq(x)
+ assert [p.name for p in seq._params] == ["RandomHorizontalFlip_0"]
+ self.assert_close(out, x.flip(-1))
+
+ def test_random_apply_weights_keep_a_float_dtype_6049(self):
+ # Float weights keep their dtype, so the selections of existing calls are unchanged.
+ flips = (K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0))
+ assert K.ImageSequential(
+ *flips, random_apply=1, random_apply_weights=[0.7, 0.3]
+ ).random_apply_weights.dtype == (torch.get_default_dtype())
+ weights64 = torch.tensor([0.7, 0.3], dtype=torch.float64)
+ assert K.ImageSequential(*flips, random_apply=1, random_apply_weights=weights64).random_apply_weights.dtype == (
+ torch.float64
+ )
+ assert K.ImageSequential(*flips, random_apply=1).random_apply_weights.dtype == torch.get_default_dtype()
+
+ @pytest.mark.parametrize("weights", [[7, 2, 1], torch.tensor([7, 2, 1])])
+ def test_random_apply_weights_integer_select_like_floats_6049(self, weights):
+ # Integer weights are relative weights, converted to the default dtype: they select exactly as the same values
+ # given as floats.
+ def build(w):
+ augs = (K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), K.RandomInvert(p=1.0))
+ return K.ImageSequential(*augs, random_apply=1, random_apply_weights=w)
+
+ x = torch.zeros(1, 3, 4, 4)
+ reference, seq = build([7.0, 2.0, 1.0]), build(weights)
+ assert seq.random_apply_weights.dtype == torch.get_default_dtype()
+ for seed in range(30):
+ torch.manual_seed(seed)
+ reference(x)
+ torch.manual_seed(seed)
+ seq(x)
+ assert [p.name for p in seq._params] == [p.name for p in reference._params]
+
+ @pytest.mark.parametrize("weights", [torch.tensor([[0.7], [0.3]]), [[1.0, 0.0], [0.0, 1.0]]])
+ def test_random_apply_weights_reject_non_vectors_6049(self, weights):
+ # A nested float list used to be accepted and drew a selection per row, so random_apply=1 applied two.
+ with pytest.raises(ValueError, match="must be one-dimensional"):
+ K.ImageSequential(
+ K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), random_apply=1, random_apply_weights=weights
+ )
+
def test_convention_augmentation_sequential_leaves_plain_modules_applied_4423(self, device, dtype):
# #4423: `AugmentationSequential` does not take `if_unsupported_ops`; it leaves a plain module child applied,
# also when nested in another container, while a nested `ImageSequential` follows its own setting.