Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Explicitly cast output to input type to avoid type mismatch errors (#1842)

Jan Sellner0152691a8002
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 613c4008a..faa6477bb 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
+ return output.type(in_tensor.dtype)
def 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.py
index 625e66fdf..3794faf5e 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -246,6 +246,14 @@ class _AugmentationBase(_BasicAugmentationBase):
flags = self.flags
to_apply = params['batch_prob']
+ # 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
+
# if no augmentation needed
if not to_apply.any():
output = in_tensor
@@ -258,13 +266,16 @@ class _AugmentationBase(_BasicAugmentationBase):
output = in_tensor.clone()
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)
+ (to_apply,),
+ self.compute_transformation(in_tensor[to_apply], params=params, flags=flags).type(in_tensor.dtype),
)
output = output.index_put(
(to_apply,),
- self.apply_transform(in_tensor[to_apply], params=params, flags=flags, transform=trans_matrix[to_apply]),
+ self.apply_transform(
+ in_tensor[to_apply], params=params, flags=flags, transform=trans_matrix[to_apply]
+ ).type(in_tensor.dtype),
)
- self._transform_matrix = trans_matrix
+ self._transform_matrix = trans_matrix.type(in_tensor.dtype)
- return output
+ return output.type(in_tensor.dtype)
diff --git a/test/augmentation/test_base.py b/test/augmentation/test_base.py
index 1c7eac4d4..be1f48779 100644
--- a/test/augmentation/test_base.py
+++ b/test/augmentation/test_base.py
@@ -5,6 +5,7 @@ import torch
from torch.autograd import gradcheck
import kornia.testing as utils # test utils
+from kornia.augmentation import RandomGaussianBlur
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.augmentation.base import _BasicAugmentationBase
from kornia.testing import assert_close
@@ -75,6 +76,28 @@ class TestBasicAugmentationBase:
assert output.shape == expected_output.shape
assert_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:
@pytest.mark.parametrize(