Skip to content

Commit fdf2c2e

Browse files
xiaoyu-workCopilotjustinchubyCopilot
authored
Qwen3-ASR: feature_attention_mask + chunked conv for HF parity (#264)
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. --------- Signed-off-by: Justin Chu <[email protected]> Signed-off-by: Justin Chu <[email protected]> Co-authored-by: copilot-swe-agent[bot] <[email protected]> Co-authored-by: Justin Chu <[email protected]> Co-authored-by: Copilot <[email protected]> Co-authored-by: Justin Chu <[email protected]>
1 parent 96957d9 commit fdf2c2e

8 files changed

Lines changed: 385 additions & 54 deletions

File tree

‎examples/qwen3_asr.py‎

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -196,10 +196,21 @@ def compute_mel_spectrogram(
196196
n_mels: int = 128,
197197
n_fft: int = 400,
198198
hop_length: int = 160,
199-
) -> np.ndarray:
199+
) -> tuple[np.ndarray, np.ndarray]:
200200
"""Compute log-mel spectrogram using WhisperFeatureExtractor.
201201
202-
Returns array of shape ``(1, n_mels, time_frames)``.
202+
The Whisper extractor pads to a fixed 30-second window
203+
(``max_length=3000`` mel frames). Without the matching padding
204+
mask, the mobius audio encoder treats trailing zero-padded frames
205+
as real audio and the LLM downstream emits degenerate loops. We
206+
therefore always request ``return_attention_mask=True`` so the
207+
encoder can crop padding from the audio token stream.
208+
209+
Returns:
210+
``(input_features, feature_attention_mask)`` where
211+
``input_features`` has shape ``(1, n_mels, time_frames)`` and
212+
``feature_attention_mask`` has shape ``(1, time_frames)``
213+
(1 = real audio, 0 = padding).
203214
"""
204215
from transformers import WhisperFeatureExtractor
205216

@@ -213,11 +224,12 @@ def compute_mel_spectrogram(
213224
audio,
214225
sampling_rate=sample_rate,
215226
return_tensors="np",
216-
padding=False,
227+
return_attention_mask=True,
217228
)
218-
return out["input_features"].astype(
219-
np.float32
220-
) # Always float32; caller casts to model dtype
229+
# Always float32 for input_features; caller casts to model dtype.
230+
input_features = out["input_features"].astype(np.float32)
231+
feature_attention_mask = out["attention_mask"].astype(np.int64)
232+
return input_features, feature_attention_mask
221233

222234

