Skip to content

feat(turbomind): add DFlash2 block-diffusion speculative decoding [stacked on #5006] - #5192

Draft
richardclli wants to merge 17 commits into
InternLM:mainfrom
richardclli:pr/dflash2
Draft

richardclli wants to merge 17 commits into
InternLM:mainfrom
richardclli:pr/dflash2

Conversation

@richardclli

Copy link
Copy Markdown

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 keeps
its 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

  • Draft weights and loader: Dflash2Weight (fc, hidden_norm, selector),
    grouped-conv and candidate-selector weight modules, a qwen3-dflash2 input
    model, DRAFT_WEIGHT_SPECS['dflash2'], and a decoder-only draft config. The
    loader also accepts a quantized draft (compressed-tensors
    nvfp4-pack-quantized).
  • Kernels: grouped conv, candidate-selector score/lattice, NeoX RoPE for
    context-KV materialization, and a non-causal GQA block attention over
    [context | block].
  • Method: Dflash2Policy block extents, incremental context materialization from
    the 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.
  • Optional memory: an int4 draft-context-KV mode (packed uint4 + scale/zero,
    dequantized in the draft attention) selected by
    SpeculativeConfig.dflash_ctx_kv_int4 /
    --speculative-draft-ctx-kv-int4 (default off). This is a VRAM feature; the
    target KV is unchanged.
  • Perf (last three commits): a single-pass online softmax + threaded top-k, a
    warp-parallel split-K block attention with a shared-memory combine, and a
    window-start key loop. Measured wins only; no functional change.
  • Robustness (post-perf fix commit): per-request draft-context reset, a real
    dtype discriminator with __nv_bfloat16 dispatch, padded-vocab scoring, and
    enforced limits (max_batch_size, num_draft_tokens, head_dim,
    selector_top_k, no prefix caching). rope_theta comes from the draft config.

Dependency note

Kind Required Why
Code #5006 speculative framework (SpeculativeModel, policy, RunDraft, hidden-state tap)
Code #5142 NVFP4 weight format for the quantized-draft lane
SM75 runtime #5019 GDN half_t + method alias; needed to run the target on SM75
SM75 verification #5145 native target verification used by the MTP/DFlash2 stack
Robustness #5144 speculative KV margin at admission; validation path, not code

Validated checkpoints

SM75 (RTX 2080 Ti), TP2: qwen38-27b-quasar-nvfp4 (BF16 LM head) + a 5-layer
DFlash2 draft (BF16 and NVFP4 checkpoints).

config draft decode t/s @6.6K mean accept
AR (no spec) — 45.4 1.00
MTP-4 baseline — 91.3 3.71
Feature-only ablation (0f216591) BF16 54.3 4.76
Combined tip (1164d713) BF16 137.3 4.74

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 twice
on 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):

check result
VRAM idle 20,834 -> 20,066 MiB; 256K 21,368 -> 20,600 MiB (−768 MiB/card)
decode 128K 65.5 t/s; 256K 57.4 t/s; 32K −2.6 %
canary / vision 10/10 / 2/2

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

  • Device-side draft-context bookkeeping was measured neutral (6.38 vs 6.37 s) but
    is a prerequisite for the int4 context-KV feature; it stays in the feature
    commits, not in the perf tail.
  • Split-vocab top-k was measured flat (~2.5 % of the round); its remaining change
    was NVTX profiling and is not included.

BC-breaking

None. dflash2 is a new speculative method and remains off unless selected; the
int4 draft-context-KV mode defaults to off and keeps the BF16 path. Existing
target/model paths are unchanged.

Notes

  • The target must expose a BF16 LM head: the selector's candidate top-k runs
    the target LM head, and a 4-bit head (-lh4) halves acceptance.
  • DFlash2 in TurboMind is a single-request path (--max-batch-size 1); the engine
    rejects other values.
  • --speculative-num-draft-tokens must be block_size - 1 (7 for the current
    draft); a mismatch is rejected.
  • Prefix caching is not supported: the draft context KV lives outside the cache
    manager, so a restored prefix cannot be populated. The engine rejects
    --enable-prefix-caching with dflash2.
  • SM75 is the validation platform. Upstream CI (A100/SM80+) cannot run the SM75
    e2e lane; the kernel tests are synthetic and skip-guarded where needed. BF16
    dispatch is compiled and parity-tested on SM80+ CI.
  • The draft attention requires head_dim == 128; the draft checkpoints in scope
    satisfy this and the engine rejects other head dims.

lzhangzz and others added 17 commits November 17, 2026 12:57
- 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

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants