Skip to content

Fix Qwen2.5/3-VL vision PackedMultiHeadAttention crash on CUDA - #358

Merged
justinchuby merged 4 commits into
mainfrom
justinchu/fix-qwen-vl-packed-mha
Jun 17, 2026
Merged

justinchuby merged 4 commits into
mainfrom
justinchu/fix-qwen-vl-packed-mha

Conversation

@justinchuby

Copy link
Copy Markdown
Member

Problem

Building Qwen2.5-VL-3B with Mobius and evaluating on CUDA crashes at the first windowed vision block:

[E ... PackedMultiHeadAttention node 'vision_encoder/visual/blocks.0/attn/PackedMultiHeadAttention_node_214']
Status Message: Input 'cumulative_sequence_length' should have 1 dimension with size equal to batch_size + 1

Root cause

The EP-gated packed path (_emit_packed_mha, used when the EP advertises supports_packed_multi_head_attention, i.e. CUDA / trt-rtx) built token_offset as shape (1, N), declaring batch_size = 1 to com.microsoft::PackedMultiHeadAttention.

ORT derives batch_size from token_offset.shape[0] and requires cumulative_sequence_length (our cu_seqlens) to have length batch_size + 1 (contrib_ops/cuda/bert/packed_multihead_attention.cc). Whenever cu_seqlens enumerates more than one sub-sequence:

  • windowed vision blocks (cu_window_seqlens, length num_windows + 1), or
  • multi-frame video / multi-image full-attention blocks (length T + 1),

num_sub_seqs + 1 > 2, so the kernel rejects the input and the run crashes. The Copilot diagnosis in the issue was accurate.

Even in the non-crashing single-sub-sequence case, batch_size = 1 made the kernel compute full attention over all N tokens instead of the intended block-diagonal attention — so the path was doubly broken.

_qwen3_vl_vision.py had the identical copy-pasted bug (latent crash for multi-image / video).

Fix

Build token_offset with shape (num_sub_seqs, max_seq_len) following ORT's GetPaddingOffset convention — valid padded-layout token indices (b * max_seq_len + s) in packed order, then padding-slot indices. This matches the already-correct BlockDiagonalToPackedMHA rewrite rule, extracted into a shared build_packed_token_offset helper in components/_common.py and reused by both vision encoders.

Also stop unconditionally down-casting q/k/v to float16: the PackedMHA CUDA kernel supports both float32 and float16, so only bfloat16 builds (unsupported) are cast to f16; f32/f16 stay native to preserve precision.

Verification

  • CUDA parity: with the fix, the packed path matches the standard block-diagonal attention path (CPU) on a 4-window grid (grid_thw=[1,12,12]) that crashed before — cosine 1.0, max abs diff ~7e-8.
  • New exact-value unit tests for build_packed_token_offset against ORT's own reference data (e.g. cu=[0,1,3] -> [[0,2],[3,1]], including padding indices >= token_count, single-subsequence identity, uniform windows).
  • Full non-integration suite green (1318 passed); existing qwen2_5_vl / qwen3_vl graph tests and packed-attention rewrite tests unaffected.

The EP-gated packed attention path for the Qwen2.5-VL and Qwen3-VL
vision encoders built `token_offset` as shape `(1, N)`, declaring
`batch_size = 1` to ORT's `com.microsoft::PackedMultiHeadAttention`.
ORT derives `batch_size` from `token_offset.shape[0]` and requires
`cumulative_sequence_length` (our `cu_seqlens`) to have length
`batch_size + 1`. Whenever `cu_seqlens` enumerates more than one
sub-sequence — i.e. windowed vision blocks, or multi-frame video /
multi-image full-attention blocks — the kernel rejects the input:

    Input 'cumulative_sequence_length' should have 1 dimension with
    size equal to batch_size + 1

and the run crashes at the first windowed block (e.g. `blocks.0`).
Even when it did not crash (a single sub-sequence), `batch_size = 1`
made the kernel compute full attention over all N tokens instead of
the intended block-diagonal attention.

