Skip to content

Export DeepSeek-V4 dense attention as fused GroupQueryAttention - #585

Merged
justinchuby merged 2 commits into
mainfrom
deepseek-v4-fused-gqa-attention
Aug 24, 2026
Merged

justinchuby merged 2 commits into
mainfrom
deepseek-v4-fused-gqa-attention

Conversation

@justinchuby

Copy link
Copy Markdown
Member

Summary

Rewrites DeepSeek-V4's dense attention export (DeepSeekV4Attention) to emit fused com.microsoft::GroupQueryAttention when the target execution provider supports it, replacing the decomposed manual attention (Transpose/Concat/MatMul/Softmax + explicit attention_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

  • V4 always applies RoPE explicitly in-graph (both nope/rope split + rotate), so GroupQueryAttention's do_rotary stays at its default (0/off) in both fused and decomposed paths — no fused-rotary mode is ever requested.
  • V4 is single-KV-head MQA (kv_num_heads=1); the fused op's own broadcast-across-query-heads handling replaces the manual _expand_kv broadcast.
  • Plain causal decoding (no sliding window, no cross-layer KV sharing) means GQA's implicit causal mask + seqlens_k/total_seq_len already carries the exact same causal+padding semantics create_attention_bias bakes into an explicit float bias — the same "direct GQA" convention Attention._forward_gqa already uses for every other simple-causal model in this codebase.
  • The learned per-head attention sink is passed as GQA's first-class head_sink input (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_gqa convention, 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.py deliberately declares gqa_dtypes=frozenset() for "default" (used whenever no execution_provider kwarg is passed — effectively all existing tests/consumers), "onnx-standard", "qnn", and "openvino", specifically to guarantee their exported graphs stay free of com.microsoft custom ops — a real, load-bearing portability contract other code depends on (e.g. glm_moe_dsa_test.py asserts zero GroupQueryAttention nodes under the default build).

The fix adds _use_fused_gqa(), mirroring TextModel.forward's use_gqa gate (mobius/models/base.py) via ep_capabilities()/get_build_dtype(), and branches DeepSeekV4Attention.forward accordingly:

  • Fused path (EP declares GQA support for the build dtype, e.g. "cpu" with FLOAT, "cuda" with FLOAT16/BFLOAT16): emits the single GroupQueryAttention call described above.
  • Decomposed path (all other EPs, including "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, 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 under execution_provider="cpu" (whose gqa_dtypes={FLOAT} matches the tiny config's default dtype) and assert the fused-GQA structural properties: 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 — the manual attention softmax is gone).

All 14 tests in deepseek_v4_flash_test.py pass, plus the 3 in deepseek_v4_test.py (17 total). ruff check/ruff format --check clean. tests/synthetic_parity_test.py -k deepseek_v4 has 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-review sub-agent:

  1. First pass (on the unconditional-fusion version): REQUEST CHANGES — found the EP-gating bypass described above.
  2. Second pass (on this corrected diff): APPROVE — byte-diffed both branches against the pre-fusion and unconditional-fusion implementations, confirmed plumbing/argument-order consistency across 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 rejects attention_bias entirely") — 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_sink kernel support — the one real onnx-genai runtime gap this export change depends on).

justinchuby and others added 2 commits August 24, 2026 02:51
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]>
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 24, 2026 07:04
@github-actions

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 89ff75f → 73dc483

Model Sub-model Changes Status

No architecture changes detected. ✅


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

@github-actions

Copy link
Copy Markdown

Performance Comparison

Comparing 89ff75f → 73dc483

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 68 68 +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 105 105 +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 60 60 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 56 56 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 58 58 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 54 54 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 60 60 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 56 56 +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 264 264 +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 126 126 +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 428 428 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 176 176 +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.

@justinchuby
justinchuby merged commit 70b24ed into main Aug 24, 2026
23 checks passed
@justinchuby
justinchuby deleted the deepseek-v4-fused-gqa-attention branch August 24, 2026 07:07

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 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 shared seqlens_k / total_seq_len derivation (_gqa_kv_lengths) to drive fused vs decomposed attention emission.
  • Refactor DeepSeekV4Attention to emit a single GroupQueryAttention op (with head_sink, and no attention_bias) on supported EPs, while keeping the prior decomposed attention logic as fallback.
  • Extend DeepSeek-V4 flash tests to assert GroupQueryAttention is absent under the default EP and present (structurally) under execution_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).
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]>
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.

2 participants