Skip to content

Commit ed0319d

Browse files
justinchubyCopilot
andauthored
Add Moonshine speech recognition support (#463)
## Summary - add native `moonshine` support for `moonshine-ai/moonshine-tiny` without aliasing it to Whisper - implement the raw-waveform convolution encoder, GroupNorm, partial interleaved RoPE, bias-free encoder/decoder attention, gated decoder MLP, cross-attention masking, tied output projection, and cached decoding - generalize `SpeechToTextTask` while preserving Whisper, including correct 80/128 `num_mel_bins` input-channel handling - export tokenizer, `audio_processor.json`, and composite onnx-genai metadata - add L1 graph/config/alignment, L2 real-config, L3 synthetic/real-weight parity, and real-audio L4/L5 goldens ## Updated from main Rebased onto `origin/main` at `1e6f61f42b0ddbc90f60bccbf00eff26cd484256`, including main's fused Swish support. Moonshine now uses the public `SiLU` component and emits one ONNX `Swish` op per decoder layer instead of `Sigmoid + Mul`. ## Fusion and optimized-graph audit Audited fp16 opset-24 graphs with ONNX Runtime GPU 1.28.0 on CUDA EP; `CUDAExecutionProvider` was asserted first for encoder and decoder. | Graph | Mobius nodes | ORT-optimized nodes | Key optimized ops | Identity | Unused initializers | Memcpy | |---|---:|---:|---|---:|---:|---:| | encoder | 115 | 131 | 6 Attention, 6 BiasGelu, 12 SkipLayerNormalization | 0 | 0 | 0 | | decoder | 151 | 151 | 12 Attention, 6 QuickGelu(alpha=1.0), 18 SkipLayerNormalization | 0 | 0 | 0 | Additional structural evidence: - Mobius decoder graph: 6 `Swish`, 0 `Sigmoid` - ORT folds each Swish to `QuickGelu(alpha=1.0)` - encoder GroupNormalization is optimized without CPU fallback - only one encoder transpose remains, required for Conv1d `[B,C,T]` to transformer `[B,T,C]` - no protobuf construction APIs - no opset-lowering workaround needed on ORT 1.28 The standard ONNX `Attention` op is intentional: encoder and cross-attention require explicit padding bias, which contrib GQA rejects, and Moonshine's head dimension 36 is not XQA-eligible. ## Validation ### CPU and CUDA parity Environment: NVIDIA RTX A1000, driver 573.44, CUDA 12.8, ONNX Runtime GPU 1.28.0. Real `652-129742-0006.flac`, fp32: | Boundary | Max abs diff | Mean abs diff | Result | |---|---:|---:|---| | encoder hidden states | 0.0045447 | 0.0001437 | finite; masks exact | | decoder prefill logits | 0.0098586 | 0.0011758 | finite; identical argmax 29892 | | greedy transcription | exact | exact | CPU == CUDA == 32-token golden | ### Dtype coverage - fp16 CUDA: finite encoder/decoder state and exact 32/32 fp32-golden transcription tokens - bf16 CUDA: finite state and exact Hugging Face bf16 CUDA generation tokens; bf16 output differs from fp32 at the expected near-tie prefix ### Test commands/results - `python -m pytest tests/build_graph_test.py -k "moonshine or whisper" -q`: 17 passed - `python -m pytest tests/moonshine_integration_test.py -q`: 5 passed - speech config/alignment/parity selection: 18 passed - CUDA `tests/e2e_golden_test.py -m "golden or generation" -k moonshine`: 2 passed - fusion/task/export selection: 13 passed - YAML schema + model coverage: 945 passed, 215 skipped - `lintrunner -a`: no lint issues - automated review findings resolved, including explicit Whisper 128-mel config/graph regression coverage ## Checklist / waivers - [x] L1 graph construction and weight alignment - [x] L2 real Hugging Face config build - [x] L3 synthetic and real-weight encoder/decoder/cache parity - [x] L4 real-audio logits golden on CPU and CUDA - [x] L5 deterministic transcription golden on CPU and CUDA - [x] fp32/fp16/bf16 CUDA validation - [x] CLI export, processor/tokenizer wiring, runtime load, and generation - [x] ORT 1.28 optimized-graph and fusion audit with zero Memcpy - [x] full `lintrunner -a`, schema, coverage, and targeted regressions **Waivers:** - **Native onnxruntime-genai:** upstream's audio-language runtime is Whisper-specific and hardcodes 3000 input / 1500 encoder frames plus Whisper alignment tensors. Moonshine uses variable-length raw waveforms, so this PR explicitly rejects falsely mapping it to Whisper and validates onnx-genai metadata plus direct ONNX Runtime CUDA generation instead. - **Foundry Local:** not installed in this environment. - **Olive quantization:** Olive is 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 1e6f61f commit ed0319d

26 files changed

Lines changed: 1417 additions & 58 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, 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, FastConformer-RNNT, FunASR, Qwen3-ASR, SenseVoice |
35+
| **Speech-to-Text** | Whisper, Moonshine, FastConformer-RNNT, FunASR, 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, HunyuanDiT, CogVideoX |

‎scripts/generate_golden.py‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -620,16 +620,22 @@ def _generate_image_to_text(case: TestCase, json_path: Path, device: str) -> Non
620620

621621

622622
def _generate_speech_to_text(case: TestCase, json_path: Path, device: str) -> None:
623-
"""Generate golden data for a speech-to-text (Whisper) model."""
623+
"""Generate golden data for an encoder-decoder speech recognition model."""
624624
import librosa
625625
import torch
626+
import transformers
626627

627628
from mobius._testing.golden import save_generation_json, save_golden_ref
628-
from mobius._testing.torch_reference import (
629-
load_torch_whisper_model,
630-
)
631629

632-
model, processor = load_torch_whisper_model(case.model_id, device=device)
630+
model = transformers.AutoModelForSpeechSeq2Seq.from_pretrained(
631+
case.model_id,
632+
device_map=device,
633+
trust_remote_code=case.trust_remote_code,
634+
)
635+
model.eval()
636+
processor = transformers.AutoProcessor.from_pretrained(
637+
case.model_id, trust_remote_code=case.trust_remote_code
638+
)
633639

634640
# Load and preprocess audio
635641
audio_path = Path("testdata") / case.audio[0]
@@ -638,8 +644,6 @@ def _generate_speech_to_text(case: TestCase, json_path: Path, device: str) -> No
638644
processed = processor(audio_array, sampling_rate=sample_rate, return_tensors="pt").to(
639645
model_device
640646
)
641-
input_features = processed["input_features"]
642-
643647
# L4: single decoder step with forced decoder start token
644648
decoder_start_id = (
645649
model.config.decoder_start_token_id or model.generation_config.decoder_start_token_id
@@ -649,7 +653,7 @@ def _generate_speech_to_text(case: TestCase, json_path: Path, device: str) -> No
649653
)
650654
with torch.no_grad():
651655
outputs = model(
652-
input_features=input_features,
656+
**processed,
653657
decoder_input_ids=decoder_input_ids,
654658
)
655659
last_logits = outputs.logits[0, -1, :].cpu().numpy()
@@ -661,11 +665,18 @@ def _generate_speech_to_text(case: TestCase, json_path: Path, device: str) -> No
661665
if "L5" in case.level:
662666
with torch.no_grad():
663667
gen = model.generate(
664-
input_features=input_features,
668+
**processed,
665669
max_new_tokens=case.generation_params.get("max_new_tokens", 50),
666670
do_sample=False,
667671
)
668672
generated_ids = gen[0].cpu().numpy()
673+
# Generic encoder-decoder generation includes the decoder start token,
674+
# while Whisper's specialized generation returns content tokens only.
675+
if len(generated_ids) and generated_ids[0] == decoder_start_id:
676+
generated_ids = generated_ids[1:]
677+
eos_token_id = model.generation_config.eos_token_id
678+
while len(generated_ids) and generated_ids[-1] == eos_token_id:
679+
generated_ids = generated_ids[:-1]
669680

670681
save_golden_ref(
671682
json_path,

‎src/mobius/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"Gemma4Config",
2020
"MambaConfig",
2121
"MllamaConfig",
22+
"MoonshineConfig",
2223
"ModelPackage",
2324
"ModelRegistration",
2425
"ModelRegistry",
@@ -28,6 +29,7 @@
2829
"OPSET_VERSION",
2930
"Sam2Config",
3031
"SegformerConfig",
32+
"SpeechToTextConfig",
3133
"VisionConfig",
3234
"VisionLanguageConfig",
3335
"WhisperConfig",
@@ -76,8 +78,10 @@
7678
MambaConfig,
7779
MllamaConfig,
7880
MMSConfig,
81+
MoonshineConfig,
7982
Sam2Config,
8083
SegformerConfig,
84+
SpeechToTextConfig,
8185
VisionConfig,
8286
VisionLanguageConfig,
8387
WhisperConfig,

‎src/mobius/_config_resolver_test.py‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
)
1515
from mobius._configs import (
1616
ArchitectureConfig,
17+
MoonshineConfig,
1718
WhisperConfig,
1819
)
1920

@@ -408,10 +409,16 @@ def test_whisper_speech_specific_fields(self):
408409
hf = self._whisper_hf_config()
409410
result = _config_from_hf(hf)
410411
assert result.num_mel_bins == 80
412+
assert result.encoder_input_channels == 80
411413
assert result.max_source_positions == 1500
412414
assert result.max_target_positions == 448
413415
assert result.decoder_start_token_id == 50258
414416

417+
def test_whisper_128_mel_channels_are_synchronized(self):
418+
result = _config_from_hf(self._whisper_hf_config(num_mel_bins=128))
419+
assert result.num_mel_bins == 128
420+
assert result.encoder_input_channels == 128
421+
415422
def test_whisper_default_task(self):
416423
assert _default_task_for_model("whisper") == "speech-to-text"
417424

@@ -428,6 +435,64 @@ def test_whisper_tie_word_embeddings(self):
428435
assert result.tie_word_embeddings is True
429436

430437

438+
class TestMoonshineEncoderDecoder:
439+
"""Moonshine config extraction preserves its distinct ASR architecture."""
440+
441+
def _moonshine_hf_config(self):
442+
return type(
443+
"FakeMoonshineConfig",
444+
(),
445+
{
446+
"model_type": "moonshine",
447+
"vocab_size": 32768,
448+
"hidden_size": 288,
449+
"intermediate_size": 1152,
450+
"decoder_num_hidden_layers": 6,
451+
"decoder_num_attention_heads": 8,
452+
"decoder_num_key_value_heads": 8,
453+
"encoder_num_hidden_layers": 6,
454+
"encoder_num_attention_heads": 8,
455+
"encoder_num_key_value_heads": 8,
456+
"decoder_hidden_act": "silu",
457+
"encoder_hidden_act": "gelu",
458+
"max_position_embeddings": 194,
459+
"partial_rotary_factor": 0.9,
460+
"rope_scaling": {
461+
"rope_type": "default",
462+
"rope_theta": 10_000.0,
463+
"partial_rotary_factor": 0.9,
464+
},
465+
"attention_bias": False,
466+
"pad_token_id": 2,
467+
"bos_token_id": 1,
468+
"eos_token_id": 2,
469+
"decoder_start_token_id": 1,
470+
"tie_word_embeddings": True,
471+
},
472+
)()
473+
474+
def test_moonshine_routes_to_moonshine_config(self):
475+
result = _config_from_hf(self._moonshine_hf_config())
476+
assert isinstance(result, MoonshineConfig)
477+
assert result.encoder_input_name == "input_values"
478+
assert result.encoder_input_channels is None
479+
assert result.encoder_uses_attention_mask is True
480+
assert result.decoder_uses_encoder_attention_mask is True
481+
482+
def test_moonshine_attention_and_rope_fields(self):
483+
result = _config_from_hf(self._moonshine_hf_config())
484+
assert result.head_dim == 36
485+
assert result.encoder_num_hidden_layers == 6
486+
assert result.encoder_num_attention_heads == 8
487+
assert result.partial_rotary_factor == pytest.approx(0.9)
488+
assert result.rope_interleave is True
489+
assert result.attn_qkv_bias is False
490+
assert result.attn_o_bias is False
491+
492+
def test_moonshine_default_task(self):
493+
assert _default_task_for_model("moonshine") == "speech-to-text"
494+
495+
431496
# ── _dict_to_pretrained_config ──────────────────────────────────────────
432497

433498

‎src/mobius/_configs/__init__.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,13 +45,15 @@
4545
MambaConfig,
4646
MllamaConfig,
4747
MMSConfig,
48+
MoonshineConfig,
4849
MuseGlimmerConfig,
4950
NanoChatConfig,
5051
NemotronHConfig,
5152
NemotronParseConfig,
5253
Qwen35MtpConfig,
5354
Sam2Config,
5455
SegformerConfig,
56+
SpeechToTextConfig,
5557
VisionLanguageConfig,
5658
WhisperConfig,
5759
YolosConfig,
@@ -114,6 +116,7 @@
114116
"MambaConfig",
115117
"MllamaConfig",
116118
"MMSConfig",
119+
"MoonshineConfig",
117120
"MuseGlimmerConfig",
118121
"NanoChatConfig",
119122
"NemotronParseConfig",
@@ -123,6 +126,7 @@
123126
"RoPEConfig",
124127
"Sam2Config",
125128
"SegformerConfig",
129+
"SpeechToTextConfig",
126130
"SpeakerEncoderConfig",
127131
"TTSConfig",
128132
"VisionConfig",

‎src/mobius/_configs/_base.py‎

Lines changed: 99 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2743,7 +2743,19 @@ def from_transformers(cls, config, parent_config=None) -> JetMoeConfig:
27432743

27442744

27452745
@dataclasses.dataclass
2746-
class WhisperConfig(BaseModelConfig):
2746+
class SpeechToTextConfig(ArchitectureConfig):
2747+
"""Shared configuration contract for encoder-decoder speech models."""
2748+
2749+
encoder_input_name: str = "input_features"
2750+
encoder_input_channels: int | None = None
2751+
encoder_uses_attention_mask: bool = False
2752+
decoder_uses_encoder_attention_mask: bool = False
2753+
decoder_start_token_id: int | None = None
2754+
layer_norm_eps: float = 1e-5
2755+
2756+
2757+
@dataclasses.dataclass
2758+
class WhisperConfig(SpeechToTextConfig):
27472759
"""Configuration for Whisper encoder-decoder models."""
27482760

27492761
encoder_layers: int = DEFAULT_INT
@@ -2753,11 +2765,19 @@ class WhisperConfig(BaseModelConfig):
27532765
max_source_positions: int = 1500
27542766
max_target_positions: int = 448
27552767
scale_embedding: bool = False
2756-
decoder_start_token_id: int | None = None
2757-
layer_norm_eps: float = 1e-5
2768+
2769+
def __post_init__(self):
2770+
if self.encoder_input_channels is None:
2771+
self.encoder_input_channels = self.num_mel_bins
2772+
elif self.encoder_input_channels != self.num_mel_bins:
2773+
raise ValueError(
2774+
"WhisperConfig: encoder_input_channels "
2775+
f"({self.encoder_input_channels}) must equal num_mel_bins "
2776+
f"({self.num_mel_bins})."
2777+
)
27582778

27592779
@classmethod
2760-
def from_transformers(cls, config) -> WhisperConfig:
2780+
def from_transformers(cls, config, parent_config=None) -> WhisperConfig:
27612781
if config.model_type != "whisper":
27622782
raise ValueError(
27632783
f"WhisperConfig expects model_type='whisper', got '{config.model_type}'"
@@ -2797,6 +2817,81 @@ def from_transformers(cls, config) -> WhisperConfig:
27972817
return cls(**options)
27982818

27992819

2820+
@dataclasses.dataclass
2821+
class MoonshineConfig(SpeechToTextConfig):
2822+
"""Configuration for Moonshine raw-waveform encoder-decoder ASR models."""
2823+
2824+
encoder_input_name: str = "input_values"
2825+
encoder_input_channels: int | None = None
2826+
encoder_uses_attention_mask: bool = True
2827+
decoder_uses_encoder_attention_mask: bool = True
2828+
encoder_num_hidden_layers: int = DEFAULT_INT
2829+
encoder_num_attention_heads: int = DEFAULT_INT
2830+
encoder_num_key_value_heads: int = DEFAULT_INT
2831+
encoder_hidden_act: str = "gelu"
2832+
decoder_hidden_act: str = "silu"
2833+
2834+
@classmethod
2835+
def from_transformers(cls, config, parent_config=None) -> MoonshineConfig:
2836+
if config.model_type != "moonshine":
2837+
raise ValueError(
2838+
f"MoonshineConfig expects model_type='moonshine', got '{config.model_type}'"
2839+
)
2840+
2841+
hidden_size = config.hidden_size
2842+
decoder_heads = config.decoder_num_attention_heads
2843+
encoder_heads = config.encoder_num_attention_heads
2844+
rope_parameters = getattr(config, "rope_parameters", None) or getattr(
2845+
config, "rope_scaling", None
2846+
)
2847+
rope_type = (rope_parameters or {}).get("rope_type", "default")
2848+
options = dict(
2849+
vocab_size=config.vocab_size,
2850+
hidden_size=hidden_size,
2851+
intermediate_size=config.intermediate_size,
2852+
num_hidden_layers=config.decoder_num_hidden_layers,
2853+
num_attention_heads=decoder_heads,
2854+
num_key_value_heads=getattr(config, "decoder_num_key_value_heads", decoder_heads),
2855+
head_dim=hidden_size // decoder_heads,
2856+
hidden_act=getattr(config, "decoder_hidden_act", "silu"),
2857+
pad_token_id=getattr(config, "pad_token_id", 2),
2858+
tie_word_embeddings=getattr(config, "tie_word_embeddings", True),
2859+
attn_qkv_bias=getattr(config, "attention_bias", False),
2860+
attn_o_bias=getattr(config, "attention_bias", False),
2861+
max_position_embeddings=getattr(config, "max_position_embeddings", 194),
2862+
rope_type=rope_type,
2863+
rope_theta=getattr(
2864+
config,
2865+
"rope_theta",
2866+
(rope_parameters or {}).get("rope_theta", 10_000.0),
2867+
),
2868+
rope_scaling=rope_parameters,
2869+
partial_rotary_factor=getattr(
2870+
config,
2871+
"partial_rotary_factor",
2872+
(rope_parameters or {}).get("partial_rotary_factor", 0.9),
2873+
),
2874+
rope_interleave=True,
2875+
mlp_bias=True,
2876+
encoder_num_hidden_layers=config.encoder_num_hidden_layers,
2877+
encoder_num_attention_heads=encoder_heads,
2878+
encoder_num_key_value_heads=getattr(
2879+
config, "encoder_num_key_value_heads", encoder_heads
2880+
),
2881+
encoder_hidden_act=getattr(config, "encoder_hidden_act", "gelu"),
2882+
decoder_hidden_act=getattr(config, "decoder_hidden_act", "silu"),
2883+
decoder_start_token_id=getattr(config, "decoder_start_token_id", 1),
2884+
layer_norm_eps=getattr(config, "layer_norm_eps", 1e-5),
2885+
model_type="moonshine",
2886+
bos_token_id=getattr(config, "bos_token_id", 1),
2887+
eos_token_id=getattr(config, "eos_token_id", 2),
2888+
)
2889+
resolved = _resolve_dtype(config)
2890+
if resolved is not None:
2891+
options["dtype"] = resolved
2892+
return cls(**options)
2893+
2894+
28002895
@dataclasses.dataclass
28012896
class MMSConfig(ArchitectureConfig):
28022897
"""Configuration for MMS (Massively Multilingual Speech) CTC models.

‎src/mobius/_registry.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
Gemma4Config,
3131
Lfm2Config,
3232
MMSConfig,
33+
MoonshineConfig,
3334
MuseGlimmerConfig,
3435
NemotronParseConfig,
3536
WhisperConfig,
@@ -76,6 +77,7 @@
7677
LLaDAModel,
7778
Llama4CausalLMModel,
7879
MoECausalLMModel,
80+
MoonshineForConditionalGeneration,
7981
NanoChatCausalLMModel,
8082
NemotronCausalLMModel,
8183
NemotronParseForConditionalGeneration,
@@ -681,6 +683,11 @@ def _detect_fallback_registration(hf_config) -> ModelRegistration | None:
681683
task="speech-to-text",
682684
config_class=WhisperConfig,
683685
),
686+
"moonshine": ModelRegistration(
687+
MoonshineForConditionalGeneration,
688+
task="speech-to-text",
689+
config_class=MoonshineConfig,
690+
),
684691
# --- Encoder-only ---
685692
"albert": ModelRegistration(BertModel, task="feature-extraction"),
686693
"bert": ModelRegistration(BertModel, task="feature-extraction"),
@@ -1052,6 +1059,7 @@ def _create_default_registry() -> ModelRegistry:
10521059
"vipllava": "llava-hf/vip-llava-7b-hf",
10531060

10541061
# --- Speech ---
1062+
"moonshine": "moonshine-ai/moonshine-tiny",
10551063
"whisper": "openai/whisper-tiny",
10561064
"qwen3_asr": "Qwen/Qwen3-ASR-0.6B",
10571065
"fun_asr": "justinchuby/Fun-ASR-Nano-2512",

0 commit comments

Comments
 (0)