Skip to content

feat(gemma4): DSpark speculative decoding (DeepSeek DeepSpec external draft) - #86

Merged
Brooooooklyn merged 13 commits into
mainfrom
feat/gemma4-dspark
Jul 6, 2026
Merged

Brooooooklyn merged 13 commits into
mainfrom
feat/gemma4-dspark

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds DSpark speculative decoding for Gemma 4, using DeepSeek's DeepSpec released draft checkpoint deepseek-ai/dspark_gemma4_12b_block7 (external 5-layer draft transformer for google/gemma-4-12B-it).

ChatSession (enableMtp auto-on when draft loaded)
  └─ gemma4 dspark_chat_turn
       ├─ chunked prefill w/ hidden taps @ layers [5,17,29,41,46]
       └─ engine run_dspark_turn (per cycle)
            ├─ draft: [anchor, MASK×6] → one non-causal forward
            │         + sequential markov head + confidence truncation
            ├─ verify: ONE target forward over 1+L tokens (w/ taps)
            ├─ accept: greedy argmax / Leviathan rejection sampling
            └─ commit: global KV trim + sliding snapshot/re-append
                       (explicit KV-shared-slot mask, validated every commit)

Usage

const session = await loadSession('.cache/models/gemma-4-12b-it', {
  draftModelPath: '.cache/models/dspark_gemma4_12b_block7',
});
const res = await session.send('...');   // enableMtp auto-enabled
res.performance.mtpCycles / mtpMeanAcceptedTokensTotal  // acceptance stats

Correctness

Speculative decoding is lossless at T=0: the E2E oracle asserts greedy byte-equality vs plain AR — including generation crossing the sliding-window (1024) wrap, wrap during prefill, stop shapes (EOS as boundary AND as accepted draft), warm-continue delta turns, and streaming==sync.

  • Rust #[ignore] suite: 6/6 black-box + white-box regressions green on the real 12B + draft (--release --test-threads=1)
  • TS gated e2e green; full cargo test -p mlx-core (2000+), vp test (1415), clippy -D warnings, fmt, typecheck all clean

Performance (M5 Max, bf16 12B target)

Mean accepted 2.86–6.05 tokens/cycle depending on content; decode up to 2.46× AR (46.8 vs 19.0 tok/s).

