Skip to content

Commit 79b48bc

Browse files
justinchubyCopilotCopilot
authored
Add GLM-ASR Nano speech-language support (#509)
## Summary - Add complete `glmasr` support for `zai-org/GLM-ASR-Nano-2512` as standardized `audio_encoder` → `embedding` → cached `decoder` ONNX models. - Implement the convolutional 32-layer bidirectional partial-RoPE audio tower, config-driven audio/projector activations, four-frame projector, audio-token embedding replacement, and 28-layer Llama-like decoder with dynamic KV cache. - Add exact checkpoint weight alignment, registry/config/task exports, ONNX GenAI metadata, immutable CLI `--revision` propagation, and documentation metadata. - Add a pinned real nonzero speech fixture plus exact L4 prefill and L5 transcript/token goldens. ## Immutable inputs - Model: `zai-org/GLM-ASR-Nano-2512@61ba4e0b3309b6656edea3e93e419f7bd5c61957` - Audio: `eustlb/audio-samples@1045238c3afdc0254472ecdde5dae95370d621e4` - All config, weight, tokenizer, processor, metadata, golden-generation, and test Hub calls carry the immutable revision. ## Architecture checklist - [x] Nested GLM-ASR text/audio config extraction - [x] Registry and default speech-language task wiring - [x] Standardized `audio_encoder`, `embedding`, and `decoder` package keys - [x] Whisper feature-extractor contract: float32 `[B,128,3000]`, 16 kHz, FFT 400, hop 160 - [x] 20-head bidirectional audio Attention with 32/64 partial RoPE, asymmetric Q/V/O biases, and one output (no unused present KV) - [x] Config-driven audio MLP and projector activations - [x] Four-frame `5120 → 4096 → 2048` projector - [x] Exact audio-placeholder replacement and valid projected-feature stripping inside ONNX - [x] Llama decoder with 16 query heads, 4 KV heads, full RoPE, and cached decode - [x] All 745 checkpoint parameter names aligned after preprocessing - [x] ONNX GenAI speech-language metadata includes the pinned audio processor ## Validation evidence ### L1–L3 and regression gates - GLM-ASR graph/config/parity and rebase regression suite: **46 passed** - ORT GenAI compatibility guard tests: **2 passed** - Complete CLI suite: **37 passed** - Synthetic FP32 HF/ONNX parity executes the complete audio → embedding → decoder pipeline and compares every stage, including short-audio zero-token behavior. - Standard non-integration gate: **4051 passed, 58 skipped, 10 deselected**. Five unrelated environment-sensitive failures remain in GGUF Q4 dequantization, Qwen Image CUDA tolerance, and softcap Attention-decomposition parity; none overlap this change set or the required CI failures previously reported. ### L4 CUDA prefill (rebased head) ```powershell $env:MOBIUS_TEST_DEVICE='cuda' python -m pytest tests/e2e_golden_test.py -m golden --models glmasr -v --timeout=300 --tb=short ``` - **1 passed, 240 skipped, 161 deselected in 166.73s** - Real pinned speech, 138 projected audio tokens, 153-token prompt. - FP16 full-logit reference comparison: shape `[1,153,59264]`, correlation `0.9991001`, mean absolute difference `0.02795`, maximum absolute difference `7.456`; greedy token matches. ### L5 CUDA cached generation (rebased head) ```powershell $env:MOBIUS_TEST_DEVICE='cuda' python -m pytest tests/e2e_golden_test.py -m generation --models glmasr -v --timeout=300 --tb=short ``` - **1 passed, 156 skipped, 245 deselected in 238.19s** - Exact 23-token sequence and exact decoded transcript asserted: - `Yesterday it was thirty five degrees in Barcelona, but today the temperature will go down to minus twenty degrees.` ### CLI export and CUDA execution ```powershell python -m mobius build --model zai-org/GLM-ASR-Nano-2512 <output> \ --revision 61ba4e0b3309b6656edea3e93e419f7bd5c61957 \ --ep cuda --dtype f16 ``` - Direct three-model ONNX export and saved-file CUDA execution pass: - audio `(138, 2048)` - embeddings `(1, 153, 2048)` - logits `(1, 153, 59264)` - prefill top-1 token `89` - The staged test harness now destroys each ORT session before loading the next component. This fixes the old CI `BFCArena` initialization OOM (`242745344`-byte decoder allocation) and returns CUDA memory to baseline between stages. ### Formatting and review - `lintrunner -a`: **passed** - Final specialist re-review: **no high-confidence findings** - All inline review threads are addressed and resolved. ## Waivers and runtime constraints - **FP32:** complete synthetic stage-by-stage semantic parity passes at `rtol=2e-4`, `atol=2e-4` for decoder logits and tighter tolerances for earlier stages. A full real FP32 CUDA checkpoint run is not practical on the available 8 GB RTX A1000. - **FP16:** full real-checkpoint CUDA L4/L5 and saved CLI artifact execution pass as documented above. - **BF16:** the weighted package builds and loads on CUDA. ORT 1.26 Python's NumPy API cannot materialize BF16 outputs (`No corresponding Numpy type for Tensor Type. bfloat16`), so executable L4/L5 uses FP16; BF16 output validation requires I/O binding or a runtime with BF16 host materialization. - **GQA fusion:** CUDA FP16 `GroupQueryAttention` changed greedy termination from the exact 23-token HF sequence to an earlier valid EOS at 21 tokens. GLM-ASR intentionally preserves standard opset-24 `Attention` for exact transcript parity; graph coverage locks this dispatch decision. - **ORT GenAI:** onnxruntime-genai 0.15.2 registers multimodal model types only for `gemma4` and `phi4mm`; loading `type: glmasr` fails as unsupported. Mobius now rejects `--runtime ort-genai` before saving rather than emitting unloadable metadata. Direct ONNX and ONNX GenAI metadata remain supported; native ORT GenAI packaging is deferred until the runtime registers a compatible GLM-ASR pipeline. - **Memcpy:** ORT reports small control-tensor Memcpy nodes from dynamic shape/index operations (`NonZero`, integer `CumSum`, and placeholder indexing). Eliminating them would require changing the feature-stripping/embedding contract. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]> Co-authored-by: copilot-swe-agent <[email protected]> Co-authored-by: justinchuby <[email protected]>
1 parent b2b8213 commit 79b48bc

33 files changed

Lines changed: 1856 additions & 93 deletions

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ multi-component export for pipelines.
3232
| **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 |
35-
| **Speech-to-Text** | Whisper, Moonshine, FastConformer-RNNT, FunASR, Qwen3-ASR, SenseVoice |
35+
| **Speech-to-Text** | Whisper, Moonshine, FastConformer-RNNT, FunASR, GLM-ASR, Qwen3-ASR, SenseVoice |
3636
| **Audio** | Wav2Vec2, HuBERT, WavLM, SpeechT5 |
3737
| **Vision** | ViT, BEiT, DeiT, DINOv2, Swin, CLIP, SigLIP |
3838
| **Diffusion** | Stable Diffusion (UNet + VAE + ControlNet), Flux, SD3, DiT, QwenImage / Qwen-Image-Edit-2509, HunyuanDiT, CogVideoX |

‎docs/cli_reference.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ mobius build --model meta-llama/Llama-3.2-1B output/ \
236236
|--------|-------------|
237237
| `--task TASK` | Model task (auto-detected if not specified). Use `mobius list tasks` to see available tasks. |
238238
| `--dtype DTYPE` | Target dtype for model weights: `f16`, `bf16`, `f32` (also accepts `float16`, `bfloat16`, `float32`). If omitted, the dtype is auto-detected from the HuggingFace config (`torch_dtype`); provide `--dtype` to override it. Weights are cast at save time. |
239+
| `--revision REVISION` | Immutable HuggingFace revision used consistently for config, weights, tokenizer, processor, and runtime metadata artifacts. |
239240
| `--no-weights` | Export graph structure only, without weight data. Useful for inspection or testing. |
240241
| `--external-data FORMAT` | External data format: `onnx` (default) or `safetensors`. |
241242
| `--max-shard-size SIZE` | Maximum shard size for safetensors external data (e.g. `5GB`). Only used with `--external-data safetensors`. |

‎scripts/generate_golden.py‎

Lines changed: 50 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -704,7 +704,7 @@ def _generate_speech_to_text(case: TestCase, json_path: Path, device: str) -> No
704704
**processed,
705705
decoder_input_ids=decoder_input_ids,
706706
)
707-
last_logits = outputs.logits[0, -1, :].cpu().numpy()
707+
last_logits = outputs.logits[0, -1, :].float().cpu().numpy()
708708
golden = _extract_logits_golden(last_logits)
709709
input_ids_np = decoder_input_ids.cpu().numpy()
710710

