Repository navigation
Add DDTree speculative decoding - #29907
AllenFeiZZ wants to merge 6 commits into
Conversation
|
Warning You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again! |
| bs = len(batch.reqs) | ||
| device = batch.device | ||
|
|
||
| target_predict = torch.argmax(logits_output.next_token_logits, dim=-1) |
There was a problem hiding this comment.
This makes DDTree verification greedy-only, but the scheduler currently reuses the DFLASH request validator and does not reject normal sampling requests. With default sampling params (temperature=1, top_k=TOP_K_ALL), DDTree will silently return greedy tokens instead of honoring temperature/top-p/top-k/repetition/logit-bias behavior. Please either implement the sampling/rejection path for DDTree, or add a DDTree-specific validator that rejects any non-greedy sampling params with an explicit error.
| return | ||
|
|
||
| # --- 4) Full tree path (budget > L): compute logits, beam search, compile mask. --- | ||
| draft_logits = self._compute_draft_logits( |
There was a problem hiding this comment.
In full-tree mode this tensor is later top-k'd by build_ddtree_tree, but _compute_draft_logits does not preserve real vocab IDs under TP>1. The TP path concatenates rank-local/padded shard columns, so top-k indices become shard/padding positions rather than global token IDs; it also has a suspicious broadcast in global_logits / global_sum.unsqueeze(-1) that can change the returned shape. The PR only validates TP=1, so TP>1 can build trees with wrong token IDs or malformed logits. Please reuse/port the DFLASH vocab-parallel sampler mapping, or gather (score, global_token_id) candidates per rank and test TP>1.
| # DDTree currently uses the non-overlap worker path. | ||
| server_args.disable_overlap_schedule = True | ||
|
|
||
| block_size = server_args.speculative_num_draft_tokens |
There was a problem hiding this comment.
When speculative_ddtree_budget > block_size - 1, the target verify path forwards tree_budget + 1 tokens per request, but the global sizing helpers still key off speculative_num_draft_tokens/block_size. That under-reserves req_to_token headroom, KV/decode allocation, SWA capacity, and MoE token buffers for configs like the benchmarked block_size=16, budget=32. Please add a single DDTree effective-token helper, e.g. max(block_size, speculative_ddtree_budget + 1), and use it in the server/memory sizing paths.
| max_extend_len = None | ||
| elif forward_batch.forward_mode.is_target_verify(): | ||
| bs = len(forward_batch.req_pool_indices) | ||
| # DDTree full-tree verifies budget+1 tokens (> block_size); use the |
There was a problem hiding this comment.
This dynamic draft_token_num handling fixes the Triton target-verify path, but DDTree full-tree is not guarded to Triton. Other target-verify backends still assume server_args.speculative_num_draft_tokens in their masks/QO indptr/max query lengths, so budget > block_size - 1 can hit shape mismatches or wrong masks when SGLang auto-selects FlashAttention/DSA/FlashMLA/XPU/TRTLLM. Please either plumb spec_info.draft_token_num through all supported backends, or reject unsupported attention backends at startup with an explicit DDTree error.
| self.model_runner.spec_algorithm.is_dflash() | ||
| ( | ||
| self.model_runner.spec_algorithm.is_dflash() | ||
| or self.model_runner.spec_algorithm.is_ddtree() |
There was a problem hiding this comment.
This adds DDTree to the load_batch token-count path, but can_run_graph() still omits is_ddtree() in the require_mlp_tp_gather branch. For DDTree full-tree, that branch compares max(global_num_tokens_cpu) as if it were batch size instead of dividing by self.num_tokens_per_bs, so graph eligibility/bucketing can be wrong. Please add the same DDTree condition there as well.
| # movement (works on hybrid Mamba models; Mamba state is committed | ||
| # separately by the worker). Only page_size==1 is supported for now. --- | ||
| if model_runner is not None: | ||
| assert page_size == 1, "DDTREE full-tree currently supports page_size==1" |
There was a problem hiding this comment.
If DDTree only supports page_size == 1, this should fail during server argument validation rather than asserting on the first verify request. As written, --page-size > 1 can start successfully and then crash at runtime after verify allocation/state mutation begins. Please either implement the paged KV path or reject this configuration in _handle_ddtree with a clear error.
|
Thanks for the review! I pushed an update in
Validation done locally with the NVFP4 model:
|
| # same accept order as accept_index_flat (= concatenation per req). | ||
| hidden = logits_output.hidden_states | ||
| if hidden is not None: | ||
| next_target_hidden = hidden[self.accept_index_flat] |
There was a problem hiding this comment.
This only reorders the accepted hidden states for the next draft step; the logits_output.hidden_states returned to the scheduler stays in raw tree-slot order. When a request asks for return_hidden_states, batch_result_processor slices by i * speculative_num_draft_tokens, so a branching accepted path like slots [0, 3] returns hidden rows [0, 1]. Please either reject return_hidden_states for DDTree or reorder/pad logits_output.hidden_states to the same per-request emitted-token stride as accepted_tokens.
| server_args.disable_overlap_schedule = True | ||
|
|
||
| block_size = server_args.speculative_num_draft_tokens | ||
| is_full_tree = server_args.speculative_ddtree_budget > block_size - 1 |
There was a problem hiding this comment.
This guard misses the smaller-spine case where speculative_ddtree_budget + 1 < speculative_num_draft_tokens. DDTree then verifies fewer tokens than the block size, but non-Triton target-verify backends such as FlashAttention/TRTLLM still size metadata from server_args.speculative_num_draft_tokens, so block=16,budget=8 can build mismatched QO/mask shapes. Please guard whenever budget + 1 != block_size, or plumb spec_info.draft_token_num through every allowed backend.
| if self.scheduler.server_args.max_speculative_num_draft_tokens: | ||
| draft_per_round = ( | ||
| self.scheduler.server_args.speculative_num_draft_tokens - 1 | ||
| self.scheduler.server_args.max_speculative_num_draft_tokens - 1 |
There was a problem hiding this comment.
max_speculative_num_draft_tokens is a capacity bound, not the number of draft tokens DDTree actually proposes. For block=16,budget=8 this denominator becomes 15 while each verify round only proposes 8 draft nodes, so the reported accept rate is undercounted. Please use the runtime result.speculative_num_draft_tokens - 1 / DDTree budget for metrics denominators, and mirror that in the per-request metadata path.
|
Why TPS mean becomes smaller after using DDTree? |
| ) | ||
|
|
||
| # --- 2) Draft a non-causal block (reuse parent's shared implementation). | ||
| draft_hidden, positions_2d, block_ids = self._run_draft_forward( |
There was a problem hiding this comment.
This still drafts a full block_size block even when speculative_ddtree_budget < block_size - 1 and the later verify path truncates to D = budget + 1. That means a budget=8, block_size=16 run pays almost the same draft-model forward/KV allocation cost as the 16-token baseline, plus DDTree bookkeeping. If budget is meant to trade accuracy for speed, the draft forward should either run only the needed length or small-budget DDTree should route through the existing DFLASH-style path.
| ) | ||
|
|
||
| # --- 3) Spine-mode fast path: a degenerate chain tree. --- | ||
| if self.tree_budget <= self.block_size - 1: |
There was a problem hiding this comment.
The spine case is a pure linear chain, but it still builds DDTree LCRS metadata and a custom tree mask, then verifies via DDTreeVerifyInput. DFLASH's comparable path uses standard causal verify with custom_mask = None, which avoids this extra mask/topology work. This likely explains why the small/spine budgets can be slower even though they do not verify a wider tree. Please either reuse the DFLASH verify fast path for spine mode or add a benchmark showing this extra protocol cost is negligible.
| return | ||
|
|
||
| # --- 4) Full tree path (budget > L): compute logits, beam search, compile mask. --- | ||
| draft_logits = self._compute_draft_logits( |
There was a problem hiding this comment.
Full-tree construction materializes dense [bs, block_size - 1, vocab] logits before selecting a small top-k. The tree builder only needs a few candidates per depth, so this pays full-vocab bandwidth/activation memory every decode round. For TP>1 the helper also gathers/scatters dense global-vocab logits. A more serving-friendly implementation would compute top-k candidates directly from the vocab-parallel head and gather only (score, token_id) candidates.
| topk = min(max(tree_budget // max(L, 1) + 1, 2), V, _max_topk) | ||
| top_logits, top_token_ids = torch.topk(logits, k=topk, dim=-1) | ||
| log_z = torch.logsumexp(logits, dim=-1, keepdim=True) | ||
| top_log_probs = (top_logits - log_z).to(device="cpu", dtype=torch.float32) |
There was a problem hiding this comment.
This moves the per-position top-k data to CPU, then _build_single_tree uses NumPy/Python heapq per request. That creates a GPU sync in the decode hot path and serial Python work proportional to batch size and budget. This is not inherent to DDTree; the tree selection/topology build should stay on device or be implemented as a batched compiled kernel before using TPS numbers as evidence for/against the algorithm.
| batch.spec_info = verify_input | ||
| batch.return_hidden_states = False | ||
|
|
||
| def _build_flat_tree_mask(self, *, batch, visibility, actual_tree_sizes): |
There was a problem hiding this comment.
_build_flat_tree_mask does seq_lens.detach().cpu().tolist() / actual_tree_sizes.detach().cpu().tolist(), allocates one D x (prefix_len + D) tensor per request, and then concatenates. For long contexts this is O(batch * D * context_len) mask materialization plus CPU synchronization every decode step. Please preallocate/vectorize this path, or encode the tree visibility in a compact form consumed by the attention kernel.
|
|
||
| # accept_index[b]: [root_global_slot, accepted child global slots..., -1...] | ||
| # accept_length[b]: number of accepted *draft* tokens (excludes root). | ||
| accept_index_cpu = accept_index.tolist() |
There was a problem hiding this comment.
accept_index.tolist() and predict.tolist() force a device-to-host sync, then the accepted-token path is rebuilt in Python and copied back to GPU tensors below. This places result processing on the critical decode path. The accepted slots/tokens/commit lens should be produced by a device kernel, with only the final scheduler-facing D2H copy happening asynchronously like other spec-v2 workers.
| ) | ||
|
|
||
| # DDTree currently uses the non-overlap worker path. | ||
| server_args.disable_overlap_schedule = True |
There was a problem hiding this comment.
Disabling overlap scheduling makes DDTree pay all of its CPU tree-build, mask construction, verify, and draft-KV materialization costs serially in the decode loop, while the DFLASH baseline can use the optimized overlap/spec-v2 path. For the benchmark to be actionable, please either implement the overlap path for DDTree or compare against a DFLASH configuration with the same non-overlap scheduling constraints.
|
@wenqf11 Good question. I don't think the lower TPS should be attributed only to DDTree's algorithmic verify cost yet. Part of it is expected: DDTree full-tree verifies But this PR also has several implementation overheads that can depress TPS:
So the benchmark currently mixes algorithmic cost with implementation overhead. It would be useful to add a breakdown for draft forward / tree build / mask build / target verify / KV materialization, and compare against DFLASH under the same overlap/non-overlap setting. I left inline comments on the concrete hot-path locations. |
- Reject DDTree return_hidden_states until per-request hidden-state ordering is implemented (validate_dflash_request gains is_ddtree kwarg). - Guard non-Triton DDTree whenever verify_token_num != block_size (covers both full-tree and smaller-spine cases in _handle_ddtree). - Report spec accept rate from actual proposed drafts instead of max_speculative_num_draft_tokens capacity: plumb spec_num_proposed_drafts through GenerationBatchResult, Req, metrics_reporter, io_struct, output_streamer, multi_tokenizer_mixin, detokenizer_manager, and tokenizer_manager (with fallback for legacy payloads).
In upstream main, ServerArgs.page_size defaults to None and is only
resolved to 1 later in _handle_page_size(). The DDTree startup guard
was rejecting page_size != 1 unconditionally, which caused every default
DDTree launch to fail with
ValueError: DDTREE currently supports only page_size == 1.
Got page_size=None.
Allow None (means 'use default', which resolves to 1); only reject when
the user explicitly sets page_size to a value other than 1.
…nv-state regressions Sync ddtree-v2 with upstream/main: resolve conflicts, drop model_runner_kv_cache_mixin for upstream KVCacheConfigurator, and adapt DDTree to upstream API changes (ParallelState ctor, mem_cache.allocation moves, ForwardBatch.init_new kwarg, resolve_num_tokens_per_req). Fix two regressions found via pre/post-merge tensor-dump bisection: 1. SM120 NVFP4 MoE garbage output. trtllm-gen MoE is SM100-only, so upstream falls back to FLASHINFER_CUTLASS on SM120, but that runner assumes the dispatcher pre-quantizes activations to fp4 (only true under DP-attention allgather). Under tp-only serving StandardDispatcher leaves bf16 activations with scale=None, so the kernel reads garbage. Upstream also deleted the self-contained cutlass_moe_fp4 path. Restore cutlass_moe_fp4 (+ its JIT kernels) and select it unless the fp4-allgather path is active. 2. DDTree tree-branch conv-state corruption. HybridReqToTokenPool now needs tree_verify_uses_per_token_ancestors; DDTree keeps speculative_eagle_topk==1 but routes the tree-aware mamba scan, so the dedup conv-window layout silently corrupted branch conv state. Pass it as is_ddtree() in the configurator. Verified on SM120 (RTX PRO 5000) tp1 + CUDA graph: 4 real prompts produce byte-identical output vs the pre-merge baseline with matching accept length.
|
Follow-up after my last update (93e9850), addressing the review comments raised since then:
|
… 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 @AllenFeiZZ. Closing this because it has had no updates in 91 days. Reopen it if the work is still relevant. Some directories moved recently, so an older branch may need retargeting: |
Summary
This PR adds DDTree (Diffusion Draft Tree) speculative decoding support.
DDTree extends DFLASH-style draft execution with tree-based verification. Instead of verifying only a linear draft chain, DDTree can use a larger tree budget to verify multiple candidate branches and improve acceptance length. The worker uses
DFlashWorkerV2for draft-worker initialization, memory pool setup, and CUDA graph handling, while keeping a DDTree-specific non-overlap decode loop for tree construction and verification.Changes
DDTreeWorker,DDTreeDraftInput, andDDTreeVerifyInput.DDTREEas a speculative decoding algorithm.--speculative-ddtree-budget.SGLANG_DDTREE_MAX_TOPKSGLANG_DDTREE_DEPTH_BONUSSGLANG_DDTREE_RANK_PROBEdraft_token_num = ddtree_budget + 1.input_embeds.spec_info.topkand support DDTree tree topology tensors.Validation
Correctness
Tested on a hybrid GDN model with:
max_new_tokens=512max_running_requests=1Single prompt generation succeeds:
spec_accept_length = 1.8235The 40-prompt benchmark completes without scheduler exceptions or memory leak reports.
Performance
Benchmark setup:
DDTree shows clear budget scaling:
2.329to2.621(+12.5%)2.621to2.750(+4.9%)2.329to2.750(+18.1%)Compared with DFLASH block=16:
As expected, larger DDTree budgets trade additional verification work for higher acceptance length.
Contributors
Engine Architecture Group 5, Engine Infrastructure Department, Xiaohongshu (RedNote): Fei Ziyu, Luo Zhaokai, Su Zhan, Chenchen Hong, Jin Huayi.
CI States
Latest PR Test (Base): ❌ Missing
run-cilabel -- add it to run CI tests.Latest PR Test (Extra): ❌ Blocked --
run-ciis required first.