Skip to content

Commit c3b7cf1

Browse files
justinchubyCopilot
andauthored
Add Mage-VL image and video support (#472)
## Summary Adds first-class support for [`microsoft/Mage-VL`](https://huggingface.co/microsoft/Mage-VL) (`model_type: mage_vl`) as a standardized three-model package: - `decoder`: Qwen3 text decoder with ordinary 1D RoPE - `vision_encoder`: custom 24-layer Mage-ViT for images and streaming video - `embedding`: batch-safe text/visual feature mixer The vision graph matches Mage-VL's fused biased QKV layout, exact 4:6:6 temporal/height/width RoPE, original sampled-frame temporal positions, 2x2 patch merger, and independent four-frame attention windows. CUDA/DML builds use packed attention with dynamically derived window boundaries; portable builds retain a standard-ONNX block-diagonal fallback. This also adds remote config extraction, registry/public exports, exact checkpoint weight routing, ordered mixed image/video processing, ORT GenAI compatibility guardrails, real media fixtures, and L1-L5 coverage. ## Validation - Unsupported status verified before implementation; no existing `mage_vl` registry/config/model support was present. - Upstream revision studied and pinned: `d88b153285f1633a61b2f693c59c8576693af185`. - Real processor path exercised with a nonzero Apache-2.0 image and soccer video: 4,284 packed patches, five sampled frames, original temporal indices `[0, 180, 360, 539, 719]`, and 1,138 prompt tokens. - `python -m pytest tests/build_graph_test.py tests/weight_alignment_test.py tests/mage_vl_parity_test.py -k "mage_vl" -q`: **10 passed**. - Includes exact checkpoint-key alignment, FP32 parity (`atol/rtol=1e-4`), FP16 parity (`1e-2`), four-frame-boundary video coverage, empty-media decode, multi-row media ordering, and packed-CUDA graph coverage. - `python -m pytest tests/yaml_schema_test.py src/mobius/_testing/golden_test.py src/mobius/integrations/ort_genai/auto_export_test.py -q`: **345 passed**. - `python -m pytest tests/build_graph_test.py tests/cli_test.py src/ -q -k "not phi4mm and not apply_weights_unknown" --tb=short -n auto`: **3,639 passed, 57 skipped**. - `python -m pytest tests/quantization_integration_test.py -v`: **6 passed**. - `lintrunner -a`: **clean**. - Automated code review was run repeatedly; findings for batch indexing, strict image-only processors, and quadratic video attention were fixed. Final review reported no significant issues. ### Real checkpoint / GPU Hardware: NVIDIA RTX A1000, 8,188 MiB; ORT 1.28.0 CUDA EP. - BF16 L4 mixed real image/video, CUDA-specialized build and `CUDAExecutionProvider`: **1 passed in 324.12s**. - BF16 L5 deterministic generation, 24 new tokens, same real image/video and CUDA path: **1 passed in 236.19s**. - The committed HF golden's 24-token continuation begins: `The image depicts a group of four men standing around a table in a stadium...`. - No peak-memory number is claimed. ### CLI exports Direct three-model ONNX export remains supported for CPU and CUDA builds. `--runtime ort-genai` is explicitly rejected before any model artifacts are saved because ORT GenAI cannot supply Mage-VL's required `patch_positions` vision input or its 1D decoder `position_ids`. ```text Error: ORT GenAI does not support Mage-VL's required patch_positions vision input or its 1D decoder position_ids contract. Export without --runtime ort-genai to save the runnable direct three-model ONNX package. ``` ### Olive Olive 0.10.2 NF4 quantization completed on the real FP16 decoder in **74.46s**, reducing external weights from **8,112,046,080 bytes** to **2,204,314,624 bytes**. The quantized decoder loaded in ORT CPU, produced finite `(1, 3, 151936)` logits, and generated: ```text The capital of France is Paris. The capital of Germany is Berlin ``` ## Known runtime limits - **ORT GenAI / Foundry Local:** unsupported until the runtime supports both Mage-VL's required `patch_positions` input (including original sampled-frame indices) and Mage-VL's 1D decoder positions. Mobius rejects `--runtime ort-genai` instead of emitting a non-runnable package. - **Direct ONNX:** supported as the standardized `decoder` + `vision_encoder` + `embedding` package and covered by real CUDA L4/L5 validation. - **Full real-weight FP32/FP16 generation matrix:** FP32 and FP16 are covered by independent synthetic numerical parity; FP16 is additionally covered by full real-weight direct ONNX exports; native BF16 is covered by real CUDA L4/L5. A full FP32 checkpoint run would approximately double the 9.5 GB BF16 checkpoint footprint and was not repeated on this 8 GB GPU. <!-- TODO: verify Foundry Local image/video generation once ORT GenAI supports Mage-VL's 1D decoder positions and patch_positions input. --> --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: justinchuby <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 62b093e commit c3b7cf1

31 files changed

Lines changed: 2883 additions & 59 deletions

‎README.md‎

Lines changed: 5 additions & 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, 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), 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 |
@@ -38,6 +38,10 @@ multi-component export for pipelines.
3838
| **Diffusion** | Stable Diffusion (UNet + VAE + ControlNet), Flux, SD3, DiT, QwenImage, HunyuanDiT, CogVideoX |
3939
| **Adapters** | T2I-Adapter, IP-Adapter |
4040

