Repository navigation
feat(dflash): run DFlash in the batched engines and remove dflash-mlx - #4508
Conversation
Batched DFlash verified every draft of the block and ignored dflash_verify_mode. Drafter rows now use the Lightning MTP depth controllers (the singleton controller and the cohort batch policy), and each block is clipped to the chosen depth right before verify. "dflash" and "off" keep the whole block.
GLM-5.3 VLM targets now draft with the batched DFlash drafter instead of the single-stream DFlashEngine, so they share the paged hot/SSD prefix cache and continuous batching. The glm5_next runtime captures the drafter layers with the HC streams averaged, like the dflash-mlx adapter, during prefill, verify and one-token decode. Verify blocks stay within the 8-row PoolingCache undo log, and verify-shape FFNs run once eagerly before compiling so kernel self-checks still run.
Cached prompt tokens skip prefill, so the batched DFlash drafter started a prefix cache hit with almost no context and accepted fewer drafts. The drafter now keeps the projected context of the newest rows of each finished request (memory only, the last 8 requests) and seeds a hit whose cached tokens match it. Requests with media keep no context, since tokens alone cannot tell their inputs apart.
Gemma 4's sliding-window layers use mlx-vlm's own RotatingKVCache and BatchRotatingKVCache, which the verify undo log did not cover. Once the window was full, trimming a rejected verify only moved the write index, so a following one-token step (a depth-0 cycle or a park to ordinary decode) kept the rejected drafts in the window and dropped older tokens. The undo log now wraps the mlx-vlm classes too.
Gemma 4 VLM targets now draft with the batched DFlash drafter instead of the single-stream DFlashEngine, so they use the paged hot/SSD prefix cache and serve concurrent requests together. Verify forwards return the drafter captures and the last layer's hidden, and ordinary decode steps feed the drafter. Speculation stays single-row, since a ragged accept cannot roll back the batched sliding-window caches; batches of two or more decode normally.
The stock Gemma 4 rollback built an mx.array from the host accept count and read it back with item(), which waited for the draft already queued behind the verify. A single-row rollback now trims with host integers. On M3 Ultra this cut about 2 ms from each Gemma 4 26B-A4B DFlash cycle.
…d engines (#4327) Text-only Qwen3/Qwen3.5 and Laguna targets on BatchedEngine and Muse Glimmer on the VLM engine now draft with the batched DFlash drafter instead of the single-stream DFlashEngine, so they use the paged prefix cache and batch concurrent requests. Targets without a speculative rollback hook get layer captures by wrapping their decoder layer class around the model's own forward, plus a KV-trim rollback, and speculate for single rows. The drafter forward covers Laguna's fused QKV, per-head output gate, causal block and per-capture norms, and Muse's encoder projection; partial RoPE is rebuilt from the checkpoint since mlx-vlm rotates the whole head. Prefill captures now start at the cached prefix position when boundary snapshots are off.
Move omlx/speculative/dflash_drafter.py into omlx/speculative/dflash/ (drafter, variants, selection, kernels) without behavior changes.
…4327) DFlash now always runs as the batched block drafter inside BatchedEngine and VLMBatchedEngine, so the single-stream DFlashEngine, its dflash-mlx target adapters (GLM-5.3, Laguna, MiMo V2) and lifecycle hooks are removed together with the dflash-mlx pin. Settings only the old engine read are dropped from the server, the admin API and both UIs: the L1/L2 prefix caches, max_ctx, the draft sink size and activation-bit quantization. A stored ddtree verify mode loads as adaptive, dflash_draft_window_size now sets the batched drafter's context window, and model types without a batched drafter path, including MiMo V2, load without DFlash.
Uses the draft bundled in the checkpoint's dflash/ folder when no draft model is set.
Also fixes Gemma 4 capture order, detaches the drafter on engine stop, and sizes the memory estimate from the draft config.
62c8707 to
f8b7b84
Compare
|
A possible follow-up we could contribute is request-owned random keys for concurrent DFlash. The scheduler and #4376 already document global/best-effort seed semantics; a per-row sampler still draws from that shared stream. Using this PR head's import mlx.core as mx
from omlx.utils.sampling import make_sampler
mx.set_default_device(mx.cpu)
sampler = make_sampler(temp=1.0)
logits = mx.zeros((1, 256))
def run(neighbor):
mx.random.seed(123) # request A
first = int(sampler(logits).item())
if neighbor:
mx.random.seed(321) # request B arrives
sampler(logits).item()
return [first, int(sampler(logits).item())]
print(run(False)) # [11, 221]
print(run(True)) # [11, 160]mlx2 carries a key on each request and splits it for each draw. Its CPU DFlash regression preserves a sampled lane's seeded output when a short neighbor finishes. A port would need request-owned keys through target sampling, draft proposals, acceptance uniforms and residual sampling, while retaining the shared filtering optimization from #4376. Would that fit as a separate follow-up to this PR? The reproduction isolates RNG behavior with fixed logits; full-model batch numerics would need separate validation. |
|
@pierre427 Seed in oMLX is best-effort, which is the same contract the OpenAI API documents: Request-owned keys would isolate the RNG stream, but a seeded row still would not reproduce under concurrency. Batched decode in oMLX is not batch-invariant, so even greedy rows can differ from a solo run once a neighbor joins. Other servers see the same thing: llama.cpp reports nondeterministic output across multiple slots even at temperature 0, and vLLM only promises batch-independent output in its separate batch invariance mode. Real reproducibility needs batch-invariant kernels on top of per-request RNG, and that costs throughput. The Thinking Machines write-up measured about 2.1x slower than stock vLLM in their first version (55s vs 26s, 42s after more tuning), and SGLang's deterministic mode reports an average 34% slowdown. Servers that do isolate the RNG pay for it in batched sampling. vLLM and TGI keep a generator per request and sample seeded rows one by one, and mlx-lm's server takes seeded requests out of the batch entirely. None of these fix the numerics. So I'd rather not add key plumbing through target sampling, draft proposals, acceptance and residual sampling for now. If deterministic serving turns into a real need, I think it belongs in a separate opt-in mode with batch-invariant kernels, and I'd keep it out of #4508. |
|
Point your agent to Github.com/pierre427/mlx2 I’ve implemented request-owned RNG, row-invariant projection kernels, and a model-specific row-exact verification path. The projection kernels keep reduction order independent of batch size and use the same arithmetic for solo and batched rows; full-model invariance still requires validation for the particular route. After you see what i did, let me know if it should be a pr |
|
Ps - look at my varlen krrnel work which is related - row padding messes with the gdn state iirc. |
|
@pierre427 I reproduced a GDN state mismatch in the pinned mlx-vlm Qwen code when zero left padding causes the SSM helper to ignore right-padding lengths. I opened #4526 to preserve both bounds; the reproducer now matches separate unpadded GDN states. This predates #4508. The DFlash server path in this PR prefills requests individually and groups verification by draft width, so it does not hit that specific case. Thanks for flagging the padding issue. |
Upstream jundot#4508 removes DFlashEngine and runs DFlash in the batched engines, which already install the Qwen3.5-family prefill stack, so the fork's DFlash prefill patch (0f371c6, 9bf31ab) is dropped.
…undot#4508) Field was deleted from ModelSettings upstream; fork-side profile lists, engine_pool passthrough, benchmark allowlist and admin routes still referenced it, tripping test_admin_profiles_api field classification.
Keep the fork's changes on top of upstream: - classifier steering settings, admin fields, and UI toggle; the toggle moves to apps/omlx-web (upstream split the web UI out in jundot#4359) - cluster mDNS retries, TCP link-probe fallback (now with the absolute /usr/bin/python3 upstream uses), Thunderbolt Bridge address, nested safetensors shards, and the quoted df path (a leading ~/ stays expandable) Take upstream's design where it replaced the fork's: - remote_model_dir() expands a ~-form path again and callers convert with home_relative_model_path(), so explicit path_map entries stay literal - the dflash engine and its compatibility check are gone (jundot#4508)
Conflict resolution: - engine_pool.py, engine/vlm.py: keep both sides (prefill_step_size reload key next to activation_fp16_enabled; effective-width log next to the prefill helper setup, which reads the already-resolved step size). - engine/dflash.py: accept main's deletion (jundot#4508). DFlash now runs in the batched engines, which already call resolve_prefill_step_size; drop it from the engine seam test and the stale comment in engine/base.py. - dashboard.js: main moved the PUT body into buildModelSettingsPayload(ms), so prefill_step_size (and its diffusion reset) moves there; the seam test now targets that function. - _modal_model_settings.html: keep main's LoopCD card and the prefill chunk size card, the latter still directly before SpecPrefill. - i18n: add the prefill_step_size keys to the new de and it locales. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
DFlash ran on its own single-stream engine built on dflash-mlx, outside the scheduler and the paged prefix cache, so DFlash requests did not use the hot/SSD cache and were served one at a time (#4327). This PR moves every supported family onto the batched block drafter that Qwen3.5-family VLM targets already used, then removes the separate engine and the dflash-mlx dependency. DFlash requests now go through the scheduler, continuous batching and the paged prefix cache like any other request.
qwen3_5,qwen3_5_moe)glm5_next)gemma4,gemma4_unified)"Single row" means a request speculates while it decodes alone; batches of two or more decode normally, since rows that accept different counts would need a ragged rollback of sliding-window caches.
Changes
dflash_verify_modeset todflashoroffkeeps full-block verify.dflash/directory is used when no draft model is set.omlx/speculative/dflash/(drafter, variants, selection, kernels).DFlashEngine, its dflash-mlx target adapters and lifecycle hooks, and the dflash-mlx pin.Behavior changes
dflash_in_memory_cache*,dflash_ssd_cache*),dflash_max_ctx,dflash_draft_sink_size, activation-bit draft quantization and theddtreeverify mode. Older settings files still load; a storedddtreeloads asadaptive.dflash_draft_window_sizenow sets the batched drafter's context window.Validation
M3 Ultra, 512-token completions, greedy and sampled (temperature 1.0, top_p 0.95, top_k 20), two runs per arm. Change in tok/s against the previous DFlash engine on main:
GLM-5.3-Flash oQ4e + DFlash2: single requests +2% to +27% and four concurrent +25% to +34% across prompts and modes. In a multi-turn agent replay with the hot and SSD cache on, turns after the first reuse the cached prefix and reach the first token in about 1.2 s, against 4 to 5 s when every turn prefills from scratch.
For Laguna, Muse Glimmer and MiMo I compared the candidate drafter layouts offline on real target hidden states before picking one. Laguna follows the checkpoint's partial RoPE (mean accepted drafts per block 2.55 / 1.02 / 2.57 against 1.57 / 0.73 / 1.59 with full-head RoPE), Muse Glimmer follows the Transformers reference layout with a bidirectional block and raw token embeddings, and MiMo needs its partial RoPE and trained mask embedding (3.24 / 1.54 / 4.09, against 0.43 / 0.33 / 0.54 with full-head RoPE and 0.89 / 0.63 / 1.35 with the mask token's embedding).
Tiny-model tests drive Qwen3, Laguna and GLM-5.3 targets through the Lightning MTP verify path and require the greedy output to match plain decoding, including a Laguna target whose sliding window wraps during generation, and check the batched forward of the DFlash2, Laguna, Muse Glimmer and MiMo drafters against their mlx-vlm references. Qwen3.8-27B, Laguna and MiMo also ran single, sampled and concurrent requests on a server built from the final commit.