Skip to content

Fix DeepSeek-V4: wire mandatory sliding-window into both attention paths - #596

Merged
justinchuby merged 2 commits into
mainfrom
sapper/deepseek-v4-window-fix
Aug 24, 2026
Merged

justinchuby merged 2 commits into
mainfrom
sapper/deepseek-v4-window-fix

Conversation

@justinchuby

Copy link
Copy Markdown
Member

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:

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

justinchuby and others added 2 commits August 24, 2026 15:24
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 Mobius attention path applied this: the decomposed
path's `create_attention_bias(...)` call never passed `sliding_window`,
and 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 (ratio-0 layers are otherwise exactly correct; ratio>0
layers were already missing the compressed/indexed component and now
additionally get the window right).

Fix:
- `DeepSeekV4Attention.__init__`: compute `self.local_window_size` from
  `config.sliding_window` (matching the `-1` no-window sentinel already
  used elsewhere in the codebase).
- Fused-GQA forward branch: emit `local_window_size` as a GQA attribute
  (only when >0, matching `Attention._forward_gqa`'s established
  conditional-attrs convention in `components/_attention.py`, so 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.

Evidence (before/after, seq_len=6, sliding_window=2, seeded random
weights/inputs, standalone GraphBuilder + onnxruntime CPUExecutionProvider):
- unbounded (no window) vs. windowed (decomposed, sliding_window=2):
  max abs diff = 0.0203 -- confirms the window changes the output.
- pre-fix fused-GQA (no local_window_size wired) vs. unbounded: identical
  -- confirms the bug (fused path silently ignored any configured window).
- post-fix fused-GQA (local_window_size=2) vs. windowed decomposed:
  max abs diff = 1.86e-9 (fp noise only) -- confirms the two paths now
  agree exactly.

Both new tests were verified to fail against the pre-fix
`deepseek_v4.py` and pass against the fix.

Tests:
- deepseek_v4_flash_test.py::test_sliding_window_sets_local_window_size_on_fused_gqa_regardless_of_compress_ratio
  (new): structural -- local_window_size==8 on every fused-GQA node
  regardless of compress_ratio in {0, 4, 128}.
- deepseek_v4_flash_test.py::test_missing_sliding_window_regression_fused_gqa_matches_windowed_decomposed
  (new): numeric regression per the evidence 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/no-op check).
- tests/_test_configs.py: added sliding_window=8 to the deepseek_v4 tiny
  config (smaller than the parity tests' sequence length, so windowing
  is actually exercised end-to-end by the existing synthetic-parity/
  build-graph/weight-alignment suites, matching the established
  gemma/gemma4/muse-glimmer sliding_window:8 tiny-config convention).

Verified: deepseek_v4_flash_test.py (16/16), deepseek_v4_test.py +
tests/model_coverage_test.py (743 passed, 218 pre-existing skips),
tests/build_graph_test.py + synthetic_parity_test.py +
weight_alignment_test.py full suite (1722 passed, 123 skipped,
62 xfailed, all pre-existing), ruff check + ruff format (clean).

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); this change
only fixes the window that applies uniformly to every layer.

Co-authored-by: Copilot <[email protected]>
…comment

Independent review flagged two non-blocking nits:
- test_sliding_window_sets_local_window_size_on_fused_gqa_regardless_of_compress_ratio
  only exercised the backbone model graph; the MTP sidecar's identical
  sliding_window wiring (DeepSeekV4Mtp.__init__/forward) had no test
  coverage even though it was independently hand-verified correct.
  Extended the test to also build the mtp sidecar and assert its single
  GroupQueryAttention node carries local_window_size=8.
- tests/_test_configs.py's comment on the new sliding_window=8 tiny-config
  field overstated that it was 'exercised end-to-end by the existing
  synthetic-parity/build-graph/weight-alignment suites' -- those suites
  either don't execute a forward pass at all, or currently skip
  deepseek_v4 for an unrelated pre-existing reason. Corrected the comment
  to accurately attribute numeric coverage to deepseek_v4_flash_test.py's
  dedicated window tests instead.

Re-verified: both nit fixes verified to fail pre-fix (checked out
deepseek_v4.py at 059bf5f) and pass post-fix; full targeted suite
(deepseek_v4_flash_test.py 16/16, deepseek_v4_test.py + model_coverage_test.py
727 passed/218 pre-existing skips) re-run clean; ruff check + ruff format
clean.

Co-authored-by: Copilot <[email protected]>
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 24, 2026 17:55
@github-actions

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 059bf5f → ec3bca6

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 059bf5f → ec3bca6

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 cec78d2 into main Aug 24, 2026
24 checks passed
@justinchuby
justinchuby deleted the sapper/deepseek-v4-window-fix branch August 24, 2026 17:57

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 fixes a DeepSeek-V4 correctness gap by ensuring the model’s mandatory sliding_window restriction is applied consistently in both attention implementations: the fused com.microsoft::GroupQueryAttention path (via local_window_size) and the portable decomposed path (via create_attention_bias(sliding_window=...)). It also adds/extends regression tests to prevent the fused path from silently widening attention again.

