Skip to content

Commit f494a75

Browse files
justinchubyCopilot
andauthored
Add nine core GGUF VLM projector routes (#689)
## Summary - Add role-explicit standalone GGUF sidecar export for `gemma3na`, `gemma3nv`, `gemma4a`, `gemma4ua`, `gemma4uv`, `idefics3`, `internvl`, `llama4`, and `pixtral`. - Add reusable pixel-unshuffle, Idefics3, InternVL, Llama4, and Pixtral projector components plus a dedicated Llama4 vision tower. - Recover revision-neutral graph config and exact tensor mappings from each sidecar while pinning immutable revisions only in the evidence registry. - Preserve active Gemma4 audio by default and support encoder-free Gemma4 unified vision/audio sidecars without collapsing their roles. - Integrate the #688 graph-versus-runtime policy: exact component export remains non-gating, while every saved standalone graph records `mobius.runtime_support=standalone-sidecar-only; paired multimodal runtime unvalidated` and the dispatcher emits a warning. ## Route contracts | Projector | ModelPackage role | Text target | Processor-native feature contract | |---|---|---|---| | `gemma3nv` | `vision_encoder` | `gemma3n` | 768x768 image, 256 feature rows | | `gemma3na` | `audio_encoder` | `gemma3n` | 128-bin input features, 188 feature rows | | `gemma4a` | `audio_encoder` | `gemma4` | Clipped Conformer audio features | | `gemma4uv` | `vision_encoder` | `gemma4` | 48x48 merged patches, one row per valid patch | | `gemma4ua` | `audio_encoder` | `gemma4` | Raw 640-sample frames, one row per valid frame | | `idefics3` | `vision_encoder` | `llama` | Dynamic tile count, 512x512 tiles, 64 rows per tile | | `internvl` | `vision_encoder` | `qwen2` | Dynamic tile count, 448x448 tiles, 256 rows per tile, CLS-last GGUF ordering | | `llama4` | `vision_encoder` | `llama4` | Dynamic tile count, 336x336 tiles, 144 rows per tile; adjacent-pair split-axis 2D RoPE | | `pixtral` | `vision_encoder` | `llama` | Dynamic patch-aligned image; `(H/16)*(W/16)+(H/16)-1` rows | For Idefics3, InternVL, and Llama4, the symbolic `num_tiles` input is processed tile-wise by the encoder/projector and reshaped from `[tiles, rows_per_tile, hidden]` to rank-2 `[tiles * rows_per_tile, hidden]`. ONNX row-major reshape preserves processor tile order and raster order inside each tile; no synthetic tile separators are inserted because the processor owns refined-crop/overview ordering. Gemma3n's combined sidecar requires both presence flags and validates all 825 co-resident vision/audio tensors against both role graphs. Cross-pairing, aliasing, unknown tensors, unsupported packed projector qtypes, and unrepresentable dynamic ABI paths fail closed. ## Runtime policy Mobius emits the exact ONNX component whenever the graph is representable. Downstream paired runtime execution remains explicitly deferred and advisory; it does not gate standalone graph export. Every standalone vision graph declares `when_present=image`. Only F32/F16/BF16 sidecar tensor storage is accepted. ## Evidence and validation - Semantically rebased onto `main@50bb373` (#688), retaining its advisory runtime policy and regenerated census/docs. - Immutable sparse-header preflight covered every promoted route; artifacts and processors are pinned in the generated evidence census and remain within the 16 GiB budget. - 226 focused projector, mapping, pairing, census, documentation, and independent numerical parity tests passed. - One- and three-tile executable tests for Idefics3, InternVL, and Llama4 prove symbolic input shape, cardinality, batch-major tile/raster ordering, image-presence metadata, and parity with independently executed single tiles. - 9,038 broad non-integration tests passed, with 64 skipped and one subtest passed. - Llama4 full-tower independent parity uses `head_dim=8`, which distinguishes adjacent complex-pair rotation from the incorrect split-half layout. - Targeted mypy passed for all new/shared projector sources. - `lintrunner -a` passed. - Independent medium-effort final review found no remaining issues. - The inline image-presence review thread was answered and resolved. - Temporary GGUF headers, sparse files, extracted sources, and scratch payloads were removed before publication. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 50bb373 commit f494a75

23 files changed

Lines changed: 4392 additions & 161 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 19 additions & 14 deletions
Large diffs are not rendered by default.

‎src/mobius/components/__init__.py‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,17 @@
4545
"GQAContext",
4646
"INT64_MAX",
4747
"InputMixer",
48+
"Idefics3Projector",
49+
"InternVLProjector",
4850
"LayerNorm",
4951
"LayerNormNoAffine",
5052
"LayerNormNoBias",
5153
"OffsetLayerNorm",
5254
"LayerScale",
5355
"Linear",
5456
"LinearMultiModalProjector",
57+
"Llama4Projector",
58+
"Llama4VisionTower",
5559
"GGUFMLPProjector",
5660
"GLMEdgeAdapterProjector",
5761
"LoRALinear",
@@ -71,6 +75,7 @@
7175
"ParakeetFastConformerEncoder",
7276
"PostGatedRMSNorm",
7377
"PostNormDecoderLayer",
78+
"PixtralProjector",
7479
"QuantizedEmbedding",
7580
"QuantizedLinear",
7681
"RadioVisionModel",
@@ -87,6 +92,7 @@
8792
"SoftmaxTopKGate",
8893
"SparseMixerGate",
8994
"SpeakerEncoder",
95+
"SpatialPixelUnshuffle",
9096
"SplitResidualVectorQuantizer",
9197
"StaticCacheState",
9298
"TimestepEmbedding",
@@ -162,6 +168,13 @@
162168
ConvTranspose2d,
163169
RmsNorm2d,
164170
)
171+
from mobius.components._core_vlm_projector import (
172+
Idefics3Projector,
173+
InternVLProjector,
174+
Llama4Projector,
175+
PixtralProjector,
176+
SpatialPixelUnshuffle,
177+
)
165178
from mobius.components._decoder import (
166179
DecoderLayer,
167180
PostNormDecoderLayer,
@@ -195,6 +208,7 @@
195208
from mobius.components._lightning_attention import (
196209
LightningAttention as LightningAttention,
197210
)
211+
from mobius.components._llama4_vision import Llama4VisionTower
198212
from mobius.components._lora import LoRALinear
199213
from mobius.components._mamba_block import Mamba2Block as Mamba2Block
200214
from mobius.components._mamba_block import MambaBlock as MambaBlock
Lines changed: 221 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,221 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Reusable projector heads used by architecture-specific GGUF VLM sidecars."""
5+
6+
from __future__ import annotations
7+
8+
from typing import TYPE_CHECKING
9+
10+
from onnxscript import OpBuilder, nn
11+
12+
from mobius.components._common import LayerNorm, Linear
13+
14+
if TYPE_CHECKING:
15+
import onnx_ir as ir
16+
17+
18+
class _GELU(nn.Module):
19+
def forward(self, op: OpBuilder, hidden_states: ir.Value) -> ir.Value:
20+
return op.Gelu(hidden_states)
21+
22+
23+
class SpatialPixelUnshuffle(nn.Module):
24+
"""Merge adjacent image patches while preserving the upstream raster order.
25+
26+
Idefics3, InternVL, and Llama4 use the same two-permutation pixel-unshuffle
27+
topology. A ``scale_factor`` by ``scale_factor`` patch group becomes one
28+
token whose channel width is multiplied by ``scale_factor**2``.
29+
"""
30+
31+
def __init__(self, grid_height: int, grid_width: int, scale_factor: int):
32+
super().__init__()
33+
if grid_height <= 0 or grid_width <= 0 or scale_factor <= 1:
34+
raise ValueError(
35+
"Pixel-unshuffle grid dimensions and scale factor must be positive"
36+
)
37+
if grid_height % scale_factor or grid_width % scale_factor:
38+
raise ValueError(
39+
f"{grid_height}x{grid_width} patch grid is not divisible by "
40+
f"scale factor {scale_factor}"
41+
)
42+
self._grid_height = grid_height
43+
self._grid_width = grid_width
44+
self._scale_factor = scale_factor
45+
46+
def forward(self, op: OpBuilder, hidden_states: ir.Value) -> ir.Value:
47+
# [B, H*W, C] -> [B, H, W, C].
48+
batch = op.Shape(hidden_states, start=0, end=1)
49+
channels = op.Shape(hidden_states, start=2, end=3)
50+
hidden_states = op.Reshape(
51+
hidden_states,
52+
op.Concat(batch, [self._grid_height, self._grid_width], channels, axis=0),
53+
)
54+
55+
scale = self._scale_factor
56+
# Match HF pixel_shuffle: fold width into channels, swap H/W, then fold
57+
# the remaining spatial factor and swap back to raster order.
58+
hidden_states = op.Reshape(
59+
hidden_states,
60+
op.Concat(
61+
batch,
62+
[self._grid_height, self._grid_width // scale],
63+
op.Mul(channels, scale),
64+
axis=0,
65+
),
66+
)
67+
hidden_states = op.Transpose(hidden_states, perm=[0, 2, 1, 3])
68+
hidden_states = op.Reshape(
69+
hidden_states,
70+
op.Concat(
71+
batch,
72+
[self._grid_width // scale, self._grid_height // scale],
73+
op.Mul(channels, scale * scale),
74+
axis=0,
75+
),
76+
)
77+
hidden_states = op.Transpose(hidden_states, perm=[0, 2, 1, 3])
78+
return op.Reshape(
79+
hidden_states,
80+
op.Concat(
81+
batch,
82+
[self._grid_height * self._grid_width // (scale * scale)],
83+
op.Mul(channels, scale * scale),
84+
axis=0,
85+
),
86+
)
87+
88+
89+
class Idefics3Projector(nn.Module):
90+
"""Idefics3 ``pixel_shuffle -> bias-free Linear`` projector."""
91+
92+
def __init__(
93+
self,
94+
vision_hidden_size: int,
95+
text_hidden_size: int,
96+
*,
97+
grid_size: int,
98+
scale_factor: int,
99+
):
100+
super().__init__()
101+
self.pixel_shuffle = SpatialPixelUnshuffle(grid_size, grid_size, scale_factor)
102+
self.model_fc = Linear(
103+
vision_hidden_size * scale_factor * scale_factor,
104+
text_hidden_size,
105+
bias=False,
106+
)
107+
108+
def forward(self, op: OpBuilder, vision_features: ir.Value) -> ir.Value:
109+
return self.model_fc(op, self.pixel_shuffle(op, vision_features))
110+
111+
112+
class InternVLProjector(nn.Module):
113+
"""InternVL ``pixel_shuffle -> LayerNorm -> Linear -> GELU -> Linear`` head."""
114+
115+
def __init__(
116+
self,
117+
vision_hidden_size: int,
118+
text_hidden_size: int,
119+
*,
120+
grid_size: int,
121+
scale_factor: int,
122+
eps: float = 1e-5,
123+
):
124+
super().__init__()
125+
merged_hidden = vision_hidden_size * scale_factor * scale_factor
126+
self.pixel_shuffle = SpatialPixelUnshuffle(grid_size, grid_size, scale_factor)
127+
self.mlp = nn.Sequential(
128+
LayerNorm(merged_hidden, eps=eps),
129+
Linear(merged_hidden, text_hidden_size, bias=True),
130+
_GELU(),
131+
Linear(text_hidden_size, text_hidden_size, bias=True),
132+
)
133+
134+
def forward(self, op: OpBuilder, vision_features: ir.Value) -> ir.Value:
135+
return self.mlp(op, self.pixel_shuffle(op, vision_features))
136+
137+
138+
class Llama4Projector(nn.Module):
139+
"""Llama4 pixel-shuffle adapter and final multimodal projection."""
140+
141+
def __init__(
142+
self,
143+
vision_hidden_size: int,
144+
adapter_hidden_size: int,
145+
text_hidden_size: int,
146+
*,
147+
grid_size: int,
148+
scale_factor: int,
149+
):
150+
super().__init__()
151+
merged_hidden = vision_hidden_size * scale_factor * scale_factor
152+
self.pixel_shuffle = SpatialPixelUnshuffle(grid_size, grid_size, scale_factor)
153+
self.model_mlp_1 = Linear(merged_hidden, adapter_hidden_size, bias=False)
154+
self.model_mlp_2 = Linear(adapter_hidden_size, adapter_hidden_size, bias=False)
155+
self.model_fc = Linear(adapter_hidden_size, text_hidden_size, bias=False)
156+
157+
def forward(self, op: OpBuilder, vision_features: ir.Value) -> ir.Value:
158+
hidden_states = self.pixel_shuffle(op, vision_features)
159+
hidden_states = op.Gelu(self.model_mlp_1(op, hidden_states))
160+
hidden_states = op.Gelu(self.model_mlp_2(op, hidden_states))
161+
return self.model_fc(op, hidden_states)
162+
163+
164+
class PixtralProjector(nn.Module):
165+
"""Original Pixtral MLP plus row-separating ``[IMG_BREAK]`` embeddings."""
166+
167+
def __init__(
168+
self,
169+
vision_hidden_size: int,
170+
text_hidden_size: int,
171+
*,
172+
with_image_break: bool,
173+
):
174+
super().__init__()
175+
self.linear_1 = Linear(vision_hidden_size, text_hidden_size, bias=True)
176+
self.linear_2 = Linear(text_hidden_size, text_hidden_size, bias=True)
177+
self.image_break = nn.Parameter([text_hidden_size]) if with_image_break else None
178+
self._text_hidden_size = text_hidden_size
179+
180+
def forward(
181+
self,
182+
op: OpBuilder,
183+
vision_features: ir.Value,
184+
grid_height: ir.Value,
185+
grid_width: ir.Value,
186+
) -> ir.Value:
187+
# The GGUF Pixtral sidecar processes one image per invocation.
188+
hidden_states = self.linear_2(op, op.Gelu(self.linear_1(op, vision_features)))
189+
hidden_states = op.Reshape(
190+
hidden_states,
191+
op.Concat(
192+
op.Reshape(grid_height, [1]),
193+
op.Reshape(grid_width, [1]),
194+
[self._text_hidden_size],
195+
axis=0,
196+
),
197+
)
198+
if self.image_break is None:
199+
return op.Reshape(hidden_states, [-1, self._text_hidden_size])
200+
201+
# Append a break to every row, flatten, then remove the final row's break.
202+
breaks = op.Expand(
203+
op.Reshape(self.image_break, [1, 1, self._text_hidden_size]),
204+
op.Concat(
205+
op.Reshape(grid_height, [1]),
206+
[1, self._text_hidden_size],
207+
axis=0,
208+
),
209+
)
210+
hidden_states = op.Concat(hidden_states, breaks, axis=1)
211+
hidden_states = op.Reshape(hidden_states, [-1, self._text_hidden_size])
212+
output_rows = op.Sub(
213+
op.Mul(grid_height, op.Add(grid_width, op.CastLike(1, grid_width))),
214+
op.CastLike(1, grid_height),
215+
)
216+
return op.Slice(
217+
hidden_states,
218+
op.Constant(value_ints=[0]),
219+
op.Reshape(output_rows, [1]),
220+
op.Constant(value_ints=[0]),
221+
)

0 commit comments

Comments
 (0)