🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Fix output types of augmentations on autocast regions (#2168)
João Gustavo A. Amorim3e0a95fd9892
diff --git a/docs/source/utils.rst b/docs/source/utils.rstindex 2a8664bfb..8e81a3386 100644--- a/docs/source/utils.rst+++ b/docs/source/utils.rst@@ -39,3 +39,9 @@ Device-------.. autofunction:: get_cuda_device_if_available+.. autofunction:: map_location_to_cpu+++Automatic Mixed Precision+-------------------------+.. autofunction:: is_autocast_enableddiff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.pyindex a8f983902..ba7e2502b 100644--- a/kornia/augmentation/_2d/base.py+++ b/kornia/augmentation/_2d/base.py@@ -1,12 +1,13 @@from typing import Any, Dict, Optional-from torch import Tensor, float16, float32, float64+from torch import float16, float32, float64from kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.utils import _transform_input, _validate_input_dtype+from kornia.core import Tensorfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints-from kornia.utils import eye_like+from kornia.utils import eye_like, is_autocast_enabledclass AugmentationBase2D(_AugmentationBase):@@ -69,27 +70,23 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):def generate_transformation_matrix(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:"""Generate transformation matrices with the given input and param settings."""- # Note about the explicit type conversions here:- # If this code is run in an autocast-enabled region, the transformation matrix or the output- # may be float16 even though the input was float32 (e.g. torch.mm produces float16 output),- # see also the documentation on autocasting: https://pytorch.org/docs/stable/amp.html.- # It may be unexpected for the user if the output type changes and it can also lead to errors- # for the index_put operation below (see also https://github.com/kornia/kornia/issues/1737)- # In case the type already matches the input type, the conversions are no-ops-to_apply = params['batch_prob']in_tensor = self.transform_tensor(input)if not to_apply.any():trans_matrix = self.identity_matrix(in_tensor)elif to_apply.all():- trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags).type(in_tensor.dtype)+ trans_matrix = self.compute_transformation(in_tensor, params=params, flags=flags)else:- trans_matrix = self.identity_matrix(in_tensor)- trans_matrix = trans_matrix.index_put(- (to_apply,),- self.compute_transformation(in_tensor[to_apply], params=params, flags=flags).type(in_tensor.dtype),- )- return trans_matrix.type(in_tensor.dtype)+ trans_matrix_A = self.identity_matrix(in_tensor)+ trans_matrix_B = self.compute_transformation(in_tensor[to_apply], params=params, flags=flags)++ if is_autocast_enabled():+ trans_matrix_A = trans_matrix_A.type(input.dtype)+ trans_matrix_B = trans_matrix_B.type(input.dtype)++ trans_matrix = trans_matrix_A.index_put((to_apply,), trans_matrix_B)++ return trans_matrixdef inverse_inputs(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any], transform: Optional[Tensor] = Nonediff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.pyindex faa6477bb..613c4008a 100644--- a/kornia/augmentation/_2d/mix/base.py+++ b/kornia/augmentation/_2d/mix/base.py@@ -63,7 +63,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):output = self.apply_non_transform(in_tensor, params, flags)output = output.index_put((to_apply,), self.apply_non_transform(applied, params, flags))output = _transform_output_shape(output, ori_shape) if self.keepdim else output- return output.type(in_tensor.dtype)+ return outputdef transform_mask(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:to_apply = params['batch_prob']diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 3d1e0ba0d..75ad9bf00 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -9,6 +9,7 @@ from kornia.augmentation.utils import _adapted_sampling, _transform_output_shapefrom kornia.core import Module, Tensor, tensorfrom kornia.geometry.boxes import Boxesfrom kornia.geometry.keypoints import Keypoints+from kornia.utils import is_autocast_enabledTensorWithTransformMat = Union[Tensor, Tuple[Tensor, Tensor]]@@ -250,8 +251,15 @@ class _AugmentationBase(_BasicAugmentationBase):applied = self.apply_transform(in_tensor[to_apply], params, flags, transform=transform if transform is None else transform[to_apply])++ if is_autocast_enabled():+ output = output.type(input.dtype)+ applied = applied.type(input.dtype)output = output.index_put((to_apply,), applied)output = _transform_output_shape(output, ori_shape) if self.keepdim else output++ if is_autocast_enabled():+ output = output.type(input.dtype)return outputdef transform_masks(@@ -311,6 +319,10 @@ class _AugmentationBase(_BasicAugmentationBase):applied = self.apply_transform_box(input[to_apply], params, flags, transform=transform if transform is None else transform[to_apply])+ if is_autocast_enabled():+ output = output.type(input.dtype)+ applied = applied.type(input.dtype)+output = output.index_put((to_apply,), applied)return output@@ -340,6 +352,9 @@ class _AugmentationBase(_BasicAugmentationBase):applied = self.apply_transform_keypoint(input[to_apply], params, flags, transform=transform if transform is None else transform[to_apply])+ if is_autocast_enabled():+ output = output.type(input.dtype)+ applied = applied.type(input.dtype)output = output.index_put((to_apply,), applied)return output@@ -425,4 +440,4 @@ class _AugmentationBase(_BasicAugmentationBase):output = self.transform_inputs(in_tensor, params, flags)- return output.type(in_tensor.dtype)+ return outputdiff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex 28717a52f..606b32a8b 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -11,7 +11,7 @@ from kornia.constants import DataKey, Resamplefrom kornia.core import Module, Tensorfrom kornia.geometry.boxes import Boxes, VideoBoxesfrom kornia.geometry.keypoints import Keypoints, VideoKeypoints-from kornia.utils import eye_like+from kornia.utils import eye_like, is_autocast_enabled__all__ = ["AugmentationSequential"]@@ -144,6 +144,10 @@ class AugmentationSequential(ImageSequential):_transform_matrix: Optional[Tensor]_transform_matrices: List[Tensor] = []+ _boxes_options = {DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH}+ _keypoints_options = {DataKey.KEYPOINTS}+ _img_msk_options = {DataKey.INPUT, DataKey.MASK}+def __init__(self,*args: Union[_AugmentationBase, ImageSequential],@@ -286,11 +290,11 @@ class AugmentationSequential(ImageSequential):def _arguments_preproc(self, *args: DataType, data_keys: List[DataKey]) -> List[DataType]:inp: List[DataType] = []for arg, dcate in zip(args, data_keys):- if DataKey.get(dcate) in [DataKey.INPUT, DataKey.MASK]:+ if DataKey.get(dcate) in self._img_msk_options:inp.append(arg)- elif DataKey.get(dcate) in [DataKey.KEYPOINTS]:+ elif DataKey.get(dcate) in self._keypoints_options:inp.append(self._preproc_keypoints(arg, dcate))- elif DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH]:+ elif DataKey.get(dcate) in self._boxes_options:inp.append(self._preproc_boxes(arg, dcate))else:raise NotImplementedError(f"input type of {dcate} is not implemented.")@@ -301,16 +305,29 @@ class AugmentationSequential(ImageSequential):) -> List[DataType]:out: List[DataType] = []for in_arg, out_arg, dcate in zip(in_args, out_args, data_keys):- if DataKey.get(dcate) in [DataKey.INPUT]:+ if DataKey.get(dcate) in self._img_msk_options:# It is tensor type already.out.append(out_arg)- elif DataKey.get(dcate) in [DataKey.MASK]:- # TODO: may add the float to integer, etc.- out.append(out_arg)- elif DataKey.get(dcate) in [DataKey.KEYPOINTS]:- out.append(self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate))- elif DataKey.get(dcate) in [DataKey.BBOX, DataKey.BBOX_XYXY, DataKey.BBOX_XYWH]:- out.append(self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate))+ # TODO: may add the float to integer (for masks), etc.++ elif DataKey.get(dcate) in self._keypoints_options:+ _out_k = self._postproc_keypoint(in_arg, cast(Keypoints, out_arg), dcate)+ if is_autocast_enabled() and isinstance(in_arg, (Tensor, Keypoints)):+ if isinstance(_out_k, list):+ _out_k = [i.type(in_arg.dtype) for i in _out_k]+ else:+ _out_k = _out_k.type(in_arg.dtype)+ out.append(_out_k)++ elif DataKey.get(dcate) in self._boxes_options:+ _out_b = self._postproc_boxes(in_arg, cast(Boxes, out_arg), dcate)+ if is_autocast_enabled() and isinstance(in_arg, (Tensor, Boxes)):+ if isinstance(_out_b, list):+ _out_b = [i.type(in_arg.dtype) for i in _out_b]+ else:+ _out_b = _out_b.type(in_arg.dtype)+ out.append(_out_b)+else:raise NotImplementedError(f"input type of {dcate} is not implemented.")@@ -397,6 +414,7 @@ class AugmentationSequential(ImageSequential):mode = "xywh"else:raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")+# TODO: handle 3d scenariosif isinstance(in_arg, (Boxes,)):return out_argdiff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex f4fa0f12d..001b7b9df 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -658,6 +658,10 @@ class Boxes:obj._is_batched = self._is_batchedreturn obj+ def type(self, dtype: torch.dtype) -> "Boxes":+ self._data = self._data.type(dtype)+ return self+class VideoBoxes(Boxes):temporal_channel_size: intdiff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.pyindex ca55d2670..fbc27f04a 100644--- a/kornia/geometry/keypoints.py+++ b/kornia/geometry/keypoints.py@@ -1,5 +1,7 @@from typing import List, Optional, Tuple, Union, cast+import torch+from kornia.core import Tensorfrom kornia.geometry import transform_points@@ -52,6 +54,16 @@ class Keypoints:def data(self):return self._data+ @property+ def device(self) -> torch.device:+ """Returns keypoints device."""+ return self._data.device++ @property+ def dtype(self) -> torch.dtype:+ """Returns keypoints dtype."""+ return self._data.dtype+def index_put(self,indices: Union[Tuple[Tensor, ...], List[Tensor]],@@ -145,6 +157,10 @@ class Keypoints:def clone(self) -> "Keypoints":return Keypoints(self._data.clone(), False)+ def type(self, dtype: torch.dtype) -> "Keypoints":+ self._data = self._data.type(dtype)+ return self+class VideoKeypoints(Keypoints):temporal_channel_size: intdiff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.pyindex 114bfa910..a9b4c902d 100644--- a/kornia/utils/__init__.py+++ b/kornia/utils/__init__.py@@ -4,6 +4,7 @@ from .grid import create_meshgrid, create_meshgrid3dfrom .helpers import (_extract_device_dtype,get_cuda_device_if_available,+ is_autocast_enabled,map_location_to_cpu,safe_inverse_with_mask,safe_solve_with_mask,@@ -36,4 +37,5 @@ __all__ = ["vec_like","torch_meshgrid","map_location_to_cpu",+ "is_autocast_enabled",]diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.pyindex 43fe891ae..78f1bb03d 100644--- a/kornia/utils/helpers.py+++ b/kornia/utils/helpers.py@@ -40,6 +40,7 @@ def map_location_to_cpu(storage: str) -> str:def map_location_to_cpu(storage: Union[str, Tensor], *args: Any, **kwargs: Any) -> Union[str, Tensor]:+ """Map location of device to CPU, util for loading things from HUB."""return storage@@ -248,3 +249,28 @@ def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:inverse, info = inv_ex(A.to(dtype))mask = info == 0return inverse.to(dtype_original), mask+++def is_autocast_enabled(both: bool = True) -> bool:+ """Check if torch autocast is enabled.++ Args:+ both: if True will consider autocast region for both types of devices++ Returns:+ Return a Bool,+ will always return False for a torch without support, otherwise will be: if both is True+ `torch.is_autocast_enabled() or torch.is_autocast_cpu_enabled()`. If both is Flase will return just+ `torch.is_autocast_enabled()`.+ """+ if TYPE_CHECKING:+ # TODO: remove this branch when kornia relies on torch >= 1.10.2+ return False++ if not torch_version_ge(1, 10, 2):+ return False++ if both:+ return torch.is_autocast_enabled() or torch.is_autocast_cpu_enabled()++ return torch.is_autocast_enabled()diff --git a/kornia/utils/misc.py b/kornia/utils/misc.pyindex b81977b9b..f601f3bef 100644--- a/kornia/utils/misc.py+++ b/kornia/utils/misc.py@@ -23,7 +23,7 @@ def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.if len(input.shape) < 1:raise AssertionError(input.shape)- identity = torch.eye(n, device=input.device, dtype=input.dtype)+ identity = torch.eye(n, device=input.device).type(input.dtype)return identity[None].expand(input.shape[0], n, n) if shared_memory else identity[None].repeat(input.shape[0], 1, 1)diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.pyindex 0b869e994..0c8023d3b 100644--- a/test/augmentation/test_base.py+++ b/test/augmentation/test_base.py@@ -5,8 +5,11 @@ import torchfrom torch.autograd import gradcheckimport kornia.testing as utils # test utils-from kornia.augmentation import RandomGaussianBlurfrom kornia.augmentation._2d.base import AugmentationBase2D+from kornia.augmentation._2d.geometric.affine import RandomAffine+from kornia.augmentation._2d.intensity.gaussian_blur import RandomGaussianBlur+from kornia.augmentation._3d.geometric.affine import RandomAffine3D+from kornia.augmentation._3d.intensity.motion_blur import RandomMotionBlur3Dfrom kornia.augmentation.base import _BasicAugmentationBasefrom kornia.testing import assert_close@@ -76,28 +79,6 @@ class TestBasicAugmentationBase:assert output.shape == expected_output.shapeassert_close(output, expected_output)- @pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])- def test_autocast(self, batch_prob, device, dtype):- if not hasattr(torch, "autocast"):- pytest.skip("PyTorch version without autocast support")-- torch.manual_seed(42)-- aug = RandomGaussianBlur((3, 3), (0.1, 3), p=1)- x = torch.rand(len(batch_prob), 3, 100, 100, dtype=dtype).to(device)-- # Explicitly set the batch probability to trigger the different conditions in apply_func()- params = aug.forward_parameters(x.shape)- params["batch_prob"] = torch.tensor(batch_prob, device=params["batch_prob"].device)-- # There is usually only a sigma value for the batch images which get transformed- params["sigma"] = params["sigma"][params["batch_prob"]]-- with torch.autocast(device.type):- res = aug(x, params)-- assert res.dtype == dtype, "The output dtype should match the input dtype"-class TestAugmentationBase2D:def test_forward(self, device, dtype):@@ -165,3 +146,87 @@ class TestAugmentationBase2D:with patch.object(augmentation, "apply_transform", autospec=True) as apply_transform:apply_transform.return_value = outputassert gradcheck(augmentation, ((input, input_param)), raise_exception=True, fast_mode=True)+++class TestGeometricAugmentationBase2D:+ @pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])+ def test_autocast(self, batch_prob, device, dtype):+ if not hasattr(torch, "autocast"):+ pytest.skip("PyTorch version without autocast support")++ # Uses some subclass of `GeometricAugmentationBase2D` which perform some op which can mismatch the dtype+ # Will cover AugmentationBase2D and RigidAffineAugmentationBase2D too+ aug = RandomAffine(0.5, (0.1, 0.5), (0.5, 1.5), 1.2, p=1.0)+ x = torch.rand(len(batch_prob), 5, 10, 7, dtype=dtype, device=device)++ to_apply = torch.tensor(batch_prob, device=device)+ with patch.object(aug, '__batch_prob_generator__', return_value=to_apply):+ params = aug.forward_parameters(x.shape)++ with torch.autocast(device.type):+ res = aug(x, params)++ assert res.dtype == dtype, "The output dtype should match the input dtype"+++class TestIntensityAugmentationBase2D:+ @pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])+ def test_autocast(self, batch_prob, device, dtype):+ if not hasattr(torch, "autocast"):+ pytest.skip("PyTorch version without autocast support")++ # Uses some subclass of `IntensityAugmentationBase2D` which perform some op which can mismatch the dtype+ # Will cover AugmentationBase2D and RigidAffineAugmentationBase2D too+ aug = RandomGaussianBlur((3, 3), (0.1, 3), p=1)+ x = torch.rand(len(batch_prob), 5, 10, 7, dtype=dtype, device=device)++ to_apply = torch.tensor(batch_prob, device=device)+ with patch.object(aug, '__batch_prob_generator__', return_value=to_apply):+ params = aug.forward_parameters(x.shape)++ with torch.autocast(device.type):+ res = aug(x, params)++ assert res.dtype == dtype, "The output dtype should match the input dtype"+++class TestIntensityAugmentationBase3D:+ @pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])+ def test_autocast(self, batch_prob, device, dtype):+ if not hasattr(torch, "autocast"):+ pytest.skip("PyTorch version without autocast support")++ # Uses some subclass of `IntensityAugmentationBase3D` which perform some op which can mismatch the dtype+ # Will cover RigidAffineAugmentationBase3D and AugmentationBase3D too+ aug = RandomMotionBlur3D(3, 35.0, 0.5, p=1)+ x = torch.rand(len(batch_prob), 1, 3, 10, 7, dtype=dtype, device=device)++ to_apply = torch.tensor(batch_prob, device=device)+ with patch.object(aug, '__batch_prob_generator__', return_value=to_apply):+ params = aug.forward_parameters(x.shape)++ with torch.autocast(device.type):+ res = aug(x, params)++ assert res.dtype == dtype, "The output dtype should match the input dtype"+++class TestGeometricAugmentationBase3D:+ @pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])+ def test_autocast(self, batch_prob, device, dtype):+ if not hasattr(torch, "autocast"):+ pytest.skip("PyTorch version without autocast support")++ # Uses some subclass of `GeometricAugmentationBase3D` which perform some op which can mismatch the dtype+ # Will cover RigidAffineAugmentationBase3D and AugmentationBase3D too+ aug = RandomAffine3D((15.0, 20.0, 20.0), p=1)+ x = torch.rand(len(batch_prob), 1, 3, 10, 7, dtype=dtype, device=device)++ to_apply = torch.tensor(batch_prob, device=device)+ with patch.object(aug, '__batch_prob_generator__', return_value=to_apply):+ params = aug.forward_parameters(x.shape)++ with torch.autocast(device.type):+ res = aug(x, params)++ assert res.dtype == dtype, "The output dtype should match the input dtype"diff --git a/test/augmentation/test_container.py b/test/augmentation/test_container.pyindex bdca4e859..59e26b7e1 100644--- a/test/augmentation/test_container.py+++ b/test/augmentation/test_container.py@@ -1,8 +1,12 @@+from functools import partial+from unittest.mock import patch+import pytestimport torchimport korniaimport kornia.augmentation as K+from kornia.augmentation.container.base import ParamItemfrom kornia.constants import BorderTypefrom kornia.geometry.bbox import bbox_to_maskfrom kornia.testing import assert_close@@ -149,6 +153,23 @@ class TestVideoSequential:op_jit = torch.jit.script(op)assert_close(op(img), op_jit(img))+ @pytest.mark.parametrize('data_format', ["BCTHW", "BTCHW"])+ def test_autocast(self, data_format, device, dtype):+ if not hasattr(torch, "autocast"):+ pytest.skip("PyTorch version without autocast support")++ tfs = (K.RandomAffine(0.5, (0.1, 0.5), (0.5, 1.5), 1.2, p=1.0), K.RandomGaussianBlur((3, 3), (0.1, 3), p=1))+ aug = K.VideoSequential(*tfs, data_format=data_format, random_apply=True)+ if data_format == 'BCTHW':+ imgs = torch.randn(2, 3, 1, 5, 6, device=device, dtype=dtype).repeat(1, 1, 4, 1, 1)+ elif data_format == 'BTCHW':+ imgs = torch.randn(2, 1, 3, 5, 6, device=device, dtype=dtype).repeat(1, 4, 1, 1, 1)++ with torch.autocast(device.type):+ output = aug(imgs)++ assert output.dtype == dtype, 'Output image dtype should match the input dtype'+class TestSequential:@pytest.mark.parametrize('random_apply_weights', [None, [0.8, 0.9]])@@ -611,6 +632,57 @@ class TestAugmentationSequential:op_jit = torch.jit.script(op)assert_close(op(img), op_jit(img))+ @pytest.mark.parametrize("batch_prob", [[True, True], [False, True], [False, False]])+ @pytest.mark.parametrize("box", ['bbox', 'bbox_xyxy', 'bbox_xywh'])+ def test_autocast(self, batch_prob, box, device, dtype):+ if not hasattr(torch, "autocast"):+ pytest.skip("PyTorch version without autocast support")++ def mock_forward_parameters_sequential(batch_shape, cls, batch_prob):+ named_modules = cls.get_forward_sequence()+ params = []+ for name, module in named_modules:+ if isinstance(module, (K.base._AugmentationBase, K.MixAugmentationBaseV2, K.ImageSequential)):+ with patch.object(module, '__batch_prob_generator__', return_value=batch_prob):+ mod_param = module.forward_parameters(batch_shape)++ param = ParamItem(name, mod_param)+ else:+ param = ParamItem(name, None)+ batch_shape = K.container.image._get_new_batch_shape(param, batch_shape)+ params.append(param)+ return params++ tfs = (K.RandomAffine(0.5, (0.1, 0.5), (0.5, 1.5), 1.2, p=1.0), K.RandomGaussianBlur((3, 3), (0.1, 3), p=1))+ data_keys = ['input', 'mask', box, 'keypoints']+ aug = K.AugmentationSequential(*tfs, data_keys=data_keys, random_apply=True)+ bs = len(batch_prob)+ imgs = torch.rand(bs, 3, 7, 4, dtype=dtype, device=device)+ if box == 'bbox':+ bb = torch.tensor([[[1.0, 1.0], [2.0, 1.0], [2.0, 2.0], [1.0, 2.0]]], dtype=dtype, device=device).expand(+ bs, 1, -1, -1+ )+ else:+ bb = torch.rand(bs, 1, 4, dtype=dtype, device=device)++ msk = torch.zeros_like(imgs)+ msk[..., 3:, 2] = 1.0+ points = torch.rand(bs, 1, 2, dtype=dtype, device=device)++ to_apply = torch.tensor(batch_prob, device=device)++ fwd_params = partial(mock_forward_parameters_sequential, cls=aug, batch_prob=to_apply)+ with patch.object(aug, 'forward_parameters', fwd_params):+ params = aug.forward_parameters(imgs.shape)++ with torch.autocast(device.type):+ outputs = aug(imgs, msk, bb, points, params=params)++ assert outputs[0].dtype == dtype, 'Output image dtype should match the input dtype'+ assert outputs[1].dtype == dtype, 'Output mask dtype should match the input dtype'+ assert outputs[2].dtype == dtype, 'Output box dtype should match the input dtype'+ assert outputs[3].dtype == dtype, 'Output keypoints dtype should match the input dtype'+class TestPatchSequential:@pytest.mark.parametrize(@@ -701,6 +773,19 @@ class TestPatchSequential:)assert seq.is_intensity_only()+ def test_autocast(self, device, dtype):+ if not hasattr(torch, "autocast"):+ pytest.skip("PyTorch version without autocast support")++ tfs = (K.RandomAffine(0.5, (0.1, 0.5), (0.5, 1.5), 1.2, p=1.0), K.RandomGaussianBlur((3, 3), (0.1, 3), p=1))+ aug = K.PatchSequential(*tfs, grid_size=(2, 2), random_apply=True)+ imgs = torch.rand(2, 3, 7, 4, dtype=dtype, device=device)++ with torch.autocast(device.type):+ output = aug(imgs)++ assert output.dtype == dtype, 'Output image dtype should match the input dtype'+class TestDispatcher:def test_many_to_many(self, device, dtype):