Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): select nothing when random_apply draws 0 (#6057)

Saksham Sharma57adc099ebac
diff --git a/changelog.d/6057.fixed.md b/changelog.d/6057.fixed.md
new file mode 100644
index 000000000..0e8775dea
--- /dev/null
+++ b/changelog.d/6057.fixed.md
@@ -0,0 +1 @@
+`ImageSequential` and `AugmentationSequential` with a `random_apply` range that includes 0, such as `(0, 2)`, `(0,)` or `0`, apply no transformation when 0 is drawn, a mix augmentation included, and return their inputs unchanged. Previously such a call raised `RuntimeError: cannot sample n_sample <= 0 samples`, so a range that includes 0 crashed at random. A negative bound, or an upper bound below the lower one, now raises a `ValueError` naming `random_apply` when the container is constructed, instead of a raw `torch.multinomial` or `torch.randint` error at call time. Ranges that never draw 0 select exactly as before.
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 9b76b814b..21a45dd00 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -182,6 +182,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
self, random_apply: Union[int, bool, Tuple[int, int]], max_length: int
) -> Union[Tuple[int, int], bool]:
"""Process the scenarios for random apply."""
+ requested = random_apply
if isinstance(random_apply, bool) and random_apply is False:
random_apply = False
elif isinstance(random_apply, bool) and random_apply is True:
@@ -206,6 +207,13 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
and isinstance(random_apply[1], int)
):
raise AssertionError(f"Expect a tuple of (int, int). Got {random_apply}.")
+ # The stored upper bound is exclusive. A negative count or an upper bound below the lower one used to fail
+ # only at call time, in torch.multinomial or torch.randint.
+ if random_apply is not False and (random_apply[0] < 0 or random_apply[1] <= random_apply[0]):
+ raise ValueError(
+ "random_apply must select a non-negative number of transformations, with the lower bound not above "
+ f"the upper one. Got {requested}."
+ )
return random_apply
def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, nn.Module]], bool]:
@@ -230,7 +238,8 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
multinomial_weights[mix_indices] = 0
total_weight = multinomial_weights.sum()
- if total_weight == 0:
+ # A drawn count of 0 selects nothing, like all-zero weights; torch.multinomial rejects a count of 0.
+ if total_weight == 0 or num_samples == 0:
indices = torch.tensor([], device=multinomial_weights.device, dtype=torch.long)
else:
indices = torch.multinomial(
@@ -240,9 +249,10 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
)
mix_added = False
- # Make the selection fair.
+ # Make the selection fair. A mix member takes one of the drawn places, so a drawn count of 0 adds none.
if (
with_mix
+ and num_samples > 0
and len(mix_indices) != 0
and (torch.rand(1) < ((len(mix_indices) + len(indices)) / len(self))).item()
):
diff --git a/tests/augmentation/container/test_sequential_aug.py b/tests/augmentation/container/test_sequential_aug.py
index 64b7b0958..dc6246eb3 100644
--- a/tests/augmentation/container/test_sequential_aug.py
+++ b/tests/augmentation/container/test_sequential_aug.py
@@ -142,6 +142,40 @@ class TestConventionImageSequential(BaseTester):
with pytest.raises(ValueError, match="Invalid output_type"):
aug(torch.zeros(1, 3, 4, 4, device=device, dtype=dtype), output_type="jpg")
+ @pytest.mark.parametrize("random_apply", [0, (0,), (0, 0), (0, 1), (0, 2)])
+ @pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
+ def test_random_apply_range_with_zero_never_crashes_6055(self, random_apply, container, device, dtype):
+ # A drawn count of 0 used to reach torch.multinomial and raise "cannot sample n_sample <= 0 samples", so a
+ # range that includes 0 crashed whenever the draw was 0. It now applies no transformation.
+ 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=random_apply)
+ counts = set()
+ for seed in range(30):
+ torch.manual_seed(seed)
+ out = seq(x)
+ counts.add(len(seq._params))
+ if len(seq._params) == 0:
+ self.assert_close(out, x, rtol=0.0, atol=0.0)
+ assert 0 in counts
+
+ @pytest.mark.parametrize("random_apply", [-1, (-1,), (-1, 1), (2, 1)])
+ @pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
+ def test_random_apply_rejects_negative_or_inverted_ranges_6055(self, random_apply, container):
+ # These used to fail only at call time, with torch.multinomial's or torch.randint's own error.
+ with pytest.raises(ValueError, match="random_apply must select a non-negative number of transformations"):
+ container(K.RandomHorizontalFlip(p=1.0), K.RandomVerticalFlip(p=1.0), random_apply=random_apply)
+
+ @pytest.mark.parametrize("container", [K.ImageSequential, K.AugmentationSequential])
+ def test_random_apply_zero_draw_adds_no_mix_6055(self, container, device, dtype):
+ # A mix member replaces one of the drawn members, so a drawn count of 0 must not add it either.
+ x = torch.rand(4, 3, 6, 8, device=device, dtype=dtype)
+ seq = container(K.RandomHorizontalFlip(p=1.0), K.RandomMixUpV2(p=1.0), random_apply=0)
+ for seed in range(20):
+ torch.manual_seed(seed)
+ out = seq(x)
+ assert seq._params == []
+ self.assert_close(out, x, rtol=0.0, atol=0.0)
+
def test_convention_slice_crop_inverse_restores_the_canvas(self, device, dtype):
seq = K.ImageSequential(K.CenterCrop((4, 6), p=1.0))
out = seq(torch.rand(1, 3, 6, 8, device=device, dtype=dtype))