Skip to content

feat(cache): spec 020 — StateReplayCache protocol + native GDN state-replay kernels + iterator wiring - #143

Merged
ekryski merged 15 commits into
alphafrom
ek/020-tape-replay-phase1
May 12, 2026
Merged

ekryski merged 15 commits into
alphafrom
ek/020-tape-replay-phase1

Conversation

@ekryski

@ekryski ekryski commented Apr 29, 2026 •

Copy link
Copy Markdown
Owner

Lands state-replay rollback end-to-end for hybrid GDN+Attention models. Speculative decoders (n-gram today, future DFlash and Mirror SD) can now run on Qwen 3.5 / 3.6 without falling back to vanilla AR. Nemotron-H / Jamba cleanly opt out (per-instance flag) until their Mamba kernel variants land — no crash, no surprise.

Originally specced as a three-phase rollout (protocol → kernel → iterator); consolidated into a single PR so the whole chain is testable end-to-end. Phases 4 (DFlash iterator) and 5 (PrefixKVCache) are deferred to follow-ups on their parent specs' branches.

Mental model

The cache records per-step state-update (δ, k, g) triples into a delta log during the verify forward; on partial accept of k of N drafts, we replay the first (k + 1) log entries onto the pre-record state snapshot to recover the post-accept state — no need to re-run the layer. The +1 accounts for the y-baseline token (the previous round's bonus, always kept). Full accept skips the kernel entirely (state already advanced through all entries during verify).

(Originally written as "tape replay" / "innovation tape" — Kalman-filter terminology. Renamed 2026-05-08; math unchanged.)

What's here

Phase 1 — Protocol + dispatch helpers (Libraries/MLXLMCommon/StateReplayCache.swift)

  • StateReplayCache protocol — beginRecord → recordStep(_:) → commitFull / rollback(acceptedPrefix:) / cancel lifecycle.
  • recordStep(_ tensors: [MLXArray]) takes a tensor list from day 1 (carries the [delta, k, g] triple for GDN; extensible for future SSM variants).
  • StateReplayCacheError enum (alreadyRecording / notRecording / arityMismatch / outOfRange) per dflash-mlx 4bc72c8 fail-fast philosophy. Canonical conformances use Swift preconditions; the error enum is available for trim-fallback adapters.
  • Free helpers canRollbackPromptCache, beginCacheRecord, commitCacheRecord, rollbackPromptCache(_:acceptedPrefix:numDraft:), cancelCacheRecord. The helper encapsulates the iterator → protocol translation (acceptedPrefix + 1 entries to fold) so the protocol stays a low-level "fold first k entries" primitive and the iterator stays unaware of the entry count.

Phase 2A — SSMStateCache: StateReplayCache conformance (Libraries/MLXLMCommon/KVCache.swift)

  • SSMStateCache.isRecording: Bool public predicate so GDN layers can gate the kernel-routing branch.
  • canStateReplay: Bool stored property (default true, per-instance configurable) — Mamba-using factories opt out without subclassing.
  • Internal deltaLog: [[MLXArray]]? storage; snapshot/restore lifecycle for cancel + partial-accept paths.
  • rollback(acceptedPrefix:) reads slot 1 (recurrent state, 4D) — NOT slot 0 (conv state, 3D).
  • State kept in fp32 through the GDN recurrence, so the replay kernel folds entries through an fp32 reference — no precision loss across rollback boundaries.

Phase 2B — Native-C Metal kernels (4-repo plumbing)

  • gated_delta_step_record — forward GDN kernel variant that ALSO writes per-step delta_t to a delta-log output buffer.
  • state_replay — re-folds the accepted prefix of a delta log onto a pre-record state snapshot via the recurrence state = state * g + k * delta.
  • Both adopt upstream dflash-mlx correctness patterns from day 1: masked-timestep fix (3217e15) + branchless metal::select pattern (c9f992e). Function-constant variants for masked vs. non-masked; cells for fp16/bf16/fp32 × Qwen 3.5 GQA-asymmetric AND GQA-symmetric Hk=Hv shapes.
  • Full plumbing chain: mlx C++ Primitive classes → mlx-c C ABI → mlx-swift Swift wrappers → mlx-swift-lm dispatch via MLXFast.gatedDeltaStepRecord / MLXFast.stateReplay.

Phase 2C — GDN layer integration (Libraries/MLXLLM/Models/GatedDelta.swift, Qwen3Next.swift, Qwen35.swift)

  • gatedDeltaUpdateRecord(...) — record-aware wrapper around gatedDeltaUpdate. When cache.isRecording, dispatches the with-tape kernel; else delegates to the existing fast forward (zero overhead in non-speculative decoding).
  • Qwen3NextGatedDeltaNet.update(...) and Qwen35GatedDeltaNet.update(...) S>1 path route through the new wrapper. S==1 fused-decode (fusedGatedDeltaUpdate) is untouched — speculative verify is always S>1, the fused path never sees a recording session.
  • Perf — Option A batching: one recordStep per layer per round with T-axis tensors intact (~30× fewer Swift dispatches on a 30-GDN-layer model vs. per-step recording). Storage is references to the kernel's existing output buffers — no fresh allocation.

Phase 3 — Iterator wiring (Libraries/MLXLMCommon/NgramSpeculativeDecoding.swift, Evaluate.swift)

  • Three predicate flips: canTrimPromptCache → canRollbackPromptCache at the n-gram iterator init, the asymmetric SpeculativeTokenIterator init, and the auto-route gate in generate(...).
  • speculateRound body: beginCacheRecord(mainCache) before the verify forward; rollbackPromptCache(...) after accept-count computation handles both partial-accept (routes through rollback) and full-accept (routes through commitFull internally). Applied to both greedy + Leviathan paths.

Mamba opt-out (Libraries/MLXLLM/Models/NemotronH.swift, Jamba.swift)

  • Cache factories set cache.canStateReplay = false on .mamba cache slots. canRollbackPromptCache returns false for the stack; iterator declines and falls back to TokenIterator. Identical to pre-spec-020 behaviour — no crash, no surprise. Future-work kernel options are ranked in spec 020's §"Mamba / Mamba 2 follow-up (post-MVP)".

Off-by-one fix (worth calling out)

The verify forward records T = numDraft + 1 entries per round (y baseline + numDraft drafts). The iterator's acceptedPrefix counts only accepted draft tokens; the helper translates to rollback(acceptedPrefix + 1) so the y baseline is always kept. Without this fix, every partial-accept round drifted the SSM state by one position; zero-accept rounds discarded y entirely. Locked by two regression tests in RollbackPromptCacheTests + one end-to-end in SSMStateCacheStateReplayTests. Bench impact was significant (see bench-summary comment) — Qwen3.5-35B-A3B D=12 acceptance jumped from 34% to 92%.

Bench-harness debug surface (Tests/Benchmarks/InferenceBenchmark.swift, scripts/benchmark.sh --debug)

  • MLX_BENCH_DEBUG=1 installs a crash-stack capture handler that writes Thread.callStackSymbols to /tmp/mlx-bench-crash.log before fatalError. --debug flag wires the env var. Used during this PR to root-cause the SmallVector out of range crash that turned out to be the wrong cache slot.

Cross-repo PRs

The kernel ships as native-C plumbing — not JIT. The chain (in dependency order):

# Repo PR What
1 ekryski/mlx #26 GatedDeltaStepRecord + StateReplay C++ Primitive classes + Metal kernel + mlx::core::fast API
2 ekryski/mlx-c #14 C ABI bridges mlx_fast_gated_delta_step_record + mlx_fast_state_replay
3 ekryski/mlx-swift #25 MLXFast.gatedDeltaStepRecord / MLXFast.stateReplay Swift wrappers + .metal mirror + submodule pin bumps
4 ekryski/mlx-swift-lm this PR StateReplayCache protocol + SSMStateCache conformance + iterator wiring + tests

Package.swift uses a .package(path: "../mlx-swift") local dependency for cross-repo development; CI checks out the sibling. Will switch to url:, exact: "0.32.2-alpha" once mlx-swift PR #25 + the upstream chain merge and the tag is cut.

Verification

  • 27 state-replay tests all pass end-to-end through the native kernel path:
    • CanRollbackPromptCacheTests (6) — predicate logic on mixed stacks
    • RollbackPromptCacheTests (6) — dispatch + off-by-one regressions
    • CacheRecordHelpersTests (4) — beginRecord / commit / cancel helpers
    • SSMStateCacheStateReplayTests (9) — end-to-end with a real SSMStateCache + native kernels (commit, cancel, rollback at k=0/k=mid/k=full, per-step equivalence, free-helper dispatch with off-by-one regressions)
    • GDNRecordPathTests (2) — direct kernel-level exercise at Qwen 3.5 9B shapes
  • make clean-all && make build && make build-tests clean.
  • Bench validation on Qwen 3.5 9B, 35B-A3B, 3.6 27B (4bit, M1 Max 64GB, recipe-bulk 1000-token decode): correctness ✅ across all three; perf ranges from 0.94× (3.6-27B dense, poor spec-decode target) to 1.64× baseline (35B-A3B D=12 with 92% acceptance). Full numbers in the bench-summary comment.
  • Nemotron Cascade 2: cleanly opts out, identical to pre-spec-020 baseline.

Spec

specs/020-tape-replay-rollback-generalised.md — updated to reflect what shipped. Status / Risks / Files-touched sections audited; off-by-one is documented as Risk #7 with mitigation + regression coverage.

Out of scope (explicit)

  • Spec 017 phase 3 (SSMStateCache prefix snapshot via state replay) — picked up on spec 017's branch once this PR lands.
  • Spec 015 phase 4 (DFlash iterator using StateReplayCache protocol) — gated on DFlash phase 1 (PR feat(dflash): spec 015 phase 1 — DFlash speculative decoding scaffold #141) merging.
  • Nemotron-H / Jamba kernel variants — they use traditional Mamba / Mamba 2 (ssm_step, 3D selective state), not GDN. Different recurrence; separate kernels needed. Models opt out via canStateReplay = false until then; three implementation options ranked in spec 020's §"Mamba / Mamba 2 follow-up (post-MVP)".

ekryski added a commit that referenced this pull request Apr 30, 2026
Following the broad-sweep validation (1.31× speedup on the favourable
regime, ≤±2% deviation elsewhere), Leviathan accept/reject sampling
now engages by default at `temperature != 0`. Set
`MLX_NGRAM_LEVIATHAN=0` to disable.

**What changed:**

- `ngramLeviathanEnabled()` semantics: was "literal '1' enables"; now
  "anything except literal '0' enables" (matches the existing
  MLX_NGRAM_ADAPTIVE / MLX_NGRAM_STRICT_GREEDY / MLX_NGRAM_MULTI_CANDIDATE
  default-on convention).

- Doc-comment updated with the rationale: callers who opted into
  n-gram (Swift parameters or MLX_NGRAM_ENABLED=1) and use sampling
  now get Leviathan automatically. Same regression regimes inherit
  from greedy n-gram (paraphrastic content, small/fast models); the
  decision to engage spec-decode at all is the user's, made when they
  opted in.

- Route-decision tests rewritten for default-on semantics:
    - "Non-greedy temperature engages by default (Leviathan default-on)"
    - "MLX_NGRAM_LEVIATHAN=0 explicitly disables and declines temp != 0 route"
    - "MLX_NGRAM_LEVIATHAN=1 redundant but engages (explicit opt-in)"
    - "Greedy temperature engages regardless of MLX_NGRAM_LEVIATHAN"
    - `ngramLeviathanEnabled` reads-env-var test: unset → enabled,
      "0" → disabled, anything else → enabled.
    - "Env-var opt-in engages at temp != 0 (Leviathan default-on
      covers it)" + "Env-var opt-in declines at temp != 0 when
      MLX_NGRAM_LEVIATHAN=0".

  21 tests pass under `swift test -c release` after `make`.

**Spec 023 — phases 2 and 3 closed out without implementation:**

- **Phase 2 (unify with greedy path) deferred / not pursuing.** The
  "~50 LOC cleanup" framing underestimates the surface area:
    1. The greedy batch-sample-no-processor path is a real
       optimisation (one batched `sampler.sample(verifyLogits)` over
       `[numDraft+1, V]` in a single eval). Leviathan-style per-position
       sampling at temp=0 would lose that.
    2. The strict-greedy guard has no Leviathan analog (greedy
       compares argmax — argmax stability under numerical drift
       matters; Leviathan compares actual probabilities — tight
       margins naturally produce ~50% accept). Removing strict-greedy
       changes observable behaviour on real models.
    3. `softmax(logits / 0)` is undefined; needs a special case
       anyway, so unification isn't pure.

- **Phase 3 (self-disengage on chronically-low accept) subsumed by
  issue #153.** Same heuristic, same design tradeoffs (always-on vs
  opt-in vs doc-only); whatever form ships should apply to both
  greedy and Leviathan paths uniformly. Tracking in one place avoids
  divergence.