41+
Mage-VL supports direct three-model ONNX export. ORT GenAI export is currently
42+
rejected because the runtime cannot supply its required `patch_positions` input
43+
or Mage-VL's 1D decoder positions.
44+
4145
Supports **290+ Transformers model types** and **10 Diffusers component types**
4246
across **40+ task types** and **100+ reusable components**.
4347

‎scripts/generate_golden.py‎

Lines changed: 51 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,41 @@
5050

5151
import numpy as np
5252

53+
_MISSING_ATTRIBUTE = object()
54+
55+
56+
@contextlib.contextmanager
57+
def _temporary_processor_max_pixels(processor: object, max_pixels: int | None):
58+
"""Temporarily override processor pixel limits and restore their exact state."""
59+
if max_pixels is None:
60+
yield
61+
return
62+
63+
saved_attributes: list[tuple[object, str, object]] = []
64+
65+
def override(obj: object | None, name: str) -> None:
66+
if obj is None:
67+
return
68+
saved_attributes.append((obj, name, getattr(obj, name, _MISSING_ATTRIBUTE)))
69+
setattr(obj, name, max_pixels)
70+
71+
image_processor = getattr(processor, "image_processor", None)
72+
video_processor = getattr(processor, "video_processor", None)
73+
override(image_processor, "max_pixels")
74+
image_size = getattr(image_processor, "size", None)
75+
if image_size is not None and hasattr(image_size, "longest_edge"):
76+
override(image_size, "longest_edge")
77+
override(video_processor, "max_pixels")
78+
79+
try:
80+
yield
81+
finally:
82+
for obj, name, previous in reversed(saved_attributes):
83+
if previous is _MISSING_ATTRIBUTE:
84+
delattr(obj, name)
85+
else:
86+
setattr(obj, name, previous)
87+
5388

5489
def parse_args() -> argparse.Namespace:
5590
"""Parse command-line arguments."""
@@ -379,7 +414,7 @@ def _generate_seq2seq(case: TestCase, json_path: Path, device: str) -> None:
379414
input_ids=torch.from_numpy(input_ids).to(torch_device),
380415
decoder_input_ids=torch.from_numpy(decoder_start).to(torch_device),
381416
)
382-
last_logits = outputs.logits[0, -1, :].cpu().numpy()
417+
last_logits = outputs.logits[0, -1, :].float().cpu().numpy()
383418
golden = _extract_logits_golden(last_logits)
384419

385420
# L5: greedy generation
@@ -439,8 +474,9 @@ def _generate_vision_language(case: TestCase, json_path: Path, device: str) -> N
439474
case.model_id, dtype=torch_dtype, device=device
440475
)
441476

442-
# Load images from testdata/
477+
# Load real image/video media from testdata/.
443478
images = [Image.open(Path("testdata") / img_path) for img_path in case.images]
479+
videos = [str(Path("testdata") / video_path) for video_path in case.videos]
444480

445481
# Build a chat-formatted prompt when a usable template is available.
446482
# Phi-3 Vision exposes its template on the underlying tokenizer rather
@@ -451,6 +487,8 @@ def _generate_vision_language(case: TestCase, json_path: Path, device: str) -> N
451487
content: list[dict[str, str]] = []
452488
for img_path in case.images:
453489
content.append({"type": "image", "image": str(Path("testdata") / img_path)})
490+
for video_path in case.videos:
491+
content.append({"type": "video", "video": str(Path("testdata") / video_path)})
454492
content.append({"type": "text", "text": prompt_text})
455493
messages = [{"role": "user", "content": content}]
456494
try:
@@ -477,11 +515,17 @@ def _generate_vision_language(case: TestCase, json_path: Path, device: str) -> N
477515
prompt_text = processor.image_token * len(case.images) + prompt_text
478516

479517
# Process multimodal inputs through the HF processor
480-
processed = processor(
481-
text=prompt_text,
482-
images=images if images else None,
483-
return_tensors="pt",
484-
)
518+
with _temporary_processor_max_pixels(processor, case.media_max_pixels):
519+
processor_kwargs: dict[str, object] = {
520+
"text": prompt_text,
521+
"return_tensors": "pt",
522+
}
523+
if images:
524+
processor_kwargs["images"] = images
525+
if videos:
526+
processor_kwargs["videos"] = videos
527+
processor_kwargs["num_frames"] = case.video_num_frames
528+
processed = processor(**processor_kwargs)
485529

