Skip to content

Add bounded prompt lookup decoding - #643

Open
aleroot wants to merge 4 commits into
ml-explore:mainfrom
aleroot:alessio/indexed-prompt-lookup
Open

aleroot wants to merge 4 commits into
ml-explore:mainfrom
aleroot:alessio/indexed-prompt-lookup

Conversation

@aleroot

@aleroot aleroot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Proposed changes

Continuing after some explorations on performance after swift-tokenizers I have this week worked on this set of changes which I later discovered are addressing: #425 and at the end supersede #426. Basically it adds opt-in prompt-lookup decoding: a bounded index finds likely continuations in text already seen, and the target model verifies the proposed tokens. Compared with #426, it avoids scanning the full history for each lookup, continues speculative verification across sliding-window cache wraps, integrates with ChatSession.

In a nutshell this new prompt lookup decoding mechanism autocompletes suggesting the next few pieces of a sentence from text already in the conversation. The model checks those suggestions together. When it agrees, it can produce the same text with fewer model calls. This is useful for copying and editing, including coding-agent tasks that reproduce or modify existing code. It offers less benefit when the output is mostly new, such as an original story or a short tool call.

To enable it in a chat session with an already loaded ModelContainer:

let session = ChatSession(
    model,
    generateParameters: GenerateParameters(
        maxTokens: 512,
        temperature: 0,
        promptLookup: .init(maxDraftTokens: 8)
    )
)

let response = try await session.respond(to: "Revise this code and return the full file: …")

Benchmarks: Release build on an Apple M2 with 16 GB RAM, pinned Gemma 3 1B and Qwen3 4B models, 128 greedy output tokens, and three interleaved baseline/lookup pairs after warmup. The second column measures token generation; the third adds model prompt prefill. These are model-only measurements, not end-to-end ChatSession timings.

Model and workload Generation, ordinary → lookup Generation speedup Prefill + generation, ordinary → lookup Overall model speedup Same tokens?
Gemma, short code edit 96.0 → 144.8 tok/s 1.51× 63.2 → 82.9 output tok/s 1.31× Yes
Gemma, short document copy 98.1 → 182.0 tok/s 1.85× 78.0 → 123.3 output tok/s 1.58× Yes
Gemma, long document copy 93.9 → 142.3 tok/s 1.52× 35.8 → 41.4 output tok/s 1.16× Yes
Qwen, short document copy 30.2 → 37.9 tok/s 1.25× 18.0 → 20.7 output tok/s 1.15× Yes
Gemma, short creative story 101.5 → 93.3 tok/s 0.92× 97.1 → 89.6 output tok/s 0.92× Yes
Gemma, long creative story 95.7 → 85.6 tok/s 0.89× 42.6 → 39.6 output tok/s 0.93× No¹
Qwen, short creative story 30.6 → 28.1 tok/s 0.92× 28.0 → 25.8 output tok/s 0.92× No¹

Creative example: The prompt asks for “an original 1000-word story about a botanist discovering a silent floating island,” with dialogue and a surprising ending. The long variant adds unrelated inventory records that the model is explicitly told not to quote. That makes it a useful counterexample: the prompt is substantial, but repeating it would not help answer the request.

Each run produces exactly 128 tokens. The prefill-plus-generation rate excludes ChatSession, text preparation, and detokenization. ¹The creative outputs diverged at near-tied logits, so those rows compare measured latency but not identical token sequences. In the Gemma run, the first difference occurred with no accepted draft tokens, consistent with numerical differences from batched verification. llama.cpp also notes that “the logits are not guaranteed to be bit-for-bit identical for different batch sizes.” Exact token-for-token output is therefore backend-dependent.

Checklist

Put an x in the boxes that apply.

  • I have read the CONTRIBUTING document
  • I have run pre-commit run --all-files to format my code / installed pre-commit prior to committing changes
  • I have added tests that prove my fix is effective or that my feature works
  • I have updated the necessary documentation (if needed)

AI usage

  • I have read this PR description in full and approve it as my own, and it
    accurately describes the code changes.
  • AI usage disclosure: used a combination of LLMs for automating some of the work, I won't disclose the techniques used.

@aleroot
aleroot force-pushed the alessio/indexed-prompt-lookup branch from 792635b to 6d93801 Compare November 21, 2026 04:43
@aleroot aleroot mentioned this pull request Nov 21, 2026
9 of 19 tasks
@aleroot

aleroot commented Nov 21, 2026

Copy link
Copy Markdown
Contributor Author

