π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): draw RandomRotation90's times uniformly over its closed integer range (#6288)
Aryan Kumar0abac999ea88
diff --git a/changelog.d/6288.fixed.md b/changelog.d/6288.fixed.mdnew file mode 100644index 000000000..dce651f1a--- /dev/null+++ b/changelog.d/6288.fixed.md@@ -0,0 +1 @@+`RandomRotation90` now draws `times` uniformly over the whole numbers of its closed range. The draw used to be a continuous number that was then rounded, which gave the two end points half the probability of the others: `times=(-1, 1)` drew no turn about half of the time and each quarter turn about a quarter of the time (#4409). Seeded draws therefore differ from earlier releases, and an integer tensor range such as `torch.tensor([0, 2])` now draws its upper bound too, where it used to draw only `0` and `1`. A range with a fractional bound is drawn as before.diff --git a/kornia/augmentation/_2d/geometric/rotation.py b/kornia/augmentation/_2d/geometric/rotation.pyindex 87fbb8c50..58120811d 100644--- a/kornia/augmentation/_2d/geometric/rotation.py+++ b/kornia/augmentation/_2d/geometric/rotation.py@@ -148,7 +148,8 @@ class RandomRotation90(GeometricAugmentationBase2D):r"""Apply a random 90 * n degree rotation to a torch.Tensor image or a batch of torch.Tensor images.Args:- times: the range of n times 90 degree rotation needs to be applied.+ times: the range of n times 90 degree rotation needs to be applied. A range of whole numbers is closed:+ every whole number from the lower to the upper bound is drawn with the same probability.resample: Default: the interpolation mode.same_on_batch: apply the same transformation across the batch.align_corners: interpolation flag.@@ -163,8 +164,10 @@ class RandomRotation90(GeometricAugmentationBase2D):Convention:- See :class:`~kornia.augmentation.GeometricAugmentationBase2D` for coordinates, defaults and inverse.- a positive rounded ``times`` rotates the displayed image counter-clockwise by ``times * 90`` degrees.- - ``times`` is sampled from a continuous uniform range and rounded, and a non-square image keeps its- ``(H, W)`` shape (`#4409 <https://github.com/kornia/kornia/issues/4409>`_).+ - a range of whole numbers for ``times`` is closed and uniform: ``times=(-1, 1)`` gives a clockwise quarter+ turn, no turn and a counter-clockwise quarter turn with the same probability. A range with a fractional+ bound is still drawn continuously and rounded.+ - a non-square image keeps its ``(H, W)`` shape (`#4409 <https://github.com/kornia/kornia/issues/4409>`_)... note::This function internally uses :func:`kornia.geometry.transform.affine`. This version is relatively@@ -207,7 +210,7 @@ class RandomRotation90(GeometricAugmentationBase2D):keepdim: bool = False,) -> None:super().__init__(p=p, same_on_batch=same_on_batch, keepdim=keepdim)- self._param_generator = rg.PlainUniformGenerator((times, "times", 0.0, (-3, 3)))+ self._param_generator = rg.Rotation90Generator(times)self.flags = {"resample": Resample.get(resample), "align_corners": align_corners}diff --git a/kornia/augmentation/random_generator/_2d/__init__.py b/kornia/augmentation/random_generator/_2d/__init__.pyindex b43eda013..27225ae60 100644--- a/kornia/augmentation/random_generator/_2d/__init__.py+++ b/kornia/augmentation/random_generator/_2d/__init__.py@@ -40,6 +40,7 @@ from kornia.augmentation.random_generator._2d.probability import *from kornia.augmentation.random_generator._2d.random_rain import *from kornia.augmentation.random_generator._2d.rectangle_earase import *from kornia.augmentation.random_generator._2d.resize import *+from kornia.augmentation.random_generator._2d.rotation90 import *from kornia.augmentation.random_generator._2d.salt_pepper_noise import *from kornia.augmentation.random_generator._2d.shear import *from kornia.augmentation.random_generator._2d.translate import *diff --git a/kornia/augmentation/random_generator/_2d/rotation90.py b/kornia/augmentation/random_generator/_2d/rotation90.pynew file mode 100644index 000000000..6b52d2b56--- /dev/null+++ b/kornia/augmentation/random_generator/_2d/rotation90.py@@ -0,0 +1,78 @@+# LICENSE HEADER MANAGED BY add-license-header+#+# Copyright 2018 Kornia Team+#+# Licensed under the Apache License, Version 2.0 (the "License");+# you may not use this file except in compliance with the License.+# You may obtain a copy of the License at+#+# http://www.apache.org/licenses/LICENSE-2.0+#+# Unless required by applicable law or agreed to in writing, software+# distributed under the License is distributed on an "AS IS" BASIS,+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+# See the License for the specific language governing permissions and+# limitations under the License.+#++from __future__ import annotations++from typing import Any++import torch++from kornia.augmentation.random_generator._2d.plain_uniform import PlainUniformGenerator+from kornia.augmentation.random_generator.base import UniformDistribution+from kornia.augmentation.utils import _adapted_rsampling, _common_param_check+from kornia.core.utils import _extract_device_dtype++__all__ = ["Rotation90Generator"]+++class Rotation90Generator(PlainUniformGenerator):+ r"""Generate the number of quarter turns for a batch of images.++ The range is validated exactly as :class:`PlainUniformGenerator` validates it, with ``0.0`` as the center and+ ``(-3, 3)`` as the bounds. A range of whole numbers is closed and uniform: every whole number from the lower to+ the upper bound is drawn with the same probability. A range with a fractional bound keeps the continuous draw.++ Args:+ times: the range of whole numbers of 90 degree turns. A ``(low, high)`` pair, a ``(2,)`` shaped torch.Tensor,+ or a single number ``x`` for ``(-x, x)``.++ Returns:+ A dict of parameters to be passed for transformation.+ - times (torch.Tensor): the number of quarter turns, with a shape of (B,).++ Note:+ The generated random numbers are not reproducible across different devices and dtypes. By default,+ the parameters will be generated on CPU in float32. This can be changed by calling+ ``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.++ """++ def __init__(self, times: Any) -> None:+ super().__init__((times, "times", 0.0, (-3, 3)))+ self._whole_range = bool(self.times.to(torch.float64).round().eq(self.times).all())++ def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:+ super().make_samplers(device, dtype)+ if self._whole_range:+ # The sampler covers ``[lo, hi + 1)`` and ``forward`` floors the draw, so every whole number from ``lo``+ # to ``hi`` owns a bucket of width one. Rounding a draw on ``[lo, hi]`` gave the two end points half of+ # that width, so ``times=(-1, 1)`` drew ``0`` about twice as often as ``-1`` or ``1``.+ sampler = self.sampler_dict["times"]+ self.sampler_dict["times"] = UniformDistribution(sampler.low, sampler.high + 1, validate_args=False)++ def forward(self, batch_shape: tuple[int, ...], same_on_batch: bool = False) -> dict[str, torch.Tensor]:+ batch_size = batch_shape[0]+ _common_param_check(batch_size, same_on_batch)+ _device, _dtype = _extract_device_dtype([t for t, _, _, _ in self.samplers])+ sampler = self.sampler_dict["times"]+ drawn = _adapted_rsampling((batch_size,), sampler, same_on_batch)+ if self._whole_range:+ # The clamp removes the excluded end point: for the largest draw ``u = 1 - 2 ** -24``,+ # ``lo + u * (hi + 1 - lo)`` rounds up onto ``hi + 1`` for a range such as ``(1, 1)``, which ``floor``+ # would keep, so a rare draw would turn a quarter turn into a half turn.+ drawn = drawn.floor().clamp(max=sampler.high - 1)+ return {"times": drawn.to(device=_device, dtype=_dtype)}diff --git a/tests/augmentation/test_conventions_geometric_matrix.py b/tests/augmentation/test_conventions_geometric_matrix.pyindex f7eb962e1..7a3ef9af4 100644--- a/tests/augmentation/test_conventions_geometric_matrix.py+++ b/tests/augmentation/test_conventions_geometric_matrix.py@@ -263,14 +263,85 @@ class TestConventionGeometricMatrices(BaseTester):assert rotation[0, 0].argmax().item() == 2 * 7 + 1assert affine[0, 0].argmax().item() == 4 * 7 + 5- def test_wart_random_rotation90_continuously_samples_then_rounds_4409(self, device, dtype):- augmentation = K.RandomRotation90((0, 1), p=1.0)- torch.manual_seed(1)- params = augmentation.forward_parameters((64, 1, 5, 7))+ # Rounding a continuous draw on `[lo, hi]` gave the two end points half the weight of the others, so+ # `times=(-1, 1)` drew 0 about twice as often as -1 or 1 (25% / 50% / 25%). The draw is now floored on+ # `[lo, hi + 1)`, so every whole number of a closed range has the same probability.+ # Snippet used to generate expected:+ # torch.manual_seed(0)+ # drawn = K.RandomRotation90((-1, 1), p=1.0).forward_parameters((9000, 1, 4, 4))["times"]+ # print(torch.unique(drawn, return_counts=True))+ # The pin allows 15% around the uniform count, 8 sigma for 3000 draws per value, and what it has to separate+ # is a factor of two, not a few percent.+ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("times", [(-1, 1), (0, 2), (0, 3), (-3, 3)])+ def test_convention_random_rotation90_times_are_closed_and_uniform_4409(self, times):+ low, high = times+ count = high - low + 1+ torch.manual_seed(0)+ drawn = K.RandomRotation90(times, p=1.0).forward_parameters((count * 3000, 1, 4, 4))["times"]++ assert torch.equal(drawn, drawn.round())+ assert (int(drawn.min()), int(drawn.max())) == (low, high)+ counts = torch.bincount((drawn - low).long(), minlength=count)+ expected = drawn.numel() / count+ assert bool(((counts > 0.85 * expected) & (counts < 1.15 * expected)).all()), counts.tolist()++ @pytest.mark.device_agnostic+ def test_convention_random_rotation90_same_on_batch_shares_one_whole_number_4409(self):+ torch.manual_seed(0)+ drawn = K.RandomRotation90((-3, 3), p=1.0, same_on_batch=True).forward_parameters((16, 1, 4, 4))["times"]++ assert drawn.shape == (16,)+ assert bool((drawn == drawn[0]).all())+ assert float(drawn[0]) == float(drawn[0].round())++ # The excluded end point of the half-open sampler range is clamped back, not drawn: for the largest value+ # `torch.rand` can return, `lo + u * (hi + 1 - lo)` rounds up onto `hi + 1` in float32 for these ranges+ # (`1 + (1 - 2 ** -24) * 1` is exactly `2.0`), which `floor` would keep -- about one draw in 2**24, and+ # `times=(1, 1)` would turn a quarter turn into a half turn.+ # Snippet used to generate expected: the same ranges, with `torch.rand` patched to return `1 - 2 ** -24`.+ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("times", [(1, 1), (-3, -3), (-2, -2), (1, 2)])+ def test_convention_random_rotation90_largest_draw_stays_in_the_closed_range_4409(self, monkeypatch, times):+ largest = 1 - 2**-24+ real_rand = torch.rand+ monkeypatch.setattr(torch, "rand", lambda *args, **kwargs: torch.full_like(real_rand(*args, **kwargs), largest))+ drawn = K.RandomRotation90(times, p=1.0).forward_parameters((4, 1, 4, 4))["times"]- assert ((params["times"] >= 0) & (params["times"] <= 1)).all()- assert not torch.equal(params["times"], params["times"].round())+ assert drawn.tolist() == [float(times[1])] * 4+ @pytest.mark.device_agnostic+ @pytest.mark.parametrize(+ "times,error,match",+ [+ ((2, 1), ValueError, r"times\[0\] should be smaller than times\[1\]"),+ ((-4, 4), ValueError, "times out of bounds"),+ ((float("nan"), 1), ValueError, "must be finite"),+ ((1, 2, 3), TypeError, "length 2"),+ ],+ )+ def test_convention_random_rotation90_times_range_validation_is_unchanged_4409(self, times, error, match):+ with pytest.raises(error, match=match):+ K.RandomRotation90(times, p=1.0)++ # A range with a fractional bound is not a closed range of whole numbers, so it keeps the continuous draw+ # that is rounded when the matrix is built, and an integer tensor range draws its upper bound too.+ @pytest.mark.device_agnostic+ def test_convention_random_rotation90_fractional_and_tensor_ranges_4409(self):+ torch.manual_seed(0)+ fractional = K.RandomRotation90((0.5, 2.5), p=1.0).forward_parameters((6000, 1, 4, 4))["times"]+ assert float(fractional.min()) >= 0.5+ assert float(fractional.max()) <= 2.5+ assert not torch.equal(fractional, fractional.round())++ tensor_range = K.RandomRotation90(torch.tensor([0, 2]), p=1.0).forward_parameters((6000, 1, 4, 4))["times"]+ assert tensor_range.dtype == torch.int64+ assert set(tensor_range.tolist()) == {0, 1, 2}++ def test_convention_random_rotation90_rounds_supplied_times_4409(self, device, dtype):+ # `times` passed through `params`, for instance saved by an earlier release that drew them continuously,+ # is still rounded to a whole number of quarter turns.+ augmentation = K.RandomRotation90((0, 1), p=1.0)x = torch.zeros(2, 1, 7, 7, device=device, dtype=dtype)x[..., 1, 4] = 1params = augmentation.forward_parameters(x.shape)