Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

chore(typing): drop unused type: ignore comments and make ty reject them (#5791)

Daisy DAI542752eff7dc
diff --git a/kornia/augmentation/_2d/intensity/base.py b/kornia/augmentation/_2d/intensity/base.py
index e9c5aaee8..033d514d6 100644
--- a/kornia/augmentation/_2d/intensity/base.py
+++ b/kornia/augmentation/_2d/intensity/base.py
@@ -38,18 +38,18 @@ class _PicklableCompileMixin:
self._compile_kwargs = compile_kwargs
def __getstate__(self) -> Dict[str, Any]:
- state = super().__getstate__() # type: ignore[misc]
+ state = super().__getstate__()
uncompiled = state.get("_uncompiled_fns")
if uncompiled is not None:
state.update(uncompiled)
return state
def __setstate__(self, state: Dict[str, Any]) -> None:
- super().__setstate__(state) # type: ignore[misc]
+ super().__setstate__(state)
compile_kwargs = state.get("_compile_kwargs")
if compile_kwargs is not None:
self._uncompiled_fns = None
- self.compile(**compile_kwargs) # type: ignore[attr-defined]
+ self.compile(**compile_kwargs)
class IntensityAugmentationBase2D(RigidAffineAugmentationBase2D):
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 39bd49931..e5ef8909b 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -260,7 +260,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
) -> torch.Tensor:
raise NotImplementedError
- def forward( # type: ignore[override]
+ def forward(
self,
*input: torch.Tensor,
params: Optional[Dict[str, torch.Tensor]] = None,
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index 5b0b9de29..cb8f5e198 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -232,13 +232,13 @@ class RandomTransplantation(MixAugmentationBaseV2):
) -> torch.Tensor:
return input
- def transform_input(self, acceptor: torch.Tensor, donor: torch.Tensor, selection: torch.Tensor) -> torch.Tensor: # type: ignore[override]
+ def transform_input(self, acceptor: torch.Tensor, donor: torch.Tensor, selection: torch.Tensor) -> torch.Tensor:
# Expand selection to the channel dimension
selection = selection.unsqueeze(dim=self._channel_dim).expand_as(donor)
acceptor[selection] = donor[selection]
return acceptor
- def transform_mask(self, acceptor: torch.Tensor, donor: torch.Tensor, selection: torch.Tensor) -> torch.Tensor: # type: ignore[override]
+ def transform_mask(self, acceptor: torch.Tensor, donor: torch.Tensor, selection: torch.Tensor) -> torch.Tensor:
if acceptor.ndim == selection.ndim + 1:
# A mask with a singleton channel axis, ``(B, 1, *spatial)``, as a container hands it on (#4707).
selection = selection.unsqueeze(dim=self._channel_dim).expand_as(donor)
@@ -383,7 +383,7 @@ class RandomTransplantation(MixAugmentationBaseV2):
return params
- def forward( # type: ignore[override]
+ def forward(
self,
*input: torch.Tensor,
params: Optional[dict[str, torch.Tensor]] = None,
diff --git a/kornia/augmentation/_3d/mix/transplantation.py b/kornia/augmentation/_3d/mix/transplantation.py
index 8abd677eb..4fce28306 100644
--- a/kornia/augmentation/_3d/mix/transplantation.py
+++ b/kornia/augmentation/_3d/mix/transplantation.py
@@ -21,7 +21,7 @@ from kornia.augmentation._3d.base import AugmentationBase3D
__all__ = ["RandomTransplantation3D"]
-class RandomTransplantation3D(RandomTransplantation, AugmentationBase3D): # type: ignore
+class RandomTransplantation3D(RandomTransplantation, AugmentationBase3D):
"""RandomTransplantation3D augmentation.
3D version of the :class:`kornia.augmentation.RandomTransplantation` augmentation intended to be used with
diff --git a/kornia/augmentation/auto/base.py b/kornia/augmentation/auto/base.py
index a6fae65c8..5bfd8e24b 100644
--- a/kornia/augmentation/auto/base.py
+++ b/kornia/augmentation/auto/base.py
@@ -65,7 +65,7 @@ class PolicyAugmentBase(ImageSequentialBase, TransformMatrixMinIn):
self._parse_transformation_matrix_mode(transformation_matrix_mode)
self._valid_ops_for_transform_computation: Tuple[Any, ...] = (PolicySequential,)
- def _update_transform_matrix_for_valid_op(self, module: PolicySequential) -> None: # type: ignore
+ def _update_transform_matrix_for_valid_op(self, module: PolicySequential) -> None:
self._transform_matrices.append(module.transform_matrix)
def clear_state(self) -> None:
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 9723b1647..6605bbd88 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -440,7 +440,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
return eye_like(3, input)
- def inverse( # type: ignore[override]
+ def inverse(
self,
*args: Union[DataType, Dict[str, DataType]],
params: Optional[List[ParamItem]] = None,
@@ -467,9 +467,9 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
try:
if params is None:
params = self._params
- self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys, params=params) # type: ignore
+ self._validate_args_datakeys(*args, data_keys=self.transform_op.data_keys, params=params)
- in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys) # type: ignore
+ in_args = self._arguments_preproc(*args, data_keys=self.transform_op.data_keys)
if params is None:
raise ValueError(
@@ -480,14 +480,12 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
outputs: List[DataType] = in_args
for param in params[::-1]:
module = self.get_submodule(param.name)
- outputs = self.transform_op.inverse( # type: ignore
- *outputs, module=module, param=param, extra_args=self.extra_args
- )
+ outputs = self.transform_op.inverse(*outputs, module=module, param=param, extra_args=self.extra_args)
if len(self.transform_op.data_keys) == 1 or not isinstance(outputs, (list, tuple)):
# One data key can itself hold a mask list; keep it as one argument for the next child.
outputs = [outputs]
- outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys) # type: ignore
+ outputs = self._arguments_postproc(args, outputs, data_keys=self.transform_op.data_keys)
finally:
self.transform_op.data_keys = original_data_keys
@@ -683,7 +681,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
return out
- def forward( # type: ignore[override]
+ def forward(
self,
*args: Union[DataType, Dict[str, DataType]],
params: Optional[List[ParamItem]] = None,
@@ -761,7 +759,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
outputs = [outputs[i] for i in restore_order]
self.transform_op.data_keys = original_data_keys
- outputs = self._arguments_postproc(args, outputs, data_keys=original_data_keys) # type: ignore
+ outputs = self._arguments_postproc(args, outputs, data_keys=original_data_keys)
finally:
self.transform_op.data_keys = self.data_keys
if not is_exporting():
@@ -931,7 +929,7 @@ class AugmentationSequential(TransformMatrixMinIn, ImageSequential):
if data_key in _MSK_OPTIONS:
# A PIL image or an image file converts like its NumPy array, so labels and palette indices are kept.
if isinstance(arg, str) and self._is_valid_arg(arg):
- with Image.open(arg) as mask: # type: ignore
+ with Image.open(arg) as mask:
arg = np.array(mask)
elif _is_pil_image(arg):
arg = np.array(arg)
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 94e7368ed..163ff421f 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -459,7 +459,7 @@ class TransformMatrixMinIn:
_valid_ops_for_transform_computation: Tuple[Any, ...] = ()
_transformation_matrix_arg: str = "silent"
- def __init__(self, *args, **kwargs) -> None: # type:ignore
+ def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self._transform_matrix: Optional[torch.Tensor] = None
self._transform_matrices: List[Optional[torch.Tensor]] = []
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index f15c0dc2f..189572917 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -235,9 +235,9 @@ class AugmentationSequentialOps:
param = ParamItem(
name=param.name,
data=module.params_from_input(
- *arg, # type: ignore[arg-type]
+ *arg,
data_keys=_data_keys,
- params=param.data, # type: ignore[arg-type]
+ params=param.data,
extra_args=extra_args,
),
)
@@ -753,7 +753,7 @@ class BoxSequentialOps(SequentialOpsInterface[Boxes]):
transform = module.compute_inverse_transformation(cls.get_transform_matrix(module, param, _input))
_input = module.inverse_boxes(
_input,
- param.data, # type: ignore[arg-type]
+ param.data,
module.flags,
transform=transform,
**extra_args,
diff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.py
index d2004c1fe..eece7a79f 100644
--- a/kornia/augmentation/container/patch.py
+++ b/kornia/augmentation/container/patch.py
@@ -191,7 +191,7 @@ class PatchSequential(ImageSequential):
self.grid_size = grid_size
self.padding = padding
self.patchwise_apply = patchwise_apply
- self._params: Optional[List[PatchParamItem]] # type: ignore[assignment]
+ self._params: Optional[List[PatchParamItem]]
@staticmethod
def _validate_grid_size(grid_size: Tuple[int, int]) -> None:
@@ -342,7 +342,7 @@ class PatchSequential(ImageSequential):
restored_tensor = F.pad(restored_tensor, [-max(i, 0) for i in pad])
return restored_tensor
- def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]: # type: ignore[override]
+ def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]:
"""Generate patch-level parameters for a forward pass.
Args:
@@ -441,7 +441,7 @@ class PatchSequential(ImageSequential):
return input.reshape(in_shape)
- def transform_inputs( # type: ignore[override]
+ def transform_inputs(
self, input: torch.Tensor, params: Optional[List[PatchParamItem]], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
"""Apply patch-wise augmentation to an input tensor.
@@ -464,7 +464,7 @@ class PatchSequential(ImageSequential):
return input
- def inverse_inputs( # type: ignore[override]
+ def inverse_inputs(
self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
"""Inverse the patch pipeline when supported.
@@ -485,7 +485,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
- def transform_masks( # type: ignore[override]
+ def transform_masks(
self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
"""Transform masks for intensity-only patch pipelines.
@@ -506,7 +506,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")
- def inverse_masks( # type: ignore[override]
+ def inverse_masks(
self, input: torch.Tensor, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> torch.Tensor:
"""Inverse mask transforms for supported patch pipelines.
@@ -527,7 +527,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
- def transform_boxes( # type: ignore[override]
+ def transform_boxes(
self, input: Boxes, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Boxes:
"""Transform boxes for intensity-only patch pipelines.
@@ -548,7 +548,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential for boxes cannot be used with geometric transformations.")
- def inverse_boxes( # type: ignore[override]
+ def inverse_boxes(
self, input: Boxes, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Boxes:
"""Inverse box transforms for supported patch pipelines.
@@ -569,7 +569,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
- def transform_keypoints( # type: ignore[override]
+ def transform_keypoints(
self, input: Keypoints, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
"""Transform keypoints for intensity-only patch pipelines.
@@ -590,7 +590,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential for keypoints cannot be used with geometric transformations.")
- def inverse_keypoints( # type: ignore[override]
+ def inverse_keypoints(
self, input: Keypoints, params: List[PatchParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Keypoints:
"""Inverse keypoint transforms for supported patch pipelines.
@@ -612,7 +612,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
- def inverse( # type: ignore[override]
+ def inverse(
self,
input: torch.Tensor,
params: Optional[List[PatchParamItem]] = None,
@@ -628,7 +628,7 @@ class PatchSequential(ImageSequential):
raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")
- def forward(self, input: torch.Tensor, params: Optional[List[PatchParamItem]] = None) -> torch.Tensor: # type: ignore[override]
+ def forward(self, input: torch.Tensor, params: Optional[List[PatchParamItem]] = None) -> torch.Tensor:
"""Augment an image batch, optionally replaying previously generated patch parameters."""
if isinstance(input, (tuple,)):
raise ValueError("tuple input is not currently supported.")
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index e13f70404..10ca7e911 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -386,7 +386,7 @@ class VideoSequential(ImageSequential):
return self._input_shape_convert_back(input, frame_num)
- def transform_boxes( # type: ignore[override]
+ def transform_boxes(
self, input: Union[torch.Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Union[torch.Tensor, Boxes]:
"""Transform bounding boxes.
@@ -408,7 +408,7 @@ class VideoSequential(ImageSequential):
input = super().transform_boxes(input, params, extra_args=extra_args)
return input
- def inverse_boxes( # type: ignore[override]
+ def inverse_boxes(
self, input: Union[torch.Tensor, Boxes], params: List[ParamItem], extra_args: Optional[Dict[str, Any]] = None
) -> Union[torch.Tensor, Boxes]:
"""Transform bounding boxes.
@@ -430,7 +430,7 @@ class VideoSequential(ImageSequential):
input = super().inverse_boxes(input, params, extra_args=extra_args)
return input
- def transform_keypoints( # type: ignore[override]
+ def transform_keypoints(
self,
input: Union[torch.Tensor, Keypoints],
params: List[ParamItem],
@@ -453,7 +453,7 @@ class VideoSequential(ImageSequential):
input = super().transform_keypoints(input, params, extra_args=extra_args)
return input
- def inverse_keypoints( # type: ignore[override]
+ def inverse_keypoints(
self,
input: Union[torch.Tensor, Keypoints],
params: List[ParamItem],
diff --git a/kornia/augmentation/presets/ada.py b/kornia/augmentation/presets/ada.py
index 01339b129..fa90b1962 100644
--- a/kornia/augmentation/presets/ada.py
+++ b/kornia/augmentation/presets/ada.py
@@ -284,7 +284,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
)
return merged
- def forward( # type: ignore[override]
+ def forward(
self,
inputs: _inputs_type,
params: Optional[List[ParamItem]] = None,
@@ -338,7 +338,7 @@ class AdaptiveDiscriminatorAugmentation(AugmentationSequential):
augmented_inputs = cast(
_inputs_type,
super().forward(
- selected_inputs, # type: ignore[arg-type]
+ selected_inputs,
params=params,
data_keys=forward_data_keys,
),
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 6af795887..2b601a786 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -145,7 +145,7 @@ class DistributionWithMapper(Distribution):
self.dist = dist
self.map_fn = map_fn
- def rsample(self, sample_shape: Tuple[int, ...]) -> torch.Tensor: # type: ignore[override]
+ def rsample(self, sample_shape: Tuple[int, ...]) -> torch.Tensor:
"""Draw a reparameterized sample and apply ``map_fn`` when provided.
Args:
@@ -159,7 +159,7 @@ class DistributionWithMapper(Distribution):
out = self.map_fn(out)
return out
- def sample(self, sample_shape: Tuple[int, ...]) -> torch.Tensor: # type: ignore[override]
+ def sample(self, sample_shape: Tuple[int, ...]) -> torch.Tensor:
"""Draw a sample and apply ``map_fn`` when provided.
Args:
diff --git a/kornia/constants.py b/kornia/constants.py
index 226666dcb..d6ff6e54e 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -32,10 +32,10 @@ TKEnum = Union[str, int, _T]
class _KORNIA_EnumMeta(EnumMeta):
"""Custom metaclass for enums to support string and integer comparisons."""
- def __iter__(self) -> Iterator[Enum]: # type: ignore[override]
+ def __iter__(self) -> Iterator[Enum]:
return super().__iter__()
- def __contains__(self, other: TKEnum[Enum]) -> bool: # type: ignore[override]
+ def __contains__(self, other: TKEnum[Enum]) -> bool:
if isinstance(other, str):
return any(val.name.upper() == other.upper() for val in self)
diff --git a/kornia/contrib/edge_detection.py b/kornia/contrib/edge_detection.py
index 717b5bb5b..feb475823 100644
--- a/kornia/contrib/edge_detection.py
+++ b/kornia/contrib/edge_detection.py
@@ -120,7 +120,7 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
images: Union[torch.Tensor, list[torch.Tensor]],
edge_maps: Optional[Union[torch.Tensor, list[torch.Tensor]]] = None,
output_type: str = "torch",
- ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]: # type: ignore
+ ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]:
"""Draw the edge detection results.
Args:
@@ -163,7 +163,7 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
self._save_outputs(images, directory, suffix="_src")
self._save_outputs(outputs, directory, suffix="_edge")
- def to_onnx( # type: ignore[override]
+ def to_onnx(
self,
onnx_name: Optional[str] = None,
image_size: Optional[int] = 352,
@@ -171,7 +171,7 @@ class EdgeDetector(ModelBase, ONNXExportMixin):
save: bool = True,
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
- ) -> onnx.ModelProto: # type: ignore
+ ) -> onnx.ModelProto:
"""Export the current edge detection model to an ONNX model file.
Args:
diff --git a/kornia/contrib/object_detection.py b/kornia/contrib/object_detection.py
index 83aead493..1c4cc95b9 100644
--- a/kornia/contrib/object_detection.py
+++ b/kornia/contrib/object_detection.py
@@ -186,7 +186,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
images: Union[torch.Tensor, list[torch.Tensor]],
detections: Optional[torch.Tensor] = None,
output_type: str = "torch",
- ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]: # type: ignore
+ ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]:
"""Very simple drawing.
Needs to be more fancy later.
@@ -222,7 +222,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
outputs = self.visualize(images, detections)
self._save_outputs(outputs, directory)
- def to_onnx( # type: ignore[override]
+ def to_onnx(
self,
onnx_name: Optional[str] = None,
image_size: Optional[int] = 640,
@@ -230,7 +230,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
save: bool = True,
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
- ) -> onnx.ModelProto: # type: ignore
+ ) -> onnx.ModelProto:
"""Export an RT-DETR object detection model to ONNX format.
Either `model_name` or `config` must be provided. If neither is provided,
@@ -279,7 +279,7 @@ class ObjectDetector(ModelBase, ONNXExportMixin):
disable: bool = False,
) -> None:
"""Compile the internal object detection model with :py:func:`torch.compile()`."""
- self.model = torch.compile( # type: ignore
+ self.model = torch.compile(
self.model,
fullgraph=fullgraph,
dynamic=dynamic,
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index 860367ea8..407dc43ad 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -167,7 +167,7 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):
images: Union[torch.Tensor, List[torch.Tensor]],
edge_maps: Optional[Union[torch.Tensor, List[torch.Tensor]]] = None,
output_type: str = "torch",
- ) -> Union[torch.Tensor, List[torch.Tensor], List["Image.Image"]]: # type: ignore
+ ) -> Union[torch.Tensor, List[torch.Tensor], List["Image.Image"]]:
"""Draw the super resolution results.
Args:
@@ -211,14 +211,14 @@ class SuperResolution(ModelBase[SuperResolutionConfig], ONNXExportMixin):
self._save_outputs(images, directory, suffix="_src")
self._save_outputs(outputs, directory, suffix="_sr")
- def to_onnx( # type: ignore[override]
+ def to_onnx(
self,
onnx_name: Optional[str] = None,
include_pre_and_post_processor: bool = True,
save: bool = True,
additional_metadata: Optional[List[Tuple[str, str]]] = None,
**kwargs: Any,
- ) -> "onnx.ModelProto": # type: ignore
+ ) -> "onnx.ModelProto":
"""Export the current super resolution model to an ONNX model file.
Args:
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 9b552e8cf..1dd36f11d 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -369,7 +369,7 @@ class VisualPrompter:
>>> # Use the prompter methods ...
"""
- # self.set_image = torch.compile( # type: ignore[method-assign]
+ # self.set_image = torch.compile(
# self.set_image,
# fullgraph=fullgraph,
# dynamic=dynamic,
@@ -379,7 +379,7 @@ class VisualPrompter:
# disable=disable,
# )
# FIXME: compile set image will try to compile AugmentationSequential which fails
- self.model.image_encoder = torch.compile( # type: ignore
+ self.model.image_encoder = torch.compile(
self.model.image_encoder,
fullgraph=fullgraph,
dynamic=dynamic,
@@ -389,7 +389,7 @@ class VisualPrompter:
disable=disable,
)
- # self.preprocess_image = torch.compile( # type: ignore[method-assign]
+ # self.preprocess_image = torch.compile(
# self.preprocess_image,
# fullgraph=fullgraph,
# dynamic=dynamic,
@@ -401,7 +401,7 @@ class VisualPrompter:
# FIXME: compile predict will try to compile Preproc prompts, which need to compileAugmentationSequential
# which fails
- # self.predict = torch.compile( # type: ignore[method-assign]
+ # self.predict = torch.compile(
# self.predict,
# fullgraph=fullgraph,
# dynamic=dynamic,
@@ -410,7 +410,7 @@ class VisualPrompter:
# options=options,
# disable=disable,
# )
- self.model.mask_decoder = torch.compile( # type: ignore
+ self.model.mask_decoder = torch.compile(
self.model.mask_decoder,
fullgraph=fullgraph,
dynamic=dynamic,
@@ -419,7 +419,7 @@ class VisualPrompter:
options=options,
disable=disable,
)
- self.model.prompt_encoder = torch.compile( # type: ignore
+ self.model.prompt_encoder = torch.compile(
self.model.prompt_encoder,
fullgraph=fullgraph,
dynamic=dynamic,
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index ab71e54e3..8f41499b0 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -71,7 +71,7 @@ def _rebuild_container(source: Any, items: List[Any]) -> Any:
field-aware ``_make``. A plain tuple or list takes an iterable.
"""
if hasattr(type(source), "_make"):
- return type(source)._make(items) # type: ignore[attr-defined]
+ return type(source)._make(items)
return type(source)(items)
@@ -257,7 +257,7 @@ class ImageModuleMixIn:
return True
if isinstance(arg, torch.Tensor):
return True
- if isinstance(arg, np.ndarray): # type: ignore
+ if isinstance(arg, np.ndarray):
return True
# A PIL image exists only once PIL is imported: look the module up instead of importing it through the lazy
# loader, which would raise on an install without the "image" extra for every non-image argument.
@@ -300,12 +300,12 @@ class ImageModuleMixIn:
image = _image_to_float(image)
elif isinstance(x, torch.Tensor):
return x
- elif isinstance(x, np.ndarray): # type: ignore
+ elif isinstance(x, np.ndarray):
image = _array_to_float_image(x)
- elif isinstance(x, Image.Image): # type: ignore
+ elif isinstance(x, Image.Image):
if x.mode in ("P", "PA"): # palette indices are not intensities
x = x.convert("RGBA" if x.mode == "PA" or "transparency" in x.info else "RGB")
- image = _array_to_float_image(np.array(x)) # type: ignore
+ image = _array_to_float_image(np.array(x))
else:
raise TypeError("Input type not supported")
return self._to_module_device_dtype(image)
@@ -335,7 +335,7 @@ class ImageModuleMixIn:
floating_dtype = torch.get_default_dtype()
return image.to(device=reference.device, dtype=floating_dtype)
- def to_numpy(self, x: Any) -> "np.array": # type: ignore
+ def to_numpy(self, x: Any) -> "np.array":
"""Convert input to numpy array.
A :math:`(C, H, W)` or :math:`(B, C, H, W)` tensor becomes a channels-last :math:`(H, W, C)` or
@@ -362,13 +362,13 @@ class ImageModuleMixIn:
elif x.dim() == 4:
x = x.permute(0, 2, 3, 1)
return x.contiguous().numpy()
- if isinstance(x, np.ndarray): # type: ignore
+ if isinstance(x, np.ndarray):
return x
- if isinstance(x, Image.Image): # type: ignore
- return np.array(x) # type: ignore
+ if isinstance(x, Image.Image):
+ return np.array(x)
raise TypeError("Input type not supported")
- def to_pil(self, x: Any) -> "Image.Image": # type: ignore
+ def to_pil(self, x: Any) -> "Image.Image":
"""Convert input to PIL image.
A floating image is clamped to ``[0, 1]`` and rounded to 8 bits on the CPU; a ``uint8`` image keeps its
@@ -386,18 +386,18 @@ class ImageModuleMixIn:
if x.dim() == 3:
return self._chw_to_pil(x)
if x.dim() == 4:
- return [self._chw_to_pil(_x) for _x in x] # type: ignore
+ return [self._chw_to_pil(_x) for _x in x]
raise NotImplementedError(
f"to_pil converts a (C, H, W) or (B, C, H, W) tensor, got a tensor of shape {tuple(x.shape)}."
)
- if isinstance(x, np.ndarray): # type: ignore
+ if isinstance(x, np.ndarray):
raise NotImplementedError("to_pil does not convert NumPy arrays; convert them with to_tensor first.")
- if isinstance(x, Image.Image): # type: ignore
+ if isinstance(x, Image.Image):
return x
raise TypeError("Input type not supported")
@staticmethod
- def _chw_to_pil(image: torch.Tensor) -> "Image.Image": # type: ignore
+ def _chw_to_pil(image: torch.Tensor) -> "Image.Image":
image = _to_uint8_image(image.detach().cpu())
if image.dtype != torch.uint8 and (image.shape[0] != 1 or image.dtype not in _PIL_ONE_CHANNEL_DTYPES):
raise NotImplementedError(
@@ -405,8 +405,8 @@ class ImageModuleMixIn:
f"image; got a {image.shape[0]}-channel {image.dtype} tensor."
)
if image.shape[0] == 1:
- return Image.fromarray(image[0].numpy()) # type: ignore
- return Image.fromarray(image.permute(1, 2, 0).numpy()) # type: ignore
+ return Image.fromarray(image[0].numpy())
+ return Image.fromarray(image.permute(1, 2, 0).numpy())
def _detach_tensor(
self, output_image: Union[torch.Tensor, List[Any], Tuple[Any, ...]]
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index ba5682b3f..6a42745aa 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -100,7 +100,7 @@ class ONNXExportMixin:
save: bool = True,
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
- ) -> onnx.ModelProto: # type: ignore
+ ) -> onnx.ModelProto:
"""Export the current object to an ONNX model file.
Args:
@@ -219,12 +219,12 @@ class ONNXExportMixin:
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_path = os.path.join(tmp_dir, "model.onnx")
torch.onnx.export(
- module, # type: ignore[arg-type]
- dummy_input, # type: ignore[arg-type]
+ module,
+ dummy_input,
tmp_path,
**default_args,
)
- onnx_model = onnx.load(tmp_path) # type: ignore
+ onnx_model = onnx.load(tmp_path)
finally:
# The flag is set directly on purpose: ``train()`` recurses into the children, which would lose a mixed
# state. It also skips ``train()`` overrides: TinyViT's ``Attention.train(True)`` would drop the attention
@@ -237,7 +237,7 @@ class ONNXExportMixin:
metadata = [*self.ADDITIONAL_METADATA, *(additional_metadata or [])]
onnx_model = kornia.onnx.utils.add_metadata(onnx_model, metadata)
if save:
- onnx.save(onnx_model, onnx_name) # type: ignore
+ onnx.save(onnx_model, onnx_name)
return onnx_model
def _create_dummy_input(
@@ -271,10 +271,10 @@ class ONNXRuntimeMixin:
def _create_session(
self,
- op: onnx.ModelProto, # type:ignore
+ op: onnx.ModelProto,
providers: Optional[list[str]] = None,
- session_options: Optional[ort.SessionOptions] = None, # type:ignore
- ) -> ort.InferenceSession: # type:ignore
+ session_options: Optional[ort.SessionOptions] = None,
+ ) -> ort.InferenceSession:
"""Create an optimized ONNXRuntime InferenceSession for the combined model.
Args:
@@ -290,15 +290,15 @@ class ONNXRuntimeMixin:
"""
if session_options is None:
- session_options = ort.SessionOptions() # type:ignore
- session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED # type:ignore
- return ort.InferenceSession( # type:ignore
+ session_options = ort.SessionOptions()
+ session_options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_EXTENDED
+ return ort.InferenceSession(
op.SerializeToString(),
sess_options=session_options,
providers=providers or ["CPUExecutionProvider"],
)
- def set_session(self, session: ort.InferenceSession) -> None: # type: ignore
+ def set_session(self, session: ort.InferenceSession) -> None:
"""Set a custom ONNXRuntime InferenceSession.
Args:
@@ -308,7 +308,7 @@ class ONNXRuntimeMixin:
"""
self._session = session
- def get_session(self) -> ort.InferenceSession: # type: ignore
+ def get_session(self) -> ort.InferenceSession:
"""Get the current ONNXRuntime InferenceSession.
Returns:
@@ -373,7 +373,7 @@ class ONNXRuntimeMixin:
["OpenVINOExecutionProvider"], provider_options=[{"device_type": device_type, **kwargs}]
)
- def __call__(self, *inputs: np.ndarray) -> list[np.ndarray]: # type:ignore
+ def __call__(self, *inputs: np.ndarray) -> list[np.ndarray]:
"""Perform inference using the combined ONNX model.
Args:
@@ -398,9 +398,9 @@ class ONNXMixin:
def _load_op(
self,
- arg: Union[onnx.ModelProto, str], # type:ignore
+ arg: Union[onnx.ModelProto, str],
cache_dir: Optional[str] = None,
- ) -> onnx.ModelProto: # type:ignore
+ ) -> onnx.ModelProto:
"""Load an ONNX model, either from a file path or use the provided ONNX ModelProto.
Args:
@@ -413,15 +413,15 @@ class ONNXMixin:
"""
if isinstance(arg, str):
return kornia.onnx.utils.ONNXLoader.load_model(arg, cache_dir=cache_dir)
- if isinstance(arg, onnx.ModelProto): # type:ignore
+ if isinstance(arg, onnx.ModelProto):
return arg
raise ValueError(f"Invalid argument type. Got {type(arg)}")
def _load_ops(
self,
- *args: Union[onnx.ModelProto, str], # type:ignore
+ *args: Union[onnx.ModelProto, str],
cache_dir: Optional[str] = None,
- ) -> list[onnx.ModelProto]: # type:ignore
+ ) -> list[onnx.ModelProto]:
"""Load multiple ONNX models or operators and returns them as a list.
Args:
@@ -441,9 +441,9 @@ class ONNXMixin:
def _combine(
self,
- *args: list[onnx.ModelProto], # type:ignore
+ *args: list[onnx.ModelProto],
io_maps: Optional[list[tuple[str, str]]] = None,
- ) -> onnx.ModelProto: # type:ignore
+ ) -> onnx.ModelProto:
"""Combine the provided ONNX models into a single ONNX graph.
Optionally, map inputs and outputs between operators using the `io_map`.
@@ -462,21 +462,21 @@ class ONNXMixin:
raise ValueError("No operators found.")
combined_op = args[0]
- combined_op = onnx.compose.add_prefix(combined_op, prefix=f"K{str(0).zfill(2)}-") # type:ignore
+ combined_op = onnx.compose.add_prefix(combined_op, prefix=f"K{str(0).zfill(2)}-")
for i, op in enumerate(args[1:]):
- next_op = onnx.compose.add_prefix(op, prefix=f"K{str(i + 1).zfill(2)}-") # type:ignore
+ next_op = onnx.compose.add_prefix(op, prefix=f"K{str(i + 1).zfill(2)}-")
if io_maps is None:
io_map = [(f"K{str(i).zfill(2)}-output", f"K{str(i + 1).zfill(2)}-input")]
else:
io_map = [(f"K{str(i).zfill(2)}-{it[0]}", f"K{str(i + 1).zfill(2)}-{it[1]}") for it in io_maps[i]]
- combined_op = onnx.compose.merge_models(combined_op, next_op, io_map=io_map) # type:ignore
+ combined_op = onnx.compose.merge_models(combined_op, next_op, io_map=io_map)
return combined_op
def _export(
self,
- op: onnx.ModelProto, # type:ignore
+ op: onnx.ModelProto,
file_path: str,
**kwargs: Any,
) -> None:
@@ -489,13 +489,13 @@ class ONNXMixin:
kwargs: Additional arguments to save onnx model.
"""
- onnx.save(op, file_path, **kwargs) # type:ignore
+ onnx.save(op, file_path, **kwargs)
def _add_metadata(
self,
- op: onnx.ModelProto, # type:ignore
+ op: onnx.ModelProto,
additional_metadata: Optional[list[tuple[str, str]]] = None,
- ) -> onnx.ModelProto: # type:ignore
+ ) -> onnx.ModelProto:
"""Add metadata to the combined ONNX model.
The ``source`` and ``version`` entries are always written. A key that is already present is overwritten,
@@ -512,10 +512,10 @@ class ONNXMixin:
def _onnx_version_conversion(
self,
- op: onnx.ModelProto, # type:ignore
+ op: onnx.ModelProto,
target_ir_version: Optional[int] = None,
target_opset_version: Optional[int] = None,
- ) -> onnx.ModelProto: # type:ignore
+ ) -> onnx.ModelProto:
"""Automatic conversion of the model's IR/OPSET version to the given target version.
Args:
@@ -527,13 +527,11 @@ class ONNXMixin:
if op.ir_version != target_ir_version or self._opset_version(op) != target_opset_version:
# Check if all ops are supported in the current IR version
model_bytes = io.BytesIO()
- onnx.save_model(op, model_bytes) # type:ignore
- loaded_model = onnx.load_model_from_string(model_bytes.getvalue()) # type:ignore
+ onnx.save_model(op, model_bytes)
+ loaded_model = onnx.load_model_from_string(model_bytes.getvalue())
if target_opset_version is not None:
- loaded_model = onnx.version_converter.convert_version( # type:ignore
- loaded_model, target_opset_version
- )
- onnx.checker.check_model(loaded_model) # type:ignore
+ loaded_model = onnx.version_converter.convert_version(loaded_model, target_opset_version)
+ onnx.checker.check_model(loaded_model)
# Set the IR version if it passed the checking
if target_ir_version is not None:
loaded_model.ir_version = target_ir_version
@@ -541,7 +539,7 @@ class ONNXMixin:
return op
@staticmethod
- def _opset_version(op: onnx.ModelProto) -> Optional[int]: # type:ignore
+ def _opset_version(op: onnx.ModelProto) -> Optional[int]:
"""Return the version of the default (``ai.onnx``) operator set that ``op`` imports, or None."""
for entry in op.opset_import:
if entry.domain in ("", "ai.onnx"):
diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.py
index 33df59c30..6f8ea77e1 100644
--- a/kornia/feature/aliked/aliked.py
+++ b/kornia/feature/aliked/aliked.py
@@ -331,11 +331,11 @@ class DKD(nn.Module):
x_exp = ((patch_scores - max_v) / self.temperature).exp()
x_sum = x_exp.sum(dim=1, keepdim=True)
- xy_residual = x_exp @ self.hw_grid / x_sum # type: ignore[operator]
+ xy_residual = x_exp @ self.hw_grid / x_sum
hw_grid_dist2 = (
torch.norm(
- (self.hw_grid[None, :, :] - xy_residual[:, None, :]) / self.radius, # type: ignore[index]
+ (self.hw_grid[None, :, :] - xy_residual[:, None, :]) / self.radius,
dim=-1,
)
** 2
@@ -361,7 +361,7 @@ class DKD(nn.Module):
# w_i = x_exp_i / sum(x_exp), mu = xy_residual (already computed).
# cov = sum_i w_i (g_i - mu)(g_i - mu)^T -> (N, 2, 2)
W = x_exp / x_sum # (N, K²) normalised weights
- delta = self.hw_grid[None] - xy_residual[:, None] # type: ignore[index] # (N, K², 2)
+ delta = self.hw_grid[None] - xy_residual[:, None] # (N, K², 2)
cov = torch.einsum("ni,nij,nik->njk", W, delta, delta) # (N, 2, 2)
local_affines.append(_affine_from_cov(cov))
else:
@@ -1038,9 +1038,9 @@ class ALIKED(nn.Module):
dkd_out = self.dkd(score_map, return_affine=compute_affine)
if compute_affine:
- keypoints, kptscores, _scoredispersitys, local_affines = dkd_out # type: ignore[misc]
+ keypoints, kptscores, _scoredispersitys, local_affines = dkd_out
else:
- keypoints, kptscores, _scoredispersitys = dkd_out # type: ignore[misc]
+ keypoints, kptscores, _scoredispersitys = dkd_out
local_affines = None
descriptors, _offsets = self.desc_head(feature_map, keypoints)
diff --git a/kornia/feature/dedode/decoder.py b/kornia/feature/dedode/decoder.py
index bb40d29ae..36700c4da 100644
--- a/kornia/feature/dedode/decoder.py
+++ b/kornia/feature/dedode/decoder.py
@@ -30,7 +30,7 @@ class Decoder(nn.Module):
num_prototypes: The number of prototypes for the output head.
"""
- def __init__(self, layers: Any, *args, super_resolution: bool = False, num_prototypes: int = 1, **kwargs) -> None: # type: ignore[no-untyped-def]
+ def __init__(self, layers: Any, *args, super_resolution: bool = False, num_prototypes: int = 1, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.layers = layers
self.scales = self.layers.keys()
@@ -73,7 +73,7 @@ class ConvRefiner(nn.Module):
amp_dtype: The data type for automatic mixed precision.
"""
- def __init__( # type: ignore[no-untyped-def]
+ def __init__(
self,
in_dim=6,
hidden_dim=16,
@@ -108,7 +108,7 @@ class ConvRefiner(nn.Module):
self.amp_dtype = amp_dtype
self.residual = residual
- def create_block( # type: ignore[no-untyped-def]
+ def create_block(
self,
in_dim,
out_dim,
diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.py
index b545a7b78..6d795dfe4 100644
--- a/kornia/feature/dedode/dedode.py
+++ b/kornia/feature/dedode/dedode.py
@@ -318,8 +318,8 @@ class DeDoDe(nn.Module):
# e.g. "L-C4-v2" -> "L", "G-upright" -> "G". All current checkpoints follow this
# convention intentionally so that new variants only need a new URL entry.
model: DeDoDe = cls(
- detector_model=detector_weights[0], # type: ignore[arg-type]
- descriptor_model=descriptor_weights[0], # type: ignore[arg-type]
+ detector_model=detector_weights[0],
+ descriptor_model=descriptor_weights[0],
amp_dtype=amp_dtype,
)
model.detector.load_state_dict(
diff --git a/kornia/feature/dedode/descriptor.py b/kornia/feature/dedode/descriptor.py
index 9ffb3bcdf..9cca7e41c 100644
--- a/kornia/feature/dedode/descriptor.py
+++ b/kornia/feature/dedode/descriptor.py
@@ -28,7 +28,7 @@ class DeDoDeDescriptor(nn.Module):
decoder: The decoder module for descriptor generation.
"""
- def __init__(self, encoder: nn.Module, decoder: nn.Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
+ def __init__(self, encoder: nn.Module, decoder: nn.Module, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.encoder = encoder
self.decoder = decoder
diff --git a/kornia/feature/dedode/detector.py b/kornia/feature/dedode/detector.py
index 04c8c5fc7..49f919746 100644
--- a/kornia/feature/dedode/detector.py
+++ b/kornia/feature/dedode/detector.py
@@ -28,7 +28,7 @@ class DeDoDeDetector(nn.Module):
decoder: The decoder module for probability map generation.
"""
- def __init__(self, encoder: nn.Module, decoder: nn.Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
+ def __init__(self, encoder: nn.Module, decoder: nn.Module, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.encoder = encoder
self.decoder = decoder
@@ -58,4 +58,4 @@ class DeDoDeDetector(nn.Module):
size = sizes[-(idx + 2)]
logits = F.interpolate(logits, size=size, mode="bicubic", align_corners=False)
context = F.interpolate(context.float(), size=size, mode="bilinear", align_corners=False).to(dtype)
- return logits.to(dtype) # type: ignore
+ return logits.to(dtype)
diff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.py
index 55f6f1f8d..9c51e238b 100644
--- a/kornia/feature/dedode/encoder.py
+++ b/kornia/feature/dedode/encoder.py
@@ -42,12 +42,12 @@ class VGG19(nn.Module):
def __init__(self, amp: bool = False, amp_dtype: torch.dtype = torch.float16) -> None:
super().__init__()
- self.layers = nn.ModuleList(vgg19_bn().features[:40]) # type: ignore
+ self.layers = nn.ModuleList(vgg19_bn().features[:40])
# Maxpool layers: 6, 13, 26, 39
self.amp = amp
self.amp_dtype = amp_dtype
- def forward(self, x: torch.Tensor, **kwargs): # type: ignore[no-untyped-def]
+ def forward(self, x: torch.Tensor, **kwargs):
"""Run this DeDoDe module forward.
Args:
@@ -94,7 +94,7 @@ class FrozenDINOv2(nn.Module):
# The backbone keeps the dtype of the checkpoint; `forward` casts it to ``amp_dtype`` once it runs on CUDA.
self.dinov2_vitl14 = [dinov2_vitl14] # ugly hack to not show parameters to DDP
- def forward(self, x: torch.Tensor): # type: ignore[no-untyped-def]
+ def forward(self, x: torch.Tensor):
"""Run this DeDoDe module forward.
``amp_dtype`` is CUDA mixed precision, as in the other DeDoDe components: on a CUDA input with ``amp=True``
@@ -129,7 +129,7 @@ class FrozenDINOv2(nn.Module):
class VGG_DINOv2(nn.Module):
"""Implement a hybrid encoder combining VGG and DINOv2 features."""
- def __init__(self, vgg_kwargs=None, dinov2_kwargs=None): # type: ignore[no-untyped-def]
+ def __init__(self, vgg_kwargs=None, dinov2_kwargs=None):
if (vgg_kwargs is None) or (dinov2_kwargs is None):
raise ValueError("Input kwargs please")
super().__init__()
diff --git a/kornia/feature/dedode/transformer/layers/attention.py b/kornia/feature/dedode/transformer/layers/attention.py
index b2cdaacb6..c5de21c80 100644
--- a/kornia/feature/dedode/transformer/layers/attention.py
+++ b/kornia/feature/dedode/transformer/layers/attention.py
@@ -91,7 +91,7 @@ class MemEffAttention(Attention):
DINOv2 signature. Nothing in kornia passes it, and it must be ``None``.
"""
- def forward(self, x: Tensor, attn_bias=None) -> Tensor: # type: ignore[no-untyped-def]
+ def forward(self, x: Tensor, attn_bias=None) -> Tensor:
"""Run this DeDoDe module forward.
Args:
diff --git a/kornia/feature/dedode/transformer/layers/drop_path.py b/kornia/feature/dedode/transformer/layers/drop_path.py
index 2d00711fc..8d79a767d 100644
--- a/kornia/feature/dedode/transformer/layers/drop_path.py
+++ b/kornia/feature/dedode/transformer/layers/drop_path.py
@@ -36,7 +36,7 @@ def drop_path(x: torch.Tensor, drop_prob: Optional[float] = 0.0, training: bool
drop_path = 0.0
if drop_prob == 0.0 or not training:
return x
- keep_prob = 1.0 - drop_prob # type: ignore
+ keep_prob = 1.0 - drop_prob
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
if keep_prob > 0.0:
diff --git a/kornia/feature/dedode/utils.py b/kornia/feature/dedode/utils.py
index 2ae307c72..aac18b280 100644
--- a/kornia/feature/dedode/utils.py
+++ b/kornia/feature/dedode/utils.py
@@ -39,7 +39,7 @@ def sample_keypoints(
local_density = F.conv2d(local_density_x, weights[..., None], padding=(51 // 2, 0))[:, 0]
scoremap = scoremap * (local_density + 1e-8) ** (-1 / 2)
grid = get_grid(B, H, W, device=device).reshape(B, H * W, 2)
- num_samples = min(num_samples, H * W) if num_samples is not None else H * W # type: ignore
+ num_samples = min(num_samples, H * W) if num_samples is not None else H * W
inds = torch.topk(scoremap.reshape(B, H * W), k=num_samples).indices
kps = torch.gather(grid, dim=1, index=inds[..., None].expand(B, num_samples, 2))
if return_scoremap:
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 7351e60a4..8b5d1932d 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -1011,7 +1011,7 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
"superpoint",
]
- def __init__(self, feature_name: str = "disk", params: Optional[Dict] = None) -> None: # type: ignore
+ def __init__(self, feature_name: str = "disk", params: Optional[Dict] = None) -> None:
feature_name_: str = feature_name.lower()
super().__init__(feature_name_)
self.feature_name = feature_name_
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index e5fc24d71..b7ee1ccd7 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -31,7 +31,7 @@ from kornia.core.utils import is_exporting
from kornia.feature.laf import laf_to_three_points, scale_laf
-def math_clamp(x, min_, max_): # type: ignore
+def math_clamp(x, min_, max_):
"""Clamp a value to lie within [min, max]."""
return min(max(x, min_), max_)
@@ -251,9 +251,9 @@ class CrossBlock(nn.Module):
if flash:
self.flash = Attention(True)
else:
- self.flash = None # type: ignore
+ self.flash = None
- def map_(self, func: Callable, x0: torch.Tensor, x1: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
+ def map_(self, func: Callable, x0: torch.Tensor, x1: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
"""Apply the same function to descriptor tensors from both images.
Args:
@@ -313,7 +313,7 @@ class TransformerLayer(nn.Module):
to update local feature descriptors.
"""
- def __init__(self, *args, **kwargs): # type: ignore
+ def __init__(self, *args, **kwargs):
super().__init__()
self.self_attn = SelfBlock(*args, **kwargs)
self.cross_attn = CrossBlock(*args, **kwargs)
@@ -457,7 +457,7 @@ _KEYPOINT_RANGE_MSG = (
def _check_keypoints_normalized(kpts: torch.Tensor) -> None:
"""Check that keypoints lie in [-1, 1]; skipped under export, where reading the data is not possible."""
if not is_exporting():
- KORNIA_CHECK(torch.all(kpts >= -1).item() and torch.all(kpts <= 1).item(), _KEYPOINT_RANGE_MSG) # type: ignore
+ KORNIA_CHECK(torch.all(kpts >= -1).item() and torch.all(kpts <= 1).item(), _KEYPOINT_RANGE_MSG)
def _select_pair(image: Dict[str, Any], k: int, b: int) -> Dict[str, Any]:
@@ -610,7 +610,7 @@ class LightGlue(nn.Module):
},
}
- def __init__(self, features: str = "superpoint", **conf_) -> None: # type: ignore
+ def __init__(self, features: str = "superpoint", **conf_) -> None:
super().__init__()
self.conf = conf = SimpleNamespace(**{**self.default_conf, **conf_})
if features is not None:
@@ -622,7 +622,7 @@ class LightGlue(nn.Module):
if conf.input_dim != conf.descriptor_dim:
self.input_proj = nn.Linear(conf.input_dim, conf.descriptor_dim, bias=True)
else:
- self.input_proj = nn.Identity() # type: ignore
+ self.input_proj = nn.Identity()
head_dim = conf.descriptor_dim // conf.num_heads
self.posenc = LearnableFourierPositionalEncoding(
@@ -715,13 +715,13 @@ class LightGlue(nn.Module):
):
torch._inductor.cudagraph_mark_step_begin()
for i in range(self.conf.n_layers):
- self.transformers[i].masked_forward = torch.compile( # type: ignore[assignment]
+ self.transformers[i].masked_forward = torch.compile(
self.transformers[i].masked_forward, mode=mode, fullgraph=True
)
- self.static_lengths = static_lengths # type: ignore
+ self.static_lengths = static_lengths
- def forward(self, data: dict) -> dict: # type: ignore
+ def forward(self, data: dict) -> dict:
"""Match keypoints and descriptors between two images.
Input (dict):
@@ -755,7 +755,7 @@ class LightGlue(nn.Module):
with torch.autocast(enabled=self.conf.mp, device_type=device_type, dtype=dtype):
return self._forward(data)
- def _forward(self, data: dict) -> dict: # type: ignore
+ def _forward(self, data: dict) -> dict:
data0, data1 = data["image0"], data["image1"]
kpts0, kpts1 = data0["keypoints"], data1["keypoints"]
b, m, _ = kpts0.shape
@@ -874,7 +874,7 @@ class LightGlue(nn.Module):
# Pruning runs here for a single pair only: a batch that would prune runs its pairs one at a time.
if do_point_pruning and desc0.shape[-2] > pruning_th:
scores0 = self.log_assignment[i].get_matchability(desc0)
- prunemask0 = self.get_pruning_mask(token0, scores0, i) # type: ignore
+ prunemask0 = self.get_pruning_mask(token0, scores0, i)
keep0 = torch.where(prunemask0)[1]
ind0 = ind0.index_select(1, keep0)
desc0 = desc0.index_select(1, keep0)
@@ -882,7 +882,7 @@ class LightGlue(nn.Module):
prune0[:, ind0] += 1
if do_point_pruning and desc1.shape[-2] > pruning_th:
scores1 = self.log_assignment[i].get_matchability(desc1)
- prunemask1 = self.get_pruning_mask(token1, scores1, i) # type: ignore
+ prunemask1 = self.get_pruning_mask(token1, scores1, i)
keep1 = torch.where(prunemask1)[1]
ind1 = ind1.index_select(1, keep1)
desc1 = desc1.index_select(1, keep1)
@@ -960,7 +960,7 @@ class LightGlue(nn.Module):
"prune1": prune1,
}
- def _forward_pairs(self, data0: dict, data1: dict, b: int) -> dict: # type: ignore
+ def _forward_pairs(self, data0: dict, data1: dict, b: int) -> dict:
"""Match the ``b`` pairs of a batch one at a time and stack their outputs.
The pairs have no common ``log_assignment``, since each covers the points its pair kept, and ``stop`` is the
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 9ae0a4b71..e6da979ee 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -167,14 +167,14 @@ class OnnxLightGlue:
# Normalize keypoints.
size0, size1 = data0.get("image_size"), data1.get("image_size")
- size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1] # type: ignore
- size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1] # type: ignore
+ size0 = size0 if size0 is not None else data0["image"].shape[-2:][::-1]
+ size1 = size1 if size1 is not None else data1["image"].shape[-2:][::-1]
- kpts0 = normalize_keypoints(kpts0_, size=size0) # type: ignore
- kpts1 = normalize_keypoints(kpts1_, size=size1) # type: ignore
+ kpts0 = normalize_keypoints(kpts0_, size=size0)
+ kpts1 = normalize_keypoints(kpts1_, size=size1)
- KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), _KEYPOINT_RANGE_MSG) # type: ignore
- KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), _KEYPOINT_RANGE_MSG) # type: ignore
+ KORNIA_CHECK(torch.all(kpts0 >= -1).item() and torch.all(kpts0 <= 1).item(), _KEYPOINT_RANGE_MSG)
+ KORNIA_CHECK(torch.all(kpts1 >= -1).item() and torch.all(kpts1 <= 1).item(), _KEYPOINT_RANGE_MSG)
# Inference.
lightglue_inputs = {"kpts0": kpts0, "kpts1": kpts1, "desc0": desc0, "desc1": desc1}
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index f4e22388a..25c692f17 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -295,7 +295,7 @@ class LoFTR(nn.Module):
raise TypeError(f"Expected torch.Tensor for item `{k}`. Got {type(_d)}")
return out
- def load_state_dict(self, state_dict: dict[str, Any], *args: Any, **kwargs: Any) -> Any: # type: ignore[override]
+ def load_state_dict(self, state_dict: dict[str, Any], *args: Any, **kwargs: Any) -> Any:
"""Load a checkpoint state dictionary into the module.
Args:
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 4a9f47cd3..16748d6b8 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -324,7 +324,7 @@ class CoarseMatching(nn.Module):
# silently upcast the padded mconf below via torch.cat's type promotion.
mconf_gt = torch.zeros(len(data["spv_b_ids"]), device=_device, dtype=mconf.dtype)
- b_ids, i_ids, j_ids, mconf = ( # type: ignore
+ b_ids, i_ids, j_ids, mconf = (
torch.cat([x[pred_indices], y[gt_pad_indices]], dim=0)
for x, y in zip(
[b_ids, i_ids, j_ids, mconf],
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 9871f5b27..575d5cf6f 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -783,7 +783,7 @@ class GeometryAwareDescriptorMatcher(nn.Module):
params.update(self.params)
out = match_fginn(desc1, desc2, lafs1, lafs2, params["th"], params["spatial_th"], params["mutual"])
elif self.match_mode == "adalam":
- out = match_adalam(desc1, desc2, lafs1, lafs2, config=self.params) # type: ignore[arg-type]
+ out = match_adalam(desc1, desc2, lafs1, lafs2, config=self.params)
else:
raise NotImplementedError
return out
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
index 29de1ada7..12f00a921 100644
--- a/kornia/feature/sold2/backbones.py
+++ b/kornia/feature/sold2/backbones.py
@@ -196,12 +196,12 @@ class Hourglass(nn.Module):
return nn.ModuleList(hgl)
def _hour_glass_forward(self, n: int, x: torch.Tensor) -> torch.Tensor:
- up1 = self.hg[n - 1][0](x) # type: ignore[index]
+ up1 = self.hg[n - 1][0](x)
low1 = F.max_pool2d(x, 2, stride=2)
- low1 = self.hg[n - 1][1](low1) # type: ignore[index]
+ low1 = self.hg[n - 1][1](low1)
- low2 = self._hour_glass_forward(n - 1, low1) if n > 1 else self.hg[n - 1][3](low1) # type: ignore[index]
- low3 = self.hg[n - 1][2](low2) # type: ignore[index]
+ low2 = self._hour_glass_forward(n - 1, low1) if n > 1 else self.hg[n - 1][3](low1)
+ low3 = self.hg[n - 1][2](low2)
up2 = F.interpolate(low3, size=up1.shape[2:])
return up1 + up2
diff --git a/kornia/filters/dissolving.py b/kornia/filters/dissolving.py
index 215fa8c67..96e05039f 100644
--- a/kornia/filters/dissolving.py
+++ b/kornia/filters/dissolving.py
@@ -235,7 +235,7 @@ class StableDiffusionDissolving(ImageModule):
DDIMScheduler = diffusers.DDIMScheduler
# Load the scheduler and model pipeline from diffusers library
- scheduler = DDIMScheduler( # type:ignore
+ scheduler = DDIMScheduler(
beta_start=0.00085,
beta_end=0.012,
beta_schedule="scaled_linear",
@@ -257,17 +257,17 @@ class StableDiffusionDissolving(ImageModule):
if version == "1.4":
StableDiffusionPipeline = diffusers.StableDiffusionPipeline
- self._sdm_model = StableDiffusionPipeline.from_pretrained( # type:ignore
+ self._sdm_model = StableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4", scheduler=scheduler, **kwargs
)
elif version == "1.5":
StableDiffusionPipeline = diffusers.StableDiffusionPipeline
- self._sdm_model = StableDiffusionPipeline.from_pretrained( # type:ignore
+ self._sdm_model = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5", scheduler=scheduler, **kwargs
)
elif version == "xl":
StableDiffusionXLPipeline = diffusers.StableDiffusionXLPipeline
- self._sdm_model = StableDiffusionXLPipeline.from_pretrained( # type:ignore
+ self._sdm_model = StableDiffusionXLPipeline.from_pretrained(
"stabilityai/stable-diffusion-xl-base-1.0", scheduler=scheduler, **kwargs
)
is_sdxl = True
diff --git a/kornia/geometry/_ransac_program.py b/kornia/geometry/_ransac_program.py
index 3e184e8f4..01f1dc1f2 100644
--- a/kornia/geometry/_ransac_program.py
+++ b/kornia/geometry/_ransac_program.py
@@ -272,10 +272,10 @@ def build_lm_program(model_type: str, score_type: str, max_lo_iters: int, refine
pad_scores = torch.full((_POOL,), -2.0, dtype=torch.float64, device=device)
pad_counts = torch.zeros(_POOL, dtype=torch.int64, device=device)
- def cond(drawn, batch, max_samples, best_score, pool, pool_scores): # type: ignore[no-untyped-def]
+ def cond(drawn, batch, max_samples, best_score, pool, pool_scores):
return drawn < max_samples
- def body(drawn, batch, max_samples, best_score, pool, pool_scores): # type: ignore[no-untyped-def]
+ def body(drawn, batch, max_samples, best_score, pool, pool_scores):
current = torch.minimum(batch, max_samples - drawn)
size = current.item()
torch._check(size >= 1)
@@ -543,11 +543,11 @@ def _load_or_save_artifact(
with _compiled_autocast_disabled(), _dynamo_config():
try:
- artifact = compiled.aot_compile((example_inputs, {})) # type: ignore[attr-defined]
+ artifact = compiled.aot_compile((example_inputs, {}))
except TensorifyScalarRestartAnalysis:
# torch.compile restarts its analysis once when a Python scalar cannot become a tensor; aot_compile
# (torch 2.14) raises instead, and succeeds when called again.
- artifact = compiled.aot_compile((example_inputs, {})) # type: ignore[attr-defined]
+ artifact = compiled.aot_compile((example_inputs, {}))
directory = os.path.dirname(path)
os.makedirs(directory, exist_ok=True)
descriptor, temporary = tempfile.mkstemp(prefix=".tmp-", suffix=".bin", dir=directory)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index dfd25d46a..e27114675 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -1096,9 +1096,7 @@ class VideoBoxes(Boxes):
temporal_channel_size: int
@classmethod
- def from_tensor( # type: ignore[override]
- cls, boxes: torch.Tensor | list[torch.Tensor], validate_boxes: bool = True
- ) -> VideoBoxes:
+ def from_tensor(cls, boxes: torch.Tensor | list[torch.Tensor], validate_boxes: bool = True) -> VideoBoxes:
r"""Create :class:`VideoBoxes` from a video box tensor.
Args:
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index ed81d994e..b39f3dedc 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -316,7 +316,7 @@ class VideoKeypoints(Keypoints):
out.temporal_channel_size = temporal_channel_size
return out
- def to_tensor(self) -> torch.torch.Tensor: # type: ignore[override]
+ def to_tensor(self) -> torch.torch.Tensor:
out = super().to_tensor(as_padded_sequence=False)
out = cast(torch.torch.Tensor, out)
batch_size = out.shape[0] // self.temporal_channel_size
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 22271a361..43091b915 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -275,7 +275,7 @@ class So3(nn.Module):
KORNIA_CHECK_SHAPE(v, ["*", "3"])
if isinstance(v, torch.Tensor):
# TODO: Figure out why mypy think `v` can be a Vector3 which didn't allow ellipsis on index
- a, b, c = v[..., 0], v[..., 1], v[..., 2] # type: ignore[index]
+ a, b, c = v[..., 0], v[..., 1], v[..., 2]
else:
a, b, c = v.x, v.y, v.z
z = torch.zeros_like(a)
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 7a94fbe98..16aa662f2 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -708,12 +708,12 @@ class CenterCrop2D(nn.Module):
input,
transform[:, :2, :],
self.size,
- self.flags["resample"].name.lower(), # type:ignore
+ self.flags["resample"].name.lower(),
"zeros",
- self.flags["align_corners"], # type:ignore
+ self.flags["align_corners"],
)
if self.flags["cropping_mode"] == "slice": # uses advanced slicing to crop
- return crop_by_indices(input, self.points_src.expand(batch_size, -1, -1).to(input), self.flags["size"]) # type:ignore
+ return crop_by_indices(input, self.points_src.expand(batch_size, -1, -1).to(input), self.flags["size"])
raise NotImplementedError(f"Not supported type: {self.flags['cropping_mode']}.")
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index fd629f5b6..653ab3854 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -20,7 +20,7 @@ from typing import Optional, Tuple, Union, cast
import torch
from kornia.core.check import KORNIA_CHECK
-from kornia.core.tensor_wrapper import TensorWrapper, _wrap # type: ignore[attr-defined]
+from kornia.core.tensor_wrapper import TensorWrapper, _wrap
from kornia.geometry.conversions import _normalize_last_dim
from kornia.geometry.linalg import batched_dot_product, batched_squared_norm
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.py
index 5c929aba6..1f0387f33 100644
--- a/kornia/models/_hf_models/hf_onnx_community.py
+++ b/kornia/models/_hf_models/hf_onnx_community.py
@@ -74,7 +74,7 @@ class HFONNXComunnityModelLoader:
def load_model(
self, download: bool = True, io_name_mapping: Optional[dict[str, str]] = None, **kwargs: Any
- ) -> onnx.ModelProto: # type:ignore
+ ) -> onnx.ModelProto:
"""Load the ONNX model file from the configured onnx-community repository.
Args:
@@ -104,7 +104,7 @@ class HFONNXComunnityModelLoader:
suffix=".onnx_data",
**kwargs,
)
- onnx_model = onnx.load(file_path) # type:ignore
+ onnx_model = onnx.load(file_path)
if io_name_mapping is not None:
onnx_model = io_name_conversion(onnx_model, io_name_mapping)
@@ -154,9 +154,9 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
def __init__(
self,
- model: onnx.ModelProto, # type: ignore
- pre_processor: Optional[onnx.ModelProto] = None, # type: ignore
- post_processor: Optional[onnx.ModelProto] = None, # type: ignore
+ model: onnx.ModelProto,
+ pre_processor: Optional[onnx.ModelProto] = None,
+ post_processor: Optional[onnx.ModelProto] = None,
name: Optional[str] = None,
auto_ir_version_conversion: bool = True,
io_maps: Optional[list[tuple[str, str]]] = None,
@@ -194,7 +194,7 @@ class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):
save: bool = True,
additional_metadata: Optional[list[tuple[str, str]]] = None,
**kwargs: Any,
- ) -> onnx.ModelProto: # type:ignore
+ ) -> onnx.ModelProto:
"""Export a depth estimation model to ONNX format.
Args:
diff --git a/kornia/models/base.py b/kornia/models/base.py
index 14d114eb5..db4365390 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -70,7 +70,7 @@ class ModelBaseMixin:
def _tensor_to_type(
self, output: Union[torch.Tensor, List[torch.Tensor]], output_type: str, is_batch: bool = False
- ) -> Union[torch.Tensor, List[torch.Tensor], List[Image.Image]]: # type: ignore
+ ) -> Union[torch.Tensor, List[torch.Tensor], List[Image.Image]]:
"""Convert the output tensor to the desired type.
Args:
diff --git a/kornia/models/depth_estimation/base.py b/kornia/models/depth_estimation/base.py
index 9e95dc01f..cfd3da838 100644
--- a/kornia/models/depth_estimation/base.py
+++ b/kornia/models/depth_estimation/base.py
@@ -33,7 +33,7 @@ class DepthEstimation(HFONNXComunnityModel):
name: str = "depth_estimation"
- def __call__(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]: # type: ignore[override]
+ def __call__(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]:
"""Detect objects in a given list of images.
Args:
@@ -69,7 +69,7 @@ class DepthEstimation(HFONNXComunnityModel):
output_type: str = "torch",
depth_type: str = "relative",
max_depth: int = 80,
- ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]: # type: ignore
+ ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]:
"""Draw the segmentation results.
Args:
diff --git a/kornia/models/efficient_vit/backbone.py b/kornia/models/efficient_vit/backbone.py
index b8cb57df6..6b86e5f0a 100644
--- a/kornia/models/efficient_vit/backbone.py
+++ b/kornia/models/efficient_vit/backbone.py
@@ -25,7 +25,7 @@ from typing import Any
import torch
from torch import nn
-from kornia.models.efficient_vit.nn.ops import ( # type: ignore
+from kornia.models.efficient_vit.nn.ops import (
ConvLayer,
DSConv,
EfficientViTBlock,
diff --git a/kornia/models/efficient_vit/nn/act.py b/kornia/models/efficient_vit/nn/act.py
index 5cf39f7b8..38f152739 100644
--- a/kornia/models/efficient_vit/nn/act.py
+++ b/kornia/models/efficient_vit/nn/act.py
@@ -33,7 +33,7 @@ REGISTERED_ACT_DICT: dict[str, type[nn.Module]] = {
"relu6": nn.ReLU6,
"hswish": nn.Hardswish,
"silu": nn.SiLU,
- "gelu": partial(nn.GELU, approximate="tanh"), # type: ignore
+ "gelu": partial(nn.GELU, approximate="tanh"),
}
diff --git a/kornia/models/efficient_vit/nn/ops.py b/kornia/models/efficient_vit/nn/ops.py
index 371e5f6d4..d95a8df3a 100644
--- a/kornia/models/efficient_vit/nn/ops.py
+++ b/kornia/models/efficient_vit/nn/ops.py
@@ -19,7 +19,6 @@
# Han Cai, Junyan Li, Muyan Hu, Chuang Gan, Song Han
# International Conference on Computer Vision (ICCV), 2023
-# type: ignore
from __future__ import annotations
import torch
diff --git a/kornia/models/efficient_vit/utils/network.py b/kornia/models/efficient_vit/utils/network.py
index 6d8df4b27..623aecb7a 100644
--- a/kornia/models/efficient_vit/utils/network.py
+++ b/kornia/models/efficient_vit/utils/network.py
@@ -27,7 +27,7 @@ from typing import Any, Union
def get_same_padding(kernel_size: Union[int, tuple[int, ...]]) -> Union[int, tuple[int, ...]]:
"""Return padding values."""
if isinstance(kernel_size, (tuple,)):
- return tuple([get_same_padding(ks) for ks in kernel_size]) # type: ignore
+ return tuple([get_same_padding(ks) for ks in kernel_size])
# assert kernel_size % 2 > 0, "kernel size should be odd number"
return kernel_size // 2
diff --git a/kornia/models/rt_detr/model.py b/kornia/models/rt_detr/model.py
index fbcfcb8af..c67bad6e9 100644
--- a/kornia/models/rt_detr/model.py
+++ b/kornia/models/rt_detr/model.py
@@ -271,7 +271,7 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
return re.sub(".branch2c.", ".convs.branch2c.", new_name)
def _state_dict_proc(state_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:
- state_dict = state_dict["ema"]["module"] # type:ignore
+ state_dict = state_dict["ema"]["module"]
new_state_dict = {}
# Apply the regex-based mapping function to each key
diff --git a/kornia/models/segmentation/base.py b/kornia/models/segmentation/base.py
index f1f62f897..67107698c 100644
--- a/kornia/models/segmentation/base.py
+++ b/kornia/models/segmentation/base.py
@@ -211,7 +211,7 @@ class SemanticSegmentation(ModelBase):
output_type: str = "torch",
colormap: str = "random",
manual_seed: int = 2147,
- ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]: # type: ignore
+ ) -> Union[torch.Tensor, list[torch.Tensor], list[Image.Image]]:
"""Visualize the segmentation masks.
Args:
diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.py
index 4114df463..d5070cab1 100644
--- a/kornia/models/tiny_vit.py
+++ b/kornia/models/tiny_vit.py
@@ -628,7 +628,7 @@ class TinyViT(nn.Module):
if self.mobile_sam:
# MobileSAM
x = x.unflatten(1, (self.feat_size, self.feat_size)).permute(0, 3, 1, 2)
- x = self.neck(x) # type: ignore
+ x = self.neck(x)
else:
# classification
x = x.mean(1)
diff --git a/kornia/onnx/module.py b/kornia/onnx/module.py
index aea5dc4ad..077bfbabb 100644
--- a/kornia/onnx/module.py
+++ b/kornia/onnx/module.py
@@ -45,9 +45,9 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
def __init__(
self,
- op: Union[onnx.ModelProto, str], # type:ignore
+ op: Union[onnx.ModelProto, str],
providers: Optional[list[str]] = None,
- session_options: Optional[ort.SessionOptions] = None, # type:ignore
+ session_options: Optional[ort.SessionOptions] = None,
cache_dir: Optional[str] = None,
target_ir_version: Optional[int] = None,
target_opset_version: Optional[int] = None,
@@ -62,7 +62,7 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
def create_session(
self, providers: list[str] | None = None, session_options: Any | None = None
- ) -> ort.InferenceSession: # type: ignore
+ ) -> ort.InferenceSession:
"""Create an ONNX Runtime session for the wrapped model graph.
Args:
@@ -90,7 +90,7 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
"""
return super()._export(self.op, file_path, **kwargs)
- def add_metadata(self, additional_metadata: Optional[list[tuple[str, str]]] = None) -> onnx.ModelProto: # type:ignore
+ def add_metadata(self, additional_metadata: Optional[list[tuple[str, str]]] = None) -> onnx.ModelProto:
"""Attach metadata entries to the wrapped ONNX model graph.
Args:
@@ -103,7 +103,7 @@ class ONNXModule(ONNXMixin, ONNXRuntimeMixin):
return super()._add_metadata(self.op, additional_metadata)
-def load(model_name: Union[onnx.ModelProto, str]) -> ONNXModule: # type:ignore
+def load(model_name: Union[onnx.ModelProto, str]) -> ONNXModule:
"""Load an ONNX model from either a file path or HuggingFace.
The loaded model is an ONNXModule object, of which you may run the model with
diff --git a/kornia/onnx/sequential.py b/kornia/onnx/sequential.py
index 759d56fb8..48b77b2d8 100644
--- a/kornia/onnx/sequential.py
+++ b/kornia/onnx/sequential.py
@@ -52,9 +52,9 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
def __init__(
self,
- *args: Union[onnx.ModelProto, str], # type:ignore
+ *args: Union[onnx.ModelProto, str],
providers: Optional[list[str]] = None,
- session_options: Optional[ort.SessionOptions] = None, # type:ignore
+ session_options: Optional[ort.SessionOptions] = None,
io_maps: Optional[list[tuple[str, str]]] = None,
cache_dir: Optional[str] = None,
auto_ir_version_conversion: bool = False,
@@ -72,10 +72,10 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
def _auto_version_conversion(
self,
- *args: onnx.ModelProto, # type:ignore
+ *args: onnx.ModelProto,
target_ir_version: Optional[int] = None,
target_opset_version: Optional[int] = None,
- ) -> list[onnx.ModelProto]: # type:ignore
+ ) -> list[onnx.ModelProto]:
"""Automatic conversion of the model's IR/OPSET version to the given target version.
If `target_ir_version` is not provided, the model is converted to 9 by default.
@@ -102,7 +102,7 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
op_list.append(op)
return op_list
- def combine(self, io_maps: list[tuple[str, str]] | None = None) -> onnx.ModelProto: # type: ignore
+ def combine(self, io_maps: list[tuple[str, str]] | None = None) -> onnx.ModelProto:
"""Combine the stored ONNX operators into one executable graph.
Args:
@@ -119,7 +119,7 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
def create_session(
self, providers: list[str] | None = None, session_options: Any | None = None
- ) -> ort.InferenceSession: # type: ignore
+ ) -> ort.InferenceSession:
"""Create an ONNX Runtime session for the combined graph.
Args:
@@ -142,7 +142,7 @@ class ONNXSequential(ONNXMixin, ONNXRuntimeMixin):
"""
return super()._export(self._combined_op, file_path, **kwargs)
- def add_metadata(self, additional_metadata: Optional[list[tuple[str, str]]] = None) -> onnx.ModelProto: # type:ignore
+ def add_metadata(self, additional_metadata: Optional[list[tuple[str, str]]] = None) -> onnx.ModelProto:
"""Attach metadata entries to the combined ONNX graph.
Args:
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index f86092714..4d1c40e6e 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -131,7 +131,7 @@ class ONNXLoader(CachedDownloader):
raise RuntimeError(f"File `{url}` not found.")
@classmethod
- def load_model(cls, model_name: str, download: bool = True, with_data: bool = False, **kwargs) -> onnx.ModelProto: # type:ignore
+ def load_model(cls, model_name: str, download: bool = True, with_data: bool = False, **kwargs) -> onnx.ModelProto:
"""Load an ONNX model from the local cache or downloads it from Hugging Face if necessary.
Args:
@@ -172,7 +172,7 @@ class ONNXLoader(CachedDownloader):
if with_data:
url_data = f"https://huggingface.co/kornia/ONNX_models/resolve/main/{model_name}.onnx_data"
cls.download_to_cache(url_data, name, download=download, suffix=".onnx_data", **kwargs)
- return onnx.load(file_path) # type:ignore
+ return onnx.load(file_path)
if model_name.startswith(("http://", "https://")):
name = _url_cache_name(model_name)
@@ -182,10 +182,10 @@ class ONNXLoader(CachedDownloader):
parts = urlsplit(model_name)
url_data = urlunsplit(parts._replace(path=_onnx_data_name(parts.path)))
cls.download_to_cache(url_data, _onnx_data_name(name), download=download, suffix=".onnx_data", **kwargs)
- return onnx.load(file_path) # type:ignore
+ return onnx.load(file_path)
if os.path.exists(model_name):
- return onnx.load(model_name) # type:ignore
+ return onnx.load(model_name)
raise ValueError(f"File {model_name} not found")
@@ -228,9 +228,9 @@ class ONNXLoader(CachedDownloader):
def io_name_conversion(
- onnx_model: onnx.ModelProto, # type:ignore
+ onnx_model: onnx.ModelProto,
io_name_mapping: dict[str, str],
-) -> onnx.ModelProto: # type:ignore
+) -> onnx.ModelProto:
"""Convert the input and output names of an ONNX model to 'input' and 'output'.
Args:
@@ -265,9 +265,9 @@ def io_name_conversion(
def add_metadata(
- onnx_model: onnx.ModelProto, # type: ignore
+ onnx_model: onnx.ModelProto,
additional_metadata: Optional[list[tuple[str, str]]] = None,
-) -> onnx.ModelProto: # type: ignore
+) -> onnx.ModelProto:
"""Add metadata to an ONNX model.
The metadata includes the source library (set to "kornia"), the version of kornia,
diff --git a/pyproject.toml b/pyproject.toml
index f7075c344..ae5c1d258 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -418,6 +418,10 @@ name = "Breaking changes"
include = ["kornia"]
exclude = ["tests", "docs", "conftest.py"]
+[tool.ty.rules]
+# A `type: ignore` that suppresses nothing is an error, so dead ones do not pile up again (#2445)
+unused-ignore-comment = "error"
+
[[tool.ty.overrides]]
include = ["kornia"]