Skip to content

feat(speculative): add DeepSeek-V4.1 bundled DSpark drafter (#3262) - #3686

Merged
inureyes merged 6 commits into
mainfrom
feat/issue-3262-deepseek-v41-dspark
Dec 4, 2026
Merged

inureyes merged 6 commits into
mainfrom
feat/issue-3262-deepseek-v41-dspark

Conversation

@inureyes

@inureyes inureyes commented Dec 2, 2026 •

Copy link
Copy Markdown
Member

Summary

Every DeepSeek-V4.1 checkpoint ships a three-stage DSpark drafter under mtp.0 to mtp.2. This PR makes the same checkpoint usable as --draft-model / --model-draft, so DFlash speculative decoding runs against the V4.1 target.

  • src/models/deepseek_v41_dspark.rs (plus _tests.rs) implements the Drafter trait as a DFlash-kind drafter. It imports the V4.1 decoder pieces (V41Moe, V41Rope, fake_quant_fp8_ue8m0, the HyperConnections, hc_collapse) rather than copying them, canonicalizes mtp.N.* onto stages.N.*, repacks native scale sidecars, stacks the MoE experts, splits the flattened grouped wo_a into [o_groups, o_lora_rank, -1], drops the unused confidence head, and keeps a quantized Markov head packed by loading it through VanillaMarkovHead::from_weights (with the markov_head.embed / markov_head.head rename).
  • src/models/deepseek_v41.rs gains the capture_layer_ids tap (the HyperConnection-mean input, taken after the engram write) and a speculation transaction on the model-owned V4.1 cache: per-token snapshots, commit(accepted), abort(), and errors for a nested start or an out-of-range commit. Verification replays each row as one classic decode step, so temperature-0 output is byte-identical by construction.
  • Core detection resolves a deepseek_v41 / deepseek_v41_text directory to DrafterKind::Dflash when the last stage's mtp.{n-1}.markov_head.* tensors exist. That arm sits above the generic num_nextn_predict_layers rule from feat: Load bundled Qwen 3.5 MTP drafters and detect native MTP heads #2400, and core load_drafter refuses the family with BinaryCrateDrafter.
  • Server and CLI wiring: DFlashDrafterFamily::DeepseekV41DSpark, DFlashTargetModel for the text and VL models (EveryPromptRow, supports_batched() = false, exactness allowed at every width), the binary-side drafter_loader, block-size peeking (so the default is the runtime min(2, block_size)), and the offline mlxcel generate --draft-model and server --model-draft paths.

Validation

Unit tests run on this host:

  • deepseek_v41_dspark_tests::config_derives_block_and_runtime_width (3 stages, verify width 6, runtime width 2, mask 128799, taps [37, 38, 39], explicit runtime width wins).
  • deepseek_v41_dspark_tests::sanitize_maps_stages_and_drops_confidence_head (stage rename, expert stacking, grouped wo_a, f32 router, confidence head dropped).
  • deepseek_v41_dspark_tests::quantized_markov_head_loads_without_cast (packed factors stay packed and match the dense reference within 1e-3).
  • deepseek_v41_dspark_tests::a_v41_checkpoint_with_markov_tensors_resolves_to_dflash_before_generic_mtp (the ordering requirement: DFlash, not Mtp, and core refuses with BinaryCrateDrafter).
  • deepseek_v41_dspark_tests::without_markov_tensors_the_generic_mtp_rule_still_captures_a_v41_declaration (the control that makes the ordering meaningful).
  • deepseek_v41_tests::speculation_commit_equals_shorter_forward (committing n = 0..=4 of a 4-token transaction equals a plain forward over n tokens, with compression and engram state).
  • deepseek_v41_tests::speculation_rejects_a_nested_start_and_an_out_of_range_commit.
  • dflash_target::a_v41_target_requires_its_bundled_dspark_and_declines_lfm2.

Also green: cargo fmt --check; cargo clippy -p mlxcel-core --lib --tests -- -D warnings; cargo clippy -p mlxcel --lib --tests --bins -- -D warnings; check_env_var_docs.py, check_cross_repo_refs.py, check_kernel_dtype_keys.py, check_crate_versions.py, check_technical_reports_layout.py.

The real-checkpoint test ran on an M3 Ultra with 512 GB of unified memory using mlx-community/DeepSeek-V4.1-Flash-MLX-2bit. Ordinary CLI generation, CLI with the bundled drafter, and the server completion endpoint produced the same 128 token IDs and identical UTF-8 bytes at temperature zero for “Explain the Sinkhorn algorithm briefly.” The CLI and server each accepted 8 of 15 proposals in 119 rounds. The ordinary CLI run measured 9.84 tokens/s and the speculative run measured 8.47 tokens/s.

The checkpoint required preserving engram projection names and affine expert sidecars, matching the two-layer hash layout, and padding the final partial index block correctly. The CLI now uses the binary-side drafter loader. Regression tests cover the checkpoint layouts and partial blocks. The generated text was repetitive and a separate mlx-vlm probe emitted a different sequence for the same prompt IDs. These measurements establish equivalence among mlxcel decoding modes.

The macOS Metal workspace gate (make verify-test) finished with 18,842 passed, 576 ignored, and zero failures. After a test-only iterator cleanup, all eight Step3p7 integration tests passed again. Workspace all-targets Clippy with Metal and Accelerate, formatting, and technical report layout checks passed.

Closes #3262

DeepSeek-V4.1 checkpoints bundle a three-stage DSpark head under `mtp.0..2` and no mlxcel path could run it: `resolve_drafter_kind` sent the family through the generic `num_nextn_predict_layers` rule to `Mtp`, core `load_drafter` had no builder for the V4.1 block stages, and the model-owned V4.1 cache could not rewind a verify block to its accepted prefix.

Add `src/models/deepseek_v41_dspark.rs` (+ tests), a binary-side DFlash-kind drafter that imports the V4.1 block, attention, MoE, HyperConnection and fake-quant code instead of copying it. Add the `capture_layer_ids` hidden tap and a per-token speculation transaction (`start` / snapshot / `commit` / `abort`) on the V4.1 cache, with verification replayed as single-token steps. Resolve the family to `DrafterKind::Dflash` from the last stage's `markov_head.*` tensors above the generic MTP rule, refuse it in core with `BinaryCrateDrafter`, and wire the server family, `DFlashTargetModel` for the text and VL models, the drafter loader, block-size peeking and the offline/server drive paths.

The integrated real-checkpoint check is deferred: it needs the 238.8 GB `mlx-community/DeepSeek-V4.1-Flash-MLX-2bit` pack on a 256 GB+ unified-memory host, while this work was developed and unit-tested on a 128 GB M1 Ultra. The PR body lists the unit tests that cover every other acceptance criterion and the pre-existing, unrelated fake-quant test failure observed on this host.
@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:low Low priority area:inference Generation, sampling, decoding (incl. speculative, DRY) modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:text Text-only language model arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) status:done Completed labels Dec 2, 2026
@inureyes inureyes self-assigned this Dec 2, 2026
inureyes and others added 4 commits December 3, 2026 08:13
The published drafter has 64 attention heads. Broadcasting its sinks over the query positions expanded a one-token proposal to 64 rows and aborted the first draft round. Normalize each head independently and cover both single-token and multi-token queries.