@@ -800,7 +800,8 @@ def _generate_speech_language(case: TestCase, json_path: Path, device: str) -> N
800800
with torch.no_grad():
801801
outputs = forward_model(**processed)
802802

803-
last_logits = outputs.logits[0, -1, :].cpu().numpy()
803+
# NumPy does not expose bfloat16; store reference logits as float32.
804+
last_logits = outputs.logits[0, -1, :].float().cpu().numpy()
804805
golden = _extract_logits_golden(last_logits)
805806
input_ids_np = processed["input_ids"].cpu().numpy()
806807

@@ -856,7 +857,9 @@ def _load_speech_language_model(case: TestCase, device: str) -> tuple:
856857
_try_register_qwen3_asr()
857858

858859
config = transformers.AutoConfig.from_pretrained(
859-
case.model_id, trust_remote_code=case.trust_remote_code
860+
case.model_id,
861+
revision=case.revision,
862+
trust_remote_code=case.trust_remote_code,
860863
)
861864
model_type = getattr(config, "model_type", "")
862865

@@ -867,19 +870,50 @@ def _load_speech_language_model(case: TestCase, device: str) -> tuple:
867870

868871
if device == "auto":
869872
model = Qwen3ASRForConditionalGeneration.from_pretrained(
870-
case.model_id, torch_dtype=torch.float32, device_map=device
873+
case.model_id,
874+
revision=case.revision,
875+
torch_dtype=torch.float32,
876+
device_map=device,
871877
)
872878
else:
873879
model = Qwen3ASRForConditionalGeneration.from_pretrained(
874-
case.model_id, torch_dtype=torch.float32
880+
case.model_id,
881+
revision=case.revision,
882+
torch_dtype=torch.float32,
875883
)
876884
model = model.to(device)
877885
model.eval()
878886
processor = transformers.AutoProcessor.from_pretrained(
879-
case.model_id, trust_remote_code=True
887+
case.model_id,
888+
revision=case.revision,
889+
trust_remote_code=True,
880890
)
881891
# Qwen3-ASR wraps a thinker; the thinker produces logits.
882892
forward_model = model.thinker
893+
elif model_type == "glmasr":
894+
dtype = {
895+
"float16": torch.float16,
896+
"bfloat16": torch.bfloat16,
897+
"float32": torch.float32,
898+
}.get(case.dtype, torch.float32)
899+
if device == "cpu" and dtype != torch.float32:
900+
dtype = torch.float32
901+
model = transformers.GlmAsrForConditionalGeneration.from_pretrained(
902+
case.model_id,
903+
revision=case.revision,
904+
dtype=dtype,
905+
)
906+
if device == "auto":
907+
model = model.cuda()
908+
else:
909+
model = model.to(device)
910+
model.eval()
911+
processor = transformers.AutoProcessor.from_pretrained(
912+
case.model_id,
913+
revision=case.revision,
914+
trust_remote_code=case.trust_remote_code,
915+
)
916+
forward_model = model
883917
else:
884918
# Gemma4-style: AutoModelForImageTextToText
885919
from mobius._testing.torch_reference import (
@@ -913,8 +947,17 @@ def _prepare_speech_language_inputs(
913947
# Detect Qwen3-ASR by processor class name (avoids redundant
914948
# config download).
915949
is_qwen3_asr = "Qwen3ASR" in type(processor).__name__
950+
is_glmasr = "GlmAsr" in type(processor).__name__
916951

917-
if is_qwen3_asr:
952+
if is_glmasr:
953+
model_device = _get_model_device(model, device)
954+
processed = processor.apply_transcription_request(
955+
audio_array,
956+
prompt=case.prompts[0] if case.prompts else None,
957+
return_tensors="pt",
958+
).to(model_device, dtype=model.dtype)
959+
prompt_for_golden = case.prompts[0] if case.prompts else str(audio_path)
960+
elif is_qwen3_asr:
918961
# Qwen3-ASR prompt: system + user with audio placeholder
919962
messages = [
920963
{"role": "system", "content": ""},

‎src/mobius/__main__.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -442,18 +442,28 @@ def _save_package(
442442

443443
config = getattr(pkg, "config", None)
444444
source = getattr(args, "config", None) or getattr(args, "model", None)
445+
revision_kwargs = (
446+
{"revision": args.revision} if getattr(args, "revision", None) is not None else {}
447+
)
445448
if is_native_vlm_package(pkg):
446449
try:
447450
artifacts = write_native_vlm_package_metadata(
448451
pkg,
449452
output_dir,
450453
config=config,
451454
source=source,
455+
**revision_kwargs,
452456
)
453457
except ValueError as error:
454458
raise SystemExit(f"Error: {error}") from error
455459
else:
456-
artifacts = write_onnx_genai_config(pkg, output_dir, config=config, source=source)
460+
artifacts = write_onnx_genai_config(
461+
pkg,
462+
output_dir,
463+
config=config,
464+
source=source,
465+
**revision_kwargs,
466+
)
457467
for name, path in artifacts.items():
458468
print(f" {name}: {path}")
459469

‎src/mobius/_configs/__init__.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
Gemma3nMultiModalConfig,
3737
Gemma4AssistantConfig,
3838
Gemma4Config,
39+
GlmAsrConfig,
3940
GraniteMoeHybridConfig,
4041
JambaConfig,
4142
JetMoeConfig,
@@ -109,6 +110,7 @@
109110
"Gemma3nMultiModalConfig",
110111
"Gemma4AudioConfig",
111112
"Gemma4Config",
113+
"GlmAsrConfig",
112114
"GraniteMoeHybridConfig",
113115
"JambaConfig",
114116
"JetMoeConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2787,6 +2787,34 @@ def from_transformers(cls, config, parent_config=None) -> JetMoeConfig:
27872787
return cls(**base_fields)
27882788

27892789

2790+
@dataclasses.dataclass
2791+
class GlmAsrConfig(CausalLMConfig):
2792+
"""Configuration for GLM-ASR audio-language models."""
2793+
2794+
projector_hidden_act: str = "gelu"
2795+
2796+
@classmethod
2797+
def from_transformers(cls, config, parent_config=None) -> GlmAsrConfig:
2798+
composite = parent_config or config
2799+
text_config = getattr(composite, "text_config", None) or config
2800+
base = ArchitectureConfig.from_transformers(text_config, parent_config=composite)
2801+
fields = _shallow_fields(base)
2802+
fields.update(
2803+
model_type=getattr(composite, "model_type", "glmasr"),
2804+
audio_token_id=getattr(composite, "audio_token_id", base.audio_token_id),
2805+
tie_word_embeddings=getattr(
2806+
composite, "tie_word_embeddings", base.tie_word_embeddings
2807+
),
2808+
)
2809+
resolved_dtype = _resolve_dtype(composite)
2810+
if resolved_dtype is not None:
2811+
fields["dtype"] = resolved_dtype
2812+
return cls(
2813+
**fields,
2814+
projector_hidden_act=getattr(composite, "projector_hidden_act", "gelu"),
2815+
)
2816+
2817+
27902818
@dataclasses.dataclass
27912819
class SpeechToTextConfig(ArchitectureConfig):
27922820
"""Shared configuration contract for encoder-decoder speech models."""

‎src/mobius/_configs/_sub_configs.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,11 @@ class AudioConfig:
226226
encoder_layers: int | None = None
227227
encoder_attention_heads: int | None = None
228228
encoder_ffn_dim: int | None = None
229+
encoder_head_dim: int | None = None
230+
encoder_num_key_value_heads: int | None = None
231+
encoder_partial_rotary_factor: float | None = None
232+
encoder_rope_theta: float | None = None
233+
encoder_layer_norm_eps: float | None = None
229234
num_mel_bins: int | None = None
230235
max_source_positions: int | None = None
231236
downsample_hidden_size: int | None = None

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
_gemma4_audio,
3030
_gemma4_unified_audio,
3131
_gemma4_unified_vision,
32+
_glmasr_audio,
3233
_hunyuan_vl_mot_vision,
3334
_internvl_vision,
3435
_lfm2_vl_vision,
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Copyright (c) Microsoft Corporation.
2+
# Licensed under the MIT License.
3+
4+
"""GLM-ASR audio encoder config extraction."""
5+
6+
from __future__ import annotations
7+
8+
from mobius._configs._extractors import register_audio_hook
9+
10+
11+
@register_audio_hook
12+
def _glmasr_audio(config, parent_config, model_type: str, fields: dict):
13+
composite = parent_config or config
14+
if getattr(composite, "model_type", None) != "glmasr":
15+
return None
16+
17+
audio_config = getattr(composite, "audio_config", None)
18+
if audio_config is None:
19+
return None
20+
if isinstance(audio_config, dict):
21+
audio_config = type("GlmAsrAudioConfig", (), audio_config)()
22+
23+
rope_parameters = getattr(audio_config, "rope_parameters", None) or {}
24+
fields.update(
25+
d_model=getattr(audio_config, "hidden_size", None),
26+
encoder_layers=getattr(audio_config, "num_hidden_layers", None),
27+
encoder_attention_heads=getattr(audio_config, "num_attention_heads", None),
28+
encoder_num_key_value_heads=getattr(
29+
audio_config,
30+
"num_key_value_heads",
31+
getattr(audio_config, "num_attention_heads", None),
32+
),
33+
encoder_head_dim=getattr(audio_config, "head_dim", None),
34+
encoder_ffn_dim=getattr(audio_config, "intermediate_size", None),
35+
encoder_partial_rotary_factor=getattr(
36+
audio_config,
37+
"partial_rotary_factor",
38+
rope_parameters.get("partial_rotary_factor", 0.5),
39+
),
40+
encoder_rope_theta=rope_parameters.get("rope_theta", 10_000.0),
41+
encoder_layer_norm_eps=getattr(audio_config, "layer_norm_eps", 1e-5),
42+
num_mel_bins=getattr(audio_config, "num_mel_bins", None),
43+
max_source_positions=getattr(audio_config, "max_position_embeddings", None),
44+
activation_function=getattr(audio_config, "hidden_act", "gelu"),
45+
audio_token_id=getattr(composite, "audio_token_id", None),
46+
output_dim=getattr(getattr(composite, "text_config", None), "hidden_size", None),
47+
)
48+
return None

‎src/mobius/_configs_test.py‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
DEFAULT_INT,
1616
ArchitectureConfig,
1717
AudioConfig,
18+
GlmAsrConfig,
1819
MuseGlimmerConfig,
1920
QuantizationConfig,
2021
VisionConfig,
@@ -754,6 +755,62 @@ class Cfg:
754755
assert result["audio"].encoder_layers == 32
755756
assert result["audio"].audio_token_id == 151646
756757

758+
def test_glmasr_nested_config(self):
759+
"""GLM-ASR unwraps its Llama text config and preserves audio metadata."""
760+
text_config = SimpleNamespace(
761+
model_type="llama",
762+
vocab_size=59264,
763+
hidden_size=2048,
764+
intermediate_size=6144,
765+
num_hidden_layers=28,
766+
num_attention_heads=16,
767+
num_key_value_heads=4,
768+
head_dim=128,
769+
hidden_act="silu",
770+
max_position_embeddings=32768,
771+
rms_norm_eps=1e-5,
772+
rope_parameters={"rope_type": "default", "rope_theta": 500000.0},
773+
tie_word_embeddings=True,
774+
pad_token_id=59263,
775+
)
776+
audio_config = SimpleNamespace(
777+
hidden_size=1280,
778+
intermediate_size=5120,
779+
num_hidden_layers=32,
780+
num_attention_heads=20,
781+
num_key_value_heads=20,
782+
head_dim=64,
783+
partial_rotary_factor=0.5,
784+
rope_parameters={"rope_type": "default", "rope_theta": 10000.0},
785+
layer_norm_eps=1e-5,
786+
num_mel_bins=128,
787+
max_position_embeddings=1500,
788+
hidden_act="gelu",
789+
)
790+
parent = SimpleNamespace(
791+
model_type="glmasr",
792+
text_config=text_config,
793+
audio_config=audio_config,
794+
audio_token_id=59260,
795+
projector_hidden_act="gelu",
796+
tie_word_embeddings=True,
797+
dtype="bfloat16",
798+
)
799+
800+
config = GlmAsrConfig.from_transformers(parent)
801+
802+
assert config.model_type == "glmasr"
803+
assert config.hidden_size == 2048
804+
assert config.num_hidden_layers == 28
805+
assert config.num_key_value_heads == 4
806+
assert config.audio_token_id == 59260
807+
assert config.audio is not None
808+
assert config.audio.d_model == 1280
809+
assert config.audio.encoder_head_dim == 64
810+
assert config.audio.encoder_partial_rotary_factor == pytest.approx(0.5)
811+
assert config.audio.encoder_rope_theta == pytest.approx(10000.0)
812+
assert config.audio.output_dim == 2048
813+
757814
def test_phi4mm_audio_token_id(self):
758815
"""phi4mm extracts audio_token_id from audio_config attr."""
759816

0 commit comments

Comments
 (0)