Spec 023 updated to mark phase 1 as shipped (with the batched
optimisation and default-on flip) and phases 2 / 3 with the rationale
above.

**User-facing doc article (`Documentation.docc/speculative-decoding.md`)
updated:**

- Opening paragraph distinguishes greedy (byte-identical) from
  Leviathan-sampling (distributionally equivalent) output guarantees.
- New "Models supported" section above the engage/fall-back table:
  per-model status (Gemma 4 26B A4B 4-bit ✅ engages; Gemma 4 E2B
  4-bit ⚠️ engages but slower; Qwen 3.5 / 3.6 + Nemotron-H + Jamba
  🔁 auto-fallback to TokenIterator) with a star-note explaining
  GDN / Mamba models await spec 020's tape-replay rollback (PR #143).
- "About the temperature condition" rewritten as "About the
  sampling-temperature path (Leviathan)" — describes greedy vs
  Leviathan paths, the default-on flip, the diagnostic A/B
  use case for `MLX_NGRAM_LEVIATHAN=0`, and notes that top-p / top-k /
  min-p samplers route through the same Leviathan path.
- Compatibility-conditions table reduced to one row (cache
  trimmability) — the old "temperature == 0" row is gone.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request Apr 30, 2026
Several follow-ups to spec 023 (Leviathan) bundled into PR #154's tail
since they share the "set up the rest of the speculative-decoding
roadmap" theme.

**Q2 — spec 013 close-out:**

- Implements phase 3.3 ("ngram-map-k4v" / "first 1-2 tokens"): adds
  `multiCandidateLookahead: Int = 1` parameter to
  `NGramLookup.proposeDraft` plus `MLX_NGRAM_MULTI_LOOKAHEAD=N` env
  var (default 1, preserves prior behaviour). Lookahead=2 disambiguates
  patterns where multiple prior occurrences share the same first
  continuation token but diverge on the second — group key changes
  from `Int` to `[Int]` for the multi-candidate grouping.
- 2 new unit tests cover lookahead=1 vs lookahead=2 disambiguation
  (the "[A,B] → [X,Y] count 2 vs [X,Z] count 1" canonical case).
  37/37 ngram tests pass.
- Updates `specs/013-ngram-speculative-decoding.md` with an
  implementation-status table at the bottom: phases 1.4 / 2.2 / 2.3 /
  3.1 / 3.2 / 3.3 shipped; 1.1 / 1.5 deferred (need real-model test
  harness); 1.2 mitigated; 2.1 partial (more model coverage as needed);
  3.4 superseded by spec 020 tape-replay.

**Q3 — eval harness:**

- `scripts/spec-decode-sweep.sh` — parameterised sweep runner. Takes
  `--model`, `--quant`, `--prompts` (file or directory), `--cells`
  (colon-separated `LABEL:NGRAM:TEMP:EXTRA_ENV` specs comma-joined),
  `--trials`, `--max-tokens`. Replaces the per-PR ad-hoc shell loops
  in /tmp/ that we've been writing fresh each time.
- `scripts/spec-decode-compare.py` — A vs B compare on two sweep
  logs. Computes per-cell medians + speedup-ratios with directional
  emoji (✅ / ⚠️ / ≈). Tolerates both the new `extra=...` cell-line
  format and the older `leviathan=...` format from /tmp/ legacy runs.
- `Tests/Benchmarks/Resources/ngram-sweep-prompts/README.md` —
  regime-classified workload guide. Three regimes (regurgitative /
  structured / paraphrastic) with expected speedup bands per regime,
  per-directory prompt counts, and the canonical 6-cell × 5-trial
  cell-set used in the Leviathan analysis. Reference for any future
  spec-decode PR's eval section.