Bound stage indexing and width arithmetic when reading checkpoint metadata. Cover the split drafter in the model-type registry test and serialize the quantized Markov test on the shared MLX device.

Refs #3262
@inureyes
inureyes marked this pull request as ready for review December 4, 2026 02:50
@inureyes
inureyes merged commit be51bc3 into main Dec 4, 2026
36 checks passed
inureyes added a commit that referenced this pull request Dec 4, 2026
#3686 added the MLX test guard to the nemotron_h_nano_omni pos_embed resample test that failed the guard coverage scan. The other MLX-building tests in that file (vision tower forward and loader tests) now take the guard too, through a module-level import.

The catalog projection read gpu_backend_kind() deep inside metadata_for, so on a no-GPU build every qwen fixture projected as not runnable and five catalog tests failed. The backend kind is now a parameter of catalog_entry, single_model_entry_with_provider and metadata_for. CatalogProjectionCache resolves gpu_backend_kind() lazily as before, and a test-only with_backend constructor pins a kind. The catalog test module pins Metal for its helpers, and a new test asserts the GpuBackendKind::None reason through both a direct projection and the cache.

Closes #3764
inureyes added a commit that referenced this pull request Dec 4, 2026
## Summary

- #3686 already guarded `pos_embed_resample_runs_in_f32`; the other MLX-building tests in `nemotron_h_nano_omni_tests.rs` (vision tower forward and loader tests) now take `mlx_test_guard()` too, and the guard coverage scan passes.
- The catalog projection takes the GPU backend kind as an input instead of calling `gpu_backend_kind()` inside `metadata_for`. `CatalogProjectionCache::new()` still resolves the runtime backend lazily, so production behavior is unchanged; a test-only `CatalogProjectionCache::with_backend` pins a kind. No process-global override is involved, so parallel tests cannot race.
- Catalog tests project for a pinned `GpuBackendKind::Metal`, so the five tests that failed on default-feature Linux builds now pass there. A new test pins `GpuBackendKind::None` and asserts the "architecture is not runnable on the current backend" reason through both a direct projection and the cache.

## Test plan

- [x] `cargo test --lib server::webui::catalog` on default features (43 passed) and with `--features cuda`
- [x] `cargo test --test mlx_test_guard_coverage`
- [x] `cargo clippy --all-targets -- -D warnings` on default and cuda features, `cargo fmt --check`

Closes #3764
inureyes added a commit that referenced this pull request Dec 4, 2026
Follow-up to #3686. DeepSeek V4.1 conversions that omit the chat template now use the official turn format in CLI and API requests. The fallback defaults to direct answers and supports explicit reasoning requests.

Match FP8 activation rounding, expert weighting, attention sinks, compressed attention and residual accumulation to the training-time numerical conventions. Bound sliding-window prefill while retaining the preceding keys at chunk boundaries.

On the real 2-bit checkpoint, ordinary and DSpark CLI decoding produced identical token IDs on a 128-token greedy probe, and the chat API returned identical bytes. Repeating the probe after integrating the latest main produced 621 matching bytes across all three paths. A Korean request for the capital of France returned 파리 and stopped. Long greedy explanations still repeated in both mlxcel and mlx-vlm, with different continuations.

Local validation passed 103 V4.1 tests, formatting and Clippy. The full workspace run passed 18,844 tests with one Laya parity failure. The pre-change binary reproduced the same discrepancy on the same local checkpoint (1.1712 versus 1.1694).

The WebUI and OpenXLA CUDA builds reused an obsolete fp_qmv.cu from a previous overlay. Extend the existing configure-time restoration to tracked CUDA backend paths absent from the current overlay set so cached builds compile the pinned source.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

arch:hybrid Hybrid attention stack (linear/sliding/full or attention+SSM interleave) area:inference Generation, sampling, decoding (incl. speculative, DRY) modelsize:xlarge 4-bit checkpoint > 100GB; exceeds a 128GB dev box, needs bigger hardware modeltype:text Text-only language model priority:low Low priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(speculative): DeepSeek-V4.1 bundled DSpark drafter

1 participant