Notable internals

  • RotatingKVCache::snapshot had a latent aliasing bug (snapshot shared storage with in-place single-token writes) — fixed and hardened for all existing users
  • Sliding-window rollback: snapshot-before-verify + restore + re-append of the verify block tail — exact pre- and post-wrap (mlx-lm's trim-based approach silently breaks post-wrap)
  • Draft geometry pinned at load (5L/16H/512/rope/block-7, bf16-only, mask-token bounds); draft weights materialized at load (cold-mmap watchdog class); draft's 6.9GB counted in cache-limit accounting
  • Cancel/stream residual semantics deliberately match the documented AR/MTP contract (engine/decode.rs), pinned by tests
  • Memory: +6.9 GB bf16 draft; docs note the requirement. mtpDepth caps the block (≤7); mtpAdaptiveDepth is ignored for gemma4 (confidence head is DSpark's adaptive mechanism)

Eagle3 (eagle3_gemma4_12b_ttt7) can follow as a small PR — it shares the tap/verify/rollback infra added here.

🤖 Generated with Claude Code


Note

High Risk
Large new decode path touching KV commit, sliding-window rollback, and load-time memory (~7GB draft); incorrect cache or accept logic would change generation semantics despite T=0 oracles.

Overview
Gemma 4 can load an external DSpark draft via Gemma4Model.load(..., { draftModelPath }) (flat KV only; paged cache is rejected or forced off). hasMtpWeights() exposes draft availability so ChatSession can auto-enable the speculative path (enableMtp), reusing existing MTP perf fields for cycle stats.

The core addition is an engine-owned propose → verify → accept → pre-commit stop-clamp → commit loop (run_dspark_turn) behind new DsparkBackend / DsparkStepper traits, plus a large dspark.rs module (checkpoint validation, fused context from tapped target hiddens, markov + confidence truncation, bf16 loader). Greedy output is intended to be lossless at T=0; a gated TS e2e mirrors the Rust greedy byte-match oracle.

MxArray.addmm is changed to an explicit matmul+scale+add path instead of fused addmm, avoiding a known local metallib miscompile that dropped bias terms (notably in biased vision linears).

Docs/README note Gemma4 DSpark; NAPI/types add Gemma4LoadOptions. Qwen3.5 config comments are updated for VLM default-on block-paged cache and image-turn behavior (not a full new feature in this diff slice).

Reviewed by Cursor Bugbot for commit a656f33. Bugbot is set up for automated code reviews on this repo. Configure here.

Brooooooklyn and others added 13 commits July 6, 2026 11:08
Standalone DeepSeek DSpark draft module for Gemma 4 speculative decoding:
serde config + target-geometry validation, 5-layer cross-attending backbone
(MQA global-head geometry, attention_k_eq_v, proportional RoPE, non-causal
ctx+block SDPA at scale 1.0), per-layer context K/V cache, scaled own
embedding, untied softcapped lm_head, vanilla markov bias head with
sequential block sampling, confidence head with pure truncation helper, and
a completeness-gated bf16 safetensors loader for the 74-tensor draft
checkpoint. Gemma4ProportionalRoPE promoted to pub(crate) (visibility only).
Engine wiring lands separately.

Co-Authored-By: Claude Fable 5 <[email protected]>
Review fixes: validate() no longer trusts config-derived geometry for the
74-tensor completeness contract — num_hidden_layers=5, 16 Q heads, 1 KV
head, global_head_dim=512, enable_confidence_head=true, rope factor 0.25 and
theta 1e6 are pinned with per-field errors, so a config-consistent but
wrong-shape checkpoint can no longer load under a weaker expected-key set.
The weight-install seam (take_tensor) now rejects any non-bf16 tensor with a
key-specific error; f32 stays confined to runtime readbacks. Adds 7
pinned-geometry negative tests and 3 apply_weights seam tests (complete
synthetic bf16 set, f32 rejection, missing+leftover key listing).

Co-Authored-By: Claude Fable 5 <[email protected]>
… in-place updates

MxArray::clone shares the same C-side handle (Arc), and temporal_order
returns a clone of the live storage when it is already temporally ordered
(idx == cache_len). The single-token update path overwrites that handle's
descriptor in place, so a RotatingKVCacheSnapshot taken in that state was
silently rewritten by the next single-token append — corrupting any later
restore (speculative-decode rollback, checkpoint heal re-restore).

snapshot() and restore_snapshot() now take/store full-range slice_axis
views: a slice is a new array object capturing the descriptor by value,
unreachable by overwrite_descriptor on the live cache. Lazy, O(1), no
data copy. Pinned by test_snapshot_is_immune_to_in_place_updates.

Co-Authored-By: Claude Fable 5 <[email protected]>
Target-side pieces the DSpark speculative-decode engine loop builds on:

- DsparkTap (dspark.rs): per-layer residual-stream capture request; ids
  strictly ascending, one [B, T, hidden] push per tapped layer per forward
  (post residual add, pre final-norm — HF hidden_states[i+1]).
- Tap threaded through forward_body / forward_inner / prefill_body_gemma4;
  all existing callers pass None (byte-identical graph, proven by the
  tap-purity test on a tiny random-weight hybrid model with a KV-shared
  layer). dspark_verify_forward runs a [1, T] block at the current cache
  offset with a tap and returns [1, T, vocab] logits; no sampling, no
  history bookkeeping, caches advance by T.
- Rollback primitives (layer_cache.rs): trim_global (global-only trim),
  sliding_tail (last n window entries in temporal order),
  Gemma4VerifyRollback + snapshot_before_verify / commit_after_verify.
  Partial keep trims global caches and restore+re-appends the kept block
  prefix on sliding caches, leaving state byte-identical to a cache that
  only ever saw the kept prefix — exact pre-wrap, post-wrap, rotated
  storage, empty prefill, and keep == 0, for every keep in 0..=T.
  KV-shared layers' never-written cache entries are skipped, so each
  physical cache is touched exactly once.

Co-Authored-By: Claude Fable 5 <[email protected]>
Engine-owned, model-agnostic DSpark draft/verify whole-turn loop:

- engine/backend.rs: DsparkBackend/DsparkStepper trait pair (+
  DsparkTurnSetup, DsparkProposal, DsparkVerifyOutput) next to the MTP
  traits. Tapped hidden states never cross the trait: the stepper
  stashes them in verify and consumes them in commit.
- engine/dspark_turn.rs: run_dspark_turn mirrors run_mtp_turn's
  structure (initial-y emit guarded by budget, pre-cycle stop-check
  order and finish-reason strings, emit-block bookkeeping, every-256-
  token cache clear) with DSpark's own cycle body: propose (L_cap =
  min(block_size, mtp_depth, remaining-1); L_cap == 0 degenerates to a
  single AR step THROUGH verify) -> one batched verify over
  [anchor, drafts..] -> greedy batched-argmax or per-position
  accept_with_residual acceptance -> STOP-CLAMP BEFORE COMMIT (budget /
  cancel / EOS / repetition resolved on the accepted list first) ->
  commit(keep = 1 + min(emit_count, k), 1 + L) exactly once -> emit.
  last_in_cache is true iff the last emitted token's K/V is in the
  target cache (boundary tokens are not). Deliberate divergence from
  MTP: cancellation is checked at the cycle top and in the stop-clamp,
  not per emitted token, bounding cancel latency to <= block_size + 1
  tokens while keeping caches desync-free (gemma4 has no heal path).
- 12 MockDsparkStepper ledger tests (TDD: keep-math/stop-clamp cases
  written RED against a clamp-less loop first): emission order + commit
  ledger, EOS-at-draft / EOS-at-boundary keep math, budget and
  repetition mid-block clamps, degenerate remaining==1 cycle, propose
  max_len caps, record_mtp_cycle stats seam, streaming/sync chunk
  parity, cancel at cycle boundary and inside the clamp, sampled
  all-accept + first-reject residual paths.

Task 4 wires the gemma4 stepper against these traits.

Co-Authored-By: Claude Fable 5 <[email protected]>
Two adversarial-review findings on the DSpark turn loop:

- Over-long proposals no longer bypass L_cap: run_dspark_turn hard-
  errors at the proposal boundary (before verify writes any target-
  cache slot) when propose returns more than the requested cap. The
  DsparkProposal/propose docs now state "fewer, never more". The old
  budget-clamp test that enshrined the over-return is replaced by an
  exact-budget-fit compliant case (a compliant mid-block budget cut is
  arithmetically unreachable: L <= l_cap <= remaining-1 bounds a cycle
  to at most `remaining` emitted tokens; the clamp's budget arm stays
  as documented defense-in-depth) plus a test asserting the over-
  return error with verify never called.

- Greedy temperature with active penalties no longer errors: at
  is_greedy_temperature, acceptance is ALWAYS argmax-based and never
  requires proposal dists or RNG. penalties_no_op now only selects
  between the batched-argmax fast path and a new penalized-greedy arm
  (per-row apply_all_penalties over the sequentially extended history,
  argmax accept, argmax boundary) — behaviorally identical to
  run_mtp_cycle's T=0-with-penalties legacy dense branch, where
  accept_with_residual's T=0 shortcut reads the penalized argmax and
  the bonus sample degenerates to it. Trait docs updated (draft_dists
  empty whenever the temperature is greedy). New test drives T=0 +
  repetition_penalty with EMPTY dists through rows where raw and
  penalized argmax disagree, and a counting-RNG wrapper proves zero
  draws.

14/14 dspark_turn mock tests green; full cargo test -p mlx-core exit 0;
clippy -D warnings + fmt clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
…every commit

Review finding (High): commit_after_verify inferred the active/KV-shared
distinction from offsets — full keep early-returned with zero validation,
and on partial keep an ACTIVE cache the verify forward failed to write was
indistinguishable from a shared slot and silently accepted, leaving that
physical cache at the old prefix while the turn considered the tokens
committed.

snapshot_before_verify now takes a caller-declared shared_slots mask
(length-validated, stored in Gemma4VerifyRollback), built from config via
the new dspark_shared_slot_mask helper (is_kv_shared_layer per layer).
commit_after_verify validates the whole vec on EVERY commit, full keep
included: active caches must sit at exactly start + total_written, shared
slots must not have moved — specific errors naming the offending cache.
Validation runs before any mutation, so a failed commit leaves all caches
untouched. Partial-keep rollback behavior for active caches is unchanged.

Tests: unmoved active cache fails partial keep (and mutates nothing),
unmoved active cache fails FULL keep (previously swallowed), moved shared
slot fails both, mask-length mismatch rejected; all prior scenarios
re-pass with the mask; model-level purity test now drives the real
snapshot -> dspark_verify_forward -> partial commit flow with the
config-derived mask.

Co-Authored-By: Claude Fable 5 <[email protected]>
Implement the family side of the engine-owned DSpark loop
(engine::dspark_turn::run_dspark_turn) for Gemma 4:

* NEW models/gemma4/dspark_decode.rs — Gemma4DsparkStepper
  (propose: [anchor, MASK×(L-1)] forward_block + markov-chained
  sample_block_sequential + confidence truncation via
  MLX_DSPARK_CONFIDENCE_THRESHOLD, read once at stepper construction;
  verify: snapshot_before_verify with the config-derived shared-slot
  mask + dspark_verify_forward with the target-layer tap; commit:
  commit_after_verify + fuse the kept tapped prefix into the draft
  context at the block's absolute base; eval_boundary: async token
  eval), impl DsparkBackend for Gemma4Inner, and the dspark_chat_turn
  whole-turn core (sync + streaming through one body): prefix decision
  via the existing cache-prefix machinery, chunked prefill WITH the tap
  (per-chunk capture→fuse→append→drop; target compute byte-identical to
  the AR prefill), generic-flow anchor sampling, run_dspark_turn, save
  with drop-last driven by the loop's last_in_cache, default
  augment_performance filling the mtp_* acceptance stats.
* models/gemma4/model.rs — Gemma4Inner::{dspark, dspark_turn_state}
  fields, ChatBackend::mtp_turn override (enableMtp && draft loaded &&
  flat KV && text-only), resolve_params family depth (unset ⇒ draft
  block_size; explicit ⇒ clamp [1, block_size] from the raw config
  value; shared [1,5] clamp untouched), deleted the no-op
  augment_performance override, NAPI Gemma4LoadOptions
  { draft_model_path } + Gemma4Model::load(path, options) +
  has_mtp_weights() (mirrored dspark_active), test-only streaming
  entry.
* models/gemma4/persistence.rs — thread the draft path through load:
  hard error on draft + EXPLICIT use_block_paged_cache=true (before any
  weight I/O; unit-tested), unset default forced to flat, draft loaded
  after the body with loader errors propagated verbatim + cold-mmap
  prewarm.
* models/gemma4/dspark.rs — reconcile the draft sampler's greedy
  predicate with the engine's sampling::is_greedy_temperature (the
  private 1e-5 threshold disagreed on temperatures in (1e-6, 1e-5),
  which would hard-error the sampled accept path); pinned by a unit
  test.
