Repository navigation
feat(speculative): load Speculators and OpenBMB DSpark drafters for Qwen3 and Llama targets - #3499
Conversation
…wen3 and Llama targets The official DSpark drafters for dense targets did not load: RedHatAI/Qwen3-4B-speculator.dspark (for Qwen/Qwen3-4B) and openbmb/MiniCPM5-2B-DSpark (for openbmb/MiniCPM5-2B, a llama checkpoint) carry no dflash_config block, so both directories were routed as ordinary full-model drafters and failed on a missing vocab_size or a missing model.embed_tokens.weight. DSpark was LFM2-only, and neither Qwen3 nor Llama was a DFlash-family target. Config (drafter/dflash/config.rs): DFlashConfig::from_json reads the Speculators layout (backbone under transformer_layer_config, taps in aux_hidden_state_layer_ids, is_causal unset) and the flat OpenBMB layout, and is_dflash_drafter_config recognizes speculators_model_type "dspark" and the Qwen3DSparkModel architecture. New fields: draft_vocab_size (refused outside 1..=vocab_size), layer_types, sliding_window, sliding_window_non_causal, is_causal, sample_from_anchor and dspark_bonus_anchor. num_target_layers is now optional: a config that declares none is not given a depth derived from its taps, and the taps are checked against the bound target instead. Fields upstream implements and this port does not (attention sinks, logit softcapping, a rope scaling scheme, a draft window) are refused by name on the two new layouts. Drafter (attention.rs, layer.rs, model.rs, markov.rs, drafter.rs): a sliding_attention layer keeps the newest sliding_window - 1 context rows and, when causal, masks the proposal block with the windowed causal mask, following upstream DFlashAttention. A checkpoint that ships lm_head.weight keeps its own head. With a reduced draft vocabulary the head and markov_w2 score draft ids, markov_w1 stays indexed by target ids, and each chosen draft id t leaves the Markov chain as the target id t + d2t[t]; d2t is validated against both vocabularies at load (length, every mapped id inside the target vocabulary) and t2d is ignored. A plain DFlash checkpoint is left as it was: it ignores layer_types and cannot declare a reduced draft vocabulary. Targets (models/dense_speculative.rs, qwen3.rs, llama3.rs): Qwen3Model and Llama3Model implement SpeculativeTarget. The capture lives inside their generation forward, so a verify block builds the graph a decode step builds; the prefill forwards the pieces classic decode forwards and computes logits for the last prompt row only; a partial accept is a KV trim; the block-versus-chain exactness probe gates the burst. Both hand out their embedding table and output head for a drafter that ships none. Wiring: DFlashTargetModel for both in server/batch/dflash_target.rs with a new drafter_pairing_error hook (tap depth and vocabulary, naming both numbers), the three dispatch arms in speculative_burst.rs, and an offline arm in commands/generate_dflash.rs. Qwen3 and Llama name no required drafter family, as Qwen 3.5 does not, and the decline text no longer calls every DSpark drafter an LFM2 one. Validated on GB10 (CUDA). The exactness probe declines for both bf16 targets there, so by default the pairings fall back to classic decode, as LFM2 DSpark does where its probe declines. Under MLXCEL_MTP_ALLOW_INEXACT=1 both engage; the text then leaves classic decode's at a near-tie. With each verify row run as its own single-token forward, drafted tokens equal classic tokens on both real pairings. Neither published checkpoint uses a reduced draft vocabulary, so that path is covered by unit tests and tiny on-disk checkpoints only. Closes lablup#3261
# Conflicts: # CHANGELOG.md # docs/supported-models.md
The two real-checkpoint gates looked only in the mlxcel store, the HuggingFace cache and models/<repo basename> (Qwen3-4B, MiniCPM5-2B, ...), which never matches the lowercase names the shared models/ link farm uses, so on the CI and dev hosts they always soft-skipped. They now also try the link-farm names (qwen3-4b-bf16, qwen3-4b-speculator-dspark, minicpm5-2b, minicpm5-2b-dspark), and MLXCEL_REQUIRE_MODELS=1 turns a missing checkpoint into a failure instead of a silent pass, as the other real-model tests do.
The branch predates the v0.9.0-beta.3 release, so after merging main its CHANGELOG entry landed inside the released section. It belongs under [Unreleased] / Added, next to the other entries that have not shipped.
Hardening reviewReviewed against #3261. No code defect found. Detection does not misclassify existing checkpoints: the new markers are only Pushed (
|
Summary
Closes #3261.
The official DSpark drafters for dense targets did not load. On unmodified
main(944dbfc2d), GB10:mlxcel generate -m models/Qwen3-4B --draft-model models/Qwen3-4B-speculator.dspark -p "Explain speculative decoding." -n 128 --temp 0exits 1 withthe draft model's config ... declares no vocab_size at top level or under text_config, so the pair cannot be checked. The Speculators config has nodflash_configblock, so the directory is routed as an ordinary full-model drafter.mlxcel generate -m models/MiniCPM5-2B --draft-model models/MiniCPM5-2B-DSpark -p "Write a Python function that adds two integers." -n 128 --temp 0exits 1 withLoading full-model drafter ... Weight not found: model.embed_tokens.weight, for the same reason.This PR parses both config layouts, gives the DSpark drafter causal sliding-window attention, a draft head the checkpoint may ship itself and a reduced draft vocabulary with
d2t, makes dense Qwen3 and Llama DFlash-family targets, and wires both into the server burst and the offlinemlxcel generatedriver.Read this first. On GB10 the block-versus-chain exactness probe declines for both bf16 targets. With default settings the pairings therefore fall back to classic decode on the server (output identical to a server without a drafter, token for token) and are an error naming the override in
mlxcel generate. That is the fail-closed result #1751 recorded for LFM2 DSpark on an M5 Max and #3384 for Inkling 2. UnderMLXCEL_MTP_ALLOW_INEXACT=1both pairings engage and decode about 1.8x faster, and in both the text leaves classic decode's within 128 tokens, at a position where the top two candidates are one bf16 step apart or tied. So the issue's acceptance line "non-zero acceptance rate and output byte-identical to the run without--draft-model" is not met on this host with the drafter engaged. The cause is measured below (a one-row and an eight-row matmul, and a one-query and an eight-query attention, take different CUDA kernels), and two real-checkpoint tests show the drafter and target logic itself emits classic decode's tokens when the verify rows are computed one at a time. Metal was not available to me.What changed
Numbered as in the issue's "Required changes".
src/lib/mlxcel-core/src/drafter/dflash/config.rs).DFlashConfig::from_jsonreads both layouts:transformer_layer_configis merged under the root (a root key of the same name wins, as upstream's{**transformer_layer_config, **params}),aux_hidden_state_layer_idsbecomestarget_layer_ids,is_causalis left unset, andsample_from_anchor: falsemarks the block as already counting the anchor.draft_vocab_size: Option<usize>(refused outside1..=vocab_sizeat load),layer_types,sliding_window,sliding_window_non_causal,is_causal: Option<bool>,sample_from_anchor,dspark_bonus_anchor.num_target_layersbecomesOption<usize>; on the two new layouts an absent value staysNone, on every existing layout it keeps the default ofSome(32).is_dflash_drafter_configrecognizesspeculators_model_type == "dspark"andarchitectures: ["Qwen3DSparkModel"].verify_width()isblock_size + 1for a DSpark drafter unless the checkpoint says its block includes the anchor. Both published configs give 8.attention.rs,layer.rs,model.rs,markov.rs,drafter.rs).sliding_attentionlayer keeps the newestsliding_window - 1context rows in its cache (KVCache::trim_frontafter the write, sooffsetkeeps counting absolute positions for RoPE) and, when causal, masks the block withcreate_causal_mask_with_window_full(L, prior, window). Causality follows upstreamDFlashAttention: an explicitis_causalwins, and when it is unset a layer is causal exactly when it is sliding andsliding_window_non_causalis false.VanillaMarkovHead::from_weights_with_draft_vocab:markov_w1is[vocab, rank](indexed by target ids),markov_w2is[draft_vocab, rank].DraftToTargetholds the validatedd2toffsets; each chosen draft idtleaves the chain ast + d2t[t], which is also the next step'sprev.t2dis never read.lm_head.weightis kept, at any vocabulary, and measured against the draft vocabulary. A reduced draft vocabulary without its own head or withoutd2tis a load error.draft_block_dspark_arrayhandles both anchor layouts (sample_from_anchor).dspark_config_pairing_error,dspark_target_pairing_error) checks taps against the bound target's depth whether or not the config declares one, and names the tap index and the depth.src/models/dense_speculative.rs:forward_speculative,prefill_planned,rollback, the block-versus-chain probe,dense_target_pairing_error, andSpeculativeTargetplus a small publicDenseSpeculativeTargettrait forQwen3ModelandLlama3Model.Qwen3Model::forward_hiddenandLlama3Model::hidden_statesnow delegate to a capturing variant with an empty capture list, so the generation forward and the verify forward are one body. Both models implementembed_tokens_moduleandlm_head_module.src/server/batch/dflash_target.rs:DFlashTargetModelfor both (every prompt row as the first draft context, classic prefill partition, the probe as the gate, B = 1 only),DFlashVerifyOutputforDenseVerifyOutput, and a new trait hookdrafter_pairing_errorwith a no-objection default.src/server/batch/speculative_burst.rs: the three match arms.src/commands/generate_dflash.rs: the offline arm.required_family_pairing_errorcalls the drafter "a DSpark drafter", not "an LFM2 DSpark drafter". Qwen3 and Llama keeprequired_drafter_family() = None.Also:
src/models/detection.rs(the "not a standalone model" refusal names the two new markers),src/lib/mlxcel-core/src/utils.rs(theUsed by:line ofcreate_causal_mask_with_window_full),docs/supported-models.md,docs/speculative-acceptance.md,README.md,CHANGELOG.md.Where this differs from the issue text
RedHatAI/Qwen3-4B-speculator.dsparkdeclaresdraft_vocab_size 151936withvocab_size 151936,openbmb/MiniCPM5-2B-DSparkdeclares130560with130560, and neither safetensors file holds ad2tort2dtensor (headers read at revisionsbdffaa5fanda63eb96b). Thed2tpath is implemented and tested, but only on synthetic tensors and tiny on-disk checkpoints.layer_typessays so". Thez-lab/Qwen3.5-4B-DFlashconfig on the Hub today also declaressliding_attentionlayers (five of six, window 4096), so applying the rule to every DFlash drafter would change the existing Qwen 3.5 DFlash pairing, which this PR cannot measure (its checkpoints are not among those the issue names). A plain DFlash checkpoint therefore keeps attending its whole context, as before, andplain_dflash_configs_ignore_the_dspark_only_fieldspins that.src/bin/speculative_bench.rsis not changed. It has no DFlash dispatch onmain:--kind dflashprints aDEFERREDrow for every family, Qwen 3.5 included. There is nothing to add two targets to.src/commands/generate_dflash.rs, whichgenerate.rsroutes to; the two targets are added there.validate_target_compatdoes it for a DSpark drafter. Because Qwen3 and Llama admit every DFlash-family drafter (required_drafter_family() = None), and that method is a no-op for a plain DFlash drafter, the same two bounds are also checked by the target throughDFlashTargetModel::drafter_pairing_error, on both run arms and in the offline driver.d2tis applied even when the draft vocabulary equals the target one, unless it is all zeros. Upstream builds nod2tin that case. Applying a table the checkpoint ships is the reading that cannot propose a wrong id; an all-zero table is dropped so the chain does no gather.forward_last_logitsdoes, instead of for every row. The first token is then sampled from the bytes classic decode would produce, and a long prompt is not projected through the vocabulary (a 4096-token prompt on Qwen3-4B would otherwise build a[1, 4096, 151936]tensor).attention_sink_bias: true, a non-nullfinal_logit_softcapping, a non-defaultrope_parametersscheme, a positivedraft_window_size, and the three values upstream itself refuses (hidden_act,markov_head_type,projector_type). Neither published config sets any of them.--draft-block-sizeoverrides it.Every other caller
Places that assumed draft ids are target ids, or that the changed helpers touch:
sample_block_per_position,sample_block_per_position_array,sample_block_per_position_batched(plain DFlash sampling, reads the head's argmax as target ids)DFlashDraftModel::from_weightsrefusesdraft_vocab_size < vocab_sizeon a checkpoint without a Markov headDFlashDrafter::draft_block_batched(B > 1)greedy_only:ensure_sampler_supportedreturnsGreedyOnly, the server declines the request to classic decode, the offline driver refuses it.sampled_verifyis never taken (supports_sampled_verifystaysfalse)run_dflash_on_target,run_dflash_batched_on_target)materialize_argmax_i32_vechas no vocabulary assumption.VanillaMarkovHeadis used only byDFlashDraftModel; the Inkling 2 DSpark drafter has its own head (inkling2_dspark/markov.rs) and is untouchedpeek_dspark_configured_block_size(resolve_draft_block_size)from_json, so both layouts resolve to their verify width of 8is_dflash_drafter_config/is_dflash_drafter_dircallers:models::detection(standalone refusal),auto_detected_full_model_dir, the server's full-model refusal,resolve_offline_draft_routecheckpoint_vocab_size(top-levelvocab_sizeonly)DFlashConfig::num_target_layersreadersdspark_config_pairing_error,dspark_target_pairing_errorupdated. Muse and Laguna have their own config typesDFlashAttention::from_weights,DFlashDecoderLayer::from_weights(newlayer_idxargument)layer.rs,model.rs, one test. Muse, Laguna and Raon use their own attention typesQwen3Model::forward_hidden,Llama3Model::hidden_statesLanguageModel::embed_tokens_module/lm_head_module, newly answered byQwen3ModelandLlama3Model--spec-type draft-dspark(llama.cpp-compatible flag,cli/spec_compat_args.rs)The four review lessons
draft_vocab_size0, 1,vocab_size,vocab_size + 1and a huge value; ad2tthat maps to exactlyvocab_size, to a negative id, withi32::MAXandi32::MINoffsets, and with 0, too few and too many entries; block size 0 and 1 and verify width 2; a tap at the last layer, at the depth, one past it, atusize::MAX, and a target depth of 0; sliding windownull, 0, 1, 2 and a huge value; a block wider than the window and a block of one row; an empty block; a prompt of one token, one shorter than the drafter's window and one longer than it (and longer than a prefill chunk). An empty prompt is refused before any forward by the existing guards inrun_dflash_on_targetandrun_offline_dflash; nothing new reaches a forward with zero rows.window - 1rows over 400 rounds and for a 200,000-row context in one chunk (a_long_run_keeps_the_sliding_cache_bounded). Thed2ttable is validated in one pass, 250,000 entries (a_vocabulary_sized_d2t_validates_in_one_pass). The prefill builds one row of logits whatever the prompt length (the_planned_prefill_covers_every_prompt_row). The per-request gates read lazy array shapes and evaluate nothing.cargo fmt.cargo fmt --all -- --checkon the committed tree, in the list below.Verification
All on GB10 (NVIDIA DGX Spark, CUDA 13,
MLX_ENABLE_TF32=0 MLXCEL_SDPA_DETERMINISTIC=1),--profile test-fast --features cuda, base944dbfc2d. Every model, server and real-checkpoint test process ran under a watchdog (stop below 25 GiB available or above 40 GiB RSS); no trip.Tested tree
3e240c6577d1b93e6da534cbee257f821a2b22bc, the tree of the commit (the same before and after the gate).cargo fmt --all -- --checkcargo clippy --locked --workspace --all-targets --features cuda -- -D warningspython3 scripts/ci/check_used_by.py,bash scripts/ci/check_used_by_test.shand the otherscripts/cicheckscargo test --locked -p mlxcel --profile test-fast --features cuda --lib -- --test-threads=1 <filter>:detection285 passed / 7 ignored,router_catalog_route_tests6 passed,dflash_target7 passed;--test speculative_dispatch22 passed. The newmlxcel-coretests are listed under "Tests".make verify-test-cudawith a private 0700TMPDIR: 17,454 passed, 5 failed, 517 ignored over 199test resultlines. The five failures are the Raon testsmodels::raon1_mini::speculative::tests::{a_steered_verify_block_applies_the_alpha_exactly_as_decode_does, a_verify_block_equals_the_decode_chain_byte_for_byte, rollback_after_a_partial_accept_equals_a_fresh_decode_of_the_accepted_tokens, the_exactness_probe_passes_on_the_tiny_model}andmodels::raon_mhc::tests::compiled_site_equals_the_eager_site_bit_for_bit; the same five fail with the same messages on unmodified944dbfc2don this host.The drafter's "not a standalone model" diagnostic now names the Speculators and OpenBMB layouts, so
tests/fixtures/webui/examples/catalog.dflash-page.json(the WebUI catalog contract for a DFlash drafter directory) is updated to the new text at the catalog's 512-character bound. An earlier gate run on this branch failedrouter_catalog_route_tests::mounted_dflash_catalog_matches_bounded_whole_fixturebecause that fixture had not been updated; the run above is after the update. The fixture is the only file that differs from the tree the real-checkpoint runs below were built from, so those runs apply to this commit.Tests
On unmodified
main:The test files as written for this change do not compile there (64 errors, all missing API:
DraftToTarget,layer_is_causal,layer_sliding_window,draft_vocab,dspark_bonus_anchor,from_weights_with_draft_vocab,Optiondepth, ...).The issue's five core acceptance tests, rewritten against
main's API so they compile, all fail:mainspeculators_layout_parsesnot recognized as a drafteropenbmb_layout_parsesnot recognized as a drafterdraft_vocab_out_of_range_is_rejecteddraft_vocab_size 0 was acceptedmissing_num_target_layers_is_not_derived_from_tapsa depth was invented for a config that declares none(32)reduced_vocab_markov_and_d2t_map_to_target_idsmarkov_w2.weight has 4 rows but the drafter config declares vocab_size 10The
dflash_targetacceptance test cannot be written againstmain:Qwen3ModelandLlama3Modeldo not implementDFlashTargetModelthere.On this commit:
mlxcel-coredrafter::dflash(config, Markov, attention, model, drafter)mlxcel-coredrafter::(every drafter),row_invariantmlxceldense_speculative::tests(tiny Qwen3 and Llama targets, a realDFlashDrafterloaded from a tiny on-disk checkpoint in each layout)mlxceldflash_target(includes the two new server-gate tests)mlxceldetection,lfm2,qwen3,llama3,cli::speculative_args,drafter,generatemlxceldense_speculative::real_checkpoint_testswith the four checkpoints presentNew tests, by acceptance line of the issue:
config_tests.rs:speculators_layout_parses,openbmb_layout_parses,draft_vocab_out_of_range_is_rejected,missing_num_target_layers_is_not_derived_from_taps, plusdspark_block_size_counts_the_anchor_only_when_the_checkpoint_says_so,dspark_layer_causality_follows_the_layer_type_unless_set,dspark_sliding_fields_are_bounded_at_load,unsupported_dspark_fields_are_refused_by_name,plain_dflash_configs_ignore_the_dspark_only_fields,probe_accepts_the_speculators_and_openbmb_markers. The two fixtures are the publishedconfig.jsonfiles at revisionsbdffaa5fanda63eb96b.markov_tests.rs:reduced_vocab_markov_and_d2t_map_to_target_ids(draft vocabulary 4 in target vocabulary 10,d2t = [0, 2, 4, 6], draft id 3 becomes target id 9, a[4, rank]markov_w2loads), plus the feedback of the target id into the next step, the out-of-range refusals, integer dtypes, and a 250,000-entry table.dflash_target_dense_tests.rs:qwen3_and_llama_targets_admit_dspark_and_refuse_a_tap_at_or_above_their_depth(the error names the index and the depth),qwen3_and_llama_targets_run_the_dspark_burst_policy.attention_sliding_tests.rs(8 tests, each against a reference built from the plain attention),model_dspark_tests.rs(8),dense_speculative_tests.rs(10),detection_tests.rs(two new cases).Real checkpoints
Revisions:
Qwen/Qwen3-4B1cfa9a72,RedHatAI/Qwen3-4B-speculator.dsparkbdffaa5f,openbmb/MiniCPM5-2B42433e90,openbmb/MiniCPM5-2B-DSparka63eb96b,LiquidAI/LFM2.5-2.6B7141b56c,LiquidAI/LFM2.5-2.6B-DSpark458cedab.CLI,
mlxcel generate -m <target> [--draft-model <drafter>] -p <prompt> -n 128 --temp 0 --show-reasoning, three runs each (one process per run, so each number includes that process's warm-up):Qwen3 DFlash speculative decoding declined ...; probeverify block position 0 differs from the single-token chain in 140205 of 303872 logit bytesMLXCEL_MTP_ALLOW_INEXACT=1, width 8133206 of 261120 logit bytesMLXCEL_MTP_ALLOW_INEXACT=1, width 8Server,
mlxcel-server -m <target> [--model-draft <drafter>], one/v1/chat/completionsrequest (temperature 0, 128 tokens,logprobswith 3 alternatives), then the same request again:timings)MLXCEL_MTP_ALLOW_INEXACT=1draft_n 262,draft_n_accepted 88,draft_rounds 40; decode 44.6 / 53.0 tok/s; 3.00 s / 2.45 sMLXCEL_MTP_ALLOW_INEXACT=1draft_n 164,draft_n_accepted 103,draft_rounds 24; decode 73.1 / 130.3 tok/s; 1.85 s / 1.02 sWhere the override arm leaves the reference, from the two responses' logprobs:
makeat -1.25 withnotsecond at -1.375, a gap of 0.125. The drafter run has both at -1.25 and emitsnot.likelyandwantsboth at -1.5 and emitslikely. The drafter run haswantsat -1.375 and emits it.Up to those positions the largest logprob difference on an emitted token is 0.25 and 0.125.
Exact arm, as a test.
dense_speculative::real_checkpoint_testswraps the target so each row of a verify block is its own single-token forward (classic decode's arithmetic by construction, on any backend) and runs the production drafter, captures, hidden slicing, rollback and round loop around it. On both pairings, three prompts of 96 tokens each (5, 9 or 10, and about 290 prompt tokens), the drafted tokens equalforward_last_logitsgreedy tokens. Accepted / proposed: Qwen3-4B 57/261, 57/267, 74/150; MiniCPM5-2B 66/203, 74/149, 80/105. The tests soft-skip when the checkpoints are absent, as the other real-checkpoint tests do.Why the probe declines on GB10. A throwaway test (not in this PR) compared row
rof an 8-row product with the same row computed alone, bf16, real shapes:matmul2560 to 9728matmul2560 to 151,936KVCache::attend, block of 8 queries against one query at a time, 20 cached keysA batched verify block of a dense bf16 target therefore cannot equal single-token decode bit for bit on this backend. Computing it row by row is exact and gives up the speedup. The existing
MLXCEL_MLA_ROW_INVARIANT=1switch (Llama-class models, #3421) brings the MiniCPM5-2B probe from 133,206 differing bytes to 494, not to 0, on GB10; I did not chase the remainder.LFM2.5 unchanged.
LiquidAI/LFM2.5-2.6BwithLiquidAI/LFM2.5-2.6B-DSparkon the server,mainagainst this commit, same request: no drafter, drafter with default settings (the probe declines on GB10 here too) and drafter with the override give the same text on both builds in each arm, and the override arm reportsdraft_n 272,draft_n_accepted 88,draft_rounds 39on both.Verification limits
d2t.z-lab/Qwen3-4B-DFlash-b16now passes the family gate on a Qwen3 target and is held to the tap and vocabulary bounds only. It would get every prompt row as its first draft context, the DSpark policy.timings, so that arm is compared by request round trip only.src/bin/speculative_bench.rsis unchanged (no DFlash dispatch exists there).