Skip to content

[Speculative] DFlash tree drafting: host-side tree-construction core (#29524) - #29587

Closed
ajinkyajawale14499 wants to merge 6 commits into
sgl-project:mainfrom
ajinkyajawale14499:feat/dflash-tree-drafting
Closed

ajinkyajawale14499 wants to merge 6 commits into
sgl-project:mainfrom
ajinkyajawale14499:feat/dflash-tree-drafting

Conversation

@ajinkyajawale14499

@ajinkyajawale14499 ajinkyajawale14499 commented Jun 28, 2026 •

Copy link
Copy Markdown

Motivation

This is the first step toward JetSpec speculative decoding (#29524). SGLang's DFlash drafts a linear chain — one candidate token per draft depth, scored independently of which branch it sits on. JetSpec (Hao AI Lab, arXiv 2606.18394) keeps DFlash's single draft-head forward pass but proposes a token tree and verifies the whole tree in one target pass under a tree-causal mask.

The core problem with the chain: it cannot use a larger draft budget productively. Once you draft more tokens linearly, acceptance saturates, because a single mispredicted token truncates the whole proposal. A tree spends the same budget on branches, so more of it survives verification. Concretely, from the paper (Qwen3-8B, temperature 0):

Drafting Accept length τ @ budget 256 (MATH-500) Speedup
DFlash chain saturates ~budget 32 (τ≈6.9), no gain beyond —
EAGLE-3 tree (depth 8, budget 64) τ≈4.13 2.36×
JetSpec tree τ≈10.76 9.64×

(JetSpec also reports ~1000 TPS on a single B200 and 9.45× on MoE Qwen3-30B-A3B.) The win is structural: same one-pass draft head, but branch scores are conditioned on ancestors and verified as a tree.

This is a large, GPU-bound feature (verify-loop integration, CUDA-graph capture, multiple attention backends, kernels, perf). This PR lands only the GPU-independent host-side core + plumbing, fully CPU-unit-tested, so the verify-loop integration can be built on a tested foundation. Tree mode is guarded off at startup; the chain path is byte-for-byte unchanged.

I want to be transparent up front: I don't currently have GPU access, so I deliberately stopped at the GPU boundary rather than ship untested kernel/worker code (see Accuracy Tests / Speed Tests). I'd welcome collaboration on the verify-loop wiring and validation — @vincentzed.

Background — how the tree is built (1 minute)

Per request, the draft head's one forward pass gives per-depth logits. From these we take top-W tokens + log-probs per depth ((depth, W)), pulled to host. The tree is then built entirely on CPU:

  • opt_prefix (paper Algorithm 1): a best-first max-heap keyed by accumulated branch log-prob Σ log q(y_u | x, h, ancestors). Each pop emits one node and pushes its next sibling (same parent, next rank) and first child (next depth, rank 0) — enumerating exactly the top-B highest-probability root→node prefixes without expanding the exponential space.
  • depth_first (default): lays down the greedy top-1 chain (the "spine") first, then adds side branches by accumulated log-prob. Because the spine is always present, tree acceptance ≥ chain acceptance by construction — a safe no-regression floor.

The tree is then encoded for verification: a tree-causal "allow" mask where each node attends only to the prefix + its ancestors (not siblings/cousins), and SGLang's existing retrieve_next_token/retrieve_next_sibling left-child/right-sibling pointers that the tree-general verify kernels already walk. Acceptance is greedy: a child is accepted iff its token equals the target's argmax at its parent; the longest fully-accepted root→leaf path wins.

This is a faithful port of the reference vLLM integration (Jet-Flow/vllm-jetspec), adapted to SGLang's DFlash/EAGLE conventions.

Modifications

New python/sglang/srt/speculative/dflash_tree.py — pure-Python/torch, no sglang-internal imports, no GPU:

  • build_tree_opt_prefix, build_tree_depth_first, and a build_tree dispatcher (caps fan-out to tree_width).
  • tree_to_verify_buffers — tree → SGLang verify buffers (retrieve_next_token/retrieve_next_sibling with the -1 sentinel, positions, padded to budget).
  • build_tree_custom_mask / build_ancestor_mask — tree-causal mask in the existing flattened Σkv·N + N²·bs layout.
  • compute_tree_budget, DFlashDraftTree (msgspec.Struct), and verify_tree_greedy_cpu (CPU reference of greedy tree acceptance — test oracle + eager fallback).

Plumbing:

  • server_args.py — --speculative-dflash-tree-{width,budget,construction} (documented as guarded/inert until the verify-loop integration lands).
  • arg_groups/speculative_hook.py — _handle_dflash_tree rejects --speculative-dflash-tree-width > 1 at startup with a clear message, so the flag can't trigger an unimplemented path. width <= 1 (chain) is unaffected.
  • dflash_info.py — DFlashVerifyInput.from_tree (populates the existing topk/custom_mask fields) and build_dflash_tree_verify_input (draft top-W output → tree-mode verify input): the seam the worker integration will call.
  • test/registered/spec/dflash/test_dflash_tree.py — CPU unit + integration suite (register_cpu_ci, base-a-test-cpu).

Key design decisions:

  1. Reuse the tree-general verify kernels (verify_tree_greedy / tree_speculative_sampling_target_only), not build_tree_kernel_efficient — a best-first tree is general and doesn't fit EAGLE's per-step beam parent_list format, whereas the verify kernels consume our hand-built retrieve_* + custom_mask directly. No new kernels.
  2. tree_width == 1 is byte-identical to the current chain buffers (retrieve_next_token = t→t+1, last -1; retrieve_next_sibling all -1) — asserted in a test against the actual _get_or_create_chain_verify_buffers. Existing DFlash users are unaffected.
  3. The DFlash worker decode loop is intentionally untouched (zero risk to the chain path); tree mode is wired through the new bridge in a follow-up.

Deferred (follow-up, GPU-bound): wiring the tree path into dflash_worker_v2's verify loop — CUDA-graph capture for a variable-size tree, and the non-contiguous accepted-path KV commit (the chain path assumes a contiguous accepted prefix); plus trtllm_mha/flashinfer tree-verify, MoE/hybrid recurrent-tree commit, SM90/SM100, rejection-sampling tree, and perf.

Accuracy Tests

This PR does not change model outputs: tree mode is guarded off at startup, and the chain path is byte-identical (asserted). So there is no accuracy delta to report here.

The host-side core is validated by a CPU-only suite (no GPU, no server):

  • Keystone integration test — a faithful CPU simulation of the CUDA verify_tree_greedy traversal (follow retrieve_next_token → retrieve_next_sibling) is asserted equal to an independent parent-based acceptance oracle over 200 random trees × both builders. This validates that the buffer encoding the GPU kernel will consume matches the tree the host built — the central correctness argument that substitutes for a GPU run.
  • W=1 byte-equivalence to the legacy chain buffers (via the real _get_or_create_chain_verify_buffers).
  • Builder invariants (parent < child, depth consistency, budget cap, opt_prefix best-first ordering, depth_first spine guarantee), tree-causal mask semantics + size formula, full edge-case coverage (empty depth, budget 0/1, budget > full-tree, single depth, ties, padding, batch), and the startup-guard + bridge.

The end-to-end lossless-greedy accuracy test — tree-spec output token-identical to non-spec decode on triton/fa3 with JetSpec/jetspec-qwen3-8b — is the merge gate for the follow-up verify-loop wiring. It requires a GPU (which I don't currently have); the code is structured (bridge + oracle) so it's straightforward to validate once the loop is wired, and I'd appreciate a hand running it.

Speed Tests and Profiling

No speed impact in this PR — tree mode is guarded off and the chain path is unchanged. Throughput / acceptance-length benchmarking (tree vs chain across budgets; SM90/SM100) is part of the deferred follow-up and requires a GPU; not included here.

Checklist

  • Format code with pre-commit (black + isort + ruff lint; verified clean).
  • Add unit tests (CPU unit + integration suite under test/registered/spec/dflash/).
  • Update documentation — N/A for this PR (no user-facing feature yet; flags documented in --help and marked inert/guarded).
  • Provide accuracy and speed benchmark results — deferred: tree mode isn't runnable yet (guarded) and I have no GPU; this is the follow-up's merge gate (see above).
  • Follow the SGLang code style guidance.

References

Resolves part of #29524.


CI States

Latest PR Test (Base): ❌ Run #28689534811
Latest PR Test (Extra): ❌ Run #28689534729

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request implements host-side tree construction for DFlash tree drafting (JetSpec), introducing tree builders (depth-first and optimal prefix), buffer converters, and custom mask builders, along with comprehensive CPU unit and integration tests. The review feedback highlights a potential IndexError in the depth-first tree builder when the width is zero, and recommends converting PyTorch tensors to Python lists in both the tree construction and verification steps to avoid performance overhead from scalar dispatch.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@ajinkyajawale14499

Copy link
Copy Markdown
Author

Thanks for the review — all three items addressed:

  • width==0 guard (build_tree_depth_first) and target_predict tensor→list (verify_tree_greedy_cpu): applied via the suggestions.
  • Remaining item — tensor inputs to the builders: build_tree now normalizes tensor / list-of-tensor inputs to host lists up front (_rows_to_lists), so the per-node Python loops avoid torch scalar-dispatch overhead. This covers both builders at the single production entry point (the bridge / worker call build_tree, not the inner builders directly).
  • Added tests: a zero-width-rows regression, plus tensor-input coverage for build_tree and the accept oracle.

Still a draft — the end-to-end lossless-greedy validation is the GPU follow-up (no GPU on my end yet).

…rafting (sgl-project#29524)

DFlashDraftTree (msgspec.Struct), compute_tree_budget, build_tree_{opt_prefix,
depth_first} + dispatcher (caps fan-out to tree_width; normalizes tensor inputs to
host lists; width==0 guard), tree_to_verify_buffers (left-child/right-sibling
encoding), build_tree_custom_mask (tree-causal ancestor mask), verify_tree_greedy_cpu
oracle (tensor-safe). Pure-Python/torch, no sglang-internal imports, no GPU.
Algorithms ported from Jet-Flow/vllm-jetspec dflash_tree.py.
…dge (sgl-project#29524)

server_args: --speculative-dflash-tree-{width,budget,construction} (guarded/inert
until the live verify-loop integration lands). speculative_hook: _handle_dflash_tree
rejects tree_width>1 at startup. dflash_info: DFlashVerifyInput.from_tree + the
build_dflash_tree_verify_input bridge (typed). Worker decode loop untouched.
…gl-project#29524)

Per-function + edge cases (incl. zero-width rows), full host pipeline, the keystone
retrieve_* pointer-walk == parent-oracle equivalence over 200 random trees x 2
builders, W=1 byte-equivalence to the legacy chain, tensor-input coverage, startup-
guard + bridge. Pure-CPU; register_cpu_ci (base-a-test-cpu).
@ajinkyajawale14499
ajinkyajawale14499 force-pushed the feat/dflash-tree-drafting branch from da095de to 9adf4da Compare June 28, 2026 23:46
@ronhuafeng

Copy link
Copy Markdown
Contributor

I took a pass over draft head 6694c497cf0ab3dc669ef1c36197fa48314e9b64.

Two things look actionable before the GPU follow-up:

  • The current GitHub lint failure is a real changed-file failure. In the dev container, changed-file pre-commit reproduced it: ruff rewrites the two DFlashVerifyInput return annotations in python/sglang/srt/speculative/dflash_info.py, and codespell flags the anc local name in python/sglang/srt/speculative/dflash_tree.py lines 263/265. Renaming it to something like ancestor_mask fixes the codespell part.
  • The focused CPU suite currently has one real failure: pytest test/registered/spec/dflash/test_dflash_tree.py -q gives 47 passed, 1 failed at TestTreeMask.test_context_all_allowed.

For the mask failure, the generated mask for DFlashDraftTree([0, 1], [-1, 0], [0, 1], 2) with kv_lens=[3] is row-major per query row:

mask.tolist() == [True, True, True, True, False, True, True, True, True, True]
mask.view(2, 5).tolist() == [
    [True, True, True, True, False],
    [True, True, True, True, True],
]

That matches the Triton custom-mask indexing path (row * cur_seq_kv_len + col). So I think the implementation layout is consistent with the backend reader, while the test assertion is slicing as if all prefix cells were contiguous at the front. Locally, changing that assertion to check the prefix columns per row, e.g. mask.view(2, 3 + 2)[:, :3].all(), plus the lint fixes above, gives:

  • pytest test/registered/spec/dflash/test_dflash_tree.py -q -> 48 passed
  • changed-file pre-commit run --files ... -> passed

I did not run the GPU verify-loop wiring; this is only CPU/static CI triage for the draft PR.

…ject#29524)

- codespell: rename local anc -> ancestor_mask (ctx -> context_mask) in
  build_tree_custom_mask.
- ruff: drop redundant quotes on DFlashVerifyInput return annotations (lazy under
  'from __future__ import annotations').
- test_context_all_allowed: the custom_mask is row-major per query row
  ([kv context | N block]), matching the Triton reader (row*kv_len+col); assert the
  context columns per row (mask.view(n, kv+n)[:, :kv]) instead of a flat prefix slice.
  Confirms the mask layout is correct; the prior assertion was slicing wrong.

Thanks @ronhuafeng for the CI triage.
@ajinkyajawale14499

Copy link
Copy Markdown
Author

Pushed b828b32 addressing all of @ronhuafeng's triage — thanks, this was spot-on:

  • codespell: anc → ancestor_mask.
  • ruff: dropped the redundant quotes on the two DFlashVerifyInput return annotations (lazy under from __future__ import annotations).
  • test_context_all_allowed: your diagnosis was exactly right — the mask is row-major per query row ([kv context | N block], matching the Triton row*kv_len+col reader), so the implementation layout is correct and the assertion was slicing a flat prefix. Fixed it to check the context columns per row (mask.view(n, kv+n)[:, :kv]). Local pre-commit run --files … is now green; the test fix matches what you verified (48 passed).

For context (in case anyone's landing here fresh): this PR is the GPU-independent host-side core for JetSpec tree drafting (#29524) — tree builders (opt_prefix / depth_first), the retrieve_* + tree-causal-mask buffer encoding, a CPU accept oracle, and the --speculative-dflash-tree-* flags. All CPU-unit-tested; tree mode is guarded off at startup and the chain path is byte-identical, so it's zero-risk to existing DFlash. The live dflash_worker_v2 verify-loop wiring + e2e lossless validation are the GPU follow-up, being coordinated with @vincentzed (per his note on #29524 — collaborating via Slack).

…afting

# Conflicts:
#	python/sglang/srt/arg_groups/speculative_hook.py
efschu pushed a commit to efschu/htsglang that referenced this pull request Jul 26, 2026
… group collective

Found by booting it: Nordstern L0 S4 (TP=5 over two hosts, EAGLE3, solo draft
placement, --disable-cuda-graph). Ranks 1-4 reached "Tree cache initialized"
and started their health checks; rank 0 went silent for 8 minutes until the
launcher killed it. py-spy on the solo rank:

    all_gather_object (distributed_c10d.py)
    _harmonize_cuda_graph_plan (model_runner.py:1098)
    init_cuda_graphs (model_runner.py) <- tp_worker <- eagle_worker_v2

Under --speculative-draft-placement solo only the solo rank owns a real draft
runner; the shadow ranks get a stub (install_shadow_draft_runner_surface) and
never call init_cuda_graphs on it. The harmonisation's all_gather_object is
group-wide, so the solo rank entered a collective no other rank would ever
join. This is independent of nnodes -- it is a property of solo placement.

Fix: skip the harmonisation when spec_solo_rank_local_graphs is set. That flag
already declares exactly this ("this runner's graphs are captured rank-locally,
the shadow ranks skip draft capture entirely") and already suppresses the
capture backends' per-warmup TP barrier; the harmonisation is a second group
collective in the same category. It also MUTATES the shared cuda_graph_config,
so letting the draft runner harmonise could disable a phase for the target
runner too.

Also in this commit, from the same window:

* sgl-project#76 GUARD HARDENED (sgl-project#98 sighting). The trigger is no longer "topk > 1" but
  "anything that would activate a tree-masked verify", via the new
  ServerArgs.tree_verify_activation_reason(). Upstream carries three
  unconsolidated PRs (sgl-project#31069/sgl-project#29587/sgl-project#29907) adding
  --speculative-dflash-tree-verify, a SECOND door onto the terrain sgl-project#76 fenced
  off. It does not exist here yet, so it is read with getattr: the guard is
  armed for its arrival instead of waiting to be remembered during a merge.
  The refusal is not theoretical -- see the byte-gate numbers below.
* l0_rank.sh: --max-total-tokens is now optional (MAXTOK=0 leaves the KV pool
  uncapped) because a tok/s number without the context it was reached at is not
  a result (harness rule sgl-project#4).
* l0_launch.sh: forward MAXTOK/MEMFRAC/EXTRA to the second host. They were not
  forwarded, so MAXTOK=0 applied to the main rig only: rank 0 sized its pool to
  133802 tokens while ranks 3/4 silently kept the 2048 default. A capacity
  number measured that way means nothing.

TESTED

CPU: test_uneven_tp_args.py -- 13 passed (TreeSpec*), both directions. The new
flag is rejected under uneven DCP WITH topk=1 (i.e. exactly the case the old
guard would have let through), the healthy path (chain, no tree verify) stays
open with the flag false AND with it absent, the original topk door still
rejects, the message names which flag tripped it, and a single-GPU tree run is
untouched. Full suites: server_args + spec kernel backend -- 271 passed.

GPU, RTX 5090, byte gate step 1 (native sgl_kernel vs Triton spec kernels,
identical inputs, bit comparison of every output tensor of build and verify):
  topk=1 chains  16/16 EXACT   (bs 1-2, steps 2-3, FULL_MASK and QLEN_ONLY)
  topk=2,4 trees 8/32 exact -- tree_mask differs by 6-13 elements, and one
                 case raised a CUDA error inside the Triton kernel
So the group-decision's refusal of topk>1 on the Triton path is now measured,
not precautionary, and this guard's subject matter is the same computation.

GPU, five ranks, both hosts (Llama-3.1-8B fp16, ratio 4,3,3,2,1, ctx 2048,
eager, HTCCL/gloo): S4 (solo) and S3 (split) BOTH BOOT AND SERVE after this
fix. That is the first live proof of the narrowed nnodes gate (f34a343) and
of the capability-keyed spec kernels (4bcb310) -- ranks 3 and 4 have no
sgl_kernel, so the group ran the Triton path end to end.
@github-actions

Copy link
Copy Markdown
Contributor

Thanks @ajinkyajawale14499. Closing this because it is still a draft and has not been updated in 77 days.

Reopen it if the work is still relevant.

Some directories moved recently, so an older branch may need retargeting:
sgl-kernel/ -> python/sglang/kernels/aot/, python/sglang/jit_kernel/
-> python/sglang/kernels/jit/, docs/ -> docs/docs/ (.mdx),
bench_serving.py -> benchmark/serving.py, test/srt/ -> test/registered/.

@github-actions github-actions Bot closed this Sep 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants