Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Nick/ruff bugbear (#3076)

Nick52cee42a15f4
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 97b55a4cc..0c5b2a3a8 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -211,7 +211,7 @@ def main():
mix_augmentations_list = {"RandomMixUpV2": ((), 2, 20), "RandomCutMixV2": ((), 2, 2019)}
# ITERATE OVER THE TRANSFORMS
- for aug_name, (args, num_samples, seed) in mix_augmentations_list.items():
+ for aug_name, (args, _, seed) in mix_augmentations_list.items():
img_in = torch.cat([img1, img2])
# dynamically create the class instance
cls = getattr(mod, aug_name)
@@ -328,7 +328,7 @@ def main():
"ApplyColorMap": ((K.color.ColorMap("winter", 256),), 1),
}
# ITERATE OVER THE TRANSFORMS
- for fn_name, (args, num_samples) in color_transforms_list.items():
+ for fn_name, (args, _) in color_transforms_list.items():
# import function and apply
fn = getattr(mod, fn_name)
if fn_name == "grayscale_to_rgb":
@@ -528,7 +528,7 @@ def main():
"in_range": (((0.314, 0.2, 0.2), (0.47, 1.0, 1.0), True), 1),
}
# ITERATE OVER THE TRANSFORMS
- for fn_name, (args, num_samples) in transforms.items():
+ for fn_name, (args, _) in transforms.items():
img_hsv = K.color.rgb_to_hsv(img1)
h, s, v = torch.split(img_hsv, split_size_or_sections=1, dim=1)
h = h / (2 * torch.pi)
diff --git a/kornia/augmentation/_2d/intensity/invert.py b/kornia/augmentation/_2d/intensity/invert.py
index 72f27e34b..8b83af89d 100644
--- a/kornia/augmentation/_2d/intensity/invert.py
+++ b/kornia/augmentation/_2d/intensity/invert.py
@@ -42,7 +42,7 @@ class RandomInvert(IntensityAugmentationBase2D):
def __init__(
self,
- max_val: Union[float, Tensor] = torch.tensor(1.0),
+ max_val: Union[float, Tensor] = 1.0,
same_on_batch: bool = False,
p: float = 0.5,
keepdim: bool = False,
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 0d2dbd6fb..66a565150 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -38,10 +38,12 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
p_batch: float,
same_on_batch: bool = False,
keepdim: bool = False,
- data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
) -> None:
super().__init__(p, p_batch=p_batch, same_on_batch=same_on_batch, keepdim=keepdim)
- self.data_keys = [DataKey.get(inp) for inp in data_keys]
+ self.data_keys = [DataKey.INPUT]
+ if data_keys is not None:
+ self.data_keys = [DataKey.get(inp) for inp in data_keys]
def transform_tensor(self, input: Tensor, *, shape: Optional[Tensor] = None, match_channel: bool = True) -> Tensor:
"""Convert any incoming (H, W), (C, H, W) and (B, C, H, W) into (B, C, H, W)."""
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index b8ce79ee8..037ca1fe6 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -75,7 +75,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
) -> None:
super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim, data_keys=data_keys)
self._param_generator: rg.CutmixGenerator = rg.CutmixGenerator(cut_size, beta, num_mix, p=p)
diff --git a/kornia/augmentation/_2d/mix/jigsaw.py b/kornia/augmentation/_2d/mix/jigsaw.py
index bd994a3e6..ba0b23929 100644
--- a/kornia/augmentation/_2d/mix/jigsaw.py
+++ b/kornia/augmentation/_2d/mix/jigsaw.py
@@ -42,7 +42,7 @@ class RandomJigsaw(MixAugmentationBaseV2):
def __init__(
self,
grid: Tuple[int, int] = (4, 4),
- data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
p: float = 0.5,
same_on_batch: bool = False,
keepdim: bool = False,
diff --git a/kornia/augmentation/_2d/mix/mixup.py b/kornia/augmentation/_2d/mix/mixup.py
index e8df4c851..857f01d14 100644
--- a/kornia/augmentation/_2d/mix/mixup.py
+++ b/kornia/augmentation/_2d/mix/mixup.py
@@ -81,7 +81,7 @@ class RandomMixUpV2(MixAugmentationBaseV2):
same_on_batch: bool = False,
p: float = 1.0,
keepdim: bool = False,
- data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
) -> None:
super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim, data_keys=data_keys)
self._param_generator = rg.MixupGenerator(lambda_val, p=p)
diff --git a/kornia/augmentation/_2d/mix/mosaic.py b/kornia/augmentation/_2d/mix/mosaic.py
index 2a5537dec..822b9372d 100644
--- a/kornia/augmentation/_2d/mix/mosaic.py
+++ b/kornia/augmentation/_2d/mix/mosaic.py
@@ -66,7 +66,7 @@ class RandomMosaic(MixAugmentationBaseV2):
mosaic_grid: Tuple[int, int] = (2, 2),
start_ratio_range: Tuple[float, float] = (0.3, 0.7),
min_bbox_size: float = 0.0,
- data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
+ data_keys: Optional[List[Union[str, int, DataKey]]] = None,
p: float = 0.7,
keepdim: bool = False,
padding_mode: str = "constant",
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index 86ab1123e..b7cc90057 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -47,7 +47,7 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
input: Tensor,
params: Optional[List[ParamItem]] = None,
recompute: bool = False,
- extra_args: Dict[str, Any] = {},
+ extra_args: Optional[Dict[str, Any]] = None,
) -> Optional[Tensor]:
"""Compute the transformation matrix according to the provided parameters.
@@ -91,14 +91,16 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
params.append(param)
return params
- def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform_inputs(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
return input
def forward(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
self.clear_state()
diff --git a/kornia/augmentation/auto/operations/policy.py b/kornia/augmentation/auto/operations/policy.py
index 9d9c9bb4b..52866869c 100644
--- a/kornia/augmentation/auto/operations/policy.py
+++ b/kornia/augmentation/auto/operations/policy.py
@@ -48,7 +48,7 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
input: Tensor,
params: Optional[List[ParamItem]] = None,
recompute: bool = False,
- extra_args: Dict[str, Any] = {},
+ extra_args: Optional[Dict[str, Any]] = None,
) -> Tensor:
"""Compute the transformation matrix according to the provided parameters.
@@ -107,7 +107,9 @@ class PolicySequential(TransformMatrixMinIn, ImageSequentialBase):
params.append(param)
return params
- def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform_inputs(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index a9cad9192..d17ae7744 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -208,15 +208,13 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
def __init__(
self,
*args: Union[_AugmentationBase, ImageSequential],
- data_keys: Optional[Union[List[str], List[int], List[DataKey]]] = [DataKey.INPUT],
+ data_keys: Optional[Union[Sequence[str], Sequence[int], Sequence[DataKey]]] = (DataKey.INPUT,),
same_on_batch: Optional[bool] = None,
keepdim: Optional[bool] = None,
random_apply: Union[int, bool, Tuple[int, int]] = False,
random_apply_weights: Optional[List[float]] = None,
transformation_matrix_mode: str = "silent",
- extra_args: Dict[DataKey, Dict[str, Any]] = {
- DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}
- },
+ extra_args: Optional[Dict[DataKey, Dict[str, Any]]] = None,
) -> None:
self._transform_matrix: Optional[Tensor]
self._transform_matrices: List[Optional[Tensor]] = []
@@ -256,14 +254,16 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
self.contains_3d_augmentation: bool = False
for arg in args:
if isinstance(arg, PatchSequential) and not arg.is_intensity_only():
- warnings.warn("Geometric transformation detected in PatchSeqeuntial, which would break bbox, mask.")
+ warnings.warn(
+ "Geometric transformation detected in PatchSeqeuntial, which would break bbox, mask.", stacklevel=1
+ )
if isinstance(arg, VideoSequential):
self.contains_video_sequential = True
# NOTE: only for images are supported for 3D.
if isinstance(arg, AugmentationBase3D):
self.contains_3d_augmentation = True
self._transform_matrix = None
- self.extra_args = extra_args
+ self.extra_args = extra_args or {DataKey.MASK: {"resample": Resample.NEAREST, "align_corners": None}}
def clear_state(self) -> None:
self._reset_transform_matrix_state()
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index da305179a..896f888c5 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -173,7 +173,7 @@ class ImageSequentialBase(SequentialBase):
input: Tensor,
params: Optional[List[ParamItem]] = None,
recompute: bool = False,
- extra_args: Dict[str, Any] = {},
+ extra_args: Optional[Dict[str, Any]] = None,
) -> Optional[Tensor]:
"""Compute the transformation matrix according to the provided parameters.
@@ -192,41 +192,53 @@ class ImageSequentialBase(SequentialBase):
"""Get module sequence by input params."""
raise NotImplementedError
- def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform_inputs(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
for param in params:
module = self.get_submodule(param.name)
input = InputSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
return input
- def inverse_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ def inverse_inputs(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
+ for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = InputSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
- def transform_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform_masks(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
for param in params:
module = self.get_submodule(param.name)
input = MaskSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
return input
- def inverse_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ def inverse_masks(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
+ for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = MaskSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
- def transform_boxes(self, input: Boxes, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Boxes:
+ def transform_boxes(
+ self, input: Boxes, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Boxes:
for param in params:
module = self.get_submodule(param.name)
input = BoxSequentialOps.transform(input, module=module, param=param, extra_args=extra_args)
return input
- def inverse_boxes(self, input: Boxes, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Boxes:
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ def inverse_boxes(
+ self, input: Boxes, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Boxes:
+ for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = BoxSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
def transform_keypoints(
- self, input: Keypoints, params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Keypoints, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
for param in params:
module = self.get_submodule(param.name)
@@ -234,14 +246,14 @@ class ImageSequentialBase(SequentialBase):
return input
def inverse_keypoints(
- self, input: Keypoints, params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Keypoints, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
+ for (_, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):
input = KeypointSequentialOps.inverse(input, module=module, param=param, extra_args=extra_args)
return input
def inverse(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
"""Inverse transformation.
@@ -261,7 +273,7 @@ class ImageSequentialBase(SequentialBase):
return input
def forward(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
self.clear_state()
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index c67666942..d1bc87797 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -237,7 +237,7 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
input: Tensor,
params: Optional[List[ParamItem]] = None,
recompute: bool = False,
- extra_args: Dict[str, Any] = {},
+ extra_args: Optional[Dict[str, Any]] = None,
) -> Optional[Tensor]:
"""Compute the transformation matrix according to the provided parameters.
@@ -249,6 +249,8 @@ class ImageSequential(ImageSequentialBase, ImageModuleForSequentialMixIn):
"""
if params is None:
raise NotImplementedError("requires params to be provided.")
+ if extra_args is None:
+ extra_args = {}
named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
# Define as 1 for broadcasting
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 602bf1cf9..5fd71ddb0 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -42,7 +42,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
@classmethod
@abstractmethod
- def transform(cls, input: T, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> T:
+ def transform(cls, input: T, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None) -> T:
"""Apply a transformation with respect to the parameters.
Args:
@@ -55,7 +55,7 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
@classmethod
@abstractmethod
- def inverse(cls, input: T, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> T:
+ def inverse(cls, input: T, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None) -> T:
"""Inverse a transformation with respect to the parameters.
Args:
@@ -181,7 +181,11 @@ def get_geometric_only_param(module: "K.container.ImageSequentialBase", param: L
class InputSequentialOps(SequentialOpsInterface[Tensor]):
@classmethod
- def transform(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform(
+ cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
+ if extra_args is None:
+ extra_args = {}
if isinstance(module, (_AugmentationBase, K.MixAugmentationBaseV2)):
input = module(input, params=cls.get_instance_module_param(param), data_keys=[DataKey.INPUT], **extra_args)
elif isinstance(module, (K.container.ImageSequentialBase,)):
@@ -195,7 +199,11 @@ class InputSequentialOps(SequentialOpsInterface[Tensor]):
return input
@classmethod
- def inverse(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ def inverse(
+ cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
+ if extra_args is None:
+ extra_args = {}
if isinstance(module, K.GeometricAugmentationBase2D):
input = module.inverse(input, params=cls.get_instance_module_param(param), **extra_args)
elif isinstance(module, (K.GeometricAugmentationBase3D,)):
@@ -215,7 +223,9 @@ class ClassSequentialOps(SequentialOpsInterface[Tensor]):
"""Apply and inverse transformations for class labels if needed."""
@classmethod
- def transform(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform(
+ cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
if isinstance(module, K.MixAugmentationBaseV2):
raise NotImplementedError(
"The support for class labels for mix augmentations that change the class label is not yet supported."
@@ -223,7 +233,9 @@ class ClassSequentialOps(SequentialOpsInterface[Tensor]):
return input
@classmethod
- def inverse(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ def inverse(
+ cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
return input
@@ -231,7 +243,9 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
"""Apply and inverse transformations for mask tensors."""
@classmethod
- def transform(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform(
+ cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
"""Apply a transformation with respect to the parameters.
Args:
@@ -240,6 +254,8 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
to apply transformations.
param: the corresponding parameters to the module.
"""
+ if extra_args is None:
+ extra_args = {}
if isinstance(module, (K.GeometricAugmentationBase2D,)):
input = module.transform_masks(
@@ -276,7 +292,7 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
@classmethod
def transform_list(
- cls, input: List[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
+ cls, input: List[Tensor], module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> List[Tensor]:
"""Apply a transformation with respect to the parameters.
@@ -286,6 +302,8 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
to apply transformations.
param: the corresponding parameters to the module.
"""
+ if extra_args is None:
+ extra_args = {}
if isinstance(module, (K.GeometricAugmentationBase2D,)):
tfm_input = []
params = cls.get_instance_module_param(param)
@@ -337,7 +355,9 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
return input
@classmethod
- def inverse(cls, input: Tensor, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Tensor:
+ def inverse(
+ cls, input: Tensor, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
"""Inverse a transformation with respect to the parameters.
Args:
@@ -346,6 +366,8 @@ class MaskSequentialOps(SequentialOpsInterface[Tensor]):
to apply transformations.
param: the corresponding parameters to the module.
"""
+ if extra_args is None:
+ extra_args = {}
if isinstance(module, (K.GeometricAugmentationBase2D,)):
if module.transform_matrix is None:
@@ -380,7 +402,9 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
"""
@classmethod
- def transform(cls, input: Boxes, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Boxes:
+ def transform(
+ cls, input: Boxes, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Boxes:
"""Apply a transformation with respect to the parameters.
Args:
@@ -389,6 +413,8 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
to apply transformations.
param: the corresponding parameters to the module.
"""
+ if extra_args is None:
+ extra_args = {}
_input = input.clone()
if isinstance(module, (K.GeometricAugmentationBase2D,)):
@@ -421,7 +447,9 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
return _input
@classmethod
- def inverse(cls, input: Boxes, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Boxes:
+ def inverse(
+ cls, input: Boxes, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Boxes:
"""Inverse a transformation with respect to the parameters.
Args:
@@ -430,6 +458,8 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
to apply transformations.
param: the corresponding parameters to the module.
"""
+ if extra_args is None:
+ extra_args = {}
_input = input.clone()
if isinstance(module, (K.GeometricAugmentationBase2D,)):
@@ -468,7 +498,7 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
@classmethod
def transform(
- cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
+ cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
"""Apply a transformation with respect to the parameters.
@@ -478,6 +508,8 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
to apply transformations.
param: the corresponding parameters to the module.
"""
+ if extra_args is None:
+ extra_args = {}
_input = input.clone()
if isinstance(module, (K.GeometricAugmentationBase2D,)):
@@ -511,7 +543,9 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
return _input
@classmethod
- def inverse(cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}) -> Keypoints:
+ def inverse(
+ cls, input: Keypoints, module: Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
+ ) -> Keypoints:
"""Inverse a transformation with respect to the parameters.
Args:
@@ -520,6 +554,8 @@ class KeypointSequentialOps(SequentialOpsInterface[Keypoints]):
to apply transformations.
param: the corresponding parameters to the module.
"""
+ if extra_args is None:
+ extra_args = {}
_input = input.clone()
if isinstance(module, (K.GeometricAugmentationBase2D,)):
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index e7d28aa47..7eae3536a 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -311,7 +311,7 @@ class PatchSequential(ImageSequential):
return input.reshape(in_shape)
def transform_inputs( # type: ignore[override]
- self, input: Tensor, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
pad = self.compute_padding(input, self.padding)
input = self.extract_patches(input, self.grid_size, pad)
@@ -321,7 +321,7 @@ class PatchSequential(ImageSequential):
return input
def inverse_inputs( # type: ignore[override]
- self, input: Tensor, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
if self.is_intensity_only():
return input
@@ -329,7 +329,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
def transform_masks( # type: ignore[override]
- self, input: Tensor, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
if self.is_intensity_only():
return input
@@ -337,7 +337,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")
def inverse_masks( # type: ignore[override]
- self, input: Tensor, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
if self.is_intensity_only():
return input
@@ -345,7 +345,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
def transform_boxes( # type: ignore[override]
- self, input: Boxes, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Boxes, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Boxes:
if self.is_intensity_only():
return input
@@ -353,7 +353,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")
def inverse_boxes( # type: ignore[override]
- self, input: Boxes, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Boxes, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Boxes:
if self.is_intensity_only():
return input
@@ -361,7 +361,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
def transform_keypoints( # type: ignore[override]
- self, input: Keypoints, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Keypoints, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
if self.is_intensity_only():
return input
@@ -369,7 +369,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential for keypoints cannot be used with geometric transformations.")
def inverse_keypoints( # type: ignore[override]
- self, input: Keypoints, params: List[PatchParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Keypoints, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
if self.is_intensity_only():
return input
@@ -377,7 +377,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
def inverse( # type: ignore[override]
- self, input: Tensor, params: Optional[List[PatchParamItem]] = None, extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: Optional[List[PatchParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
"""Inverse transformation.
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 372f26b83..3003121cc 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -200,7 +200,9 @@ class VideoSequential(ImageSequential):
params.append(param)
return params
- def transform_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform_inputs(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -209,7 +211,9 @@ class VideoSequential(ImageSequential):
input = self._input_shape_convert_back(input, frame_num)
return input
- def inverse_inputs(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ def inverse_inputs(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -218,7 +222,9 @@ class VideoSequential(ImageSequential):
input = self._input_shape_convert_back(input, frame_num)
return input
- def transform_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ def transform_masks(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -227,7 +233,9 @@ class VideoSequential(ImageSequential):
input = self._input_shape_convert_back(input, frame_num)
return input
- def inverse_masks(self, input: Tensor, params: List[ParamItem], extra_args: Dict[str, Any] = {}) -> Tensor:
+ def inverse_masks(
+ self, input: Tensor, params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
+ ) -> Tensor:
frame_num: int = input.size(self._temporal_channel)
input = self._input_shape_convert_in(input, frame_num)
@@ -237,7 +245,7 @@ class VideoSequential(ImageSequential):
return input
def transform_boxes( # type: ignore[override]
- self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Union[Tensor, Boxes]:
"""Transform bounding boxes.
@@ -255,7 +263,7 @@ class VideoSequential(ImageSequential):
return input
def inverse_boxes( # type: ignore[override]
- self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Union[Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Union[Tensor, Boxes]:
"""Transform bounding boxes.
@@ -273,7 +281,7 @@ class VideoSequential(ImageSequential):
return input
def transform_keypoints( # type: ignore[override]
- self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Union[Tensor, Keypoints]:
"""Transform bounding boxes.
@@ -291,7 +299,7 @@ class VideoSequential(ImageSequential):
return input
def inverse_keypoints( # type: ignore[override]
- self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Dict[str, Any] = {}
+ self, input: Union[Tensor, Keypoints], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Union[Tensor, Keypoints]:
"""Transform bounding boxes.
@@ -309,7 +317,7 @@ class VideoSequential(ImageSequential):
return input
def inverse(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
"""Inverse transformation.
@@ -325,7 +333,7 @@ class VideoSequential(ImageSequential):
return self.inverse_inputs(input, params, extra_args=extra_args)
def forward(
- self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Optional[Dict[str, Any]] = None
) -> Tensor:
"""Define the video computation performed."""
if len(input.shape) != 5:
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 3b65c22cf..ab392f1b7 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -252,7 +252,7 @@ class ResizedCropGenerator(CropGenerator):
def center_crop_generator(
- batch_size: int, height: int, width: int, size: Tuple[int, int], device: Device = torch.device("cpu")
+ batch_size: int, height: int, width: int, size: Tuple[int, int], device: Optional[Device] = None
) -> Dict[str, Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
@@ -271,6 +271,8 @@ def center_crop_generator(
Note:
No random number will be generated.
"""
+ if device is None:
+ device = torch.device("cpu")
_common_param_check(batch_size)
if not isinstance(size, (tuple, list)) and len(size) == 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.py
index a0277ba89..fd285f338 100644
--- a/kornia/augmentation/random_generator/_2d/probability.py
+++ b/kornia/augmentation/random_generator/_2d/probability.py
@@ -1,4 +1,4 @@
-from typing import Dict, Tuple
+from typing import Dict, Optional, Tuple
import torch
from torch.distributions import Bernoulli
@@ -48,7 +48,7 @@ def random_prob_generator(
batch_size: int,
p: float = 0.5,
same_on_batch: bool = False,
- device: torch.device = torch.device("cpu"),
+ device: Optional[torch.device] = None,
dtype: torch.dtype = torch.float32,
) -> Tensor:
r"""Generate random probabilities for a batch of inputs.
@@ -67,6 +67,8 @@ def random_prob_generator(
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
+ if device is None:
+ device = torch.device("cpu")
_common_param_check(batch_size, same_on_batch)
if not isinstance(p, (int, float)) or p > 1 or p < 0:
raise TypeError(f"The probability should be a float number within [0, 1]. Got {type(p)}.")
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 5e493a65b..5129382b5 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -142,7 +142,7 @@ def center_crop_generator3d(
height: int,
width: int,
size: Tuple[int, int, int],
- device: Device = torch.device("cpu"),
+ device: Optional[Device] = None,
) -> Dict[str, Tensor]:
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
@@ -162,6 +162,8 @@ def center_crop_generator3d(
Note:
No random number will be generated.
"""
+ if device is None:
+ device = torch.device("cpu")
if not isinstance(size, (tuple, list)) and len(size) == 3:
raise ValueError(f"Input size must be a tuple/list of length 3. Got {size}")
if not (
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index d9ea16c5b..ceecee6be 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -32,7 +32,7 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
def set_rng_device_and_dtype(
self,
- device: torch.device = torch.device("cpu"),
+ device: Optional[torch.device] = None,
dtype: torch.dtype = torch.float32,
) -> None:
"""Change the random generation device and dtype.
@@ -40,6 +40,8 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
+ if device is None:
+ device = torch.device("cpu")
if self.device != device or self.dtype != dtype:
self.make_samplers(device, dtype)
self.device = device
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index ec32af77a..d453b310f 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -19,10 +19,14 @@ def _range_bound(
center: Optional[float] = 0.0,
bounds: Optional[Tuple[float, float]] = (0, float("inf")),
check: Optional[str] = "joint",
- device: torch.device = torch.device("cpu"),
- dtype: torch.dtype = torch.get_default_dtype(),
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
) -> Tensor:
r"""Check inputs and compute the corresponding factor bounds."""
+ if device is None:
+ device = torch.device("cpu")
+ if dtype is None:
+ dtype = torch.get_default_dtype()
if not isinstance(factor, (Tensor)):
factor = tensor(factor, device=device, dtype=dtype)
factor_bound: Tensor
diff --git a/kornia/config.py b/kornia/config.py
index 2f171399d..60052c7f0 100644
--- a/kornia/config.py
+++ b/kornia/config.py
@@ -33,7 +33,9 @@ class LazyLoaderConfig:
try:
self._installation_mode = InstallationMode(value.upper())
except ValueError:
- raise ValueError(f"{value} is not a valid InstallationMode. Choose from: {list(InstallationMode)}")
+ raise ValueError(
+ f"{value} is not a valid InstallationMode. Choose from: {list(InstallationMode)}"
+ ) from None
elif isinstance(value, InstallationMode):
self._installation_mode = value
else:
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 21565f52d..1f7760dea 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -351,7 +351,8 @@ def combine_tensor_patches(
"This means we probably cannot correctly recombine patches. By enabling `allow_auto_unpadding`, "
"the input will be unpadded to fit the window and stride.\n"
"If the patches have been obtained through `extract_tensor_patches` with the correct padding or "
- "the argument `allow_auto_padding`, this will result in a correct reconstruction."
+ "the argument `allow_auto_padding`, this will result in a correct reconstruction.",
+ stacklevel=1,
)
else:
unpadding = compute_padding(original_size=original_size, window_size=window_size, stride=stride)
@@ -463,7 +464,8 @@ def extract_tensor_patches(
f"The window will not fit into the image. \nWindow size: {window_size}\nStride: {stride}\n"
f"Image size: {original_size}\n"
"This means that the final incomplete patches will be dropped. By enabling `allow_auto_padding`, "
- "the input will be padded to fit the window and stride."
+ "the input will be padded to fit the window and stride.",
+ stacklevel=1,
)
else:
padding = compute_padding(original_size=original_size, window_size=window_size, stride=stride)
diff --git a/kornia/contrib/models/base.py b/kornia/contrib/models/base.py
index 366466340..39f85af97 100644
--- a/kornia/contrib/models/base.py
+++ b/kornia/contrib/models/base.py
@@ -47,7 +47,7 @@ class ModelBase(ABC, Module, Generic[ModelConfig]):
dynamic: bool = False,
backend: str = "inductor",
mode: Optional[str] = None,
- options: dict[Any, Any] = {},
+ options: Optional[dict[Any, Any]] = None,
disable: bool = False,
) -> ModelBase[ModelConfig]:
compiled = torch.compile(
diff --git a/kornia/contrib/models/efficient_vit/model.py b/kornia/contrib/models/efficient_vit/model.py
index 3e3720b8e..09bdded1a 100644
--- a/kornia/contrib/models/efficient_vit/model.py
+++ b/kornia/contrib/models/efficient_vit/model.py
@@ -63,7 +63,7 @@ class EfficientViT(ModelBase[EfficientViTConfig]):
model_file = torch.hub.load_state_dict_from_url(config.checkpoint, map_location="cpu")
model_file = model_file["state_dict"] if "state_dict" in model_file else model_file
except RuntimeError:
- raise RuntimeError(f"Unable to load the model from {config.checkpoint}.")
+ raise RuntimeError(f"Unable to load the model from {config.checkpoint}.") from None
file_name = config.checkpoint.split("/")[-1]
model_type = file_name.split("-")[0]
diff --git a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
index 3c731238b..61b179c10 100644
--- a/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/contrib/models/rt_detr/architecture/rtdetr_head.py
@@ -364,7 +364,7 @@ class RTDETRHead(Module):
spatial_shapes: list[tuple[int, int]] = []
level_start_index: list[int] = [0]
- for i, feat in enumerate(proj_feats):
+ for _, feat in enumerate(proj_feats):
_, _, h, w = feat.shape
# [b, c, h, w] -> [b, h*w, c]
feat_flatten_list.append(feat.flatten(2).permute(0, 2, 1))
diff --git a/kornia/contrib/models/sam/model.py b/kornia/contrib/models/sam/model.py
index c528baf36..1aaaf3b00 100644
--- a/kornia/contrib/models/sam/model.py
+++ b/kornia/contrib/models/sam/model.py
@@ -205,7 +205,7 @@ class Sam(ModelBase[SamConfig]):
SamModelType.mobile_sam: "https://github.com/ChaoningZhang/MobileSAM/raw/a509aac54fdd7af59f843135f2f7cee307283c88/weights/mobile_sam.pt",
}[model_type]
else:
- warnings.warn("checkpoint is not None. pretrained=True is ignored")
+ warnings.warn("checkpoint is not None. pretrained=True is ignored", stacklevel=1)
if checkpoint:
model.load_checkpoint(checkpoint)
diff --git a/kornia/contrib/models/tiny_vit.py b/kornia/contrib/models/tiny_vit.py
index 6c493ed9b..ee06aa093 100644
--- a/kornia/contrib/models/tiny_vit.py
+++ b/kornia/contrib/models/tiny_vit.py
@@ -5,7 +5,7 @@ from __future__ import annotations
import itertools
import warnings
-from typing import Any, Optional
+from typing import Any, Optional, Sequence
import torch
import torch.nn.functional as F
@@ -332,10 +332,10 @@ class TinyViT(Module):
img_size: int = 224,
in_chans: int = 3,
num_classes: int = 1000,
- embed_dims: list[int] = [96, 192, 384, 768],
- depths: list[int] = [2, 2, 6, 2],
- num_heads: list[int] = [3, 6, 12, 24],
- window_sizes: list[int] = [7, 7, 14, 7],
+ embed_dims: Sequence[int] = (96, 192, 384, 768),
+ depths: Sequence[int] = (2, 2, 6, 2),
+ num_heads: Sequence[int] = (3, 6, 12, 24),
+ window_sizes: Sequence[int] = (7, 7, 14, 7),
mlp_ratio: float = 4.0,
drop_rate: float = 0.0,
drop_path_rate: float = 0.0,
@@ -475,7 +475,7 @@ def _load_pretrained(model: TinyViT, url: str) -> TinyViT:
if state_dict["head.weight"].shape[0] != model.head.out_features:
msg = "Number of classes does not match pre-trained checkpoint's. Resetting classification head to zeros"
- warnings.warn(msg)
+ warnings.warn(msg, stacklevel=1)
state_dict["head.weight"] = torch.zeros_like(model.head.weight)
state_dict["head.bias"] = torch.zeros_like(model.head.bias)
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index e43d97394..3ded2bdfa 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -37,6 +37,7 @@ class BoundingBox(BoundingBoxBase):
"BoundingBox is deprecated and will be removed in v0.8.0. "
"Use kornia.models.detection.BoundingBox instead.",
DeprecationWarning,
+ stacklevel=1,
)
@@ -45,6 +46,7 @@ def results_from_detections(*args: Any, **kwargs: Any) -> list[ObjectDetectorRes
"results_from_detections is deprecated and will be removed in v0.8.0. "
"Use kornia.models.detection.results_from_detections instead.",
DeprecationWarning,
+ stacklevel=1,
)
return results_from_detections_base(*args, **kwargs)
@@ -56,6 +58,7 @@ class ResizePreProcessor(ResizePreProcessorBase):
"ResizePreProcessor is deprecated and will be removed in v0.8.0. "
"Use kornia.models.utils.ResizePreProcessor instead.",
DeprecationWarning,
+ stacklevel=1,
)
@@ -66,6 +69,7 @@ class ObjectDetector(ObjectDetectorBase):
"ObjectDetector is deprecated and will be removed in v0.8.0. "
"Use kornia.models.detection.ObjectDetector instead.",
DeprecationWarning,
+ stacklevel=1,
)
@@ -76,4 +80,5 @@ class ObjectDetectorResult(ObjectDetectorResultBase):
"ObjectDetectorResult is deprecated and will be removed in v0.8.0. "
"Use kornia.models.detection.ObjectDetectorResult instead.",
DeprecationWarning,
+ stacklevel=1,
)
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 11fb0eedf..25d7ece0b 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -52,11 +52,14 @@ class VisualPrompter:
def __init__(
self,
- config: SamConfig = SamConfig(model_type="vit_h", pretrained=True),
+ config: Optional[SamConfig] = None,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> None:
super().__init__()
+ if config is None:
+ config = SamConfig(model_type="vit_h", pretrained=True)
+
if isinstance(config, SamConfig):
self.model = Sam.from_config(config)
transforms = (LongestMaxSize(self.model.image_encoder.img_size, p=1.0),)
@@ -163,9 +166,11 @@ class VisualPrompter:
return masks
def _transform_prompts(
- self, *prompts: Tensor | Boxes | Keypoints, data_keys: list[str] = []
+ self, *prompts: Tensor | Boxes | Keypoints, data_keys: Optional[list[str]] = None
) -> dict[str, Tensor | Boxes | Keypoints]:
transformed_prompts = self.transforms(*prompts, data_keys=data_keys, params=self._tfs_params)
+ if data_keys is None:
+ data_keys = []
# prevent unpacking tensor when creating the output dict (issue #2627)
if not isinstance(transformed_prompts, (list, tuple)):
@@ -295,7 +300,7 @@ class VisualPrompter:
dynamic: bool = False,
backend: str = "inductor",
mode: Optional[str] = None,
- options: dict[Any, Any] = {},
+ options: Optional[dict[Any, Any]] = None,
disable: bool = False,
) -> None:
"""Applies `torch.compile(...)`/dynamo API into the VisualPrompter API.
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index 4d5498352..9ac1c890e 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -53,7 +53,7 @@ class ONNXExportMixin:
pseudo_shape: Optional[list[int]] = None,
model: Optional[Module] = None,
save: bool = True,
- additional_metadata: list[tuple[str, str]] = [],
+ additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto: # type: ignore
"""Exports the current object to an ONNX model file.
@@ -119,6 +119,8 @@ class ONNXExportMixin:
onnx_buffer.seek(0)
onnx_model = onnx.load(onnx_buffer) # type: ignore
+ if additional_metadata is None:
+ additional_metadata = []
additional_metadata = copy.deepcopy(additional_metadata)
additional_metadata.extend(self.ADDITIONAL_METADATA)
onnx_model = kornia.onnx.utils.add_metadata(onnx_model, additional_metadata)
@@ -343,7 +345,7 @@ class ONNXMixin:
def _add_metadata(
self,
op: onnx.ModelProto, # type:ignore
- additional_metadata: list[tuple[str, str]] = [],
+ additional_metadata: Optional[list[tuple[str, str]]] = None,
) -> onnx.ModelProto: # type:ignore
"""Add metadata to the combined ONNX model.
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 66a056de0..b5eb5f008 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -7,7 +7,7 @@ import torch
from kornia.color import hsv_to_rgb, rgb_to_grayscale, rgb_to_hsv
from kornia.core import ImageModule as Module
-from kornia.core import Parameter, Tensor
+from kornia.core import Parameter, Tensor, tensor
from kornia.core.check import (
KORNIA_CHECK,
KORNIA_CHECK_IS_COLOR_OR_GRAY,
@@ -976,7 +976,7 @@ def equalize3d(input: Tensor) -> Tensor:
return torch.stack(res)
-def invert(image: Tensor, max_val: Tensor = Tensor([1.0])) -> Tensor:
+def invert(image: Tensor, max_val: Optional[Tensor] = None) -> Tensor:
r"""Invert the values of an input image tensor by its maximum value.
.. image:: _static/img/invert.png
@@ -1002,10 +1002,14 @@ def invert(image: Tensor, max_val: Tensor = Tensor([1.0])) -> Tensor:
if not isinstance(image, Tensor):
raise AssertionError(f"Input is not a Tensor. Got: {type(input)}")
- if not isinstance(max_val, Tensor):
- raise AssertionError(f"max_val is not a Tensor. Got: {type(max_val)}")
+ if max_val is None:
+ _max_val = tensor([1.0])
+ else:
+ _max_val = max_val
+ if not isinstance(_max_val, Tensor):
+ raise AssertionError(f"max_val is not a Tensor. Got: {type(_max_val)}")
- return max_val.to(image) - image
+ return _max_val.to(image) - image
class AdjustSaturation(Module):
@@ -1425,8 +1429,10 @@ class Invert(Module):
torch.Size([1, 3, 4, 4])
"""
- def __init__(self, max_val: Tensor = torch.tensor(1.0)) -> None:
+ def __init__(self, max_val: Optional[Tensor] = None) -> None:
super().__init__()
+ if max_val is None:
+ max_val = torch.tensor(1.0)
if not isinstance(max_val, Parameter):
self.register_buffer("max_val", max_val)
else:
diff --git a/kornia/feature/disk/_unets/unet.py b/kornia/feature/disk/_unets/unet.py
index a9af25d4f..01327c60f 100644
--- a/kornia/feature/disk/_unets/unet.py
+++ b/kornia/feature/disk/_unets/unet.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
from torch import nn
from kornia.core import Module, Tensor
@@ -8,14 +10,19 @@ from .blocks import ThinUnetDownBlock, ThinUnetUpBlock
class Unet(Module):
- def __init__(self, in_features: int = 1, up: list[int] = [], down: list[int] = [], size: int = 5) -> None:
+ def __init__(
+ self, in_features: int = 1, up: Optional[list[int]] = None, down: Optional[list[int]] = None, size: int = 5
+ ) -> None:
super().__init__()
-
+ if up is None:
+ up = []
+ self.up = up
+ if down is None:
+ down = []
+ self.down = down
if not len(down) == len(up) + 1:
raise ValueError("`down` must be 1 item longer than `up`")
- self.up = up
- self.down = down
self.in_features = in_features
down_dims = [in_features, *down]
@@ -27,7 +34,7 @@ class Unet(Module):
bot_dims = [down[-1], *up]
hor_dims = down_dims[-2::-1]
self.path_up = nn.ModuleList()
- for i, (d_bot, d_hor, d_out) in enumerate(zip(bot_dims, hor_dims, up)):
+ for _, (d_bot, d_hor, d_out) in enumerate(zip(bot_dims, hor_dims, up)):
up_block = ThinUnetUpBlock(d_bot, d_hor, d_out, size=size)
self.path_up.append(up_block)
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index da05fe1a3..9ab5c4782 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -106,7 +106,7 @@ class DISK(Module):
return features
@classmethod
- def from_pretrained(cls, checkpoint: str = "depth", device: torch.device = torch.device("cpu")) -> DISK:
+ def from_pretrained(cls, checkpoint: str = "depth", device: Optional[torch.device] = None) -> DISK:
r"""Loads a pretrained model.
Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypoints
@@ -129,6 +129,8 @@ class DISK(Module):
if checkpoint not in urls:
raise ValueError(f"Unknown pretrained model: {checkpoint}")
+ if device is None:
+ device = torch.device("cpu")
pretrained_dict = torch.hub.load_state_dict_from_url(urls[checkpoint], map_location=device)
model: DISK = cls().to(device)
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 3ebd26af3..7cdbeb946 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -49,7 +49,7 @@ def get_laf_descriptors(
timg: Tensor = img
if lafs.shape[1] == 0:
- warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty tensor")
+ warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty tensor", stacklevel=1)
return torch.empty(lafs.shape[0], lafs.shape[1], 128, dtype=lafs.dtype, device=lafs.device)
if grayscale_descriptor and img.size(1) == 3:
timg = rgb_to_grayscale(img)
@@ -155,10 +155,14 @@ class SIFTFeature(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: Device = torch.device("cpu"),
- config: Detector_config = get_default_detector_config(),
+ device: Optional[Device] = None,
+ config: Optional[Detector_config] = None,
) -> None:
patch_size: int = 41
+ if device is None:
+ device = torch.device("cpu")
+ if config is None:
+ config = get_default_detector_config()
detector = MultiResolutionDetector(
BlobDoGSingle(1.0, 1.6),
num_features,
@@ -184,8 +188,10 @@ class SIFTFeatureScaleSpace(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: Device = torch.device("cpu"),
+ device: Optional[Device] = None,
) -> None:
+ if device is None:
+ device = torch.device("cpu")
patch_size: int = 41
detector = ScaleSpaceDetector(
num_features,
@@ -210,9 +216,13 @@ class GFTTAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Device = torch.device("cpu"),
- config: Detector_config = get_default_detector_config(),
+ device: Optional[Device] = None,
+ config: Optional[Detector_config] = None,
) -> None:
+ if device is None:
+ device = torch.device("cpu")
+ if config is None:
+ config = get_default_detector_config()
detector = MultiResolutionDetector(
CornerGFTT(),
num_features,
@@ -231,9 +241,13 @@ class HesAffNetHardNet(LocalFeature):
self,
num_features: int = 2048,
upright: bool = False,
- device: Device = torch.device("cpu"),
- config: Detector_config = get_default_detector_config(),
+ device: Optional[Device] = None,
+ config: Optional[Detector_config] = None,
) -> None:
+ if device is None:
+ device = torch.device("cpu")
+ if config is None:
+ config = get_default_detector_config()
detector = MultiResolutionDetector(
BlobHessian(),
num_features,
@@ -252,9 +266,11 @@ class KeyNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Device = torch.device("cpu"),
+ device: Optional[Device] = None,
scale_laf: float = 1.0,
) -> None:
+ if device is None:
+ device = torch.device("cpu")
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
detector = KeyNetDetector(True, num_features=num_features, ori_module=ori_module).to(device)
descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)
@@ -271,9 +287,11 @@ class KeyNetAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: Device = torch.device("cpu"),
+ device: Optional[Device] = None,
scale_laf: float = 1.0,
) -> None:
+ if device is None:
+ device = torch.device("cpu")
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
detector = KeyNetDetector(
True, num_features=num_features, ori_module=ori_module, aff_module=LAFAffNetShapeEstimator(True).eval()
@@ -421,10 +439,12 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
"superpoint",
]
- def __init__(self, feature_name: str = "disk", params: Dict = {}) -> None: # type: ignore
+ def __init__(self, feature_name: str = "disk", params: Optional[Dict] = None) -> None: # type: ignore
feature_name_: str = feature_name.lower()
super().__init__(feature_name_)
self.feature_name = feature_name_
+ if params is None:
+ params = {}
self.params = params
self.matcher = LightGlue(self.feature_name, **params)
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index 7e9348569..483e25deb 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -154,7 +154,7 @@ class KeyNet(Module):
"""
shape_im = x.shape
feats: List[Tensor] = [self.feature_extractor(x)]
- for i in range(1, self.num_levels):
+ for _ in range(1, self.num_levels):
x = pyrdown(x, factor=1.2)
feats_i = self.feature_extractor(x)
feats_i = F.interpolate(feats_i, size=(shape_im[2], shape_im[3]), mode="bilinear")
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 74709d4ac..12a989957 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -2,7 +2,7 @@ import math
import warnings
from pathlib import Path
from types import SimpleNamespace
-from typing import Any, Callable, ClassVar, Dict, List, Optional, Tuple
+from typing import Any, Callable, ClassVar, Dict, List, Optional, Sequence, Tuple
import torch
import torch.nn.functional as F
@@ -459,7 +459,7 @@ class LightGlue(Module):
self.static_lengths = None
def compile(
- self, mode: str = "reduce-overhead", static_lengths: List[int] = [256, 512, 768, 1024, 1280, 1536]
+ self, mode: str = "reduce-overhead", static_lengths: Sequence[int] = (256, 512, 768, 1024, 1280, 1536)
) -> None:
if self.conf.width_confidence != -1:
warnings.warn(
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 473866452..404f9b49e 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -78,7 +78,7 @@ class CoarseMatching(Module):
try:
from .superglue import log_optimal_transport
except ImportError:
- raise ImportError("download superglue.py first!")
+ raise ImportError("download superglue.py first!") from None
self.log_optimal_transport = log_optimal_transport
self.bin_score = nn.Parameter(torch.tensor(config["skh_init_bin_score"], requires_grad=True))
self.skh_iters = config["skh_iters"]
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 4b55d88ab..4e383ca87 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -463,7 +463,7 @@ class DescriptorMatcherWithSteerer(Module):
dist, idx, rot1to2 = dist_new, idx_new, r
elif self.steer_mode == "local":
dm = _cdist(desc1, desc2)
- for r in range(1, self.steerer_order):
+ for _ in range(1, self.steerer_order):
desc1 = self.steerer.steer_descriptions(desc1, normalize=normalize)
dm_new = _cdist(desc1, desc2)
dm = torch.minimum(dm, dm_new)
@@ -487,13 +487,13 @@ class GeometryAwareDescriptorMatcher(Module):
known_modes: ClassVar[List[str]] = ["fginn", "adalam"]
- def __init__(self, match_mode: str = "fginn", params: Dict[str, Tensor] = {}) -> None:
+ def __init__(self, match_mode: str = "fginn", params: Optional[Dict[str, Tensor]] = None) -> None:
super().__init__()
_match_mode: str = match_mode.lower()
if _match_mode not in self.known_modes:
raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}")
self.match_mode = _match_mode
- self.params = params
+ self.params = params or {}
def forward(self, desc1: Tensor, desc2: Tensor, lafs1: Tensor, lafs2: Tensor) -> Tuple[Tensor, Tensor]:
"""
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index c685e8093..e3fcefaa3 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -79,23 +79,33 @@ class ScaleSpaceDetector(Module):
self,
num_features: int = 500,
mr_size: float = 6.0,
- scale_pyr_module: Module = ScalePyramid(3, 1.6, 15),
- resp_module: Module = BlobHessian(),
- nms_module: Module = ConvSoftArgmax3d(
- (3, 3, 3), (1, 1, 1), (1, 1, 1), normalized_coordinates=False, output_value=True
- ),
- ori_module: Module = PassLAF(),
- aff_module: Module = PassLAF(),
+ scale_pyr_module: Optional[Module] = None,
+ resp_module: Optional[Module] = None,
+ nms_module: Optional[Module] = None,
+ ori_module: Optional[Module] = None,
+ aff_module: Optional[Module] = None,
minima_are_also_good: bool = False,
scale_space_response: bool = False,
) -> None:
super().__init__()
self.mr_size = mr_size
self.num_features = num_features
+ if scale_pyr_module is None:
+ scale_pyr_module = ScalePyramid(3, 1.6, 15)
self.scale_pyr = scale_pyr_module
+ if resp_module is None:
+ resp_module = BlobHessian()
self.resp = resp_module
+ if nms_module is None:
+ nms_module = ConvSoftArgmax3d(
+ (3, 3, 3), (1, 1, 1), (1, 1, 1), normalized_coordinates=False, output_value=True
+ )
self.nms = nms_module
+ if ori_module is None:
+ ori_module = PassLAF()
self.ori = ori_module
+ if aff_module is None:
+ aff_module = PassLAF()
self.aff = aff_module
self.minima_are_also_good = minima_are_also_good
# scale_space_response should be True if the response function works on scale space
@@ -265,12 +275,14 @@ class MultiResolutionDetector(Module):
self,
model: Module,
num_features: int = 2048,
- config: Detector_config = get_default_detector_config(),
+ config: Optional[Detector_config] = None,
ori_module: Optional[Module] = None,
aff_module: Optional[Module] = None,
) -> None:
super().__init__()
self.model = model
+ if config is None:
+ config = get_default_detector_config()
# Load extraction configuration
self.num_pyramid_levels = config["pyramid_levels"]
self.num_upscale_levels = config["up_levels"]
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index 326230c8e..1b0ca798b 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -137,9 +137,11 @@ class WunschLineMatcher(Module):
TODO: move it later in kornia.feature.matching
"""
- def __init__(self, config: LineMatcherCfg = LineMatcherCfg()) -> None:
+ def __init__(self, config: Optional[LineMatcherCfg] = None) -> None:
super().__init__()
# Initialize the parameters
+ if config is None:
+ config = LineMatcherCfg()
self.config = config
self.cross_check = self.config.cross_check
self.num_samples = self.config.num_samples
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 80820a2bf..e826fce9d 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -134,8 +134,10 @@ class LineSegmentDetectionModule:
>>> line_map, junctions, _ = module.detect(junctions, heatmap)
"""
- def __init__(self, config: LineDetectorCfg = LineDetectorCfg()) -> None:
+ def __init__(self, config: Optional[LineDetectorCfg] = None) -> None:
# Load LineDetectorCfg
+ if config is None:
+ config = LineDetectorCfg()
self.config = config
# Line detection parameters
diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.py
index 8c49c9199..45480694b 100644
--- a/kornia/geometry/bbox.py
+++ b/kornia/geometry/bbox.py
@@ -475,7 +475,8 @@ def transform_bbox(
"Previous behaviour produces incorrect box coordinates if a flip transformation performed on boxes."
"The previous wrong behaviour has been corrected and will be removed in the future versions."
"If you wish to keep the previous behaviour, please set `restore_coordinates=False`."
- "Otherwise, set `restore_coordinates=True` as an acknowledgement."
+ "Otherwise, set `restore_coordinates=True` as an acknowledgement.",
+ stacklevel=1,
)
# convert boxes to format xyxy
diff --git a/kornia/geometry/homography.py b/kornia/geometry/homography.py
index a97dbea71..55cc331b9 100644
--- a/kornia/geometry/homography.py
+++ b/kornia/geometry/homography.py
@@ -172,7 +172,7 @@ def find_homography_dlt(
try:
_, _, V = _torch_svd_cast(A)
except RuntimeError:
- warnings.warn("SVD did not converge", RuntimeWarning)
+ warnings.warn("SVD did not converge", RuntimeWarning, stacklevel=1)
return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)
H = V[..., -1].view(-1, 3, 3)
elif solver == "lu":
@@ -306,7 +306,7 @@ def find_homography_lines_dlt(ls1: Tensor, ls2: Tensor, weights: Optional[Tensor
try:
_, _, V = _torch_svd_cast(A)
except RuntimeError:
- warnings.warn("SVD did not converge", RuntimeWarning)
+ warnings.warn("SVD did not converge", RuntimeWarning, stacklevel=1)
return torch.empty((points1_norm.size(0), 3, 3), device=device, dtype=dtype)
H = V[..., -1].view(-1, 3, 3)
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 64e101bb7..39bcd5d0c 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -84,12 +84,14 @@ class RANSAC(Module):
else:
raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")
- def sample(self, sample_size: int, pop_size: int, batch_size: int, device: Device = torch.device("cpu")) -> Tensor:
+ def sample(self, sample_size: int, pop_size: int, batch_size: int, device: Optional[Device] = None) -> Tensor:
"""Minimal sampler, but unlike traditional RANSAC we sample in batches to get benefit of the parallel
processing, esp.
on GPU.
"""
+ if device is None:
+ device = torch.device("cpu")
rand = torch.rand(batch_size, pop_size, device=device)
_, out = rand.topk(k=sample_size, dim=1)
return out
@@ -209,7 +211,7 @@ class RANSAC(Module):
# Store far-the-best model and (optionally) do a local optimization
if model_score > best_score_total:
# Local optimization
- for lo_step in range(self.max_lo_iters):
+ for _ in range(self.max_lo_iters):
model_lo = self.polish_model(kp1, kp2, inliers)
if (model_lo is None) or (len(model_lo) == 0):
continue
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 431abee25..833c4fa07 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -3,6 +3,8 @@ r"""Implementation of "differentiable spatial to numerical" (soft-argmax) operat
from __future__ import annotations
+from typing import Optional
+
import torch
from kornia.core import Tensor, concatenate, softmax
@@ -15,7 +17,7 @@ def _validate_batched_image_tensor_input(tensor: Tensor) -> None:
KORNIA_CHECK_SHAPE(tensor, ["B", "C", "H", "W"])
-def spatial_softmax2d(input: Tensor, temperature: Tensor = torch.tensor(1.0)) -> Tensor:
+def spatial_softmax2d(input: Tensor, temperature: Optional[Tensor] = None) -> Tensor:
r"""Apply the Softmax function over features in each image channel.
Note that this function behaves differently to :py:class:`torch.nn.Softmax2d`, which
@@ -41,6 +43,8 @@ def spatial_softmax2d(input: Tensor, temperature: Tensor = torch.tensor(1.0)) ->
_validate_batched_image_tensor_input(input)
batch_size, channels, height, width = input.shape
+ if temperature is None:
+ temperature = torch.tensor(1.0)
temperature = temperature.to(device=input.device, dtype=input.dtype)
x = input.view(batch_size, channels, -1)
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index de0545cd9..d8994b148 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
import torch.nn.functional as F
@@ -14,7 +16,7 @@ from .dsnt import spatial_expectation2d, spatial_softmax2d
from .nms import nms3d
-def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device("cpu")) -> Tensor:
+def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
r"""Helper function, which generates a kernel to with window coordinates, residual to window center.
Args:
@@ -25,13 +27,15 @@ def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.devic
Returns:
conv_kernel [2x1xhxw]
"""
+ if device is None:
+ device = torch.device("cpu")
window_grid2d = create_meshgrid(h, w, False, device=device)
window_grid2d = normalize_pixel_coordinates(window_grid2d, h, w)
conv_kernel = window_grid2d.permute(3, 0, 1, 2)
return conv_kernel
-def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device("cpu")) -> Tensor:
+def _get_center_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 2d
coordinates grid.
@@ -43,6 +47,8 @@ def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device("cp
Returns:
conv_kernel [2x2xhxw].
"""
+ if device is None:
+ device = torch.device("cpu")
center_kernel = zeros(2, 2, h, w, device=device)
# If the size is odd, we have one pixel for center, if even - 2
@@ -62,7 +68,7 @@ def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device("cp
return center_kernel
-def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device("cpu")) -> Tensor:
+def _get_center_kernel3d(d: int, h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 3d
coordinates grid.
@@ -75,6 +81,8 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.de
Returns:
conv_kernel [3x3xdxhxw].
"""
+ if device is None:
+ torch.device("cpu")
center_kernel = zeros(3, 3, d, h, w, device=device)
# If the size is odd, we have one pixel for center, if even - 2
if h % 2 != 0:
@@ -100,7 +108,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.de
return center_kernel
-def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device("cpu")) -> Tensor:
+def _get_window_grid_kernel3d(d: int, h: int, w: int, device: Optional[torch.device] = None) -> Tensor:
r"""Helper function, which generates a kernel to return coordinates, residual to window center.
Args:
@@ -112,6 +120,8 @@ def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = tor
Returns:
conv_kernel [3x1xdxhxw]
"""
+ if device is None:
+ device = torch.device("cpu")
grid2d = create_meshgrid(h, w, True, device=device)
if d > 1:
z = torch.linspace(-1, 1, d, device=device).view(d, 1, 1, 1)
@@ -134,7 +144,7 @@ class ConvSoftArgmax2d(Module):
kernel_size: tuple[int, int] = (3, 3),
stride: tuple[int, int] = (1, 1),
padding: tuple[int, int] = (1, 1),
- temperature: Tensor | float = tensor(1.0),
+ temperature: Tensor | float = 1.0,
normalized_coordinates: bool = True,
eps: float = 1e-8,
output_value: bool = False,
@@ -185,7 +195,7 @@ class ConvSoftArgmax3d(Module):
kernel_size: tuple[int, int, int] = (3, 3, 3),
stride: tuple[int, int, int] = (1, 1, 1),
padding: tuple[int, int, int] = (1, 1, 1),
- temperature: Tensor | float = tensor(1.0),
+ temperature: Tensor | float = 1.0,
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
@@ -233,7 +243,7 @@ def conv_soft_argmax2d(
kernel_size: tuple[int, int] = (3, 3),
stride: tuple[int, int] = (1, 1),
padding: tuple[int, int] = (1, 1),
- temperature: Tensor | float = tensor(1.0),
+ temperature: Tensor | float = 1.0,
normalized_coordinates: bool = True,
eps: float = 1e-8,
output_value: bool = False,
@@ -346,7 +356,7 @@ def conv_soft_argmax3d(
kernel_size: tuple[int, int, int] = (3, 3, 3),
stride: tuple[int, int, int] = (1, 1, 1),
padding: tuple[int, int, int] = (1, 1, 1),
- temperature: Tensor | float = tensor(1.0),
+ temperature: Tensor | float = 1.0,
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
@@ -470,7 +480,7 @@ def conv_soft_argmax3d(
def spatial_soft_argmax2d(
- input: Tensor, temperature: Tensor = tensor(1.0), normalized_coordinates: bool = True
+ input: Tensor, temperature: Optional[Tensor] = None, normalized_coordinates: bool = True
) -> Tensor:
r"""Compute the Spatial Soft-Argmax 2D of a given input heatmap.
@@ -492,6 +502,8 @@ def spatial_soft_argmax2d(
>>> spatial_soft_argmax2d(input, normalized_coordinates=False)
tensor([[[1.0000, 1.0000]]])
"""
+ if temperature is None:
+ temperature = tensor(1.0)
input_soft: Tensor = spatial_softmax2d(input, temperature)
output: Tensor = spatial_expectation2d(input_soft, normalized_coordinates)
return output
@@ -503,8 +515,10 @@ class SpatialSoftArgmax2d(Module):
See :func:`~kornia.geometry.subpix.spatial_soft_argmax2d` for details.
"""
- def __init__(self, temperature: Tensor = tensor(1.0), normalized_coordinates: bool = True) -> None:
+ def __init__(self, temperature: Optional[Tensor] = None, normalized_coordinates: bool = True) -> None:
super().__init__()
+ if temperature is None:
+ temperature = tensor(1.0)
self.temperature: Tensor = temperature
self.normalized_coordinates: bool = normalized_coordinates
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 1e5450f97..14c4c83f9 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -568,7 +568,9 @@ def resize(
input_size = h, w = input.shape[-2:]
if isinstance(size, int):
if torch.onnx.is_in_onnx_export():
- warnings.warn("Please pass the size with a tuple when exporting to ONNX to correct the tracing.")
+ warnings.warn(
+ "Please pass the size with a tuple when exporting to ONNX to correct the tracing.", stacklevel=1
+ )
aspect_ratio = w / h
size = _side_to_image_size(size, aspect_ratio, side)
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 39bacb21c..93465fd01 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -52,7 +52,7 @@ def warp_perspective(
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
- fill_value: Tensor = zeros(3), # needed for jit
+ fill_value: Optional[Tensor] = None, # needed for jit
) -> Tensor:
r"""Apply a perspective transformation to an image.
@@ -104,6 +104,8 @@ def warp_perspective(
# fill padding is only supported for 3 channels because we can't set fill_value default
# to None as this gives jit issues.
+ if fill_value is None:
+ fill_value = zeros(3)
if padding_mode == "fill" and fill_value.shape != torch.Size([3]):
raise ValueError(f"Padding_tensor only supported for 3 channels. Got {fill_value.shape}")
@@ -135,7 +137,7 @@ def warp_affine(
mode: str = "bilinear",
padding_mode: str = "zeros",
align_corners: bool = True,
- fill_value: Tensor = zeros(3), # needed for jit
+ fill_value: Optional[Tensor] = None, # needed for jit
) -> Tensor:
r"""Apply an affine transformation to a tensor.
@@ -198,6 +200,8 @@ def warp_affine(
grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :], [B, C, dsize[0], dsize[1]], align_corners=align_corners)
if padding_mode == "fill":
+ if fill_value is None:
+ fill_value = zeros(3)
return _fill_and_warp(src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)
return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
diff --git a/kornia/losses/ms_ssim.py b/kornia/losses/ms_ssim.py
index 65c6049bc..b9989adbb 100644
--- a/kornia/losses/ms_ssim.py
+++ b/kornia/losses/ms_ssim.py
@@ -1,6 +1,6 @@
from __future__ import annotations
-from typing import Optional
+from typing import Optional, Sequence
import torch
import torch.nn.functional as F
@@ -56,7 +56,7 @@ class MS_SSIMLoss(nn.Module):
def __init__(
self,
- sigmas: list[float] = [0.5, 1.0, 2.0, 4.0, 8.0],
+ sigmas: Sequence[float] = (0.5, 1.0, 2.0, 4.0, 8.0),
data_range: float = 1.0,
K: tuple[float, float] = (0.01, 0.03),
alpha: float = 0.025,
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index a50c33562..f377cca8d 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -15,13 +15,13 @@ from .preprocessor import PreprocessingLoader
class HFONNXComunnityModelLoader:
- f"""Initializes the ONNXComunnityModelLoader for onnx-community repo of Hugging Face.
+ """Initializes the ONNXComunnityModelLoader for onnx-community repo of Hugging Face.
Args:
model_name: The name of the model to load.
model_type: The type of the model to load.
cache_dir: The directory where models are cached locally.
- Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.
+ Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
with_data: Whether to download the model weights such as `model.onnx_data`.
"""
@@ -63,8 +63,10 @@ class HFONNXComunnityModelLoader:
def _add_metadata(
self,
model: onnx.ModelProto, # type:ignore
- additional_metadata: dict[str, Any] = {},
+ additional_metadata: Optional[dict[str, Any]] = None,
) -> onnx.ModelProto: # type:ignore
+ if additional_metadata is None:
+ additional_metadata = {}
for key, value in additional_metadata.items():
metadata_props = model.metadata_props.add()
metadata_props.key = key
@@ -114,7 +116,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
onnx_name: Optional[str] = None,
include_pre_and_post_processor: bool = True,
save: bool = True,
- additional_metadata: list[tuple[str, str]] = [],
+ additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto: # type:ignore
"""Exports a depth estimation model to ONNX format.
diff --git a/kornia/models/detection/base.py b/kornia/models/detection/base.py
index 45b39893d..ecdbf7693 100644
--- a/kornia/models/detection/base.py
+++ b/kornia/models/detection/base.py
@@ -158,7 +158,7 @@ class ObjectDetector(ModelBase):
image_size: Optional[int] = 640,
include_pre_and_post_processor: bool = True,
save: bool = True,
- additional_metadata: list[tuple[str, str]] = [],
+ additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto: # type: ignore
"""Exports an RT-DETR object detection model to ONNX format.
diff --git a/kornia/models/detection/rtdetr.py b/kornia/models/detection/rtdetr.py
index 1a076b8f4..2884f0ee6 100644
--- a/kornia/models/detection/rtdetr.py
+++ b/kornia/models/detection/rtdetr.py
@@ -70,7 +70,7 @@ class RTDETRDetectorBuilder:
model = RTDETR.from_name(model_name)
image_size = RTDETRConfig.from_name(model_name).input_size
else:
- warnings.warn("No `model_name` or `config` found. Will build pretrained `rtdetr_r18vd`.")
+ warnings.warn("No `model_name` or `config` found. Will build pretrained `rtdetr_r18vd`.", stacklevel=1)
model = RTDETR.from_pretrained("rtdetr_r18vd")
image_size = RTDETRConfig.from_name("rtdetr_r18vd").input_size
diff --git a/kornia/models/edge_detection/base.py b/kornia/models/edge_detection/base.py
index a1eda20a1..589865d5b 100644
--- a/kornia/models/edge_detection/base.py
+++ b/kornia/models/edge_detection/base.py
@@ -82,7 +82,7 @@ class EdgeDetector(ModelBase):
image_size: Optional[int] = 352,
include_pre_and_post_processor: bool = True,
save: bool = True,
- additional_metadata: list[tuple[str, str]] = [],
+ additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
) -> onnx.ModelProto: # type: ignore
"""Exports the current edge detection model to an ONNX model file.
diff --git a/kornia/models/super_resolution/base.py b/kornia/models/super_resolution/base.py
index bb87410fa..bfd896120 100644
--- a/kornia/models/super_resolution/base.py
+++ b/kornia/models/super_resolution/base.py
@@ -95,7 +95,7 @@ class SuperResolution(ModelBase):
onnx_name: Optional[str] = None,
include_pre_and_post_processor: bool = True,
save: bool = True,
- additional_metadata: List[Tuple[str, str]] = [],
+ additional_metadata: Optional[List[Tuple[str, str]]] = None,
**kwargs: Any,
) -> "onnx.ModelProto": # type: ignore
"""Exports the current super resolution model to an ONNX model file.
diff --git a/kornia/models/utils.py b/kornia/models/utils.py
index 5f351f2b4..4c350587f 100644
--- a/kornia/models/utils.py
+++ b/kornia/models/utils.py
@@ -64,7 +64,8 @@ class ResizePostProcessor(Module):
if torch.onnx.is_in_onnx_export():
warnings.warn(
"ResizePostProcessor is not supported in ONNX export. "
- "The output will not be resized back to the original size."
+ "The output will not be resized back to the original size.",
+ stacklevel=1,
)
return imgs
diff --git a/kornia/onnx/module.py b/kornia/onnx/module.py
index 66ee579f1..8231f6be8 100644
--- a/kornia/onnx/module.py
+++ b/kornia/onnx/module.py
@@ -2,7 +2,6 @@ from __future__ import annotations
from typing import Any, Optional, Union
-from kornia.config import kornia_config
from kornia.core.external import onnx
from kornia.core.external import onnxruntime as ort
from kornia.core.mixin.onnx import ONNXMixin, ONNXRuntimeMixin
@@ -11,7 +10,7 @@ __all__ = ["ONNXModule", "load"]
class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
- f"""ONNXModule to wrap an ONNX operator.
+ """ONNXModule to wrap an ONNX operator.
Args:
arg: A variable number of ONNX models (either ONNX ModelProto objects or file paths).
@@ -21,7 +20,7 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
(e.g., ['CUDAExecutionProvider', 'CPUExecutionProvider']).
session_options: Optional ONNXRuntime session options for optimizing the session.
cache_dir: The directory where ONNX models are cached locally (only for downloading from HuggingFace).
- Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.
+ Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
target_ir_version: The target IR version to convert to.
target_opset_version: The target OPSET version to convert to.
"""
@@ -51,7 +50,7 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
def export(self, file_path: str, **kwargs: Any) -> None:
return super()._export(self.op, file_path, **kwargs)
- def add_metadata(self, additional_metadata: list[tuple[str, str]] = []) -> onnx.ModelProto: # type:ignore
+ def add_metadata(self, additional_metadata: Optional[list[tuple[str, str]]] = None) -> onnx.ModelProto: # type:ignore
return super()._add_metadata(self.op, additional_metadata)
diff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.py
index f882bae64..949a2ecf7 100644
--- a/kornia/onnx/sequential.py
+++ b/kornia/onnx/sequential.py
@@ -2,7 +2,6 @@ from __future__ import annotations
from typing import Any, Optional, Union
-from kornia.config import kornia_config
from kornia.core.external import onnx
from kornia.core.external import onnxruntime as ort
from kornia.core.mixin import ONNXMixin, ONNXRuntimeMixin
@@ -11,7 +10,7 @@ __all__ = ["ONNXSequential"]
class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
- f"""ONNXSequential to chain multiple ONNX operators together.
+ """ONNXSequential to chain multiple ONNX operators together.
Args:
*args: A variable number of ONNX models (either ONNX ModelProto objects or file paths).
@@ -25,7 +24,7 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
only one input and output node for each graph.
If not None, `io_maps[0]` shall represent the `io_map` for combining the first and second ONNX models.
cache_dir: The directory where ONNX models are cached locally (only for downloading from HuggingFace).
- Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.
+ Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
auto_ir_version_conversion: If True, automatically convert the model's IR version to 9, and OPSET version to 17.
Other versions may be pointed to by `target_ir_version` and `target_opset_version`.
target_ir_version: The target IR version to convert to.
@@ -92,5 +91,5 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
def export(self, file_path: str, **kwargs: Any) -> None:
return super()._export(self._combined_op, file_path, **kwargs)
- def add_metadata(self, additional_metadata: list[tuple[str, str]] = []) -> onnx.ModelProto: # type:ignore
+ def add_metadata(self, additional_metadata: Optional[list[tuple[str, str]]] = None) -> onnx.ModelProto: # type:ignore
return super()._add_metadata(self._combined_op, additional_metadata)
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index 05b6544f0..d17e605bf 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -4,7 +4,7 @@ import json
import logging
import os
import pprint
-from typing import Any
+from typing import Any, Optional
import kornia
from kornia.config import kornia_config
@@ -182,7 +182,7 @@ def io_name_conversion(
def add_metadata(
onnx_model: onnx.ModelProto, # type: ignore
- additional_metadata: list[tuple[str, str]] = [],
+ additional_metadata: Optional[list[tuple[str, str]]] = None,
) -> onnx.ModelProto: # type: ignore
"""Adds metadata to an ONNX model.
@@ -197,6 +197,8 @@ def add_metadata(
Returns:
The ONNX model with the added metadata.
"""
+ if additional_metadata is None:
+ additional_metadata = []
for key, value in [
("source", "kornia"),
("version", kornia.__version__),
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 1812a063c..d2acfb1b8 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -134,14 +134,15 @@ class BaseTester(ABC):
def test_cardinality(self, device: Device, dtype: Dtype) -> None:
raise NotImplementedError("Implement a stupid routine.")
- # TODO: add @abstractmethod
+ @abstractmethod
def test_dynamo(self, device: Device, dtype: Dtype, torch_optimizer: Callable[..., Any]) -> None:
- pass # TODO: raise NotImplementedError -- now we see a bunch of dynamo tests running by inheritance
+ raise NotImplementedError("Implement a stupid routine.")
@abstractmethod
def test_gradcheck(self, device: Device) -> None:
raise NotImplementedError("Implement a stupid routine.")
+ @abstractmethod
def test_module(self, device: Device, dtype: Dtype) -> None:
pass
@@ -195,11 +196,11 @@ class BaseTester(ABC):
return gradcheck(func, inputs, raise_exception=raise_exception, fast_mode=fast_mode, **kwargs)
-def generate_two_view_random_scene(
- device: Device = torch.device("cpu"), dtype: Dtype = torch.float32
-) -> Dict[str, Tensor]:
+def generate_two_view_random_scene(device: Optional[Device] = None, dtype: Dtype = torch.float32) -> Dict[str, Tensor]:
from kornia.geometry import epipolar as epi
+ if device is None:
+ device = torch.device("cpu")
num_views: int = 2
num_points: int = 30
@@ -258,7 +259,9 @@ def cartesian_product_of_parameters(**possible_parameters: Sequence[Any]) -> Ite
yield dict(zip(parameter_names, param_combination))
-def default_with_one_parameter_changed(*, default: Dict[str, Any] = {}, **possible_parameters: Any) -> Any:
+def default_with_one_parameter_changed(*, default: Optional[Dict[str, Any]] = None, **possible_parameters: Any) -> Any:
+ if default is None:
+ default = {}
if not isinstance(default, dict):
raise AssertionError(f"default should be a dict not a {type(default)}")
diff --git a/kornia/utils/download.py b/kornia/utils/download.py
index 177a0e25a..153493cc7 100644
--- a/kornia/utils/download.py
+++ b/kornia/utils/download.py
@@ -17,12 +17,12 @@ class CachedDownloader:
@classmethod
def _get_file_path(cls, model_name: str, cache_dir: Optional[str], suffix: Optional[str] = None) -> str:
- f"""Constructs the file path for the ONNX model based on the model name and cache directory.
+ """Constructs the file path for the ONNX model based on the model name and cache directory.
Args:
model_name: The name of the model or operator, typically in the format 'operators/model_name'.
cache_dir: The directory where the model should be cached.
- Defaults to None, which will use a default `{kornia_config.hub_onnx_dir}` directory.
+ Defaults to None, which will use a default `kornia.config.hub_onnx_dir` directory.
Returns:
str: The full local path where the model should be stored or loaded from.
@@ -77,6 +77,6 @@ class CachedDownloader:
logger.info(f"Downloading `{url}` to `{file_path}`.")
urllib.request.urlretrieve(url, file_path) # noqa: S310
except urllib.error.HTTPError as e:
- raise ValueError(f"Error in resolving `{url}`. {e}.")
+ raise ValueError(f"Error in resolving `{url}`.") from e
else:
raise ValueError("URL must start with 'http:' or 'https:'")
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index e8c27af7f..e1ccd9b22 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -240,7 +240,7 @@ def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
solution."""
if not torch_version_ge(1, 10):
sol = _torch_solve_cast(A, B)
- warnings.warn("PyTorch version < 1.10, solve validness mask maybe not correct", RuntimeWarning)
+ warnings.warn("PyTorch version < 1.10, solve validness mask maybe not correct", RuntimeWarning, stacklevel=1)
return sol, sol, torch.ones(len(A), dtype=torch.bool, device=A.device)
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
if not isinstance(B, Tensor):
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
index 1be5deb72..f78896eca 100644
--- a/kornia/x/trainer.py
+++ b/kornia/x/trainer.py
@@ -69,7 +69,7 @@ class Trainer:
optimizer: Optimizer,
scheduler: lr_scheduler._LRScheduler,
config: Configuration,
- callbacks: Dict[str, Callable[..., None]] = {},
+ callbacks: Optional[Dict[str, Callable[..., None]]] = None,
) -> None:
# setup the accelerator
if Accelerator is None:
@@ -86,6 +86,8 @@ class Trainer:
self.config = config
# configure callbacks
+ if callbacks is None:
+ callbacks = {}
for fn_name, fn in callbacks.items():
if fn_name not in callbacks_whitelist:
raise ValueError(f"Not supported: {fn_name}.")
diff --git a/pyproject.toml b/pyproject.toml
index 9e073590b..470df5e37 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -77,6 +77,7 @@ skip-magic-trailing-comma = false
select = [
"AIR", # Airflow
"ASYNC", # flake8-async
+ "B", # flake8-bugbear
"BLE", # flake8-blind-except
"C4", # flake8-comprehensions
"C90", # McCabe cyclomatic complexity
@@ -103,7 +104,6 @@ select = [
# "A", # flake8-builtins
# "ANN", # flake8-annotations
# "ARG", # flake8-unused-arguments
- # "B", # flake8-bugbear
# "COM", # flake8-commas
# "D", # pydocstyle
# "DJ", # flake8-django
@@ -185,6 +185,7 @@ max-statements = 64 # Recommended: 50
"RUF012",
"S101",
"S311",
+ "B017", # Check for Exception since KORNIA_CHECK raises it
] # allow assert, random, ignore BLE, mutable class attr
[tool.pytest.ini_options]
diff --git a/testing/geometry/create.py b/testing/geometry/create.py
index a34012fc7..b989300ec 100644
--- a/testing/geometry/create.py
+++ b/testing/geometry/create.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+from typing import Optional
+
import torch
import kornia.geometry.epipolar as epi
@@ -32,8 +34,10 @@ def create_random_fundamental_matrix(
def generate_two_view_random_scene(
- device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32
+ device: Optional[torch.device] = None, dtype: torch.dtype = torch.float32
) -> dict[str, torch.Tensor]:
+ if device is None:
+ device = torch.device("cpu")
num_views: int = 2
num_points: int = 30
diff --git a/testing/overwrite.py b/testing/overwrite.py
index f06f69bf8..b44ec5ca1 100644
--- a/testing/overwrite.py
+++ b/testing/overwrite.py
@@ -1,10 +1,12 @@
from __future__ import annotations
from copy import deepcopy
-from typing import Any
+from typing import Any, Optional
-def default_with_one_parameter_changed(*, default: dict[str, Any] = {}, **possible_parameters: Any) -> Any:
+def default_with_one_parameter_changed(*, default: Optional[dict[str, Any]] = None, **possible_parameters: Any) -> Any:
+ if default is None:
+ default = {}
if not isinstance(default, dict):
raise AssertionError(f"default should be a dict not a {type(default)}")
diff --git a/tests/augmentation/test_backward.py b/tests/augmentation/test_backward.py
index c1db083e3..63d88c081 100644
--- a/tests/augmentation/test_backward.py
+++ b/tests/augmentation/test_backward.py
@@ -181,7 +181,7 @@ class TestRandomAffineBackward:
try:
loss.backward()
except Exception as e:
- assert False, (list(aug.named_parameters()), e)
+ raise AssertionError(list(aug.named_parameters())) from e
opt.step()
if not isinstance(degrees, (int, float, list, tuple)):
diff --git a/tests/augmentation/test_container.py b/tests/augmentation/test_container.py
index f0dcff64b..e8482f93c 100644
--- a/tests/augmentation/test_container.py
+++ b/tests/augmentation/test_container.py
@@ -42,7 +42,7 @@ def reproducibility_test(input, seq):
if isinstance(o1, (torch.Tensor,)) and isinstance(o2, (torch.Tensor,))
]
else:
- assert False, ("cannot compare", type(output_1), type(output_2))
+ raise AssertionError(f"cannot compare {type(output_1)} {type(output_2)}")
class TestVideoSequential:
diff --git a/tests/benchmark.py b/tests/benchmark.py
index 3f43ecc69..24814e837 100644
--- a/tests/benchmark.py
+++ b/tests/benchmark.py
@@ -7,7 +7,7 @@ from torch.utils import benchmark
results = []
sizes = [1, 64, 1024]
-for b, n in product(sizes, sizes):
+for b, _ in product(sizes, sizes):
# label and sub_label are the rows
# description is the column
label = "get_perspective_transform"
diff --git a/tests/core/test_lazyloader.py b/tests/core/test_lazyloader.py
index b832de99c..e74ccc139 100644
--- a/tests/core/test_lazyloader.py
+++ b/tests/core/test_lazyloader.py
@@ -26,7 +26,7 @@ class TestLazyLoader:
# Test that LazyLoader raises an ImportError for an invalid module
loader = LazyLoader("non_existent_module")
with pytest.raises(ImportError) as excinfo:
- loader.non_existent_attribute # Accessing any attribute should raise the error
+ _ = loader.non_existent_attribute # Accessing any attribute should raise the error
assert "Optional dependency 'non_existent_module' is not installed" in str(excinfo.value)
@@ -56,4 +56,4 @@ class TestLazyLoader:
# Test that accessing a non-existing attribute raises an AttributeError after loading
loader = LazyLoader("math")
with pytest.raises(AttributeError):
- loader.non_existent_attribute
+ _ = loader.non_existent_attribute
diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.py
index 5d9871102..f14a19c26 100644
--- a/tests/geometry/test_boxes.py
+++ b/tests/geometry/test_boxes.py
@@ -120,13 +120,13 @@ class TestBoxes2D(BaseTester):
try:
Boxes.from_tensor(box_xyxy, mode="xyxy")
- assert False, "Boxes.from_tensor should have raised any exception"
+ raise AssertionError("Boxes.from_tensor should have raised any exception")
except ValueError:
pass
try:
Boxes.from_tensor(box_xyxy_plus, mode="xyxy_plus")
- assert False, "Boxes.from_tensor should have raised any exception"
+ raise AssertionError("Boxes.from_tensor should have raised any exception")
except ValueError:
pass
@@ -561,13 +561,13 @@ class TestBbox3D(BaseTester):
try:
Boxes3D.from_tensor(box_xyzxyz, mode="xyzxyz")
- assert False, "Boxes3D.from_tensor should have raised any exception"
+ raise AssertionError("Boxes3D.from_tensor should have raised any exception")
except ValueError:
pass
try:
Boxes3D.from_tensor(box_xyzxyz_plus, mode="xyzxyz_plus")
- assert False, "Boxes3D.from_tensor should have raised any exception"
+ raise AssertionError("Boxes3D.from_tensor should have raised any exception")
except ValueError:
pass
diff --git a/tests/geometry/test_vector.py b/tests/geometry/test_vector.py
index b0d2c4c1d..d1c49c9bd 100644
--- a/tests/geometry/test_vector.py
+++ b/tests/geometry/test_vector.py
@@ -10,9 +10,9 @@ class TestVector3(BaseTester):
def test_smoke(self, device, dtype):
vec = Vector3.random(device=device, dtype=dtype)
assert vec.shape == (3,)
- vec.x is not None
- vec.y is not None
- vec.z is not None
+ assert vec.x is not None
+ assert vec.y is not None
+ assert vec.z is not None
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_getitem(self, device, dtype, batch_size):
@@ -82,8 +82,8 @@ class TestVector2(BaseTester):
def test_smoke(self, device, dtype):
vec = Vector2.random(device=device, dtype=dtype)
assert vec.shape == (2,)
- vec.x is not None
- vec.y is not None
+ assert vec.x is not None
+ assert vec.y is not None
@pytest.mark.parametrize("batch_size", (1, 2, 5))
def test_getitem(self, device, dtype, batch_size):
diff --git a/tests/nerf/test_camera_utils.py b/tests/nerf/test_camera_utils.py
index 26823408c..952124c25 100755
--- a/tests/nerf/test_camera_utils.py
+++ b/tests/nerf/test_camera_utils.py
@@ -84,4 +84,4 @@ def test_create_spiral_path(device, dtype, colmap_cameras_path, colmap_images_pa
try:
create_spiral_path(cameras, 1, 30, 3)
except Exception as err:
- assert False, err
+ raise AssertionError from err