π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(augmentation): propagate 3D crop output shapes in sequences (#6011)
renta0426576d9b3636c8
diff --git a/changelog.d/6011.fixed.md b/changelog.d/6011.fixed.mdnew file mode 100644index 000000000..3ec9d546d--- /dev/null+++ b/changelog.d/6011.fixed.md@@ -0,0 +1 @@+`AugmentationSequential` now propagates all three output spatial dimensions after `CenterCrop3D` and `RandomCrop3D`, so later transforms generate parameters for the volume they actually receive. Previously, later 3D crops, `RandomAffine3D` and `RandomPerspective3D` drew their parameters for the original D/H/W even for nonempty batches: a later crop could read outside the cropped volume and return zero-filled voxels, and one larger than the cropped volume returned such a zero-filled result where it now raises the same `ValueError` as a direct call. Statically applied empty crops also propagate their configured size. This corrects newly generated parameter sequences; previously saved coordinates and shape history are not recalculated. Part of #4429.diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.pyindex 0cfadbac5..94ab4bf2a 100644--- a/kornia/augmentation/_3d/geometric/center_crop.py+++ b/kornia/augmentation/_3d/geometric/center_crop.py@@ -110,7 +110,7 @@ class CenterCrop3D(GeometricAugmentationBase3D):self.size = (size, size, size)else:raise TypeError(f"Invalid `size` type. Expected int or tuple[int, int, int] (D, H, W). Got {size!r}.")- self.flags = {"align_corners": align_corners, "resample": Resample.get(resample)}+ self.flags = {"size": self.size, "align_corners": align_corners, "resample": Resample.get(resample)}def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, torch.Tensor]:return rg.center_crop_generator3d(diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex a6b8b482f..d2150103a 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -15,6 +15,7 @@# limitations under the License.#+import operatorfrom typing import Any, Dict, Iterator, List, Literal, Optional, Tuple, Union, castimport torch@@ -472,8 +473,8 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Opti"""Get the new batch shape if the augmentation changes the image size.Note:- Augmentations that change the image size must provide the parameter `output_size`.- Empty RandomCrop, CenterCrop, RandomResizedCrop and Resize batches have no sampled+ Augmentations that change the spatial size provide `output_size` with shape (B, spatial_dims).+ Empty crops and resizes have no sampledoutput-size rows, so their configured size is used only when the image forward pathalways applies the transform. Other probability branches retain the current empty-gatefallback tracked in #4429.@@ -508,31 +509,46 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Optibatch_shape = _get_new_batch_shape(p, batch_shape, children.get(p.name))return batch_shape- if batch_shape[0] == 0 and isinstance(module, (K.RandomCrop, K.CenterCrop, K.RandomResizedCrop, K.Resize)):+ if (+ batch_shape[0] == 0+ and isinstance(module, _AugmentationBase)+ and ("output_size" in data or isinstance(module, (K.RandomCrop, K.CenterCrop, K.RandomResizedCrop, K.Resize)))+ ):# Match the image forward's unconditional path. An empty gate selects the original# canvas in the other probability branches, including Resize's p_batch setting (#4429).- if module.p != 1.0 or module.p_batch != 1.0:+ size = module.flags.get("size")+ if module.p != 1.0 or module.p_batch != 1.0 or size is None:return batch_shape- size = module.flags["size"]if isinstance(module, K.Resize) and isinstance(size, int):size = _side_to_image_size(size, batch_shape[-1] / batch_shape[-2], module.flags["side"])new_batch_shape = list(batch_shape)- new_batch_shape[-2:] = size+ new_batch_shape[-len(size) :] = [operator.index(dim) for dim in size]return torch.Size(new_batch_shape)# Carefully avoid evaluating expression multiple times; batch_prob is often a 1-element torch.Tensorif "output_size" in data:- if is_exporting():+ size = getattr(module, "flags", {}).get("size") if module is not None else None+ # Fixed, always-applied 3D crops also use this static path in eager/compile:+ # reading their gate and output-size tensors would add needless device synchronization.+ static_crop3d = (+ isinstance(module, (K.CenterCrop3D, K.RandomCrop3D))+ and module.p == 1.0+ and module.p_batch == 1.0+ and size is not None+ and all(isinstance(dim, int) for dim in size)+ )+ if is_exporting() or static_crop3d:# The sampled ``output_size`` is an unbacked tensor under export (no python int for# ``torch.Size``). Use the module's static ``flags["size"]`` β known at construction β# so the tracked shape stays correct for a *subsequent* shape-dependent child (e.g. a# resample-mode crop after a resize). Fall back to leaving the shape unchanged when the# size isn't statically available.- size = getattr(module, "flags", {}).get("size") if module is not None else None- if size is None:+ # Export must not propagate the cropped canvas of a statically skipped 3D crop.+ # Intermediate probabilities still require data-dependent control flow in forward.+ if size is None or (isinstance(module, (K.CenterCrop3D, K.RandomCrop3D)) and module.p_batch == 0.0):return batch_shapenew_batch_shape = list(batch_shape)- new_batch_shape[-2:] = size+ new_batch_shape[-data["output_size"].shape[-1] :] = [operator.index(dim) for dim in size]return torch.Size(new_batch_shape)# Inline check for common PyTorch float torch.Tensor casebatch_prob = data.get("batch_prob", None)@@ -543,9 +559,9 @@ def _get_new_batch_shape(param: ParamItem, batch_shape: torch.Size, module: Optiprob = batch_prob.item() if batch_prob.numel() == 1 else batch_prob[0].item()if prob <= 0.5:return batch_shape- # Mutate only last two dims+ # The generator declares how many spatial axes it changes (H/W or D/H/W).new_batch_shape = list(batch_shape)- new_batch_shape[-2:] = data["output_size"][0]+ new_batch_shape[-data["output_size"].shape[-1] :] = data["output_size"][0]return torch.Size(new_batch_shape)return batch_shapediff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.pyindex 4d8a4e37c..ee392411d 100644--- a/kornia/augmentation/random_generator/_3d/crop.py+++ b/kornia/augmentation/random_generator/_3d/crop.py@@ -46,6 +46,7 @@ class CropGenerator3D(RandomGeneratorBase):A dict of parameters to be passed for transformation.- src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).- dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).+ - output_size (torch.Tensor): output spatial size (D, H, W) with shape (B, 3).Note:The generated random numbers are not reproducible across different devices and dtypes. By default,@@ -118,6 +119,7 @@ class CropGenerator3D(RandomGeneratorBase):return {"src": torch.zeros([0, 8, 3], device=_device, dtype=_dtype),"dst": torch.zeros([0, 8, 3], device=_device, dtype=_dtype),+ "output_size": torch.empty((0, 3), device=_device, dtype=torch.long),}# The draw is scaled and floored in the draw's dtype when that is the wider one: cast to a half ``size``@@ -167,7 +169,12 @@ class CropGenerator3D(RandomGeneratorBase):dtype=_dtype,).repeat(batch_size, 1, 1)- return {"src": crop_src.to(device=_device), "dst": crop_dst.to(device=_device)}+ output_size = (+ size.to(dtype=torch.long, copy=True)+ if self.resize_to is None+ else _constant_tensor(self.resize_to, device=_device, dtype=torch.long).expand(batch_size, -1)+ )+ return {"src": crop_src.to(device=_device), "dst": crop_dst.to(device=_device), "output_size": output_size}def center_crop_generator3d(@@ -194,6 +201,7 @@ def center_crop_generator3d(params Dict[str, torch.Tensor]: parameters to be passed for transformation.- src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).- dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).+ - output_size (torch.Tensor): output spatial size (D, H, W) with shape (B, 3).Note:No random number will be generated.@@ -277,4 +285,5 @@ def center_crop_generator3d(device=device,dtype=torch.long,).expand(batch_size, -1, -1)- return {"src": points_src, "dst": points_dst}+ output_size = _constant_tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)+ return {"src": points_src, "dst": points_dst, "output_size": output_size}diff --git a/tests/augmentation/container/test_augmentation_sequential.py b/tests/augmentation/container/test_augmentation_sequential.pyindex 24aba8e35..2fb8e9f28 100644--- a/tests/augmentation/container/test_augmentation_sequential.py+++ b/tests/augmentation/container/test_augmentation_sequential.py@@ -3002,3 +3002,126 @@ class TestAugmentationSequentialReplay:aug(torch.rand(3, 1, 15, 17, device=device, dtype=dtype), keypoints[:1].expand(3, -1, -1))replayed = aug(keypoints, params=params, data_keys=["keypoints"])assert_close(replayed, expected)+++class TestCrop3DShapePropagation(BaseTester):+ @pytest.mark.parametrize("batch", [0, 1, 2])+ @pytest.mark.parametrize(+ "first_type,nested", [(K.CenterCrop3D, False), (K.RandomCrop3D, False), (K.CenterCrop3D, True)]+ )+ @pytest.mark.parametrize("second_type", [K.CenterCrop3D, K.RandomCrop3D])+ @pytest.mark.parametrize("p", [0.0, 1.0])+ def test_downstream_canvas_and_replay(self, batch, first_type, nested, second_type, p, device, dtype):+ from copy import deepcopy++ from testing.base import supports_bilinear_3d_grid_sample++ if batch and not supports_bilinear_3d_grid_sample(device, dtype):+ pytest.skip("3D grid sampling is unsupported for this device/dtype.")+ image = torch.arange(batch * 8 * 10 * 12, device=device, dtype=dtype).reshape(batch, 1, 8, 10, 12)++ def make_seq():+ first = first_type((4, 5, 6), p=p)+ return K.AugmentationSequential(+ K.AugmentationSequential(first) if nested else first, second_type((2, 3, 4))+ )++ torch.manual_seed(17)+ expected = second_type((2, 3, 4))(first_type((4, 5, 6), p=p)(image))+ seq = make_seq()+ seen = []+ handle = seq[1].register_forward_pre_hook(lambda module, args: seen.append(args[0].shape))+ torch.manual_seed(17)+ actual = seq(image)+ handle.remove()+ self.assert_close(actual, expected)+ saved = deepcopy(seq._params)+ canvas = (4, 5, 6) if p == 1.0 else (8, 10, 12)+ assert seen == [torch.Size((batch, 1, *canvas))]+ assert tuple(saved[1].data["forward_input_shape"]) == seen[0]+ assert saved[1].data["output_size"].shape == (batch, 3)+ src = saved[1].data["src"]+ assert (src >= 0).all()+ assert (src < src.new_tensor(canvas[::-1])).all()+ seq(image)+ self.assert_close(seq(image, params=deepcopy(saved)), actual)+ self.assert_close(make_seq()(image, params=deepcopy(saved)), actual)++ @pytest.mark.parametrize("batch", [0, 2])+ def test_dynamo(self, batch, device, dtype, torch_optimizer):+ from testing.base import supports_bilinear_3d_grid_sample++ if batch and not supports_bilinear_3d_grid_sample(device, dtype):+ pytest.skip("3D grid sampling is unsupported for this device/dtype.")+ image = torch.arange(batch * 8 * 10 * 12, device=device, dtype=dtype).reshape(batch, 1, 8, 10, 12)+ first, second = K.CenterCrop3D((4, 5, 6)), K.CenterCrop3D((2, 3, 4))+ expected = second(first(image))+ seq = K.AugmentationSequential(first, second)+ self.assert_close(torch_optimizer(seq)(image), expected)++ def test_static_shape_does_not_read_scalars(self, device):+ from kornia.augmentation.container.image import _get_new_batch_shape++ shape = torch.Size((2, 1, 8, 10, 12))+ for op in (K.CenterCrop3D((4, 5, 6)), K.RandomCrop3D((4, 5, 6))):+ params = {key: value.to(device) for key, value in op.forward_parameters(shape).items()}+ with torch.profiler.profile(activities=[torch.profiler.ProfilerActivity.CPU]) as profiler:+ actual = _get_new_batch_shape(ParamItem("crop", params), shape, op)+ assert actual == (2, 1, 4, 5, 6)+ assert not any(event.key == "aten::_local_scalar_dense" for event in profiler.key_averages())++ @pytest.mark.parametrize("p", [0.0, 1.0])+ def test_export_shape_respects_static_crop_gate(self, p):+ from kornia.augmentation.container.image import _get_new_batch_shape++ shape = torch.Size((2, 1, 8, 10, 12))+ for crop in (K.CenterCrop3D, K.RandomCrop3D):+ op = crop((4, 5, 6), p=p)+ params = ParamItem("crop", op.forward_parameters(shape))+ with patch("kornia.augmentation.container.image.is_exporting", return_value=True):+ actual = _get_new_batch_shape(params, shape, op)+ assert actual == (shape if p == 0.0 else torch.Size((2, 1, 4, 5, 6)))++ @pytest.mark.parametrize("first_type", [K.CenterCrop3D, K.RandomCrop3D])+ @pytest.mark.parametrize("second_type", [K.CenterCrop3D, K.RandomCrop3D])+ def test_intermediate_probability_follows_gate(self, first_type, second_type, device, dtype):+ from testing.base import supports_bilinear_3d_grid_sample++ if not supports_bilinear_3d_grid_sample(device, dtype):+ pytest.skip("3D grid sampling is unsupported for this device/dtype.")+ image = torch.arange(2 * 8 * 10 * 12, device=device, dtype=dtype).reshape(2, 1, 8, 10, 12)+ canvases = set()+ for seed in range(6):+ torch.manual_seed(seed)+ expected = second_type((2, 3, 4))(first_type((4, 5, 6), p=0.5)(image))+ seq = K.AugmentationSequential(first_type((4, 5, 6), p=0.5), second_type((2, 3, 4)))+ torch.manual_seed(seed)+ self.assert_close(seq(image), expected)+ canvases.add(tuple(seq._params[1].data["forward_input_shape"].tolist()))+ # p < 1 reads the sampled gate; both outcomes must occur and each must set the next crop's canvas.+ assert canvases == {(2, 1, 4, 5, 6), (2, 1, 8, 10, 12)}++ @pytest.mark.parametrize("batch", [0, 2])+ def test_numpy_integer_size(self, batch, device, dtype):+ from kornia.augmentation.container.image import _get_new_batch_shape++ from testing.base import supports_bilinear_3d_grid_sample++ if batch and not supports_bilinear_3d_grid_sample(device, dtype):+ pytest.skip("3D grid sampling is unsupported for this device/dtype.")+ # The 3D crops accept NumPy integer sizes; the tracked shape must hold Python ints for the next generator.+ size = (np.int64(4), np.int64(5), np.int64(6))+ image = torch.arange(batch * 8 * 10 * 12, device=device, dtype=dtype).reshape(batch, 1, 8, 10, 12)+ for first_type in (K.CenterCrop3D, K.RandomCrop3D):+ torch.manual_seed(17)+ expected = K.RandomCrop3D((2, 3, 4))(first_type(size)(image))+ seq = K.AugmentationSequential(first_type(size), K.RandomCrop3D((2, 3, 4)))+ torch.manual_seed(17)+ self.assert_close(seq(image), expected)+ assert tuple(seq._params[1].data["forward_input_shape"].tolist()) == (batch, 1, 4, 5, 6)+ op = first_type(size)+ params = ParamItem("crop", op.forward_parameters(image.shape))+ with patch("kornia.augmentation.container.image.is_exporting", return_value=True):+ actual = _get_new_batch_shape(params, image.shape, op)+ assert [type(dim) for dim in actual] == [int] * 5+ assert actual == (batch, 1, 4, 5, 6)diff --git a/tests/augmentation/test_random_generator_3d.py b/tests/augmentation/test_random_generator_3d.pyindex 39acf521f..842086f9f 100644--- a/tests/augmentation/test_random_generator_3d.py+++ b/tests/augmentation/test_random_generator_3d.py@@ -448,7 +448,9 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):size = size.repeat(batch_size, 1).to(device=device, dtype=dtype)param_gen = CropGenerator3D(size=size, resize_to=resize_to)- param_gen(batch_shape=torch.Size((batch_size, 1, *input_size)), same_on_batch=same_on_batch)+ params = param_gen(batch_shape=torch.Size((batch_size, 1, *input_size)), same_on_batch=same_on_batch)+ expected = torch.as_tensor(resize_to if resize_to is not None else size).expand(batch_size, 3)+ assert_close(params["output_size"].to(device=device, dtype=dtype), expected.to(device=device, dtype=dtype))@pytest.mark.parametrize("input_size,size,resize_to",@@ -527,7 +529,9 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):dtype=dtype,),}+ expected["output_size"] = torch.tensor([[100, 100, 100]]).expand(2, -1)assert res.keys() == expected.keys()+ assert_close(res["output_size"].cpu(), expected["output_size"])assert_close(res["src"], expected["src"], atol=1e-4, rtol=1e-4)assert_close(res["dst"], expected["dst"], atol=1e-4, rtol=1e-4)@@ -593,7 +597,9 @@ class TestRandomCropGen3D(RandomGeneratorBaseTests):dtype=dtype,),}+ expected["output_size"] = torch.tensor([[100, 100, 100]]).expand(2, -1)assert res.keys() == expected.keys()+ assert_close(res["output_size"].cpu(), expected["output_size"])assert_close(res["src"], expected["src"], atol=1e-4, rtol=1e-4)assert_close(res["dst"], expected["dst"], atol=1e-4, rtol=1e-4)@@ -656,7 +662,9 @@ class TestCenterCropGen3D(RandomGeneratorBaseTests):dtype=torch.long,).repeat(2, 1, 1),}+ expected["output_size"] = torch.tensor([[120, 150, 100]]).expand(2, -1)assert res.keys() == expected.keys()+ assert_close(res["output_size"].cpu(), expected["output_size"])assert_close(res["src"].to(device=device), expected["src"], atol=1e-4, rtol=1e-4)assert_close(res["dst"].to(device=device), expected["dst"], atol=1e-4, rtol=1e-4)@@ -840,3 +848,13 @@ class TestRandomMotionBlur3D(RandomGeneratorBaseTests):angle=torch.tensor([(0.0, 0.0)] * 3, device=device, dtype=dtype),direction=torch.tensor([0.0, 0.0], device=device, dtype=dtype),)+++def test_crop3d_output_size_owns_storage(device):+ size = torch.tensor([[4, 5, 6]], device=device, dtype=torch.long)+ generator = CropGenerator3D(size)+ params = generator((1, 1, 8, 10, 12))+ params["output_size"][0, 0] = 2+ assert_close(size, torch.tensor([[4, 5, 6]], device=device))+ size[0, 1] = 3+ assert_close(params["output_size"], torch.tensor([[2, 5, 6]], device=device))