Repository navigation
fix(speculative): correct the draft KV cache rewind arithmetic - #1002
Merged
Merged
Conversation
`SpeculativeGenerator::generate` rewound the draft model's KV cache by `min(rejected + 1, k)` on every rejecting round, two entries more than the round had to give back. The shortfall was never recovered, so the drafter's context fell monotonically behind the emitted sequence and its proposals decayed until speculation stopped paying for itself. At `accepted == 0` the draft cache did not advance at all: `k` forwards followed by a trim of `k`, so the drafter proposed forever from the prompt alone.
Writing `k` for the number of proposals and `a` for the number accepted: the draft loop forwards `current_token, d_0..d_{k-2}` while the verify pass forwards `current_token, d_0..d_{k-1}`, one token more. Both caches must end the round holding the prompt plus every emitted token except the next `current_token`, so the main trim is `k - a == rejected` and the draft trim is `(k - 1) - a == rejected - 1`, one less. This matches upstream mlx-lm `speculative_generate_step::_rewind_cache`, which trims `num_draft - num_accept` and `max(num_draft - num_accept - 1, 0)` respectively.
At `a == k` the arithmetic runs off the other end and cannot be fixed by trimming or by clamping at zero: `d_{k-1}` is sampled from the forward of `d_{k-2}` and is never itself forwarded, so a fully-accepted round emits a token the draft cache has no entry for. A negative trim would have to insert it, which `trim` cannot do. The missing entry is now parked in the new `SpeculativeGenerator::pending_draft_context` and replayed at the head of the next round's first draft forward, which makes that forward two tokens wide instead of one and keeps the round at `num_draft` forwards rather than adding a catch-up pass. This mirrors the `draft_y` concatenation upstream uses for the same case. The debt is recorded at the point the token is pushed to `generated_tokens`, so a round that stops on `max_tokens` records it correctly and an accepted-EOS proposal, which breaks before the push, never records a debt for a token that was never emitted.
The fix is identical for the sampler-match, greedy-argmax and stochastic acceptance rules: the trim runs after the accept loop and does not read the rule.
`draft_cache_falls_behind_the_main_cache_every_round_pre_existing_defect` pinned the broken arithmetic so a fix would surface as a failing test rather than silence. It is replaced by `draft_cache_tracks_the_emitted_sequence_in_every_acceptance_regime`, which asserts `draft offset + tokens owed == main offset` across the all-reject, all-accept and mixed regimes, and by `a_fully_accepted_round_owes_its_last_proposal_and_the_next_round_pays_it`, which pins that the debt is real and that the next round clears it by replaying rather than staying two entries behind. Both were verified to fail against the old arithmetic before being committed.
Measured on `models/meta-llama-3.1-8b-instruct-4bit` with a `llama-3.2-1b-instruct` drafter, `--num-draft-tokens 4 --temp 0.7 --no-chat-template -n 200`, five seeds, `MLXCEL_SPECULATIVE_ACCEPT_DIAG=1`: mean `per_position_acceptance` rises from 0.159 to 0.651 and mean throughput from 20.8 to 41.8 tok/s. `closed_form_sum_min`, which is a property of the model pair and should not move between runs, had a 3.09x spread across seeds before (0.0913 to 0.2823) and 1.06x after (0.7468 to 0.7945).
Temperature-0 output is unchanged, byte for byte, on both prompts at `num_draft` 1 and 4, and both the old and new speculative streams match a drafterless greedy reference exactly. That is the expected result rather than a surprise: at temperature 0 the emitted token is the target's argmax whether the proposal is accepted or rejected, so the drafter cannot move the stream.
Refs #994
…um_prod The diagnostic line still asserted that the measured per-position acceptance must sit at sum_min. Under the default sampler-match rule it sits at sum_prod; sum_min is the ceiling only the opt-in acceptance-optimal rule reaches. This PR already corrected the same claim in docs/speculative-acceptance.md, so the runtime string was left contradicting the documentation, and the runtime string is the one a user actually reads. Measured on Llama 3.1 8B with a Llama 3.2 1B drafter at temp 0.7: per_position 0.7374 against sum_prod 0.7182 and sum_min 0.8102.
inureyes
added a commit
that referenced
this pull request
Aug 2, 2026
…1003) PR #1002 corrected the "measured per-position acceptance must sit at sum_min" claim in the prose of docs/speculative-acceptance.md and, in a follow-up commit, in the runtime diagnostic string itself. Two places still carried the old claim: the example diagnostic line quoted in that same document, and the MLXCEL_SPECULATIVE_ACCEPT_DIAG row in docs/environment-variables.md. Both now say what the code says, that the measured value sits at sum_prod under the default sampler-match rule and at sum_min under the opt-in acceptance-optimal rule, and the bullet points to the rule= token on the line above as the way to tell which one ran. The quoted example is also re-measured. Its old numbers (sum_min 0.2213, sum_prod 0.2087) came from the pre-#1002 draft cache defect, where the drafter conditioned on a truncated prefix and both closed forms collapsed toward each other, which is exactly why the wrong claim was not visible: the two quantities were indistinguishable. Post-fix they separate, so the example now shows a representative separated pair. Verified by diffing the live diagnostic line against the documented example with the numeric fields masked; they are identical. Also corrects "the probability the pre-#902 rule accepts" to "the probability the sampler-match rule accepts". Sampler-match is the current default, not a superseded rule, so dating it by the issue that added its alternative misreads which one a default run measures.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…p#1002) `SpeculativeGenerator::generate` rewound the draft model's KV cache by `min(rejected + 1, k)` on every rejecting round, two entries more than the round had to give back. The shortfall was never recovered, so the drafter's context fell monotonically behind the emitted sequence and its proposals decayed until speculation stopped paying for itself. At `accepted == 0` the draft cache did not advance at all: `k` forwards followed by a trim of `k`, so the drafter proposed forever from the prompt alone. Writing `k` for the number of proposals and `a` for the number accepted: the draft loop forwards `current_token, d_0..d_{k-2}` while the verify pass forwards `current_token, d_0..d_{k-1}`, one token more. Both caches must end the round holding the prompt plus every emitted token except the next `current_token`, so the main trim is `k - a == rejected` and the draft trim is `(k - 1) - a == rejected - 1`, one less. This matches upstream mlx-lm `speculative_generate_step::_rewind_cache`, which trims `num_draft - num_accept` and `max(num_draft - num_accept - 1, 0)` respectively. At `a == k` the arithmetic runs off the other end and cannot be fixed by trimming or by clamping at zero: `d_{k-1}` is sampled from the forward of `d_{k-2}` and is never itself forwarded, so a fully-accepted round emits a token the draft cache has no entry for. A negative trim would have to insert it, which `trim` cannot do. The missing entry is now parked in the new `SpeculativeGenerator::pending_draft_context` and replayed at the head of the next round's first draft forward, which makes that forward two tokens wide instead of one and keeps the round at `num_draft` forwards rather than adding a catch-up pass. This mirrors the `draft_y` concatenation upstream uses for the same case. The debt is recorded at the point the token is pushed to `generated_tokens`, so a round that stops on `max_tokens` records it correctly and an accepted-EOS proposal, which breaks before the push, never records a debt for a token that was never emitted. The fix is identical for the sampler-match, greedy-argmax and stochastic acceptance rules: the trim runs after the accept loop and does not read the rule. `draft_cache_falls_behind_the_main_cache_every_round_pre_existing_defect` pinned the broken arithmetic so a fix would surface as a failing test rather than silence. It is replaced by `draft_cache_tracks_the_emitted_sequence_in_every_acceptance_regime`, which asserts `draft offset + tokens owed == main offset` across the all-reject, all-accept and mixed regimes, and by `a_fully_accepted_round_owes_its_last_proposal_and_the_next_round_pays_it`, which pins that the debt is real and that the next round clears it by replaying rather than staying two entries behind. Both were verified to fail against the old arithmetic before being committed. Measured on `models/meta-llama-3.1-8b-instruct-4bit` with a `llama-3.2-1b-instruct` drafter, `--num-draft-tokens 4 --temp 0.7 --no-chat-template -n 200`, five seeds, `MLXCEL_SPECULATIVE_ACCEPT_DIAG=1`: mean `per_position_acceptance` rises from 0.159 to 0.651 and mean throughput from 20.8 to 41.8 tok/s. `closed_form_sum_min`, which is a property of the model pair and should not move between runs, had a 3.09x spread across seeds before (0.0913 to 0.2823) and 1.06x after (0.7468 to 0.7945). Temperature-0 output is unchanged, byte for byte, on both prompts at `num_draft` 1 and 4, and both the old and new speculative streams match a drafterless greedy reference exactly. That is the expected result rather than a surprise: at temperature 0 the emitted token is the target's argmax whether the proposal is accepted or rejected, so the drafter cannot move the stream. Refs lablup#994 The diagnostic line still asserted that the measured per-position acceptance must sit at sum_min. Under the default sampler-match rule it sits at sum_prod; sum_min is the ceiling only the opt-in acceptance-optimal rule reaches. This PR already corrected the same claim in docs/speculative-acceptance.md, so the runtime string was left contradicting the documentation, and the runtime string is the one a user actually reads. Measured on Llama 3.1 8B with a Llama 3.2 1B drafter at temp 0.7: per_position 0.7374 against sum_prod 0.7182 and sum_min 0.8102.
be-free-snowboy
pushed a commit
to freestylejs/snowbrain-mlxcel
that referenced
this pull request
Oct 27, 2026
…ablup#1003) PR lablup#1002 corrected the "measured per-position acceptance must sit at sum_min" claim in the prose of docs/speculative-acceptance.md and, in a follow-up commit, in the runtime diagnostic string itself. Two places still carried the old claim: the example diagnostic line quoted in that same document, and the MLXCEL_SPECULATIVE_ACCEPT_DIAG row in docs/environment-variables.md. Both now say what the code says, that the measured value sits at sum_prod under the default sampler-match rule and at sum_min under the opt-in acceptance-optimal rule, and the bullet points to the rule= token on the line above as the way to tell which one ran. The quoted example is also re-measured. Its old numbers (sum_min 0.2213, sum_prod 0.2087) came from the pre-lablup#1002 draft cache defect, where the drafter conditioned on a truncated prefix and both closed forms collapsed toward each other, which is exactly why the wrong claim was not visible: the two quantities were indistinguishable. Post-fix they separate, so the example now shows a representative separated pair. Verified by diffing the live diagnostic line against the documented example with the numeric fields masked; they are identical. Also corrects "the probability the pre-lablup#902 rule accepts" to "the probability the sampler-match rule accepts". Sampler-match is the current default, not a superseded rule, so dating it by the issue that added its alternative misreads which one a default run measures.
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
The draft model's KV cache was rewound by
min(rejected + 1, k)on every rejecting round, two entries more than the round had to give back, and the shortfall was never recovered. The drafter's context fell monotonically behind the emitted sequence, its proposals decayed, acceptance fell, and the loop reinforced itself. This corrects the trim torejected - 1and resolves the fully-accepted case, which the trim cannot reach at all.The arithmetic
Write
kfordraft_tokens.len()andaforaccepted.The draft loop forwards
current_token, d_0, ..., d_{k-2}: the input to iterationjis the token iterationj - 1produced, so the last proposald_{k-1}is sampled from the forward ofd_{k-2}and is never itself forwarded. The verify pass forwardscurrent_token, d_0, ..., d_{k-1}, one token more.Both caches must end the round holding the prompt plus every emitted token except the next round's
current_token, which the next round forwards itself. So the main trim isk - a == rejected(unchanged, and it was already right) and the draft trim is(k - 1) - a == rejected - 1, exactly one less. This matches upstream mlx-lmspeculative_generate_step, whose_rewind_cachetrimsnum_draft - num_acceptfrom the target cache andmax(num_draft - num_accept - 1, 0)from the draft cache.The all-accepted case, and why clamping at zero is wrong
At
a == kthe formula gives-1, and the issue asks for this to be resolved rather than clamped. Clamping is wrong because the sign is telling the truth: the cache is genuinely missing an entry rather than holding a spare one.d_{k-1}was accepted and emitted, so it is part of the sequence, but the draft loop never forwarded it. A trim of-1would have to insert it, whichKVCache::trimcannot do, and a trim of0leaves the drafter one token behind for the rest of the run, accumulating one entry per fully-accepted round.The entry has to be supplied, and there are two ways to do it: a separate one-token catch-up forward, or fold it into the next forward the draft model was going to make anyway. This PR takes the second.
d_{k-1}is parked in a newSpeculativeGenerator::pending_draft_contextand replayed at the head of the next round's first draft forward, making that forward two tokens wide instead of one. The round still costsnum_draftdraft forwards rather thannum_draft + 1, and the sampler'sslice_last_logitspre-step already reads the final position, so the proposal sampled there is the one conditioned on the full replayed prefix. The draft model sees a multi-token block with no explicit mask, which is the same contract it already meets during chunked prefill and the target already meets during verification. Upstream handles the same case the same way, withdraft_y = concatenate([draft_tokens[-1:], draft_y]).The debt is recorded where the token is pushed to
generated_tokens, not beside the bonus token, so it is also correct on the round that stops onmax_tokens, and so an accepted-EOS proposal (which breaks before the push) never records a debt for a token that was never emitted.All three regimes and all three acceptance rules are covered: the trim runs after the accept loop and never reads the rule, so sampler-match, greedy-argmax and stochastic are affected identically.
What changed
src/lib/mlxcel-core/src/speculative/mod.rsmin(rejected + 1, k)torejected - 1; main trim unchanged.pending_draft_context: Option<i32>, cleared byreset, set when a round emits its last proposal, consumed bytake()at the first draft forward of the next round.## Cache invariantsection stating the invariant both caches must satisfy at a round boundary.src/lib/mlxcel-core/src/speculative/distribution_tests.rsdraft_cache_falls_behind_the_main_cache_every_round_pre_existing_defect(which deliberately asserted the wrong values) replaced bydraft_cache_tracks_the_emitted_sequence_in_every_acceptance_regime, assertingdraft offset + tokens owed == main offsetper layer across the all-reject, all-accept and mixed regimes atnum_draft1 through 5.a_fully_accepted_round_owes_its_last_proposal_and_the_next_round_pays_it, which pins that the debt is a real one-token shortfall and that the next round clears it by replaying rather than staying two entries behind. Without it the+ owedterm could be vacuously zero.docs/speculative-acceptance.md: re-measured entropy table, corrected the claim that the measured rate sits onsum_minunder the default rule (it sits onsum_prod), removed the now-obsolete note about 2x between-trajectory variance, and listed the two new regression guards.Measurements
models/meta-llama-3.1-8b-instruct-4bittarget,models/llama-3.2-1b-instructdrafter,--num-draft-tokens 4 --temp 0.7 --no-chat-template -n 200,MLXCEL_SPECULATIVE_ACCEPT_DIAG=1, default sampler-match rule, five seeds. A raw continuation prompt is used rather than a chat-templated one because the Llama 3.1 chat template emits a tool call and hits EOS after ~65 tokens on some seeds, which mixes trajectory length into the spread being measured.per_position_acceptancebeforeclosed_form_sum_minbeforeMeasured per-position acceptance moves from 0.159 to 0.651, into the 0.6 to 0.8 band the issue cites for a comparable pair, and throughput doubles.
Run-to-run spread of
closed_form_sum_minclosed_form_sum_minissum_x min(p(x), q(x))averaged over tested positions. It is a property of the model pair, so it should barely move between runs; the issue reports 0.221 and 0.396 on two 200-token runs, a 1.8x spread, as evidence of the feedback loop.The spread collapsing is the direct evidence that the feedback loop is gone. Under the defect the drift rate depended on the acceptance rate, so two runs that diverged early ended up in different regimes; with the drafter kept level with the target, every trajectory measures the same underlying quantity.
Secondary confirmation from the same runs:
positions_tested / roundswas about 1.2 before (nearly every round rejecting at position 0, the frozen-drafter signature) and about 2.4 after, and rounds per 200 emitted tokens fell from about 167 to about 80.Temperature-0 equivalence
The issue expects temperature-0 output to change. It does not, and that is worth stating as a finding rather than glossing.
Two prompts,
num_draft1 and 4, 128 tokens, compared against a drafterless greedy reference produced by the same binary with no--draft-model:At temperature 0 the emitted token is the target's argmax whether the proposal is accepted (the argmax equals the proposal, by definition of the accept test) or rejected (the argmax is emitted as the replacement). The drafter therefore cannot move the stream at all; it only changes how many target forwards it takes to produce it. The verify batch shape does change with the proposals, which leaves room for f16 jitter, but none was observed on either prompt at either block size. Speculative decoding remains output-equivalent to plain greedy at temperature 0, before and after.
Test plan
cargo fmt --all -- --checkclean.cargo clippy --release --all-targets --features metal,accelerate -- -D warningsclean. Run in the release profile deliberately:make verify-clippyuses the debug profile, which would trigger a cold MLX C++ build in this environment.cargo test --release --features metal,accelerate --no-fail-fast -- --test-threads=1. One failure,granite4_vision_parity::text_only_forward_produces_finite_logits, which is pre-existing and already tracked by fix: Resolve flaky text_only_forward_produces_finite_logits in granite4_vision and hunyuan_vl parity tests #997. Confirmed unrelated: the test performs a singleLanguageModel::forwardon a VLM and never constructs aSpeculativeGenerator, and pre-fix and post-fix binaries produce byte-identical degenerate output on that checkpoint.cargo test --release --features metal,accelerate -p mlxcel-core speculative::distribution_tests:: -- --test-threads=1: 15 passed, 0 failed.rejected + 1and the debt recording removed, both new tests fail (draft cache holds 1 entries against the target's 24in the all-reject regime, andleft: None, right: Some(5)for the debt), while the other 13 in the file still pass. The new gate has teeth against exactly the defect it describes.num_draft1 and 4.python3 scripts/ci/check_cross_repo_refs.pyclean.Closes #994