Skip to content

feat(spec-decode): spec 022 phase 1 — deterministic-stretch acceleration - #145

Draft
ekryski wants to merge 6 commits into
alphafrom
ek/022-deterministic-stretch-phase1
Draft

ekryski wants to merge 6 commits into
alphafrom
ek/022-deterministic-stretch-phase1

Conversation

@ekryski

@ekryski ekryski commented Apr 29, 2026 •

Copy link
Copy Markdown
Owner

Summary

Spec 022 phase 1 — "free-token short-circuit" speculation. Two complementary mechanisms:

  • A. Chat-template grammar state machine — deterministic stretches at structural boundaries (channel markers, thinking-end, turn openers).
  • B. Common-bigram fallback drafter — high-confidence two-token-history → next-token table for broad probabilistic coverage.

Phase 1 ships the protocol + state types + a NoOp / Trigger grammar + the bigram data structure + a frequency-map → table builder. Per-family grammars (Qwen 3.5 / Gemma 4 / GPT-OSS / Llama) and the offline corpus builder land in phases 2-3.

Stack: #113 → #140 → #141 → #142 → #143 → #144 → this PR.

What lands

  • `Libraries/MLXLMCommon/ChatTemplateGrammar.swift` — `ChatTemplateGrammar` protocol, `ChatTemplatePhase` enum, `ChatTemplateConfig` (turn / think / channel / message / newline token IDs), `ChatTemplateState` (phase + recent tokens + config), `NoOpChatGrammar` (always nil — fallback default), `TriggerTokenGrammar` (test stub).
  • `Libraries/MLXLMCommon/BigramTable.swift` — `BigramKey`, `BigramEntry`, `BigramTable` (two-level dict, `confidentNext`, greedy `bigramDraft` chain walk), and `BigramTable.build(fromFrequencies:threshold:)` builder.
  • `Tests/MLXLMTests/DeterministicStretchTests.swift` — 16 tests:
    • `ChatTemplateGrammarTests` (3): NoOp behaviour, TriggerToken selectivity, phase equality.
    • `BigramTableTests` (13): empty lookup, insert/lookup, overwrite, greedy chain walk, chain break, maxK cap, short recentTokens, zero maxK, threshold admission, top-1 selection, empty input, defensive zero-count handling, BigramKey equality + hashable.

Pure-Swift, no MLX eval. All 16 tests pass under `swift test`.

Phase-1 limitations (deferred)

  • Per-family grammars (`Qwen35Grammar`, `Gemma4Grammar`, `GPTOSSGrammar`, `LlamaGrammar`) → phase 2; depend on tokenizer-resolved special-token IDs.
  • Offline bigram corpus build pipeline + binary serialisation → phase 2.
  • Iterator wiring (the new draft ladder in `NGramSpeculativeTokenIterator.speculateRound`) → phase 3 once both mechanisms have populated implementations.
  • `--method free-tokens` bench harness mode → phase 3.

Test plan

  • `swift test --filter ChatTemplateGrammarTests` — 3 pass.
  • `swift test --filter BigramTableTests` — 13 pass.
  • Full `swift build` clean.

Evaluation (when phase 2+ lands)

Deterministic-stretch (spec 022) eval — phase 2+: Once per-family chat-template grammars land (Qwen 3.5 / Gemma 4 / GPT-OSS / Llama) plus the bigram corpus build:

# Highest-leverage target: GPT-OSS harmony channel transitions
scripts/spec-decode-sweep.sh --model gpt-oss-20b --quant mxfp4 \
    --prompts Tests/Benchmarks/Resources/ngram-sweep-prompts/chat-instruction \
    --cells "no-grammar:3:0:,grammar:3:0:MLX_NGRAM_GRAMMAR=1" \
    --trials 5 --output /tmp/grammar-treatment.log
scripts/spec-decode-compare.py /tmp/no-grammar.log /tmp/grammar-treatment.log

Pass criterion: +15-30% on GPT-OSS harmony format (per spec 022 published projection). Smaller model families should show +5%.

For the canonical sweep+compare workflow, see scripts/spec-decode-sweep.sh and scripts/spec-decode-compare.py (added in PR #154). Workload classification + recommended cell-set in Tests/Benchmarks/Resources/ngram-sweep-prompts/README.md.

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
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 and others added 6 commits April 30, 2026 00:23
Ports the DFlash block-diffusion speculative-decoding cycle from
`bstnxbt/dflash-mlx` (Python) and `SharpAI/SwiftLM` (Swift in-progress)
to mlx-swift-lm. Phase 1 lands the protocol surface, the iterator, and
two stub draft backends — proving the cycle plumbing end-to-end on
full-attention targets without depending on a trained draft model.
Phase 2 (real diffusion draft + per-target conformances) and phase 3
(hybrid GDN tape-replay rollback) follow in stacked PRs.

New files:
- `Libraries/MLXLMCommon/DFlashTargetModel.swift` — `DFlashTargetModel`
  protocol (embed / lm-head / forward-with-capture / `dflashIsHybridGDN`)
  + `dflashDefaultCaptureLayerIDs` helper mirroring dflash-mlx's
  `buildTargetLayerIDs`.
- `Libraries/MLXLMCommon/DFlashDraftBackend.swift` — `DFlashDraftBackend`
  protocol + `ZeroAcceptDraftBackend` (always-rejects stub for cycle
  tests) + `ScriptedDraftBackend` (replay scripted blocks for
  deterministic accept/reject pattern testing) + pure-Swift
  `dflashAcceptedPrefixLength` helper.
- `Libraries/MLXLMCommon/DFlashSpeculativeDecoding.swift` —
  `DFlashSpeculativeTokenIterator` conforming to `TokenIteratorProtocol`.
  Cycle: draft → verify (with hidden-state capture) → accept-prefix
  walk → emit prefix + bonus token → trim cache → slice captured
  hidden state for next draft.
- `Tests/MLXLMTests/DFlashSpeculativeTests.swift` — 19 tests across
  three suites:
  - `DFlashHelperTests` (9): pure-Swift helpers, no MLX eval.
  - `DFlashDraftBackendTests` (4): stub backend behavior.
  - `DFlashSpeculativeIteratorTests` (6): integration with a
    `MockDFlashTarget` wrapping `Gemma3TextModel` — exercises emit
    count, zero-accept path, capture-call routing, count-parity vs.
    `TokenIterator`, AR fallback after script exhaustion, and the
    hybrid-GDN init-time rejection guard.

Phase-1 limitations (deferred to phase 2/3):
- Hybrid GDN/Mamba targets (`dflashIsHybridGDN == true`) throw at init.
  Phase 3 will add tape-replay rollback (spec 020 dependency).
- Stub backends produce 0% acceptance, so the iterator runs **slower**
  than baseline `TokenIterator` — this is intentional. The goal is
  cycle-correctness validation; speedup measurement waits on phase 2's
  trained draft model.
- No auto-routing in `MLXLMCommon.generate(...)` yet — callers must
  construct the iterator directly. Wiring lands in phase 2 alongside
  draft-resolution registry.

13 unit tests pass via `swift test`; 6 integration tests build cleanly
and run under Xcode/CI (the CLI runner hits the same metallib-loading
issue that affects existing `NGramSpeculativeTests` integration cases).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Empty-draft AR fallback near `maxTokens` (when `remaining - 1 == 0`)
bumps `dflashCycleCount` but skips the capture forward, so the strict
equality I asserted only holds when generation length is an exact
multiple of (blockSize + 1). Real fix: assert
`captureCalls <= cycleCount` and let the bookkeeping match across all
budget shapes.

All 19 DFlash tests pass under `swift test -c release`.

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

Spec 021's headline path: a small ANE draft (Core ML) paired with a GPU
target (MLX), executing in parallel across compute units. Phase 1A is
nominally a measurement spike that requires the `CoreML-LLM` Swift
package + a real Qwen 3.5 0.8B Core ML bundle on hardware. This commit
lands the *scaffold* — protocol surface, registry, vocab gate, iterator
skeleton, full unit tests — without the Core ML dependency, so Phase 1B
can swap in a real backend without iterator changes.

Same scaffold pattern as DFlash phase 1 (#141): separate the protocol
from the concrete backend, make the protocol scriptable for tests, ship
a sequential cycle now and pipeline draft↔verify in a later PR.

New files:
- `Libraries/MLXLMCommon/ANEDraftBackend.swift` — `ANEDraftBackend`
  protocol + `ScriptedANEDraftBackend` (test stub) +
  `ZeroAcceptANEDraftBackend` (always-rejects, exercises the
  reject-everything cycle). Cross-framework friendly: takes
  `committedTokens` + `lastCommittedToken`, returns `[Int]` — no MLX
  tensors crossing the protocol boundary.
- `Libraries/MLXLMCommon/ANEDraftRegistry.swift` — pure-Swift target ID →
  draft bundle URL mapping. Default registry ships empty; apps populate
  at launch (e.g. for any drafts shipped with the bundle). No Core ML
  import — just metadata.
- `Libraries/MLXLMCommon/ANEVocabEquivalence.swift` — llama.cpp-style
  vocabulary equivalence gate (`SPEC_VOCAB_MAX_SIZE_DIFFERENCE = 128`,
  `SPEC_VOCAB_CHECK_START_TOKEN_ID = 5`, zero-disagreement policy by
  default). Pure-Swift; takes two `[Int: String]` maps to stay
  decoupled from the `Tokenizers` package.
- `Libraries/MLXLMCommon/MirrorSpeculativeDecoding.swift` —
  `MirrorSpeculativeTokenIterator: TokenIteratorProtocol`. Sequential
  draft→verify cycle (Phase 2 will pipeline). Reuses
  `dflashAcceptedPrefixLength` for the accept walk — same contract.
  Init-time gate: throws on incompatible vocab report or non-trimmable
  cache (hybrid GDN; awaits spec 020).
- `Tests/MLXLMTests/MirrorSpeculativeTests.swift` — 23 tests across
  four suites:
  - `ANEDraftRegistryTests` (4): register / lookup / remove / replace.
  - `ANEVocabEquivalenceTests` (9): identical / disagreement /
    startTokenID skip / size-gate boundaries / sparse holes /
    disagreement-rate computation.
  - `ANEDraftBackendStubTests` (4): scripted replay + reset + zero-accept
    + default cache-bytes nil.
  - `MirrorSpeculativeIteratorTests` (6): emit count, zero-accept path,
    count parity vs `TokenIterator`, vocab-gate rejection, vocab-gate
    pass-through, empty-script AR fallback.

Phase-1A limitations (deferred to phase 1B / phase 2):
- No Core ML backend yet — that lands when `CoreML-LLM` dependency is
  decided + Qwen 3.5 0.8B bundle is integrated. The protocol surface is
  ready for the swap.
- Sequential draft→verify (no compute-unit pipelining). Phase 2 unlocks
  the parallelism that gives Mirror SD its 3× headline speedup.
- No auto-routing in `MLXLMCommon.generate(...)` yet — same as the
  DFlash side; lands in Phase 2 alongside registry-driven dispatch.
- Hybrid GDN/Mamba targets blocked at construction; awaits spec 020
  tape-replay rollback.

All 23 tests pass under `swift test -c release` (DFlash side now at
19 + Mirror SD side 23 = 42 spec-decoding tests across both stacks).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…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>
…ory)

Multi-turn chat and agentic workloads send a prompt whose **prefix is
identical** to the previous turn's prompt. Today every turn re-runs
prefill over that prefix; this spec snapshots the target's KV state at
a stable prefix boundary so the next turn hydrates and prefills only
the suffix. vLLM's APC, llama.cpp's `--prompt-cache`, and dflash-mlx's
`DFlashPrefixCache` are the references.

Phase 1 scope: in-memory LRU cache with token-exact prefix matching,
byte-budget eviction, and a configurable `StablePrefixPolicy`. Phase 2
will wire `LastAssistantOpenerPolicy` (chat-aware boundary detection);
phase 3 will add `MambaCache` snapshot via spec 020 tape-replay; phase
4 will add disk persistence.

This PR is decoder-agnostic — the prefix cache helps `TokenIterator`
baseline, the n-gram path, and the future DFlash / Mirror SD paths
equally.

New files:
- `Libraries/MLXLMCommon/StablePrefixPolicy.swift` — `StablePrefixPolicy`
  protocol + `IdentityPolicy` (full-prompt is stable; right for
  completion workloads) + `FixedTrimPolicy(trimSuffix:)` (crude
  phase-1 alternative for chat workloads pending phase 2's chat-aware
  policy).
- `Libraries/MLXLMCommon/PrefixKVCache.swift` — `PrefixKey` (model ID +
  layers + head dim + KV bits, hashable), `LayerCacheState` (per-layer
  opaque arrays + token count), `PrefixSnapshot` (key + tokens +
  layer states + last hidden + timestamp), `PrefixCacheLookupResult`
  (matchedLength + snapshot), `PrefixCacheStats` (hits / misses /
  partial / insertions / evictions / bytes / entries / mean matched
  length / hit rate), and `PrefixKVCache` (in-memory LRU). Uses
  insertion-ordered storage; lookup is longest-token-prefix match
  scoped to a `PrefixKey`. Eviction is byte-budget + entry-count cap.
  Hits bump entries to MRU position. Re-insert of the same
  (key, tokens) replaces in place without double-counting.
- `Tests/MLXLMTests/PrefixKVCacheTests.swift` — 21 tests across three
  suites:
  - `StablePrefixPolicyTests` (4): identity, fixed-trim, floor at 0,
    zero-trim identity-equivalent.
  - `PrefixKeyTests` (2): field-by-field equality, set bucketing.
  - `PrefixKVCacheTests` (15): empty miss, exact match, partial-hit
    accounting, longest-prefix selection, cross-model-ID isolation,
    mismatching-prefix miss, snapshot-longer-than-request guard,
    re-insert dedup, LRU bump on hit, entry-count eviction,
    byte-budget eviction, clear, resetStats, hitRate, mean matched
    length.

All 21 tests pass under \`swift test -c release\`. Pure-Swift logic;
backing arrays use \`MLXArray.zeros\` for byte-size accounting tests but
no MLX evaluation is required.

Phase-1 limitations:
- Concrete `KVCache.serialise()` / `KVCache.hydrate(from:)` methods on
  the standard cache types are deferred to phase 1B (the type-switch
  per concrete cache class is invasive enough to want its own PR).
  This PR's snapshot type is opaque-`[MLXArray]`; the hydrate-time
  code in phase 1B interprets per-layer.
- Not thread-safe — phase 4 will add an actor wrapper if/when
  concurrent serving lands. Current `PrefixKVCache.shared` is for
  single-iterator use (matches the existing iterator concurrency
  model).
- No disk persistence (phase 4).
- No chat-aware stable-prefix policy (phase 2).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Spec 022's two complementary mechanisms for "free token" speculation:
  A. Chat-template grammar state machine (deterministic stretches at
     structural boundaries — channel markers, thinking-end tags, turn
     openers/closers).
  B. Common-bigram fallback drafter (probabilistic, broad — high-
     confidence two-token-history → next-token table).

Phase 1 (this PR): protocol + state types + a NoOp/Trigger grammar +
the bigram data structure + a frequency-map → table builder. Per-family
grammars (Qwen 3.5 / Gemma 4 / GPT-OSS / Llama) and the offline corpus
builder land in phases 2-3.

The piece that's most leveraged short-term is mechanism A's GPT-OSS
harmony-channel handling (the spec calls out 5-15 channel transitions
per turn, each saving 3 forward passes). But it depends on knowing the
target's harmony special-token IDs, which is per-tokenizer and lives
behind the per-family grammar — phase 2 work.

New files:
- `Libraries/MLXLMCommon/ChatTemplateGrammar.swift` —
  `ChatTemplateGrammar` protocol, `ChatTemplatePhase` enum,
  `ChatTemplateConfig` (turn / think / channel / message / newline
  token IDs), `ChatTemplateState` (phase + recent tokens + config),
  `NoOpChatGrammar` (always nil), `TriggerTokenGrammar` (test stub —
  fires fixed continuation on configured trigger).
- `Libraries/MLXLMCommon/BigramTable.swift` — `BigramKey`,
  `BigramEntry`, `BigramTable` (two-level dict for hot-path-friendly
  lookup; insert / overwrite / `confidentNext` / `bigramDraft`
  greedy chain walk), `BigramTable.build(fromFrequencies:threshold:)`
  static builder applying the admission threshold.
- `Tests/MLXLMTests/DeterministicStretchTests.swift` — 16 tests
  across two suites:
  - `ChatTemplateGrammarTests` (3): NoOp behaviour, TriggerToken
    selectivity, phase equality.
  - `BigramTableTests` (13): empty lookup, insert / lookup,
    overwrite, greedy chain walk, chain break, maxK cap, short
    recentTokens, zero maxK, threshold admission, top-1 selection,
    empty input, defensive zero-count handling, BigramKey
    equality + hashable.

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>
@ekryski
ekryski force-pushed the ek/017-prefix-cache-phase1 branch from 69f72b5 to c332968 Compare April 30, 2026 06:24
@ekryski
ekryski force-pushed the ek/022-deterministic-stretch-phase1 branch from 3e73a62 to b3bf981 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/017-prefix-cache-phase1 branch 4 times, most recently from 6bba7fb to 1750f73 Compare May 12, 2026 06:58
Base automatically changed from ek/017-prefix-cache-phase1 to alpha May 12, 2026 08:07
div0-space pushed a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Nov 29, 2026
Support request-owned paged MTP and typed native generation channels
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