Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(augmentation): scale and floor the crop start draw in the wider dtype before casting it to the parameter dtype (#5061)

εŒΊζ’“η721f31fc9f6a
diff --git a/changelog.d/5061.fixed.md b/changelog.d/5061.fixed.md
new file mode 100644
index 000000000..7e373e621
--- /dev/null
+++ b/changelog.d/5061.fixed.md
@@ -0,0 +1,6 @@
+Crop starts no longer land one past the last valid position for `CropGenerator` and `CropGenerator3D` with a float16
+or bfloat16 `size` tensor, for `RandomResizedCrop` with a float16 or bfloat16 `scale` or `ratio` tensor, and for
+`RandomCrop`, `RandomResizedCrop` and `RandomCrop3D` moved to float64: the start draw is scaled and floored in the
+wider dtype and the integer start is cast afterwards. When the draw and the crop parameters share a dtype, the
+parameters are unchanged. With a float16 or bfloat16 tensor, the same seed also moves a few in-range starts, those
+whose draw crossed a start boundary when it was rounded to half precision, to the start of the unrounded draw (#5052).
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index fef6d756d..571eedb43 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -26,6 +26,7 @@ from kornia.augmentation.utils import (
_check_positive_int_or_traced,
_common_param_check,
_joint_range_check,
+ _truncate_to_start,
)
from kornia.augmentation.utils.helpers import _constant_tensor
from kornia.core.utils import _extract_device_dtype
@@ -113,17 +114,15 @@ class CropGenerator(RandomGeneratorBase):
x_diff = x_diff.clamp(0)
y_diff = y_diff.clamp(0)
+ # The draw is scaled and floored in the draw's dtype when that is the wider one: cast to a half ``size``
+ # dtype first, a draw close to 1 rounds up to 1.0 and the start lands one past the last valid position.
if same_on_batch:
# If same_on_batch, select the first then repeat.
- x_start = (
- _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(x_diff) * x_diff[0]
- ).floor()
- y_start = (
- _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(y_diff) * y_diff[0]
- ).floor()
+ x_start = _truncate_to_start(_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch), x_diff[0])
+ y_start = _truncate_to_start(_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch), y_diff[0])
else:
- x_start = (_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(x_diff) * x_diff).floor()
- y_start = (_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(y_diff) * y_diff).floor()
+ x_start = _truncate_to_start(_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch), x_diff)
+ y_start = _truncate_to_start(_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch), y_diff)
crop_src = bbox_generator(
x_start.view(-1).to(device=_device, dtype=_dtype),
y_start.view(-1).to(device=_device, dtype=_dtype),
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 0ca16afb9..2ce2b92fa 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -21,7 +21,12 @@ import torch
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
-from kornia.augmentation.utils import _adapted_rsampling, _check_positive_int_or_traced, _common_param_check
+from kornia.augmentation.utils import (
+ _adapted_rsampling,
+ _check_positive_int_or_traced,
+ _common_param_check,
+ _truncate_to_start,
+)
from kornia.augmentation.utils.helpers import _constant_tensor
from kornia.core.utils import _extract_device_dtype, is_exporting
from kornia.geometry.bbox import bbox_generator3d
@@ -113,13 +118,11 @@ class CropGenerator3D(RandomGeneratorBase):
"dst": torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
}
- x_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- y_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
- z_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
-
- x_start = (x_start * x_diff).floor()
- y_start = (y_start * y_diff).floor()
- z_start = (z_start * z_diff).floor()
+ # The draw is scaled and floored in the draw's dtype when that is the wider one: cast to a half ``size``
+ # dtype first, a draw close to 1 rounds up to 1.0 and the start lands one past the last valid position.
+ x_start = _truncate_to_start(_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch), x_diff)
+ y_start = _truncate_to_start(_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch), y_diff)
+ z_start = _truncate_to_start(_adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch), z_diff)
crop_src = bbox_generator3d(
x_start.view(-1), y_start.view(-1), z_start.view(-1), size[:, 2] - 1, size[:, 1] - 1, size[:, 0] - 1
diff --git a/kornia/augmentation/utils/__init__.py b/kornia/augmentation/utils/__init__.py
index 2d4332780..813bdd076 100644
--- a/kornia/augmentation/utils/__init__.py
+++ b/kornia/augmentation/utils/__init__.py
@@ -35,6 +35,7 @@ from kornia.augmentation.utils.helpers import (
_transform_input3d_by_shape,
_transform_input_by_shape,
_transform_output_shape,
+ _truncate_to_start,
_validate_input,
_validate_input3d,
_validate_input_dtype,
@@ -74,6 +75,7 @@ __all__ = [
"_transform_input3d_by_shape",
"_transform_input_by_shape",
"_transform_output_shape",
+ "_truncate_to_start",
"_tuple_range_reader",
"_validate_input",
"_validate_input3d",
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 99145a242..aebf9c373 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -414,6 +414,17 @@ def _adapted_rsampling(
return dist.rsample(shape)
+def _truncate_to_start(draw: torch.Tensor, extent: torch.Tensor) -> torch.Tensor:
+ r"""Turn a ``[0, 1)`` draw into an integer start in ``[0, extent)`` for a crop or patch.
+
+ The product and the floor are taken in the wider of the two dtypes and the result is cast to the dtype of
+ ``extent``. Casting the draw to a narrower ``extent`` dtype first rounds a draw close to 1 up to 1.0, which
+ puts the start one past the last valid position (#5052).
+ """
+ dtype = torch.promote_types(draw.dtype, extent.dtype)
+ return (draw.to(device=extent.device, dtype=dtype) * extent.to(dtype)).floor().to(extent.dtype)
+
+
def _adapted_sampling(
shape: Union[Tuple[int, ...], torch.Size],
dist: torch.distributions.Distribution,
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index 8462c622b..fdf086bd9 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -58,7 +58,6 @@ call builtins.AssertionError tests/augmentation/test_random_generator.py::TestRa
call builtins.AssertionError tests/augmentation/test_random_generator.py::TestRandomCropSizeGen::test_random_gen[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_random_generator.py::TestRandomCropSizeGen::test_same_on_batch[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomAffineGen3D::test_random_gen[cpu-bfloat16]
-call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomCropGen3D::test_random_gen[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomPerspectiveGen3D::test_random_gen[cpu-bfloat16]
call builtins.AssertionError tests/augmentation/test_random_generator_3d.py::TestRandomPerspectiveGen3D::test_same_on_batch[cpu-bfloat16]
call builtins.AssertionError tests/color/test_lab.py::TestLabToRgb::test_forth_and_back[cpu-bfloat16]
diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.py
index 9b856df27..8dc84d732 100644
--- a/tests/augmentation/test_random_generator.py
+++ b/tests/augmentation/test_random_generator.py
@@ -43,6 +43,7 @@ from kornia.augmentation.random_generator import (
ResizedCropGenerator,
center_crop_generator,
)
+from kornia.augmentation.utils import _truncate_to_start
from testing.base import assert_close
@@ -1917,6 +1918,31 @@ _POSITION_SAMPLER_CASES = [
]
+# The three crop generators with a half-precision ``size``, ``scale`` or ``ratio`` tensor. The parameter dtype
+# follows the tensor while the draw stays float32, so the start used to be computed in half precision.
+_HALF_PARAMETER_CASES = [
+ pytest.param(
+ lambda device, dtype: CropGenerator(torch.full((1 << 16, 2), 4.0, device=device, dtype=dtype)),
+ torch.Size([1 << 16, 1, 8, 8]),
+ id="crop",
+ ),
+ pytest.param(
+ lambda device, dtype: ResizedCropGenerator(
+ (4, 4),
+ torch.tensor([0.25, 0.25], device=device, dtype=dtype),
+ torch.tensor([1.0, 1.0], device=device, dtype=dtype),
+ ),
+ torch.Size([1 << 16, 1, 8, 8]),
+ id="resized_crop",
+ ),
+ pytest.param(
+ lambda device, dtype: CropGenerator3D(torch.full((1 << 16, 3), 4.0, device=device, dtype=dtype)),
+ torch.Size([1 << 16, 1, 8, 8, 8]),
+ id="crop3d",
+ ),
+]
+
+
class TestHalfPrecisionPositionSamplers:
# The half dtypes are named rather than taken from the fixture so the pins run on the default float32
# legs too; the device comes from the fixture so the MPS leg draws on MPS.
@@ -1960,3 +1986,57 @@ class TestHalfPrecisionPositionSamplers:
last_covered = params["src"]
assert int(last_covered.min()) >= 0
assert int(last_covered.max()) < 8
+
+ # A half ``size``, ``scale`` or ``ratio`` tensor makes the parameter dtype half while the draw stays float32.
+ # Cast to half before it was scaled, about 30 (float16) or 270 (bfloat16) of 2**16 draws rounded up to 1.0 and
+ # put the start one past the last valid position (#5052).
+ @pytest.mark.parametrize("make_generator,batch_shape", _HALF_PARAMETER_CASES)
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ def test_half_precision_parameters_keep_starts_in_range(self, make_generator, batch_shape, device, half_dtype):
+ generator = make_generator(device, half_dtype)
+ generator.set_rng_device_and_dtype(device, half_dtype)
+ torch.manual_seed(0)
+ src = generator(batch_shape)["src"]
+ assert src.dtype == half_dtype
+ assert int(src.min()) >= 0
+ assert int(src.max()) < 8
+
+ # With ``same_on_batch`` the batch shares one draw, so a large batch never reaches the rare draw above. Pin the
+ # draw to the largest float32 below 1 instead: rounded to half precision it is 1.0, and the start was 5, not 4.
+ @pytest.mark.parametrize("same_on_batch", [False, True])
+ @pytest.mark.parametrize("half_dtype", [torch.float16, torch.bfloat16])
+ @pytest.mark.parametrize("ndim", [2, 3])
+ def test_draw_below_one_keeps_the_last_start(self, device, half_dtype, same_on_batch, ndim):
+ if ndim == 2:
+ generator = CropGenerator(torch.full((2, 2), 4.0, device=device, dtype=half_dtype))
+ else:
+ generator = CropGenerator3D(torch.full((2, 3), 4.0, device=device, dtype=half_dtype))
+ generator.set_rng_device_and_dtype(device, half_dtype)
+ draw = torch.tensor(1.0 - 2.0**-24, device=device, dtype=torch.float32)
+ generator.rand_sampler = torch.distributions.Uniform(draw, draw, validate_args=False)
+ src = generator(torch.Size([2, 1, *([8] * ndim)]), same_on_batch)["src"]
+ assert src[:, 0].tolist() == [[4.0] * ndim] * 2
+
+
+class TestTruncateToStart:
+ # The largest float32 below 1 rounds to 1.0 in float16 and in bfloat16, the largest float64 below 1 rounds to
+ # 1.0 in float32. The start has to stay at the last valid position and come back in the extent's dtype.
+ @pytest.mark.parametrize(
+ "draw_dtype,extent_dtype",
+ [(torch.float32, torch.float16), (torch.float32, torch.bfloat16), (torch.float64, torch.float32)],
+ )
+ def test_draw_below_one_stays_in_range(self, device, draw_dtype, extent_dtype):
+ if device.type == "mps" and draw_dtype == torch.float64:
+ pytest.skip("MPS has no float64.")
+ draw = torch.tensor([0.0, 0.5, 1.0 - torch.finfo(draw_dtype).eps / 2], device=device, dtype=draw_dtype)
+ extent = torch.tensor(5.0, device=device, dtype=extent_dtype)
+ start = _truncate_to_start(draw, extent)
+ assert start.dtype == extent_dtype
+ assert start.device.type == device.type
+ assert start.tolist() == [0.0, 2.0, 4.0]
+
+ def test_same_dtype_matches_the_plain_formula(self, device, dtype):
+ torch.manual_seed(0)
+ draw = torch.rand(1 << 12, device=device, dtype=dtype)
+ extent = torch.randint(1, 100, (1 << 12,), device=device).to(dtype)
+ assert torch.equal(_truncate_to_start(draw, extent), (draw * extent).floor())