π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(models): add detailed missing public docstrings (#3735)
Jeevang1-epic4cd46bc1c332
diff --git a/kornia/models/_hf_models/hf_onnx_community.py b/kornia/models/_hf_models/hf_onnx_community.pyindex 0e5a15adb..d429e547d 100644--- a/kornia/models/_hf_models/hf_onnx_community.py+++ b/kornia/models/_hf_models/hf_onnx_community.py@@ -65,6 +65,21 @@ class HFONNXComunnityModelLoader:def load_model(self, download: bool = True, io_name_mapping: Optional[dict[str, str]] = None, **kwargs: Any) -> onnx.ModelProto: # type:ignore+ """Load the ONNX model file from the configured onnx-community repository.++ Args:+ download: Whether to download the remote ONNX file when it is not already+ available in the local cache directory.+ io_name_mapping: Optional mapping used to rename ONNX graph input and+ output names after loading. This is useful when composing the model+ with Kornia pre-processing or post-processing graphs that expect+ specific tensor names.+ kwargs: Additional keyword arguments forwarded to :class:`ONNXLoader`.++ Returns:+ The loaded ONNX model graph. If ``io_name_mapping`` is provided, the graph+ is returned after its input and output names have been converted.+ """onnx_model = ONNXLoader.load_model(self.model_url, download=download, with_data=self.with_data, cache_dir=self.cache_dir, **kwargs)@@ -77,6 +92,17 @@ class HFONNXComunnityModelLoader:def load_preprocessing(self,) -> ImageSequential:+ """Load the preprocessing pipeline described by the remote processor config.++ The Hugging Face onnx-community repositories store image preprocessing+ settings in ``preprocessor_config.json``. This method reads that JSON file and+ converts the supported operations, such as resize, rescale, and normalize, into+ a Kornia :class:`~kornia.core.ImageSequential` module.++ Returns:+ Sequential Kornia image preprocessing module built from the repository+ configuration.+ """json_req = ONNXLoader.load_config(self.config_url)return PreprocessingLoader.from_json(json_req)@@ -95,6 +121,24 @@ class HFONNXComunnityModelLoader:class HFONNXComunnityModel(ONNXSequential, ModelBaseMixin):+ """ONNX model wrapper for Kornia pipelines loaded from onnx-community repositories.++ The wrapper combines an optional preprocessing graph, the core ONNX model, and an+ optional postprocessing graph into a single :class:`ONNXSequential` module. It also+ keeps references to the individual components so callers can export either the+ complete pipeline or only the model graph.++ Args:+ model: Main ONNX model graph.+ pre_processor: Optional ONNX graph executed before ``model``.+ post_processor: Optional ONNX graph executed after ``model``.+ name: Optional human-readable model name used for export filenames.+ auto_ir_version_conversion: Whether to allow automatic ONNX IR version+ conversion when composing the sequence.+ io_maps: Optional list of input/output name mappings used when connecting the+ ONNX graphs together.+ """+name: str = "onnx_community_model"def __init__(diff --git a/kornia/models/_hf_models/preprocessor.py b/kornia/models/_hf_models/preprocessor.pyindex c0af70748..64dafe396 100644--- a/kornia/models/_hf_models/preprocessor.py+++ b/kornia/models/_hf_models/preprocessor.py@@ -29,28 +29,107 @@ from kornia.geometry.transform import Resizeclass PreprocessingLoader:+ """Factory for converting image-processor settings into Kornia modules.++ Hugging Face image processor configuration files describe preprocessing as JSON+ fields, for example whether to resize an image, multiply it by a rescale factor,+ or normalize it with channel statistics. This helper maps the supported fields to+ Kornia modules so the preprocessing can be composed with ONNX model pipelines.+ """+@staticmethoddef normalize(mean: torch.Tensor, std: torch.Tensor) -> Normalize:+ """Create a channel-wise normalization module.++ Args:+ mean: Mean value used for each channel. The tensor is passed directly to+ :class:`~kornia.enhance.normalize.Normalize`.+ std: Standard deviation value used for each channel.++ Returns:+ Kornia normalization module that subtracts ``mean`` and divides by ``std``+ for every image in the batch.+ """return Normalize(mean=mean, std=std)@staticmethoddef rescale(rescale_factor: float) -> Rescale:+ """Create an intensity rescaling module.++ Args:+ rescale_factor: Multiplicative factor applied to image values. In the DPT+ pipeline this is typically derived from the processor JSON so the+ tensor range matches what the exported model expects.++ Returns:+ Kornia rescaling module that multiplies the input image tensor by+ ``rescale_factor``.+ """return Rescale(factor=rescale_factor)@staticmethoddef resize(width: int, height: int) -> Resize:+ """Create an image resize module from width and height values.++ Args:+ width: Target image width, corresponding to the last spatial dimension+ ``W`` of an image tensor.+ height: Target image height, corresponding to the second-to-last spatial+ dimension ``H`` of an image tensor.++ Returns:+ Kornia resize module configured with output size ``(height, width)``.+ """return Resize((height, width))@staticmethoddef from_json(req: dict[str, Any]) -> ImageSequential:+ """Build a preprocessing pipeline from a processor configuration dictionary.++ Args:+ req: Parsed processor configuration. The dictionary must contain+ ``image_processor_type`` so the loader can choose the matching+ processor-specific parser.++ Returns:+ Sequential Kornia module containing the supported preprocessing steps.++ Raises:+ RuntimeError: If the requested image processor type is not supported by+ this loader.+ """if req["image_processor_type"] == "DPTImageProcessor":return DPTImageProcessor.from_json(req)raise RuntimeError(f"Unsupported image processor type: {req['image_processor_type']}")class DPTImageProcessor(PreprocessingLoader):+ """Parser for DPT image processor configurations.++ DPT models use a fixed image preprocessing recipe before inference. This parser+ reads the supported JSON fields and constructs the equivalent Kornia pipeline in+ the same order used by the processor configuration: resize, rescale, and normalize.+ Padding is intentionally not handled here because the current implementation does+ not include the extra parameters needed to reproduce that branch safely.+ """+@staticmethoddef from_json(json_data: dict[str, Any]) -> ImageSequential:+ """Convert a DPT processor JSON dictionary into a Kornia preprocessing pipeline.++ Args:+ json_data: Parsed DPT processor configuration. Supported fields include+ ``do_resize``, ``size``, ``do_rescale``, ``rescale_factor``,+ ``do_normalize``, ``image_mean``, and ``image_std``.++ Returns:+ :class:`~kornia.core.ImageSequential` containing the enabled preprocessing+ modules in execution order.++ Raises:+ NotImplementedError: If the configuration requests padding, which is not+ implemented by this loader.+ """preproc_list: list[nn.Module] = []if json_data["do_pad"]:raise NotImplementedErrordiff --git a/kornia/models/base.py b/kornia/models/base.pyindex 2fdf05875..21a9852b1 100644--- a/kornia/models/base.py+++ b/kornia/models/base.py@@ -150,6 +150,21 @@ class ModelBase(ABC, nn.Module, ModelBaseMixin, Generic[ModelConfig]):options: Optional[dict[Any, Any]] = None,disable: bool = False,) -> ModelBase[ModelConfig]:+ """Compile this model with :func:`torch.compile`.++ Args:+ fullgraph: Whether Dynamo should require a single full graph.+ dynamic: Whether dynamic shape tracing is enabled.+ backend: Compilation backend name passed to :func:`torch.compile`.+ mode: Optional backend-specific compilation mode.+ options: Optional backend-specific option dictionary.+ disable: If ``True``, return an uncompiled model wrapper according+ to PyTorch's compile semantics.++ Returns:+ Compiled model object with the same high-level interface as this+ instance.+ """compiled = torch.compile(self, fullgraph=fullgraph, dynamic=dynamic, backend=backend, mode=mode, options=options, disable=disable)diff --git a/kornia/models/common.py b/kornia/models/common.pyindex f16440668..3ebd166df 100644--- a/kornia/models/common.py+++ b/kornia/models/common.py@@ -92,6 +92,16 @@ class MLP(nn.Module):self.sigmoid_output = sigmoid_outputdef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the configured MLP to the last tensor dimension.++ Args:+ x: Input tensor whose last dimension equals ``input_dim``.++ Returns:+ Tensor with the same leading dimensions as ``x`` and final+ dimension ``output_dim``. If ``sigmoid_output`` is enabled, the+ final values are passed through a sigmoid.+ """for i, layer in enumerate(self.layers):x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)if self.sigmoid_output:@@ -110,6 +120,17 @@ class DropPath(nn.Module):self.scale_by_keep = scale_by_keepdef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply stochastic depth to a residual branch.++ Args:+ x: Residual-branch tensor with arbitrary shape. The first dimension+ is treated as the batch dimension.++ Returns:+ Tensor with the same shape as ``x``. During training, complete+ samples may be dropped and optionally scaled by the keep+ probability; during evaluation the input is returned unchanged.+ """if self.drop_prob == 0.0 or not self.training:return xkeep_prob = 1 - self.drop_prob@@ -132,6 +153,17 @@ class LayerNorm2d(nn.Module):self.eps = epsdef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply channel-wise layer normalization to an NCHW tensor.++ Args:+ x: Tensor with shape :math:`(B, C, H, W)`, where :math:`B` is batch+ size, :math:`C` is channel count, :math:`H` is height, and+ :math:`W` is width.++ Returns:+ Tensor with the same shape as ``x`` after normalizing across the+ channel dimension and applying learned affine parameters.+ """u = x.mean(1, keepdim=True)s = (x - u).pow(2).mean(1, keepdim=True)x = (x - u) / (s + self.eps).sqrt()diff --git a/kornia/models/dexined.py b/kornia/models/dexined.pyindex 292ffbfd9..d3116ddee 100644--- a/kornia/models/dexined.py+++ b/kornia/models/dexined.py@@ -242,12 +242,29 @@ class DexiNed(ONNXExportMixin, nn.Module):self.apply(weight_init)def load_from_file(self, path_file: str) -> None:+ """Load pretrained DexiNed weights and switch the module to evaluation mode.++ Args:+ path_file: URL or local checkpoint path accepted by+ :func:`torch.hub.load_state_dict_from_url`.+ """# use torch.hub to load pretrained modelpretrained_dict = torch.hub.load_state_dict_from_url(path_file, map_location=torch.device("cpu"))self.load_state_dict(pretrained_dict, strict=True)self.eval()def get_features(self, x: torch.Tensor) -> list[torch.Tensor]:+ """Compute the six multi-scale DexiNed side-output edge maps.++ Args:+ x: Input RGB image tensor with shape :math:`(B, 3, H, W)`, where+ :math:`B` is batch size, :math:`H` is height, and :math:`W` is+ width.++ Returns:+ List of six tensors aligned to the input spatial size. Each tensor+ is a side-output edge response used by the final fusion block.+ """# Block 1block_1 = self.block_1(x)block_1_side = self.side_1(block_1)@@ -294,6 +311,15 @@ class DexiNed(ONNXExportMixin, nn.Module):return resultsdef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Predict a fused edge map from an RGB image batch.++ Args:+ x: Input RGB image tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ Tensor with shape :math:`(B, 1, H, W)` containing the fused DexiNed+ edge response.+ """features = self.get_features(x)# concatenate multiscale outputsdiff --git a/kornia/models/efficient_vit/backbone.py b/kornia/models/efficient_vit/backbone.pyindex 6011a3540..04f5e6ae5 100644--- a/kornia/models/efficient_vit/backbone.py+++ b/kornia/models/efficient_vit/backbone.py@@ -141,6 +141,20 @@ class EfficientViTBackbone(nn.Module):act_func: str,fewer_norm: bool = False,) -> nn.Module:+ """Build the local convolution block used between EfficientViT stages.++ Args:+ in_channels: Number of input feature channels.+ out_channels: Number of output feature channels.+ stride: Spatial stride for the block.+ expand_ratio: Expansion ratio used by MBConv-style blocks.+ norm: Normalization layer name.+ act_func: Activation function name.+ fewer_norm: If ``True``, omit selected normalization layers.++ Returns:+ Depthwise-separable or inverted-bottleneck convolution block.+ """if expand_ratio == 1:block = DSConv(in_channels=in_channels,@@ -163,6 +177,15 @@ class EfficientViTBackbone(nn.Module):return blockdef forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]:+ """Run the EfficientViT backbone and collect stage outputs.++ Args:+ x: Image tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Dictionary containing the input, each stage output, and+ ``"stage_final"`` for the final feature map.+ """output_dict = {"input": x}output_dict["stage0"] = x = self.input_stem(x)for stage_id, stage in enumerate(self.stages, 1):@@ -323,6 +346,21 @@ class EfficientViTLargeBackbone(nn.Module):act_func: str,fewer_norm: bool = False,) -> nn.Module:+ """Build a local block for an EfficientViT large stage.++ Args:+ stage_id: Index of the stage being constructed.+ in_channels: Number of input feature channels.+ out_channels: Number of output feature channels.+ stride: Spatial stride for the block.+ expand_ratio: Expansion ratio controlling intermediate channels.+ norm: Normalization layer name.+ act_func: Activation function name.+ fewer_norm: If ``True``, use the reduced-normalization variant.++ Returns:+ Residual, fused-MBConv, or MBConv block chosen for the stage.+ """if expand_ratio == 1:block = ResBlock(in_channels=in_channels,@@ -355,6 +393,15 @@ class EfficientViTLargeBackbone(nn.Module):return blockdef forward(self, x: torch.Tensor) -> dict[str, torch.Tensor]:+ """Run the EfficientViT large backbone and collect stage outputs.++ Args:+ x: Image tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Dictionary with entries for each stage and ``"stage_final"`` for+ the final feature map.+ """output_dict = {"input": x}for stage_id, stage in enumerate(self.stages):output_dict[f"stage{stage_id}"] = x = stage(x)diff --git a/kornia/models/efficient_vit/nn/norm.py b/kornia/models/efficient_vit/nn/norm.pyindex cf62710d5..1cf00f604 100644--- a/kornia/models/efficient_vit/nn/norm.py+++ b/kornia/models/efficient_vit/nn/norm.py@@ -32,6 +32,15 @@ class LayerNorm2d(nn.LayerNorm):"""Apply Layer Normalization over a 4D input tensor (NCHW format)."""def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Normalize an NCHW feature map across channels.++ Args:+ x: Tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Tensor with the same shape as ``x`` after channel-wise layer+ normalization and optional affine scaling.+ """out = x - torch.mean(x, dim=1, keepdim=True)out = out / torch.sqrt(torch.square(out).mean(dim=1, keepdim=True) + self.eps)if self.elementwise_affine:diff --git a/kornia/models/efficient_vit/nn/ops.py b/kornia/models/efficient_vit/nn/ops.pyindex cb9f5bbc6..188e24cfe 100644--- a/kornia/models/efficient_vit/nn/ops.py+++ b/kornia/models/efficient_vit/nn/ops.py@@ -95,6 +95,14 @@ class ConvLayer(nn.Module):self.act = build_act(act_func)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply dropout, convolution, optional normalization, and activation.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map after the configured convolutional layer stack.+ """if self.dropout is not None:x = self.dropout(x)x = self.conv(x)@@ -109,6 +117,7 @@ class IdentityLayer(nn.Module):"""Implement a placeholder layer that returns the input as-is."""def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Return the input tensor unchanged."""return x@@ -164,6 +173,15 @@ class DSConv(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply depthwise then pointwise convolution.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map with ``out_channels`` produced by the pointwise+ projection.+ """x = self.depth_conv(x)x = self.point_conv(x)return x@@ -229,6 +247,14 @@ class MBConv(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply an inverted bottleneck convolution block.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map after expansion, depthwise convolution, and projection.+ """x = self.inverted_conv(x)x = self.depth_conv(x)x = self.point_conv(x)@@ -294,6 +320,15 @@ class FusedMBConv(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply a fused mobile inverted bottleneck convolution.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map after fused spatial convolution and pointwise+ projection.+ """x = self.spatial_conv(x)x = self.point_conv(x)return x@@ -348,6 +383,14 @@ class ResBlock(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the two-convolution residual-block main branch.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map after the block's convolutional transformations.+ """x = self.conv1(x)x = self.conv2(x)return x@@ -457,6 +500,15 @@ class LiteMLA(nn.Module):return outdef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply lightweight multi-scale linear attention.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map after multi-scale query/key/value aggregation, linear+ attention, and output projection.+ """# generate multi-scale q, k, vqkv = self.qkv(x)multi_scale_qkv = [qkv]@@ -515,6 +567,15 @@ class EfficientViTBlock(nn.Module):self.local_module = ResidualBlock(local_module, IdentityLayer())def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply an EfficientViT attention-plus-local block.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map with the same shape after the context module and local+ MBConv module.+ """x = self.context_module(x)x = self.local_module(x)return x@@ -550,12 +611,30 @@ class ResidualBlock(nn.Module):self.post_act = build_act(post_act)def forward_main(self, x: torch.Tensor) -> torch.Tensor:+ """Run the main branch, applying pre-normalization when configured.++ Args:+ x: Input tensor for the residual block.++ Returns:+ Output from ``self.main`` with optional ``self.pre_norm`` applied+ first.+ """if self.pre_norm is None:return self.main(x)else:return self.main(self.pre_norm(x))def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the residual wrapper to an input tensor.++ Args:+ x: Input tensor passed to the main and shortcut branches.++ Returns:+ Tensor from the main branch, optionally added to the shortcut and+ passed through ``self.post_act``.+ """if self.main is None:res = xelif self.shortcut is None:@@ -588,6 +667,14 @@ class OpSequential(nn.Module):self.op_list = nn.ModuleList(valid_op_list)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply each non-empty operation in sequence.++ Args:+ x: Input tensor for the first operation.++ Returns:+ Tensor after all stored operations have been applied.+ """for op in self.op_list:x = op(x)return xdiff --git a/kornia/models/kimi_vl/moonvit.py b/kornia/models/kimi_vl/moonvit.pyindex 84b9b033c..ade38af72 100644--- a/kornia/models/kimi_vl/moonvit.py+++ b/kornia/models/kimi_vl/moonvit.py@@ -56,6 +56,23 @@ class MoonViTRotaryEmbedding(nn.Module):self.theta = thetadef forward(self, h: int, w: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:+ """Build cosine and sine tables for two-dimensional rotary position embeddings.++ The MoonViT encoder works on a flattened patch grid. This method receives the+ grid height ``h`` and width ``w`` after patch embedding, creates one frequency+ bank for the vertical axis and one for the horizontal axis, and then expands+ them so each flattened patch token has a matching rotary embedding. The+ returned tensors are later applied to the query and key vectors in attention.++ Args:+ h: Number of patch rows in the image grid.+ w: Number of patch columns in the image grid.+ device: Device on which the cosine and sine tensors should be allocated.++ Returns:+ A tuple containing the cosine and sine lookup tables, each with shape+ :math:`(h * w, D)`, where ``D`` is the per-head rotary embedding dimension.+ """# dim must be divisible by 2 for 2D RoPE (half for H, half for W)# And each half must be divisible by 2 for complex rotationdim_h = self.dim // 2@@ -89,6 +106,18 @@ class MoonViTRotaryEmbedding(nn.Module):class MoonViTAttention(nn.Module):+ """Multi-head self-attention layer used by the MoonViT vision encoder.++ The layer projects input tokens into query, key, and value tensors, splits the+ hidden dimension across attention heads, applies two-dimensional rotary positional+ embeddings (RoPE) to the query and key tensors, and finally computes scaled+ dot-product attention. The output is projected back to the model hidden size.++ Args:+ config: MoonViT configuration containing the hidden size, number of attention+ heads, and attention dropout probability.+ """+def __init__(self, config: MoonViTConfig) -> None:super().__init__()self.num_heads = config.num_attention_heads@@ -109,6 +138,24 @@ class MoonViTAttention(nn.Module):sin: torch.Tensor,attention_mask: Optional[torch.Tensor] = None,) -> torch.Tensor:+ """Apply rotary self-attention to a sequence of visual patch tokens.++ Args:+ hidden_states: Input token tensor with shape :math:`(B, N, D)`, where+ ``B`` is the batch size, ``N`` is the number of flattened image+ patches, and ``D`` is the hidden size.+ cos: Cosine component of the rotary positional embedding with shape+ :math:`(N, d)`, where ``d`` is the per-head dimension.+ sin: Sine component of the rotary positional embedding with shape+ :math:`(N, d)`.+ attention_mask: Optional mask broadcastable to the scaled dot-product+ attention scores. It can be used to prevent selected tokens from+ attending to one another.++ Returns:+ Tensor with shape :math:`(B, N, D)` containing the attended visual token+ features after the output projection.+ """batch_size, seq_len, _ = hidden_states.shapequery = self.q_proj(hidden_states)@@ -154,6 +201,17 @@ class MoonViTMLP(nn.Module):self.dropout = nn.Dropout(config.dropout_p)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Project token features through the MoonViT feed-forward network.++ Args:+ x: Input token features with shape :math:`(B, N, D)`, where ``B`` is the+ batch size, ``N`` is the number of patch tokens, and ``D`` is the model+ hidden size.++ Returns:+ Tensor with shape :math:`(B, N, D)` after expansion to the intermediate+ hidden size, GELU activation, projection back to ``D``, and dropout.+ """x = self.fc1(x)x = self.act(x)x = self.fc2(x)@@ -184,6 +242,26 @@ class MoonViTLayer(nn.Module):def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:+ """Run one pre-normalized MoonViT transformer block.++ The block first normalizes the input tokens before self-attention, adds the+ attention result back through a residual connection, then repeats the same+ pre-normalization and residual pattern for the MLP sub-block.++ Args:+ x: Token tensor with shape :math:`(B, N, D)`, where ``B`` is the batch+ size, ``N`` is the number of flattened image patches, and ``D`` is the+ hidden size.+ cos: Cosine rotary embedding table with shape :math:`(N, d)`, where ``d``+ is the per-head attention dimension.+ sin: Sine rotary embedding table with shape :math:`(N, d)`.+ attention_mask: Optional attention mask forwarded to the self-attention+ layer.++ Returns:+ Tensor with shape :math:`(B, N, D)` after attention, MLP processing, and+ residual updates.+ """x = x + self.attn(self.norm1(x), cos, sin, attention_mask)x = x + self.mlp(self.norm2(x))return x@@ -205,6 +283,20 @@ class MoonViTEncoder(nn.Module):def forward(self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:+ """Encode visual patch tokens through the full MoonViT transformer stack.++ Args:+ x: Input token tensor with shape :math:`(B, N, D)`, where ``B`` is batch+ size, ``N`` is the flattened patch count, and ``D`` is hidden size.+ cos: Cosine rotary embedding table shared by all encoder layers.+ sin: Sine rotary embedding table shared by all encoder layers.+ attention_mask: Optional attention mask passed unchanged to every+ transformer layer.++ Returns:+ Tensor with shape :math:`(B, N, D)` containing the encoded patch sequence+ after all MoonViT layers have been applied.+ """for layer in self.layers:x = layer(x, cos, sin, attention_mask)return xdiff --git a/kornia/models/paligemma/modeling_paligemma.py b/kornia/models/paligemma/modeling_paligemma.pyindex c7128ff1f..0ddbf96a9 100644--- a/kornia/models/paligemma/modeling_paligemma.py+++ b/kornia/models/paligemma/modeling_paligemma.py@@ -40,6 +40,17 @@ class GemmaRMSNorm(nn.Module):return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply Gemma RMS normalization to hidden states.++ Args:+ x: Hidden-state tensor with shape :math:`(B, N, D)`, where+ :math:`B` is batch size, :math:`N` is sequence length, and+ :math:`D` is hidden dimension.++ Returns:+ Tensor with the same shape as ``x`` after root-mean-square+ normalization and learned scaling.+ """output = self._norm(x.float()).type_as(x)return output * (1.0 + self.weight)@@ -63,6 +74,16 @@ class GemmaRotaryEmbedding(nn.Module):self.register_buffer("inv_freq", inv_freq, persistent=False)def forward(self, x: torch.Tensor, position_ids: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:+ """Create rotary sine and cosine embeddings for token positions.++ Args:+ x: Tensor whose dtype is used for the returned embeddings.+ position_ids: Position tensor with shape :math:`(B, N)`.++ Returns:+ Tuple ``(cos, sin)`` containing rotary embedding factors with dtype+ matching ``x``.+ """inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)position_ids_expanded = position_ids[:, None, :].float()@@ -105,6 +126,15 @@ class GemmaMLP(nn.Module):self.act_fn = nn.GELU()def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the gated Gemma feed-forward projection.++ Args:+ x: Hidden-state tensor with shape :math:`(B, N, D)`.++ Returns:+ Tensor with shape :math:`(B, N, D)` after gate projection,+ activation, up projection, elementwise gating, and down projection.+ """return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))@@ -146,6 +176,18 @@ class GemmaAttention(nn.Module):attention_mask: Optional[torch.Tensor] = None,position_ids: Optional[torch.LongTensor] = None,) -> torch.Tensor:+ """Apply grouped-query self-attention with rotary position embeddings.++ Args:+ hidden_states: Input token tensor with shape :math:`(B, N, D)`.+ attention_mask: Optional attention mask passed to scaled dot-product+ attention.+ position_ids: Token position ids with shape :math:`(B, N)`.++ Returns:+ Tensor with shape :math:`(B, N, D)` after attention and output+ projection.+ """bsz, q_len, _ = hidden_states.size()query_states = self.q_proj(hidden_states)@@ -200,6 +242,17 @@ class GemmaDecoderLayer(nn.Module):attention_mask: Optional[torch.Tensor] = None,position_ids: Optional[torch.LongTensor] = None,) -> torch.Tensor:+ """Run one Gemma decoder layer.++ Args:+ hidden_states: Input token tensor with shape :math:`(B, N, D)`.+ attention_mask: Optional mask used by the attention block.+ position_ids: Token position ids used to build rotary embeddings.++ Returns:+ Tensor with shape :math:`(B, N, D)` after self-attention, MLP, and+ residual connections.+ """residual = hidden_stateshidden_states = self.input_layernorm(hidden_states)hidden_states = self.self_attn(diff --git a/kornia/models/qwen25/qwen2_vl.py b/kornia/models/qwen25/qwen2_vl.pyindex 1d5745f11..f39e94946 100644--- a/kornia/models/qwen25/qwen2_vl.py+++ b/kornia/models/qwen25/qwen2_vl.py@@ -40,6 +40,15 @@ class Qwen2VLPatchMerger(Module):self.ln_q = nn.LayerNorm(dim, eps=1e-6)def forward(self, x: Tensor) -> Tensor:+ """Convert an image batch into Qwen2-VL patch tokens.++ Args:+ x: Image tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ Token tensor with shape :math:`(B, N, D)`, where :math:`N` is the+ number of extracted patches and :math:`D` is ``dim``.+ """x = self.conv(x)x = x.flatten(2)x = x.transpose(1, 2)@@ -69,6 +78,16 @@ class Qwen2VLRotaryEmbedding(Module):self.register_buffer("inv_freq", inv_freq, persistent=False)def forward(self, x: Tensor, cu_seqlens: Optional[Tensor] = None) -> Tensor:+ """Return rotary-position input unchanged for this lightweight module.++ Args:+ x: Token tensor that would receive rotary position information.+ cu_seqlens: Optional cumulative sequence lengths kept for API+ compatibility with Qwen2-VL implementations.++ Returns:+ The input tensor ``x`` unchanged.+ """return x@@ -90,6 +109,18 @@ class Qwen2VLVisionAttention(Module):self.proj = nn.Linear(dim, dim, bias=True)def forward(self, x: Tensor, cu_seqlens: Optional[Tensor] = None, rot_pos_emb: Optional[Tensor] = None) -> Tensor:+ """Apply multi-head self-attention to vision tokens.++ Args:+ x: Token tensor with shape :math:`(B, N, D)`.+ cu_seqlens: Optional cumulative sequence lengths kept for API+ compatibility.+ rot_pos_emb: Optional rotary positional embedding tensor.++ Returns:+ Tensor with shape :math:`(B, N, D)` after attention and output+ projection.+ """B, N, C = x.shapeqkv = self.qkv(x).reshape(B, N, 3, self.num_heads, self.head_dim).permute(2, 0, 3, 1, 4)q, k, v = qkv[0], qkv[1], qkv[2]@@ -119,6 +150,15 @@ class Qwen2VLMLP(Module):self.fc2 = nn.Linear(hidden_dim, dim)def forward(self, x: Tensor) -> Tensor:+ """Apply the Qwen2-VL vision feed-forward network.++ Args:+ x: Token tensor with shape :math:`(B, N, D)`.++ Returns:+ Tensor with shape :math:`(B, N, D)` after expansion, GELU+ activation, and projection.+ """return self.fc2(self.act(self.fc1(x)))@@ -143,6 +183,17 @@ class Qwen2VLVisionBlock(Module):self.mlp = Qwen2VLMLP(dim, int(dim * mlp_ratio))def forward(self, x: Tensor, rot_pos_emb: Optional[Tensor] = None) -> Tensor:+ """Run one Qwen2-VL vision transformer block.++ Args:+ x: Vision token tensor with shape :math:`(B, N, D)`.+ rot_pos_emb: Optional rotary positional embedding passed to the+ attention layer.++ Returns:+ Tensor with shape :math:`(B, N, D)` after attention, MLP, and+ residual connections.+ """x = x + self.attn(self.norm1(x), rot_pos_emb=rot_pos_emb)x = x + self.mlp(self.norm2(x))return x@@ -177,6 +228,15 @@ class Qwen2VLVisionTransformer(Module):self.rotary_pos_emb = Qwen2VLRotaryEmbedding(embed_dim // num_heads)def forward(self, x: Tensor) -> Tensor:+ """Encode an image batch into Qwen2-VL vision tokens.++ Args:+ x: Image tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ Token tensor with shape :math:`(B, N, D)` after patch embedding and+ the configured stack of vision transformer blocks.+ """x = self.patch_embed(x)rot_pos_emb = self.rotary_pos_emb(x)for block in self.blocks:diff --git a/kornia/models/rt_detr/architecture/hgnetv2.py b/kornia/models/rt_detr/architecture/hgnetv2.pyindex 693cb8955..2ec36a3cd 100644--- a/kornia/models/rt_detr/architecture/hgnetv2.py+++ b/kornia/models/rt_detr/architecture/hgnetv2.py@@ -44,6 +44,15 @@ class StemBlock(nn.Module):self.pool = nn.Sequential(nn.ZeroPad2d((0, 1, 0, 1)), nn.MaxPool2d(2, 1))def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Run the HGNetV2 stem and reduce the input spatial resolution.++ Args:+ x: Image tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Stem feature map after strided convolutions, pooling, concatenation,+ and channel projection.+ """x = self.stem1(x)x = torch.cat([self.pool(x), self.stem2b(self.stem2a(x))], 1)x = self.stem4(self.stem3(x))@@ -103,6 +112,15 @@ class HGBlock(nn.Module):self.aggregation_excitation_conv = ConvNormAct(config.out_channels // 2, config.out_channels, 1)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply one HGNetV2 aggregation block.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Aggregated feature map. If ``self.identity`` is enabled, the input+ is added as a residual connection.+ """feats = [x]for layer in self.layers:feats.append(layer(feats[-1]))@@ -148,6 +166,15 @@ class PPHGNetV2(nn.Module):self.stages.append(HGStage(cfg))def forward(self, x: torch.Tensor) -> list[torch.Tensor]:+ """Run the PPHGNetV2 backbone and return detection feature maps.++ Args:+ x: Image tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ List ``[s3, s4, s5]`` containing the final three backbone stages+ used by the detector neck.+ """x = self.stem(x)s2 = self.stages[0](x)s3 = self.stages[1](s2)@@ -157,6 +184,14 @@ class PPHGNetV2(nn.Module):@staticmethoddef from_config(variant: str) -> PPHGNetV2:+ """Create a PPHGNetV2 backbone from a named variant.++ Args:+ variant: Backbone variant name. Currently ``"L"`` is supported.++ Returns:+ Configured :class:`PPHGNetV2` instance.+ """if variant == "L":return PPHGNetV2(stem_channels=[3, 32, 48],diff --git a/kornia/models/rt_detr/architecture/hybrid_encoder.py b/kornia/models/rt_detr/architecture/hybrid_encoder.pyindex 13fd7d075..6bb2d4516 100644--- a/kornia/models/rt_detr/architecture/hybrid_encoder.py+++ b/kornia/models/rt_detr/architecture/hybrid_encoder.py@@ -49,6 +49,15 @@ class RepVggBlock(nn.Module):self.conv: Optional[nn.Conv2d] = Nonedef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the RepVGG block in training or fused deployment form.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map after either the fused convolution or the summed+ ``3x3`` and ``1x1`` branches followed by SiLU activation.+ """if self.conv is not None:out = self.act(self.conv(x))else:@@ -57,6 +66,12 @@ class RepVggBlock(nn.Module):@torch.no_grad()def optimize_for_deployment(self) -> None:+ """Fuse convolution and batch-normalization branches for inference.++ The method replaces the parallel training-time branches with a single+ equivalent ``3x3`` convolution stored in ``self.conv``.+ """+def _fuse_conv_bn_weights(m: ConvNormAct) -> tuple[nn.Parameter, nn.Parameter]:if m.norm.running_mean is None or m.norm.running_var is None:raise ValueError@@ -104,6 +119,15 @@ class CSPRepLayer(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Fuse cross-stage partial RepVGG features.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map after one branch passes through RepVGG bottlenecks and+ is added to the shortcut branch, then projected to output channels.+ """return self.conv3(self.bottlenecks(self.conv1(x)) + self.conv2(x))@@ -134,6 +158,15 @@ class AIFI(nn.Module):self.act = nn.GELU()def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply all-scale feature interaction to one feature map.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Tensor with shape :math:`(B, C, H, W)` after positional+ self-attention and feed-forward refinement.+ """# using post-normN, C, H, W = x.shapex = x.permute(2, 3, 0, 1).flatten(0, 1) # (N, C, H, W) -> (H * W, N, C)@@ -150,6 +183,15 @@ class AIFI(nn.Module):return xdef ffn(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the feed-forward sublayer used inside AIFI.++ Args:+ x: Token tensor with last dimension equal to the embedding size.++ Returns:+ Tensor with the same shape as ``x`` after linear expansion,+ activation, dropout, and projection.+ """return self.linear2(self.dropout(self.act(self.linear1(x))))# TODO: make this into a reusable function@@ -209,6 +251,14 @@ class TransformerEncoder(nn.Module):def forward(self, src: torch.Tensor) -> torch.Tensor: # NOTE: Missing src_mask: torch.Tensor = None, pos_embed: torch.Tensor = None+ """Apply the stacked transformer encoder layers.++ Args:+ src: Source feature tensor passed through each encoder layer.++ Returns:+ Tensor after all cloned encoder layers have been applied.+ """output = srcfor layer in self.layers:output = layer(output)@@ -240,6 +290,15 @@ class CCFM(nn.Module):self.pan_blocks.append(CSPRepLayer(hidden_dim * 2, hidden_dim, 3, expansion))def forward(self, fmaps: list[torch.Tensor]) -> list[torch.Tensor]:+ """Fuse multi-scale feature maps with FPN and PAN paths.++ Args:+ fmaps: Feature maps ordered from high resolution to low resolution.++ Returns:+ List of fused feature maps ordered from high resolution to low+ resolution after top-down and bottom-up mixing.+ """# fmaps is ordered from hi-res to low-resfmaps = list(fmaps) # shallow clone@@ -286,6 +345,16 @@ class HybridEncoder(nn.Module):self.ccfm = CCFM(len(in_channels), hidden_dim, expansion)def forward(self, fmaps: list[torch.Tensor]) -> list[torch.Tensor]:+ """Project and fuse backbone feature maps for RT-DETR.++ Args:+ fmaps: List of backbone feature maps with decreasing spatial+ resolution.++ Returns:+ List of encoded and cross-scale fused feature maps used by the+ RT-DETR detection head.+ """projected_maps = [proj(fmap) for proj, fmap in zip(self.input_proj, fmaps)]projected_maps[-1] = self.encoder(projected_maps[-1])new_fmaps = self.ccfm(projected_maps)diff --git a/kornia/models/rt_detr/architecture/resnet_d.py b/kornia/models/rt_detr/architecture/resnet_d.pyindex 8bcc70baf..7bc8164a3 100644--- a/kornia/models/rt_detr/architecture/resnet_d.py+++ b/kornia/models/rt_detr/architecture/resnet_d.py@@ -62,6 +62,15 @@ class BasicBlockD(nn.Module):self.relu = nn.ReLU(inplace=True)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply a basic ResNet-D residual block.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Tensor after two convolutions, shortcut projection if needed, and+ ReLU activation.+ """return self.relu(self.convs(x) + self.short(x))@@ -87,6 +96,15 @@ class BottleneckD(nn.Module):self.relu = nn.ReLU(inplace=True)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply a bottleneck ResNet-D residual block.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Tensor after ``1x1``, ``3x3``, and ``1x1`` convolutions, shortcut+ addition, and ReLU activation.+ """return self.relu(self.convs(x) + self.short(x))@@ -138,6 +156,19 @@ class ResNetD(nn.Module):def make_stage(in_channels: int, out_channels: int, stride: int, n_blocks: int, block: type[BasicBlockD | BottleneckD]) -> tuple[nn.Module, int]:+ """Build one ResNet-D stage.++ Args:+ in_channels: Number of input channels for the first block.+ out_channels: Base output channels for the stage before expansion.+ stride: Stride used by the first block.+ n_blocks: Number of residual blocks in the stage.+ block: Residual block class to instantiate.++ Returns:+ Tuple ``(stage, channels)`` containing the stage module and its+ expanded output channel count.+ """stage = Block(nn.Sequential(block(in_channels, out_channels, stride, False),@@ -147,6 +178,15 @@ class ResNetD(nn.Module):return stage, out_channels * block.expansiondef forward(self, x: torch.Tensor) -> list[torch.Tensor]:+ """Run the ResNet-D backbone and return detector feature maps.++ Args:+ x: Image tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ List ``[res3, res4, res5]`` containing the final three feature+ stages used by RT-DETR.+ """x = self.conv1(x)res2 = self.res_layers[0](x)res3 = self.res_layers[1](res2)@@ -156,6 +196,14 @@ class ResNetD(nn.Module):@staticmethoddef from_config(variant: str | int) -> ResNetD:+ """Create a ResNet-D backbone from a depth variant.++ Args:+ variant: ResNet depth, such as ``18``, ``34``, ``50``, or ``101``.++ Returns:+ Configured :class:`ResNetD` instance.+ """variant = str(variant)if variant == "18":return ResNetD([2, 2, 2, 2], BasicBlockD)diff --git a/kornia/models/rt_detr/architecture/rtdetr_head.py b/kornia/models/rt_detr/architecture/rtdetr_head.pyindex e45e29a6f..2d7f6a5dc 100644--- a/kornia/models/rt_detr/architecture/rtdetr_head.py+++ b/kornia/models/rt_detr/architecture/rtdetr_head.py@@ -203,6 +203,21 @@ class TransformerDecoderLayer(nn.Module):memory_mask: Optional[torch.Tensor] = None,query_pos_embed: Optional[torch.Tensor] = None,) -> torch.Tensor:+ """Run one RT-DETR transformer decoder layer.++ Args:+ tgt: Query tensor with shape :math:`(B, N_q, D)`.+ ref_points: Reference points for deformable cross-attention.+ memory: Flattened encoder memory tensor.+ memory_spatial_shapes: Spatial shape for each memory level.+ memory_level_start_index: Optional start index for each level.+ attn_mask: Optional self-attention mask.+ memory_mask: Optional memory mask.+ query_pos_embed: Optional positional embedding for object queries.++ Returns:+ Updated query tensor with shape :math:`(B, N_q, D)`.+ """# TODO: rename variables because is confusing# self attentionq = k = tgt + query_pos_embed@@ -242,6 +257,24 @@ class TransformerDecoder(nn.Module):attn_mask: Optional[torch.Tensor] = None,memory_mask: Optional[torch.Tensor] = None,) -> tuple[torch.Tensor, torch.Tensor]:+ """Decode object queries into bounding boxes and class logits.++ Args:+ tgt: Initial query tensor with shape :math:`(B, N_q, D)`.+ ref_points_unact: Unactivated reference boxes for the queries.+ memory: Flattened encoder feature memory.+ memory_spatial_shapes: Spatial shape for each feature level.+ memory_level_start_index: Start index for each level in ``memory``.+ bbox_head: Per-layer box prediction heads.+ score_head: Per-layer class prediction heads.+ query_pos_head: Module that maps reference boxes to query position+ embeddings.+ attn_mask: Optional query attention mask.+ memory_mask: Optional encoder memory mask.++ Returns:+ Tuple ``(boxes, logits)`` stacked from the selected decoder layer.+ """output: torch.Tensor = tgtdec_out_bboxes: list[torch.Tensor] = []dec_out_logits: list[torch.Tensor] = []@@ -352,6 +385,16 @@ class RTDETRHead(nn.Module):)def forward(self, feats: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ """Predict RT-DETR class logits and bounding boxes from neck features.++ Args:+ feats: Multi-level feature maps from the encoder/neck.++ Returns:+ Tuple ``(logits, boxes)`` for the final decoder output. ``logits``+ stores class scores and ``boxes`` stores normalized box+ coordinates.+ """# input projection and embeddingmemory, spatial_shapes, level_start_index = self._get_encoder_input(feats)diff --git a/kornia/models/sam/architecture/common.py b/kornia/models/sam/architecture/common.pyindex 715034729..c87505411 100644--- a/kornia/models/sam/architecture/common.py+++ b/kornia/models/sam/architecture/common.py@@ -45,6 +45,15 @@ class MLPBlock(nn.Module):self.act = act()def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the two-layer MLP block to token embeddings.++ Args:+ x: Token tensor with last dimension ``embedding_dim``.++ Returns:+ Tensor with the same shape as ``x`` after hidden projection,+ activation, and projection back to ``embedding_dim``.+ """return self.lin2(self.act(self.lin1(x)))diff --git a/kornia/models/sam/architecture/image_encoder.py b/kornia/models/sam/architecture/image_encoder.pyindex 2da29bed6..56c2bb608 100644--- a/kornia/models/sam/architecture/image_encoder.py+++ b/kornia/models/sam/architecture/image_encoder.py@@ -136,6 +136,17 @@ class ImageEncoderViT(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Encode an image batch into SAM image embeddings.++ Args:+ x: Image tensor with shape :math:`(B, C, H, W)`, where :math:`B`+ is batch size, :math:`C` is channel count, and :math:`H`,+ :math:`W` are image height and width.++ Returns:+ Image embedding tensor with shape :math:`(B, C_{out}, H_e, W_e)`+ after patch embedding, transformer blocks, and the neck.+ """x = self.patch_embed(x)if self.pos_embed is not None:x = x + self.pos_embed@@ -196,6 +207,15 @@ class Block(nn.Module):self.window_size = window_sizedef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply one SAM image-encoder transformer block.++ Args:+ x: Feature tensor with shape :math:`(B, H, W, C)`.++ Returns:+ Tensor with the same shape as ``x`` after window or global+ attention, MLP, and residual connections.+ """shortcut = xx = self.norm1(x)# Window partition@@ -252,6 +272,15 @@ class Attention(nn.Module):self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply multi-head attention over 2D image tokens.++ Args:+ x: Token grid with shape :math:`(B, H, W, C)`.++ Returns:+ Tensor with shape :math:`(B, H, W, C)` after attention, optional+ decomposed relative positional bias, and output projection.+ """B, H, W, _ = x.shape# qkv with shape (3, B, nHead, H * W, C)qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)@@ -370,6 +399,16 @@ class PatchEmbed(nn.Module):self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Project an image into patch embeddings.++ Args:+ x: Image tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Patch embedding tensor with shape :math:`(B, H_p, W_p, D)`, where+ :math:`H_p` and :math:`W_p` are patch-grid dimensions and+ :math:`D` is embedding dimension.+ """x = self.proj(x)# B C H W -> B H W Cx = x.permute(0, 2, 3, 1)diff --git a/kornia/models/sam/architecture/transformer.py b/kornia/models/sam/architecture/transformer.pyindex 1f731dbfc..f2d9f8877 100644--- a/kornia/models/sam/architecture/transformer.py+++ b/kornia/models/sam/architecture/transformer.py@@ -186,6 +186,19 @@ class TwoWayAttentionBlock(nn.Module):def forward(self, queries: torch.Tensor, keys: torch.Tensor, query_pe: torch.Tensor, key_pe: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ """Run one two-way transformer block for prompt and image tokens.++ Args:+ queries: Prompt token tensor with shape :math:`(B, N_q, D)`.+ keys: Image token tensor with shape :math:`(B, N_k, D)`.+ query_pe: Positional encoding for ``queries`` with the same shape.+ key_pe: Positional encoding for ``keys`` with the same shape.++ Returns:+ Tuple ``(queries, keys)`` after prompt self-attention,+ prompt-to-image cross-attention, MLP update, and image-to-prompt+ cross-attention.+ """# Self attention blockif self.skip_first_layer_pe:queries = self.self_attn(q=queries, k=queries, v=queries)@@ -243,6 +256,17 @@ class Attention(nn.Module):return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x Cdef forward(self, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:+ """Apply scaled dot-product attention to query, key, and value tokens.++ Args:+ q: Query tensor with shape :math:`(B, N_q, D)`.+ k: Key tensor with shape :math:`(B, N_k, D)`.+ v: Value tensor with shape :math:`(B, N_k, D)`.++ Returns:+ Tensor with shape :math:`(B, N_q, D)` after multi-head attention+ and output projection.+ """# Input projectionsq = self.q_proj(q)k = self.k_proj(k)diff --git a/kornia/models/segmentation/segmentation_models.py b/kornia/models/segmentation/segmentation_models.pyindex 4ec139970..d30c655a6 100644--- a/kornia/models/segmentation/segmentation_models.py+++ b/kornia/models/segmentation/segmentation_models.py@@ -89,6 +89,17 @@ class SegmentationModelsBuilder:@staticmethoddef get_preprocessing_pipeline(preproc_params: dict[str, Any]) -> kornia.augmentation.container.ImageSequential:+ """Build the preprocessing pipeline expected by a segmentation model.++ Args:+ preproc_params: Dictionary from the segmentation-model metadata.+ It must describe the input color space, value range, mean, and+ standard deviation used by the pretrained encoder.++ Returns:+ :class:`~kornia.augmentation.container.ImageSequential` containing+ ONNX-friendly color conversion, rescaling, and normalization steps.+ """# Ensure the color space transformation is ONNX-friendlyproc_sequence: list[nn.Module] = []input_space = preproc_params["input_space"]diff --git a/kornia/models/siglip2/preprocessor.py b/kornia/models/siglip2/preprocessor.pyindex 1c7381ef6..c207bbc85 100644--- a/kornia/models/siglip2/preprocessor.py+++ b/kornia/models/siglip2/preprocessor.py@@ -82,6 +82,17 @@ class SigLip2ImagePreprocessor(nn.Module):self.preprocessor = nn.Sequential(*preproc_list)def forward(self, images: torch.Tensor) -> torch.Tensor:+ """Prepare images for SigLIP2 vision encoding.++ Args:+ images: Image tensor with shape :math:`(C, H, W)` or+ :math:`(B, C, H, W)`. Values are expected in the range used by+ the configured rescale factor.++ Returns:+ Batched tensor resized to the configured image size and normalized+ with the stored mean and standard deviation.+ """# ensure batch dimensionif images.dim() == 3:images = images.unsqueeze(0)diff --git a/kornia/models/siglip2/vision_encoder.py b/kornia/models/siglip2/vision_encoder.pyindex 305ab9c3d..44d414008 100644--- a/kornia/models/siglip2/vision_encoder.py+++ b/kornia/models/siglip2/vision_encoder.py@@ -182,6 +182,18 @@ class SigLip2MultiheadAttentionPoolingHead(nn.Module):self.mlp = SigLip2VisionMLP(config)def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:+ """Pool vision tokens with a learned probe query.++ Args:+ hidden_state: Vision token tensor with shape :math:`(B, N, D)`,+ where :math:`B` is batch size, :math:`N` is token count, and+ :math:`D` is hidden size.++ Returns:+ Tensor with shape :math:`(B, 1, D)` containing the pooled visual+ representation after attention, layer normalization, and MLP+ refinement.+ """# repeat the probe token for the batch sizebatch_size = hidden_state.shape[0]probe = self.probe.repeat(batch_size, 1, 1) # (batch_size, 1, hidden_size)diff --git a/kornia/models/small_sr.py b/kornia/models/small_sr.pyindex a192c2cc7..ed2211e0d 100644--- a/kornia/models/small_sr.py+++ b/kornia/models/small_sr.py@@ -51,6 +51,13 @@ class SmallSRNet(nn.Module):weight_init(self)def load_from_file(self, path_file: str) -> None:+ """Load pretrained super-resolution weights from the model cache.++ Args:+ path_file: Checkpoint URL or path passed to the cached downloader.+ The downloaded state dictionary is loaded strictly and the+ module is switched to evaluation mode.+ """# use torch.hub to load pretrained modelmodel_path = CachedDownloader.download_to_cache(path_file, "small_sr.pth", download=True, suffix=".pth", cache_dir=kornia_config.hub_onnx_dir@@ -60,6 +67,18 @@ class SmallSRNet(nn.Module):self.eval()def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Super-resolve a single-channel image tensor.++ Args:+ x: Luminance image tensor with shape :math:`(B, 1, H, W)`, where+ :math:`B` is batch size, :math:`H` is height, and :math:`W` is+ width.++ Returns:+ Upscaled luminance tensor with shape+ :math:`(B, 1, H * r, W * r)`, where ``r`` is the configured+ upscale factor.+ """x = self.relu(self.conv1(x))x = self.relu(self.conv2(x))x = self.relu(self.conv3(x))@@ -94,6 +113,17 @@ class SmallSRNetWrapper(nn.Module):self.upscale_factor = upscale_factordef forward(self, input: torch.Tensor) -> torch.Tensor:+ """Apply RGB super-resolution through a luminance-only SR model.++ Args:+ input: RGB image tensor with shape :math:`(B, 3, H, W)`.++ Returns:+ RGB tensor upscaled by ``self.upscale_factor``. The Y channel is+ predicted by the super-resolution model, while Cb and Cr channels+ are resized with bicubic interpolation before conversion back to+ RGB.+ """ycbcr = self.rgb_to_ycbcr(input)y, cb, cr = ycbcr.split(1, dim=1)out_y = self.model(y)diff --git a/kornia/models/smolvlm2/smolvlm2.py b/kornia/models/smolvlm2/smolvlm2.pyindex e8661faa3..2b19c11c8 100644--- a/kornia/models/smolvlm2/smolvlm2.py+++ b/kornia/models/smolvlm2/smolvlm2.py@@ -28,6 +28,18 @@ class SmolVLM2(nn.Module):self.text_proj = nn.Linear(text_dim, text_dim)def forward(self, image_features: torch.Tensor, text_features: torch.Tensor) -> torch.Tensor:+ """Combine projected image and text feature tensors.++ Args:+ image_features: Visual feature tensor with last dimension matching+ the configured vision dimension.+ text_features: Text feature tensor with the same broadcastable+ leading shape and last dimension matching the configured text+ dimension.++ Returns:+ Tensor containing the sum of projected image and text features.+ """v = self.vision_proj(image_features)t = self.text_proj(text_features)return v + tdiff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.pyindex 862cd6edd..aa12ba3ca 100644--- a/kornia/models/tiny_vit.py+++ b/kornia/models/tiny_vit.py@@ -112,6 +112,18 @@ class MBConv(nn.Module):self.act = activation()def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the MBConv residual block to a feature map.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`, where+ :math:`B` is batch size, :math:`C` is channels, :math:`H` is+ height, and :math:`W` is width.++ Returns:+ Tensor with the same shape as ``x`` after pointwise expansion,+ depthwise convolution, projection, stochastic depth, and residual+ activation.+ """return self.act(x + self.drop_path(self.conv3(self.conv2(self.conv1(x)))))@@ -141,6 +153,17 @@ class PatchMerging(nn.Module):self.conv3 = ConvBN(out_dim, out_dim, 1)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Merge or project patch tokens for TinyViT downsampling.++ Args:+ x: Either token tensor with shape :math:`(B, H * W, C)` or feature+ map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Token tensor with shape :math:`(B, H_{out} * W_{out}, C_{out})`.+ The spatial size is reduced when this layer was configured with+ stride ``2``.+ """if x.ndim == 3:x = x.transpose(1, 2).unflatten(2, self.input_resolution) # (B, H * W, C) -> (B, C, H, W)x = self.conv3(self.conv2(self.conv1(x)))@@ -185,6 +208,15 @@ class ConvLayer(nn.Module):self.downsample = downsampledef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply a sequence of convolutional TinyViT blocks.++ Args:+ x: Feature tensor passed through the layer blocks.++ Returns:+ Tensor after all MBConv blocks and the optional downsample module.+ The output may be a token tensor when downsampling is configured.+ """for blk in self.blocks:x = checkpoint.checkpoint(blk, x) if self.use_checkpoint else blk(x)if self.downsample is not None:@@ -264,6 +296,17 @@ class Attention(nn.Module):@staticmethoddef build_attention_bias(resolution: tuple[int, int]) -> tuple[torch.Tensor, int]:+ """Build lookup indices for relative attention bias.++ Args:+ resolution: Window resolution ``(H, W)`` used by the attention+ block.++ Returns:+ Tuple ``(indices, size)``. ``indices`` maps each token pair in the+ window to a relative-position bias entry, and ``size`` is the+ number of unique bias entries.+ """H, W = resolutionrows = torch.arange(H)cols = torch.arange(W)@@ -280,11 +323,30 @@ class Attention(nn.Module):# is this really necessary?@torch.no_grad()def train(self, mode: bool = True) -> Attention:+ """Switch training/evaluation mode and refresh cached attention bias.++ Args:+ mode: ``True`` for training mode, ``False`` for evaluation mode.++ Returns:+ ``self`` after updating the module mode. In evaluation mode the+ relative attention bias lookup is cached for reuse.+ """super().train(mode)self.ab = None if (mode and self.ab is not None) else self.attention_biases[:, self.attention_bias_idxs]return selfdef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply relative-position self-attention to token features.++ Args:+ x: Token tensor with shape :math:`(B, N, C)`, where :math:`B` is+ batch size, :math:`N` is number of tokens, and :math:`C` is+ embedding dimension.++ Returns:+ Tensor with shape :math:`(B, N, C)` after attention and projection.+ """B, N, _ = x.shapex = self.norm(x)qkv = self.qkv(x)@@ -342,6 +404,16 @@ class TinyViTBlock(nn.Module):self.drop_path2 = DropPath(drop_path)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply one TinyViT window-attention block.++ Args:+ x: Token tensor with shape :math:`(B, H * W, C)`, where+ :math:`H` and :math:`W` match ``self.input_resolution``.++ Returns:+ Tensor with the same shape as ``x`` after window attention, local+ convolution, MLP, and residual connections.+ """H, W = self.input_resolutionB, L, C = x.shaperes_x = x@@ -422,6 +494,16 @@ class BasicLayer(nn.Module):self.downsample = downsampledef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Run a TinyViT stage made of several blocks.++ Args:+ x: Token tensor with shape :math:`(B, H * W, C)`.++ Returns:+ Tensor after all TinyViT blocks and optional patch merging. The+ channel count or token resolution may change if ``downsample`` is+ configured.+ """for blk in self.blocks:x = checkpoint.checkpoint(blk, x) if self.use_checkpoint else blk(x)if self.downsample is not None:diff --git a/kornia/models/vit.py b/kornia/models/vit.pyindex 952fee13b..f0b7cf14c 100644--- a/kornia/models/vit.py+++ b/kornia/models/vit.py@@ -242,9 +242,30 @@ class VisionTransformer(nn.Module):@propertydef encoder_results(self) -> list[torch.Tensor]:+ """Return intermediate outputs captured by the transformer encoder.++ Returns:+ List of tensors produced by the encoder blocks. Each tensor stores+ token embeddings for a layer, typically shaped :math:`(B, N, D)`,+ where :math:`B` is batch size, :math:`N` is token count, and+ :math:`D` is embedding dimension.+ """return self.encoder.resultsdef forward(self, x: torch.Tensor) -> torch.Tensor:+ """Encode an image batch into Vision Transformer token embeddings.++ Args:+ x: Image tensor with shape :math:`(B, C, H, W)`, where+ :math:`B` is batch size, :math:`C` must match+ ``self.in_channels``, and :math:`H` and :math:`W` are expected+ to match ``self.image_size``.++ Returns:+ Normalized token embedding tensor produced by patch embedding and+ the transformer encoder. The output shape follows the encoder+ layout, usually :math:`(B, N, D)`.+ """if not isinstance(x, torch.Tensor):raise TypeError(f"Input x type is not a torch.Tensor. Got: {type(x)}")diff --git a/kornia/models/vit_mobile.py b/kornia/models/vit_mobile.pyindex 3f3795fea..fc7408c30 100644--- a/kornia/models/vit_mobile.py+++ b/kornia/models/vit_mobile.py@@ -45,6 +45,15 @@ class PreNorm(nn.Module):self.fn = fndef forward(self, x: torch.Tensor, **kwargs: Dict[str, Any]) -> torch.Tensor:+ """Normalize token features before applying the wrapped block.++ Args:+ x: Token tensor whose last dimension is ``dim``.+ **kwargs: Extra keyword arguments forwarded to the wrapped module.++ Returns:+ Output tensor returned by ``self.fn`` after layer normalization.+ """return self.fn(self.norm(x), **kwargs)@@ -64,6 +73,15 @@ class FeedForward(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply the feed-forward projection to token features.++ Args:+ x: Token tensor with last dimension equal to ``dim``.++ Returns:+ Tensor with the same shape as ``x`` after two linear projections,+ activation, and dropout.+ """return self.net(x)@@ -91,6 +109,18 @@ class Attention(nn.Module):self.to_out = nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout)) if project_out else nn.Identity()def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply multi-head self-attention to MobileViT tokens.++ Args:+ x: Token tensor with shape :math:`(B, P, N, D)`, where+ :math:`B` is batch size, :math:`P` is patch area,+ :math:`N` is number of patches, and :math:`D` is embedding+ dimension.++ Returns:+ Tensor with the same shape as ``x`` after attention and output+ projection.+ """qkv = self.to_qkv(x).chunk(3, dim=-1)b, p, n, hd = qkv[0].shape@@ -133,6 +163,14 @@ class Transformer(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Run stacked attention and feed-forward residual layers.++ Args:+ x: Token tensor with shape :math:`(B, P, N, D)`.++ Returns:+ Tensor with the same shape as ``x`` after all transformer layers.+ """for attn, ff in self.layers:x = attn(x) + xx = ff(x) + x@@ -186,6 +224,15 @@ class MV2Block(nn.Module):)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Apply an inverted residual MobileNetV2 block.++ Args:+ x: Feature map tensor with shape :math:`(B, C_{in}, H, W)`.++ Returns:+ Feature map tensor with output channels ``oup``. When stride is one+ and input/output channels match, the block adds the residual input.+ """if self.use_res_connect:return x + self.conv(x)else:@@ -228,6 +275,16 @@ class MobileViTBlock(nn.Module):self.conv4 = conv_nxn_bn(2 * channel, channel, kernel_size)def forward(self, x: torch.Tensor) -> torch.Tensor:+ """Fuse local convolutions with global transformer context.++ Args:+ x: Feature map tensor with shape :math:`(B, C, H, W)`.++ Returns:+ Feature map tensor with the same spatial size as ``x``. Local+ convolutional features are unfolded into patches, processed by a+ transformer, folded back, and fused with the residual feature map.+ """y = x.clone()# Local representations@@ -322,6 +379,17 @@ class MobileViT(nn.Module):self.conv2 = conv_1x1_bn(channels[-2], channels[-1])def forward(self, x: torch.Tensor) -> torch.Tensor:+ r"""Run the MobileViT backbone and return final feature maps.++ Args:+ x: Image tensor with shape :math:`(B, C, H, W)`, where :math:`C`+ matches the configured input channel count.++ Returns:+ Feature tensor from the final MobileViT stage. For the default+ configuration, a :math:`256 \times 256` input produces+ :math:`(B, 320, 8, 8)`.+ """x = self.conv1(x)x = self.mv2[0](x)diff --git a/kornia/models/yunet/model.py b/kornia/models/yunet/model.pyindex a05935668..cd4f1b519 100644--- a/kornia/models/yunet/model.py+++ b/kornia/models/yunet/model.py@@ -109,6 +109,17 @@ class YuNet(nn.Module):self.eval()def forward(self, x: torch.Tensor) -> Dict[str, torch.Tensor]:+ """Run YuNet face detection heads over an input image batch.++ Args:+ x: Image tensor with shape :math:`(B, C, H, W)`, where :math:`B` is+ batch size, :math:`C` is channel count, :math:`H` is height,+ and :math:`W` is width.++ Returns:+ Dictionary containing head outputs for locations, confidences, and+ landmarks at the configured detection scales.+ """detection_sources, head_list = [], []x = self.model0(x)diff --git a/kornia/models/yunet/processors.py b/kornia/models/yunet/processors.pyindex f5ad1157f..58e99a519 100644--- a/kornia/models/yunet/processors.py+++ b/kornia/models/yunet/processors.py@@ -78,11 +78,27 @@ class PriorBox:self.feature_maps = [self.feature_map_3th, self.feature_map_4th, self.feature_map_5th, self.feature_map_6th]def to(self, device: torch.device, dtype: torch.dtype) -> "PriorBox":+ """Set the device and dtype used when creating prior boxes.++ Args:+ device: Target device for the generated prior-box tensor.+ dtype: Target dtype for the generated prior-box tensor.++ Returns:+ ``self`` with updated tensor creation settings.+ """self.device = deviceself.dtype = dtypereturn selfdef __call__(self) -> torch.Tensor:+ """Generate YuNet prior boxes for all configured feature maps.++ Returns:+ Tensor with shape :math:`(N, 4)`, where :math:`N` is the total+ number of anchors and the four values are normalized center-x,+ center-y, width, and height.+ """anchors: List[float] = []for k, f in enumerate(self.feature_maps):min_sizes: List[int] = self.min_sizes[k]