Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat: Add KimiVL Vision-Language Model implementation (#3448)

Meggison Oritsemisanee23688c2f02
diff --git a/kornia/models/kimi_vl/__init__.py b/kornia/models/kimi_vl/__init__.py
new file mode 100644
index 000000000..bdff9e6df
--- /dev/null
+++ b/kornia/models/kimi_vl/__init__.py
@@ -0,0 +1,29 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from .config import KimiVLConfig, KimiVLProjectorConfig, MoonViTConfig
+from .model import KimiVLModel, KimiVLProjector
+from .moonvit import MoonViT
+
+__all__ = [
+ "KimiVLConfig",
+ "KimiVLModel",
+ "KimiVLProjector",
+ "KimiVLProjectorConfig",
+ "MoonViT",
+ "MoonViTConfig",
+]
diff --git a/kornia/models/kimi_vl/config.py b/kornia/models/kimi_vl/config.py
new file mode 100644
index 000000000..ca5884207
--- /dev/null
+++ b/kornia/models/kimi_vl/config.py
@@ -0,0 +1,91 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+class MoonViTConfig:
+ """Configuration for MoonViT vision encoder.
+
+ Args:
+ image_size: Default input image size used for positional embedding initialization.
+ The model supports variable resolution inputs through interpolation.
+ patch_size: Size of image patches.
+ num_channels: Number of input channels.
+ hidden_size: Hidden dimension size.
+ num_hidden_layers: Number of transformer layers.
+ num_attention_heads: Number of attention heads.
+ intermediate_size: Intermediate size in feed-forward network.
+ hidden_act: Activation function.
+ layer_norm_eps: Epsilon for layer normalization.
+ dropout_p: Dropout probability.
+ attention_dropout_p: Attention dropout probability.
+ rope_theta: Theta value for Rotary Positional Embeddings.
+ """
+
+ image_size: int = 384
+ patch_size: int = 14
+ num_channels: int = 3
+ hidden_size: int = 1152
+ num_hidden_layers: int = 27
+ num_attention_heads: int = 16
+ intermediate_size: int = 4304
+ hidden_act: str = "gelu"
+ layer_norm_eps: float = 1e-6
+ dropout_p: float = 0.0
+ attention_dropout_p: float = 0.0
+ rope_theta: float = 800000.0
+
+
+@dataclass
+class KimiVLProjectorConfig:
+ """Configuration for KimiVL projector.
+
+ Args:
+ input_dim: Input dimension (should match vision encoder's hidden_size).
+ hidden_dim: Hidden dimension of the MLP.
+ output_dim: Output dimension (embedding dim of the LLM).
+ dropout_p: Dropout probability.
+ """
+
+ input_dim: int = 1152 # Vision encoder output dimension
+ hidden_dim: int = 4608 # Hidden dim from official KimiVL weights
+ output_dim: int = 2048 # Output dim from official KimiVL weights
+ dropout_p: float = 0.0
+
+
+@dataclass
+class KimiVLConfig:
+ """Configuration for KimiVL model.
+
+ Args:
+ vision_config: Vision encoder configuration.
+ projector_config: Projector configuration.
+ """
+
+ vision_config: Optional[MoonViTConfig] = None
+ projector_config: Optional[KimiVLProjectorConfig] = None
+
+ def __post_init__(self) -> None:
+ if self.vision_config is None:
+ self.vision_config = MoonViTConfig()
+ if self.projector_config is None:
+ self.projector_config = KimiVLProjectorConfig()
diff --git a/kornia/models/kimi_vl/model.py b/kornia/models/kimi_vl/model.py
new file mode 100644
index 000000000..fee3be11d
--- /dev/null
+++ b/kornia/models/kimi_vl/model.py
@@ -0,0 +1,123 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+from typing import Optional
+
+import torch
+from torch import nn
+
+from .config import KimiVLConfig, KimiVLProjectorConfig
+from .moonvit import MoonViT
+
+__all__ = ["KimiVLModel", "KimiVLProjector"]
+
+
+class KimiVLProjector(nn.Module):
+ """KimiVL Projector with Pixel Unshuffle and MLP."""
+
+ def __init__(self, config: KimiVLProjectorConfig) -> None:
+ super().__init__()
+ self.downsample_ratio = 2
+
+ # Pre-norm (applied before pixel unshuffle, on the vision encoder output dimension)
+ self.pre_norm = nn.LayerNorm(config.input_dim)
+
+ # After pixel unshuffle, the dimension becomes input_dim * (downsample_ratio ** 2)
+ mlp_input_dim = config.input_dim * (self.downsample_ratio**2)
+
+ # MLP
+ self.mlp = nn.Sequential(
+ nn.Linear(mlp_input_dim, config.hidden_dim),
+ nn.GELU(),
+ nn.Linear(config.hidden_dim, config.output_dim),
+ nn.Dropout(config.dropout_p),
+ )
+
+ def forward(self, x: torch.Tensor, h: int, w: int) -> torch.Tensor:
+ """Forward pass.
+
+ Args:
+ x: Input features (B, N, D)
+ h: Height in patches
+ w: Width in patches
+
+ Returns:
+ Projected features (B, N/4, output_dim)
+ """
+ B, _N, D = x.shape
+
+ # Apply pre-norm
+ x = self.pre_norm(x)
+
+ # Reshape to spatial (B, H, W, D) -> (B, D, H, W)
+ x = x.view(B, h, w, D).permute(0, 3, 1, 2)
+
+ # Pixel unshuffle for spatial downsampling -> (B, D*4, H/2, W/2)
+ x = torch.nn.functional.pixel_unshuffle(x, self.downsample_ratio)
+
+ # Flatten back -> (B, D*4, N/4) -> (B, N/4, D*4)
+ x = x.flatten(2).transpose(1, 2)
+
+ # MLP
+ x = self.mlp(x)
+
+ return x
+
+
+class KimiVLModel(nn.Module):
+ """KimiVL Vision-Language Model (Vision Part).
+
+ This model includes the Vision Encoder (MoonViT) and the Projector.
+ It does not include the LLM decoder, as Kornia focuses on the vision components.
+
+ Args:
+ config: KimiVL configuration.
+ """
+
+ def __init__(self, config: KimiVLConfig) -> None:
+ super().__init__()
+ self.config = config
+ self.patch_size = config.vision_config.patch_size
+
+ # Vision Encoder (MoonViT)
+ self.vision_encoder = MoonViT(config.vision_config)
+
+ # Projector
+ self.projector = KimiVLProjector(config.projector_config)
+
+ def forward(self, images: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Forward pass.
+
+ Args:
+ images: (B, C, H, W)
+ attention_mask: (B, 1, N, N) or (B, N, N) optional mask for vision encoder.
+
+ Returns:
+ Projected visual features (B, seq_len, output_dim)
+ """
+ vision_features = self.vision_encoder(images, attention_mask=attention_mask) # (B, N, D)
+
+ # Calculate patch grid size
+ H, W = images.shape[2], images.shape[3]
+ patch_size = self.patch_size
+ h_patches = H // patch_size
+ w_patches = W // patch_size
+ projected_features = self.projector(vision_features, h_patches, w_patches)
+
+ return projected_features
diff --git a/kornia/models/kimi_vl/moonvit.py b/kornia/models/kimi_vl/moonvit.py
new file mode 100644
index 000000000..84b9b033c
--- /dev/null
+++ b/kornia/models/kimi_vl/moonvit.py
@@ -0,0 +1,273 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from __future__ import annotations
+
+from typing import Optional, Tuple
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from .config import MoonViTConfig
+
+
+def apply_rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor) -> torch.Tensor:
+ """Apply rotary positional embeddings.
+
+ Args:
+ x: Input tensor of shape (batch, seq_len, head_dim).
+ cos: Cosine component of shape (seq_len, head_dim).
+ sin: Sine component of shape (seq_len, head_dim).
+
+ Returns:
+ Tensor with rotary embeddings applied.
+ """
+ # x: (batch, seq_len, head_dim)
+ # cos, sin: (seq_len, head_dim) or (1, seq_len, head_dim)
+
+ # rotate_half
+ x1, x2 = x.chunk(2, dim=-1)
+ x_rotated = torch.cat((-x2, x1), dim=-1)
+
+ return (x * cos) + (x_rotated * sin)
+
+
+class MoonViTRotaryEmbedding(nn.Module):
+ """2D Rotary Positional Embedding."""
+
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
+ super().__init__()
+ self.dim = dim
+ self.theta = theta
+
+ def forward(self, h: int, w: int, device: torch.device) -> Tuple[torch.Tensor, torch.Tensor]:
+ # 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 rotation
+ dim_h = self.dim // 2
+ dim_w = self.dim // 2
+
+ # Generate frequencies
+ inv_freq_h = 1.0 / (self.theta ** (torch.arange(0, dim_h, 2, device=device).float() / dim_h))
+ inv_freq_w = 1.0 / (self.theta ** (torch.arange(0, dim_w, 2, device=device).float() / dim_w))
+
+ # Generate positions
+ seq_h = torch.arange(h, device=device, dtype=inv_freq_h.dtype)
+ seq_w = torch.arange(w, device=device, dtype=inv_freq_w.dtype)
+
+ # Outer product to get (h, dim_h/2) and (w, dim_w/2)
+ freqs_h = torch.outer(seq_h, inv_freq_h) # (h, dim_h/2)
+ freqs_w = torch.outer(seq_w, inv_freq_w) # (w, dim_w/2)
+
+ # Repeat h frequencies for each w
+ freqs_h = freqs_h.repeat_interleave(w, dim=0) # (h*w, dim_h/2)
+
+ # Repeat w frequencies for each h
+ freqs_w = freqs_w.repeat(h, 1) # (h*w, dim_w/2)
+
+ # Concatenate to get full embeddings
+ emb_h = torch.cat((freqs_h, freqs_h), dim=-1) # (seq_len, dim_h)
+ emb_w = torch.cat((freqs_w, freqs_w), dim=-1) # (seq_len, dim_w)
+
+ emb = torch.cat((emb_h, emb_w), dim=-1) # (seq_len, dim)
+
+ return emb.cos(), emb.sin()
+
+
+class MoonViTAttention(nn.Module):
+ def __init__(self, config: MoonViTConfig) -> None:
+ super().__init__()
+ self.num_heads = config.num_attention_heads
+ self.hidden_size = config.hidden_size
+ self.head_dim = config.hidden_size // config.num_attention_heads
+
+ self.q_proj = nn.Linear(config.hidden_size, config.hidden_size)
+ self.k_proj = nn.Linear(config.hidden_size, config.hidden_size)
+ self.v_proj = nn.Linear(config.hidden_size, config.hidden_size)
+ self.out_proj = nn.Linear(config.hidden_size, config.hidden_size)
+
+ self.dropout = nn.Dropout(config.attention_dropout_p)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ cos: torch.Tensor,
+ sin: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ batch_size, seq_len, _ = hidden_states.shape
+
+ query = self.q_proj(hidden_states)
+ key = self.k_proj(hidden_states)
+ value = self.v_proj(hidden_states)
+
+ # Reshape query, key, and value for multi-head attention
+ query = query.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
+ key = key.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
+ value = value.view(batch_size, seq_len, self.num_heads, self.head_dim).transpose(1, 2)
+
+ # Apply RoPE
+ # cos, sin are (seq_len, head_dim) -> reshape to (1, 1, seq_len, head_dim)
+ cos = cos.view(1, 1, seq_len, self.head_dim)
+ sin = sin.view(1, 1, seq_len, self.head_dim)
+
+ query = apply_rotary_pos_emb(query, cos, sin)
+ key = apply_rotary_pos_emb(key, cos, sin)
+ attn_output = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=self.dropout.p if self.training else 0.0
+ )
+
+ attn_output = attn_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.hidden_size)
+ return self.out_proj(attn_output)
+
+
+class MoonViTMLP(nn.Module):
+ """Feed-forward MLP block used in MoonViT transformer layers.
+
+ This module implements a two-layer projection with GELU activation and dropout,
+ following the standard transformer feed-forward network pattern.
+
+ Args:
+ config: Model configuration containing ``hidden_size``, ``intermediate_size``,
+ and ``dropout_p`` used to construct the MLP.
+ """
+
+ def __init__(self, config: MoonViTConfig) -> None:
+ super().__init__()
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
+ self.act = nn.GELU()
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
+ self.dropout = nn.Dropout(config.dropout_p)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.fc2(x)
+ x = self.dropout(x)
+ return x
+
+
+class MoonViTLayer(nn.Module):
+ """Single MoonViT transformer layer with pre-normalization, RoPE attention, and an MLP block.
+
+ This layer applies layer normalization before both the self-attention and MLP submodules
+ (pre-norm transformer). The self-attention block uses rotary positional embeddings (RoPE)
+ via the provided cosine and sine tensors, and the output of each sub-block is added back
+ to the input (residual connections).
+
+ Args:
+ config: Model configuration specifying hidden sizes, number of heads, dropout, and
+ normalization parameters.
+ """
+
+ def __init__(self, config: MoonViTConfig) -> None:
+ super().__init__()
+ self.norm1 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.attn = MoonViTAttention(config)
+ self.norm2 = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+ self.mlp = MoonViTMLP(config)
+
+ def forward(
+ self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ x = x + self.attn(self.norm1(x), cos, sin, attention_mask)
+ x = x + self.mlp(self.norm2(x))
+ return x
+
+
+class MoonViTEncoder(nn.Module):
+ """Stack of MoonViT transformer layers.
+
+ This encoder sequentially applies multiple :class:`MoonViTLayer` blocks to a
+ sequence of hidden states. Each layer consists of self-attention with rotary
+ positional embeddings followed by an MLP block, with residual connections and
+ layer normalization, producing an encoded representation of the input sequence.
+ """
+
+ def __init__(self, config: MoonViTConfig) -> None:
+ super().__init__()
+ self.layers = nn.ModuleList([MoonViTLayer(config) for _ in range(config.num_hidden_layers)])
+
+ def forward(
+ self, x: torch.Tensor, cos: torch.Tensor, sin: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ for layer in self.layers:
+ x = layer(x, cos, sin, attention_mask)
+ return x
+
+
+class MoonViT(nn.Module):
+ """MoonViT Vision Encoder."""
+
+ def __init__(self, config: MoonViTConfig) -> None:
+ super().__init__()
+ self.config = config
+
+ self.patch_embed = nn.Conv2d(
+ config.num_channels, config.hidden_size, kernel_size=config.patch_size, stride=config.patch_size
+ )
+
+ # Initialized for the default image size
+ num_patches = (config.image_size // config.patch_size) ** 2
+ self.pos_embed = nn.Parameter(torch.randn(1, num_patches, config.hidden_size))
+
+ self.rope = MoonViTRotaryEmbedding(config.hidden_size // config.num_attention_heads, theta=config.rope_theta)
+
+ self.encoder = MoonViTEncoder(config)
+ self.norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
+
+ def forward(self, pixel_values: torch.Tensor, attention_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
+ """Forward pass.
+
+ Args:
+ pixel_values: (B, C, H, W)
+ attention_mask: (B, 1, N, N) or (B, N, N) optional mask.
+
+ Returns:
+ (B, seq_len, hidden_size)
+ """
+ # Patch Embedding
+ x = self.patch_embed(pixel_values) # (B, D, H', W')
+ h_patches = x.shape[2]
+ w_patches = x.shape[3]
+
+ x = x.flatten(2).transpose(1, 2) # (B, N, D)
+
+ # Add Absolute Positional Embedding (with interpolation)
+ pos_embed = self.pos_embed
+ if x.shape[1] != pos_embed.shape[1]:
+ # Interpolate pos_embed to match current resolution
+ # pos_embed is (1, N_ref, D) -> (1, D, H_ref, W_ref)
+ h_ref = int(pos_embed.shape[1] ** 0.5)
+ if h_ref * h_ref != pos_embed.shape[1]:
+ raise ValueError("pos_embed shape is not a perfect square, cannot reshape to 2D grid.")
+ w_ref = h_ref
+ pos_embed = pos_embed.permute(0, 2, 1).view(1, -1, h_ref, w_ref)
+
+ pos_embed = F.interpolate(pos_embed, size=(h_patches, w_patches), mode="bicubic", align_corners=False)
+
+ # (1, D, H', W') -> (1, N, D)
+ pos_embed = pos_embed.flatten(2).transpose(1, 2)
+
+ x = x + pos_embed
+
+ # Generate RoPE
+ cos, sin = self.rope(h_patches, w_patches, x.device) # (N, head_dim)
+ x = self.encoder(x, cos, sin, attention_mask=attention_mask)
+ x = self.norm(x)
+
+ return x
diff --git a/tests/integration/models/__init__.py b/tests/integration/models/__init__.py
new file mode 100644
index 000000000..4d273d5cb
--- /dev/null
+++ b/tests/integration/models/__init__.py
@@ -0,0 +1,16 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
diff --git a/tests/integration/models/test_kimi_vl.py b/tests/integration/models/test_kimi_vl.py
new file mode 100644
index 000000000..f78f2c076
--- /dev/null
+++ b/tests/integration/models/test_kimi_vl.py
@@ -0,0 +1,148 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Integration tests for KimiVL model.
+
+These tests verify compatibility with official model weights and require
+external resources. They are separate from unit tests to keep the main
+test suite fast and focused.
+"""
+
+import json
+import os
+
+import pytest
+import torch
+import torch.nn.functional as F
+from safetensors.torch import load_file
+
+from kornia.models.kimi_vl import KimiVLConfig, KimiVLModel
+from kornia.models.kimi_vl.config import KimiVLProjectorConfig, MoonViTConfig
+
+
+def test_kimi_vl_official_weights():
+ """Integration test for loading official KimiVL vision weights.
+
+ To run this test, set the environment variable ``KIMI_VL_WEIGHTS_DIR`` to a directory
+ containing the file ``model.safetensors.index.json`` and the referenced shard files.
+ If this variable is not set or the files are missing, the test is skipped.
+ """
+
+ weights_dir = os.environ.get("KIMI_VL_WEIGHTS_DIR")
+ if not weights_dir:
+ pytest.skip("KIMI_VL_WEIGHTS_DIR is not set; skipping test_kimi_vl_official_weights")
+
+ index_path = os.path.join(weights_dir, "model.safetensors.index.json")
+
+ if not os.path.exists(index_path):
+ pytest.skip(f"Weights index not found at {index_path}; skipping test_kimi_vl_official_weights")
+
+ with open(index_path) as f:
+ index = json.load(f)
+
+ vision_keys = [k for k in index["weight_map"].keys() if "vision_tower" in k or "multi_modal_projector" in k]
+ shards = {index["weight_map"][k] for k in vision_keys}
+
+ state_dict = {}
+ for shard in shards:
+ shard_path = os.path.join(weights_dir, shard)
+ shard_weights = load_file(shard_path)
+ for k in vision_keys:
+ if k in shard_weights:
+ state_dict[k] = shard_weights[k]
+
+ vision_config = MoonViTConfig(
+ image_size=336,
+ patch_size=14,
+ hidden_size=1152,
+ num_hidden_layers=27,
+ num_attention_heads=16,
+ intermediate_size=4304,
+ )
+
+ projector_config = KimiVLProjectorConfig(input_dim=1152, hidden_dim=4608, output_dim=2048)
+
+ config = KimiVLConfig(vision_config=vision_config, projector_config=projector_config)
+
+ model = KimiVLModel(config)
+ model.eval()
+
+ new_state_dict = {}
+
+ def get_w(key):
+ return state_dict[f"vision_tower.{key}"]
+
+ new_state_dict["vision_encoder.patch_embed.weight"] = get_w("patch_embed.proj.weight")
+ new_state_dict["vision_encoder.patch_embed.bias"] = get_w("patch_embed.proj.bias")
+
+ pos_embed = get_w("patch_embed.pos_emb.weight")
+ pos_embed_reshaped = pos_embed.permute(2, 0, 1).unsqueeze(0)
+ pos_embed_interp = F.interpolate(pos_embed_reshaped, size=(24, 24), mode="bicubic", align_corners=False)
+ pos_embed_final = pos_embed_interp.flatten(2).transpose(1, 2)
+ new_state_dict["vision_encoder.pos_embed"] = pos_embed_final
+
+ for i in range(config.vision_config.num_hidden_layers):
+ prefix_official = f"encoder.blocks.{i}"
+ prefix_kornia = f"vision_encoder.encoder.layers.{i}"
+
+ new_state_dict[f"{prefix_kornia}.norm1.weight"] = get_w(f"{prefix_official}.norm0.weight")
+ new_state_dict[f"{prefix_kornia}.norm1.bias"] = get_w(f"{prefix_official}.norm0.bias")
+ new_state_dict[f"{prefix_kornia}.norm2.weight"] = get_w(f"{prefix_official}.norm1.weight")
+ new_state_dict[f"{prefix_kornia}.norm2.bias"] = get_w(f"{prefix_official}.norm1.bias")
+
+ wqkv = get_w(f"{prefix_official}.wqkv.weight")
+ bqkv = get_w(f"{prefix_official}.wqkv.bias")
+
+ hidden_size = config.vision_config.hidden_size
+ wq, wk, wv = wqkv.split(hidden_size, dim=0)
+ bq, bk, bv = bqkv.split(hidden_size, dim=0)
+
+ new_state_dict[f"{prefix_kornia}.attn.q_proj.weight"] = wq
+ new_state_dict[f"{prefix_kornia}.attn.q_proj.bias"] = bq
+ new_state_dict[f"{prefix_kornia}.attn.k_proj.weight"] = wk
+ new_state_dict[f"{prefix_kornia}.attn.k_proj.bias"] = bk
+ new_state_dict[f"{prefix_kornia}.attn.v_proj.weight"] = wv
+ new_state_dict[f"{prefix_kornia}.attn.v_proj.bias"] = bv
+
+ new_state_dict[f"{prefix_kornia}.attn.out_proj.weight"] = get_w(f"{prefix_official}.wo.weight")
+ new_state_dict[f"{prefix_kornia}.attn.out_proj.bias"] = get_w(f"{prefix_official}.wo.bias")
+
+ new_state_dict[f"{prefix_kornia}.mlp.fc1.weight"] = get_w(f"{prefix_official}.mlp.fc0.weight")
+ new_state_dict[f"{prefix_kornia}.mlp.fc1.bias"] = get_w(f"{prefix_official}.mlp.fc0.bias")
+ new_state_dict[f"{prefix_kornia}.mlp.fc2.weight"] = get_w(f"{prefix_official}.mlp.fc1.weight")
+ new_state_dict[f"{prefix_kornia}.mlp.fc2.bias"] = get_w(f"{prefix_official}.mlp.fc1.bias")
+
+ new_state_dict["vision_encoder.norm.weight"] = get_w("encoder.final_layernorm.weight")
+ new_state_dict["vision_encoder.norm.bias"] = get_w("encoder.final_layernorm.bias")
+
+ new_state_dict["projector.pre_norm.weight"] = state_dict["multi_modal_projector.pre_norm.weight"]
+ new_state_dict["projector.pre_norm.bias"] = state_dict["multi_modal_projector.pre_norm.bias"]
+
+ new_state_dict["projector.mlp.0.weight"] = state_dict["multi_modal_projector.linear_1.weight"]
+ new_state_dict["projector.mlp.0.bias"] = state_dict["multi_modal_projector.linear_1.bias"]
+ new_state_dict["projector.mlp.2.weight"] = state_dict["multi_modal_projector.linear_2.weight"]
+ new_state_dict["projector.mlp.2.bias"] = state_dict["multi_modal_projector.linear_2.bias"]
+
+ missing, unexpected = model.load_state_dict(new_state_dict, strict=True)
+ assert len(missing) == 0
+ assert len(unexpected) == 0
+
+ x = torch.randn(1, 3, 336, 336)
+ with torch.no_grad():
+ out = model(x)
+
+ assert out.shape == (1, 144, 2048)
diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.py
new file mode 100644
index 000000000..72ed8295a
--- /dev/null
+++ b/tests/models/test_kimi_vl.py
@@ -0,0 +1,181 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+from kornia.models.kimi_vl import KimiVLConfig, KimiVLModel
+from kornia.models.kimi_vl.config import KimiVLProjectorConfig, MoonViTConfig
+from kornia.models.kimi_vl.model import KimiVLProjector
+from kornia.models.kimi_vl.moonvit import MoonViT, MoonViTAttention, MoonViTEncoder, MoonViTRotaryEmbedding
+
+from testing.base import BaseTester
+
+
+def config():
+ vision_config = MoonViTConfig(
+ image_size=32,
+ patch_size=4,
+ hidden_size=32,
+ num_hidden_layers=2,
+ num_attention_heads=4,
+ intermediate_size=64,
+ )
+ projector_config = KimiVLProjectorConfig(
+ input_dim=32, # Matches vision_config.hidden_size
+ hidden_dim=64,
+ output_dim=64,
+ )
+ return KimiVLConfig(vision_config=vision_config, projector_config=projector_config)
+
+
+def model(device, dtype, config):
+ return KimiVLModel(config).to(device, dtype)
+
+
+class TestKimiVLModel(BaseTester):
+ def test_smoke(self, model):
+ assert model is not None
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 4])
+ def test_cardinality(self, device, dtype, model, config, batch_size):
+ images = torch.randn(batch_size, 3, 32, 32, device=device, dtype=dtype)
+
+ output = model(images)
+
+ # Expected output shape:
+ # H_patches = 32/4 = 8
+ # W_patches = 32/4 = 8
+ # After pixel shuffle (downsample 2): H_new = 4, W_new = 4 -> 16 patches
+ # Output dim = 64
+ expected_patches = 16
+ assert output.shape == (batch_size, expected_patches, config.projector_config.output_dim)
+
+ def test_variable_resolution(self, device, dtype, model, config):
+ batch_size = 1
+ # 48x48 image -> 12x12 patches -> 6x6 after shuffle -> 36 patches
+ images = torch.randn(batch_size, 3, 48, 48, device=device, dtype=dtype)
+
+ output = model(images)
+ assert output.shape == (batch_size, 36, config.projector_config.output_dim)
+
+ def test_attention_mask(self, device, dtype, model, config):
+ batch_size = 1
+ images = torch.randn(batch_size, 3, 32, 32, device=device, dtype=dtype)
+
+ # Create a mask (B, N, N) or (B, 1, N, N)
+ # N = 64 (8x8 patches)
+ N = 64
+ mask = torch.ones(batch_size, N, N, device=device, dtype=torch.bool)
+
+ # Mask out the last token
+ mask[:, :, -1] = 0
+
+ output = model(images, attention_mask=mask)
+ assert output.shape == (batch_size, 16, config.projector_config.output_dim)
+
+ def test_exception(self, device, dtype, model):
+ # Test invalid input shape (missing batch dim)
+ with pytest.raises((RuntimeError, ValueError, IndexError)):
+ images = torch.randn(3, 32, 32, device=device, dtype=dtype)
+ model(images)
+
+ def test_gradcheck(self, device, config):
+ # Convert model to float64 for gradcheck
+ model = KimiVLModel(config).to(device, torch.float64).train()
+ batch_size = 1
+ images = torch.randn(batch_size, 3, 32, 32, device=device, dtype=torch.float64, requires_grad=True)
+
+ self.gradcheck(model, images, raise_exception=True, fast_mode=True)
+
+ def test_dynamo(self, device, dtype, torch_optimizer, model):
+ model = model.eval()
+ batch_size = 1
+ images = torch.randn(batch_size, 3, 32, 32, device=device, dtype=dtype)
+
+ model_optimized = torch_optimizer(model)
+
+ with torch.no_grad():
+ expected = model(images)
+ actual = model_optimized(images)
+
+ self.assert_close(actual, expected)
+
+
+class TestKimiVLComponents(BaseTester):
+ def test_moonvit(self, device, dtype, config):
+ model = MoonViT(config.vision_config).to(device, dtype)
+ batch_size = 2
+ images = torch.randn(batch_size, 3, 32, 32, device=device, dtype=dtype)
+
+ output = model(images)
+ # MoonViT output is (B, N, D)
+ # N = (32/4)^2 = 64
+ assert output.shape == (batch_size, 64, config.vision_config.hidden_size)
+
+ def test_moonvit_encoder(self, device, dtype, config):
+ encoder = MoonViTEncoder(config.vision_config).to(device, dtype)
+ batch_size = 2
+ seq_len = 64
+ hidden_size = config.vision_config.hidden_size
+
+ x = torch.randn(batch_size, seq_len, hidden_size, device=device, dtype=dtype)
+
+ # Create dummy cos/sin for RoPE
+ head_dim = hidden_size // config.vision_config.num_attention_heads
+ cos = torch.randn(seq_len, head_dim, device=device, dtype=dtype)
+ sin = torch.randn(seq_len, head_dim, device=device, dtype=dtype)
+
+ output = encoder(x, cos, sin)
+ assert output.shape == (batch_size, seq_len, hidden_size)
+
+ def test_moonvit_attention(self, device, dtype, config):
+ attention = MoonViTAttention(config.vision_config).to(device, dtype)
+ batch_size = 2
+ seq_len = 64
+ hidden_size = config.vision_config.hidden_size
+
+ x = torch.randn(batch_size, seq_len, hidden_size, device=device, dtype=dtype)
+
+ # Create dummy cos/sin for RoPE
+ head_dim = hidden_size // config.vision_config.num_attention_heads
+ cos = torch.randn(seq_len, head_dim, device=device, dtype=dtype)
+ sin = torch.randn(seq_len, head_dim, device=device, dtype=dtype)
+
+ output = attention(x, cos, sin)
+ assert output.shape == (batch_size, seq_len, hidden_size)
+
+ def test_moonvit_rotary_embedding(self, device, dtype, config):
+ dim = config.vision_config.hidden_size // config.vision_config.num_attention_heads
+ rope = MoonViTRotaryEmbedding(dim).to(device, dtype)
+
+ h, w = 8, 8
+ cos, sin = rope(h, w, device)
+
+ seq_len = h * w
+ assert cos.shape == (seq_len, dim)
+ assert sin.shape == (seq_len, dim)
+
+ def test_projector(self, device, dtype, config):
+ model = KimiVLProjector(config.projector_config).to(device, dtype)
+ batch_size = 2
+ input_features = torch.randn(batch_size, 64, 32, device=device, dtype=dtype)
+
+ output = model(input_features, h=8, w=8)
+ assert output.shape == (batch_size, 16, config.projector_config.output_dim)