Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Fix] Fixed mypy warnings (#1920)

Jian Shidaa382c40e2f
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index e7b9b50a8..5e8f4a23e 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -5,7 +5,7 @@ import torch
from kornia.augmentation.base import TensorWithTransformMat, _BasicAugmentationBase
from kornia.augmentation.utils import _transform_input, _transform_output_shape, _validate_input_dtype
-from kornia.constants import DataKey
+from kornia.constants import DataKey, DType
from kornia.core import Tensor
from kornia.geometry.boxes import Boxes
from kornia.testing import KORNIA_UNWRAP
@@ -249,7 +249,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
in_tensor: Tensor = input[in_tensor_idx]
in_tensor = self.transform_tensor(in_tensor)
self._params = self.forward_parameters(in_tensor.shape)
- self._params.update({"device": in_tensor.device, "dtype": in_tensor.dtype})
+ self._params.update({"dtype": torch.tensor(DType.get(in_tensor.dtype).value)})
else:
self._params = params
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 48ee17987..bc560748c 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -6,7 +6,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBase, MixAugmentationBaseV2
from kornia.augmentation.utils import _shape_validation
-from kornia.constants import DataKey
+from kornia.constants import DataKey, DType
from kornia.core import Tensor
from kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape
@@ -222,9 +222,9 @@ class RandomCutMixV2(MixAugmentationBaseV2):
out_labels.append(
torch.stack(
[
- input.to(device=input.device, dtype=params["dtype"]),
- labels_permute.to(device=input.device, dtype=params["dtype"]),
- lam.to(device=input.device, dtype=params["dtype"]),
+ input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
+ labels_permute.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
+ lam.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
],
dim=1,
)
@@ -236,13 +236,13 @@ class RandomCutMixV2(MixAugmentationBaseV2):
self, input: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
) -> Tensor:
out_labels = []
- lam = torch.zeros((len(input)), device=input.device, dtype=params["dtype"])
+ lam = torch.zeros((len(input)), device=input.device, dtype=DType.to_torch(int(params["dtype"].item())))
for _ in range(self._param_generator.num_mix):
out_labels.append(
torch.stack(
[
- input.to(device=input.device, dtype=params["dtype"]),
- input.to(device=input.device, dtype=params["dtype"]),
+ input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
+ input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
lam,
],
dim=1,
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index 162c0cd1c..65345c3ae 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -5,7 +5,7 @@ import torch
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBase, MixAugmentationBaseV2
-from kornia.constants import DataKey
+from kornia.constants import DataKey, DType
from kornia.core import Tensor
@@ -202,9 +202,9 @@ class RandomMixUpV2(MixAugmentationBaseV2):
) -> Tensor:
out_labels = torch.stack(
[
- input.to(device=input.device, dtype=params["dtype"]),
- input.to(device=input.device, dtype=params["dtype"]),
- torch.zeros((len(input),), device=input.device, dtype=params["dtype"]),
+ input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
+ input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
+ torch.zeros((len(input),), device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
],
dim=-1,
)
@@ -217,9 +217,9 @@ class RandomMixUpV2(MixAugmentationBaseV2):
out_labels = torch.stack(
[
- input.to(device=input.device, dtype=params["dtype"]),
- labels_permute.to(device=input.device, dtype=params["dtype"]),
- params["mixup_lambdas"].to(device=input.device, dtype=params["dtype"]),
+ input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
+ labels_permute.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
+ params["mixup_lambdas"].to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
],
dim=-1,
)
diff --git a/kornia/constants.py b/kornia/constants.py
index 3797db792..3b15b7428 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -2,8 +2,9 @@ from enum import Enum, EnumMeta
from typing import TypeVar, Union, cast
import torch
+from torch import Tensor
-__all__ = ['pi', 'Resample', 'BorderType', 'SamplePadding']
+__all__ = ['pi', 'DType', 'Resample', 'BorderType', 'SamplePadding']
pi = torch.tensor(3.14159265358979323846)
T = TypeVar('T', bound='ConstantBase')
@@ -53,7 +54,43 @@ class SamplePadding(ConstantBase, Enum, metaclass=EnumMetaFlags):
REFLECTION = 2
-# TODO: (low-priority) add INPUT3D, MASK3D, BBOX3D, etc.
+class DType(ConstantBase, Enum, metaclass=EnumMetaFlags):
+ INT64 = 0
+ FLOAT16 = 1
+ FLOAT32 = 2
+ FLOAT64 = 3
+
+ @classmethod
+ def get(cls, value: Union[str, int, torch.dtype, Tensor, T]) -> T: # type: ignore
+ if type(value) is torch.dtype:
+ value = str(value).upper() # Convert to str
+ if type(value) is Tensor:
+ value = value.item() # Convert to int
+ if type(value) is str:
+ if value.upper().startswith("TORCH."):
+ return cls[value.upper()[6:]] # type: ignore
+ return cls[value.upper()] # type: ignore
+ if type(value) is int:
+ return cls(value) # type: ignore
+ if type(value) is cls:
+ return value # type: ignore
+ raise TypeError(f"Invalid identifier {value}.")
+
+ @classmethod
+ def to_torch(cls, value: Union[str, int, T]) -> T: # type: ignore
+ data = cls.get(value=value)
+ if data == DType.INT64:
+ return torch.long
+ if data == DType.FLOAT16:
+ return torch.float16
+ if data == DType.FLOAT32:
+ return torch.float32
+ if data == DType.FLOAT64:
+ return torch.float64
+ raise ValueError()
+
+
+# TODO: (low-priority) add INPUT3D, MASK3D, BBOX3D, LAFs etc.
class DataKey(ConstantBase, Enum, metaclass=EnumMetaFlags):
INPUT = 0
MASK = 1