* Removed the now-stale #[allow(dead_code)] scaffolding markers on the
  wired DSpark seams (engine/dspark_turn.rs, engine/backend.rs,
  gemma4/layer_cache.rs); hand-synced both index.d.cts copies.

E2E-proven on the real Gemma-4-12B-IT + dspark_gemma4_12b_block7
checkpoints: greedy byte-equal to plain AR across multi-cycle decode,
sliding-window wrap mid-decode AND mid-prefill, and a stop +
warm-continue 2-turn session; decode speedup up to 2.46x (46.8 vs 19.0
tok/s) at mean 6.05 accepted tokens/cycle on constrained text.

Co-Authored-By: Claude Fable 5 <[email protected]>
Six env-gated #[ignore] tests against the real Gemma-4-12B-IT target +
dspark_gemma4_12b_block7 draft (MLX_TEST_GEMMA4_MODEL_PATH /
MLX_TEST_GEMMA4_DSPARK_PATH; single-threaded, release):

1. dspark_greedy_matches_ar_multi_cycle — PRIMARY ORACLE: 200-token
   T=0 run byte-equal (text/raw_text/finish_reason/num_tokens) to the
   plain-AR run on the same instance, with real cycles recorded.
2. dspark_greedy_matches_ar_across_sliding_wrap — the RotatingKVCache
   trap: byte-equal with the 1024-token sliding window wrapping BOTH
   mid-decode (832-token prompt + 600 generated, asserted to cross) and
   mid-prefill (>1100-token prompt + 300 generated).
