Skip to content

refactor(speculative): remove the classic draft-model path - #2756

Merged
inureyes merged 5 commits into
mainfrom
refactor/issue-2754-remove-classic-speculative
Nov 1, 2026
Merged

inureyes merged 5 commits into
mainfrom
refactor/issue-2754-remove-classic-speculative

Conversation

@inureyes

@inureyes inureyes commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Do not merge this PR without #2768. This PR alone removes the classic draft-model path, so drafting with an ordinary full model stops working. The capability returns through FullModelDrafter in #2768, which is stacked on this branch. The owner decided the two ship together.

Removes SpeculativeGenerator, the last decode loop outside the batch-native engine, as promised for v0.8.0 (Refs #2176).

Behavior

  • mlxcel generate --draft-model with an explicit or auto-detected MTP drafter, or a DFlash drafter directory on a target with an offline arm (Laguna), routes as before.
  • Anything else fails before any drafter load, naming --draft-kind mtp, --draft-kind dflash and --prompt-lookup. A DFlash directory on a target with no offline arm also gets a pointer to mlxcel-server.
  • Breaking: --num-draft-tokens on generate, MLXCEL_SPECULATIVE_STOCHASTIC_ACCEPT and MLXCEL_SPECULATIVE_ACCEPT_DIAG are gone. ServerConfig::num_draft_tokens stays (--draft-max, /props, metrics, settings).
  • The server's Classic dispatch is gone. A kind with no server round loop now fails at startup instead of decoding plainly; no drafter model_type maps to one today.

Removed code

speculative/stochastic_accept.rs had no caller outside the loop, so modified rejection sampling goes with it. sample_token_with_distribution is deleted. effective_token_distribution is now #[cfg(test)], because the sampler tests that pin filter masking still read it. docs/speculative-acceptance.md no longer documents the removed rule's knobs, and docs/benchmark_results/ is untouched.

Tests

Moved to the engine's token-only verify loop (engine/speculative_distribution_tests.rs, engine/verify_round_rollback_tests.rs), with a scripted drafter: speculative_stream_matches_the_target_distribution (and _at_block_size_one, absorbing the_default_sampler_match_rule_also_matches_the_target_distribution), chi_square_rejects_known_wrong_acceptance_rules (arms rewritten: the residual-resample arm exercised the removed rule), filtered_target_support_is_never_violated, temperature_zero_stream_is_byte_identical_to_greedy_target_only, the_mixed_draft_agrees_on_exactly_one_token_in_six, acceptance_accounting_is_exact_in_both_deterministic_regimes, kv_cache_length_is_exact_in_both_acceptance_regimes, kv_cache_stays_consistent_across_mixed_accept_reject_rounds.

Moved elsewhere: the test_kv_cache_trim_* tests and kv_cache_trim_then_append_matches_untrimmed_reference to cache/kv_trim_tests.rs; stochastic_accept_uses_untempered_support to sampling.rs as effective_token_distribution_uses_untempered_support.

Deleted, pinning only the removed loop or rule: all of stochastic_accept_tests.rs; stochastic_runs_report_the_stochastic_rule_and_a_longer_accepted_run, closed_form_acceptance_matches_the_hand_computed_values, cli_summary_line_carries_the_rule_id_and_mean_accepted_len, draft_cache_tracks_the_emitted_sequence_in_every_acceptance_regime, a_fully_accepted_round_owes_its_last_proposal_and_the_next_round_pays_it; from speculative/mod.rs test_trim_caches_helper, the speculative_generator_* bias tests, prefill_step_size_matches_upstream_default, generate_refuses_* and refused_call_clears_tokens_from_a_previous_success (the surviving refusal is pinned by verify_round_tests::the_predicate_refuses_a_model_a_trim_cannot_roll_back), speculative_generate_max_tokens_one_emits_first_non_eos_token, the mod.rs duplicates of can_trim_prompt_cache_* and kv_cache_is_trimmable_always_true; the two b8_speculative_generator_* tests; dispatch_classic_fallback_is_not_burstable; the reject_dflash_drafter_offline tests, replaced by the offline_route_* matrix in generate_tests.rs.

Validation

Run on M1 Ultra with a rebuilt release binary. Refused before any drafter load: qwen3-4b-4bit with qwen3-0.6b-4bit as drafter (auto and explicit --draft-kind dflash), and qwen3.5-4b-4bit with qwen3.5-4b-dflash. gemma-4-12b-it-4bit with its 4-bit assistant under --draft-kind mtp at --temp 0: 29 of 90 accepted, and the first 250 characters match plain decode. The same pair auto-detected as MTP. qwen3-4b-4bit --prompt-lookup: 5 of 27 accepted.

Narrow targets pass: core speculative, engine::speculative_distribution_tests, verify_round, kv_trim_tests, root commands::, speculative_dispatch, lang_analyzer, mtp_policy, tests/speculative_dispatch.rs, clippy on lib and tests. A mutated verify_round (off-by-one commit plus an accept-everything test) fails 4 of the 9 ported tests, including both rollback tests. The full workspace gate was not run locally.

Not validated: a positive offline DFlash run. The only offline arm is Laguna and no Laguna DFlash drafter exists locally, so that route is pinned only by the fixture-based offline_route_takes_an_auto_detected_dflash_drafter_on_a_target_with_an_arm.

Closes #2754

@inureyes inureyes added status:review Under review type:refactor Code restructuring without changing functionality priority:high High priority area:core mlxcel-core: MLX FFI, primitives, KV cache, layers labels Oct 30, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Remove the classic draft-model loop for v0.8.0 without losing anything MTP, DFlash, prompt lookup or the server use.

Findings Addressed

  • The ported chi-square stream tests cannot see the accept/reject decision, because the target is context-free and the round emits its draw either way. Added markov_stream_keeps_the_target_conditional (dof 30). Ignoring a rejection fails it at chi-square 50887; reading position 0 everywhere fails it at 1529, and fails nothing else. (MEDIUM)
  • README.md still said the classic path is deprecated and will be removed in v0.8.0. (MEDIUM)
  • Unused parameter on should_route_offline_mtp; stale comments in speculative_burst.rs, generate.rs, generate_tests.rs. (LOW)
  • CHANGELOG.md did not list the removed public sample_token_with_distribution and effective_token_distribution. (LOW)

Remaining Items

  • Positive offline DFlash run, no Laguna drafter available locally. (LOW), as the PR states.

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (narrow targets: engine distribution tests, commands::generate, clippy on lib and tests; workspace gate not run)

The server InvalidKind arm is unreachable from shipped configurations: the model_type map holds only MTP and DFlash kinds, the default is DFlash, explicit internal-mtp and prompt-lookup return earlier, and model_provider.rs propagates the error at startup. No --num-draft-tokens or removed env var remains in the Makefile, scripts or docs outside historical records.

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review of the behavior changes. No CRITICAL or HIGH findings. Fixes are in 19590fe.

Fixed:

  • MEDIUM: a --draft-model with a missing, unreadable, malformed or non-object config.json was refused as "an ordinary full model", because the kind peek and the DFlash probe both treat those failures as absent. The removed load_model used to report the cause. The refusal now names the config path and the I/O or parse error. Routing is unchanged.
  • LOW: SpeculativeDispatchError::InvalidKind and KVCache::eval_state comments were stale. eval_state's Used by: named DeepSeek V4, whose calls act on its own cache types.

Checked, no finding:

  • Hostile config.json: no panic path. Non-object JSON and wrong field types fail soft, and refusals never echo config values (the new parse error prints serde's position text). The path shown is the operator's own argument, on a local CLI. Reads are unbounded, as in the existing peeks, with no trust boundary crossed.
  • Server InvalidKind: resolved at startup and propagated through ? from model_provider.rs before any worker starts, so it fails closed without a panic. The arm is unreachable today, so no test exercises it.
  • Cleanup: the removed loop's clear_memory_cache calls, trims and thread-local stream install affected only its own caches and thread, and it had no Drop. Nothing surviving depended on them.
  • Performance: the probe adds one small config read at startup. fused_sample_probs_dispatch still has a non-test caller.

Not changed:

Validation: the 7 offline_route tests in the mlxcel bin, narrow clippy and cargo fmt --check pass. No workspace-wide run.

The classic draft-model loop was the last decode loop outside the batch-native engine, and its removal was promised for v0.8.0 (#2176). `mlxcel generate --draft-model` now runs the MTP or DFlash round loop, or fails before any drafter load with an error naming `--draft-kind mtp`, `--draft-kind dflash` and `--prompt-lookup`.

Removes `SpeculativeGenerator`, `stochastic_accept`, `--num-draft-tokens` on `generate`, both acceptance environment variables and the server's `Classic` dispatch. Coverage of surviving acceptance logic moves onto the engine's token-only verify loop, and the `KVCache::trim` tests move to the cache module.

Refs #2754
The ported chi-square stream tests use a context-free target and a round emits the target's draw either way, so they guard the sampler path and cannot see a wrong accept/reject decision. Add markov_stream_keeps_the_target_conditional, a chi-square over (previous, next) on a target whose distribution depends on the previous token. Mutating verify_round to ignore a rejection, or to read position 0 at every position, fails it; the second mutation fails nothing else.

Drop the unused explicit-kind parameter of should_route_offline_mtp, remove stale references to the classic path in README, generate.rs, generate_tests.rs and speculative_burst.rs, and list the removed public sampling functions in the changelog.

Validated with the engine distribution tests, commands::generate and clippy on lib and tests.

Refs #2754
A `--draft-model` whose `config.json` is missing, unreadable or malformed resolves to the default DFlash kind, because the kind peek and the DFlash probe both treat those failures as absent. The refusal then called it an ordinary full model. The classic path's model load used to report the real cause, and this branch removed that load, so nothing did. A typo'd path now gets the path and the I/O or parse error.

Routing is unchanged: the same inputs are refused or routed. The probe's doc comment now states that a false return does not separate the two cases. Also corrects the `InvalidKind` and `KVCache::eval_state` comments.

Validated with the `offline_route` tests in the `mlxcel` bin, including a new matrix of nonexistent, empty, malformed and non-object configs.

Refs #2754
@inureyes
inureyes force-pushed the refactor/issue-2754-remove-classic-speculative branch from 48703ca to 349c407 Compare October 31, 2026 13:15
@inureyes
inureyes merged commit ffb27b8 into main Nov 1, 2026
32 checks passed
@inureyes
inureyes deleted the refactor/issue-2754-remove-classic-speculative branch November 1, 2026 04:07
@inureyes
inureyes restored the refactor/issue-2754-remove-classic-speculative branch November 1, 2026 04:09
@inureyes
inureyes deleted the refactor/issue-2754-remove-classic-speculative branch November 1, 2026 04:09
inureyes added a commit that referenced this pull request Nov 1, 2026
…ine (#2768)

## Summary

Replaces the classic draft-model loop removed by #2754 with a token-only `Drafter` (`speculative::full_model_drafter::FullModelDrafter`). It runs an ordinary smaller checkpoint from its own KV caches and proposes its argmax, and the engine's `Engine::verify_round` (the one prompt lookup uses) decides every position. `mlxcel generate`, `run`, `serve` and `mlxcel-server` drive it, the last three through a new `SpeculativeDispatch::FullModel` arm. `--draft-kind full-model` selects it, and an ordinary model directory is auto-detected by one structural rule on both surfaces. MTP and DFlash keep their kinds. `--num-draft-tokens` stays removed, `--draft-block-size` (default 4) is the one width knob, and `--spec-type draft-simple` maps onto this kind.

This PR must not merge before #2756, and #2756 must not merge without it.

## Behavior

- Draft caches hold a prefix of the context that stops short of the current token; rejected proposals are trimmed. Prefill only records the prompt, and a gated-in row catches the draft up one chunk per tick (rules and cost in the comment below).
- Refused at startup on both surfaces: a target or drafter a trim cannot roll back (#2495), a draft vocabulary larger than the target's or a config with no `vocab_size`, and a DFlash directory passed as a full model.
- `--draft-model` accepts an `owner/name` repo id on all four surfaces, resolved like `-m` without the target's `--revision`. Before, only `-m` was resolved, so a drafter repo id failed as a literal path.
- Not served: `--no-batch`, rows adopted through a disaggregated KV handoff, `--kv-unified`, and per request images, audio, video, structured output, logprobs and extended sampler chains (these decode plainly).

## Known limits

- B > 1 verification runs only up to `--prompt-lookup-max-batch` (default 2, measured for this drafter on M1 Ultra, see below). Wider rows decode plainly with the drafter idle.
- Draft caches sit outside memory admission.
- Temperature 0 does not meet the MTP bar: 32 of 36 drafted runs matched plain decode. The divergence is not from draft-cache misalignment and reproduces on `--prompt-lookup` alone; the Qwen3 `copy` swing at position 197 is unexplained and goes to a follow-up issue. The sampled stream passes the chi-square and Markov guards.
- 8 of 223 local checkpoints declare no `vocab_size` at the two levels read, all multimodal or non-LLM, and are refused as a pair.

## Measurements (M1 Ultra, Metal, idle host, bddf672)

The drafter makes neither measured pair faster at B = 1, so this PR restores the capability, not a speedup. Qwen3-8B 4-bit with a 0.6B drafter: 93.5 tok/s plain, 56.1 drafted. Llama 3.1 8B bf16 with a 1B drafter: 40.3 and 40.3. `--prompt-lookup-max-batch` stays at 2, because a wider gate cost 35 to 68 percent at B = 4 and 8. Identity holds at B = 1 on both pairs and at B = 2 on Llama; Qwen3 B = 2 has one row that stably differs from plain. Full tables and catch-up cost are in the comment below.

## Test plan

- [x] Narrow core and root suites for the drafter, scheduler, dispatch and resolver, clippy on both crates, `cargo fmt --check`
- [x] Real checkpoints for identity and acceptance on `generate` and the server (earlier revision)
- [x] Workspace gate before the rebase onto 7750a13: only nine `commands::serve` fixture failures on what is now 0935662, fixed in what is now bddf672 with the `mlxcel` bin tests rerun (324 passed); the other targets were not rerun because only that test fixture changed
- [x] Real-checkpoint smoke on release binaries built before the rebase (same patches as bddf672 per `git range-diff`, older main), `qwen3-8b-4bit` with the 0.6B drafter: `generate` with the kind explicit and auto-detected, `mlxcel-server` by path, `serve` by repo id (`--offline`, from the cache), solo, B=2, and a 6405-token prompt beside a short one, where the long row never drafted because its 48-token budget cannot repay catch-up. Real download and client cancel not exercised
- [x] Workspace gate on bddf672: 14874 passed, 0 failed, 490 ignored
- [x] Idle-host re-measurement of throughput, the `--prompt-lookup-max-batch` default and catch-up cost on bddf672

Closes #2757
inureyes added a commit that referenced this pull request Nov 1, 2026
`tests/shell.spec.ts` read the drawer's scrollWidth as soon as it was visible. Mid-slide that reads twice the viewport (640 against 320), so the overflow check failed intermittently with no layout defect behind it (the #2756 CI failure was at the same test): once the transition ends the width equals the viewport. Both measurement sites now wait for the drawer's animations through one helper.

Before: 10 to 32 failures in 40 runs of one test. After: `tests/shell.spec.ts` passes 280 of 280 at --repeat-each=20, and `pnpm run browser` passes 128 of 128, with typecheck and lint clean.
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers priority:high High priority status:review Under review type:refactor Code restructuring without changing functionality

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(speculative): remove the classic draft-model path for v0.8.0

1 participant