Fix: build `token_offset` with shape `(num_sub_seqs, max_seq_len)`
following ORT's GetPaddingOffset convention (valid padded-layout token
indices in packed order, then padding-slot indices), matching the
existing, correct `BlockDiagonalToPackedMHA` rewrite rule. This is
extracted into a shared `build_packed_token_offset` helper in
`components/_common.py` and reused by both vision encoders.

Also stop unconditionally down-casting q/k/v to float16: ORT's
PackedMultiHeadAttention CUDA kernel supports both float32 and
float16, so only bfloat16 builds (unsupported by the kernel) are cast
to float16; float32/float16 builds stay native to preserve precision.

Verified on CUDA: with the fix the packed path matches the standard
block-diagonal attention path (CPU) on a 4-window grid that crashed
before, with cosine 1.0 and max abs diff ~7e-8. Adds exact-value unit
tests for the token_offset helper against ORT's own reference data.

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

github-actions Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 92d0538 → 068feef

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 68 68 +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 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 62 62 +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 60 60 +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 62 62 +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 413 413 +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.

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

Fixes a CUDA runtime crash in Qwen2.5-VL / Qwen3-VL vision when using ORT’s com.microsoft::PackedMultiHeadAttention by constructing a correct token_offset tensor (so ORT derives the correct batch_size for varlen sub-sequences) and by avoiding unnecessary precision loss for fp32/fp16 builds.

Changes:

  • Add build_packed_token_offset(op, cu_seqlens) helper implementing ORT’s GetPaddingOffset convention for PackedMHA.
  • Update Qwen2.5-VL and Qwen3-VL vision packed-attention emission to use the helper (fixing both crash and incorrect full-attention behavior).
  • Only cast Q/K/V to fp16 for bf16 builds (PackedMHA unsupported), keeping fp32/fp16 native.

Reviewed changes

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

File Description
src/mobius/components/_qwen3_vl_vision.py Use build_packed_token_offset and conditional bf16→fp16 casting in the PackedMHA path.
src/mobius/components/_qwen25_vl_vision.py Same PackedMHA token_offset fix + conditional dtype casting for Qwen2.5-VL vision.
src/mobius/components/_common.py Introduce build_packed_token_offset helper matching ORT varlen PackedMHA requirements.
src/mobius/components/_common_test.py Add exact-value ORT-backed unit tests for build_packed_token_offset.

@github-actions

github-actions Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 92d0538 → 068feef

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)

@codecov

codecov Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.49541% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/mobius/components/_qwen3_vl_vision.py 25.00% 6 Missing ⚠️

📢 Thoughts on this report? Let us know!

@titaiwangms

Copy link
Copy Markdown
Contributor

Review team synthesis 🛬

Five reviewers (readability, code, critical, deep, integration) reviewed this PR in parallel. Verdict: correct, ready to merge. No Critical or Major correctness blockers. The findings below are in-scope polish + out-of-scope follow-ups.

✅ Correctness — verified, grounded in ORT source

  • build_packed_token_offset reproduces ORT's getTokenOffset exactly. Grounded in contrib_ops/cuda/bert/bert_padding.cu (valid offsets b*seq_len + s in sub-seq-major order, then padding slots). The row-major dual-Compress (valid then padding) matches ORT's for i … for j loop nesting, with sequence_length = max(lengths). Verified executably: 20,000 random cu_seqlens → 0 mismatches; ORT's own example and all four PR test vectors reproduced byte-for-byte (incl. the ragged cu=[0,2,5] → [[0,1,3],[4,5,2]]).
  • Shape invariant correct. packed_multihead_attention.cc derives batch_size = token_offset.shape[0] and rejects cu_seqlens length ≠ batch_size+1. The new (num_sub_seqs, max_seq_len) shape is exactly what the kernel requires — fixing the old (1, N) crash.
  • Parity with the existing reference. The helper is line-for-line the same algorithm as BlockDiagonalToPackedMHA in rewrite_rules/_packed_attention.py (the already-correct path) — genuine centralization, no divergence.
  • dtype change is correct. The kernel registers only float and MLFloat16 (no BFloat16). So f32/f16 native passthrough is valid and bf16 must be cast — both halves grounded in the kernel registration table.
  • Qwen3 docstring fix is real, not masking a bug. v traces to Split(qkv, num_outputs=3) → (total_seq, hidden_size); the old 3*hidden_size comment was wrong. Good catch.

