🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat(models): add pretrained Kimi-VL weight loading (#3875)
Tomás Guija Valiente9ec66f358918
diff --git a/docs/source/models.rst b/docs/source/models.rstindex cf6fac7a9..ddc1e01a5 100644--- a/docs/source/models.rst+++ b/docs/source/models.rst@@ -98,6 +98,34 @@ The `SegmentationModelsBuilder` class offers a flexible API for implementing andsegmented_output = model(input_tensor)print(segmented_output.shape)+.. _KimiVLBuilder:++KimiVLBuilder+-------------++The `KimiVLBuilder` class constructs Kimi-VL models from a configuration or downloads pretrained weights. Pretrained+loading currently supports only the converted Kimi-VL-A3B-Instruct vision encoder and projector checkpoint.++**Key Methods:**++- `from_config`: Constructs a randomly initialized Kimi-VL model from a `KimiVLConfig`.+- `from_pretrained_hf`: Downloads and strictly loads the supported pretrained checkpoint.++.. autoclass:: kornia.models.kimi_vl.KimiVLBuilder+ :members:+ :undoc-members:+ :show-inheritance:++ .. rubric:: Example++ The following code loads the supported pretrained Kimi-VL vision model:++ .. code-block:: python++ from kornia.models.kimi_vl import KimiVLBuilder++ model = KimiVLBuilder.from_pretrained_hf().eval()+.. _BoxMotTracker:BoxMotTrackerdiff --git a/kornia/models/kimi_vl/__init__.py b/kornia/models/kimi_vl/__init__.pyindex bdff9e6df..734682406 100644--- a/kornia/models/kimi_vl/__init__.py+++ b/kornia/models/kimi_vl/__init__.py@@ -15,11 +15,15 @@# limitations under the License.#+from __future__ import annotations++from .builder import KimiVLBuilderfrom .config import KimiVLConfig, KimiVLProjectorConfig, MoonViTConfigfrom .model import KimiVLModel, KimiVLProjectorfrom .moonvit import MoonViT__all__ = [+ "KimiVLBuilder","KimiVLConfig","KimiVLModel","KimiVLProjector",diff --git a/kornia/models/kimi_vl/builder.py b/kornia/models/kimi_vl/builder.pynew file mode 100644index 000000000..3e69756d1--- /dev/null+++ b/kornia/models/kimi_vl/builder.py@@ -0,0 +1,102 @@+# 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.+#++"""Builder for Kimi-VL models."""++from __future__ import annotations++import logging+from typing import Optional++import torch++from .config import KimiVLConfig, _kimi_vl_a3b_instruct_config+from .model import KimiVLModel++logger = logging.getLogger(__name__)++__all__ = ["KimiVLBuilder"]++_KIMI_VL_A3B_INSTRUCT_REPO_ID = "kornia/kimi-vl-a3b-instruct-vision"+++def _download_weights(model_name: str, cache_dir: Optional[str]) -> dict[str, torch.Tensor]:+ """Download model weights from HuggingFace Hub."""+ try:+ from huggingface_hub import hf_hub_download+ from safetensors import safe_open+ except ImportError as e:+ error_msg = (+ "huggingface_hub and safetensors are required for loading model weights. "+ "Install them with: pip install huggingface_hub safetensors"+ )+ logger.error(error_msg)+ raise ImportError(error_msg) from e++ weights_path = hf_hub_download(repo_id=model_name, filename="model.safetensors", cache_dir=cache_dir)+ state_dict = {}+ with safe_open(weights_path, framework="pt", device="cpu") as f:+ for key in f.keys():+ state_dict[key] = f.get_tensor(key)+ return state_dict+++class KimiVLBuilder:+ """Builder for Kimi-VL models.++ Provides convenient methods to create Kimi-VL models from configs or+ load pretrained weights.+ """++ @staticmethod+ def from_config(config: KimiVLConfig) -> KimiVLModel:+ """Build model from configuration.++ Args:+ config: Model configuration.++ Returns:+ KimiVLModel instance.+ """+ return KimiVLModel(config)++ @staticmethod+ def from_pretrained_hf(cache_dir: Optional[str] = None) -> KimiVLModel:+ """Load pretrained Kimi-VL-A3B-Instruct vision weights from Hugging Face Hub.++ Downloads the vision encoder and projector weights of+ `moonshotai/Kimi-VL-A3B-Instruct` from the Kornia-owned safetensors+ checkpoint at https://huggingface.co/kornia/kimi-vl-a3b-instruct-vision.+ The checkpoint values are bitwise-identical to the original release+ (bf16), including the full 64x64 positional-embedding grid, which the+ model interpolates at runtime for other input resolutions.++ Args:+ cache_dir: Optional cache directory for downloaded files.++ Returns:+ KimiVLModel instance with pretrained weights.++ .. note::+ Only Kimi-VL-A3B-Instruct is currently supported. This method+ requires the `huggingface_hub` and `safetensors` libraries:+ ``pip install huggingface_hub safetensors``+ """+ state_dict = _download_weights(_KIMI_VL_A3B_INSTRUCT_REPO_ID, cache_dir)+ model = KimiVLBuilder.from_config(_kimi_vl_a3b_instruct_config())+ model.load_state_dict(state_dict, strict=True)+ return modeldiff --git a/kornia/models/kimi_vl/config.py b/kornia/models/kimi_vl/config.pyindex ca5884207..e0ee1c4b9 100644--- a/kornia/models/kimi_vl/config.py+++ b/kornia/models/kimi_vl/config.py@@ -89,3 +89,31 @@ class KimiVLConfig:self.vision_config = MoonViTConfig()if self.projector_config is None:self.projector_config = KimiVLProjectorConfig()+++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,+ patch_size=14,+ 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,+ dropout_p=0.0,+ attention_dropout_p=0.0,+ rope_theta=800000.0,+ )+ projector_config = KimiVLProjectorConfig(+ input_dim=1152,+ hidden_dim=4608,+ output_dim=2048,+ dropout_p=0.0,+ )+ return KimiVLConfig(vision_config=vision_config, projector_config=projector_config)diff --git a/tests/models/test_kimi_vl.py b/tests/models/test_kimi_vl.pyindex 72ed8295a..322d72531 100644--- a/tests/models/test_kimi_vl.py+++ b/tests/models/test_kimi_vl.py@@ -15,10 +15,13 @@# limitations under the License.#+from unittest.mock import patch+import pytestimport torch-from kornia.models.kimi_vl import KimiVLConfig, KimiVLModel+import kornia.models.kimi_vl.builder as kimi_vl_builder+from kornia.models.kimi_vl import KimiVLBuilder, KimiVLConfig, KimiVLModelfrom kornia.models.kimi_vl.config import KimiVLProjectorConfig, MoonViTConfigfrom kornia.models.kimi_vl.model import KimiVLProjectorfrom kornia.models.kimi_vl.moonvit import MoonViT, MoonViTAttention, MoonViTEncoder, MoonViTRotaryEmbedding@@ -49,6 +52,31 @@ def model(device, dtype, config):return KimiVLModel(config).to(device, dtype)+class TestKimiVLBuilder(BaseTester):+ def test_from_config(self, config):+ model = KimiVLBuilder.from_config(config)++ assert isinstance(model, KimiVLModel)+ assert model.config is config++ def test_from_pretrained_hf(self, config):+ expected = KimiVLBuilder.from_config(config)+ with (+ patch.object(kimi_vl_builder, "_download_weights", return_value=expected.state_dict()) as mock_download,+ patch.object(kimi_vl_builder, "_kimi_vl_a3b_instruct_config", return_value=config),+ ):+ actual = KimiVLBuilder.from_pretrained_hf(cache_dir="cache")++ assert isinstance(actual, KimiVLModel)+ assert actual.config is config+ mock_download.assert_called_once_with(kimi_vl_builder._KIMI_VL_A3B_INSTRUCT_REPO_ID, "cache")++ 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++class TestKimiVLModel(BaseTester):def test_smoke(self, model):assert model is not None