Skip to content

perf(mtp): draft from context copies when the reply repeats the context (+30% file edits, +20% The Grill) - #4104

Merged
jundot merged 2 commits into
jundot:mainfrom
jerryfane:perf/mtp-context-copy
Oct 5, 2026
Merged

jundot merged 2 commits into
jundot:mainfrom
jerryfane:perf/mtp-context-copy

Conversation

@jerryfane

@jerryfane jerryfane commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #4101. Part of roadmap #4018.

What

Greedy singleton Lightning MTP cycles can now draft from the context. After each verify, the proposer looks for the longest earlier match of the context tail (prompt + reply, 3-gram index, up to 64 tokens back, newest on ties). When at least 12 tokens match, the next window verifies the 7 tokens that followed that stretch instead of the MTP chain (7 drafts + the pending token = the 8-row row-exact window). Otherwise the MTP head drafts as before.

  • The target model verifies every draft with the same greedy rule, so output does not change. The MTP head still folds the committed tokens every cycle, so its history stays exact for the next MTP cycle.
  • Index: the prompt is sorted once with numpy (about 3 ms per 44K tokens), reply tokens go into a dict; about 2 us per cycle after that. The cycle that builds the index is kept out of the depth controller's timing.
  • Copy cycles are counted apart (copy=accepted/drafted in N in the MTP[...] line) and never update the controller's per-depth acceptance or cost.
  • Four zero-accept copies in a row pause copies for 8 cycles.
  • OMLX_MTP_CONTEXT_COPY=0 disables it. Stochastic sampling, batched MTP and block drafters are unchanged.

Matching rule after TensorFold's SuffixLookupProposer (MIT). Differences: 12-token matches instead of 8 (replaying our chat and long-context replies, copies after 8-11-token matches had 1.3-2.0 of 7 tokens accepted on average, fewer than the MTP chain they replace), and only the 32 newest occurrences are compared.

Results

This branch (upstream main d6b2b92 + this commit) on M5 Ultra, GBP-DE/Qwen3.8-Flash-Next-oQ5e-mtp, MTP on, greedy, prompt cache off, same server build with OMLX_MTP_CONTEXT_COPY 1 vs 0:

Workload copies off copies on Change
File edits (four 6,000-char source slices returned with a small change), tok/s 190.0 247.9 +30.5%
The Grill decode (50 near-identical functions), tok/s 193.3 231.6 +19.8%
Four coding chat prompts, tok/s 178.3 177.9 flat

On our integration build (main + #4052 + #4055 + #4062), two alternating rounds with an earlier revision of this commit: file edits 210 -> 275 tok/s, The Grill 216 -> 255, chat -0.4%, ~48K-token context -1.1%, ~96K -1.4%. That revision timed the index build as part of the first cycle, which skewed the depth controller toward shallower drafts on long prompts; with the build kept out of the timing (this commit, plus the 16-row follow-up) the same comparison gave +1.2% at ~48K and +3.1% at ~96K.

Exactness

  • MTP on == MTP off byte for byte on this branch for the chat and file-edit prompts, and on the integration build also for ~48K and ~96K-token contexts.
  • Copies on == copies off byte for byte on every workload.

Tests

  • New: test_context_copy_drafts_keep_greedy_output (qwen and qwen4 test models): the proposer is replaced by the true continuation with one token flipped at a position that moves every cycle, so 8-row windows are verified with 0, 1, 3, 6 and 7 accepted drafts; the output equals MTP-off decode.
  • Suites: test_mlx_lm_mtp_patch, test_mtp_depth_controller, test_qwen35_moe_verify_window, test_qwen35_gdn_prework, test_row_exact_qmv pass (642).

Tested on M5 Ultra only; there is no M3 or other Mac here.

@jundot

jundot commented Sep 30, 2026

Copy link
Copy Markdown
Owner

The greedy numbers reproduce on an M3 Ultra: file edits 130.4 -> 186.6 tok/s with byte-identical output, and chat is flat.

My hesitation is about who actually gets it. Copies only run at temperature 0, and I don't think many people run these models that way. Most setups sit somewhere around 0.6 to 1.0, the server default is 1.0, and the recommended settings here are 1.0 / top_p 0.95 / top_k 20. At those settings the same file-edit run was 140.6 vs 141.0 tok/s with zero copy cycles. So in practice the gain would mostly show up in greedy benchmarks, and carrying another drafting path in the MTP cycle for that feels like more code to maintain than it gives back to users. If a version shows a clear gain in the 0.6 to 1.0 range, I'd look at it again.

@sethforprivacy

Copy link
Copy Markdown

Posted by Claude (Anthropic's AI assistant) on behalf of @sethforprivacy, as part of our local-inference tuning work on a Mac Studio M5 Ultra.

On the 0.6–1.0 question, one data point from a different model: copies can run at T>0 without changing the output distribution. We run the same idea on GLM-5.3-Flash and it gains more at T=0.6 than at T=0.

How we keep it exact when sampling. Each copied draft goes in as a one-hot draft distribution: logprob 0 on the copied token, −inf elsewhere. It goes through the MTP cycle's existing Leviathan/Chen verifier as draft_accept_lps, with draft_lps left empty (the block-drafter contract). Acceptance is then p(x) under the target's processed distribution, and the residual on rejection is p without x. That is the standard speculative-sampling rule for a deterministic proposer, so the sampled output distribution is unchanged. If the copied token falls outside top-k / top-p it has p = 0 and is simply rejected. The code is ~150 lines here: p2_lookup.py in our recipe patch. It uses an 8-gram index over prompt + reply and up to 7 drafts (the GLM indexer's 8-row rollback cap). A tokens-per-second EMA gate compares lookup cycles with MTP cycles. The idea is ported from mlx-serve #523/#533.

Numbers (M5 Ultra 80c / 256 GB, macOS 27.0, GLM-5.3-Flash oQ4e with a grafted MTP head, MTP fixed depth 2 on both sides, single stream, decode tok/s; measured 2026-09-26 on our 0.7.0rc1-based stack):

task lookup gain T=0 lookup gain T=0.6
return a 140-line file with one rename 1.64× 2.18× (56.5 → 123.0)
reproduce a JSON config with one field changed 1.54× 1.63×
add docstrings, return the full code 1.54× 1.70×
write a unified diff 0.98× 1.17×
prose (control) 1.00× 0.98×
new code (control) 0.99× 0.94× (single run)

The T=0.6 gain is larger because sampling lowers MTP-chain acceptance, while a verbatim copy is still accepted almost every time (87–99 % of lookup drafts per round). The lane has served this way since then; reasoning and qualify gates pass.

Caveats: this is GLM, not Qwen. On GLM each extra MTP draft row pulls a mostly new expert set, so a near-certain 7-token draft is worth more there. We have not measured T=1.0 / top_p 0.95 / top_k 20. Higher temperature should lower acceptance on copies too, but they are verbatim spans, so they should hold up better than MTP drafts. So this is a hint that a sampled variant of #4104 could clear the bar, not a measurement of #4104 itself.

Greedy singleton chain cycles look up the longest earlier match (at least
12 tokens) of the context tail over prompt + generated tokens and, when one
exists, verify the 7 tokens that followed it instead of the MTP chain. The
target model still verifies every draft, so output is unchanged; the MTP
head still folds the committed tokens, so its history stays exact.

- 3-gram index: the prompt sorted once with numpy (about 3 ms per 44K
  tokens), generated tokens in a dict; about 2 us per cycle after that.
- The index build is kept out of the depth controller's timing.
- Copy cycles are counted apart (copy=accepted/drafted in N) and never
  update the controller's per-depth acceptance or cost.
- Four zero-accept copies in a row pause copies for 8 cycles.
- OMLX_MTP_CONTEXT_COPY=0 disables it.

Matching rule after TensorFold's SuffixLookupProposer (MIT).
A copy is a deterministic proposer. Sampled verify cycles now take it as a
draft distribution with all its mass on the copied token, so the existing
Leviathan/Chen acceptance accepts it with probability p(token) under the
filtered target and resamples the residual (p without that token) on
rejection: the sampled output distribution is unchanged. Greedy cycles keep
exact token equality.
@jerryfane

Copy link
Copy Markdown
Contributor Author

Following up on the 0.6–1.0 question. Copies now run at temperature > 0 without changing the sampled distribution. Thanks @sethforprivacy for the pointer.

Change (new commit perf(mtp): context copies at temperature above zero; branch rebased onto current main):

  • Sampled verify cycles take a copy as a draft distribution with all its mass on the copied token, as a SparseDraftQ with one id per position and log q = 0.
  • The existing Leviathan/Chen acceptance in _stochastic_verify_tokens then accepts the copied token with probability p(token) under the filtered target. On rejection it samples the residual, which is p without that token. A token outside top-k/top-p has p = 0 and is always rejected.
  • Greedy cycles keep exact token equality.
  • No other changes; it is about 25 lines in batch_generator.py.

Test: test_copied_drafts_preserve_filtered_target_marginal draws 4,096 emitted tokens per case through _stochastic_verify_tokens with the one-hot q. It checks that they follow the filtered target within 0.03, at T 0.6, dense and top-k 3, with the copied token likely, unlikely, or outside the support. Giving the copy any other q mass makes it fail.

A/B on an M5 Ultra. Qwen3.8-Flash-Next oQ5e, MTP on, main 87460f4 + this PR. Copies were switched off and on with OMLX_MTP_CONTEXT_COPY in the same build, in the order off, on, off, on. Settings: top_p 0.95 and top_k 20 (your recommended sampling). The edit and chat prompts are The Grill's realistic-decode-v1 cells: whole-file edits of a 5.8 KB module, and two coding questions. Each cell is per-request decode in tok/s, the median over 8 acquisitions × 3 trials. Both runs of each arm are shown:

cell T 0.6 off T 0.6 on T 1.0 off T 1.0 on
edit: logger.debug( → logger.info( 203.5 / 204.3 257.9 / 258.5 203.3 / 203.7 256.3 / 257.9
edit: rename qty → quantity 202.9 / 203.7 217.1 / 217.0 202.8 / 203.9 215.7 / 217.0
chat: LRU cache 187.6 / 192.5 189.5 / 195.2 185.6 / 189.8 187.5 / 192.3
chat: React debounce 171.3 / 172.0 169.7 / 168.7 166.9 / 167.8 164.8 / 165.1
  • File edits are +26% and +6.5% at both temperatures, about the same as greedy. Chat is within ±1.5%.
  • Off arms logged 0 copy cycles; on arms logged 206 and 144.
  • Greedy (same build, copies off vs on): every reply is identical, 144 of 144 lanes (grill-perf outputs).
  • Full test suite: 16,382 passed. The 2 failures and 8 errors (muse_glimmer, gdn_sidecar cross-process bytes, Moondream imports) fail the same way on plain main in my environment.

Measured on an M5 Ultra only; I have no M3 or any other non-M5 Mac. #4105 still carries the earlier copy commit. I'll rebase it onto this once #4052 is settled.

@jerryfane
jerryfane force-pushed the perf/mtp-context-copy branch from ba43c58 to 6d2cf49 Compare October 1, 2026 12:13

@jundot jundot left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The temp > 0 version works well here. At temp 1.0 on M3 Ultra, file edits got 1.5-2x faster on Qwen, Gemma 4, GLM-5.3 and MiMo. Chat speed didn't change, and greedy output stayed the same. LGTM, merging.

@jundot
jundot merged commit c41cd51 into jundot:main Oct 5, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf(mtp): replies that repeat the context still draft every token with the MTP head

3 participants