- 8 draft spec PRs (#141 / #142 / #143 / #144 / #145 / #146 / #147 /
  #148) updated with per-spec "Evaluation (when phase 2+ lands)"
  sections that include the canonical sweep+compare commands +
  per-spec pass criteria.

**Q4 — IMPLEMENTATION-PLAN.md reorder:**

Tier 1 ↔ Tier 3 swap. Tape-replay (#20) + prefix cache (#17) are
now Tier 1 (deterministic infrastructure wins, scaffolds landed,
unblocks 5+ models / universal multi-turn TTFT win). DFlash (#15) +
Mirror SD (#21) are now Tier 3 (more experimental — DFlash needs
draft model availability, Mirror SD needs CoreML-LLM Swift Package
dep + ANE measurement infra).

Rationale: lower experimental risk to land deterministic wins first.
By the time DFlash + Mirror SD are unblocked (external model release,
ANE infra), tape-replay will be in place to support DFlash phase 3.

Status snapshot updated: Tier 0 (013 + 018 + 023 + eval harness)
shipped; Tier 1 in flight (phase-1 scaffolds at #143, #144); Tier 2
phase-1 scaffolds also landed (#145, #146, #147, #148).

Closing notes in the plan also reflect spec 023's phase-2 / phase-3
deferral (subsumed by issue #153) so they're not re-attempted.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request Apr 30, 2026
Following the broad-sweep validation (1.31× speedup on the favourable
regime, ≤±2% deviation elsewhere), Leviathan accept/reject sampling
now engages by default at `temperature != 0`. Set
`MLX_NGRAM_LEVIATHAN=0` to disable.

**What changed:**

- `ngramLeviathanEnabled()` semantics: was "literal '1' enables"; now
  "anything except literal '0' enables" (matches the existing
  MLX_NGRAM_ADAPTIVE / MLX_NGRAM_STRICT_GREEDY / MLX_NGRAM_MULTI_CANDIDATE
  default-on convention).

- Doc-comment updated with the rationale: callers who opted into
  n-gram (Swift parameters or MLX_NGRAM_ENABLED=1) and use sampling
  now get Leviathan automatically. Same regression regimes inherit
  from greedy n-gram (paraphrastic content, small/fast models); the
  decision to engage spec-decode at all is the user's, made when they
  opted in.

- Route-decision tests rewritten for default-on semantics:
    - "Non-greedy temperature engages by default (Leviathan default-on)"
    - "MLX_NGRAM_LEVIATHAN=0 explicitly disables and declines temp != 0 route"
    - "MLX_NGRAM_LEVIATHAN=1 redundant but engages (explicit opt-in)"
    - "Greedy temperature engages regardless of MLX_NGRAM_LEVIATHAN"
    - `ngramLeviathanEnabled` reads-env-var test: unset → enabled,
      "0" → disabled, anything else → enabled.
    - "Env-var opt-in engages at temp != 0 (Leviathan default-on
      covers it)" + "Env-var opt-in declines at temp != 0 when
      MLX_NGRAM_LEVIATHAN=0".

  21 tests pass under `swift test -c release` after `make`.

**Spec 023 — phases 2 and 3 closed out without implementation:**

- **Phase 2 (unify with greedy path) deferred / not pursuing.** The
  "~50 LOC cleanup" framing underestimates the surface area:
    1. The greedy batch-sample-no-processor path is a real
       optimisation (one batched `sampler.sample(verifyLogits)` over
       `[numDraft+1, V]` in a single eval). Leviathan-style per-position
       sampling at temp=0 would lose that.
    2. The strict-greedy guard has no Leviathan analog (greedy
       compares argmax — argmax stability under numerical drift
       matters; Leviathan compares actual probabilities — tight
       margins naturally produce ~50% accept). Removing strict-greedy
       changes observable behaviour on real models.
    3. `softmax(logits / 0)` is undefined; needs a special case
       anyway, so unification isn't pure.

- **Phase 3 (self-disengage on chronically-low accept) subsumed by
  issue #153.** Same heuristic, same design tradeoffs (always-on vs
  opt-in vs doc-only); whatever form ships should apply to both
  greedy and Leviathan paths uniformly. Tracking in one place avoids
  divergence.

Spec 023 updated to mark phase 1 as shipped (with the batched
optimisation and default-on flip) and phases 2 / 3 with the rationale
above.

**User-facing doc article (`Documentation.docc/speculative-decoding.md`)
updated:**

- Opening paragraph distinguishes greedy (byte-identical) from
  Leviathan-sampling (distributionally equivalent) output guarantees.
- New "Models supported" section above the engage/fall-back table:
  per-model status (Gemma 4 26B A4B 4-bit ✅ engages; Gemma 4 E2B
  4-bit ⚠️ engages but slower; Qwen 3.5 / 3.6 + Nemotron-H + Jamba
  🔁 auto-fallback to TokenIterator) with a star-note explaining
  GDN / Mamba models await spec 020's tape-replay rollback (PR #143).
- "About the temperature condition" rewritten as "About the
  sampling-temperature path (Leviathan)" — describes greedy vs
  Leviathan paths, the default-on flip, the diagnostic A/B
  use case for `MLX_NGRAM_LEVIATHAN=0`, and notes that top-p / top-k /
  min-p samplers route through the same Leviathan path.
- Compatibility-conditions table reduced to one row (cache
  trimmability) — the old "temperature == 0" row is gone.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request Apr 30, 2026
Several follow-ups to spec 023 (Leviathan) bundled into PR #154's tail
since they share the "set up the rest of the speculative-decoding
roadmap" theme.

**Q2 — spec 013 close-out:**

- Implements phase 3.3 ("ngram-map-k4v" / "first 1-2 tokens"): adds
  `multiCandidateLookahead: Int = 1` parameter to
  `NGramLookup.proposeDraft` plus `MLX_NGRAM_MULTI_LOOKAHEAD=N` env
  var (default 1, preserves prior behaviour). Lookahead=2 disambiguates
  patterns where multiple prior occurrences share the same first
  continuation token but diverge on the second — group key changes
  from `Int` to `[Int]` for the multi-candidate grouping.
- 2 new unit tests cover lookahead=1 vs lookahead=2 disambiguation
  (the "[A,B] → [X,Y] count 2 vs [X,Z] count 1" canonical case).
  37/37 ngram tests pass.
- Updates `specs/013-ngram-speculative-decoding.md` with an
  implementation-status table at the bottom: phases 1.4 / 2.2 / 2.3 /
  3.1 / 3.2 / 3.3 shipped; 1.1 / 1.5 deferred (need real-model test
  harness); 1.2 mitigated; 2.1 partial (more model coverage as needed);
  3.4 superseded by spec 020 tape-replay.

**Q3 — eval harness:**

- `scripts/spec-decode-sweep.sh` — parameterised sweep runner. Takes
  `--model`, `--quant`, `--prompts` (file or directory), `--cells`
  (colon-separated `LABEL:NGRAM:TEMP:EXTRA_ENV` specs comma-joined),
  `--trials`, `--max-tokens`. Replaces the per-PR ad-hoc shell loops
  in /tmp/ that we've been writing fresh each time.
- `scripts/spec-decode-compare.py` — A vs B compare on two sweep
  logs. Computes per-cell medians + speedup-ratios with directional
  emoji (✅ / ⚠️ / ≈). Tolerates both the new `extra=...` cell-line
  format and the older `leviathan=...` format from /tmp/ legacy runs.
- `Tests/Benchmarks/Resources/ngram-sweep-prompts/README.md` —
  regime-classified workload guide. Three regimes (regurgitative /
  structured / paraphrastic) with expected speedup bands per regime,
  per-directory prompt counts, and the canonical 6-cell × 5-trial
  cell-set used in the Leviathan analysis. Reference for any future
  spec-decode PR's eval section.
- 8 draft spec PRs (#141 / #142 / #143 / #144 / #145 / #146 / #147 /
  #148) updated with per-spec "Evaluation (when phase 2+ lands)"
  sections that include the canonical sweep+compare commands +
  per-spec pass criteria.

**Q4 — IMPLEMENTATION-PLAN.md reorder:**

Tier 1 ↔ Tier 3 swap. Tape-replay (#20) + prefix cache (#17) are
now Tier 1 (deterministic infrastructure wins, scaffolds landed,
unblocks 5+ models / universal multi-turn TTFT win). DFlash (#15) +
Mirror SD (#21) are now Tier 3 (more experimental — DFlash needs
draft model availability, Mirror SD needs CoreML-LLM Swift Package
dep + ANE measurement infra).

Rationale: lower experimental risk to land deterministic wins first.
By the time DFlash + Mirror SD are unblocked (external model release,
ANE infra), tape-replay will be in place to support DFlash phase 3.

Status snapshot updated: Tier 0 (013 + 018 + 023 + eval harness)
shipped; Tier 1 in flight (phase-1 scaffolds at #143, #144); Tier 2
phase-1 scaffolds also landed (#145, #146, #147, #148).

Closing notes in the plan also reflect spec 023's phase-2 / phase-3
deferral (subsumed by issue #153) so they're not re-attempted.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski force-pushed the ek/021-mirror-sd-phase1a branch from 8b02077 to a965885 Compare April 30, 2026 06:24
@ekryski
ekryski force-pushed the ek/020-tape-replay-phase1 branch from 0a84aec to 7d61c7b Compare April 30, 2026 06:24
@ekryski ekryski added the feature New feature (auto-applied from feat: prefix) label May 8, 2026
@ekryski
ekryski force-pushed the ek/020-tape-replay-phase1 branch from 7d61c7b to 56a03f7 Compare May 8, 2026 05:04
@ekryski
ekryski changed the base branch from ek/021-mirror-sd-phase1a to alpha May 8, 2026 05:04
@ekryski
ekryski force-pushed the ek/020-tape-replay-phase1 branch from 56a03f7 to e768660 Compare May 8, 2026 05:05
@ekryski
ekryski marked this pull request as ready for review May 8, 2026 05:11
@ekryski
ekryski force-pushed the ek/020-tape-replay-phase1 branch from e768660 to cbe0357 Compare May 8, 2026 06:02
ekryski added a commit that referenced this pull request May 11, 2026
Upstream `bstnxbt/dflash-mlx@main` advanced three commits past our
drafted-against reference (`8d8545d`). Captures the design-surface
implications in both specs without changing the implementation plan.

**Spec 017 (prefix KV cache) — three deltas:**
- 463d722 — format_version bumped 1→2 (back-incompatible); new snapshot
  invariants (FA offset == prefix length; hidden chunks truncated);
  L1.lookup gets `record:` param; L2.lookup gets `min_token_len:` param;
  combined L1+L2 prefers longer-prefix matches across tiers; L2 insert
  deduplicates by key.
- 8c29e3e — survival-gate test methodology: five behavioural contracts
  (budget fit / cold→warm prefix preservation / ≥80% reuse floor /
  staleness guard / non-speculative-fallback gate). Phase 2 ships these.
- 4bc72c8 — fail-fast contract philosophy for cache lifecycle. Adopt as
  `PrefixKVCacheError` (closed / missingLogits / formatVersionMismatch /
  wrappedWindowedCache / snapshotInvariantViolation). Every serialise /
  hydrate is throws — no silent fallbacks across the cache boundary.

**Spec 020 (tape-replay rollback) — light-touch:**
- Kernel surface unchanged since 8d8545d; existing 3217e15 + c9f992e
  notes remain authoritative.
- 4bc72c8 — adopt fail-fast for tape lifecycle: `TapeReplayCacheError`
  with cases (.alreadyRecording / .notRecording / .arityMismatch /
  .outOfRange). Iterator must `try` every terminator.
- 05cc456 / 2274b67 — Gemma4 DFlash backend now supported upstream;
  phase 3 smoke must verify tape-replay path is no-op for pure-attention
  Gemma4 (every layer trimmable) and composes with TurboQuant trim on
  full-accept rounds.
- 8c29e3e survival methodology applied to spec 020 as round-trip
  equivalence: fresh-prefill KV state after N tokens vs. tape-replay
  rollback from N-M checkpoint must match within bf16 stability bounds.

No source changes — pure spec updates so PRs #143 (spec 020 phase 1) and
#144 (spec 017 phase 1) rebase cleanly with the latest design intent
captured.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski and others added 2 commits May 11, 2026 15:47
…elpers

Tape-replay rollback is the high-leverage technical change that unblocks
PLD and DFlash on the entire hybrid-architecture model family (Qwen 3.5/
3.6, Nemotron-H, Jamba, etc.). Phase 1 lands the protocol + the
free-function rollback dispatch helpers so call sites can adopt the new
predicate without committing to a Mamba kernel yet. Phase 2 adds the
`MambaCache` conformance + Metal kernel; phase 3 wires the n-gram +
DFlash iterators to the new gate.

Why ship phase 1 standalone: the predicate change is a pure widening —
existing trimmable caches keep working through the trim fallback path;
new tape-replay caches plug in via the protocol. The iterators don't
have to flip yet; this lets the next PR be focused (just the kernel).

New files:
- `Libraries/MLXLMCommon/TapeReplayCache.swift` — `TapeReplayCache`
  protocol with `beginRecord` / `appendInnovation` / `commitFull` /
  `rollback(acceptedPrefix:)` / `cancel`, plus a `canTapeReplay` flag
  and a `replayCost` cost class (`o1`, `ok`, `reforward`). Free
  helpers: `canRollbackPromptCache`, `beginCacheRecord`,
  `commitCacheRecord`, `cancelCacheRecord`, `rollbackPromptCache`.
  `rollbackPromptCache` automatically dispatches per-layer: tape-replay
  layers get full/partial/cancel calls based on accepted-prefix; trim
  layers fall back to `trim(rejected)`. Mixed stacks supported.
- `Tests/MLXLMTests/TapeReplayCacheTests.swift` — 16 tests across
  three suites:
  - `CanRollbackPromptCacheTests` (6): empty / all-trimmable /
    all-tape / mixed / opaque-cache rejection / disabled-tape rejection.
  - `RollbackPromptCacheTests` (6): full-accept routes commitFull,
    zero-accept routes cancel + trim-by-all, partial-accept routes
    rollback(k) + trim-by-rejected, mixed-stack visits each layer
    once, disabled-tape is skipped.
  - `CacheRecordHelpersTests` (4): begin/commit/cancel only route
    to tape layers; disabled-tape is skipped.

The fakes in the test file (`FakeTrimmableCache`, `FakeOpaqueCache`,
`FakeTapeReplayCache`) record events without standing up real KV
shapes — phase 1 dispatch logic has no tensor-shape dependency, so
the tests run pure-CPU and zero-GPU.

Pure-Swift, no MLX evaluation. All 16 tests pass under `swift test`
without metallib.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…replay)

Adds the concrete `TapeReplayCache` conformance to `SSMStateCache` so
n-gram + speculative iterators can run on hybrid GDN+Attention models
(Qwen 3.5 / 3.6 / Qwen 3 Next / Nemotron-H / Jamba). The protocol
contract is met by an ops-based GDN recurrence that mirrors the
`gated_delta_step` Metal kernel body — this is the correctness baseline.
A separate Metal kernel (`gated_delta_replay.metal`) in the `mlx-swift`
sibling repo is the speed path with the same numerical contract,
landing in phase 2B.

Protocol generalisation
- `TapeReplayCache.appendInnovation(_ delta: MLXArray)` →
  `appendInnovation(_ innovations: [MLXArray])` per spec 020 §"Open
  work for phase 2". Upstream `tape_replay_kernel` takes a per-step
  triple `(delta, k, g)` rather than a single delta; the wider signature
  lets the protocol round-trip the kernel surface without re-shaping.
  Trim-only no-op default conformers ignore the array contents (they
  trim positionally on rollback regardless).
- `FakeTapeReplayCache` test fake updated to the new signature; the
  16 phase-1 dispatch tests continue to pass unchanged.

`SSMStateCache: TapeReplayCache` extension
- `canTapeReplay = true`, `replayCost = .ok` (linear in accepted prefix
  length, single elementwise op per step). `isTrimmable` stays false
  on the parent `ArraysCache` — rollback flows through tape replay
  rather than positional trim.
- Lifecycle: `beginRecord()` calls the existing `snapshot()` (re-using
  the pre-tape DFlash-era state machinery) and arms an empty tape;
  `appendInnovation([delta, k, g])` accumulates per-step tuples;
  `commitFull()` clears the tape (the verify forward already advanced
  state through `update(...)`); `cancel()` restores via the existing
  `restore()` and discards the tape; `rollback(acceptedPrefix: k)`
  restores the snapshot, re-folds the first k tape entries through
  the GDN recurrence, and clears the tape.
- `gatedDeltaReplayStep(state:delta:k:g:)` — the per-step ops-based
  recurrence reference. Mirrors the body of `gated_delta_step` in
  `mlx-swift/Source/Cmlx/mlx-generated/metal/gated_delta.metal`:
  `state ← state * g; state ← state + k * delta`. The Metal kernel
  in phase 2B does the same math in a fused dispatch.

Tests (`TapeReplayCacheTests.swift`, +8 cases / 1 suite)
- `canTapeReplay is true; replayCost is .ok; isTrimmable stays false` —
  basic property invariants.
- `commitFull clears tape and leaves state advanced` — verify forward
  semantics preserved.
- `cancel restores pre-record snapshot and discards tape`.
- `rollback(acceptedPrefix: 0) is equivalent to cancel` — boundary case.
- `rollback(acceptedPrefix: k) re-folds first k tape entries via the
  GDN recurrence` — partial-accept correctness, asserts cache state
  matches an explicit reference computed from the snapshot + first k
  innovations.
- `rollback(acceptedPrefix: numDraft) matches a full-accept replay` —
  full-prefix rollback.
- `Per-step equivalence: rolling 1+1 == rolling 0+2 within a round` —
  associativity check; two recording sessions of one entry each must
  produce the same final state as one session of two entries.
- `Free-helper dispatch: rollbackPromptCache routes through the cache's
  tape path` — end-to-end through the public dispatch helpers
  (`canRollbackPromptCache`, `beginCacheRecord`, `rollbackPromptCache`).

Verification
- `swift build -c release` clean.
- `swift test -c release --filter TapeReplay` — 24/24 pass (16 phase-1
  dispatch tests + 8 new phase-2 conformance tests).

Open in phase 2B (next commits)
- `mlx-swift/Source/Cmlx/mlx-generated/metal/gated_delta_replay.metal` —
  fused Metal kernel for `gated_delta_with_tape` + `tape_replay`. Ports
  bstnxbt/dflash-mlx@main with the masked-timestep correctness fix
  (`3217e15`) and branchless pattern (`c9f992e`).
- `Libraries/MLXLMCommon/TapeReplayKernels.swift` — Swift wrappers
  around the precompiled metallib symbols.
- GDN layer integration — `Qwen3NextGatedDeltaNet.update(...)` checks
  `cache.tapeIsRecording` and either uses the fused forward kernel
  (no recording) or the with-tape variant (recording).
- Iterator wiring — flip `canTrimPromptCache` → `canRollbackPromptCache`
  in `NgramSpeculativeDecoding.swift` + `Evaluate.swift`; wrap
  `speculateRound` with `beginCacheRecord` / `commitCacheRecord` /
  `rollbackPromptCache`.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski force-pushed the ek/020-tape-replay-phase1 branch from cbe0357 to d9d1b61 Compare May 11, 2026 21:47
ekryski and others added 2 commits May 11, 2026 16:28
Implements innovation-tape rollback end-to-end for hybrid GDN+Attention
models. Speculative decoders (n-gram, future DFlash) can now run on
Qwen 3.5 / 3.6 / Nemotron-H / Jamba without falling back to vanilla AR.

Cache API surface (TapeReplayCache.swift, KVCache.swift):
- Rename `appendInnovation(_:)` → `recordStep(_:)` — Kalman-filter
  "innovation" terminology was opaque. The method appends per-step
  recurrence tensors (`[delta_t, k_t, g_t]` for SSMStateCache).
- Promote `SSMStateCache.isRecording` from fileprivate to public so
  GDN layers can gate the kernel-routing branch.
- Add `TapeReplayCacheError` enum (`alreadyRecording`, `notRecording`,
  `arityMismatch(expected:got:)`, `outOfRange(k:tapeLength:)`) per
  dflash-mlx upstream commit `4bc72c8` hardening philosophy.

Two new JIT Metal kernels (SSMTapeKernels.swift, MLXLMCommon):
- `gated_delta_step_with_tape` — forward GDN kernel that also writes
  per-step `delta_t` to a tape output buffer. Variant of the existing
  `gated_delta_step` (in MLXLLM/Models/GatedDelta.swift) with masked +
  non-masked variants via function-constant-style hasMask flag.
- `tape_replay` — re-folds the accepted prefix of an innovation tape
  from a pre-record snapshot. Adopts upstream dflash-mlx correctness
  patterns from day 1: masked-timestep fix (`3217e15`, save old_state
  + restore via metal::select), branchless pattern (`c9f992e`,
  metal::select(old, new, do_step) instead of if(do_step) guards).
- Both compiled via `MLXFast.metalKernel(source:)` JIT, following the
  established pattern of the existing forward kernel. No mlx C++
  primitive / mlx-c C ABI / MLXFast.metalKernel custom-wrapper needed.

SSMStateCache.rollback swap (KVCache.swift):
- Phase 2A's ops-based per-step replay loop is replaced by a single
  call to `gatedDeltaReplayUpdate(state:tape:acceptedPrefix:)` which
  dispatches the `tape_replay` Metal kernel in one shot.
- The static `gatedDeltaReplayStep` ops reference helper is removed —
  the kernel is now the production correctness contract.

GDN layer integration (Qwen3Next.swift:342, Qwen35.swift:317):
- Replace `gatedDeltaUpdate(...)` with `gatedDeltaUpdateWithTape(...)`
  in the S>1 prefill/verify path. The dispatcher routes to the
  forward-with-tape kernel only when `cache.isRecording` is true;
  otherwise delegates to the existing fast forward kernel (zero
  overhead in non-speculative decoding).
- Qwen35 S==1 fused decode path (`fusedGatedDeltaUpdate`) unchanged —
  speculative verify is always S>1, the S==1 path never sees a
  recording session.

Iterator wiring (NgramSpeculativeDecoding.swift, Evaluate.swift):
- Three predicate flips: `canTrimPromptCache` → `canRollbackPromptCache`
  at three call sites (NgramSpec init, Evaluate ngram auto-route,
  Evaluate SpeculativeTokenIterator init). The last is asymmetric:
  main cache uses rollback (hybrid OK), draft cache stays on
  positional trim (drafts are pure-attention).
- `speculateRound` body: `beginCacheRecord(mainCache)` before the
  verify forward; terminator dispatch after accept-count computation —
  `commitCacheRecord` on full accept (fast — pure-attention stacks
  skip the loop body entirely), else `rollbackPromptCache(...,
  acceptedPrefix:, numDraft:)` which routes trim on trimmable layers
  and tape rollback on tape-replay layers transparently.
- Applied to both greedy path (line 1155) and Leviathan path (line
  999) trim sites.

Tests (TapeReplayCacheTests.swift):
- All 22 tape-replay tests pass with the new kernel path (rename +
  shape bump to Dk=64, Dv=32 so n_per_t = Dk/32 >= 1 — the kernel
  uses fixed-size arrays sized by Dk/32 and Metal C++ forbids
  zero-length arrays).
- Phase 2A's per-step / partial-accept / cancel / round-trip /
  free-helper dispatch tests all green end-to-end via the kernel.

Spec doc updated in specs/020-tape-replay-rollback-generalised.md to
match the new method name.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Replaces the JIT-compiled tape kernels in SSMTapeKernels.swift with the
new native primitives `MLXFast.gatedDeltaStepWithTape` and
`MLXFast.tapeReplay`. These call through the full multi-repo plumbing
chain (mlx C++ Primitive + Metal kernel → mlx-c C ABI → mlx-swift Swift
wrapper) — same pattern as the existing `MLXFast.gatedDeltaStep` and
`MLXFast.gatedDeltaStepFused` already used by the GDN forward path.

Why native > JIT: precompiled metallib symbols avoid the per-startup
shader compile cost (JIT compiles each (Dk, Dv, Hk, Hv) cell on first
use); the dispatched kernel binary is identical body-for-body to the
JIT version. Same correctness contract (masked-timestep fix `3217e15`
+ branchless `metal::select` pattern `c9f992e` adopted from day 1).

Switches `Package.swift` to a local-path dependency on `../mlx-swift`
during the dev iteration cycle. Will flip back to `url:, exact:` once
the tape-replay primitives are tagged as `v0.32.2-alpha` on mlx-swift.

All 22 existing tape-replay tests pass end-to-end through the native
kernel path. 228 of 229 tests pass overall — the only "failure" is the
pre-existing benchmark-harness gate that requires MLX_BENCH_MODEL env
var (not a real test).

Cross-repo commits required for this PR:
- ekryski/mlx@4a0efbd2 — GatedDeltaStepWithTape + TapeReplay primitives
- ekryski/mlx-c@dcc0a66 — C ABI bridges
- ekryski/mlx-swift@<HEAD ek/gdn-tape-native> — Swift wrappers + .metal
  mirror + submodule pin bumps

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…"delta log"

Internal-only naming refresh — no semantic changes. The original Kalman-
filter terminology ("innovation tape", "tape replay") was opaque; the
new vocabulary describes what the code actually does:
- "state replay" — replaying recorded state-update deltas on rollback
- "delta log" — the captured sequence of per-step state changes

Mapping (alphabetical):
- TapeReplayCache         → StateReplayCache
- TapeReplayCacheError    → StateReplayCacheError
- TapeReplayCost          → StateReplayCost
- canTapeReplay           → canStateReplay
- gatedDeltaStepWithTape  → gatedDeltaStepRecord (Swift + C ABI + kernel)
- gatedDeltaUpdateWithTape → gatedDeltaUpdateRecord
- gatedDeltaKernelWithTape → gatedDeltaKernelRecord
- gatedDeltaReplayUpdate  → stateReplayUpdate
- tape_replay             → state_replay (kernel + C ABI + Swift)
- TapeReplay              → StateReplay (C++ Primitive class)
- mlx_fast_tape_replay    → mlx_fast_state_replay
- mlx_fast_gated_delta_step_with_tape → mlx_fast_gated_delta_step_record
- MLXFast.tapeReplay      → MLXFast.stateReplay
- MLXFast.gatedDeltaStepWithTape → MLXFast.gatedDeltaStepRecord
- internal `tape` storage  → `deltaLog`
- recordedTape (local var) → recordedLog
- delta_tape / k_tape / g_tape (kernel buffers) → delta_log / k_log / g_log
- tape_delta (kernel output) → delta_log
- T_tape (kernel constant) → T_log
- File renames:
    Libraries/MLXLMCommon/TapeReplayCache.swift  → StateReplayCache.swift
    Libraries/MLXLMCommon/SSMTapeKernels.swift   → StateReplayKernels.swift
    Tests/MLXLMTests/TapeReplayCacheTests.swift  → StateReplayCacheTests.swift
    mlx/.../kernels/gated_delta_tape.metal       → gated_delta_replay.metal
    mlx/.../metal/gated_delta_tape.cpp           → gated_delta_replay.cpp
    mlx-swift/.../mlx-generated/.../gated_delta_tape.metal → gated_delta_replay.metal

Lifecycle method names unchanged (already intuitive): beginRecord,
recordStep, commitFull, rollback(acceptedPrefix:), cancel.

Mental model: the cache records per-step state deltas into a log during
the verify forward; on partial accept, we replay the accepted prefix of
that log onto the snapshot to recover the post-accept state.

Spec 020 + IMPLEMENTATION-PLAN.md + spec 017 prose updated to use the
new vocabulary. The spec 020 file kept its filename
(`020-tape-replay-rollback-generalised.md`) for stable URL/PR references;
a naming note at the top documents the rename.

Cross-repo commits required for this rename:
- ekryski/mlx@<HEAD ek/gdn-tape-primitives>     — Primitive classes
                                                    + Metal kernel + .metal
                                                    canonical source
- ekryski/mlx-c@<HEAD ek/gdn-tape-primitives>   — C ABI bridges
- ekryski/mlx-swift@<HEAD ek/gdn-tape-native>   — vendored headers +
                                                    Swift wrappers + .metal
                                                    mirror + submodule bumps

All 22 SSMStateCache state-replay tests pass end-to-end through the
renamed native kernel chain.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski ekryski changed the title feat(cache): spec 020 phase 1 — TapeReplayCache protocol + dispatch helpers feat(cache): spec 020 — StateReplayCache protocol + native GDN state-replay kernels + iterator wiring May 11, 2026
`SSMStateCache.rollback(acceptedPrefix:)` was reading and writing
`state[0]`, but the production GDN layer (Qwen35GatedDeltaNet /
Qwen3NextGatedDeltaNet) puts the recurrent SSM state at **slot 1**:

  - state[0] = conv state (3D, [B, kernel-1, conv_dim])
  - state[1] = recurrent state (4D, [B, Hv, Dv, Dk])

Calling stateReplayUpdate with state[0] passed a 3D conv tensor to the
replay kernel, which then crashed in mlx_array_dim with "SmallVector out
of range" when it tried `state.dim(3)`. Manifested as a hard crash
during ngram-spot's pass-2 verify forward on Qwen 3.5 9B / 35B-A3B.

Fix: read self.state[1] and write back to newState[1] in rollback.

Also fixes the corresponding StateReplayCacheTests fixtures, which had
inherited the same slot mistake and were happily testing the wrong slot
against the wrong-slot rollback (so they passed despite the bug).

Adds `MLX_BENCH_DEBUG=1` env-gated crash-stack capture in the bench
harness (BenchEnv.debugCrashCapture + installCrashStackCapture()) +
`--debug` flag in scripts/benchmark.sh. On MLX C++ errors, writes the
Swift backtrace to /tmp/mlx-bench-crash.log before fatalError aborts
the process — Swift Testing captures stdout/stderr but loses both on
process abort, so a file write is the only way to see what crashed.
Off by default, no runtime overhead when unset.

Adds GDNRecordPathTests: exercises gatedDeltaUpdateRecord directly with
realistic Qwen 3.5 9B shapes (Dk=128, Dv=128, Hk=16, Hv=32). Proves the
layer-side record path is correct in isolation — used during diagnosis
to bisect the bug to the cache rollback rather than the kernel itself.

Verified end-to-end via ngram-spot (4 cells, 200 tokens each):
- Qwen3.5-0.8B-4bit:  5/58 accepted (8.6%)
- Qwen3.5-9B-4bit:    8/72 accepted (11.1%)
- Qwen3.5-35B-A3B-4bit: 6/72 accepted (8.3%)

All produce coherent output.

Cross-repo: depends on ekryski/mlx@6a93a40 + ekryski/mlx-swift@e02344b
which add the Hk=Hv replay-kernel instantiations needed when Hv differs
from the layer's original Hk (the cache stores GQA-expanded k_log).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski force-pushed the ek/020-tape-replay-phase1 branch from 70cb3db to cd63ac0 Compare May 12, 2026 01:06
ekryski and others added 6 commits May 11, 2026 19:17
Spec 020 phase 2 currently implements state-replay rollback for the
GatedDeltaNet recurrence only. Mamba / Mamba 2 (Nemotron Cascade 2,
Jamba, …) share the `SSMStateCache` storage class but use a different
recurrence, and their production S>1 forward uses a chunked parallel
scan that doesn't expose per-step deltas — implementing Mamba state
replay needs its own native kernel pair (see spec 020 §"Mamba / Mamba 2
follow-up").

Until that ships, this commit:

- Promotes `SSMStateCache.canStateReplay` from a constant `true` in
  the StateReplayCache extension to a stored property on the class
  itself, default `true`. Model factories that emit SSM caches for
  Mamba layers set it to `false` per-cache.
- Wires the opt-out in NemotronH.newCache (mamba blocks) and
  Jamba.newCache (non-attention layers).
- When any layer reports `canStateReplay == false`,
  `canRollbackPromptCache` returns `false` for the stack, and
  `MLXLMCommon.generate(...)` auto-routing gracefully declines the
  n-gram speculative path → falls back to vanilla `TokenIterator`. No
  crash; behaviour is identical to pre-spec-020 baseline on these
  models.

Spec 020 §"Mamba / Mamba 2 follow-up" lays out the three concrete
options for implementing Mamba state replay properly, with option 1
(native ssm_step_record + ssm_replay kernel pair) recommended.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
`gatedDeltaUpdateRecord` previously called `cache.recordStep(...)` once
per verify step, creating 3 lazy slices (`tapeDelta[:, t]`, `kExpanded[:, t]`,
`g[:, t]`) per call. For a 1000-token generation at D=4 on 30 GDN layers,
that's:

  200 rounds × 4 steps × 30 layers = 24 000 record calls + 72 000 slice ops

Option A batches recording: each layer calls `recordStep` **once per
round** with the whole verify forward's tensors (T-axis intact). The
slicing happens once at rollback time, on partial-accept rounds only
(~25% of rounds at typical acceptance rates).

Change surface:

- `gatedDeltaUpdateRecord` (Libraries/MLXLLM/Models/GatedDelta.swift):
  replaces the `for t in 0..<T { cache.recordStep([.. slice ..]) }` loop
  with a single `cache.recordStep([tapeDelta, kExpanded, g])` call
  carrying [B, T, Hv, *] tensors.

- `SSMStateCache.recordStep` (Libraries/MLXLMCommon/KVCache.swift):
  docstring updated to describe both formats (per-round T-axis preferred;
  per-step legacy supported for unit tests). The `tensors.count == 3`
  precondition is unchanged.

- `SSMStateCache.rollback`: moves the `k <= recordedLog.count` bound
  check into `stateReplayUpdate` where `T_log` is resolved per-format.

- `stateReplayUpdate` (Libraries/MLXLMCommon/StateReplayKernels.swift):
  detects entry format via `deltaLog[0][0].ndim`. ndim==4 → per-round
  fast path (no stacking, dispatch directly). ndim==3 → legacy per-step
  path (existing stack+transpose logic). Multi-batched case
  (improbable but handled) concatenates along T-axis.

Both unit tests and the bench harness validate end-to-end:

  Qwen 3.5 9B-4bit / ngram-spot recipe-bulk (1000 tokens):
    baseline   53.1 tok/s
    D=2        53.5 tok/s   (was 52.6 — D=2 flips to net-positive)
    D=4        52.0 tok/s   (was 51.6)
    D=8        49.7 tok/s   (was 48.8)

  Qwen 3.5 35B-A3B-4bit / ngram-spot recipe-bulk (1000 tokens):
    baseline   66.5 tok/s
    D=2        60.4 tok/s   (was 59.2)
    D=4        74.5 tok/s   (was 73.0) — 1.12× baseline at the sweet spot
    D=8        71.1 tok/s   (was 70.3)

22 state-replay unit tests pass — the dispatcher's format auto-detection
lets the legacy per-step tests continue working unchanged while the
production path uses the batched layout.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The verify forward processes T = numDraft + 1 tokens per round: a
y-baseline (the bonus token from the prior round, always kept) followed
by numDraft drafts. Each tape entry records ONE token's recurrence, so
the recorded log has numDraft + 1 entries — but the iterator-side
`acceptedPrefix` counts only accepted draft tokens (0..numDraft).

The trim path got this right by accident — `trim(numDraft - accepted)`
leaves `accepted + 1` tokens in the cache past the snapshot (y + accepted
drafts), which is what the next round expects.

The state-replay path was passing `acceptedPrefix` directly to
`cache.rollback(acceptedPrefix:)`, folding only `accepted` entries —
ONE fewer than the trim path. On every partial-accept round, the SSM
state drifted by one position. Worse: the zero-draft-accept case routed
through `cancel()` which restored the pre-record snapshot entirely,
discarding y. So the very common "iterator emits correction token at
position 0" path was producing wrong state every time.

Fix: helper `rollbackPromptCache(_:acceptedPrefix:numDraft:)` now passes
`acceptedPrefix + 1` to state-replay caches, and the zero-draft-accept
branch goes through `rollback(1)` (keep y) instead of `cancel()` (lose y).
The protocol's `rollback(acceptedPrefix: k)` stays a low-level "fold the
first k entries" primitive — the +1 mapping is encapsulated in the
free helper so the iterator stays unaware of the entry count.

Added two regression tests in `StateReplayCacheTests`:
- Free-helper translation: zero-accept folds `rollback(1)` on state-replay
  layers (was `cancel`); partial-accept folds `acceptedPrefix + 1` (was
  `acceptedPrefix`).
- End-to-end with real `SSMStateCache`: records T=5 entries, accepts 0,
  expects state = snapshot folded through y only; offset = snapshot + 1.

Bench impact on Qwen3.5-35B-A3B-4bit (recipe-bulk, 1000 tokens):
- ngram-spot D=4: 65.3 → 89.5 tok/s (1.37× baseline, accept 67% → 83%)
- ngram-spot D=12: 65.3 → 107.3 tok/s (1.64× baseline, accept 34% → 92%)

The acceptance-rate jump (50+ pp at D=12) reflects what was happening
underneath: stale SSM state was producing logits inconsistent with the
draft model's predictions, so almost every draft was rejected. With
state correct, the verify model agrees with itself.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Confirms iterator runs cleanly on the hybrid cache, output coherent.
Perf is per-model: verify-of-T cost on dense 27B doesn't pay back at
this model's acceptance rates (44.5% at D=4 on recipe-bulk vs 83% on
Qwen3.5-35B-A3B's MoE verify, where T-token verify is comparatively
cheap because only A3B params route per token).

| Prompt | Config | tok/s | vs base | accept |
|--------|--------|------:|--------:|-------:|
| name   | base   | 17.9  | —       | —      |
| name   | D=2    | 17.2  | 0.96×   | 63.9%  |
| name   | D=4    | 15.4  | 0.86×   | 29.9%  |
| recipe | base   | 17.9  | —       | —      |
| recipe | D=2    | 16.9  | 0.94×   | 70.2%  |
| recipe | D=4    | 13.6  | 0.76×   | 44.5%  |
| recipe | D=8    | 9.3   | 0.52×   | 31.2%  |

Not a regression from the off-by-one fix — just a model + prompt combo
where spec-decode doesn't win. Recorded for completeness in the
hybrid-model coverage matrix.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Spec 020 PR diff should stay focused on the protocol + kernel + iterator
wiring. Qwen 3.5 / 3.6 ngram-spot numbers are summarized in the PR body
itself — the per-run rows in benchmarks/m1-max-64gb-2026-05-{06,07,11}.md
stay local. Matches the existing 2026-05-05 precedent.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Companion to the previous commit that removed the tracked bench files —
this entry keeps them ignored going forward so re-running the bench
script doesn't re-stage them.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski

ekryski commented May 12, 2026 •

Copy link
Copy Markdown
Owner Author

Hybrid-model ngram-spot bench (post off-by-one fix)

M1 Max 64GB, 4bit weights, no-quant KV, T=0, 1000-token decode (recipe-bulk prompt). All three hybrid models run cleanly on the state-replay path — NGramSpeculativeTokenIterator no longer throws on the GDN/attention hybrid cache, output coherent across all cells.

Qwen3.5-9B-4bit (recipe-bulk, 1000 tokens)

Config tok/s vs baseline acceptance
baseline 52.2 — —
ngram D=4 54.0 1.03× 77.3%
ngram D=12 adapt+strict 47.6 0.91× (mixed)

Qwen3.5-35B-A3B-4bit (recipe-bulk, 1000 tokens) — biggest win

Config tok/s vs baseline acceptance
baseline 65.3 — —
ngram D=4 89.5 1.37× 83.0%
ngram D=12 adapt+strict 107.3 1.64× 92.2%

Qwen3.6-27B-4bit (recipe-bulk, 1000 tokens) — correctness OK, no perf win

Config tok/s vs baseline acceptance
baseline 17.9 — —
ngram D=2 16.9 0.94× 70.2%
ngram D=4 13.6 0.76× 44.5%
ngram D=8 9.3 0.52× 31.2%
ngram D=12 adapt+strict 14.6 0.82× 37.2%

Iterator runs cleanly and output matches baseline structure — just a poor spec-decode target. Dense 27B + freeform thinking-mode output drops acceptance to 44.5% at D=4, and the T-token verify cost doesn't pay back at that rate. Not a regression from this PR; just confirming the hybrid cache works regardless of whether spec-decode wins for that particular model.

Nemotron Cascade 2 — cleanly opts out

canStateReplay = false set in NemotronH.swift for .mamba cache slots → iterator falls back to vanilla decode, ~77-79 tok/s consistent across all ngram configs (matches baseline). Mamba/Mamba 2 kernel support is documented as future work in spec 020.

ekryski and others added 3 commits May 11, 2026 20:12
Spec was originally written as a multi-phase plan with phase 1 (protocol)
landing first and phases 2 (kernel) / 3 (iterator) deferred to follow-ups.
The actual implementation consolidated phases 1-3 into PR #143 with a
4-repo native-kernel chain (mlx#26 → mlx-c#14 → mlx-swift#25 → mlx-swift-lm#143).

Status header now reflects:
  - Phases 1+2+3: DONE, GDN coverage (Qwen 3.5 / 3.6) live.
  - Phase 4 (DFlash iterator): DEFERRED — picks up when spec 015 phase 1 merges.
  - Phase 5 (PrefixKVCache): DEFERRED — picks up on spec 017's branch.
  - Mamba / Mamba 2: opted out via canStateReplay=false; future-work options
    ranked in §"Mamba / Mamba 2 follow-up (post-MVP)".

Risks section audited against the actual implementation — every risk now
has an explicit "mitigated" or "deferred + how" note:
  - #1 fp32 numerical equivalence: mitigated via state-in-fp32 throughout
    the recurrence; 4 equivalence tests lock it.
  - #2 memory pressure cap: no longer needed after Option A's per-round
    recording (50ba77f); 30 entries per round, not 360.
  - #3 Mamba variants: opted out cleanly; future work documented.
  - #4 spec-006 hierarchy: integration complete, no friction.
  - #5 masked-timestep correctness: kernel adopts 3217e15 pattern from
    day 1; verified at gated_delta_replay.metal:200-216. Gap noted:
    masked-replay unit test deferred (no live caller passes mask != nil).
  - #6 branchless discipline: c9f992e pattern adopted.
  - #7 NEW — off-by-one in iterator → protocol translation: documented
    with the fix and its bench impact (35B-A3B D=12 acceptance 34% → 92%).

Files-touched table rewritten with final paths + the 4-repo chain split.
Iterator-changes pseudo-code updated to match the shipped single-dispatch
shape (helper routes full vs partial accept internally) and the +1
translation is now called out explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Package.swift on the spec-020 branch uses
  .package(path: "../mlx-swift")
to develop native GDN tape kernels across the 4-repo chain without
round-tripping through tags every iteration. CI was failing at
"swift package resolve" because the runner only checked out
mlx-swift-lm, not the sibling.

Fix: split the checkout into two steps:
  - mlx-swift-lm @ this branch         → ./mlx-swift-lm
  - ekryski/mlx-swift @ ek/gdn-tape-native → ./mlx-swift

`defaults.run.working-directory: mlx-swift-lm` keeps existing run-steps
unchanged otherwise. Cache key now hashes both Package files so a push
to either repo busts the cache. Revert this whole change once mlx-swift
PR #25 merges and Package.swift goes back to a `.package(url:, exact:)`
pin on a new `0.32.2-alpha` tag.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
… convention

Two changes:

1. `alpha-ci.yml`: replace the hardcoded `ref: ek/gdn-tape-native`
   sibling-checkout pin with a "look up the PR branch name on
   ekryski/mlx-swift; fall back to alpha" auto-resolve step.

   Cross-repo PRs (where Package.swift is temporarily flipped to
   `.package(path: "../mlx-swift")` for native-kernel development)
   no longer require editing the workflow before push or reverting
   it before merge. Single-repo PRs continue to fall back to alpha.

2. `CONTRIBUTING.md`: new `Cross-repo pull requests (ekryski fork)`
   section documenting:
   - Conventions: identical branch names across all 4 repos,
     parallel PRs, explicit submodule bumps, Package.swift dev/
     release form.
   - Pre-merge checklist: merge order (mlx → mlx-c → mlx-swift →
     mlx-swift-lm), what to revert at each step, when to cut tags.
   - What the auto-resolve does so reviewers / contributors can
     reason about CI behaviour without spelunking the workflow.

Paired commit: `ekryski/mlx-c@031080d` does the same auto-resolve for
mlx-c's `Checkout ekryski/mlx` step.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski merged commit bf2d9e9 into alpha May 12, 2026
5 checks passed
ekryski added a commit that referenced this pull request May 12, 2026
Spec was originally written as a multi-phase plan with phase 1 (protocol)
landing first and phases 2 (kernel) / 3 (iterator) deferred to follow-ups.
The actual implementation consolidated phases 1-3 into PR #143 with a
4-repo native-kernel chain (mlx#26 → mlx-c#14 → mlx-swift#25 → mlx-swift-lm#143).

Status header now reflects:
  - Phases 1+2+3: DONE, GDN coverage (Qwen 3.5 / 3.6) live.
  - Phase 4 (DFlash iterator): DEFERRED — picks up when spec 015 phase 1 merges.
  - Phase 5 (PrefixKVCache): DEFERRED — picks up on spec 017's branch.
  - Mamba / Mamba 2: opted out via canStateReplay=false; future-work options
    ranked in §"Mamba / Mamba 2 follow-up (post-MVP)".

Risks section audited against the actual implementation — every risk now
has an explicit "mitigated" or "deferred + how" note:
  - #1 fp32 numerical equivalence: mitigated via state-in-fp32 throughout
    the recurrence; 4 equivalence tests lock it.
  - #2 memory pressure cap: no longer needed after Option A's per-round
    recording (50ba77f); 30 entries per round, not 360.
  - #3 Mamba variants: opted out cleanly; future work documented.
  - #4 spec-006 hierarchy: integration complete, no friction.
  - #5 masked-timestep correctness: kernel adopts 3217e15 pattern from
    day 1; verified at gated_delta_replay.metal:200-216. Gap noted:
    masked-replay unit test deferred (no live caller passes mask != nil).
  - #6 branchless discipline: c9f992e pattern adopted.
  - #7 NEW — off-by-one in iterator → protocol translation: documented
    with the fix and its bench impact (35B-A3B D=12 acceptance 34% → 92%).

Files-touched table rewritten with final paths + the 4-repo chain split.
Iterator-changes pseudo-code updated to match the shipped single-dispatch
shape (helper routes full vs partial accept internally) and the +1
translation is now called out explicitly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@ekryski
ekryski deleted the ek/020-tape-replay-phase1 branch May 12, 2026 03:12
ekryski added a commit that referenced this pull request May 12, 2026
Spec 020 (state-replay rollback at the cache layer) landed 2026-05-11
via PR #143 + the 4-repo cross-repo native kernel chain. Updates the
implementation plan to reflect:

  - Tier 1 row #5: ✅ SHIPPED with measured wins (Qwen3.5-35B-A3B-4bit
    D=12 adapt+strict 1.64× baseline at 92% accept).
  - Tier 2 row #10a (Spec 030 MTP): Variant A on hybrid Qwen no longer
    waits on Tier 1 — unblocked.
  - Tier 3 row #11 (Spec 015 DFlash): phase 3 prerequisite landed —
    now blocked only on draft-model availability, not on the rollback
    primitive.
  - Dependency graph: 020's "downstream unblocks" inlined.
  - Decision point #1: gate passed (fp32 state throughout the GDN
    recurrence; 7 equivalence tests lock it).
  - Decision point #3: prerequisite landed.
  - Status snapshot: "Tier 1 work — state-replay #143 phases 2-3"
    line replaced with the shipped milestone; "remaining Tier 1 item"
    is now prefix cache #144 phase 1B alone.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski added a commit that referenced this pull request May 12, 2026
…urface

IMPLEMENTATION-PLAN.md — perf backlog tables get a Status column:
- Six-emoji legend: 🟢/🔵/🟡/🟣/⚪/✅. Status applies per-row.
- Audited every issue (#61 / #73 / #74 / #77 / #89 / #114-#162) against
  GitHub. Found exactly one stale row: **#73 (KVCache refactor)** —
  already CLOSED on GitHub (spec 006 shipped via PRs #163-#166); the
  plan now reflects that. Every other row is OPEN with the appropriate
  blocked / investigation / re-bench / partial-progress sub-state.
- **#133 (prefix caching across sessions)** marked as partially
  addressed by spec 017 phase 4. Left a comment on the issue
  explaining the opaque-snapshot vs. zero-copy distinction and what's
  still pending (PagedKVCache + actor wrapping for concurrent serving).
  See issue thread.

documentation/generate-parameters.md — new spec 017 fields documented:
- New "Cross-request prefix KV cache (spec 017)" section covering
  `prefixCacheEnabled`, `prefixCachePolicy`, `prefixCacheModelID`,
  `prefixCacheDiskEnabled` — all default false / nil. Quick example
  showing a chat-mode setup with `FixedTrimPolicy(trimSuffix: 4)`.
- Extended the n-gram speculative section with `ngramDraftMin`,
  `ngramMinHits`, `minNgramSize` (which were missing from the public
  reference but shipped already).
- Added a "Prefix-cache env knobs" subsection covering
  `MLX_PREFIX_CACHE` / `MLX_PREFIX_CACHE_DISK` /
  `MLX_PREFIX_CACHE_DEBUG`.
- Cross-ref note on the n-gram + hybrid models section pointing at
  spec 020 coverage in speculative-decoding.md.

documentation/kv-cache.md — spec 020 + 017 user-facing surface:
- New "What's shipped recently" section covering spec 020
  (`StateReplayCache` protocol + `SSMStateCache` conformance +
  `canStateReplay` opt-out for Mamba) and spec 017 (cross-request
  prefix cache + quantisation-kind hydrate guard + opt-in L2 disk).
- Trimmable-cache section extended with a note on hybrid models'
  `canRollbackPromptCache(_:)` predicate.
- Cross-ref to the prefix-cache parameter section in
  generate-parameters.md so users don't manually thread caches across
  `generate(...)` calls when the prefix-cache opt-in does it
  transparently.

documentation/speculative-decoding.md — hybrid model coverage now live:
- Per-model table flipped Qwen 3.5 / 3.6 rows from "🔁 Auto-fallback"
  to "✅ Engages (spec 020)" with the measured 1.37x-1.64x numbers
  from PR #143 inlined. Mamba (Nemotron-H, Jamba) stays on auto-
  fallback per the per-cache `canStateReplay = false` opt-out.
- Compatibility-condition table updated to reference
  `canRollbackPromptCache(_:)` (the spec-020 predicate) instead of
  the legacy `canTrimPromptCache(_:)`.
- New "Hybrid model coverage (spec 020)" subsection explaining the
  `StateReplayCache` opt-in/opt-out model and how to set
  `canStateReplay` per-instance when wiring a new model factory.

Status-snapshot in the plan reflects the captured-reply bench numbers
(replaced the inflated stub-based ~10.9× headline with the honest
~4.3× number) and notes #73's closure.
ekryski added a commit that referenced this pull request May 12, 2026
…urface

IMPLEMENTATION-PLAN.md — perf backlog tables get a Status column:
- Six-emoji legend: 🟢/🔵/🟡/🟣/⚪/✅. Status applies per-row.
- Audited every issue (#61 / #73 / #74 / #77 / #89 / #114-#162) against
  GitHub. Found exactly one stale row: **#73 (KVCache refactor)** —
  already CLOSED on GitHub (spec 006 shipped via PRs #163-#166); the
  plan now reflects that. Every other row is OPEN with the appropriate
  blocked / investigation / re-bench / partial-progress sub-state.
- **#133 (prefix caching across sessions)** marked as partially
  addressed by spec 017 phase 4. Left a comment on the issue
  explaining the opaque-snapshot vs. zero-copy distinction and what's
  still pending (PagedKVCache + actor wrapping for concurrent serving).
  See issue thread.

documentation/generate-parameters.md — new spec 017 fields documented:
- New "Cross-request prefix KV cache (spec 017)" section covering
  `prefixCacheEnabled`, `prefixCachePolicy`, `prefixCacheModelID`,
  `prefixCacheDiskEnabled` — all default false / nil. Quick example
  showing a chat-mode setup with `FixedTrimPolicy(trimSuffix: 4)`.
- Extended the n-gram speculative section with `ngramDraftMin`,
  `ngramMinHits`, `minNgramSize` (which were missing from the public
  reference but shipped already).
- Added a "Prefix-cache env knobs" subsection covering
  `MLX_PREFIX_CACHE` / `MLX_PREFIX_CACHE_DISK` /
  `MLX_PREFIX_CACHE_DEBUG`.
- Cross-ref note on the n-gram + hybrid models section pointing at
  spec 020 coverage in speculative-decoding.md.

documentation/kv-cache.md — spec 020 + 017 user-facing surface:
- New "What's shipped recently" section covering spec 020
  (`StateReplayCache` protocol + `SSMStateCache` conformance +
  `canStateReplay` opt-out for Mamba) and spec 017 (cross-request
  prefix cache + quantisation-kind hydrate guard + opt-in L2 disk).
- Trimmable-cache section extended with a note on hybrid models'
  `canRollbackPromptCache(_:)` predicate.
- Cross-ref to the prefix-cache parameter section in
  generate-parameters.md so users don't manually thread caches across
  `generate(...)` calls when the prefix-cache opt-in does it
  transparently.

documentation/speculative-decoding.md — hybrid model coverage now live:
- Per-model table flipped Qwen 3.5 / 3.6 rows from "🔁 Auto-fallback"
  to "✅ Engages (spec 020)" with the measured 1.37x-1.64x numbers
  from PR #143 inlined. Mamba (Nemotron-H, Jamba) stays on auto-
  fallback per the per-cache `canStateReplay = false` opt-out.
- Compatibility-condition table updated to reference
  `canRollbackPromptCache(_:)` (the spec-020 predicate) instead of
  the legacy `canTrimPromptCache(_:)`.
- New "Hybrid model coverage (spec 020)" subsection explaining the
  `StateReplayCache` opt-in/opt-out model and how to set
  `canStateReplay` per-instance when wiring a new model factory.

Status-snapshot in the plan reflects the captured-reply bench numbers
(replaced the inflated stub-based ~10.9× headline with the honest
~4.3× number) and notes #73's closure.
TheTom pushed a commit to TheTom/mlx-swift-lm that referenced this pull request Jun 11, 2026
…l-explore#254)

**Fix Qwen35 VLM sanitize for bare `model.*` weight keys (ekryski#143)**

Unified Qwen 3.5 checkpoints ship language-model tensors at bare `model.*` paths instead of `model.language_model.*`, causing a `keyNotFound` failure at load time. Adds the same `else if key.hasPrefix("model.")` fallback already present in the LLM path, prepending `language_model.` to route tensors correctly.

Also adds a regression test covering all four key shapes: bare `model.*`, `model.language_model.*`, and `lm_head.*`.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

feature New feature (auto-applied from feat: prefix)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant