Skip to content

fix(speculative): correct the draft KV cache rewind arithmetic - #1002

Merged
inureyes merged 2 commits into
mainfrom
fix/issue-994-draft-cache-rewind
Aug 2, 2026
Merged

inureyes merged 2 commits into
mainfrom
fix/issue-994-draft-cache-rewind

Conversation

@inureyes

@inureyes inureyes commented Aug 2, 2026

Copy link
Copy Markdown
Member

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 to rejected - 1 and resolves the fully-accepted case, which the trim cannot reach at all.

The arithmetic

Write k for draft_tokens.len() and a for accepted.

The draft loop forwards current_token, d_0, ..., d_{k-2}: the input to iteration j is the token iteration j - 1 produced, so the last proposal d_{k-1} is sampled from the forward of d_{k-2} and is never itself forwarded. 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 round's current_token, which the next round forwards itself. So the main trim is k - 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-lm speculative_generate_step, whose _rewind_cache trims num_draft - num_accept from the target cache and max(num_draft - num_accept - 1, 0) from the draft cache.

The all-accepted case, and why clamping at zero is wrong

At a == k the 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 -1 would have to insert it, which KVCache::trim cannot do, and a trim of 0 leaves 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 new SpeculativeGenerator::pending_draft_context and replayed at the head of the next round's first draft forward, making that forward two tokens wide instead of one. The round still costs num_draft draft forwards rather than num_draft + 1, and the sampler's slice_last_logits pre-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, with draft_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 on max_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.rs
    • Draft trim corrected from min(rejected + 1, k) to rejected - 1; main trim unchanged.
    • New private field pending_draft_context: Option<i32>, cleared by reset, set when a round emits its last proposal, consumed by take() at the first draft forward of the next round.
    • Module-level ## Cache invariant section stating the invariant both caches must satisfy at a round boundary.
  • src/lib/mlxcel-core/src/speculative/distribution_tests.rs
    • draft_cache_falls_behind_the_main_cache_every_round_pre_existing_defect (which deliberately asserted the wrong values) replaced by draft_cache_tracks_the_emitted_sequence_in_every_acceptance_regime, asserting draft offset + tokens owed == main offset per layer across the all-reject, all-accept and mixed regimes at num_draft 1 through 5.
    • New 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 + owed term could be vacuously zero.
  • docs/speculative-acceptance.md: re-measured entropy table, corrected the claim that the measured rate sits on sum_min under the default rule (it sits on sum_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-4bit target, models/llama-3.2-1b-instruct drafter, --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.

seed per_position_acceptance before after closed_form_sum_min before after tok/s before after
1234 0.0452 0.6854 0.0913 0.7780 18.46 42.99
2345 0.1768 0.6721 0.2109 0.7945 21.29 43.41
3456 0.1878 0.5676 0.2084 0.7468 21.40 36.08
4567 0.1667 0.6505 0.2204 0.7737 20.85 42.54
5678 0.2205 0.6813 0.2823 0.7787 21.99 43.82
mean 0.159 0.651 0.203 0.774 20.80 41.77

Measured 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_min

closed_form_sum_min is sum_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.

  • Before: 0.0913 to 0.2823, a 3.09x spread.
  • After: 0.7468 to 0.7945, a 1.06x spread.

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 / rounds was 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_draft 1 and 4, 128 tokens, compared against a drafterless greedy reference produced by the same binary with no --draft-model:

comparison result
before, speculative vs drafterless greedy identical, all 4 combinations
after, speculative vs drafterless greedy identical, all 4 combinations
before vs after, speculative identical, all 4 combinations

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 -- --check clean.
  • cargo clippy --release --all-targets --features metal,accelerate -- -D warnings clean. Run in the release profile deliberately: make verify-clippy uses 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 single LanguageModel::forward on a VLM and never constructs a SpeculativeGenerator, 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.
  • Negative control: with the trim reverted to rejected + 1 and the debt recording removed, both new tests fail (draft cache holds 1 entries against the target's 24 in the all-reject regime, and left: 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.
  • Real-checkpoint acceptance and throughput measurements above, five seeds each arm.
  • Real-checkpoint temperature-0 equivalence against a drafterless greedy reference, both prompts, num_draft 1 and 4.
  • python3 scripts/ci/check_cross_repo_refs.py clean.

Closes #994

`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
@inureyes inureyes added status:review Under review type:bug Bug fixes, error corrections, or issue resolutions priority:high High priority area:inference Generation, sampling, decoding (incl. speculative, DRY) labels Aug 2, 2026
…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
inureyes merged commit a95e485 into main Aug 2, 2026
4 checks passed
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.
@inureyes inureyes self-assigned this Aug 31, 2026
@inureyes inureyes added status:done Completed and removed status:review Under review labels Sep 6, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:high High priority status:done Completed type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(speculative): draft KV cache rewind trims two entries too many, starving the drafter

1 participant