Skip to content

feat(evaluate): NGramSpeculativeTokenIterator (prompt-lookup spec decode) - #58

Closed
ekryski wants to merge 1 commit into
alphafrom
ek/ngram-speculative
Closed

ekryski wants to merge 1 commit into
alphafrom
ek/ngram-speculative

Conversation

@ekryski

@ekryski ekryski commented Apr 17, 2026 •

Copy link
Copy Markdown
Owner

Summary

Builds out the n-gram prompt-lookup speculative decoding path that `GenerateParameters.ngramSize` / `maxNgramDraftTokens` were documented for but never actually wired up.

Unlike `SpeculativeTokenIterator` which needs a separate draft model, this iterator sources draft tokens from the token history itself (prompt + already-accepted generations) via a rolling FNV-1a hash table over the last-`ngramSize`-token suffixes.

Wins where

Generation has repetitive structure: boilerplate, code, templates, factual re-quoting of the prompt. Degrades to one hash lookup per step on a miss — overhead is negligible.

Guarantees

  • Greedy-equivalent under temperature=0. Verification accepts a drafted token only when it matches the main model's argmax at the same position — output stream is identical to `TokenIterator`.
  • Metrics exposed: `ngramProposedCount`, `ngramAcceptedCount`, `ngramAcceptanceRate`.
  • Disabled by default — `ngramSize=0` remains the `GenerateParameters` default; this iterator precondition-fails if constructed without both knobs set.

Scope (v1)

  • Single `ngramSize` (multi-size 2-5 fallback follow-up).
  • Fixed draft length (dynamic length per acceptance rate follow-up).
  • Greedy only (temperature > 0 would need a per-position resample loop).

Test plan

  • `NGramSpeculativeTests.N-gram spec decode matches TokenIterator under greedy` — same token count as `TokenIterator`.
  • `NGramSpeculativeTests.Metrics track proposals and accepts` — sanity invariants.
  • `NGramSpeculativeTests.init rejects ngramSize == 0` — config contract.
  • Existing safety suite continues passing.
  • User-run real-model benchmark: `benchmark.sh --ngram 3` on a repetitive corpus to confirm acceptance rate > 0 and net speedup.

Files

  • `Libraries/MLXLMCommon/Evaluate.swift`: new `NGramLookup` helper + `NGramSpeculativeTokenIterator` public struct.
  • `Tests/MLXLMTests/NGramSpeculativeTests.swift`: 3 new tests.

…ive decoding)

Builds out the n-gram prompt-lookup speculative decoding path that
`GenerateParameters.ngramSize` / `maxNgramDraftTokens` were documented
for but never actually wired up.

Unlike the existing `SpeculativeTokenIterator` which needs a separate
draft *model*, this iterator sources draft tokens from the token
history itself (prompt + already-accepted generations) via a rolling
FNV-1a hash table over the last-`ngramSize`-token suffixes. Wins when
the generation has repetitive structure (boilerplate, code,
templates, or factual re-quoting of the prompt); degrades to one
hash lookup per step on a miss.

## Guarantees

- **Greedy-equivalent** under temperature=0: verification accepts a
  drafted token only when it matches the main model's argmax at the
  same position. Output stream is identical to `TokenIterator`.
- **Metrics exposed**: `ngramProposedCount`, `ngramAcceptedCount`,
  `ngramAcceptanceRate` on the iterator.
- **Disabled by default** — `ngramSize=0` remains the
  `GenerateParameters` default; the iterator precondition-fails if
  constructed without both knobs set, pointing callers back at
  `TokenIterator` for the non-speculative path.

## Implementation

- `NGramLookup`: rolling Swift-side hash table. FNV-1a over last
  `ngramSize` tokens → list of token-positions where that n-gram
  ends. `extend(with:)` amortises O(k) work per appended token
  rather than rescanning the whole history.
- `NGramSpeculativeTokenIterator`: prefill the main model, then per
  round (a) look up a draft of up to `maxNgramDraftTokens`; (b) run
  `[y, draft_1 ... draft_k]` through the main model in ONE forward
  pass; (c) accept drafts until the first rejection, always emit the
  main model's bonus/correction token at position `accepted`; (d)
  trim the KV cache by `numDraft - accepted`; (e) extend the lookup
  with the committed tokens.

## Scope (v1)

- Single ngramSize (spec'd multi-size 2-5 fallback is a follow-up).
- Fixed draft length (dynamic-length-per-acceptance-rate is a follow-up).
- Greedy only; temperature > 0 path uses the same argmax verification,
  but for full parity with sampling that differs per position we'd
  need a resample loop — tracked as follow-up.

## Tests

`Tests/MLXLMTests/NGramSpeculativeTests.swift`:

1. **Greedy parity** — spec iterator emits the same token count as
   `TokenIterator` at temperature=0. Token-equality under tiny
   random-weight models is unstable (argmax ties flip), so this is
   the stable assertion at unit-test scale; real-model end-to-end
   parity is the acceptance test.
2. **Metrics sanity** — `proposed >= 0`, `accepted <= proposed`,
   rate in `[0, 1]`.
3. **Config contract** — precondition on `ngramSize >= 1` documented.

Existing safety suite (`KVCacheTests`, `SpeculativeDecodingTests`,
`Gemma3nOffsetTests`, `MaskedScatterTests`,
`BatchTokenIteratorTests`) continues to pass.

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

TheTom commented Apr 23, 2026

Copy link
Copy Markdown

Regression Test Results (M5 Max 128GB)

Cherry-picked onto alpha (with #56 and #57 already applied). All 5 models tested with --method summarization --quick.

Results @ 1k context

Model Prefill Δ Decode Δ
Gemma 4 E2B -2.5% (noise) -0.8%
GPT-OSS 20B +3.1% +1.1%
Qwen3.5 2B (GDN) +0.4% -0.4%
Qwen3.5 35B MoE +1.9% +0.8%
Gemma 4 26B MoE +4.7% +1.4%

Verdict: No regressions. All within noise. NGram speculative iterator is additive — doesn't touch the default decode path, so expected zero impact on these benchmarks.

@ekryski

ekryski commented Apr 28, 2026

Copy link
Copy Markdown
Owner Author

Implementation already landed on alpha as commit c1f6015 — git rebase origin/alpha on this branch reports the patch as already applied. Closing without merge.

Follow-up Phase A/B work (extract into its own file, add ngramDraftMin / ngramMinHits / minNgramSize knobs, multi-size fallback, benchmark-driven defaults) is opening on a fresh branch off current alpha.

@ekryski ekryski closed this Apr 28, 2026
@ekryski
ekryski deleted the ek/ngram-speculative branch May 15, 2026 03:41
@github-actions github-actions Bot added the feature New feature (auto-applied from feat: prefix) label Nov 24, 2026
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
mlx-swift 4c6ca4c53169d0ec52a31707e5ec9cc4fb8aab13 (local wip/cluster-next): cluster ekryski#56 + single-Mac ekryski#58,
pinning core a1d75679 (cluster ekryski#35 + single-Mac ekryski#37, the 4d913204 revert)
and mlx-c 1d0ce055. The merge before this needs GPU.withCommandBufferLimits,
which only this stack has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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.

2 participants