Repository navigation
Description
Blocked by #900 (sampling kernel plumbing; the residual resample reuses its primitives).
Background
mlxcel's speculative-decoding verify loop accepts a draft token iff it equals the target model's argmax at that position: src/lib/mlxcel-core/src/speculative/mod.rs, verify loop around lines 372-530 (builds verify_tokens = [current, ...draft], one batched forward, greedy comparison; acceptance invariant around lines 734-739; bonus_token on full accept; cache rewind on rejection). Draft sampling is deliberately un-biased to preserve acceptance (draft_sampling, lines ~154/234).
Argmax-comparison acceptance has two problems at temperature > 0:
- It changes the output distribution. The served stream becomes greedy-like at verified positions instead of sampling from the target model's temperature distribution, so speculative on/off changes generation behavior.
- It rejects more than necessary. A draft token that is not the argmax but still has high target probability is always rejected.
The standard fix is modified rejection sampling, from the original speculative-decoding papers (Leviathan et al. 2023; Chen et al. 2023):
- For draft position i with drafted token t: draw
u ~ U(0,1), accept iffu * p_draft(t) <= p_target(t). - On the first rejection, resample from the residual distribution
normalize(relu(p_target - p_draft))and stop the speculative chain there. - If all draft tokens are accepted, sample the bonus token from the target's final-position distribution as usual.
This is provably lossless: the resulting stream is distributed exactly as target-only sampling, while the acceptance rate is optimal for the given draft/target pair. At temperature == 0 it degenerates to the current argmax comparison, so greedy behavior is unchanged.
Task
- Expose draft probabilities: extend the drafter interfaces (classic draft model, MTP drafters under
speculative/mtp/,drafter/dflash,drafter/gemma4_assistant) to return the probability of each proposed token under the draft distribution actually used to propose it. For drafters that propose greedily,p_draftis a one-hot; handle that degenerate case (accept iffu * 1 <= p_target(t)). - Acceptance logic: implement the accept loop and residual resample. The residual
relu(p_target - p_draft)normalization and sampling can run through the primitives from Softmax-free GPU sampling: Gumbel-max categorical sampling kernel #900 (single filtered CDF-scan sample) or, initially, composed MLX ops; keep it per-sequence correct in batched speculative rounds. - Wiring and policy: route
temperature > 0verify through the new acceptance; keeptemperature == 0on the existing argmax comparison. Feed the acceptance-rate statistics into the MTP round-cost policy (src/server/batch/mtp_policy.rs) so measured-cost adaptation keeps working with the new (higher) acceptance profile. Env kill switchMLXCEL_SPECULATIVE_STOCHASTIC_ACCEPT=0. - Docs: update the speculative-decoding docs to state the distribution-preservation guarantee and the RNG dependency.
Performance validation (mandatory)
- Run
speculative_bench(src/bin/speculative_bench.rs) and the documented speculative pairings (seedocs/benchmark_results/speculative-acceptance-m5max-2026-07-11.md,speculative-pairing-gb10-2026-07-10.md) at temperatures {0.0, 0.7, 1.0}, before/after. - Required outcomes: mean accepted draft length at temp 0.7 strictly improves vs argmax acceptance; end-to-end tok/s at temp 0.7 improves or stays within noise; temp 0.0 numbers identical to baseline.
- Record in
docs/benchmark_results/chain-speculative-acceptance-<hw>-<date>.md.
Regression guard (mandatory)
- Distribution preservation test: with a small target/draft pair on fixed prompts, compare the empirical next-token distribution at selected positions between (a) target-only sampling and (b) speculative decoding with stochastic acceptance, over a large sample count; chi-square must not distinguish them (threshold documented in the test). The same test against the old argmax acceptance should demonstrate the bias it removes (recorded, not gating).
temperature == 0: token streams byte-identical to current speculative decoding on pinned prompts (all families with speculative support exercised in CI where feasible).- Cache-rewind correctness: rejected positions rewind exactly as today (existing tests plus one new test asserting KV length after mixed accept/reject rounds).
- Kill switch restores argmax acceptance; full speculative and MTP test suites pass; non-speculative decode untouched.
References
src/lib/mlxcel-core/src/speculative/mod.rssrc/server/batch/{speculative_slice,speculative_burst,mtp_policy}.rssrc/bin/speculative_bench.rs- Leviathan et al., "Fast Inference from Transformers via Speculative Decoding" (2023); Chen et al., "Accelerating Large Language Model Decoding with Speculative Sampling" (2023).
Line numbers are indicative as of current main; search for the named symbols.
Part of epic #909.
Activity
test(speculative): end-to-end distributional guard with measured power
docs(speculative): acceptance-rule reference and per-call acceptance …
inureyes commentedon Aug 2, 2026
PR #992 implements tasks 2 and 4, plus the regression guards, on the classic
SpeculativeGeneratorpath. Two scope notes worth recording here for whoever picks up the rest.The issue's premise applies to a different path than the one it cites.
speculative/mod.rs(the file and line numbers in the Background section) does not compare against the target's argmax. It compares againstsample_token_optimized(&pos_logits, target_sampling, ...), a fresh draw from the target sampler, which is argmax only attemperature == 0, and it emits that draw on both the accept and the reject branch. Every emitted token is therefore already a fresh conditional draw fromp, so that path was distribution-preserving before this change. What it lost was acceptance rate:sum_x p(x) q(x)rather thansum_x min(p(x), q(x)), which for the model pair in the committed test is 0.34 versus 0.71, or 0.52 versus 1.80 mean accepted draft tokens per round at a 4-token block. Problem 2 in the issue is real for this path; problem 1 is not.Problem 1 is real on the MTP and DFlash round loops.
Gemma4MtpTargetAdapter::verify_forwardpicks the target token withargmax_per_position(src/models/gemma4_mtp_target.rs:655) and the DFlash round loop withargmax_logits_to_array(drafter/dflash/round_loop.rs:728), both regardless ofsampler.temperature, and both files already carry comments saying greedy is the only mode they gate parity on. Those paths are not changed in #992 and remain biased attemperature > 0. The same chi-square harness measures that bias at ~1825 against a 25.74 rejection threshold, recorded inchi_square_rejects_known_wrong_acceptance_rules.Task 1 is not done. Wiring stochastic acceptance into MTP/DFlash needs
Drafter::draft_block(returnsVec<i32>) to also report the distribution each proposal was drawn from, andMtpTarget::verify_forwardto surface the target logits, which today are a local inside the Gemma 4 adapter that is dropped at the end of the function (MtpBatchedVerifyForwardOutputhas no logprobs field at all). That is a trait-surface change across every implementor on the perf-critical deferred-greedy path, and there is no Gemma 4 or DFlash checkpoint in the implementation environment to validate it against, so it was deliberately left out rather than shipped unexercised. TheAcceptanceRule::ArgmaxNoProposalDistributionvariant exists so those paths have a correct, logged answer once they are wired, anddocs/speculative-acceptance.mdcarries a per-path table of which rule each code path actually runs.The throughput sweep and
docs/benchmark_results/chain-speculative-acceptance-<hw>-<date>.mdare also outstanding; the PR body carries the exactmlxcel generate --draft-modelA/B commands, and notes thatspeculative_benchis the wrong tool for this change because all of its pairings are MTP or DFlash and would compare the unchanged fallback against itself.fix(speculative): make the acceptance rule and rate observable from t…
fix(speculative): name the rules correctly and make the optimal rule …
5 remaining items
docs(speculative): finish correcting the acceptance-diagnostic claim (#…
perf(core): compute shared prompt prefixes once per decode batch (#1004)
feat(speculative): opt-in acceptance-optimal rejection sampling, and …
fix(sampling): filter on the untempered distribution and scale by tem…
feat(sampling): add top-n-sigma logit filtering with a row-filter hook (
feat(sampling): add locally typical sampling (typical_p)
feat(sampling): add locally typical sampling (typical_p) (#1482)
feat(speculative): opt-in acceptance-optimal rejection sampling, and …
perf(sampling): sorting-free top-p sampling with dual-pivot rejection…
docs(speculative): finish correcting the acceptance-diagnostic claim (l…
perf(core): compute shared prompt prefixes once per decode batch (lab…
fix(sampling): filter on the untempered distribution and scale by tem…
feat(sampling): add top-n-sigma logit filtering with a row-filter hook (
feat(sampling): add locally typical sampling (typical_p) (lablup#1482)