π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
[Enhance] Added forward_parameters (#885)
shijianjian9fe69c8c18ab
diff --git a/docs/source/augmentation.base.rst b/docs/source/augmentation.base.rstindex c52cd3652..d20bc25db 100644--- a/docs/source/augmentation.base.rst+++ b/docs/source/augmentation.base.rst@@ -1,10 +1,8 @@-kornia.augmentation.base-========================+Base Classes+============.. currentmodule:: kornia.augmentation.base-Base Classes-------------This is the base class for creating a new transform. The user only needs to override: `generate_parameters`, `apply_transform` and optionally, `compute_transformation`.diff --git a/docs/source/augmentation.container.rst b/docs/source/augmentation.container.rstindex d295944f8..d288f6ed8 100644--- a/docs/source/augmentation.container.rst+++ b/docs/source/augmentation.container.rst@@ -1,5 +1,5 @@-kornia.augmentation.container-=============================+Augmentation Containers+=======================.. currentmodule:: kornia.augmentation.containerdiff --git a/docs/source/augmentation.module.rst b/docs/source/augmentation.module.rstindex cd8107abf..fdc97da38 100644--- a/docs/source/augmentation.module.rst+++ b/docs/source/augmentation.module.rst@@ -1,10 +1,8 @@-kornia.augmentation-===================-.. currentmodule:: kornia.augmentation+Transforms2D-------------+============Set of operators to perform data augmentation on 2D image tensors.@@ -28,8 +26,12 @@ Set of operators to perform data augmentation on 2D image tensors... autoclass:: RandomMixUp.. autoclass:: RandomCutMix+.. automodule:: kornia.augmentation.functional.functional+ :members:++Transforms3D-------------+============Set of operators to perform data augmentation on 3D volumetric tensors.@@ -43,18 +45,14 @@ Set of operators to perform data augmentation on 3D volumetric tensors... autoclass:: RandomMotionBlur3D.. autoclass:: RandomEqualize3D+.. automodule:: kornia.augmentation.functional.functional3d+ :members:++Normalizations---------------+==============Normalization operations are shape-agnostic for both 2D and 3D tensors... autoclass:: Denormalize.. autoclass:: Normalize--Functional-------------.. automodule:: kornia.augmentation.functional.functional- :members:-.. automodule:: kornia.augmentation.functional.functional3d- :members:diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rstindex 06eaa3396..092b81915 100644--- a/docs/source/augmentation.rst+++ b/docs/source/augmentation.rst@@ -13,9 +13,6 @@ Kornia provides Torchvision-like augmentation APIs while may not reproduce TorchFor detailed comparison, please checkout the `Colab: Kornia Playground <https://colab.research.google.com/drive/1T20UNAG4SdlE2n2wstuhiewve5Q81VpS#revisionId=0B4unZG1uMc-WR3NVeTBDcmRwN0NxcGNNVlUwUldPMVprb1dJPQ>`_.-Module API------------Kornia augmentation implementations can be easily used in a TorchVision style using `nn.Sequential`... code-block:: python@@ -64,11 +61,11 @@ Example for semantic segmentation using low-level randomness control:f"Input shape should be consistent with mask shape, "f"while got {input.shape}, {mask.shape}"- aff_params = self.aff.generate_parameters(input.shape)+ aff_params = self.aff.forward_parameters(input.shape)input = self.aff(input, aff_params)mask = self.aff(mask, aff_params)- jit_params = self.jit.generate_parameters(input.shape)+ jit_params = self.jit.forward_parameters(input.shape)input = self.jit(input, jit_params)mask = self.jit(mask, jit_params)return input, maskdiff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 4ae462ee9..eafbdef1d 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -79,17 +79,8 @@ class _BasicAugmentationBase(nn.Module):self.device = deviceself.dtype = dtype- def __selective_param_gen__(- self, batch_shape: torch.Size, to_apply: torch.Tensor) -> Dict[str, torch.Tensor]:- _params = self.generate_parameters(- torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))- if _params is None:- _params = {}- _params['batch_prob'] = to_apply- return _params-- def __forward_parameters__(- self, batch_shape: torch.Size, p: float, p_batch: float, same_on_batch: bool) -> Dict[str, torch.Tensor]:+ def __batch_prob_generator__(+ self, batch_shape: torch.Size, p: float, p_batch: float, same_on_batch: bool) -> torch.Tensor:batch_prob: torch.Tensorif p_batch == 1:batch_prob = torch.tensor([True])@@ -109,8 +100,16 @@ class _BasicAugmentationBase(nn.Module):batch_prob = batch_prob * elem_probelse:batch_prob = batch_prob.repeat(batch_shape[0])- # selectively param gen- return self.__selective_param_gen__(batch_shape, batch_prob)+ return batch_prob++ def forward_parameters(self, batch_shape):+ to_apply = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch)+ _params = self.generate_parameters(+ torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))+ if _params is None:+ _params = {}+ _params['batch_prob'] = to_apply+ return _paramsdef apply_func(self, input: torch.Tensor, params: Dict[str, torch.Tensor],) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:@@ -125,7 +124,7 @@ class _BasicAugmentationBase(nn.Module):in_tensor = self.transform_tensor(in_tensor)batch_shape = in_tensor.shapeif params is None:- params = self.__forward_parameters__(batch_shape, self.p, self.p_batch, self.same_on_batch)+ params = self.forward_parameters(batch_shape)self._params = paramsoutput = self.apply_func(input, self._params)@@ -224,7 +223,7 @@ class _AugmentationBase(_BasicAugmentationBase):if return_transform is None:return_transform = self.return_transformif params is None:- params = self.__forward_parameters__(batch_shape, self.p, self.p_batch, self.same_on_batch)+ params = self.forward_parameters(batch_shape)if 'batch_prob' not in params:params['batch_prob'] = torch.tensor([True] * batch_shape[0])warnings.warn("`batch_prob` is not found in params. Will assume applying on all data.")@@ -387,7 +386,7 @@ class MixAugmentationBase(_BasicAugmentationBase):in_tensor = self.transform_tensor(in_tensor)if params is None:batch_shape = in_tensor.shape- params = self.__forward_parameters__(batch_shape, self.p, self.p_batch, self.same_on_batch)+ params = self.forward_parameters(batch_shape)self._params = paramsoutput = self.apply_func(in_tensor, label, self._params)diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex f9a9d6074..1ec4e89b2 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -1,11 +1,10 @@-from typing import List, Tuple, Union, cast+from typing import Tuple, Union, castimport torchimport torch.nn as nnimport korniafrom kornia.augmentation.base import _AugmentationBase, MixAugmentationBase-from kornia.augmentation import ColorJitterclass VideoSequential(nn.Sequential):@@ -109,18 +108,17 @@ class VideoSequential(nn.Sequential):# Got param generation shape to (B, C, H, W). Ignoring T.batch_shape = self.__infer_channel_exclusive_batch_shape__(input)input = self._input_shape_convert_in(input)- _original_shape = input.shapeinput = input.reshape(-1, *batch_shape[1:])if not self.same_on_frame:# Overwrite param generation shape to (B * T, C, H, W).batch_shape = input.shapefor aug in self.children():aug = cast(_AugmentationBase, aug)- param = aug.__forward_parameters__(batch_shape, aug.p, aug.p_batch, aug.same_on_batch)+ param = aug.forward_parameters(batch_shape)if self.same_on_frame:for k, v in param.items():# TODO: revise colorjitter order param in the future to align the standard.- if not (k == "order" and isinstance(aug, ColorJitter)):+ if not (k == "order" and isinstance(aug, kornia.augmentation.ColorJitter)):param.update({k: self.__repeat_param_across_channels__(v, frame_num)})input = aug(input, params=param)diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.pyindex a7b7ba3a4..18e78cdc7 100644--- a/test/augmentation/test_augmentation.py+++ b/test/augmentation/test_augmentation.py@@ -1550,7 +1550,7 @@ class TestRectangleRandomErasing:aspect_ratio_range = (.3, .5)rand_rec = RandomErasing(erase_scale_range, aspect_ratio_range, p=1.0)- rect_params = rand_rec.__forward_parameters__(batch_shape, p=1.0, p_batch=1., same_on_batch=False)+ rect_params = rand_rec.forward_parameters(batch_shape)# evaluate function gradientinput = torch.rand(batch_shape, device=device, dtype=dtype)diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.pyindex abc841fe3..0cfc33728 100644--- a/test/augmentation/test_base.py+++ b/test/augmentation/test_base.py@@ -47,7 +47,7 @@ class TestBasicAugmentationBase:generate_parameters.side_effect = lambda shape: {'degrees': torch.arange(0, shape[0], device=device, dtype=dtype)}- output = augmentation.__forward_parameters__(input_shape, p, p_batch, same_on_batch)+ output = augmentation.forward_parameters(input_shape)assert "batch_prob" in outputassert len(output['degrees']) == output['batch_prob'].sum().item() == numdiff --git a/test/geometry/transform/crop/test_crop2d.py b/test/geometry/transform/crop/test_crop2d.pyindex 536e7f83b..4dc70e87e 100644--- a/test/geometry/transform/crop/test_crop2d.py+++ b/test/geometry/transform/crop/test_crop2d.py@@ -87,7 +87,7 @@ class TestCropAndResize:]], device=device, dtype=dtype) # 1x4x2patches = kornia.crop_and_resize(inp, boxes, (height, width))- assert_allclose(patches, expected)+ assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)def test_crop_batch(self, device, dtype):inp = torch.tensor([[[@@ -123,7 +123,7 @@ class TestCropAndResize:]], device=device, dtype=dtype) # 2x4x2patches = kornia.crop_and_resize(inp, boxes, (2, 2), align_corners=True)- assert_allclose(patches, expected)+ assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)def test_crop_batch_broadcast(self, device, dtype):inp = torch.tensor([[[@@ -154,7 +154,7 @@ class TestCropAndResize:]], device=device, dtype=dtype) # 1x4x2patches = kornia.crop_and_resize(inp, boxes, (2, 2), align_corners=True)- assert_allclose(patches, expected)+ assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)def test_gradcheck(self, device, dtype):img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)@@ -193,7 +193,7 @@ class TestCropAndResize:crop_height, crop_width = 4, 2actual = op_script(img, boxes, (crop_height, crop_width))expected = op(img, boxes, (crop_height, crop_width))- assert_allclose(actual, expected)+ assert_allclose(actual, expected, rtol=1e-4, atol=1e-4)class TestCenterCrop:@@ -211,7 +211,7 @@ class TestCenterCrop:]]], device=device, dtype=dtype)out_crop = kornia.center_crop(inp, (2, 4))- assert_allclose(out_crop, expected)+ assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)def test_center_crop_h4_w2(self, device, dtype):inp = torch.tensor([[[@@ -229,8 +229,8 @@ class TestCenterCrop:[14., 15.],]]], device=device, dtype=dtype)- out_crop = kornia.center_crop(inp, (4, 2))- assert_allclose(out_crop, expected)+ out_crop = kornia.center_crop(inp, (height, width))+ assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)def test_center_crop_h4_w2_batch(self, device, dtype):inp = torch.tensor([@@ -257,7 +257,7 @@ class TestCenterCrop:]]], device=device, dtype=dtype)out_crop = kornia.center_crop(inp, (4, 2))- assert_allclose(out_crop, expected)+ assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)def test_gradcheck(self, device, dtype):img = torch.rand(1, 2, 5, 4, device=device, dtype=dtype)@@ -274,7 +274,7 @@ class TestCenterCrop:actual = op_script(img, (4, 2))expected = op(img, (4, 2))- assert_allclose(actual, expected)+ assert_allclose(actual, expected, rtol=1e-4, atol=1e-4)def test_jit_trace(self, device, dtype):# Define script@@ -287,7 +287,7 @@ class TestCenterCrop:# Runactual = op_trace(img, (torch.tensor(2), torch.tensor(3)))expected = op(img, (2, 3))- assert_allclose(actual, expected)+ assert_allclose(actual, expected, rtol=1e-4, atol=1e-4)class TestCropByBoxes:@@ -349,7 +349,7 @@ class TestCropByBoxes:]]], device=device, dtype=dtype)patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst, align_corners=True)- assert_allclose(patches, expected)+ assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)def test_gradcheck(self, device, dtype):inp = torch.randn((1, 1, 3, 3), device=device, dtype=dtype)diff --git a/test/geometry/transform/crop/test_crop3d.py b/test/geometry/transform/crop/test_crop3d.pyindex 3d67b5daf..9f34469c2 100644--- a/test/geometry/transform/crop/test_crop3d.py+++ b/test/geometry/transform/crop/test_crop3d.py@@ -190,7 +190,7 @@ class TestCenterCrop3D:(inp.size(4) // 2 - crop_size[2] // 2):(inp.size(4) // 2 + crop_size[2] // 2 + 1)]out_crop = kornia.center_crop3d(inp, crop_size, align_corners=True)- assert_allclose(out_crop, expected)+ assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)@pytest.mark.parametrize("crop_size", [(3, 5, 7), (5, 3, 7), (7, 3, 5)])def test_center_crop_357_batch(self, crop_size, device, dtype):@@ -205,7 +205,7 @@ class TestCenterCrop3D:(inp.size(4) // 2 - crop_size[2] // 2):(inp.size(4) // 2 + crop_size[2] // 2 + 1)]out_crop = kornia.center_crop3d(inp, crop_size, align_corners=True)- assert_allclose(out_crop, expected)+ assert_allclose(out_crop, expected, rtol=1e-4, atol=1e-4)def test_gradcheck(self, device, dtype):img = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)@@ -221,7 +221,7 @@ class TestCenterCrop3D:actual = op_script(img, (4, 3, 2))expected = kornia.center_crop3d(img, (4, 3, 2))- assert_allclose(actual, expected)+ assert_allclose(actual, expected, rtol=1e-4, atol=1e-4)class TestCropByBoxes3D:@@ -251,7 +251,7 @@ class TestCropByBoxes3D:expected = inp[:, :, 1:3, 1:4, 1:4]patches = kornia.geometry.transform.crop.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)- assert_allclose(patches, expected)+ assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)def test_crop_by_boxes_resizing(self, device, dtype):inp = torch.arange(0., 343., device=device, dtype=dtype).view(1, 1, 7, 7, 7)@@ -284,7 +284,7 @@ class TestCropByBoxes3D:]]], device=device, dtype=dtype)patches = kornia.geometry.transform.crop.crop_by_boxes3d(inp, src_box, dst_box, align_corners=True)- assert_allclose(patches, expected)+ assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)def test_jit(self, device, dtype):# Define script@@ -315,7 +315,7 @@ class TestCropByBoxes3D:actual = op_script(inp, src_box, dst_box, align_corners=True)expected = op(inp, src_box, dst_box, align_corners=True)- assert_allclose(actual, expected)+ assert_allclose(actual, expected, rtol=1e-4, atol=1e-4)def test_gradcheck(self, device, dtype):inp = torch.randn((1, 1, 7, 7, 7), device=device, dtype=dtype)