Skip to content

Commit a1ea520

Browse files
justinchubyCopilot
andauthored
Add seven Qwen and GLM GGUF projector routes (#690)
## Summary - add exact standalone GGUF projector routes for `glm4v`, `glma`, `qwen2.5o`, `qwen2a`, `qwen3a`, `qwen3vl_merger`, and `qwen3tts_spkenc` - enforce metadata, tensor closure, shape, modality pairing, and F32/F16/BF16-only qtype contracts; quarantine `qwen3tts_gen` - cover Qwen3-VL 2x2 merge cardinality, DeepStack width packing, four-section decoder MRoPE, and route-selected transformer activation semantics - preserve #688's advisory-only downstream-runtime policy and semantically retain #689's core-VLM builders, roles, evidence, component-presence metadata, census, docs, and tests ## Rebased commit stack - `171cec98` — small remaining shared standalone-dispatch/export delta after #689 absorbed the reusable projector foundation - `168414fe` — exactly the seven Qwen/GLM routes, mappings, components, evidence, docs, and tests - `1de782cf` — strict pre-closure metadata validation and Qwen3 audio padding/length hardening - `4b03d27e` — processor-native Qwen3 mask ABI, consumer-scoped SiLU semantics, and single-preflight fix Shared surfaces remain additive with #689: `_MMPROJ_BUILDERS` retains both `core_vlm_projector` and `qwen_glm_projector`; generic vision/audio/speaker tasks retain core component-presence metadata and Qwen multi-output audio support. ## Review hardening - `qwen3a` accepts the pinned `Qwen3ASRProcessor` output directly as `input_features_mask: int32`, casts internally only for length arithmetic, compacts padding-derived rows, and publishes `audio_feature_lengths` - all seven routes validate consumed metadata types, positive/finite ranges, boolean presence flags, exact projector enums, and route-specific geometry before tensor closure or graph construction - `clip.use_silu` is validated and fingerprint-relevant only for `glm4v`, `glma`, and `qwen3vl_merger`; Qwen3-VL transformer FFNs follow it while final and DeepStack mergers remain tanh-GELU - public standalone dispatch performs the expensive Qwen/GLM preflight once; direct route-wrapper calls still validate when no prevalidated model is injected - the outstanding duplicate-preflight review thread was answered and resolved ## Validation - combined focused projector/task suite: 440 passed - broad non-integration suite: 9,230 passed, 64 skipped, 1 subtest passed - lintrunner clean - generated GGUF docs clean - changed production modules pass mypy with import traversal isolated - independent medium-effort review and follow-up review: no findings Immutable selected evidence totals 5,980,273,312 bytes, below the 16 GiB cap. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Copilot-Session: e45c53d8-129d-461b-86fc-8ed79d816efe
1 parent f494a75 commit a1ea520

18 files changed

Lines changed: 5353 additions & 127 deletions

‎docs/api/build_from_gguf.md‎

Lines changed: 75 additions & 65 deletions
Large diffs are not rendered by default.

‎src/mobius/components/__init__.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@
3939
"Gemma3nAudioEncoder",
4040
"Gemma3nMultimodalEmbedder",
4141
"GlmOcrVisionModel",
42+
"Glm4VVisionModel",
4243
"GatedShortConv",
4344
"ClippableLinear",
4445
"GroupNorm",
@@ -57,6 +58,9 @@
5758
"Llama4Projector",
5859
"Llama4VisionTower",
5960
"GGUFMLPProjector",
61+
"GGUFLegacyGlmAudioProjector",
62+
"GGUFQwen2AudioProjector",
63+
"GGUFWhisperAudioTower",
6064
"GLMEdgeAdapterProjector",
6165
"LoRALinear",
6266
"MLP",
@@ -203,6 +207,12 @@
203207
from mobius.components._gemma3n_embedder import Gemma3nMultimodalEmbedder
204208
from mobius.components._gemma4_audio import ClippableLinear
205209
from mobius.components._gemma4_audio import Gemma4AudioEncoder as Gemma4AudioEncoder
210+
from mobius.components._gguf_audio_projectors import (
211+
GGUFLegacyGlmAudioProjector,
212+
GGUFQwen2AudioProjector,
213+
GGUFWhisperAudioTower,
214+
)
215+
from mobius.components._glm4v_vision import Glm4VVisionModel
206216
from mobius.components._glm_ocr_vision import GlmOcrVisionModel
207217
from mobius.components._kimi_linear import KimiDeltaAttention, KimiMLAAttention
208218
from mobius.components._lightning_attention import (
Lines changed: 214 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,214 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""Reusable audio encoder/projectors used by GGUF ``clip`` sidecars."""
5+
6+
from __future__ import annotations
7+
8+
import onnx_ir as ir
9+
from onnxscript import OpBuilder, nn
10+
11+
from mobius.components._activations import get_activation
12+
from mobius.components._common import LayerNorm, Linear
13+
from mobius.components._whisper import Conv1d, WhisperEncoderLayer
14+
15+
16+
class GGUFWhisperAudioTower(nn.Module):
17+
"""Whisper encoder stored by llama.cpp audio-projector sidecars.
18+
19+
The processor boundary is a log-mel tensor ``[B, n_mels, frames]``.
20+
Qwen2-Audio enables the final two-frame average pool; legacy GLM-ASR
21+
leaves the post-convolution sequence unpooled before its own frame stack.
22+
"""
23+
24+
def __init__(
25+
self,
26+
*,
27+
num_mel_bins: int,
28+
hidden_size: int,
29+
intermediate_size: int,
30+
num_hidden_layers: int,
31+
num_attention_heads: int,
32+
max_source_positions: int,
33+
norm_eps: float,
34+
average_pool: bool,
35+
) -> None:
36+
super().__init__()
37+
self.conv1 = Conv1d(num_mel_bins, hidden_size, kernel_size=3, padding=1)
38+
self.conv2 = Conv1d(hidden_size, hidden_size, kernel_size=3, stride=2, padding=1)
39+
self.position_embeddings = nn.Parameter([max_source_positions, hidden_size])
40+
self.layers = nn.ModuleList(
41+
[
42+
WhisperEncoderLayer(
43+
hidden_size,
44+
num_attention_heads,
45+
intermediate_size,
46+
activation="gelu",
47+
eps=norm_eps,
48+
)
49+
for _ in range(num_hidden_layers)
50+
]
51+
)
52+
self.post_layernorm = LayerNorm(hidden_size, eps=norm_eps)
53+
self._average_pool = average_pool
54+
55+
def forward(self, op: OpBuilder, input_features: ir.Value) -> ir.Value:
56+
input_features = op.CastLike(input_features, self.conv1.weight)
57+
hidden_states = op.Gelu(self.conv1(op, input_features), approximate="none")
58+
hidden_states = op.Gelu(self.conv2(op, hidden_states), approximate="none")
59+
hidden_states = op.Transpose(hidden_states, perm=[0, 2, 1])
60+
# [B, ceil(frames / 2), hidden]
61+
62+
sequence_length = op.Shape(hidden_states, start=1, end=2)
63+
positions = op.Slice(
64+
self.position_embeddings,
65+
op.Constant(value_ints=[0]),
66+
sequence_length,
67+
op.Constant(value_ints=[0]),
68+
)
69+
hidden_states = op.Add(hidden_states, op.CastLike(positions, hidden_states))
70+
for layer in self.layers:
71+
hidden_states = layer(op, hidden_states)
72+
73+
if self._average_pool:
74+
hidden_states = op.Transpose(hidden_states, perm=[0, 2, 1])
75+
hidden_states = op.AveragePool(
76+
hidden_states,
77+
kernel_shape=[2],
78+
strides=[2],
79+
)
80+
hidden_states = op.Transpose(hidden_states, perm=[0, 2, 1])
81+
# [B, floor(ceil(frames / 2) / 2), hidden]
82+
return self.post_layernorm(op, hidden_states)
83+
84+
85+
class GGUFQwen2AudioProjector(nn.Module):
86+
"""Qwen2-Audio Whisper tower followed by one text-width affine projection."""
87+
88+
def __init__(
89+
self,
90+
*,
91+
num_mel_bins: int,
92+
hidden_size: int,
93+
intermediate_size: int,
94+
num_hidden_layers: int,
95+
num_attention_heads: int,
96+
max_source_positions: int,
97+
output_size: int,
98+
norm_eps: float = 1e-5,
99+
) -> None:
100+
super().__init__()
101+
self.audio_tower = GGUFWhisperAudioTower(
102+
num_mel_bins=num_mel_bins,
103+
hidden_size=hidden_size,
104+
intermediate_size=intermediate_size,
105+
num_hidden_layers=num_hidden_layers,
106+
num_attention_heads=num_attention_heads,
107+
max_source_positions=max_source_positions,
108+
norm_eps=norm_eps,
109+
average_pool=True,
110+
)
111+
self.projection = Linear(hidden_size, output_size, bias=True)
112+
self.input_schema = (
113+
(
114+
"input_features",
115+
ir.DataType.FLOAT,
116+
(1, num_mel_bins, 2 * max_source_positions),
117+
),
118+
)
119+
120+
def forward(self, op: OpBuilder, input_features: ir.Value) -> ir.Value:
121+
projected = self.projection(op, self.audio_tower(op, input_features))
122+
return op.Squeeze(projected, [0])
123+
124+
125+
class GGUFLegacyGlmAudioProjector(nn.Module):
126+
"""Legacy llama.cpp GLMA Whisper tower and boundary-token projector.
127+
128+
This component documents and tests the serialized graph. The current
129+
GLM-ASR checkpoint instead uses partial RoPE and cannot be converted into
130+
this legacy topology, so registry dispatch remains fail-closed.
131+
"""
132+
133+
def __init__(
134+
self,
135+
*,
136+
num_mel_bins: int,
137+
hidden_size: int,
138+
intermediate_size: int,
139+
num_hidden_layers: int,
140+
num_attention_heads: int,
141+
max_source_positions: int,
142+
stack_factor: int,
143+
projector_intermediate_size: int,
144+
output_size: int,
145+
norm_eps: float = 1e-5,
146+
activation: str = "gelu",
147+
) -> None:
148+
super().__init__()
149+
if stack_factor <= 0:
150+
raise ValueError("GLMA stack factor must be positive")
151+
self.audio_tower = GGUFWhisperAudioTower(
152+
num_mel_bins=num_mel_bins,
153+
hidden_size=hidden_size,
154+
intermediate_size=intermediate_size,
155+
num_hidden_layers=num_hidden_layers,
156+
num_attention_heads=num_attention_heads,
157+
max_source_positions=max_source_positions,
158+
norm_eps=norm_eps,
159+
average_pool=False,
160+
)
161+
self.pre_projector_norm = LayerNorm(hidden_size, eps=norm_eps)
162+
self.linear_1 = Linear(
163+
hidden_size * stack_factor,
164+
projector_intermediate_size,
165+
bias=True,
166+
)
167+
self.linear_2 = Linear(projector_intermediate_size, output_size, bias=True)
168+
self.boi = nn.Parameter([output_size])
169+
self.eoi = nn.Parameter([output_size])
170+
self._activation = get_activation(activation)
171+
self._stack_factor = stack_factor
172+
self._hidden_size = hidden_size
173+
self._output_size = output_size
174+
self.input_schema = (
175+
(
176+
"input_features",
177+
ir.DataType.FLOAT,
178+
(1, num_mel_bins, 2 * max_source_positions),
179+
),
180+
)
181+
182+
def _stack_frames(self, op: OpBuilder, hidden_states: ir.Value) -> ir.Value:
183+
sequence_length = op.Squeeze(op.Shape(hidden_states, start=1, end=2), [0])
184+
factor = op.Constant(value_int=self._stack_factor)
185+
remainder = op.Mod(sequence_length, factor)
186+
pad_length = op.Mod(op.Sub(factor, remainder), factor)
187+
pads = op.Concat(
188+
op.Constant(value_ints=[0, 0, 0, 0]),
189+
op.Reshape(pad_length, [1]),
190+
op.Constant(value_ints=[0]),
191+
axis=0,
192+
)
193+
hidden_states = op.Pad(hidden_states, pads)
194+
return op.Reshape(
195+
hidden_states,
196+
[0, -1, self._hidden_size * self._stack_factor],
197+
)
198+
199+
def forward(self, op: OpBuilder, input_features: ir.Value) -> ir.Value:
200+
hidden_states = self.pre_projector_norm(
201+
op,
202+
self.audio_tower(op, input_features),
203+
)
204+
hidden_states = self._stack_frames(op, hidden_states)
205+
hidden_states = self.linear_2(
206+
op,
207+
self._activation(op, self.linear_1(op, hidden_states)),
208+
)
209+
210+
batch = op.Shape(hidden_states, start=0, end=1)
211+
boundary_shape = op.Concat(batch, [1, self._output_size], axis=0)
212+
boi = op.Expand(op.Reshape(self.boi, [1, 1, self._output_size]), boundary_shape)
213+
eoi = op.Expand(op.Reshape(self.eoi, [1, 1, self._output_size]), boundary_shape)
214+
return op.Squeeze(op.Concat(boi, hidden_states, eoi, axis=1), [0])

0 commit comments

Comments
 (0)