Changes:

  • Wire config.sliding_window into DeepSeekV4Attention as local_window_size, and emit local_window_size on fused GQA nodes only when a window is configured.
  • Thread sliding_window into the decomposed-path create_attention_bias(...) calls for both the backbone and the MTP sidecar.
  • Add structural + numeric regression tests to validate fused-GQA matches windowed decomposed attention, and update the tiny DeepSeek-V4 config to include a representative sliding_window.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
tests/_test_configs.py Adds sliding_window=8 to the DeepSeek-V4 tiny config and documents why it’s required.
src/mobius/models/deepseek_v4.py Implements mandatory sliding-window wiring for both fused-GQA and decomposed attention paths (including MTP).
src/mobius/models/deepseek_v4_flash_test.py Adds regression tests (structural + numeric) covering sliding-window behavior on fused GQA and parity with decomposed windowed attention.
docs/design/deepseek-v4-flash-export.md Updates design documentation to reflect window-restricted dense attention behavior and the remaining CSA/HCA gap.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines 569 to +573
# literally the same rotated `kv` tensor -- broadcasting
# `kv_num_heads=1` across all query heads is the fused op's own
# job, so `_expand_kv` isn't needed on this path. No explicit
# `attention_bias` is passed: this is a plain causal decoder
# attention (no sliding window, no KV-sharing across layers, no
# per-layer dual head_dim), so GQA's own implicit causal masking
# plus `seqlens_k`/`total_seq_len` already carries the exact same
# causal+padding semantics `create_attention_bias` bakes into an
# explicit float bias on the decomposed path below -- this is the
# same "direct GQA" convention `Attention._forward_gqa`
# (mobius/components/_attention.py) already uses for every other
# simple-causal model in this codebase (see the
# `attention-optimization` skill: "Use Contrib GQA when you don't
# need attention bias"). `head_sink` carries the learned per-head
# attention sink exactly as the decomposed path's
# `Concat(scores, sinks) -> Softmax -> slice` sequence does, now
# as a first-class op input instead of a manually broadcast
# Concat.
# `attention_bias` is passed: causal + padding is carried by
# `seqlens_k`/`total_seq_len` (no KV-sharing across layers, no
justinchuby added a commit that referenced this pull request Aug 25, 2026
## Summary

- clean up still-valid typing, documentation, test robustness,
error-message,
  maintainability, and performance findings left by the GGUF PR stack
- preserve the behavioral fixes merged in #625-#632
- hash reused multi-GB GGUF sources once, at the final pre-publication
integrity
  gate, while retaining cheap identity checks around staging

Exact base: `2db9d33debdc254d879a51b14434c9a81c230f4f`

Exact head: `4541ed2bc9d2ab4227484510b4a85b2d9113eb25`

## Reconstructed original 17-item low-priority tranche

The persisted audit retained only the totals, so this list was
reconstructed
from the live threads and current source. All but the already-fixed #596
comment are addressed in this PR.

| PR | Comment | Disposition |
|---|---:|---|
| #550 | 3837144656 | Implemented: correct tuple return annotation |
| #552 | 3837389183 | Implemented: multichannel waveform shape docs |
| #559 | 3837716261 | Implemented: name-based cache assertions |
| #573 | 3854308350 | Implemented: one final GGUF hash, with integrity
regression coverage |
| #574 | 3854345521 | Implemented: `TensorRole \| None` typing |
| #574 | 3854345597 | Implemented: removed obsolete verdict filtering |
| #577 | 3854472859 | Implemented: documented SSM sequence length |
| #578 | 3843112613 | Implemented: documented F64 passthrough |
| #579 | 3854518332 | Implemented: generalized fused-projection error |
| #580 | 3854576300 | Implemented: removed brittle node counts |
| #583 | 3854681386 | Implemented: documented conditional draft outputs
|
| #587 | 3854816872 | Implemented: corrected MTP output contract docs |
| #596 | 3846110059 | Already fixed on base: unambiguous GQA bias
comment |
| #600 | 3855174281 | Implemented: metadata-count-only MTP error |
| #607 | 3855776048 | Implemented: stable route-field assertions |
| #607 | 3855776086 | Implemented: public tensor iterator |
| #609 | 3856486136 | Implemented: fail-closed LM-head comment |

## Current unresolved-thread disposition

This covers all 48 Copilot threads returned by the reproducible
#600-#630
query. The one human #623 thread is excluded.