486530
# Normalize the CLI/device-map selection to a concrete runtime device
487531
# before moving any tensors. `device="auto"` is handled by Transformers/

‎scripts/generate_golden_test.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,29 @@ def test_dtype_promotion(self):
6666
assert result["logits_summary"].dtype == np.float64
6767

6868

69+
def test_temporary_processor_max_pixels_restores_none_and_missing_attributes():
70+
class ProcessorPart:
71+
pass
72+
73+
image_processor = ProcessorPart()
74+
image_processor.max_pixels = None
75+
image_processor.size = ProcessorPart()
76+
image_processor.size.longest_edge = None
77+
video_processor = ProcessorPart()
78+
processor = ProcessorPart()
79+
processor.image_processor = image_processor
80+
processor.video_processor = video_processor
81+
82+
with generate_golden._temporary_processor_max_pixels(processor, 1234):
83+
assert image_processor.max_pixels == 1234
84+
assert image_processor.size.longest_edge == 1234
85+
assert video_processor.max_pixels == 1234
86+
87+
assert image_processor.max_pixels is None
88+
assert image_processor.size.longest_edge is None
89+
assert not hasattr(video_processor, "max_pixels")
90+
91+
6992
class TestDryRun:
7093
"""Tests for main() with --dry-run (no HF inference needed)."""
7194

