Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix: align Kimi-VL with Moonshot implementation (#3968)

Tomás Guija Valiente2215bb31a915
diff --git a/README.md b/README.md
index 3f13f3715..5511fe1c5 100644
--- a/README.md
+++ b/README.md
@@ -112,7 +112,7 @@ covers CUDA or MPS half precision.
| `kornia.losses` | ⚠️ | ⚠️ | 3 / 4 | Dice averaging overflows to inf/NaN in float16; mutual information range check; bfloat16 Dice weighting and total variation |
| `kornia.feature` | ✅ | ✅ | 0 / 0 | Matching uses a manual `cdist` fallback for half dtypes; LightGlue's float16 tests are skipped, so that path is unmeasured |
| `kornia.metrics` | ✅ | ⚠️ | 0 / 1 | bfloat16: `ssim3d` accuracy |
-| `kornia.models` | ⚠️ | ⚠️ | 15 / 7 | EfficientViT (float16) and Kimi-VL MoonViT raise dtype mismatches; bfloat16 RT-DETR RepVGG fusion accuracy |
+| `kornia.models` | ⚠️ | ⚠️ | 9 / 1 | EfficientViT raises dtype mismatches (float16); bfloat16 RT-DETR RepVGG fusion accuracy |
| `contrib`, `core`, `io`, `onnx`, `sensors`, `tracking`, `utils` | ✅ | ⚠️ | 0 / 3 | bfloat16: histogram matching, `_torch_svd_cast`, camera-model projection |
✅ No known CPU failures   ⚠️ Runs, with known failures (mostly accuracy; notes name the ops that raise)
diff --git a/changelog.d/3968.fixed.md b/changelog.d/3968.fixed.md
new file mode 100644
index 000000000..d473bc1c1
--- /dev/null
+++ b/changelog.d/3968.fixed.md
@@ -0,0 +1 @@
+Align Kimi-VL positional embeddings, rotary embeddings, and projector ordering with Moonshot.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index 0417998e0..f6a1578b0 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -146,9 +146,9 @@ precision, so the table says nothing about those backends.
* - ``kornia.models``
- ⚠️ Partial
- ⚠️ Partial
- - 15 / 7
- - EfficientViT (float16) and the Kimi-VL MoonViT encoder (both dtypes) raise dtype-mismatch errors;
- bfloat16 RT-DETR RepVGG deployment fusion misses accuracy.
+ - 9 / 1
+ - float16: EfficientViT raises dtype-mismatch errors. bfloat16: RT-DETR RepVGG deployment fusion misses
+ accuracy.
* - ``contrib``, ``core``, ``io``, ``onnx``, ``sensors``, ``tracking``, ``utils``
- ✅ Yes
- ⚠️ Partial
diff --git a/kornia/models/kimi_vl/config.py b/kornia/models/kimi_vl/config.py
index e0ee1c4b9..40e8a4bf8 100644
--- a/kornia/models/kimi_vl/config.py
+++ b/kornia/models/kimi_vl/config.py
@@ -26,9 +26,11 @@ 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.
+ image_size: Default input image size. The model supports variable
+ resolution inputs through positional interpolation.
patch_size: Size of image patches.
+ init_pos_emb_height: Initial positional embedding grid height.
+ init_pos_emb_width: Initial positional embedding grid width.
num_channels: Number of input channels.
hidden_size: Hidden dimension size.
num_hidden_layers: Number of transformer layers.
@@ -41,18 +43,20 @@ class MoonViTConfig:
rope_theta: Theta value for Rotary Positional Embeddings.
"""
- image_size: int = 384
+ image_size: int = 392
patch_size: int = 14
+ init_pos_emb_height: int = 64
+ init_pos_emb_width: int = 64
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
+ hidden_act: str = "gelu_tanh"
+ layer_norm_eps: float = 1e-5
dropout_p: float = 0.0
attention_dropout_p: float = 0.0
- rope_theta: float = 800000.0
+ rope_theta: float = 10000.0
@dataclass
@@ -94,21 +98,20 @@ class KimiVLConfig:
def _kimi_vl_a3b_instruct_config() -> KimiVLConfig:
"""Return the configuration for the supported pretrained Kimi-VL-A3B-Instruct model."""
vision_config = MoonViTConfig(
- # 896 / 14 = 64 patches per side, matching the original checkpoint's
- # native 64x64 positional-embedding grid (interpolated at runtime for
- # other input resolutions).
- image_size=896,
+ image_size=392,
patch_size=14,
+ init_pos_emb_height=64,
+ init_pos_emb_width=64,
num_channels=3,
hidden_size=1152,
num_hidden_layers=27,
num_attention_heads=16,
intermediate_size=4304,
- hidden_act="gelu",
- layer_norm_eps=1e-6,
+ hidden_act="gelu_tanh",
+ layer_norm_eps=1e-5,
dropout_p=0.0,
attention_dropout_p=0.0,
- rope_theta=800000.0,
+ rope_theta=10000.0,
)
projector_config = KimiVLProjectorConfig(
input_dim=1152,
diff --git a/kornia/models/kimi_vl/model.py b/kornia/models/kimi_vl/model.py
index fee3be11d..3be52b608 100644
--- a/kornia/models/kimi_vl/model.py
+++ b/kornia/models/kimi_vl/model.py
@@ -29,16 +29,16 @@ __all__ = ["KimiVLModel", "KimiVLProjector"]
class KimiVLProjector(nn.Module):
- """KimiVL Projector with Pixel Unshuffle and MLP."""
+ """KimiVL projector with patch merging 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)
+ # Pre-norm (applied before patch merging, 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)
+ # Merging each spatial group multiplies the dimension by downsample_ratio**2.
mlp_input_dim = config.input_dim * (self.downsample_ratio**2)
# MLP
@@ -61,18 +61,20 @@ class KimiVLProjector(nn.Module):
Projected features (B, N/4, output_dim)
"""
B, _N, D = x.shape
+ ratio = self.downsample_ratio
# 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)
+ # Reshape the patch grid into spatial groups of ratio x ratio patches.
+ new_height, new_width = h // ratio, w // ratio
+ x = x.view(B, new_height, ratio, new_width, ratio, D)
- # Pixel unshuffle for spatial downsampling -> (B, D*4, H/2, W/2)
- x = torch.nn.functional.pixel_unshuffle(x, self.downsample_ratio)
+ # Place the output-grid dimensions before the offsets within each group.
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous()
- # Flatten back -> (B, D*4, N/4) -> (B, N/4, D*4)
- x = x.flatten(2).transpose(1, 2)
+ # Flatten the output grid and concatenate each group's patch features.
+ x = x.view(B, new_height * new_width, ratio * ratio * D)
# MLP
x = self.mlp(x)
diff --git a/kornia/models/kimi_vl/moonvit.py b/kornia/models/kimi_vl/moonvit.py
index ade38af72..d56ace595 100644
--- a/kornia/models/kimi_vl/moonvit.py
+++ b/kornia/models/kimi_vl/moonvit.py
@@ -30,21 +30,18 @@ def apply_rotary_pos_emb(x: torch.Tensor, cos: torch.Tensor, sin: 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).
+ x: Query or key tensor with shape :math:`(B, H, N, d)`.
+ cos: Cosine component with shape :math:`(1, 1, N, d / 2)`.
+ sin: Sine component with shape :math:`(1, 1, N, d / 2)`.
Returns:
- Tensor with rotary embeddings applied.
+ Tensor with rotary embeddings applied and the same shape as ``x``.
"""
- # 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)
+ # Complex ops require at least float32; preserve float64 inputs for numerical accuracy.
+ compute_dtype = torch.float64 if x.dtype == torch.float64 else torch.float32
+ x_complex = torch.view_as_complex(x.to(compute_dtype).reshape(*x.shape[:-1], -1, 2))
+ freqs_cis = torch.complex(cos.to(compute_dtype), sin.to(compute_dtype))
+ return torch.view_as_real(x_complex * freqs_cis).flatten(-2).to(x.dtype)
class MoonViTRotaryEmbedding(nn.Module):
@@ -52,6 +49,8 @@ class MoonViTRotaryEmbedding(nn.Module):
def __init__(self, dim: int, theta: float = 10000.0) -> None:
super().__init__()
+ if dim % 4 != 0:
+ raise ValueError(f"Rotary embedding dimension must be divisible by 4. Got {dim}.")
self.dim = dim
self.theta = theta
@@ -71,38 +70,18 @@ class MoonViTRotaryEmbedding(nn.Module):
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.
+ :math:`(h * w, D / 2)`, 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 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()
+ flat_pos = torch.arange(h * w, device=device, dtype=torch.float32)
+ x_pos = flat_pos % w
+ y_pos = flat_pos // w
+ dim_range = torch.arange(0, self.dim, 4, device=device, dtype=torch.float32)[: self.dim // 4]
+ frequencies = 1.0 / (self.theta ** (dim_range / self.dim))
+ x_freqs = torch.outer(x_pos, frequencies)
+ y_freqs = torch.outer(y_pos, frequencies)
+ angles = torch.stack((x_freqs, y_freqs), dim=-1).reshape(h * w, self.dim // 2)
+ freqs_cis = torch.polar(torch.ones_like(angles), angles)
+ return freqs_cis.real, freqs_cis.imag
class MoonViTAttention(nn.Module):
@@ -145,9 +124,9 @@ class MoonViTAttention(nn.Module):
``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.
+ :math:`(N, d / 2)`, where ``d = D / H`` is the per-head dimension.
sin: Sine component of the rotary positional embedding with shape
- :math:`(N, d)`.
+ :math:`(N, d / 2)`.
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.
@@ -168,9 +147,9 @@ class MoonViTAttention(nn.Module):
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)
+ # cos, sin are (seq_len, head_dim / 2) -> reshape for complex-pair rotation
+ cos = cos.view(1, 1, seq_len, self.head_dim // 2)
+ sin = sin.view(1, 1, seq_len, self.head_dim // 2)
query = apply_rotary_pos_emb(query, cos, sin)
key = apply_rotary_pos_emb(key, cos, sin)
@@ -196,7 +175,12 @@ class MoonViTMLP(nn.Module):
def __init__(self, config: MoonViTConfig) -> None:
super().__init__()
self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
- self.act = nn.GELU()
+ if config.hidden_act == "gelu":
+ self.act = nn.GELU()
+ elif config.hidden_act == "gelu_tanh":
+ self.act = nn.GELU(approximate="tanh")
+ else:
+ raise ValueError(f"Unsupported activation: {config.hidden_act}.")
self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
self.dropout = nn.Dropout(config.dropout_p)
@@ -252,9 +236,9 @@ class MoonViTLayer(nn.Module):
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``
+ cos: Cosine rotary embedding table with shape :math:`(N, d / 2)`, where ``d``
is the per-head attention dimension.
- sin: Sine rotary embedding table with shape :math:`(N, d)`.
+ sin: Sine rotary embedding table with shape :math:`(N, d / 2)`.
attention_mask: Optional attention mask forwarded to the self-attention
layer.
@@ -313,8 +297,7 @@ class MoonViT(nn.Module):
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
+ num_patches = config.init_pos_emb_height * config.init_pos_emb_width
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)
@@ -341,13 +324,11 @@ class MoonViT(nn.Module):
# Add Absolute Positional Embedding (with interpolation)
pos_embed = self.pos_embed
- if x.shape[1] != pos_embed.shape[1]:
+ h_ref = self.config.init_pos_emb_height
+ w_ref = self.config.init_pos_emb_width
+ if (h_patches, w_patches) != (h_ref, w_ref):
# 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)
@@ -358,7 +339,7 @@ class MoonViT(nn.Module):
x = x + pos_embed
# Generate RoPE
- cos, sin = self.rope(h_patches, w_patches, x.device) # (N, head_dim)
+ cos, sin = self.rope(h_patches, w_patches, x.device) # (N, head_dim / 2)
x = self.encoder(x, cos, sin, attention_mask=attention_mask)
x = self.norm(x)
diff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txt
index f287bd54b..eaed77eb4 100644
--- a/testing/half_precision_xfails/cpu_bfloat16.txt
+++ b/testing/half_precision_xfails/cpu_bfloat16.txt
@@ -510,11 +510,5 @@ call builtins.AssertionError tests/losses/test_mutual_information.py::TestMutual
call builtins.AssertionError tests/losses/test_total_variation.py::TestTotalVariation::test_tv_on_3d[cpu-bfloat16-pred0-expected0]
call builtins.AssertionError tests/losses/test_total_variation.py::TestTotalVariation::test_tv_on_4d[cpu-bfloat16-pred0-expected0]
call builtins.AssertionError tests/metrics/test_ssim3d.py::TestSSIM3d::test_unit[cpu-bfloat16]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLComponents::test_moonvit[cpu-bfloat16]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_attention_mask[cpu-bfloat16]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_cardinality[cpu-bfloat16-1]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_cardinality[cpu-bfloat16-2]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_cardinality[cpu-bfloat16-4]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_variable_resolution[cpu-bfloat16]
call builtins.AssertionError tests/models/test_rt_detr.py::test_regvgg_optimize_for_deployment[cpu-bfloat16]
call builtins.AssertionError tests/sensors/camera/test_camera_model.py::TestPinholeCamera::test_project_unproject[cpu-bfloat16-2]
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index 7929b59e6..7135ab91a 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -525,9 +525,3 @@ call builtins.RuntimeError tests/models/test_efficient_vit.py::TestEfficientViT:
call builtins.RuntimeError tests/models/test_efficient_vit.py::TestEfficientViT::test_smoke[cpu-float16-96-3-b0]
call builtins.RuntimeError tests/models/test_efficient_vit.py::TestEfficientViT::test_smoke[cpu-float16-96-3-b1]
call builtins.RuntimeError tests/models/test_efficient_vit.py::TestEfficientViT::test_smoke[cpu-float16-96-3-b2]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLComponents::test_moonvit[cpu-float16]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_attention_mask[cpu-float16]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_cardinality[cpu-float16-1]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_cardinality[cpu-float16-2]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_cardinality[cpu-float16-4]
-call builtins.RuntimeError tests/models/test_kimi_vl.py::TestKimiVLModel::test_variable_resolution[cpu-float16]
diff --git a/tests/integration/models/test_kimi_vl.py b/tests/integration/models/test_kimi_vl.py
index 5be1a9b6c..ce35d3799 100644
--- a/tests/integration/models/test_kimi_vl.py
+++ b/tests/integration/models/test_kimi_vl.py
@@ -27,7 +27,6 @@ import os
import pytest
import torch
-import torch.nn.functional as F
from kornia.core import load_safetensors
from kornia.models.kimi_vl import KimiVLConfig, KimiVLModel
@@ -68,6 +67,8 @@ def test_kimi_vl_official_weights():
vision_config = MoonViTConfig(
image_size=336,
patch_size=14,
+ init_pos_emb_height=64,
+ init_pos_emb_width=64,
hidden_size=1152,
num_hidden_layers=27,
num_attention_heads=16,
@@ -90,10 +91,7 @@ def test_kimi_vl_official_weights():
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
+ new_state_dict["vision_encoder.pos_embed"] = pos_embed.flatten(0, 1).unsqueeze(0)
for i in range(config.vision_config.num_hidden_layers):
prefix_official = f"encoder.blocks.{i}"
diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.py
index 6afa38094..fb9d18a34 100644
--- a/tests/models/test_kimi_vl.py
+++ b/tests/models/test_kimi_vl.py
@@ -24,7 +24,13 @@ import kornia.models.kimi_vl.builder as kimi_vl_builder
from kornia.models.kimi_vl import KimiVLBuilder, 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 kornia.models.kimi_vl.moonvit import (
+ MoonViT,
+ MoonViTAttention,
+ MoonViTEncoder,
+ MoonViTRotaryEmbedding,
+ apply_rotary_pos_emb,
+)
from testing.base import BaseTester
@@ -34,6 +40,8 @@ def config():
vision_config = MoonViTConfig(
image_size=32,
patch_size=4,
+ init_pos_emb_height=8,
+ init_pos_emb_width=8,
hidden_size=32,
num_hidden_layers=2,
num_attention_heads=4,
@@ -91,8 +99,8 @@ class TestKimiVLBuilder(BaseTester):
def test_pretrained_config_matches_checkpoint_grid(self):
config = kimi_vl_builder._kimi_vl_a3b_instruct_config()
- # The published checkpoint stores the original 64x64 pos-embed grid.
- assert config.vision_config.image_size // config.vision_config.patch_size == 64
+ assert config.vision_config.init_pos_emb_height == 64
+ assert config.vision_config.init_pos_emb_width == 64
class TestKimiVLModel(BaseTester):
@@ -121,6 +129,29 @@ class TestKimiVLModel(BaseTester):
output = model(images)
assert output.shape == (batch_size, 36, config.projector_config.output_dim)
+ def test_pretrained_image_size(self, device: torch.device, dtype: torch.dtype) -> None:
+ pretrained_config = kimi_vl_builder._kimi_vl_a3b_instruct_config()
+ image_size = pretrained_config.vision_config.image_size
+ patch_size = pretrained_config.vision_config.patch_size
+ vision_config = MoonViTConfig(
+ image_size=image_size,
+ patch_size=patch_size,
+ init_pos_emb_height=64,
+ init_pos_emb_width=64,
+ hidden_size=8,
+ num_hidden_layers=1,
+ num_attention_heads=1,
+ intermediate_size=16,
+ )
+ projector_config = KimiVLProjectorConfig(input_dim=8, hidden_dim=16, output_dim=8)
+ config = KimiVLConfig(vision_config=vision_config, projector_config=projector_config)
+ model = KimiVLModel(config).to(device, dtype)
+
+ output = model(torch.randn(1, 3, image_size, image_size, device=device, dtype=dtype))
+
+ output_grid_size = image_size // patch_size // model.projector.downsample_ratio
+ assert output.shape == (1, output_grid_size**2, 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)
@@ -165,6 +196,63 @@ class TestKimiVLModel(BaseTester):
class TestKimiVLComponents(BaseTester):
+ def test_apply_rotary_pos_emb_preserves_float64_precision(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+
+ # These values intentionally differ below float32 resolution. Before the
+ # dtype-aware promotion, the identity rotation rounded them before casting
+ # the result back to float64 and failed both checks below.
+ x = torch.tensor(
+ [1.000000001, 2.000000001, 3.000000001, 4.000000001],
+ device=device,
+ dtype=torch.float64,
+ requires_grad=True,
+ ).view(1, 1, 1, 4)
+ cos = torch.ones(1, 1, 1, 2, device=device, dtype=torch.float64)
+ sin = torch.zeros_like(cos)
+
+ actual = apply_rotary_pos_emb(x, cos, sin)
+
+ self.assert_close(actual, x, rtol=0.0, atol=0.0)
+ self.gradcheck(lambda value: apply_rotary_pos_emb(value, cos, sin), x)
+
+ def test_rotary_pos_emb_2d_expected_values(self, device):
+ # Source: Moonshot Kimi-VL-A3B-Instruct Rope2DPosEmb at revision
+ # 398eede0903cd983a2bfa0cc634e9ac1d843f375. The expected angles below
+ # are derived by hand for a 2x2 row-major grid and theta=100:
+ # [x * 1, y * 1, x * 0.1, y * 0.1].
+ rope = MoonViTRotaryEmbedding(dim=8, theta=100.0)
+ cos, sin = rope(h=2, w=2, device=device)
+ expected_angles = torch.tensor(
+ [
+ [0.0, 0.0, 0.0, 0.0],
+ [1.0, 0.0, 0.1, 0.0],
+ [0.0, 1.0, 0.0, 0.1],
+ [1.0, 1.0, 0.1, 0.1],
+ ],
+ device=device,
+ )
+ expected_cos = expected_angles.cos()
+ expected_sin = expected_angles.sin()
+
+ self.assert_close(cos, expected_cos)
+ self.assert_close(sin, expected_sin)
+
+ x = torch.arange(1.0, 33.0, device=device).view(1, 1, 4, 8)
+ x_pairs = x.view(1, 1, 4, 4, 2)
+ expected = torch.stack(
+ (
+ x_pairs[..., 0] * expected_cos - x_pairs[..., 1] * expected_sin,
+ x_pairs[..., 0] * expected_sin + x_pairs[..., 1] * expected_cos,
+ ),
+ dim=-1,
+ ).flatten(-2)
+
+ actual = apply_rotary_pos_emb(x, cos.view(1, 1, 4, 4), sin.view(1, 1, 4, 4))
+
+ self.assert_close(actual, expected)
+
def test_moonvit(self, device, dtype, config):
model = MoonViT(config.vision_config).to(device, dtype)
batch_size = 2
@@ -185,8 +273,8 @@ class TestKimiVLComponents(BaseTester):
# 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)
+ cos = torch.randn(seq_len, head_dim // 2, device=device, dtype=dtype)
+ sin = torch.randn(seq_len, head_dim // 2, device=device, dtype=dtype)
output = encoder(x, cos, sin)
assert output.shape == (batch_size, seq_len, hidden_size)
@@ -201,8 +289,8 @@ class TestKimiVLComponents(BaseTester):
# 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)
+ cos = torch.randn(seq_len, head_dim // 2, device=device, dtype=dtype)
+ sin = torch.randn(seq_len, head_dim // 2, device=device, dtype=dtype)
output = attention(x, cos, sin)
assert output.shape == (batch_size, seq_len, hidden_size)
@@ -215,8 +303,8 @@ class TestKimiVLComponents(BaseTester):
cos, sin = rope(h, w, device)
seq_len = h * w
- assert cos.shape == (seq_len, dim)
- assert sin.shape == (seq_len, dim)
+ assert cos.shape == (seq_len, dim // 2)
+ assert sin.shape == (seq_len, dim // 2)
def test_projector(self, device, dtype, config):
model = KimiVLProjector(config.projector_config).to(device, dtype)
@@ -225,3 +313,22 @@ class TestKimiVLComponents(BaseTester):
output = model(input_features, h=8, w=8)
assert output.shape == (batch_size, 16, config.projector_config.output_dim)
+
+ def test_projector_patch_concatenation_order(self, device):
+ # Reference: Moonshot's KimiVLMultiModalProjector at revision
+ # 398eede0903cd983a2bfa0cc634e9ac1d843f375. Values 0..15 form a row-major 2x4 grid
+ # of two-feature patches. When each 2x2 block is merged, the features from each patch must stay
+ # adjacent, with patches ordered top-left, top-right, bottom-left, bottom-right.
+ config = KimiVLProjectorConfig(input_dim=2, hidden_dim=8, output_dim=8)
+ projector = KimiVLProjector(config).to(device)
+ projector.pre_norm = torch.nn.Identity()
+ projector.mlp = torch.nn.Identity()
+ patches = torch.arange(16.0, device=device).view(1, 8, 2)
+ expected = torch.tensor(
+ [[[0.0, 1.0, 2.0, 3.0, 8.0, 9.0, 10.0, 11.0], [4.0, 5.0, 6.0, 7.0, 12.0, 13.0, 14.0, 15.0]]],
+ device=device,
+ )
+
+ actual = projector(patches, h=2, w=4)
+
+ self.assert_close(actual, expected, rtol=0.0, atol=0.0)