Repository navigation
Export DeepSeek-V4 dense attention as fused GroupQueryAttention - #585
Merged
Merged
Conversation
Replaces DeepSeekV4Attention's fully-decomposed manual attention (Transpose/ Concat/MatMul/Softmax/sink-Concat chain) with one com.microsoft:: GroupQueryAttention op per layer. Path B chosen over the general decomposed-attention KV-capacity-emission mechanism (S3) after empirical verification against stock ORT 1.29.0 and onnx-genai's own native kernels: - GQA's head_sink input is a real, load-bearing per-head learned parameter (attention sink) that DeepSeek-V4 always uses -- kept, threaded via op.CastLike(self.attn_sink, query). - attention_bias is dropped entirely: V4's dense attention is plain causal (no sliding window, no cross-layer KV sharing, no per-layer dual head_dim), so GQA's implicit causal masking plus seqlens_k/total_seq_len already reproduces create_attention_bias's semantics exactly. This matches the existing `Attention._forward_gqa` "simple causal" convention already used by every other GQA-eligible model in this codebase. - The compressor/indexer zero-shape-anchor tensors (gated by compress_ratio) don't affect the dense attention math at any compress_ratio value, so the fusion is correct and uniform across every layer. Adds `_gqa_kv_lengths`, matching the canonical GQAContext derivation formula in base.py. Removes the now-fully-unused `create_attention_bias` import and the `_expand_kv` broadcast helper (redundant: GQA broadcasts kv_num_heads=1 across query heads itself). Strengthens deepseek_v4_flash_test.py's 3 structural tests to prove the fusion actually happened (previously fusion-agnostic assertions): exact GroupQueryAttention node count == num_hidden_layers, com.microsoft domain, 12-input arity with attention_bias absent (inputs[10] is None) and head_sink present (inputs[11] is not None), and tightened the Softmax count to the exact `2 * num_hidden_layers` (Hyper-Connection softmaxes only -- proves the old per-layer attention-softmax is gone). Corrects the attention-optimization skill doc's blanket "GQA rejects attention_bias entirely" claim: verified stock ORT 1.29.0's CPU EP actually computes with attention_bias (and head_sink) when supplied. The rejection is specific to the CUDA fused-kernel cascade (XQA/Flash/MEA), not the op as a whole; onnx-genai's own native kernels remain a stricter subset for unrelated reasons (documented inline). The corresponding CPU head_sink port for onnx-genai's native GroupQueryAttention kernel (the one real runtime gap this fusion depends on) ships alongside this in a separate onnx-genai PR. Tests: `pytest src/mobius/models/deepseek_v4_test.py src/mobius/models/deepseek_v4_flash_test.py` (14 passed). `ruff check` / `ruff format --check` clean. Co-authored-by: Copilot <[email protected]>
The previous commit (d2d5596) unconditionally emitted com.microsoft::GroupQueryAttention regardless of the target execution provider, bypassing this codebase's established EP-capability gating convention. mobius/_execution_providers.py deliberately declares gqa_dtypes=frozenset() for "default" (used whenever no execution_provider kwarg is passed -- essentially all existing tests and consumers), "onnx-standard", "qnn", and "openvino" specifically to guarantee their exported graphs stay free of com.microsoft custom ops. Since build_from_module defaults to execution_provider="default", the prior commit silently broke that portability contract for every default-EP DeepSeek-V4 build. Add _use_fused_gqa(), mirroring TextModel.forward's use_gqa gate (mobius/models/base.py) via ep_capabilities()/get_build_dtype(), and branch DeepSeekV4Attention.forward between the fused GroupQueryAttention path (unchanged from d2d5596, used only when the active EP declares GQA support for the build dtype) and a restored portable decomposed path (manual Transpose/Concat/MatMul/Softmax + explicit attention_bias + attention-sink Concat/slice, byte-identical to the pre-fusion implementation). seqlens_k/total_seq_len (fused) and attention_bias (decomposed) are threaded through DeepSeekV4DecoderLayer.forward, DeepSeekV4TextModel.forward, and DeepSeekV4Mtp.forward, with exactly one of the two computed per build based on _use_fused_gqa(). V4's gate omits base.py's caps.supports_fused_rope check: RoPE is always applied explicitly in-graph via _rotate in both paths (do_rotary stays at its default/off), so there's no fused-rotary mode being requested that could be EP-unsupported. Test changes in deepseek_v4_flash_test.py: - test_tiny_graph_builds_v4_backbone, test_csa_schedule_exports_compressor_and_indexer_tensors_with_dense_attention, and test_mtp_sidecar_exports_official_block_and_hyper_connection_state now assert GroupQueryAttention count == 0 under the default EP (in addition to their original decomposed-path assertions), proving the portability contract holds. - Three new tests build the same tiny configs with execution_provider="cpu" (whose gqa_dtypes={FLOAT} matches the tiny config's default dtype) and assert the fused-GQA structural properties previously (incorrectly) asserted unconditionally: node count == num_hidden_layers, com.microsoft domain, 12-input arity with attention_bias unset and head_sink populated, and halved Softmax count (only the Hyper-Connection combination softmax remains). Reviewed independently via a code-review sub-agent (verdict: APPROVE), which byte-diffed both branches against the pre-fusion and prior-commit implementations and confirmed plumbing/argument-order consistency and that the new EP-gated tests genuinely exercise the fused path. All 14 tests in deepseek_v4_flash_test.py pass; ruff check/format clean. Co-authored-by: Copilot <[email protected]>
Performance Comparison
|
Contributor
There was a problem hiding this comment.
Pull request overview
This PR updates the DeepSeek-V4 model export to optionally emit a fused com.microsoft::GroupQueryAttention node (instead of a decomposed attention subgraph) when the active execution provider (EP) declares GQA support for the current build dtype, while preserving the existing portable decomposed attention path for EPs that must remain free of com.microsoft ops.
Changes:
- Add EP + dtype gating (
_use_fused_gqa) and sharedseqlens_k/total_seq_lenderivation (_gqa_kv_lengths) to drive fused vs decomposed attention emission. - Refactor
DeepSeekV4Attentionto emit a singleGroupQueryAttentionop (withhead_sink, and noattention_bias) on supported EPs, while keeping the prior decomposed attention logic as fallback. - Extend DeepSeek-V4 flash tests to assert
GroupQueryAttentionis absent under the default EP and present (structurally) underexecution_provider="cpu".
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.
| File | Description |
|---|---|
src/mobius/models/deepseek_v4.py |
Adds EP/dtype gating and dual-path attention: fused GroupQueryAttention when supported, decomposed attention otherwise. |
src/mobius/models/deepseek_v4_flash_test.py |
Adds structural assertions for both default (portable) and CPU EP (fused GQA) builds. |
.agents/skills/attention-optimization/SKILL.md |
Updates guidance on GQA attention_bias/head_sink support across EPs/kernels. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Comment on lines
+217
to
+221
| > implemented `head_sink` (see | ||
| > `crates/onnx-runtime-ep-cpu/src/kernels/group_query_attention.rs`, | ||
| > which now also implements `head_sink` on CPU; `attention_bias` remains | ||
| > unimplemented there by design, matching the CUDA fused-kernel | ||
| > limitation above, not an oversight). |
This was referenced Aug 24, 2026
justinchuby
added a commit
that referenced
this pull request
Aug 24, 2026
…ths (#596) ## Root cause The official DeepSeek-V4-Flash reference (`inference/model.py::Attention.forward`, `get_window_topk_idxs`) unconditionally restricts **every** layer, regardless of `compress_ratio`, to a circular-buffer window of `config.sliding_window` (128) most-recent positions. Neither of Mobius's two `DeepSeekV4Attention` forward paths applied this: - The decomposed path's `create_attention_bias(...)` call never passed `sliding_window`. - The fused-GQA path (added in #585) never emitted GQA's `local_window_size` attribute at all. Both silently computed **unbounded** causal attention instead of the mandatory windowed variant. This affects every layer — `compress_ratio=0` layers were otherwise exactly correct; `compress_ratio>0` (CSA/HCA) layers were already missing their compressed/indexed component (tracked separately, see `docs/models/DEEPSEEK_CSA_MTP_RUNTIME.md` in onnx-genai) and now additionally get the window right too. ## Fix - `DeepSeekV4Attention.__init__`: compute `self.local_window_size` from `config.sliding_window` (matching the established `-1` no-window sentinel convention). - Fused-GQA forward branch: emit `local_window_size` as a GQA attribute only when `>0`, matching `Attention._forward_gqa`'s conditional-attributes convention in `components/_attention.py` — a config with no window keeps a byte-identical graph to before this change. - `DeepSeekV4TextModel` / `DeepSeekV4Mtp`: thread `sliding_window=config.sliding_window` into their `create_attention_bias` calls so the decomposed path's shared bias also carries the window. ## Before/after evidence Standalone `GraphBuilder` + plain `onnxruntime` CPUExecutionProvider execution, seq_len=6, `sliding_window=2`, seeded random weights/inputs, byte-identical weights shared across builds via `load_state_dict`: | Comparison | Max abs diff | Meaning | |---|---|---| | unbounded vs. windowed (decomposed) | 0.0203 | confirms the window changes the output at all | | **pre-fix** fused-GQA vs. unbounded | 0.0 (identical) | confirms the bug: fused path silently ignored the configured window | | **post-fix** fused-GQA vs. windowed decomposed | 1.86e-9 (fp noise) | confirms the two paths now agree exactly | Both new regression tests were verified to **fail** against pre-fix `deepseek_v4.py` (checked out at the parent commit) and **pass** post-fix. ## Tests - `deepseek_v4_flash_test.py::test_sliding_window_sets_local_window_size_on_fused_gqa_regardless_of_compress_ratio` (new, extended to also cover the MTP sidecar): structural — `local_window_size==8` on every fused-GQA node (backbone, all 3 compress_ratios, and MTP) regardless of `compress_ratio`. - `deepseek_v4_flash_test.py::test_missing_sliding_window_regression_fused_gqa_matches_windowed_decomposed` (new): numeric regression per the evidence table above. - `deepseek_v4_flash_test.py::test_tiny_graph_builds_v4_backbone_fused_gqa_on_cpu_ep`: extended with an assertion that `local_window_size` is absent when no window is configured (backward-compat check). - `tests/_test_configs.py`: added `sliding_window=8` to the `deepseek_v4` tiny config (matches the established `gemma`/`gemma4`/`muse-glimmer` tiny-config convention); numerically exercised by the new `deepseek_v4_flash_test.py` tests above. **Verified:** - `deepseek_v4_flash_test.py`: 16/16 passed. - `deepseek_v4_test.py` + `tests/model_coverage_test.py`: 727 passed, 218 pre-existing skips. - `tests/build_graph_test.py` + `tests/synthetic_parity_test.py` + `tests/weight_alignment_test.py` (full suite): 1722 passed, 123 skipped, 62 xfailed — all pre-existing, no regressions. - `ruff check` + `ruff format` (the only two lintrunner-configured linters): clean. ## Independent review Reviewed by an independent agent, which re-derived the root cause against the HF reference implementation, re-ran both new tests pre/post-fix, rebuilt graphs to confirm byte-identical backward-compat hashes, and manually verified the MTP wiring. Verdict: **APPROVE WITH NITS** (2 non-blocking findings — missing MTP test coverage for an already-correct path, and an inaccurate test-config comment). Both nits addressed in a follow-up commit (extended the structural test to cover the MTP graph; corrected the comment's coverage claim), independently re-verified fail-before/pass-after. ## Out of scope `compress_ratio>0` (CSA/HCA) layers' compressed/indexed attention component remains unimplemented — tracked separately per `docs/models/DEEPSEEK_CSA_MTP_RUNTIME.md` in onnx-genai (parallel effort in progress). This PR only fixes the window restriction that applies uniformly to every layer. Closes: DeepSeek-V4 attention correctness gap identified during Mobius/onnx-genai GLM-5.2 & DeepSeek-V4 audit (Sapper, Systems Dev for Models & Preprocess). 🤖 Generated with [GitHub Copilot](https://github.com/copilot) --------- Co-authored-by: Copilot <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Rewrites DeepSeek-V4's dense attention export (
DeepSeekV4Attention) to emit fusedcom.microsoft::GroupQueryAttentionwhen the target execution provider supports it, replacing the decomposed manual attention (Transpose/Concat/MatMul/Softmax + explicitattention_bias+ attention-sink Concat/slice) with a single op call — while preserving the exact same portable decomposed path as a fallback for EPs that don't support GQA.This is Justin-authorized Path B from the DeepSeek-V4 native-CUDA capacity-emission investigation: rather than building a general graph-capture-safe KV-capacity-write mechanism for the decomposed attention path (Path A, previously in progress), modify the Mobius export itself to emit the existing fused GQA contract, since DeepSeek-V4's attention geometry (MQA,
kv_num_heads=1; RoPE always applied externally via_rotate, never fused; plain causal decoding, no sliding window, no per-layer dual head_dim) fits GQA's contract exactly, with no lossy approximation.Why GQA fits with no lossy approximation
GroupQueryAttention'sdo_rotarystays at its default (0/off) in both fused and decomposed paths — no fused-rotary mode is ever requested.kv_num_heads=1); the fused op's own broadcast-across-query-heads handling replaces the manual_expand_kvbroadcast.seqlens_k/total_seq_lenalready carries the exact same causal+padding semanticscreate_attention_biasbakes into an explicit float bias — the same "direct GQA" conventionAttention._forward_gqaalready uses for every other simple-causal model in this codebase.head_sinkinput (12th positional), verified to be genuinely supported by stock ORT 1.29.0's CPU EP; this crate's own CPU kernel previously rejected it — see the paired onnx-genai PR (justinchuby/onnx-genai#1956) which closes that gap.attention_bias(GQA's 11th input) is intentionally never passed — matches the existing_forward_gqaconvention, and sidesteps the one real remaining gap: neither this crate's CPU nor CUDA GQA kernels implement it.EP-capability gating (critical correctness fix — see review history below)
An initial version of this change emitted fused GQA unconditionally, regardless of execution provider. Independent review caught this as a critical bug:
mobius/_execution_providers.pydeliberately declaresgqa_dtypes=frozenset()for"default"(used whenever noexecution_providerkwarg is passed — effectively all existing tests/consumers),"onnx-standard","qnn", and"openvino", specifically to guarantee their exported graphs stay free ofcom.microsoftcustom ops — a real, load-bearing portability contract other code depends on (e.g.glm_moe_dsa_test.pyasserts zeroGroupQueryAttentionnodes under the default build).The fix adds
_use_fused_gqa(), mirroringTextModel.forward'suse_gqagate (mobius/models/base.py) viaep_capabilities()/get_build_dtype(), and branchesDeepSeekV4Attention.forwardaccordingly:"cpu"with FLOAT,"cuda"with FLOAT16/BFLOAT16): emits the singleGroupQueryAttentioncall described above."default"): restores the original portable manual attention, byte-identical to the pre-fusion implementation.Tests
deepseek_v4_flash_test.py:test_tiny_graph_builds_v4_backbone,test_csa_schedule_exports_compressor_and_indexer_tensors_with_dense_attention, andtest_mtp_sidecar_exports_official_block_and_hyper_connection_statenow assertGroupQueryAttentioncount == 0 under the default EP (in addition to their original decomposed-path assertions), proving the portability contract holds.execution_provider="cpu"(whosegqa_dtypes={FLOAT}matches the tiny config's default dtype) and assert the fused-GQA structural properties: node count ==num_hidden_layers,com.microsoftdomain, 12-input arity withattention_biasunset andhead_sinkpopulated, and halvedSoftmaxcount (only the Hyper-Connection combination softmax remains — the manual attention softmax is gone).All 14 tests in
deepseek_v4_flash_test.pypass, plus the 3 indeepseek_v4_test.py(17 total).ruff check/ruff format --checkclean.tests/synthetic_parity_test.py -k deepseek_v4has one pre-existing, unrelated skip (Weight transfer failed ... expects [64, 32], got [2048, 32]), confirmed to skip identically on the pre-fusion commit — not introduced by this change.Review
Independently reviewed twice via a
code-reviewsub-agent:DeepSeekV4Attention/DeepSeekV4DecoderLayer/DeepSeekV4TextModel/DeepSeekV4Mtp, and confirmed the new EP-gated tests genuinely exercise the fused path.Also included
Corrects a stale claim in
.agents/skills/attention-optimization/SKILL.md("GQA contrib op rejectsattention_biasentirely") — the blanket rejection only holds for the CUDA fused-kernel cascade (XQA/Flash/MEA), not the op as a whole; clarifies onnx-genai's own kernel status per-EP.Out of scope
No GLM-5.2 registration, paging/residency, YaRN, or unrelated attention changes. No Mobius exporter changes beyond DeepSeek-V4 attention itself.
Related
Pairs with justinchuby/onnx-genai#1956 (CPU
head_sinkkernel support — the one real onnx-genai runtime gap this export change depends on).