Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(augmentation): reconcile the batch 6d Convention blocks and pins with the #4649, #4655 and #4656 fixes (#4711)

Dmytro Mishkin088586663f4d
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 31db33e99..f40bb6508 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -452,11 +452,9 @@ Serializing an augmentation
default policies currently cannot
(`#4469 <https://github.com/kornia/kornia/issues/4469>`_). An empty
``AutoAugment(policy=[[]])`` has no wrappers and can be pickled, and so can
- a policy holding only ``posterize`` entries. ``copy.deepcopy`` raises
- ``RuntimeError`` once a policy has rebuilt its probability samplers with
- gradients enabled: after a ``RandAugment`` forward pass, or after
- ``.train()`` / ``.eval()`` on any of the three policies, even one that was
- never called (`#4656 <https://github.com/kornia/kornia/issues/4656>`_).
+ a policy holding only ``posterize`` entries. ``copy.deepcopy`` works on all
+ three policies, before and after a forward pass or a ``.train()`` /
+ ``.eval()`` call, and the copy replays the original's recorded ``_params``.
A normal forward draws fresh parameters; replay requires passing the
saved parameters and controlling any application-time randomness.
- Built-in lazy matrices keep only the input's shape, dtype and device
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 8dbdb7f2a..0780d7d12 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -78,11 +78,13 @@ class RandomCutMixV2(MixAugmentationBaseV2):
``2 ** 24`` stay exact.
``use_correct_lambda=True`` returns ``1 - cut_area / image_area``;
the compatibility default returns ``cut_area / image_area`` and emits a deprecation warning.
- - ``p`` is a batch-wide gate, and the generator applies it a second time per row and mix: inside a selected
- batch each cut is kept with probability ``p`` and zeroed otherwise. Each cut passes both gates with
- probability ``p ** 2``; it can still leave the image unchanged through self-pairing or a zero-sized cut.
- With ``same_on_batch=True`` the inner gate is shared across rows and mixes
- (`#4649 <https://github.com/kornia/kornia/issues/4649>`_).
+ - ``p`` is a batch-wide gate and is applied once: one draw per call selects the whole batch with probability
+ ``p``, so ``_params["batch_prob"]`` is all ones or all zeros. Every row and mix of a selected batch receives
+ a cut and none is dropped again. With ``same_on_batch=False`` each row and mix draws its own cut size, but
+ the placement comes from one uniform draw per axis that all of them share
+ (`#4712 <https://github.com/kornia/kornia/issues/4712>`_); ``same_on_batch=True`` shares the size as well,
+ so all rows and mixes receive one geometry. A cut can still leave the image unchanged through self-pairing
+ or a zero-sized cut.
At ``p=0`` the image is unchanged and each class row contains the original
label twice with lambda zero. The current ``cut_size`` interpretation and its rejection of a minimum of
``1`` are described in its argument above; this is the repaired behavior from
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index 49a08f6ad..1ab1bd28e 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -81,11 +81,10 @@ class RandomMixUpV2(MixAugmentationBaseV2):
``input * (1 - lambda) + paired_input * lambda``. Labels must be one-dimensional and are returned as
floating values in the image dtype, except that a ``float16`` or ``bfloat16`` image yields ``float32``
labels so integer class ids up to ``2 ** 24`` stay exact.
- - ``p`` is a batch-wide gate for this class, and the generator applies it a second time per row: inside a
- selected batch each row's lambda is kept with probability ``p`` and zeroed otherwise. A row passes both
- gates with probability ``p ** 2``; its image can still be unchanged if lambda is zero or it is paired
- with itself. With ``same_on_batch=True`` the inner gate is also shared across rows
- (`#4649 <https://github.com/kornia/kornia/issues/4649>`_).
+ - ``p`` is a batch-wide gate for this class and is applied once: one draw per call selects the whole batch
+ with probability ``p``, so ``_params["batch_prob"]`` is all ones or all zeros. Every row of a selected
+ batch draws its lambda from ``lambda_val`` and none is dropped again; a row's image can still be unchanged
+ if its lambda is zero or it is paired with itself.
At ``p=0`` the image is unchanged and the class output holds
the original label twice with a zero lambda. ``same_on_batch=True`` shares lambda draws, but it does not
constrain the pairing indices: they can differ across rows and can select the original sample.
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index fb00f1a80..a1c3c9483 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -41,11 +41,15 @@ class OperationBase(nn.Module):
Convention:
- this wrapper owns a probability parameter and, when configured, one learnable magnitude. The
``probability`` property clamps to the closed interval ``[1e-7, 1 - 1e-7]`` and ``magnitude`` clamps to
- the wrapped generator's configured range. ``forward_parameters`` builds a (relaxed) Bernoulli sampler
- from that probability, but nothing reads it: the gate is drawn from the wrapped augmentation's own float
- ``p`` and ``p_batch``, the sampled ``batch_prob`` is a hard ``0`` or ``1``, and the probability parameter
- receives no gradient (`#4656 <https://github.com/kornia/kornia/issues/4656>`_). It then draws the wrapped
- augmentation's parameters and substitutes the supplied or learned magnitude.
+ the wrapped generator's configured range. The probability parameter is initialized from the wrapped
+ augmentation's ``p`` (``p_batch`` for a batch operation) and kept in ``state_dict()`` for API and
+ checkpoint compatibility; it does not take part in sampling. The gate is drawn from the wrapped
+ augmentation's own float ``p`` and ``p_batch``, the sampled ``batch_prob`` is a hard ``0`` or ``1``, and
+ the probability parameter receives no gradient, while the magnitude does. ``forward_parameters`` draws
+ the wrapped augmentation's parameters and substitutes the supplied or learned magnitude. The wrapper
+ builds no probability sampler, on itself or on the wrapped augmentation, which keeps its own parameter
+ samplers; ``copy.deepcopy`` therefore works before and after a forward pass or a ``train()`` / ``eval()``
+ call.
- ``forward`` linearly blends the wrapped augmentation's output with the input using ``batch_prob``.
With supplied fractional gates, the wrapped augmentation first keeps rows whose gate is at most ``0.5``
unchanged, unless both its ``p`` and ``p_batch`` equal ``1``. Only that unconditional configuration
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index 5d4ff1d95..c6ca04e97 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -45,7 +45,7 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
:meth:`~kornia.augmentation.auto.operations.OperationBase.forward_parameters`.
It consequently samples the wrapped operation's native
magnitude instead of the ``OperationBase`` magnitude mapping; the gate comes from the wrapped
- augmentation's ``p`` on both paths (`#4656 <https://github.com/kornia/kornia/issues/4656>`_). Tracked
+ augmentation's ``p`` on both paths. The magnitude bypass is tracked
in `#4441 <https://github.com/kornia/kornia/issues/4441>`_. Policy augmentations use their own
samplers where needed.
diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.py
index d676f68a1..c3bc3d0a8 100644
--- a/kornia/augmentation/auto/rand_augment/rand_augment.py
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -58,13 +58,15 @@ class RandAugment(PolicyAugmentBase):
- ``m`` must be strictly between ``0`` and ``30``. For every magnitude-bearing selected operation it
sets a per-row magnitude to ``low + (high - low) * m / 30`` over that operation's magnitude range. For a
symmetric operation that range is ``(0, max)`` and each row independently gets a positive or negative
- sign, so ``m=15`` on ``("rotate", -30, 30)`` gives ``+15`` or ``-15``. That value then passes through
- the wrapper's magnitude mapping, which is the identity for every default entry except three:
- ``shear_x`` / ``shear_y`` multiply it by ``180``, so ``m=15`` on the default ``("shear_x", -0.3, 0.3)``
- shears by ``27`` degrees and not by ``0.15``; ``posterize`` truncates it to integer bits (``0`` for
- ``m < 7.5`` with the default entry, an all-black image); and ``translate_x`` / ``translate_y`` take it
- as pixels, not as a fraction of the image size
- (`#4655 <https://github.com/kornia/kornia/issues/4655>`_).
+ sign, so ``m=15`` on ``("rotate", -30, 30)`` gives ``+15`` or ``-15``. Two kinds of entry depart from
+ that formula. ``posterize`` runs its range backwards, ``high - (high - low) * m / 30``, so a larger ``m``
+ keeps fewer bits. A ``translate_x`` / ``translate_y`` range is a fraction of the image width / height
+ and the value is multiplied by that size, so ``m=15`` on the default ``("translate_x", -0.1, 0.1)`` shifts
+ a 32-pixel-wide image by ``1.6`` pixels either way. The value then passes through the wrapper's magnitude
+ mapping, which is the identity for every default entry except three: ``shear_x`` / ``shear_y`` multiply
+ it by ``180``, so ``m=15`` on the default ``("shear_x", -0.3, 0.3)`` shears by ``27`` degrees and not by
+ ``0.15``, and ``posterize`` truncates it to integer bits, so the default ``("posterize", 4.0, 8.0)``
+ keeps ``7`` bits at ``m=7``, ``6`` at ``m=15`` and ``4`` at ``m=29``.
Args:
n: the number of augmentations to apply sequentially. Must be at least ``1`` and at
diff --git a/tests/augmentation/test_conventions_auto.py b/tests/augmentation/test_conventions_auto.py
index 9a3d72744..2f74f9973 100644
--- a/tests/augmentation/test_conventions_auto.py
+++ b/tests/augmentation/test_conventions_auto.py
@@ -340,18 +340,24 @@ class TestAutoAugmentConventions(BaseTester):
self.assert_close(bits, torch.full_like(bits, 5), rtol=0, atol=0)
@pytest.mark.device_agnostic
- def test_wart_randaugment_posterize_and_translate_units_4655(self):
- image = torch.rand(4, 3, 32, 32)
- posterize = RandAugment(n=1, m=7, policy=[[("posterize", 0.0, 4)]])
- output = posterize(image)
- assert posterize._params[0].data[0].data["bits_factor"].tolist() == [0, 0, 0, 0]
- self.assert_close(output, torch.zeros_like(image))
- translate = RandAugment(n=1, m=29, policy=[[("translate_x", -0.5, 0.5)]])
- pixels = translate.forward_parameters(image.shape)[0].data[0].data["translate_x"]
- self.assert_close(pixels.abs(), torch.full_like(pixels, 0.5 * 29 / 30))
+ def test_convention_randaugment_posterize_and_translate_units_4655(self):
+ from kornia.enhance import posterize as posterize_bits
+
+ image = torch.rand(4, 3, 20, 32)
+ # The range runs backwards, high - (high - low) * m / 30, and is then truncated: a larger m keeps fewer bits.
+ for m, bits in ((7, 7), (15, 6), (29, 4)):
+ posterize = RandAugment(n=1, m=m, policy=[[("posterize", 4.0, 8.0)]])
+ output = posterize(image)
+ assert posterize._params[0].data[0].data["bits_factor"].tolist() == [bits] * 4
+ self.assert_close(output, posterize_bits(image, bits), rtol=0, atol=0)
+ # A translate range is a fraction of the width (x) or the height (y); H != W tells the two apart.
+ for name, pixels in (("translate_x", 0.05 * 32), ("translate_y", 0.05 * 20)):
+ translate = RandAugment(n=1, m=15, policy=[[(name, -0.1, 0.1)]])
+ drawn = translate.forward_parameters(image.shape)[0].data[0].data[name]
+ self.assert_close(drawn.abs(), torch.full_like(drawn, pixels))
@pytest.mark.device_agnostic
- def test_wart_operation_probability_parameter_is_inert_4656(self):
+ def test_convention_operation_probability_parameter_is_inert_4656(self):
import copy
gates = []
@@ -369,20 +375,17 @@ class TestAutoAugmentConventions(BaseTester):
operation(torch.rand(8, 3, 4, 4)).sum().backward()
assert operation._probability.grad is None
assert operation._magnitude.grad is not None
- policy = RandAugment(n=2, m=15)
- copy.deepcopy(policy)
- policy(torch.rand(2, 3, 8, 8))
- with pytest.raises(RuntimeError, match="graph leaves"):
+ # The parameter is kept in the state dict, and no sampler is stored on the wrapper or the wrapped op.
+ assert "_probability" in operation.state_dict()
+ assert not hasattr(operation.op, "_p_gen") and not hasattr(operation.op, "_p_batch_gen")
+ # So a policy deep-copies after a forward and after train() / eval(), and the copy replays the original.
+ image = torch.rand(2, 3, 8, 8)
+ for policy in (AutoAugment(), TrivialAugment(), RandAugment(n=2, m=15)):
copy.deepcopy(policy)
- # A forward is not the only trigger: train() / eval() rebuild the samplers on every policy, used or not,
- # while AutoAugment and TrivialAugment survive a forward because theirs bypasses the wrapper.
- for unused in (AutoAugment(), TrivialAugment(), RandAugment(n=2, m=15)):
- copy.deepcopy(unused)
- with pytest.raises(RuntimeError, match="graph leaves"):
- copy.deepcopy(unused.eval())
- for forwarded in (AutoAugment(), TrivialAugment()):
- forwarded(torch.rand(2, 3, 8, 8))
- copy.deepcopy(forwarded)
+ copy.deepcopy(policy.eval())
+ copy.deepcopy(policy.train())
+ output = policy(image)
+ self.assert_close(copy.deepcopy(policy)(image, params=policy._params), output, rtol=0, atol=0)
@pytest.mark.device_agnostic
def test_convention_randaugment_shear_passes_through_the_180_mapping(self):
@@ -504,6 +507,7 @@ class TestAutoAugmentConventions(BaseTester):
from kornia.augmentation.auto.rand_augment.rand_augment import default_policy
checked = []
+ height, width = 8, 6
for subpolicy in default_policy:
name = subpolicy[0][0]
aug = RandAugment(n=1, m=10, policy=[subpolicy])
@@ -515,8 +519,11 @@ class TestAutoAugmentConventions(BaseTester):
if name in ("shear_x", "shear_y"):
expected *= 180
elif name == "posterize":
- expected = math.floor(expected) # 4 * 10 / 30 = 1.33 -> 1 bit: truncation, not rounding
- drawn = aug.forward_parameters(torch.Size([8, 1, 8, 6]))[0].data[0].data[operation._factor_name]
+ # The range runs backwards: 8 - 4 * 10 / 30 = 6.67 -> 6 bits, truncation and not rounding.
+ expected = math.floor(high - (high - low) * 10 / 30)
+ elif name in ("translate_x", "translate_y"):
+ expected *= width if name == "translate_x" else height # a fraction of that side, in pixels
+ drawn = aug.forward_parameters(torch.Size([8, 1, height, width]))[0].data[0].data[operation._factor_name]
self.assert_close(drawn.abs().float(), torch.full((8,), float(expected)))
checked.append(name)
assert len(checked) == 12 and {"shear_x", "shear_y", "posterize", "translate_x", "translate_y"} <= set(checked)
diff --git a/tests/augmentation/test_conventions_mix.py b/tests/augmentation/test_conventions_mix.py
index dacdebe19..ee38dc14d 100644
--- a/tests/augmentation/test_conventions_mix.py
+++ b/tests/augmentation/test_conventions_mix.py
@@ -403,23 +403,58 @@ class TestMixConventions(BaseTester):
K.RandomCutMixV2(use_correct_lambda=True)
@pytest.mark.device_agnostic
- def test_wart_mixup_and_cutmix_apply_p_to_rows_a_second_time_4649(self):
- # #4649: inside a selected batch, rows are dropped again with probability 1 - p.
+ def test_convention_mixup_and_cutmix_apply_p_once_per_batch_4649(self):
+ from kornia.geometry.bbox import infer_bbox_shape
+
+ # ``p`` selects the whole batch; inside a selected batch no row (or mix) is dropped a second time.
mixup = K.RandomMixUpV2(p=0.5, lambda_val=(0.5, 0.5))
- cutmix = K.RandomCutMixV2(p=0.5, cut_size=(0.5, 0.5), use_correct_lambda=True)
- image = torch.rand(8, 1, 8, 8)
- mixup_rows, cutmix_rows = [], []
- for seed in range(40):
+ cutmix = K.RandomCutMixV2(p=0.5, cut_size=(0.5, 0.5), num_mix=2, use_correct_lambda=True)
+ shape = torch.Size([8, 1, 8, 8])
+
+ def mixup_rows(params):
+ return params["mixup_lambdas"] > 0
+
+ def cutmix_rows(params): # one (B, 4, 2) box set per mix
+ sides = [torch.stack(infer_bbox_shape(boxes)) for boxes in params["crop_src"]]
+ return (torch.stack(sides) > 0).flatten()
+
+ for aug, mixed in ((mixup, mixup_rows), (cutmix, cutmix_rows)):
+ rows = []
+ for seed in range(40):
+ torch.manual_seed(seed)
+ params = aug.forward_parameters(shape)
+ gate = params["batch_prob"]
+ assert bool((gate == gate[0]).all()) # all ones or all zeros
+ if gate[0] > 0:
+ rows.append(mixed(params))
+ assert 10 <= len(rows) <= 30 # the batch gate itself still fires at rate p
+ assert bool(torch.cat(rows).all())
+
+ @pytest.mark.device_agnostic
+ def test_convention_cutmix_same_on_batch_shares_cut_geometry(self):
+ from kornia.geometry.bbox import infer_bbox_shape
+
+ # The default ``cut_size`` lets the sizes vary, so sharing is what makes the boxes equal: a fixed
+ # ``cut_size`` would pass with ``same_on_batch=False`` as well.
+ shape = torch.Size([8, 1, 64, 48])
+ for seed in range(10):
+ torch.manual_seed(seed)
+ shared = K.RandomCutMixV2(p=1.0, num_mix=2, same_on_batch=True, use_correct_lambda=True)
+ crop_src = shared.forward_parameters(shape)["crop_src"]
+ self.assert_close(crop_src, crop_src[0, 0].expand_as(crop_src), rtol=0, atol=0)
+ independent = K.RandomCutMixV2(p=1.0, num_mix=2, same_on_batch=False, use_correct_lambda=True)
+ heights, widths = infer_bbox_shape(independent.forward_parameters(shape)["crop_src"].flatten(0, 1))
+ assert heights.unique().numel() > 1 and widths.unique().numel() > 1
+
+ @pytest.mark.device_agnostic
+ def test_wart_cutmix_placement_is_one_shared_draw_4712(self):
+ # #4712: with the size fixed, only the placement could differ, and it never does with same_on_batch=False.
+ shape = torch.Size([8, 1, 64, 48])
+ for seed in range(10):
torch.manual_seed(seed)
- params = mixup.forward_parameters(image.shape)
- if params["batch_prob"].all():
- mixup_rows.append(params["mixup_lambdas"] > 0)
- output = cutmix(image)
- if cutmix._params["batch_prob"].all():
- cutmix_rows.append((output != image).flatten(1).any(1))
- for rows in (torch.cat(mixup_rows), torch.cat(cutmix_rows)):
- assert rows.numel() >= 64
- assert 0.3 < rows.float().mean() < 0.7
+ aug = K.RandomCutMixV2(p=1.0, cut_size=(0.5, 0.5), num_mix=2, same_on_batch=False, use_correct_lambda=True)
+ crop_src = aug.forward_parameters(shape)["crop_src"]
+ self.assert_close(crop_src, crop_src[0, 0].expand_as(crop_src), rtol=0, atol=0)
@pytest.mark.device_agnostic
@pytest.mark.parametrize("p", [0.0, 1.0])