A possible follow-up, not for this PR: the adaptive policy could also use the verifier's entropy from the last step, for example skipping or shortening drafts when entropy is high, which may reduce the 0.89–0.92× slowdown on creative text. I'll measure it once this: #822 lands before proposing anything.

@aleroot

aleroot commented Nov 26, 2026

Copy link
Copy Markdown
Contributor Author

A possible follow-up, not for this PR: the adaptive policy could also use the verifier's entropy from the last step, for example skipping or shortening drafts when entropy is high, which may reduce the 0.89–0.92× slowdown on creative text. I'll measure it once this: #822 lands before proposing anything.

I’ve left the entropy experiment out of this PR, first benchmark did not pay off. I will eventually open another PR if I can make it work.

div0-space added a commit to LibraxisAI/mlx-swift-lm that referenced this pull request Dec 2, 2026
…20cb09) into unified LibraxisAI core

- Integrates MLXWhisper Swift 6 library, POST /v1/audio/transcriptions (--whisper-model), ml-explore#854 compiled SwiGLU, ml-explore#436 PromptTrie/LRUPromptCache, ml-explore#643 bounded Prompt-Lookup Decoding, and ml-explore#392/ml-explore#400 Gemma 4 audio/video
- Reconciles Package.swift (both MLXGuidedGeneration and MLXWhisper linked into MLXLMServer), ServerConfiguration (--batch-v2/--max-concurrency/--kv-cache-mb/--served-model-name + --whisper-model), and MLXServerRunner (CBv2 + Whisper + Embeddings in one mlx-server process)

Authored-By: gemini <agents@vetcoders.io>
Add a public, idempotent finish() so direct callers that stop early canremove verified but unreturned tokens before reusing the cache. It also releases the last round's sliding-window snapshot.
Stop verification rounds at a dynamic compression threshold, so each position runs against the cache representation ordinary decoding uses.
Every proposed token widens the verify pass, and a rejected one widens
it without emitting anything, so the default draft length sets how much
throughput text that does not repeat the prompt loses.

Measured on an M2 with Qwen3-4B-4bit, 1024 greedy tokens, interleaved
baseline and lookup pairs after a warmup pair. Speedup over plain
decoding:

  workload                d=3    d=4    d=8
  code edit, short        1.21   1.16   1.12
  code edit, long         1.20   1.16   1.07
  document copy, short    1.29   1.22   1.13
  document copy, long     1.15   1.21   1.07
  rename a type, short    0.95   0.96   0.88
  rename a type, long     0.97   0.96   0.92
  prose, short            0.93   0.93   0.84
  prose, long             0.93   0.94   0.91
  geometric mean         1.070  1.061  0.986

3 and 4 sit within run-to-run drift of each other and both beat 8 on all
eight workloads, where 8 makes the feature a net loss on average. Four
also leaves the adaptive policy a ladder of 4, 2, 1, 3 to settle on; a
cap of 3 only ever reaches 3 and 1.

Starting the adaptive limit below the cap was measured and rejected: a
rejection already halves it, so a low start moved total forwards by
under 0.1% and verified positions by under 1%.

The article now states that batched verification need not match plain
decoding token for token. At the old default, greedy output diverged
from plain decoding after 9 to 169 tokens on all eight workloads,
deterministically. The previous wording read like a corner case near
tied logits.
GenerateParameters.logProbabilities asks an iterator to report the
distribution behind each token it returns. Prompt lookup returned
verified drafts without one, so lastLogProbabilities was nil for most
of its tokens.

Record a deferred distribution for every pending token. The batched
greedy round passes its verify logits to
DeferredTokenLogProbabilities.recording(_:sampledFrom:topK:), as the
other speculative iterators do. The sequential round samples through
TokenIterator.convertToToken(logits:), so processors and log
probabilities follow the ordinary decode path.

Add tests that compare the reported values with ordinary decoding,
greedy and sampled, with and without a penalty.
@aleroot
aleroot force-pushed the alessio/indexed-prompt-lookup branch from 2a520c0 to 16334b9 Compare December 3, 2026 21:46
@aleroot

aleroot commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

I rebased onto main and adapted the iterator to the prompt checkpoints from #845: it now takes and records several checkpoints, as TokenIterator does. Log probabilities keep working with the logProbabilitySource setting from #864.

Prompt lookup is still the only speculation here that needs no extra model, and it pays off most when an agent rewrites code that's already in the conversation. @davidkoski would you have time for a review?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants