Skip to content

Commit c2a3a93

Browse files
justinchubyCopilot
andauthored
Add OpenBMB MiniCPM-V 4.6 support (#464)
## Summary - add native `minicpmv4_6` support for `openbmb/MiniCPM-V-4.6` / Transformers 5.7+ - implement packed variable-resolution SigLIP2 vision, ragged overview/slice batching, inserted window-attention merger, final MLP merger, and 16x/4x modes - reuse the Qwen3.5 hybrid decoder and standard three-model VLM helpers; support image and video placeholder routing - add config/registry/CLI/runtime integration, weight mapping, synthetic and real-weight parity, and genuine image-conditioned L4/L5 goldens ## Updated from main Rebased the linear six-commit PR series onto current `origin/main` at `c3b7cf1`, incorporating Mage-VL image/video support and Parakeet CTC in addition to Moonshine, Nemotron Parse 2.0, LFM2.5, fused Swish, Gemma 3n, and Muse Glimmer. Conflict resolution preserves all upstream registrations, configs, tasks, docs, and tests alongside MiniCPM. ## Validation after latest rebase - `lintrunner -a`: clean - config extractor: `1 passed, 24 deselected` - MiniCPM unit/L1: `6 passed, 1392 deselected` - CUDA real-weight nonzero-image parity: `1 passed, 126 deselected` - prior CPU real parity and CUDA L4/L5 image generation remain unchanged by the registration-only main conflicts - FP16 CUDA stages: vision cosine `0.999961913`, embedding cosine `0.999961913`, last-token logits cosine `0.999991179`, identical argmax `760`, no NaNs ## Fused and optimized graphs Weighted FP16 CUDA-targeted graph audit after the latest rebase: | Graph | Nodes | Identity | Unused inputs | Fused/layout evidence | |---|---:|---:|---:|---| | decoder | 1,107 | 0 | 0 | 6 GQA, 18 LinearAttention, 18 CausalConvWithState, 48 SkipSimplifiedLayerNormalization, 42 Swish, 36 transpose | | vision_encoder | 619 | 0 | 0 | 28 Attention, 54 SkipLayerNormalization, 5 transpose, 2 cast | | embedding | 15 | 0 | 0 | 0 transpose, 1 cast, 2 reshape | Initializer folding reduces unweighted vision transposes from 175 to five required raster/window permutations. FP16 avoids BF16-only compatibility casts. Actual CUDA profiling confirms the fused kernels execute on CUDA: vision 542 CUDA nodes / 0 CPU compute, embedding 15 CUDA / 0 CPU, decoder 991 CUDA nodes with all GQA/LinearAttention/CausalConv/skip-RMSNorm kernels on CUDA. Outputs are finite and image-conditioned argmax remains `760`. ## DRYness Reuses `Qwen35TextModel`, shared hybrid-cache task machinery, `VisionEncoderLayer`, `VisionAttention`, `LayerNorm`, `Linear`, activation helpers, `VisionLanguageTask`, `build_decoder_from_embeds`, and `build_embedding_from_features`. Only MiniCPM-specific NaViT/ragged-grid/merger logic remains local. The specialized dual image/video embedding graph is 15 nodes. ## Runtime limitations - ort-extensions has no native MiniCPM adaptive slicing + horizontal NaViT packing transform; callers supply Hugging Face processor tensors, including native INT32 `target_sizes`. - `onnxruntime-genai-cuda 0.15.2` crashes loading this hybrid package on Windows, while raw ORT CUDA executes all three graphs and exact L5 generation successfully. - FP16 is the validated end-to-end reduced-precision CUDA path; BF16 decoder awaits an ORT `CausalConvWithState` kernel. - Foundry Local and Olive are not installed in this environment. --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: justinchuby <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent c3b7cf1 commit c2a3a93

19 files changed

Lines changed: 1773 additions & 1 deletion

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ multi-component export for pipelines.
2929
|---|---|
3030
| **Text Generation** | Llama 2/3/4, Mistral, Qwen 2/2.5/3/3.5/3.6, Phi-3/3.5, Gemma 1/2/3/4, Granite, GPT-2, OPT, OLMo, SmolLM3, and many more |
3131
| **Mixture of Experts** | PhiMoE, GPTOSS, Mixtral, OLMoE, DeepSeek-V2/V3, Qwen2-MoE, Qwen3-MoE, Qwen3-Next, GLM-4-MoE, Arctic, DBRX, Jamba |
32-
| **Multimodal** | Gemma 3/4, Phi-4MM (vision + audio + LoRA), Nemotron Parse, LLaVA, InternVL2, Mage-VL (image + streaming video), Qwen2.5-VL, Qwen3-VL, Qwen3.5/3.6-VL, Pixtral |
32+
| **Multimodal** | Gemma 3/4, Phi-4MM (vision + audio + LoRA), Nemotron Parse, LLaVA, InternVL2, Mage-VL (image + streaming video), MiniCPM-V 4.6, Qwen2.5-VL, Qwen3-VL, Qwen3.5/3.6-VL, Pixtral |
3333
| **Encoder-only** | BERT, RoBERTa, ALBERT, DeBERTa, DistilBERT, ELECTRA, XLNet |
3434
| **Encoder-Decoder** | BART, T5/mT5, Marian, M2M-100, Pegasus, BigBird-Pegasus |
3535
| **Speech-to-Text** | Whisper, Moonshine, FastConformer-RNNT, FunASR, Qwen3-ASR, SenseVoice |

‎src/mobius/_configs/_base.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -501,6 +501,7 @@ class ArchitectureConfig(BaseModelConfig):
501501
video_token_id: int | None = None
502502
vision_start_token_id: int | None = None
503503
vision_end_token_id: int | None = None
504+
downsample_mode: str = "16x"
504505
spatial_merge_size: int = 2
505506
temporal_patch_size: int = 2
506507
frame_windows_size: int = 4

‎src/mobius/_configs/_extractors_test.py‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -345,6 +345,38 @@ def test_hunyuan_vl_mot_image_token_id_survives_default_hook(loaded_vision_hooks
345345
assert out.get("image_token_id") == 12
346346

347347

348+
def test_minicpm_vision_defaults_explicit_none_kernels(loaded_vision_hooks):
349+
"""Explicit None merger kernels fall back to MiniCPM's 2x2 defaults."""
350+
vision_config = _FakeHFConfig(
351+
model_type="minicpmv4_6_vision",
352+
hidden_size=32,
353+
intermediate_size=64,
354+
num_hidden_layers=2,
355+
num_attention_heads=2,
356+
image_size=56,
357+
patch_size=14,
358+
layer_norm_eps=1e-6,
359+
num_channels=3,
360+
window_kernel_size=None,
361+
)
362+
parent_config = _FakeHFConfig(
363+
model_type="minicpmv4_6",
364+
vision_config=vision_config,
365+
image_token_id=250,
366+
merge_kernel_size=None,
367+
)
368+
text_config = _FakeHFConfig(model_type="qwen3_5_text")
369+
370+
out = _extractors.extract_vision_config(
371+
text_config,
372+
parent_config,
373+
"qwen3_5_text",
374+
)
375+
376+
assert out["vision"].window_kernel_size == (2, 2)
377+
assert out["vision"].merge_kernel_size == (2, 2)
378+
379+
348380
# ---------------------------------------------------------------------------
349381
# Gemma 3n hooks (MobileNet-V5 vision tower + USM Conformer audio tower)
350382
# ---------------------------------------------------------------------------

‎src/mobius/_configs/_sub_configs.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,11 @@ class VisionConfig:
103103
do_pooling: bool = True
104104
# RMSNorm epsilon for the vision tower (may differ from the text decoder's).
105105
rms_norm_eps: float | None = None
106+
# MiniCPM-V packed-NaViT vision encoder and its two spatial mergers.
107+
insert_layer_id: int | None = None
108+
window_kernel_size: tuple[int, int] = (2, 2)
109+
merge_kernel_size: tuple[int, int] = (2, 2)
110+
merger_times: int = 1
106111

107112

108113
@dataclasses.dataclass

‎src/mobius/_configs/per_model/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
_hunyuan_vl_mot_vision,
3333
_internvl_vision,
3434
_mage_vl_vision,
35+
_minicpmv4_6_vision,
3536
_muse_glimmer_vision,
3637
_phi4mm_audio,
3738
_phi4mm_vision,
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""MiniCPM-V-4.6 vision extractor hook."""
5+
6+
from __future__ import annotations
7+
8+
from mobius._configs._extractors import register_vision_hook
9+
10+
11+
@register_vision_hook("qwen3_5_text")
12+
def _minicpmv4_6_vision(config, parent_config, model_type: str, fields: dict):
13+
"""Extract the packed SigLIP2 geometry from the composite MiniCPM config."""
14+
if getattr(parent_config, "model_type", None) != "minicpmv4_6":
15+
return None
16+
17+
vision = parent_config.vision_config
18+
image_size = getattr(vision, "image_size", 980)
19+
patch_size = getattr(vision, "patch_size", 14)
20+
fields.update(
21+
model_type="minicpmv4_6_vision",
22+
hidden_size=vision.hidden_size,
23+
intermediate_size=vision.intermediate_size,
24+
num_hidden_layers=vision.num_hidden_layers,
25+
num_attention_heads=vision.num_attention_heads,
26+
image_size=image_size,
27+
patch_size=patch_size,
28+
norm_eps=vision.layer_norm_eps,
29+
hidden_act=getattr(vision, "hidden_act", "gelu_pytorch_tanh"),
30+
in_channels=getattr(vision, "num_channels", 3),
31+
num_position_embeddings=(image_size // patch_size) ** 2,
32+
image_token_id=parent_config.image_token_id,
33+
insert_layer_id=getattr(parent_config, "insert_layer_id", 6),
34+
window_kernel_size=tuple(getattr(vision, "window_kernel_size", None) or (2, 2)),
35+
merge_kernel_size=tuple(getattr(parent_config, "merge_kernel_size", None) or (2, 2)),
36+
merger_times=getattr(parent_config, "merger_times", 1),
37+
)
38+
return None

‎src/mobius/_registry.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,7 @@
141141
from mobius.models.llava import LLaVAModel
142142
from mobius.models.longcat_flash import LongcatFlashCausalLMModel
143143
from mobius.models.mamba import Mamba2CausalLMModel, MambaCausalLMModel
144+
from mobius.models.minicpmv4_6 import MiniCPMV46ForConditionalGeneration
144145
from mobius.models.minimax import MiniMaxCausalLMModel
145146
from mobius.models.mllama import MllamaCausalLMModel
146147
from mobius.models.modernbert import ModernBertDecoderModel, ModernBertModel
@@ -626,6 +627,10 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
626627
"llava_next_video": ModelRegistration(LLaVAModel, task="vision-language"),
627628
"llava_onevision": ModelRegistration(LLaVAModel, task="vision-language"),
628629
"mistral3": ModelRegistration(LLaVAModel, task="pixtral-vl"),
630+
"minicpmv4_6": ModelRegistration(
631+
MiniCPMV46ForConditionalGeneration,
632+
task="minicpm-vl",
633+
),
629634
"mllama": ModelRegistration(MllamaCausalLMModel, task="mllama-vision-language"),
630635
"muse_glimmer": ModelRegistration(
631636
MuseGlimmerForConditionalGeneration,
@@ -1038,6 +1043,7 @@ def _create_default_registry() -> ModelRegistry:
10381043
"llava_onevision": "llava-hf/llava-onevision-qwen2-0.5b-ov-hf",
10391044
"molmo": "allenai/MolmoE-1B-0924",
10401045
"mistral3": "mistralai/Ministral-3-3B-Instruct-2512",
1046+
"minicpmv4_6": "openbmb/MiniCPM-V-4.6",
10411047
"aya_vision": "CohereForAI/aya-vision-8b",
10421048
"chameleon": "facebook/chameleon-7b",
10431049
"cohere2_vision": "CohereForAI/c4ai-command-r7b-12-2024",

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,10 @@
9494
"qwen3_vl_text": "qwen3_vl",
9595
"qwen3_5": "qwen2_5_vl",
9696
"qwen3_5_vl": "qwen2_5_vl",
97+
# MiniCPM uses standard 1D decoder position IDs (unlike Qwen-VL MRoPE).
98+
# The phi3v multimodal runtime provides that contract; callers supply
99+
# HF-preprocessed packed pixels through Generator.set_inputs().
100+
"minicpmv4_6": "phi3v",
97101
}
98102

99103
_GEMMA4_MODEL_TYPES = frozenset(
@@ -108,6 +112,7 @@
108112
# must preprocess with the HuggingFace processor and feed tensors via
109113
# ``Generator.set_inputs`` (see examples/gemma4_unified_ort_genai.py).
110114
_GEMMA4_UNIFIED_MODEL_TYPES = frozenset({"gemma4_unified", "gemma4_unified_text"})
115+
_MINICPM_MODEL_TYPES = frozenset({"minicpmv4_6"})
111116
# gemma-3 multimodal. build() unwraps the composite HF config to its text
112117
# sub-config, so at export time ``config.model_type`` is "gemma3_text" (not
113118
# "gemma3").
@@ -145,6 +150,9 @@
145150
"merges.txt", # BPE
146151
"vocab.json", # BPE
147152
"chat_template.jinja", # Chat template for ORT GenAI
153+
# Preserve HuggingFace processor metadata for VLMs whose preprocessing
154+
# cannot be represented by an ort-extensions image_processor.json.
155+
"preprocessor_config.json",
148156
]
149157

150158

@@ -558,6 +566,17 @@ def _write_vision_processor_config(
558566
model_type,
559567
)
560568
return None
569+
if model_type in _MINICPM_MODEL_TYPES:
570+
# MiniCPM needs adaptive slicing and NaViT horizontal patch packing.
571+
# ort-extensions has no equivalent transform, so preserving the HF
572+
# processor output and injecting it through set_inputs is the only
573+
# numerically faithful runtime path.
574+
logger.info(
575+
"Skipping image_processor.json for %s "
576+
"(use MiniCPMV4_6Processor + Generator.set_inputs)",
577+
model_type,
578+
)
579+
return None
561580

562581
vision_model_type = getattr(vision, "model_type", None)
563582
is_pixtral = vision_model_type == "pixtral" or model_type in _PIXTRAL_MODEL_TYPES
@@ -1018,6 +1037,12 @@ def _write_genai_config(
10181037
model_type = getattr(config, "model_type", "")
10191038
vision_input_mapping = _introspect_inputs(pkg, "vision_encoder")
10201039
embedding_input_mapping = _introspect_inputs(pkg, "embedding")
1040+
if model_type in _MINICPM_MODEL_TYPES and vision_input_mapping is not None:
1041+
# ORT GenAI's VisionInputs schema only accepts its predefined
1042+
# semantic keys. ``target_sizes`` remains an ONNX graph input
1043+
# and is supplied as a named tensor through set_inputs().
1044+
vision_input_mapping.pop("target_sizes", None)
1045+
10211046
# spatial_merge_size and config_filename are config-level
10221047
# properties that cannot be inferred from the graph.
10231048
vision_kwargs: dict[str, Any] = {}
@@ -1026,6 +1051,10 @@ def _write_genai_config(
10261051
vision_kwargs["spatial_merge_size"] = getattr(
10271052
vision_cfg, "spatial_merge_size", 2
10281053
)
1054+
elif model_type in _MINICPM_MODEL_TYPES:
1055+
# MiniCPM performs both 2x2 merges inside the ONNX vision
1056+
# graph and consumes HF-prepacked pixels, not Qwen grid_thw.
1057+
vision_kwargs["spatial_merge_size"] = None
10291058
elif has_speech:
10301059
vision_kwargs["spatial_merge_size"] = None
10311060
# Gemma3n shares gemma3's fixed-resize branch in

‎src/mobius/models/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,7 @@
8383
"Mamba2CausalLMModel",
8484
"MambaCausalLMModel",
8585
"MiniMaxCausalLMModel",
86+
"MiniCPMV46ForConditionalGeneration",
8687
"MoonshineForConditionalGeneration",
8788
"MuseGlimmerForConditionalGeneration",
8889
"MuseGlimmerTextCausalLMModel",
@@ -235,6 +236,7 @@
235236
from mobius.models.mage_vl import MageVLForConditionalGeneration
236237
from mobius.models.mamba import Mamba2CausalLMModel, MambaCausalLMModel
237238
from mobius.models.mimi import MimiModel, mimi_default_config
239+
from mobius.models.minicpmv4_6 import MiniCPMV46ForConditionalGeneration
238240
from mobius.models.minimax import MiniMaxCausalLMModel
239241
from mobius.models.moe import (
240242
Ernie45MoECausalLMModel,

0 commit comments

Comments
 (0)