3. dspark_stop_mid_block_then_delta_turn — early-EOS stop parity, then
   a warm-continue delta turn on the same session; 2-turn transcript
   byte-equal to the AR 2-turn baseline (cached_tokens > 0, cycles > 0).
4. dspark_acceptance_sanity — draft-fidelity floor on natural prose:
   mean accepted tokens/cycle >= 2.0 (observed 3.62).
5. dspark_sampled_smoke — T=0.7 completes with sane stats.
6. dspark_stream_matches_send — terminal-chunk raw_text byte-equal to
   the sync run (token-stream oracle) + chunk-concat parity modulo the
   parser's pre-existing trailing trim on channel-only promotion
   (verified identical on the plain-AR path).

The module doc records the measured bf16 near-tie phenomenon (T>1
verify kernels vs T=1 decode kernels flip greedy argmax at top-2 gaps
<= ~2 bf16 ULP; cross-tiling depth-1/2/7 byte-agree while AR differs at
exactly one tied token) and the tie-free fixture-selection rule that
keeps the byte-equal oracle strict.

Co-Authored-By: Claude Fable 5 <[email protected]>
…aft weight accounting

Adversarial-review fixes (3 verified findings):

1. In-cycle stop tokens are never committed (AR parity). The engine
   stop-clamp now excludes the tripping token's verify slot when the cut
   lands on an accepted draft (keep = 1 + emit_count - 1) and reports
   last_in_cache = false on every stop cut, so the save drops the stop
   token from cached_token_history exactly like the AR flow — which
   never forwards its final token on a non-length stop. Length exits now
   materialize the final boundary token's K/V (dspark_materialize_final,
   the AR materialize_final analog) and keep-all. Post-turn history AND
   physical cache offsets equal the AR session's for every stop shape.
   Mock keep-math tests updated + new j=0 edge test; new env-gated
   white-box e2e pins the EOS-accepted-as-draft SHAPE via mtp stats
   (deficit = 1 + sum(k) + cycles - num_tokens = 3 on the fixture) and
   asserts byte-equal cached_token_history vs an AR baseline across a
   2-turn warm-continue, plus offsets == history length per layer.

