[RFC] DFlash on Qwen3-4b#20840
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/pytorch/executorch/20840
Note: Links to docs will display an error until the docs builds have been completed. This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
Hi @cthotti! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks! |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
|
@claude review this code |
|
Thanks @cthotti! Am I right in reading the PR that you're not seeing speedup from dflash? |
|
Claude finished @metascroy's task in 3m 33s —— View job Code Review — DFlash on Qwen3-4BNice work — the DFlash design is well thought out, the model-agnostic 🔴 Blocking / correctness1. 2. 🟡 Should fix3. Leftover profiling scaffolding in 4. Missing BSD license headers 🟢 Minor / nits
Testing / CI noteNone of the DFlash tests can run in this repo's CI: they require exported Overall the core algorithm and export pipeline look solid and the correctness claim checks out on inspection. The main things to resolve before merge are the dead |
… hazard, trim profiling scaffolding, add license headers, fix typos - Remove qwen3_dflash-mlx Makefile target + .gitignore block: depended on C++ engine files that are gitignored/not yet landed (follow-up PR) - Rename tests/test_dflash_*.py -> check_dflash_*.py so pytest's test_* glob never collects these manual, hardware-gated driver scripts - Trim sub-millisecond profiling scaffolding in run_dflash.py, keep only draft_exec/target_exec timing under --verbose (those dominate wall time) - Add missing BSD license headers to 8 files - Fix no-op --chat-template flag (only --no-chat-template had any effect) - Fix typos: frmo->from, prodcues->produces, an .pte->a .pte, output project->output projection weights - Add one-line comment on first_mismatch's draft/target length asymmetry - Remove unused default_dflash_layer_ids (layer ids come from --dflash-layers / draft config, not this helper) - Document DFlash's check_dflash_*.py as manual/CI-exempt in README
Yes, I didn't see a speedup on my original hardware, although the implementation is functionally correct and produces token for token identical output to baseline decoding. From profiling, the verification stage dominated each speculative round on my Macbook M2 Air (8 core GPU), so the cost of verifying each drafted block outweighed the time saved by drafting. However, since then, I've rerun the implementation on another Apple Silicon environment using a MacBook M4 (10-core GPU), where I observed a 1.4x speedup over a baseline run. Which makes me think that earlier results were more so hardware dependent. Before drawing a conclusion, I'd like to spend more time running experiments and testing out other Apple environments, like a M2 Pro (16 core GPU) and, if possible, M4 Pro (20 core GPU). Would it be alright if I spend a little more time validating the implementation and updating the PR with those results? |
Yes, that would be great! Pybindings do add overhead, and we do usually benchmark with c++ runners. We have a C++ runner for gemma4-31b (this would require an M4 to run). |
Summary
This PR adds support for DFlash speculative decoding to the ExecuTorch MLX delegate using Qwen3-4B as the reference model. It has hidden-state export for the target model, a configurable DFlash draft model, export support for both models, and an end-to-end speculative decoding driver. The implementation has been verified to produce an identical output to standard greedy decoding.
Although the original issue was targeted at Gemma, my implementation was developed and validated on Qwen3 because publicly available DFlash draft weights are available and the model fits within local hardware constraints. The overall implementation is model-agnostic and designed to support additional architectures in follow-up work.
Fixes #20701
DFlash Overview
Unlike conventional speculative decoding, where a small autoregressive draft model predicts one token at a time, DFlash predicts an entire block of tokens in a single forward pass over a masked block. The draft model is conditioned on intermediate hidden states from the target model, which are added into the Key/Value projections of every draft rather than only at the input. This provides richer conditioning throughout the draft network while keeping the draft model relatively small.
The draft model is implemented through a configurable DFlashConfig, making it adaptable to different transformer architectures. It has been numerically verified on Qwen3 and structurally validated against Llama-3.1 and Gemma-style configurations. There are additional Gemma-specific features documented, like partial RoPE and post-layer scaling, but they remain outside the scope of this PR.
Key Implementation Details
Phase 1: Target hidden-state export
TorchExportableModuleWithStaticCacheAndHidden, which extends the existing Hugging Face export wrapper to return both logits and concatenated hidden states from the selected target layers.Phase 2: Draft model and export
Phase 3: Speculative decoding driver
Python Driver
My PR includes the Python implementation of the speculative decoding loop rather than the earlier C++ engine recommended in the issue.
Profiling showed that nearly all execution time is spent inside the exported target and draft model execution, while the Python overhead contributes only a very small fraction of the total runtime. Since both implementations execute the same exported MLX programs, the Python driver provides similar functionality and is simpler to maintain. A C++ implementation can be added later if tighter runtime integration is needed.
Performance
My primary goal of this PR is to add DFlash support and verify that the implementation is correct. In addition to correctness, I benchmarked the implementation on Apple M2 hardware to understand its performance characteristics.
The most significant observation is that the target model's verification pass scales almost linearly with the number of tokens being verified. On this system, verifying a single token (T=1) takes approximately 32 ms, while verifying a block of 16 tokens (T=16) takes approximately 239 ms, roughly 7.5× the latency for a 16× larger verification window.
Since speculative decoding relies on verifying multiple draft tokens in a single target forward pass, this scaling behavior directly impacts the achievable speedup. The measured acceptance rates (chat: 4.17, math: 5.59, code: 6.81) are not sufficient to offset the additional verification cost on this hardware, so the implementation is currently slower than baseline greedy decoding for a single-request inference on an Apple M2.
This appears to be because of the underlying hardware rather than the DFlash implementation itself. The speculative decoding algorithm is functioning correctly and produces token-for-token identical output to baseline decoding. Platforms where verification cost grows more slowly with batch size are expected to benefit more from DFlash, since speculative decoding becomes increasingly effective as the cost of verifying larger blocks approaches the cost of verifying a single token.
Test Plan
All tests were run using exported target and draft models (
qwen3_4b_dflash_target.pteandqwen3_4b_dflash_draft.pte) with a block size of 16 and 4-bit quantization.Lossless speculative decoding:
python3 examples/models/qwen3/tests/test_dflash_lossless.pyVerifies that DFlash produces token-for-token identical output to standard greedy decoding.
Target model export
Draft model export and dynamic context lengths
Final Results
Math prompt
Code prompt
Chat prompt
cc @mergennachin @iseeyuan @lucylq @helunwencser @tarun292 @kimishpatel @jackzhxng