Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): map the auto shear magnitude to degrees with rad2deg(atan) (#6252)

Suryakant Sahoo459aa0a8029f
diff --git a/changelog.d/6252.fixed.md b/changelog.d/6252.fixed.md
new file mode 100644
index 000000000..bf3863005
--- /dev/null
+++ b/changelog.d/6252.fixed.md
@@ -0,0 +1 @@
+`ShearX` and `ShearY` in `kornia.augmentation.auto.operations`, and with them the `shear_x` / `shear_y` entries of `AutoAugment`, `RandAugment` and `TrivialAugment`, now read the magnitude as a shear factor and map it to degrees with `rad2deg(atan(magnitude))`, as torchvision does. They used to multiply it by 180, so the top of the default range, 0.3, sheared by 54 degrees (a shear factor of 1.38) instead of about 16.7 degrees (a factor of 0.3).
diff --git a/kornia/augmentation/auto/autoaugment/autoaugment.py b/kornia/augmentation/auto/autoaugment/autoaugment.py
index 69b565baa..a3c1ba539 100644
--- a/kornia/augmentation/auto/autoaugment/autoaugment.py
+++ b/kornia/augmentation/auto/autoaugment/autoaugment.py
@@ -127,8 +127,8 @@ class AutoAugment(PolicyAugmentBase):
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``), ``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.
+ pixels, and ``shear_x`` / ``shear_y``, whose scale is a shear factor from ``-0.3`` to ``0.3``, map
+ it to degrees with ``rad2deg(atan(x))``, as torchvision does.
Args:
policy: a customized policy config or presets of "imagenet", "cifar10", and "svhn".
diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.py
index 95dbbcc68..effdfa993 100644
--- a/kornia/augmentation/auto/operations/ops.py
+++ b/kornia/augmentation/auto/operations/ops.py
@@ -446,8 +446,12 @@ class Rotate(OperationBase):
class ShearX(OperationBase):
"""Apply shear operation along x-axis.
+ The magnitude is the shear factor, as in PIL and torchvision, whether it is sampled from ``magnitude_range``,
+ learned, or passed to :meth:`forward_parameters`. It is mapped to the wrapped augmentation's degrees with
+ ``rad2deg(atan(magnitude))``, so a magnitude of ``0.3`` shears by about ``16.7`` degrees.
+
Args:
- initial_magnitude: the initial magnitude.
+ initial_magnitude: the initial magnitude, a shear factor.
initial_probability: the initial probability. If None, the augmentation will be randomly
applied according to he augmentation sampling range.
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
@@ -458,8 +462,9 @@ class ShearX(OperationBase):
@staticmethod
def _process_magnitude(magnitude: torch.Tensor) -> torch.Tensor:
- # make it sign-agnostic
- return magnitude * 180
+ # the magnitude is the shear factor; map it to degrees as torchvision
+ # does (atan keeps the sign)
+ return torch.atan(magnitude) * 57.29577951308232 # 180/pi; aten::rad2deg is not ONNX-exportable
def __init__(
self,
@@ -486,8 +491,12 @@ class ShearX(OperationBase):
class ShearY(OperationBase):
"""Apply shear operation along y-axis.
+ The magnitude is the shear factor, as in PIL and torchvision, whether it is sampled from ``magnitude_range``,
+ learned, or passed to :meth:`forward_parameters`. It is mapped to the wrapped augmentation's degrees with
+ ``rad2deg(atan(magnitude))``, so a magnitude of ``0.3`` shears by about ``16.7`` degrees.
+
Args:
- initial_magnitude: the initial magnitude.
+ initial_magnitude: the initial magnitude, a shear factor.
initial_probability: the initial probability. If None, the augmentation will be randomly
applied according to he augmentation sampling range.
magnitude_range: the sampling range for random sampling and clamping the optimized magnitude.
@@ -498,8 +507,9 @@ class ShearY(OperationBase):
@staticmethod
def _process_magnitude(magnitude: torch.Tensor) -> torch.Tensor:
- # make it sign-agnostic
- return magnitude * 180
+ # the magnitude is the shear factor; map it to degrees as torchvision
+ # does (atan keeps the sign)
+ return torch.atan(magnitude) * 57.29577951308232 # 180/pi; aten::rad2deg is not ONNX-exportable
def __init__(
self,
diff --git a/kornia/augmentation/auto/rand_augment/rand_augment.py b/kornia/augmentation/auto/rand_augment/rand_augment.py
index 2c0ee9cb0..9c6d6b2df 100644
--- a/kornia/augmentation/auto/rand_augment/rand_augment.py
+++ b/kornia/augmentation/auto/rand_augment/rand_augment.py
@@ -60,10 +60,10 @@ class RandAugment(PolicyAugmentBase):
``(0, max)`` with a random sign per row: ``m=15`` on ``("rotate", -30, 30)`` gives ``+15`` or ``-15``. A
``translate_x`` / ``translate_y`` value is a fraction of the image width / height, applied in pixels.
The operation's magnitude mapping is the identity for every default entry except ``shear_x`` /
- ``shear_y``, which multiply by ``180`` (``27`` degrees at ``m=15`` for the default range), and
- ``posterize``, which truncates to integer bits. ``posterize`` also runs its range backwards,
- ``high - (high - low) * m / 30``, so a larger ``m`` keeps fewer bits (``7``, ``6`` and ``4`` at ``m=7``,
- ``15`` and ``29``).
+ ``shear_y``, which map the shear factor to degrees with ``rad2deg(atan(x))`` (about ``8.5`` degrees at
+ ``m=15`` for the default range), and ``posterize``, which truncates to integer bits. ``posterize`` also
+ runs its range backwards, ``high - (high - low) * m / 30``, so a larger ``m`` keeps fewer bits (``7``,
+ ``6`` and ``4`` at ``m=7``, ``15`` and ``29``).
Args:
n: the number of augmentations to apply sequentially. Must be at least ``1`` and at
diff --git a/kornia/augmentation/auto/trivial_augment/trivial_augment.py b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
index 49bfcac1b..79caa4ff3 100644
--- a/kornia/augmentation/auto/trivial_augment/trivial_augment.py
+++ b/kornia/augmentation/auto/trivial_augment/trivial_augment.py
@@ -58,7 +58,8 @@ class TrivialAugment(PolicyAugmentBase):
independently for every batch row.
- 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.
+ ``[-30, 30]`` with a random sign, and ``("shear_x", -0.3, 0.3)`` shears by up to ``rad2deg(atan(0.3))``,
+ about ``16.7`` degrees.
- the default ``posterize`` candidate keeps ``4`` to ``8`` bits, the range of the paper's RA
augmentation space (Table 8) and of :class:`~kornia.augmentation.auto.RandAugment`.
diff --git a/tests/augmentation/test_conventions_auto.py b/tests/augmentation/test_conventions_auto.py
index b44c88591..100e9c84d 100644
--- a/tests/augmentation/test_conventions_auto.py
+++ b/tests/augmentation/test_conventions_auto.py
@@ -261,7 +261,7 @@ class TestAutoAugmentConventions(BaseTester):
nonzero = ops.Posterize(initial_magnitude=5.5, magnitude_range=(0.0, 8.0), symmetric_megnitude=True)
signed = nonzero.forward_parameters(torch.Size([64, 1, 1, 1]))["bits_factor"]
assert set(signed.tolist()) == {5, -5}
- # Every built-in mapping is odd (identity, x * 180, truncation), so {5, -5} holds for either order. A
+ # Every built-in mapping is odd (identity, rad2deg(atan(x)), truncation), so {5, -5} holds for either order. A
# mapping that is not odd separates them: sign after gives {13, -13}, sign before would give {13, 7}.
from kornia.augmentation import RandomRotation
from kornia.augmentation.auto.operations.base import OperationBase
@@ -461,7 +461,11 @@ class TestAutoAugmentConventions(BaseTester):
@pytest.mark.device_agnostic
def test_convention_policy_shear_entries_are_mapped_to_degrees_4441(self):
- # #4441: every policy applies ShearX's 180 factor, so ("shear_x", -0.3, 0.3) shears by up to 54 degrees.
+ # #4441: every policy applies ShearX's mapping, so ("shear_x", -0.3, 0.3) shears by up to
+ # rad2deg(atan(0.3)), about 16.7 degrees (#6250: the magnitude is the shear factor).
+ import math
+
+ bound = math.degrees(math.atan(0.3))
torch.manual_seed(17)
trivial = (
TrivialAugment(policy=[[("shear_x", -0.3, 0.3)]])
@@ -469,16 +473,17 @@ class TestAutoAugmentConventions(BaseTester):
.data[0]
.data["shear_x"]
)
- assert bool((trivial.abs() <= 0.3 * 180).all())
- assert trivial.abs().max() > 30.0
+ assert bool((trivial.abs() <= bound + 1e-3).all())
+ assert trivial.abs().max() > 15.0
assert (trivial < 0).any()
assert (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.
+ # AutoAugment's shear bins are factors too, so the mapping is applied once: bin b of either shear op spans
+ # rad2deg(atan) of the adjacent points b and b + 1 of linspace(-0.3, 0.3, 11), 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
+ low = math.degrees(math.atan(edges[magnitude_bin]))
+ high = math.degrees(math.atan(edges[magnitude_bin + 1]))
auto = (
AutoAugment(policy=[[(name, 1.0, magnitude_bin)]])
.forward_parameters(torch.Size([256, 1, 8, 6]))[0]
@@ -496,7 +501,20 @@ class TestAutoAugmentConventions(BaseTester):
.data[0]
.data["shear_x"]
)
- self.assert_close(mapped.abs(), torch.full_like(mapped, 0.29 * 180))
+ self.assert_close(mapped.abs(), torch.full_like(mapped, math.degrees(math.atan(0.29))))
+
+ @pytest.mark.device_agnostic
+ def test_shear_magnitude_is_the_shear_factor_6250(self):
+ # #6250: ShearX(0.3) shears by rad2deg(atan(0.3)), about 16.7 degrees, so the shear
+ # matrix off-diagonal is the factor 0.3 (up to sign), not tan(54 degrees) = 1.38.
+ import math
+
+ operation = ops.ShearX(initial_magnitude=0.3, initial_probability=1.0, symmetric_megnitude=False)
+ image = torch.zeros(1, 3, 32, 32)
+ params = operation.forward_parameters(image.shape)
+ self.assert_close(params["shear_x"], torch.full_like(params["shear_x"], math.degrees(math.atan(0.3))))
+ matrix = operation.op.compute_transformation(image, params, operation.op.flags)
+ self.assert_close(matrix[0, 0, 1].abs(), torch.full_like(matrix[0, 0, 1], 0.3))
@pytest.mark.device_agnostic
def test_convention_operation_wrappers_pickle_and_replay_4469(self):
@@ -570,7 +588,7 @@ class TestAutoAugmentConventions(BaseTester):
low, high = (float(bound) for bound in operation.magnitude_range)
expected = low + (high - low) * 10 / 30
if name in ("shear_x", "shear_y"):
- expected *= 180
+ expected = math.degrees(math.atan(expected))
elif name == "posterize":
# The range runs backwards: 8 - 4 * 10 / 30 = 6.67 -> 6 bits, truncation and not rounding.
expected = math.floor(high - (high - low) * 10 / 30)