Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: finish RET505 cleanup and enforce resolved return rules (#4660)

Daniele Lorufa7dc71d2f68
diff --git a/kornia/color/utils.py b/kornia/color/utils.py
index a6e57d980..bd335a524 100644
--- a/kornia/color/utils.py
+++ b/kornia/color/utils.py
@@ -60,14 +60,13 @@ def _apply_linear_transformation(
return out.contiguous()
# BRANCH 2: GPU/Accelerators (Conv2d)
- else:
- # Reshape for conv2d: (B*..., C, H, W)
- input_flat = image_compute.reshape(-1, 3, input_shape[-2], input_shape[-1])
+ # Reshape for conv2d: (B*..., C, H, W)
+ input_flat = image_compute.reshape(-1, 3, input_shape[-2], input_shape[-1])
- weight = kernel_compute.view(3, 3, 1, 1)
- out_flat = F.conv2d(input_flat, weight, bias=bias_compute)
+ weight = kernel_compute.view(3, 3, 1, 1)
+ out_flat = F.conv2d(input_flat, weight, bias=bias_compute)
- # Unflatten back to original shape
- out = out_flat.reshape(input_shape)
+ # Unflatten back to original shape
+ out = out_flat.reshape(input_shape)
return out
diff --git a/kornia/constants.py b/kornia/constants.py
index afaf39965..6348b4af1 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -39,7 +39,7 @@ class _KORNIA_EnumMeta(EnumMeta):
if isinstance(other, str):
return any(val.name.upper() == other.upper() for val in self)
- elif isinstance(other, int):
+ if isinstance(other, int):
return any(val.value == other for val in self)
return any(val == other for val in self)
@@ -52,10 +52,10 @@ def _get(cls: Type[_T], value: TKEnum[_T]) -> _T:
if isinstance(value, str):
return cls[value.upper()]
- elif isinstance(value, int):
+ if isinstance(value, int):
return cls(value)
- elif isinstance(value, cls):
+ if isinstance(value, cls):
return value
raise TypeError(
@@ -115,16 +115,16 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):
if isinstance(value, torch.dtype):
return cls[str(value).upper()[6:]]
- elif isinstance(value, torch.Tensor):
+ if isinstance(value, torch.Tensor):
return cls(int(value.item()))
- elif isinstance(value, str):
+ if isinstance(value, str):
return cls[value.upper()]
- elif isinstance(value, int):
+ if isinstance(value, int):
return cls(value)
- elif isinstance(value, cls):
+ if isinstance(value, cls):
return value
raise TypeError(f"Invalid identifier {value} with type {type(value)}.")
@@ -136,16 +136,16 @@ class DType(Enum, metaclass=_KORNIA_EnumMeta):
if data == DType.INT64:
return torch.long
- elif data == DType.FLOAT16:
+ if data == DType.FLOAT16:
return torch.float16
- elif data == DType.FLOAT32:
+ if data == DType.FLOAT32:
return torch.float32
- elif data == DType.FLOAT64:
+ if data == DType.FLOAT64:
return torch.float64
- elif data == DType.BFLOAT16:
+ if data == DType.BFLOAT16:
return torch.bfloat16
raise ValueError
diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.py
index 92e28dd68..0904ab3a5 100644
--- a/kornia/contrib/kmeans.py
+++ b/kornia/contrib/kmeans.py
@@ -91,8 +91,7 @@ class KMeans:
return self._final_cluster_centers
if isinstance(self._cluster_centers, torch.Tensor):
return self._cluster_centers
- else:
- raise TypeError("Model has not been fit to a dataset")
+ raise TypeError("Model has not been fit to a dataset")
@property
def cluster_assignments(self) -> torch.Tensor:
@@ -108,8 +107,7 @@ class KMeans:
"""
if isinstance(self._final_cluster_assignments, torch.Tensor):
return self._final_cluster_assignments
- else:
- raise TypeError("Model has not been fit to a dataset")
+ raise TypeError("Model has not been fit to a dataset")
def _initialise_cluster_centers(self, X: torch.Tensor, num_clusters: int) -> torch.Tensor:
"""Chooses num_cluster points from X as the initial cluster centers.
diff --git a/kornia/core/_compat.py b/kornia/core/_compat.py
index 9ebc937d4..274bdc116 100644
--- a/kornia/core/_compat.py
+++ b/kornia/core/_compat.py
@@ -217,13 +217,13 @@ def deprecated(
class_wrapper.__doc__ = func.__doc__
class_wrapper.__annotations__ = getattr(func, "__annotations__", {})
return class_wrapper
- else:
- # For functions, use @wraps normally
- @wraps(func)
- def wrapper(*args: Any, **kwargs: Any) -> Any:
- _emit_deprecation_warning(name, replace_with, version, extra_reason)
- return func(*args, **kwargs)
- return wrapper
+ # For functions, use @wraps normally
+ @wraps(func)
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
+ _emit_deprecation_warning(name, replace_with, version, extra_reason)
+ return func(*args, **kwargs)
+
+ return wrapper
return _deprecated
diff --git a/kornia/core/mixin/image_module.py b/kornia/core/mixin/image_module.py
index 14aeef8d4..92828a4b5 100644
--- a/kornia/core/mixin/image_module.py
+++ b/kornia/core/mixin/image_module.py
@@ -180,11 +180,10 @@ class ImageModuleMixIn:
if x.dim() == 3:
x = x.permute(1, 2, 0)
return Image.fromarray(x.byte().numpy()) # type: ignore
- elif x.dim() == 4:
+ if x.dim() == 4:
x = x.permute(0, 2, 3, 1)
return [Image.fromarray(_x.byte().numpy()) for _x in x] # type: ignore
- else:
- raise NotImplementedError
+ raise NotImplementedError
if isinstance(x, np.ndarray): # type: ignore
raise NotImplementedError
if isinstance(x, Image.Image): # type: ignore
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index 583e49da8..4fd55bfa9 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -89,8 +89,7 @@ def get_cuda_or_mps_device_if_available() -> torch.device:
"""
if sys.platform == "darwin" and platform.machine() == "arm64":
return get_mps_device_if_available()
- else:
- return get_cuda_device_if_available()
+ return get_cuda_device_if_available()
def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:
@@ -421,8 +420,7 @@ def is_autocast_enabled(both: bool = True) -> bool:
if both:
if torch_version_ge(2, 4):
return torch.is_autocast_enabled() or torch.is_autocast_enabled("cpu")
- else:
- return torch.is_autocast_enabled() or torch.is_autocast_cpu_enabled()
+ return torch.is_autocast_enabled() or torch.is_autocast_cpu_enabled()
return torch.is_autocast_enabled()
@@ -492,12 +490,11 @@ def dataclass_to_dict(obj: Any) -> Any:
"""Recursively convert dataclass instances to dictionaries."""
if is_dataclass(obj) and not isinstance(obj, type):
return {key: dataclass_to_dict(value) for key, value in asdict(obj).items()}
- elif isinstance(obj, list | tuple):
+ if isinstance(obj, list | tuple):
return type(obj)(dataclass_to_dict(item) for item in obj)
- elif isinstance(obj, dict):
+ if isinstance(obj, dict):
return {key: dataclass_to_dict(value) for key, value in obj.items()}
- else:
- return obj
+ return obj
T = TypeVar("T")
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index fb900d5a8..69b07db5d 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -387,8 +387,7 @@ def adalam_core(
idxs, out_scores = _no_match(scores1)
if return_dist:
return idxs, out_scores
- else:
- return idxs
+ return idxs
# Format neighborhoods for parallel RANSACs
im1loc, im2loc, ransidx, tokp1, tokp2 = extract_local_patterns(
diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.py
index 186f70f01..dbd2fe2fc 100644
--- a/kornia/feature/dedode/transformer/dinov2.py
+++ b/kornia/feature/dedode/transformer/dinov2.py
@@ -358,8 +358,7 @@ class DinoVisionTransformer(nn.Module):
ret = self.forward_features(*args, **kwargs)
if is_training:
return ret
- else:
- return self.head(ret["x_norm_clstoken"])
+ return self.head(ret["x_norm_clstoken"])
def init_weights_vit_timm(module: nn.Module, name: str = ""):
diff --git a/kornia/feature/dedode/transformer/layers/dino_head.py b/kornia/feature/dedode/transformer/layers/dino_head.py
index 7dddd4350..3f85ba3a0 100644
--- a/kornia/feature/dedode/transformer/layers/dino_head.py
+++ b/kornia/feature/dedode/transformer/layers/dino_head.py
@@ -83,15 +83,14 @@ class DINOHead(nn.Module):
def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True):
if nlayers == 1:
return nn.Linear(in_dim, bottleneck_dim, bias=bias)
- else:
- layers = [nn.Linear(in_dim, hidden_dim, bias=bias)]
+ layers = [nn.Linear(in_dim, hidden_dim, bias=bias)]
+ if use_bn:
+ layers.append(nn.BatchNorm1d(hidden_dim))
+ layers.append(nn.GELU())
+ for _ in range(nlayers - 2):
+ layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias))
if use_bn:
layers.append(nn.BatchNorm1d(hidden_dim))
layers.append(nn.GELU())
- for _ in range(nlayers - 2):
- layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias))
- if use_bn:
- layers.append(nn.BatchNorm1d(hidden_dim))
- layers.append(nn.GELU())
- layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias))
- return nn.Sequential(*layers)
+ layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias))
+ return nn.Sequential(*layers)
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 2abb9c4f6..1954d8484 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -162,10 +162,9 @@ class Attention(nn.Module):
args = [x.half().contiguous() for x in [q, k, v]]
v = F.scaled_dot_product_attention(*args, attn_mask=mask).to(q.dtype) # type: ignore
return v if mask is None else v.nan_to_num()
- else:
- args = [x.contiguous() for x in [q, k, v]]
- v = F.scaled_dot_product_attention(*args, attn_mask=mask) # type: ignore
- return v if mask is None else v.nan_to_num()
+ args = [x.contiguous() for x in [q, k, v]]
+ v = F.scaled_dot_product_attention(*args, attn_mask=mask) # type: ignore
+ return v if mask is None else v.nan_to_num()
class SelfBlock(nn.Module):
@@ -341,10 +340,9 @@ class TransformerLayer(nn.Module):
"""
if mask0 is not None and mask1 is not None:
return self.masked_forward(desc0, desc1, encoding0, encoding1, mask0, mask1)
- else:
- desc0 = self.self_attn(desc0, encoding0)
- desc1 = self.self_attn(desc1, encoding1)
- return self.cross_attn(desc0, desc1)
+ desc0 = self.self_attn(desc0, encoding0)
+ desc1 = self.self_attn(desc1, encoding1)
+ return self.cross_attn(desc0, desc1)
# This part is compiled and allows padding inputs
def masked_forward(
@@ -924,5 +922,4 @@ class LightGlue(nn.Module):
"""
if self.conf.flash and device.type == "cuda":
return self.pruning_keypoint_thresholds["flash"]
- else:
- return self.pruning_keypoint_thresholds[device.type]
+ return self.pruning_keypoint_thresholds[device.type]
diff --git a/kornia/feature/loftr/backbone/__init__.py b/kornia/feature/loftr/backbone/__init__.py
index 5578c37b4..523480307 100644
--- a/kornia/feature/loftr/backbone/__init__.py
+++ b/kornia/feature/loftr/backbone/__init__.py
@@ -32,7 +32,7 @@ def build_backbone(config: dict[str, Any]) -> ResNetFPN_8_2 | ResNetFPN_16_4:
if config["backbone_type"] == "ResNetFPN":
if config["resolution"] == (8, 2):
return ResNetFPN_8_2(config["resnetfpn"])
- elif config["resolution"] == (16, 4):
+ if config["resolution"] == (16, 4):
return ResNetFPN_16_4(config["resnetfpn"])
raise ValueError(f"LOFTR.BACKBONE_TYPE {config['backbone_type']} with res {config['resolution']} not supported.")
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 824582df9..40dfc0adf 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -484,14 +484,13 @@ class DescriptorMatcherWithSteerer(nn.Module):
"""
if self.match_mode == "nn":
return match_nn(d1, d2, dm=dm)
- elif self.match_mode == "mnn":
+ if self.match_mode == "mnn":
return match_mnn(d1, d2, dm=dm)
- elif self.match_mode == "snn":
+ if self.match_mode == "snn":
return match_snn(d1, d2, self.th, dm=dm)
- elif self.match_mode == "smnn":
+ if self.match_mode == "smnn":
return match_smnn(d1, d2, self.th, dm=dm)
- else:
- raise NotImplementedError
+ raise NotImplementedError
def forward(
self,
diff --git a/kornia/feature/steerers.py b/kornia/feature/steerers.py
index 7091e0fb9..ad8ac82c3 100644
--- a/kornia/feature/steerers.py
+++ b/kornia/feature/steerers.py
@@ -105,7 +105,7 @@ class DiscreteSteerer(nn.Module):
generator = torch.block_diag(*([c4_block] * (descriptor_dim // 4)))
return cls(generator).eval()
- elif generator_type == "SO2":
+ if generator_type == "SO2":
num_rot_blocks_per_freq = descriptor_dim // 14
dim_rot = 12 * num_rot_blocks_per_freq
dim_trivial = descriptor_dim - dim_rot
@@ -129,5 +129,4 @@ class DiscreteSteerer(nn.Module):
generator = torch.block_diag(*blocks)
return cls(generator).eval()
- else:
- raise ValueError(f"Unknown generator_type: {generator_type}")
+ raise ValueError(f"Unknown generator_type: {generator_type}")
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index 9fc635a12..39e306b74 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -202,16 +202,15 @@ def guided_blur(
subsample,
separable=separable,
)
- else:
- return _guided_blur_multichannel_guidance(
- guidance,
- input,
- kernel_size,
- eps,
- border_type,
- subsample,
- separable=separable,
- )
+ return _guided_blur_multichannel_guidance(
+ guidance,
+ input,
+ kernel_size,
+ eps,
+ border_type,
+ subsample,
+ separable=separable,
+ )
class GuidedBlur(nn.Module):
diff --git a/kornia/filters/otsu_thresholding.py b/kornia/filters/otsu_thresholding.py
index e8c3008c6..8fac6c249 100644
--- a/kornia/filters/otsu_thresholding.py
+++ b/kornia/filters/otsu_thresholding.py
@@ -88,16 +88,15 @@ class OtsuThreshold(torch.nn.Module):
if dimensionality <= 2:
return x.flatten().unsqueeze(0), original_shape
- elif dimensionality == 3:
+ if dimensionality == 3:
return x.flatten(start_dim=1), original_shape
- elif dimensionality == 4:
+ if dimensionality == 4:
b, c, h, w = x.shape
return self.transform_input(x.reshape(b * c, h, w), original_shape=original_shape)
- elif dimensionality == 5:
+ if dimensionality == 5:
f, b, c, h, w = x.shape
return self.transform_input(x.reshape(f * b * c, h, w), original_shape=original_shape)
- else:
- raise ValueError(f"Unsupported tensor dimensionality: {dimensionality}")
+ raise ValueError(f"Unsupported tensor dimensionality: {dimensionality}")
def forward(
self, x: torch.Tensor, nbins: int = 256, slow_and_differentiable: bool = False
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index f4230eb0a..5b6ad63d6 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -131,11 +131,10 @@ class Se2(nn.Module):
if isinstance(right, Se2):
KORNIA_CHECK_TYPE(right, Se2)
return self._mul_se2(right)
- elif isinstance(right, (Vector2, torch.Tensor)):
+ if isinstance(right, (Vector2, torch.Tensor)):
# _check_se2_r_t_shape(so2, risght)
return so2 * right + t
- else:
- raise TypeError(f"Unsupported type: {type(right)}")
+ raise TypeError(f"Unsupported type: {type(right)}")
@property
def so2(self) -> So2:
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index e2f48afe2..4b481c7e1 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -118,12 +118,11 @@ class Se3(nn.Module):
if isinstance(right, Se3):
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py#L97
return self._mul_se3(right)
- elif isinstance(right, (Vector3, torch.Tensor)):
+ if isinstance(right, (Vector3, torch.Tensor)):
_right_data = right if isinstance(right, torch.Tensor) else right.data
KORNIA_CHECK_SHAPE(_right_data, ["*", "N"])
return so3 * right + _unwrap(t)
- else:
- raise TypeError(f"Unsupported type: {type(right)}")
+ raise TypeError(f"Unsupported type: {type(right)}")
@property
def so3(self) -> So3:
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index 448c1128c..8e0b8189c 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -100,7 +100,7 @@ class So2(nn.Module):
z = self.z
if isinstance(right, So2):
return So2(z * right.z)
- elif isinstance(right, (Vector2, torch.Tensor)):
+ if isinstance(right, (Vector2, torch.Tensor)):
if isinstance(right, torch.Tensor):
# check_so2_t_shape
is_batch_shape = KORNIA_CHECK_SHAPE(right, ["B", "2"], raises=False)
@@ -115,10 +115,8 @@ class So2(nn.Module):
out = torch.stack((real * x - imag * y, imag * x + real * y), -1)
if isinstance(right, torch.Tensor):
return out
- else:
- return Vector2(out)
- else:
- raise TypeError(f"Not So2 or torch.Tensor type. Got: {type(right)}")
+ return Vector2(out)
+ raise TypeError(f"Not So2 or torch.Tensor type. Got: {type(right)}")
@property
def z(self) -> torch.Tensor:
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 79907ac20..19d9d37ce 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -88,15 +88,14 @@ class So3(nn.Module):
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py#L98
if isinstance(right, So3):
return So3(self.q * right.q)
- elif isinstance(right, (torch.Tensor, Vector3)):
+ if isinstance(right, (torch.Tensor, Vector3)):
_right_data = _unwrap(right)
KORNIA_CHECK_SHAPE(_right_data, ["*", "3"])
w = torch.zeros(*right.shape[:-1], 1, device=right.device, dtype=right.dtype)
quat = Quaternion(torch.cat((w, _right_data), -1))
out = (self.q * quat * self.q.conj()).vec
return Vector3(out) if isinstance(right, Vector3) else out
- else:
- raise TypeError(f"Not So3 or torch.Tensor type. Got: {type(right)}")
+ raise TypeError(f"Not So3 or torch.Tensor type. Got: {type(right)}")
@property
def q(self) -> Quaternion:
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index bfbd93ba6..56ce53a1b 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -269,8 +269,7 @@ def fit_line(points: torch.Tensor, weights: Optional[torch.Tensor] = None) -> Pa
KORNIA_CHECK_SHAPE(weights, ["B", "N"])
KORNIA_CHECK(points.shape[0] == weights.shape[0])
return _fit_line_weighted_ols_2d(points, weights)
- else:
- return _fit_line_ols_2d(points)
+ return _fit_line_ols_2d(points)
mean = points.mean(-2, True)
A = points - mean
diff --git a/kornia/geometry/pose.py b/kornia/geometry/pose.py
index d25c966cb..60f64de7f 100644
--- a/kornia/geometry/pose.py
+++ b/kornia/geometry/pose.py
@@ -98,10 +98,9 @@ class NamedPose:
raise ValueError(f"Cannot compose {self} with {other}")
if isinstance(other.pose, Se2):
return NamedPose(self._dst_from_src._mul_se2(other.pose), other._frame_src, self._frame_dst)
- elif isinstance(other.pose, Se3):
+ if isinstance(other.pose, Se3):
return NamedPose(self._dst_from_src._mul_se3(other.pose), other._frame_src, self._frame_dst)
- else:
- raise ValueError(f"Pose must be either Se2 or Se3, got {type(self._dst_from_src)}")
+ raise ValueError(f"Pose must be either Se2 or Se3, got {type(self._dst_from_src)}")
@property
def pose(self) -> Se2 | Se3:
@@ -160,9 +159,9 @@ class NamedPose:
"""
if isinstance(rotation, (So3, Quaternion)):
return cls(Se3(rotation, translation), frame_src, frame_dst)
- elif isinstance(rotation, So2):
+ if isinstance(rotation, So2):
return cls(Se2(rotation, translation), frame_src, frame_dst)
- elif isinstance(rotation, torch.Tensor):
+ if isinstance(rotation, torch.Tensor):
check_matrix_shape(rotation)
dim = rotation.shape[-1]
RT = torch.eye(dim + 1, device=rotation.device, dtype=rotation.dtype)
@@ -170,7 +169,7 @@ class NamedPose:
RT[..., :dim, dim] = translation
if dim == 2:
return cls(Se2.from_matrix(RT), frame_src, frame_dst)
- elif dim == 3:
+ if dim == 3:
return cls(Se3.from_matrix(RT), frame_src, frame_dst)
else:
raise ValueError(f"R must be either So2, So3, Quaternion, or Tensor, got {type(rotation)}")
@@ -204,7 +203,7 @@ class NamedPose:
dim = matrix.shape[-1]
if dim == 3:
return cls(Se2.from_matrix(matrix), frame_src, frame_dst)
- elif dim == 4:
+ if dim == 4:
return cls(Se3.from_matrix(matrix), frame_src, frame_dst)
return None
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index 3c544bd1f..72055be45 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -186,9 +186,8 @@ class Quaternion(nn.Module):
"""
if isinstance(right, Quaternion):
return Quaternion(self.data + right.data)
- else:
- right_quat = self._to_scalar_quaternion(right)
- return Quaternion(self.data + right_quat.data)
+ right_quat = self._to_scalar_quaternion(right)
+ return Quaternion(self.data + right_quat.data)
def __sub__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":
"""Subtract a given quaternion, scalar, or torch.Tensor.
@@ -206,13 +205,12 @@ class Quaternion(nn.Module):
"""
if isinstance(right, Quaternion):
return Quaternion(self.data - right.data)
- else:
- right_quat = self._to_scalar_quaternion(right)
- # For scalar operations, ensure we return a torch.Tensor to preserve gradients
- result_data = self.data - right_quat.data
- if isinstance(result_data, nn.Parameter):
- result_data = result_data.data # Convert to torch.Tensor to preserve gradients
- return Quaternion(result_data)
+ right_quat = self._to_scalar_quaternion(right)
+ # For scalar operations, ensure we return a torch.Tensor to preserve gradients
+ result_data = self.data - right_quat.data
+ if isinstance(result_data, nn.Parameter):
+ result_data = result_data.data # Convert to torch.Tensor to preserve gradients
+ return Quaternion(result_data)
def __mul__(self, right: Union["Quaternion", torch.Tensor, float]) -> "Quaternion":
# If right is a Quaternion, do quaternion multiplication
@@ -226,15 +224,14 @@ class Quaternion(nn.Module):
return Quaternion(torch.cat((new_real[..., None], new_vec), -1))
# If right is a scalar/torch.Tensor, convert to scalar quaternion and multiply
- else:
- right_quat = self._to_scalar_quaternion(right)
- new_real = self.real * right_quat.real - batched_dot_product(self.vec, right_quat.vec)
- new_vec = (
- self.real[..., None] * right_quat.vec
- + right_quat.real[..., None] * self.vec
- + torch.linalg.cross(self.vec, right_quat.vec, dim=-1)
- )
- return Quaternion(torch.cat((new_real[..., None], new_vec), -1))
+ right_quat = self._to_scalar_quaternion(right)
+ new_real = self.real * right_quat.real - batched_dot_product(self.vec, right_quat.vec)
+ new_vec = (
+ self.real[..., None] * right_quat.vec
+ + right_quat.real[..., None] * self.vec
+ + torch.linalg.cross(self.vec, right_quat.vec, dim=-1)
+ )
+ return Quaternion(torch.cat((new_real[..., None], new_vec), -1))
def __rmul__(self, left: Union[torch.Tensor, float]) -> "Quaternion":
"""Right multiplication (left * self) where left is a scalar or torch.Tensor."""
@@ -250,25 +247,24 @@ class Quaternion(nn.Module):
def __div__(self, right: Union[torch.Tensor, "Quaternion", float]) -> "Quaternion":
if isinstance(right, Quaternion):
return self * right.inv()
+ # For scalars/tensors, just divide the quaternion data directly
+ if isinstance(right, (int, float)):
+ right_tensor = torch.tensor(right, device=self.data.device, dtype=self.data.dtype)
+ else:
+ right_tensor = right.to(device=self.data.device, dtype=self.data.dtype)
+
+ # For division by scalar, expand to [right, right, right, right] for element-wise division
+ if right_tensor.dim() == 0: # scalar
+ divisor = right_tensor.expand_as(self.data[..., 0]).unsqueeze(-1).expand_as(self.data)
else:
- # For scalars/tensors, just divide the quaternion data directly
- if isinstance(right, (int, float)):
- right_tensor = torch.tensor(right, device=self.data.device, dtype=self.data.dtype)
- else:
- right_tensor = right.to(device=self.data.device, dtype=self.data.dtype)
-
- # For division by scalar, expand to [right, right, right, right] for element-wise division
- if right_tensor.dim() == 0: # scalar
- divisor = right_tensor.expand_as(self.data[..., 0]).unsqueeze(-1).expand_as(self.data)
- else:
- # Broadcast the torch.Tensor to match the quaternion dimensions
- divisor = right_tensor.unsqueeze(-1).expand_as(self.data)
-
- # For scalar operations, ensure we return a torch.Tensor to preserve gradients
- result_data = self.data / divisor
- if isinstance(result_data, nn.Parameter):
- result_data = result_data.data # Convert to torch.Tensor to preserve gradients
- return Quaternion(result_data)
+ # Broadcast the torch.Tensor to match the quaternion dimensions
+ divisor = right_tensor.unsqueeze(-1).expand_as(self.data)
+
+ # For scalar operations, ensure we return a torch.Tensor to preserve gradients
+ result_data = self.data / divisor
+ if isinstance(result_data, nn.Parameter):
+ result_data = result_data.data # Convert to torch.Tensor to preserve gradients
+ return Quaternion(result_data)
def __truediv__(self, right: Union[torch.Tensor, "Quaternion", float]) -> "Quaternion":
return self.__div__(right)
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.py
index e7a361768..3365eb8a1 100644
--- a/kornia/losses/mutual_information.py
+++ b/kornia/losses/mutual_information.py
@@ -100,8 +100,7 @@ class MIKernel(Enum):
def _flatten_mask(mask: torch.Tensor | None) -> torch.Tensor:
if mask is None:
return torch.tensor([True])
- else:
- return mask.view(-1)
+ return mask.view(-1)
def _mask_is_full(mask: torch.Tensor | None) -> bool:
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index 0a4a206aa..6fc28ad7c 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -89,13 +89,13 @@ def _convert_boxes_to_xyxy(boxes: torch.Tensor, box_format: str) -> torch.Tensor
"""
if box_format == "xyxy":
return boxes
- elif box_format == "xywh":
+ if box_format == "xywh":
# (x, y, w, h) -> (x1, y1, x2, y2)
x, y, w, h = boxes[:, 0:1], boxes[:, 1:2], boxes[:, 2:3], boxes[:, 3:4]
x2 = x + w
y2 = y + h
return torch.cat([x, y, x2, y2], dim=1)
- elif box_format == "cxcywh":
+ if box_format == "cxcywh":
# (cx, cy, w, h) -> (x1, y1, x2, y2)
cx, cy, w, h = boxes[:, 0:1], boxes[:, 1:2], boxes[:, 2:3], boxes[:, 3:4]
x1 = cx - w / 2
@@ -103,8 +103,7 @@ def _convert_boxes_to_xyxy(boxes: torch.Tensor, box_format: str) -> torch.Tensor
x2 = cx + w / 2
y2 = cy + h / 2
return torch.cat([x1, y1, x2, y2], dim=1)
- else:
- raise ValueError(f"Unsupported box format: {box_format}. Must be one of 'xyxy', 'xywh', or 'cxcywh'.")
+ raise ValueError(f"Unsupported box format: {box_format}. Must be one of 'xyxy', 'xywh', or 'cxcywh'.")
def mean_iou_bbox(boxes_1: torch.Tensor, boxes_2: torch.Tensor, box_format: str = "xyxy") -> torch.Tensor:
diff --git a/kornia/models/base.py b/kornia/models/base.py
index 7ae1b4cdf..39f69079b 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -99,13 +99,11 @@ class ModelBaseMixin:
"""
if output_type == "torch":
return output
- elif output_type == "pil":
+ if output_type == "pil":
if isinstance(output, list):
return [tensor_to_image(t) for t in output]
- else:
- return tensor_to_image(output)
- else:
- raise RuntimeError(f"Output type {output_type} is not supported. Accepted values are 'torch' and 'pil'.")
+ return tensor_to_image(output)
+ raise RuntimeError(f"Output type {output_type} is not supported. Accepted values are 'torch' and 'pil'.")
def save(self, output: Union[torch.Tensor, List[torch.Tensor]], directory: str, is_batch: bool = False) -> None:
"""Save the output tensor to a directory.
diff --git a/kornia/models/efficient_vit/nn/norm.py b/kornia/models/efficient_vit/nn/norm.py
index 1cf00f604..ec1b133fd 100644
--- a/kornia/models/efficient_vit/nn/norm.py
+++ b/kornia/models/efficient_vit/nn/norm.py
@@ -62,5 +62,4 @@ def build_norm(name: str = "bn2d", num_features: Optional[int] = None, **kwargs:
norm_cls = REGISTERED_NORM_DICT[name]
args = build_kwargs_from_config(kwargs, norm_cls)
return norm_cls(**args)
- else:
- return None
+ return None
diff --git a/kornia/models/efficient_vit/nn/ops.py b/kornia/models/efficient_vit/nn/ops.py
index 188e24cfe..17fa46de0 100644
--- a/kornia/models/efficient_vit/nn/ops.py
+++ b/kornia/models/efficient_vit/nn/ops.py
@@ -622,8 +622,7 @@ class ResidualBlock(nn.Module):
"""
if self.pre_norm is None:
return self.main(x)
- else:
- return self.main(self.pre_norm(x))
+ return self.main(self.pre_norm(x))
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Apply the residual wrapper to an input tensor.
diff --git a/kornia/models/efficient_vit/utils/list.py b/kornia/models/efficient_vit/utils/list.py
index e7b3135aa..56f1156b8 100644
--- a/kornia/models/efficient_vit/utils/list.py
+++ b/kornia/models/efficient_vit/utils/list.py
@@ -27,10 +27,9 @@ def val2list(x: Union[list[Any], tuple[Any, ...], Any], repeat_time: int = 1) ->
"""Convert value to list."""
if isinstance(x, list):
return x
- elif isinstance(x, tuple):
+ if isinstance(x, tuple):
return list(x)
- else:
- return [x] * repeat_time
+ return [x] * repeat_time
def val2tuple(x: Union[list[Any], tuple[Any, ...], Any], min_len: int = 1, idx_repeat: int = -1) -> tuple[Any, ...]:
diff --git a/kornia/models/rt_detr/architecture/hgnetv2.py b/kornia/models/rt_detr/architecture/hgnetv2.py
index 2ec36a3cd..0c8b0dfc0 100644
--- a/kornia/models/rt_detr/architecture/hgnetv2.py
+++ b/kornia/models/rt_detr/architecture/hgnetv2.py
@@ -202,7 +202,7 @@ class PPHGNetV2(nn.Module):
StageConfig(1024, 384, 2048, 1, True, True, 5, 6),
],
)
- elif variant == "X":
+ if variant == "X":
return PPHGNetV2(
stem_channels=[3, 32, 64],
stage_configs=[
@@ -212,5 +212,4 @@ class PPHGNetV2(nn.Module):
StageConfig(1024, 512, 2048, 2, True, True, 5, 6),
],
)
- else:
- raise ValueError("Only variant L and X are supported")
+ raise ValueError("Only variant L and X are supported")
diff --git a/kornia/models/rt_detr/architecture/resnet_d.py b/kornia/models/rt_detr/architecture/resnet_d.py
index 7bc8164a3..013d78e7f 100644
--- a/kornia/models/rt_detr/architecture/resnet_d.py
+++ b/kornia/models/rt_detr/architecture/resnet_d.py
@@ -207,13 +207,12 @@ class ResNetD(nn.Module):
variant = str(variant)
if variant == "18":
return ResNetD([2, 2, 2, 2], BasicBlockD)
- elif variant == "34":
+ if variant == "34":
return ResNetD([3, 4, 6, 3], BasicBlockD)
- elif variant == "50":
+ if variant == "50":
return ResNetD([3, 4, 6, 3], BottleneckD)
- elif variant == "101":
+ if variant == "101":
return ResNetD([3, 4, 23, 3], BottleneckD)
- elif variant == "152":
+ if variant == "152":
return ResNetD([3, 8, 36, 3], BottleneckD)
- else:
- raise ValueError("Only variant 18, 34, 50, 101, and 152 are supported")
+ raise ValueError("Only variant 18, 34, 50, 101, and 152 are supported")
diff --git a/kornia/models/sam/architecture/prompt_encoder.py b/kornia/models/sam/architecture/prompt_encoder.py
index 0d3bd53c7..28421a521 100644
--- a/kornia/models/sam/architecture/prompt_encoder.py
+++ b/kornia/models/sam/architecture/prompt_encoder.py
@@ -135,12 +135,11 @@ class PromptEncoder(nn.Module):
"""Get the batch size of the output given the batch size of the input prompts."""
if points is not None:
return points[0].shape[0]
- elif boxes is not None:
+ if boxes is not None:
return boxes.shape[0]
- elif masks is not None:
+ if masks is not None:
return masks.shape[0]
- else:
- return 1
+ return 1
def _get_device(self) -> torch.device:
return self.point_embeddings[0].weight.device
diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.py
index 9502f0ab1..51d0114f4 100644
--- a/kornia/models/sam/model.py
+++ b/kornia/models/sam/model.py
@@ -140,8 +140,7 @@ class Sam(ONNXExportMixin, ModelBase[SamConfig]):
"""
if name in ["vit_b", "vit_l", "vit_h", "mobile_sam"]:
return Sam.from_config(SamConfig(name))
- else:
- raise ValueError(f"Invalid SAM model name: {name}")
+ raise ValueError(f"Invalid SAM model name: {name}")
@staticmethod
def from_config(config: SamConfig) -> Sam:
diff --git a/kornia/models/vit_mobile.py b/kornia/models/vit_mobile.py
index fc7408c30..fa8b39b84 100644
--- a/kornia/models/vit_mobile.py
+++ b/kornia/models/vit_mobile.py
@@ -235,8 +235,7 @@ class MV2Block(nn.Module):
"""
if self.use_res_connect:
return x + self.conv(x)
- else:
- return self.conv(x)
+ return self.conv(x)
class MobileViTBlock(nn.Module):
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index e3a9f580d..acadabdbc 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -105,7 +105,7 @@ class ONNXLoader(CachedDownloader):
)
return onnx.load(file_path) # type:ignore
- elif model_name.startswith(("http://", "https://")):
+ if model_name.startswith(("http://", "https://")):
cache_dir = kwargs.get("cache_dir", None) or kornia_config.hub_onnx_dir
kwargs.update({"cache_dir": cache_dir})
file_path = cls.download_to_cache(
@@ -126,7 +126,7 @@ class ONNXLoader(CachedDownloader):
)
return onnx.load(file_path) # type:ignore
- elif os.path.exists(model_name):
+ if os.path.exists(model_name):
return onnx.load(model_name) # type:ignore
raise ValueError(f"File {model_name} not found")
diff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.py
index 8e1587e6f..8f1490b35 100644
--- a/kornia/sensors/camera/camera_model.py
+++ b/kornia/sensors/camera/camera_model.py
@@ -51,14 +51,13 @@ def get_model_from_type(
"""Get camera model from model type."""
if model_type == CameraModelType.PINHOLE:
return PinholeModel(image_size, params)
- elif model_type == CameraModelType.BROWN_CONRADY:
+ if model_type == CameraModelType.BROWN_CONRADY:
return BrownConradyModel(image_size, params)
- elif model_type == CameraModelType.KANNALA_BRANDT_K3:
+ if model_type == CameraModelType.KANNALA_BRANDT_K3:
return KannalaBrandtK3(image_size, params)
- elif model_type == CameraModelType.ORTHOGRAPHIC:
+ if model_type == CameraModelType.ORTHOGRAPHIC:
return Orthographic(image_size, params)
- else:
- raise ValueError("Invalid Camera Model Type")
+ raise ValueError("Invalid Camera Model Type")
CameraDistortionType = Union[AffineTransform, BrownConradyTransform, KannalaBrandtK3Transform]
diff --git a/pyproject.toml b/pyproject.toml
index b558fc579..051531453 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -213,7 +213,14 @@ select = [
"PIE", # flake8-pie
"PL", # Pylint
"PYI", # flake8-pyi
- "RET506", # unnecessary branch after raise
+ "RET501", # unnecessary-return-none
+ "RET502", # implicit-return-value
+ "RET503", # implicit-return
+ # "RET504", # unnecessary-assign
+ "RET505", # superfluous-else-return
+ "RET506", # superfluous-else-raise
+ "RET507", # superfluous-else-continue
+ "RET508", # superfluous-else-break
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"S", # flake8-bandit