Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs: add missing docstrings for public classes (D101) (#3447)

Keshav Singh32aec762542c
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 751f76b78..7e290913c 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -183,6 +183,12 @@ class SequentialBase(BasicSequentialBase):
class ImageSequentialBase(SequentialBase):
+ """Provide a base class for sequential image-only augmentations.
+
+ This class handles the logic for applying a series of transformations
+ sequentially to input tensors while managing the transformation matrices.
+ """
+
def identity_matrix(self, input: torch.Tensor) -> torch.Tensor:
"""Return identity matrix."""
raise NotImplementedError
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index ce9eb231a..3e311917d 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -88,6 +88,15 @@ class SequentialOpsInterface(Generic[T], metaclass=ABCMeta):
class AugmentationSequentialOps:
+ """Implement the operational logic for the Augmentation Sequential container.
+
+ This class manages how data keys (e.g., IMAGE, MASK, BBOX) are handled
+ during the execution of an augmentation pipeline.
+
+ Args:
+ data_keys: A list of :class:`DataKey` defining the types of data to process.
+ """
+
def __init__(self, data_keys: Optional[List[DataKey]]) -> None:
self._data_keys = data_keys
@@ -201,6 +210,12 @@ def get_geometric_only_param(module: "K.container.ImageSequentialBase", param: L
class InputSequentialOps(SequentialOpsInterface[torch.Tensor]):
+ """Implement the operations for processing input tensors within a sequential container.
+
+ This class provides class methods to apply transformations and manage the
+ flow of data through the augmentation pipeline.
+ """
+
@classmethod
def transform(
cls, input: torch.Tensor, module: nn.Module, param: ParamItem, extra_args: Optional[Dict[str, Any]] = None
diff --git a/kornia/augmentation/container/params.py b/kornia/augmentation/container/params.py
index 50d4e72d8..b138609ae 100644
--- a/kornia/augmentation/container/params.py
+++ b/kornia/augmentation/container/params.py
@@ -23,10 +23,24 @@ __all__ = ["ParamItem", "PatchParamItem"]
class ParamItem(NamedTuple):
+ """Store the parameters for a single augmentation operation.
+
+ Attributes:
+ name: The name of the augmentation operation.
+ data: The dictionary of parameters or a list of nested parameters.
+ """
+
name: str
data: Optional[Union[Dict[str, torch.Tensor], List["ParamItem"]]]
class PatchParamItem(NamedTuple):
+ """Store parameters for patch-based augmentation operations.
+
+ Attributes:
+ indices: The list of patch indices where the augmentation is applied.
+ param: The specific :class:`ParamItem` containing the operation parameters.
+ """
+
indices: List[int]
param: ParamItem
diff --git a/kornia/config.py b/kornia/config.py
index ade48b88c..6ed670d40 100644
--- a/kornia/config.py
+++ b/kornia/config.py
@@ -23,6 +23,8 @@ __all__ = ["InstallationMode", "kornia_config"]
class InstallationMode(str, Enum):
+ """Represent the installation mode for external dependencies."""
+
# Ask the user if to install the dependencies
ASK = "ASK"
# Install the dependencies
@@ -37,6 +39,8 @@ class InstallationMode(str, Enum):
class LazyLoaderConfig:
+ """Configure lazy loading behavior for external dependencies."""
+
_installation_mode: InstallationMode = InstallationMode.ASK
@property
@@ -61,6 +65,8 @@ class LazyLoaderConfig:
@dataclass
class KorniaConfig:
+ """Configure Kornia's behavior."""
+
hub_models_dir: str
hub_onnx_dir: str
output_dir: str = "kornia_outputs"
diff --git a/kornia/constants.py b/kornia/constants.py
index 4f733d036..15aba0ac1 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -30,6 +30,8 @@ TKEnum = Union[str, int, T]
class _KORNIA_EnumMeta(EnumMeta):
+ """Custom metaclass for enums to support string and integer comparisons."""
+
def __iter__(self) -> Iterator[Enum]: # type: ignore[override]
return super().__iter__()
@@ -62,6 +64,8 @@ def _get(cls: Type[T], value: TKEnum[T]) -> T:
class Resample(Enum, metaclass=_KORNIA_EnumMeta):
+ """Represent the resampling mode for image interpolation."""
+
NEAREST = 0
BILINEAR = 1
BICUBIC = 2
@@ -72,6 +76,8 @@ class Resample(Enum, metaclass=_KORNIA_EnumMeta):
class BorderType(Enum, metaclass=_KORNIA_EnumMeta):
+ """Represent the border padding mode for image operations."""
+
CONSTANT = 0
REFLECT = 1
REPLICATE = 2
@@ -83,6 +89,8 @@ class BorderType(Enum, metaclass=_KORNIA_EnumMeta):
class SamplePadding(Enum, metaclass=_KORNIA_EnumMeta):
+ """Represent the padding mode used during spatial sampling."""
+
ZEROS = 0
BORDER = 1
REFLECTION = 2
@@ -94,6 +102,8 @@ class SamplePadding(Enum, metaclass=_KORNIA_EnumMeta):
class DType(Enum, metaclass=_KORNIA_EnumMeta):
+ """Represent the internal data types used across the library."""
+
INT64 = 0
FLOAT16 = 1
FLOAT32 = 2
diff --git a/kornia/contrib/super_resolution.py b/kornia/contrib/super_resolution.py
index c3ba46a9f..0f0e8a18c 100644
--- a/kornia/contrib/super_resolution.py
+++ b/kornia/contrib/super_resolution.py
@@ -163,6 +163,8 @@ class SuperResolution(ModelBase, ONNXExportMixin):
class RRDBNetBuilder:
+ """Provide a static factory to build Residual-in-Residual Dense Block (RRDB) networks."""
+
@staticmethod
def build(model_name: str = "RealESRNet_x4plus", pretrained: bool = True) -> SuperResolution:
if model_name == "RealESRGAN_x4plus":
@@ -205,6 +207,8 @@ class RRDBNetBuilder:
class SmallSRBuilder:
+ """Provide a static factory to build lightweight Super-Resolution models."""
+
@staticmethod
def build(
model_name: str = "small_sr", pretrained: bool = True, upscale_factor: int = 3, image_size: Optional[int] = None
diff --git a/kornia/core/mixin/onnx.py b/kornia/core/mixin/onnx.py
index de71ec187..0a0552464 100644
--- a/kornia/core/mixin/onnx.py
+++ b/kornia/core/mixin/onnx.py
@@ -165,6 +165,8 @@ class ONNXExportMixin:
class ONNXRuntimeMixin:
+ """Provide methods to manage ONNX Runtime inference sessions."""
+
def _create_session(
self,
op: onnx.ModelProto, # type:ignore
@@ -287,6 +289,8 @@ class ONNXRuntimeMixin:
class ONNXMixin:
+ """Provide functionality for exporting and loading models in ONNX format."""
+
def _load_op(
self,
arg: Union[onnx.ModelProto, str], # type:ignore
diff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.py
index fc0e50a15..9e4f398fb 100644
--- a/kornia/core/tensor_wrapper.py
+++ b/kornia/core/tensor_wrapper.py
@@ -45,6 +45,12 @@ def unwrap(v):
class TensorWrapper:
+ """Wrap a PyTorch Tensor to provide additional metadata and specialized methods.
+
+ Args:
+ data: The underlying :class:`torch.Tensor` to be wrapped.
+ """
+
def __init__(self, data: Tensor) -> None:
self.__dict__["_data"] = data
self.__dict__["used_attrs"] = set()
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 4f75398d0..3e2310243 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -117,6 +117,15 @@ def match_adalam(
class AdalamFilter:
+ """Implement the AdaLAM (Adaptive Locally-Affine Matching) filter for outlier rejection.
+
+ This class wraps the AdaLAM algorithm to filter feature matches based on
+ local affine consistency.
+
+ Args:
+ custom_config: Optional configuration object for AdaLAM parameters.
+ """
+
def __init__(self, custom_config: Optional[AdalamConfig] = None) -> None:
"""Wrap the method AdaLAM for outlier filtering.
diff --git a/kornia/feature/dedode/decoder.py b/kornia/feature/dedode/decoder.py
index bd7d34ac8..9cffa546d 100644
--- a/kornia/feature/dedode/decoder.py
+++ b/kornia/feature/dedode/decoder.py
@@ -22,6 +22,14 @@ from torch import nn
class Decoder(nn.Module):
+ """Implement the decoder module for DeDoDe feature extraction.
+
+ Args:
+ layers: The architectural layers for the decoder.
+ super_resolution: Whether to apply super-resolution upsampling.
+ num_prototypes: The number of prototypes for the output head.
+ """
+
def __init__(self, layers: Any, *args, super_resolution: bool = False, num_prototypes: int = 1, **kwargs) -> None: # type: ignore[no-untyped-def]
super().__init__(*args, **kwargs)
self.layers = layers
@@ -40,6 +48,20 @@ class Decoder(nn.Module):
class ConvRefiner(nn.Module):
+ """Implement a convolutional refiner for DeDoDe feature extraction.
+
+ Args:
+ in_dim: The input dimension for the refiner.
+ hidden_dim: The hidden dimension for the refiner.
+ out_dim: The output dimension for the refiner.
+ dw: Whether to use depthwise convolution.
+ kernel_size: The kernel size for the convolution.
+ hidden_blocks: The number of hidden blocks in the refiner.
+ amp: Whether to use automatic mixed precision.
+ residual: Whether to use residual connections.
+ amp_dtype: The data type for automatic mixed precision.
+ """
+
def __init__( # type: ignore[no-untyped-def]
self,
in_dim=6,
diff --git a/kornia/feature/dedode/descriptor.py b/kornia/feature/dedode/descriptor.py
index a598c3b47..5296a7ad9 100644
--- a/kornia/feature/dedode/descriptor.py
+++ b/kornia/feature/dedode/descriptor.py
@@ -21,6 +21,13 @@ from torch import nn
class DeDoDeDescriptor(nn.Module):
+ """Implement the DeDoDe descriptor for learning local feature representations.
+
+ Args:
+ encoder: The backbone encoder module.
+ decoder: The decoder module for descriptor generation.
+ """
+
def __init__(self, encoder: nn.Module, decoder: nn.Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
super().__init__(*args, **kwargs)
self.encoder = encoder
diff --git a/kornia/feature/dedode/detector.py b/kornia/feature/dedode/detector.py
index 9ad5b0390..9283c0ede 100644
--- a/kornia/feature/dedode/detector.py
+++ b/kornia/feature/dedode/detector.py
@@ -21,6 +21,13 @@ from torch import nn
class DeDoDeDetector(nn.Module):
+ """Implement the DeDoDe detector for keypoint learning and localization.
+
+ Args:
+ encoder: The backbone encoder module.
+ decoder: The decoder module for probability map generation.
+ """
+
def __init__(self, encoder: nn.Module, decoder: nn.Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]
super().__init__(*args, **kwargs)
self.encoder = encoder
diff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.py
index 74a43ca27..c9f2b8006 100644
--- a/kornia/feature/dedode/encoder.py
+++ b/kornia/feature/dedode/encoder.py
@@ -24,6 +24,13 @@ from .vgg import vgg19_bn
class VGG19(nn.Module):
+ """Implement the VGG19 encoder for feature encoding.
+
+ Args:
+ amp: Whether to use automatic mixed precision.
+ amp_dtype: The data type for automatic mixed precision.
+ """
+
def __init__(self, amp: bool = False, amp_dtype: torch.dtype = torch.float16) -> None:
super().__init__()
self.layers = nn.ModuleList(vgg19_bn().features[:40]) # type: ignore
@@ -44,6 +51,8 @@ class VGG19(nn.Module):
class FrozenDINOv2(nn.Module):
+ """Implement a wrapper for a frozen DINOv2 vision transformer backbone."""
+
def __init__(self, amp: bool = True, amp_dtype: torch.dtype = torch.float16, dinov2_weights: Optional[Any] = None):
super().__init__()
if dinov2_weights is None:
@@ -78,6 +87,8 @@ class FrozenDINOv2(nn.Module):
class VGG_DINOv2(nn.Module):
+ """Implement a hybrid encoder combining VGG and DINOv2 features."""
+
def __init__(self, vgg_kwargs=None, dinov2_kwargs=None): # type: ignore[no-untyped-def]
if (vgg_kwargs is None) or (dinov2_kwargs is None):
raise ValueError("Input kwargs please")
diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.py
index cb61e6b84..7859a70c9 100644
--- a/kornia/feature/dedode/transformer/dinov2.py
+++ b/kornia/feature/dedode/transformer/dinov2.py
@@ -53,6 +53,8 @@ def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, incl
class BlockChunk(nn.ModuleList):
+ """Implement a container for sequential execution of transformer block chunks."""
+
def forward(self, x):
for b in self:
x = b(x)
@@ -60,6 +62,8 @@ class BlockChunk(nn.ModuleList):
class DinoVisionTransformer(nn.Module):
+ """Implement the DINOv2 Vision Transformer architecture."""
+
def __init__(
self,
img_size=224,
diff --git a/kornia/feature/dedode/transformer/layers/attention.py b/kornia/feature/dedode/transformer/layers/attention.py
index ba8206dab..0af518424 100644
--- a/kornia/feature/dedode/transformer/layers/attention.py
+++ b/kornia/feature/dedode/transformer/layers/attention.py
@@ -41,6 +41,17 @@ except ImportError:
class Attention(nn.Module):
+ """Implement the standard Multi-Head Self-Attention mechanism.
+
+ Args:
+ dim: Total dimension of the input and output features.
+ num_heads: Number of attention heads.
+ qkv_bias: If True, add a bias term to the query, key, and value projections.
+ proj_bias: If True, add a bias term to the output projection.
+ attn_drop: Dropout probability applied to the attention weights.
+ proj_drop: Dropout probability applied to the output projection.
+ """
+
def __init__(
self,
dim: int,
@@ -77,6 +88,8 @@ class Attention(nn.Module):
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]
if not XFORMERS_AVAILABLE:
if attn_bias is not None:
diff --git a/kornia/feature/dedode/transformer/layers/block.py b/kornia/feature/dedode/transformer/layers/block.py
index 324c8889e..e0187ce76 100644
--- a/kornia/feature/dedode/transformer/layers/block.py
+++ b/kornia/feature/dedode/transformer/layers/block.py
@@ -51,6 +51,28 @@ except ImportError:
class Block(nn.Module):
+ """Implement a transformer block with attention and feed-forward sublayers.
+
+ Args:
+ dim: Embedding dimension of the input and output features.
+ num_heads: Number of attention heads.
+ mlp_ratio: Expansion ratio used to compute the hidden dimension of the feed-forward network
+ as ``int(dim * mlp_ratio)``.
+ qkv_bias: If True, add a learnable bias to the query, key and value projections.
+ proj_bias: If True, add a learnable bias to the output projection of the attention layer.
+ ffn_bias: If True, add a learnable bias to the linear layers in the feed-forward network.
+ drop: Dropout probability applied after attention projection and inside the feed-forward network.
+ attn_drop: Dropout probability applied to the attention weights.
+ init_values: Initial value for the :class:`LayerScale` modules. If falsy, LayerScale is disabled
+ and an identity mapping is used instead.
+ drop_path: Stochastic depth probability for dropping the residual branch.
+ act_layer: Callable that constructs the activation layer used in the feed-forward network.
+ norm_layer: Callable that constructs the normalization layers applied before attention and
+ feed-forward sublayers.
+ attn_class: Callable that constructs the attention module.
+ ffn_layer: Callable that constructs the feed-forward network module.
+ """
+
def __init__(
self,
dim: int,
@@ -221,6 +243,8 @@ def drop_add_residual_stochastic_depth_list(
class NestedTensorBlock(Block):
+ """Implement a Transformer block capable of processing :class:`torch.NestedTensor` inputs."""
+
def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
"""x_list contains a list of tensors to nest together and run."""
KORNIA_CHECK(isinstance(self.attn, MemEffAttention))
diff --git a/kornia/feature/dedode/transformer/layers/dino_head.py b/kornia/feature/dedode/transformer/layers/dino_head.py
index 00d6090cd..7aaa73b58 100644
--- a/kornia/feature/dedode/transformer/layers/dino_head.py
+++ b/kornia/feature/dedode/transformer/layers/dino_head.py
@@ -28,6 +28,18 @@ from torch.nn.utils import weight_norm
class DINOHead(nn.Module):
+ """Implement the projection head for DINO-based models.
+
+ Args:
+ in_dim: Input feature dimensionality.
+ out_dim: Output feature dimensionality of the projection head.
+ use_bn: Whether to use batch normalization layers in the MLP.
+ nlayers: Number of layers in the MLP projection head. A value smaller than 1 is clamped to 1.
+ hidden_dim: Hidden dimensionality used in intermediate MLP layers when ``nlayers > 1``.
+ bottleneck_dim: Dimensionality of the bottleneck output of the MLP before the final normalized layer.
+ mlp_bias: Whether to include bias terms in the MLP linear layers.
+ """
+
def __init__(
self,
in_dim,
diff --git a/kornia/feature/dedode/transformer/layers/layer_scale.py b/kornia/feature/dedode/transformer/layers/layer_scale.py
index 90af95de1..d9314ceaa 100644
--- a/kornia/feature/dedode/transformer/layers/layer_scale.py
+++ b/kornia/feature/dedode/transformer/layers/layer_scale.py
@@ -30,6 +30,14 @@ from torch import Tensor, nn
class LayerScale(nn.Module):
+ """Implement the LayerScale mechanism for stabilizing transformer training.
+
+ Args:
+ dim: Dimensionality of the input features used to define the size of the scaling parameter.
+ init_values: Initial value or tensor used to initialize the learnable scaling parameter ``gamma``.
+ inplace: If True, apply the scaling operation in-place on the input tensor.
+ """
+
def __init__(
self,
dim: int,
diff --git a/kornia/feature/dedode/transformer/layers/mlp.py b/kornia/feature/dedode/transformer/layers/mlp.py
index 761c3e528..1b77fc7a0 100644
--- a/kornia/feature/dedode/transformer/layers/mlp.py
+++ b/kornia/feature/dedode/transformer/layers/mlp.py
@@ -32,6 +32,16 @@ from torch import Tensor, nn
class Mlp(nn.Module):
+ """Implement the Multi-Layer Perceptron (MLP) used in transformer blocks.
+
+ Args:
+ in_features: The number of input features.
+ hidden_features: The number of hidden layer features. Default: None.
+ out_features: The number of output features. Default: None.
+ act_layer: The activation function to use. Default: :class:`nn.GELU`.
+ drop: The dropout probability. Default: 0.0.
+ """
+
def __init__(
self,
in_features: int,
diff --git a/kornia/feature/dedode/transformer/layers/swiglu_ffn.py b/kornia/feature/dedode/transformer/layers/swiglu_ffn.py
index 637fb53c3..ab4639e85 100644
--- a/kornia/feature/dedode/transformer/layers/swiglu_ffn.py
+++ b/kornia/feature/dedode/transformer/layers/swiglu_ffn.py
@@ -28,6 +28,19 @@ from torch import Tensor, nn
class SwiGLUFFN(nn.Module):
+ """Implement the SwiGLU Feed-Forward Network.
+
+ This block uses the Gated Linear Unit with Swish activation, common in
+ modern transformer architectures like DINOv2.
+
+ Args:
+ in_features: The number of input features.
+ hidden_features: The number of hidden features in the gating branch.
+ out_features: The number of output features. Default: None.
+ act_layer: The activation function. Default: :class:`nn.SiLU`.
+ drop: The dropout probability. Default: 0.0.
+ """
+
def __init__(
self,
in_features: int,
@@ -60,6 +73,11 @@ except ImportError:
class SwiGLUFFNFused(SwiGLU):
+ """Implement the fused SwiGLU activation and Feed-Forward Network.
+
+ This implementation is optimized for training speed and memory usage.
+ """
+
def __init__(
self,
in_features: int,
diff --git a/kornia/feature/dedode/vgg.py b/kornia/feature/dedode/vgg.py
index cf3194795..db0c834db 100644
--- a/kornia/feature/dedode/vgg.py
+++ b/kornia/feature/dedode/vgg.py
@@ -22,6 +22,15 @@ from torch import nn
class VGG(nn.Module):
+ """Implement a flexible VGG-style backbone for feature extraction.
+
+ Args:
+ features: The convolutional feature extractor module.
+ num_classes: The number of classes for the classification head. Default: 1000.
+ init_weights: Whether to initialize weights using a predefined scheme. Default: True.
+ dropout: The dropout probability for the classifier. Default: 0.5.
+ """
+
def __init__(
self, features: nn.Module, num_classes: int = 1000, init_weights: bool = True, dropout: float = 0.5
) -> None:
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index 444726a1c..c8565db70 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -49,6 +49,22 @@ def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, d
class Bottleneck(nn.Module):
+ """Implement the Bottleneck building block for ResNet.
+
+ This block follows the ResNet V1.5 design where the stride is applied to the 3x3 convolution
+ instead of the first 1x1 convolution to better preserve spatial information.
+
+ Args:
+ inplanes: The number of input channels.
+ planes: The number of intermediate channels.
+ stride: The stride size for the convolution. Default: 1.
+ downsample: An optional module to downsample the input identity. Default: None.
+ groups: The number of blocked connections from input channels to output channels. Default: 1.
+ base_width: The width of each group. Default: 64.
+ dilation: The spacing between kernel elements. Default: 1.
+ norm_layer: The normalization layer to use. Default: None.
+ """
+
# Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)
# while original implementation places the stride at the first 1x1 convolution(self.conv1)
# according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.
@@ -107,6 +123,22 @@ class Bottleneck(nn.Module):
class ResNet(nn.Module):
+ """Implement the ResNet architecture for feature extraction.
+
+ This implementation provides a flexible backbone used as the encoder in the DeFMO framework.
+
+ Args:
+ block: The block type to use, typically :class:`Bottleneck`.
+ layers: A list containing the number of blocks in each of the four stages.
+ num_classes: The number of output classes. Default: 1000.
+ zero_init_residual: Whether to initialize the last batch norm in each residual branch to zero. Default: False.
+ groups: The number of groups for the convolution. Default: 1.
+ width_per_group: The width of each group. Default: 64.
+ replace_stride_with_dilation: A list of booleans indicating
+ if stride should be replaced by dilation in each stage. Default: None.
+ norm_layer: The normalization layer to use. Default: None.
+ """
+
def __init__(
self,
block: Type[Bottleneck],
@@ -219,6 +251,17 @@ class ResNet(nn.Module):
class EncoderDeFMO(nn.Module):
+ """Implement the Encoder module for the Deblurring Fast Moving Objects (DeFMO) model.
+
+ The encoder extracts latent features from the concatenation of the blurred input image and
+ the estimated background. It uses a modified ResNet-50 backbone to accept 6-channel inputs.
+
+
+ Shape:
+ - Input: (B, 6, H, W) where 6 represents the concatenated blurred image and background.
+ - Output: A list of feature maps from different stages of the ResNet backbone.
+ """
+
def __init__(self) -> None:
super().__init__()
model = ResNet(Bottleneck, [3, 4, 6, 3]) # ResNet50
@@ -232,6 +275,16 @@ class EncoderDeFMO(nn.Module):
class RenderingDeFMO(nn.Module):
+ """Implement the Rendering module for the Deblurring Fast Moving Objects (DeFMO) model.
+
+ This module acts as a decoder that transforms the latent features from the encoder into
+ a temporal sequence of sharp sub-frames, recovering the object's appearance and motion.
+
+ Shape:
+ - Input: Latent feature representation from the :class:`EncoderDeFMO`.
+ - Output: (B, T, 4, H, W) where T is the number of sub-frames and 4 represents RGBA channels.
+ """
+
def __init__(self) -> None:
super().__init__()
self.tsr_steps: int = 24
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index 8837f8ef0..c70c285d3 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -29,6 +29,13 @@ from .scale_space_detector import Detector_config, MultiResolutionDetector, get_
class KeyNet_conf(TypedDict):
+ """Define the configuration schema for the KeyNet feature detector.
+
+ Attributes:
+ num_filters: The number of filters in the convolutional layers.
+ num_levels: The number of levels in the image pyramid.
+ """
+
num_filters: int
num_levels: int
kernel_size: int
diff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.py
index 79c3b87ce..bba5adfc2 100644
--- a/kornia/feature/lightglue.py
+++ b/kornia/feature/lightglue.py
@@ -80,6 +80,18 @@ def apply_cached_rotary_emb(freqs: torch.Tensor, t: torch.Tensor) -> torch.Tenso
class LearnableFourierPositionalEncoding(nn.Module):
+ """Implement learnable Fourier features for positional encoding.
+
+ This module encodes spatial coordinates into high-dimensional embeddings
+ using a learnable projection and periodic functions.
+
+ Args:
+ M: The number of frequencies to use.
+ dim: The dimension of the output embedding.
+ F_dim: The dimension of the Fourier features. Default: None.
+ gamma: The scaling factor for the initialization. Default: 1.0.
+ """
+
def __init__(self, M: int, dim: int, F_dim: Optional[int] = None, gamma: float = 1.0) -> None:
super().__init__()
F_dim = F_dim if F_dim is not None else dim
@@ -96,6 +108,12 @@ class LearnableFourierPositionalEncoding(nn.Module):
class TokenConfidence(nn.Module):
+ """Predict the confidence score for each token in the sequence.
+
+ Args:
+ dim: The dimension of the input feature tokens.
+ """
+
def __init__(self, dim: int) -> None:
super().__init__()
self.token = nn.Sequential(nn.Linear(dim, 1), nn.Sigmoid())
@@ -111,6 +129,12 @@ class TokenConfidence(nn.Module):
class Attention(nn.Module):
+ """Implement the optimized multi-head attention mechanism for LightGlue.
+
+ Args:
+ allow_flash: Whether to enable FlashAttention for increased performance.
+ """
+
def __init__(self, allow_flash: bool) -> None:
super().__init__()
if allow_flash and not FLASH_AVAILABLE:
@@ -153,6 +177,15 @@ class Attention(nn.Module):
class SelfBlock(nn.Module):
+ """Implement a self-attention block to process features within a single image.
+
+ Args:
+ embed_dim: The dimension of the feature embeddings.
+ num_heads: The number of attention heads.
+ flash: Whether to use FlashAttention. Default: False.
+ bias: Whether to include bias in the linear layers. Default: True.
+ """
+
def __init__(self, embed_dim: int, num_heads: int, flash: bool = False, bias: bool = True) -> None:
super().__init__()
self.embed_dim = embed_dim
@@ -186,6 +219,15 @@ class SelfBlock(nn.Module):
class CrossBlock(nn.Module):
+ """Implement a cross-attention block to exchange information between two images.
+
+ Args:
+ embed_dim: The dimension of the feature embeddings.
+ num_heads: The number of attention heads.
+ flash: Whether to use FlashAttention. Default: False.
+ bias: Whether to include bias in the linear layers. Default: True.
+ """
+
def __init__(self, embed_dim: int, num_heads: int, flash: bool = False, bias: bool = True) -> None:
super().__init__()
self.heads = num_heads
@@ -237,6 +279,12 @@ class CrossBlock(nn.Module):
class TransformerLayer(nn.Module):
+ """Implement a complete Transformer layer for feature matching.
+
+ This layer typically alternates between self-attention and cross-attention
+ to update local feature descriptors.
+ """
+
def __init__(self, *args, **kwargs): # type: ignore
super().__init__()
self.self_attn = SelfBlock(*args, **kwargs)
@@ -290,6 +338,12 @@ def sigmoid_log_double_softmax(sim: torch.Tensor, z0: torch.Tensor, z1: torch.Te
class MatchAssignment(nn.Module):
+ """Assign matches between two sets of local features using a dual-softmax approach.
+
+ Args:
+ dim: The dimension of the feature descriptors.
+ """
+
def __init__(self, dim: int) -> None:
super().__init__()
self.dim = dim
@@ -331,6 +385,16 @@ def filter_matches(scores: torch.Tensor, th: float) -> Tuple[torch.Tensor, torch
class LightGlue(nn.Module):
+ """Implement the LightGlue matcher for sparse local features.
+
+ LightGlue is a deep network that matches local features across image pairs
+ using a series of transformer layers and an adaptive pruning mechanism.
+
+ Args:
+ features: The type of local features to match (e.g., 'superpoint', 'disk').
+ conf: A configuration dictionary to override default parameters.
+ """
+
default_conf: ClassVar[Dict[str, Any]] = {
"name": "lightglue", # just for interfacing
"input_dim": 256, # input descriptor dimension (autoselected from weights)
diff --git a/kornia/feature/loftr/backbone/resnet_fpn.py b/kornia/feature/loftr/backbone/resnet_fpn.py
index 5f3e12c8d..5c7040aac 100644
--- a/kornia/feature/loftr/backbone/resnet_fpn.py
+++ b/kornia/feature/loftr/backbone/resnet_fpn.py
@@ -33,6 +33,14 @@ def conv3x3(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
class BasicBlock(nn.Module):
+ """Implement a basic residual block for the ResNet-FPN backbone.
+
+ Args:
+ in_planes: Number of input channels.
+ planes: Number of output channels.
+ stride: Stride of the first convolution. Default: 1.
+ """
+
def __init__(self, in_planes: int, planes: int, stride: int = 1) -> None:
super().__init__()
self.conv1 = conv3x3(in_planes, planes, stride)
diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.py
index 477098fc8..e3753a697 100644
--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py
+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py
@@ -23,6 +23,12 @@ from torch import nn
class FinePreprocess(nn.Module):
+ """Preprocess feature maps for fine-level matching in LoFTR.
+
+ Args:
+ config: A dictionary containing configuration parameters for fine-level processing.
+ """
+
def __init__(self, config: Dict[str, Any]) -> None:
super().__init__()
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index d086695ba..e58aa6473 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -35,6 +35,14 @@ def elu_feature_map(x: torch.Tensor) -> torch.Tensor:
class LinearAttention(nn.Module):
+ """Implement the Linear Attention mechanism for efficient transformer processing.
+
+ This module uses the ELU-based kernel map to approximate softmax attention.
+
+ Args:
+ eps: A small value to avoid division by zero. Default: 1e-6.
+ """
+
def __init__(self, eps: float = 1e-6) -> None:
super().__init__()
self.feature_map = elu_feature_map
@@ -81,6 +89,13 @@ class LinearAttention(nn.Module):
class FullAttention(nn.Module):
+ """Implement the standard Multi-Head Softmax Attention.
+
+ Args:
+ use_dropout: Whether to apply dropout to the attention weights. Default: False.
+ attention_dropout: The dropout probability. Default: 0.1.
+ """
+
def __init__(self, use_dropout: bool = False, attention_dropout: float = 0.1) -> None:
super().__init__()
self.use_dropout = use_dropout
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index 8dbc30a64..f77be52d7 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -27,6 +27,14 @@ from .linear_attention import FullAttention, LinearAttention
class LoFTREncoderLayer(nn.Module):
+ """Implement a single encoder layer for the LoFTR transformer.
+
+ Args:
+ d_model: The number of expected features in the input.
+ nhead: The number of heads in the multi-head attention.
+ attention: The type of attention to use. Supported: "linear". Default: "linear".
+ """
+
def __init__(self, d_model: int, nhead: int, attention: Optional[Literal["linear"]] = "linear") -> None:
super().__init__()
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index baf87691b..0e0e66936 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -81,6 +81,15 @@ def compute_max_candidates(p_m0: torch.Tensor, p_m1: torch.Tensor) -> torch.Tens
class CoarseMatching(nn.Module):
+ """Perform coarse-level matching between two sets of feature maps.
+
+ This module calculates the confidence matrix and produces coarse matches
+ using an optimal transport layer or a dual-softmax operator.
+
+ Args:
+ config: A dictionary containing configuration parameters for the matching.
+ """
+
def __init__(self, config: Dict[str, Any]) -> None:
super().__init__()
self.config = config
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 76f7589e3..bb9707319 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -265,6 +265,13 @@ class ScaleSpaceDetector(nn.Module):
class Detector_config(TypedDict):
+ """Configuration for the Scale Space Detector.
+
+ Attributes:
+ nms_size: The size of the Non-Maximum Suppression window.
+ pyramid_levels: The number of levels in the image pyramid.
+ """
+
nms_size: int
pyramid_levels: int
up_levels: int
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
index 306c11146..8d6b216a5 100644
--- a/kornia/feature/sold2/backbones.py
+++ b/kornia/feature/sold2/backbones.py
@@ -28,6 +28,13 @@ from torch.nn.functional import pixel_shuffle, softmax
class HourglassConfig(NamedTuple):
+ """Define the configuration for the Hourglass backbone.
+
+ Attributes:
+ depth: The number of downsampling levels in the hourglass.
+ num_stacks: The number of stacked hourglass modules.
+ """
+
depth: int
num_stacks: int
num_blocks: int
@@ -61,6 +68,8 @@ class HourglassBackbone(nn.Module):
class MultitaskHead(nn.Module):
+ """Implement a multitask head for the Hourglass backbone."""
+
def __init__(self, input_channels: int) -> None:
super().__init__()
@@ -83,6 +92,8 @@ class MultitaskHead(nn.Module):
class Bottleneck2D(nn.Module):
+ """Implement a 2D Bottleneck block for the Hourglass backbone."""
+
def __init__(
self,
inplanes: int,
@@ -126,6 +137,16 @@ class Bottleneck2D(nn.Module):
class Hourglass(nn.Module):
+ """Implement the Hourglass network for symmetric feature extraction.
+
+ Args:
+ block: The block type to use (e.g., Bottleneck2D).
+ num_blocks: The number of blocks per level.
+ planes: The number of channels in the blocks.
+ depth: The depth of the hourglass.
+ expansion: The expansion factor for the bottleneck. Default: 2.
+ """
+
def __init__(self, block: Type[Bottleneck2D], num_blocks: int, planes: int, depth: int, expansion: int = 2) -> None:
super().__init__()
self.depth = depth
diff --git a/kornia/feature/sold2/structures.py b/kornia/feature/sold2/structures.py
index f725523fe..6774ab11e 100644
--- a/kornia/feature/sold2/structures.py
+++ b/kornia/feature/sold2/structures.py
@@ -20,6 +20,8 @@ from dataclasses import dataclass, field
@dataclass
class HeatMapRefineCfg:
+ """Configuration for heatmap refinement in the SOLD2 pipeline."""
+
mode: str = "local"
ratio: float = 0.2
valid_thresh: float = 0.001
@@ -29,12 +31,16 @@ class HeatMapRefineCfg:
@dataclass
class JunctionRefineCfg:
+ """Configuration for junction refinement in the SOLD2 pipeline."""
+
num_perturbs: int = 9
perturb_interval: float = 0.25
@dataclass
class LineDetectorCfg:
+ """Configuration for line detection in the SOLD2 pipeline."""
+
detect_thresh: float = 0.5
num_samples: int = 64
inlier_thresh: float = 0.99
@@ -52,6 +58,8 @@ class LineDetectorCfg:
@dataclass
class LineMatcherCfg:
+ """Configuration for line matching in the SOLD2 pipeline."""
+
cross_check: bool = True
num_samples: int = 5
min_dist_pts: int = 8
@@ -62,6 +70,8 @@ class LineMatcherCfg:
@dataclass
class BackboneCfg:
+ """Configuration for the backbone network in the SOLD2 pipeline."""
+
input_channel: int = 1
depth: int = 4
num_stacks: int = 2
@@ -71,6 +81,8 @@ class BackboneCfg:
@dataclass
class DetectorCfg:
+ """Configuration for the SOLD2 detector."""
+
backbone_cfg: BackboneCfg = field(default_factory=BackboneCfg)
use_descriptor: bool = False
grid_size: int = 8
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index 154d51ae7..cb3aeca6d 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -132,6 +132,17 @@ class MaxBlurPool2D(nn.Module):
class EdgeAwareBlurPool2D(nn.Module):
+ """Apply an edge-aware anti-aliasing filter during downsampling.
+
+ This module performs blur pooling while preserving edges by using an
+ edge-intensity threshold.
+
+ Args:
+ kernel_size: The size of the Gaussian blur kernel.
+ edge_threshold: The threshold for detecting edges. Default: 1.25.
+ edge_dilation_kernel_size: The kernel size for dilating the edge map. Default: 3.
+ """
+
def __init__(
self, kernel_size: tuple[int, int] | int, edge_threshold: float = 1.25, edge_dilation_kernel_size: int = 3
) -> None:
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 9032921c3..797da997e 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -56,6 +56,13 @@ def weight_init(m: nn.Module) -> None:
class CoFusion(nn.Module):
+ """Implement the weight-fusion layer for multi-scale edge maps.
+
+ Args:
+ in_ch: The number of input channels.
+ out_ch: The number of output channels.
+ """
+
def __init__(self, in_ch: int, out_ch: int) -> None:
super().__init__()
self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=3, stride=1, padding=1)
@@ -114,6 +121,13 @@ class _DenseBlock(nn.Sequential):
class UpConvBlock(nn.Module):
+ """Implement an upsampling convolutional block for edge refinement.
+
+ Args:
+ in_features: The number of input channels.
+ up_scale: The scale factor for upsampling.
+ """
+
def __init__(self, in_features: int, up_scale: int) -> None:
super().__init__()
self.up_factor = 2
@@ -146,6 +160,15 @@ class UpConvBlock(nn.Module):
class SingleConvBlock(nn.Module):
+ """Implement a single convolutional layer with optional Batch Normalization.
+
+ Args:
+ in_features: The number of input channels.
+ out_features: The number of output channels.
+ stride: The stride of the convolution.
+ use_bs: Whether to use Batch Normalization. Default: True.
+ """
+
def __init__(self, in_features: int, out_features: int, stride: int, use_bs: bool = True) -> None:
super().__init__()
self.use_bn = use_bs
@@ -160,6 +183,8 @@ class SingleConvBlock(nn.Module):
class DoubleConvBlock(nn.Sequential):
+ """Apply two consecutive convolutional blocks for edge feature extraction."""
+
def __init__(
self,
in_features: int,
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 5c9cbcf47..768cb5375 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -24,6 +24,8 @@ from kornia.utils.grid import create_meshgrid
class StereoException(Exception):
+ """Handle errors related to stereo camera calibration and rectification."""
+
def __init__(self, msg: str, *args: Any, **kwargs: Any) -> None:
r"""Construct custom exception for the :module:`~kornia.geometry.camera.stereo` module.
@@ -46,6 +48,13 @@ class StereoException(Exception):
class StereoCamera:
+ """Represent a horizontal stereo camera setup for depth estimation.
+
+ Args:
+ rectified_left_camera: The intrinsic matrix for the left camera.
+ rectified_right_camera: The intrinsic matrix for the right camera.
+ """
+
def __init__(self, rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor) -> None:
r"""Class representing a horizontal stereo camera setup.
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index 1dfa5ef63..9cac30490 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -38,6 +38,13 @@ def normalized(v: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
class Hyperplane(nn.Module):
+ """Represent a hyperplane in n-dimensional space.
+
+ Args:
+ n: The normal vector of the hyperplane.
+ d: The scalar distance from the origin.
+ """
+
def __init__(self, n: Vector3, d: Scalar) -> None:
super().__init__()
KORNIA_CHECK_TYPE(n, Vector3)
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index f9f8a0f14..b6329c2f0 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -32,6 +32,8 @@ __all__ = ["BaseWarper", "HomographyWarper"]
class BaseWarper(nn.Module):
+ """Provide a base class for homography-based image warping."""
+
def __init__(self, height: int, width: int, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.height = height
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 2c86d31fa..90914b08a 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -31,6 +31,8 @@ __all__ = ["BaseModel", "Homography", "ImageRegistrator", "Similarity"]
class BaseModel(nn.Module):
+ """Provide an abstract base class for image registration models."""
+
@abstractmethod
def reset_model(self) -> None: ...
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index 0cb476a42..fdb308e5d 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -29,11 +29,15 @@ __all__ = ["Scalar", "Vector2", "Vector3"]
# TODO: implement more functionality to validate
class Scalar(TensorWrapper):
+ """Wrap a tensor representing a scalar value."""
+
def __init__(self, data: torch.Tensor) -> None:
super().__init__(data)
class Vector3(TensorWrapper):
+ """Wrap a tensor representing a 3D vector."""
+
def __init__(self, vector: torch.Tensor) -> None:
super().__init__(vector)
KORNIA_CHECK(vector.shape[-1] == 3)
@@ -115,6 +119,8 @@ class Vector3(TensorWrapper):
class Vector2(TensorWrapper):
+ """Wrap a tensor representing a 2D vector."""
+
def __init__(self, vector: torch.Tensor) -> None:
super().__init__(vector)
KORNIA_CHECK(vector.shape[-1] == 2)
diff --git a/kornia/models/base.py b/kornia/models/base.py
index 729cf0cb4..61f02d1c1 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -36,6 +36,8 @@ ModelConfig = TypeVar("ModelConfig")
class ModelBaseMixin:
+ """Provide common properties and utilities for Kornia model classes."""
+
name: str = "model"
def _tensor_to_type(
diff --git a/kornia/models/common.py b/kornia/models/common.py
index 9df194052..f16440668 100644
--- a/kornia/models/common.py
+++ b/kornia/models/common.py
@@ -23,6 +23,19 @@ from torch import nn
class ConvNormAct(nn.Sequential):
+ """Apply a sequence of Convolution, Normalization, and Activation layers.
+
+ Args:
+ in_channels: Number of input channels.
+ out_channels: Number of output channels.
+ kernel_size: Size of the convolution kernel.
+ stride: Stride of the convolution. Default: 1.
+ padding: Zero-padding added to both sides of the input. Default: 0.
+ groups: Number of blocked connections from input to output. Default: 1.
+ norm: Normalization layer type. Default: :class:`nn.BatchNorm2d`.
+ act: Activation layer type. Default: :class:`nn.ReLU`.
+ """
+
def __init__(
self,
in_channels: int,
@@ -59,6 +72,16 @@ class ConvNormAct(nn.Sequential):
# Lightly adapted from
# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py
class MLP(nn.Module):
+ """Implement a Multi-Layer Perceptron (MLP) for feature projection.
+
+ Args:
+ input_dim: The number of input features.
+ hidden_dim: The number of features in hidden layers.
+ output_dim: The number of output features.
+ num_layers: The total number of layers.
+ sigmoid_output: Whether to apply a sigmoid to the final output. Default: False.
+ """
+
def __init__(
self, input_dim: int, hidden_dim: int, output_dim: int, num_layers: int, sigmoid_output: bool = False
) -> None:
@@ -100,6 +123,8 @@ class DropPath(nn.Module):
# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py
# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
class LayerNorm2d(nn.Module):
+ """Apply Layer Normalization over a 4D input tensor (NCHW)."""
+
def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
super().__init__()
self.weight = nn.Parameter(torch.ones(num_channels))
diff --git a/kornia/models/depth_estimation/base.py b/kornia/models/depth_estimation/base.py
index 3953d9ef7..497d510e8 100644
--- a/kornia/models/depth_estimation/base.py
+++ b/kornia/models/depth_estimation/base.py
@@ -29,6 +29,8 @@ __all__ = ["DepthEstimation"]
class DepthEstimation(HFONNXComunnityModel):
+ """Base class for depth estimation models compatible with HuggingFace and ONNX."""
+
name: str = "depth_estimation"
def __call__(self, images: Union[torch.Tensor, list[torch.Tensor]]) -> Union[torch.Tensor, list[torch.Tensor]]: # type: ignore[override]
diff --git a/kornia/models/depth_estimation/depth_anything.py b/kornia/models/depth_estimation/depth_anything.py
index 4ca1a2f82..0ee9b25d3 100644
--- a/kornia/models/depth_estimation/depth_anything.py
+++ b/kornia/models/depth_estimation/depth_anything.py
@@ -25,6 +25,8 @@ __all__ = ["DepthAnythingONNXBuilder"]
class DepthAnythingONNXBuilder:
+ """Provide static methods to build DepthAnything models for ONNX inference."""
+
@staticmethod
def build(
model_name: str = "depth-anything-v2-small", model_type: str = "model", cache_dir: Optional[str] = None
diff --git a/kornia/models/efficient_vit/backbone.py b/kornia/models/efficient_vit/backbone.py
index 27cd94453..6011a3540 100644
--- a/kornia/models/efficient_vit/backbone.py
+++ b/kornia/models/efficient_vit/backbone.py
@@ -40,6 +40,22 @@ from kornia.models.efficient_vit.utils import build_kwargs_from_config
class EfficientViTBackbone(nn.Module):
+ """Implement the EfficientViT backbone architecture.
+
+ EfficientViT is a high-speed vision transformer designed for efficient
+ inference on mobile and edge devices by optimizing the attention mechanism
+ and structural blocks.
+
+ Args:
+ width_list: List of widths for each stage.
+ depth_list: List of depths (number of blocks) for each stage.
+ in_channels: Number of input image channels. Default: 3.
+ dim: Dimension of the query, key, and value tensors in the attention mechanism. Default: 32.
+ expand_ratio: Expansion ratio for the MBConv blocks. Default: 4.
+ norm: Normalization layer type. Default: "bn2d".
+ act_func: Activation function type. Default: "hswish".
+ """
+
def __init__(
self,
width_list: list[int],
@@ -200,6 +216,25 @@ def efficientvit_backbone_b3(**kwargs: dict[str, Any]) -> EfficientViTBackbone:
class EfficientViTLargeBackbone(nn.Module):
+ """Implement the large-scale variant of the EfficientViT backbone.
+
+ This backbone is designed for high-resolution dense prediction tasks. It
+ utilizes multi-scale linear attention to achieve a global receptive field
+ while maintaining linear computational complexity relative to the input
+ resolution.
+
+ Args:
+ width_list: List of channel widths for each stage of the backbone.
+ depth_list: List of number of blocks for each stage.
+ in_channels: Number of input image channels. Default: 3.
+ qkv_dim: The internal dimension for query, key, and value projections
+ in the attention layers. Default: 32.
+ norm: Normalization layer type to use (e.g., "bn2d", "ln").
+ Default: "bn2d".
+ act_func: Activation function type to use (e.g., "gelu", "relu").
+ Default: "gelu".
+ """
+
def __init__(
self,
width_list: list[int],
diff --git a/kornia/models/efficient_vit/nn/norm.py b/kornia/models/efficient_vit/nn/norm.py
index 0afc34b22..cf62710d5 100644
--- a/kornia/models/efficient_vit/nn/norm.py
+++ b/kornia/models/efficient_vit/nn/norm.py
@@ -29,6 +29,8 @@ from kornia.models.efficient_vit.utils import build_kwargs_from_config
class LayerNorm2d(nn.LayerNorm):
+ """Apply Layer Normalization over a 4D input tensor (NCHW format)."""
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
out = x - torch.mean(x, dim=1, keepdim=True)
out = out / torch.sqrt(torch.square(out).mean(dim=1, keepdim=True) + self.eps)
diff --git a/kornia/models/efficient_vit/nn/ops.py b/kornia/models/efficient_vit/nn/ops.py
index 455504c8d..7c86b2845 100644
--- a/kornia/models/efficient_vit/nn/ops.py
+++ b/kornia/models/efficient_vit/nn/ops.py
@@ -49,6 +49,20 @@ __all__ = [
class ConvLayer(nn.Module):
+ """Implement a standard convolutional layer with Batch Normalization and Activation.
+
+ Args:
+ in_channels: Number of input channels.
+ out_channels: Number of output channels.
+ kernel_size: Size of the convolving kernel.
+ stride: Stride of the convolution. Default: 1.
+ groups: Number of blocked connections from input to output. Default: 1.
+ use_bias: Whether to include a bias term in the convolution. Default: False.
+ dropout: Dropout rate to apply before convolution. Default: 0 (no dropout).
+ norm: Normalization layer type. Default: :class:`bn2d` (BatchNorm2d).
+ act_func: Activation layer type. Default: :class:`relu` (ReLU).
+ """
+
def __init__(
self,
in_channels: int,
@@ -93,6 +107,8 @@ class ConvLayer(nn.Module):
class IdentityLayer(nn.Module):
+ """Implement a placeholder layer that returns the input as-is."""
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x
@@ -103,6 +119,21 @@ class IdentityLayer(nn.Module):
class DSConv(nn.Module):
+ """Implement Depthwise Separable Convolution.
+
+ This layer splits a standard convolution into a depthwise convolution
+ followed by a pointwise convolution to reduce parameters and FLOPs.
+
+ Args:
+ in_channels: Number of input channels.
+ out_channels: Number of output channels.
+ kernel_size: Size of the convolving kernel. Default: 3.
+ stride: Stride of the convolution. Default: 1.
+ use_bias: Whether to use bias in the convolutional layers. Default: False.
+ norm: Normalization layers for the depthwise and pointwise stages. Default: ("bn2d", "bn2d").
+ act_func: Activation functions for the depthwise and pointwise stages. Default: ("relu6", None).
+ """
+
def __init__(
self,
in_channels: int,
@@ -140,6 +171,28 @@ class DSConv(nn.Module):
class MBConv(nn.Module):
+ """Implement the Inverted Residual Block (Mobile Inverted Bottleneck).
+
+ This block follows the MobileNetV2 design: a wide intermediate layer
+ (expansion) between two narrow layers, using depthwise convolutions
+ to maintain efficiency.
+
+ Args:
+ in_channels: Number of input channels.
+ out_channels: Number of output channels.
+ kernel_size: Size of the depthwise convolution kernel. Default: 3.
+ stride: Stride of the depthwise convolution. Default: 1.
+ mid_channels: Number of intermediate expansion channels. If None, calculated
+ using expand_ratio. Default: None.
+ expand_ratio: Expansion factor for the intermediate channels relative to
+ in_channels. Default: 6.
+ use_bias: Whether to use bias in the convolutional layers. Default: False.
+ norm: Normalization layers for the expansion, depthwise, and pointwise stages.
+ Default: ("bn2d", "bn2d", "bn2d").
+ act_func: Activation functions for the expansion, depthwise, and pointwise stages.
+ Default: ("relu6", "relu6", None).
+ """
+
def __init__(
self,
in_channels: int,
@@ -184,6 +237,29 @@ class MBConv(nn.Module):
class FusedMBConv(nn.Module):
+ """Implement a fused version of the Inverted Residual Block for efficiency.
+
+ This block improves throughput on certain hardware by replacing the
+ separate expansion and depthwise convolutions with a single regular
+ convolution, as seen in EfficientNet-V2.
+
+ Args:
+ in_channels: Number of input channels.
+ out_channels: Number of output channels.
+ kernel_size: Size of the main convolution kernel. Default: 3.
+ stride: Stride of the convolution. Default: 1.
+ mid_channels: Number of intermediate expansion channels. If None,
+ calculated using expand_ratio. Default: None.
+ expand_ratio: Expansion factor for the intermediate channels relative
+ to in_channels. Default: 6.
+ groups: Number of groups for the main convolution. Default: 1.
+ use_bias: Whether to use bias in the convolutional layers. Default: False.
+ norm: Normalization layers for the fused and pointwise stages.
+ Default: ("bn2d", "bn2d").
+ act_func: Activation functions for the fused and pointwise stages.
+ Default: ("relu6", None).
+ """
+
def __init__(
self,
in_channels: int,
@@ -225,6 +301,27 @@ class FusedMBConv(nn.Module):
class ResBlock(nn.Module):
+ """Implement a standard residual block for EfficientViT.
+
+ This block applies a series of convolutions and adds the original input
+ back to the output via a skip connection, helping to mitigate the
+ vanishing gradient problem in deep networks.
+
+ Args:
+ in_channels: Number of input channels.
+ out_channels: Number of output channels.
+ kernel_size: Size of the convolving kernel. Default: 3.
+ stride: Stride of the convolution. Default: 1.
+ mid_channels: Number of intermediate channels. If None, calculated
+ using expand_ratio. Default: None.
+ expand_ratio: Expansion factor for the intermediate channels. Default: 1.
+ use_bias: Whether to use bias in the convolutional layers. Default: False.
+ norm: Normalization layers for the main and projection stages.
+ Default: ("bn2d", "bn2d").
+ act_func: Activation functions for the main and projection stages.
+ Default: ("relu6", None).
+ """
+
def __init__(
self,
in_channels: int,
@@ -258,7 +355,32 @@ class ResBlock(nn.Module):
class LiteMLA(nn.Module):
- r"""Lightweight multi-scale linear attention."""
+ r"""Lightweight multi-scale linear attention.
+
+ This module implements a linear attention mechanism that avoids the quadratic
+ complexity of standard self-attention. It incorporates multi-scale depthwise
+ convolutions (scales) to aggregate local information effectively.
+
+ Args:
+ in_channels: Number of input channels.
+ out_channels: Number of output channels.
+ heads: Number of attention heads. If None, calculated using heads_ratio.
+ Default: None.
+ heads_ratio: Ratio to determine the number of heads relative to channels.
+ Default: 1.0.
+ dim: Dimension of each attention head. Default: 8.
+ use_bias: Whether to use bias in the linear projections. Default: False.
+ norm: Normalization layers for the query/key/value and output projections.
+ Default: (None, "bn2d").
+ act_func: Activation functions for the internal and output stages.
+ Default: (None, None).
+ kernel_func: The kernel function to use for linear attention (e.g., "relu").
+ Default: "relu".
+ scales: Kernel sizes for the multi-scale depthwise convolutions.
+ Default: (5,).
+ eps: A small value to ensure numerical stability during division.
+ Default: 1.0e-15.
+ """
def __init__(
self,
@@ -350,6 +472,23 @@ class LiteMLA(nn.Module):
class EfficientViTBlock(nn.Module):
+ """Implement a single EfficientViT building block.
+
+ This block consists of two main components: a Lightweight Multi-scale Linear
+ Attention (LiteMLA) layer and a Feed-Forward Network (FFN). It follows the
+ standard transformer-style residual architecture optimized for efficiency.
+
+ Args:
+ in_channels: Number of input channels.
+ heads_ratio: Ratio to determine the number of attention heads in LiteMLA.
+ Default: 1.0.
+ dim: The dimension for the attention head and FFN layers. Default: 32.
+ expand_ratio: Expansion factor for the FFN (Feed-Forward Network).
+ Default: 4.
+ norm: Normalization layer type to use (e.g., "bn2d"). Default: "bn2d".
+ act_func: Activation function type to use (e.g., "hswish"). Default: "hswish".
+ """
+
def __init__(
self,
in_channels: int,
@@ -388,9 +527,22 @@ class EfficientViTBlock(nn.Module):
class ResidualBlock(nn.Module):
+ """Provide a flexible residual wrapper for a main branch and a shortcut.
+
+ Args:
+ main: The primary neural network branch.
+ shortcut: The identity or projection shortcut branch.
+ post_act: Activation to apply after the summation.
+ pre_norm: Normalization to apply before the branches.
+ """
+
def __init__(
- self, main: nn.Module or None, shortcut: nn.Module or None, post_act=None, pre_norm: nn.Module or None = None
- ):
+ self,
+ main: nn.Module | None,
+ shortcut: nn.Module | None,
+ post_act: nn.Module | None = None,
+ pre_norm: nn.Module | None = None,
+ ) -> None:
super().__init__()
self.pre_norm = pre_norm
@@ -417,7 +569,18 @@ class ResidualBlock(nn.Module):
class OpSequential(nn.Module):
- def __init__(self, op_list: list[nn.Module or None]):
+ """A container for sequential execution that handles optional or None modules.
+
+ This class behaves similarly to :class:`nn.Sequential` but explicitly
+ allows for ``None`` elements within the operation list, which are
+ ignored during the forward pass.
+
+ Args:
+ op_list: A list of modules to be executed sequentially.
+ Elements can be ``None``, in which case they act as an identity.
+ """
+
+ def __init__(self, op_list: list[nn.Module | None]):
super().__init__()
valid_op_list = []
for op in op_list:
diff --git a/kornia/models/processors.py b/kornia/models/processors.py
index df55e5913..2f82572ba 100644
--- a/kornia/models/processors.py
+++ b/kornia/models/processors.py
@@ -68,6 +68,12 @@ class ResizePreProcessor(nn.Module):
class ResizePostProcessor(nn.Module):
+ """Rescale model outputs back to the original image dimensions.
+
+ Args:
+ interpolation_mode: The algorithm used for upsampling. Default: "bilinear".
+ """
+
def __init__(self, interpolation_mode: str = "bilinear") -> None:
super().__init__()
self.interpolation_mode = interpolation_mode
@@ -104,6 +110,13 @@ class ResizePostProcessor(nn.Module):
class OutputRangePostProcessor(nn.Module):
+ """Clip and scale model outputs to a specific numerical range.
+
+ Args:
+ min_val: The minimum value for clipping. Default: 0.0.
+ max_val: The maximum value for clipping. Default: 1.0.
+ """
+
def __init__(self, min_val: float = 0.0, max_val: float = 1.0) -> None:
super().__init__()
self.min_val = min_val
diff --git a/kornia/models/rt_detr/architecture/hgnetv2.py b/kornia/models/rt_detr/architecture/hgnetv2.py
index cc0252aeb..693cb8955 100644
--- a/kornia/models/rt_detr/architecture/hgnetv2.py
+++ b/kornia/models/rt_detr/architecture/hgnetv2.py
@@ -32,6 +32,8 @@ from kornia.models.common import ConvNormAct
class StemBlock(nn.Module):
+ """Implement the entry-level Stem block for HGNetV2 backbones."""
+
def __init__(self, in_channels: int, mid_channels: int, out_channels: int) -> None:
super().__init__()
self.stem1 = ConvNormAct(in_channels, mid_channels, 3, 2)
@@ -50,6 +52,14 @@ class StemBlock(nn.Module):
# Separable conv
class LightConvNormAct(nn.Sequential):
+ """Implement a composite layer containing Convolution, Normalization, and Activation.
+
+ Args:
+ in_channels: Number of input channels.
+ out_channels: Number of output channels.
+ kernel_size: Size of the convolving kernel.
+ """
+
def __init__(self, in_channels: int, out_channels: int, kernel_size: int) -> None:
super().__init__()
self.conv1 = ConvNormAct(in_channels, out_channels, 1, act="none") # point-wise
@@ -57,6 +67,8 @@ class LightConvNormAct(nn.Sequential):
class StageConfig(NamedTuple):
+ """Represent configuration parameters for a single HGNetV2 stage."""
+
in_channels: int
mid_channels: int
out_channels: int
@@ -68,6 +80,14 @@ class StageConfig(NamedTuple):
class HGBlock(nn.Module):
+ """Implement the High-Performance GPU block for HGNetV2.
+
+ Args:
+ in_channels: The number of input channels.
+ config: The configuration object containing stage details.
+ identity: Whether to use a residual identity connection.
+ """
+
def __init__(self, in_channels: int, config: StageConfig, identity: bool) -> None:
super().__init__()
self.identity = identity
@@ -93,6 +113,12 @@ class HGBlock(nn.Module):
class HGStage(nn.Sequential):
+ """Implement a single stage of the HGNetV2 architecture.
+
+ Args:
+ config: The configuration object for the specific stage.
+ """
+
def __init__(self, config: StageConfig) -> None:
super().__init__()
ch_in = config.in_channels
@@ -104,6 +130,13 @@ class HGStage(nn.Sequential):
class PPHGNetV2(nn.Module):
+ """Implement the PPHGNetV2 backbone for real-time object detection.
+
+ Args:
+ stem_channels: A list of three integers for the stem convolution channels.
+ stage_configs: A list of StageConfig objects for each of the four stages.
+ """
+
def __init__(self, stem_channels: list[int], stage_configs: list[StageConfig]) -> None:
KORNIA_CHECK(len(stem_channels) == 3)
KORNIA_CHECK(len(stage_configs) == 4)
diff --git a/kornia/models/rt_detr/architecture/hybrid_encoder.py b/kornia/models/rt_detr/architecture/hybrid_encoder.py
index e5fc07e6f..c3908f434 100644
--- a/kornia/models/rt_detr/architecture/hybrid_encoder.py
+++ b/kornia/models/rt_detr/architecture/hybrid_encoder.py
@@ -35,6 +35,13 @@ from kornia.utils._compat import torch_meshgrid
class RepVggBlock(nn.Module):
+ """Implement the re-parameterizable VGG-style block.
+
+ Args:
+ in_channels: The number of input channels.
+ out_channels: The number of output channels.
+ """
+
def __init__(self, in_channels: int, out_channels: int) -> None:
super().__init__()
self.conv1 = ConvNormAct(in_channels, out_channels, 3, act="none")
@@ -76,6 +83,15 @@ class RepVggBlock(nn.Module):
class CSPRepLayer(nn.Module):
+ """Implement the Cross-Stage Partial Rep-layer.
+
+ Args:
+ in_channels: The number of input channels.
+ out_channels: The number of output channels.
+ num_blocks: The number of RepVggBlocks to include.
+ expansion: The expansion factor for the internal channels. Default: 1.0.
+ """
+
def __init__(self, in_channels: int, out_channels: int, num_blocks: int, expansion: float = 1.0) -> None:
super().__init__()
hidden_channels = int(out_channels * expansion)
@@ -95,6 +111,15 @@ class CSPRepLayer(nn.Module):
# almost identical to nn.TransformerEncoderLayer
# but add positional embeddings to q and k
class AIFI(nn.Module):
+ """Implement the All-scale Indoor/Outdoor Feature Interaction (AIFI) module.
+
+ Args:
+ embed_dim: The dimension of the input embeddings.
+ num_heads: The number of attention heads.
+ dim_feedforward: The dimension of the feed-forward network.
+ dropout: The dropout probability. Default: 0.0.
+ """
+
def __init__(self, embed_dim: int, num_heads: int, dim_feedforward: int, dropout: float = 0.0) -> None:
super().__init__()
self.self_attn = nn.MultiheadAttention(embed_dim, num_heads, dropout) # NOTE: batch_first = False
@@ -170,6 +195,13 @@ class AIFI(nn.Module):
class TransformerEncoder(nn.Module):
+ """Implement a transformer encoder comprising multiple encoder layers.
+
+ Args:
+ encoder_layer: An instance of a transformer encoder layer.
+ num_layers: The total number of encoder layers to stack.
+ """
+
def __init__(self, encoder_layer: nn.Module, num_layers: int) -> None:
super().__init__()
self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(num_layers)])
@@ -186,6 +218,14 @@ class TransformerEncoder(nn.Module):
class CCFM(nn.Module):
+ """Implement the Cross-Column Feature Mixing (CCFM) module.
+
+ Args:
+ num_fmaps: The number of input feature maps.
+ hidden_dim: The hidden dimension for the fusion layers.
+ expansion: The expansion ratio for the internal layers. Default: 1.0.
+ """
+
def __init__(self, num_fmaps: int, hidden_dim: int, expansion: float = 1.0) -> None:
super().__init__()
self.lateral_convs = nn.ModuleList()
@@ -226,6 +266,12 @@ class CCFM(nn.Module):
class HybridEncoder(nn.Module):
+ """Implement the Efficient Hybrid Encoder for RT-DETR.
+
+ This module combines multi-scale feature fusion with Intra-scale
+ Feature Interaction using transformer layers.
+ """
+
def __init__(self, in_channels: list[int], hidden_dim: int, dim_feedforward: int, expansion: float = 1.0) -> None:
super().__init__()
self.input_proj = nn.ModuleList(
diff --git a/kornia/models/rt_detr/architecture/resnet_d.py b/kornia/models/rt_detr/architecture/resnet_d.py
index f74d0d697..8bcc70baf 100644
--- a/kornia/models/rt_detr/architecture/resnet_d.py
+++ b/kornia/models/rt_detr/architecture/resnet_d.py
@@ -43,6 +43,8 @@ def _make_shortcut(in_channels: int, out_channels: int, stride: int) -> nn.Modul
class BasicBlockD(nn.Module):
+ """Implement the Basic Block for the ResNet-D variant."""
+
expansion = 1
def __init__(self, in_channels: int, out_channels: int, stride: int, shortcut: bool) -> None:
@@ -64,6 +66,8 @@ class BasicBlockD(nn.Module):
class BottleneckD(nn.Module):
+ """Implement the Bottleneck Block for the ResNet-D variant."""
+
expansion = 4
def __init__(self, in_channels: int, out_channels: int, stride: int, shortcut: bool) -> None:
@@ -87,12 +91,25 @@ class BottleneckD(nn.Module):
class Block(nn.Sequential):
+ """Implement a residual block for the ResNet-D architecture.
+
+ Args:
+ blocks: A module containing the sequence of operations for the block.
+ """
+
def __init__(self, blocks: nn.Module) -> None:
super().__init__()
self.blocks = blocks
class ResNetD(nn.Module):
+ """Implement the ResNet-D architecture.
+
+ Args:
+ n_blocks: A list of integers representing the number of blocks in each stage.
+ block: The block class type (BasicBlockD or BottleneckD).
+ """
+
def __init__(self, n_blocks: list[int], block: type[BasicBlockD | BottleneckD]) -> None:
KORNIA_CHECK(len(n_blocks) == 4)
super().__init__()
diff --git a/kornia/models/rt_detr/architecture/rtdetr_head.py b/kornia/models/rt_detr/architecture/rtdetr_head.py
index e7f7429b5..8ab3726c7 100644
--- a/kornia/models/rt_detr/architecture/rtdetr_head.py
+++ b/kornia/models/rt_detr/architecture/rtdetr_head.py
@@ -221,6 +221,8 @@ class TransformerDecoderLayer(nn.Module):
class TransformerDecoder(nn.Module):
+ """Implement the transformer decoder for generating object queries."""
+
def __init__(self, hidden_dim: int, decoder_layer: nn.Module, num_layers: int, eval_idx: int = -1) -> None:
super().__init__()
self.layers = nn.ModuleList([copy.deepcopy(decoder_layer) for _ in range(num_layers)])
@@ -287,6 +289,8 @@ class TransformerDecoder(nn.Module):
class RTDETRHead(nn.Module):
+ """Implement the RT-DETR prediction head for object detection."""
+
def __init__(
self,
num_classes: int,
diff --git a/kornia/models/rt_detr/post_processor.py b/kornia/models/rt_detr/post_processor.py
index 04d397cb7..890830d1d 100644
--- a/kornia/models/rt_detr/post_processor.py
+++ b/kornia/models/rt_detr/post_processor.py
@@ -52,6 +52,19 @@ def mod(a: torch.Tensor, b: int) -> torch.Tensor:
# TODO: deprecate the confidence threshold and add the num_top_queries as a parameter and num_classes as a parameter
class DETRPostProcessor(nn.Module):
+ """Convert raw DETR model outputs into final bounding box detections.
+
+ This module applies the softmax function to scores and transforms normalized
+ bounding box coordinates into the pixel coordinate system of the input image.
+
+ Args:
+ num_classes: The number of object classes.
+ confidence_threshold: The threshold to filter out low-confidence detections.
+ num_top_queries: The number of top queries to consider for each image.
+ confidence_filtering: Whether to apply confidence-based filtering.
+ filter_as_zero: If True, boxes below the confidence threshold are set to zero instead of being removed.
+ """
+
def __init__(
self,
confidence_threshold: Optional[float] = None,
diff --git a/kornia/models/sam/architecture/common.py b/kornia/models/sam/architecture/common.py
index ebc3abb22..715034729 100644
--- a/kornia/models/sam/architecture/common.py
+++ b/kornia/models/sam/architecture/common.py
@@ -30,6 +30,14 @@ from torch import nn
class MLPBlock(nn.Module):
+ """Implement a standard Multi-Layer Perceptron (MLP) block.
+
+ Args:
+ embedding_dim: The size of the input and output embeddings.
+ mlp_dim: The size of the hidden layer.
+ act: The activation function class to use. Default: nn.GELU.
+ """
+
def __init__(self, embedding_dim: int, mlp_dim: int, act: type[nn.Module] = nn.GELU) -> None:
super().__init__()
self.lin1 = nn.Linear(embedding_dim, mlp_dim)
@@ -41,6 +49,8 @@ class MLPBlock(nn.Module):
class LayerNorm(nn.LayerNorm):
+ """Implement Layer Normalization with a small epsilon to avoid division by zero."""
+
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
self.eps = 1e-6
diff --git a/kornia/models/sam/architecture/image_encoder.py b/kornia/models/sam/architecture/image_encoder.py
index e92fd9a1b..2da29bed6 100644
--- a/kornia/models/sam/architecture/image_encoder.py
+++ b/kornia/models/sam/architecture/image_encoder.py
@@ -35,6 +35,27 @@ from kornia.models.sam.architecture.common import MLPBlock
# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
class ImageEncoderViT(nn.Module):
+ """Implement the Vision Transformer (ViT) based image encoder for SAM.
+
+ Args:
+ img_size: The input image resolution.
+ patch_size: The size of the patches for the embedding.
+ in_chans: The number of input color channels.
+ embed_dim: The dimension of the patch embeddings.
+ depth: The number of transformer blocks.
+ num_heads: The number of attention heads.
+ mlp_ratio: The ratio of MLP hidden dim to embedding dim.
+ out_chans: The number of output feature channels.
+ qkv_bias: Whether to use bias in the QKV projection.
+ norm_layer: The normalization layer class.
+ act_layer: The activation layer class.
+ use_abs_pos: Whether to use absolute position embeddings.
+ use_rel_pos: Whether to use relative position embeddings.
+ rel_pos_zero_init: Whether to zero-initialize relative position.
+ window_size: The window size for windowed attention.
+ global_attn_indexes: Indexes of blocks that use global attention.
+ """
+
def __init__(
self,
img_size: int = 1024,
diff --git a/kornia/models/sam/architecture/mask_decoder.py b/kornia/models/sam/architecture/mask_decoder.py
index a4e55e54e..07e2bbe41 100644
--- a/kornia/models/sam/architecture/mask_decoder.py
+++ b/kornia/models/sam/architecture/mask_decoder.py
@@ -30,6 +30,8 @@ from kornia.models.common import MLP, LayerNorm2d
class MaskDecoder(nn.Module):
+ """Predict object masks and quality scores from image and prompt embeddings."""
+
def __init__(
self,
*,
diff --git a/kornia/models/sam/architecture/prompt_encoder.py b/kornia/models/sam/architecture/prompt_encoder.py
index 55c00485a..0d3bd53c7 100644
--- a/kornia/models/sam/architecture/prompt_encoder.py
+++ b/kornia/models/sam/architecture/prompt_encoder.py
@@ -33,6 +33,19 @@ from kornia.models.common import LayerNorm2d
class PromptEncoder(nn.Module):
+ """Encode sparse (points, boxes) and dense (masks) prompts into embeddings.
+
+ This module transforms different types of prompts into a common embedding space
+ to be consumed by the mask decoder.
+
+ Args:
+ embed_dim: The internal embedding dimension.
+ image_embedding_size: The spatial resolution of the image embedding as $(H, W)$.
+ input_image_size: The resolution of the input image as $(H, W)$.
+ mask_in_chans: The number of hidden channels used for encoding input masks.
+ activation: The activation function for the mask encoder. Default: :class:`nn.GELU`.
+ """
+
def __init__(
self,
embed_dim: int,
diff --git a/kornia/models/sam/architecture/transformer.py b/kornia/models/sam/architecture/transformer.py
index 8c2767158..1f731dbfc 100644
--- a/kornia/models/sam/architecture/transformer.py
+++ b/kornia/models/sam/architecture/transformer.py
@@ -33,6 +33,20 @@ from kornia.models.sam.architecture.common import MLPBlock
class TwoWayTransformer(nn.Module):
+ """Implement a two-way transformer for interaction between image and prompt embeddings.
+
+ This transformer allows for simultaneous attention between the image features
+ and the prompt tokens (e.g., points or boxes).
+
+ Args:
+ depth: The number of transformer layers.
+ embedding_dim: The dimension of the embeddings.
+ num_heads: The number of heads in the multi-head attention.
+ mlp_dim: The dimension of the internal MLP layers.
+ activation: The activation function to use. Default: :class:`nn.GELU`.
+ attention_type: The type of attention mechanism to apply. Default: "unnorm".
+ """
+
def __init__(
self,
depth: int,
@@ -116,6 +130,20 @@ class TwoWayTransformer(nn.Module):
class TwoWayAttentionBlock(nn.Module):
+ """Implement a single block for the Two-Way Transformer.
+
+ This block performs self-attention on tokens, cross-attention from tokens to
+ image features, and cross-attention from image features to tokens.
+
+ Args:
+ embedding_dim: The dimension of the embeddings.
+ num_heads: The number of attention heads.
+ mlp_dim: The dimension of the internal MLP layers. Default: 2048.
+ activation: The activation function to use. Default: :class:`nn.GELU`.
+ attention_type: The type of attention mechanism. Default: "unnorm".
+ skip_first_layer_pe: Whether to skip position encoding in the first layer. Default: False.
+ """
+
def __init__(
self,
embedding_dim: int,
diff --git a/kornia/models/sam/model.py b/kornia/models/sam/model.py
index bc2033009..a93fc17e8 100644
--- a/kornia/models/sam/model.py
+++ b/kornia/models/sam/model.py
@@ -84,6 +84,11 @@ class SamConfig:
class Sam(ModelBase[SamConfig]):
+ """Implement the Segment Anything Model (SAM) wrapper.
+
+ This class coordinates the image encoder, prompt encoder, and mask decoder.
+ """
+
mask_threshold: float = 0.0
def __init__(
diff --git a/kornia/models/segmentation/segmentation_models.py b/kornia/models/segmentation/segmentation_models.py
index d90f15c75..4ec139970 100644
--- a/kornia/models/segmentation/segmentation_models.py
+++ b/kornia/models/segmentation/segmentation_models.py
@@ -31,6 +31,12 @@ __all__ = ["SegmentationModelsBuilder"]
class SegmentationModelsBuilder:
+ """Provide a factory to build various semantic segmentation models.
+
+ This builder simplifies the creation of models like UNet or DeepLabV3
+ by providing a unified interface for configuration and weight loading.
+ """
+
@staticmethod
def build(
model_name: str = "Unet",
diff --git a/kornia/models/small_sr.py b/kornia/models/small_sr.py
index a0c1c1efd..ddef29384 100644
--- a/kornia/models/small_sr.py
+++ b/kornia/models/small_sr.py
@@ -75,6 +75,13 @@ def weight_init(model: nn.Module) -> None:
class SmallSRNetWrapper(nn.Module):
+ """Wrap a Super-Resolution model with pre-processing and post-processing.
+
+ Args:
+ upscale_factor: The factor by which the image resolution is increased.
+ pretrained: Whether to load weights from a pre-trained model. Default: True.
+ """
+
def __init__(self, upscale_factor: int = 3, pretrained: bool = True) -> None:
super().__init__()
self.rgb_to_ycbcr = RgbToYcbcr()
diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.py
index 4624fccfb..862cd6edd 100644
--- a/kornia/models/tiny_vit.py
+++ b/kornia/models/tiny_vit.py
@@ -37,6 +37,17 @@ def _make_pair(x: int | tuple[int, int]) -> tuple[int, int]:
class ConvBN(nn.Sequential):
+ """Implement a sequential block containing a convolution followed by Batch Normalization.
+
+ Args:
+ in_channels: The number of input channels.
+ out_channels: The number of output channels.
+ kernel_size: The size of the convolving kernel. Default: 1.
+ stride: The stride of the convolution. Default: 1.
+ padding: The zero-padding added to both sides of the input. Default: 0.
+ groups: The number of blocked connections from input to output. Default: 1.
+ """
+
def __init__(
self,
in_channels: int,
@@ -54,6 +65,17 @@ class ConvBN(nn.Sequential):
class PatchEmbed(nn.Sequential):
+ """Perform patch embedding using a series of convolutions.
+
+ This module divides the input image into patches and projects them into
+ the embedding dimension.
+
+ Args:
+ in_channels: The number of input image channels.
+ embed_dim: The dimension of the resulting embeddings.
+ activation: The activation layer to use. Default: :class:`nn.GELU`.
+ """
+
def __init__(self, in_channels: int, embed_dim: int, activation: type[nn.Module] = nn.GELU) -> None:
super().__init__()
self.seq = nn.Sequential(
@@ -62,6 +84,17 @@ class PatchEmbed(nn.Sequential):
class MBConv(nn.Module):
+ """Implement the Mobile Inverted Residual Bottleneck Convolution layer.
+
+ Args:
+ in_channels: The number of input channels.
+ out_channels: The number of output channels.
+ expansion: The expansion ratio for the hidden dimension.
+ kernel_size: The convolution kernel size.
+ stride: The stride of the convolution.
+ dropout: The dropout rate for the stochastic depth.
+ """
+
def __init__(
self,
in_channels: int,
@@ -83,6 +116,15 @@ class MBConv(nn.Module):
class PatchMerging(nn.Module):
+ """Implement the patch merging layer for downsampling in TinyViT.
+
+ Args:
+ input_resolution: The height and width of the input feature map.
+ dim: The number of input channels.
+ out_dim: The number of output channels.
+ act: The activation function class. Default: nn.GELU.
+ """
+
def __init__(
self,
input_resolution: int | tuple[int, int],
@@ -107,6 +149,18 @@ class PatchMerging(nn.Module):
class ConvLayer(nn.Module):
+ """Implement a convolutional layer with optional checkpointing and downsample.
+
+ Args:
+ dim: The number of input channels.
+ depth: The number of blocks in the convolutional layer.
+ activation: The activation function to use. Default: :class:`nn.GELU`.
+ drop_path: The dropout rate for the stochastic depth. Default: 0.0.
+ downsample: The downsample module to use. Default: None.
+ use_checkpoint: Whether to use checkpointing for memory efficiency. Default: False.
+ conv_expand_ratio: The expansion ratio for the hidden dimension. Default: 4.0.
+ """
+
def __init__(
self,
dim: int,
@@ -139,6 +193,16 @@ class ConvLayer(nn.Module):
class MLP(nn.Sequential):
+ """Implement a multi-layer perceptron (MLP) with optional dropout.
+
+ Args:
+ in_features: The number of input features.
+ hidden_features: The number of hidden features.
+ out_features: The number of output features.
+ activation: The activation function to use. Default: :class:`nn.GELU`.
+ drop: The dropout rate. Default: 0.0.
+ """
+
def __init__(
self,
in_features: int,
@@ -160,6 +224,16 @@ class MLP(nn.Sequential):
# - different relative position encoding mechanism (separable/decomposed vs joint)
# - this impl supports attn_ratio (increase output size for value), though it is not used
class Attention(nn.Module):
+ """Implement an attention mechanism with optional relative position encoding.
+
+ Args:
+ dim: The number of input channels.
+ key_dim: The dimension of the key.
+ num_heads: The number of attention heads. Default: 8.
+ attn_ratio: The ratio of the attention dimension. Default: 4.0.
+ resolution: The resolution of the input feature map. Default: (14, 14).
+ """
+
def __init__(
self,
dim: int,
@@ -227,6 +301,22 @@ class Attention(nn.Module):
class TinyViTBlock(nn.Module):
+ """Implement a single block of the TinyViT architecture.
+
+ This block consists of multi-head self-attention and a feed-forward network
+ with residual connections.
+
+ Args:
+ dim: The input dimension size.
+ input_resolution: The height and width of the input feature map.
+ num_heads: The number of attention heads.
+ window_size: The size of the local attention window.
+ mlp_ratio: The ratio of MLP hidden dimension to embedding dimension.
+ drop: The dropout rate. Default: 0.0.
+ drop_path: The stochastic depth rate. Default: 0.0.
+ layer_scale_init_value: The initial value for layer scaling. Default: 1e-5.
+ """
+
def __init__(
self,
dim: int,
@@ -273,6 +363,26 @@ class TinyViTBlock(nn.Module):
class BasicLayer(nn.Module):
+ """Implement a basic layer of the TinyViT architecture.
+
+ This layer consists of a series of TinyViT blocks, each followed by a patch
+ merging operation.
+
+ Args:
+ dim: The input dimension size.
+ input_resolution: The height and width of the input feature map.
+ depth: The number of blocks in the layer.
+ num_heads: The number of attention heads.
+ window_size: The size of the local attention window.
+ mlp_ratio: The ratio of MLP hidden dimension to embedding dimension.
+ drop: The dropout rate. Default: 0.0.
+ drop_path: The stochastic depth rate. Default: 0.0.
+ downsample: The downsample module to use. Default: None.
+ use_checkpoint: Whether to use checkpointing for memory efficiency. Default: False.
+ local_conv_size: The size of the local convolution kernel. Default: 3.
+ activation: The activation function to use. Default: :class:`nn.GELU`.
+ """
+
def __init__(
self,
dim: int,
diff --git a/kornia/models/vit_mobile.py b/kornia/models/vit_mobile.py
index 97b316853..3f3795fea 100644
--- a/kornia/models/vit_mobile.py
+++ b/kornia/models/vit_mobile.py
@@ -32,6 +32,13 @@ def conv_nxn_bn(inp: int, oup: int, kernal_size: int = 3, stride: int = 1) -> nn
class PreNorm(nn.Module):
+ """Apply a normalization layer before the functional block.
+
+ Args:
+ dim: The input dimension size.
+ fn: The module or function to be executed after normalization.
+ """
+
def __init__(self, dim: int, fn: nn.Module) -> None:
super().__init__()
self.norm = nn.LayerNorm(dim)
@@ -42,6 +49,14 @@ class PreNorm(nn.Module):
class FeedForward(nn.Module):
+ """Implement the Feed-Forward network block for Vision Transformers.
+
+ Args:
+ dim: The input dimension size.
+ hidden_dim: The dimension of the hidden layer.
+ dropout: The dropout probability. Default: 0.0.
+ """
+
def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.0) -> None:
super().__init__()
self.net = nn.Sequential(
@@ -53,6 +68,15 @@ class FeedForward(nn.Module):
class Attention(nn.Module):
+ """Implement the Multi-Head Attention module.
+
+ Args:
+ dim: The input dimension size.
+ heads: The number of attention heads. Default: 8.
+ dim_head: The dimension of each head. Default: 64.
+ dropout: The dropout probability. Default: 0.0.
+ """
+
def __init__(self, dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.0) -> None:
super().__init__()
inner_dim = dim_head * heads
diff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.py
index 34eaad73e..2635f7d21 100644
--- a/kornia/sensors/camera/camera_model.py
+++ b/kornia/sensors/camera/camera_model.py
@@ -30,6 +30,15 @@ from kornia.sensors.camera.projection_model import OrthographicProjection, Z1Pro
class CameraModelType(Enum):
+ """Represent the type of camera projection and distortion model.
+
+ Supported types:
+ - PINHOLE: Standard perspective projection with no distortion.
+ - BROWN_CONRADY: Standard radial and tangential distortion model, often used for wide-angle lenses.
+ - KANNALA_BRANDT_K3: Fisheye distortion model using a 9th-order polynomial for equidistant projection.
+ - ORTHOGRAPHIC: Parallel projection where rays are perpendicular to the image plane, with no perspective effect.
+ """
+
PINHOLE = 0
BROWN_CONRADY = 1
KANNALA_BRANDT_K3 = 2
diff --git a/kornia/sensors/camera/distortion_model.py b/kornia/sensors/camera/distortion_model.py
index ef9622e1f..9c113e10e 100644
--- a/kornia/sensors/camera/distortion_model.py
+++ b/kornia/sensors/camera/distortion_model.py
@@ -22,6 +22,12 @@ from kornia.geometry.vector import Vector2
class AffineTransform:
+ """Apply an affine transformation to a set of 2D points.
+
+ This class handles the scaling and shifting of coordinates, typically used
+ to map normalized coordinates to pixel coordinates.
+ """
+
def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:
"""Distort one or more Vector2 points using the affine transform.
@@ -70,6 +76,18 @@ class AffineTransform:
class BrownConradyTransform:
+ """Implement the Brown-Conrady model for lens distortion and undistortion.
+
+ The model accounts for radial distortion (due to lens shape) and tangential
+ distortion (due to lens misalignment). It is commonly used to transform
+ points between ideal pinhole projections and distorted image coordinates.
+
+ Args:
+ params: A tensor containing the distortion coefficients
+ (usually k1, k2, p1, p2, k3).
+ points: A :class:`Vector2` representing the 2D coordinates to be transformed.
+ """
+
def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:
raise NotImplementedError
@@ -78,6 +96,12 @@ class BrownConradyTransform:
class KannalaBrandtK3Transform:
+ """Apply the Kannala-Brandt (K3) distortion model.
+
+ This model is specifically designed for fisheye lenses with significant
+ radial distortion, using a polynomial approximation for the projection.
+ """
+
def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:
raise NotImplementedError
diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.py
index 94eae1f97..40acaa358 100644
--- a/kornia/sensors/camera/projection_model.py
+++ b/kornia/sensors/camera/projection_model.py
@@ -23,6 +23,12 @@ from kornia.geometry.vector import Vector2, Vector3
class Z1Projection:
+ """Project 3D points from the camera frame into the canonical $z=1$ plane.
+
+ This performs perspective division by dividing the $x$ and $y$ coordinates
+ by the depth $z$.
+ """
+
def project(self, points: Vector3) -> Vector2:
"""Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division.
@@ -72,6 +78,12 @@ class Z1Projection:
class OrthographicProjection:
+ """Project 3D points using an orthographic projection model.
+
+ This model assumes parallel projection where the $z$ coordinate is
+ discarded and no perspective scaling is applied.
+ """
+
def project(self, points: Vector3) -> Vector2:
raise NotImplementedError