223235
# ---------------------------------------------------------------------------
@@ -312,11 +324,24 @@ def transcribe(
312324
batch_size = 1
313325

314326
# Step 1: Compute mel spectrogram
315-
mel = compute_mel_spectrogram(audio).astype(model_dtype) # (1, n_mels, time)
327+
mel, feature_attention_mask = compute_mel_spectrogram(audio)
328+
mel = mel.astype(model_dtype) # (1, n_mels, time)
316329

317330
# Step 2: Run audio encoder
318-
audio_out = sessions["audio_encoder"].run({"input_features": mel})
331+
audio_out = sessions["audio_encoder"].run(
332+
{
333+
"input_features": mel,
334+
"feature_attention_mask": feature_attention_mask,
335+
}
336+
)
319337
audio_features = audio_out["audio_features"] # (1, audio_seq, dim)
338+
audio_feature_lengths = audio_out["audio_feature_lengths"] # (1,)
339+
# Crop padding-derived rows so they never reach the embedding's
340+
# gather. The encoder emits a fixed-length output equal to the
341+
# padded mel length / 8, but only ``audio_feature_lengths[0]`` of
342+
# those rows correspond to real audio.
343+
valid_audio_tokens = int(audio_feature_lengths[0])
344+
audio_features = audio_features[:, :valid_audio_tokens, :]
320345
num_audio_tokens = audio_features.shape[1]
321346

322347
# Flatten to (num_audio_tokens, output_dim) for the embedding model

‎examples/qwen3_forced_aligner.py‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,18 @@ def run_alignment(
156156
alignment_text += "<timestamp><timestamp>"
157157

158158
# Step 2: Compute mel spectrogram and run audio encoder
159-
mel = compute_mel_spectrogram(audio)
160-
audio_out = sessions["audio_encoder"].run({"input_features": mel})
159+
mel, feature_attention_mask = compute_mel_spectrogram(audio)
160+
audio_out = sessions["audio_encoder"].run(
161+
{
162+
"input_features": mel,
163+
"feature_attention_mask": feature_attention_mask,
164+
}
165+
)
161166
audio_features = audio_out["audio_features"]
167+
audio_feature_lengths = audio_out["audio_feature_lengths"]
168+
# Crop padding-derived audio tokens
169+
valid_audio_tokens = int(audio_feature_lengths[0])
170+
audio_features = audio_features[:, :valid_audio_tokens, :]
162171
num_audio_tokens = audio_features.shape[1]
163172
audio_features_2d = audio_features.reshape(-1, audio_features.shape[-1])
164173

‎src/mobius/_configs.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,16 @@ class AudioConfig:
281281
audio_start_token_id: int | None = None
282282
audio_end_token_id: int | None = None
283283
classify_num: int | None = None
284+
# Qwen3-ASR chunked conv parameters. ``n_window`` is half the
285+
# number of mel frames per conv chunk (so chunk_size = 2 *
286+
# n_window). ``n_window_infer`` is the attention window in mel
287+
# frames; encoder self-attention is block-diagonal with windows
288+
# of n_window_infer / (2 * n_window) post-conv chunks (~=
289+
# n_window_infer * tokens_per_chunk / chunk_size_mel post-conv
290+
# tokens). HF reference: QwenLM/Qwen3-ASR
291+
# qwen_asr/core/transformers_backend/modeling_qwen3_asr.py
292+
n_window: int | None = None
293+
n_window_infer: int | None = None
284294
# Fun-ASR / SenseVoice encoder config
285295
tp_num_blocks: int | None = None
286296
adaptor_proj_dim: int | None = None
@@ -712,6 +722,8 @@ def _extract_audio_config(config, parent_config, model_type: str) -> dict:
712722
downsample_hidden_size=getattr(ac, "downsample_hidden_size", None),
713723
output_dim=getattr(ac, "output_dim", None),
714724
activation_function=getattr(ac, "activation_function", "gelu"),
725+
n_window=getattr(ac, "n_window", None),
726+
n_window_infer=getattr(ac, "n_window_infer", None),
715727
)
716728
# Special tokens from thinker config
717729
audio_fields["audio_token_id"] = getattr(tc, "audio_token_id", None)

‎src/mobius/components/_qwen3_asr_audio.py‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,20 @@ def __init__(self, d_model: int, num_heads: int):
3939
self._num_heads = num_heads
4040
self._head_dim = d_model // num_heads
4141

42-
def forward(self, op: builder.OpBuilder, hidden_states: ir.Value):
42+
def forward(
43+
self,
44+
op: builder.OpBuilder,
45+
hidden_states: ir.Value,
46+
attention_mask: ir.Value | None = None,
47+
):
4348
"""Bidirectional self-attention.
4449
4550
Args:
4651
hidden_states: (batch, seq_len, d_model)
52+
attention_mask: optional bool mask of shape ``(batch, seq_len, seq_len)``
53+
(True = attend, False = mask out). Used to ignore padded
54+
mel positions that were added by the HF processor when
55+
padding to a fixed 30s window.
4756
4857
Returns:
4958
output: (batch, seq_len, d_model)
@@ -57,6 +66,7 @@ def forward(self, op: builder.OpBuilder, hidden_states: ir.Value):
5766
q,
5867
k,
5968
v,
69+
attention_mask,
6070
q_num_heads=self._num_heads,
6171
kv_num_heads=self._num_heads,
6272
scale=float(self._head_dim**-0.5),
@@ -88,19 +98,25 @@ def __init__(
8898
self.fc2 = Linear(ffn_dim, d_model, bias=True)
8999
self.final_layer_norm = LayerNorm(d_model, eps=eps)
90100

91-
def forward(self, op: builder.OpBuilder, hidden_states: ir.Value):
101+
def forward(
102+
self,
103+
op: builder.OpBuilder,
104+
hidden_states: ir.Value,
105+
attention_mask: ir.Value | None = None,
106+
):
92107
"""Pre-norm encoder layer with bidirectional attention.
93108
94109
Args:
95110
hidden_states: (batch, seq_len, d_model)
111+
attention_mask: optional bool mask, see ``Qwen3ASRAudioAttention``.
96112
97113
Returns:
98114
hidden_states: (batch, seq_len, d_model)
99115
"""
100116
# Self-attention with pre-norm and residual
101117
residual = hidden_states
102118
hidden_states = self.self_attn_layer_norm(op, hidden_states)
103-
hidden_states = self.self_attn(op, hidden_states)
119+
hidden_states = self.self_attn(op, hidden_states, attention_mask)
104120
hidden_states = op.Add(residual, hidden_states)
105121

106122
# FFN with pre-norm, GELU, and residual

0 commit comments

Comments
 (0)