Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): sample PolicySequential operations through their wrapper (#4761)

Aditya Malkara15ca510268d
diff --git a/changelog.d/4495.fixed.md b/changelog.d/4495.fixed.md
index 23d49ef82..fdd7f49c6 100644
--- a/changelog.d/4495.fixed.md
+++ b/changelog.d/4495.fixed.md
@@ -3,6 +3,6 @@
mask rather than a sign, so these ops never drew a negative magnitude: rows meant to get `-m` got
`0`, a silent no-op on roughly half of their draws. This reaches the five ops used directly and
`RandAugment`. `AutoAugment` builds them with `symmetric_megnitude=False` and is unaffected;
-`TrivialAugment` samples without the sign and is also unaffected, tracked separately in #4441. For a
+`TrivialAugment` skipped the sign altogether and is covered by #4761 instead (#4441). For a
seeded pipeline the random stream, the ops picked and the rows that already drew `+m` are unchanged;
only the rows that drew `0` now draw `-m`. (#4440, #4494)
diff --git a/changelog.d/4761.breaking.md b/changelog.d/4761.breaking.md
new file mode 100644
index 000000000..7fa1c4e7d
--- /dev/null
+++ b/changelog.d/4761.breaking.md
@@ -0,0 +1,11 @@
+`TrivialAugment`, and `PolicySequential` when used directly, now sample each operation through its
+`OperationBase` wrapper, so a policy entry means what it means under `RandAugment`. They used to call the
+wrapped augmentation's own sampler, which skipped the wrapper's magnitude mapping: `("shear_x", -0.3, 0.3)`
+sheared by at most `0.3` degrees instead of up to `54`, and the symmetric ops (`rotate`, `shear_x`,
+`shear_y`, `translate_x`, `translate_y`) never drew a negative magnitude. A `PolicySequential` built from
+operations with an `initial_magnitude` used to ignore it; it now uses that magnitude, as the wrapper does,
+and the magnitude receives a gradient. For a fixed seed, `TrivialAugment` now draws different magnitudes,
+and a symmetric op draws its random signs from the global generator, so every later random draw in the
+pipeline changes as well. `AutoAugment` samples as before, up to float32 rounding of the shear values: its
+shear bins were pre-scaled to degrees to work around the skipped mapping and are now fractions, which the
+mapping scales once. Fixes #4441.
diff --git a/kornia/augmentation/auto/autoaugment/autoaugment.py b/kornia/augmentation/auto/autoaugment/autoaugment.py
index 212d55d97..69474442f 100644
--- a/kornia/augmentation/auto/autoaugment/autoaugment.py
+++ b/kornia/augmentation/auto/autoaugment/autoaugment.py
@@ -126,8 +126,9 @@ class AutoAugment(PolicyAugmentBase):
through ``9`` are valid for operations with a magnitude; operations that ignore magnitude accept any
value. The wrapped operation samples a value inside its selected interval for every batch row;
``posterize`` then rounds to the nearest integer number of bits (so bin ``1``, spanning ``4.4`` to
- ``4.8``, produces ``4`` or ``5``), and ``translate_x`` / ``translate_y``
- multiply it by the image size in pixels.
+ ``4.8``, produces ``4`` or ``5``), ``translate_x`` / ``translate_y`` multiply it by the image size in
+ pixels, and ``shear_x`` / ``shear_y``, whose scale is a shear fraction from ``-0.3`` to ``0.3``, multiply
+ it by ``180`` to give degrees.
Args:
policy: a customized policy config or presets of "imagenet", "cifar10", and "svhn".
diff --git a/kornia/augmentation/auto/autoaugment/ops.py b/kornia/augmentation/auto/autoaugment/ops.py
index 75671b152..05c685aa2 100644
--- a/kornia/augmentation/auto/autoaugment/ops.py
+++ b/kornia/augmentation/auto/autoaugment/ops.py
@@ -67,7 +67,8 @@ def _magnitude_bin(magnitudes: torch.Tensor, magnitude: int, name: str) -> Tuple
def shear_x(probability: float, magnitude: int) -> OperationBase:
"""Return ShearX op."""
- magnitudes = torch.linspace(-0.3, 0.3, 11) * 180.0
+ # A shear fraction, which ShearX's magnitude mapping turns into degrees.
+ magnitudes = torch.linspace(-0.3, 0.3, 11)
return ShearX(
None,
probability,
@@ -78,7 +79,8 @@ def shear_x(probability: float, magnitude: int) -> OperationBase:
def shear_y(probability: float, magnitude: int) -> OperationBase:
"""Return ShearY op."""
- magnitudes = torch.linspace(-0.3, 0.3, 11) * 180.0
+ # A shear fraction, which ShearY's magnitude mapping turns into degrees.
+ magnitudes = torch.linspace(-0.3, 0.3, 11)
return ShearY(
None,
probability,
diff --git a/kornia/augmentation/auto/operations/base.py b/kornia/augmentation/auto/operations/base.py
index a1c3c9483..fb57a8ac9 100644
--- a/kornia/augmentation/auto/operations/base.py
+++ b/kornia/augmentation/auto/operations/base.py
@@ -58,10 +58,8 @@ class OperationBase(nn.Module):
- a symmetric magnitude first applies the configured magnitude mapping, then chooses an independent sign
for every row. Sign selection preserves the mapped magnitude, but the mapping can first quantize it to
zero. For example, ``Posterize`` maps ``0.5`` to zero with ``magnitude_range=(0, 8)``.
- - :class:`~kornia.augmentation.auto.PolicySequential` is a lower-level container. Its own sampler calls
- ``operation.op.forward_parameters`` directly, bypassing this wrapper's magnitude mapping. This is a
- distinct direct-use behavior, tracked in `#4441
- <https://github.com/kornia/kornia/issues/4441>`_.
+ - :class:`~kornia.augmentation.auto.PolicySequential` samples each operation through
+ ``forward_parameters``, so the magnitude mapping applies under every policy container.
- The concrete operation classes in ``kornia.augmentation.auto.operations.ops`` only configure this
wrapper around public 2D augmentations; their input, dtype, RNG, and replay contracts are those of
their wrapped augmentation and :doc:`/get-started/conventions`. Serialization is the exception: this
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index c6ca04e97..d9717c473 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -41,13 +41,11 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
replay the same operations through ``forward(input, params=...)``.
- its transformation matrix is the ordered product of its geometric wrapped operations. Intensity
operations do not contribute to that matrix.
- - direct ``forward_parameters`` delegates to each wrapped augmentation rather than to
- :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. The magnitude bypass is tracked
- in `#4441 <https://github.com/kornia/kornia/issues/4441>`_. Policy augmentations use their own
- samplers where needed.
+ - ``forward_parameters`` samples each child through
+ :meth:`~kornia.augmentation.auto.operations.OperationBase.forward_parameters`, so a policy entry gets
+ the operation's magnitude and magnitude mapping, including the random sign of a symmetric magnitude,
+ as it does under :class:`~kornia.augmentation.auto.RandAugment`. The gate comes from the wrapped
+ augmentation's ``p``. Policy augmentations use their own samplers where needed.
Args:
operations: the operations to perform, passed as positional arguments rather than as one list.
@@ -170,7 +168,7 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
mod_param: Union[Dict[str, torch.Tensor], List[ParamItem]]
for name, module in named_modules:
module = cast(OperationBase, module)
- mod_param = module.op.forward_parameters(batch_shape)
+ mod_param = module.forward_parameters(batch_shape)
param = ParamItem(name, mod_param)
params.append(param)
return params
diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
index 24984935d..99a18cc6b 100644
--- a/kornia/augmentation/auto/trivial_augment/trivial_augment.py
+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
@@ -55,11 +55,9 @@ class TrivialAugment(PolicyAugmentBase):
probability is sampled; a candidate's second and third entries are its magnitude range, not a
probability, unlike :class:`~kornia.augmentation.auto.AutoAugment`. Only the magnitude is drawn
independently for every batch row.
- - sampling bypasses the operation wrapper's magnitude mapping. For example, a ``("rotate", -30, 30)``
- candidate draws angles in ``[0, 30]`` without applying the random sign; for ``shear_x`` / ``shear_y``
- the same bypass also drops the mapping's factor of ``180``, so those candidates shear by at most
- ``0.3`` degrees. This follows the :class:`~kornia.augmentation.auto.PolicySequential` limitation
- tracked in `#4441 <https://github.com/kornia/kornia/issues/4441>`_.
+ - the operation wrapper's magnitude mapping applies, as under
+ :class:`~kornia.augmentation.auto.RandAugment`. A ``("rotate", -30, 30)`` candidate draws angles in
+ ``[-30, 30]`` with a random sign, and ``("shear_x", -0.3, 0.3)`` shears by up to ``0.3 * 180`` degrees.
Args:
policy: candidate transformations. If None, a default candidate list will be used.
diff --git a/tests/augmentation/test_conventions_auto.py b/tests/augmentation/test_conventions_auto.py
index 2f74f9973..18756f2ba 100644
--- a/tests/augmentation/test_conventions_auto.py
+++ b/tests/augmentation/test_conventions_auto.py
@@ -108,13 +108,15 @@ class TestAutoAugmentConventions(BaseTester):
assert degrees.min() < 1.0 and degrees.max() > 5.0
@pytest.mark.device_agnostic
- def test_wart_trivialaugment_bypasses_symmetric_magnitude_mapping_4441(self):
+ def test_convention_trivialaugment_applies_the_symmetric_magnitude_mapping_4441(self):
+ # #4441: TrivialAugment used to sample the wrapped augmentation directly, which skipped the random sign,
+ # so a symmetric op such as rotate only ever drew non-negative magnitudes.
torch.manual_seed(17)
aug = TrivialAugment(policy=[[("rotate", -30.0, 30.0)]])
degrees = aug.forward_parameters(torch.Size([64, 1, 8, 6]))[0].data[0].data["degrees"]
- assert (degrees >= 0.0).all()
- assert (degrees <= 30.0).all()
- assert degrees.min() < 5.0 and degrees.max() > 25.0
+ assert (degrees.abs() <= 30.0).all()
+ assert (degrees < 0).any() and (degrees > 0).any()
+ assert degrees.abs().min() < 5.0 and degrees.abs().max() > 25.0
@pytest.mark.device_agnostic
def test_convention_randaugment_maps_m_and_validates_the_policy_cardinality(self):
@@ -288,7 +290,10 @@ class TestAutoAugmentConventions(BaseTester):
self.assert_close(invert(image, params=params).flatten(), image.new_tensor(expected))
@pytest.mark.device_agnostic
- def test_wart_policy_sequential_bypasses_operation_wrapper_sampling_4441(self):
+ def test_convention_policy_sequential_samples_through_the_operation_wrapper_4441(self):
+ # #4441: PolicySequential used to call the wrapped augmentation's forward_parameters, so it ignored the
+ # wrapper's magnitude and magnitude mapping. The gate still comes from the wrapped augmentation's p, and
+ # the wrapper's probability parameter is still not consulted on either path.
operation = ops.Rotate(initial_magnitude=3.0, initial_probability=0.5)
direct_operation = ops.Rotate(initial_magnitude=3.0, initial_probability=0.5)
direct_policy = PolicySequential(direct_operation)
@@ -302,8 +307,9 @@ class TestAutoAugmentConventions(BaseTester):
direct_params = direct_policy.forward_parameters(shape)[0].data
self.assert_close(wrapped_params["degrees"].abs(), torch.full_like(wrapped_params["degrees"], 3.0))
- assert not torch.equal(direct_params["degrees"], wrapped_params["degrees"])
- assert not torch.allclose(direct_params["degrees"].abs(), torch.full_like(direct_params["degrees"], 3.0))
+ assert direct_params.keys() == wrapped_params.keys()
+ for key, value in wrapped_params.items():
+ self.assert_close(direct_params[key], value)
self.assert_close(operation.probability, torch.tensor([1e-7]))
assert direct_operation.op.p == 0.5
@@ -421,16 +427,33 @@ class TestAutoAugmentConventions(BaseTester):
assert magnitudes.unique().numel() == 8
@pytest.mark.device_agnostic
- def test_wart_trivialaugment_shear_bypass_drops_the_180_factor_4441(self):
+ def test_convention_policy_shear_entries_are_mapped_to_degrees_4441(self):
+ # #4441: TrivialAugment used to drop ShearX's 180 factor, so ("shear_x", -0.3, 0.3) sheared by at most
+ # 0.3 degrees, where RandAugment sheared by up to 54 degrees for the same entry.
torch.manual_seed(17)
- bypassed = (
+ trivial = (
TrivialAugment(policy=[[("shear_x", -0.3, 0.3)]])
.forward_parameters(torch.Size([64, 1, 8, 6]))[0]
.data[0]
.data["shear_x"]
)
- assert bool((bypassed.abs() <= 0.3).all()) and bypassed.abs().max() > 0.05
- # The same policy entry through RandAugment, which does apply the mapping.
+ assert bool((trivial.abs() <= 0.3 * 180).all()) and trivial.abs().max() > 30.0
+ assert (trivial < 0).any() and (trivial > 0).any()
+ # AutoAugment's shear bins are fractions too, so the mapping is applied once: bin b of either shear op spans
+ # the adjacent points b and b + 1 of linspace(-0.3, 0.3, 11), times 180, and 256 rows reach both ends.
+ edges = [-0.3 + 0.06 * point for point in range(11)]
+ for name in ("shear_x", "shear_y"):
+ for magnitude_bin in range(10):
+ low, high = edges[magnitude_bin] * 180, edges[magnitude_bin + 1] * 180
+ auto = (
+ AutoAugment(policy=[[(name, 1.0, magnitude_bin)]])
+ .forward_parameters(torch.Size([256, 1, 8, 6]))[0]
+ .data[0]
+ .data[name]
+ )
+ assert bool((auto >= low - 1e-3).all()) and bool((auto <= high + 1e-3).all()), (name, magnitude_bin)
+ assert auto.min() < low + 1.0 and auto.max() > high - 1.0, (name, magnitude_bin)
+ # The same policy entry through RandAugment, which always applied the mapping.
mapped = (
RandAugment(n=1, m=29, policy=[[("shear_x", -0.3, 0.3)]])
.forward_parameters(torch.Size([8, 1, 8, 6]))[0]