π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): keep half-precision erasing positions in bounds (#4587)
Dex Hunter18e0f36d7f13
diff --git a/changelog.d/4587.fixed.md b/changelog.d/4587.fixed.mdnew file mode 100644index 000000000..93e3a328c--- /dev/null+++ b/changelog.d/4587.fixed.md@@ -0,0 +1 @@+RectangleEraseGenerator now keeps position sampling in safe floating-point precision and preserves nonnegative erase positions for half and bfloat16 parameters. (#4553)diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.pyindex 5891cdf6c..0975011dd 100644--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py@@ -26,6 +26,7 @@ from kornia.augmentation.utils import (_common_param_check,_joint_range_check,)+from kornia.augmentation.utils.helpers import _constant_tensorfrom kornia.core.utils import _extract_device_dtype__all__ = ["RectangleEraseGenerator"]@@ -90,9 +91,10 @@ class RectangleEraseGenerator(RandomGeneratorBase):)else:self.ratio_sampler = UniformDistribution(ratio[0], ratio[1], validate_args=False)+ position_sampler_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtypeself.uniform_sampler = UniformDistribution(- torch.tensor(0, device=device, dtype=dtype),- torch.tensor(1, device=device, dtype=dtype),+ torch.tensor(0, device=device, dtype=position_sampler_dtype),+ torch.tensor(1, device=device, dtype=position_sampler_dtype),validate_args=False,)@@ -130,20 +132,55 @@ class RectangleEraseGenerator(RandomGeneratorBase):heights = torch.round((target_areas * aspect_ratios) ** (1 / 2)).clamp(1.0, height)widths = torch.round((target_areas / aspect_ratios) ** (1 / 2)).clamp(1.0, width)+ position_dtype = torch.promote_types(self.uniform_sampler.low.dtype, _dtype)+ if position_dtype in (torch.float16, torch.bfloat16):+ position_dtype = torch.float32xs_ratio = _adapted_rsampling((batch_size,), self.uniform_sampler, same_on_batch).to(- device=_device, dtype=_dtype+ device=_device, dtype=position_dtype)ys_ratio = _adapted_rsampling((batch_size,), self.uniform_sampler, same_on_batch).to(- device=_device, dtype=_dtype+ device=_device, dtype=position_dtype)- xs = xs_ratio * (width - widths + 1)- ys = ys_ratio * (height - heights + 1)+ xs = xs_ratio * (width - widths.to(dtype=position_dtype) + 1)+ ys = ys_ratio * (height - heights.to(dtype=position_dtype) + 1)++ def _cast_position(position: torch.Tensor, size: torch.Tensor, limit: int) -> torch.Tensor:+ floored = position.floor()+ output = floored.to(device=_device, dtype=_dtype)+ if _dtype not in (torch.float16, torch.bfloat16):+ return output++ max_start = (+ _constant_tensor(limit, device=_device, dtype=position_dtype)+ - size.to(device=_device, dtype=position_dtype)+ ).floor()+ # Coordinates are nonnegative integers. Deliberately round the bound down+ # to the output format's local representable integer grid.+ max_start = torch.minimum(+ max_start,+ _constant_tensor(torch.finfo(_dtype).max, device=_device, dtype=position_dtype),+ )+ max_start = torch.clamp(max_start, min=0)+ mantissa_bits = 10 if _dtype == torch.float16 else 7+ clamped_start = torch.clamp(max_start, min=1)+ exponent = torch.floor(torch.log2(clamped_start))+ power = torch.pow(+ _constant_tensor(2.0, device=_device, dtype=position_dtype),+ exponent,+ )+ exponent = torch.where(power > clamped_start, exponent - 1, exponent)+ quantum = torch.pow(+ _constant_tensor(2.0, device=_device, dtype=position_dtype),+ torch.clamp(exponent - mantissa_bits, min=0),+ )+ max_start_output = (torch.floor(max_start / quantum) * quantum).to(device=_device, dtype=_dtype).detach()+ return torch.minimum(torch.maximum(output, torch.zeros_like(output)), max_start_output)return {"widths": widths.floor(),"heights": heights.floor(),- "xs": xs.floor(),- "ys": ys.floor(),+ "xs": _cast_position(xs, widths, width),+ "ys": _cast_position(ys, heights, height),"values": torch.full((batch_size,), self.value, device=_device, dtype=_dtype),}diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.pyindex 5e0afec52..33638e0af 100644--- a/tests/augmentation/test_augmentation.py+++ b/tests/augmentation/test_augmentation.py@@ -2645,6 +2645,72 @@ class TestRectangleRandomErasing(BaseTester):res = f(input)self.assert_close(res[0], res[1])+ @pytest.mark.parametrize("parameter_dtype", [torch.float16, torch.bfloat16])+ @pytest.mark.parametrize("same_on_batch", [False, True])+ def test_half_precision_random_erasing_replays_native_params(self, device, parameter_dtype, same_on_batch):+ if device.type != "cpu":+ pytest.skip("This regression exercises the CPU sampler with half tensor parameters.")+ batch_size, height, width = 65536, 16, 16+ scale = torch.tensor((0.25, 0.25), device=device, dtype=parameter_dtype)+ ratio = torch.tensor((1.0, 1.0), device=device, dtype=parameter_dtype)+ input = torch.ones((batch_size, 1, height, width), device=device, dtype=parameter_dtype)+ augmentation = RandomErasing(+ scale=scale,+ ratio=ratio,+ value=0.25,+ same_on_batch=same_on_batch,+ p=1.0,+ )+ torch.manual_seed(0)+ params = augmentation.forward_parameters(input.shape)+ output = augmentation(input, params=params)+ replay = augmentation(input, params=params)+ assert output.shape == input.shape+ assert output.device == input.device+ assert output.dtype == input.dtype+ assert torch.equal(output, replay)+ if same_on_batch:+ assert torch.equal(output[0], output[1])+ assert bool((output != input).any())+ for name in ("xs", "ys", "widths", "heights"):+ assert params[name].dtype == parameter_dtype, name+ assert params[name].device == device, name+ xs = params["xs"].to(torch.float64)+ ys = params["ys"].to(torch.float64)+ widths = params["widths"].to(torch.float64)+ heights = params["heights"].to(torch.float64)+ assert bool((xs + widths <= width).all())+ assert bool((ys + heights <= height).all())+ observed_area = (output != input).flatten(1).sum(dim=1).to(torch.float64)+ expected_area = widths * heights+ assert torch.equal(observed_area, expected_area)+ for index in (0, batch_size // 2, batch_size - 1):+ x, y, box_width, box_height = (+ params[name][index].long().item() for name in ("xs", "ys", "widths", "heights")+ )+ expected = input[index].clone()+ expected[:, y : y + box_height, x : x + box_width] = params["values"][index].to(input)+ assert torch.equal(output[index], expected)++ @pytest.mark.device_agnostic+ @pytest.mark.parametrize("parameter_dtype,image_size", [(torch.bfloat16, 299), (torch.float16, 2051)])+ def test_half_precision_erasing_positions_are_nonnegative_for_rounded_extents(self, parameter_dtype, image_size):+ scale = torch.tensor([1.0, 1.0], dtype=parameter_dtype)+ ratio = torch.tensor([1.0, 1.0], dtype=parameter_dtype)+ augmentation = RandomErasing(scale=scale, ratio=ratio, same_on_batch=True, p=1.0)+ input = torch.ones((4, 1, image_size, image_size), dtype=parameter_dtype)++ torch.manual_seed(0)+ params = augmentation.forward_parameters(input.shape)+ assert bool((params["xs"] >= 0).all())+ assert bool((params["ys"] >= 0).all())+ assert torch.equal(params["xs"], params["xs"][0].expand_as(params["xs"]))+ assert torch.equal(params["ys"], params["ys"][0].expand_as(params["ys"]))++ output = augmentation(input, params=params)+ assert torch.equal(output[0], output[1])+ assert torch.equal(output, torch.zeros_like(output))+def test_dynamo(self, device, dtype, torch_optimizer):torch.manual_seed(0)input = torch.rand(2, 3, 11, 7, device=device, dtype=dtype)diff --git a/tests/augmentation/test_onnx_export.py b/tests/augmentation/test_onnx_export.pyindex 707d1b1eb..45ec26754 100644--- a/tests/augmentation/test_onnx_export.py+++ b/tests/augmentation/test_onnx_export.py@@ -93,6 +93,26 @@ def _erasing() -> torch.nn.Module:return K.RandomErasing(p=1.0)+ "parameter_dtype,image_dtype",+ [+ (torch.float16, torch.float32),+ (torch.float16, torch.float16),+ (torch.bfloat16, torch.float32),+ ],+ ids=["float16-params-float32-image", "float16-params-float16-image", "bfloat16-params-float32-image"],+)[email protected]_agnostic+def test_onnx_export_random_erasing_tensor_parameters(parameter_dtype, image_dtype) -> None:+ module = K.RandomErasing(+ scale=torch.tensor((0.25, 0.25), dtype=parameter_dtype),+ ratio=torch.tensor((1.0, 1.0), dtype=parameter_dtype),+ p=1.0,+ )+ size = _try_export(module, torch.randn(2, 3, 16, 16, dtype=image_dtype))+ assert size > 0++def _posterize() -> torch.nn.Module:return K.RandomPosterize(3, p=1.0)diff --git a/tests/augmentation/test_random_generator.py b/tests/augmentation/test_random_generator.pyindex b038b3e63..b6cc47724 100644--- a/tests/augmentation/test_random_generator.py+++ b/tests/augmentation/test_random_generator.py@@ -1078,6 +1078,23 @@ class TestRandomCropSizeGen(RandomGeneratorBaseTests):class TestRandomRectangleGen(RandomGeneratorBaseTests):+ @staticmethod+ def _assert_rectangle_parameters_in_bounds(params, batch_size, height, width, device, dtype):+ for name in ("xs", "ys", "widths", "heights", "values"):+ value = params[name]+ assert value.shape == (batch_size,), name+ assert value.device == device, name+ assert value.dtype == dtype, name+ assert bool(torch.isfinite(value).all()), name+ xs = params["xs"].to(torch.float64)+ ys = params["ys"].to(torch.float64)+ widths = params["widths"].to(torch.float64)+ heights = params["heights"].to(torch.float64)+ assert bool((xs >= 0).all() and (ys >= 0).all())+ assert bool((widths >= 1).all() and (heights >= 1).all())+ assert bool((xs + widths <= width).all())+ assert bool((ys + heights <= height).all())+@pytest.mark.parametrize("batch_size", [0, 1, 8])@pytest.mark.parametrize("height", [200])@pytest.mark.parametrize("width", [300])@@ -1182,6 +1199,100 @@ class TestRandomRectangleGen(RandomGeneratorBaseTests):assert_close(res["ys"], expected["ys"])assert_close(res["values"], expected["values"])+ @pytest.mark.parametrize("parameter_dtype", [torch.float16, torch.bfloat16])+ def test_half_precision_positions_stay_in_bounds(self, device, parameter_dtype):+ if device.type != "cpu":+ pytest.skip("This regression exercises the CPU sampler with half tensor parameters.")+ batch_size, height, width = 65536, 16, 16+ scale = torch.tensor((0.25, 0.25), device=device, dtype=parameter_dtype)+ ratio = torch.tensor((1.0, 1.0), device=device, dtype=parameter_dtype)+ generator = RectangleEraseGenerator(scale=scale, ratio=ratio, value=0.25)+ assert generator.uniform_sampler.low.dtype == torch.float32+ assert generator.uniform_sampler.low.device == device+ torch.manual_seed(0)+ params = generator(torch.Size([batch_size, 1, height, width]))+ self._assert_rectangle_parameters_in_bounds(params, batch_size, height, width, device, parameter_dtype)++ @pytest.mark.parametrize("parameter_dtype", [torch.float16, torch.bfloat16])+ def test_half_precision_positions_stay_in_bounds_on_wide_image(self, device, parameter_dtype):+ if device.type != "cpu":+ pytest.skip("This regression exercises the CPU sampler with half tensor parameters.")+ batch_size, height, width = 1024, 4, 4096+ scale = torch.tensor((0.001, 0.001), device=device, dtype=parameter_dtype)+ ratio = torch.tensor((1.0, 1.0), device=device, dtype=parameter_dtype)+ generator = RectangleEraseGenerator(scale=scale, ratio=ratio, value=0.25)+ torch.manual_seed(0)+ params = generator(torch.Size([batch_size, 1, height, width]))+ self._assert_rectangle_parameters_in_bounds(params, batch_size, height, width, device, parameter_dtype)++ @pytest.mark.parametrize("parameter_dtype", [torch.float32, torch.float64])+ def test_float_positions_stay_in_bounds(self, device, parameter_dtype):+ if device.type != "cpu":+ pytest.skip("This control records CPU sampler parity.")+ batch_size, height, width = 32, 11, 19+ scale = torch.tensor((0.25, 0.25), device=device, dtype=parameter_dtype)+ ratio = torch.tensor((1.0, 1.0), device=device, dtype=parameter_dtype)+ torch.manual_seed(0)+ params = RectangleEraseGenerator(scale=scale, ratio=ratio, value=0.25)(+ torch.Size([batch_size, 1, height, width])+ )+ self._assert_rectangle_parameters_in_bounds(params, batch_size, height, width, device, parameter_dtype)++ @pytest.mark.parametrize(+ "requested_sampler_dtype, expected_sampler_dtype",+ [+ (torch.float16, torch.float32),+ (torch.bfloat16, torch.float32),+ (torch.float32, torch.float32),+ (torch.float64, torch.float64),+ ],+ )+ def test_tuple_position_sampler_uses_safe_bounds(self, device, requested_sampler_dtype, expected_sampler_dtype):+ if device.type != "cpu":+ pytest.skip("This control records CPU sampler parity.")+ generator = RectangleEraseGenerator(scale=(0.25, 0.25), ratio=(1.0, 1.0))+ generator.set_rng_device_and_dtype(device, requested_sampler_dtype)+ assert generator.uniform_sampler.low.dtype == expected_sampler_dtype+ assert generator.uniform_sampler.high.dtype == expected_sampler_dtype+ assert generator.uniform_sampler.low.device == device+ assert generator.uniform_sampler.high.device == device++ @pytest.mark.parametrize("parameter_dtype", [torch.float16, torch.bfloat16])+ def test_half_position_sampler_uses_selected_device(self, device, parameter_dtype):+ generator = RectangleEraseGenerator(+ scale=torch.tensor((0.25, 0.25), device=device, dtype=parameter_dtype),+ ratio=torch.tensor((1.0, 1.0), device=device, dtype=parameter_dtype),+ )+ generator.set_rng_device_and_dtype(device, parameter_dtype)+ assert generator.uniform_sampler.low.dtype == torch.float32+ assert generator.uniform_sampler.high.dtype == torch.float32+ assert generator.uniform_sampler.low.device == device+ assert generator.uniform_sampler.high.device == device++ def test_tuple_positions_stay_in_bounds(self, device):+ if device.type != "cpu":+ pytest.skip("This control records CPU sampler parity.")+ batch_size, height, width = 32, 11, 19+ torch.manual_seed(0)+ params = RectangleEraseGenerator(scale=(0.25, 0.25), ratio=(1.0, 1.0), value=0.25)(+ torch.Size([batch_size, 1, height, width])+ )+ self._assert_rectangle_parameters_in_bounds(params, batch_size, height, width, device, torch.float32)++ @pytest.mark.parametrize("parameter_dtype", [torch.float16, torch.bfloat16])+ def test_half_precision_same_on_batch_preserves_rectangle(self, device, parameter_dtype):+ if device.type != "cpu":+ pytest.skip("This regression exercises the CPU sampler with half tensor parameters.")+ height, width = 16, 16+ scale = torch.tensor((0.25, 0.25), device=device, dtype=parameter_dtype)+ ratio = torch.tensor((1.0, 1.0), device=device, dtype=parameter_dtype)+ generator = RectangleEraseGenerator(scale=scale, ratio=ratio, value=0.25)+ torch.manual_seed(0)+ params = generator(torch.Size([2, 1, height, width]), same_on_batch=True)+ self._assert_rectangle_parameters_in_bounds(params, 2, height, width, device, parameter_dtype)+ for name in ("xs", "ys", "widths", "heights", "values"):+ assert torch.equal(params[name][0], params[name][1]), name+class TestCenterCropGen(RandomGeneratorBaseTests):@pytest.mark.parametrize("batch_size", [0, 2])