Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(feature): add detailed missing public docstrings (#3737)

Jeevang1-epic7c2fee721659
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index 3f26d365b..c9bab83da 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -92,7 +92,8 @@ def select_seeds(
scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.
fnn12: Matches between keypoints of I_1 and I_2.
The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2
- mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.
+ mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on
+ 'force_seed_mnn' in the DEFAULT_CONFIG.
If None, it disables the mutual nearest neighbor filtering on seed point selection.
Expected a bool torch.Tensor with shape (num_keypoints_in_source_image,)
@@ -102,7 +103,7 @@ def select_seeds(
im1seeds: Keypoint index of chosen seeds in image I_1
im2seeds: Keypoint index of chosen seeds in image I_2
- """ # noqa: E501
+ """
im1neighmap = dist1 < R1**2 # (n1, n1)
# find out who scores higher than whom
im1scorescomp = scores1.unsqueeze(1) > scores1.unsqueeze(0) # (n1, n1)
diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.py
index f1c53e5f5..a72b10ecb 100644
--- a/kornia/feature/aliked/aliked.py
+++ b/kornia/feature/aliked/aliked.py
@@ -458,6 +458,16 @@ class DeformableConv2d(nn.Module):
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the module forward pass.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
h, w = x.shape[2:]
max_offset = max(h, w) / 4.0
out = self.offset_conv(x)
@@ -529,6 +539,16 @@ class ConvBlock(nn.Module):
self.bn2 = norm_layer(out_channels)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the module forward pass.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
x = self.gate(self.bn1(self.conv1(x)))
return self.gate(self.bn2(self.conv2(x)))
@@ -571,6 +591,16 @@ class ResBlock(nn.Module):
self.stride = stride
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the module forward pass.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
identity = x
out = self.gate(self.bn1(self.conv1(x)))
out = self.bn2(self.conv2(out))
diff --git a/kornia/feature/dedode/decoder.py b/kornia/feature/dedode/decoder.py
index 4d982d815..ef8e1fe26 100644
--- a/kornia/feature/dedode/decoder.py
+++ b/kornia/feature/dedode/decoder.py
@@ -40,6 +40,20 @@ class Decoder(nn.Module):
def forward(
self, features: torch.Tensor, context: Optional[torch.Tensor] = None, scale: Optional[int] = None
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ features: Input value used by this method.
+ context: Input value used by this method.
+ scale: Input value used by this method.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
if context is not None:
features = torch.cat((features, context), dim=1)
stuff = self.layers[scale](features)
@@ -106,6 +120,19 @@ class ConvRefiner(nn.Module):
bias=True,
norm_type=nn.BatchNorm2d,
):
+ """Create one decoder block for the requested scale.
+
+ Args:
+ in_dim: Input value used by this method.
+ out_dim: Input value used by this method.
+ dw: Input value used by this method.
+ kernel_size: Input value used by this method.
+ bias: Input value used by this method.
+ norm_type: Input value used by this method.
+
+ Returns:
+ Decoder block configured for the requested input and output channel counts.
+ """
num_groups = 1 if not dw else in_dim
if dw:
if out_dim % in_dim != 0:
@@ -125,6 +152,18 @@ class ConvRefiner(nn.Module):
return nn.Sequential(conv1, norm, relu, conv2)
def forward(self, feats: torch.Tensor) -> torch.Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ feats: Input value used by this method.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
_b, _c, _hs, _ws = feats.shape
# AMP is intentionally scoped to "cuda" only: float16 autocast on CPU is not
# supported by PyTorch and a no-op on MPS. Use amp_dtype=torch.float32 on
diff --git a/kornia/feature/dedode/descriptor.py b/kornia/feature/dedode/descriptor.py
index 2125a4cc6..9c4f37dc3 100644
--- a/kornia/feature/dedode/descriptor.py
+++ b/kornia/feature/dedode/descriptor.py
@@ -37,6 +37,18 @@ class DeDoDeDescriptor(nn.Module):
self,
images: torch.Tensor,
) -> torch.Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ images: Input value used by this method.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
features, sizes = self.encoder(images)
context = None
descriptions = None
diff --git a/kornia/feature/dedode/detector.py b/kornia/feature/dedode/detector.py
index 9283c0ede..1681494e8 100644
--- a/kornia/feature/dedode/detector.py
+++ b/kornia/feature/dedode/detector.py
@@ -37,6 +37,18 @@ class DeDoDeDetector(nn.Module):
self,
images: torch.Tensor,
) -> torch.Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ images: Input value used by this method.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
dtype = images.dtype
features, sizes = self.encoder(images)
context = None
diff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.py
index 9aa0d3c5d..a39768d26 100644
--- a/kornia/feature/dedode/encoder.py
+++ b/kornia/feature/dedode/encoder.py
@@ -42,6 +42,21 @@ class VGG19(nn.Module):
# AMP is intentionally scoped to "cuda" only: float16 autocast on CPU is not
# supported by PyTorch and a no-op on MPS. Use amp_dtype=torch.float32 on
# non-CUDA devices to disable AMP entirely.
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+ **kwargs: Additional keyword arguments accepted for compatibility with the shared encoder interface. They
+ are not used by this VGG19 batch-normalized backbone wrapper.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
with torch.autocast("cuda", enabled=self.amp, dtype=self.amp_dtype):
feats = []
sizes = []
@@ -80,6 +95,19 @@ class FrozenDINOv2(nn.Module):
self.dinov2_vitl14 = [dinov2_vitl14] # ugly hack to not show parameters to DDP
def forward(self, x: torch.Tensor): # type: ignore[no-untyped-def]
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
B, _C, H, W = x.shape
if self.dinov2_vitl14[0].device != x.device:
self.dinov2_vitl14[0] = self.dinov2_vitl14[0].to(x.device).to(self.amp_dtype)
@@ -100,6 +128,19 @@ class VGG_DINOv2(nn.Module):
self.frozen_dinov2 = FrozenDINOv2(**dinov2_kwargs)
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, Tuple[int, int]]:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
feats_vgg, sizes_vgg = self.vgg(x)
feat_dinov2, size_dinov2 = self.frozen_dinov2(x)
return feats_vgg + feat_dinov2, sizes_vgg + size_dinov2
diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.py
index c1a2be4e9..5170fc231 100644
--- a/kornia/feature/dedode/transformer/dinov2.py
+++ b/kornia/feature/dedode/transformer/dinov2.py
@@ -56,6 +56,19 @@ class BlockChunk(nn.ModuleList):
"""Implement a container for sequential execution of transformer block chunks."""
def forward(self, x):
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
for b in self:
x = b(x)
return x
@@ -180,14 +193,35 @@ class DinoVisionTransformer(nn.Module):
@property
def device(self):
+ """Return the device of the stored tensors or module parameters.
+
+ Returns:
+ Device used by the model parameters.
+ """
return self.cls_token.device
def init_weights(self):
+ """Initialize transformer weights.
+
+ Returns:
+ None. Model weights are initialized in place.
+ """
trunc_normal_(self.pos_embed, std=0.02)
nn.init.normal_(self.cls_token, std=1e-6)
named_apply(init_weights_vit_timm, self)
def interpolate_pos_encoding(self, x, w, h):
+ """Interpolate positional encodings to the current patch grid.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+ w: Input value used by this method.
+ h: Input value used by this method.
+
+ Returns:
+ Positional embedding tensor resized to match the current patch grid.
+ """
previous_dtype = x.dtype
npatch = x.shape[1] - 1
N = self.pos_embed.shape[1] - 1
@@ -214,6 +248,16 @@ class DinoVisionTransformer(nn.Module):
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
def prepare_tokens_with_masks(self, x, masks=None):
+ """Prepare image patch tokens before transformer encoding.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+ masks: Input value used by this method.
+
+ Returns:
+ Token sequence prepared with class token, positional embeddings, and optional masks.
+ """
_B, _nc, w, h = x.shape
x = self.patch_embed(x)
if masks is not None:
@@ -225,6 +269,15 @@ class DinoVisionTransformer(nn.Module):
return x
def forward_features_list(self, x_list, masks_list):
+ """Compute transformer features for a list of image tensors.
+
+ Args:
+ x_list: Input value used by this method.
+ masks_list: Input value used by this method.
+
+ Returns:
+ List of intermediate feature dictionaries, one per input image tensor.
+ """
x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
for blk in self.blocks:
x = blk(x)
@@ -244,6 +297,16 @@ class DinoVisionTransformer(nn.Module):
return output
def forward_features(self, x, masks=None):
+ """Compute transformer features for one image tensor.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+ masks: Input value used by this method.
+
+ Returns:
+ Feature dictionary produced by the transformer backbone.
+ """
if isinstance(x, list):
return self.forward_features_list(x, masks)
@@ -294,6 +357,19 @@ class DinoVisionTransformer(nn.Module):
return_class_token: bool = False,
norm=True,
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
+ """Return selected intermediate transformer layer outputs.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+ n: Current hourglass recursion depth.
+ reshape: Input value used by this method.
+ return_class_token: Input value used by this method.
+ norm: Input value used by this method.
+
+ Returns:
+ Tuple or list of intermediate transformer layer outputs.
+ """
if self.chunked_blocks:
outputs = self._get_intermediate_layers_chunked(x, n)
else:
@@ -313,6 +389,15 @@ class DinoVisionTransformer(nn.Module):
return tuple(outputs)
def forward(self, *args, is_training=False, **kwargs):
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
ret = self.forward_features(*args, **kwargs)
if is_training:
return ret
diff --git a/kornia/feature/dedode/transformer/layers/attention.py b/kornia/feature/dedode/transformer/layers/attention.py
index 0af518424..a0e4a25d6 100644
--- a/kornia/feature/dedode/transformer/layers/attention.py
+++ b/kornia/feature/dedode/transformer/layers/attention.py
@@ -72,6 +72,19 @@ class Attention(nn.Module):
self.proj_drop = nn.Dropout(proj_drop)
def forward(self, x: Tensor) -> Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
B, N, C = x.shape
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
@@ -91,6 +104,20 @@ class MemEffAttention(Attention):
"""Implement a memory-efficient version of Multi-Head Self-Attention using xFormers."""
def forward(self, x: Tensor, attn_bias=None) -> Tensor: # type: ignore[no-untyped-def]
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+ attn_bias: Input value used by this method.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
if not XFORMERS_AVAILABLE:
if attn_bias is not None:
raise ValueError("xFormers is required for nested tensors usage")
diff --git a/kornia/feature/dedode/transformer/layers/block.py b/kornia/feature/dedode/transformer/layers/block.py
index e0187ce76..d4863cb36 100644
--- a/kornia/feature/dedode/transformer/layers/block.py
+++ b/kornia/feature/dedode/transformer/layers/block.py
@@ -119,6 +119,20 @@ class Block(nn.Module):
self.sample_drop_ratio = drop_path
def forward(self, x: Tensor) -> Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
+
def attn_residual_func(x: Tensor) -> Tensor:
return self.ls1(self.attn(self.norm1(x)))
@@ -284,6 +298,18 @@ class NestedTensorBlock(Block):
return attn_bias.split(x)
def forward(self, x_or_x_list):
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x_or_x_list: Input value used by this method.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
if isinstance(x_or_x_list, Tensor):
return super().forward(x_or_x_list)
elif isinstance(x_or_x_list, list):
diff --git a/kornia/feature/dedode/transformer/layers/dino_head.py b/kornia/feature/dedode/transformer/layers/dino_head.py
index 7aaa73b58..63249229d 100644
--- a/kornia/feature/dedode/transformer/layers/dino_head.py
+++ b/kornia/feature/dedode/transformer/layers/dino_head.py
@@ -64,6 +64,19 @@ class DINOHead(nn.Module):
nn.init.constant_(m.bias, 0)
def forward(self, x):
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
x = self.mlp(x)
eps = 1e-6 if x.dtype == torch.float16 else 1e-12
x = nn.functional.normalize(x, dim=-1, p=2, eps=eps)
diff --git a/kornia/feature/dedode/transformer/layers/drop_path.py b/kornia/feature/dedode/transformer/layers/drop_path.py
index f5c7ba7aa..630127ab1 100644
--- a/kornia/feature/dedode/transformer/layers/drop_path.py
+++ b/kornia/feature/dedode/transformer/layers/drop_path.py
@@ -53,4 +53,17 @@ class DropPath(nn.Module):
self.drop_prob = drop_prob
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return drop_path(x, self.drop_prob, self.training)
diff --git a/kornia/feature/dedode/transformer/layers/layer_scale.py b/kornia/feature/dedode/transformer/layers/layer_scale.py
index d9314ceaa..fdfbe01db 100644
--- a/kornia/feature/dedode/transformer/layers/layer_scale.py
+++ b/kornia/feature/dedode/transformer/layers/layer_scale.py
@@ -49,4 +49,17 @@ class LayerScale(nn.Module):
self.gamma = nn.Parameter(init_values * torch.ones(dim))
def forward(self, x: Tensor) -> Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return x.mul_(self.gamma) if self.inplace else x * self.gamma
diff --git a/kornia/feature/dedode/transformer/layers/mlp.py b/kornia/feature/dedode/transformer/layers/mlp.py
index 1b77fc7a0..51ddcd698 100644
--- a/kornia/feature/dedode/transformer/layers/mlp.py
+++ b/kornia/feature/dedode/transformer/layers/mlp.py
@@ -60,6 +60,19 @@ class Mlp(nn.Module):
self.drop = nn.Dropout(drop)
def forward(self, x: Tensor) -> Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
x = self.fc1(x)
x = self.act(x)
x = self.drop(x)
diff --git a/kornia/feature/dedode/transformer/layers/patch_embed.py b/kornia/feature/dedode/transformer/layers/patch_embed.py
index f0a1609fd..60b844e66 100644
--- a/kornia/feature/dedode/transformer/layers/patch_embed.py
+++ b/kornia/feature/dedode/transformer/layers/patch_embed.py
@@ -85,6 +85,19 @@ class PatchEmbed(nn.Module):
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
def forward(self, x: Tensor) -> Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
_, _, H, W = x.shape
patch_H, patch_W = self.patch_size
KORNIA_CHECK(H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}")
@@ -99,6 +112,11 @@ class PatchEmbed(nn.Module):
return x
def flops(self) -> float:
+ """Estimate this layer computational cost.
+
+ Returns:
+ Estimated number of floating-point operations for this layer.
+ """
Ho, Wo = self.patches_resolution
flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
if self.norm is not None:
diff --git a/kornia/feature/dedode/transformer/layers/swiglu_ffn.py b/kornia/feature/dedode/transformer/layers/swiglu_ffn.py
index ab4639e85..0df40fc54 100644
--- a/kornia/feature/dedode/transformer/layers/swiglu_ffn.py
+++ b/kornia/feature/dedode/transformer/layers/swiglu_ffn.py
@@ -57,6 +57,19 @@ class SwiGLUFFN(nn.Module):
self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
def forward(self, x: Tensor) -> Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
x12 = self.w12(x)
x1, x2 = x12.chunk(2, dim=-1)
hidden = F.silu(x1) * x2
diff --git a/kornia/feature/dedode/vgg.py b/kornia/feature/dedode/vgg.py
index 9a5eff5c3..5872c6f50 100644
--- a/kornia/feature/dedode/vgg.py
+++ b/kornia/feature/dedode/vgg.py
@@ -60,6 +60,19 @@ class VGG(nn.Module):
nn.init.constant_(m.bias, 0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this DeDoDe module forward.
+
+ Inputs are image, feature, or token tensors used by the DeDoDe detector/descriptor pipeline. `B` denotes batch
+ size, `C` channels, `H` height, `W` width, `N` token count, and `D` feature dimension where those axes appear.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
x = self.features(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index c8565db70..88edf559e 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -100,6 +100,15 @@ class Bottleneck(nn.Module):
self.stride = stride
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the bottleneck residual block.
+
+ Args:
+ x: Feature tensor with shape :math:`(B, C, H, W)`, where ``B`` is batch
+ size, ``C`` is channel count, and ``H``/``W`` are spatial dimensions.
+
+ Returns:
+ Output feature tensor after the residual branch and identity connection.
+ """
identity = x
out = self.conv1(x)
@@ -247,6 +256,14 @@ class ResNet(nn.Module):
return x
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the ResNet backbone and classification head.
+
+ Args:
+ x: Input image or feature tensor with shape :math:`(B, C, H, W)`.
+
+ Returns:
+ Tensor with shape :math:`(B, N)`, where ``N`` is ``num_classes``.
+ """
return self._forward_impl(x)
@@ -271,6 +288,15 @@ class EncoderDeFMO(nn.Module):
self.net = nn.Sequential(modelc1, modelc2)
def forward(self, input_data: torch.Tensor) -> torch.Tensor:
+ """Encode blurred-image and background inputs into latent features.
+
+ Args:
+ input_data: Tensor with shape :math:`(B, 6, H, W)`. The 6 channels usually
+ concatenate RGB blurred input and RGB background estimate.
+
+ Returns:
+ Latent feature tensor produced by the modified ResNet encoder.
+ """
return self.net(input_data)
@@ -308,6 +334,16 @@ class RenderingDeFMO(nn.Module):
self.times = torch.linspace(0, 1, self.tsr_steps)
def forward(self, latent: torch.Tensor) -> torch.Tensor:
+ """Render a temporal RGBA sequence from latent DeFMO features.
+
+ Args:
+ latent: Latent feature tensor from :class:`EncoderDeFMO` with shape
+ :math:`(B, C, H, W)`.
+
+ Returns:
+ Tensor with shape :math:`(B, T, 4, H_{out}, W_{out})`, where ``T`` is the
+ number of rendered time steps and 4 represents RGBA channels.
+ """
times = self.times.to(latent.device).unsqueeze(0).repeat(latent.shape[0], 1)
renders = []
for ki in range(times.shape[1]):
@@ -367,6 +403,16 @@ class DeFMO(nn.Module):
self.eval()
def forward(self, input_data: torch.Tensor) -> torch.Tensor:
+ """Deblur a fast-moving object into a sequence of RGBA sub-frames.
+
+ Args:
+ input_data: Tensor with shape :math:`(B, 6, H, W)` containing the blurred
+ RGB image concatenated with an RGB background estimate.
+
+ Returns:
+ Tensor with shape :math:`(B, T, 4, H, W)`, where ``T`` is the number of
+ temporal sub-frames and 4 stores red, green, blue, and alpha channels.
+ """
latent = self.encoder(input_data)
x_out = self.rendering(latent)
return x_out
diff --git a/kornia/feature/disk/_unets/blocks.py b/kornia/feature/disk/_unets/blocks.py
index 42cb847ea..7afee19bf 100644
--- a/kornia/feature/disk/_unets/blocks.py
+++ b/kornia/feature/disk/_unets/blocks.py
@@ -23,16 +23,55 @@ from torch import nn
class TrivialUpsample(nn.Module):
+ """Bilinear upsampling layer used inside the thin DISK U-Net.
+
+ The layer doubles spatial height and width while keeping batch size and channel count unchanged.
+ """
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this DISK component forward.
+
+ Feature maps use `(B, C, H, W)`, where `B` is batch size, `C` channels, and `H`/`W` are spatial dimensions.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return F.interpolate(x, scale_factor=2, mode="bilinear", align_corners=False)
class TrivialDownsample(nn.Module):
+ """Average-pooling downsampling layer used inside the thin DISK U-Net.
+
+ The layer halves spatial height and width with a `2x2` average-pooling window.
+ """
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this DISK component forward.
+
+ Feature maps use `(B, C, H, W)`, where `B` is batch size, `C` channels, and `H`/`W` are spatial dimensions.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return F.avg_pool2d(x, 2)
class Conv(nn.Sequential):
+ """Convolution block used by the thin DISK U-Net.
+
+ The block optionally applies instance normalization and a PReLU gate before a same-padded convolution.
+ """
+
def __init__(self, in_: int, out_: int, size: int, skip_norm_and_gate: bool = False) -> None:
norm: nn.Module
nonl: nn.Module
@@ -51,6 +90,11 @@ class Conv(nn.Sequential):
class ThinUnetDownBlock(nn.Sequential):
+ """Downsampling block for the thin DISK U-Net encoder path.
+
+ The block optionally downsamples the feature map and then applies the configured convolution block.
+ """
+
def __init__(self, in_: int, out_: int, size: int = 5, is_first: bool = False) -> None:
self.in_ = in_
self.out_ = out_
@@ -67,6 +111,12 @@ class ThinUnetDownBlock(nn.Sequential):
class ThinUnetUpBlock(nn.Module):
+ """Upsampling block for the thin DISK U-Net decoder path.
+
+ The block upsamples the bottom feature map, concatenates it with the horizontal skip feature map, and applies a
+ convolution block.
+ """
+
def __init__(self, bottom_: int, horizontal_: int, out_: int, size: int = 5) -> None:
super().__init__()
@@ -79,6 +129,18 @@ class ThinUnetUpBlock(nn.Module):
self.conv = Conv(self.cat_, self.out_, size)
def forward(self, bot: torch.Tensor, hor: torch.Tensor) -> torch.Tensor:
+ """Run this DISK component forward.
+
+ Feature maps use `(B, C, H, W)`, where `B` is batch size, `C` channels, and `H`/`W` are spatial dimensions.
+
+ Args:
+ bot: Input value used by this method.
+ hor: Input value used by this method.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
bot_big = self.upsample(bot)
combined = torch.cat([bot_big, hor], dim=1)
diff --git a/kornia/feature/disk/_unets/unet.py b/kornia/feature/disk/_unets/unet.py
index 547d17ccb..034a3ffc6 100644
--- a/kornia/feature/disk/_unets/unet.py
+++ b/kornia/feature/disk/_unets/unet.py
@@ -26,6 +26,12 @@ from .blocks import ThinUnetDownBlock, ThinUnetUpBlock
class Unet(nn.Module):
+ """U-Net backbone used by DISK to predict dense feature maps.
+
+ The network follows an encoder-decoder layout with skip connections. Input and output tensors use `(B, C, H, W)`,
+ where `B` is batch size, `C` is channel count, and `H`/`W` are spatial dimensions.
+ """
+
def __init__(
self, in_features: int = 1, up: Optional[list[int]] = None, down: Optional[list[int]] = None, size: int = 5
) -> None:
@@ -59,6 +65,17 @@ class Unet(nn.Module):
self.n_params += param.numel()
def forward(self, inp: torch.Tensor) -> torch.Tensor:
+ """Run this DISK component forward.
+
+ Feature maps use `(B, C, H, W)`, where `B` is batch size, `C` channels, and `H`/`W` are spatial dimensions.
+
+ Args:
+ inp: Input tensor passed to the module.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
if inp.size(1) != self.in_features:
fmt = "Expected {} feature channels in input, got {}"
msg = fmt.format(self.in_features, inp.size(1))
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index 76b5f44b0..70cff4805 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -45,10 +45,20 @@ class DISKFeatures:
@property
def n(self) -> int:
+ """Return the number of stored keypoints.
+
+ Returns:
+ Number of detected DISK keypoints stored in this feature container.
+ """
return self.keypoints.shape[0]
@property
def device(self) -> Union[str, torch.device, None]:
+ """Return the device of the stored tensors or module parameters.
+
+ Returns:
+ Device used by the model parameters.
+ """
return self.keypoints.device
@property
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 0653db058..ca36c6e44 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -103,6 +103,14 @@ class HardNet(nn.Module):
return (x - mp.detach()) / (sp.detach() + eps)
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Compute HardNet descriptors for normalized 32x32 patches.
+
+ Args:
+ input: Grayscale patch tensor of shape :math:`(B, 1, 32, 32)`.
+
+ Returns:
+ L2-normalized descriptor tensor with shape :math:`(B, 128)`.
+ """
KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])
x_norm: torch.Tensor = self._normalize_input(input)
x_features: torch.Tensor = self.features(x_norm)
@@ -175,6 +183,11 @@ class HardNet8(nn.Module):
@staticmethod
def weights_init(m: object) -> None:
+ """Initialize convolutional layers for HardNet8.
+
+ Args:
+ m: Module instance passed by ``nn.Module.apply``.
+ """
if isinstance(m, nn.Conv2d):
nn.init.orthogonal_(m.weight.data, gain=0.6)
if m.bias is not None:
@@ -194,6 +207,14 @@ class HardNet8(nn.Module):
return (x - mp.detach()) / (sp.detach() + eps)
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Compute HardNet8 descriptors with PCA projection.
+
+ Args:
+ input: Grayscale patch tensor of shape :math:`(B, 1, 32, 32)`.
+
+ Returns:
+ L2-normalized descriptor tensor after learned PCA projection.
+ """
KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])
x_norm: torch.Tensor = self._normalize_input(input)
x_features: torch.Tensor = self.features(x_norm)
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index cdf45faaa..b5ee2ab8b 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -76,16 +76,39 @@ class FilterResponseNorm2d(nn.Module):
self.reset_parameters()
def reset_parameters(self) -> None:
+ """Reset learnable parameters to their initial values.
+
+ Returns:
+ None. The module parameters are reset in place.
+ """
nn.init.ones_(self.weight)
nn.init.zeros_(self.bias)
if self.is_eps_leanable:
nn.init.constant_(self.eps, self.init_eps)
def extra_repr(self) -> str:
+ """Return a compact text summary for module printing.
+
+ Returns:
+ Readable string summarizing the module configuration.
+ """
return "num_features={num_features}, eps={init_eps}".format(**self.__dict__)
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Compute the mean norm of activations per channel.
+ """Run the HyNet normalization or descriptor layer.
+
+ Patch tensors use `(B, C, H, W)`. For HyNet descriptors the expected input is usually grayscale `(B, 1, 32, 32)`
+ and the final descriptor has shape `(B, D)`.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
nu2 = x.pow(2).mean(dim=[2, 3], keepdim=True)
# Perform FRN.
@@ -127,12 +150,35 @@ class TLU(nn.Module):
def reset_parameters(self) -> None:
# nn.init.zeros_(self.tau)
+ """Reset learnable parameters to their initial values.
+
+ Returns:
+ None. The module parameters are reset in place.
+ """
nn.init.constant_(self.tau, -1)
def extra_repr(self) -> str:
+ """Return a compact text summary for module printing.
+
+ Returns:
+ Readable string summarizing the module configuration.
+ """
return "num_features={num_features}".format(**self.__dict__)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the HyNet normalization or descriptor layer.
+
+ Patch tensors use `(B, C, H, W)`. For HyNet descriptors the expected input is usually grayscale `(B, 1, 32, 32)`
+ and the final descriptor has shape `(B, D)`.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return torch.max(x, self.tau)
@@ -231,6 +277,19 @@ class HyNet(nn.Module):
self.eval()
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the HyNet normalization or descriptor layer.
+
+ Patch tensors use `(B, C, H, W)`. For HyNet descriptors the expected input is usually grayscale `(B, 1, 32, 32)`
+ and the final descriptor has shape `(B, D)`.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 962448bcc..d90882f08 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -391,6 +391,16 @@ class LocalFeatureMatcher(nn.Module):
return {"lafs": lafs0, "responses": resps0, "descriptors": descs0}
def no_match_output(self, device: Union[str, torch.device, None], dtype: torch.dtype) -> Dict[str, torch.Tensor]:
+ """Create an empty output structure when no correspondences are found.
+
+ Args:
+ device: Device on which empty tensors should be allocated.
+ dtype: Floating-point dtype used for keypoints/LAF/confidence.
+
+ Returns:
+ Dictionary with correctly typed empty tensors for all expected
+ output fields.
+ """
return {
"keypoints0": torch.empty(0, 2, device=device, dtype=dtype),
"keypoints1": torch.empty(0, 2, device=device, dtype=dtype),
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 9c59cc6a9..7568ad133 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -158,6 +158,21 @@ class Attention(nn.Module):
def forward(
self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, mask: Optional[torch.Tensor] = None
) -> torch.Tensor:
+ """Apply multi-head attention to query, key, and value tensors.
+
+ Args:
+ q: Query tensor with shape :math:`(B, H, N_q, D_h)`, where ``B`` is batch size,
+ ``H`` is the number of attention heads, ``N_q`` is the number of query tokens,
+ and ``D_h`` is the per-head descriptor dimension.
+ k: Key tensor with shape :math:`(B, H, N_k, D_h)`, where ``N_k`` is the number
+ of key tokens.
+ v: Value tensor with shape :math:`(B, H, N_k, D_h)`.
+ mask: Optional boolean attention mask. ``True`` entries mark token pairs that
+ are allowed to attend to each other.
+
+ Returns:
+ Attention output with shape :math:`(B, H, N_q, D_h)`.
+ """
if self.enable_flash and q.device.type == "cuda":
# use torch 2.0 scaled_dot_product_attention with flash
if self.has_sdp:
@@ -214,6 +229,18 @@ class SelfBlock(nn.Module):
encoding: torch.Tensor,
mask: Optional[torch.Tensor] = None,
) -> torch.Tensor:
+ """Update descriptors from one image using self-attention.
+
+ Args:
+ x: Descriptor tensor with shape :math:`(B, N, D)`, where ``B`` is batch size,
+ ``N`` is the number of local features, and ``D`` is descriptor dimension.
+ encoding: Positional encoding tensor aligned with ``x`` and used for rotary
+ position embedding inside attention.
+ mask: Optional boolean mask limiting which descriptors may attend to each other.
+
+ Returns:
+ Updated descriptor tensor with the same shape as ``x``.
+ """
qkv = self.Wqkv(x)
qkv = qkv.unflatten(-1, (self.num_heads, -1, 3)).transpose(1, 2)
q, k, v = qkv[..., 0], qkv[..., 1], qkv[..., 2]
@@ -255,11 +282,34 @@ class CrossBlock(nn.Module):
self.flash = None # type: ignore
def map_(self, func: Callable, x0: torch.Tensor, x1: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: # type: ignore
+ """Apply the same function to descriptor tensors from both images.
+
+ Args:
+ func: Callable applied independently to ``x0`` and ``x1``.
+ x0: Descriptor tensor for the first image.
+ x1: Descriptor tensor for the second image.
+
+ Returns:
+ A tuple containing ``func(x0)`` and ``func(x1)``.
+ """
return func(x0), func(x1)
def forward(
self, x0: torch.Tensor, x1: torch.Tensor, mask: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Exchange information between two images using cross-attention.
+
+ Args:
+ x0: Descriptor tensor from the first image with shape :math:`(B, M, D)`,
+ where ``M`` is the number of local features in image 0.
+ x1: Descriptor tensor from the second image with shape :math:`(B, N, D)`,
+ where ``N`` is the number of local features in image 1.
+ mask: Optional boolean mask with shape :math:`(B, H, M, N)` or a broadcastable
+ equivalent, marking valid descriptor pairs.
+
+ Returns:
+ A tuple ``(x0_out, x1_out)`` with updated descriptors for both images.
+ """
qk0, qk1 = self.map_(self.to_qk, x0, x1)
v0, v1 = self.map_(self.to_v, x0, x1)
qk0, qk1, v0, v1 = (t.unflatten(-1, (self.heads, -1)).transpose(1, 2) for t in (qk0, qk1, v0, v1))
@@ -305,6 +355,19 @@ class TransformerLayer(nn.Module):
mask0: Optional[torch.Tensor] = None,
mask1: Optional[torch.Tensor] = None,
) -> torch.Tensor:
+ """Run one LightGlue transformer layer over two descriptor sets.
+
+ Args:
+ desc0: Descriptor tensor from image 0 with shape :math:`(B, M, D)`.
+ desc1: Descriptor tensor from image 1 with shape :math:`(B, N, D)`.
+ encoding0: Positional encoding for ``desc0``.
+ encoding1: Positional encoding for ``desc1``.
+ mask0: Optional validity mask for descriptors in image 0.
+ mask1: Optional validity mask for descriptors in image 1.
+
+ Returns:
+ A tuple containing updated descriptor tensors for image 0 and image 1.
+ """
if mask0 is not None and mask1 is not None:
return self.masked_forward(desc0, desc1, encoding0, encoding1, mask0, mask1)
else:
@@ -322,6 +385,19 @@ class TransformerLayer(nn.Module):
mask0: torch.Tensor,
mask1: torch.Tensor,
) -> torch.Tensor:
+ """Run the transformer layer with explicit descriptor validity masks.
+
+ Args:
+ desc0: Descriptor tensor from image 0 with shape :math:`(B, M, D)`.
+ desc1: Descriptor tensor from image 1 with shape :math:`(B, N, D)`.
+ encoding0: Positional encoding for image 0 descriptors.
+ encoding1: Positional encoding for image 1 descriptors.
+ mask0: Boolean mask for valid image 0 descriptors.
+ mask1: Boolean mask for valid image 1 descriptors.
+
+ Returns:
+ A tuple with masked self-attention and cross-attention updates for both images.
+ """
mask = mask0 & mask1.transpose(-1, -2)
mask0 = mask0 & mask0.transpose(-1, -2)
mask1 = mask1 & mask1.transpose(-1, -2)
@@ -368,6 +444,15 @@ class MatchAssignment(nn.Module):
return scores, sim
def get_matchability(self, desc: torch.Tensor) -> torch.Tensor:
+ """Estimate how likely each descriptor is to obtain a valid match.
+
+ Args:
+ desc: Descriptor tensor with shape :math:`(B, N, D)`, where ``N`` is the
+ number of local features.
+
+ Returns:
+ Matchability probabilities with shape :math:`(B, N)`.
+ """
return torch.sigmoid(self.matchability(desc)).squeeze(-1)
@@ -567,6 +652,13 @@ class LightGlue(nn.Module):
def compile(
self, mode: str = "reduce-overhead", static_lengths: Sequence[int] = (256, 512, 768, 1024, 1280, 1536)
) -> None:
+ """Compile masked transformer layers with ``torch.compile``.
+
+ Args:
+ mode: Compilation mode forwarded to ``torch.compile``.
+ static_lengths: Descriptor sequence lengths prepared for compiled execution.
+ These lengths represent possible numbers of local features.
+ """
if self.conf.width_confidence != -1:
warnings.warn(
"Point pruning is partially disabled for compiled forward.",
@@ -829,6 +921,15 @@ class LightGlue(nn.Module):
return ratio_confident > self.conf.depth_confidence
def pruning_min_kpts(self, device: torch.device) -> int:
+ """Return the minimum keypoint count needed before pruning is enabled.
+
+ Args:
+ device: Torch device on which descriptors are processed.
+
+ Returns:
+ Minimum number of keypoints required for width pruning on that device.
+ A negative value disables pruning for the device.
+ """
if self.conf.flash and FLASH_AVAILABLE and device.type == "cuda":
return self.pruning_keypoint_thresholds["flash"]
else:
diff --git a/kornia/feature/lightglue_onnx/lightglue.py b/kornia/feature/lightglue_onnx/lightglue.py
index 7e7302422..195724059 100644
--- a/kornia/feature/lightglue_onnx/lightglue.py
+++ b/kornia/feature/lightglue_onnx/lightglue.py
@@ -92,6 +92,14 @@ class OnnxLightGlue:
self.session = ort.InferenceSession(weights, providers=providers)
def __call__(self, data: dict[str, dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
+ """Run the ONNX LightGlue matcher.
+
+ Args:
+ data: Dictionary containing image features, keypoints, descriptors, and image sizes for matching.
+
+ Returns:
+ Dictionary containing ONNX LightGlue matches and matching scores.
+ """
return self.forward(data)
def forward(self, data: dict[str, dict[str, torch.Tensor]]) -> dict[str, torch.Tensor]:
diff --git a/kornia/feature/loftr/backbone/resnet_fpn.py b/kornia/feature/loftr/backbone/resnet_fpn.py
index 5c7040aac..91a1ed256 100644
--- a/kornia/feature/loftr/backbone/resnet_fpn.py
+++ b/kornia/feature/loftr/backbone/resnet_fpn.py
@@ -55,6 +55,19 @@ class BasicBlock(nn.Module):
self.downsample = nn.Sequential(conv1x1(in_planes, planes, stride=stride), nn.BatchNorm2d(planes))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this LoFTR component forward.
+
+ The method processes coarse or fine matching tensors used by LoFTR. Shape symbols such as `B`, `C`, `H`, `W`,
+ `N`, and `D` refer to batch size, channels, height, width, token count, and feature dimension.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
y = x
y = self.relu(self.bn1(self.conv1(y)))
y = self.bn2(self.conv2(y))
@@ -124,6 +137,19 @@ class ResNetFPN_8_2(nn.Module):
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
# ResNet Backbone
+ """Run this LoFTR component forward.
+
+ The method processes coarse or fine matching tensors used by LoFTR. Shape symbols such as `B`, `C`, `H`, `W`,
+ `N`, and `D` refer to batch size, channels, height, width, token count, and feature dimension.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
x0 = self.relu(self.bn1(self.conv1(x)))
x1 = self.layer1(x0) # 1/2
x2 = self.layer2(x1) # 1/4
@@ -204,6 +230,19 @@ class ResNetFPN_16_4(nn.Module):
def forward(self, x: torch.Tensor) -> List[torch.Tensor]:
# ResNet Backbone
+ """Run this LoFTR component forward.
+
+ The method processes coarse or fine matching tensors used by LoFTR. Shape symbols such as `B`, `C`, `H`, `W`,
+ `N`, and `D` refer to batch size, channels, height, width, token count, and feature dimension.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
x0 = self.relu(self.bn1(self.conv1(x)))
x1 = self.layer1(x0) # 1/2
x2 = self.layer2(x1) # 1/4
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index b182af7f8..0718ffdcc 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -206,6 +206,16 @@ class LoFTR(nn.Module):
return out
def load_state_dict(self, state_dict: dict[str, Any], *args: Any, **kwargs: Any) -> Any: # type: ignore[override]
+ """Load a checkpoint state dictionary into the module.
+
+ Args:
+ state_dict: Checkpoint state dictionary whose keys are adapted to this module layout.
+ *args: Additional positional arguments forwarded to the parent `load_state_dict` implementation.
+ **kwargs: Additional keyword arguments forwarded to the parent `load_state_dict` implementation.
+
+ Returns:
+ Result returned by the parent `load_state_dict` implementation.
+ """
for k in list(state_dict.keys()):
if k.startswith("matcher."):
state_dict[k.replace("matcher.", "", 1)] = state_dict.pop(k)
diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.py
index e3753a697..c6b635e0e 100644
--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py
+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py
@@ -58,6 +58,22 @@ class FinePreprocess(nn.Module):
feat_c1: torch.Tensor,
data: Dict[str, Any],
) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Run this LoFTR component forward.
+
+ The method processes coarse or fine matching tensors used by LoFTR. Shape symbols such as `B`, `C`, `H`, `W`,
+ `N`, and `D` refer to batch size, channels, height, width, token count, and feature dimension.
+
+ Args:
+ feat_f0: Input value used by this method.
+ feat_f1: Input value used by this method.
+ feat_c0: Input value used by this method.
+ feat_c1: Input value used by this method.
+ data: Dictionary containing image features, keypoints, descriptors, and image sizes for matching.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
W = self.W
stride = data["hw0_f"][0] // data["hw0_c"][0]
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index 309a0ebe7..7b1363943 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -90,6 +90,15 @@ class FineMatching(nn.Module):
@torch.no_grad()
def get_fine_match(self, coords_normed: torch.Tensor, data: dict[str, Any]) -> None:
+ """Extract fine-level correspondences from the refined matching heatmap.
+
+ Args:
+ coords_normed: Input value used by this method.
+ data: Dictionary containing image features, keypoints, descriptors, and image sizes for matching.
+
+ Returns:
+ Dictionary updated with refined fine-level correspondences.
+ """
W, _, _, scale = self.W, self.WW, self.C, self.scale
# mkpts0_f and mkpts1_f
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index bcce01678..755e2a8c2 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -447,6 +447,18 @@ class DescriptorMatcherWithSteerer(nn.Module):
def matching_function(
self, d1: torch.Tensor, d2: torch.Tensor, dm: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Dispatch descriptor matching to the configured matching strategy.
+
+ Args:
+ d1: Descriptor tensor from the first image with shape `(N1, D)`, where `N1` is descriptor count and `D` is
+ descriptor dimension.
+ d2: Descriptor tensor from the second image with shape `(N2, D)`, where `N2` is descriptor count and `D` is
+ descriptor dimension.
+ dm: Optional descriptor-distance matrix used instead of recomputing distances from `d1` and `d2`.
+
+ Returns:
+ Tuple containing match distances or scores and index pairs selected by the configured matching strategy.
+ """
if self.match_mode == "nn":
return match_nn(d1, d2, dm=dm)
elif self.match_mode == "mnn":
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index ff0b2fc18..e86d5d81b 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -87,6 +87,16 @@ class MKDGradients(nn.Module):
self.grad = SpatialGradient(mode="diff", order=1, normalized=False)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Compute gradient magnitude and orientation channels for grayscale patches.
+
+ Args:
+ x: Patch tensor with shape :math:`(B, 1, H, W)`, where ``B`` is batch size,
+ ``1`` is the grayscale channel, and ``H``/``W`` are patch height and width.
+
+ Returns:
+ Tensor with shape :math:`(B, 2, H, W)`. Channel 0 stores gradient magnitude,
+ and channel 1 stores gradient orientation in radians.
+ """
if not isinstance(x, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
if not len(x.shape) == 4:
@@ -151,6 +161,16 @@ class VonMisesKernel(nn.Module):
self.register_buffer("weights", weights)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Embed orientation values with the Von Mises kernel basis.
+
+ Args:
+ x: Orientation tensor with shape :math:`(B, 1, H, W)`, where values are
+ angular orientations in radians.
+
+ Returns:
+ Kernel embedding with shape :math:`(B, D, H, W)`, where ``D`` is the
+ number of channels produced by the configured coefficient list.
+ """
if not isinstance(x, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
@@ -214,6 +234,16 @@ class EmbedGradients(nn.Module):
return mags
def forward(self, grads: torch.Tensor) -> torch.Tensor:
+ """Embed gradient magnitude and orientation into kernel descriptor channels.
+
+ Args:
+ grads: Gradient tensor with shape :math:`(B, 2, H, W)`. Channel 0 contains
+ magnitudes, and channel 1 contains orientations.
+
+ Returns:
+ Embedded gradient tensor with shape :math:`(B, D, H, W)`, where ``D`` is
+ the number of channels produced by the orientation kernel.
+ """
if not isinstance(grads, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(grads)}")
if not len(grads.shape) == 4:
@@ -342,6 +372,16 @@ class ExplicitSpacialEncoding(nn.Module):
return emb2, kron[:, 0]
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply explicit spatial encoding to embedded patch features.
+
+ Args:
+ x: Feature map with shape :math:`(B, C, H, W)`, where ``C`` must match
+ ``in_dims`` and ``H``/``W`` are expected to match ``fmap_size``.
+
+ Returns:
+ Encoded descriptor tensor with shape :math:`(B, D)`, where ``D`` is the
+ flattened spatial-kernel descriptor dimension.
+ """
if not isinstance(x, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)):
@@ -432,6 +472,13 @@ class Whitening(nn.Module):
self.load_whitening_parameters(whitening_model)
def load_whitening_parameters(self, whitening_model: Dict[str, Dict[str, torch.Tensor]]) -> None:
+ """Load and adapt whitening statistics for the selected transform.
+
+ Args:
+ whitening_model: Dictionary containing whitening tensors. The expected
+ entries are model variants such as ``"pca"`` or ``"lw"``, each holding
+ ``mean``, ``eigvecs`` (eigenvectors), and ``eigvals`` (eigenvalues).
+ """
algo = "lw" if self.xform == "lw" else "pca"
wh_model = whitening_model[algo]
self.mean.data = wh_model["mean"]
@@ -467,6 +514,16 @@ class Whitening(nn.Module):
self.evecs.data = self.evecs @ torch.diag(torch.pow(self.evals, m))
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Whiten and L2-normalize local descriptors.
+
+ Args:
+ x: Descriptor tensor with shape :math:`(N, D)`, where ``N`` is the number
+ of descriptors and ``D`` is the input descriptor dimension.
+
+ Returns:
+ Whitened descriptor tensor with shape :math:`(N, O)`, where ``O`` is
+ ``output_dims``.
+ """
if not isinstance(x, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
if not len(x.shape) == 2:
@@ -562,6 +619,16 @@ class MKDDescriptor(nn.Module):
self.eval()
def forward(self, patches: torch.Tensor) -> torch.Tensor:
+ """Compute Multiple Kernel Descriptor (MKD) vectors for image patches.
+
+ Args:
+ patches: Grayscale patch tensor with shape :math:`(B, 1, H, W)`, where
+ ``B`` is the number of patches and ``H``/``W`` are patch dimensions.
+
+ Returns:
+ Descriptor tensor with shape :math:`(B, D)`, where ``D`` is the configured
+ output descriptor dimension after optional whitening.
+ """
if not isinstance(patches, torch.Tensor):
raise TypeError(f"Input type is not a torch.Tensor. Got {type(patches)}")
if not len(patches.shape) == 4:
@@ -634,4 +701,13 @@ class SimpleKD(nn.Module):
self.features = nn.Sequential(smoothing, gradients, ori, ese, wh)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the example kernel-descriptor pipeline.
+
+ Args:
+ x: Grayscale patch tensor with shape :math:`(B, 1, H, W)`.
+
+ Returns:
+ Descriptor tensor produced by smoothing, gradient extraction, spatial
+ encoding, and whitening.
+ """
return self.features(x)
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 1627d04f2..b5b1fbcb7 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -333,6 +333,15 @@ class BlobDoG(nn.Module):
return self.__class__.__name__
def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Compute Difference-of-Gaussians response maps.
+
+ Args:
+ input: Input tensor of shape :math:`(B, C, H, W)`.
+ sigmas: Unused in this wrapper; kept for API compatibility.
+
+ Returns:
+ DoG response tensor from :func:`dog_response`.
+ """
return dog_response(input)
@@ -353,6 +362,16 @@ class BlobDoGSingle(nn.Module):
return f"{self.__class__.__name__}, sigma1={self.sigma1}, sigma2={self.sigma2})"
def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Compute single-scale Difference-of-Gaussians response.
+
+ Args:
+ input: Input tensor of shape :math:`(B, C, H, W)`.
+ sigmas: Unused in this wrapper; kept for API compatibility.
+
+ Returns:
+ Response tensor from :func:`dog_response_single` using stored
+ ``sigma1`` and ``sigma2``.
+ """
return dog_response_single(input, self.sigma1, self.sigma2)
@@ -378,6 +397,16 @@ class CornerHarris(nn.Module):
return f"{self.__class__.__name__}(k={self.k}, grads_mode={self.grads_mode})"
def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Compute Harris corner response for each input channel.
+
+ Args:
+ input: Input tensor of shape :math:`(B, C, H, W)`.
+ sigmas: Optional Gaussian smoothing values forwarded to
+ :func:`harris_response`.
+
+ Returns:
+ Harris response map tensor.
+ """
return harris_response(input, self.k, self.grads_mode, sigmas)
@@ -397,6 +426,15 @@ class CornerGFTT(nn.Module):
return f"{self.__class__.__name__}(grads_mode={self.grads_mode})"
def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Compute Shi-Tomasi (GFTT) corner response maps.
+
+ Args:
+ input: Input tensor of shape :math:`(B, C, H, W)`.
+ sigmas: Optional smoothing sigmas for multi-scale workflows.
+
+ Returns:
+ GFTT response map tensor from :func:`gftt_response`.
+ """
return gftt_response(input, self.grads_mode, sigmas)
@@ -416,4 +454,14 @@ class BlobHessian(nn.Module):
return f"{self.__class__.__name__}(grads_mode={self.grads_mode})"
def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Compute Hessian determinant-like blob responses.
+
+ Args:
+ input: Input tensor of shape :math:`(B, C, H, W)`.
+ sigmas: Optional smoothing values passed to
+ :func:`hessian_response`.
+
+ Returns:
+ Hessian response map tensor.
+ """
return hessian_response(input, self.grads_mode, sigmas)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 3f2489b12..7288caf5d 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -312,6 +312,17 @@ class ScaleSpaceDetector(nn.Module):
def detect(
self, img: torch.Tensor, num_feats: int, mask: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Detect local features in an image batch.
+
+ Args:
+ img: Input image tensor with shape `(B, C, H, W)`.
+ num_feats: Number of features requested from the detector.
+ mask: Optional mask tensor used to restrict valid image locations.
+
+ Returns:
+ Tuple containing detection scores and local affine frames. Local affine frames are usually shaped `(B, N, 2,
+ 3)`, where `N` is the selected feature count.
+ """
dev = img.device
dtype: torch.dtype = img.dtype
sp, sigmas, _ = self.scale_pyr(img)
@@ -469,6 +480,17 @@ class MultiResolutionDetector(nn.Module):
def detect_features_on_single_level(
self, level_img: torch.Tensor, num_kp: int, factor: Tuple[float, float]
) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Detect keypoints on one image-pyramid level.
+
+ Args:
+ level_img: Image tensor for a single pyramid level.
+ num_kp: Number of keypoints requested from this pyramid level.
+ factor: Scale factor mapping coordinates from the current pyramid level back to the original image
+ resolution.
+
+ Returns:
+ Tuple containing scores and local affine frames detected at the requested pyramid level.
+ """
det_map = self.nms(self.remove_borders(self.model(level_img)))
_, _, _h, w = det_map.shape
det_flat = det_map.view(-1) # (H*W,) β€” B=1, C=1 guaranteed by MultiResolutionDetector
@@ -493,6 +515,16 @@ class MultiResolutionDetector(nn.Module):
def detect(self, img: torch.Tensor, mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
# Compute points per level
+ """Detect local features in an image batch.
+
+ Args:
+ img: Input image tensor with shape `(B, C, H, W)`.
+ mask: Optional mask tensor used to restrict valid image locations.
+
+ Returns:
+ Tuple containing detection scores and local affine frames. Local affine frames are usually shaped `(B, N, 2,
+ 3)`, where `N` is the selected feature count.
+ """
num_features_per_level: List[float] = []
tmp = 0.0
factor_points = self.scale_factor_levels**2
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 75bbf769f..8314aa7a5 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -158,12 +158,32 @@ class SIFTDescriptor(nn.Module):
self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1)))
def get_pooling_kernel(self) -> torch.Tensor:
+ """Return the spatial pooling kernel used for histogram accumulation.
+
+ Returns:
+ Detached convolution kernel tensor from the pooling layer.
+ """
return self.pk.weight.detach()
def get_weighting_kernel(self) -> torch.Tensor:
+ """Return the Gaussian weighting kernel used before orientation pooling.
+
+ Returns:
+ Detached Gaussian kernel tensor.
+ """
return self.gk.detach()
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ r"""Compute SIFT descriptors for square grayscale patches.
+
+ Args:
+ input: Patch tensor shaped
+ :math:`(B, 1, \text{patch\_size}, \text{patch\_size})`.
+
+ Returns:
+ Descriptor tensor of size
+ :math:`(B, \text{num\_ang\_bins} \times \text{num\_spatial\_bins}^2)`.
+ """
KORNIA_CHECK_SHAPE(input, ["B", "1", f"{self.patch_size}", f"{self.patch_size}"])
B: int = input.shape[0]
self.pk = self.pk.to(input.dtype).to(input.device)
@@ -306,10 +326,24 @@ class DenseSIFTDescriptor(nn.Module):
self._pooling_kernel = self._bin_pooling_kernel_weight.detach()
def get_pooling_kernel(self) -> torch.Tensor:
+ """Return the cached pooling kernel for dense SIFT binning.
+
+ Returns:
+ Detached tensor containing pooling weights.
+ """
# Return the cached detached pooling kernel directly for optimal speed
return self._pooling_kernel
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Compute dense SIFT descriptors over a full image grid.
+
+ Args:
+ input: Grayscale image tensor with shape :math:`(B, 1, H, W)`.
+
+ Returns:
+ Dense descriptor map tensor with channel dimension
+ ``num_ang_bins * num_spatial_bins**2``.
+ """
KORNIA_CHECK_SHAPE(input, ["B", "1", "H", "W"])
_B, _CH, _W, _H = input.size()
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
index 8d6b216a5..aa6d94c5d 100644
--- a/kornia/feature/sold2/backbones.py
+++ b/kornia/feature/sold2/backbones.py
@@ -64,6 +64,19 @@ class HourglassBackbone(nn.Module):
self.net = hg(HourglassConfig(depth, num_stacks, num_blocks, num_classes, input_channel, head=self.head))
def forward(self, input_images: torch.Tensor) -> torch.Tensor:
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ input_images: Input image batch with shape `(B, C, H, W)`, where `B` is batch size, `C` is channel count,
+ and `H`/`W` are spatial dimensions.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return self.net(input_images)
@@ -88,6 +101,19 @@ class MultitaskHead(nn.Module):
self.heads = nn.ModuleList(heads)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return torch.cat([head(x) for head in self.heads], dim=1)
@@ -114,6 +140,19 @@ class Bottleneck2D(nn.Module):
self.stride = stride
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
residual = x
out = self.bn1(x)
@@ -186,6 +225,19 @@ class Hourglass(nn.Module):
return out
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return self._hour_glass_forward(self.depth, x)
@@ -256,6 +308,19 @@ class HourglassNet(nn.Module):
return nn.Sequential(conv, bn, self.relu)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
out = []
x = self.conv1(x)
x = self.bn1(x)
@@ -314,6 +379,18 @@ class SuperpointDecoder(nn.Module):
self.grid_size = grid_size
def forward(self, input_features: torch.Tensor) -> torch.Tensor:
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ input_features: Input feature map with shape `(B, C, H, W)`.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
feat = self.relu(self.convPa(input_features))
semi = self.convPb(feat)
@@ -379,6 +456,18 @@ class PixelShuffleDecoder(nn.Module):
def forward(self, input_features: torch.Tensor) -> torch.Tensor:
# Iterate til output block
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ input_features: Input feature map with shape `(B, C, H, W)`.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
out = input_features
for block in self.conv_block_lst[:-1]:
out = block(out)
@@ -409,6 +498,18 @@ class SuperpointDescriptor(nn.Module):
self.convPb = nn.Conv2d(256, 128, kernel_size=1, stride=1, padding=0)
def forward(self, input_features: torch.Tensor) -> torch.Tensor:
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ input_features: Input feature map with shape `(B, C, H, W)`.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
feat = self.relu(self.convPa(input_features))
semi = self.convPb(feat)
@@ -452,6 +553,19 @@ class SOLD2Net(nn.Module):
def forward(self, input_images: torch.Tensor) -> Dict[str, torch.Tensor]:
# The backbone
+ """Run this SOLD2 backbone component forward.
+
+ This method processes image or feature tensors used by the SOLD2 line detector. Tensor layouts follow `(B, C, H,
+ W)` for feature maps unless the surrounding class documentation states otherwise.
+
+ Args:
+ input_images: Input image batch with shape `(B, C, H, W)`, where `B` is batch size, `C` is channel count,
+ and `H`/`W` are spatial dimensions.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
features = self.backbone_net(input_images)
# junction decoder
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index 4e928a247..352fe8d8f 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -139,6 +139,14 @@ class SOLD2(nn.Module):
return self.line_matcher(line_seg1, line_seg2, desc1, desc2)
def adapt_state_dict(self, state_dict: Dict[str, Any]) -> Dict[str, Any]:
+ """Adapt pretrained checkpoint keys to this module implementation.
+
+ Args:
+ state_dict: Checkpoint state dictionary whose keys are adapted to this module layout.
+
+ Returns:
+ State dictionary with checkpoint keys renamed or removed so it can be loaded by the current module.
+ """
del state_dict["w_junc"]
del state_dict["w_heatmap"]
del state_dict["w_desc"]
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 5669f8686..b2797cbd1 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -85,6 +85,14 @@ class SOLD2_detector(nn.Module):
self.line_detector = LineSegmentDetectionModule(self.config.line_detector_cfg)
def adapt_state_dict(self, state_dict: Dict[str, Any]) -> Dict[str, Any]:
+ """Adapt pretrained checkpoint keys to this module implementation.
+
+ Args:
+ state_dict: Checkpoint state dictionary whose keys are adapted to this module layout.
+
+ Returns:
+ State dictionary with checkpoint keys renamed or removed so it can be loaded by the current module.
+ """
del state_dict["w_junc"]
del state_dict["w_heatmap"]
del state_dict["w_desc"]
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 9a1ef064c..c6bb9d053 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -83,6 +83,15 @@ class SOSNet(nn.Module):
self.eval()
def forward(self, input: torch.Tensor, eps: float = 1e-10) -> torch.Tensor:
+ """Compute SOSNet descriptors for grayscale 32x32 patches.
+
+ Args:
+ input: Input tensor with shape :math:`(B, 1, 32, 32)`.
+ eps: Small constant added before normalization for stability.
+
+ Returns:
+ Descriptor tensor with shape :math:`(B, 128)`.
+ """
KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])
descr = self.desc_norm(self.layers(input) + eps)
descr = descr.view(descr.size(0), -1)
diff --git a/kornia/feature/steerers.py b/kornia/feature/steerers.py
index 822756775..f3541906d 100644
--- a/kornia/feature/steerers.py
+++ b/kornia/feature/steerers.py
@@ -44,6 +44,15 @@ class DiscreteSteerer(nn.Module):
self.generator = torch.nn.Parameter(generator)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Apply one steering step in descriptor space.
+
+ Args:
+ x: Input descriptor tensor whose last dimension matches the
+ steerer generator size.
+
+ Returns:
+ Steered descriptors after one linear transformation.
+ """
return torch.nn.functional.linear(x, self.generator)
def steer_descriptions(
@@ -52,6 +61,16 @@ class DiscreteSteerer(nn.Module):
steerer_power: int = 1,
normalize: bool = False,
) -> torch.Tensor:
+ """Apply the steerer repeatedly to descriptor vectors.
+
+ Args:
+ descriptions: Descriptor tensor to steer.
+ steerer_power: Number of repeated steering applications.
+ normalize: If ``True``, L2-normalize descriptors after steering.
+
+ Returns:
+ Steered descriptors with optional normalization.
+ """
for _ in range(steerer_power):
descriptions = self.forward(descriptions)
if normalize:
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index c8af68309..31fc77edf 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -72,6 +72,14 @@ class TFeat(nn.Module):
self.eval()
def forward(self, input: torch.Tensor) -> torch.Tensor:
+ """Compute TFeat descriptors for grayscale 32x32 patches.
+
+ Args:
+ input: Input tensor with shape :math:`(B, 1, 32, 32)`.
+
+ Returns:
+ Descriptor tensor with shape :math:`(B, 128)`.
+ """
KORNIA_CHECK_SHAPE(input, ["B", "1", "32", "32"])
x = self.features(input)
x = x.view(x.size(0), -1)
diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.py
index 2b5b807a5..de18c10b9 100644
--- a/kornia/feature/xfeat.py
+++ b/kornia/feature/xfeat.py
@@ -74,6 +74,16 @@ class BasicLayer(nn.Module):
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Run the module forward pass.
+
+ Args:
+ x: Input tensor processed by this module. For image-like features this usually follows the `(B, C, H, W)`
+ layout, where `B` is batch size, `C` is channels, and `H`/`W` are height and width.
+
+ Returns:
+ Output tensor or dictionary produced by the module while preserving the shape contract documented by the
+ surrounding class.
+ """
return self.layer(x)