2. Turn errors fail CLOSED. Any error between prefill start and the
   save (prefill, anchor sample, eval, loop, materialize) now drops the
   whole warm session via reset_caches_sync + clears the draft stash,
   so a later prefix-reuse hit can never warm-start on K/V the history
   does not cover. New regression injects a real snapshot_before_verify
   window violation through dspark_chat_turn (sliding_window 2, depth 3)
   and proves the session is not warm-reusable, then a depth-1 turn
   recovers cold with fully consistent history/offsets.

3. Draft weights count toward the cache limit. load_draft_model sums
   checkpoint tensor bytes before apply_weights drains the map;
   Gemma4Inner::load_from_dir folds them into the deterministic
   weight-byte total (measured 6.86 GB on the real draft). Exact-sum
   unit test through a v1-contract mini checkpoint + env-gated two-load
   e2e (with == without + draft, strictly larger).

Gates: full cargo test -p mlx-core green; 6/6 real-model e2e suite green
(--release --test-threads=1); both new env-gated e2e regressions green;
clippy -D warnings + fmt clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
Thread the Task-4 NAPI surface (Gemma4Model.load(modelPath, options?),
Gemma4LoadOptions.draftModelPath, hasMtpWeights) through @mlx-node/lm:

- loadModel/loadSession accept LoadModelOptions { draftModelPath? };
  the option reaches ONLY the gemma4 registry row — every other family
  rejects it with a clear error instead of silently ignoring it.
