Repository navigation
feat(speculative): run an ordinary full model as a drafter on the engine - #2768
Conversation
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
Security pass summaryFixes, all found by reading the code and not reproduced at runtime:
Catch-up rules:
Known limits:
All throughput numbers in the PR are provisional, taken under heavy CPU load, and to be re-measured on an idle host before merge. Pending and not ticked: workspace gate on the merged code, real-checkpoint smoke on the merged code, idle-host re-measurement. |
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
The classic draft-model loop removed with #2754 was the only path that let a small ordinary checkpoint draft for a larger one, and the server never had that pairing. This adds `speculative::full_model_drafter::FullModelDrafter`, a token-only `Drafter` that runs the small model from its own KV caches, proposes its argmax, and lets the same `Engine::verify_round` prompt lookup uses decide every position, so `mlxcel generate`, `mlxcel run`, `mlxcel serve` and `mlxcel-server` all drive it through the existing round loops. The draft caches mirror the target's state: before every ask they hold a prefix of the context that stops short of the current token, a round of k proposals costs k draft forwards, and after the target decides the fed proposals the context confirms are kept and the rest trimmed (`DraftModelState::realign`), which is the classic loop's `rejected - 1` trim written against the context so early finishes and retracted asks take the same path. The draft model is shared and the per-sequence state is not: on the server one loaded checkpoint serves every row and each row owns a `DraftModelState`, so B > 1 needs no batched drafter and each row rolls back on its own caches. The scheduler's prompt-lookup tick is generalized to a `TokenOnlyRow` that carries either drafter kind, gated by the same `--prompt-lookup-max-batch`. Routing: `DrafterKind::FullModel` (`--draft-kind full-model`), auto-detected on both surfaces by one structural rule (`auto_detected_full_model_dir`: the resolver's DFlash default, no DFlash-family marker, a readable config) so MTP and DFlash drafters keep their kinds and a DFlash directory is refused as a full model. The server loads the drafter next to the target at startup and reports an unreadable config there. Both surfaces refuse, with the rule `Engine::verify_rounds_unsupported` already applies, a target or drafter whose state a trim cannot roll back, and a draft vocabulary larger than the target's. b10621's `--spec-type draft-simple` maps onto the kind. `--num-draft-tokens` stays removed; `--draft-block-size` is the one width knob. Validated with the new cache-alignment tests in `full_model_drafter_tests.rs`, the chi-square, Markov and temperature-0 guards in `engine/speculative_full_model_tests.rs` over the stub models, the dispatch and route tests on both surfaces, and a real `qwen3-8b-4bit` target drafted by `qwen3-0.6b-4bit` on M1 Ultra, measured on both surfaces (numbers in the pull request). Closes #2757
…the block The first cut of the full-model drafter chained a round's k draft forwards as one lazy graph, each argmax fed back as a device array, so the round read the host once. Measured on M1 Ultra with the same prompts and widths it was within noise of one read per proposal on `qwen3-8b-4bit` drafted by `qwen3-0.6b-4bit` and about 15 percent slower on `llama-3.1-8b-instruct-bf16` drafted by `llama-3.2-1b-instruct-4bit` (code prompt, width 6: 43.1 against 50.5 tok/s; prose: 28.6 against 32.3), so the per-proposal read stays, and with it the early stop at a draft-model EOS that the chain could not take. Refs #2757
…work A server given a target or drafter a trim cannot roll back loaded the drafter and decoded plainly with a per-request debug line, and `/health` turned ready before the drafter load finished, so a failed load read as healthy. The worker now refuses the pair at startup and marks itself loaded only after the drafter is up. Every admitted row prefilled the prompt through the draft model and kept the caches, even above the verify gate or under `--kv-unified`, where they are never used, and a row re-entering after a gated stretch fed its whole tail in one unchunked forward. The prefill now only records the prompt, and the first ask feeds any uncached tail in prefill-sized chunks. This moves the prompt forward from prefill completion to the first decode tick. A context id past a smaller draft table is fed as id 0. Adds scheduler tests with two full-model rows, a gated row catching up, and a cancelled row's slot reuse; the two-row test fails with the rollback trim removed. Docs now state the default B = 2 limit and that temperature 0 is not byte-identical to plain decode: prompt lookup, with no draft model, emits the same divergent streams. Validated on real Qwen3 and VLM targets for refusal, resume and byte-identity. No throughput was measured. Refs #2757
Findings from the security pass on the full-model drafter, all read from the code and none reproduced at runtime. - Draft catch-up evaluated cache state through `ffi::eval` on the scheduler thread, which has no `Result` to carry an MLX throw (#822). `KVCache::try_eval_state` returns the failure as `DraftFailed`, and that row decodes plainly. - `--context-shift` keeps the proposal budget open and shifts only the target's caches, so draft KV grew past `--max-kv-size`. A full-model row now stops being asked at that bound. Reverting this makes the new scheduler test fail on 12 held positions against a limit of 11. - `full_model_vocab_problem` passed when either config lacked `vocab_size`, which skipped both the larger-draft refusal and the id-0 clamp. Such a pair is now refused. 8 of 223 local checkpoints declare no `vocab_size` at the two levels read, all multimodal or non-LLM, and they cannot pair until the lookup learns their layout. - `draft_block` on an empty context wrapped `held`; it now returns `DraftFailed`. Narrow test filters, clippy on both crates and fmt pass. Workspace gate not run on this commit. Refs #2757
FullModelDrafter fed a row's whole uncached context in one call on the scheduler thread, so a first ask, or the first ask after a gated stretch, ran every chunk (one forward of the whole tail under MLXCEL_PREFILL_CHUNK=0) while all other rows waited. The draft has no prompt cache, so this recurred per request, a client with a small max_tokens paid it for one proposal, and a cancelled row finished its catch-up. The scheduler now feeds at most one catch-up chunk per tick, to the first row that owes more than a steady tail of two tokens. That row proposes nothing and decodes plainly until caught up; other owing rows wait their turn. The chunk is the server prefill chunk for the tick's width; 0 takes the adaptive default on this path. A row catches up only if its remaining budget covers ticks * (block + 2), and a cancelled row feeds nothing further. FullModelDrafter::catch_up stops short of the current token, so the cache prefix invariant holds at each step. The Drafter contract, draft_block and the offline path are unchanged. Validated with counted draft forwards per tick in the narrow core and scheduler suites, and a negative check with the catch-up branch removed. Real-checkpoint smoke not run. Refs #2757
Only the target model went through the model-source resolver. `--draft-model owner/name` on `generate`, `run`, `serve` and `mlxcel-server` was handed to the drafter loader as a literal path and failed, which matters now that an ordinary small checkpoint is the common drafter and is normally named by repo id. A new `resolve_draft_model_source` wraps the existing resolver and drops `--revision`, which pins the target and would otherwise fail on a local drafter path or select a revision the drafter repository does not have. The four surfaces resolve the draft value right after the target, with the same models dir, token and offline settings. The CHANGELOG entry now also states the catch-up, `--max-kv-size`, undeclared vocabulary and draft-failure behavior of the earlier fixes. Validation: `cargo test --profile test-fast -p mlxcel --lib draft_model_source` passes; clippy with -D warnings on the mlxcel crate and cargo fmt --check pass. No real-checkpoint download was run. Refs #2757
`--draft-model` now resolves like `-m`, so the fixture's nonexistent `models/draft` was fetched as a repo id and nine `commands::serve` tests failed on an HTTP 404 in the workspace gate. The fixture now names an existing path, which the resolver returns verbatim. The gate's other targets passed on fe3099c, and the `mlxcel` bin tests pass with this change (324 passed). Refs #2757
48703ca to
349c407
Compare
fd927e0 to
bddf672
Compare
|
Idle-host re-measurement on bddf672 (base 7750a13). M1 Ultra 128 GB ( The drafter did not make either pair faster at B = 1. Aggregate tok/s, median:
Acceptance on these rows was 0.58 to 0.70 for Qwen3 and 0.58 to 0.80 for Llama.
Catch-up cost. Time to first token is unchanged at B = 1. Total wall time on a short prompt (13 to 14 tokens): 8 tokens goes from 0.16 s to 0.25 s on Qwen3 and 0.27 s to 0.44 s on Llama; 64 tokens goes from 0.74 s to 1.77 s and 1.64 s to 2.08 s. On a long prompt (about 4000 tokens) with 256 tokens, Qwen3 goes from 10.99 s to 15.68 s at acceptance 0.29 and Llama stays at 11.8 s at acceptance 0.93. With two long requests the slower row's first token moves from 11.26 s to 16.46 s on Qwen3 and from 5.02 s to 11.83 s on Llama. In that case one row of each request pair reused the prompt cache in every arm. Output identity corrects an earlier claim. The summary said server runs at B = 1 and 2 were byte-identical to plain. That holds at B = 1 on both pairs and at B = 2 on Llama. On Qwen3 at B = 2 row 0 matches and row 1 differs from plain, stably in all 18 drafted requests, so it is a deterministic flip and not noise. It belongs with #2778; the text was not saved, so the first differing position is not recorded. Plain itself is not stable at B >= 4 on either pair (up to 4 variants per row on Qwen3), so B >= 4 identity cannot be judged from these runs. |
…emove-classic-speculative
…ature/issue-2757-full-model-drafter
The idle-host re-measurement on M1 Ultra found no throughput gain at B = 1: Qwen3-8B with a 0.6B drafter fell from 93.5 to 56.1 tok/s and Llama 3.1 8B bf16 with a 1B drafter held at 40.3. Say so in the changelog and `docs/CONTINUOUS_BATCHING.md`, replace the provisional-numbers note, and record what a wider `--prompt-lookup-max-batch` costs. Refs #2757
**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
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'sEngine::verify_round(the one prompt lookup uses) decides every position.mlxcel generate,run,serveandmlxcel-serverdrive it, the last three through a newSpeculativeDispatch::FullModelarm.--draft-kind full-modelselects it, and an ordinary model directory is auto-detected by one structural rule on both surfaces. MTP and DFlash keep their kinds.--num-draft-tokensstays removed,--draft-block-size(default 4) is the one width knob, and--spec-type draft-simplemaps onto this kind.This PR must not merge before #2756, and #2756 must not merge without it.
Behavior
vocab_size, and a DFlash directory passed as a full model.--draft-modelaccepts anowner/namerepo id on all four surfaces, resolved like-mwithout the target's--revision. Before, only-mwas resolved, so a drafter repo id failed as a literal path.--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
--prompt-lookup-max-batch(default 2, measured for this drafter on M1 Ultra, see below). Wider rows decode plainly with the drafter idle.--prompt-lookupalone; the Qwen3copyswing at position 197 is unexplained and goes to a follow-up issue. The sampled stream passes the chi-square and Markov guards.vocab_sizeat 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-batchstays 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
cargo fmt --checkgenerateand the server (earlier revision)commands::servefixture failures on what is now 0935662, fixed in what is now bddf672 with themlxcelbin tests rerun (324 passed); the other targets were not rerun because only that test fixture changedgit range-diff, older main),qwen3-8b-4bitwith the 0.6B drafter:generatewith the kind explicit and auto-detected,mlxcel-serverby path,serveby 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--prompt-lookup-max-batchdefault and catch-up cost on bddf672Closes #2757