Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: complete Ruff RET cleanup and enforce the rule family (#4808)

Daniele Loruf7dcdf8596df
diff --git a/.github/scripts/check_import_surface.py b/.github/scripts/check_import_surface.py
index 5babcec0e..fdf538ff6 100644
--- a/.github/scripts/check_import_surface.py
+++ b/.github/scripts/check_import_surface.py
@@ -502,8 +502,7 @@ class _ExportResolver:
return None
if all_values:
names = self._literal_all(all_values[-1])
- result = None if names is None else set(names)
- return result
+ return None if names is None else set(names)
return self._bound_exports(tree, module, is_package)
def _import_bindings(self, node: ast.Import | ast.ImportFrom, module: str, is_package: bool) -> set[str] | None:
diff --git a/docs/export_support/cases_aug.py b/docs/export_support/cases_aug.py
index 9e90e5e6a..c77395073 100644
--- a/docs/export_support/cases_aug.py
+++ b/docs/export_support/cases_aug.py
@@ -78,8 +78,7 @@ class Rand(nn.Module):
self.n_data = n_data
def forward(self, *xs):
- out = self.aug(*xs[: self.n_data])
- return out
+ return self.aug(*xs[: self.n_data])
def eval(self): # keep the augmentation in train mode (harness calls .eval())
return self
diff --git a/docs/generate_examples.py b/docs/generate_examples.py
index 829916ab8..ad537aa2a 100644
--- a/docs/generate_examples.py
+++ b/docs/generate_examples.py
@@ -107,9 +107,7 @@ def draw_bbox_kpts(imgs: torch.Tensor, bboxes: torch.Tensor, keypoints: torch.Te
rectangle2[..., n, 2] = keypoints[..., n, 0] + 2
rectangle2[..., n, 3] = keypoints[..., n, 1] + 2
color = torch.tensor([0, 0, 1]).repeat(imgs.shape[0], imgs.shape[1], 1)
- imgs_draw = K.image.draw_rectangle(imgs_draw, rectangle2, color=color, fill=True)
-
- return imgs_draw
+ return K.image.draw_rectangle(imgs_draw, rectangle2, color=color, fill=True)
def main():
diff --git a/kornia/image/utils.py b/kornia/image/utils.py
index 9e06eb993..d15d841b0 100644
--- a/kornia/image/utils.py
+++ b/kornia/image/utils.py
@@ -298,9 +298,8 @@ def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int =
# crop trailing right/bottom padding to match original
combined_H = n_row * padded_H - padding
combined_W = n_col * padded_W - padding
- combined = combined[:, :combined_H, :combined_W]
- return combined
+ return combined[:, :combined_H, :combined_W]
def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., torch.Tensor]:
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 87f40eca2..13a6e477a 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -148,9 +148,7 @@ def dice_loss(
if average == "macro":
dice_loss = (dice_loss * weight).sum(-1) / weight.sum()
- dice_loss = torch.mean(dice_loss)
-
- return dice_loss
+ return torch.mean(dice_loss)
class DiceLoss(nn.Module):
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index d367d1e48..9591b867d 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -29,8 +29,8 @@ def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
unsummed_kl = F.kl_div(
q.reshape(batch * chans, height * width).log(), p.reshape(batch * chans, height * width), reduction="none"
)
- kl_values = unsummed_kl.sum(-1).view(batch, chans)
- return kl_values
+
+ return unsummed_kl.sum(-1).view(batch, chans)
def _js_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/losses/mutual_information.py b/kornia/losses/mutual_information.py
index 3365eb8a1..d75fb11e9 100644
--- a/kornia/losses/mutual_information.py
+++ b/kornia/losses/mutual_information.py
@@ -288,9 +288,7 @@ class EntropyBasedLossBase(torch.nn.Module):
vals_1 = self.kernel_function(diff_1)
vals_2 = self.kernel_function(diff_2)
- joint_histogram = torch.einsum("...in,...jn->...ij", vals_1, vals_2)
-
- return joint_histogram
+ return torch.einsum("...in,...jn->...ij", vals_1, vals_2)
def entropies(
self, other_signal: torch.Tensor, other_mask: torch.Tensor | None = None
diff --git a/kornia/losses/one_hot.py b/kornia/losses/one_hot.py
index b82ce27ad..e260a1bd9 100644
--- a/kornia/losses/one_hot.py
+++ b/kornia/losses/one_hot.py
@@ -66,7 +66,6 @@ def one_hot(
# Convert to desired dtype and device, then apply eps for numerical stability
one_hot_tensor = one_hot_tensor.to(dtype=dtype, device=device)
- # Apply eps: multiply by (1-eps) and add eps to all elements
- one_hot_tensor = one_hot_tensor * (1.0 - eps) + eps
- return one_hot_tensor
+ # Apply eps: multiply by (1-eps) and add eps to all elements
+ return one_hot_tensor * (1.0 - eps) + eps
diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.py
index 6fc28ad7c..b9891d41c 100644
--- a/kornia/metrics/mean_iou.py
+++ b/kornia/metrics/mean_iou.py
@@ -73,8 +73,7 @@ def mean_iou(pred: torch.Tensor, target: torch.Tensor, num_classes: int, eps: fl
# NOTE: we add epsilon so that samples that are neither in the
# prediction or ground truth are taken into account.
- ious = (conf_mat_diag + eps) / (denominator + eps)
- return ious
+ return (conf_mat_diag + eps) / (denominator + eps)
def _convert_boxes_to_xyxy(boxes: torch.Tensor, box_format: str) -> torch.Tensor:
diff --git a/kornia/models/base.py b/kornia/models/base.py
index 39f69079b..a4996d5b1 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -206,5 +206,4 @@ class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):
compiled = torch.compile(
self, fullgraph=fullgraph, dynamic=dynamic, backend=backend, mode=mode, options=options, disable=disable
)
- compiled = cast(ModelBase[ModelConfig], compiled)
- return compiled
+ return cast(ModelBase[ModelConfig], compiled)
diff --git a/kornia/models/common.py b/kornia/models/common.py
index 3ebd166df..5e58d77a3 100644
--- a/kornia/models/common.py
+++ b/kornia/models/common.py
@@ -167,8 +167,7 @@ class LayerNorm2d(nn.Module):
u = x.mean(1, keepdim=True)
s = (x - u).pow(2).mean(1, keepdim=True)
x = (x - u) / (s + self.eps).sqrt()
- x = self.weight[:, None, None] * x + self.bias[:, None, None]
- return x
+ return self.weight[:, None, None] * x + self.bias[:, None, None]
def window_partition(x: torch.Tensor, window_size: int) -> tuple[torch.Tensor, tuple[int, int]]:
diff --git a/kornia/models/depth_estimation/base.py b/kornia/models/depth_estimation/base.py
index 497d510e8..9e95dc01f 100644
--- a/kornia/models/depth_estimation/base.py
+++ b/kornia/models/depth_estimation/base.py
@@ -53,11 +53,10 @@ class DepthEstimation(HFONNXComunnityModel):
),
):
results = [super(DepthEstimation, self).__call__(image[None].cpu().numpy())[0] for image in images]
- results = [
+ return [
self.resize_back(torch.tensor(result, device=image.device, dtype=image.dtype), image)
for result, image in zip(results, images)
]
- return results
result = super().__call__(images.cpu().numpy())[0]
result = torch.tensor(result, device=images.device, dtype=images.dtype)
diff --git a/kornia/models/dexined.py b/kornia/models/dexined.py
index 974fa5caa..80c0822ef 100644
--- a/kornia/models/dexined.py
+++ b/kornia/models/dexined.py
@@ -148,8 +148,7 @@ class UpConvBlock(nn.Module):
def forward(self, x: torch.Tensor, out_shape: list[int]) -> torch.Tensor:
out = self.features(x)
- out = F.interpolate(out, out_shape, mode="bilinear")
- return out
+ return F.interpolate(out, out_shape, mode="bilinear")
class SingleConvBlock(nn.Module):
@@ -312,8 +311,7 @@ class DexiNed(ONNXExportMixin, nn.Module):
out_4 = self.up_block_4(block_4, out_shape)
out_5 = self.up_block_5(block_5, out_shape)
out_6 = self.up_block_6(block_6, out_shape)
- results = [out_1, out_2, out_3, out_4, out_5, out_6]
- return results
+ return [out_1, out_2, out_3, out_4, out_5, out_6]
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Predict a fused edge map from an RGB image batch.
@@ -329,6 +327,4 @@ class DexiNed(ONNXExportMixin, nn.Module):
# concatenate multiscale outputs
block_cat = torch.cat(features, dim=1) # Bx6xHxW
- block_cat = self.block_cat(block_cat) # Bx1xHxW
-
- return block_cat
+ return self.block_cat(block_cat) # Bx1xHxW
diff --git a/kornia/models/efficient_vit/backbone.py b/kornia/models/efficient_vit/backbone.py
index 04f5e6ae5..b8cb57df6 100644
--- a/kornia/models/efficient_vit/backbone.py
+++ b/kornia/models/efficient_vit/backbone.py
@@ -196,46 +196,42 @@ class EfficientViTBackbone(nn.Module):
def efficientvit_backbone_b0(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
"""Create EfficientViT B0."""
- backbone = EfficientViTBackbone(
+ return EfficientViTBackbone(
width_list=[8, 16, 32, 64, 128],
depth_list=[1, 2, 2, 2, 2],
dim=16,
**build_kwargs_from_config(kwargs, EfficientViTBackbone),
)
- return backbone
def efficientvit_backbone_b1(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
"""Create EfficientViT B1."""
- backbone = EfficientViTBackbone(
+ return EfficientViTBackbone(
width_list=[16, 32, 64, 128, 256],
depth_list=[1, 2, 3, 3, 4],
dim=16,
**build_kwargs_from_config(kwargs, EfficientViTBackbone),
)
- return backbone
def efficientvit_backbone_b2(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
"""Create EfficientViT B2."""
- backbone = EfficientViTBackbone(
+ return EfficientViTBackbone(
width_list=[24, 48, 96, 192, 384],
depth_list=[1, 3, 4, 4, 6],
dim=32,
**build_kwargs_from_config(kwargs, EfficientViTBackbone),
)
- return backbone
def efficientvit_backbone_b3(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
"""Create EfficientViT B3."""
- backbone = EfficientViTBackbone(
+ return EfficientViTBackbone(
width_list=[32, 64, 128, 256, 512],
depth_list=[1, 4, 6, 6, 9],
dim=32,
**build_kwargs_from_config(kwargs, EfficientViTBackbone),
)
- return backbone
class EfficientViTLargeBackbone(nn.Module):
@@ -411,39 +407,35 @@ class EfficientViTLargeBackbone(nn.Module):
def efficientvit_backbone_l0(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone:
"""Create EfficientViT L0."""
- backbone = EfficientViTLargeBackbone(
+ return EfficientViTLargeBackbone(
width_list=[32, 64, 128, 256, 512],
depth_list=[1, 1, 1, 4, 4],
**build_kwargs_from_config(kwargs, EfficientViTLargeBackbone),
)
- return backbone
def efficientvit_backbone_l1(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone:
"""Create EfficientViT L."""
- backbone = EfficientViTLargeBackbone(
+ return EfficientViTLargeBackbone(
width_list=[32, 64, 128, 256, 512],
depth_list=[1, 1, 1, 6, 6],
**build_kwargs_from_config(kwargs, EfficientViTLargeBackbone),
)
- return backbone
def efficientvit_backbone_l2(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone:
"""Create EfficientViT L2."""
- backbone = EfficientViTLargeBackbone(
+ return EfficientViTLargeBackbone(
width_list=[32, 64, 128, 256, 512],
depth_list=[1, 2, 2, 8, 8],
**build_kwargs_from_config(kwargs, EfficientViTLargeBackbone),
)
- return backbone
def efficientvit_backbone_l3(**kwargs: dict[str, Any]) -> EfficientViTLargeBackbone:
"""Create EfficientViT L3."""
- backbone = EfficientViTLargeBackbone(
+ return EfficientViTLargeBackbone(
width_list=[64, 128, 256, 512, 1024],
depth_list=[1, 2, 2, 8, 8],
**build_kwargs_from_config(kwargs, EfficientViTLargeBackbone),
)
- return backbone
diff --git a/kornia/models/efficient_vit/model.py b/kornia/models/efficient_vit/model.py
index 48cc4c075..dd02dd3e8 100644
--- a/kornia/models/efficient_vit/model.py
+++ b/kornia/models/efficient_vit/model.py
@@ -107,5 +107,4 @@ class EfficientViT(ModelBase[EfficientViTConfig]):
Dict[str, torch.Tensor]: a dictionary containing the features.
"""
- feats = self.backbone(images)
- return feats
+ return self.backbone(images)
diff --git a/kornia/models/efficient_vit/nn/ops.py b/kornia/models/efficient_vit/nn/ops.py
index 17fa46de0..6122e4244 100644
--- a/kornia/models/efficient_vit/nn/ops.py
+++ b/kornia/models/efficient_vit/nn/ops.py
@@ -183,8 +183,7 @@ class DSConv(nn.Module):
projection.
"""
x = self.depth_conv(x)
- x = self.point_conv(x)
- return x
+ return self.point_conv(x)
class MBConv(nn.Module):
@@ -257,8 +256,7 @@ class MBConv(nn.Module):
"""
x = self.inverted_conv(x)
x = self.depth_conv(x)
- x = self.point_conv(x)
- return x
+ return self.point_conv(x)
class FusedMBConv(nn.Module):
@@ -330,8 +328,7 @@ class FusedMBConv(nn.Module):
projection.
"""
x = self.spatial_conv(x)
- x = self.point_conv(x)
- return x
+ return self.point_conv(x)
class ResBlock(nn.Module):
@@ -392,8 +389,7 @@ class ResBlock(nn.Module):
Feature map after the block's convolutional transformations.
"""
x = self.conv1(x)
- x = self.conv2(x)
- return x
+ return self.conv2(x)
class LiteMLA(nn.Module):
@@ -496,8 +492,7 @@ class LiteMLA(nn.Module):
out = out[..., :-1] / (out[..., -1:] + self.eps)
out = torch.transpose(out, -1, -2)
- out = torch.reshape(out, (B, -1, H, W))
- return out
+ return torch.reshape(out, (B, -1, H, W))
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Apply lightweight multi-scale linear attention.
@@ -517,9 +512,7 @@ class LiteMLA(nn.Module):
multi_scale_qkv = torch.cat(multi_scale_qkv, dim=1)
out = self.relu_linear_att(multi_scale_qkv)
- out = self.proj(out)
-
- return out
+ return self.proj(out)
class EfficientViTBlock(nn.Module):
@@ -577,8 +570,7 @@ class EfficientViTBlock(nn.Module):
MBConv module.
"""
x = self.context_module(x)
- x = self.local_module(x)
- return x
+ return self.local_module(x)
#################################################################################
diff --git a/kornia/models/kimi_vl/model.py b/kornia/models/kimi_vl/model.py
index 3be52b608..1d61ac4cf 100644
--- a/kornia/models/kimi_vl/model.py
+++ b/kornia/models/kimi_vl/model.py
@@ -77,9 +77,7 @@ class KimiVLProjector(nn.Module):
x = x.view(B, new_height * new_width, ratio * ratio * D)
# MLP
- x = self.mlp(x)
-
- return x
+ return self.mlp(x)
class KimiVLModel(nn.Module):
@@ -120,6 +118,4 @@ class KimiVLModel(nn.Module):
patch_size = self.patch_size
h_patches = H // patch_size
w_patches = W // patch_size
- projected_features = self.projector(vision_features, h_patches, w_patches)
-
- return projected_features
+ return self.projector(vision_features, h_patches, w_patches)
diff --git a/kornia/models/kimi_vl/moonvit.py b/kornia/models/kimi_vl/moonvit.py
index d56ace595..daf1bd02c 100644
--- a/kornia/models/kimi_vl/moonvit.py
+++ b/kornia/models/kimi_vl/moonvit.py
@@ -199,8 +199,7 @@ class MoonViTMLP(nn.Module):
x = self.fc1(x)
x = self.act(x)
x = self.fc2(x)
- x = self.dropout(x)
- return x
+ return self.dropout(x)
class MoonViTLayer(nn.Module):
@@ -247,8 +246,7 @@ class MoonViTLayer(nn.Module):
residual updates.
"""
x = x + self.attn(self.norm1(x), cos, sin, attention_mask)
- x = x + self.mlp(self.norm2(x))
- return x
+ return x + self.mlp(self.norm2(x))
class MoonViTEncoder(nn.Module):
@@ -341,6 +339,4 @@ class MoonViT(nn.Module):
# Generate RoPE
cos, sin = self.rope(h_patches, w_patches, x.device) # (N, head_dim / 2)
x = self.encoder(x, cos, sin, attention_mask=attention_mask)
- x = self.norm(x)
-
- return x
+ return self.norm(x)
diff --git a/kornia/models/paligemma/modeling_paligemma.py b/kornia/models/paligemma/modeling_paligemma.py
index 0ddbf96a9..2ff02eed4 100644
--- a/kornia/models/paligemma/modeling_paligemma.py
+++ b/kornia/models/paligemma/modeling_paligemma.py
@@ -219,9 +219,7 @@ class GemmaAttention(nn.Module):
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.view(bsz, q_len, self.hidden_size)
- attn_output = self.o_proj(attn_output)
-
- return attn_output
+ return self.o_proj(attn_output)
class GemmaDecoderLayer(nn.Module):
@@ -265,9 +263,7 @@ class GemmaDecoderLayer(nn.Module):
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
- hidden_states = residual + hidden_states
-
- return hidden_states
+ return residual + hidden_states
class PaliGemma(nn.Module):
@@ -356,6 +352,4 @@ class PaliGemma(nn.Module):
)
hidden_states = self.norm(hidden_states)
- logits = self.lm_head(hidden_states)
-
- return logits
+ return self.lm_head(hidden_states)
diff --git a/kornia/models/qwen25/qwen2_vl.py b/kornia/models/qwen25/qwen2_vl.py
index f39e94946..e5b7760da 100644
--- a/kornia/models/qwen25/qwen2_vl.py
+++ b/kornia/models/qwen25/qwen2_vl.py
@@ -52,8 +52,7 @@ class Qwen2VLPatchMerger(Module):
x = self.conv(x)
x = x.flatten(2)
x = x.transpose(1, 2)
- x = self.ln_q(x)
- return x
+ return self.ln_q(x)
class Qwen2VLRotaryEmbedding(Module):
@@ -128,8 +127,7 @@ class Qwen2VLVisionAttention(Module):
x = F.scaled_dot_product_attention(q, k, v, dropout_p=0.0)
x = x.transpose(1, 2).reshape(B, N, C)
- x = self.proj(x)
- return x
+ return self.proj(x)
class Qwen2VLMLP(Module):
@@ -195,8 +193,7 @@ class Qwen2VLVisionBlock(Module):
residual connections.
"""
x = x + self.attn(self.norm1(x), rot_pos_emb=rot_pos_emb)
- x = x + self.mlp(self.norm2(x))
- return x
+ return x + self.mlp(self.norm2(x))
class Qwen2VLVisionTransformer(Module):
diff --git a/kornia/models/rt_detr/architecture/hgnetv2.py b/kornia/models/rt_detr/architecture/hgnetv2.py
index 0c8b0dfc0..cde93c7ed 100644
--- a/kornia/models/rt_detr/architecture/hgnetv2.py
+++ b/kornia/models/rt_detr/architecture/hgnetv2.py
@@ -55,8 +55,7 @@ class StemBlock(nn.Module):
"""
x = self.stem1(x)
x = torch.cat([self.pool(x), self.stem2b(self.stem2a(x))], 1)
- x = self.stem4(self.stem3(x))
- return x
+ return self.stem4(self.stem3(x))
# Separable conv
diff --git a/kornia/models/rt_detr/architecture/hybrid_encoder.py b/kornia/models/rt_detr/architecture/hybrid_encoder.py
index 6bb2d4516..19d346309 100644
--- a/kornia/models/rt_detr/architecture/hybrid_encoder.py
+++ b/kornia/models/rt_detr/architecture/hybrid_encoder.py
@@ -179,8 +179,7 @@ class AIFI(nn.Module):
x = self.norm1(x + self.dropout1(attn))
x = self.norm2(x + self.dropout2(self.ffn(x)))
- x = x.view(H, W, N, C).permute(2, 3, 0, 1) # (H * W, N, C) -> (N, C, H, W)
- return x
+ return x.view(H, W, N, C).permute(2, 3, 0, 1) # (H * W, N, C) -> (N, C, H, W)
def ffn(self, x: torch.Tensor) -> torch.Tensor:
"""Apply the feed-forward sublayer used inside AIFI.
@@ -357,5 +356,4 @@ class HybridEncoder(nn.Module):
"""
projected_maps = [proj(fmap) for proj, fmap in zip(self.input_proj, fmaps)]
projected_maps[-1] = self.encoder(projected_maps[-1])
- new_fmaps = self.ccfm(projected_maps)
- return new_fmaps
+ return self.ccfm(projected_maps)
diff --git a/kornia/models/rt_detr/architecture/rtdetr_head.py b/kornia/models/rt_detr/architecture/rtdetr_head.py
index 2d7f6a5dc..c85541b8f 100644
--- a/kornia/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/models/rt_detr/architecture/rtdetr_head.py
@@ -158,9 +158,7 @@ class MultiScaleDeformableAttention(nn.Module):
out = _deformable_attention_kernel(value_buf, value_spatial_shapes, sampling_locations, attention_weights)
# final projection
- out = self.output_proj(out)
-
- return out
+ return self.output_proj(out)
class TransformerDecoderLayer(nn.Module):
@@ -229,9 +227,7 @@ class TransformerDecoderLayer(nn.Module):
tgt = self.norm2(tgt + self.dropout2(out))
# ffn
- out = self.norm3(tgt + self.dropout4(self._ffn(tgt)))
-
- return out
+ return self.norm3(tgt + self.dropout4(self._ffn(tgt)))
class TransformerDecoder(nn.Module):
diff --git a/kornia/models/rt_detr/model.py b/kornia/models/rt_detr/model.py
index 69f7c5443..5f77ed877 100644
--- a/kornia/models/rt_detr/model.py
+++ b/kornia/models/rt_detr/model.py
@@ -268,9 +268,7 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
# Backbone renaming
new_name = re.sub(".branch2b.", ".convs.branch2b.", new_name)
new_name = re.sub(".branch2a.", ".convs.branch2a.", new_name)
- new_name = re.sub(".branch2c.", ".convs.branch2c.", new_name)
-
- return new_name
+ 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
@@ -297,8 +295,7 @@ class RTDETR(ONNXExportMixin, ModelBase[RTDETRConfig]):
num_classes: number of classes to detect.
"""
- model = RTDETR.from_config(RTDETRConfig.from_name(model_name, num_classes))
- return model
+ return RTDETR.from_config(RTDETRConfig.from_name(model_name, num_classes))
def to_onnx(
self,
diff --git a/kornia/models/sam/architecture/image_encoder.py b/kornia/models/sam/architecture/image_encoder.py
index 56c2bb608..695a80d79 100644
--- a/kornia/models/sam/architecture/image_encoder.py
+++ b/kornia/models/sam/architecture/image_encoder.py
@@ -154,9 +154,7 @@ class ImageEncoderViT(nn.Module):
for blk in self.blocks:
x = blk(x)
- x = self.neck(x.permute(0, 3, 1, 2))
-
- return x
+ return self.neck(x.permute(0, 3, 1, 2))
class Block(nn.Module):
@@ -229,9 +227,7 @@ class Block(nn.Module):
x = window_unpartition(x, self.window_size, pad_hw, (H, W))
x = shortcut + x
- x = x + self.mlp(self.norm2(x))
-
- return x
+ return x + self.mlp(self.norm2(x))
class Attention(nn.Module):
@@ -294,9 +290,7 @@ class Attention(nn.Module):
attn = attn.softmax(dim=-1)
x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
- x = self.proj(x)
-
- return x
+ return self.proj(x)
def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
@@ -366,12 +360,10 @@ def add_decomposed_rel_pos(
rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
- attn = (attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).view(
+ return (attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]).view(
B, q_h * q_w, k_h * k_w
)
- return attn
-
class PatchEmbed(nn.Module):
"""Image to Patch Embedding."""
@@ -411,5 +403,4 @@ class PatchEmbed(nn.Module):
"""
x = self.proj(x)
# B C H W -> B H W C
- x = x.permute(0, 2, 3, 1)
- return x
+ return x.permute(0, 2, 3, 1)
diff --git a/kornia/models/sam/architecture/prompt_encoder.py b/kornia/models/sam/architecture/prompt_encoder.py
index 28421a521..873445b66 100644
--- a/kornia/models/sam/architecture/prompt_encoder.py
+++ b/kornia/models/sam/architecture/prompt_encoder.py
@@ -123,8 +123,7 @@ class PromptEncoder(nn.Module):
def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
"""Embeds mask inputs."""
- mask_embedding = self.mask_downscaling(masks)
- return mask_embedding
+ return self.mask_downscaling(masks)
def _get_batch_size(
self,
diff --git a/kornia/models/sam/architecture/transformer.py b/kornia/models/sam/architecture/transformer.py
index f2d9f8877..eb9026a6e 100644
--- a/kornia/models/sam/architecture/transformer.py
+++ b/kornia/models/sam/architecture/transformer.py
@@ -286,6 +286,4 @@ class Attention(nn.Module):
# Get output
out = attn @ v
out = self._recombine_heads(out)
- out = self.out_proj(out)
-
- return out
+ return self.out_proj(out)
diff --git a/kornia/models/sam3/architecture/image_encoder.py b/kornia/models/sam3/architecture/image_encoder.py
index cc1d25f59..6af5eba26 100644
--- a/kornia/models/sam3/architecture/image_encoder.py
+++ b/kornia/models/sam3/architecture/image_encoder.py
@@ -73,8 +73,7 @@ class PatchEmbedding(nn.Module):
)
x = self.proj(x) # (B, embed_dim, H//patch_size, W//patch_size)
x = x.flatten(2).transpose(1, 2) # (B, H*W, embed_dim)
- x = self.norm(x)
- return x
+ return self.norm(x)
class ViTBlock(nn.Module):
@@ -109,8 +108,7 @@ class ViTBlock(nn.Module):
Output tensor of the same shape.
"""
x = x + self.attn(self.norm1(x))
- x = x + self.mlp(self.norm2(x))
- return x
+ return x + self.mlp(self.norm2(x))
class ImageEncoderHiera(nn.Module):
@@ -201,9 +199,7 @@ class ImageEncoderHiera(nn.Module):
x = block(x)
# Final normalization
- x = self.norm(x)
-
- return x
+ return self.norm(x)
def get_output_shape(self, input_shape: tuple[int, ...]) -> tuple[int, ...]:
"""Get output shape given input shape.
diff --git a/kornia/models/sam3/architecture/mask_decoder.py b/kornia/models/sam3/architecture/mask_decoder.py
index 8d48b6434..4cc44abf0 100644
--- a/kornia/models/sam3/architecture/mask_decoder.py
+++ b/kornia/models/sam3/architecture/mask_decoder.py
@@ -81,9 +81,7 @@ class CrossAttentionTransformer(nn.Module):
# MLP
prompts_norm = self.norm3(prompts)
mlp_out = self.mlp(prompts_norm)
- prompts = prompts + mlp_out
-
- return prompts
+ return prompts + mlp_out
class MaskDecoder(nn.Module):
diff --git a/kornia/models/sam3/architecture/prompt_encoder.py b/kornia/models/sam3/architecture/prompt_encoder.py
index 99c95825e..a7c65c26a 100644
--- a/kornia/models/sam3/architecture/prompt_encoder.py
+++ b/kornia/models/sam3/architecture/prompt_encoder.py
@@ -173,8 +173,7 @@ class PromptEncoder(nn.Module):
label_idx = min(label, 1) # 0 or 1 for background/foreground
label_embeddings[b, i] = self.point_embeddings[label_idx].weight[0]
- output = pe + label_embeddings
- return output
+ return pe + label_embeddings
def forward(
self,
diff --git a/kornia/models/siglip2/text_encoder.py b/kornia/models/siglip2/text_encoder.py
index 2e59a1d6e..e5aec3fbc 100644
--- a/kornia/models/siglip2/text_encoder.py
+++ b/kornia/models/siglip2/text_encoder.py
@@ -74,9 +74,7 @@ class SigLip2TextEmbeddings(nn.Module):
position_embeddings = self.position_embedding(position_ids)
# combine embeddings - [batch_size, seq_len, hidden_size]
- embeddings = token_embeddings + position_embeddings
-
- return embeddings
+ return token_embeddings + position_embeddings
class SigLip2TextMLP(nn.Module):
@@ -100,8 +98,7 @@ class SigLip2TextMLP(nn.Module):
hidden_states = self.activation(hidden_states)
# linear transformation - [batch_size, seq_len, hidden_size]
hidden_states = self.fc2(hidden_states)
- hidden_states = self.dropout(hidden_states)
- return hidden_states
+ return self.dropout(hidden_states)
class SigLip2TextLayer(nn.Module):
@@ -144,10 +141,9 @@ class SigLip2TextLayer(nn.Module):
residual = hidden_states
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.mlp(hidden_states)
- hidden_states = residual + hidden_states
+ return residual + hidden_states
# return the hidden states - [batch_size, seq_len, hidden_size]
- return hidden_states
class SigLip2TextEncoder(nn.Module):
diff --git a/kornia/models/siglip2/vision_encoder.py b/kornia/models/siglip2/vision_encoder.py
index 44d414008..6882a3797 100644
--- a/kornia/models/siglip2/vision_encoder.py
+++ b/kornia/models/siglip2/vision_encoder.py
@@ -85,9 +85,7 @@ class SigLip2VisionEmbeddings(nn.Module):
embeddings = embeddings.flatten(2).transpose(1, 2) # (batch_size, num_patches, hidden_size)
# add position embeddings to the embeddings
- embeddings = embeddings + self.position_embedding.unsqueeze(0)
-
- return embeddings
+ return embeddings + self.position_embedding.unsqueeze(0)
class SigLip2VisionMLP(nn.Module):
@@ -108,8 +106,7 @@ class SigLip2VisionMLP(nn.Module):
hidden_states = self.fc1(hidden_states)
hidden_states = self.activation(hidden_states)
hidden_states = self.fc2(hidden_states)
- hidden_states = self.dropout(hidden_states)
- return hidden_states
+ return self.dropout(hidden_states)
class SigLip2VisionLayer(nn.Module):
@@ -152,9 +149,7 @@ class SigLip2VisionLayer(nn.Module):
residual = hidden_states
hidden_states = self.layer_norm2(hidden_states)
hidden_states = self.mlp(hidden_states)
- hidden_states = residual + hidden_states
-
- return hidden_states
+ return residual + hidden_states
class SigLip2MultiheadAttentionPoolingHead(nn.Module):
diff --git a/kornia/models/small_sr.py b/kornia/models/small_sr.py
index ed2211e0d..f29f39fd1 100644
--- a/kornia/models/small_sr.py
+++ b/kornia/models/small_sr.py
@@ -82,8 +82,7 @@ class SmallSRNet(nn.Module):
x = self.relu(self.conv1(x))
x = self.relu(self.conv2(x))
x = self.relu(self.conv3(x))
- x = self.pixel_shuffle(self.conv4(x))
- return x
+ return self.pixel_shuffle(self.conv4(x))
def weight_init(module: nn.Module) -> None:
diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.py
index dc5f77240..4802356ea 100644
--- a/kornia/models/tiny_vit.py
+++ b/kornia/models/tiny_vit.py
@@ -168,8 +168,7 @@ class PatchMerging(nn.Module):
if x.ndim == 3:
x = x.transpose(1, 2).unflatten(2, self.input_resolution) # (B, H * W, C) -> (B, C, H, W)
x = self.conv3(self.conv2(self.conv1(x)))
- x = x.flatten(2).transpose(1, 2) # (B, C, H, W) -> (B, H * W, C)
- return x
+ return x.flatten(2).transpose(1, 2) # (B, C, H, W) -> (B, H * W, C)
class ConvLayer(nn.Module):
@@ -359,8 +358,7 @@ class Attention(nn.Module):
attn = attn.softmax(dim=-1)
x = (attn @ v).transpose(1, 2).reshape(B, N, self.dh)
- x = self.proj(x)
- return x
+ return self.proj(x)
class TinyViTBlock(nn.Module):
@@ -431,8 +429,7 @@ class TinyViTBlock(nn.Module):
x = self.local_conv(x)
x = x.view(B, C, L).transpose(1, 2)
- x = x + self.drop_path2(self.mlp(x))
- return x
+ return x + self.drop_path2(self.mlp(x))
class BasicLayer(nn.Module):
diff --git a/kornia/models/vit.py b/kornia/models/vit.py
index c31d325bf..f9ee9ceef 100644
--- a/kornia/models/vit.py
+++ b/kornia/models/vit.py
@@ -98,8 +98,7 @@ class MultiHeadAttention(nn.Module):
out = torch.einsum("bhal, bhlv -> bhav ", att, v)
out = out.permute(0, 2, 1, 3).contiguous().view(B, N, -1)
out = self.projection(out)
- out = self.projection_drop(out)
- return out
+ return self.projection_drop(out)
class TransformerEncoderBlock(nn.Sequential):
@@ -277,8 +276,7 @@ class VisionTransformer(nn.Module):
out = self.patch_embedding(x)
out = self.encoder(out)
- out = self.norm(out)
- return out
+ return self.norm(out)
@staticmethod
def from_config(variant: str, pretrained: bool = False, **kwargs: Any) -> VisionTransformer:
diff --git a/kornia/models/vit_mobile.py b/kornia/models/vit_mobile.py
index fa8b39b84..8758de884 100644
--- a/kornia/models/vit_mobile.py
+++ b/kornia/models/vit_mobile.py
@@ -309,8 +309,7 @@ class MobileViTBlock(nn.Module):
# Fusion
x = self.conv3(x)
x = torch.cat((x, y), 1)
- x = self.conv4(x)
- return x
+ return self.conv4(x)
class MobileViT(nn.Module):
@@ -404,5 +403,4 @@ class MobileViT(nn.Module):
x = self.mv2[6](x)
x = self.mvit[2](x)
- x = self.conv2(x)
- return x
+ return self.conv2(x)
diff --git a/kornia/onnx/download.py b/kornia/onnx/download.py
index 7e7a02661..357b42cae 100644
--- a/kornia/onnx/download.py
+++ b/kornia/onnx/download.py
@@ -55,8 +55,8 @@ class CachedDownloader:
file_name = f"{os.path.split(model_name)[-1]}{suffix}"
else:
file_name = os.path.split(model_name)[-1]
- file_path = os.path.join(*cache_dir.split(os.sep), *model_name.split(os.sep)[:-1], file_name)
- return file_path
+
+ return os.path.join(*cache_dir.split(os.sep), *model_name.split(os.sep)[:-1], file_name)
@classmethod
def download_to_cache(cls, url: str, name: str, download: bool = True, **kwargs: Any) -> str:
diff --git a/kornia/onnx/utils.py b/kornia/onnx/utils.py
index acadabdbc..8d8480166 100644
--- a/kornia/onnx/utils.py
+++ b/kornia/onnx/utils.py
@@ -61,8 +61,7 @@ class ONNXLoader(CachedDownloader):
**kwargs,
)
with open(file_path) as f:
- json_data = json.load(f)
- return json_data
+ return json.load(f)
if not download:
raise RuntimeError(f"File `{url}` not found. You may set `download=True`.")
diff --git a/pyproject.toml b/pyproject.toml
index 051531453..3457c7545 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -213,14 +213,7 @@ select = [
"PIE", # flake8-pie
"PL", # Pylint
"PYI", # flake8-pyi
- "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
+ "RET", # flake8-return
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"S", # flake8-bandit
@@ -253,7 +246,6 @@ select = [
# "PT", # flake8-pytest-style
# "PTH", # flake8-use-pathlib
# "Q", # flake8-quotes
- # "RET", # flake8-return
# "SIM", # flake8-simplify
# "SLF", # flake8-self
# "T20", # flake8-print
diff --git a/testing/geometry/create.py b/testing/geometry/create.py
index c70e1323b..0ff1ff2b9 100644
--- a/testing/geometry/create.py
+++ b/testing/geometry/create.py
@@ -39,8 +39,7 @@ def create_rectified_fundamental_matrix(
F_rect = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype).view(
1, 3, 3
)
- F_repeat = F_rect.expand(batch_size, 3, 3)
- return F_repeat
+ return F_rect.expand(batch_size, 3, 3)
def create_random_fundamental_matrix(
diff --git a/tests/contrib/test_kmeans.py b/tests/contrib/test_kmeans.py
index d784baf90..88188a165 100644
--- a/tests/contrib/test_kmeans.py
+++ b/tests/contrib/test_kmeans.py
@@ -150,14 +150,13 @@ class TestKMeans(BaseTester):
x = torch.vstack(
[x, torch.randn((500, 2), dtype=dtype, device=device) + torch.tensor((15, -12), dtype=dtype, device=device)]
)
- x = torch.vstack(
+ return torch.vstack(
[
x,
13 * torch.randn((500, 2), dtype=dtype, device=device)
+ torch.tensor((35, 15), dtype=dtype, device=device),
]
)
- return x
def test_module(self, device, dtype):
x = TestKMeans._create_data(device, dtype)
diff --git a/tests/enhance/test_adjust.py b/tests/enhance/test_adjust.py
index e073d7fc4..17d05cef4 100644
--- a/tests/enhance/test_adjust.py
+++ b/tests/enhance/test_adjust.py
@@ -1032,9 +1032,7 @@ class TestEqualize(BaseTester):
channel = torch.stack([row] * height).to(device, dtype)
image = torch.stack([channel] * channels).to(device, dtype)
- batch = torch.stack([image] * batch_size).to(device, dtype)
-
- return batch
+ return torch.stack([image] * batch_size).to(device, dtype)
class TestEqualize3D(BaseTester):
@@ -1126,9 +1124,7 @@ class TestEqualize3D(BaseTester):
channel = torch.stack([row] * height).to(device, dtype)
image = torch.stack([channel] * channels).to(device, dtype)
image3d = torch.stack([image] * depth).transpose(0, 1).to(device, dtype)
- batch = torch.stack([image3d] * batch_size).to(device, dtype)
-
- return batch
+ return torch.stack([image3d] * batch_size).to(device, dtype)
class TestSharpness(BaseTester):
diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.py
index ace625fbb..d634e9f9d 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -220,8 +220,7 @@ class TestEqualization(BaseTester):
def img(self, device, dtype):
height, width = 20, 20
# TODO: test with a more realistic pattern
- img = torch.arange(width, device=device).div(float(width - 1))[None].expand(height, width)[None][None]
- return img
+ return torch.arange(width, device=device).div(float(width - 1))[None].expand(height, width)[None][None]
def test_he(self, img):
# should be similar to enhance.equalize but slower. Similar because the lut is computed in a different way.
diff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.py
index 3cb835caf..19c40461f 100644
--- a/tests/geometry/calibration/test_pnp.py
+++ b/tests/geometry/calibration/test_pnp.py
@@ -39,9 +39,7 @@ class TestSolvePnpDlt(BaseTester):
kornia.geometry.project_points can be used.
"""
cam_points = kornia.geometry.transform_points(world_to_cam_4x4, world_points)
- img_points = kornia.geometry.project_points(cam_points, repeated_intrinsics)
-
- return img_points
+ return kornia.geometry.project_points(cam_points, repeated_intrinsics)
@staticmethod
def _get_world_points_and_img_points(cam_points, world_to_cam_4x4, repeated_intrinsics):
diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.py
index 96dddef49..a9c43dbeb 100644
--- a/tests/geometry/camera/test_pinhole.py
+++ b/tests/geometry/camera/test_pinhole.py
@@ -62,15 +62,13 @@ class TestCam2Pixel(BaseTester):
temp = torch.eye(4, device=device, dtype=dtype)
temp[0, 0], temp[0, 2] = fx, cx
temp[1, 1], temp[1, 2] = fy, cy
- intrinsics = temp.expand(batch_size, -1, -1)
- return intrinsics
+ return temp.expand(batch_size, -1, -1)
def _create_intrinsics_inv(self, batch_size, fx, fy, cx, cy, device, dtype):
temp = torch.eye(4, device=device, dtype=dtype)
temp[0, 0], temp[0, 2] = 1 / fx, -cx / fx
temp[1, 1], temp[1, 2] = 1 / fy, -cy / fy
- intrinsics_inv = temp.expand(batch_size, -1, -1)
- return intrinsics_inv
+ return temp.expand(batch_size, -1, -1)
def _get_samples(self, shape, low, high, device, dtype):
"""Return a tensor having the given shape and whose values are in the range [low, high)"""
@@ -214,15 +212,13 @@ class TestPixel2Cam(BaseTester):
temp = torch.eye(4, device=device, dtype=dtype)
temp[0, 0], temp[0, 2] = fx, cx
temp[1, 1], temp[1, 2] = fy, cy
- intrinsics = temp.expand(batch_size, -1, -1)
- return intrinsics
+ return temp.expand(batch_size, -1, -1)
def _create_intrinsics_inv(self, batch_size, fx, fy, cx, cy, device, dtype):
temp = torch.eye(4, device=device, dtype=dtype)
temp[0, 0], temp[0, 2] = 1 / fx, -cx / fx
temp[1, 1], temp[1, 2] = 1 / fy, -cy / fy
- intrinsics_inv = temp.expand(batch_size, -1, -1)
- return intrinsics_inv
+ return temp.expand(batch_size, -1, -1)
def _get_samples(self, shape, low, high, device, dtype):
"""Return a tensor having the given shape and whose values are in the range [low, high)"""
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index 4e244951a..253551ff9 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -54,8 +54,7 @@ def _download_image(url: str, filename: str = "") -> Path:
def png_image(tmp_path_factory):
url = "https://github.com/kornia/data/raw/main/simba.png"
filename = tmp_path_factory.mktemp("data") / "image.png"
- filename = _download_image(url, str(filename))
- return filename
+ return _download_image(url, str(filename))
@pytest.fixture(scope="session")
@@ -71,8 +70,7 @@ def rgba_png_image(tmp_path_factory):
def jpg_image(tmp_path_factory):
url = "https://github.com/kornia/data/raw/main/crowd.jpg"
filename = tmp_path_factory.mktemp("data") / "image.jpg"
- filename = _download_image(url, str(filename))
- return filename
+ return _download_image(url, str(filename))
@pytest.fixture(scope="session")
diff --git a/tests/onnx/test_sequential.py b/tests/onnx/test_sequential.py
index 1b1aa1942..5b4a9f057 100644
--- a/tests/onnx/test_sequential.py
+++ b/tests/onnx/test_sequential.py
@@ -37,8 +37,7 @@ class TestONNXSequential:
graph = make_graph([node], "test_graph", [input_info], [output_info])
op = onnx.OperatorSetIdProto()
op.version = 17
- model = make_model(graph, opset_imports=[op], ir_version=9)
- return model
+ return make_model(graph, opset_imports=[op], ir_version=9)
@pytest.fixture
def onnx_sequential(self, mock_model_proto):