Repository navigation
feat(turbomind): add DFlash2 block-diffusion speculative decoding [stacked on #5006] - #5192
Draft
richardclli wants to merge 17 commits into
Draft
richardclli wants to merge 17 commits into
richardclli wants to merge 17 commits into
Conversation
- Fixed-chain speculator base with EAGLE3 and Qwen3.5 MTP draft models, target-native speculation, and method-keyed draft weight registry - Block speculative verification: paged CuTe verification attention, SM90 GDR verify and commit kernels with persistent pipelining - Unified parameterized batch-op pipeline; executor forward split into target pass and speculative round; host batch ops moved engine-side - Scheduler: unified required admission, simplified rollback, submitted rows carry producer-set effects instead of a kind tag - Op-level pytest suites: verification attention, draft carry, speculative sampling, speculative sequence, target hidden projection, copy
CI fixes for the MTP feature commit: - Use the canonical 'from lmdeploy.turbomind import _tm' import in the TurboMind tests and apply the ruff fixes inherited from the feature PR. - Apply clang-format to the files introduced or changed by the feature. - Inject the engine symmetric buffer into the pass environment before the vision model runs, so VLM TP with cuda-ipc keeps its symmetric buffer. - Keep the previous whole-archive link order on MSVC, whose linker does not support LINK_GROUP:RESCAN. Co-authored-by: Richard Li <richard.li@ces.hk>
- Normalize qwen3_5_mtp/hy3_mtp/deepseek_mtp to the registered 'mtp' name before building the draft model and assigning EngineConfig.spec_method. - Accept half_t for the GDN recurrent state in the accepted-state commit kernel, so speculative rounds run with the float16 dtype on pre-SM80 GPUs.
Keep the normalize_spec_method docstring within the lint summary width and apply the lint fixes for the files touched by the SM75 MTP changes. Co-authored-by: Richard Li <richard.li@ces.hk>
- MoE gate: initialize routing slots to a skip sentinel and bounds-check the expert id, so a valid token that selects fewer than top_k experts no longer indexes masks[] out of range. Adds a regression test. - Synchronize the target-pass logits before publishing them; the sampler runs on another stream and the first step could hang on stale data. - Reserve 2*(max_proposals+1) rows below session_len at admission so a speculative round cannot write past the allocated KV columns.
Add a native paged verification-attention path for SM75 so MTP no longer falls back to the prefill path: - policy_sm75.cuh + kernel_sm75.cu, compiled 75-real only; the Turing MMA path reuses the m16n8k8 emulation and keeps k16 tiling. - int4/uint4 KV reader and dequant (quant_policy 4). - Per-arch static libraries plus a host dispatch_arch.cc; the SM90 WGMMA path is namespaced and behavior-unchanged. - SM75 split tuning and an int4 verification-attention bench.
Add the DFlash2 draft weight tree (fc, hidden_norm, candidate selector), grouped-conv and selector weight modules, the qwen3-dflash2 input model, DRAFT_WEIGHT_SPECS['dflash2'], the CLI choice, and the decoder-only draft config. The loader also accepts a quantized draft checkpoint (compressed-tensors nvfp4-pack-quantized).
Add invokeGroupedConv and invokeCandidateSelector CUDA kernels with their python bindings and CMake targets. Both match the PyTorch reference on synthetic inputs (1.9e-6 / 2.7e-5 fp32).
Add the non-causal GQA block-attention kernel over [context | block] and the NeoX RoPE kernel used to materialize the draft context KV, with python bindings. The shared-decoder non-causal plumbing from the prototype is intentionally omitted: the final RunBlock uses the bespoke kernels.
Add Dflash2Policy block extents, incremental context-KV materialization from the target-hidden tap, the 5-layer block forward (grouped conv + non-causal attention + SwiGLU) with TP allreduce, the candidate selector (target-LM-head top-k -> lattice -> greedy chain), and proposal storage. The draft is a decoder-only 5-layer Qwen3-style model; the target keeps its normal forward and verification. All acceptance/correctness fixes are folded into this commit (contiguous q/k/v, positions from the committed seqlen, range-preserving residual and draft contract, zero-init draft KV, block-forward math, successor-indexed selector).
Replace the per-step host bookkeeping in RunDraft (three blocking D2H reads, a host position loop, H2D copies) with device kernels for the committed length, count-up positions and KV scatter. One host read of the committed length remains to size the block attention, preceded by a stream sync. Behavior-neutral; this is also the prerequisite for the int4 draft context KV path. The prototype dump/debug hooks are removed.
Store the DFlash2 draft context K/V as packed uint4 with per-(token,head) scale/zero and dequantize them in the draft attention kernel. Block KV stays in the compute dtype. Selected by SpeculativeConfig.dflash_ctx_kv_int4 / --speculative-draft-ctx-kv-int4 (default off); the BF16 path is kept. The kernel requires head_dim 128 and falls back to BF16 otherwise. This is a VRAM feature: QProd-256K saves ~768 MiB/card with the NVFP4 draft; decode is neutral to slightly down at short context.
Cover grouped conv, candidate selector, non-causal block attention, and int4-context-KV dequant parity against compact PyTorch references, plus the draft loader/config (method spec, ctx-kv-int4 validation, NVFP4 quantization_config detection). Expose dflash2_attention_int4 on the python bridge for the parity test.
Use a single-pass online softmax for the block attention instead of three serial passes over all keys, and parallelize the selector top-k over the 248k vocabulary (256 threads/row + shared-memory merge). Decode 40 -> 83 t/s @5.7K with acceptance unchanged.
Split the key range across 4 warps and combine the online-softmax partials in shared memory. Decode 72 -> 85 t/s (+18%) @5.7K; acceptance and block-hidden parity unchanged.
Start the key loop at first_ctx (everything in [first_ctx, nkeys) is valid) instead of scanning the whole context and masking the out-of-window prefix, and widen to 8 warps for more key parallelism. Decode 85 -> 98 t/s (+15%) @5.7K; the attention section drops from ~2.66 ms to ~1.0 ms; block-hidden parity unchanged.
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Stacked on #5006 (TurboMind
speculative decoding). Adds a DFlash2 block-diffusion drafter (block 8 / depth 7)
to TurboMind: grouped depthwise convs, a candidate-selector lattice, non-causal
sliding-window block attention, incremental context-KV materialization, and a
bespoke
RunDraft. The draft is a 5-layer Qwen3-style decoder; the target keepsits normal forward and verification.
The branch is also built on the current #5019, #5142, #5144, and #5145 work;
once those merge, the diff of this PR shrinks to the DFlash2 commits. The last
three commits are measured kernel perf wins; they are isolated and can be dropped
without changing the feature.
Motivation
DFlash2's block-diffusion drafter gives a larger acceptance length than MTP on the
same target and beats MTP-4 at short/mid context on the validation platform
(RTX 2080 Ti, SM75, TP2). It is a single-request lever, complementary to MTP.
Modification
Dflash2Weight(fc,hidden_norm, selector),grouped-conv and candidate-selector weight modules, a
qwen3-dflash2inputmodel,
DRAFT_WEIGHT_SPECS['dflash2'], and a decoder-only draft config. Theloader also accepts a quantized draft (
compressed-tensorsnvfp4-pack-quantized).context-KV materialization, and a non-causal GQA block attention over
[context | block].Dflash2Policyblock extents, incremental context materialization fromthe target-hidden tap, a 5-layer block forward (conv + non-causal attention +
SwiGLU) with TP allreduce, a selector (target-LM-head top-k -> lattice -> greedy
chain), and proposal storage. Device-side commit/position/KV bookkeeping keeps
the decode step free of per-step host I/O.
dequantized in the draft attention) selected by
SpeculativeConfig.dflash_ctx_kv_int4/--speculative-draft-ctx-kv-int4(default off). This is a VRAM feature; thetarget KV is unchanged.
warp-parallel split-K block attention with a shared-memory combine, and a
window-start key loop. Measured wins only; no functional change.
dtype discriminator with
__nv_bfloat16dispatch, padded-vocab scoring, andenforced limits (
max_batch_size,num_draft_tokens,head_dim,selector_top_k, no prefix caching).rope_thetacomes from the draft config.Dependency note
SpeculativeModel, policy,RunDraft, hidden-state tap)half_t+ method alias; needed to run the target on SM75Validated checkpoints
SM75 (RTX 2080 Ti), TP2:
qwen38-27b-quasar-nvfp4(BF16 LM head) + a 5-layerDFlash2 draft (BF16 and NVFP4 checkpoints).
0f216591)1164d713)Re-measured 2026-11-25 on the natural-corpus 6.6K lane, gen 256, median of 3
(earlier: 54.8 / 4.41 and 139.7 / 4.74). The knowledge-base 115.1 t/s / 4.13
figure came from a different corpus and the production tree; the branch
measurements above are the source of truth. The last three perf commits are
isolated; dropping them leaves the working feature. The post-perf fix commit
(
1164d713) does not change the FP16 numerics. F4 e2e: BF16 canary 10/10 twiceon one server, NVFP4+int4 canary 10/10; BF16 kernel parity skips on SM75 and runs
on SM80+ CI.
Memory variant (QProd-256K: NVFP4 draft + int4 draft context KV, 256K, 1 slot):
Kernel parity: grouped conv (1.9e-6), candidate selector (2.7e-5), non-causal
block attention (6e-7) against the PyTorch reference; int4-vs-BF16 context KV
parity is added in the test suite.
Perf layer A/B @5.7K (commit-time): 40 -> 83 -> 85 -> 98 t/s. Acceptance and block
hidden parity are unchanged.
Dropped from this PR
is a prerequisite for the int4 context-KV feature; it stays in the feature
commits, not in the perf tail.
was NVTX profiling and is not included.
BC-breaking
None.
dflash2is a new speculative method and remains off unless selected; theint4 draft-context-KV mode defaults to off and keeps the BF16 path. Existing
target/model paths are unchanged.
Notes
the target LM head, and a 4-bit head (
-lh4) halves acceptance.--max-batch-size 1); the enginerejects other values.
--speculative-num-draft-tokensmust beblock_size - 1(7 for the currentdraft); a mismatch is rejected.
manager, so a restored prefix cannot be populated. The engine rejects
--enable-prefix-cachingwithdflash2.e2e lane; the kernel tests are synthetic and skip-guarded where needed. BF16
dispatch is compiled and parity-tested on SM80+ CI.
head_dim == 128; the draft checkpoints in scopesatisfy this and the engine rejects other head dims.