Minor (in-scope, optional)

  1. dtype enum consistency — the conditional cast block uses magic ints to=10 # FLOAT16 (and key/value casts in _qwen3_vl_vision.py carry no comment), while the rest of the codebase — including the new helper three lines up — uses ir.DataType.FLOAT16. Prefer the named enum.
  2. Test gaps — all 4 new tests feed int64, but the helper documents INT32 or INT64; add one INT32-input case. No graph test asserts the dtype-gating wiring (bf16 inserts Cast-to-f16; f32/f16 pass through).
  3. Naming nits — helper's cu_i32 vs callers' cu_seqlens_int32; valid/padding read as booleans but hold indices (valid_indices/padding_indices per the docstring's own vocabulary); pos_shape → pos_matrix_shape.

Follow-up suggestions (out of scope for this PR)

  • Unify the duplication: rewrite_rules/_packed_attention.py:172-202 still inlines the identical token_offset logic. Now that the shared helper exists, the rewrite rule could call it (would need exporting from components/__init__.py) to kill the drift risk. Both reviewers who flagged this agree it's not blocking.
  • Trust-boundary hardening (open question, not introduced by this PR): the native packed path assumes cu_seqlens is monotonic and cu_seqlens[-1] == token_count. ORT validates only token_offset rank and cu length, so a malformed externally-derived grid_thw could fault on CUDA rather than fail-closed. Pre-existing property of the packed path; worth a defensive check + negative test someday.
  • bf16 guard is build-dtype-keyed (deep reviewer Question): gating on get_build_dtype() rather than the tensor's actual dtype is correct for all current callers, but is an implicit invariant — keying off the tensor dtype would make it self-contained.

Nice work — the math is clearly derived rather than copy-pasted, and the docstring + worked example are excellent.

🤖 Synthesized from a 5-agent review fan-out (readability / code / critical / deep / integration).

justinchuby and others added 2 commits June 17, 2026 16:49
Apply non-blocking review feedback on PR #358:

- Rename internals of build_packed_token_offset for clarity
  (cu_seqlens_i32, pos_matrix_shape, valid_indices, padding_indices).
- Add an INT32 cu_seqlens unit test to confirm the helper accepts both
  documented integer widths.
- Add _qwen25_vl_vision_test.py exercising the EP-gated packed path that
  CPU unit tests never reach (the codecov-flagged uncovered branch):
  asserts the CUDA build emits PackedMultiHeadAttention with the
  helper-built (Compress-based) token_offset, that f32 stays native, and
  that bf16 down-casts q/k/v to float16.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
Follow-ups from PR #358 review:

- Make build_packed_token_offset materialise its axis/index tensors as
  explicit Constant nodes so it works under both the component OpBuilder
  and the onnxscript rewriter op. BlockDiagonalToPackedMHA.rewrite now
  calls the shared helper instead of duplicating the (previously
  copy-pasted) token_offset construction, keeping the rewrite rule and
  the vision encoders in sync.

- Let the L4/L5 golden harness build an EP-specialized graph via the
  opt-in MOBIUS_TEST_BUILD_EP env var (default "default" leaves the
  portable build unchanged). Setting MOBIUS_TEST_BUILD_EP=cuda exercises
  the Qwen-VL PackedMultiHeadAttention path end-to-end; a build/runtime
  EP mismatch is rejected with a clear pytest.UsageError. Verified: the
  3 Qwen-VL golden L4 cases pass with the CUDA-built packed graph.

Co-authored-by: Copilot <[email protected]>
Signed-off-by: Justin Chu <[email protected]>
@justinchuby
justinchuby merged commit af2a28c into main Jun 17, 2026
16 of 21 checks passed
@justinchuby
justinchuby deleted the justinchu/fix-qwen-vl-packed-mha branch June 17, 2026 17:17
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.

3 participants