Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): draw a two-value RandomAffine3D scale once per sample (#4731)

abhijeet sharma41331665247c
diff --git a/changelog.d/4731.fixed.md b/changelog.d/4731.fixed.md
new file mode 100644
index 000000000..c2f18a166
--- /dev/null
+++ b/changelog.d/4731.fixed.md
@@ -0,0 +1 @@
+`RandomAffine3D` and `AffineGenerator3D` now draw a two-value `scale=(a, b)` once per sample and apply it to all three axes, as the docstring says and as the 2D `RandomAffine` does; each axis used to be drawn independently. The three-pair form `((a, b), (c, d), (e, f))` is unchanged. The random stream for a fixed seed changes for the two-value form: the scale consumes one draw instead of three, so the translations and shears drawn after it move.
diff --git a/kornia/augmentation/_3d/geometric/affine.py b/kornia/augmentation/_3d/geometric/affine.py
index 25cd505f5..ca19249c2 100644
--- a/kornia/augmentation/_3d/geometric/affine.py
+++ b/kornia/augmentation/_3d/geometric/affine.py
@@ -83,9 +83,9 @@ class RandomAffine3D(GeometricAugmentationBase3D):
unit scale, and zero shear, it reproduces the input at that setting up to floating-point roundoff in
``float32`` and ``float64``. In half precision the sampling grid itself is rounded, so the error grows
with the volume size (about ``0.5`` for a ``32 x 48 x 96`` volume in ``bfloat16``).
- - a two-value ``scale=(a, b)`` is documented as isotropic but currently draws the three axes
- independently, unlike the 2D :class:`~kornia.augmentation.RandomAffine`
- (`#4704 <https://github.com/kornia/kornia/issues/4704>`_).
+ - a two-value ``scale=(a, b)`` is isotropic: one factor per sample is drawn from ``[a, b]`` and applied
+ to all three axes, as the 2D :class:`~kornia.augmentation.RandomAffine` does. The three-pair form
+ ``((a, b), (c, d), (e, f))`` draws each axis independently.
Examples:
>>> import torch
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index c8935c2fe..4659779a7 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -142,20 +142,25 @@ class AffineGenerator3D(RandomGeneratorBase):
# check scale range
self._scale: Optional[torch.Tensor] = None
+ self._isotropic_scale: bool = False
if self.scale is not None:
_scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
if _scale.shape == torch.Size([2]):
+ # (a, b) is isotropic: one factor per sample is drawn and used on all three axes.
+ _singular_range_check(_scale, "scale", bounds=(0, float("inf")), mode="2d")
self._scale = _scale.unsqueeze(0).repeat(3, 1)
+ self._isotropic_scale = True
+ self.scale_sampler = UniformDistribution(_scale[0], _scale[1], validate_args=False)
elif _scale.shape != torch.Size([3, 2]):
raise ValueError(f"'scale' shall be either shape (2) or (3, 2). Got {self.scale}.")
else:
self._scale = _scale
- _singular_range_check(self._scale[0], "scale-x", bounds=(0, float("inf")), mode="2d")
- _singular_range_check(self._scale[1], "scale-y", bounds=(0, float("inf")), mode="2d")
- _singular_range_check(self._scale[2], "scale-z", bounds=(0, float("inf")), mode="2d")
- self.scale_1_sampler = UniformDistribution(self._scale[0, 0], self._scale[0, 1], validate_args=False)
- self.scale_2_sampler = UniformDistribution(self._scale[1, 0], self._scale[1, 1], validate_args=False)
- self.scale_3_sampler = UniformDistribution(self._scale[2, 0], self._scale[2, 1], validate_args=False)
+ _singular_range_check(self._scale[0], "scale-x", bounds=(0, float("inf")), mode="2d")
+ _singular_range_check(self._scale[1], "scale-y", bounds=(0, float("inf")), mode="2d")
+ _singular_range_check(self._scale[2], "scale-z", bounds=(0, float("inf")), mode="2d")
+ self.scale_1_sampler = UniformDistribution(self._scale[0, 0], self._scale[0, 1], validate_args=False)
+ self.scale_2_sampler = UniformDistribution(self._scale[1, 0], self._scale[1, 1], validate_args=False)
+ self.scale_3_sampler = UniformDistribution(self._scale[2, 0], self._scale[2, 1], validate_args=False)
self.yaw_sampler = UniformDistribution(degrees[0][0], degrees[0][1], validate_args=False)
self.pitch_sampler = UniformDistribution(degrees[1][0], degrees[1][1], validate_args=False)
@@ -186,7 +191,9 @@ class AffineGenerator3D(RandomGeneratorBase):
angles = torch.stack([yaw, pitch, roll], dim=1)
# compute tensor ranges
- if self._scale is not None:
+ if self._scale is not None and self._isotropic_scale:
+ scale = _adapted_rsampling((batch_size,), self.scale_sampler, same_on_batch).unsqueeze(1).repeat(1, 3)
+ elif self._scale is not None:
scale = torch.stack(
[
_adapted_rsampling((batch_size,), self.scale_1_sampler, same_on_batch),
diff --git a/tests/augmentation/test_conventions_3d.py b/tests/augmentation/test_conventions_3d.py
index 0766b7516..a52fc6285 100644
--- a/tests/augmentation/test_conventions_3d.py
+++ b/tests/augmentation/test_conventions_3d.py
@@ -488,16 +488,29 @@ class Test3DAugmentationConventions(BaseTester):
aug(volume, params=params)
@pytest.mark.device_agnostic
- def test_wart_random_affine3d_two_value_scale_is_not_isotropic_4704(self):
- # Documented as isotropic; the 2D class draws one value per sample, the 3D class one per axis.
+ def test_convention_random_affine3d_two_value_scale_is_isotropic_4704(self):
+ # A two-value scale draws one factor per sample for all three axes, as the 2D class does; the
+ # three-pair form keeps one independent draw per axis.
flat = K.RandomAffine(0.0, scale=(0.5, 2.0), p=1.0).forward_parameters(torch.Size([64, 1, 6, 7]))["scale"]
assert bool((flat[:, 0] == flat[:, 1]).all())
aug = K.RandomAffine3D(0.0, scale=(0.5, 2.0), p=1.0)
aug(torch.rand(64, 1, 5, 6, 7))
scale = aug._params["scale"]
assert scale.shape == (64, 3)
- assert not bool((scale[:, 0] == scale[:, 1]).any()) and not bool((scale[:, 1] == scale[:, 2]).any())
+ assert bool((scale[:, 0] == scale[:, 1]).all()) and bool((scale[:, 1] == scale[:, 2]).all())
+ assert 0.5 <= float(scale.min()) and float(scale.max()) <= 2.0
+ assert len(scale[:, 0].unique()) > 1
self.assert_close(aug.transform_matrix[:, :3, :3].diagonal(dim1=-2, dim2=-1), scale)
+ shared = K.RandomAffine3D(0.0, scale=(0.5, 2.0), same_on_batch=True, p=1.0)
+ shared_scale = shared.forward_parameters(torch.Size([64, 1, 5, 6, 7]))["scale"]
+ assert len(shared_scale.unique()) == 1
+ per_axis = K.RandomAffine3D(0.0, scale=((0.5, 2.0), (0.5, 2.0), (0.5, 2.0)), p=1.0)
+ axes = per_axis.forward_parameters(torch.Size([64, 1, 5, 6, 7]))["scale"]
+ assert axes.shape == (64, 3)
+ assert not bool((axes[:, 0] == axes[:, 1]).any()) and not bool((axes[:, 1] == axes[:, 2]).any())
+ # The two-value form is range-checked once under its own name; main reported it as "scale-x".
+ with pytest.raises(ValueError, match="scale out of bounds"):
+ K.RandomAffine3D(0.0, scale=(-0.5, 2.0), p=1.0)
@pytest.mark.device_agnostic
def test_convention_random_affine3d_six_pair_shears_keep_their_lower_bound(self):