Repository navigation
feat(ngram): spec 023 phase 1 — Leviathan accept/reject sampling - #154
Merged
Merged
Conversation
Adds the Leviathan accept/reject sampling path to
NGramSpeculativeTokenIterator, enabling speculative decoding to engage
at temperature > 0 without breaking the distributional-equivalence
contract. Gated behind `MLX_NGRAM_LEVIATHAN=1` (opt-in for A/B
benchmarking; will flip to default-on at temp != 0 once the multi-
model sweep validates).
What's added:
- `ngramLeviathanEnabled()` — env-var read.
- `sampleResidual(logits:rejectedToken:sampler:)` — masks the
rejected slot to -inf via `MLX.where` (non-aliasing — does NOT
mutate the caller's logits tensor) then delegates to the
configured sampler. Works with any LogitSampler; the truncation-
at-rejected-slot collapses to "all mass redistributed to non-
rejected tokens" which the existing samplers handle natively.
- `leviathanActive` stored property on the iterator, set at init
from `parameters.temperature != 0 && ngramLeviathanEnabled()`.
- New verify-batch branch in `speculateRound` that runs per-position
accept/reject:
* Per position i: process logits, compute p[draft_i], sample
u ~ U(0,1), accept if u < p[draft_i] else reject.
* On reject: sample replacement from residual; stop chain.
* On full accept: sample bonus from full distribution at K+1.
* Strict-greedy guard not applicable (sampling has no argmax-
stability concept).
Uses a value-copy of the processor advancing through verify
positions (mirrors the greedy path's `verifyProcessor` pattern).
Original processor advances on accepted prefix + final token.
Route decision relaxed:
- `ngramRouteDecision(parameters:)` no longer disqualifies on
`temperature != 0` *when MLX_NGRAM_LEVIATHAN=1 is set*. Greedy
still takes the existing path; temp > 0 with the flag set runs
Leviathan.
Tests:
- 4 new route-decision tests covering Leviathan opt-in flipping the
temperature gate, plus the existing temp=0.6 declines test
renamed to "(Leviathan disabled)" for clarity.
- 1 test for `ngramLeviathanEnabled()` env-var parsing.
- 3 tests for `sampleResidual`: argmax-masked → second-largest
returned, non-argmax-masked → argmax preserved, aliasing-safety
(input logits tensor unmodified after call).
- withCleanEnv extended to also save/restore MLX_NGRAM_LEVIATHAN.
All 20 new/modified tests pass under `swift test -c release` after
`make` builds the metallib.
Phase status: Phase 1 (the iterator path). Phase 2 (unify with greedy
path — the temperature=0 case is byte-identical degenerate so we can
remove the dual implementation later) and Phase 3 (self-disengage on
chronically-low accept) are tracked in the spec.
Refs: specs/023-leviathan-accept-reject-sampling.md
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Initial spec-023 implementation computed `p[draft_i]` from `softmax(logits)` directly, ignoring the sampler's temperature. That's wrong: Leviathan's accept condition is `u < p_target(x)` where `p_target` is the *sampling* distribution — which for `CategoricalSampler(temperature: T)` is `softmax(logits / T)`. Without the temperature scaling, the accept-probability comparison uses a flatter distribution than the sampler actually draws from, biasing toward over-rejection of high-margin tokens at low temperature. Fix: store `leviathanTemperature` on the iterator at init time (captured from `parameters.temperature`) and apply `logits / leviathanTemperature` before the softmax in the accept-probability computation. Greedy path (`temperature == 0`) ignores this field; we store 1.0 to keep the type total. Empirically the A/B-test impact on the recipe-rewrite prompt was nil — the top-1 token's probability is so close to 1 that temperature scaling doesn't move it noticeably (`softmax(raw)[top]` ≈ `softmax(raw/0.6)[top]` ≈ 0.99+). Accept rate identical (75/107) both before and after the fix. The bug would matter on flatter distributions (paraphrastic content, large vocabularies, low- confidence positions) — to be validated in the broader multi-prompt sweep. A/B numbers post-fix on Gemma 4 26B A4B + recipe-rewrite, 5 trials per cell: - TI greedy (control) : 28.4 tok/s - NGram greedy (control) : 42.8 tok/s (1.51× — variance vs prior 1.29× run) - TI temp=0.6 : 28.6 tok/s - NGram + Leviathan temp=0.6: 33.2 tok/s (1.16× over TI temp=0.6) The 1.16× is meaningfully smaller than greedy's 1.51× because the Leviathan path does per-position softmax + per-position `eval(p)` to extract `p[draft_i]` — multiple CPU↔GPU syncs per cycle vs the greedy path's single batch `eval` at the end of verify. Reducing this overhead (batch the softmax across positions, single eval) is a phase-2 optimisation tracked in the spec. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
120-run multi-model multi-prompt multi-temperature sweep validating spec 023 phase 1 (Leviathan accept/reject sampling). Findings: **1. Leviathan delivers the headline win on big-model + regurgitative content.** Gemma 4 26B A4B + recipe-rewrite at temp=0.6 and temp=1.0 both produce **1.18× speedup** vs the matching `TokenIterator` baseline (34.4 / 29.1 and 34.3 / 29.1 tok/s). Previously unattainable — n-gram declined at temp != 0 pre-PR-#154. Spec-023 hypothesis validated for this regime. **2. Speedup is invariant to temperature.** temp=0.6 and temp=1.0 produce identical speedups and identical accept rates (75/107 = 70.1% across both, matching greedy's accept rate exactly). On this prompt class the top-1 logit margin is wide enough that softmax(L/T)[argmax] ≈ 0.99+ at both temperatures — temperature scaling doesn't move the needle. **3. Greedy n-gram beats Leviathan even at the same regime.** 1.32× greedy vs 1.18× Leviathan on 26B + recipe. The ~10-15% speedup-ratio gap is entirely from per-position softmax + per-position eval(p) introducing extra CPU↔GPU syncs. Phase-2 batched-softmax optimisation is well-motivated. Greedy and Leviathan cover disjoint regimes (temp=0 vs temp>0), so this isn't a competition. **4. Paraphrastic content + Leviathan = consistent regression** (0.86-0.94× across both models). Same root cause as paraphrastic + greedy: lookup almost never hits (3-13 proposals vs 105-108 on recipe), and when it does the low-probability draft (Leviathan path) or strict-greedy guard (greedy path) rejects everything. **5. Small/fast model + Leviathan = strong regression** (0.77× on E2B 4-bit + recipe at temp=0.6). Per-position softmax + per-position eval is brutal at 100+ tok/s baseline. Leviathan inherits and *amplifies* the small-model regression of greedy (0.97× → 0.77×). **6. Cross-cutting recommendation:** engage Leviathan only where greedy would also be engaged. Phase-1 release should keep MLX_NGRAM_LEVIATHAN=1 opt-in (not default-on). Auto-engagement decision should track issue #153's auto-disengage heuristic discussion. Methodology: 5 trials per cell, median reported. Parser bug in initial pass (last cell of each section misattributed to next) caught and fixed before final medians. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…ycle)
Phase 1's Leviathan implementation called `eval(p)` per draft position
to extract `p[draft_i]` for the accept/reject comparison. Each eval is
a CPU↔GPU sync, costing ~1-3 ms/sync depending on model size. With
numDraft=3 that's ~3-9 evals per cycle plus the final residual/bonus
sample.
This commit collapses the verify-batch's p-value extraction to a
single eval. Structure:
- Sequential `process(logits) + didSample(draft_i)` builds a lazy
chain across all `numDraft` positions. The didSample tokens are
CPU-known constants (the draft IDs), so the verify-processor's
state evolves through the loop without forcing GPU sync.
- After the loop: stack all logits to `[numDraft, V]`, scale by
temperature, softmax, and gather `p[i, draft_i]` per row via
`takeAlong(probs, draftIndices, axis: -1)`.
- One eval flushes the entire graph; `pValues.asArray(Float.self)`
produces a Swift `[Float]` for the CPU accept/reject walk.
- The residual sample (on reject) or bonus sample (on full accept)
runs as one final eval. Total per cycle: 2 evals.
Re-ran the same broad sweep as the prior phase-1 implementation
(120 runs across 2 models × 2 prompts × 3 temps × 6 cells, 5-trial
medians). Speedup-ratio deltas (NGlev / matching `TI@temp`):
- 26B A4B + recipe + temp=0.6: 1.18× → **1.31×** (+0.13) ✅
- 26B A4B + recipe + temp=1.0: 1.18× → **1.25×** (+0.07) ✅
- 26B A4B + lighthouse @ both: -0.01 / -0.02 (within noise)
- E2B + recipe @ both: +0.01 / 0.00 (within noise)
- E2B + lighthouse @ both: -0.01 / -0.02 (within noise)
The optimisation **closes the Leviathan-vs-greedy throughput gap**
on the favourable regime (greedy's 1.32× → Leviathan's 1.31×, ~1%
remainder). On the regression regimes the bottleneck was never
per-position eval — it was lookup-misses (paraphrastic) or per-token
bookkeeping floor (small/fast model) — so batching neither helps nor
hurts there.
The remaining ~7-point gap at temp=1.0 vs temp=0.6 comes from the
residual / bonus sampling step's eval scaling modestly with
distribution flatness (more probability mass spread across more
tokens means the categorical sampler does more meaningful work per
call). Not eliminable without restructuring the Leviathan algorithm
itself.
Analysis file (`benchmarks/gemma4-leviathan-broad-sweep-analysis.md`)
updated with phase-1 vs phase-1+batched comparison table and revised
findings/conclusions. Recommendation unchanged: keep
`MLX_NGRAM_LEVIATHAN=1` opt-in for phase-1 release; auto-engagement
decision should track issue #153.
20 unit tests still pass (3 sampleResidual + 17 route-decision).
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
marked this pull request as ready for review
April 30, 2026 04:37
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>
This was referenced 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>
Per the user's request, ran the same 6-cell × 5-trial sweep on GPT-OSS-20B (mxfp4, mlx-community/gpt-oss-20b-MXFP4-Q8) to fill in the third pure-attention model class. Result: GPT-OSS sits in the fast-model regression regime, not the favourable one. Recipe-rewrite (regurgitative) speedups: - NGgreedy@0: 61.3 / 72.0 = 0.85×⚠️ - NGlev@0.6: 51.4 / 67.9 = 0.76× ❌ - NGlev@1.0: 44.0 / 66.9 = 0.66× ❌ Lighthouse-keeper (paraphrastic): - NGgreedy@0: 63.8 / 69.8 = 0.91×⚠️ - NGlev@0.6: 59.2 / 68.9 = 0.86×⚠️ - NGlev@1.0: 58.0 / 67.8 = 0.86×⚠️ The pattern from prior sweeps tightens: the threshold for n-gram to win is ~30-40 ms/token forward time (≈25-30 tok/s baseline) on M1 Max. Below that, the iterator's per-token overhead doesn't amortise even at 50-70% accept rate. GPT-OSS-20B at ~14 ms/token forward (~70 tok/s baseline) sits below the threshold despite its 20B parameter count — "weight-bandwidth-bound" was the right intuition but the threshold is absolute per-token forward cost, not param count. Notable observations: - NGlev@1.0 recipe trials show wide variance (32.9-54.6 tok/s) with accept rates 14-62%. Higher temperature → more stochastic token selection → more variable lookup hit rate. Inherent to sampling. - 44.2% accept rate on GPT-OSS recipe (vs 70% on Gemma 4 26B A4B) suggests GPT-OSS's tokenizer / generation pattern produces fewer exact-prefix repeats than Gemma's. - This is the cleanest argument yet for issue #153 option (B): a per-model baseline tok/s threshold would catch GPT-OSS automatically; rolling-accept-rate (option A) would NOT, since 44% accept is well above any "low accept" threshold. Updates `Documentation.docc/speculative-decoding.md` to add GPT-OSS-20B to the supported-models table (⚠️ engages but slower, same row class as Gemma 4 E2B 4-bit). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
ekryski
added a commit
that referenced
this pull request
Apr 30, 2026
120-run multi-model multi-prompt multi-temperature sweep validating spec 023 phase 1 (Leviathan accept/reject sampling). Findings: **1. Leviathan delivers the headline win on big-model + regurgitative content.** Gemma 4 26B A4B + recipe-rewrite at temp=0.6 and temp=1.0 both produce **1.18× speedup** vs the matching `TokenIterator` baseline (34.4 / 29.1 and 34.3 / 29.1 tok/s). Previously unattainable — n-gram declined at temp != 0 pre-PR-#154. Spec-023 hypothesis validated for this regime. **2. Speedup is invariant to temperature.** temp=0.6 and temp=1.0 produce identical speedups and identical accept rates (75/107 = 70.1% across both, matching greedy's accept rate exactly). On this prompt class the top-1 logit margin is wide enough that softmax(L/T)[argmax] ≈ 0.99+ at both temperatures — temperature scaling doesn't move the needle. **3. Greedy n-gram beats Leviathan even at the same regime.** 1.32× greedy vs 1.18× Leviathan on 26B + recipe. The ~10-15% speedup-ratio gap is entirely from per-position softmax + per-position eval(p) introducing extra CPU↔GPU syncs. Phase-2 batched-softmax optimisation is well-motivated. Greedy and Leviathan cover disjoint regimes (temp=0 vs temp>0), so this isn't a competition. **4. Paraphrastic content + Leviathan = consistent regression** (0.86-0.94× across both models). Same root cause as paraphrastic + greedy: lookup almost never hits (3-13 proposals vs 105-108 on recipe), and when it does the low-probability draft (Leviathan path) or strict-greedy guard (greedy path) rejects everything. **5. Small/fast model + Leviathan = strong regression** (0.77× on E2B 4-bit + recipe at temp=0.6). Per-position softmax + per-position eval is brutal at 100+ tok/s baseline. Leviathan inherits and *amplifies* the small-model regression of greedy (0.97× → 0.77×). **6. Cross-cutting recommendation:** engage Leviathan only where greedy would also be engaged. Phase-1 release should keep MLX_NGRAM_LEVIATHAN=1 opt-in (not default-on). Auto-engagement decision should track issue #153's auto-disengage heuristic discussion. Methodology: 5 trials per cell, median reported. Parser bug in initial pass (last cell of each section misattributed to next) caught and fixed before final medians. 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
May 15, 2026
…to Tier 2 (#222) * docs(specs + skills): refresh status against alpha (specs 040/041/043, spec 006/017/020/023 shipped; skills/kv-cache rewrite) Spec status headers: - 006: ✅ Shipped via PRs #163–#166 (KV cache type consolidation) - 014/015/016/019/021/022: 🚧 Phase 1 scaffolds landed; phase 2+ open - 017: ✅ All phases (1, 1B, 2, 3, 4, 5 Option A) shipped via #144 + #198 - 023: ✅ Phase 1 shipped via #154; Phase 3 subsumed by #153 - 041: ✅ Phases 1, 1.1, 1.2, 2, 4, 5 shipped via #212→#213→#214→#215; Phase 1.2 perf uplift moved to spec 042 Phase 1b; Phase 3 deferred to spec 039 IMPLEMENTATION-PLAN.md: - Last-updated bump 2026-05-13 → 2026-05-14 - New 2026-05-14 update note covering the spec 040/041/6c/043 ship wave - Row 6c (GPT-OSS sinks) rewritten with actual landing PRs (#213 + #215 chain — prior row cited fabricated commit SHAs) - Row 6d (spec 043) updated to "doc shipped via #219; impl not started" - Spec 041 promoted from Tier 4 row 25 to Tier 2 row 10g (landed early as a gate-keeper for spec 040, Tier 1 row 6c, Gemma 4 KV-sharing fallback retirement, spec 042/043 kernel-uplift wave) - Tier 4 renumbered: 042 is now row 25 (was row 26) - Status snapshot rewritten: Tier 2 row 10g spec 041 ship state, Tier 1 row 6b spec 040 ship state, Tier 1 row 6d spec 043 doc ship, expanded closed-issue list, new Kernel-uplift-wave priority bullet - Dependency graph: spec 040 reframed from "future work" to "shipped"; spec 017 phase 3 marked shipped - Issue #185 marked ✅ CLOSED (was 🟡 OPEN); resolution path cited - Issue #77 cross-linked to #160 + spec 043 Phase 1 - Issue #61 confirmed still relevant - Fixed stale "Tier 4 row 26 spec 042" refs across the doc to "Tier 4 row 25" Skills directory: - references/kv-cache.md: major rewrite. Old text had AffineQuantizedKVCache as "unbounded only" (now rotating-window via spec 041 phase 1.2), TurboQuantizedKVCache windowed eviction "until #185 is fixed" (#185 closed 2026-05-12), stale "Gemma 4 produces incoherent output under windowed turbo", wrong makeAttentionCache signature. Added sections for AffineSDPAStrategy + MLX_AFFINE_SDPA env var, useBias/DC-bias correction, TurboFlash A/B decode paths, state-replay rollback (specs 020 + 040), cross-request prefix cache (spec 017), prefillStep parameter threading. - references/supported-models.md: GPT-OSS row no longer claims supportsTurboQuantization: false; documents DC-bias + hybrid sliding-FP16 policy + turbo_flash_sdpa_v sinks kernel. - SKILL.md: GenerateParameters maxKVSize comment updated to reflect uniform rotating-eviction across .none/.affine/.turbo; added prefixCacheEnabled to example + Optional Configuration table. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(specs): bulletize Status / Branch / Depends-on frontmatter blocks Convert the **Field:** paragraph blocks at the top of each spec to a bullet list (`- **Field:** ...`). Same content, easier to scan — fields render as a unified list instead of stacked bold-prefix lines. Sub-bullets under "Depends on:" indent under their parent. Wrapped continuation lines indent to align with the bullet body. Spec 040 also restructured: the multi-paragraph ship details that lived under the Status field moved to a new "## Ship details (2026-05-13)" section below the metadata bullets, so Status / Branch / Depends-on form a clean top-of-file block. Spec 020 closed the blank line that separated Status from Branch so the metadata renders as a single tight bullet list. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
div0-space
pushed a commit
to LibraxisAI/mlx-swift-lm
that referenced
this pull request
Nov 29, 2026
…port-20260917 Bonsai 2 27B: native packed Hadamard text and vision support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Spec 023 — extends `NGramSpeculativeTokenIterator` with Leviathan accept/reject sampling so n-gram speculative decoding can engage at `temperature > 0`. Pre-PR-#154, the route declined on non-greedy temperature, falling back to plain `TokenIterator` and losing the entire spec-decode speedup. Leviathan closes that gap.
Default-on at `temperature != 0` when n-gram is opted into. Set `MLX_NGRAM_LEVIATHAN=0` to disable (diagnostic A/B only — production should leave it on).
Spec 023 phases 2 (unify-with-greedy) and 3 (self-disengage) are explicitly closed out without implementation — phase 2 has hidden complexity that turns the "~50 LOC cleanup" into a correctness/perf surface, phase 3 is subsumed by issue #153 and should apply uniformly to both greedy and Leviathan. See spec 023 for the full rationale.
Refs: `specs/023-leviathan-accept-reject-sampling.md`, `benchmarks/gemma4-leviathan-broad-sweep-analysis.md`.
What lands
User-facing doc and analysis writeup also land in this PR.
Headline result — broad sweep
240 total runs across two implementations (per-position eval vs batched eval) × 2 models × 2 prompts × 3 temperatures × 6 cells, 5-trial median. Numbers below are the batched (current) implementation:
Batched optimisation closes the Leviathan-vs-greedy gap on the favourable regime — phase-1 implementation hit 1.18×; batched hits 1.31× at temp=0.6, within ~1% of greedy's 1.32×.
Phase comparison:
The optimisation is concentrated where it could matter (favourable regime where per-position eval was the dominant overhead). On the regression regimes the bottleneck is something else — lookup misses on paraphrastic content, per-token bookkeeping floor on E2B — so batching doesn't help there but doesn't hurt either.
Tests
21 tests, all passing under `swift test -c release` after `make`:
Spec phases — final status
Phase-1 shipping recommendation
Default-on for sampling, opt-in for n-gram itself. With the batched optimisation, the throughput case for engaging Leviathan is strong on the favourable regime (matches greedy's 1.32× within 1%). The case for not engaging on the regression regimes is unchanged from greedy n-gram — paraphrastic content, small/fast models — and is the user's choice when they decided to opt into n-gram in the first place. `MLX_NGRAM_LEVIATHAN=0` exists for diagnostic A/B; production should leave the default.
Limitations / explicit non-goals
Test plan