Skip to content

Qwen3-ASR: feature_attention_mask + chunked conv for HF parity - #264

Merged
justinchuby merged 8 commits into
mainfrom
xiaoyu/qwenasr
May 7, 2026
Merged

justinchuby merged 8 commits into
mainfrom
xiaoyu/qwenasr

Conversation

@xiaoyu-work

Copy link
Copy Markdown
Member

Fixes two bugs in the audio encoder export that caused Qwen3-ASR ONNX outputs to drift on long audio:

  1. feature_attention_mask was missing from the audio encoder graph, so padded mel frames produced finite values that fed the LLM and triggered runaway repetition

    • AudioEncoderLayer / AudioAttention now plumb attention_mask through to op.Attention as the 4th positional arg.
    • _build_audio_encoder declares feature_attention_mask (INT64) as graph input and audio_feature_lengths as output.
    • examples/qwen3_asr.py uses processor with return_attention_mask and crops audio_features by audio_feature_lengths.
  2. The audio encoder used a single-shot conv over the full mel spectrogram (375 tokens / 30s) instead of HF's chunked conv with per-chunk positional embeddings and block-diagonal attention mask (390 tokens / 30s, 100-frame chunks, 13 tokens/chunk, 8-chunk blocks). This caused the 1.7B model to drift on 30s clips

    • AudioConfig gains n_window / n_window_infer fields, derived from the HF config in _extract_audio_config.
    • Qwen3ASRAudioEncoder now reshapes mel into chunks, runs Conv2d batched across (B*num_chunks), broadcasts PE[0:tokens_per_chunk] over chunks, computes per-batch audio_feature_lengths via HF's _get_feat_extract_output_lengths formula, and builds an (B, S, S) block-diagonal attention mask. Empty rows for padded queries are OR'd with the identity matrix to avoid NaN in ORT softmax; padded outputs are cropped by callers.

Validated against HF reference on a 30s Chinese clip: mobius's 1.7B ONNX output now matches HF's reference output near byte-for-byte.

All 1201 build_graph tests pass.

Tests added:

  • test_audio_encoder_attention_uses_mask: every Attention op has 4 inputs with non-null attn_mask.
  • test_3model_pipeline_runs_with_ort updated to feed mask + crop by audio_feature_lengths.

Fixes two bugs in the audio encoder export that caused Qwen3-ASR
ONNX outputs to drift on long audio:

1. feature_attention_mask was missing from the audio encoder graph,
   so padded mel frames produced finite values that fed the LLM and
   triggered runaway repetition (e.g. '有趣的事情有趣的事情...').

   - AudioEncoderLayer / AudioAttention now plumb attention_mask
     through to op.Attention as the 4th positional arg.
   - _build_audio_encoder declares feature_attention_mask (INT64) as
     graph input and audio_feature_lengths as output.
   - examples/qwen3_asr.py uses processor with return_attention_mask
     and crops audio_features by audio_feature_lengths.

2. The audio encoder used a single-shot conv over the full mel
   spectrogram (375 tokens / 30s) instead of HF's chunked conv with
   per-chunk positional embeddings and block-diagonal attention mask
   (390 tokens / 30s, 100-frame chunks, 13 tokens/chunk, 8-chunk
   blocks). This caused the 1.7B model to drift on 30s clips
   (e.g. '世界世界世界世界...').

   - AudioConfig gains n_window / n_window_infer fields, derived from
     the HF config in _extract_audio_config.
   - Qwen3ASRAudioEncoder now reshapes mel into chunks, runs Conv2d
     batched across (B*num_chunks), broadcasts PE[0:tokens_per_chunk]
     over chunks, computes per-batch audio_feature_lengths via HF's
     _get_feat_extract_output_lengths formula, and builds an
     (B, S, S) block-diagonal attention mask. Empty rows for padded
     queries are OR'd with the identity matrix to avoid NaN in ORT
     softmax; padded outputs are cropped by callers.

Validated against HF reference on a 30s Chinese clip: mobius's 1.7B
ONNX output now matches HF's reference output near byte-for-byte.

All 1201 build_graph tests pass.

Tests added:
  - test_audio_encoder_attention_uses_mask: every Attention op has 4
    inputs with non-null attn_mask.
  - test_3model_pipeline_runs_with_ort updated to feed mask + crop by
    audio_feature_lengths.
@github-actions