- makeStreamingModel's static load now forwards trailing load options
  to the native class, and the factory return type keeps each family's
  native load signature via Parameters<C['load']> ([modelPath] for
  most, [modelPath, options?] for Gemma4).
- ChatSession: no logic change — mergeConfig's duck-typed
  hasMtpWeights() auto-default already covers the DSpark draft; jsdoc
  documents that, plus the gemma4 knob reinterpretation (mtpDepth caps
  the 7-token draft block, clamped [1, blockSize]; mtpAdaptiveDepth is
  ignored).
- packages/core/index.d.cts regenerated by yarn build:native;
  crates/mlx-core/index.d.cts hand-synced byte-identical (also clears
  stale doc drift vs current Rust doc comments). The extra
  hasMtpWeights jsdoc line ("reports an external DSpark draft model,
  not in-checkpoint MTP heads") lives in the Rust doc comment so
  regens keep it.
- New env-gated e2e (MLX_TEST_GEMMA4_MODEL_PATH +
  MLX_TEST_GEMMA4_DSPARK_PATH): greedy send on a draftModelPath session
  byte-matches a no-draft session and reports mtpCycles > 0; skipped
  when the env is unset.

Co-Authored-By: Claude Fable 5 <[email protected]>
docs/models.md gains a DSpark section (draft checkpoint
deepseek-ai/dspark_gemma4_12b_block7, loadSession example with
draftModelPath, T=0 losslessness, mtpCycles /
mtpMeanAcceptedTokensTotal stats, ~6.9 GB bf16 draft memory note,
flat-KV constraint) and the Gemma4 capability row mentions it; README
adds a one-line speculative-decoding pointer.

Co-Authored-By: Claude Fable 5 <[email protected]>
…t weights at load, pin cancel-stream contract

Whole-branch review fixes:

1. Cancelled-stream residual semantics: VERIFIED AR/MTP-consistent, not a
   leak — the AR loop pushes the cancel-observed token at the loop top,
   breaks before detok, and its unconditioned residual flush re-streams
   decode(generated)[streamed..] by documented origin/main design
   (engine/decode.rs cancel-snapshot comment); the MTP core and DSpark do
   the same, so total streamed text always reconstructs raw_text.
   Suppressing it only for DSpark would break cross-path consistency.
   Instead the contract is now pinned: the engine streaming harness
   exposes streamed_text_len and asserts the unstreamed suffix is EXACTLY
   the one cancel-observed token (never more) on the mid-clamp cancel,
   the seed on a boundary cancel, and empty on uncancelled turns; a new
   whole-turn regression through dspark_chat_turn proves a sink-raised
   cancel finishes "cancelled" with bounded block-granular overrun,
   AR-parity dropped-last state (history and offsets consistent), a
   warm-reusable session, and a working next turn. The residual flush
   carries a contract comment citing decode.rs. De-flake: the tiny
   fixture inherited eos_token_ids default [1] (in-vocab for the 16-token
   test vocab) — now explicitly empty; the cancel test pins the MLX PRNG.

2. DsparkConfig::validate pins block_size == 7 (v1 contract, like every
   other geometry constant — an unpinned block_size flows into the
   default mtp_depth and sizes every [1,1+L,vocab] verify forward, an
   OOM/abort reachable from the load surface) and bounds
   0 <= mask_token_id < vocab_size. Negative tests for both.

3. Draft weights are materialized at load: new
   DsparkDraftModel::collect_weight_arrays() enumerates all 74
   checkpoint tensors; the gemma4 loader feeds them to the same chunked
   materialize_weights pass the target uses, so the first speculative
   forward no longer evaluates ~6.9GB from lazy mmap (the qwen3.5
   cold-mmap watchdog class). Coverage test pins count == 74 AND byte
   total == weight_bytes through the real v1-mini checkpoint loader.
   GemmaMLP weight getters promoted from #[cfg(test)] to pub(crate).

Gates (all synchronous, exit codes checked): full cargo test -p mlx-core
green; 6/6 real-model e2e (--release --test-threads=1) EXIT=0; both
env-gated white-box e2e regressions EXIT=0; TS gated e2e EXIT=0; clippy
-D warnings + fmt + yarn typecheck clean.

Co-Authored-By: Claude Fable 5 <[email protected]>
@cursor

cursor Bot commented Jul 6, 2026

Copy link
Copy Markdown

Bugbot couldn't run - usage limit reached

Bugbot is counted against Cursor usage for this user or team, and this run hit a usage or spend limit.

A user or team admin can review and increase usage limits in the Cursor dashboard.

(requestId: serverGenReqId_e85df0ab-905f-4380-8926-bd8dadc923c9)

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 336c80a6-a158-4349-af4f-623fd2280f10

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/gemma4-dspark

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Brooooooklyn
Brooooooklyn enabled auto-merge (squash) July 6, 2026 17:01
@Brooooooklyn
Brooooooklyn merged commit c84764f into main Jul 6, 2026
7 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/gemma4-dspark branch July 6, 2026 17:06
Brooooooklyn added a commit that referenced this pull request Jul 7, 2026
…oints (#88)

## What

Adds gemma-4 **native MTP** speculative decoding: support for Google's
official assistant draft checkpoints
(`google/gemma-4-{12B,26B-A4B,31B}-it-assistant`, apache-2.0, ~800 MB)
as a **second draft variant** next to DSpark (#86), behind the same
`loadSession(path, { draftModelPath })` surface — the loader picks the
variant from the draft checkpoint's `config.json`.

```
DSpark (existing):    5-layer draft, masked block-7 proposals, tapped target hiddens
Assistant MTP (new):  4-layer draft, Q-only attention reading the TARGET's KV caches
                      (last non-KV-shared sliding/full layers), no draft KV, no prefill;
                      one token per step chained through a hidden feedback loop,
                      constant RoPE position per cycle; mtpDepth drafts/cycle (default 3, clamp [1,8])
```

Both variants share the engine turn loop (`run_dspark_turn`),
verify/rollback machinery, stop-clamp semantics, and telemetry. E2B/E4B
assistants (centroid sparse lm_head) are rejected at load with a clear
error — follow-up.

## Design

- `Gemma4Draft { Dspark, Assistant }` enum dispatch (invalid states
unrepresentable); `Gemma4DraftStepper`/`Gemma4DraftTurnState` enums
delegate the engine seam; whole-turn core generalized with exactly 3
variant points.
- Draft reads target K/V **verbatim** (target caches K post-RoPE) via
`get_cached_kv()` re-read after every commit; sliding caches return
temporally-ordered windows.
- Target-side seams: `lm_head_logits` extraction (pure refactor),
`assistant_verify_forward` (logits + post-final-norm hidden),
`assistant_kv_source_indices` (exact `layer_types` matching, consistent
with `should_store_shared_kv`).
- Greedy longest-prefix + Leviathan rejection sampling from the engine —
distribution-preserving at T>0 (stronger than mlx-vlm's naive match).
- **Zero TS surface changes** — proven by the TS e2e passing with no
edits under `packages/` (only doc comments + the server
`extra_body.mtp_depth` cap lift landed there).

## Verification

- **E2E oracles 6/6 green first run** on real 12B
(`tests/gemma4_assistant.rs`): greedy byte-parity vs AR incl.
sliding-window wraps, stop-mid-block + warm delta turn, acceptance
canary, sampled smoke, stream==sync. DSpark regression suite 6/6
unchanged. TS e2e mirror 1/1.
- Unit: 2078 lib tests green; clippy `-D warnings` + fmt clean;
typecheck + type-aware lint clean.
- Per-phase codex adversarial reviews (5 fix rounds all resolved: exact
layer_types KV mapping, draft-dim validation gates ×2, rawText parity
asserts, stale MTP docs + server depth cap) + whole-branch review
**PASS**.

## Numbers (M5 Max, bf16 12B target, greedy, cooled 3 min between runs)

Structured prompt (numbered pancake recipe, 200 tok — same prompt as the
PR #86/#87 quantized benches):

| Path | tok/s | vs AR | accepted/cycle |
|---|---|---|---|
| AR | 18.4 | — | — |
| **Assistant MTP** | **29.9** | **1.63×** | 3.25 |
| DSpark | 27.0 | 1.47× | 3.41 |

Open-prose prompt (pour-over brewing guide, run to EOS ~1.7k tok):

| Path | tok/s | vs AR | accepted/cycle |
|---|---|---|---|
| AR | 19.8 | — | — |
| **Assistant MTP** | **24.5** | **1.24×** | 2.80 |
| DSpark | 27.4 | 1.38× | 3.78 |

Speedup is acceptance-driven and prompt-dependent — the PR #86 "2.46×"
headline was the `decode_wrap` oracle fixture (highly predictable
600-tok continuation, accept 6.05/cycle, the ceiling); its `multi_cycle`
fixture printed 26.7 tok/s accept 3.49, matching these numbers exactly.
The assistant beats DSpark on the structured prompt despite lower
acceptance because its cycles are much cheaper (0.8 GB Q-only draft +
4-row verify at depth 3 vs 6.9 GB draft + 8-row verify at block 7); it
needs no per-cycle context fusion and no draft prefill.

Docs: `docs/models.md` speculative-decoding section covers both
variants; `ChatConfig.mtpDepth`/TSDoc scoped per family.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Large change to the Gemma4 speculative-decode and KV rollback path;
wrong assistant wiring could break greedy parity or session reuse,
though fail-closed reset and T=0 e2e oracles target that.
> 
> **Overview**
> Adds **Google `gemma-4-*-it-assistant`** as a second Gemma4 external
draft alongside DSpark, still loaded through **`loadSession` /
`draftModelPath`** with variant chosen from the draft `config.json`.
> 
> The assistant is a Q-only draft that reads the **target’s committed
KV** (no draft KV / DSpark-style context fusion), chains single-token
proposals with a fixed query position per cycle, and uses
family-specific **`mtpDepth`** (default 3, clamp **[1, 8]**). DSpark and
assistant share a refactored **`Gemma4Draft`** /
**`Gemma4DraftStepper`** / **`draft_chat_turn`** path instead of
DSpark-only `dspark_chat_turn` and `dspark_turn_state`.
> 
> **Server/API:** HTTP mappers stop capping `extra_body.mtp_depth` at 5;
they forward **6–8** and reject invalid values above **64**, leaving
per-family clamps to native code. NAPI/TSDoc now describe both draft
kinds and depth rules.
> 
> **Tests:** New env-gated TS e2e for assistant greedy **byte-parity vs
no-draft** plus real speculative cycles; DSpark e2e also asserts
**`rawText`** parity.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
aff9c98. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Fable 5 <[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.

1 participant