Repository navigation
[Speculative] DFlash tree drafting: host-side tree-construction core (#29524) - #29587
ajinkyajawale14499 wants to merge 6 commits into
Conversation
There was a problem hiding this comment.
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.
|
Thanks for the review — all three items addressed:
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).
da095de to
9adf4da
Compare
|
I took a pass over draft head Two things look actionable before the GPU follow-up:
For the mask failure, the generated mask for 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 (
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.
|
Pushed
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 ( |
…afting # Conflicts: # python/sglang/srt/arg_groups/speculative_hook.py
… 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.
|
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: |
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):
(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_siblingleft-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 abuild_treedispatcher (caps fan-out totree_width).tree_to_verify_buffers— tree → SGLang verify buffers (retrieve_next_token/retrieve_next_siblingwith the-1sentinel,positions, padded to budget).build_tree_custom_mask/build_ancestor_mask— tree-causal mask in the existing flattenedΣkv·N + N²·bslayout.compute_tree_budget,DFlashDraftTree(msgspec.Struct), andverify_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_treerejects--speculative-dflash-tree-width > 1at 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 existingtopk/custom_maskfields) andbuild_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:
verify_tree_greedy/tree_speculative_sampling_target_only), notbuild_tree_kernel_efficient— a best-first tree is general and doesn't fit EAGLE's per-step beamparent_listformat, whereas the verify kernels consume our hand-builtretrieve_*+custom_maskdirectly. No new kernels.tree_width == 1is byte-identical to the current chain buffers (retrieve_next_token = t→t+1, last-1;retrieve_next_siblingall-1) — asserted in a test against the actual_get_or_create_chain_verify_buffers. Existing DFlash users are unaffected.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); plustrtllm_mha/flashinfertree-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):
verify_tree_greedytraversal (followretrieve_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._get_or_create_chain_verify_buffers).The end-to-end lossless-greedy accuracy test — tree-spec output token-identical to non-spec decode on
triton/fa3withJetSpec/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
test/registered/spec/dflash/).--helpand marked inert/guarded).References
Jet-Flow/vllm-jetspec· Draft heads: https://huggingface.co/JetSpecResolves part of #29524.
CI States
Latest PR Test (Base): ❌ Run #28689534811
Latest PR Test (Extra): ❌ Run #28689534729