| PR | Comment | Current-main disposition and evidence |
|---|---:|---|
| #600 | 3855174177 | Already fixed by #629: package cycle and
reserved-sidecar validation |
| #600 | 3855174238 | Already fixed by #629: explicit MTP sidecar
naming/loading |
| #600 | 3855174281 | Implemented here: error no longer invents an
observed block count |
| #602 | 3848155961 | Outside exact stack; already fixed: top-level
`expert_dtype` is classified before early return |
| #602 | 3848155983 | Outside exact stack; still-valid behavioral
block-quant validation, unchanged |
| #602 | 3848156000 | Outside exact stack; still-valid truncated-read
behavioral finding, unchanged |
| #602 | 3848156022 | Outside exact stack; still-valid descriptor
byte/dtype validation, unchanged |
| #602 | 3848156040 | Outside exact stack; still-valid expert-bank
payload validation, unchanged |
| #603 | 3855249765 | Already fixed by #630: runtime preflight preserves
shard sets |
| #603 | 3855249840 | Already fixed by #630: success output follows
durable runtime publication |
| #604 | 3855343082 | Implemented here: graph-only MTP persistence
distinguished from runtime rejection |
| #604 | 3855343131 | Already fixed by #630: runtime success messages
are atomic |
| #607 | 3855776001 | Implemented here: missing generation golden skips
before provenance read |
| #607 | 3855776048 | Implemented here: only stable route fields are
asserted |
| #607 | 3855776086 | Implemented here: tensor count uses
`tensor_items_raw()` |
| #608 | 3856079371 | Still-valid behavioral cache-symlink containment
finding; unchanged |
| #608 | 3856079415 | Still-valid behavioral lowercase-digest validation
finding; unchanged |
| #609 | 3856486136 | Implemented here: comment matches value-preserving
policy |
| #610 | 3855541683 | Already fixed by #628: Falcon bias precedence is
explicit |
| #610 | 3855541761 | Already fixed by #628: CTRL tiny config exercises
projection biases |
| #611 | 3856595840 | Implemented here: runtime test resolves the
distribution providing the module |
| #612 | 3855677383 | Already fixed by #625: supported-version
endianness detection |
| #612 | 3855677427 | Implemented here: shared `INT64_MAX` sentinel |
| #612 | 3855677460 | Implemented here: shared PLaMo2 width inference |
| #612 | 3855677486 | Implemented here: accepted PLaMo2 activation
spellings are explicit |
| #613 | 3855845678 | Implemented here: canonical issue URL |
| #613 | 3855845757 | Implemented here: Mamba-1 function-registration
docs |
| #613 | 3855845806 | Implemented here: test expects the canonical issue
URL |
| #614 | 3855988545 | Implemented here: removed stale Nemotron-H
divergence comments |
| #614 | 3855988597 | Already fixed by #628: zero-head geometry raises
actionable `ValueError` |
| #615 | 3856082290 | Already fixed by #626: dense GraniteHybrid bias
closure |
| #618 | 3856729330 | Implemented here: required routes filter ORT GenAI
evidence |
| #618 | 3856729409 | Implemented here: env-selected runtime version is
authoritative |
| #618 | 3856729490 | Stale/N/A: PR-description-only matrix claim;
repository workflow claims one pinned version |
| #618 | 3856729563 | Implemented here: schema tail restored to normal
indentation |
| #619 | 3856342484 | Already fixed on base: Kimi Linear uses
`/issues/605` |
| #619 | 3856342532 | Already fixed by #628: config rejects convolution
kernels below 2 |
| #619 | 3856342580 | Already fixed by #628: GGUF contract rejects
convolution kernels below 2 |
| #620 | 3855717041 | Already fixed by #627: tied LM-head-only
checkpoints are retained |
| #621 | 3856722324 | Already fixed by #628: Kimi-K3 required metadata
is complete |
| #623 | 3855931210 | N/A to current main: comment belongs to open,
unmerged #623 |
| #623 | 3855939302 | N/A to current main: comment belongs to open,
unmerged #623 |
| #623 | 3855939358 | N/A to current main: comment belongs to open,
unmerged #623 |
| #623 | 3855939394 | N/A to current main: comment belongs to open,
unmerged #623 |
| #624 | 3856777152 | Implemented here: runtime compatibility reuses the
emitted model type |
| #625 | 3857049733 | Implemented here: unsupported header reports both
endian candidates |
| #629 | 3857313182 | Newer post-audit behavioral sidecar-symlink
cleanup finding; unchanged |
| #629 | 3857313251 | Newer post-audit cross-platform path-safety
finding; unchanged |

## Validation

- affected GGUF/package/ORT GenAI/model/schema tests: 1,040 passed
- broad non-integration suite: 7,851 passed, 56 skipped, 1 subtest
passed
- generated GGUF docs checks: 7 passed
- initialized `lintrunner`; full lint/format passed
- GPT-5.6 Sol medium review: one integrity finding fixed; re-review
found no significant issues

Signed-off-by: Justin Chu <[email protected]>
Co-authored-by: Copilot App <[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