github-actions Bot commented May 5, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 8542e9f → 81d9ec1

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 60 60 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 107 107 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 53 53 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 61 61 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 58 58 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 98 98 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 59 59 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 61 61 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 58 58 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 275 275 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 129 129 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 408 408 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 166 166 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

@xiaoyu-work

Copy link
Copy Markdown
Member Author

@copilot fix lint issue

@codecov

codecov Bot commented May 5, 2026

Copy link
Copy Markdown

The author of this PR, xiaoyu-work, is not an activated member of this organization on Codecov.
Please activate this user on Codecov to display this PR comment.
Coverage data is still being uploaded to Codecov.io for purposes of overall coverage calculations.
Please don't hesitate to email us at [email protected] with any questions.

@github-actions

github-actions Bot commented May 5, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 8542e9f → 81d9ec1

Model Sub-model Changes Status
bert (feature-extraction) model 0 ⚪
falcon model 0 ⚪
gemma2 model 0 ⚪
gemma4 (gemma4) decoder 0 ⚪
gemma4 (gemma4) embedding 0 ⚪
gemma4 (gemma4) vision_encoder 0 ⚪
gemma4_text model 0 ⚪
gpt2 model 0 ⚪
llama model 0 ⚪
llama (static-cache) model 0 ⚪
mamba (ssm-text-generation) model 0 ⚪
phi3 model 0 ⚪
phi3 (static-cache) model 0 ⚪
qwen model 0 ⚪
qwen (static-cache) model 0 ⚪
qwen2 model 0 ⚪
qwen2 (static-cache) model 0 ⚪
qwen2_moe model 0 ⚪
qwen2_moe (static-cache) model 0 ⚪
qwen3 model 0 ⚪
qwen3 (static-cache) model 0 ⚪
qwen3_5_moe (hybrid-text-generation) model 0 ⚪
qwen3_5_text (hybrid-text-generation) model 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) decoder 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) embedding 0 ⚪
qwen3_5_vl (hybrid-qwen-vl) vision_encoder 0 ⚪
qwen3_moe model 0 ⚪
qwen3_moe (static-cache) model 0 ⚪
qwen3_next (hybrid-text-generation) model 0 ⚪
t5 (seq2seq) decoder 0 ⚪
t5 (seq2seq) encoder 0 ⚪
whisper (speech-to-text) decoder 0 ⚪
whisper (speech-to-text) encoder 0 ⚪

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR updates the Qwen3-ASR speech pipeline so the exported audio encoder more closely matches HuggingFace behavior on padded/long audio. It adds mel-frame masking, chunked convolution/block-local attention in the audio tower, and updates the example/tests to consume the new encoder outputs.

Changes:

  • Add feature_attention_mask to the speech audio-encoder graph and expose audio_feature_lengths for downstream cropping.
  • Rework Qwen3ASRAudioEncoder to use chunked conv + block-diagonal attention derived from new audio config fields.
  • Update the Qwen3-ASR example and build-graph tests for the new mask/cropping flow.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
tests/build_graph_test.py Adds graph/ORT tests for mask wiring and audio-length cropping.
src/mobius/tasks/_speech_language.py Changes speech audio-encoder task I/O to require a mask and emit token lengths.
src/mobius/models/qwen3_asr.py Implements chunked-conv audio encoding, token-length computation, and block-local masking.
src/mobius/components/_qwen3_asr_audio.py Threads attention masks through Qwen3-ASR audio attention/layers.
src/mobius/_configs.py Extends AudioConfig extraction with Qwen3-ASR chunking parameters.
examples/qwen3_asr.py Updates the example pipeline to request attention masks and crop padded audio tokens.

Comment thread src/mobius/tasks/_speech_language.py Resolved
Comment thread src/mobius/models/qwen3_asr.py Resolved
Comment thread src/mobius/tasks/_speech_language.py Resolved
Comment thread examples/qwen3_asr.py Resolved

Copilot AI commented May 5, 2026

Copy link
Copy Markdown
Contributor

@copilot fix lint issue

Fixed in 66fe492 — applied ruff format to src/mobius/models/qwen3_asr.py.

@justinchuby justinchuby left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM thanks. Could you fix comments?

@justinchuby

Copy link
Copy Markdown
Member

Also please run the L4/L5 tests locally to ensure they still pass.

1. Fix _StubAudio test stub to match new SpeechLanguageTask contract:
   forward() now takes feature_attention_mask and returns
   (audio_features, audio_feature_lengths) 2-tuple.