‎src/mobius/__main__.py‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -353,6 +353,17 @@ def _save_package(
353353
pkg, output_dir: str, args, optimize: str | None, component_filter: str | None
354354
) -> None:
355355
"""Save a ModelPackage to disk, applying optimizations and runtime configs."""
356+
runtime = getattr(args, "runtime", None)
357+
if runtime == "ort-genai":
358+
from mobius.integrations.ort_genai.auto_export import (
359+
_validate_ort_genai_compatibility,
360+
)
361+
362+
try:
363+
_validate_ort_genai_compatibility(pkg)
364+
except ValueError as error:
365+
raise SystemExit(f"Error: {error}") from error
366+
356367
components = (lambda name: name == component_filter) if component_filter else None
357368
for name, model in pkg.items():
358369
if components is not None and not components(name):
@@ -384,7 +395,6 @@ def _save_package(
384395
path = os.path.join(output_dir, "model.onnx")
385396
print(f"Saved {name} to {path}")
386397

387-
runtime = getattr(args, "runtime", None)
388398
if runtime == "ort-genai":
389399
from mobius.integrations.ort_genai import write_ort_genai_config
390400

@@ -399,6 +409,7 @@ def _save_package(
399409
hf_model_id=hf_model_id,
400410
ep=ep,
401411
local_config_dir=local_config_dir,
412+
trust_remote_code=getattr(args, "trust_remote_code", False),
402413
)
403414
for name, path in artifacts.items():
404415
print(f" {name}: {path}")

‎src/mobius/_configs/_base.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -499,8 +499,12 @@ class ArchitectureConfig(BaseModelConfig):
499499
mm_tokens_per_image: int | None = None
500500
image_token_id: int | None = None
501501
video_token_id: int | None = None
502+
vision_start_token_id: int | None = None
503+
vision_end_token_id: int | None = None
502504
spatial_merge_size: int = 2
503505
temporal_patch_size: int = 2
506+
frame_windows_size: int = 4
507+
tokens_per_second: float = 1.0
504508
deepstack_visual_indexes: list[int] | None = None
505509
fullatt_block_indexes: list[int] | None = None
506510
window_size: int = 112
@@ -997,6 +1001,8 @@ def from_transformers(cls, config, parent_config=None) -> ArchitectureConfig:
9971001

9981002
# Vision config (from multimodal models)
9991003
options.update(_extract_vision_config(config, parent_config, model_type))
1004+
if getattr(parent_config, "model_type", None) == "mage_vl":
1005+
options["model_type"] = "mage_vl"
10001006

10011007
# Audio config
10021008
options.update(_extract_audio_config(config, parent_config, model_type))

‎src/mobius/_configs/_extractors.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,8 +182,13 @@ def extract_vision_config(config, parent_config, model_type: str) -> dict:
182182
for shared in (
183183
"mm_tokens_per_image",
184184
"image_token_id",
185+
"video_token_id",
186+
"vision_start_token_id",
187+
"vision_end_token_id",
185188
"spatial_merge_size",
186189
"temporal_patch_size",
190+
"frame_windows_size",
191+
"tokens_per_second",
187192
"deepstack_visual_indexes",
188193
"fullatt_block_indexes",
189194
"window_size",

‎src/mobius/_configs/_sub_configs.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,9 @@ class VisionConfig:
4747
norm_eps: float = 1e-6
4848
mm_tokens_per_image: int | None = None
4949
image_token_id: int | None = None
50+
video_token_id: int | None = None
51+
vision_start_token_id: int | None = None
52+
vision_end_token_id: int | None = None
5053
# Pixtral / Mistral-3 vision fields
5154
model_type: str | None = None
5255
head_dim: int | None = None
@@ -56,6 +59,8 @@ class VisionConfig:
5659
in_channels: int = 3
5760
spatial_merge_size: int = 2
5861
temporal_patch_size: int = 2
62+
frame_windows_size: int = 4
63+
tokens_per_second: float = 1.0
5964
num_position_embeddings: int | None = None
6065
deepstack_visual_indexes: list[int] | None = None
6166
fullatt_block_indexes: list[int] | None = None

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
_gemma4_unified_vision,
3232
_hunyuan_vl_mot_vision,
3333
_internvl_vision,
34+
_mage_vl_vision,
3435
_muse_glimmer_vision,
3536
_phi4mm_audio,
3637
_phi4mm_vision,
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
from __future__ import annotations
5+
6+
from mobius._configs._extractors import register_vision_hook
7+
8+
9+
@register_vision_hook
10+
def _mage_vl_vision(config, parent_config, model_type: str, fields: dict):
11+
"""Extract the custom Mage-ViT configuration from a Mage-VL parent."""
12+
del config, model_type
13+
if parent_config is None or getattr(parent_config, "model_type", None) != "mage_vl":
14+
return None
15+
16+
vision = getattr(parent_config, "vision_config", None)
17+
if vision is None:
18+
return None
19+
20+
fields.update(
21+
model_type=getattr(vision, "model_type", "mage_vl_vision"),
22+
hidden_size=getattr(vision, "hidden_size", 1024),
23+
intermediate_size=getattr(vision, "intermediate_size", 4096),
24+
num_hidden_layers=getattr(vision, "num_hidden_layers", 24),
25+
num_attention_heads=getattr(vision, "num_attention_heads", 16),
26+
image_size=getattr(vision, "image_size", 448),
27+
patch_size=getattr(vision, "patch_size", 16),
28+
in_channels=getattr(vision, "num_channels", 3),
29+
out_hidden_size=getattr(vision, "out_hidden_size", 2560),
30+
spatial_merge_size=getattr(vision, "spatial_merge_size", 2),
31+
temporal_patch_size=getattr(vision, "temporal_patch_size", 1),
32+
frame_windows_size=getattr(vision, "frame_windows_size", 4),
33+
norm_eps=getattr(vision, "layer_norm_eps", 1e-6),
34+
rope_theta=getattr(vision, "rope_theta", 10_000.0),
35+
hidden_act=getattr(vision, "hidden_act", "gelu"),
36+
image_token_id=getattr(parent_config, "image_token_id", None),
37+
video_token_id=getattr(parent_config, "video_token_id", None),
38+
vision_start_token_id=getattr(parent_config, "vision_start_token_id", None),
39+
vision_end_token_id=getattr(parent_config, "vision_end_token_id", None),
40+
tokens_per_second=getattr(parent_config, "tokens_per_second", 1.0),
41+
)
42+
return None

‎src/mobius/_registry.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777
Lfm2CausalLMModel,
7878
LLaDAModel,
7979
Llama4CausalLMModel,
80+
MageVLForConditionalGeneration,
8081
MoECausalLMModel,
8182
MoonshineForConditionalGeneration,
8283
NanoChatCausalLMModel,
@@ -618,6 +619,7 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
618619
"internvl": ModelRegistration(InternVL2Model, task="vision-language"),
619620
"internvl2": ModelRegistration(InternVL2Model, task="vision-language"),
620621
"internvl_chat": ModelRegistration(InternVL2Model, task="vision-language"),
622+
"mage_vl": ModelRegistration(MageVLForConditionalGeneration, task="mage-vl"),
621623
"janus": ModelRegistration(LLaVAModel, task="vision-language"),
622624
"llava": ModelRegistration(LLaVAModel, task="vision-language"),
623625
"llava_next": ModelRegistration(LLaVAModel, task="vision-language"),
@@ -1023,6 +1025,7 @@ def _create_default_registry() -> ModelRegistry:
10231025
"gemma4_unified": "google/gemma-4-12B",
10241026
"gemma4_unified_text": "google/gemma-4-12B",
10251027
"internvl2": "OpenGVLab/InternVL2-1B",
1028+
"mage_vl": "microsoft/Mage-VL",
10261029
"phi4mm": "microsoft/Phi-4-multimodal-instruct",
10271030
"phi4_multimodal": "microsoft/Phi-4-multimodal-instruct",
10281031
"phi3_v": "microsoft/Phi-3.5-vision-instruct",

0 commit comments

Comments
 (0)