Repository navigation
Fix Qwen2.5/3-VL vision PackedMultiHeadAttention crash on CUDA - #358
Conversation
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]>
Performance Comparison
|
There was a problem hiding this comment.
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’sGetPaddingOffsetconvention 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. |
🏗️ Architecture Diff
No architecture changes detected. ✅ Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed) |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Co-authored-by: Copilot <[email protected]> Signed-off-by: Justin Chu <[email protected]>
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
Minor (in-scope, optional)
Follow-up suggestions (out of scope for this PR)
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). |
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]>
Problem
Building Qwen2.5-VL-3B with Mobius and evaluating on CUDA crashes at the first windowed vision block:
Root cause
The EP-gated packed path (
_emit_packed_mha, used when the EP advertisessupports_packed_multi_head_attention, i.e. CUDA / trt-rtx) builttoken_offsetas shape(1, N), declaringbatch_size = 1tocom.microsoft::PackedMultiHeadAttention.ORT derives
batch_sizefromtoken_offset.shape[0]and requirescumulative_sequence_length(ourcu_seqlens) to have lengthbatch_size + 1(contrib_ops/cuda/bert/packed_multihead_attention.cc). Whenevercu_seqlensenumerates more than one sub-sequence:cu_window_seqlens, lengthnum_windows + 1), orT + 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 = 1made the kernel compute full attention over allNtokens instead of the intended block-diagonal attention — so the path was doubly broken._qwen3_vl_vision.pyhad the identical copy-pasted bug (latent crash for multi-image / video).Fix
Build
token_offsetwith shape(num_sub_seqs, max_seq_len)following ORT'sGetPaddingOffsetconvention — valid padded-layout token indices (b * max_seq_len + s) in packed order, then padding-slot indices. This matches the already-correctBlockDiagonalToPackedMHArewrite rule, extracted into a sharedbuild_packed_token_offsethelper incomponents/_common.pyand 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
grid_thw=[1,12,12]) that crashed before — cosine 1.0, max abs diff ~7e-8.build_packed_token_offsetagainst 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).qwen2_5_vl/qwen3_vlgraph tests and packed-attention rewrite tests unaffected.