2. Document mel_seq divisibility requirement in chunked reshape comment:
   WhisperFeatureExtractor pads to 3000 frames (30s * 100 fps), which
   is always divisible by chunk_size_mel (2 * n_window = 100).

3. Add NOTE documenting that ORT GenAI's speech pipeline does not yet
   wire audio_feature_lengths output. Custom inference scripts must
   read and crop manually.

4. Fix qwen3_forced_aligner.py: update compute_mel_spectrogram() call
   to unpack (mel, feature_attention_mask) tuple, pass mask to audio
   encoder, and crop audio_features using audio_feature_lengths.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@justinchuby

Copy link
Copy Markdown
Member

Addressed all 4 review comments in commit 27465ef:

Comment 1 — Stub audio encoder test breaks: Fixed _StubAudio.forward() to accept feature_attention_mask and return (audio_features, audio_feature_lengths) 2-tuple matching the new SpeechLanguageTask contract.

Comment 2 — Reshape assumes divisible mel_seq_len: Added a comment documenting that mel_seq must be divisible by chunk_size_mel. This is guaranteed because WhisperFeatureExtractor pads to 3000 frames (30s * 100 fps), which is divisible by the default chunk_size_mel (2 * n_window = 100).

Comment 3 — genai_config doesn't wire audio_feature_lengths: Added a NOTE documenting that ORT GenAI's speech pipeline does not yet wire this output. Custom inference scripts (e.g. examples/qwen3_asr.py) must read audio_feature_lengths and crop manually. Full GenAI integration would require runtime changes.

Comment 4 — forced_aligner example breaks: Fixed qwen3_forced_aligner.py to unpack (mel, feature_attention_mask) from compute_mel_spectrogram(), pass mask to the audio encoder, and crop audio_features using audio_feature_lengths.

Test results: 2703 passed, 41 skipped, lint clean.

@xiaoyu-work

Copy link
Copy Markdown
Member Author

@copilot resolve the merge conflicts in this pull request

…nflict

Merge changes from main (f32 input casting via _cast_encoder_input) with
our branch's feature_attention_mask + audio_feature_lengths additions.

The merged _build_audio_encoder:
- Accepts input_features as FLOAT and casts to model dtype via _cast_encoder_input
- Adds feature_attention_mask (INT64) as a second graph input
- Calls audio_encoder with both inputs, returning (audio_features, audio_feature_lengths)
- Outputs both audio_features and audio_feature_lengths

Signed-off-by: GitHub <[email protected]>

Co-authored-by: xiaoyu-work <[email protected]>

Copilot AI commented May 6, 2026

Copy link
Copy Markdown
Contributor

@copilot resolve the merge conflicts in this pull request

Resolved in a960ecc — merged origin/main into the branch. The only conflict was in src/mobius/tasks/_speech_language.py, where I combined main's _cast_encoder_input call with our branch's feature_attention_mask input and audio_feature_lengths output.

@justinchuby justinchuby left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

justinchuby and others added 2 commits May 7, 2026 00:16
Move the padding crop from callers into the audio encoder ONNX graph.
The encoder now outputs only valid audio features [batch, valid_tokens,
hidden_size] instead of [batch, max_tokens, hidden_size] + a separate
audio_feature_lengths output.

This simplifies the GenAI integration (no need to wire
audio_feature_lengths) and removes manual cropping from the example
script.

Changes:
- _speech_language.py: Add Slice op after encoder forward to crop
  audio_features to audio_feature_lengths. Remove audio_feature_lengths
  from graph outputs.
- qwen3_asr.py: Remove manual crop since encoder now does it.
- build_graph_test.py: Update IO assertion and pipeline test to
  match new single-output encoder.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@justinchuby justinchuby self-assigned this May 7, 2026
justinchuby and others added 2 commits May 7, 2026 00:38
The in-graph Slice crop only works for batch_size=1 because ONNX Slice
uses a single ends value per axis, not per batch item. Since the audio
encoder uses padding masks for batched inputs, the crop must be handled
by the caller (GenAI runtime or inference script) which can crop
per-batch-item using audio_feature_lengths.

Restores:
- audio_feature_lengths as audio encoder graph output
- Manual crop in examples/qwen3_asr.py
- Test assertions for audio_feature_lengths output

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@justinchuby
justinchuby merged commit fdf2c2e into main May 7, 2026
16 of 18 checks passed
@justinchuby
justinchuby deleted the xiaoyu/qwenasr branch May 7, 2026 00:51
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants