From c76710a1d44bd59786dad4e7eaa4612a01bf7c2b Mon Sep 17 00:00:00 2001 From: weireweire <20922698+weireweire@users.noreply.github.com> Date: Fri, 23 Oct 2026 18:11:55 +0800 Subject: [PATCH 1/4] feat(agentx): run GB300 DSV4.1-Flash agg TP4 c1 as a batch-1 NVIDIA megakernel point MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root cause: the TP4 c1 aggregated point ran the October 15 image without the megakernel. The batch-1 megakernel recipe (sglang#45450 decode-graph gates, 42 kernel slots, max-running-requests and decode graph batch 1) needs #45450, which no public nightly ships yet. It also needs an sgl-nvidia-mega newer than the image's Dockerfile pin d47deb33, which fails on c1c287a4 after sglang#45112 and #44912. Fix: move the aggregated row to nightly-dev-cu13-20261021-c1c287a4 with the ai-dynamo 1.6.0.dev20261019 it ships. Port the strict batch-1 launcher env and args into override_tp4_c1. Its setup_script applies the merged #45450 backported to c1c287a4 and checks out sgl-nvidia-mega 3333e4cf. The waiver is in docs/waiver. Only c1 runs the setup script. c1 also sets kv-cache-dtype fp8_e4m3 and SGLANG_SPEC_TP_SYNC as in the reference BS1 recipe, mem-fraction-static 0.91 (the reference launch's resolved default), and drops cuda-graph-backend-prefill (the image default disables the prefill graph for DeepSeek-V4). The c4/c16 and TP2 c16 args are unchanged. They run the image as shipped and were not rerun on c1c287a4; the CI sweep is their first run. The changelog entry also lists the unchanged disaggregated key so the curve is swept together. Validation: a plain SGLang reproduction of the same launcher on c1c287a4 + pre-merge #45450 (4e76b879) + 3333e4cf, AgentX c1 3600 s, measured 481 requests with 0 errors. P50/P90 interactivity was 991.7/965.0 tok/s/user, P90 TTFT 0.199 s, 8314.5 tok/s/GPU. The Dynamo recipe itself (bound override_tp4_c1, srt-slurm ae3d6877, setup script) measured 473 requests with 0 errors: P50/P90 interactivity 984.0/941.4, P90 TTFT 0.286 s, 8276.9 tok/s/GPU, median decode step 3.55 ms (plain 3.54 ms). On a CPU node the backport applies idempotently and its modules import. 根因:聚合 TP4 c1 点使用 10 月 15 日镜像且未启用 megakernel。batch-1 megakernel 配方需要 #45450(尚无公开 nightly 包含),且需要比镜像 Dockerfile 固定的 d47deb33 更新的 sgl-nvidia-mega;d47deb33 在 c1c287a4(已含 sglang#45112、#44912)上无法运行。 修复:聚合配置迁移到 nightly-dev-cu13-20261021-c1c287a4 及其自带的 ai-dynamo 1.6.0.dev20261019。将严格 batch-1 启动参数与环境变量移植到 override_tp4_c1。其 setup_script 应用回移到 c1c287a4 的已合并 #45450, 并检出 sgl-nvidia-mega 3333e4cf,豁免说明见 docs/waiver。c4/c16 与 TP2 c16 参数不变,按原镜像运行,未在 c1c287a4 上重新运行,CI sweep 是其首次运行。只有 c1 运行 setup 脚本。c1 另设 kv-cache-dtype fp8_e4m3 与 SGLANG_SPEC_TP_SYNC(同参考 BS1 配方)、mem-fraction-static 0.91(参考启动默认解析值),并移除 cuda-graph-backend-prefill(镜像默认对 DeepSeek-V4 关闭 prefill graph)。 changelog 条目同时列出未改动的分离式配置,使整条曲线一起测试。 验证:同一启动器的纯 SGLang 复现(c1c287a4 + 合并前 #45450 (4e76b879) + 3333e4cf,AgentX c1 3600 秒)完成 481 个请求、0 错误。P50/P90 交互性 为 991.7/965.0 tok/s/user,P90 TTFT 0.199 秒,8314.5 tok/s/GPU。Dynamo 配方 本身(绑定后的 override_tp4_c1,srt-slurm ae3d6877,setup 脚本)完成 473 个 请求、0 错误:P50/P90 交互性 984.0/941.4,P90 TTFT 0.286 秒,8276.9 tok/s/GPU,decode step 中位数 3.55 ms(纯 SGLang 3.54 ms)。在 CPU 节点上, 回移补丁可幂等应用,相关模块均可导入。 --- .../configs/dsv41flash-sglang-patches.sh | 43 + .../sglang-pr45450.patch | 4936 +++++++++++++++++ .../sglang/gb300-fp4/agentx/agg-variants.yaml | 47 +- inferencex-e2e/configs/nvidia-master.yaml | 4 +- inferencex-e2e/docs/waiver/XXXX.md | 42 + inferencex-e2e/perf-changelog.yaml | 13 + 6 files changed, 5078 insertions(+), 7 deletions(-) create mode 100755 inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh create mode 100644 inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches/sglang-pr45450.patch create mode 100644 inferencex-e2e/docs/waiver/XXXX.md diff --git a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh new file mode 100755 index 0000000000..21cd34b24a --- /dev/null +++ b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# sglang#45450 and sgl-nvidia-mega 3333e4cf for the October 21 nightly; see docs/waiver. +set -eo pipefail + +sglang_root=/sgl-workspace/sglang +mega_root=/sgl-workspace/sgl-nvidia-mega +mega_repo=https://github.com/sgl-project/sgl-nvidia-mega.git +mega_commit=3333e4cfac0f2b15603565d702b4c67538f1628f +patch_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/dsv41flash-sglang-patches" +patches=( + sglang-pr45450.patch +) + +origin=$(python3 -c 'import importlib.util; print(importlib.util.find_spec("sglang").origin)') +if [[ "$origin" != "$sglang_root/python/sglang/__init__.py" ]]; then + echo "sglang imports from $origin, not the editable checkout in $sglang_root" >&2 + exit 1 +fi +mega_origin=$(python3 -c 'import importlib.util; print(importlib.util.find_spec("sgl_nvidia_mega").origin)') +if [[ "$mega_origin" != "$mega_root/sgl_nvidia_mega/__init__.py" ]]; then + echo "sgl_nvidia_mega imports from $mega_origin, not the editable checkout in $mega_root" >&2 + exit 1 +fi + +# Workers sharing a node and container must not patch the tree concurrently. +exec 9<"$sglang_root" +flock 9 +cd / +for name in "${patches[@]}"; do + patch="$patch_dir/$name" + if git apply --directory="${sglang_root#/}" --reverse --check "$patch" 2>/dev/null; then + echo "SGLang patch $name: already applied" + else + git apply --directory="${sglang_root#/}" --verbose "$patch" + echo "SGLang patch $name: applied" + fi +done + +if [[ "$(git -C "$mega_root" rev-parse HEAD)" != "$mega_commit" ]]; then + git -C "$mega_root" fetch --quiet --depth 1 "$mega_repo" "$mega_commit" + git -C "$mega_root" checkout --quiet --force "$mega_commit" +fi +echo "sgl-nvidia-mega: $(git -C "$mega_root" rev-parse HEAD)" diff --git a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches/sglang-pr45450.patch b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches/sglang-pr45450.patch new file mode 100644 index 0000000000..7c0880935e --- /dev/null +++ b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches/sglang-pr45450.patch @@ -0,0 +1,4936 @@ +diff --git a/python/sglang/kernels/ops/embeddings/engram_hash.py b/python/sglang/kernels/ops/embeddings/engram_hash.py +index deb58658f7..65a3d9e6f2 100644 +--- a/python/sglang/kernels/ops/embeddings/engram_hash.py ++++ b/python/sglang/kernels/ops/embeddings/engram_hash.py +@@ -28,12 +28,19 @@ def _engram_commit_history_kernel( + tokens_ptr, + slots_ptr, + commit_ptr, ++ live_ptr, ++ gate_ptr, + HISTORY_STRIDE: tl.constexpr, + HISTORY_WIDTH: tl.constexpr, + TOKEN_STRIDE: tl.constexpr, + BLOCK: tl.constexpr, ++ GATED: tl.constexpr, + ): + row = tl.program_id(0) ++ if GATED: ++ # Captured rows past the live batch, or a step the graph does not commit. ++ if (tl.load(live_ptr + row) == 0) | (tl.load(gate_ptr) == 0): ++ return + slot = tl.load(slots_ptr + row).to(tl.int64) + commit = tl.load(commit_ptr + row) + col = tl.arange(0, BLOCK) +@@ -60,8 +67,11 @@ def engram_commit_history( + verify_ids: torch.Tensor, + req_slots: torch.Tensor, + commit_lens: torch.Tensor, ++ live_rows: Optional[torch.Tensor] = None, ++ gate: Optional[torch.Tensor] = None, + ) -> None: +- """Update distinct live request slots with anchor + correct drafts, not bonus.""" ++ """Update distinct live request slots with anchor + correct drafts, not bonus. ++ Skips rows whose ``live_rows`` entry is 0, and all rows when ``gate[0]`` is 0.""" + bs = req_slots.numel() + width = history.shape[1] + if bs == 0 or width == 0: +@@ -73,10 +83,13 @@ def engram_commit_history( + verify_ids, + req_slots, + commit_lens, ++ live_rows if live_rows is not None else commit_lens, ++ gate if gate is not None else commit_lens, + HISTORY_STRIDE=history.stride(0), + HISTORY_WIDTH=width, + TOKEN_STRIDE=verify_ids.stride(0), + BLOCK=triton.next_power_of_2(width), ++ GATED=live_rows is not None, + num_warps=4, + ) + +diff --git a/python/sglang/kernels/ops/speculative/cache_locs.py b/python/sglang/kernels/ops/speculative/cache_locs.py +index a93975e392..cc11b56cb3 100644 +--- a/python/sglang/kernels/ops/speculative/cache_locs.py ++++ b/python/sglang/kernels/ops/speculative/cache_locs.py +@@ -627,6 +627,10 @@ def assign_extend_cache_locs_uniform( + PAGE_SIZE: tl.constexpr = 1, + num_v_pages=0, + num_swa_pages=0, ++ positions_out=None, ++ anchor_src=None, ++ anchor_out=None, ++ anchor_stride=0, + ): + """Uniform-length variant of assign_extend_cache_locs: every row extends + exactly draft_token_num tokens, so the end offset is start + +@@ -637,6 +641,8 @@ def assign_extend_cache_locs_uniform( + kv_start = tl.load(start_offset + pid) + token_pool = req_to_token + tl.load(req_pool_indices + pid) * pool_len + out_cache_ptr = out_cache_loc + pid * draft_token_num ++ if anchor_out is not None: ++ tl.store(anchor_out + pid * anchor_stride, tl.load(anchor_src + pid)) + + offs = tl.arange(0, BLOCK_SIZE) + num_loop = tl.cdiv(draft_token_num, BLOCK_SIZE) +@@ -645,6 +651,12 @@ def assign_extend_cache_locs_uniform( + mask = o < draft_token_num + data = tl.load(token_pool + kv_start + o, mask=mask) + tl.store(out_cache_ptr + o, data, mask=mask) ++ if positions_out is not None: ++ tl.store( ++ positions_out + pid * draft_token_num + o, ++ kv_start.to(tl.int64) + o, ++ mask=mask, ++ ) + if full_v2p is not None: + page = data // PAGE_SIZE + valid = mask & (data >= 0) & (page < num_v_pages) +@@ -675,6 +687,9 @@ def assign_extend_cache_locs_uniform_func( + full_out: Optional[torch.Tensor] = None, + swa_out: Optional[torch.Tensor] = None, + page_size: int = 1, ++ positions_out: Optional[torch.Tensor] = None, ++ anchor_src: Optional[torch.Tensor] = None, ++ anchor_out: Optional[torch.Tensor] = None, + ) -> torch.Tensor: + """assign_extend_cache_locs for the uniform case (all rows extend exactly + draft_token_num tokens, e.g. spec target-verify prep). Computes end +@@ -683,6 +698,8 @@ def assign_extend_cache_locs_uniform_func( + and SWA write windows in the same launch; the returned ids stay virtual. + Mapping tables and output buffers must be contiguous, with one output + per gathered token. Translation is rank-local (no DCP widening). ++ ``positions_out`` ([batch, draft_token_num] int64) gets start + column and ++ ``anchor_out[:, 0]`` gets ``anchor_src``, in the same launch. + """ + if full_v2p is not None: + assert full_out is not None and full_out.numel() == batch_size * draft_token_num +@@ -713,11 +730,22 @@ def assign_extend_cache_locs_uniform_func( + PAGE_SIZE=page_size, + num_v_pages=0 if full_v2p is None else full_v2p.numel(), + num_swa_pages=0 if swa_v2p is None else swa_v2p.numel(), ++ positions_out=positions_out, ++ anchor_src=anchor_src, ++ anchor_out=anchor_out, ++ anchor_stride=0 if anchor_out is None else anchor_out.stride(0), + ) + return out_cache_loc + + # NPU / CPU platforms: fall back to the end_offset-tensor path. + assert full_v2p is None, "fused write translation requires a Triton device" ++ if positions_out is not None: ++ positions_out.copy_( ++ start_offset.to(torch.int64).view(-1, 1) ++ + torch.arange(draft_token_num, device=start_offset.device) ++ ) ++ if anchor_out is not None: ++ anchor_out[:, 0].copy_(anchor_src.view(-1)) + return assign_extend_cache_locs_func( + req_pool_indices=req_pool_indices, + req_to_token=req_to_token, +diff --git a/python/sglang/kernels/ops/speculative/dspark/blockwise_rejection.py b/python/sglang/kernels/ops/speculative/dspark/blockwise_rejection.py +new file mode 100644 +index 0000000000..10c93570a9 +--- /dev/null ++++ b/python/sglang/kernels/ops/speculative/dspark/blockwise_rejection.py +@@ -0,0 +1,551 @@ ++"""Block-wise rejection sampling of a DSpark verify chain (SGLANG_OPT_DSV41_BLOCKWISE_REJECTION). ++ ++Classic chain verification only. It replaces the draft / target softmax writes and the ++single-CTA ``speculative_sampling_classic_kernel``: ++ ++1. per-vocab-block target / draft max and sum-exp (rows x 8,192-token blocks), no ++ probability tensors; ++2. a one-warp accept per request that reads only those stats plus the draft token's ++ logits: accept iff ``log p(x) > log u + log q(x)``, i.e. ``u * q < p`` as before; ++3. a block-parallel Gumbel-max resample of the rejected row's residual ++ ``max(p - q, 0)`` (or of ``p`` at the bonus row), reduced by a one-program insert. ++ ++The draws are counter-based: a request row's accept coins and its resample noise are ++functions of (server key, a device step counter, row, token). Every TP rank holds the ++same key, counter and logits, so ranks agree without a broadcast, and a CUDA graph ++replay advances the counter like an eager call. Distributions are those of the classic ++kernel; only the random stream differs. ++""" ++ ++from __future__ import annotations ++ ++from typing import Optional ++ ++import msgspec ++import torch ++import triton ++import triton.language as tl ++from triton.language.extra import libdevice ++ ++from sglang.kernels.ops.speculative.dspark.dispatch import inputs_on_cuda ++ ++# XORed into the server seed so the rejection draws differ from other samplers'. ++_REJECTION_NOISE_DOMAIN = 0x5B1E3C7A9D2F4E61 ++# Odd multiplier mixing the step counter into the per-step seed. ++_STEP_SEED_MULT = tl.constexpr(0x632BE59BD9B4E019) ++# Smallest positive fp32 value of tl.rand; coins stay in (0, 1). ++_TL_RAND_MIN = tl.constexpr(4.6566127342e-10) ++_STATS_BLOCK = 8192 ++_RESAMPLE_BLOCK = 1024 ++ ++ ++class RejectionNoise(msgspec.Struct, frozen=True): ++ """Key of the rejection draws, and a device step counter each call advances.""" ++ ++ key: int ++ counter: torch.Tensor ++ ++ ++def rejection_noise_key(random_seed: int) -> int: ++ return (int(random_seed) ^ _REJECTION_NOISE_DOMAIN) & 0x7FFFFFFFFFFFFFFF ++ ++ ++def make_rejection_noise(random_seed: int, device) -> RejectionNoise: ++ return RejectionNoise( ++ key=rejection_noise_key(random_seed), ++ counter=torch.zeros(1, dtype=torch.int64, device=device), ++ ) ++ ++ ++@triton.jit ++def _step_seed(key, counter_ptr): ++ return key + tl.load(counter_ptr) * _STEP_SEED_MULT ++ ++ ++@triton.jit ++def _rotl32(value, shift: tl.constexpr): ++ return (value << shift) | (value >> (32 - shift)) ++ ++ ++@triton.jit ++def _murmur3_mix(h, key): ++ key *= 0xCC9E2D51 ++ key = _rotl32(key, 15) ++ key *= 0x1B873593 ++ h ^= key ++ h = _rotl32(h, 13) ++ return h * 5 + 0xE6546B64 ++ ++ ++@triton.jit ++def _murmur3_uniform32(seed, pos, offset): ++ seed = seed.to(tl.int64) ++ pos = pos.to(tl.int64) ++ offset = offset.to(tl.uint32) ++ h = (seed ^ seed).to(tl.uint32) ++ h = _murmur3_mix(h, (seed & 0xFFFFFFFF).to(tl.uint32)) ++ h = _murmur3_mix(h, ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)) ++ h = _murmur3_mix(h, (pos & 0xFFFFFFFF).to(tl.uint32)) ++ h = _murmur3_mix(h, offset) ++ h ^= 16 ++ h ^= h >> 16 ++ h *= 0x85EBCA6B ++ h ^= h >> 13 ++ h *= 0xC2B2AE35 ++ h ^= h >> 16 ++ # Both 16-bit halves convert exactly: (h + 0.5) * 2**-32 keeps the u -> 0 tail. ++ hi16 = (h >> 16).to(tl.int32) ++ lo16 = (h & 0xFFFF).to(tl.int32) ++ return ( ++ hi16.to(tl.float32) * 1.52587890625e-05 ++ + (lo16.to(tl.float32) + 0.5) * 2.3283064365386963e-10 ++ ) ++ ++ ++@triton.jit ++def _log1p_neg_stable(value): ++ # log(1 - value): series below 0.25 (abs error < 6e-7), direct above. ++ polynomial = 1.0 / 8.0 ++ polynomial = 1.0 / 7.0 + value * polynomial ++ polynomial = 1.0 / 6.0 + value * polynomial ++ polynomial = 1.0 / 5.0 + value * polynomial ++ polynomial = 1.0 / 4.0 + value * polynomial ++ polynomial = 1.0 / 3.0 + value * polynomial ++ polynomial = 1.0 / 2.0 + value * polynomial ++ polynomial = 1.0 + value * polynomial ++ series = -value * polynomial ++ direct = tl.log(tl.maximum(1.0 - value, 5.960464477539063e-08)) ++ return tl.where(value < 0.25, series, direct) ++ ++ ++@triton.jit ++def _global_lse( ++ max_ptr, sumexp_ptr, row, NUM_BLOCKS: tl.constexpr, PADDED: tl.constexpr ++): ++ blocks = tl.arange(0, PADDED) ++ mask = blocks < NUM_BLOCKS ++ maxes = tl.load(max_ptr + row * NUM_BLOCKS + blocks, mask=mask, other=float("-inf")) ++ sumexps = tl.load(sumexp_ptr + row * NUM_BLOCKS + blocks, mask=mask, other=0.0) ++ global_max = tl.max(maxes, axis=0) ++ return global_max + tl.log(tl.sum(sumexps * tl.exp(maxes - global_max))) ++ ++ ++@triton.jit ++def _stats_kernel( ++ t_max_ptr, ++ t_sumexp_ptr, ++ d_max_ptr, ++ d_sumexp_ptr, ++ target_logits_ptr, ++ target_stride, ++ draft_logits_ptr, ++ draft_stride_0, ++ draft_stride_1, ++ target_temp_ptr, ++ draft_temp_ptr, ++ target_vocab, ++ draft_vocab, ++ STRIDE: tl.constexpr, ++ NUM_BLOCKS: tl.constexpr, ++ BLOCK: tl.constexpr, ++ HAS_DRAFT_LOGITS: tl.constexpr, ++): ++ row = tl.program_id(0).to(tl.int64) ++ req = row // STRIDE ++ step = row % STRIDE ++ if step == STRIDE - 1: ++ # Bonus row: its resample reads raw logits, no stats. ++ return ++ block_idx = tl.program_id(1) ++ offs = block_idx * BLOCK + tl.arange(0, BLOCK) ++ t_temp = tl.load(target_temp_ptr + req).to(tl.float32) ++ t = ( ++ tl.load( ++ target_logits_ptr + row * target_stride + offs, ++ mask=offs < target_vocab, ++ other=float("-inf"), ++ ).to(tl.float32) ++ / t_temp ++ ) ++ t_max = tl.max(t, axis=0) ++ tl.store(t_max_ptr + row * NUM_BLOCKS + block_idx, t_max) ++ tl.store( ++ t_sumexp_ptr + row * NUM_BLOCKS + block_idx, ++ tl.where(t_max > float("-inf"), tl.sum(tl.exp(t - t_max)), 0.0), ++ ) ++ if HAS_DRAFT_LOGITS: ++ d_temp = tl.load(draft_temp_ptr + req).to(tl.float32) ++ d = ( ++ tl.load( ++ draft_logits_ptr + req * draft_stride_0 + step * draft_stride_1 + offs, ++ mask=offs < draft_vocab, ++ other=float("-inf"), ++ ).to(tl.float32) ++ / d_temp ++ ) ++ d_max = tl.max(d, axis=0) ++ tl.store(d_max_ptr + row * NUM_BLOCKS + block_idx, d_max) ++ tl.store( ++ d_sumexp_ptr + row * NUM_BLOCKS + block_idx, ++ tl.where(d_max > float("-inf"), tl.sum(tl.exp(d - d_max)), 0.0), ++ ) ++ ++ ++@triton.jit ++def _rejection_kernel( ++ correct_len_ptr, ++ raw_len_ptr, ++ trim_ptr, ++ rej_lse_ptr, ++ candidates_ptr, ++ candidates_stride, ++ verify_lens_ptr, ++ t_max_ptr, ++ t_sumexp_ptr, ++ d_max_ptr, ++ d_sumexp_ptr, ++ target_logits_ptr, ++ target_stride, ++ draft_logits_ptr, ++ draft_stride_0, ++ draft_stride_1, ++ target_temp_ptr, ++ draft_temp_ptr, ++ target_vocab, ++ draft_vocab, ++ bs, ++ key, ++ counter_ptr, ++ STRIDE: tl.constexpr, ++ NUM_BLOCKS: tl.constexpr, ++ PADDED_BLOCKS: tl.constexpr, ++ HAS_DRAFT_LOGITS: tl.constexpr, ++ HAS_CUTOFF: tl.constexpr, ++): ++ req = tl.program_id(0).to(tl.int64) ++ seed = _step_seed(key, counter_ptr) ++ t_temp = tl.load(target_temp_ptr + req).to(tl.float32) ++ d_temp = 1.0 ++ if HAS_DRAFT_LOGITS: ++ d_temp = tl.load(draft_temp_ptr + req).to(tl.float32) ++ accepted = tl.zeros((), tl.int32) ++ verifying = True ++ for i in range(STRIDE - 1): ++ if verifying: ++ row = req * STRIDE + i ++ token = tl.load(candidates_ptr + req * candidates_stride + i + 1).to( ++ tl.int64 ++ ) ++ valid = (token >= 0) & (token < target_vocab) ++ token = tl.minimum(tl.maximum(token, 0), target_vocab - 1) ++ t_lse = _global_lse(t_max_ptr, t_sumexp_ptr, row, NUM_BLOCKS, PADDED_BLOCKS) ++ log_p = ( ++ tl.load(target_logits_ptr + row * target_stride + token).to(tl.float32) ++ / t_temp ++ - t_lse ++ ) ++ log_q = 0.0 ++ if HAS_DRAFT_LOGITS: ++ d_lse = _global_lse( ++ d_max_ptr, d_sumexp_ptr, row, NUM_BLOCKS, PADDED_BLOCKS ++ ) ++ log_q = ( ++ tl.load( ++ draft_logits_ptr ++ + req * draft_stride_0 ++ + i * draft_stride_1 ++ + token, ++ mask=token < draft_vocab, ++ other=float("-inf"), ++ ).to(tl.float32) ++ / d_temp ++ - d_lse ++ ) ++ u = tl.maximum(tl.rand(seed, (req * STRIDE + i).to(tl.int32)), _TL_RAND_MIN) ++ # A proposal must have positive draft probability (classic kernel's guard). ++ ok = valid & (log_q > float("-inf")) & (log_p > tl.log(u) + log_q) ++ verifying = ok ++ accepted += ok.to(tl.int32) ++ tl.store(raw_len_ptr + req, accepted) ++ capped = accepted ++ if HAS_CUTOFF: ++ cap = tl.load(verify_lens_ptr + req).to(tl.int32) - 1 ++ capped = tl.minimum(accepted, cap) ++ tl.store(correct_len_ptr + req, capped) ++ tl.store(trim_ptr + req, accepted - capped) ++ t_lse_rej = 0.0 ++ d_lse_rej = 0.0 ++ if accepted < STRIDE - 1: ++ rej_row = req * STRIDE + accepted ++ t_lse_rej = _global_lse( ++ t_max_ptr, t_sumexp_ptr, rej_row, NUM_BLOCKS, PADDED_BLOCKS ++ ) ++ if HAS_DRAFT_LOGITS: ++ d_lse_rej = _global_lse( ++ d_max_ptr, d_sumexp_ptr, rej_row, NUM_BLOCKS, PADDED_BLOCKS ++ ) ++ tl.store(rej_lse_ptr + req, t_lse_rej) ++ tl.store(rej_lse_ptr + bs + req, d_lse_rej) ++ ++ ++@triton.jit ++def _resample_kernel( ++ res_max_ptr, ++ res_arg_ptr, ++ raw_len_ptr, ++ rej_lse_ptr, ++ candidates_ptr, ++ candidates_stride, ++ target_logits_ptr, ++ target_stride, ++ draft_logits_ptr, ++ draft_stride_0, ++ draft_stride_1, ++ target_temp_ptr, ++ draft_temp_ptr, ++ target_vocab, ++ draft_vocab, ++ bs, ++ key, ++ counter_ptr, ++ STRIDE: tl.constexpr, ++ NUM_BLOCKS: tl.constexpr, ++ BLOCK: tl.constexpr, ++ HAS_DRAFT_LOGITS: tl.constexpr, ++): ++ req = tl.program_id(0).to(tl.int64) ++ block_idx = tl.program_id(1) ++ seed = _step_seed(key, counter_ptr) ++ r = tl.load(raw_len_ptr + req).to(tl.int64) ++ row = req * STRIDE + r ++ is_bonus = r == STRIDE - 1 ++ offs = block_idx * BLOCK + tl.arange(0, BLOCK) ++ mask = offs < target_vocab ++ t_temp = tl.load(target_temp_ptr + req).to(tl.float32) ++ t = ( ++ tl.load( ++ target_logits_ptr + row * target_stride + offs, ++ mask=mask, ++ other=float("-inf"), ++ ).to(tl.float32) ++ / t_temp ++ ) ++ if is_bonus: ++ residual = t ++ else: ++ rejected = tl.load(candidates_ptr + req * candidates_stride + r + 1) ++ if HAS_DRAFT_LOGITS: ++ d_temp = tl.load(draft_temp_ptr + req).to(tl.float32) ++ log_p = t - tl.load(rej_lse_ptr + req) ++ log_q = tl.load( ++ draft_logits_ptr + req * draft_stride_0 + r * draft_stride_1 + offs, ++ mask=offs < draft_vocab, ++ other=float("-inf"), ++ ).to(tl.float32) / d_temp - tl.load(rej_lse_ptr + bs + req) ++ # log max(p - q, 0) = log p + log1p(-q / p), -inf where q >= p. ++ ratio = tl.exp(log_q - log_p) ++ residual = tl.where( ++ ratio < 1.0, log_p + libdevice.log1p(-ratio), float("-inf") ++ ).to(tl.float32) ++ else: ++ # One-hot draft: the residual is p without the rejected token. ++ residual = tl.where(offs != rejected, t, float("-inf")) ++ u = _murmur3_uniform32(seed, req, offs) ++ noised = tl.where(mask, residual - tl.log(-_log1p_neg_stable(u)), float("-inf")) ++ value, idx = tl.max(noised, axis=0, return_indices=True) ++ tl.store(res_max_ptr + req * NUM_BLOCKS + block_idx, value) ++ tl.store(res_arg_ptr + req * NUM_BLOCKS + block_idx, block_idx * BLOCK + idx) ++ ++ ++@triton.jit ++def _insert_kernel( ++ bonus_ptr, ++ correct_len_ptr, ++ raw_len_ptr, ++ res_max_ptr, ++ res_arg_ptr, ++ candidates_ptr, ++ candidates_stride, ++ counter_ptr, ++ NUM_BLOCKS: tl.constexpr, ++ PADDED_BLOCKS: tl.constexpr, ++): ++ req = tl.program_id(0).to(tl.int64) ++ capped = tl.load(correct_len_ptr + req) ++ raw = tl.load(raw_len_ptr + req) ++ if capped < raw: ++ # Capped by the verify budget: the bonus is the accepted draft after the cap. ++ bonus = tl.load(candidates_ptr + req * candidates_stride + capped + 1).to( ++ tl.int64 ++ ) ++ else: ++ blocks = tl.arange(0, PADDED_BLOCKS) ++ local_max = tl.load( ++ res_max_ptr + req * NUM_BLOCKS + blocks, ++ mask=blocks < NUM_BLOCKS, ++ other=float("-inf"), ++ ) ++ # NaN would make argmax land in the padded tail. ++ local_max = tl.where(local_max != local_max, float("-inf"), local_max) ++ best = tl.argmax(local_max, axis=0) ++ bonus = tl.load(res_arg_ptr + req * NUM_BLOCKS + best) ++ tl.store(bonus_ptr + req, bonus) ++ if req == 0: ++ # The other kernels of this call have read the counter (stream order). ++ tl.store(counter_ptr, tl.load(counter_ptr) + 1) ++ ++ ++class BlockwiseRejection: ++ @classmethod ++ def execute( ++ cls, *args, **kwargs ++ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: ++ if inputs_on_cuda(*args, **kwargs): ++ return blockwise_rejection_triton(*args, **kwargs) ++ return blockwise_rejection_torch(*args, **kwargs) ++ ++ ++def blockwise_rejection_triton( ++ *, ++ candidates: torch.Tensor, ++ target_logits: torch.Tensor, ++ draft_logits: Optional[torch.Tensor], ++ target_temperatures: torch.Tensor, ++ draft_temperatures: torch.Tensor, ++ noise: RejectionNoise, ++ cutoff_verify_lens: Optional[torch.Tensor] = None, ++) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: ++ """``draft_logits`` is pre-temperature, or None for a one-hot draft. Returns ++ (correct_len int32, bonus int64, cap_trim_lens int32), each [bs].""" ++ bs, stride = candidates.shape ++ target_vocab = target_logits.shape[-1] ++ assert target_logits.stride(-1) == 1 and target_logits.shape[0] == bs * stride ++ has_draft = draft_logits is not None ++ draft_vocab = draft_logits.shape[-1] if has_draft else target_vocab ++ if has_draft: ++ assert draft_logits.stride(-1) == 1 and draft_logits.shape[1] >= stride - 1 ++ device = candidates.device ++ target_temperatures = target_temperatures.reshape(-1).contiguous() ++ draft_temperatures = draft_temperatures.reshape(-1).contiguous() ++ num_blocks = triton.cdiv(max(target_vocab, draft_vocab), _STATS_BLOCK) ++ padded_blocks = triton.next_power_of_2(num_blocks) ++ stats = torch.empty( ++ (4, bs * stride, num_blocks), dtype=torch.float32, device=device ++ ) ++ lens = torch.empty((3, bs), dtype=torch.int32, device=device) ++ rej_lse = torch.empty((2, bs), dtype=torch.float32, device=device) ++ res_blocks = triton.cdiv(target_vocab, _RESAMPLE_BLOCK) ++ res_max = torch.empty((bs, res_blocks), dtype=torch.float32, device=device) ++ res_arg = torch.empty((bs, res_blocks), dtype=torch.int64, device=device) ++ bonus = torch.empty((bs,), dtype=torch.int64, device=device) ++ correct_len, raw_len, trim = lens[0], lens[1], lens[2] ++ t_max, t_sumexp, d_max, d_sumexp = stats[0], stats[1], stats[2], stats[3] ++ d_ptr = draft_logits if has_draft else target_logits ++ d_s0 = draft_logits.stride(0) if has_draft else 0 ++ d_s1 = draft_logits.stride(1) if has_draft else 0 ++ _stats_kernel[(bs * stride, num_blocks)]( ++ t_max, t_sumexp, d_max, d_sumexp, ++ target_logits, target_logits.stride(0), ++ d_ptr, d_s0, d_s1, ++ target_temperatures, draft_temperatures, ++ target_vocab, draft_vocab, ++ STRIDE=stride, NUM_BLOCKS=num_blocks, BLOCK=_STATS_BLOCK, ++ HAS_DRAFT_LOGITS=has_draft, ++ ) # fmt: skip ++ has_cutoff = cutoff_verify_lens is not None ++ verify_lens = ( ++ cutoff_verify_lens.to(device=device).contiguous() if has_cutoff else correct_len ++ ) ++ _rejection_kernel[(bs,)]( ++ correct_len, raw_len, trim, rej_lse, ++ candidates, candidates.stride(0), verify_lens, ++ t_max, t_sumexp, d_max, d_sumexp, ++ target_logits, target_logits.stride(0), ++ d_ptr, d_s0, d_s1, ++ target_temperatures, draft_temperatures, ++ target_vocab, draft_vocab, bs, ++ noise.key, noise.counter, ++ STRIDE=stride, NUM_BLOCKS=num_blocks, PADDED_BLOCKS=padded_blocks, ++ HAS_DRAFT_LOGITS=has_draft, HAS_CUTOFF=has_cutoff, ++ num_warps=1, ++ ) # fmt: skip ++ _resample_kernel[(bs, res_blocks)]( ++ res_max, res_arg, raw_len, rej_lse, ++ candidates, candidates.stride(0), ++ target_logits, target_logits.stride(0), ++ d_ptr, d_s0, d_s1, ++ target_temperatures, draft_temperatures, ++ target_vocab, draft_vocab, bs, ++ noise.key, noise.counter, ++ STRIDE=stride, NUM_BLOCKS=res_blocks, BLOCK=_RESAMPLE_BLOCK, ++ HAS_DRAFT_LOGITS=has_draft, ++ ) # fmt: skip ++ _insert_kernel[(bs,)]( ++ bonus, correct_len, raw_len, res_max, res_arg, ++ candidates, candidates.stride(0), noise.counter, ++ NUM_BLOCKS=res_blocks, PADDED_BLOCKS=triton.next_power_of_2(res_blocks), ++ num_warps=1, ++ ) # fmt: skip ++ return correct_len, bonus, trim ++ ++ ++def blockwise_rejection_torch( ++ *, ++ candidates: torch.Tensor, ++ target_logits: torch.Tensor, ++ draft_logits: Optional[torch.Tensor], ++ target_temperatures: torch.Tensor, ++ draft_temperatures: torch.Tensor, ++ noise: RejectionNoise, ++ cutoff_verify_lens: Optional[torch.Tensor] = None, ++) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: ++ """Reference with the same math; draws from a generator seeded by (key, counter).""" ++ bs, stride = candidates.shape ++ gamma = stride - 1 ++ vocab = target_logits.shape[-1] ++ gen = torch.Generator(device=candidates.device) ++ gen.manual_seed((noise.key + int(noise.counter.item()) * 1_000_003) % (2**63)) ++ t_temp = target_temperatures.reshape(bs, 1, 1).float() ++ log_p = torch.log_softmax( ++ target_logits.float().view(bs, stride, vocab) / t_temp, -1 ++ ) ++ if draft_logits is not None: ++ d_temp = draft_temperatures.reshape(bs, 1, 1).float() ++ d = draft_logits[:bs, :gamma].float() / d_temp ++ log_q = torch.full((bs, gamma, vocab), float("-inf"), device=d.device) ++ log_q[..., : d.shape[-1]] = torch.log_softmax(d, -1)[..., :vocab] ++ else: ++ log_q = torch.full((bs, gamma, vocab), float("-inf"), device=log_p.device) ++ log_q.scatter_(-1, candidates[:, 1:].unsqueeze(-1), 0.0) ++ coins = torch.rand((bs, gamma), generator=gen, device=candidates.device) ++ gumbel = -torch.log( ++ -torch.log(torch.rand((bs, vocab), generator=gen, device=candidates.device)) ++ ) ++ tokens = candidates[:, 1:].long() ++ lp = log_p[:, :gamma].gather(-1, tokens.unsqueeze(-1)).squeeze(-1) ++ lq = log_q.gather(-1, tokens.unsqueeze(-1)).squeeze(-1) ++ ok = (lq > float("-inf")) & (lp > torch.log(coins.clamp_min(4.6566127342e-10)) + lq) ++ raw = torch.cumprod(ok.int(), dim=-1).sum(-1).int() ++ rows = torch.arange(bs, device=candidates.device) ++ lp_rej = log_p[rows, raw.long()] ++ lq_rej = torch.cat([log_q, log_q[:, :1]], 1)[rows, raw.long()] ++ residual = torch.where( ++ raw.unsqueeze(-1) == gamma, ++ lp_rej, ++ torch.where( ++ lq_rej < lp_rej, ++ lp_rej + torch.log1p(-torch.exp(lq_rej - lp_rej)), ++ float("-inf"), ++ ), ++ ) ++ bonus = (residual + gumbel).argmax(-1) ++ if cutoff_verify_lens is not None: ++ capped = torch.minimum(raw, cutoff_verify_lens.to(raw.device).int() - 1) ++ else: ++ capped = raw ++ capped_bonus = candidates.gather( ++ 1, (capped.long() + 1).clamp_max(gamma).unsqueeze(-1) ++ ).squeeze(-1) ++ bonus = torch.where(capped < raw, capped_bonus, bonus) ++ noise.counter.add_(1) ++ return capped, bonus.long(), raw - capped +diff --git a/python/sglang/kernels/ops/speculative/dspark/simulated_bonus.py b/python/sglang/kernels/ops/speculative/dspark/simulated_bonus.py +index ec1e073db1..49140711ae 100644 +--- a/python/sglang/kernels/ops/speculative/dspark/simulated_bonus.py ++++ b/python/sglang/kernels/ops/speculative/dspark/simulated_bonus.py +@@ -66,6 +66,7 @@ def _simulated_bonus_row_partial_kernel( + logits_stride, + temperatures_ptr, + correct_len_ptr, ++ correct_len_stride, + seed_ptr, + part_val_ptr, + part_idx_ptr, +@@ -76,7 +77,7 @@ def _simulated_bonus_row_partial_kernel( + ): + req = tl.program_id(0) + split = tl.program_id(1) +- row = req * ROWS + tl.load(correct_len_ptr + req) ++ row = req * ROWS + tl.load(correct_len_ptr + req * correct_len_stride) + t = tl.load(temperatures_ptr + req).to(tl.float32) + offs = split * BLOCK + tl.arange(0, BLOCK) + mask = offs < vocab +@@ -125,7 +126,34 @@ def simulated_bonus_sample_graph( + """Graph-safe variant of simulated_bonus_sample: seed ([1] int) and per-request + temperatures ([bs] float; <= 0 means argmax) are read from device buffers, and + only the row at ``correct_len`` is sampled. [bs] int64.""" ++ part_val, part_idx = simulated_bonus_partials_graph( ++ target_logits=target_logits, ++ correct_len=correct_len, ++ temperatures=temperatures, ++ seed=seed, ++ bs=bs, ++ rows_per_request=rows_per_request, ++ ) ++ out = torch.empty((bs,), dtype=torch.int64, device=target_logits.device) ++ _simulated_bonus_row_select_kernel[(bs,)]( ++ part_val, part_idx, out, target_logits.shape[1], NSPLIT=part_val.shape[1] ++ ) ++ return out ++ ++ ++def simulated_bonus_partials_graph( ++ *, ++ target_logits: torch.Tensor, ++ correct_len: torch.Tensor, ++ temperatures: torch.Tensor, ++ seed: torch.Tensor, ++ bs: int, ++ rows_per_request: int, ++) -> tuple[torch.Tensor, torch.Tensor]: ++ """simulated_bonus_sample_graph's per-split (value, index) maxima, [bs, NSPLIT], ++ reduced by ``simulated_bonus_select_partials``. ``correct_len`` may be stride-0.""" + assert target_logits.stride(1) == 1 ++ assert correct_len.dim() == 1 and correct_len.shape[0] == bs + device = target_logits.device + vocab = target_logits.shape[1] + block = 4096 +@@ -136,7 +164,8 @@ def simulated_bonus_sample_graph( + target_logits, + target_logits.stride(0), + temperatures, +- correct_len.contiguous(), ++ correct_len, ++ correct_len.stride(0), + seed, + part_val, + part_idx, +@@ -146,11 +175,17 @@ def simulated_bonus_sample_graph( + BLOCK=block, + num_warps=8, + ) +- out = torch.empty((bs,), dtype=torch.int64, device=device) +- _simulated_bonus_row_select_kernel[(bs,)]( +- part_val, part_idx, out, vocab, NSPLIT=nsplit +- ) +- return out ++ return part_val, part_idx ++ ++ ++def simulated_bonus_select_partials( ++ *, part_val: torch.Tensor, part_idx: torch.Tensor, vocab: int ++) -> torch.Tensor: ++ """Torch reference of _simulated_bonus_row_select_kernel: the largest value, ++ ties to the lowest index. [bs] int64.""" ++ top = part_val.max(dim=1, keepdim=True).values ++ sentinel = torch.full_like(part_idx, vocab) ++ return torch.where(part_val == top, part_idx, sentinel).min(dim=1).values.long() + + + def simulated_bonus_sample( +diff --git a/python/sglang/kernels/ops/speculative/dspark/stage_commit.py b/python/sglang/kernels/ops/speculative/dspark/stage_commit.py +new file mode 100644 +index 0000000000..cf470847f6 +--- /dev/null ++++ b/python/sglang/kernels/ops/speculative/dspark/stage_commit.py +@@ -0,0 +1,73 @@ ++"""The deferred context-KV commit's staging in one launch: the verify rows' write ++locations, positions and (with a ring) state slots, and the gated commit lengths ++with zeros past the staged requests.""" ++ ++from typing import Optional ++ ++import torch ++import triton ++import triton.language as tl ++ ++ ++@triton.jit ++def _stage_commit_kernel( ++ loc_src_ptr, ++ loc_dst_ptr, ++ pos_src_ptr, ++ pos_dst_ptr, ++ slot_src_ptr, ++ slot_dst_ptr, ++ lens_src_ptr, ++ lens_dst_ptr, ++ rows, ++ bs, ++ max_bs, ++ HAS_SLOT: tl.constexpr, ++ ROWS_BLOCK: tl.constexpr, ++ LENS_BLOCK: tl.constexpr, ++): ++ r = tl.arange(0, ROWS_BLOCK) ++ m = r < rows ++ tl.store(loc_dst_ptr + r, tl.load(loc_src_ptr + r, mask=m), mask=m) ++ tl.store(pos_dst_ptr + r, tl.load(pos_src_ptr + r, mask=m), mask=m) ++ if HAS_SLOT: ++ tl.store(slot_dst_ptr + r, tl.load(slot_src_ptr + r, mask=m), mask=m) ++ q = tl.arange(0, LENS_BLOCK) ++ lens = tl.load(lens_src_ptr + q, mask=q < bs, other=0) ++ tl.store(lens_dst_ptr + q, lens, mask=q < max_bs) ++ ++ ++def stage_commit( ++ *, ++ cache_loc_dst: torch.Tensor, ++ positions_dst: torch.Tensor, ++ commit_lens_dst: torch.Tensor, ++ state_slot_dst: Optional[torch.Tensor], ++ cache_loc: torch.Tensor, ++ positions: torch.Tensor, ++ commit_lens: torch.Tensor, ++ state_slot: Optional[torch.Tensor], ++ rows: int, ++) -> None: ++ """``cache_loc_dst[:rows] = cache_loc[:rows]``, likewise positions / state slots, ++ ``commit_lens_dst[:bs] = commit_lens`` and ``commit_lens_dst[bs:] = 0``.""" ++ assert cache_loc.is_contiguous() and positions.is_contiguous() ++ assert commit_lens.is_contiguous() ++ assert (state_slot is None) == (state_slot_dst is None) ++ bs, max_bs = commit_lens.shape[0], commit_lens_dst.shape[0] ++ _stage_commit_kernel[(1,)]( ++ cache_loc, ++ cache_loc_dst, ++ positions, ++ positions_dst, ++ state_slot if state_slot is not None else cache_loc, ++ state_slot_dst if state_slot_dst is not None else cache_loc_dst, ++ commit_lens, ++ commit_lens_dst, ++ rows, ++ bs, ++ max_bs, ++ HAS_SLOT=state_slot is not None, ++ ROWS_BLOCK=triton.next_power_of_2(max(rows, 1)), ++ LENS_BLOCK=triton.next_power_of_2(max_bs), ++ ) +diff --git a/python/sglang/kernels/ops/speculative/dspark/static_accept_tail.py b/python/sglang/kernels/ops/speculative/dspark/static_accept_tail.py +new file mode 100644 +index 0000000000..416b309657 +--- /dev/null ++++ b/python/sglang/kernels/ops/speculative/dspark/static_accept_tail.py +@@ -0,0 +1,247 @@ ++"""DSpark static greedy verify: the accept and its bookkeeping in one launch ++(SGLANG_DSPARK_FUSED_ACCEPT_TAIL), one program per request row. ++ ++Per row, from the target's argmax ids: the leading draft matches and the bonus ++(AcceptGreedy; ``bonus_in`` replaces the bonus, ``bonus_parts`` replaces it with the ++in-graph simulated bonus's per-split maxima reduced here), ++the simulated correct length override (build_accept_outs), commit / new seq lens and ++a zero cap trim (FinalizeAcceptLens), the output tokens (BuildOutTokens), and the ++gated commit lengths the static epilogue's draft-KV commit reads. Every output equals ++the separate ops' bit for bit. With a simulated length and a supplied bonus the argmax ids ++are not read (``target_predict`` may be None). ++""" ++ ++from __future__ import annotations ++ ++from typing import Optional ++ ++import torch ++import triton ++import triton.language as tl ++ ++from sglang.kernels.ops.speculative.dspark.dispatch import inputs_on_cuda ++from sglang.kernels.ops.speculative.dspark.simulated_bonus import ( ++ simulated_bonus_select_partials, ++) ++ ++ ++@triton.jit ++def _static_accept_tail_kernel( ++ candidates_ptr, ++ target_ptr, ++ seq_lens_ptr, ++ verify_lens_ptr, ++ gate_ptr, ++ sim_ptr, ++ bonus_in_ptr, ++ part_val_ptr, ++ part_idx_ptr, ++ correct_out_ptr, ++ bonus_out_ptr, ++ cap_trim_out_ptr, ++ commit_out_ptr, ++ new_seq_out_ptr, ++ out_tokens_ptr, ++ gated_out_ptr, ++ cand_stride, ++ out_tokens_stride, ++ vocab, ++ T: tl.constexpr, ++ BLOCK_T: tl.constexpr, ++ NSPLIT: tl.constexpr, ++ HAS_SIM: tl.constexpr, ++ HAS_BONUS_IN: tl.constexpr, ++ HAS_PARTS: tl.constexpr, ++ NEED_TARGET: tl.constexpr, ++ HAS_GATED: tl.constexpr, ++): ++ row = tl.program_id(0).to(tl.int64) ++ offs = tl.arange(0, BLOCK_T) ++ in_t = offs < T ++ gamma = T - 1 ++ in_draft = offs < gamma ++ drafts = tl.load( ++ candidates_ptr + row * cand_stride + 1 + offs, mask=in_draft, other=-1 ++ ) ++ if NEED_TARGET: ++ targets = tl.load(target_ptr + row * T + offs, mask=in_draft, other=-2) ++ eq = (drafts == targets) & in_draft ++ num_correct = tl.min(tl.where(eq, BLOCK_T, offs), 0) ++ if HAS_PARTS: ++ # _simulated_bonus_row_select_kernel's reduction. ++ s = tl.arange(0, NSPLIT) ++ val = tl.load(part_val_ptr + row * NSPLIT + s) ++ idx = tl.load(part_idx_ptr + row * NSPLIT + s) ++ top = tl.max(val, axis=0) ++ bonus = tl.min(tl.where(val == top, idx, vocab), axis=0).to(tl.int64) ++ elif HAS_BONUS_IN: ++ bonus = tl.load(bonus_in_ptr + row).to(tl.int64) ++ else: ++ bonus = tl.load(target_ptr + row * T + num_correct).to(tl.int64) ++ if HAS_SIM: ++ correct = tl.load(sim_ptr).to(tl.int32) ++ else: ++ correct = num_correct.to(tl.int32) ++ commit = correct + 1 ++ new_seq = tl.load(seq_lens_ptr + row) + commit ++ tl.store(correct_out_ptr + row, correct) ++ tl.store(bonus_out_ptr + row, bonus) ++ tl.store(cap_trim_out_ptr + row, 0) ++ tl.store(commit_out_ptr + row, commit) ++ tl.store(new_seq_out_ptr + row, new_seq) ++ token = tl.where(offs == correct, bonus, tl.where(in_draft, drafts.to(tl.int64), 0)) ++ tl.store(out_tokens_ptr + row * out_tokens_stride + offs, token, mask=in_t) ++ if HAS_GATED: ++ verify_len = tl.load(verify_lens_ptr + row) ++ gate = tl.load(gate_ptr) ++ gated = tl.minimum(commit, verify_len.to(tl.int32)) * gate ++ tl.store(gated_out_ptr + row, gated) ++ ++ ++def static_accept_tail( ++ *, ++ candidates: torch.Tensor, ++ target_predict: Optional[torch.Tensor], ++ seq_lens: torch.Tensor, ++ verify_lens: torch.Tensor, ++ gate: torch.Tensor, ++ correct_len_out: torch.Tensor, ++ bonus_out: torch.Tensor, ++ cap_trim_lens_out: torch.Tensor, ++ commit_lens_out: torch.Tensor, ++ new_seq_lens_out: torch.Tensor, ++ out_tokens_out: torch.Tensor, ++ simulated_correct_len: Optional[torch.Tensor] = None, ++ bonus_in: Optional[torch.Tensor] = None, ++ bonus_parts: Optional[tuple[torch.Tensor, torch.Tensor, int]] = None, ++ gated_commit_lens_out: Optional[torch.Tensor] = None, ++) -> None: ++ """``candidates`` [bs, T] (anchor + drafts), ``target_predict`` [bs * T] argmax ids, ++ ``bonus_parts`` (part_val [bs, NSPLIT], part_idx, vocab); outputs go to rows [:bs].""" ++ assert bonus_in is None or bonus_parts is None ++ assert target_predict is not None or ( ++ simulated_correct_len is not None ++ and (bonus_in is not None or bonus_parts is not None) ++ ) ++ fn = ( ++ _static_accept_tail_triton ++ if inputs_on_cuda(candidates) ++ else static_accept_tail_torch ++ ) ++ fn( ++ candidates=candidates, ++ target_predict=target_predict, ++ seq_lens=seq_lens, ++ verify_lens=verify_lens, ++ gate=gate, ++ correct_len_out=correct_len_out, ++ bonus_out=bonus_out, ++ cap_trim_lens_out=cap_trim_lens_out, ++ commit_lens_out=commit_lens_out, ++ new_seq_lens_out=new_seq_lens_out, ++ out_tokens_out=out_tokens_out, ++ simulated_correct_len=simulated_correct_len, ++ bonus_in=bonus_in, ++ bonus_parts=bonus_parts, ++ gated_commit_lens_out=gated_commit_lens_out, ++ ) ++ ++ ++def _static_accept_tail_triton(**kw) -> None: ++ candidates = kw["candidates"] ++ bs, T = candidates.shape ++ assert candidates.stride(1) == 1 and kw["out_tokens_out"].stride(1) == 1 ++ dummy = kw["seq_lens"] ++ sim, bonus_in, parts, gated = ( ++ kw["simulated_correct_len"], ++ kw["bonus_in"], ++ kw["bonus_parts"], ++ kw["gated_commit_lens_out"], ++ ) ++ target = kw["target_predict"] ++ _static_accept_tail_kernel[(bs,)]( ++ candidates, ++ target if target is not None else dummy, ++ kw["seq_lens"], ++ kw["verify_lens"], ++ kw["gate"], ++ sim if sim is not None else dummy, ++ bonus_in if bonus_in is not None else dummy, ++ parts[0] if parts is not None else dummy, ++ parts[1] if parts is not None else dummy, ++ kw["correct_len_out"], ++ kw["bonus_out"], ++ kw["cap_trim_lens_out"], ++ kw["commit_lens_out"], ++ kw["new_seq_lens_out"], ++ kw["out_tokens_out"], ++ gated if gated is not None else dummy, ++ candidates.stride(0), ++ kw["out_tokens_out"].stride(0), ++ parts[2] if parts is not None else 0, ++ T=T, ++ BLOCK_T=triton.next_power_of_2(T), ++ NSPLIT=parts[0].shape[1] if parts is not None else 1, ++ HAS_SIM=sim is not None, ++ HAS_BONUS_IN=bonus_in is not None, ++ HAS_PARTS=parts is not None, ++ # The argmax ids only decide a length or bonus nothing else supplies. ++ NEED_TARGET=sim is None or (bonus_in is None and parts is None), ++ HAS_GATED=gated is not None, ++ num_warps=4, ++ ) ++ ++ ++def static_accept_tail_torch( ++ *, ++ candidates: torch.Tensor, ++ target_predict: Optional[torch.Tensor], ++ seq_lens: torch.Tensor, ++ verify_lens: torch.Tensor, ++ gate: torch.Tensor, ++ correct_len_out: torch.Tensor, ++ bonus_out: torch.Tensor, ++ cap_trim_lens_out: torch.Tensor, ++ commit_lens_out: torch.Tensor, ++ new_seq_lens_out: torch.Tensor, ++ out_tokens_out: torch.Tensor, ++ simulated_correct_len: Optional[torch.Tensor] = None, ++ bonus_in: Optional[torch.Tensor] = None, ++ bonus_parts: Optional[tuple[torch.Tensor, torch.Tensor, int]] = None, ++ gated_commit_lens_out: Optional[torch.Tensor] = None, ++) -> None: ++ """Reference: the same outputs from per-row torch ops (CPU or GPU).""" ++ bs, T = candidates.shape ++ gamma = T - 1 ++ if target_predict is not None: ++ target = target_predict.view(bs, T) ++ matches = (candidates[:, 1:] == target[:, :gamma]).to(torch.int32) ++ num_correct = matches.cumprod(dim=1).sum(dim=1).to(torch.int32) ++ rows = torch.arange(bs, device=candidates.device) ++ if bonus_parts is not None: ++ part_val, part_idx, vocab = bonus_parts ++ bonus = simulated_bonus_select_partials( ++ part_val=part_val[:bs], part_idx=part_idx[:bs], vocab=vocab ++ ) ++ elif bonus_in is not None: ++ bonus = bonus_in[:bs].to(torch.int64) ++ else: ++ bonus = target[rows, num_correct.long()].to(torch.int64) ++ if simulated_correct_len is not None: ++ correct = simulated_correct_len.repeat(bs).to(torch.int32) ++ else: ++ correct = num_correct ++ commit = correct + 1 ++ new_seq = seq_lens[:bs] + commit.to(seq_lens.dtype) ++ correct_len_out[:bs].copy_(correct) ++ bonus_out[:bs].copy_(bonus) ++ cap_trim_lens_out[:bs].zero_() ++ commit_lens_out[:bs].copy_(commit) ++ new_seq_lens_out[:bs].copy_(new_seq) ++ tokens = torch.zeros((bs, T), dtype=torch.int64, device=candidates.device) ++ tokens[:, :gamma] = candidates[:, 1:] ++ tokens.scatter_(1, correct.long()[:, None], bonus[:, None]) ++ out_tokens_out[:bs].copy_(tokens) ++ if gated_commit_lens_out is not None: ++ gated = torch.minimum(commit, verify_lens[:bs].to(torch.int32)) * gate ++ gated_commit_lens_out[:bs].copy_(gated) +diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py +index 818e011a61..b14c61ed96 100644 +--- a/python/sglang/srt/environ.py ++++ b/python/sglang/srt/environ.py +@@ -562,6 +562,32 @@ class Envs: + SGLANG_DSPARK_NVLINK_VOCAB_GATHER = EnvBool(True) + SGLANG_DSPARK_ENABLE_MULTI_STREAM = EnvBool(True) + SGLANG_DSPARK_CONFIDENCE_RELAY_LAG_STEPS = EnvInt(2) ++ # Static verify graphs with bs in [MIN_BS, MAX_BS] (MAX_BS 0: unbounded) run the ++ # greedy accept and its bookkeeping as one kernel. ++ SGLANG_DSPARK_FUSED_ACCEPT_TAIL = EnvBool(False) ++ SGLANG_DSPARK_ACCEPT_TAIL_MIN_BS = EnvInt(1) ++ SGLANG_DSPARK_ACCEPT_TAIL_MAX_BS = EnvInt(0) ++ # Static verify graphs stage the draft context-KV commit; the next draft graph ++ # writes it on a side stream forked at its head, joined at its first KV store. ++ SGLANG_DSPARK_DEFER_CONTEXT_KV = EnvBool(False) ++ # DSpark draft graph: its in-graph attention-metadata prep runs on a side stream ++ # and joins at the first draft KV store, overlapping the embedding. ++ SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK = EnvBool(False) ++ # DSpark static verify: the verify graph scatters new seq lens and the bonus into ++ # the FutureMap's slots; the host skips those scatters for folded accepts. ++ SGLANG_OPT_DSV41_DSPARK_POST_FOLD = EnvBool(False) ++ # DSpark target verify: a pre-planned replay skips re-copying input_ids / positions ++ # the plan-time load already copied from the same tensors. ++ SGLANG_OPT_DSV41_DSPARK_SKIP_PREFILLED_INPUTS = EnvBool(False) ++ # DSpark: draw the simulated acceptance length (and the sim bonus seed) before the ++ # draft launch instead of between the draft and the target verify. ++ SGLANG_OPT_DSV41_DSPARK_SIM_DRAW_AHEAD = EnvBool(False) ++ # Sampled DSpark verify accepts draw with block-wise rejection (blockwise_rejection.py: ++ # exact in law, counter-based draws agree across TP ranks) instead of the classic kernel. ++ SGLANG_OPT_DSV41_BLOCKWISE_REJECTION = EnvBool(False) ++ # The deferred commit's staging (hidden, write locations, positions, commit lengths) ++ # in one Triton launch instead of four copies and a fill. ++ SGLANG_OPT_DSV41_DSPARK_ONE_LAUNCH_COMMIT_STAGE = EnvBool(False) + + # =================================================================== + # Memory pools and KV-cache sizing +@@ -896,6 +922,9 @@ class Envs: + # Hand AITER only ceil32(sum of per-rank DP tokens) rows of the MORI EP receive + # buffer; unproved layouts or metadata keep the full view. Forces DP-synced buckets. + SGLANG_MORI_RECV_BOUND = EnvBool(False) ++ # MXFP4 trtllm-gen MoE: deferred-finalize calls above 32 rows pass the finalized ++ # output shape, so they hit FlashInfer's tuned tactics (off: only 97-384 rows do). ++ SGLANG_OPT_MXFP4_DEFERRED_FINALIZED_SHAPE = EnvBool(False) + # Manual MoE input row limit (EPv1 and EPv2); 0 leaves it to SGLANG_MORI_RECV_BOUND. + SGLANG_MORI_MOE_MAX_INPUT_TOKENS = EnvInt(0) + +@@ -1552,6 +1581,9 @@ class Envs: + # Guards CUDA graph executable dedup via cudaGraphExecUpdate. + SGLANG_ENABLE_CUDA_GRAPH_DEDUP = EnvBool(False) + SGLANG_MEMORY_SAVER_CUDA_GRAPH = EnvBool(False) ++ # Graph-input fill fast paths: skip the padding reset of an unpadded replay and copy ++ # one dense integer dtype pair with a single foreach launch. ++ SGLANG_OPT_CUDA_GRAPH_FILL_FAST_PATH = EnvBool(False) + # Reuse wholly-free graph-pool segments for step-local eager allocations. + SGLANG_ENABLE_GRAPH_POOL_BORROW = EnvBool(False) + # Mint capture's measured footprint as one span so the graph pool is carved +@@ -1780,6 +1812,27 @@ class Envs: + SGLANG_OPT_USE_AITER_BATCHED_GEMM = EnvBool(False) + SGLANG_OPT_BF16_FP32_GEMM_ALGO = EnvStr("cublas") + SGLANG_OPT_FUSE_WQA_WKV = EnvBool(True) ++ # DSpark decode: build the verify window and the draft anchor column in one ++ # launch instead of two adds, assign_extend_cache_locs and a copy. ++ SGLANG_OPT_DSV41_DSPARK_PREPARE_INPUTS_ONCE = EnvBool(False) ++ # DSpark folded draft: the draft graph's tail writes [anchor | draft tokens] ++ # into the sampler's own buffer, so the step skips its eager concat. ++ SGLANG_OPT_DSV41_DSPARK_MID_FOLD = EnvBool(False) ++ # DSpark static verify: run the target verify runner's metadata prep through the ++ # metadata glue graph where its backend declares the prep host-free. ++ SGLANG_OPT_DSV41_TARGET_VERIFY_METADATA_GLUE = EnvBool(False) ++ # DSpark static verify: build the target verify metadata on a side stream beside the ++ # draft graph, for requests up to the candidate span (needs the glue switch above). ++ SGLANG_OPT_DSV41_TARGET_METADATA_EARLY = EnvBool(False) ++ # Decode / verify graph replays whose metadata glue graph is captured skip the ++ # replay ForwardBatch view (the graph reads slots and buffers by address). ++ SGLANG_OPT_SKIP_GLUED_REPLAY_VIEW = EnvBool(False) ++ # DSpark static verify: record the post-verify engram history commit in the ++ # target-verify CUDA graph (epilogue) instead of launching it after the replay. ++ SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH = EnvBool(False) ++ # DSpark static verify: an all-sampled step (no top-k / top-p) replays its ++ # sampling accept and commits as a CUDA graph right after the verify graph. ++ SGLANG_OPT_DSV41_SAMPLING_ACCEPT_GRAPH = EnvBool(False) + SGLANG_OPT_USE_MULTI_STREAM_OVERLAP = EnvBool(True) + + # =================================================================== +diff --git a/python/sglang/srt/layers/attention/base_attn_backend.py b/python/sglang/srt/layers/attention/base_attn_backend.py +index c317997479..9c43fe95a4 100644 +--- a/python/sglang/srt/layers/attention/base_attn_backend.py ++++ b/python/sglang/srt/layers/attention/base_attn_backend.py +@@ -104,6 +104,16 @@ class AttentionBackend(ABC): + self.init_forward_metadata_out_graph(forward_batch) + self.init_forward_metadata_in_graph(forward_batch) + ++ def glue_target_verify_metadata(self) -> str: ++ """Empty if the target verify prep may be captured into the metadata glue graph ++ (reads only runner slots and backend buffers), else the reason it may not.""" ++ return "the attention backend declares no host-free target verify prep" ++ ++ def glue_draft_metadata(self) -> str: ++ """Empty if the draft prep may be captured into the metadata glue graph (host ++ inputs constant per replay key), else the reason it may not.""" ++ return "the attention backend declares no host-free draft prep" ++ + def init_forward_metadata_out_graph( + self, + forward_batch: ForwardBatch, +diff --git a/python/sglang/srt/layers/attention/deepseek_v4_backend.py b/python/sglang/srt/layers/attention/deepseek_v4_backend.py +index aa2ae0e598..cdc156eb64 100644 +--- a/python/sglang/srt/layers/attention/deepseek_v4_backend.py ++++ b/python/sglang/srt/layers/attention/deepseek_v4_backend.py +@@ -6,6 +6,7 @@ import logging + from dataclasses import dataclass, field + from typing import ( + TYPE_CHECKING, ++ Callable, + Dict, + List, + Literal, +@@ -91,6 +92,7 @@ from sglang.srt.layers.attention.dsv4.v41_indexer import ( + from sglang.srt.layers.attention.dsv4.v41_indexer.sparse_table import ( + SparseTableBackend, + ) ++from sglang.srt.layers.attention.graph_variants import DSV41_EARLY_VERIFY_VARIANTS + from sglang.srt.layers.attention.verify_mask import ( + VerifyMask, + maybe_create_verify_mask, +@@ -123,6 +125,9 @@ from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.breakab + from sglang.srt.model_executor.runner_backend_utils.tc_piecewise_cuda_graph import ( + get_tc_piecewise_forward_context, + ) ++from sglang.srt.model_executor.runner_utils.forked_metadata_prep import ( ++ join_in_graph_metadata_prep, ++) + from sglang.srt.runtime_context import ( + get_exec, + get_parallel, +@@ -1165,6 +1170,18 @@ class DSV4RawDecodeMetadata: + self.out_cache_loc.copy_(other.out_cache_loc) + + ++def _replan_topk_in_graph(metadata) -> None: ++ from sglang.kernels.ops.attention.dsv4 import plan_topk_v2 ++ ++ for indexer in ( ++ metadata.indexer_metadata, ++ metadata.c1_indexer_metadata, ++ metadata.c2_indexer_metadata, ++ ): ++ if indexer is not None and indexer.use_topk_v2: ++ plan_topk_v2(indexer.compressed_seq_lens, out=indexer.topk_metadata) ++ ++ + class _GraphBucket(enum.Enum): + DECODE_OR_IDLE = "decode_or_idle" + TARGET_VERIFY = "target_verify" +@@ -1184,6 +1201,9 @@ class _GraphBucket(enum.Enum): + class DeepseekV4AttnBackend( + AttentionBackend, C4IndexerBackendMixin, CompressorBackendMixin + ): ++ pre_kv_store_hook = None ++ builds_verify_metadata_early = False ++ draft_metadata_glued = False + use_captured_forward_metadata_for_breakable_cuda_graph: bool = True + supports_prefill_cuda_graph_max_context_size: bool = True + supports_ragged_verify_graph: bool = True +@@ -1212,6 +1232,9 @@ class DeepseekV4AttnBackend( + ): + super().__init__() + self.model_runner = model_runner ++ # Run at every KV store-location read; the DSpark deferred context-KV commit ++ # joins its forked write there (SGLANG_DSPARK_DEFER_CONTEXT_KV). ++ self.pre_kv_store_hook: Optional[Callable[[], None]] = None + self.encoder_replay = False + self.encoder_row_floor = None + self.device = torch.device(model_runner.device) +@@ -1328,11 +1351,67 @@ class DeepseekV4AttnBackend( + self.is_draft_runner = model_runner.is_draft_worker + self._verify_mask = None + self.cuda_graph_swa_out_cache_loc: Optional[torch.Tensor] = None ++ # Once a draft runner glues this prep (glue_draft_metadata): the draft ++ # block's extend lengths come from device constants, one per batch size. ++ self.draft_metadata_glued = False ++ self._draft_extend_lens: Dict[Tuple[int, ...], torch.Tensor] = {} ++ # Set by the target verify runner that stages this metadata early: the replay ++ # prep then builds the full metadata and the verify graph records none. ++ self.builds_verify_metadata_early = False ++ # Ids of the captured verify metadata built that way; the bucket keeps them alive. ++ self._early_verify_metadata_ids: set = set() + + def _move_to_device(self, x: List[int]) -> torch.Tensor: + pin_tensor = torch.tensor(x, dtype=torch.int32, pin_memory=True) + return pin_tensor.to(self.device, non_blocking=True) + ++ def glue_target_verify_metadata(self) -> str: ++ # The static target verify prep reads the runner's slots and own buffers only; ++ # host lengths, online c128 MTP, trtllm, a request window and CP are unaudited. ++ for bad, why in ( ++ (self.is_draft_runner, "a draft runner"), ++ (self.needs_cpu_seq_lens, "host sequence lengths"), ++ (self.trtllm_attn, "trtllm-gen attention"), ++ (self.online_c128_mtp.enabled(), "online c128 MTP"), ++ (read_ragged_verify_mode() is not RaggedVerifyMode.STATIC, "ragged verify"), ++ (self.token_to_kv_pool.request_window is not None, "a request window"), ++ (get_parallel().attn_cp_size != 1, "context parallelism"), ++ ): ++ if bad: ++ return why ++ return "" ++ ++ def glue_draft_metadata(self) -> str: ++ # The draft block prep is host-free (host inputs follow from bs, CPU lengths ++ # feed only asserts) except in these cases. ++ for bad, why in ( ++ (not self.is_dspark_draft, "not the DSpark draft runner"), ++ (self.trtllm_attn, "trtllm-gen attention"), ++ (self.online_c128_mtp.enabled(), "online c128 MTP"), ++ (self.token_to_kv_pool.request_window is not None, "a request window"), ++ (get_parallel().attn_cp_size != 1, "context parallelism"), ++ ): ++ if bad: ++ return why ++ self.draft_metadata_glued = True ++ return "" ++ ++ def _draft_block_extend_lens(self, lens: List[int]) -> torch.Tensor: ++ """The draft block's extend lengths on the device; glued, a cached constant ++ (a captured host copy would replay from a freed pinned buffer).""" ++ if not self.draft_metadata_glued: ++ return self._move_to_device(lens) ++ key = tuple(lens) ++ cached = self._draft_extend_lens.get(key) ++ if cached is None: ++ if torch.cuda.is_available() and torch.cuda.is_current_stream_capturing(): ++ raise RuntimeError( ++ f"draft block extend lengths {key} first seen inside the metadata " ++ "glue capture" ++ ) ++ cached = self._draft_extend_lens[key] = self._move_to_device(lens) ++ return cached ++ + def _resolve_verify_layout( + self, + forward_batch: ForwardBatch, +@@ -2146,7 +2225,7 @@ class DeepseekV4AttnBackend( + seq_lens_cpu=seq_lens_cpu_list, + extend_len=block_size, + ) +- extend_seq_lens = self._move_to_device(lengths.extend_seq_lens_cpu) ++ extend_seq_lens = self._draft_block_extend_lens(lengths.extend_seq_lens_cpu) + return self.init_forward_metadata_prefill( + # DSpark draft blocks are SWA-only, like draft extend. Their full + # context page table is unused; retain only its 2-D placeholder. +@@ -2169,6 +2248,7 @@ class DeepseekV4AttnBackend( + self, + raw_metadata: DSV4RawVerifyMetadata, + online_c128_state_slot_offset: int = 0, ++ graph_backed: bool = False, + ) -> DSV4Metadata: + req_pool_indices = raw_metadata.req_pool_indices + seq_lens = raw_metadata.seq_lens +@@ -2214,7 +2294,9 @@ class DeepseekV4AttnBackend( + num_groups=bs, + ) + indexer_metadata = ( +- self.init_forward_metadata_indexer(core_attn_metadata) ++ self.init_forward_metadata_indexer( ++ core_attn_metadata, use_prefill_cuda_graph=graph_backed ++ ) + if self.has_c4 + else None + ) +@@ -2245,6 +2327,7 @@ class DeepseekV4AttnBackend( + core_attn_metadata, + compress_ratio=1, + rows_per_request=rows_per_request, ++ use_prefill_cuda_graph=graph_backed, + ) + if 1 in low + else None +@@ -2254,6 +2337,7 @@ class DeepseekV4AttnBackend( + core_attn_metadata, + compress_ratio=2, + rows_per_request=rows_per_request, ++ use_prefill_cuda_graph=graph_backed, + ) + if 2 in low + else None +@@ -2397,6 +2481,11 @@ class DeepseekV4AttnBackend( + skip_low_ratio_indexer, + ) + ++ # Replay prep built this in full except the indexer top-k plans, which the graph ++ # records like the in-graph upgrade (the prep's copy diverged at long context). ++ if id(self.forward_metadata) in self._early_verify_metadata_ids: ++ _replan_topk_in_graph(self.forward_metadata) ++ return + # Upgrade Raw->Full so compress + core_attn + indexer materialization is + # recorded inside the cuda graph. + if isinstance(self.forward_metadata, DSV4RawVerifyMetadata): +@@ -2499,6 +2588,68 @@ class DeepseekV4AttnBackend( + if self.trtllm_attn: + metadata.core_attn_metadata.init_trtllm_sparse_buffers() + ++ def enable_early_verify_metadata(self) -> None: ++ """Called by the target verify runner whose own predicate stages the metadata ++ early, so capture and replay agree on which metadata object the graph reads.""" ++ self.builds_verify_metadata_early = True ++ logger.info("Target verify metadata built outside the verify graph.") ++ ++ def _uses_early_verify_metadata(self, *, ragged_layout) -> bool: ++ """Whether this prep builds the full verify metadata: only for an early ++ variant; the others keep their in-graph upgrade.""" ++ if not self.builds_verify_metadata_early or ragged_layout is not None: ++ return False ++ from sglang.srt.model_executor.runner_utils.capture_mode import ( ++ get_capture_attention_variant, ++ skip_low_ratio_indexer, ++ ) ++ ++ early = get_capture_attention_variant() in DSV41_EARLY_VERIFY_VARIANTS ++ # Only the in-graph upgrade fills the all-position indices of such a variant. ++ assert not (early and any(map(skip_low_ratio_indexer, self.low_ratios))), ( ++ "early verify metadata does not fill candidate_all indices" ++ ) ++ return early ++ ++ def _install_early_verify_metadata( ++ self, *, graph_key, raw_metadata: DSV4RawVerifyMetadata, out_cache_loc ++ ) -> None: ++ """Build what ``init_forward_metadata_in_graph`` records for target verify and ++ copy it into the metadata the early variant's graph was captured with.""" ++ graph_key = (graph_key, "early") ++ # Graph-backed, like the in-graph build it replaces: one indexer call per layer, ++ # no free-memory row chunking (a chunked schedule would be rebound, not copied). ++ metadata = self.make_forward_metadata_from_raw_verify( ++ raw_metadata=raw_metadata, ++ online_c128_state_slot_offset=self.online_c128_mtp.state_slot_offset(), ++ graph_backed=True, ++ ) ++ # The full build leaves the SWA write locations to the in-graph op it replaces. ++ pool = self.token_to_kv_pool ++ swa_out_cache_loc = ( ++ pool.translate_loc_from_full_to_swa(out_cache_loc).to(torch.int32) ++ if pool.request_window is None and pool.swa_req_ring_size is None ++ else None ++ ) ++ self.tail_forward_metadata = None ++ bucket_metadata = self.cuda_graph_metadata_of_bucket_and_bs[ ++ _GraphBucket.TARGET_VERIFY ++ ] ++ captured = bucket_metadata.get(graph_key) ++ if captured is None: ++ metadata.core_attn_metadata.swa_out_cache_loc = swa_out_cache_loc ++ bucket_metadata[graph_key] = metadata ++ self._early_verify_metadata_ids.add(id(metadata)) ++ self.forward_metadata = metadata ++ return ++ # copy_ assigns swa_out_cache_loc; the verify graphs read the captured tensor. ++ captured_swa_out_cache_loc = captured.core_attn_metadata.swa_out_cache_loc ++ captured.copy_(metadata) ++ if captured_swa_out_cache_loc is not None: ++ captured_swa_out_cache_loc.copy_(swa_out_cache_loc) ++ captured.core_attn_metadata.swa_out_cache_loc = captured_swa_out_cache_loc ++ self.forward_metadata = captured ++ + def _dspark_seq_lens_casual( + self, *, seq_lens: torch.Tensor, block_size: int + ) -> torch.Tensor: +@@ -2661,6 +2812,15 @@ class DeepseekV4AttnBackend( + online_c128_state_slot_offset=online_c128_state_slot_offset, + ragged_layout=ragged_layout, + ) ++ if self._uses_early_verify_metadata(ragged_layout=ragged_layout): ++ self._install_early_verify_metadata( ++ graph_key=graph_key, ++ raw_metadata=temp_metadata, ++ out_cache_loc=out_cache_loc_padded, ++ ) ++ if in_capture: ++ self._current_capture_raw = None ++ return + elif bucket == _GraphBucket.DRAFT_EXTEND: + self.online_c128_mtp.prepare_forward( + actual_forward_mode, +@@ -3889,6 +4049,9 @@ class DeepseekV4AttnBackend( + def get_swa_out_cache_loc(self, forward_batch: ForwardBatch) -> torch.Tensor: + """Idle always re-translates at store time: its metadata may be stale, and + translating the zero-padded out_cache_loc writes to the dummy slot.""" ++ join_in_graph_metadata_prep() ++ if self.pre_kv_store_hook is not None: ++ self.pre_kv_store_hook() + metadata = self.forward_metadata + if self.token_to_kv_pool.request_window is not None: + layout = metadata.core_attn_metadata.request_window_layout +diff --git a/python/sglang/srt/layers/attention/graph_variants.py b/python/sglang/srt/layers/attention/graph_variants.py +index e3244aa0c1..a06ff32b13 100644 +--- a/python/sglang/srt/layers/attention/graph_variants.py ++++ b/python/sglang/srt/layers/attention/graph_variants.py +@@ -69,6 +69,10 @@ def create_attention_graph_variants(hf_config) -> Optional[AttentionGraphVariant + + + DSV41_CANDIDATE_FILTERED = "candidate_filtered" ++DSV41_CANDIDATE_UNFILTERED = "candidate_unfiltered" ++# SGLANG_OPT_DSV41_TARGET_METADATA_EARLY serves these target verify variants (requests ++# up to the candidate span); longer ones keep the in-graph metadata upgrade. ++DSV41_EARLY_VERIFY_VARIANTS = frozenset({DSV41_CANDIDATE_UNFILTERED}) + + + @dataclass(frozen=True) +@@ -93,6 +97,11 @@ class Dsv41CandidateGraphVariants: + "candidate_max_seq_len_upper_bound", + None, + ) ++ return self.select_for_max_seq_len(max_seq_len) ++ ++ def select_for_max_seq_len(self, max_seq_len: Optional[int]) -> str: ++ """The variant for a batch whose longest request (before this step's verify ++ tokens) is ``max_seq_len``; None, when unknown, takes the fallback.""" + if max_seq_len is not None: + max_seq_len += self.verify_extra_tokens + for variant, limit in self.graph_limits: +@@ -139,7 +148,7 @@ def create_dsv41_candidate_graph_variants( + variants.append(("candidate_all", topk * min(ratios))) + if ratios == {1, 2}: + variants.append(("candidate_c2_all", topk * 2)) +- variants.append(("candidate_unfiltered", span)) ++ variants.append((DSV41_CANDIDATE_UNFILTERED, span)) + graph_limits = [] + for variant, limit in variants: + graph_limits.append((variant, min(limit, span))) +diff --git a/python/sglang/srt/layers/quantization/mxfp4_flashinfer_trtllm_moe.py b/python/sglang/srt/layers/quantization/mxfp4_flashinfer_trtllm_moe.py +index 4d873c36ae..801f2fca9d 100644 +--- a/python/sglang/srt/layers/quantization/mxfp4_flashinfer_trtllm_moe.py ++++ b/python/sglang/srt/layers/quantization/mxfp4_flashinfer_trtllm_moe.py +@@ -10,6 +10,7 @@ from torch.nn.parameter import Parameter + from sglang.srt.distributed.device_communicators.pynccl_allocator import ( + use_symmetric_memory, + ) ++from sglang.srt.environ import envs + from sglang.srt.layers.dp_attention import is_allocation_symmetric + from sglang.srt.layers.moe.utils import MoeRunnerBackend, RoutingMethodType + from sglang.srt.runtime_context import ( +@@ -463,11 +464,14 @@ class Mxfp4FlashinferTrtllmMoEMethod: + # Deferred finalize returns the permuted GEMM2 output plus the routing + # triple instead of the finalized [T, hidden] tensor. + defer_finalize = is_deferred_finalize_enabled() ++ # FlashInfer keys its tactic cache on the output shape. At <= 32 rows the tuned ++ # tactic measured slower on real routing, so those keep the (M, 0) key. ++ if envs.SGLANG_OPT_MXFP4_DEFERRED_FINALIZED_SHAPE.get(): ++ deferred_output_shape = num_tokens > 32 ++ else: ++ deferred_output_shape = 96 < num_tokens <= 384 + symm_output = None +- # Preserve the ordinary output shape in the medium-batch autotuner +- # cache key. The deferred ABI ignores this allocation and returns the +- # expanded GEMM output for the separate fused finalize epilogue. +- if not defer_finalize or 96 < num_tokens <= 384: ++ if not defer_finalize or deferred_output_shape: + with use_symmetric_memory( + get_parallel().tp_group, disabled=not is_allocation_symmetric() + ): +diff --git a/python/sglang/srt/managers/overlap_utils.py b/python/sglang/srt/managers/overlap_utils.py +index 41d97577dd..afbb183e7b 100644 +--- a/python/sglang/srt/managers/overlap_utils.py ++++ b/python/sglang/srt/managers/overlap_utils.py +@@ -84,6 +84,32 @@ def _assert_nonneg_and_invalidate( + buf[indices] = -1 + + ++class FutureRelayBuffers: ++ """Seq-lens / bonus buffers a static verify graph scatters into; captured before ++ the FutureMap exists, which adopts them (SGLANG_OPT_DSV41_DSPARK_POST_FOLD).""" ++ ++ def __init__(self, *, req_pool_size: int, device) -> None: ++ self.new_seq_lens = torch.empty( ++ (req_pool_size,), dtype=torch.int64, device=device ++ ) ++ self.output_tokens = torch.empty( ++ (req_pool_size,), dtype=torch.int64, device=device ++ ) ++ self.adopted = False ++ # The step's accept outputs the graph already scattered: publish / stash of ++ # these very tensors skip their scatter (strong refs, so ids never recycle). ++ self.published_seq_lens: Optional[torch.Tensor] = None ++ self.published_bonus: Optional[torch.Tensor] = None ++ ++ ++_offered_relay: Optional[FutureRelayBuffers] = None ++ ++ ++def offer_future_relay_buffers(relay: FutureRelayBuffers) -> None: ++ global _offered_relay ++ _offered_relay = relay ++ ++ + def resolve_forward_inputs(batch: ScheduleBatch, future_map: FutureMap) -> None: + """Materialize input_ids at forward entry. Two sources: + +@@ -257,6 +283,8 @@ class FutureMap: + publish/stash; next iter reads via resolve_forward_inputs / resolve_seq_lens_cpu. + """ + ++ _relay = None ++ + def __init__( + self, + device: torch.device, +@@ -326,6 +354,21 @@ class FutureMap: + req_pool_size=self.req_pool_size, + pool=req_to_token_pool, + ) ++ self._relay: Optional[FutureRelayBuffers] = None ++ if ( ++ _offered_relay is not None ++ and _offered_relay.new_seq_lens.shape[0] == self.req_pool_size ++ ): ++ self._adopt_relay(_offered_relay) ++ ++ def _adopt_relay(self, relay: FutureRelayBuffers) -> None: ++ if _DEBUG_ASSERT: ++ relay.new_seq_lens.fill_(-1) ++ relay.output_tokens.fill_(-1) ++ self.new_seq_lens_buf = relay.new_seq_lens ++ self.output_tokens_buf = relay.output_tokens ++ relay.adopted = True ++ self._relay = relay + + def _maybe_init_forward_bufs(self, payload: RelayPayload) -> None: + # Local import (see decide_needs_cpu_seq_lens): keep module-level deps leaf. +@@ -612,7 +655,13 @@ class FutureMap: + indices = future_indices + if indices.shape[0] == 0: + return # DP idle +- self.new_seq_lens_buf[indices] = new_seq_lens.to(self.new_seq_lens_buf.dtype) ++ relay = self._relay ++ if relay is not None and new_seq_lens is relay.published_seq_lens: ++ relay.published_seq_lens = None ++ else: ++ self.new_seq_lens_buf[indices] = new_seq_lens.to( ++ self.new_seq_lens_buf.dtype ++ ) + publish_confidence = self.needs_confidence_relay and confidence is not None + if publish_confidence: + self.confidence_relay.scatter(indices, confidence) +@@ -640,9 +689,13 @@ class FutureMap: + return + self._maybe_init_forward_bufs(payload) + self._maybe_init_dsa_topk_indices_buf(payload) +- self.output_tokens_buf[indices] = payload.bonus_tokens.to( +- self.output_tokens_buf.dtype +- ) ++ relay = self._relay ++ if relay is not None and payload.bonus_tokens is relay.published_bonus: ++ relay.published_bonus = None ++ else: ++ self.output_tokens_buf[indices] = payload.bonus_tokens.to( ++ self.output_tokens_buf.dtype ++ ) + + # Staging transitions refresh only the bonus token. Preserve top-k and + # hidden state already published by the preceding target forward. +diff --git a/python/sglang/srt/mem_cache/kv_index_translator.py b/python/sglang/srt/mem_cache/kv_index_translator.py +index 821c8509cd..d4856188ff 100644 +--- a/python/sglang/srt/mem_cache/kv_index_translator.py ++++ b/python/sglang/srt/mem_cache/kv_index_translator.py +@@ -304,6 +304,9 @@ class KVIndexTranslator: + seq_lens: torch.Tensor, + seq_lens_cpu: Optional[torch.Tensor], + width: int, ++ positions_out: Optional[torch.Tensor] = None, ++ anchor_src: Optional[torch.Tensor] = None, ++ anchor_out: Optional[torch.Tensor] = None, + ) -> KVLocPlan: + """Gather one fixed-width speculative window, translating at its producer. + +@@ -341,6 +344,9 @@ class KVIndexTranslator: + full_out=writes.get(IdSpaceKind.FULL), + swa_out=writes.get(IdSpaceKind.SLIDING_WINDOW), + page_size=self.page_size, ++ positions_out=positions_out, ++ anchor_src=anchor_src, ++ anchor_out=anchor_out, + ) + return self.plan( + req_pool_indices=req_pool_indices, +diff --git a/python/sglang/srt/model_executor/cuda_graph_buffer_registry.py b/python/sglang/srt/model_executor/cuda_graph_buffer_registry.py +index 385f099090..3ac4da6da1 100644 +--- a/python/sglang/srt/model_executor/cuda_graph_buffer_registry.py ++++ b/python/sglang/srt/model_executor/cuda_graph_buffer_registry.py +@@ -31,6 +31,7 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple + + import torch + ++from sglang.srt.environ import envs + from sglang.srt.model_executor.input_buffers import ( + INDEX_SEMANTIC_BUFFERS, + share_input_buffer, +@@ -58,6 +59,12 @@ def _grouped_foreach_copy_(dsts: List[torch.Tensor], srcs: List[torch.Tensor]) - + dst.copy_(src) + + if dsts and dsts[0].is_cuda: ++ fast_path = envs.SGLANG_OPT_CUDA_GRAPH_FILL_FAST_PATH.get() ++ if fast_path and _has_foreach_copy and _one_dense_int_pair(dsts, srcs): ++ # One foreach launch already writes what the small copy would; that kernel ++ # pays off only across dtype pairs, and costs per-pair host checks. ++ torch._foreach_copy_(dsts, srcs) ++ return + from sglang.kernels.ops.memory.small_copy import try_small_copy + + if try_small_copy(dsts, srcs): +@@ -74,6 +81,28 @@ def _grouped_foreach_copy_(dsts: List[torch.Tensor], srcs: List[torch.Tensor]) - + _foreach_copy(group_dsts, group_srcs) + + ++def _one_dense_int_pair(dsts: List[torch.Tensor], srcs: List[torch.Tensor]) -> bool: ++ # One integer / bool (dst, src) dtype pair over contiguous tensors. ++ pair = (dsts[0].dtype, srcs[0].dtype) ++ if any(dtype.is_floating_point or dtype.is_complex for dtype in pair): ++ return False ++ return all( ++ (dst.dtype, src.dtype) == pair and dst.is_contiguous() and src.is_contiguous() ++ for dst, src in zip(dsts, srcs) ++ ) ++ ++ ++def same_tensor_view(a: torch.Tensor, b: torch.Tensor) -> bool: ++ """Whether ``a`` and ``b`` view the same elements of the same storage.""" ++ return ( ++ a.data_ptr() == b.data_ptr() ++ and a.device == b.device ++ and a.dtype == b.dtype ++ and a.shape == b.shape ++ and a.stride() == b.stride() ++ ) ++ ++ + class PaddingPolicy(Enum): + """How to handle ``raw_n < padded_n`` for a slot. + +@@ -394,8 +423,10 @@ class CudaGraphBufferRegistry: + raw_num_tokens: int, + padded_num_tokens: int, + pp_proxy_tensors: Optional[Any] = None, ++ skip_slots: frozenset = frozenset(), + ) -> None: +- """Copy FB → registry buffers. ++ """Copy FB → registry buffers; ``skip_slots`` are left untouched (their ++ content was staged by ``copy_slots``). + + Phase 1 — reset the padded tail per slot ``padding_policy``. + Phase 2 — grouped D2D copy of all enabled slots from FB (or from a +@@ -419,13 +450,19 @@ class CudaGraphBufferRegistry: + pp_proxy_tensors=pp_proxy_tensors, + ) + +- # Phase 1: reset padded regions where it matters. +- for slot in self._slots.values(): +- if not slot.enabled or slot.buffer is None: +- continue +- raw_n = slot._raw_n(raw_bs, raw_num_tokens) +- padded_n = slot._padded_n(padded_bs, padded_num_tokens) +- slot.reset_padding(raw_n, padded_n) ++ # Phase 1: reset padded regions where it matters (none when neither ++ # axis is padded: reset_padding is then a no-op for every slot). ++ if ( ++ not envs.SGLANG_OPT_CUDA_GRAPH_FILL_FAST_PATH.get() ++ or raw_bs < padded_bs ++ or raw_num_tokens < padded_num_tokens ++ ): ++ for slot in self._slots.values(): ++ if not slot.enabled or slot.buffer is None or slot.name in skip_slots: ++ continue ++ raw_n = slot._raw_n(raw_bs, raw_num_tokens) ++ padded_n = slot._padded_n(padded_bs, padded_num_tokens) ++ slot.reset_padding(raw_n, padded_n) + + # Phase 2: collect (dst, src) pairs and dispatch a grouped copy. + gpu_dsts: List[torch.Tensor] = [] +@@ -433,7 +470,12 @@ class CudaGraphBufferRegistry: + cpu_dsts: List[torch.Tensor] = [] + cpu_srcs: List[torch.Tensor] = [] + for slot in self._slots.values(): +- if not slot.enabled or slot.buffer is None or not slot.copy_from_fb: ++ if ( ++ not slot.enabled ++ or slot.buffer is None ++ or not slot.copy_from_fb ++ or slot.name in skip_slots ++ ): + continue + if slot.source_fn is not None: + # Structured / side-sourced slot: source comes from a nested FB +@@ -473,10 +515,28 @@ class CudaGraphBufferRegistry: + + # Phase 3: post-fill hooks (compute-then-write slots). + for slot in self._slots.values(): +- if not slot.enabled or slot.buffer is None or slot.post_fill is None: ++ if ( ++ not slot.enabled ++ or slot.buffer is None ++ or slot.post_fill is None ++ or slot.name in skip_slots ++ ): + continue + slot.post_fill(slot.buffer, forward_batch, ctx) + ++ def copy_slots(self, sources: Dict[str, torch.Tensor]) -> None: ++ """``fill_from`` for an unpadded batch, by slot name: no padding reset or hooks, ++ and no copy for a source that already is the slot's view.""" ++ dsts: List[torch.Tensor] = [] ++ srcs: List[torch.Tensor] = [] ++ for name, src in sources.items(): ++ dst = self._slots[name].buffer[: src.shape[0]] ++ if not same_tensor_view(dst, src): ++ dsts.append(dst) ++ srcs.append(src) ++ if dsts: ++ _grouped_foreach_copy_(dsts, srcs) ++ + def extract_buffer( + self, + *, +diff --git a/python/sglang/srt/model_executor/model_runner.py b/python/sglang/srt/model_executor/model_runner.py +index e646d19803..4ecea9e358 100644 +--- a/python/sglang/srt/model_executor/model_runner.py ++++ b/python/sglang/srt/model_executor/model_runner.py +@@ -391,6 +391,8 @@ class ModelRunner: + get_spec().speculative_algorithm + ) + self.capture_tail_hooks = [] ++ # Called as hook(graph_runner, forward_batch) first inside each decode graph capture. ++ self.capture_head_hooks = [] + self.page_size = get_schedule().page_size + self.req_to_token_pool = req_to_token_pool + self.token_to_kv_pool_allocator = token_to_kv_pool_allocator +diff --git a/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py b/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py +index 889f69360e..664cb93d55 100644 +--- a/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py ++++ b/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py +@@ -48,7 +48,9 @@ from sglang.srt.layers.attention.base_attn_backend import ( + ) + from sglang.srt.layers.attention.dsa.utils import is_dsa_enable_prefill_cp + from sglang.srt.layers.attention.graph_variants import ( ++ DSV41_EARLY_VERIFY_VARIANTS, + AttentionGraphVariants, ++ Dsv41CandidateGraphVariants, + create_attention_graph_variants, + create_dsv41_candidate_graph_variants, + ) +@@ -81,6 +83,11 @@ from sglang.srt.model_executor.runner.base_cuda_graph_runner import ( + freeze_gc, + get_batch_sizes_to_capture, + ) ++from sglang.srt.model_executor.runner.early_verify_metadata import ( ++ STAGED_SLOTS, ++ EarlyVerifyMetadata, ++ VerifyInputSources, ++) + from sglang.srt.model_executor.runner.flashinfer_autotune import ( + maybe_flashinfer_autotune_speculative_draft, + ) +@@ -95,11 +102,16 @@ from sglang.srt.model_executor.runner_utils.buffers import DecodeInputBuffers + from sglang.srt.model_executor.runner_utils.capture_mode import ( + _set_capture_attention_variant, + _set_capture_lora_variant, ++ get_capture_attention_variant, + model_capture_mode, + ) + from sglang.srt.model_executor.runner_utils.deepep_adapter import ( + DeepEPCudaGraphRunnerAdapter, + ) ++from sglang.srt.model_executor.runner_utils.forked_metadata_prep import ( ++ fork_in_graph_metadata_prep, ++ join_in_graph_metadata_prep, ++) + from sglang.srt.model_executor.runner_utils.pool import ( + get_or_create_global_graph_capture_stream, + ) +@@ -128,6 +140,20 @@ except ImportError: + + logger = logging.getLogger(__name__) + ++ ++@contextlib.contextmanager ++def _attention_variant_during_prep(attention_variant): ++ before = get_capture_attention_variant() ++ _set_capture_attention_variant(attention_variant) ++ try: ++ yield ++ finally: ++ _set_capture_attention_variant(before) ++ ++ ++# Draft metadata glue: steps between two "draft glue" tally lines per rank ++DRAFT_GLUE_LOG_EVERY = 1000 ++ + if TYPE_CHECKING: + from sglang.srt.model_executor.model_runner import ModelRunner + from sglang.srt.speculative.spec_info import SpeculativeAlgorithm +@@ -224,8 +250,21 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + pluggable self.backend that handles the actual capture/replay. + """ + ++ _draft_glue_logged = 0 ++ + dllm_input_preparation = None + dllm_attention = None ++ # Set in __init__: which DSpark runner's prep the glue graph serves past the guard. ++ _draft_metadata_glue = False ++ _target_metadata_glue = False ++ _metadata_prep_fork: Optional[tuple] = None ++ _metadata_prep_fork_resolved = False ++ _early_verify_metadata = None ++ _skips_prefilled_inputs = False ++ _prefilled_inputs: Optional[tuple] = None ++ num_prefilled_input_skips = 0 ++ # SGLANG_OPT_SKIP_GLUED_REPLAY_VIEW, read in __init__. ++ _skip_glued_replay_view = False + + def __init__( + self, +@@ -241,6 +280,14 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + + # In-graph metadata prep: shared buffers -> in-graph private data + self.in_graph_metadata_prep_done: Optional[torch.cuda.Event] = None ++ # SGLANG_OPT_DSV41_DSPARK_SKIP_PREFILLED_INPUTS: the (input_ids, positions) ++ # tensors the plan-time load already copied into this runner's buffers. ++ self._prefilled_inputs: Optional[tuple] = None ++ self.num_prefilled_input_skips = 0 ++ # SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK: (stream, event) the draft graph's ++ # in-graph metadata prep is forked onto; resolved at the first capture. ++ self._metadata_prep_fork: Optional[tuple] = None ++ self._metadata_prep_fork_resolved = False + + # --- core state ------------------------------------------------ + self.enable_torch_compile = get_flags().capture.enable_torch_compile +@@ -446,7 +493,11 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + ), + aux_hidden_states_width=self.model_runner.get_aux_hidden_states_width(), + ) +- self.buffers.share_buffers() ++ # The early verify metadata writes these slots beside the draft graph, which ++ # must not share their storage through the process-wide pool. ++ self.buffers.share_buffers( ++ exclude=STAGED_SLOTS if self._wants_early_verify_metadata() else () ++ ) + # FB-shared slot registry adopting DecodeInputBuffers storage (same + # physical tensors, stable data_ptr for capture vs replay). Provides + # the unified fill_from / slot access surface for capture/replay. +@@ -497,6 +548,39 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + self._metadata_glue = ( + MetadataGlueGraph(self.device) if enable_metadata_glue else None + ) ++ # The DSpark draft runner's prep has no host-fed plan, so the guard above does ++ # not apply where its backend says so. ++ self._draft_metadata_glue = ( ++ self._metadata_glue is None and self._glues_draft_metadata() ++ ) ++ # Likewise the DSpark target verify runner's static prep, behind its own switch. ++ self._target_metadata_glue = ( ++ not self._draft_metadata_glue ++ and self._metadata_glue is None ++ and self._glues_target_verify_metadata() ++ ) ++ self._draft_glue_logged = 0 ++ self._skips_prefilled_inputs = self._resolve_skips_prefilled_inputs() ++ if self._draft_metadata_glue or self._target_metadata_glue: ++ self._metadata_glue = MetadataGlueGraph(self.device) ++ self._skip_glued_replay_view = envs.SGLANG_OPT_SKIP_GLUED_REPLAY_VIEW.get() ++ # SGLANG_OPT_DSV41_TARGET_METADATA_EARLY: the verify's inputs and metadata glue ++ # graph run on a side stream beside the draft graph (stage_verify_metadata_early). ++ self._early_verify_metadata: Optional[EarlyVerifyMetadata] = ( ++ EarlyVerifyMetadata(device=self.device, log_every=10000) ++ if self._wants_early_verify_metadata() ++ and self._target_metadata_glue ++ and not self.enable_pdmux ++ and self.model_runner.lora_manager is None ++ else None ++ ) ++ if self._early_verify_metadata is not None: ++ self.attn_backend.enable_early_verify_metadata() ++ logger.info( ++ "Target verify metadata staged on a side stream beside the draft graph " ++ "for variants %s.", ++ sorted(DSV41_EARLY_VERIFY_VARIANTS), ++ ) + + # --- backend --------------------------------------------------- + self.backend = resolve_decode_backend(self) +@@ -514,6 +598,51 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + """Rows reserved for the largest shared logits output.""" + return max_num_tokens + ++ def _forks_draft_metadata_prep(self) -> bool: ++ from sglang.srt.layers.attention.deepseek_v4_backend import ( ++ DeepseekV4AttnBackend, ++ ) ++ from sglang.srt.layers.attention.dsv4.unified_kv_gate import ( ++ is_unified_kv_triton, ++ ) ++ ++ return ( ++ envs.SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK.get() ++ # The unified-KV store location is not a join point. ++ and not is_unified_kv_triton() ++ and self.model_runner.spec_algorithm.is_dspark() ++ and self.model_runner.is_draft_worker ++ and self.capture_forward_mode == ForwardMode.TARGET_VERIFY ++ # Its KV store-location reads are where the forked prep joins. ++ and isinstance(self.attn_backend, DeepseekV4AttnBackend) ++ and self.device_module is torch.cuda ++ and not get_exec().graph.debug_cuda_graph ++ and not self.enable_torch_compile ++ and not get_parallel().attn_dp_enabled ++ and not self.enable_two_batch_overlap ++ and not self.enable_pdmux ++ and self.model_runner.lora_manager is None ++ ) ++ ++ def _run_in_graph_metadata_prep(self, attn_backend, forward_batch) -> None: ++ def prep(): ++ attn_backend.init_forward_metadata_in_graph(forward_batch) ++ self._record_in_graph_metadata_prep_done() ++ ++ if not self._metadata_prep_fork_resolved: ++ self._metadata_prep_fork_resolved = True ++ if self._forks_draft_metadata_prep(): ++ self._metadata_prep_fork = (torch.cuda.Stream(), torch.cuda.Event()) ++ logger.info( ++ "SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK: draft in-graph " ++ "metadata prep forked onto a side stream." ++ ) ++ if self._metadata_prep_fork is None: ++ prep() ++ return ++ stream, done = self._metadata_prep_fork ++ fork_in_graph_metadata_prep(stream=stream, done=done, prep=prep) ++ + def _record_in_graph_metadata_prep_done(self): + # Purely a marker at this point in the graph; where the shared reads + # actually end is the attn backend's call. +@@ -1269,10 +1398,11 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + ForwardContext(attn_backend=attn_backend), + forward_batch=forward_batch, + ): ++ for capture_hook in self.model_runner.capture_head_hooks: ++ capture_hook(self, forward_batch) + # Backends may gather live pool mappings into their static + # metadata here; these nodes run before any model KV reads. +- attn_backend.init_forward_metadata_in_graph(forward_batch) +- self._record_in_graph_metadata_prep_done() ++ self._run_in_graph_metadata_prep(attn_backend, forward_batch) + + forward_batch.dp_local_start_pos = ( + forward_batch.dp_local_num_tokens +@@ -1322,6 +1452,11 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + forward_batch, + **kwargs, + ) ++ if join_in_graph_metadata_prep(): ++ raise RuntimeError( ++ "The draft forward never joined its forked metadata prep; " ++ "unset SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK." ++ ) + for capture_hook in self.model_runner.capture_tail_hooks: + capture_hook(self, out, forward_batch, num_tokens) + return out +@@ -1420,8 +1555,7 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + ) + self._stage_ragged_verify_layout(ragged_layout, graph_size_key) + self._set_dp_real_num_tokens(self.raw_num_token) +- self.buffers.input_ids[: self.raw_num_token].copy_(forward_batch.input_ids) +- self.buffers.positions[: self.raw_num_token].copy_(forward_batch.positions) ++ self._copy_replay_inputs(forward_batch) + if ( + pp_proxy_tensors is not None + and self.buffers.pp_proxy_tensors is not None +@@ -1488,6 +1622,13 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + bs=bs, num_tokens=padded_num_tokens + ) + ++ attention_variant = self._resolve_attention_variant(forward_batch, bs) ++ glue_key = self._glue_key( ++ bs, str(forward_batch.forward_mode), attention_variant ++ ) ++ early_staged = self._take_early_verify_metadata( ++ forward_batch, raw_bs=raw_bs, bs=bs, is_ragged=is_ragged, key=glue_key ++ ) + self.buffer_registry.fill_from( + forward_batch, + raw_bs=raw_bs, +@@ -1495,7 +1636,10 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + raw_num_tokens=raw_num_token, + padded_num_tokens=padded_num_tokens, + pp_proxy_tensors=pp_proxy_tensors, ++ skip_slots=STAGED_SLOTS if early_staged else frozenset(), + ) ++ if self._skips_prefilled_inputs: ++ self._prefilled_inputs = (forward_batch.input_ids, forward_batch.positions) + + if ( + not is_ragged +@@ -1526,14 +1670,117 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + ): + forward_batch.spec_info.custom_mask = buffers.custom_mask + ++ self._init_replay_attn_metadata( ++ forward_batch, ++ raw_bs=raw_bs, ++ bs=bs, ++ num_tokens=padded_num_tokens, ++ glue_key=glue_key, ++ early_staged=early_staged, ++ attention_variant=attention_variant, ++ ) ++ if self._draft_metadata_glue or self._target_metadata_glue: ++ self._maybe_log_draft_glue() ++ ++ self.raw_bs = raw_bs ++ self.raw_num_token = raw_num_token ++ self.bs = bs ++ if is_ragged: ++ self._ragged_graph_size = graph_size_key ++ ++ if self.model_runner.hisparse_coordinator is not None: ++ self.model_runner.hisparse_coordinator.num_real_reqs.fill_(raw_bs) ++ ++ variant_label = self._resolve_lora_variant(forward_batch) ++ if self._early_verify_metadata is not None: ++ self._early_verify_metadata.count_variant( ++ attention_variant, taken=early_staged ++ ) ++ stream_idx = get_current_stream_idx() if self.enable_pdmux else None ++ self._replay_graph_key = self._make_graph_key( ++ graph_size_key, stream_idx, variant_label, attention_variant ++ ) ++ ++ def _glues_draft_metadata(self) -> bool: ++ """Whether this draft runner's metadata prep runs through the glue graph: a ++ static-verify draft runner whose backend accepts it.""" ++ if not self.model_runner.is_draft_worker: ++ return False ++ if envs.SGLANG_RAGGED_VERIFY_MODE.get() != "static": ++ why = "ragged verify" ++ else: ++ why = self.attn_backend.glue_draft_metadata() ++ if why: ++ logger.info("Draft metadata glue graph off: %s.", why) ++ return False ++ logger.info("Draft metadata prep through the glue graph, one per replay key.") ++ return True ++ ++ def _init_replay_attn_metadata( ++ self, ++ forward_batch: ForwardBatch, ++ *, ++ raw_bs: int, ++ bs: int, ++ num_tokens: int, ++ glue_key: tuple, ++ early_staged: bool, ++ attention_variant, ++ ) -> None: ++ """The attention backend's out-of-graph metadata prep for this replay.""" ++ # Glue-graph fast path: pointer-stable prep (static buffers + pool ++ # tensors only) is captured per key; guards keep every python-visible ++ # branch inside the backends constant for that key. ++ glue_route = ( ++ self._metadata_glue is not None ++ and not self._metadata_glue.disabled ++ and raw_bs == bs ++ and not self.enable_two_batch_overlap ++ and not self.enable_pdmux ++ and self.model_runner.lora_manager is None ++ ) ++ if early_staged: ++ # The side stream already replayed the glue graph for this step's inputs. ++ self._metadata_glue.reinstall(glue_key) ++ elif ( ++ glue_route ++ and self._skip_glued_replay_view ++ and isinstance(self._metadata_glue, MetadataGlueGraph) ++ and self._metadata_glue.is_captured(glue_key) ++ ): ++ # A captured glue graph reads slots and backend buffers by address: no ++ # replay view, no out_cache_loc re-point. ++ self._metadata_glue.replay(glue_key) ++ else: ++ self._init_replay_attn_metadata_from_view( ++ forward_batch, ++ raw_bs=raw_bs, ++ bs=bs, ++ num_tokens=num_tokens, ++ glue_key=glue_key if glue_route else None, ++ attention_variant=attention_variant, ++ ) ++ ++ def _init_replay_attn_metadata_from_view( ++ self, ++ forward_batch: ForwardBatch, ++ *, ++ raw_bs: int, ++ bs: int, ++ num_tokens: int, ++ glue_key: Optional[tuple], ++ attention_variant, ++ ) -> None: ++ """The replay metadata prep through the replay ForwardBatch view: the glue ++ graph's warm-ups and capture (``glue_key``), or the eager prep (None).""" + attn_backend = self._replay_attn_backend() + fb_view = build_replay_fb_view( + forward_batch=forward_batch, +- buffers=buffers, ++ buffers=self.buffers, + bs=bs, + raw_bs=raw_bs, +- num_tokens=padded_num_tokens, +- global_num_tokens_cpu=self._global_num_tokens_for_graph(padded_num_tokens), ++ num_tokens=num_tokens, ++ global_num_tokens_cpu=self._global_num_tokens_for_graph(num_tokens), + seq_len_fill_value=self.seq_len_fill_value, + capture_forward_mode=self.capture_forward_mode, + is_encoder_decoder=self.is_encoder_decoder, +@@ -1545,50 +1792,177 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): + self.model_runner.lora_manager.prepare_lora_batch( + cast(ForwardBatch, fb_view) + ) +- # Glue-graph fast path: pointer-stable prep (static buffers + pool +- # tensors only) is captured per key; guards keep every python-visible +- # branch inside the backends constant for that key. +- if ( +- self._metadata_glue is not None +- and not self._metadata_glue.disabled +- and raw_bs == bs ++ if glue_key is not None: ++ self._glue_draft_inputs(fb_view) ++ with self._prep_attention_variant(attention_variant): ++ self._metadata_glue.run(attn_backend, fb_view, glue_key) ++ else: ++ if self._metadata_glue is not None: ++ self._metadata_glue.note_not_routed() ++ with self._prep_attention_variant(attention_variant): ++ attn_backend.init_forward_metadata_out_graph(fb_view) ++ ++ def _wants_early_verify_metadata(self) -> bool: ++ """SGLANG_OPT_DSV41_TARGET_METADATA_EARLY, from facts fixed before the buffers ++ are shared.""" ++ return ( ++ envs.SGLANG_OPT_DSV41_TARGET_METADATA_EARLY.get() ++ and self.capture_forward_mode == ForwardMode.TARGET_VERIFY ++ and not self.model_runner.is_draft_worker ++ and self.model_runner.spec_algorithm.is_dspark() ++ and not self.ragged_verify_mode ++ and torch.device(self.model_runner.device).type == "cuda" ++ and not get_parallel().attn_dp_enabled ++ and not self.require_gathered_buffer + and not self.enable_two_batch_overlap +- and not self.enable_pdmux +- and self.model_runner.lora_manager is None ++ ) ++ ++ def _glue_key(self, bs: int, actual_mode: str, attention_variant) -> tuple: ++ # actual_forward_mode belongs in the key even though the captured graph always ++ # targets capture_forward_mode: DSV4's replay prep substitutes seq_lens / ++ # seq_lens_cpu / seq_lens_sum / req_pool_indices / out_cache_loc when the ++ # runtime mode is IDLE, so IDLE and active DECODE are different python branches ++ # and must not share a captured graph. Under the early metadata the variant ++ # picks the prep's branch too (early install or Raw copy). ++ key = (bs, str(self.capture_forward_mode), actual_mode) ++ if self._early_verify_metadata is None: ++ return key ++ return key + (attention_variant,) ++ ++ def _prep_attention_variant(self, attention_variant): ++ """The variant set while this replay's prep runs in python, so the backend ++ builds the metadata the variant's graph reads (early metadata only).""" ++ if self._early_verify_metadata is None: ++ return contextlib.nullcontext() ++ return _attention_variant_during_prep(attention_variant) ++ ++ def _early_variant_for(self, max_seq_len: Optional[int]) -> Optional[str]: ++ variants = self.attention_graph_variants ++ if not isinstance(variants, Dsv41CandidateGraphVariants): ++ return None ++ return variants.select_for_max_seq_len(max_seq_len) ++ ++ def stage_verify_metadata_early( ++ self, ++ *, ++ seq_lens: torch.Tensor, ++ req_pool_indices: torch.Tensor, ++ out_cache_loc: Optional[torch.Tensor], ++ positions: torch.Tensor, ++ max_seq_len: Optional[int], ++ after: torch.cuda.Event, ++ ) -> bool: ++ """After the draft launch, stage the verify inputs and glue replay on a side ++ stream waiting on ``after``; False when this batch cannot be staged.""" ++ early = self._early_verify_metadata ++ if early is None: ++ return False ++ bs = seq_lens.shape[0] ++ num_tokens = bs * self.captured_req_width ++ variant = self._early_variant_for(max_seq_len) ++ key = self._glue_key(bs, str(ForwardMode.TARGET_VERIFY), variant) ++ if ( ++ bs not in self.capture_bs ++ or variant not in DSV41_EARLY_VERIFY_VARIANTS ++ or positions.shape[0] != num_tokens ++ or out_cache_loc is None ++ or out_cache_loc.shape[0] != num_tokens ++ or not self._metadata_glue.is_captured(key) + ): +- # actual_forward_mode belongs in the key even though the captured +- # graph always targets capture_forward_mode: DSV4's replay prep +- # substitutes seq_lens / seq_lens_cpu / seq_lens_sum / +- # req_pool_indices / out_cache_loc when the runtime mode is IDLE, +- # so IDLE and active DECODE are different python branches and must +- # not share a captured graph. +- self._metadata_glue.run( +- attn_backend, +- fb_view, +- ( +- bs, +- str(self.capture_forward_mode), +- str(fb_view.actual_forward_mode), +- ), ++ early.discard() ++ return False ++ early.stage( ++ glue=self._metadata_glue, ++ key=key, ++ registry=self.buffer_registry, ++ sources=VerifyInputSources( ++ positions=positions, ++ out_cache_loc=out_cache_loc, ++ req_pool_indices=req_pool_indices, ++ seq_lens=seq_lens, ++ ), ++ after=after, ++ ) ++ return True ++ ++ def _take_early_verify_metadata( ++ self, forward_batch: ForwardBatch, *, raw_bs: int, bs: int, is_ragged: bool, key ++ ) -> bool: ++ early = self._early_verify_metadata ++ if early is None: ++ return False ++ if is_ragged or raw_bs != bs or not self._metadata_glue.is_captured(key): ++ early.discard() ++ return False ++ return early.take(key=key, forward_batch=forward_batch) ++ ++ def _copy_replay_inputs(self, forward_batch: ForwardBatch) -> None: ++ prefilled = self._prefilled_inputs ++ self._prefilled_inputs = None ++ # The plan-time load (or the early stage it took) filled these from the very ++ # same tensors. ++ if prefilled is None or forward_batch.input_ids is not prefilled[0]: ++ self.buffers.input_ids[: self.raw_num_token].copy_(forward_batch.input_ids) ++ if prefilled is None or forward_batch.positions is not prefilled[1]: ++ self.buffers.positions[: self.raw_num_token].copy_(forward_batch.positions) ++ if prefilled is not None: ++ self._note_prefilled_input_skip() ++ ++ def _note_prefilled_input_skip(self) -> None: ++ self.num_prefilled_input_skips += 1 ++ if self.num_prefilled_input_skips == 1: ++ logger.info( ++ "Pre-planned verify replay skipped its input_ids / positions " ++ "re-copy (first step)." + ) +- else: +- attn_backend.init_forward_metadata_out_graph(fb_view) + +- self.raw_bs = raw_bs +- self.raw_num_token = raw_num_token +- self.bs = bs +- if is_ragged: +- self._ragged_graph_size = graph_size_key ++ def _resolve_skips_prefilled_inputs(self) -> bool: ++ """The DSpark target verify runner, whose verify batches are pre-planned by ++ prepare_for_verify and then replayed from the same tensors.""" ++ return ( ++ envs.SGLANG_OPT_DSV41_DSPARK_SKIP_PREFILLED_INPUTS.get() ++ and not self.model_runner.is_draft_worker ++ and self.capture_forward_mode == ForwardMode.TARGET_VERIFY ++ and self.model_runner.spec_algorithm.is_dspark() ++ ) + +- if self.model_runner.hisparse_coordinator is not None: +- self.model_runner.hisparse_coordinator.num_real_reqs.fill_(raw_bs) ++ def _glues_target_verify_metadata(self) -> bool: ++ """Whether this DSpark target verify runner's metadata prep runs through the ++ glue graph: switched on, and its backend declares the prep host-free.""" ++ if ( ++ not envs.SGLANG_OPT_DSV41_TARGET_VERIFY_METADATA_GLUE.get() ++ or self.model_runner.is_draft_worker ++ or self.capture_forward_mode != ForwardMode.TARGET_VERIFY ++ or not self.model_runner.spec_algorithm.is_dspark() ++ ): ++ return False ++ why = self.attn_backend.glue_target_verify_metadata() ++ if why: ++ logger.info("Target verify metadata glue graph off: %s.", why) ++ return False ++ logger.info("Target verify metadata prep through the glue graph, one per key.") ++ return True ++ ++ def _maybe_log_draft_glue(self) -> None: ++ glue = self._metadata_glue ++ steps = glue.replays + glue.eager ++ if steps >= self._draft_glue_logged + DRAFT_GLUE_LOG_EVERY: ++ self._draft_glue_logged = steps ++ logger.debug( ++ "%s glue: %d graph replays, %d eager (since warm-up)", ++ "target verify" if self._target_metadata_glue else "draft", ++ glue.replays, ++ glue.eager, ++ ) + +- variant_label = self._resolve_lora_variant(forward_batch) +- attention_variant = self._resolve_attention_variant(forward_batch, bs) +- stream_idx = get_current_stream_idx() if self.enable_pdmux else None +- self._replay_graph_key = self._make_graph_key( +- graph_size_key, stream_idx, variant_label, attention_variant +- ) ++ def _glue_draft_inputs(self, fb_view) -> None: ++ """The draft glue graph reads its inputs by address: out_cache_loc from the ++ registry slot fill_from just wrote, not the step's own (fresh) tensor.""" ++ if ( ++ self._draft_metadata_glue or self._target_metadata_glue ++ ) and fb_view.out_cache_loc is not None: ++ n = fb_view.out_cache_loc.shape[0] ++ fb_view.out_cache_loc = self.buffers.out_cache_loc[:n] + + def _ragged_graph_num_tokens(self, total_verify_tokens: int) -> int: + from sglang.srt.speculative.ragged_verify import round_up_grid +diff --git a/python/sglang/srt/model_executor/runner/early_verify_metadata.py b/python/sglang/srt/model_executor/runner/early_verify_metadata.py +new file mode 100644 +index 0000000000..81bc9c9db7 +--- /dev/null ++++ b/python/sglang/srt/model_executor/runner/early_verify_metadata.py +@@ -0,0 +1,149 @@ ++"""Target-verify attention metadata staged during the draft forward ++(SGLANG_OPT_DSV41_TARGET_METADATA_EARLY). ++ ++The verify inputs the metadata reads (positions, write locations, seq lens and ++req pool indices) are final once the decode head has run. ``stage``, which the host ++issues right after it launches the draft graph, copies them into the verify graph's ++buffers and replays the runner's captured metadata glue graph on a side stream that ++waits only for the head, so the GPU runs it beside the draft; the verify replay ++orders itself after that stream (``take``). Issued after the draft launch, the stage ++replaces the fill and glue replay the host would otherwise run before the verify, ++instead of adding host time before the draft. ++ ++Contract: ++ ++- The side stream first waits for the head's event, recorded on the current stream ++ after the previous verify replay, which has therefore finished reading the buffers ++ it rewrites. ++- The staged slots are private to the verify runner (never shared through the ++ process-wide input-buffer pool), so the draft graph neither reads nor writes ++ them; the glue graph writes only the verify backend's metadata. ++- ``take`` accepts the staged work only for the same glue key and the very same ++ source views; otherwise the current stream still waits for the side stream and ++ the runner refills and re-runs the glue graph itself. ++- Every staged record ends in a wait (``take`` or ``discard``) on the current ++ stream before anyone else refills the buffers. ++""" ++ ++from __future__ import annotations ++ ++import logging ++from typing import Any, Dict, Optional ++ ++import msgspec ++import torch ++ ++from sglang.srt.model_executor.cuda_graph_buffer_registry import ( ++ CudaGraphBufferRegistry, ++ same_tensor_view, ++) ++from sglang.srt.model_executor.runner.metadata_glue_graph import MetadataGlueGraph ++ ++logger = logging.getLogger(__name__) ++ ++ ++class VerifyInputSources(msgspec.Struct, frozen=True): ++ # input_ids is not staged: the draft graph may write it in place (mid fold). ++ positions: torch.Tensor ++ out_cache_loc: torch.Tensor ++ req_pool_indices: torch.Tensor ++ seq_lens: torch.Tensor ++ ++ ++STAGED_SLOTS = frozenset(VerifyInputSources.__struct_fields__) ++ ++ ++class _StagedVerifyInputs(msgspec.Struct, frozen=True): ++ key: Any ++ sources: VerifyInputSources ++ ++ ++class EarlyVerifyMetadata: ++ def __init__(self, *, device, log_every: int) -> None: ++ self._stream = torch.cuda.Stream(device=device) ++ self._done = torch.cuda.Event() ++ self._staged: Optional[_StagedVerifyInputs] = None ++ self._log_every = log_every ++ self.staged_ct = 0 ++ self.taken_ct = 0 ++ self.rejected_ct = 0 ++ # Per attention variant: [replays that took the staged metadata, replays]. ++ self.variant_cts: Dict[Any, list] = {} ++ ++ def stage( ++ self, ++ *, ++ glue: MetadataGlueGraph, ++ key, ++ registry: CudaGraphBufferRegistry, ++ sources: VerifyInputSources, ++ after: torch.cuda.Event, ++ ) -> None: ++ self.discard() ++ self._stream.wait_event(after) ++ slot_sources = msgspec.structs.asdict(sources) ++ with torch.cuda.stream(self._stream): ++ registry.copy_slots(slot_sources) ++ glue.replay(key) ++ self._done.record() ++ for src in slot_sources.values(): ++ src.record_stream(self._stream) ++ self._staged = _StagedVerifyInputs(key=key, sources=sources) ++ self.staged_ct += 1 ++ if self.staged_ct == 1 or self.staged_ct % self._log_every == 0: ++ logger.debug( ++ "Target verify metadata staged on the side stream: %d staged, " ++ "%d taken, %d rejected.", ++ self.staged_ct, ++ self.taken_ct, ++ self.rejected_ct, ++ ) ++ ++ def take(self, *, key, forward_batch) -> bool: ++ """True when this replay's inputs are the staged ones: the fill skips ++ ``STAGED_SLOTS`` and the glue graph already ran for ``key``.""" ++ staged = self._staged ++ if staged is None: ++ return False ++ self.discard() ++ src = staged.sources ++ matches = staged.key == key and all( ++ cur is not None and same_tensor_view(cur, staged_src) ++ for cur, staged_src in ( ++ (forward_batch.positions, src.positions), ++ (forward_batch.out_cache_loc, src.out_cache_loc), ++ (forward_batch.req_pool_indices, src.req_pool_indices), ++ (forward_batch.seq_lens, src.seq_lens), ++ ) ++ ) ++ if matches: ++ self.taken_ct += 1 ++ else: ++ self.rejected_ct += 1 ++ if self.rejected_ct == 1: ++ logger.info( ++ "Staged target verify metadata did not match the replay " ++ "(key %s vs %s); refilling on the main stream.", ++ staged.key, ++ key, ++ ) ++ return matches ++ ++ def count_variant(self, variant, *, taken: bool) -> None: ++ cts = self.variant_cts.setdefault(variant, [0, 0]) ++ cts[0] += taken ++ cts[1] += 1 ++ if cts[1] % self._log_every == 0: ++ logger.debug( ++ "Target verify replays of attention variant %s with staged metadata: " ++ "%d of %d.", ++ variant, ++ cts[0], ++ cts[1], ++ ) ++ ++ def discard(self) -> None: ++ """Order the current stream after any staged side-stream work.""" ++ if self._staged is not None: ++ torch.cuda.current_stream().wait_event(self._done) ++ self._staged = None +diff --git a/python/sglang/srt/model_executor/runner/metadata_glue_graph.py b/python/sglang/srt/model_executor/runner/metadata_glue_graph.py +index 1a6436b974..3f6cc1f135 100644 +--- a/python/sglang/srt/model_executor/runner/metadata_glue_graph.py ++++ b/python/sglang/srt/model_executor/runner/metadata_glue_graph.py +@@ -47,6 +47,10 @@ class MetadataGlueGraph: + def __init__(self, device): + self.device = device + self.disabled = False ++ # Since the first warm-up: prep steps served by a graph replay, and steps ++ # that ran eagerly after it (capture failure, disabled, or never routed here). ++ self.replays = 0 ++ self.eager = 0 + self._states: Dict[Any, dict] = {} + self._capture_stream = None + +@@ -55,6 +59,12 @@ class MetadataGlueGraph: + static buffers and backend state may have been rebuilt).""" + self._states.clear() + ++ def note_not_routed(self) -> None: ++ """A replay the caller prepared eagerly without calling ``run`` (padding, ++ TBO, pdmux, LoRA, disabled).""" ++ if self._states or self.disabled: ++ self.eager += 1 ++ + @staticmethod + def _leaves(attn_backend) -> List[Any]: + backends = [attn_backend] +@@ -62,6 +72,22 @@ class MetadataGlueGraph: + backends.extend(attn_backend.attn_backend_list) + return backends + ++ def is_captured(self, key) -> bool: ++ st = self._states.get(key) ++ return not self.disabled and st is not None and st["graph"] is not None ++ ++ def reinstall(self, key) -> None: ++ """Point each backend at the metadata ``key``'s graph writes.""" ++ for backend, metadata in self._states[key]["meta"]: ++ backend.forward_metadata = metadata ++ ++ def replay(self, key) -> None: ++ """Replay ``key``'s captured prep on the current stream (a staging side stream ++ included); the caller reinstalls its metadata before the forward.""" ++ self.reinstall(key) ++ self._states[key]["graph"].replay() ++ self.replays += 1 ++ + def run(self, attn_backend, fb_view, key) -> None: + """Run ``init_forward_metadata_out_graph`` for this replay, through the + captured glue graph once it is ready.""" +@@ -74,6 +100,7 @@ class MetadataGlueGraph: + for backend, metadata in st["meta"]: + backend.forward_metadata = metadata + st["graph"].replay() ++ self.replays += 1 + return + + if st["warmups"] < self.NUM_WARMUP: +@@ -85,7 +112,10 @@ class MetadataGlueGraph: + self._capture_stream = torch.cuda.Stream() + graph = torch.cuda.CUDAGraph() + try: +- with torch.cuda.graph(graph, stream=self._capture_stream): ++ # captured while serving: other threads may use CUDA meanwhile ++ with torch.cuda.graph( ++ graph, stream=self._capture_stream, capture_error_mode="thread_local" ++ ): + attn_backend.init_forward_metadata_out_graph(fb_view) + except Exception: + logger.warning( +@@ -95,6 +125,7 @@ class MetadataGlueGraph: + exc_info=True, + ) + self.disabled = True ++ self.eager += 1 + # Ops under a failed capture were recorded, not executed — run + # this step's prep for real. + attn_backend.init_forward_metadata_out_graph(fb_view) +diff --git a/python/sglang/srt/model_executor/runner_utils/forked_metadata_prep.py b/python/sglang/srt/model_executor/runner_utils/forked_metadata_prep.py +new file mode 100644 +index 0000000000..8b6494efeb +--- /dev/null ++++ b/python/sglang/srt/model_executor/runner_utils/forked_metadata_prep.py +@@ -0,0 +1,34 @@ ++"""The DSpark draft graph's in-graph metadata prep forked onto a side stream ++(SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK): embedding and the first layer's ++pre-attention run meanwhile, and the first draft attention joins it before it ++stores KV or reads the attention metadata.""" ++ ++from __future__ import annotations ++ ++from typing import Callable, Optional ++ ++import torch ++ ++_pending_join: Optional[torch.cuda.Event] = None ++ ++ ++def fork_in_graph_metadata_prep( ++ *, stream: torch.cuda.Stream, done: torch.cuda.Event, prep: Callable[[], None] ++) -> None: ++ global _pending_join ++ assert _pending_join is None, "previous forked metadata prep was never joined" ++ stream.wait_stream(torch.cuda.current_stream()) ++ with torch.cuda.stream(stream): ++ prep() ++ done.record() ++ _pending_join = done ++ ++ ++def join_in_graph_metadata_prep() -> bool: ++ """Make the current stream wait for a pending forked prep; True if one was.""" ++ global _pending_join ++ if _pending_join is None: ++ return False ++ torch.cuda.current_stream().wait_event(_pending_join) ++ _pending_join = None ++ return True +diff --git a/python/sglang/srt/models/deepseek_v4_dspark.py b/python/sglang/srt/models/deepseek_v4_dspark.py +index bcebe99303..0b0a8c676b 100644 +--- a/python/sglang/srt/models/deepseek_v4_dspark.py ++++ b/python/sglang/srt/models/deepseek_v4_dspark.py +@@ -851,9 +851,16 @@ class DeepseekV4ForCausalLMDSpark(nn.Module): + positions: torch.Tensor, + pool: DeepSeekV4TokenToKVPool, + ) -> None: ++ kvs = self.project_commit_kv(main_hidden=main_hidden, pool=pool) ++ self.store_commit_kv(kvs=kvs, swa_loc=swa_loc, positions=positions, pool=pool) ++ ++ def project_commit_kv( ++ self, *, main_hidden: torch.Tensor, pool: DeepSeekV4TokenToKVPool ++ ) -> List[torch.Tensor]: ++ """The context rows' per-stage KV, before norm / rope / store; reads no KV ++ location, so it can run before the accept decides what is committed.""" + main_x = self.project_target_hidden(main_hidden) +- swa_loc = swa_loc.to(torch.int32) +- kvs = CommitKvProj.execute( ++ return CommitKvProj.execute( + main_x=main_x, + wkv_linears=[stage.self_attn.wkv for stage in self.stages], + # The FlashMLA writer reads an explicit KV row stride, so views are fine. +@@ -863,6 +870,16 @@ class DeepseekV4ForCausalLMDSpark(nn.Module): + and not pool.uniform_fp8 + ), + ) ++ ++ def store_commit_kv( ++ self, ++ *, ++ kvs: List[torch.Tensor], ++ swa_loc: torch.Tensor, ++ positions: torch.Tensor, ++ pool: DeepSeekV4TokenToKVPool, ++ ) -> None: ++ swa_loc = swa_loc.to(torch.int32) + # Under unified_kv the swa_kv_pool is None; the caller passes a unified + # ring loc (state_slot * ring + pos % ring, -1 for uncommitted) so the + # store just needs to target the bf16 ring instead of the fp8 flashmla +diff --git a/python/sglang/srt/speculative/dspark_components/dspark_deferred_commit.py b/python/sglang/srt/speculative/dspark_components/dspark_deferred_commit.py +new file mode 100644 +index 0000000000..f34686ed52 +--- /dev/null ++++ b/python/sglang/srt/speculative/dspark_components/dspark_deferred_commit.py +@@ -0,0 +1,300 @@ ++"""The draft context-KV commit of a static verify, split around the accept ++(SGLANG_DSPARK_DEFER_CONTEXT_KV). ++ ++The commit projects the committed rows' target hidden into each draft stage's KV ++(GEMMs, independent of the accept) and stores the committed rows (needs the accept's ++commit lengths). In a static verify graph the projection is forked onto a side stream ++at the target's logits processor (a forward pre-hook, which SGLang's forward and a ++megakernel's head both call), so it overlaps the LM head and the accept; the static ++epilogue joins it and stages the store's arguments (write locations, positions, gated ++commit lengths, ring slots). The next captured draft graph runs the stores on a side ++stream forked at its head (a capture head hook); the draft's first KV store joins ++them (``join``, from the draft attention backend's ``get_swa_out_cache_loc``, which ++SGLang's draft attention and a megakernel's both reach on the store's stream). Any ++other forward runs the stores eagerly first. ++ ++Contract: ++ ++- Every write disarms the staging (commit lengths 0), so a staging is written once. ++- A forward that may write or read draft KV (prefill, draft extend, an eager draft) ++ runs after the pending write; a draft graph whose rows miss staged ones is preceded ++ by an eager write of every staged row. ++- Nothing reads draft KV between the verify and the next draft forward. ++""" ++ ++from __future__ import annotations ++ ++import logging ++from typing import List, Optional ++ ++import torch ++ ++from sglang.srt.environ import envs ++from sglang.srt.layers.aux_hidden_states import pack_aux_hidden_states ++ ++logger = logging.getLogger(__name__) ++ ++# Draft forwards between two counter lines. ++_LOG_EVERY = 4096 ++ ++ ++class DeferredContextCommit: ++ def __init__( ++ self, ++ *, ++ max_bs: int, ++ stride: int, ++ device, ++ kv_injector, ++ ) -> None: ++ self.stride = stride ++ self._max_rows = max_bs * stride ++ self._device = device ++ self._kv_injector = kv_injector ++ # Per draft stage [max_rows, kv width], made at the first (warmup) projection. ++ self.kvs: Optional[List[torch.Tensor]] = None ++ rows = self._max_rows ++ self.cache_loc = torch.zeros((rows,), dtype=torch.int64, device=device) ++ self.positions = torch.zeros((rows,), dtype=torch.int64, device=device) ++ # 0 for every request past the staged ones: their rows are not written. ++ self.commit_lens = torch.zeros((max_bs,), dtype=torch.int32, device=device) ++ self.state_slot = torch.zeros((rows,), dtype=torch.int64, device=device) ++ # Host, set at the first staging: the injector writes a per-request SWA ring. ++ self._with_state_slot = False ++ # SGLANG_OPT_DSV41_DSPARK_ONE_LAUNCH_COMMIT_STAGE: stage() in one Triton launch. ++ self._one_launch_stage = ( ++ envs.SGLANG_OPT_DSV41_DSPARK_ONE_LAUNCH_COMMIT_STAGE.get() ++ and torch.device(device).type == "cuda" ++ ) ++ # Side streams and events, made at the first use. ++ self._proj_stream: Optional[torch.cuda.Stream] = None ++ self._proj_done: Optional[torch.cuda.Event] = None ++ self._store_stream: Optional[torch.cuda.Stream] = None ++ self._store_done: Optional[torch.cuda.Event] = None ++ # Host: requests a static verify staged since the last write (0: nothing pending). ++ self.staged_bs = 0 ++ # Host: a forked projection the static epilogue has not joined yet. ++ self._proj_unjoined = False ++ # Host, capture only: forked stores the draft's first KV store has not joined yet. ++ self._fork_unjoined = False ++ # Draft graph batch sizes whose capture recorded the forked stores. ++ self._forked_bs: set[int] = set() ++ self.num_written_in_graph = 0 ++ self.num_written_eagerly = 0 ++ self._eager_reasons: dict[str, int] = {} ++ self._draft_forwards = 0 ++ ++ @property ++ def pending(self) -> bool: ++ return self.staged_bs > 0 ++ ++ def _pool(self): ++ return self._kv_injector.draft_model_runner.token_to_kv_pool ++ ++ # Verify side: the projection (forked at the logits processor) and the staging. ++ ++ def logits_pre_hook(self, module, args, kwargs) -> None: ++ """Forward pre-hook on the target's logits processor: in a static verify ++ graph (capture or warmup), fork the projection of the DSpark hidden.""" ++ from sglang.srt.model_executor.runner import get_is_capture_mode ++ ++ metadata = args[3] if len(args) > 3 else kwargs.get("logits_metadata") ++ aux = args[4] if len(args) > 4 else kwargs.get("aux_hidden_states") ++ if ( ++ aux is None ++ or not metadata.forward_mode.is_target_verify() ++ or not get_is_capture_mode() ++ ): ++ return ++ if self._proj_stream is None: ++ self._proj_stream = torch.cuda.Stream(device=self._device) ++ self._proj_done = torch.cuda.Event() ++ self._proj_stream.wait_stream(torch.cuda.current_stream()) ++ with torch.cuda.stream(self._proj_stream), torch.inference_mode(): ++ kvs = self._kv_injector.draft_model.project_commit_kv( ++ main_hidden=pack_aux_hidden_states(aux), pool=self._pool() ++ ) ++ if self.kvs is None: ++ assert not _capturing(), "the commit KV buffers are made at a warmup" ++ self.kvs = [kv.new_zeros((self._max_rows, kv.shape[1])) for kv in kvs] ++ n = kvs[0].shape[0] ++ for buf, kv in zip(self.kvs, kvs): ++ buf[:n].copy_(kv) ++ self._proj_done.record() ++ self._proj_unjoined = True ++ ++ def join_projection(self) -> bool: ++ """In the static epilogue: wait for this graph's projection; False if none ran.""" ++ if not self._proj_unjoined: ++ return False ++ torch.cuda.current_stream().wait_event(self._proj_done) ++ self._proj_unjoined = False ++ return True ++ ++ def stage( ++ self, ++ *, ++ cache_loc: torch.Tensor, ++ positions: torch.Tensor, ++ commit_lens: torch.Tensor, ++ state_slot: Optional[torch.Tensor], ++ ) -> None: ++ """Recorded in a static verify graph of ``commit_lens.shape[0]`` requests.""" ++ bs = commit_lens.shape[0] ++ n = bs * self.stride ++ self._with_state_slot = state_slot is not None ++ if self._one_launch_stage: ++ from sglang.kernels.ops.speculative.dspark.stage_commit import stage_commit ++ ++ stage_commit( ++ cache_loc_dst=self.cache_loc, ++ positions_dst=self.positions, ++ commit_lens_dst=self.commit_lens, ++ state_slot_dst=self.state_slot if state_slot is not None else None, ++ cache_loc=cache_loc, ++ positions=positions, ++ commit_lens=commit_lens, ++ state_slot=state_slot, ++ rows=n, ++ ) ++ return ++ self.cache_loc[:n].copy_(cache_loc[:n]) ++ self.positions[:n].copy_(positions[:n]) ++ self.commit_lens[:bs].copy_(commit_lens) ++ self.commit_lens[bs:].zero_() ++ if state_slot is not None: ++ self.state_slot[:n].copy_(state_slot[:n]) ++ ++ def note_static_verify(self, live_bs: int) -> None: ++ """Host, after a static verify graph ran ``live_bs`` requests.""" ++ self.staged_bs = live_bs ++ ++ # Draft side: the gated stores. ++ ++ def write(self, bs: Optional[int] = None) -> None: ++ """The staged stores over the first ``bs`` requests (default all), then a ++ disarm, on the current stream.""" ++ if self.kvs is None: ++ return ++ bs = self.commit_lens.shape[0] if bs is None else bs ++ n = bs * self.stride ++ pool = self._pool() ++ cache_loc = self.cache_loc[:n] ++ positions = self.positions[:n] ++ swa_loc = self._kv_injector.committed_swa_loc( ++ pool=pool, ++ cache_loc=cache_loc, ++ positions=positions, ++ cache_loc_2d=cache_loc.view(bs, self.stride), ++ commit_lens=self.commit_lens[:bs], ++ state_slot=self.state_slot[:n] if self._with_state_slot else None, ++ ) ++ with torch.inference_mode(): ++ self._kv_injector.draft_model.store_commit_kv( ++ kvs=[kv[:n] for kv in self.kvs], ++ swa_loc=swa_loc, ++ positions=positions, ++ pool=pool, ++ ) ++ self.commit_lens.zero_() ++ ++ def flush(self, reason: str = "prefill") -> None: ++ """Host: write a pending staging now (an eager forward follows).""" ++ # A graph captured here would replay the write on every later replay. ++ if self.pending and not _capturing(): ++ self.write() ++ self.staged_bs = 0 ++ self.num_written_eagerly += 1 ++ self._eager_reasons[reason] = self._eager_reasons.get(reason, 0) + 1 ++ ++ def before_draft_forward(self, graph_bs: Optional[int]) -> None: ++ """Host, before a draft forward: a graph of ``graph_bs`` requests (None: eager) ++ writes only its own rows, so anything it would miss is written first.""" ++ self._draft_forwards += 1 ++ if self._draft_forwards % _LOG_EVERY == 0: ++ logger.debug( ++ "DSpark deferred context-KV commit: %d written in draft graphs, " ++ "%d eagerly %s", ++ self.num_written_in_graph, ++ self.num_written_eagerly, ++ self._eager_reasons, ++ ) ++ if graph_bs is None: ++ self.flush("eager draft") ++ elif graph_bs not in self._forked_bs: ++ self.flush("draft graph without the fork") ++ elif self.staged_bs > graph_bs: ++ self.flush("draft graph rows") ++ ++ def after_draft_forward(self, graph_ran: bool) -> None: ++ # A pending staging past before_draft_forward is one the graph writes. ++ if graph_ran and self.pending: ++ self.staged_bs = 0 ++ self.num_written_in_graph += 1 ++ ++ def capture_head_hook(self, graph_runner, forward_batch) -> None: ++ """First inside each draft decode graph capture (and its warmups).""" ++ if not forward_batch.forward_mode.is_target_verify(): ++ return ++ bs = forward_batch.batch_size ++ if not _capturing(): ++ # Warmups write the disarmed staging, so its kernels compile before capture. ++ if not self.pending: ++ self.write(bs) ++ return ++ if self._store_stream is None: ++ self._store_stream = torch.cuda.Stream(device=self._device) ++ self._store_done = torch.cuda.Event() ++ self._store_stream.wait_stream(torch.cuda.current_stream()) ++ with torch.cuda.stream(self._store_stream): ++ self.write(bs) ++ self._store_done.record() ++ self._fork_unjoined = True ++ self._forked_bs.add(bs) ++ logger.info( ++ "DSpark draft graph bs=%d: deferred context-KV commit forked at its head", ++ bs, ++ ) ++ ++ def join(self) -> None: ++ """At the draft's first KV store: the store waits for the forked stores.""" ++ if self._fork_unjoined and _capturing(): ++ torch.cuda.current_stream().wait_event(self._store_done) ++ self._fork_unjoined = False ++ logger.info( ++ "DSpark draft graph: deferred context-KV commit joined at the first KV store" ++ ) ++ ++ def disarm(self) -> None: ++ """Drop whatever warmups or captures staged on placeholder inputs.""" ++ self.commit_lens.zero_() ++ self.staged_bs = 0 ++ self._fork_unjoined = False ++ self._proj_unjoined = False ++ ++ ++def _capturing() -> bool: ++ return torch.cuda.is_available() and torch.cuda.is_current_stream_capturing() ++ ++ ++def defer_context_kv_refusal( ++ *, ++ static_verify: bool, ++ draft_is_moe: bool, ++ unified_kv: bool, ++ unified_memory: bool, ++ hicache: bool, ++ disaggregated: bool, ++ attn_dp: bool, ++) -> str: ++ """Why the deferred commit cannot run here, or "".""" ++ reasons = ( ++ (not static_verify, "the verify is not static (SGLANG_RAGGED_VERIFY_MODE)"), ++ (not draft_is_moe, "the draft has no MoE layers"), ++ (unified_kv, "unified KV writes the draft window through its ring"), ++ (unified_memory, "the unified memory pool compacts KV between steps"), ++ (hicache, "a HiCache storage backend moves KV between steps"), ++ (disaggregated, "PD disaggregation transfers KV between steps"), ++ (attn_dp, "attention DP runs idle draft forwards"), ++ ) ++ return "; ".join(why for refused, why in reasons if refused) +diff --git a/python/sglang/srt/speculative/dspark_components/dspark_draft.py b/python/sglang/srt/speculative/dspark_components/dspark_draft.py +index a02bb30e10..aef562ce60 100644 +--- a/python/sglang/srt/speculative/dspark_components/dspark_draft.py ++++ b/python/sglang/srt/speculative/dspark_components/dspark_draft.py +@@ -1,5 +1,6 @@ + from __future__ import annotations + ++import bisect + import functools + import logging + from typing import TYPE_CHECKING, NamedTuple, Optional +@@ -77,6 +78,9 @@ class DraftProposal(msgspec.Struct, frozen=True): + confidence: Optional[torch.Tensor] = None + confidence_raw: Optional[torch.Tensor] = None + folded: bool = False ++ # [bs, gamma + 1] ``[anchor | draft tokens]`` from the draft graph tail; None ++ # when the caller builds them. ++ verify_ids: Optional[torch.Tensor] = None + + + def select_draft_hidden_without_anchor( +@@ -164,6 +168,9 @@ def resolve_draft_params( + return DraftParams(temperatures, greedy_mask, step_temperatures) + + ++# Arbitrary; how often the proposer logs its restage-skip count, in graph steps. ++STAGED_PARAMS_LOG_EVERY = 500 ++ + # XORed into the server seed so the draft noise differs from other samplers'. + _DRAFT_NOISE_DOMAIN = 0x2D2A9C317E44B1F3 + +@@ -317,6 +324,11 @@ def sample_draft_block( + + + class DraftBlockProposer: ++ _staged_params_key = None ++ num_staged_params_skips = 0 ++ num_staged_params_calls = 0 ++ deferred_commit = None ++ + def __init__( + self, + *, +@@ -347,9 +359,16 @@ class DraftBlockProposer: + ) + self._draft_sampler = None + self._dp_moe_sync = dp_moe_sync ++ # SGLANG_DSPARK_DEFER_CONTEXT_KV's staged commit, set by the worker. ++ self.deferred_commit = None + # Persistent (bs, gamma) mask-token buffer: only column 0 (the bonus + # token) changes per step, so avoid a fresh torch.full every decode. + self._draft_block_ids_buf: Optional[torch.Tensor] = None ++ # (sampler, bs, temperatures, top_ks) last staged: SamplingBatchInfo rebinds ++ # these tensors when the batch changes, never edits them in place ++ self._staged_params_key: Optional[tuple] = None ++ self.num_staged_params_skips = 0 ++ self.num_staged_params_calls = 0 + self._num_token_non_padded = ( + torch.empty((1,), dtype=torch.int32, device=self.draft_model_runner.device) + if enable_num_token_non_padded() +@@ -363,6 +382,34 @@ class DraftBlockProposer: + def attach_draft_sampler(self, draft_sampler) -> None: + self._draft_sampler = draft_sampler + ++ def _stage_sampling_params(self, draft_sampler, *, bs: int, sampling_info) -> None: ++ """The draft graph's sampling params, restaged only when the sampler, bs or ++ the batch's temperature / top-k tensors changed since the last stage.""" ++ key = ( ++ draft_sampler, ++ bs, ++ None if sampling_info is None else sampling_info.temperatures, ++ None if sampling_info is None else sampling_info.top_ks, ++ ) ++ staged = self._staged_params_key ++ self.num_staged_params_calls += 1 ++ skip = ( ++ staged is not None ++ and staged[1] == bs ++ and all(staged[i] is key[i] for i in (0, 2, 3)) ++ ) ++ self.num_staged_params_skips += skip ++ if self.num_staged_params_calls % STAGED_PARAMS_LOG_EVERY == 0: ++ logger.debug( ++ "DSpark draft: sampling params restage skipped on %d of %d steps", ++ self.num_staged_params_skips, ++ self.num_staged_params_calls, ++ ) ++ if skip: ++ return ++ draft_sampler.stage_sampling_params(bs=bs, sampling_info=sampling_info) ++ self._staged_params_key = key ++ + def _base_logits_context(self): + return draft_tp_context(self._dp_moe_sync) + +@@ -376,6 +423,7 @@ class DraftBlockProposer: + device: str, + target_model, + sampling_info, ++ anchor_prepared: bool = False, + ) -> DraftProposal: + embed_module = unwrap_lora_layer( + self.draft_model.embed_tokens +@@ -392,10 +440,11 @@ class DraftBlockProposer: + embed_module=embed_module, + draft_sampler=draft_sampler, + sampling_info=sampling_info, ++ anchor_prepared=anchor_prepared, + ) + draft_block_ids = fwd.draft_block_ids + +- confidence = confidence_raw = None ++ confidence = confidence_raw = verify_ids = None + folded = False + if ( + envs.SGLANG_DSPARK_FOLDED_PROPOSAL.get() +@@ -415,6 +464,8 @@ class DraftBlockProposer: + if draft_sampler.confidence_out is not None: + confidence = draft_sampler.confidence_out[:bs] + confidence_raw = draft_sampler.confidence_raw_out[:bs] ++ if draft_sampler.verify_ids is not None: ++ verify_ids = draft_sampler.verify_ids[:bs] + else: + with self._base_logits_context(): + base_logits, confidence_features = self.draft_model.compute_base_logits( +@@ -449,6 +500,7 @@ class DraftBlockProposer: + confidence=confidence, + confidence_raw=confidence_raw, + folded=folded, ++ verify_ids=verify_ids, + ) + + def run_idle_participation(self, batch: ScheduleBatch) -> None: +@@ -477,6 +529,19 @@ class DraftBlockProposer: + with torch.inference_mode(): + self.draft_model_runner.forward(idle_batch) + ++ def draft_block_ids_view(self, *, bs: int, device) -> torch.Tensor: ++ """The ``[bs, query_token_num]`` draft input ids: mask tokens past column 0.""" ++ buf = self._draft_block_ids_buf ++ if buf is None or buf.shape[0] < bs or buf.device != torch.device(device): ++ buf = torch.full( ++ (bs, self.query_token_num), ++ int(self._mask_token_id), ++ dtype=torch.long, ++ device=device, ++ ) ++ self._draft_block_ids_buf = buf ++ return buf[:bs] ++ + def _run_forward( + self, + *, +@@ -488,6 +553,7 @@ class DraftBlockProposer: + embed_module, + draft_sampler=None, + sampling_info=None, ++ anchor_prepared: bool = False, + ) -> DraftForwardResult: + gamma = self.gamma + query_token_num = self.query_token_num +@@ -495,18 +561,9 @@ class DraftBlockProposer: + positions_2d = verify_window.positions_2d + verify_cache_loc_2d = verify_window.verify_cache_loc_2d + +- buf = self._draft_block_ids_buf +- if buf is None or buf.shape[0] < bs or buf.device != prefix_lens.device: +- buf = torch.full( +- (bs, query_token_num), +- int(self._mask_token_id), +- dtype=torch.long, +- device=device, +- ) +- self._draft_block_ids_buf = buf +- draft_block_ids = buf[:bs] +- +- draft_block_ids[:, 0].copy_(draft_input.bonus_tokens.view(-1)) ++ draft_block_ids = self.draft_block_ids_view(bs=bs, device=prefix_lens.device) ++ if not anchor_prepared: ++ draft_block_ids[:, 0].copy_(draft_input.bonus_tokens.view(-1)) + draft_positions = positions_2d[:, :query_token_num].reshape(-1) + draft_cache_loc = verify_cache_loc_2d[:, :query_token_num].reshape(-1) + +@@ -554,14 +611,29 @@ class DraftBlockProposer: + ) + self._fill_dp_moe_sync_metadata(draft_forward_batch, batch) + graph_runner = self.draft_model_runner.decode_cuda_graph_runner +- if ( +- draft_sampler is not None +- and graph_runner is not None +- and graph_runner.can_run_graph(draft_forward_batch) +- ): +- draft_sampler.stage_sampling_params(bs=bs, sampling_info=sampling_info) ++ runs_graph = graph_runner is not None and graph_runner.can_run_graph( ++ draft_forward_batch ++ ) ++ if draft_sampler is not None and runs_graph: ++ self._stage_sampling_params( ++ draft_sampler, bs=bs, sampling_info=sampling_info ++ ) ++ commit = self.deferred_commit ++ if commit is not None: ++ commit.before_draft_forward( ++ graph_bs=( ++ graph_runner.capture_bs[ ++ bisect.bisect_left(graph_runner.capture_bs, bs) ++ ] ++ if runs_graph ++ else None ++ ) ++ ) + with torch.inference_mode(): + draft_out = self.draft_model_runner.forward(draft_forward_batch) ++ if commit is not None: ++ assert draft_out.can_run_graph == runs_graph ++ commit.after_draft_forward(graph_ran=draft_out.can_run_graph) + logits_output = draft_out.logits_output + raw_hidden = logits_output.hidden_states + if raw_hidden is None: +diff --git a/python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py b/python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py +index f93ea04cc3..a85cc53ae9 100644 +--- a/python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py ++++ b/python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py +@@ -5,6 +5,7 @@ from typing import Callable, Optional + + import torch + ++from sglang.srt.environ import envs + from sglang.srt.layers.dp_attention import get_dp_tp_group + from sglang.srt.megakernels.runtime import megakernel_agree, megakernel_draft_sampler + from sglang.srt.speculative.dspark_components.dspark_draft import ( +@@ -26,6 +27,8 @@ _is_xpu = is_xpu() + class DsparkDraftSampler: + """The eager path's markov block, run as the draft cuda graph's tail.""" + ++ verify_ids = None ++ + def __init__( + self, + *, +@@ -53,6 +56,13 @@ class DsparkDraftSampler: + self.out = torch.empty( + (self.max_bs * self.gamma,), dtype=torch.int64, device=device + ) ++ # [max_bs, gamma + 1] verify ids ([anchor | draft tokens]) written by the ++ # graph tail, so the step skips its eager concat (SGLANG_OPT_DSV41_DSPARK_MID_FOLD). ++ self.verify_ids: Optional[torch.Tensor] = None ++ if envs.SGLANG_OPT_DSV41_DSPARK_MID_FOLD.get(): ++ self.verify_ids = torch.empty( ++ (self.max_bs, self.gamma + 1), dtype=torch.int64, device=device ++ ) + confidence_head = model.confidence_head + if confidence_head is None: + self.confidence_out = self.confidence_raw_out = None +@@ -157,6 +167,12 @@ class DsparkDraftSampler: + ) + self.confidence_out[:bs].copy_(confidence) + self.confidence_raw_out[:bs].copy_(confidence_raw) ++ if self.verify_ids is not None: ++ torch.cat( ++ [anchor.view(bs, 1), self.out[: bs * self.gamma].view(bs, self.gamma)], ++ dim=1, ++ out=self.verify_ids[:bs], ++ ) + + def _markov_block(self, model_hidden, sample_hidden, anchor, bs: int): + base_logits, confidence_features = self.model.compute_base_logits(model_hidden) +diff --git a/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py b/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py +index 24365707a4..a0a3f5ee15 100644 +--- a/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py ++++ b/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py +@@ -111,18 +111,18 @@ class TargetHiddenKvInjector: + target_hidden_is_projected=target_hidden_is_projected, + ) + +- def _inject_mla( ++ def committed_swa_loc( + self, + *, + pool, +- target_hidden: torch.Tensor, + cache_loc: torch.Tensor, + positions: torch.Tensor, + cache_loc_2d: Optional[torch.Tensor], + commit_lens: Optional[torch.Tensor], + state_slot: Optional[torch.Tensor] = None, + final_pos: Optional[torch.Tensor] = None, +- ) -> None: ++ ) -> torch.Tensor: ++ """The draft SWA rows the committed context tokens store into, -1 elsewhere.""" + if pool.swa_req_ring_size is not None: + swa_loc = self._ring_inject_loc( + pool=pool, +@@ -162,6 +162,29 @@ class TargetHiddenKvInjector: + committed_mask, swa_loc, torch.full_like(swa_loc, -1) + ) + ++ return swa_loc ++ ++ def _inject_mla( ++ self, ++ *, ++ pool, ++ target_hidden: torch.Tensor, ++ cache_loc: torch.Tensor, ++ positions: torch.Tensor, ++ cache_loc_2d: Optional[torch.Tensor], ++ commit_lens: Optional[torch.Tensor], ++ state_slot: Optional[torch.Tensor] = None, ++ final_pos: Optional[torch.Tensor] = None, ++ ) -> None: ++ swa_loc = self.committed_swa_loc( ++ pool=pool, ++ cache_loc=cache_loc, ++ positions=positions, ++ cache_loc_2d=cache_loc_2d, ++ commit_lens=commit_lens, ++ state_slot=state_slot, ++ final_pos=final_pos, ++ ) + with torch.inference_mode(): + self.draft_model.write_target_hidden_kv( + main_hidden=target_hidden, +diff --git a/python/sglang/srt/speculative/dspark_components/dspark_planner.py b/python/sglang/srt/speculative/dspark_components/dspark_planner.py +index 17a342c721..fea10838ef 100644 +--- a/python/sglang/srt/speculative/dspark_components/dspark_planner.py ++++ b/python/sglang/srt/speculative/dspark_components/dspark_planner.py +@@ -788,18 +788,30 @@ def alloc_verify_window( + block_pos_offsets: torch.Tensor, + model_runner, + seq_lens_cpu: Optional[torch.Tensor], ++ bonus: Optional[torch.Tensor] = None, ++ anchor_ids: Optional[torch.Tensor] = None, + ) -> VerifyWindow: + """``seq_lens_cpu``: a host bound on ``batch.seq_lens``, which sizes the +- plan's read table.""" ++ plan's read table. ``anchor_ids``, when given, gets ``bonus`` in column 0 ++ by the same launch (SGLANG_OPT_DSV41_DSPARK_PREPARE_INPUTS_ONCE).""" + prefix_lens = batch.seq_lens + verify_w = verify_num_draft_tokens +- positions_2d = prefix_lens.unsqueeze(1) + block_pos_offsets ++ positions_2d = None ++ if anchor_ids is not None: ++ positions_2d = torch.empty( ++ (bs, verify_w), dtype=torch.int64, device=prefix_lens.device ++ ) + plan = model_runner.kv_index_translator.plan_uniform_extend( + req_pool_indices=batch.req_pool_indices, + seq_lens=prefix_lens, + seq_lens_cpu=seq_lens_cpu, + width=verify_w, ++ positions_out=positions_2d, ++ anchor_src=bonus, ++ anchor_out=anchor_ids, + ) ++ if positions_2d is None: ++ positions_2d = prefix_lens.unsqueeze(1) + block_pos_offsets + verify_cache_loc = plan.write_virtual + return VerifyWindow( + positions_2d=positions_2d, +diff --git a/python/sglang/srt/speculative/dspark_components/dspark_sampling_accept_graph.py b/python/sglang/srt/speculative/dspark_components/dspark_sampling_accept_graph.py +new file mode 100644 +index 0000000000..521c050986 +--- /dev/null ++++ b/python/sglang/srt/speculative/dspark_components/dspark_sampling_accept_graph.py +@@ -0,0 +1,248 @@ ++"""CUDA graphs of the temperature-sampling verify accept of static DSpark decode steps ++(SGLANG_OPT_DSV41_SAMPLING_ACCEPT_GRAPH). ++ ++The static verify graph folds only the greedy accept (DsparkVerifyEpilogue). On an ++all-sampled step the rest ran eagerly after the replay: the draft and target softmax, ++the rejection kernel, the bonus gather, the accept-site TP broadcast, the engram ++history commit, the future relay and the target-hidden KV commit. This module captures ++that region once per verify-graph batch size and replays it right after the verify ++graph. ++ ++The region reads the verify graph's static inputs and outputs (``static_io``) and the ++draft sampler's static buffers, which hold this step's values after both replays, so a ++replay stages nothing. Its accept outputs land in the epilogue's static accept buffers, ++like the greedy fold. Per key the first step runs eagerly (it compiles kernels and warms ++allocations), the second captures, later steps replay. The uniform draws come from ++torch's default generator, whose graph-safe offsets make a replay draw what the eager ++accept draws at the same generator state; with block-wise rejection they come from the ++worker's one RejectionNoise, whose device step counter a replay advances like an eager ++call. The DSPARK_ACCEPT_SAMPLE broadcast stays in ++the region (pynccl inside the graph), so TP ranks agree as in the eager path. With the ++deferred context-KV commit, the verify graph already joined this step's projection, so ++the region stages the stores from it. ++ ++The caller routes only all-sampled steps without top-k / top-p, logit adjustments, ++grammar or a simulated sampled bonus; everything else keeps the eager accept. ++""" ++ ++from __future__ import annotations ++ ++import logging ++from collections.abc import Callable, Hashable ++from functools import partial ++from typing import Optional ++ ++import msgspec ++import torch ++ ++from sglang.kernels.ops.speculative.dspark.blockwise_rejection import RejectionNoise ++from sglang.srt.distributed.parallel_state import graph_capture ++from sglang.srt.speculative.dspark_components.dspark_draft import DraftBlockResult ++from sglang.srt.speculative.dspark_components.dspark_verify import ( ++ AcceptOuts, ++ DsparkVerifyEpilogue, ++ StaticVerifyIO, ++ accept_draft_tokens, ++ build_accept_outs, ++) ++from sglang.srt.speculative.spec_tp_sync import SpecTpSync, SpecTpSyncSite ++ ++logger = logging.getLogger(__name__) ++ ++ ++class GraphSamplingInfo(msgspec.Struct, frozen=True): ++ """The SamplingBatchInfo fields the sampling accept reads, for an all-sampled ++ batch without top-k / top-p.""" ++ ++ temperatures: torch.Tensor ++ is_all_greedy: bool = False ++ is_any_greedy: bool = False ++ need_top_k_sampling: bool = False ++ need_top_p_sampling: bool = False ++ ++ ++def sampling_accept_commit_lens( ++ io: StaticVerifyIO, ++ *, ++ verify_lens: torch.Tensor, ++ gate: torch.Tensor, ++ gated: bool, ++ draft_sampler, ++ epilogue: DsparkVerifyEpilogue, ++ tp_sync: SpecTpSync, ++ fused_argmax: bool, ++ block_verification: bool, ++ rejection_noise: Optional[RejectionNoise], ++) -> Optional[torch.Tensor]: ++ """The eager sampling accept and finalize into the epilogue's static buffers; ++ returns the gated commit lengths when ``gated``.""" ++ bs, stride = io.candidates.shape ++ params = draft_sampler.params ++ draft_tokens = io.candidates[:, 1:] ++ draft_block = DraftBlockResult( ++ draft_tokens=draft_tokens, ++ corrected_logits=( ++ None if draft_sampler.greedy_draft else draft_sampler.step_logits[:bs] ++ ), ++ greedy_mask=params.greedy_mask[:bs], ++ temperatures=params.temperatures[:bs], ++ greedy_draft=draft_sampler.greedy_draft, ++ ) ++ correct_len, bonus, cap_trim_lens = accept_draft_tokens( ++ candidates=io.candidates, ++ target_logits=io.logits, ++ draft_block=draft_block, ++ # params.temperatures is the batch's, clamped at 1e-5 (resolve_draft_params). ++ sampling_info=GraphSamplingInfo(temperatures=params.temperatures[:bs]), ++ draft_input=None, ++ gamma=stride - 1, ++ verify_num_draft_tokens=stride, ++ fused_argmax=fused_argmax, ++ block_verification=block_verification, ++ rejection_noise=rejection_noise, ++ ) ++ commit_lens = build_accept_outs( ++ correct_len=correct_len, ++ bonus=bonus, ++ cap_trim_lens=cap_trim_lens, ++ prefix_lens=io.seq_lens[:bs], ++ draft_tokens=draft_tokens.contiguous(), ++ gamma=stride - 1, ++ verify_num_draft_tokens=stride, ++ tp_sync=tp_sync, ++ sync_site=SpecTpSyncSite.DSPARK_ACCEPT_SAMPLE, ++ simulated_correct_len=epilogue.simulated_correct_len, ++ target_logits=io.logits, ++ out=epilogue.read_accept(bs), ++ block_accept_lens_out=epilogue.read_block_accept_lens(bs), ++ ).commit_lens ++ if not gated: ++ return None ++ return torch.minimum(commit_lens, verify_lens.to(torch.int32)) * gate ++ ++ ++class DsparkSamplingAcceptGraph: ++ """Per-batch-size CUDA graphs of the sampling accept region of static verify.""" ++ ++ # One key per verify-graph batch size is expected; more means addresses move, ++ # and the further keys run eagerly. Arbitrary bound. ++ MAX_GRAPHS = 32 ++ ++ def __init__( ++ self, ++ *, ++ epilogue: DsparkVerifyEpilogue, ++ resolve_draft_sampler: Callable[[], Optional[object]], ++ tp_sync: SpecTpSync, ++ fused_argmax: bool, ++ block_verification: bool, ++ device, ++ rejection_noise: Optional[RejectionNoise] = None, ++ ) -> None: ++ self._epilogue = epilogue ++ self._resolve_draft_sampler = resolve_draft_sampler ++ self._tp_sync = tp_sync ++ self._fused_argmax = fused_argmax ++ self._block_verification = block_verification ++ self._rejection_noise = rejection_noise ++ # The region always commits; padded rows are gated by verify_lens. ++ self._gate = torch.ones((1,), dtype=torch.int32, device=device) ++ self._graphs: dict[Hashable, torch.cuda.CUDAGraph] = {} ++ self._warmed_up: set[Hashable] = set() ++ self._pool = None ++ self.disabled = False ++ self.num_replays = 0 ++ # Set by run(): whether this step's region committed the engram history. ++ self.committed_engram = False ++ ++ def run(self, *, bs: int, target_logits: torch.Tensor) -> Optional[AcceptOuts]: ++ """This step's accept through the region, or None when the step must take the ++ eager path. Reads only host state every TP rank holds identically.""" ++ if self.disabled: ++ return None ++ draft_sampler = self._resolve_draft_sampler() ++ if draft_sampler is None or ( ++ not draft_sampler.greedy_draft and draft_sampler.step_logits is None ++ ): ++ return None ++ epilogue = self._epilogue ++ graph_bs = min((b for b in epilogue.static_io if b >= bs), default=None) ++ if graph_bs is None: ++ return None ++ io = epilogue.static_io[graph_bs] ++ # The replayed verify graph must be the one whose buffers were recorded. ++ if target_logits.data_ptr() != io.logits.data_ptr(): ++ return None ++ key = ( ++ graph_bs, ++ io.logits.data_ptr(), ++ draft_sampler.params.temperatures.data_ptr(), ++ 0 ++ if draft_sampler.step_logits is None ++ else draft_sampler.step_logits.data_ptr(), ++ ) ++ region = partial( ++ epilogue.run_static, ++ io, ++ accept=partial( ++ sampling_accept_commit_lens, ++ draft_sampler=draft_sampler, ++ epilogue=epilogue, ++ tp_sync=self._tp_sync, ++ fused_argmax=self._fused_argmax, ++ block_verification=self._block_verification, ++ rejection_noise=self._rejection_noise, ++ ), ++ gate=self._gate, ++ kv_projected=True, ++ ) ++ self.committed_engram = epilogue.engram_history() is not None ++ self._run(key, region) ++ return epilogue.read_accept(bs) ++ ++ def _run(self, key: Hashable, region: Callable[[], object]) -> None: ++ graph = self._graphs.get(key) ++ if graph is None: ++ if key not in self._warmed_up: ++ if len(self._warmed_up) < self.MAX_GRAPHS: ++ self._warmed_up.add(key) ++ region() ++ return ++ graph = self._capture(key, region) ++ if graph is None: ++ return ++ graph.replay() ++ self.num_replays += 1 ++ ++ def _capture( ++ self, key: Hashable, region: Callable[[], object] ++ ) -> Optional[torch.cuda.CUDAGraph]: ++ if self._pool is None: ++ self._pool = torch.cuda.graph_pool_handle() ++ graph = torch.cuda.CUDAGraph() ++ try: ++ # graph_capture() enables pynccl, which the in-graph accept broadcast needs. ++ with ( ++ graph_capture() as ctx, ++ torch.cuda.graph( ++ graph, ++ pool=self._pool, ++ stream=ctx.stream, ++ capture_error_mode="thread_local", ++ ), ++ ): ++ region() ++ except Exception: ++ logger.warning( ++ "DSpark sampling-accept graph capture failed for %s; sampling steps " ++ "take the eager accept from now on.", ++ key, ++ exc_info=True, ++ ) ++ self.disabled = True ++ # A failed capture recorded the ops without running them. ++ region() ++ return None ++ logger.info("Captured the DSpark sampling-accept region for %s.", key) ++ self._graphs[key] = graph ++ return graph +diff --git a/python/sglang/srt/speculative/dspark_components/dspark_verify.py b/python/sglang/srt/speculative/dspark_components/dspark_verify.py +index 86de26a3b5..9d9015839f 100644 +--- a/python/sglang/srt/speculative/dspark_components/dspark_verify.py ++++ b/python/sglang/srt/speculative/dspark_components/dspark_verify.py +@@ -1,17 +1,24 @@ + from __future__ import annotations + ++import logging + import random + from typing import Optional + + import msgspec + import torch + ++from sglang.kernels.ops.embeddings.engram_hash import engram_commit_history ++from sglang.kernels.ops.speculative.dspark.blockwise_rejection import ( ++ BlockwiseRejection, ++ RejectionNoise, ++) + from sglang.kernels.ops.speculative.dspark.dspark_accept import ( + AcceptGreedy, + AcceptSampling, + FinalizeAcceptLens, + SelectMixedAccept, + SoftmaxTemp, ++ _row_argmax, + ) + from sglang.kernels.ops.speculative.dspark.dspark_verify_window import ( + BuildCommitInjectLayout, +@@ -23,15 +30,25 @@ from sglang.kernels.ops.speculative.dspark.dspark_verify_window import ( + scatter_compact_to_strided_into, + ) + from sglang.kernels.ops.speculative.dspark.simulated_bonus import ( ++ simulated_bonus_partials_graph, + simulated_bonus_sample, + simulated_bonus_sample_graph, + ) ++from sglang.kernels.ops.speculative.dspark.static_accept_tail import static_accept_tail ++from sglang.srt.environ import envs + from sglang.srt.layers.logits_processor import LogitsProcessorOutput ++from sglang.srt.managers.overlap_utils import ( ++ FutureRelayBuffers, ++ offer_future_relay_buffers, ++) + from sglang.srt.managers.schedule_batch import ScheduleBatch + from sglang.srt.model_executor.forward_batch_info import CaptureHiddenMode, ForwardMode + from sglang.srt.speculative.dflash_info import DFlashVerifyInput + from sglang.srt.speculative.dflash_info_v2 import DFlashDraftInputV2 + from sglang.srt.speculative.dflash_utils import apply_dflash_verify_logits_adjustments ++from sglang.srt.speculative.dspark_components.dspark_deferred_commit import ( ++ DeferredContextCommit, ++) + from sglang.srt.speculative.dspark_components.dspark_draft import DraftBlockResult + from sglang.srt.speculative.dspark_components.dspark_kv_inject import ( + TargetHiddenKvInjector, +@@ -49,6 +66,8 @@ from sglang.srt.speculative.spec_utils import ( + from sglang.srt.utils import is_npu + from sglang.srt.utils.invariants import Bucket, Invariant, NotNaN, expect + ++logger = logging.getLogger(__name__) ++ + _is_npu = is_npu() + + # Draft proposal probs feeding rejection sampling; the data layer is the +@@ -103,6 +122,8 @@ def candidate_request_length_bound( + + + class TargetVerifyExecutor: ++ _rejection_noise = None ++ + def __init__( + self, + *, +@@ -116,6 +137,7 @@ class TargetVerifyExecutor: + simulate_acc_len: float = 0.0, + simulated_correct_len: Optional[torch.Tensor] = None, + block_verification: bool = False, ++ rejection_noise: Optional[RejectionNoise] = None, + ) -> None: + self.target_worker = target_worker + # candidate_max_seq_len_upper_bound only feeds the V4.1 candidate graphs. +@@ -136,6 +158,8 @@ class TargetVerifyExecutor: + self._verify_backend_self_adds_seq_lens_cache: Optional[bool] = None + self._simulate_acc_len = float(simulate_acc_len) + self._block_verification = block_verification ++ # Block-wise rejection draws (blockwise_rejection.py); None keeps the classic kernel. ++ self._rejection_noise = rejection_noise + self._simulated_correct_len = simulated_correct_len + + def accept_and_finalize( +@@ -161,6 +185,7 @@ class TargetVerifyExecutor: + override drawn by begin_simulated_step. + """ + if folded_accept: ++ self.verify_epilogue.note_static_verify(bs) + return self.verify_epilogue.read_accept(bs) + + simulate = self._simulated_correct_len is not None +@@ -178,6 +203,7 @@ class TargetVerifyExecutor: + cutoff_layout=layout, + fused_argmax=self._target_is_dsv41, + block_verification=self._block_verification, ++ rejection_noise=self._rejection_noise, + ) + sync_site = ( + SpecTpSyncSite.DSPARK_ACCEPT_GREEDY +@@ -513,6 +539,9 @@ class CommitInjectCtx(msgspec.Struct): + resolve_pool: object + resolve_req_to_token: object + kv_injector: Optional[TargetHiddenKvInjector] = None ++ # SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH: returns the target's engram hasher ++ # (or None), whose history commit the static epilogue then records in-graph. ++ resolve_engram_hasher: Optional[object] = None + + + class AcceptOuts(msgspec.Struct): +@@ -524,6 +553,18 @@ class AcceptOuts(msgspec.Struct): + out_tokens: torch.Tensor + + ++class StaticVerifyIO(msgspec.Struct, frozen=True): ++ """A static verify graph's input and output tensors for one captured batch size.""" ++ ++ candidates: torch.Tensor ++ logits: torch.Tensor ++ hidden: torch.Tensor ++ seq_lens: torch.Tensor ++ req_pool_indices: torch.Tensor ++ out_cache_loc: torch.Tensor ++ positions: torch.Tensor ++ ++ + class DsparkVerifyEpilogue: + def __init__( + self, +@@ -536,8 +577,20 @@ class DsparkVerifyEpilogue: + fused_argmax: bool = False, + simulated_correct_len: Optional[torch.Tensor] = None, + simulate_fold: bool = False, ++ fused_accept_tail: bool = False, ++ accept_tail_min_bs: int = 1, ++ accept_tail_max_bs: int = 0, ++ deferred_commit: Optional[DeferredContextCommit] = None, ++ post_fold: bool = False, + ) -> None: + self.max_bs = int(max_bs) ++ # SGLANG_OPT_DSV41_DSPARK_POST_FOLD: static graphs also scatter new seq lens ++ # and the bonus into the FutureMap's slots; built at the first warmup. ++ self._post_fold = bool(post_fold) ++ self.future_relay: Optional[FutureRelayBuffers] = None ++ # SGLANG_DSPARK_DEFER_CONTEXT_KV: static graphs join its forked projection and ++ # stage the commit's stores into it; the next draft forward runs them. ++ self.deferred_commit = deferred_commit + # SGLANG_SIMULATE_ACC_LEN with a sampled bonus inside the graph too: the bonus + # is drawn at the simulated correct_len from these buffers, which + # begin_sim_bonus writes before replay (<= 0 temperature: argmax). +@@ -575,11 +628,38 @@ class DsparkVerifyEpilogue: + self.out_tokens_buf = torch.zeros( + (self.max_bs, self.stride), dtype=torch.int64, device=device + ) ++ # Under the accept-site broadcast the fused tail serves only simulate_fold, ++ # whose broadcast inputs (length, draw) the kernel can take. ++ self._tail_broadcasts = bool(fused_accept_tail) and tp_sync.enabled( ++ SpecTpSyncSite.DSPARK_ACCEPT_GRAPH ++ ) ++ self._fused_accept_tail = bool(fused_accept_tail) and ( ++ self.simulate_fold or not self._tail_broadcasts ++ ) ++ if fused_accept_tail and not self._fused_accept_tail: ++ logger.info( ++ "DSpark fused accept tail off: the accept-site TP broadcast is " ++ "selected without SGLANG_DSPARK_SIMULATE_FOLD." ++ ) ++ self._accept_tail_bs = (int(accept_tail_min_bs), int(accept_tail_max_bs)) ++ self._accept_tail_logged: set[int] = set() ++ self.gated_commit_lens_buf = torch.zeros( ++ (self.max_bs,), dtype=torch.int32, device=device ++ ) ++ self.block_accept_lens_buf = ( ++ torch.zeros((self.max_bs,), dtype=torch.int32, device=device) ++ if envs.SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH.get() ++ else None ++ ) + # SGLANG_SIMULATE_ACC_LEN: the step's correct length, filled per step. + self.simulated_correct_len = simulated_correct_len + self.strided_logits: Optional[torch.Tensor] = None + self.strided_hidden: Optional[torch.Tensor] = None + self._static_step_state: Optional[tuple[int, bool]] = None ++ # Set when a captured static epilogue recorded the engram history commit. ++ self.folds_engram_commit = False ++ # Per captured static batch size; the sampling-accept region's replays read them. ++ self.static_io: dict[int, StaticVerifyIO] = {} + + def capture_hook(self, runner, out, forward_batch, num_tokens) -> None: + if ( +@@ -638,37 +718,224 @@ class DsparkVerifyEpilogue: + + def _static_epilogue(self, out, forward_batch) -> None: + bs = forward_batch.batch_size +- verify_lens = self.verify_lens_buf[:bs] +- candidates = forward_batch.input_ids.view(bs, self.stride) +- commit_lens = self._accept( +- candidates=candidates, ++ io = StaticVerifyIO( ++ candidates=forward_batch.input_ids.view(bs, self.stride), + logits=out.next_token_logits, +- draft_tokens=candidates[:, 1:].contiguous(), ++ hidden=out.hidden_states, + seq_lens=forward_batch.seq_lens, ++ req_pool_indices=forward_batch.req_pool_indices, ++ out_cache_loc=forward_batch.out_cache_loc, ++ positions=forward_batch.positions, + ) +- if not self.folds_commit: +- return +- # Same staged locations as target verify; padded and fallback rows skip KV. +- gated_commit_lens = ( +- torch.minimum(commit_lens, verify_lens.to(torch.int32)) +- * self.inject_gate_buf ++ capturing = ( ++ torch.cuda.is_available() and torch.cuda.is_current_stream_capturing() + ) +- cache_loc = forward_batch.out_cache_loc ++ if capturing: ++ self.static_io[bs] = io ++ committed_engram = self.run_static( ++ io, accept=self._accept_static_greedy, gate=self.inject_gate_buf ++ ) ++ if committed_engram and capturing: ++ self.folds_engram_commit = True ++ ++ def run_static( ++ self, io: StaticVerifyIO, *, accept, gate: torch.Tensor, kv_projected=False ++ ) -> bool: ++ """Run ``accept`` into the accept buffers, then the commits gated by ``gate``; ++ returns whether the engram history was committed.""" ++ bs = io.candidates.shape[0] ++ verify_lens = self.verify_lens_buf[:bs] ++ folds = self.folds_commit ++ gated_commit_lens = accept(io, verify_lens=verify_lens, gate=gate, gated=folds) ++ # Both accept branches leave the ungated commit lengths in commit_lens_buf. ++ committed_engram = self._commit_engram_history( ++ io.candidates, ++ io.req_pool_indices, ++ self.commit_lens_buf[:bs], ++ verify_lens, ++ gate, ++ ) ++ if self._post_fold: ++ self._scatter_future_relay(io.req_pool_indices, bs) ++ if not folds: ++ return committed_engram ++ cache_loc = io.out_cache_loc + state_slot = None + if self.commit_ctx.kv_injector.swa_ring_size is not None: + state_slot = ( +- forward_batch.req_pool_indices.view(-1, 1) +- .expand(bs, self.stride) +- .reshape(-1) ++ io.req_pool_indices.view(-1, 1).expand(bs, self.stride).reshape(-1) + ) ++ commit = self.deferred_commit ++ if commit is not None and (kv_projected or commit.join_projection()): ++ commit.stage( ++ cache_loc=cache_loc, ++ positions=io.positions, ++ commit_lens=gated_commit_lens, ++ state_slot=state_slot, ++ ) ++ return committed_engram + self.commit_ctx.kv_injector.inject_target_hidden( +- target_hidden=out.hidden_states, ++ target_hidden=io.hidden, + cache_loc=cache_loc, + cache_loc_2d=cache_loc.view(bs, self.stride), +- positions=forward_batch.positions, ++ positions=io.positions, + commit_lens=gated_commit_lens, + state_slot=state_slot, + ) ++ return committed_engram ++ ++ def _accept_static_greedy( ++ self, io: StaticVerifyIO, *, verify_lens, gate, gated: bool ++ ) -> Optional[torch.Tensor]: ++ bs = io.candidates.shape[0] ++ if self._serves_accept_tail(bs): ++ gated_commit_lens = self._static_accept_tail( ++ candidates=io.candidates, ++ logits=io.logits, ++ seq_lens=io.seq_lens, ++ verify_lens=verify_lens, ++ gated=gated, ++ ) ++ block = self.read_block_accept_lens(bs) ++ if block is not None: ++ # The static tail never cap-trims (it writes cap_trim_lens 0). ++ block.copy_(self.commit_lens_buf[:bs]) ++ return gated_commit_lens ++ commit_lens = self._accept( ++ candidates=io.candidates, ++ logits=io.logits, ++ draft_tokens=io.candidates[:, 1:].contiguous(), ++ seq_lens=io.seq_lens, ++ ) ++ # Same staged locations as target verify; padded and fallback rows skip KV. ++ return ( ++ torch.minimum(commit_lens, verify_lens.to(torch.int32)) * gate ++ if gated ++ else None ++ ) ++ ++ def engram_history(self) -> Optional[torch.Tensor]: ++ """The engram history the static epilogue commits into, or None.""" ++ if self.commit_ctx is None or self.commit_ctx.resolve_engram_hasher is None: ++ return None ++ hasher = self.commit_ctx.resolve_engram_hasher() ++ return None if hasher is None else hasher.history ++ ++ def _serves_accept_tail(self, bs: int) -> bool: ++ low, high = self._accept_tail_bs ++ return self._fused_accept_tail and low <= bs and (high == 0 or bs <= high) ++ ++ def _static_accept_tail( ++ self, *, candidates, logits, seq_lens, verify_lens, gated: bool ++ ) -> Optional[torch.Tensor]: ++ """The greedy ``_accept`` and gated commit lengths in one launch; under ++ simulate_fold the argmax is skipped and the bonus select runs in the tail.""" ++ bs = candidates.shape[0] ++ target_predict = bonus_in = bonus_parts = None ++ if not self.simulate_fold: ++ target_predict = _row_argmax(logits, fused=self._fused_argmax).view(-1) ++ elif self._tail_broadcasts: ++ bonus_in = self._sim_bonus(logits, bs) ++ # Rank 0's length and draw, as build_accept_outs broadcasts them. ++ self._tp_sync.sync( ++ SpecTpSyncSite.DSPARK_ACCEPT_GRAPH, self.simulated_correct_len ++ ) ++ self._tp_sync.sync(SpecTpSyncSite.DSPARK_ACCEPT_GRAPH, bonus_in) ++ else: ++ bonus_parts = ( ++ *simulated_bonus_partials_graph(**self._sim_bonus_args(logits, bs)), ++ logits.shape[1], ++ ) ++ self._log_accept_tail(bs, bonus_in=bonus_in) ++ static_accept_tail( ++ candidates=candidates, ++ target_predict=target_predict, ++ seq_lens=seq_lens, ++ verify_lens=verify_lens, ++ gate=self.inject_gate_buf, ++ correct_len_out=self.correct_len_buf, ++ bonus_out=self.bonus_buf, ++ cap_trim_lens_out=self.cap_trim_lens_buf, ++ commit_lens_out=self.commit_lens_buf, ++ new_seq_lens_out=self.new_seq_lens_buf, ++ out_tokens_out=self.out_tokens_buf, ++ simulated_correct_len=self.simulated_correct_len, ++ bonus_in=bonus_in, ++ bonus_parts=bonus_parts, ++ gated_commit_lens_out=self.gated_commit_lens_buf if gated else None, ++ ) ++ return self.gated_commit_lens_buf[:bs] if gated else None ++ ++ def _sim_bonus_args(self, logits, bs: int) -> dict: ++ return dict( ++ target_logits=logits, ++ # One length for every request: a stride-0 view, no copy node in the graph. ++ correct_len=self.simulated_correct_len.expand(bs), ++ temperatures=self.sim_temperatures_buf[:bs], ++ seed=self.sim_seed_buf, ++ bs=bs, ++ rows_per_request=self.stride, ++ ) ++ ++ def _sim_bonus(self, logits, bs: int) -> torch.Tensor: ++ return simulated_bonus_sample_graph(**self._sim_bonus_args(logits, bs)) ++ ++ def _log_accept_tail(self, bs: int, *, bonus_in) -> None: ++ """Once per captured batch size, from the branch that launches the kernel.""" ++ if ( ++ bs in self._accept_tail_logged ++ or not torch.cuda.is_available() ++ or not torch.cuda.is_current_stream_capturing() ++ ): ++ return ++ self._accept_tail_logged.add(bs) ++ logger.info( ++ "DSpark verify graph bs=%d: fused accept tail (bonus=%s, tp-broadcast=%s)", ++ bs, ++ "sim-fold" if self.simulate_fold else "argmax", ++ "inputs" if bonus_in is not None else "off", ++ ) ++ ++ def note_static_verify(self, bs: int) -> None: ++ """Host, after a static verify graph replayed ``bs`` requests.""" ++ if self.deferred_commit is not None: ++ self.deferred_commit.note_static_verify(bs) ++ ++ def _commit_engram_history( ++ self, candidates, req_pool_indices, commit_lens, verify_lens, gate ++ ) -> bool: ++ """The post-verify engram history commit, gated per row: padded rows ++ (verify_lens 0) and steps the graph does not commit (gate 0) are skipped.""" ++ history = self.engram_history() ++ if history is None: ++ return False ++ engram_commit_history( ++ history, ++ candidates, ++ req_pool_indices, ++ commit_lens, ++ live_rows=verify_lens, ++ gate=gate, ++ ) ++ return True ++ ++ def _scatter_future_relay(self, req_pool_indices: torch.Tensor, bs: int) -> None: ++ """Unconditional: a step that takes another accept publishes and stashes on ++ the host afterwards. Padded rows index slot 0, every pool's dummy row.""" ++ if self.commit_ctx is None: ++ return ++ if self.future_relay is None: ++ assert not ( ++ torch.cuda.is_available() and torch.cuda.is_current_stream_capturing() ++ ), "the future relay is built at a warmup, before capture" ++ self.future_relay = FutureRelayBuffers( ++ req_pool_size=self.commit_ctx.resolve_req_to_token().shape[0], ++ device=req_pool_indices.device, ++ ) ++ offer_future_relay_buffers(self.future_relay) ++ rows = req_pool_indices[:bs].to(torch.int64) ++ self.future_relay.new_seq_lens[rows] = self.new_seq_lens_buf[:bs] ++ self.future_relay.output_tokens[rows] = self.bonus_buf[:bs] + + def read_accept(self, bs: int) -> AcceptOuts: + return AcceptOuts( +@@ -680,6 +947,12 @@ class DsparkVerifyEpilogue: + out_tokens=self.out_tokens_buf[:bs], + ) + ++ def read_block_accept_lens(self, bs: int) -> Optional[torch.Tensor]: ++ """commit_lens + cap_trim_lens from the in-graph accept, or None.""" ++ if self.block_accept_lens_buf is None: ++ return None ++ return self.block_accept_lens_buf[:bs] ++ + @property + def folds_commit(self) -> bool: + if self.commit_ctx is None: +@@ -772,18 +1045,7 @@ class DsparkVerifyEpilogue: + ) + if self.simulate_fold: + # Before the TP broadcast in build_accept_outs: every rank commits rank 0's draw. +- bonus = ( +- simulated_bonus_sample_graph( +- target_logits=logits, +- correct_len=self.simulated_correct_len.repeat(bs), +- temperatures=self.sim_temperatures_buf[:bs], +- seed=self.sim_seed_buf, +- bs=bs, +- rows_per_request=self.stride, +- ) +- .to(bonus.dtype) +- .view_as(bonus) +- ) ++ bonus = self._sim_bonus(logits, bs).to(bonus.dtype).view_as(bonus) + accept = build_accept_outs( + correct_len=correct_len, + bonus=bonus, +@@ -796,6 +1058,7 @@ class DsparkVerifyEpilogue: + sync_site=SpecTpSyncSite.DSPARK_ACCEPT_GRAPH, + simulated_correct_len=self.simulated_correct_len, + out=self.read_accept(bs), ++ block_accept_lens_out=self.read_block_accept_lens(bs), + ) + return accept.commit_lens + +@@ -851,8 +1114,10 @@ def build_accept_outs( + target_logits: Optional[torch.Tensor] = None, + simulate_bonus_sampling_info=None, + out: Optional[AcceptOuts] = None, ++ block_accept_lens_out: Optional[torch.Tensor] = None, + ) -> AcceptOuts: +- """``out``: static buffers (the in-graph accept's) to copy the results into.""" ++ """``out``: static buffers (the in-graph accept's) to copy the results into; ++ ``block_accept_lens_out`` (with ``out``) gets commit_lens + cap_trim_lens.""" + bs = correct_len.shape[0] + if simulated_correct_len is not None: + # The accept runs as served; only its length is replaced. +@@ -898,6 +1163,10 @@ def build_accept_outs( + out.commit_lens.copy_(accept.commit_lens) + out.new_seq_lens.copy_(accept.new_seq_lens) + out.out_tokens.copy_(accept.out_tokens) ++ if block_accept_lens_out is not None: ++ torch.add( ++ accept.commit_lens, accept.cap_trim_lens, out=block_accept_lens_out ++ ) + return out + return accept + +@@ -923,6 +1192,49 @@ def sample_simulated_bonus( + return bonus.to(greedy_bonus.dtype).view_as(greedy_bonus) + + ++_blockwise_rejection_noted = False ++ ++ ++def _note_blockwise_rejection() -> None: ++ global _blockwise_rejection_noted ++ if not _blockwise_rejection_noted: ++ _blockwise_rejection_noted = True ++ logger.info("DSpark: sampled verify accepts use block-wise rejection") ++ ++ ++def _blockwise_rejection_applies( ++ *, ++ sampling_info, ++ rejection_noise: Optional[RejectionNoise], ++ block_verification: bool, ++) -> bool: ++ return ( ++ rejection_noise is not None ++ and not block_verification ++ and not sampling_info.need_top_k_sampling ++ and not sampling_info.need_top_p_sampling ++ ) ++ ++ ++def _draft_probs(draft_block: DraftBlockResult, vocab: int, device) -> torch.Tensor: ++ if draft_block.greedy_draft: ++ # An argmax draft is one-hot: rejection accepts at the target probability. ++ draft_tokens = draft_block.draft_tokens ++ draft_probs = torch.zeros( ++ (*draft_tokens.shape, vocab), dtype=torch.float32, device=device ++ ) ++ draft_probs.scatter_(-1, draft_tokens.unsqueeze(-1), 1.0) ++ return draft_probs ++ bs, gamma_rows, vocab = draft_block.corrected_logits.shape ++ draft_probs = SoftmaxTemp.execute( ++ logits=draft_block.corrected_logits.reshape(bs * gamma_rows, vocab), ++ temperatures=draft_block.temperatures, ++ rows_per_request=gamma_rows, ++ ).view(bs, gamma_rows, vocab) ++ expect(_VERIFY_DRAFT_PROBS, draft_probs) ++ return draft_probs ++ ++ + def accept_draft_tokens( + *, + candidates: torch.Tensor, +@@ -935,6 +1247,7 @@ def accept_draft_tokens( + cutoff_layout: Optional[RaggedVerifyLayout] = None, + fused_argmax: bool = False, + block_verification: bool = False, ++ rejection_noise: Optional[RejectionNoise] = None, + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + greedy_mask = draft_block.greedy_mask + cutoff_verify_lens = None if cutoff_layout is None else cutoff_layout.verify_lens +@@ -947,28 +1260,30 @@ def accept_draft_tokens( + cutoff_verify_lens=cutoff_verify_lens, + fused_argmax=fused_argmax, + ) +- if draft_block.greedy_draft: +- # An argmax draft is one-hot: rejection accepts at the target probability. +- draft_tokens = draft_block.draft_tokens +- draft_probs = torch.zeros( +- (*draft_tokens.shape, target_logits.shape[-1]), +- dtype=torch.float32, +- device=target_logits.device, ++ if _blockwise_rejection_applies( ++ sampling_info=sampling_info, ++ rejection_noise=rejection_noise, ++ block_verification=block_verification, ++ ): ++ _note_blockwise_rejection() ++ sampled = BlockwiseRejection.execute( ++ candidates=candidates, ++ target_logits=target_logits, ++ draft_logits=( ++ None if draft_block.greedy_draft else draft_block.corrected_logits ++ ), ++ target_temperatures=sampling_info.temperatures, ++ draft_temperatures=draft_block.temperatures, ++ noise=rejection_noise, ++ cutoff_verify_lens=cutoff_verify_lens, + ) +- draft_probs.scatter_(-1, draft_tokens.unsqueeze(-1), 1.0) + else: +- bs, gamma_rows, vocab = draft_block.corrected_logits.shape +- draft_probs = SoftmaxTemp.execute( +- logits=draft_block.corrected_logits.reshape(bs * gamma_rows, vocab), +- temperatures=draft_block.temperatures, +- rows_per_request=gamma_rows, +- ).view(bs, gamma_rows, vocab) +- expect(_VERIFY_DRAFT_PROBS, draft_probs) +- if not sampling_info.is_any_greedy: +- return AcceptSampling.execute( ++ sampled = AcceptSampling.execute( + candidates=candidates, + target_logits=target_logits, +- draft_probs=draft_probs, ++ draft_probs=_draft_probs( ++ draft_block, target_logits.shape[-1], target_logits.device ++ ), + sampling_info=sampling_info, + draft_input=draft_input, + gamma=gamma, +@@ -976,6 +1291,8 @@ def accept_draft_tokens( + cutoff_verify_lens=cutoff_verify_lens, + block_verification=block_verification, + ) ++ if not sampling_info.is_any_greedy: ++ return sampled + greedy_len, greedy_bonus, greedy_trim = AcceptGreedy.execute( + candidates=candidates, + target_logits=target_logits, +@@ -983,17 +1300,7 @@ def accept_draft_tokens( + cutoff_verify_lens=cutoff_verify_lens, + fused_argmax=fused_argmax, + ) +- sampling_len, sampling_bonus, sampling_trim = AcceptSampling.execute( +- candidates=candidates, +- target_logits=target_logits, +- draft_probs=draft_probs, +- sampling_info=sampling_info, +- draft_input=draft_input, +- gamma=gamma, +- verify_num_draft_tokens=verify_num_draft_tokens, +- cutoff_verify_lens=cutoff_verify_lens, +- block_verification=block_verification, +- ) ++ sampling_len, sampling_bonus, sampling_trim = sampled + selected = SelectMixedAccept.execute( + greedy_mask=greedy_mask, + greedy_len=greedy_len, +diff --git a/python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py b/python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py +index 4c9d524522..a789f2be68 100644 +--- a/python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py ++++ b/python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py +@@ -3,6 +3,9 @@ from typing import TYPE_CHECKING, Callable, Optional, Protocol, runtime_checkabl + + import torch + ++from sglang.kernels.ops.speculative.dspark.blockwise_rejection import ( ++ make_rejection_noise, ++) + from sglang.srt.configs.hybrid_arch import mambaish_config + from sglang.srt.environ import envs + from sglang.srt.layers.dp_attention import get_dp_tp_group +@@ -22,6 +25,7 @@ from sglang.srt.model_loader.weight_utils import get_pp_stage_load_group + from sglang.srt.runtime_context import ( + get_disagg, + get_exec, ++ get_memory, + get_parallel, + get_schedule, + get_spec, +@@ -44,6 +48,10 @@ from sglang.srt.speculative.dspark_components.dspark_config import ( + draft_is_deepseek_v4, + resolve_runtime_config, + ) ++from sglang.srt.speculative.dspark_components.dspark_deferred_commit import ( ++ DeferredContextCommit, ++ defer_context_kv_refusal, ++) + from sglang.srt.speculative.dspark_components.dspark_draft import ( + DraftBlockProposer, + make_next_draft_input, +@@ -64,6 +72,9 @@ from sglang.srt.speculative.dspark_components.dspark_planner import ( + dp_global_verify_tier_num_tokens, + idle_ragged_layout, + ) ++from sglang.srt.speculative.dspark_components.dspark_sampling_accept_graph import ( ++ DsparkSamplingAcceptGraph, ++) + from sglang.srt.speculative.dspark_components.dspark_verify import ( + CommitInjectCtx, + DsparkVerifyEpilogue, +@@ -132,9 +143,27 @@ def _configure_target_hidden_projection( + ) + + ++def sim_draw_ahead_enabled(simulated_correct_len: Optional[torch.Tensor]) -> bool: ++ """SGLANG_OPT_DSV41_DSPARK_SIM_DRAW_AHEAD, only under simulated acceptance: with ++ real acceptance there is no draw, so the step order stays as it was.""" ++ return ( ++ envs.SGLANG_OPT_DSV41_DSPARK_SIM_DRAW_AHEAD.get() ++ and simulated_correct_len is not None ++ ) ++ ++ + class DSparkWorkerV2(BaseSpecWorker): + """Non-last PP stages run only the target; draft state belongs to the last stage.""" + ++ _sampling_accept_graph = None ++ _rejection_noise = None ++ _sim_draw_ahead = False ++ num_sim_draws_ahead = 0 ++ _prepare_inputs_once = False ++ num_folded_verify_ids_steps = 0 ++ num_relayed_in_graph_steps = 0 ++ _verify_inputs_ready = None ++ + def weight_update_runners(self) -> list[tuple[str, "ModelRunner"]]: + return [("draft", self.draft_model_runner)] if self._hosts_draft else [] + +@@ -258,6 +287,12 @@ class DSparkWorkerV2(BaseSpecWorker): + self._block_pos_offsets = build_block_pos_offsets( + length=self.verify_num_draft_tokens, device=self.device + ) ++ # Verify-window positions, cache locs and the draft anchor column in one launch. ++ self._prepare_inputs_once = ( ++ envs.SGLANG_OPT_DSV41_DSPARK_PREPARE_INPUTS_ONCE.get() ++ ) ++ self.num_folded_verify_ids_steps = 0 ++ self.num_relayed_in_graph_steps = 0 + self._draft_block_spec_info = make_draft_block_spec_info( + draft_token_num=int(self.query_token_num), device=self.device + ) +@@ -319,6 +354,10 @@ class DSparkWorkerV2(BaseSpecWorker): + if self._simulate_acc_len > 0 + else None + ) ++ # The simulated acceptance draw (and sim bonus seed) before the draft launch, ++ # where the host waits on the previous verify anyway; off with real acceptance. ++ self._sim_draw_ahead = sim_draw_ahead_enabled(self._simulated_correct_len) ++ self.num_sim_draws_ahead = 0 + self._greedy_draft = envs.SGLANG_DSPARK_USE_GREEDY_DRAFT.get() + self._proposer = DraftBlockProposer( + draft_model=self.draft_model, +@@ -332,6 +371,14 @@ class DSparkWorkerV2(BaseSpecWorker): + dp_moe_sync=self._draft_is_moe and get_parallel().attn_dp_enabled, + ) + self._verify_epilogue = None ++ self._sampling_accept_graph: Optional[DsparkSamplingAcceptGraph] = None ++ # Counter-based draws from the server seed: every TP rank draws the same coins, ++ # so no accept broadcast is needed. ++ self._rejection_noise = ( ++ make_rejection_noise(self.target_worker.random_seed, self.device) ++ if is_cuda() and envs.SGLANG_OPT_DSV41_BLOCKWISE_REJECTION.get() ++ else None ++ ) + target_is_dsv41 = ( + getattr( + self.target_worker.model_runner.model_config.hf_text_config, +@@ -340,6 +387,16 @@ class DSparkWorkerV2(BaseSpecWorker): + ) + == "deepseek_v41" + ) ++ # SGLANG_OPT_DSV41_TARGET_METADATA_EARLY: the static verify's inputs are final ++ # after the head; the target runner stages their metadata beside the draft. ++ self._verify_inputs_ready: Optional[torch.cuda.Event] = ( ++ torch.cuda.Event() ++ if envs.SGLANG_OPT_DSV41_TARGET_METADATA_EARLY.get() ++ and self._verify_planner.mode_value == "static" ++ and not get_parallel().attn_dp_enabled ++ and torch.device(self.device).type == "cuda" ++ else None ++ ) + static_epilogue_supported = ( + target_is_dsv41 + and self._verify_planner.mode_value == "static" +@@ -362,6 +419,16 @@ class DSparkWorkerV2(BaseSpecWorker): + fused_argmax=target_is_dsv41, + simulated_correct_len=self._simulated_correct_len, + simulate_fold=envs.SGLANG_DSPARK_SIMULATE_FOLD.get(), ++ fused_accept_tail=envs.SGLANG_DSPARK_FUSED_ACCEPT_TAIL.get(), ++ accept_tail_min_bs=envs.SGLANG_DSPARK_ACCEPT_TAIL_MIN_BS.get(), ++ accept_tail_max_bs=envs.SGLANG_DSPARK_ACCEPT_TAIL_MAX_BS.get(), ++ deferred_commit=self._maybe_build_deferred_commit( ++ static_epilogue_supported ++ ), ++ post_fold=( ++ static_epilogue_supported ++ and envs.SGLANG_OPT_DSV41_DSPARK_POST_FOLD.get() ++ ), + commit_ctx=CommitInjectCtx( + draft_model=self.draft_model, + block_pos_offsets=self._block_pos_offsets, +@@ -370,11 +437,34 @@ class DSparkWorkerV2(BaseSpecWorker): + self.model_runner.req_to_token_pool.req_to_token + ), + kv_injector=self._kv_injector, ++ resolve_engram_hasher=( ++ ( ++ lambda: ( ++ self.model_runner.ngram_embedding_manager.engram_hasher ++ ) ++ ) ++ if envs.SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH.get() ++ else None ++ ), + ), + ) + self.model_runner.capture_tail_hooks.append( + self._verify_epilogue.capture_hook + ) ++ if ( ++ envs.SGLANG_OPT_DSV41_SAMPLING_ACCEPT_GRAPH.get() ++ and static_epilogue_supported ++ and is_cuda() ++ ): ++ self._sampling_accept_graph = DsparkSamplingAcceptGraph( ++ epilogue=self._verify_epilogue, ++ resolve_draft_sampler=lambda: self._draft_sampler, ++ tp_sync=self._tp_sync, ++ fused_argmax=target_is_dsv41, ++ block_verification=get_spec().speculative_use_block_verification, ++ device=self.device, ++ rejection_noise=self._rejection_noise, ++ ) + + self._simulate_acc_greedy = ( + self._simulate_acc_len > 0 and envs.SGLANG_SIMULATE_ACC_GREEDY.get() +@@ -408,6 +498,7 @@ class DSparkWorkerV2(BaseSpecWorker): + simulate_acc_len=self._simulate_acc_len, + simulated_correct_len=self._simulated_correct_len, + block_verification=get_spec().speculative_use_block_verification, ++ rejection_noise=self._rejection_noise, + ) + + self._forced_budget_frac: Optional[float] = None +@@ -520,9 +611,87 @@ class DSparkWorkerV2(BaseSpecWorker): + make_draft_sampler_capture_hook(self._draft_sampler) + ) + self._proposer.attach_draft_sampler(self._draft_sampler) ++ commit = self._deferred_commit() ++ if commit is not None: ++ self._wire_deferred_commit(commit) + self._draft_worker.init_cuda_graphs( + capture_decode_cuda_graph=capture_decode_cuda_graph + ) ++ if commit is not None: ++ commit.disarm() ++ ++ def _defer_context_kv_eligible(self, static_epilogue_supported: bool) -> bool: ++ """SGLANG_DSPARK_DEFER_CONTEXT_KV: only where nothing moves or reads draft KV ++ between a verify and the next draft forward but this worker's forwards.""" ++ if not envs.SGLANG_DSPARK_DEFER_CONTEXT_KV.get(): ++ return False ++ from sglang.srt.layers.attention.dsv4.unified_kv_gate import ( ++ is_unified_kv_triton, ++ ) ++ ++ memory = get_memory() ++ refusal = defer_context_kv_refusal( ++ static_verify=static_epilogue_supported, ++ draft_is_moe=self._draft_is_moe, ++ unified_kv=is_unified_kv_triton(), ++ unified_memory=memory.enable_unified_memory, ++ hicache=memory.enable_hierarchical_cache ++ or memory.hicache_storage_backend is not None, ++ disaggregated=get_disagg().disaggregation_mode != "null", ++ attn_dp=get_parallel().attn_dp_enabled, ++ ) ++ if refusal: ++ logger.warning( ++ "SGLANG_DSPARK_DEFER_CONTEXT_KV refused, the commit stays in the " ++ "verify graph: %s", ++ refusal, ++ ) ++ return False ++ return True ++ ++ def _maybe_build_deferred_commit( ++ self, static_epilogue_supported: bool ++ ) -> Optional[DeferredContextCommit]: ++ if not self._defer_context_kv_eligible(static_epilogue_supported): ++ return None ++ commit = DeferredContextCommit( ++ max_bs=max(get_exec().graph.cuda_graph_config.decode.bs), ++ stride=self.verify_num_draft_tokens, ++ device=self.device, ++ kv_injector=self._kv_injector, ++ ) ++ # The target's logits processor: SGLang's forward and a megakernel's head ++ # both call it, with the DSpark hidden, once the hidden is final. ++ self.model_runner.model.logits_processor.register_forward_pre_hook( ++ commit.logits_pre_hook, with_kwargs=True ++ ) ++ return commit ++ ++ def _deferred_commit(self): ++ epilogue = self._verify_epilogue ++ return None if epilogue is None else epilogue.deferred_commit ++ ++ def _wire_deferred_commit(self, commit) -> None: ++ """Draft side of SGLANG_DSPARK_DEFER_CONTEXT_KV: the draft graph forks the ++ staged write at its head and its first KV store joins it.""" ++ from sglang.srt.layers.attention.deepseek_v4_backend import ( ++ DeepseekV4AttnBackend, ++ DeepseekV4MultiStepBackend, ++ ) ++ ++ self._proposer.deferred_commit = commit ++ self.draft_model_runner.capture_head_hooks.append(commit.capture_head_hook) ++ backend = self.draft_model_runner.attn_backend ++ backends = [backend] ++ if isinstance(backend, DeepseekV4MultiStepBackend): ++ backends.extend(backend.attn_backends) ++ for b in backends: ++ if isinstance(b, DeepseekV4AttnBackend): ++ b.pre_kv_store_hook = commit.join ++ logger.info( ++ "SGLANG_DSPARK_DEFER_CONTEXT_KV: the draft context-KV commit runs at the " ++ "head of the next draft graph, joined at its first KV store." ++ ) + + def _maybe_build_draft_sampler(self): + return maybe_build_draft_sampler( +@@ -542,7 +711,12 @@ class DSparkWorkerV2(BaseSpecWorker): + ) + + def clear_cache_pool(self): +- pass ++ if not self._hosts_draft: ++ return ++ # The staged rows' slots were just freed. ++ commit = self._deferred_commit() ++ if commit is not None: ++ commit.disarm() + + def set_dspark_forced_budget_frac(self, frac: Optional[float]) -> None: + if not self._hosts_draft: +@@ -642,6 +816,10 @@ class DSparkWorkerV2(BaseSpecWorker): + ) + return self._decode_idle_result(on_publish=on_publish) + ++ # The prefill's draft KV may land in slots a pending commit targets. ++ commit = self._deferred_commit() ++ if commit is not None: ++ commit.flush() + batch_output = self.target_worker.forward_batch_generation( + batch, + pp_proxy_tensors=pp_proxy_tensors, +@@ -804,6 +982,27 @@ class DSparkWorkerV2(BaseSpecWorker): + new_seq_lens=next_draft_input.new_seq_lens, + ) + ++ def _stage_target_verify_metadata( ++ self, *, batch: ScheduleBatch, verify_window, seq_lens_cpu ++ ) -> None: ++ """Right after the draft graph's launch; the sources are the tensors the verify ++ batch uses, and the side stream waits only for the head (_verify_inputs_ready).""" ++ target_runner = self.target_worker.model_runner.decode_cuda_graph_runner ++ if target_runner is None: ++ return ++ target_runner.stage_verify_metadata_early( ++ seq_lens=batch.seq_lens, ++ req_pool_indices=batch.req_pool_indices, ++ out_cache_loc=verify_window.verify_cache_loc, ++ positions=verify_window.positions_2d.reshape(-1), ++ max_seq_len=( ++ int(seq_lens_cpu.max()) ++ if seq_lens_cpu is not None and seq_lens_cpu.numel() > 0 ++ else None ++ ), ++ after=self._verify_inputs_ready, ++ ) ++ + def _forward_decode( + self, + batch: ScheduleBatch, +@@ -860,6 +1059,16 @@ class DSparkWorkerV2(BaseSpecWorker): + self._observers.begin_step() + + target_model = self.target_worker.model_runner.model ++ anchor_ids = ( ++ self._proposer.draft_block_ids_view(bs=bs, device=prefix_lens.device) ++ if self._prepare_inputs_once ++ else None ++ ) ++ window_seq_lens_cpu = ( ++ batch.seq_lens_cpu ++ if batch.seq_lens_cpu is not None ++ else draft_input.nxt_kv_lens_cpu ++ ) + verify_window = alloc_verify_window( + batch=batch, + bs=bs, +@@ -867,12 +1076,13 @@ class DSparkWorkerV2(BaseSpecWorker): + verify_num_draft_tokens=self.verify_num_draft_tokens, + block_pos_offsets=self._block_pos_offsets, + model_runner=self.model_runner, +- seq_lens_cpu=( +- batch.seq_lens_cpu +- if batch.seq_lens_cpu is not None +- else draft_input.nxt_kv_lens_cpu +- ), ++ seq_lens_cpu=window_seq_lens_cpu, ++ bonus=draft_input.bonus_tokens.view(-1) if anchor_ids is not None else None, ++ anchor_ids=anchor_ids, + ) ++ if self._verify_inputs_ready is not None: ++ # The verify's inputs are final here; the early metadata waits for this. ++ self._verify_inputs_ready.record() + + sampling_info = batch.sampling_info + # Simulated acceptance overrides correct_len, so only the bonus token needs the +@@ -890,6 +1100,10 @@ class DSparkWorkerV2(BaseSpecWorker): + ): + simulate_bonus_sampling_info = sampling_info + sampling_info = None ++ if self._sim_draw_ahead: ++ self._begin_simulated_step_ahead( ++ bs=bs, simulate_bonus_sampling_info=simulate_bonus_sampling_info ++ ) + with self._draft_context(), self._observers.segment(InfoSegment.DRAFT): + proposal = self._proposer.propose( + batch=batch, +@@ -899,6 +1113,13 @@ class DSparkWorkerV2(BaseSpecWorker): + device=device, + target_model=target_model, + sampling_info=sampling_info, ++ anchor_prepared=anchor_ids is not None, ++ ) ++ if self._verify_inputs_ready is not None: ++ self._stage_target_verify_metadata( ++ batch=batch, ++ verify_window=verify_window, ++ seq_lens_cpu=window_seq_lens_cpu, + ) + draft_block_ids = proposal.draft_block_ids + draft_block = proposal.draft_block +@@ -926,9 +1147,15 @@ class DSparkWorkerV2(BaseSpecWorker): + ) + run_compact = self._verify_planner.should_run_compact(layout=layout) + +- verify_ids_2d = torch.cat( +- [draft_block_ids[:, :1], draft_tokens], dim=1 +- ).contiguous() ++ verify_ids_2d = proposal.verify_ids ++ if verify_ids_2d is None: ++ verify_ids_2d = torch.cat( ++ [draft_block_ids[:, :1], draft_tokens], dim=1 ++ ).contiguous() ++ else: ++ self.num_folded_verify_ids_steps += 1 ++ if self.num_folded_verify_ids_steps == 1: ++ logger.info("Verify ids read from the draft graph output (first step).") + + # Must stay ahead of the target verify launch below. + grammar_tree = ( +@@ -953,16 +1180,17 @@ class DSparkWorkerV2(BaseSpecWorker): + ) + and not batch.has_grammar + ) +- self._verify_executor.begin_simulated_step() +- if fold_eligible and self._verify_executor.verify_epilogue.simulate_fold: +- self._verify_executor.verify_epilogue.begin_sim_bonus( +- bs, +- ( +- None +- if simulate_bonus_sampling_info is None +- else simulate_bonus_sampling_info.temperatures[:bs] +- ), +- ) ++ if not self._sim_draw_ahead: ++ self._verify_executor.begin_simulated_step() ++ if fold_eligible and self._verify_executor.verify_epilogue.simulate_fold: ++ self._verify_executor.verify_epilogue.begin_sim_bonus( ++ bs, ++ ( ++ None ++ if simulate_bonus_sampling_info is None ++ else simulate_bonus_sampling_info.temperatures[:bs] ++ ), ++ ) + prepare_mamba_track_for_verify(batch) + with self._observers.segment(InfoSegment.TARGET_VERIFY): + if run_compact: +@@ -1012,24 +1240,53 @@ class DSparkWorkerV2(BaseSpecWorker): + and can_run_cuda_graph + and (run_compact or self._verify_planner.mode_value == "static") + ) +- accept = self._verify_executor.accept_and_finalize( +- folded_accept=folded_accept, +- bs=bs, +- verify_ids_2d=verify_ids_2d, +- target_logits=logits_output.next_token_logits, +- draft_block=draft_block, +- sampling_info=sampling_info, +- draft_input=draft_input, +- layout=layout, +- prefix_lens=prefix_lens, +- draft_tokens=draft_tokens, +- simulate_bonus_sampling_info=simulate_bonus_sampling_info, +- ) +- self.model_runner.ngram_embedding_manager.update_after_verify( +- verify_ids_2d=verify_ids_2d, +- req_pool_indices=batch.req_pool_indices, +- commit_lens=accept.commit_lens, ++ region_accept = None ++ if ( ++ not folded_accept ++ and can_run_cuda_graph ++ and not run_compact ++ and self._sampling_graph_eligible( ++ batch=batch, ++ proposal_folded=proposal.folded, ++ sampling_info=sampling_info, ++ simulate_bonus_sampling_info=simulate_bonus_sampling_info, ++ ) ++ ): ++ region_accept = self._sampling_accept_graph.run( ++ bs=bs, target_logits=logits_output.next_token_logits ++ ) ++ # The accept and its commits ran in a graph: the verify graph's fold or the ++ # sampling-accept region replayed right after it. ++ graph_accept = folded_accept or region_accept is not None ++ if region_accept is not None: ++ epilogue.note_static_verify(bs) ++ accept = region_accept ++ else: ++ accept = self._verify_executor.accept_and_finalize( ++ folded_accept=folded_accept, ++ bs=bs, ++ verify_ids_2d=verify_ids_2d, ++ target_logits=logits_output.next_token_logits, ++ draft_block=draft_block, ++ sampling_info=sampling_info, ++ draft_input=draft_input, ++ layout=layout, ++ prefix_lens=prefix_lens, ++ draft_tokens=draft_tokens, ++ simulate_bonus_sampling_info=simulate_bonus_sampling_info, ++ ) ++ engram_in_graph = ( ++ folded_accept and not run_compact and epilogue.folds_engram_commit ++ ) or ( ++ region_accept is not None and self._sampling_accept_graph.committed_engram + ) ++ # The static verify graph committed the engram history when it folded the accept. ++ if not engram_in_graph: ++ self.model_runner.ngram_embedding_manager.update_after_verify( ++ verify_ids_2d=verify_ids_2d, ++ req_pool_indices=batch.req_pool_indices, ++ commit_lens=accept.commit_lens, ++ ) + sampling_mask_capture = SpeculativeSamplingMaskCapture.from_logits( + sampling_info, + next_token_logits=logits_output.next_token_logits, +@@ -1051,6 +1308,11 @@ class DSparkWorkerV2(BaseSpecWorker): + chain_stride=self.verify_num_draft_tokens, + ) + ++ relay = self._future_relay_in_graph( ++ run_compact=run_compact, folded_accept=graph_accept ++ ) ++ if relay is not None: ++ relay.published_seq_lens = accept.new_seq_lens + if on_publish is not None: + if confidence is not None: + on_publish(accept.new_seq_lens, confidence=confidence) +@@ -1064,7 +1326,7 @@ class DSparkWorkerV2(BaseSpecWorker): + commit_lens=accept.commit_lens, + ) + +- folded_commit = folded_accept and epilogue.folds_commit ++ folded_commit = graph_accept and epilogue.folds_commit + # Consume in this step: every decode graph size shares one aux output, + # which the next target forward overwrites (resolve_aux_hidden_states_width). + if not folded_commit: +@@ -1108,11 +1370,15 @@ class DSparkWorkerV2(BaseSpecWorker): + bonus_tokens=accept.bonus, + new_seq_lens=accept.new_seq_lens, + ) ++ if relay is not None: ++ relay.published_bonus = next_draft_input.bonus_tokens + return GenerationBatchResult( + logits_output=logits_output, + next_token_ids=accept.out_tokens.reshape(-1), + accept_lens=accept.commit_lens, +- block_accept_lens=accept.commit_lens + accept.cap_trim_lens, ++ block_accept_lens=self._block_accept_lens( ++ accept=accept, folded_accept=graph_accept, bs=bs ++ ), + cap_lens=( + layout.verify_lens.to(torch.int32) if layout is not None else None + ), +@@ -1122,6 +1388,73 @@ class DSparkWorkerV2(BaseSpecWorker): + new_seq_lens=accept.new_seq_lens, + ) + ++ def _sampling_graph_eligible( ++ self, ++ *, ++ batch: ScheduleBatch, ++ proposal_folded: bool, ++ sampling_info, ++ simulate_bonus_sampling_info, ++ ) -> bool: ++ """An all-sampled static step the sampling-accept region reproduces exactly.""" ++ return ( ++ self._sampling_accept_graph is not None ++ and proposal_folded ++ and self._verify_planner.mode_value == "static" ++ and sampling_info is not None ++ and not sampling_info.is_any_greedy ++ and not sampling_info.need_top_k_sampling ++ and not sampling_info.need_top_p_sampling ++ and verify_logits_adjustments_are_noop(sampling_info) ++ and simulate_bonus_sampling_info is None ++ and not batch.has_grammar ++ ) ++ ++ def _future_relay_in_graph(self, *, run_compact: bool, folded_accept: bool): ++ """The FutureMap relay this step's static graph already scattered into ++ (SGLANG_OPT_DSV41_DSPARK_POST_FOLD), or None for the host scatter.""" ++ epilogue = self._verify_executor.verify_epilogue ++ if epilogue is None or run_compact or not folded_accept: ++ return None ++ relay = epilogue.future_relay ++ if relay is None or not relay.adopted: ++ return None ++ self.num_relayed_in_graph_steps += 1 ++ if self.num_relayed_in_graph_steps == 1: ++ logger.info("Seq lens and bonus relayed by the verify graph (first step).") ++ return relay ++ ++ def _begin_simulated_step_ahead(self, *, bs: int, simulate_bonus_sampling_info): ++ """Issued before the draft launch (neither write depends on it); a step that ++ turns out not fold-eligible ignores the sim bonus buffers.""" ++ executor = self._verify_executor ++ executor.begin_simulated_step() ++ epilogue = executor.verify_epilogue ++ if epilogue is not None and epilogue.simulate_fold: ++ epilogue.begin_sim_bonus( ++ bs, ++ ( ++ None ++ if simulate_bonus_sampling_info is None ++ else simulate_bonus_sampling_info.temperatures[:bs] ++ ), ++ ) ++ self.num_sim_draws_ahead += 1 ++ if self.num_sim_draws_ahead == 1: ++ logger.info( ++ "Simulated acceptance drawn ahead of the draft launch (first step)." ++ ) ++ ++ def _block_accept_lens(self, *, accept, folded_accept: bool, bs: int): ++ in_graph = ( ++ self._verify_epilogue.read_block_accept_lens(bs) ++ if folded_accept and self._verify_epilogue is not None ++ else None ++ ) ++ if in_graph is not None: ++ return in_graph ++ return accept.commit_lens + accept.cap_trim_lens ++ + def _commit_target_mamba_states_after_verify( + self, + *, diff --git a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml index 3c658c854d..9a00a81538 100644 --- a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml +++ b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml @@ -5,8 +5,8 @@ base: identity: model: {} frameworks: - dynamo: "1.6.0.dev20261014" - sglang: "0.0.0.dev1+ga6a8c5601" + dynamo: "1.6.0.dev20261019" + sglang: "0.0.0.dev1+gc1c287a42" dynamo: install: false request_plane: tcp @@ -115,16 +115,53 @@ override_tp2_c16: override_tp4_c1: name: dsv41flash-fp4-gb300-dynamo-sglang-agentx-agg-tp4ep1-c1 + setup_script: dsv41flash-sglang-patches.sh roles: agg: gpus: 4 args: tensor-parallel-size: 4 expert-parallel-size: 1 - prefill-decode-interval: 0 - max-running-requests: 1 + mem-fraction-static: 0.91 + kv-cache-dtype: fp8_e4m3 + dsv4-attn-backend: flashmla + moe-a2a-backend: none + enable-nvidia-megakernel: true + startup-weight-load-mode: serial enable-decoder-swa-bounded-replay: true - cuda-graph-backend-prefill: disabled + context-length: 1048576 + max-running-requests: 1 + cuda-graph-max-bs-decode: 1 + prefill-decode-interval: 16 + schedule-policy: lpm + swa-prefix-tails: 128 + tokenizer-backend: fastokens + enable-metrics-for-all-schedulers: true + env: + SGLANG_SPEC_TP_SYNC: rng,-dspark-accept-sample + SGLANG_ENABLE_DSV41_ENGRAM_HOST_TABLE: "1" + SGLANG_DSV41_ENGRAM_HOST_TABLE_LAYOUT: per_rank + SGLANG_NVIDIA_MEGAKERNEL_SLOTS: hop_a,moe,gate,attn,embed,two_shot,markov,draft_lm_head,aux_mean_stats,gate_wide,shared_ll,hop_a_batch2,engram,attn_qkv_a,attn_qkv_a_bf16,index_q_mxfp8_in,attn_indexer,hc_prenorm,hop_b,hop_b_wide,early_trigger,hop_b_start_trigger,draft,draft_moe,draft_gate,draft_tail,draft_post,draft_seam,draft_attn,draft_qfront,draft_wo_a,draft_swapab,draft_qkv_a,draft_prenorm,draft_qkv_a_ll,draft_wo_b_ll,sched_ahead,req_pos_once,kv_before_wait,target_lm_head,hop_b_quad_trigger,lm_head_pinned_tactic + SGLANG_DSPARK_FUSED_ACCEPT_TAIL: "1" + SGLANG_DSPARK_DEFER_CONTEXT_KV: "1" + SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK: "1" + SGLANG_OPT_DSV41_DSPARK_POST_FOLD: "1" + SGLANG_OPT_DSV41_DSPARK_SKIP_PREFILLED_INPUTS: "1" + SGLANG_OPT_DSV41_DSPARK_ONE_LAUNCH_COMMIT_STAGE: "1" + SGLANG_OPT_DSV41_DSPARK_PREPARE_INPUTS_ONCE: "1" + SGLANG_OPT_DSV41_DSPARK_MID_FOLD: "1" + SGLANG_OPT_DSV41_TARGET_VERIFY_METADATA_GLUE: "1" + SGLANG_OPT_DSV41_TARGET_METADATA_EARLY: "1" + SGLANG_OPT_SKIP_GLUED_REPLAY_VIEW: "1" + SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH: "1" + SGLANG_OPT_DSV41_BLOCKWISE_REJECTION: "1" + SGLANG_OPT_DSV41_SAMPLING_ACCEPT_GRAPH: "1" + SGLANG_SIMULATE_ACC_GREEDY: "0" + SGLANG_OPT_DSV41_DSPARK_SIM_DRAW_AHEAD: "1" + SGLANG_OPT_MXFP4_DEFERRED_FINALIZED_SHAPE: "1" + SGLANG_OPT_CUDA_GRAPH_FILL_FAST_PATH: "1" + NCCL_CUMEM_ENABLE: "0" + NCCL_MNNVL_ENABLE: "0" override_tp4_c4: name: dsv41flash-fp4-gb300-dynamo-sglang-agentx-agg-tp4ep1-c4 diff --git a/inferencex-e2e/configs/nvidia-master.yaml b/inferencex-e2e/configs/nvidia-master.yaml index f5e43bda57..ca8bc5554b 100644 --- a/inferencex-e2e/configs/nvidia-master.yaml +++ b/inferencex-e2e/configs/nvidia-master.yaml @@ -9274,13 +9274,13 @@ dsv41flash-fp4-gb300-sglang-agentic-dspark: - { tp: 2, ep: 2, dp-attn: true, kv-offloading: none, spec-decoding: mtp, conc-list: [64, 128, 160], router: { name: sglang-router, version: "0.3.2" }, srt-recipe: agentic.yaml } - { tp: 4, ep: 1, kv-offloading: none, spec-decoding: mtp, conc-list: [1, 4, 16], srt-recipe: agentic.yaml } dsv41flash-fp4-gb300-dynamo-sglang-agentic-agg: - image: lmsysorg/sglang:nightly-dev-cu13-20261015-a6a8c560@sha256:0a1ba33aa4e032b8c5bcebdc69c45664074c032074add4f7db01629ec1fcc381 + image: lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4@sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb model: deepseek-ai/DeepSeek-V4.1-Flash model-prefix: dsv41flash runner: cluster:gb300-nv precision: fp4 framework: dynamo-sglang - router: { name: dynamo-router, version: "1.6.0.dev20261014" } + router: { name: dynamo-router, version: "1.6.0.dev20261019" } multinode: true disagg: false srt-recipe-dir: dsv41flash/sglang/gb300-fp4/agentx diff --git a/inferencex-e2e/docs/waiver/XXXX.md b/inferencex-e2e/docs/waiver/XXXX.md new file mode 100644 index 0000000000..f5e6c7bff1 --- /dev/null +++ b/inferencex-e2e/docs/waiver/XXXX.md @@ -0,0 +1,42 @@ +# Inference-engine patch waiver — PR #XXXX + +Filed per [`docs/PR_REVIEW_CHECKLIST.md`](../PR_REVIEW_CHECKLIST.md) (image-provenance / patch item). One recipe variant in this PR patches the pinned serving-stack image before serving. The checklist prohibits this unless a filled-out waiver covers it. + +## Config covered + +- **Master config entry:** `dsv41flash-fp4-gb300-dynamo-sglang-agentic-agg` in [`configs/nvidia-master.yaml`](../../configs/nvidia-master.yaml). Only the TP4 c1 point is patched (`agg-variants.yaml:override_tp4_c1`). The c4, c16 and TP2 c16 points run the image as shipped. +- **Pinned image:** `lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4@sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb` +- **Patch entrypoint:** `setup_script: dsv41flash-sglang-patches.sh` in [`agg-variants.yaml`](../../benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml) (`override_tp4_c1`) +- **Patch script:** [`benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh`](../../benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh) + +## What is patched + +The patch script makes two changes. Both are idempotent and serialized with `flock`. + +| Upstream PR/commit | What it changes | How | +|---|---|---| +| sglang [#45450](https://github.com/sgl-project/sglang/pull/45450), merged as `c82f7141` | Moves the host work between DSv4.1 DSpark decode graphs into the graphs on the megakernel path. Its new code paths are opt-in `SGLANG_OPT_*` / `SGLANG_DSPARK_*` env gates, and only the c1 point sets them. | `git apply` of `dsv41flash-sglang-patches/sglang-pr45450.patch` to `/sgl-workspace/sglang`. This is the merged squash backported to `c1c287a4`, with context conflicts in 4 files resolved to the `c1c287a4` side. | +| sgl-nvidia-mega `3333e4cf` (main at [#16](https://github.com/sgl-project/sgl-nvidia-mega/pull/16), including #7, #15 and #18) | Replaces the image's plugin pin `d47deb33`. That pin predates SGLang's kernel regrouping (sglang#45112) and the `TopKConfig` split (sglang#44912/#44913), which `c1c287a4` already contains. With `d47deb33`, `--enable-nvidia-megakernel` fails at startup. | `git fetch` + `checkout` of the pinned commit in the image's editable checkout `/sgl-workspace/sgl-nvidia-mega`. Its `pyproject.toml` is unchanged since `d47deb33`, so no reinstall is needed. | + +## Why the unmodified upstream image cannot run this benchmark + +The batch-1 megakernel recipe depends on the #45450 env gates, which do not exist in `c1c287a4`. It also depends on a plugin that builds on current SGLang. No public `lmsysorg/sglang` nightly contains #45450. + +- The dev-image builds of 2026-10-22 and 2026-10-23 failed at dependency resolution (the `python-dateutil`/`botocore` conflict addressed by sglang #45857 / #45860). +- SGLang's `docker/Dockerfile` still pins `SGL_NVIDIA_MEGA_COMMIT=d47deb33`. + +## Upstream PR / issue links + +- https://github.com/sgl-project/sglang/pull/45450 (merged) +- https://github.com/sgl-project/sgl-nvidia-mega/pull/16 (merged) +- https://github.com/sgl-project/sglang/pull/45857, https://github.com/sgl-project/sglang/pull/45860 (nightly build fix, open) +- https://github.com/sgl-project/sglang/pull/46030 (pins `SGL_NVIDIA_MEGA_COMMIT` to `3333e4cf`, open) + +## Removal plan + +Once sglang#46030 lands and a public `lmsysorg/sglang` nightly contains both #45450 and that sgl-nvidia-mega pin, make these changes in one PR: + +- move `dsv41flash-fp4-gb300-dynamo-sglang-agentic-agg` to that image; +- drop `setup_script` from `override_tp4_c1`; +- delete `dsv41flash-sglang-patches.sh` and `dsv41flash-sglang-patches/`; +- delete this waiver. diff --git a/inferencex-e2e/perf-changelog.yaml b/inferencex-e2e/perf-changelog.yaml index cc0307e621..93ed866ed1 100644 --- a/inferencex-e2e/perf-changelog.yaml +++ b/inferencex-e2e/perf-changelog.yaml @@ -10911,3 +10911,16 @@ - "Update the SGLang ROCm image from v0.5.21-rocm720-mi30x to v0.5.22-rocm720-mi30x." pr-link: https://github.com/SemiAnalysisAI/InferenceX/pull/4408 scenario-type: [agentic-coding] + +- config-keys: + - dsv41flash-fp4-gb300-dynamo-sglang-agentic-agg + - dsv41flash-fp4-gb300-dynamo-sglang-agentic-dspark-disagg + scenario-type: + - agentic-coding + description: + - "Move the aggregated points to lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4 (digest sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb) with the ai-dynamo 1.6.0.dev20261019 it ships, the image the disaggregated points already use. The TP4 c4/c16 and TP2/EP2 c16 engine settings are unchanged; they run the image as shipped, without the megakernel or the setup script. They were not rerun on c1c287a4; the CI sweep is their first run." + - "TP4 c1 becomes a strict batch-1 NVIDIA megakernel point: max-running-requests 1, cuda-graph-max-bs-decode 1, --enable-nvidia-megakernel with 42 kernel slots, the sglang#45450 decode-graph gates, SWA prefix tails 128, prefill-decode interval 16, LPM scheduling and NCCL_CUMEM_ENABLE/NCCL_MNNVL_ENABLE off." + - "TP4 c1 also sets kv-cache-dtype fp8_e4m3 and SGLANG_SPEC_TP_SYNC=rng,-dspark-accept-sample as in the reference BS1 recipe, and mem-fraction-static 0.91 (the reference launch's resolved default; the base recipe sets 0.8). It drops cuda-graph-backend-prefill: disabled, so prefill uses the image default, which disables the prefill CUDA graph for DeepSeek-V4." + - "Only TP4 c1 applies sglang#45450 (merged after the October 21 nightly) and checks out sgl-nvidia-mega 3333e4cf over the image's d47deb33 at startup (dsv41flash-sglang-patches.sh); waiver in docs/waiver/XXXX.md." + - "Include the unchanged disaggregated points in the sweep so the curve is complete." + pr-link: https://github.com/SemiAnalysisAI/InferenceX/pull/XXXX From c989f0814e9d03937b998294db990995139c27de Mon Sep 17 00:00:00 2001 From: weireweire <20922698+weireweire@users.noreply.github.com> Date: Fri, 23 Oct 2026 20:15:08 +0800 Subject: [PATCH 2/4] =?UTF-8?q?chore(agentx):=20fill=20in=20PR=20number=20?= =?UTF-8?q?4434=20for=20the=20waiver=20and=20changelog=20link=20/=20?= =?UTF-8?q?=E5=A1=AB=E5=85=A5=20PR=20=E7=BC=96=E5=8F=B7=204434?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- inferencex-e2e/docs/waiver/{XXXX.md => 4434.md} | 2 +- inferencex-e2e/perf-changelog.yaml | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) rename inferencex-e2e/docs/waiver/{XXXX.md => 4434.md} (98%) diff --git a/inferencex-e2e/docs/waiver/XXXX.md b/inferencex-e2e/docs/waiver/4434.md similarity index 98% rename from inferencex-e2e/docs/waiver/XXXX.md rename to inferencex-e2e/docs/waiver/4434.md index f5e6c7bff1..8fb2842250 100644 --- a/inferencex-e2e/docs/waiver/XXXX.md +++ b/inferencex-e2e/docs/waiver/4434.md @@ -1,4 +1,4 @@ -# Inference-engine patch waiver — PR #XXXX +# Inference-engine patch waiver — PR #4434 Filed per [`docs/PR_REVIEW_CHECKLIST.md`](../PR_REVIEW_CHECKLIST.md) (image-provenance / patch item). One recipe variant in this PR patches the pinned serving-stack image before serving. The checklist prohibits this unless a filled-out waiver covers it. diff --git a/inferencex-e2e/perf-changelog.yaml b/inferencex-e2e/perf-changelog.yaml index 93ed866ed1..7512f1a1dd 100644 --- a/inferencex-e2e/perf-changelog.yaml +++ b/inferencex-e2e/perf-changelog.yaml @@ -10921,6 +10921,6 @@ - "Move the aggregated points to lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4 (digest sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb) with the ai-dynamo 1.6.0.dev20261019 it ships, the image the disaggregated points already use. The TP4 c4/c16 and TP2/EP2 c16 engine settings are unchanged; they run the image as shipped, without the megakernel or the setup script. They were not rerun on c1c287a4; the CI sweep is their first run." - "TP4 c1 becomes a strict batch-1 NVIDIA megakernel point: max-running-requests 1, cuda-graph-max-bs-decode 1, --enable-nvidia-megakernel with 42 kernel slots, the sglang#45450 decode-graph gates, SWA prefix tails 128, prefill-decode interval 16, LPM scheduling and NCCL_CUMEM_ENABLE/NCCL_MNNVL_ENABLE off." - "TP4 c1 also sets kv-cache-dtype fp8_e4m3 and SGLANG_SPEC_TP_SYNC=rng,-dspark-accept-sample as in the reference BS1 recipe, and mem-fraction-static 0.91 (the reference launch's resolved default; the base recipe sets 0.8). It drops cuda-graph-backend-prefill: disabled, so prefill uses the image default, which disables the prefill CUDA graph for DeepSeek-V4." - - "Only TP4 c1 applies sglang#45450 (merged after the October 21 nightly) and checks out sgl-nvidia-mega 3333e4cf over the image's d47deb33 at startup (dsv41flash-sglang-patches.sh); waiver in docs/waiver/XXXX.md." + - "Only TP4 c1 applies sglang#45450 (merged after the October 21 nightly) and checks out sgl-nvidia-mega 3333e4cf over the image's d47deb33 at startup (dsv41flash-sglang-patches.sh); waiver in docs/waiver/4434.md." - "Include the unchanged disaggregated points in the sweep so the curve is complete." - pr-link: https://github.com/SemiAnalysisAI/InferenceX/pull/XXXX + pr-link: https://github.com/SemiAnalysisAI/InferenceX/pull/4434 From 710e01591bae3732162668dd8bbd1bd245ce16a4 Mon Sep 17 00:00:00 2001 From: weireweire <20922698+weireweire@users.noreply.github.com> Date: Sat, 24 Oct 2026 05:08:43 +0800 Subject: [PATCH 3/4] =?UTF-8?q?fix(agentx):=20pin=20FlashMLA=20for=20GB300?= =?UTF-8?q?=20DSV4.1-Flash=20agg=20TP4=20c4/c16=20and=20TP2=20c16=20/=20?= =?UTF-8?q?=E4=B8=BA=20TP4=20c4/c16=20=E4=B8=8E=20TP2=20c16=20=E5=9B=BA?= =?UTF-8?q?=E5=AE=9A=20FlashMLA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root cause: on the 20261021 nightly, dsv4-attn-backend auto resolves to flashmla_mega for DeepSeek-V4.1 with an fp8_e4m3 KV cache on SM100 (sglang#43922). MegaAttention zero-pads the per-rank query heads to 64, so TP4 (16 local heads) does 4x and TP2 (32) 2x the attention work. The target-verify graph gets about 1.1 ms per decode step slower at TP4. Fix: set dsv4-attn-backend: flashmla in override_tp4_c4, override_tp4_c16 and override_tp2_c16. TP4 c1 already pins flashmla. Validation (local, same recipe and client as CI, 60-min profiling window): - TP4 c4: P90 interactivity 465.8 -> 590.8, decode step 6.41 -> 5.05 ms - TP4 c16: P90 403.7 -> 468.6, TTFT P90 1.89 -> 1.40 s - TP2/EP2 c16: P50/P90 376.2/309.0 -> 414.8/315.4 All runs 0 errors; throughput/GPU within 1.5%. --- .../dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml | 3 +++ inferencex-e2e/perf-changelog.yaml | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml index 9a00a81538..885433a1f7 100644 --- a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml +++ b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml @@ -102,6 +102,7 @@ override_tp2_c16: args: tensor-parallel-size: 2 expert-parallel-size: 2 + dsv4-attn-backend: flashmla enable-decoder-swa-bounded-replay: true cuda-graph-backend-prefill: disabled prefill-decode-interval: 96 @@ -171,6 +172,7 @@ override_tp4_c4: args: tensor-parallel-size: 4 expert-parallel-size: 1 + dsv4-attn-backend: flashmla prefill-decode-interval: 0 swa-prefix-tails: 4096 max-running-requests: 128 @@ -187,6 +189,7 @@ override_tp4_c16: args: tensor-parallel-size: 4 expert-parallel-size: 1 + dsv4-attn-backend: flashmla prefill-decode-interval: 192 swa-prefix-tails: 4096 max-running-requests: 128 diff --git a/inferencex-e2e/perf-changelog.yaml b/inferencex-e2e/perf-changelog.yaml index d0a2026649..55acf4b52e 100644 --- a/inferencex-e2e/perf-changelog.yaml +++ b/inferencex-e2e/perf-changelog.yaml @@ -10963,7 +10963,7 @@ scenario-type: - agentic-coding description: - - "Move the aggregated points to lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4 (digest sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb) with the ai-dynamo 1.6.0.dev20261019 it ships, the image the disaggregated points already use. The TP4 c4/c16 and TP2/EP2 c16 engine settings are unchanged; they run the image as shipped, without the megakernel or the setup script. They were not rerun on c1c287a4; the CI sweep is their first run." + - "Move the aggregated points to lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4 (digest sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb) with the ai-dynamo 1.6.0.dev20261019 it ships, the image the disaggregated points already use. On this image dsv4-attn-backend auto picks FlashMLA MegaAttention (sglang#43922), which zero-pads the per-rank attention heads to 64, so TP4 c4/c16 and TP2/EP2 c16 pin dsv4-attn-backend flashmla and otherwise run the image as shipped, without the megakernel or the setup script." - "TP4 c1 becomes a strict batch-1 NVIDIA megakernel point: max-running-requests 1, cuda-graph-max-bs-decode 1, --enable-nvidia-megakernel with 42 kernel slots, the sglang#45450 decode-graph gates, SWA prefix tails 128, prefill-decode interval 16, LPM scheduling and NCCL_CUMEM_ENABLE/NCCL_MNNVL_ENABLE off." - "TP4 c1 also sets kv-cache-dtype fp8_e4m3 and SGLANG_SPEC_TP_SYNC=rng,-dspark-accept-sample as in the reference BS1 recipe, and mem-fraction-static 0.91 (the reference launch's resolved default; the base recipe sets 0.8). It drops cuda-graph-backend-prefill: disabled, so prefill uses the image default, which disables the prefill CUDA graph for DeepSeek-V4." - "Only TP4 c1 applies sglang#45450 (merged after the October 21 nightly) and checks out sgl-nvidia-mega 3333e4cf over the image's d47deb33 at startup (dsv41flash-sglang-patches.sh); waiver in docs/waiver/4434.md." From 6e0aec9ff3ef06dc985a6408b2461b0184296e6c Mon Sep 17 00:00:00 2001 From: weireweire <20922698+weireweire@users.noreply.github.com> Date: Sun, 25 Oct 2026 09:54:08 +0800 Subject: [PATCH 4/4] =?UTF-8?q?feat(agentx):=20move=20GB300=20DSV4.1-Flash?= =?UTF-8?q?=20agg=20to=20the=2010-25=20SGLang=20nightly=20and=20drop=20the?= =?UTF-8?q?=20c1=20patch=20/=20=E5=B0=86=20GB300=20DSV4.1-Flash=20?= =?UTF-8?q?=E8=81=9A=E5=90=88=E8=BF=81=E7=A7=BB=E5=88=B0=2010-25=20SGLang?= =?UTF-8?q?=20nightly=20=E5=B9=B6=E7=A7=BB=E9=99=A4=20c1=20=E8=A1=A5?= =?UTF-8?q?=E4=B8=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Root cause: the 10-21 image lacked sglang#45450 and pinned an sgl-nvidia-mega that does not start on it, so TP4 c1 needed a startup patch, a plugin checkout and a waiver. Fix: the agg key moves to nightly-dev-cu13-20261025-65633129 (index digest sha256:069efa1d...) with the ai-dynamo 1.6.0 it ships; recipe identity is sglang 0.0.0.dev1+g656331295 / dynamo 1.6.0. That image contains #45450 and installs sgl-nvidia-mega 6fd7ac30 (3333e4cf plus Kimi K3 and the #45389 import-path fix; DSv4.1 code differs only in import paths). Removed setup_script from override_tp4_c1, the patch script and patch dir, and docs/waiver/4434.md. The c1 megakernel args, env and slot list, and the flashmla pins are unchanged; all 21 SGLANG_* gates, the c1 flags and the 42 slots resolve on the image. The changelog entry is rewritten for the new image and still lists the disagg key. Validation: GB300 runs of the four bound agg recipes at this head. 中文: 根因:10-21 镜像不含 sglang#45450,且其固定的 sgl-nvidia-mega 无法在其上启动, 因此 TP4 c1 需要启动补丁、插件检出与豁免说明。 修复:聚合配置迁移到 nightly-dev-cu13-20261025-65633129(index digest sha256:069efa1d...)及其自带的 ai-dynamo 1.6.0;配方 identity 改为 sglang 0.0.0.dev1+g656331295 / dynamo 1.6.0。该镜像包含 #45450,并安装 sgl-nvidia-mega 6fd7ac30(3333e4cf 加 Kimi K3 与 #45389 的 import 路径修复;DSv4.1 代码仅 import 路径不同)。移除 override_tp4_c1 的 setup_script、补丁脚本与补丁目录,以及 docs/waiver/4434.md。c1 megakernel 参数、环境变量、slot 列表与 flashmla 固定不变; 21 个 SGLANG_* 开关、c1 参数与 42 个 slot 在该镜像上均可解析。changelog 条目按新镜像 重写,仍包含分离式配置。 验证:在 GB300 上运行本 head 的四个绑定聚合配方。 --- .../configs/dsv41flash-sglang-patches.sh | 43 - .../sglang-pr45450.patch | 4936 ----------------- .../sglang/gb300-fp4/agentx/agg-variants.yaml | 5 +- inferencex-e2e/configs/nvidia-master.yaml | 4 +- inferencex-e2e/docs/waiver/4434.md | 42 - inferencex-e2e/perf-changelog.yaml | 4 +- 6 files changed, 6 insertions(+), 5028 deletions(-) delete mode 100755 inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh delete mode 100644 inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches/sglang-pr45450.patch delete mode 100644 inferencex-e2e/docs/waiver/4434.md diff --git a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh deleted file mode 100755 index 21cd34b24a..0000000000 --- a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh +++ /dev/null @@ -1,43 +0,0 @@ -#!/usr/bin/env bash -# sglang#45450 and sgl-nvidia-mega 3333e4cf for the October 21 nightly; see docs/waiver. -set -eo pipefail - -sglang_root=/sgl-workspace/sglang -mega_root=/sgl-workspace/sgl-nvidia-mega -mega_repo=https://github.com/sgl-project/sgl-nvidia-mega.git -mega_commit=3333e4cfac0f2b15603565d702b4c67538f1628f -patch_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/dsv41flash-sglang-patches" -patches=( - sglang-pr45450.patch -) - -origin=$(python3 -c 'import importlib.util; print(importlib.util.find_spec("sglang").origin)') -if [[ "$origin" != "$sglang_root/python/sglang/__init__.py" ]]; then - echo "sglang imports from $origin, not the editable checkout in $sglang_root" >&2 - exit 1 -fi -mega_origin=$(python3 -c 'import importlib.util; print(importlib.util.find_spec("sgl_nvidia_mega").origin)') -if [[ "$mega_origin" != "$mega_root/sgl_nvidia_mega/__init__.py" ]]; then - echo "sgl_nvidia_mega imports from $mega_origin, not the editable checkout in $mega_root" >&2 - exit 1 -fi - -# Workers sharing a node and container must not patch the tree concurrently. -exec 9<"$sglang_root" -flock 9 -cd / -for name in "${patches[@]}"; do - patch="$patch_dir/$name" - if git apply --directory="${sglang_root#/}" --reverse --check "$patch" 2>/dev/null; then - echo "SGLang patch $name: already applied" - else - git apply --directory="${sglang_root#/}" --verbose "$patch" - echo "SGLang patch $name: applied" - fi -done - -if [[ "$(git -C "$mega_root" rev-parse HEAD)" != "$mega_commit" ]]; then - git -C "$mega_root" fetch --quiet --depth 1 "$mega_repo" "$mega_commit" - git -C "$mega_root" checkout --quiet --force "$mega_commit" -fi -echo "sgl-nvidia-mega: $(git -C "$mega_root" rev-parse HEAD)" diff --git a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches/sglang-pr45450.patch b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches/sglang-pr45450.patch deleted file mode 100644 index 7c0880935e..0000000000 --- a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches/sglang-pr45450.patch +++ /dev/null @@ -1,4936 +0,0 @@ -diff --git a/python/sglang/kernels/ops/embeddings/engram_hash.py b/python/sglang/kernels/ops/embeddings/engram_hash.py -index deb58658f7..65a3d9e6f2 100644 ---- a/python/sglang/kernels/ops/embeddings/engram_hash.py -+++ b/python/sglang/kernels/ops/embeddings/engram_hash.py -@@ -28,12 +28,19 @@ def _engram_commit_history_kernel( - tokens_ptr, - slots_ptr, - commit_ptr, -+ live_ptr, -+ gate_ptr, - HISTORY_STRIDE: tl.constexpr, - HISTORY_WIDTH: tl.constexpr, - TOKEN_STRIDE: tl.constexpr, - BLOCK: tl.constexpr, -+ GATED: tl.constexpr, - ): - row = tl.program_id(0) -+ if GATED: -+ # Captured rows past the live batch, or a step the graph does not commit. -+ if (tl.load(live_ptr + row) == 0) | (tl.load(gate_ptr) == 0): -+ return - slot = tl.load(slots_ptr + row).to(tl.int64) - commit = tl.load(commit_ptr + row) - col = tl.arange(0, BLOCK) -@@ -60,8 +67,11 @@ def engram_commit_history( - verify_ids: torch.Tensor, - req_slots: torch.Tensor, - commit_lens: torch.Tensor, -+ live_rows: Optional[torch.Tensor] = None, -+ gate: Optional[torch.Tensor] = None, - ) -> None: -- """Update distinct live request slots with anchor + correct drafts, not bonus.""" -+ """Update distinct live request slots with anchor + correct drafts, not bonus. -+ Skips rows whose ``live_rows`` entry is 0, and all rows when ``gate[0]`` is 0.""" - bs = req_slots.numel() - width = history.shape[1] - if bs == 0 or width == 0: -@@ -73,10 +83,13 @@ def engram_commit_history( - verify_ids, - req_slots, - commit_lens, -+ live_rows if live_rows is not None else commit_lens, -+ gate if gate is not None else commit_lens, - HISTORY_STRIDE=history.stride(0), - HISTORY_WIDTH=width, - TOKEN_STRIDE=verify_ids.stride(0), - BLOCK=triton.next_power_of_2(width), -+ GATED=live_rows is not None, - num_warps=4, - ) - -diff --git a/python/sglang/kernels/ops/speculative/cache_locs.py b/python/sglang/kernels/ops/speculative/cache_locs.py -index a93975e392..cc11b56cb3 100644 ---- a/python/sglang/kernels/ops/speculative/cache_locs.py -+++ b/python/sglang/kernels/ops/speculative/cache_locs.py -@@ -627,6 +627,10 @@ def assign_extend_cache_locs_uniform( - PAGE_SIZE: tl.constexpr = 1, - num_v_pages=0, - num_swa_pages=0, -+ positions_out=None, -+ anchor_src=None, -+ anchor_out=None, -+ anchor_stride=0, - ): - """Uniform-length variant of assign_extend_cache_locs: every row extends - exactly draft_token_num tokens, so the end offset is start + -@@ -637,6 +641,8 @@ def assign_extend_cache_locs_uniform( - kv_start = tl.load(start_offset + pid) - token_pool = req_to_token + tl.load(req_pool_indices + pid) * pool_len - out_cache_ptr = out_cache_loc + pid * draft_token_num -+ if anchor_out is not None: -+ tl.store(anchor_out + pid * anchor_stride, tl.load(anchor_src + pid)) - - offs = tl.arange(0, BLOCK_SIZE) - num_loop = tl.cdiv(draft_token_num, BLOCK_SIZE) -@@ -645,6 +651,12 @@ def assign_extend_cache_locs_uniform( - mask = o < draft_token_num - data = tl.load(token_pool + kv_start + o, mask=mask) - tl.store(out_cache_ptr + o, data, mask=mask) -+ if positions_out is not None: -+ tl.store( -+ positions_out + pid * draft_token_num + o, -+ kv_start.to(tl.int64) + o, -+ mask=mask, -+ ) - if full_v2p is not None: - page = data // PAGE_SIZE - valid = mask & (data >= 0) & (page < num_v_pages) -@@ -675,6 +687,9 @@ def assign_extend_cache_locs_uniform_func( - full_out: Optional[torch.Tensor] = None, - swa_out: Optional[torch.Tensor] = None, - page_size: int = 1, -+ positions_out: Optional[torch.Tensor] = None, -+ anchor_src: Optional[torch.Tensor] = None, -+ anchor_out: Optional[torch.Tensor] = None, - ) -> torch.Tensor: - """assign_extend_cache_locs for the uniform case (all rows extend exactly - draft_token_num tokens, e.g. spec target-verify prep). Computes end -@@ -683,6 +698,8 @@ def assign_extend_cache_locs_uniform_func( - and SWA write windows in the same launch; the returned ids stay virtual. - Mapping tables and output buffers must be contiguous, with one output - per gathered token. Translation is rank-local (no DCP widening). -+ ``positions_out`` ([batch, draft_token_num] int64) gets start + column and -+ ``anchor_out[:, 0]`` gets ``anchor_src``, in the same launch. - """ - if full_v2p is not None: - assert full_out is not None and full_out.numel() == batch_size * draft_token_num -@@ -713,11 +730,22 @@ def assign_extend_cache_locs_uniform_func( - PAGE_SIZE=page_size, - num_v_pages=0 if full_v2p is None else full_v2p.numel(), - num_swa_pages=0 if swa_v2p is None else swa_v2p.numel(), -+ positions_out=positions_out, -+ anchor_src=anchor_src, -+ anchor_out=anchor_out, -+ anchor_stride=0 if anchor_out is None else anchor_out.stride(0), - ) - return out_cache_loc - - # NPU / CPU platforms: fall back to the end_offset-tensor path. - assert full_v2p is None, "fused write translation requires a Triton device" -+ if positions_out is not None: -+ positions_out.copy_( -+ start_offset.to(torch.int64).view(-1, 1) -+ + torch.arange(draft_token_num, device=start_offset.device) -+ ) -+ if anchor_out is not None: -+ anchor_out[:, 0].copy_(anchor_src.view(-1)) - return assign_extend_cache_locs_func( - req_pool_indices=req_pool_indices, - req_to_token=req_to_token, -diff --git a/python/sglang/kernels/ops/speculative/dspark/blockwise_rejection.py b/python/sglang/kernels/ops/speculative/dspark/blockwise_rejection.py -new file mode 100644 -index 0000000000..10c93570a9 ---- /dev/null -+++ b/python/sglang/kernels/ops/speculative/dspark/blockwise_rejection.py -@@ -0,0 +1,551 @@ -+"""Block-wise rejection sampling of a DSpark verify chain (SGLANG_OPT_DSV41_BLOCKWISE_REJECTION). -+ -+Classic chain verification only. It replaces the draft / target softmax writes and the -+single-CTA ``speculative_sampling_classic_kernel``: -+ -+1. per-vocab-block target / draft max and sum-exp (rows x 8,192-token blocks), no -+ probability tensors; -+2. a one-warp accept per request that reads only those stats plus the draft token's -+ logits: accept iff ``log p(x) > log u + log q(x)``, i.e. ``u * q < p`` as before; -+3. a block-parallel Gumbel-max resample of the rejected row's residual -+ ``max(p - q, 0)`` (or of ``p`` at the bonus row), reduced by a one-program insert. -+ -+The draws are counter-based: a request row's accept coins and its resample noise are -+functions of (server key, a device step counter, row, token). Every TP rank holds the -+same key, counter and logits, so ranks agree without a broadcast, and a CUDA graph -+replay advances the counter like an eager call. Distributions are those of the classic -+kernel; only the random stream differs. -+""" -+ -+from __future__ import annotations -+ -+from typing import Optional -+ -+import msgspec -+import torch -+import triton -+import triton.language as tl -+from triton.language.extra import libdevice -+ -+from sglang.kernels.ops.speculative.dspark.dispatch import inputs_on_cuda -+ -+# XORed into the server seed so the rejection draws differ from other samplers'. -+_REJECTION_NOISE_DOMAIN = 0x5B1E3C7A9D2F4E61 -+# Odd multiplier mixing the step counter into the per-step seed. -+_STEP_SEED_MULT = tl.constexpr(0x632BE59BD9B4E019) -+# Smallest positive fp32 value of tl.rand; coins stay in (0, 1). -+_TL_RAND_MIN = tl.constexpr(4.6566127342e-10) -+_STATS_BLOCK = 8192 -+_RESAMPLE_BLOCK = 1024 -+ -+ -+class RejectionNoise(msgspec.Struct, frozen=True): -+ """Key of the rejection draws, and a device step counter each call advances.""" -+ -+ key: int -+ counter: torch.Tensor -+ -+ -+def rejection_noise_key(random_seed: int) -> int: -+ return (int(random_seed) ^ _REJECTION_NOISE_DOMAIN) & 0x7FFFFFFFFFFFFFFF -+ -+ -+def make_rejection_noise(random_seed: int, device) -> RejectionNoise: -+ return RejectionNoise( -+ key=rejection_noise_key(random_seed), -+ counter=torch.zeros(1, dtype=torch.int64, device=device), -+ ) -+ -+ -+@triton.jit -+def _step_seed(key, counter_ptr): -+ return key + tl.load(counter_ptr) * _STEP_SEED_MULT -+ -+ -+@triton.jit -+def _rotl32(value, shift: tl.constexpr): -+ return (value << shift) | (value >> (32 - shift)) -+ -+ -+@triton.jit -+def _murmur3_mix(h, key): -+ key *= 0xCC9E2D51 -+ key = _rotl32(key, 15) -+ key *= 0x1B873593 -+ h ^= key -+ h = _rotl32(h, 13) -+ return h * 5 + 0xE6546B64 -+ -+ -+@triton.jit -+def _murmur3_uniform32(seed, pos, offset): -+ seed = seed.to(tl.int64) -+ pos = pos.to(tl.int64) -+ offset = offset.to(tl.uint32) -+ h = (seed ^ seed).to(tl.uint32) -+ h = _murmur3_mix(h, (seed & 0xFFFFFFFF).to(tl.uint32)) -+ h = _murmur3_mix(h, ((seed >> 32) & 0xFFFFFFFF).to(tl.uint32)) -+ h = _murmur3_mix(h, (pos & 0xFFFFFFFF).to(tl.uint32)) -+ h = _murmur3_mix(h, offset) -+ h ^= 16 -+ h ^= h >> 16 -+ h *= 0x85EBCA6B -+ h ^= h >> 13 -+ h *= 0xC2B2AE35 -+ h ^= h >> 16 -+ # Both 16-bit halves convert exactly: (h + 0.5) * 2**-32 keeps the u -> 0 tail. -+ hi16 = (h >> 16).to(tl.int32) -+ lo16 = (h & 0xFFFF).to(tl.int32) -+ return ( -+ hi16.to(tl.float32) * 1.52587890625e-05 -+ + (lo16.to(tl.float32) + 0.5) * 2.3283064365386963e-10 -+ ) -+ -+ -+@triton.jit -+def _log1p_neg_stable(value): -+ # log(1 - value): series below 0.25 (abs error < 6e-7), direct above. -+ polynomial = 1.0 / 8.0 -+ polynomial = 1.0 / 7.0 + value * polynomial -+ polynomial = 1.0 / 6.0 + value * polynomial -+ polynomial = 1.0 / 5.0 + value * polynomial -+ polynomial = 1.0 / 4.0 + value * polynomial -+ polynomial = 1.0 / 3.0 + value * polynomial -+ polynomial = 1.0 / 2.0 + value * polynomial -+ polynomial = 1.0 + value * polynomial -+ series = -value * polynomial -+ direct = tl.log(tl.maximum(1.0 - value, 5.960464477539063e-08)) -+ return tl.where(value < 0.25, series, direct) -+ -+ -+@triton.jit -+def _global_lse( -+ max_ptr, sumexp_ptr, row, NUM_BLOCKS: tl.constexpr, PADDED: tl.constexpr -+): -+ blocks = tl.arange(0, PADDED) -+ mask = blocks < NUM_BLOCKS -+ maxes = tl.load(max_ptr + row * NUM_BLOCKS + blocks, mask=mask, other=float("-inf")) -+ sumexps = tl.load(sumexp_ptr + row * NUM_BLOCKS + blocks, mask=mask, other=0.0) -+ global_max = tl.max(maxes, axis=0) -+ return global_max + tl.log(tl.sum(sumexps * tl.exp(maxes - global_max))) -+ -+ -+@triton.jit -+def _stats_kernel( -+ t_max_ptr, -+ t_sumexp_ptr, -+ d_max_ptr, -+ d_sumexp_ptr, -+ target_logits_ptr, -+ target_stride, -+ draft_logits_ptr, -+ draft_stride_0, -+ draft_stride_1, -+ target_temp_ptr, -+ draft_temp_ptr, -+ target_vocab, -+ draft_vocab, -+ STRIDE: tl.constexpr, -+ NUM_BLOCKS: tl.constexpr, -+ BLOCK: tl.constexpr, -+ HAS_DRAFT_LOGITS: tl.constexpr, -+): -+ row = tl.program_id(0).to(tl.int64) -+ req = row // STRIDE -+ step = row % STRIDE -+ if step == STRIDE - 1: -+ # Bonus row: its resample reads raw logits, no stats. -+ return -+ block_idx = tl.program_id(1) -+ offs = block_idx * BLOCK + tl.arange(0, BLOCK) -+ t_temp = tl.load(target_temp_ptr + req).to(tl.float32) -+ t = ( -+ tl.load( -+ target_logits_ptr + row * target_stride + offs, -+ mask=offs < target_vocab, -+ other=float("-inf"), -+ ).to(tl.float32) -+ / t_temp -+ ) -+ t_max = tl.max(t, axis=0) -+ tl.store(t_max_ptr + row * NUM_BLOCKS + block_idx, t_max) -+ tl.store( -+ t_sumexp_ptr + row * NUM_BLOCKS + block_idx, -+ tl.where(t_max > float("-inf"), tl.sum(tl.exp(t - t_max)), 0.0), -+ ) -+ if HAS_DRAFT_LOGITS: -+ d_temp = tl.load(draft_temp_ptr + req).to(tl.float32) -+ d = ( -+ tl.load( -+ draft_logits_ptr + req * draft_stride_0 + step * draft_stride_1 + offs, -+ mask=offs < draft_vocab, -+ other=float("-inf"), -+ ).to(tl.float32) -+ / d_temp -+ ) -+ d_max = tl.max(d, axis=0) -+ tl.store(d_max_ptr + row * NUM_BLOCKS + block_idx, d_max) -+ tl.store( -+ d_sumexp_ptr + row * NUM_BLOCKS + block_idx, -+ tl.where(d_max > float("-inf"), tl.sum(tl.exp(d - d_max)), 0.0), -+ ) -+ -+ -+@triton.jit -+def _rejection_kernel( -+ correct_len_ptr, -+ raw_len_ptr, -+ trim_ptr, -+ rej_lse_ptr, -+ candidates_ptr, -+ candidates_stride, -+ verify_lens_ptr, -+ t_max_ptr, -+ t_sumexp_ptr, -+ d_max_ptr, -+ d_sumexp_ptr, -+ target_logits_ptr, -+ target_stride, -+ draft_logits_ptr, -+ draft_stride_0, -+ draft_stride_1, -+ target_temp_ptr, -+ draft_temp_ptr, -+ target_vocab, -+ draft_vocab, -+ bs, -+ key, -+ counter_ptr, -+ STRIDE: tl.constexpr, -+ NUM_BLOCKS: tl.constexpr, -+ PADDED_BLOCKS: tl.constexpr, -+ HAS_DRAFT_LOGITS: tl.constexpr, -+ HAS_CUTOFF: tl.constexpr, -+): -+ req = tl.program_id(0).to(tl.int64) -+ seed = _step_seed(key, counter_ptr) -+ t_temp = tl.load(target_temp_ptr + req).to(tl.float32) -+ d_temp = 1.0 -+ if HAS_DRAFT_LOGITS: -+ d_temp = tl.load(draft_temp_ptr + req).to(tl.float32) -+ accepted = tl.zeros((), tl.int32) -+ verifying = True -+ for i in range(STRIDE - 1): -+ if verifying: -+ row = req * STRIDE + i -+ token = tl.load(candidates_ptr + req * candidates_stride + i + 1).to( -+ tl.int64 -+ ) -+ valid = (token >= 0) & (token < target_vocab) -+ token = tl.minimum(tl.maximum(token, 0), target_vocab - 1) -+ t_lse = _global_lse(t_max_ptr, t_sumexp_ptr, row, NUM_BLOCKS, PADDED_BLOCKS) -+ log_p = ( -+ tl.load(target_logits_ptr + row * target_stride + token).to(tl.float32) -+ / t_temp -+ - t_lse -+ ) -+ log_q = 0.0 -+ if HAS_DRAFT_LOGITS: -+ d_lse = _global_lse( -+ d_max_ptr, d_sumexp_ptr, row, NUM_BLOCKS, PADDED_BLOCKS -+ ) -+ log_q = ( -+ tl.load( -+ draft_logits_ptr -+ + req * draft_stride_0 -+ + i * draft_stride_1 -+ + token, -+ mask=token < draft_vocab, -+ other=float("-inf"), -+ ).to(tl.float32) -+ / d_temp -+ - d_lse -+ ) -+ u = tl.maximum(tl.rand(seed, (req * STRIDE + i).to(tl.int32)), _TL_RAND_MIN) -+ # A proposal must have positive draft probability (classic kernel's guard). -+ ok = valid & (log_q > float("-inf")) & (log_p > tl.log(u) + log_q) -+ verifying = ok -+ accepted += ok.to(tl.int32) -+ tl.store(raw_len_ptr + req, accepted) -+ capped = accepted -+ if HAS_CUTOFF: -+ cap = tl.load(verify_lens_ptr + req).to(tl.int32) - 1 -+ capped = tl.minimum(accepted, cap) -+ tl.store(correct_len_ptr + req, capped) -+ tl.store(trim_ptr + req, accepted - capped) -+ t_lse_rej = 0.0 -+ d_lse_rej = 0.0 -+ if accepted < STRIDE - 1: -+ rej_row = req * STRIDE + accepted -+ t_lse_rej = _global_lse( -+ t_max_ptr, t_sumexp_ptr, rej_row, NUM_BLOCKS, PADDED_BLOCKS -+ ) -+ if HAS_DRAFT_LOGITS: -+ d_lse_rej = _global_lse( -+ d_max_ptr, d_sumexp_ptr, rej_row, NUM_BLOCKS, PADDED_BLOCKS -+ ) -+ tl.store(rej_lse_ptr + req, t_lse_rej) -+ tl.store(rej_lse_ptr + bs + req, d_lse_rej) -+ -+ -+@triton.jit -+def _resample_kernel( -+ res_max_ptr, -+ res_arg_ptr, -+ raw_len_ptr, -+ rej_lse_ptr, -+ candidates_ptr, -+ candidates_stride, -+ target_logits_ptr, -+ target_stride, -+ draft_logits_ptr, -+ draft_stride_0, -+ draft_stride_1, -+ target_temp_ptr, -+ draft_temp_ptr, -+ target_vocab, -+ draft_vocab, -+ bs, -+ key, -+ counter_ptr, -+ STRIDE: tl.constexpr, -+ NUM_BLOCKS: tl.constexpr, -+ BLOCK: tl.constexpr, -+ HAS_DRAFT_LOGITS: tl.constexpr, -+): -+ req = tl.program_id(0).to(tl.int64) -+ block_idx = tl.program_id(1) -+ seed = _step_seed(key, counter_ptr) -+ r = tl.load(raw_len_ptr + req).to(tl.int64) -+ row = req * STRIDE + r -+ is_bonus = r == STRIDE - 1 -+ offs = block_idx * BLOCK + tl.arange(0, BLOCK) -+ mask = offs < target_vocab -+ t_temp = tl.load(target_temp_ptr + req).to(tl.float32) -+ t = ( -+ tl.load( -+ target_logits_ptr + row * target_stride + offs, -+ mask=mask, -+ other=float("-inf"), -+ ).to(tl.float32) -+ / t_temp -+ ) -+ if is_bonus: -+ residual = t -+ else: -+ rejected = tl.load(candidates_ptr + req * candidates_stride + r + 1) -+ if HAS_DRAFT_LOGITS: -+ d_temp = tl.load(draft_temp_ptr + req).to(tl.float32) -+ log_p = t - tl.load(rej_lse_ptr + req) -+ log_q = tl.load( -+ draft_logits_ptr + req * draft_stride_0 + r * draft_stride_1 + offs, -+ mask=offs < draft_vocab, -+ other=float("-inf"), -+ ).to(tl.float32) / d_temp - tl.load(rej_lse_ptr + bs + req) -+ # log max(p - q, 0) = log p + log1p(-q / p), -inf where q >= p. -+ ratio = tl.exp(log_q - log_p) -+ residual = tl.where( -+ ratio < 1.0, log_p + libdevice.log1p(-ratio), float("-inf") -+ ).to(tl.float32) -+ else: -+ # One-hot draft: the residual is p without the rejected token. -+ residual = tl.where(offs != rejected, t, float("-inf")) -+ u = _murmur3_uniform32(seed, req, offs) -+ noised = tl.where(mask, residual - tl.log(-_log1p_neg_stable(u)), float("-inf")) -+ value, idx = tl.max(noised, axis=0, return_indices=True) -+ tl.store(res_max_ptr + req * NUM_BLOCKS + block_idx, value) -+ tl.store(res_arg_ptr + req * NUM_BLOCKS + block_idx, block_idx * BLOCK + idx) -+ -+ -+@triton.jit -+def _insert_kernel( -+ bonus_ptr, -+ correct_len_ptr, -+ raw_len_ptr, -+ res_max_ptr, -+ res_arg_ptr, -+ candidates_ptr, -+ candidates_stride, -+ counter_ptr, -+ NUM_BLOCKS: tl.constexpr, -+ PADDED_BLOCKS: tl.constexpr, -+): -+ req = tl.program_id(0).to(tl.int64) -+ capped = tl.load(correct_len_ptr + req) -+ raw = tl.load(raw_len_ptr + req) -+ if capped < raw: -+ # Capped by the verify budget: the bonus is the accepted draft after the cap. -+ bonus = tl.load(candidates_ptr + req * candidates_stride + capped + 1).to( -+ tl.int64 -+ ) -+ else: -+ blocks = tl.arange(0, PADDED_BLOCKS) -+ local_max = tl.load( -+ res_max_ptr + req * NUM_BLOCKS + blocks, -+ mask=blocks < NUM_BLOCKS, -+ other=float("-inf"), -+ ) -+ # NaN would make argmax land in the padded tail. -+ local_max = tl.where(local_max != local_max, float("-inf"), local_max) -+ best = tl.argmax(local_max, axis=0) -+ bonus = tl.load(res_arg_ptr + req * NUM_BLOCKS + best) -+ tl.store(bonus_ptr + req, bonus) -+ if req == 0: -+ # The other kernels of this call have read the counter (stream order). -+ tl.store(counter_ptr, tl.load(counter_ptr) + 1) -+ -+ -+class BlockwiseRejection: -+ @classmethod -+ def execute( -+ cls, *args, **kwargs -+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: -+ if inputs_on_cuda(*args, **kwargs): -+ return blockwise_rejection_triton(*args, **kwargs) -+ return blockwise_rejection_torch(*args, **kwargs) -+ -+ -+def blockwise_rejection_triton( -+ *, -+ candidates: torch.Tensor, -+ target_logits: torch.Tensor, -+ draft_logits: Optional[torch.Tensor], -+ target_temperatures: torch.Tensor, -+ draft_temperatures: torch.Tensor, -+ noise: RejectionNoise, -+ cutoff_verify_lens: Optional[torch.Tensor] = None, -+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: -+ """``draft_logits`` is pre-temperature, or None for a one-hot draft. Returns -+ (correct_len int32, bonus int64, cap_trim_lens int32), each [bs].""" -+ bs, stride = candidates.shape -+ target_vocab = target_logits.shape[-1] -+ assert target_logits.stride(-1) == 1 and target_logits.shape[0] == bs * stride -+ has_draft = draft_logits is not None -+ draft_vocab = draft_logits.shape[-1] if has_draft else target_vocab -+ if has_draft: -+ assert draft_logits.stride(-1) == 1 and draft_logits.shape[1] >= stride - 1 -+ device = candidates.device -+ target_temperatures = target_temperatures.reshape(-1).contiguous() -+ draft_temperatures = draft_temperatures.reshape(-1).contiguous() -+ num_blocks = triton.cdiv(max(target_vocab, draft_vocab), _STATS_BLOCK) -+ padded_blocks = triton.next_power_of_2(num_blocks) -+ stats = torch.empty( -+ (4, bs * stride, num_blocks), dtype=torch.float32, device=device -+ ) -+ lens = torch.empty((3, bs), dtype=torch.int32, device=device) -+ rej_lse = torch.empty((2, bs), dtype=torch.float32, device=device) -+ res_blocks = triton.cdiv(target_vocab, _RESAMPLE_BLOCK) -+ res_max = torch.empty((bs, res_blocks), dtype=torch.float32, device=device) -+ res_arg = torch.empty((bs, res_blocks), dtype=torch.int64, device=device) -+ bonus = torch.empty((bs,), dtype=torch.int64, device=device) -+ correct_len, raw_len, trim = lens[0], lens[1], lens[2] -+ t_max, t_sumexp, d_max, d_sumexp = stats[0], stats[1], stats[2], stats[3] -+ d_ptr = draft_logits if has_draft else target_logits -+ d_s0 = draft_logits.stride(0) if has_draft else 0 -+ d_s1 = draft_logits.stride(1) if has_draft else 0 -+ _stats_kernel[(bs * stride, num_blocks)]( -+ t_max, t_sumexp, d_max, d_sumexp, -+ target_logits, target_logits.stride(0), -+ d_ptr, d_s0, d_s1, -+ target_temperatures, draft_temperatures, -+ target_vocab, draft_vocab, -+ STRIDE=stride, NUM_BLOCKS=num_blocks, BLOCK=_STATS_BLOCK, -+ HAS_DRAFT_LOGITS=has_draft, -+ ) # fmt: skip -+ has_cutoff = cutoff_verify_lens is not None -+ verify_lens = ( -+ cutoff_verify_lens.to(device=device).contiguous() if has_cutoff else correct_len -+ ) -+ _rejection_kernel[(bs,)]( -+ correct_len, raw_len, trim, rej_lse, -+ candidates, candidates.stride(0), verify_lens, -+ t_max, t_sumexp, d_max, d_sumexp, -+ target_logits, target_logits.stride(0), -+ d_ptr, d_s0, d_s1, -+ target_temperatures, draft_temperatures, -+ target_vocab, draft_vocab, bs, -+ noise.key, noise.counter, -+ STRIDE=stride, NUM_BLOCKS=num_blocks, PADDED_BLOCKS=padded_blocks, -+ HAS_DRAFT_LOGITS=has_draft, HAS_CUTOFF=has_cutoff, -+ num_warps=1, -+ ) # fmt: skip -+ _resample_kernel[(bs, res_blocks)]( -+ res_max, res_arg, raw_len, rej_lse, -+ candidates, candidates.stride(0), -+ target_logits, target_logits.stride(0), -+ d_ptr, d_s0, d_s1, -+ target_temperatures, draft_temperatures, -+ target_vocab, draft_vocab, bs, -+ noise.key, noise.counter, -+ STRIDE=stride, NUM_BLOCKS=res_blocks, BLOCK=_RESAMPLE_BLOCK, -+ HAS_DRAFT_LOGITS=has_draft, -+ ) # fmt: skip -+ _insert_kernel[(bs,)]( -+ bonus, correct_len, raw_len, res_max, res_arg, -+ candidates, candidates.stride(0), noise.counter, -+ NUM_BLOCKS=res_blocks, PADDED_BLOCKS=triton.next_power_of_2(res_blocks), -+ num_warps=1, -+ ) # fmt: skip -+ return correct_len, bonus, trim -+ -+ -+def blockwise_rejection_torch( -+ *, -+ candidates: torch.Tensor, -+ target_logits: torch.Tensor, -+ draft_logits: Optional[torch.Tensor], -+ target_temperatures: torch.Tensor, -+ draft_temperatures: torch.Tensor, -+ noise: RejectionNoise, -+ cutoff_verify_lens: Optional[torch.Tensor] = None, -+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: -+ """Reference with the same math; draws from a generator seeded by (key, counter).""" -+ bs, stride = candidates.shape -+ gamma = stride - 1 -+ vocab = target_logits.shape[-1] -+ gen = torch.Generator(device=candidates.device) -+ gen.manual_seed((noise.key + int(noise.counter.item()) * 1_000_003) % (2**63)) -+ t_temp = target_temperatures.reshape(bs, 1, 1).float() -+ log_p = torch.log_softmax( -+ target_logits.float().view(bs, stride, vocab) / t_temp, -1 -+ ) -+ if draft_logits is not None: -+ d_temp = draft_temperatures.reshape(bs, 1, 1).float() -+ d = draft_logits[:bs, :gamma].float() / d_temp -+ log_q = torch.full((bs, gamma, vocab), float("-inf"), device=d.device) -+ log_q[..., : d.shape[-1]] = torch.log_softmax(d, -1)[..., :vocab] -+ else: -+ log_q = torch.full((bs, gamma, vocab), float("-inf"), device=log_p.device) -+ log_q.scatter_(-1, candidates[:, 1:].unsqueeze(-1), 0.0) -+ coins = torch.rand((bs, gamma), generator=gen, device=candidates.device) -+ gumbel = -torch.log( -+ -torch.log(torch.rand((bs, vocab), generator=gen, device=candidates.device)) -+ ) -+ tokens = candidates[:, 1:].long() -+ lp = log_p[:, :gamma].gather(-1, tokens.unsqueeze(-1)).squeeze(-1) -+ lq = log_q.gather(-1, tokens.unsqueeze(-1)).squeeze(-1) -+ ok = (lq > float("-inf")) & (lp > torch.log(coins.clamp_min(4.6566127342e-10)) + lq) -+ raw = torch.cumprod(ok.int(), dim=-1).sum(-1).int() -+ rows = torch.arange(bs, device=candidates.device) -+ lp_rej = log_p[rows, raw.long()] -+ lq_rej = torch.cat([log_q, log_q[:, :1]], 1)[rows, raw.long()] -+ residual = torch.where( -+ raw.unsqueeze(-1) == gamma, -+ lp_rej, -+ torch.where( -+ lq_rej < lp_rej, -+ lp_rej + torch.log1p(-torch.exp(lq_rej - lp_rej)), -+ float("-inf"), -+ ), -+ ) -+ bonus = (residual + gumbel).argmax(-1) -+ if cutoff_verify_lens is not None: -+ capped = torch.minimum(raw, cutoff_verify_lens.to(raw.device).int() - 1) -+ else: -+ capped = raw -+ capped_bonus = candidates.gather( -+ 1, (capped.long() + 1).clamp_max(gamma).unsqueeze(-1) -+ ).squeeze(-1) -+ bonus = torch.where(capped < raw, capped_bonus, bonus) -+ noise.counter.add_(1) -+ return capped, bonus.long(), raw - capped -diff --git a/python/sglang/kernels/ops/speculative/dspark/simulated_bonus.py b/python/sglang/kernels/ops/speculative/dspark/simulated_bonus.py -index ec1e073db1..49140711ae 100644 ---- a/python/sglang/kernels/ops/speculative/dspark/simulated_bonus.py -+++ b/python/sglang/kernels/ops/speculative/dspark/simulated_bonus.py -@@ -66,6 +66,7 @@ def _simulated_bonus_row_partial_kernel( - logits_stride, - temperatures_ptr, - correct_len_ptr, -+ correct_len_stride, - seed_ptr, - part_val_ptr, - part_idx_ptr, -@@ -76,7 +77,7 @@ def _simulated_bonus_row_partial_kernel( - ): - req = tl.program_id(0) - split = tl.program_id(1) -- row = req * ROWS + tl.load(correct_len_ptr + req) -+ row = req * ROWS + tl.load(correct_len_ptr + req * correct_len_stride) - t = tl.load(temperatures_ptr + req).to(tl.float32) - offs = split * BLOCK + tl.arange(0, BLOCK) - mask = offs < vocab -@@ -125,7 +126,34 @@ def simulated_bonus_sample_graph( - """Graph-safe variant of simulated_bonus_sample: seed ([1] int) and per-request - temperatures ([bs] float; <= 0 means argmax) are read from device buffers, and - only the row at ``correct_len`` is sampled. [bs] int64.""" -+ part_val, part_idx = simulated_bonus_partials_graph( -+ target_logits=target_logits, -+ correct_len=correct_len, -+ temperatures=temperatures, -+ seed=seed, -+ bs=bs, -+ rows_per_request=rows_per_request, -+ ) -+ out = torch.empty((bs,), dtype=torch.int64, device=target_logits.device) -+ _simulated_bonus_row_select_kernel[(bs,)]( -+ part_val, part_idx, out, target_logits.shape[1], NSPLIT=part_val.shape[1] -+ ) -+ return out -+ -+ -+def simulated_bonus_partials_graph( -+ *, -+ target_logits: torch.Tensor, -+ correct_len: torch.Tensor, -+ temperatures: torch.Tensor, -+ seed: torch.Tensor, -+ bs: int, -+ rows_per_request: int, -+) -> tuple[torch.Tensor, torch.Tensor]: -+ """simulated_bonus_sample_graph's per-split (value, index) maxima, [bs, NSPLIT], -+ reduced by ``simulated_bonus_select_partials``. ``correct_len`` may be stride-0.""" - assert target_logits.stride(1) == 1 -+ assert correct_len.dim() == 1 and correct_len.shape[0] == bs - device = target_logits.device - vocab = target_logits.shape[1] - block = 4096 -@@ -136,7 +164,8 @@ def simulated_bonus_sample_graph( - target_logits, - target_logits.stride(0), - temperatures, -- correct_len.contiguous(), -+ correct_len, -+ correct_len.stride(0), - seed, - part_val, - part_idx, -@@ -146,11 +175,17 @@ def simulated_bonus_sample_graph( - BLOCK=block, - num_warps=8, - ) -- out = torch.empty((bs,), dtype=torch.int64, device=device) -- _simulated_bonus_row_select_kernel[(bs,)]( -- part_val, part_idx, out, vocab, NSPLIT=nsplit -- ) -- return out -+ return part_val, part_idx -+ -+ -+def simulated_bonus_select_partials( -+ *, part_val: torch.Tensor, part_idx: torch.Tensor, vocab: int -+) -> torch.Tensor: -+ """Torch reference of _simulated_bonus_row_select_kernel: the largest value, -+ ties to the lowest index. [bs] int64.""" -+ top = part_val.max(dim=1, keepdim=True).values -+ sentinel = torch.full_like(part_idx, vocab) -+ return torch.where(part_val == top, part_idx, sentinel).min(dim=1).values.long() - - - def simulated_bonus_sample( -diff --git a/python/sglang/kernels/ops/speculative/dspark/stage_commit.py b/python/sglang/kernels/ops/speculative/dspark/stage_commit.py -new file mode 100644 -index 0000000000..cf470847f6 ---- /dev/null -+++ b/python/sglang/kernels/ops/speculative/dspark/stage_commit.py -@@ -0,0 +1,73 @@ -+"""The deferred context-KV commit's staging in one launch: the verify rows' write -+locations, positions and (with a ring) state slots, and the gated commit lengths -+with zeros past the staged requests.""" -+ -+from typing import Optional -+ -+import torch -+import triton -+import triton.language as tl -+ -+ -+@triton.jit -+def _stage_commit_kernel( -+ loc_src_ptr, -+ loc_dst_ptr, -+ pos_src_ptr, -+ pos_dst_ptr, -+ slot_src_ptr, -+ slot_dst_ptr, -+ lens_src_ptr, -+ lens_dst_ptr, -+ rows, -+ bs, -+ max_bs, -+ HAS_SLOT: tl.constexpr, -+ ROWS_BLOCK: tl.constexpr, -+ LENS_BLOCK: tl.constexpr, -+): -+ r = tl.arange(0, ROWS_BLOCK) -+ m = r < rows -+ tl.store(loc_dst_ptr + r, tl.load(loc_src_ptr + r, mask=m), mask=m) -+ tl.store(pos_dst_ptr + r, tl.load(pos_src_ptr + r, mask=m), mask=m) -+ if HAS_SLOT: -+ tl.store(slot_dst_ptr + r, tl.load(slot_src_ptr + r, mask=m), mask=m) -+ q = tl.arange(0, LENS_BLOCK) -+ lens = tl.load(lens_src_ptr + q, mask=q < bs, other=0) -+ tl.store(lens_dst_ptr + q, lens, mask=q < max_bs) -+ -+ -+def stage_commit( -+ *, -+ cache_loc_dst: torch.Tensor, -+ positions_dst: torch.Tensor, -+ commit_lens_dst: torch.Tensor, -+ state_slot_dst: Optional[torch.Tensor], -+ cache_loc: torch.Tensor, -+ positions: torch.Tensor, -+ commit_lens: torch.Tensor, -+ state_slot: Optional[torch.Tensor], -+ rows: int, -+) -> None: -+ """``cache_loc_dst[:rows] = cache_loc[:rows]``, likewise positions / state slots, -+ ``commit_lens_dst[:bs] = commit_lens`` and ``commit_lens_dst[bs:] = 0``.""" -+ assert cache_loc.is_contiguous() and positions.is_contiguous() -+ assert commit_lens.is_contiguous() -+ assert (state_slot is None) == (state_slot_dst is None) -+ bs, max_bs = commit_lens.shape[0], commit_lens_dst.shape[0] -+ _stage_commit_kernel[(1,)]( -+ cache_loc, -+ cache_loc_dst, -+ positions, -+ positions_dst, -+ state_slot if state_slot is not None else cache_loc, -+ state_slot_dst if state_slot_dst is not None else cache_loc_dst, -+ commit_lens, -+ commit_lens_dst, -+ rows, -+ bs, -+ max_bs, -+ HAS_SLOT=state_slot is not None, -+ ROWS_BLOCK=triton.next_power_of_2(max(rows, 1)), -+ LENS_BLOCK=triton.next_power_of_2(max_bs), -+ ) -diff --git a/python/sglang/kernels/ops/speculative/dspark/static_accept_tail.py b/python/sglang/kernels/ops/speculative/dspark/static_accept_tail.py -new file mode 100644 -index 0000000000..416b309657 ---- /dev/null -+++ b/python/sglang/kernels/ops/speculative/dspark/static_accept_tail.py -@@ -0,0 +1,247 @@ -+"""DSpark static greedy verify: the accept and its bookkeeping in one launch -+(SGLANG_DSPARK_FUSED_ACCEPT_TAIL), one program per request row. -+ -+Per row, from the target's argmax ids: the leading draft matches and the bonus -+(AcceptGreedy; ``bonus_in`` replaces the bonus, ``bonus_parts`` replaces it with the -+in-graph simulated bonus's per-split maxima reduced here), -+the simulated correct length override (build_accept_outs), commit / new seq lens and -+a zero cap trim (FinalizeAcceptLens), the output tokens (BuildOutTokens), and the -+gated commit lengths the static epilogue's draft-KV commit reads. Every output equals -+the separate ops' bit for bit. With a simulated length and a supplied bonus the argmax ids -+are not read (``target_predict`` may be None). -+""" -+ -+from __future__ import annotations -+ -+from typing import Optional -+ -+import torch -+import triton -+import triton.language as tl -+ -+from sglang.kernels.ops.speculative.dspark.dispatch import inputs_on_cuda -+from sglang.kernels.ops.speculative.dspark.simulated_bonus import ( -+ simulated_bonus_select_partials, -+) -+ -+ -+@triton.jit -+def _static_accept_tail_kernel( -+ candidates_ptr, -+ target_ptr, -+ seq_lens_ptr, -+ verify_lens_ptr, -+ gate_ptr, -+ sim_ptr, -+ bonus_in_ptr, -+ part_val_ptr, -+ part_idx_ptr, -+ correct_out_ptr, -+ bonus_out_ptr, -+ cap_trim_out_ptr, -+ commit_out_ptr, -+ new_seq_out_ptr, -+ out_tokens_ptr, -+ gated_out_ptr, -+ cand_stride, -+ out_tokens_stride, -+ vocab, -+ T: tl.constexpr, -+ BLOCK_T: tl.constexpr, -+ NSPLIT: tl.constexpr, -+ HAS_SIM: tl.constexpr, -+ HAS_BONUS_IN: tl.constexpr, -+ HAS_PARTS: tl.constexpr, -+ NEED_TARGET: tl.constexpr, -+ HAS_GATED: tl.constexpr, -+): -+ row = tl.program_id(0).to(tl.int64) -+ offs = tl.arange(0, BLOCK_T) -+ in_t = offs < T -+ gamma = T - 1 -+ in_draft = offs < gamma -+ drafts = tl.load( -+ candidates_ptr + row * cand_stride + 1 + offs, mask=in_draft, other=-1 -+ ) -+ if NEED_TARGET: -+ targets = tl.load(target_ptr + row * T + offs, mask=in_draft, other=-2) -+ eq = (drafts == targets) & in_draft -+ num_correct = tl.min(tl.where(eq, BLOCK_T, offs), 0) -+ if HAS_PARTS: -+ # _simulated_bonus_row_select_kernel's reduction. -+ s = tl.arange(0, NSPLIT) -+ val = tl.load(part_val_ptr + row * NSPLIT + s) -+ idx = tl.load(part_idx_ptr + row * NSPLIT + s) -+ top = tl.max(val, axis=0) -+ bonus = tl.min(tl.where(val == top, idx, vocab), axis=0).to(tl.int64) -+ elif HAS_BONUS_IN: -+ bonus = tl.load(bonus_in_ptr + row).to(tl.int64) -+ else: -+ bonus = tl.load(target_ptr + row * T + num_correct).to(tl.int64) -+ if HAS_SIM: -+ correct = tl.load(sim_ptr).to(tl.int32) -+ else: -+ correct = num_correct.to(tl.int32) -+ commit = correct + 1 -+ new_seq = tl.load(seq_lens_ptr + row) + commit -+ tl.store(correct_out_ptr + row, correct) -+ tl.store(bonus_out_ptr + row, bonus) -+ tl.store(cap_trim_out_ptr + row, 0) -+ tl.store(commit_out_ptr + row, commit) -+ tl.store(new_seq_out_ptr + row, new_seq) -+ token = tl.where(offs == correct, bonus, tl.where(in_draft, drafts.to(tl.int64), 0)) -+ tl.store(out_tokens_ptr + row * out_tokens_stride + offs, token, mask=in_t) -+ if HAS_GATED: -+ verify_len = tl.load(verify_lens_ptr + row) -+ gate = tl.load(gate_ptr) -+ gated = tl.minimum(commit, verify_len.to(tl.int32)) * gate -+ tl.store(gated_out_ptr + row, gated) -+ -+ -+def static_accept_tail( -+ *, -+ candidates: torch.Tensor, -+ target_predict: Optional[torch.Tensor], -+ seq_lens: torch.Tensor, -+ verify_lens: torch.Tensor, -+ gate: torch.Tensor, -+ correct_len_out: torch.Tensor, -+ bonus_out: torch.Tensor, -+ cap_trim_lens_out: torch.Tensor, -+ commit_lens_out: torch.Tensor, -+ new_seq_lens_out: torch.Tensor, -+ out_tokens_out: torch.Tensor, -+ simulated_correct_len: Optional[torch.Tensor] = None, -+ bonus_in: Optional[torch.Tensor] = None, -+ bonus_parts: Optional[tuple[torch.Tensor, torch.Tensor, int]] = None, -+ gated_commit_lens_out: Optional[torch.Tensor] = None, -+) -> None: -+ """``candidates`` [bs, T] (anchor + drafts), ``target_predict`` [bs * T] argmax ids, -+ ``bonus_parts`` (part_val [bs, NSPLIT], part_idx, vocab); outputs go to rows [:bs].""" -+ assert bonus_in is None or bonus_parts is None -+ assert target_predict is not None or ( -+ simulated_correct_len is not None -+ and (bonus_in is not None or bonus_parts is not None) -+ ) -+ fn = ( -+ _static_accept_tail_triton -+ if inputs_on_cuda(candidates) -+ else static_accept_tail_torch -+ ) -+ fn( -+ candidates=candidates, -+ target_predict=target_predict, -+ seq_lens=seq_lens, -+ verify_lens=verify_lens, -+ gate=gate, -+ correct_len_out=correct_len_out, -+ bonus_out=bonus_out, -+ cap_trim_lens_out=cap_trim_lens_out, -+ commit_lens_out=commit_lens_out, -+ new_seq_lens_out=new_seq_lens_out, -+ out_tokens_out=out_tokens_out, -+ simulated_correct_len=simulated_correct_len, -+ bonus_in=bonus_in, -+ bonus_parts=bonus_parts, -+ gated_commit_lens_out=gated_commit_lens_out, -+ ) -+ -+ -+def _static_accept_tail_triton(**kw) -> None: -+ candidates = kw["candidates"] -+ bs, T = candidates.shape -+ assert candidates.stride(1) == 1 and kw["out_tokens_out"].stride(1) == 1 -+ dummy = kw["seq_lens"] -+ sim, bonus_in, parts, gated = ( -+ kw["simulated_correct_len"], -+ kw["bonus_in"], -+ kw["bonus_parts"], -+ kw["gated_commit_lens_out"], -+ ) -+ target = kw["target_predict"] -+ _static_accept_tail_kernel[(bs,)]( -+ candidates, -+ target if target is not None else dummy, -+ kw["seq_lens"], -+ kw["verify_lens"], -+ kw["gate"], -+ sim if sim is not None else dummy, -+ bonus_in if bonus_in is not None else dummy, -+ parts[0] if parts is not None else dummy, -+ parts[1] if parts is not None else dummy, -+ kw["correct_len_out"], -+ kw["bonus_out"], -+ kw["cap_trim_lens_out"], -+ kw["commit_lens_out"], -+ kw["new_seq_lens_out"], -+ kw["out_tokens_out"], -+ gated if gated is not None else dummy, -+ candidates.stride(0), -+ kw["out_tokens_out"].stride(0), -+ parts[2] if parts is not None else 0, -+ T=T, -+ BLOCK_T=triton.next_power_of_2(T), -+ NSPLIT=parts[0].shape[1] if parts is not None else 1, -+ HAS_SIM=sim is not None, -+ HAS_BONUS_IN=bonus_in is not None, -+ HAS_PARTS=parts is not None, -+ # The argmax ids only decide a length or bonus nothing else supplies. -+ NEED_TARGET=sim is None or (bonus_in is None and parts is None), -+ HAS_GATED=gated is not None, -+ num_warps=4, -+ ) -+ -+ -+def static_accept_tail_torch( -+ *, -+ candidates: torch.Tensor, -+ target_predict: Optional[torch.Tensor], -+ seq_lens: torch.Tensor, -+ verify_lens: torch.Tensor, -+ gate: torch.Tensor, -+ correct_len_out: torch.Tensor, -+ bonus_out: torch.Tensor, -+ cap_trim_lens_out: torch.Tensor, -+ commit_lens_out: torch.Tensor, -+ new_seq_lens_out: torch.Tensor, -+ out_tokens_out: torch.Tensor, -+ simulated_correct_len: Optional[torch.Tensor] = None, -+ bonus_in: Optional[torch.Tensor] = None, -+ bonus_parts: Optional[tuple[torch.Tensor, torch.Tensor, int]] = None, -+ gated_commit_lens_out: Optional[torch.Tensor] = None, -+) -> None: -+ """Reference: the same outputs from per-row torch ops (CPU or GPU).""" -+ bs, T = candidates.shape -+ gamma = T - 1 -+ if target_predict is not None: -+ target = target_predict.view(bs, T) -+ matches = (candidates[:, 1:] == target[:, :gamma]).to(torch.int32) -+ num_correct = matches.cumprod(dim=1).sum(dim=1).to(torch.int32) -+ rows = torch.arange(bs, device=candidates.device) -+ if bonus_parts is not None: -+ part_val, part_idx, vocab = bonus_parts -+ bonus = simulated_bonus_select_partials( -+ part_val=part_val[:bs], part_idx=part_idx[:bs], vocab=vocab -+ ) -+ elif bonus_in is not None: -+ bonus = bonus_in[:bs].to(torch.int64) -+ else: -+ bonus = target[rows, num_correct.long()].to(torch.int64) -+ if simulated_correct_len is not None: -+ correct = simulated_correct_len.repeat(bs).to(torch.int32) -+ else: -+ correct = num_correct -+ commit = correct + 1 -+ new_seq = seq_lens[:bs] + commit.to(seq_lens.dtype) -+ correct_len_out[:bs].copy_(correct) -+ bonus_out[:bs].copy_(bonus) -+ cap_trim_lens_out[:bs].zero_() -+ commit_lens_out[:bs].copy_(commit) -+ new_seq_lens_out[:bs].copy_(new_seq) -+ tokens = torch.zeros((bs, T), dtype=torch.int64, device=candidates.device) -+ tokens[:, :gamma] = candidates[:, 1:] -+ tokens.scatter_(1, correct.long()[:, None], bonus[:, None]) -+ out_tokens_out[:bs].copy_(tokens) -+ if gated_commit_lens_out is not None: -+ gated = torch.minimum(commit, verify_lens[:bs].to(torch.int32)) * gate -+ gated_commit_lens_out[:bs].copy_(gated) -diff --git a/python/sglang/srt/environ.py b/python/sglang/srt/environ.py -index 818e011a61..b14c61ed96 100644 ---- a/python/sglang/srt/environ.py -+++ b/python/sglang/srt/environ.py -@@ -562,6 +562,32 @@ class Envs: - SGLANG_DSPARK_NVLINK_VOCAB_GATHER = EnvBool(True) - SGLANG_DSPARK_ENABLE_MULTI_STREAM = EnvBool(True) - SGLANG_DSPARK_CONFIDENCE_RELAY_LAG_STEPS = EnvInt(2) -+ # Static verify graphs with bs in [MIN_BS, MAX_BS] (MAX_BS 0: unbounded) run the -+ # greedy accept and its bookkeeping as one kernel. -+ SGLANG_DSPARK_FUSED_ACCEPT_TAIL = EnvBool(False) -+ SGLANG_DSPARK_ACCEPT_TAIL_MIN_BS = EnvInt(1) -+ SGLANG_DSPARK_ACCEPT_TAIL_MAX_BS = EnvInt(0) -+ # Static verify graphs stage the draft context-KV commit; the next draft graph -+ # writes it on a side stream forked at its head, joined at its first KV store. -+ SGLANG_DSPARK_DEFER_CONTEXT_KV = EnvBool(False) -+ # DSpark draft graph: its in-graph attention-metadata prep runs on a side stream -+ # and joins at the first draft KV store, overlapping the embedding. -+ SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK = EnvBool(False) -+ # DSpark static verify: the verify graph scatters new seq lens and the bonus into -+ # the FutureMap's slots; the host skips those scatters for folded accepts. -+ SGLANG_OPT_DSV41_DSPARK_POST_FOLD = EnvBool(False) -+ # DSpark target verify: a pre-planned replay skips re-copying input_ids / positions -+ # the plan-time load already copied from the same tensors. -+ SGLANG_OPT_DSV41_DSPARK_SKIP_PREFILLED_INPUTS = EnvBool(False) -+ # DSpark: draw the simulated acceptance length (and the sim bonus seed) before the -+ # draft launch instead of between the draft and the target verify. -+ SGLANG_OPT_DSV41_DSPARK_SIM_DRAW_AHEAD = EnvBool(False) -+ # Sampled DSpark verify accepts draw with block-wise rejection (blockwise_rejection.py: -+ # exact in law, counter-based draws agree across TP ranks) instead of the classic kernel. -+ SGLANG_OPT_DSV41_BLOCKWISE_REJECTION = EnvBool(False) -+ # The deferred commit's staging (hidden, write locations, positions, commit lengths) -+ # in one Triton launch instead of four copies and a fill. -+ SGLANG_OPT_DSV41_DSPARK_ONE_LAUNCH_COMMIT_STAGE = EnvBool(False) - - # =================================================================== - # Memory pools and KV-cache sizing -@@ -896,6 +922,9 @@ class Envs: - # Hand AITER only ceil32(sum of per-rank DP tokens) rows of the MORI EP receive - # buffer; unproved layouts or metadata keep the full view. Forces DP-synced buckets. - SGLANG_MORI_RECV_BOUND = EnvBool(False) -+ # MXFP4 trtllm-gen MoE: deferred-finalize calls above 32 rows pass the finalized -+ # output shape, so they hit FlashInfer's tuned tactics (off: only 97-384 rows do). -+ SGLANG_OPT_MXFP4_DEFERRED_FINALIZED_SHAPE = EnvBool(False) - # Manual MoE input row limit (EPv1 and EPv2); 0 leaves it to SGLANG_MORI_RECV_BOUND. - SGLANG_MORI_MOE_MAX_INPUT_TOKENS = EnvInt(0) - -@@ -1552,6 +1581,9 @@ class Envs: - # Guards CUDA graph executable dedup via cudaGraphExecUpdate. - SGLANG_ENABLE_CUDA_GRAPH_DEDUP = EnvBool(False) - SGLANG_MEMORY_SAVER_CUDA_GRAPH = EnvBool(False) -+ # Graph-input fill fast paths: skip the padding reset of an unpadded replay and copy -+ # one dense integer dtype pair with a single foreach launch. -+ SGLANG_OPT_CUDA_GRAPH_FILL_FAST_PATH = EnvBool(False) - # Reuse wholly-free graph-pool segments for step-local eager allocations. - SGLANG_ENABLE_GRAPH_POOL_BORROW = EnvBool(False) - # Mint capture's measured footprint as one span so the graph pool is carved -@@ -1780,6 +1812,27 @@ class Envs: - SGLANG_OPT_USE_AITER_BATCHED_GEMM = EnvBool(False) - SGLANG_OPT_BF16_FP32_GEMM_ALGO = EnvStr("cublas") - SGLANG_OPT_FUSE_WQA_WKV = EnvBool(True) -+ # DSpark decode: build the verify window and the draft anchor column in one -+ # launch instead of two adds, assign_extend_cache_locs and a copy. -+ SGLANG_OPT_DSV41_DSPARK_PREPARE_INPUTS_ONCE = EnvBool(False) -+ # DSpark folded draft: the draft graph's tail writes [anchor | draft tokens] -+ # into the sampler's own buffer, so the step skips its eager concat. -+ SGLANG_OPT_DSV41_DSPARK_MID_FOLD = EnvBool(False) -+ # DSpark static verify: run the target verify runner's metadata prep through the -+ # metadata glue graph where its backend declares the prep host-free. -+ SGLANG_OPT_DSV41_TARGET_VERIFY_METADATA_GLUE = EnvBool(False) -+ # DSpark static verify: build the target verify metadata on a side stream beside the -+ # draft graph, for requests up to the candidate span (needs the glue switch above). -+ SGLANG_OPT_DSV41_TARGET_METADATA_EARLY = EnvBool(False) -+ # Decode / verify graph replays whose metadata glue graph is captured skip the -+ # replay ForwardBatch view (the graph reads slots and buffers by address). -+ SGLANG_OPT_SKIP_GLUED_REPLAY_VIEW = EnvBool(False) -+ # DSpark static verify: record the post-verify engram history commit in the -+ # target-verify CUDA graph (epilogue) instead of launching it after the replay. -+ SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH = EnvBool(False) -+ # DSpark static verify: an all-sampled step (no top-k / top-p) replays its -+ # sampling accept and commits as a CUDA graph right after the verify graph. -+ SGLANG_OPT_DSV41_SAMPLING_ACCEPT_GRAPH = EnvBool(False) - SGLANG_OPT_USE_MULTI_STREAM_OVERLAP = EnvBool(True) - - # =================================================================== -diff --git a/python/sglang/srt/layers/attention/base_attn_backend.py b/python/sglang/srt/layers/attention/base_attn_backend.py -index c317997479..9c43fe95a4 100644 ---- a/python/sglang/srt/layers/attention/base_attn_backend.py -+++ b/python/sglang/srt/layers/attention/base_attn_backend.py -@@ -104,6 +104,16 @@ class AttentionBackend(ABC): - self.init_forward_metadata_out_graph(forward_batch) - self.init_forward_metadata_in_graph(forward_batch) - -+ def glue_target_verify_metadata(self) -> str: -+ """Empty if the target verify prep may be captured into the metadata glue graph -+ (reads only runner slots and backend buffers), else the reason it may not.""" -+ return "the attention backend declares no host-free target verify prep" -+ -+ def glue_draft_metadata(self) -> str: -+ """Empty if the draft prep may be captured into the metadata glue graph (host -+ inputs constant per replay key), else the reason it may not.""" -+ return "the attention backend declares no host-free draft prep" -+ - def init_forward_metadata_out_graph( - self, - forward_batch: ForwardBatch, -diff --git a/python/sglang/srt/layers/attention/deepseek_v4_backend.py b/python/sglang/srt/layers/attention/deepseek_v4_backend.py -index aa2ae0e598..cdc156eb64 100644 ---- a/python/sglang/srt/layers/attention/deepseek_v4_backend.py -+++ b/python/sglang/srt/layers/attention/deepseek_v4_backend.py -@@ -6,6 +6,7 @@ import logging - from dataclasses import dataclass, field - from typing import ( - TYPE_CHECKING, -+ Callable, - Dict, - List, - Literal, -@@ -91,6 +92,7 @@ from sglang.srt.layers.attention.dsv4.v41_indexer import ( - from sglang.srt.layers.attention.dsv4.v41_indexer.sparse_table import ( - SparseTableBackend, - ) -+from sglang.srt.layers.attention.graph_variants import DSV41_EARLY_VERIFY_VARIANTS - from sglang.srt.layers.attention.verify_mask import ( - VerifyMask, - maybe_create_verify_mask, -@@ -123,6 +125,9 @@ from sglang.srt.model_executor.runner_backend_utils.breakable_cuda_graph.breakab - from sglang.srt.model_executor.runner_backend_utils.tc_piecewise_cuda_graph import ( - get_tc_piecewise_forward_context, - ) -+from sglang.srt.model_executor.runner_utils.forked_metadata_prep import ( -+ join_in_graph_metadata_prep, -+) - from sglang.srt.runtime_context import ( - get_exec, - get_parallel, -@@ -1165,6 +1170,18 @@ class DSV4RawDecodeMetadata: - self.out_cache_loc.copy_(other.out_cache_loc) - - -+def _replan_topk_in_graph(metadata) -> None: -+ from sglang.kernels.ops.attention.dsv4 import plan_topk_v2 -+ -+ for indexer in ( -+ metadata.indexer_metadata, -+ metadata.c1_indexer_metadata, -+ metadata.c2_indexer_metadata, -+ ): -+ if indexer is not None and indexer.use_topk_v2: -+ plan_topk_v2(indexer.compressed_seq_lens, out=indexer.topk_metadata) -+ -+ - class _GraphBucket(enum.Enum): - DECODE_OR_IDLE = "decode_or_idle" - TARGET_VERIFY = "target_verify" -@@ -1184,6 +1201,9 @@ class _GraphBucket(enum.Enum): - class DeepseekV4AttnBackend( - AttentionBackend, C4IndexerBackendMixin, CompressorBackendMixin - ): -+ pre_kv_store_hook = None -+ builds_verify_metadata_early = False -+ draft_metadata_glued = False - use_captured_forward_metadata_for_breakable_cuda_graph: bool = True - supports_prefill_cuda_graph_max_context_size: bool = True - supports_ragged_verify_graph: bool = True -@@ -1212,6 +1232,9 @@ class DeepseekV4AttnBackend( - ): - super().__init__() - self.model_runner = model_runner -+ # Run at every KV store-location read; the DSpark deferred context-KV commit -+ # joins its forked write there (SGLANG_DSPARK_DEFER_CONTEXT_KV). -+ self.pre_kv_store_hook: Optional[Callable[[], None]] = None - self.encoder_replay = False - self.encoder_row_floor = None - self.device = torch.device(model_runner.device) -@@ -1328,11 +1351,67 @@ class DeepseekV4AttnBackend( - self.is_draft_runner = model_runner.is_draft_worker - self._verify_mask = None - self.cuda_graph_swa_out_cache_loc: Optional[torch.Tensor] = None -+ # Once a draft runner glues this prep (glue_draft_metadata): the draft -+ # block's extend lengths come from device constants, one per batch size. -+ self.draft_metadata_glued = False -+ self._draft_extend_lens: Dict[Tuple[int, ...], torch.Tensor] = {} -+ # Set by the target verify runner that stages this metadata early: the replay -+ # prep then builds the full metadata and the verify graph records none. -+ self.builds_verify_metadata_early = False -+ # Ids of the captured verify metadata built that way; the bucket keeps them alive. -+ self._early_verify_metadata_ids: set = set() - - def _move_to_device(self, x: List[int]) -> torch.Tensor: - pin_tensor = torch.tensor(x, dtype=torch.int32, pin_memory=True) - return pin_tensor.to(self.device, non_blocking=True) - -+ def glue_target_verify_metadata(self) -> str: -+ # The static target verify prep reads the runner's slots and own buffers only; -+ # host lengths, online c128 MTP, trtllm, a request window and CP are unaudited. -+ for bad, why in ( -+ (self.is_draft_runner, "a draft runner"), -+ (self.needs_cpu_seq_lens, "host sequence lengths"), -+ (self.trtllm_attn, "trtllm-gen attention"), -+ (self.online_c128_mtp.enabled(), "online c128 MTP"), -+ (read_ragged_verify_mode() is not RaggedVerifyMode.STATIC, "ragged verify"), -+ (self.token_to_kv_pool.request_window is not None, "a request window"), -+ (get_parallel().attn_cp_size != 1, "context parallelism"), -+ ): -+ if bad: -+ return why -+ return "" -+ -+ def glue_draft_metadata(self) -> str: -+ # The draft block prep is host-free (host inputs follow from bs, CPU lengths -+ # feed only asserts) except in these cases. -+ for bad, why in ( -+ (not self.is_dspark_draft, "not the DSpark draft runner"), -+ (self.trtllm_attn, "trtllm-gen attention"), -+ (self.online_c128_mtp.enabled(), "online c128 MTP"), -+ (self.token_to_kv_pool.request_window is not None, "a request window"), -+ (get_parallel().attn_cp_size != 1, "context parallelism"), -+ ): -+ if bad: -+ return why -+ self.draft_metadata_glued = True -+ return "" -+ -+ def _draft_block_extend_lens(self, lens: List[int]) -> torch.Tensor: -+ """The draft block's extend lengths on the device; glued, a cached constant -+ (a captured host copy would replay from a freed pinned buffer).""" -+ if not self.draft_metadata_glued: -+ return self._move_to_device(lens) -+ key = tuple(lens) -+ cached = self._draft_extend_lens.get(key) -+ if cached is None: -+ if torch.cuda.is_available() and torch.cuda.is_current_stream_capturing(): -+ raise RuntimeError( -+ f"draft block extend lengths {key} first seen inside the metadata " -+ "glue capture" -+ ) -+ cached = self._draft_extend_lens[key] = self._move_to_device(lens) -+ return cached -+ - def _resolve_verify_layout( - self, - forward_batch: ForwardBatch, -@@ -2146,7 +2225,7 @@ class DeepseekV4AttnBackend( - seq_lens_cpu=seq_lens_cpu_list, - extend_len=block_size, - ) -- extend_seq_lens = self._move_to_device(lengths.extend_seq_lens_cpu) -+ extend_seq_lens = self._draft_block_extend_lens(lengths.extend_seq_lens_cpu) - return self.init_forward_metadata_prefill( - # DSpark draft blocks are SWA-only, like draft extend. Their full - # context page table is unused; retain only its 2-D placeholder. -@@ -2169,6 +2248,7 @@ class DeepseekV4AttnBackend( - self, - raw_metadata: DSV4RawVerifyMetadata, - online_c128_state_slot_offset: int = 0, -+ graph_backed: bool = False, - ) -> DSV4Metadata: - req_pool_indices = raw_metadata.req_pool_indices - seq_lens = raw_metadata.seq_lens -@@ -2214,7 +2294,9 @@ class DeepseekV4AttnBackend( - num_groups=bs, - ) - indexer_metadata = ( -- self.init_forward_metadata_indexer(core_attn_metadata) -+ self.init_forward_metadata_indexer( -+ core_attn_metadata, use_prefill_cuda_graph=graph_backed -+ ) - if self.has_c4 - else None - ) -@@ -2245,6 +2327,7 @@ class DeepseekV4AttnBackend( - core_attn_metadata, - compress_ratio=1, - rows_per_request=rows_per_request, -+ use_prefill_cuda_graph=graph_backed, - ) - if 1 in low - else None -@@ -2254,6 +2337,7 @@ class DeepseekV4AttnBackend( - core_attn_metadata, - compress_ratio=2, - rows_per_request=rows_per_request, -+ use_prefill_cuda_graph=graph_backed, - ) - if 2 in low - else None -@@ -2397,6 +2481,11 @@ class DeepseekV4AttnBackend( - skip_low_ratio_indexer, - ) - -+ # Replay prep built this in full except the indexer top-k plans, which the graph -+ # records like the in-graph upgrade (the prep's copy diverged at long context). -+ if id(self.forward_metadata) in self._early_verify_metadata_ids: -+ _replan_topk_in_graph(self.forward_metadata) -+ return - # Upgrade Raw->Full so compress + core_attn + indexer materialization is - # recorded inside the cuda graph. - if isinstance(self.forward_metadata, DSV4RawVerifyMetadata): -@@ -2499,6 +2588,68 @@ class DeepseekV4AttnBackend( - if self.trtllm_attn: - metadata.core_attn_metadata.init_trtllm_sparse_buffers() - -+ def enable_early_verify_metadata(self) -> None: -+ """Called by the target verify runner whose own predicate stages the metadata -+ early, so capture and replay agree on which metadata object the graph reads.""" -+ self.builds_verify_metadata_early = True -+ logger.info("Target verify metadata built outside the verify graph.") -+ -+ def _uses_early_verify_metadata(self, *, ragged_layout) -> bool: -+ """Whether this prep builds the full verify metadata: only for an early -+ variant; the others keep their in-graph upgrade.""" -+ if not self.builds_verify_metadata_early or ragged_layout is not None: -+ return False -+ from sglang.srt.model_executor.runner_utils.capture_mode import ( -+ get_capture_attention_variant, -+ skip_low_ratio_indexer, -+ ) -+ -+ early = get_capture_attention_variant() in DSV41_EARLY_VERIFY_VARIANTS -+ # Only the in-graph upgrade fills the all-position indices of such a variant. -+ assert not (early and any(map(skip_low_ratio_indexer, self.low_ratios))), ( -+ "early verify metadata does not fill candidate_all indices" -+ ) -+ return early -+ -+ def _install_early_verify_metadata( -+ self, *, graph_key, raw_metadata: DSV4RawVerifyMetadata, out_cache_loc -+ ) -> None: -+ """Build what ``init_forward_metadata_in_graph`` records for target verify and -+ copy it into the metadata the early variant's graph was captured with.""" -+ graph_key = (graph_key, "early") -+ # Graph-backed, like the in-graph build it replaces: one indexer call per layer, -+ # no free-memory row chunking (a chunked schedule would be rebound, not copied). -+ metadata = self.make_forward_metadata_from_raw_verify( -+ raw_metadata=raw_metadata, -+ online_c128_state_slot_offset=self.online_c128_mtp.state_slot_offset(), -+ graph_backed=True, -+ ) -+ # The full build leaves the SWA write locations to the in-graph op it replaces. -+ pool = self.token_to_kv_pool -+ swa_out_cache_loc = ( -+ pool.translate_loc_from_full_to_swa(out_cache_loc).to(torch.int32) -+ if pool.request_window is None and pool.swa_req_ring_size is None -+ else None -+ ) -+ self.tail_forward_metadata = None -+ bucket_metadata = self.cuda_graph_metadata_of_bucket_and_bs[ -+ _GraphBucket.TARGET_VERIFY -+ ] -+ captured = bucket_metadata.get(graph_key) -+ if captured is None: -+ metadata.core_attn_metadata.swa_out_cache_loc = swa_out_cache_loc -+ bucket_metadata[graph_key] = metadata -+ self._early_verify_metadata_ids.add(id(metadata)) -+ self.forward_metadata = metadata -+ return -+ # copy_ assigns swa_out_cache_loc; the verify graphs read the captured tensor. -+ captured_swa_out_cache_loc = captured.core_attn_metadata.swa_out_cache_loc -+ captured.copy_(metadata) -+ if captured_swa_out_cache_loc is not None: -+ captured_swa_out_cache_loc.copy_(swa_out_cache_loc) -+ captured.core_attn_metadata.swa_out_cache_loc = captured_swa_out_cache_loc -+ self.forward_metadata = captured -+ - def _dspark_seq_lens_casual( - self, *, seq_lens: torch.Tensor, block_size: int - ) -> torch.Tensor: -@@ -2661,6 +2812,15 @@ class DeepseekV4AttnBackend( - online_c128_state_slot_offset=online_c128_state_slot_offset, - ragged_layout=ragged_layout, - ) -+ if self._uses_early_verify_metadata(ragged_layout=ragged_layout): -+ self._install_early_verify_metadata( -+ graph_key=graph_key, -+ raw_metadata=temp_metadata, -+ out_cache_loc=out_cache_loc_padded, -+ ) -+ if in_capture: -+ self._current_capture_raw = None -+ return - elif bucket == _GraphBucket.DRAFT_EXTEND: - self.online_c128_mtp.prepare_forward( - actual_forward_mode, -@@ -3889,6 +4049,9 @@ class DeepseekV4AttnBackend( - def get_swa_out_cache_loc(self, forward_batch: ForwardBatch) -> torch.Tensor: - """Idle always re-translates at store time: its metadata may be stale, and - translating the zero-padded out_cache_loc writes to the dummy slot.""" -+ join_in_graph_metadata_prep() -+ if self.pre_kv_store_hook is not None: -+ self.pre_kv_store_hook() - metadata = self.forward_metadata - if self.token_to_kv_pool.request_window is not None: - layout = metadata.core_attn_metadata.request_window_layout -diff --git a/python/sglang/srt/layers/attention/graph_variants.py b/python/sglang/srt/layers/attention/graph_variants.py -index e3244aa0c1..a06ff32b13 100644 ---- a/python/sglang/srt/layers/attention/graph_variants.py -+++ b/python/sglang/srt/layers/attention/graph_variants.py -@@ -69,6 +69,10 @@ def create_attention_graph_variants(hf_config) -> Optional[AttentionGraphVariant - - - DSV41_CANDIDATE_FILTERED = "candidate_filtered" -+DSV41_CANDIDATE_UNFILTERED = "candidate_unfiltered" -+# SGLANG_OPT_DSV41_TARGET_METADATA_EARLY serves these target verify variants (requests -+# up to the candidate span); longer ones keep the in-graph metadata upgrade. -+DSV41_EARLY_VERIFY_VARIANTS = frozenset({DSV41_CANDIDATE_UNFILTERED}) - - - @dataclass(frozen=True) -@@ -93,6 +97,11 @@ class Dsv41CandidateGraphVariants: - "candidate_max_seq_len_upper_bound", - None, - ) -+ return self.select_for_max_seq_len(max_seq_len) -+ -+ def select_for_max_seq_len(self, max_seq_len: Optional[int]) -> str: -+ """The variant for a batch whose longest request (before this step's verify -+ tokens) is ``max_seq_len``; None, when unknown, takes the fallback.""" - if max_seq_len is not None: - max_seq_len += self.verify_extra_tokens - for variant, limit in self.graph_limits: -@@ -139,7 +148,7 @@ def create_dsv41_candidate_graph_variants( - variants.append(("candidate_all", topk * min(ratios))) - if ratios == {1, 2}: - variants.append(("candidate_c2_all", topk * 2)) -- variants.append(("candidate_unfiltered", span)) -+ variants.append((DSV41_CANDIDATE_UNFILTERED, span)) - graph_limits = [] - for variant, limit in variants: - graph_limits.append((variant, min(limit, span))) -diff --git a/python/sglang/srt/layers/quantization/mxfp4_flashinfer_trtllm_moe.py b/python/sglang/srt/layers/quantization/mxfp4_flashinfer_trtllm_moe.py -index 4d873c36ae..801f2fca9d 100644 ---- a/python/sglang/srt/layers/quantization/mxfp4_flashinfer_trtllm_moe.py -+++ b/python/sglang/srt/layers/quantization/mxfp4_flashinfer_trtllm_moe.py -@@ -10,6 +10,7 @@ from torch.nn.parameter import Parameter - from sglang.srt.distributed.device_communicators.pynccl_allocator import ( - use_symmetric_memory, - ) -+from sglang.srt.environ import envs - from sglang.srt.layers.dp_attention import is_allocation_symmetric - from sglang.srt.layers.moe.utils import MoeRunnerBackend, RoutingMethodType - from sglang.srt.runtime_context import ( -@@ -463,11 +464,14 @@ class Mxfp4FlashinferTrtllmMoEMethod: - # Deferred finalize returns the permuted GEMM2 output plus the routing - # triple instead of the finalized [T, hidden] tensor. - defer_finalize = is_deferred_finalize_enabled() -+ # FlashInfer keys its tactic cache on the output shape. At <= 32 rows the tuned -+ # tactic measured slower on real routing, so those keep the (M, 0) key. -+ if envs.SGLANG_OPT_MXFP4_DEFERRED_FINALIZED_SHAPE.get(): -+ deferred_output_shape = num_tokens > 32 -+ else: -+ deferred_output_shape = 96 < num_tokens <= 384 - symm_output = None -- # Preserve the ordinary output shape in the medium-batch autotuner -- # cache key. The deferred ABI ignores this allocation and returns the -- # expanded GEMM output for the separate fused finalize epilogue. -- if not defer_finalize or 96 < num_tokens <= 384: -+ if not defer_finalize or deferred_output_shape: - with use_symmetric_memory( - get_parallel().tp_group, disabled=not is_allocation_symmetric() - ): -diff --git a/python/sglang/srt/managers/overlap_utils.py b/python/sglang/srt/managers/overlap_utils.py -index 41d97577dd..afbb183e7b 100644 ---- a/python/sglang/srt/managers/overlap_utils.py -+++ b/python/sglang/srt/managers/overlap_utils.py -@@ -84,6 +84,32 @@ def _assert_nonneg_and_invalidate( - buf[indices] = -1 - - -+class FutureRelayBuffers: -+ """Seq-lens / bonus buffers a static verify graph scatters into; captured before -+ the FutureMap exists, which adopts them (SGLANG_OPT_DSV41_DSPARK_POST_FOLD).""" -+ -+ def __init__(self, *, req_pool_size: int, device) -> None: -+ self.new_seq_lens = torch.empty( -+ (req_pool_size,), dtype=torch.int64, device=device -+ ) -+ self.output_tokens = torch.empty( -+ (req_pool_size,), dtype=torch.int64, device=device -+ ) -+ self.adopted = False -+ # The step's accept outputs the graph already scattered: publish / stash of -+ # these very tensors skip their scatter (strong refs, so ids never recycle). -+ self.published_seq_lens: Optional[torch.Tensor] = None -+ self.published_bonus: Optional[torch.Tensor] = None -+ -+ -+_offered_relay: Optional[FutureRelayBuffers] = None -+ -+ -+def offer_future_relay_buffers(relay: FutureRelayBuffers) -> None: -+ global _offered_relay -+ _offered_relay = relay -+ -+ - def resolve_forward_inputs(batch: ScheduleBatch, future_map: FutureMap) -> None: - """Materialize input_ids at forward entry. Two sources: - -@@ -257,6 +283,8 @@ class FutureMap: - publish/stash; next iter reads via resolve_forward_inputs / resolve_seq_lens_cpu. - """ - -+ _relay = None -+ - def __init__( - self, - device: torch.device, -@@ -326,6 +354,21 @@ class FutureMap: - req_pool_size=self.req_pool_size, - pool=req_to_token_pool, - ) -+ self._relay: Optional[FutureRelayBuffers] = None -+ if ( -+ _offered_relay is not None -+ and _offered_relay.new_seq_lens.shape[0] == self.req_pool_size -+ ): -+ self._adopt_relay(_offered_relay) -+ -+ def _adopt_relay(self, relay: FutureRelayBuffers) -> None: -+ if _DEBUG_ASSERT: -+ relay.new_seq_lens.fill_(-1) -+ relay.output_tokens.fill_(-1) -+ self.new_seq_lens_buf = relay.new_seq_lens -+ self.output_tokens_buf = relay.output_tokens -+ relay.adopted = True -+ self._relay = relay - - def _maybe_init_forward_bufs(self, payload: RelayPayload) -> None: - # Local import (see decide_needs_cpu_seq_lens): keep module-level deps leaf. -@@ -612,7 +655,13 @@ class FutureMap: - indices = future_indices - if indices.shape[0] == 0: - return # DP idle -- self.new_seq_lens_buf[indices] = new_seq_lens.to(self.new_seq_lens_buf.dtype) -+ relay = self._relay -+ if relay is not None and new_seq_lens is relay.published_seq_lens: -+ relay.published_seq_lens = None -+ else: -+ self.new_seq_lens_buf[indices] = new_seq_lens.to( -+ self.new_seq_lens_buf.dtype -+ ) - publish_confidence = self.needs_confidence_relay and confidence is not None - if publish_confidence: - self.confidence_relay.scatter(indices, confidence) -@@ -640,9 +689,13 @@ class FutureMap: - return - self._maybe_init_forward_bufs(payload) - self._maybe_init_dsa_topk_indices_buf(payload) -- self.output_tokens_buf[indices] = payload.bonus_tokens.to( -- self.output_tokens_buf.dtype -- ) -+ relay = self._relay -+ if relay is not None and payload.bonus_tokens is relay.published_bonus: -+ relay.published_bonus = None -+ else: -+ self.output_tokens_buf[indices] = payload.bonus_tokens.to( -+ self.output_tokens_buf.dtype -+ ) - - # Staging transitions refresh only the bonus token. Preserve top-k and - # hidden state already published by the preceding target forward. -diff --git a/python/sglang/srt/mem_cache/kv_index_translator.py b/python/sglang/srt/mem_cache/kv_index_translator.py -index 821c8509cd..d4856188ff 100644 ---- a/python/sglang/srt/mem_cache/kv_index_translator.py -+++ b/python/sglang/srt/mem_cache/kv_index_translator.py -@@ -304,6 +304,9 @@ class KVIndexTranslator: - seq_lens: torch.Tensor, - seq_lens_cpu: Optional[torch.Tensor], - width: int, -+ positions_out: Optional[torch.Tensor] = None, -+ anchor_src: Optional[torch.Tensor] = None, -+ anchor_out: Optional[torch.Tensor] = None, - ) -> KVLocPlan: - """Gather one fixed-width speculative window, translating at its producer. - -@@ -341,6 +344,9 @@ class KVIndexTranslator: - full_out=writes.get(IdSpaceKind.FULL), - swa_out=writes.get(IdSpaceKind.SLIDING_WINDOW), - page_size=self.page_size, -+ positions_out=positions_out, -+ anchor_src=anchor_src, -+ anchor_out=anchor_out, - ) - return self.plan( - req_pool_indices=req_pool_indices, -diff --git a/python/sglang/srt/model_executor/cuda_graph_buffer_registry.py b/python/sglang/srt/model_executor/cuda_graph_buffer_registry.py -index 385f099090..3ac4da6da1 100644 ---- a/python/sglang/srt/model_executor/cuda_graph_buffer_registry.py -+++ b/python/sglang/srt/model_executor/cuda_graph_buffer_registry.py -@@ -31,6 +31,7 @@ from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple - - import torch - -+from sglang.srt.environ import envs - from sglang.srt.model_executor.input_buffers import ( - INDEX_SEMANTIC_BUFFERS, - share_input_buffer, -@@ -58,6 +59,12 @@ def _grouped_foreach_copy_(dsts: List[torch.Tensor], srcs: List[torch.Tensor]) - - dst.copy_(src) - - if dsts and dsts[0].is_cuda: -+ fast_path = envs.SGLANG_OPT_CUDA_GRAPH_FILL_FAST_PATH.get() -+ if fast_path and _has_foreach_copy and _one_dense_int_pair(dsts, srcs): -+ # One foreach launch already writes what the small copy would; that kernel -+ # pays off only across dtype pairs, and costs per-pair host checks. -+ torch._foreach_copy_(dsts, srcs) -+ return - from sglang.kernels.ops.memory.small_copy import try_small_copy - - if try_small_copy(dsts, srcs): -@@ -74,6 +81,28 @@ def _grouped_foreach_copy_(dsts: List[torch.Tensor], srcs: List[torch.Tensor]) - - _foreach_copy(group_dsts, group_srcs) - - -+def _one_dense_int_pair(dsts: List[torch.Tensor], srcs: List[torch.Tensor]) -> bool: -+ # One integer / bool (dst, src) dtype pair over contiguous tensors. -+ pair = (dsts[0].dtype, srcs[0].dtype) -+ if any(dtype.is_floating_point or dtype.is_complex for dtype in pair): -+ return False -+ return all( -+ (dst.dtype, src.dtype) == pair and dst.is_contiguous() and src.is_contiguous() -+ for dst, src in zip(dsts, srcs) -+ ) -+ -+ -+def same_tensor_view(a: torch.Tensor, b: torch.Tensor) -> bool: -+ """Whether ``a`` and ``b`` view the same elements of the same storage.""" -+ return ( -+ a.data_ptr() == b.data_ptr() -+ and a.device == b.device -+ and a.dtype == b.dtype -+ and a.shape == b.shape -+ and a.stride() == b.stride() -+ ) -+ -+ - class PaddingPolicy(Enum): - """How to handle ``raw_n < padded_n`` for a slot. - -@@ -394,8 +423,10 @@ class CudaGraphBufferRegistry: - raw_num_tokens: int, - padded_num_tokens: int, - pp_proxy_tensors: Optional[Any] = None, -+ skip_slots: frozenset = frozenset(), - ) -> None: -- """Copy FB → registry buffers. -+ """Copy FB → registry buffers; ``skip_slots`` are left untouched (their -+ content was staged by ``copy_slots``). - - Phase 1 — reset the padded tail per slot ``padding_policy``. - Phase 2 — grouped D2D copy of all enabled slots from FB (or from a -@@ -419,13 +450,19 @@ class CudaGraphBufferRegistry: - pp_proxy_tensors=pp_proxy_tensors, - ) - -- # Phase 1: reset padded regions where it matters. -- for slot in self._slots.values(): -- if not slot.enabled or slot.buffer is None: -- continue -- raw_n = slot._raw_n(raw_bs, raw_num_tokens) -- padded_n = slot._padded_n(padded_bs, padded_num_tokens) -- slot.reset_padding(raw_n, padded_n) -+ # Phase 1: reset padded regions where it matters (none when neither -+ # axis is padded: reset_padding is then a no-op for every slot). -+ if ( -+ not envs.SGLANG_OPT_CUDA_GRAPH_FILL_FAST_PATH.get() -+ or raw_bs < padded_bs -+ or raw_num_tokens < padded_num_tokens -+ ): -+ for slot in self._slots.values(): -+ if not slot.enabled or slot.buffer is None or slot.name in skip_slots: -+ continue -+ raw_n = slot._raw_n(raw_bs, raw_num_tokens) -+ padded_n = slot._padded_n(padded_bs, padded_num_tokens) -+ slot.reset_padding(raw_n, padded_n) - - # Phase 2: collect (dst, src) pairs and dispatch a grouped copy. - gpu_dsts: List[torch.Tensor] = [] -@@ -433,7 +470,12 @@ class CudaGraphBufferRegistry: - cpu_dsts: List[torch.Tensor] = [] - cpu_srcs: List[torch.Tensor] = [] - for slot in self._slots.values(): -- if not slot.enabled or slot.buffer is None or not slot.copy_from_fb: -+ if ( -+ not slot.enabled -+ or slot.buffer is None -+ or not slot.copy_from_fb -+ or slot.name in skip_slots -+ ): - continue - if slot.source_fn is not None: - # Structured / side-sourced slot: source comes from a nested FB -@@ -473,10 +515,28 @@ class CudaGraphBufferRegistry: - - # Phase 3: post-fill hooks (compute-then-write slots). - for slot in self._slots.values(): -- if not slot.enabled or slot.buffer is None or slot.post_fill is None: -+ if ( -+ not slot.enabled -+ or slot.buffer is None -+ or slot.post_fill is None -+ or slot.name in skip_slots -+ ): - continue - slot.post_fill(slot.buffer, forward_batch, ctx) - -+ def copy_slots(self, sources: Dict[str, torch.Tensor]) -> None: -+ """``fill_from`` for an unpadded batch, by slot name: no padding reset or hooks, -+ and no copy for a source that already is the slot's view.""" -+ dsts: List[torch.Tensor] = [] -+ srcs: List[torch.Tensor] = [] -+ for name, src in sources.items(): -+ dst = self._slots[name].buffer[: src.shape[0]] -+ if not same_tensor_view(dst, src): -+ dsts.append(dst) -+ srcs.append(src) -+ if dsts: -+ _grouped_foreach_copy_(dsts, srcs) -+ - def extract_buffer( - self, - *, -diff --git a/python/sglang/srt/model_executor/model_runner.py b/python/sglang/srt/model_executor/model_runner.py -index e646d19803..4ecea9e358 100644 ---- a/python/sglang/srt/model_executor/model_runner.py -+++ b/python/sglang/srt/model_executor/model_runner.py -@@ -391,6 +391,8 @@ class ModelRunner: - get_spec().speculative_algorithm - ) - self.capture_tail_hooks = [] -+ # Called as hook(graph_runner, forward_batch) first inside each decode graph capture. -+ self.capture_head_hooks = [] - self.page_size = get_schedule().page_size - self.req_to_token_pool = req_to_token_pool - self.token_to_kv_pool_allocator = token_to_kv_pool_allocator -diff --git a/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py b/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py -index 889f69360e..664cb93d55 100644 ---- a/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py -+++ b/python/sglang/srt/model_executor/runner/decode_cuda_graph_runner.py -@@ -48,7 +48,9 @@ from sglang.srt.layers.attention.base_attn_backend import ( - ) - from sglang.srt.layers.attention.dsa.utils import is_dsa_enable_prefill_cp - from sglang.srt.layers.attention.graph_variants import ( -+ DSV41_EARLY_VERIFY_VARIANTS, - AttentionGraphVariants, -+ Dsv41CandidateGraphVariants, - create_attention_graph_variants, - create_dsv41_candidate_graph_variants, - ) -@@ -81,6 +83,11 @@ from sglang.srt.model_executor.runner.base_cuda_graph_runner import ( - freeze_gc, - get_batch_sizes_to_capture, - ) -+from sglang.srt.model_executor.runner.early_verify_metadata import ( -+ STAGED_SLOTS, -+ EarlyVerifyMetadata, -+ VerifyInputSources, -+) - from sglang.srt.model_executor.runner.flashinfer_autotune import ( - maybe_flashinfer_autotune_speculative_draft, - ) -@@ -95,11 +102,16 @@ from sglang.srt.model_executor.runner_utils.buffers import DecodeInputBuffers - from sglang.srt.model_executor.runner_utils.capture_mode import ( - _set_capture_attention_variant, - _set_capture_lora_variant, -+ get_capture_attention_variant, - model_capture_mode, - ) - from sglang.srt.model_executor.runner_utils.deepep_adapter import ( - DeepEPCudaGraphRunnerAdapter, - ) -+from sglang.srt.model_executor.runner_utils.forked_metadata_prep import ( -+ fork_in_graph_metadata_prep, -+ join_in_graph_metadata_prep, -+) - from sglang.srt.model_executor.runner_utils.pool import ( - get_or_create_global_graph_capture_stream, - ) -@@ -128,6 +140,20 @@ except ImportError: - - logger = logging.getLogger(__name__) - -+ -+@contextlib.contextmanager -+def _attention_variant_during_prep(attention_variant): -+ before = get_capture_attention_variant() -+ _set_capture_attention_variant(attention_variant) -+ try: -+ yield -+ finally: -+ _set_capture_attention_variant(before) -+ -+ -+# Draft metadata glue: steps between two "draft glue" tally lines per rank -+DRAFT_GLUE_LOG_EVERY = 1000 -+ - if TYPE_CHECKING: - from sglang.srt.model_executor.model_runner import ModelRunner - from sglang.srt.speculative.spec_info import SpeculativeAlgorithm -@@ -224,8 +250,21 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - pluggable self.backend that handles the actual capture/replay. - """ - -+ _draft_glue_logged = 0 -+ - dllm_input_preparation = None - dllm_attention = None -+ # Set in __init__: which DSpark runner's prep the glue graph serves past the guard. -+ _draft_metadata_glue = False -+ _target_metadata_glue = False -+ _metadata_prep_fork: Optional[tuple] = None -+ _metadata_prep_fork_resolved = False -+ _early_verify_metadata = None -+ _skips_prefilled_inputs = False -+ _prefilled_inputs: Optional[tuple] = None -+ num_prefilled_input_skips = 0 -+ # SGLANG_OPT_SKIP_GLUED_REPLAY_VIEW, read in __init__. -+ _skip_glued_replay_view = False - - def __init__( - self, -@@ -241,6 +280,14 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - - # In-graph metadata prep: shared buffers -> in-graph private data - self.in_graph_metadata_prep_done: Optional[torch.cuda.Event] = None -+ # SGLANG_OPT_DSV41_DSPARK_SKIP_PREFILLED_INPUTS: the (input_ids, positions) -+ # tensors the plan-time load already copied into this runner's buffers. -+ self._prefilled_inputs: Optional[tuple] = None -+ self.num_prefilled_input_skips = 0 -+ # SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK: (stream, event) the draft graph's -+ # in-graph metadata prep is forked onto; resolved at the first capture. -+ self._metadata_prep_fork: Optional[tuple] = None -+ self._metadata_prep_fork_resolved = False - - # --- core state ------------------------------------------------ - self.enable_torch_compile = get_flags().capture.enable_torch_compile -@@ -446,7 +493,11 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - ), - aux_hidden_states_width=self.model_runner.get_aux_hidden_states_width(), - ) -- self.buffers.share_buffers() -+ # The early verify metadata writes these slots beside the draft graph, which -+ # must not share their storage through the process-wide pool. -+ self.buffers.share_buffers( -+ exclude=STAGED_SLOTS if self._wants_early_verify_metadata() else () -+ ) - # FB-shared slot registry adopting DecodeInputBuffers storage (same - # physical tensors, stable data_ptr for capture vs replay). Provides - # the unified fill_from / slot access surface for capture/replay. -@@ -497,6 +548,39 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - self._metadata_glue = ( - MetadataGlueGraph(self.device) if enable_metadata_glue else None - ) -+ # The DSpark draft runner's prep has no host-fed plan, so the guard above does -+ # not apply where its backend says so. -+ self._draft_metadata_glue = ( -+ self._metadata_glue is None and self._glues_draft_metadata() -+ ) -+ # Likewise the DSpark target verify runner's static prep, behind its own switch. -+ self._target_metadata_glue = ( -+ not self._draft_metadata_glue -+ and self._metadata_glue is None -+ and self._glues_target_verify_metadata() -+ ) -+ self._draft_glue_logged = 0 -+ self._skips_prefilled_inputs = self._resolve_skips_prefilled_inputs() -+ if self._draft_metadata_glue or self._target_metadata_glue: -+ self._metadata_glue = MetadataGlueGraph(self.device) -+ self._skip_glued_replay_view = envs.SGLANG_OPT_SKIP_GLUED_REPLAY_VIEW.get() -+ # SGLANG_OPT_DSV41_TARGET_METADATA_EARLY: the verify's inputs and metadata glue -+ # graph run on a side stream beside the draft graph (stage_verify_metadata_early). -+ self._early_verify_metadata: Optional[EarlyVerifyMetadata] = ( -+ EarlyVerifyMetadata(device=self.device, log_every=10000) -+ if self._wants_early_verify_metadata() -+ and self._target_metadata_glue -+ and not self.enable_pdmux -+ and self.model_runner.lora_manager is None -+ else None -+ ) -+ if self._early_verify_metadata is not None: -+ self.attn_backend.enable_early_verify_metadata() -+ logger.info( -+ "Target verify metadata staged on a side stream beside the draft graph " -+ "for variants %s.", -+ sorted(DSV41_EARLY_VERIFY_VARIANTS), -+ ) - - # --- backend --------------------------------------------------- - self.backend = resolve_decode_backend(self) -@@ -514,6 +598,51 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - """Rows reserved for the largest shared logits output.""" - return max_num_tokens - -+ def _forks_draft_metadata_prep(self) -> bool: -+ from sglang.srt.layers.attention.deepseek_v4_backend import ( -+ DeepseekV4AttnBackend, -+ ) -+ from sglang.srt.layers.attention.dsv4.unified_kv_gate import ( -+ is_unified_kv_triton, -+ ) -+ -+ return ( -+ envs.SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK.get() -+ # The unified-KV store location is not a join point. -+ and not is_unified_kv_triton() -+ and self.model_runner.spec_algorithm.is_dspark() -+ and self.model_runner.is_draft_worker -+ and self.capture_forward_mode == ForwardMode.TARGET_VERIFY -+ # Its KV store-location reads are where the forked prep joins. -+ and isinstance(self.attn_backend, DeepseekV4AttnBackend) -+ and self.device_module is torch.cuda -+ and not get_exec().graph.debug_cuda_graph -+ and not self.enable_torch_compile -+ and not get_parallel().attn_dp_enabled -+ and not self.enable_two_batch_overlap -+ and not self.enable_pdmux -+ and self.model_runner.lora_manager is None -+ ) -+ -+ def _run_in_graph_metadata_prep(self, attn_backend, forward_batch) -> None: -+ def prep(): -+ attn_backend.init_forward_metadata_in_graph(forward_batch) -+ self._record_in_graph_metadata_prep_done() -+ -+ if not self._metadata_prep_fork_resolved: -+ self._metadata_prep_fork_resolved = True -+ if self._forks_draft_metadata_prep(): -+ self._metadata_prep_fork = (torch.cuda.Stream(), torch.cuda.Event()) -+ logger.info( -+ "SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK: draft in-graph " -+ "metadata prep forked onto a side stream." -+ ) -+ if self._metadata_prep_fork is None: -+ prep() -+ return -+ stream, done = self._metadata_prep_fork -+ fork_in_graph_metadata_prep(stream=stream, done=done, prep=prep) -+ - def _record_in_graph_metadata_prep_done(self): - # Purely a marker at this point in the graph; where the shared reads - # actually end is the attn backend's call. -@@ -1269,10 +1398,11 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - ForwardContext(attn_backend=attn_backend), - forward_batch=forward_batch, - ): -+ for capture_hook in self.model_runner.capture_head_hooks: -+ capture_hook(self, forward_batch) - # Backends may gather live pool mappings into their static - # metadata here; these nodes run before any model KV reads. -- attn_backend.init_forward_metadata_in_graph(forward_batch) -- self._record_in_graph_metadata_prep_done() -+ self._run_in_graph_metadata_prep(attn_backend, forward_batch) - - forward_batch.dp_local_start_pos = ( - forward_batch.dp_local_num_tokens -@@ -1322,6 +1452,11 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - forward_batch, - **kwargs, - ) -+ if join_in_graph_metadata_prep(): -+ raise RuntimeError( -+ "The draft forward never joined its forked metadata prep; " -+ "unset SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK." -+ ) - for capture_hook in self.model_runner.capture_tail_hooks: - capture_hook(self, out, forward_batch, num_tokens) - return out -@@ -1420,8 +1555,7 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - ) - self._stage_ragged_verify_layout(ragged_layout, graph_size_key) - self._set_dp_real_num_tokens(self.raw_num_token) -- self.buffers.input_ids[: self.raw_num_token].copy_(forward_batch.input_ids) -- self.buffers.positions[: self.raw_num_token].copy_(forward_batch.positions) -+ self._copy_replay_inputs(forward_batch) - if ( - pp_proxy_tensors is not None - and self.buffers.pp_proxy_tensors is not None -@@ -1488,6 +1622,13 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - bs=bs, num_tokens=padded_num_tokens - ) - -+ attention_variant = self._resolve_attention_variant(forward_batch, bs) -+ glue_key = self._glue_key( -+ bs, str(forward_batch.forward_mode), attention_variant -+ ) -+ early_staged = self._take_early_verify_metadata( -+ forward_batch, raw_bs=raw_bs, bs=bs, is_ragged=is_ragged, key=glue_key -+ ) - self.buffer_registry.fill_from( - forward_batch, - raw_bs=raw_bs, -@@ -1495,7 +1636,10 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - raw_num_tokens=raw_num_token, - padded_num_tokens=padded_num_tokens, - pp_proxy_tensors=pp_proxy_tensors, -+ skip_slots=STAGED_SLOTS if early_staged else frozenset(), - ) -+ if self._skips_prefilled_inputs: -+ self._prefilled_inputs = (forward_batch.input_ids, forward_batch.positions) - - if ( - not is_ragged -@@ -1526,14 +1670,117 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - ): - forward_batch.spec_info.custom_mask = buffers.custom_mask - -+ self._init_replay_attn_metadata( -+ forward_batch, -+ raw_bs=raw_bs, -+ bs=bs, -+ num_tokens=padded_num_tokens, -+ glue_key=glue_key, -+ early_staged=early_staged, -+ attention_variant=attention_variant, -+ ) -+ if self._draft_metadata_glue or self._target_metadata_glue: -+ self._maybe_log_draft_glue() -+ -+ self.raw_bs = raw_bs -+ self.raw_num_token = raw_num_token -+ self.bs = bs -+ if is_ragged: -+ self._ragged_graph_size = graph_size_key -+ -+ if self.model_runner.hisparse_coordinator is not None: -+ self.model_runner.hisparse_coordinator.num_real_reqs.fill_(raw_bs) -+ -+ variant_label = self._resolve_lora_variant(forward_batch) -+ if self._early_verify_metadata is not None: -+ self._early_verify_metadata.count_variant( -+ attention_variant, taken=early_staged -+ ) -+ stream_idx = get_current_stream_idx() if self.enable_pdmux else None -+ self._replay_graph_key = self._make_graph_key( -+ graph_size_key, stream_idx, variant_label, attention_variant -+ ) -+ -+ def _glues_draft_metadata(self) -> bool: -+ """Whether this draft runner's metadata prep runs through the glue graph: a -+ static-verify draft runner whose backend accepts it.""" -+ if not self.model_runner.is_draft_worker: -+ return False -+ if envs.SGLANG_RAGGED_VERIFY_MODE.get() != "static": -+ why = "ragged verify" -+ else: -+ why = self.attn_backend.glue_draft_metadata() -+ if why: -+ logger.info("Draft metadata glue graph off: %s.", why) -+ return False -+ logger.info("Draft metadata prep through the glue graph, one per replay key.") -+ return True -+ -+ def _init_replay_attn_metadata( -+ self, -+ forward_batch: ForwardBatch, -+ *, -+ raw_bs: int, -+ bs: int, -+ num_tokens: int, -+ glue_key: tuple, -+ early_staged: bool, -+ attention_variant, -+ ) -> None: -+ """The attention backend's out-of-graph metadata prep for this replay.""" -+ # Glue-graph fast path: pointer-stable prep (static buffers + pool -+ # tensors only) is captured per key; guards keep every python-visible -+ # branch inside the backends constant for that key. -+ glue_route = ( -+ self._metadata_glue is not None -+ and not self._metadata_glue.disabled -+ and raw_bs == bs -+ and not self.enable_two_batch_overlap -+ and not self.enable_pdmux -+ and self.model_runner.lora_manager is None -+ ) -+ if early_staged: -+ # The side stream already replayed the glue graph for this step's inputs. -+ self._metadata_glue.reinstall(glue_key) -+ elif ( -+ glue_route -+ and self._skip_glued_replay_view -+ and isinstance(self._metadata_glue, MetadataGlueGraph) -+ and self._metadata_glue.is_captured(glue_key) -+ ): -+ # A captured glue graph reads slots and backend buffers by address: no -+ # replay view, no out_cache_loc re-point. -+ self._metadata_glue.replay(glue_key) -+ else: -+ self._init_replay_attn_metadata_from_view( -+ forward_batch, -+ raw_bs=raw_bs, -+ bs=bs, -+ num_tokens=num_tokens, -+ glue_key=glue_key if glue_route else None, -+ attention_variant=attention_variant, -+ ) -+ -+ def _init_replay_attn_metadata_from_view( -+ self, -+ forward_batch: ForwardBatch, -+ *, -+ raw_bs: int, -+ bs: int, -+ num_tokens: int, -+ glue_key: Optional[tuple], -+ attention_variant, -+ ) -> None: -+ """The replay metadata prep through the replay ForwardBatch view: the glue -+ graph's warm-ups and capture (``glue_key``), or the eager prep (None).""" - attn_backend = self._replay_attn_backend() - fb_view = build_replay_fb_view( - forward_batch=forward_batch, -- buffers=buffers, -+ buffers=self.buffers, - bs=bs, - raw_bs=raw_bs, -- num_tokens=padded_num_tokens, -- global_num_tokens_cpu=self._global_num_tokens_for_graph(padded_num_tokens), -+ num_tokens=num_tokens, -+ global_num_tokens_cpu=self._global_num_tokens_for_graph(num_tokens), - seq_len_fill_value=self.seq_len_fill_value, - capture_forward_mode=self.capture_forward_mode, - is_encoder_decoder=self.is_encoder_decoder, -@@ -1545,50 +1792,177 @@ class DecodeCudaGraphRunner(BaseCudaGraphRunner): - self.model_runner.lora_manager.prepare_lora_batch( - cast(ForwardBatch, fb_view) - ) -- # Glue-graph fast path: pointer-stable prep (static buffers + pool -- # tensors only) is captured per key; guards keep every python-visible -- # branch inside the backends constant for that key. -- if ( -- self._metadata_glue is not None -- and not self._metadata_glue.disabled -- and raw_bs == bs -+ if glue_key is not None: -+ self._glue_draft_inputs(fb_view) -+ with self._prep_attention_variant(attention_variant): -+ self._metadata_glue.run(attn_backend, fb_view, glue_key) -+ else: -+ if self._metadata_glue is not None: -+ self._metadata_glue.note_not_routed() -+ with self._prep_attention_variant(attention_variant): -+ attn_backend.init_forward_metadata_out_graph(fb_view) -+ -+ def _wants_early_verify_metadata(self) -> bool: -+ """SGLANG_OPT_DSV41_TARGET_METADATA_EARLY, from facts fixed before the buffers -+ are shared.""" -+ return ( -+ envs.SGLANG_OPT_DSV41_TARGET_METADATA_EARLY.get() -+ and self.capture_forward_mode == ForwardMode.TARGET_VERIFY -+ and not self.model_runner.is_draft_worker -+ and self.model_runner.spec_algorithm.is_dspark() -+ and not self.ragged_verify_mode -+ and torch.device(self.model_runner.device).type == "cuda" -+ and not get_parallel().attn_dp_enabled -+ and not self.require_gathered_buffer - and not self.enable_two_batch_overlap -- and not self.enable_pdmux -- and self.model_runner.lora_manager is None -+ ) -+ -+ def _glue_key(self, bs: int, actual_mode: str, attention_variant) -> tuple: -+ # actual_forward_mode belongs in the key even though the captured graph always -+ # targets capture_forward_mode: DSV4's replay prep substitutes seq_lens / -+ # seq_lens_cpu / seq_lens_sum / req_pool_indices / out_cache_loc when the -+ # runtime mode is IDLE, so IDLE and active DECODE are different python branches -+ # and must not share a captured graph. Under the early metadata the variant -+ # picks the prep's branch too (early install or Raw copy). -+ key = (bs, str(self.capture_forward_mode), actual_mode) -+ if self._early_verify_metadata is None: -+ return key -+ return key + (attention_variant,) -+ -+ def _prep_attention_variant(self, attention_variant): -+ """The variant set while this replay's prep runs in python, so the backend -+ builds the metadata the variant's graph reads (early metadata only).""" -+ if self._early_verify_metadata is None: -+ return contextlib.nullcontext() -+ return _attention_variant_during_prep(attention_variant) -+ -+ def _early_variant_for(self, max_seq_len: Optional[int]) -> Optional[str]: -+ variants = self.attention_graph_variants -+ if not isinstance(variants, Dsv41CandidateGraphVariants): -+ return None -+ return variants.select_for_max_seq_len(max_seq_len) -+ -+ def stage_verify_metadata_early( -+ self, -+ *, -+ seq_lens: torch.Tensor, -+ req_pool_indices: torch.Tensor, -+ out_cache_loc: Optional[torch.Tensor], -+ positions: torch.Tensor, -+ max_seq_len: Optional[int], -+ after: torch.cuda.Event, -+ ) -> bool: -+ """After the draft launch, stage the verify inputs and glue replay on a side -+ stream waiting on ``after``; False when this batch cannot be staged.""" -+ early = self._early_verify_metadata -+ if early is None: -+ return False -+ bs = seq_lens.shape[0] -+ num_tokens = bs * self.captured_req_width -+ variant = self._early_variant_for(max_seq_len) -+ key = self._glue_key(bs, str(ForwardMode.TARGET_VERIFY), variant) -+ if ( -+ bs not in self.capture_bs -+ or variant not in DSV41_EARLY_VERIFY_VARIANTS -+ or positions.shape[0] != num_tokens -+ or out_cache_loc is None -+ or out_cache_loc.shape[0] != num_tokens -+ or not self._metadata_glue.is_captured(key) - ): -- # actual_forward_mode belongs in the key even though the captured -- # graph always targets capture_forward_mode: DSV4's replay prep -- # substitutes seq_lens / seq_lens_cpu / seq_lens_sum / -- # req_pool_indices / out_cache_loc when the runtime mode is IDLE, -- # so IDLE and active DECODE are different python branches and must -- # not share a captured graph. -- self._metadata_glue.run( -- attn_backend, -- fb_view, -- ( -- bs, -- str(self.capture_forward_mode), -- str(fb_view.actual_forward_mode), -- ), -+ early.discard() -+ return False -+ early.stage( -+ glue=self._metadata_glue, -+ key=key, -+ registry=self.buffer_registry, -+ sources=VerifyInputSources( -+ positions=positions, -+ out_cache_loc=out_cache_loc, -+ req_pool_indices=req_pool_indices, -+ seq_lens=seq_lens, -+ ), -+ after=after, -+ ) -+ return True -+ -+ def _take_early_verify_metadata( -+ self, forward_batch: ForwardBatch, *, raw_bs: int, bs: int, is_ragged: bool, key -+ ) -> bool: -+ early = self._early_verify_metadata -+ if early is None: -+ return False -+ if is_ragged or raw_bs != bs or not self._metadata_glue.is_captured(key): -+ early.discard() -+ return False -+ return early.take(key=key, forward_batch=forward_batch) -+ -+ def _copy_replay_inputs(self, forward_batch: ForwardBatch) -> None: -+ prefilled = self._prefilled_inputs -+ self._prefilled_inputs = None -+ # The plan-time load (or the early stage it took) filled these from the very -+ # same tensors. -+ if prefilled is None or forward_batch.input_ids is not prefilled[0]: -+ self.buffers.input_ids[: self.raw_num_token].copy_(forward_batch.input_ids) -+ if prefilled is None or forward_batch.positions is not prefilled[1]: -+ self.buffers.positions[: self.raw_num_token].copy_(forward_batch.positions) -+ if prefilled is not None: -+ self._note_prefilled_input_skip() -+ -+ def _note_prefilled_input_skip(self) -> None: -+ self.num_prefilled_input_skips += 1 -+ if self.num_prefilled_input_skips == 1: -+ logger.info( -+ "Pre-planned verify replay skipped its input_ids / positions " -+ "re-copy (first step)." - ) -- else: -- attn_backend.init_forward_metadata_out_graph(fb_view) - -- self.raw_bs = raw_bs -- self.raw_num_token = raw_num_token -- self.bs = bs -- if is_ragged: -- self._ragged_graph_size = graph_size_key -+ def _resolve_skips_prefilled_inputs(self) -> bool: -+ """The DSpark target verify runner, whose verify batches are pre-planned by -+ prepare_for_verify and then replayed from the same tensors.""" -+ return ( -+ envs.SGLANG_OPT_DSV41_DSPARK_SKIP_PREFILLED_INPUTS.get() -+ and not self.model_runner.is_draft_worker -+ and self.capture_forward_mode == ForwardMode.TARGET_VERIFY -+ and self.model_runner.spec_algorithm.is_dspark() -+ ) - -- if self.model_runner.hisparse_coordinator is not None: -- self.model_runner.hisparse_coordinator.num_real_reqs.fill_(raw_bs) -+ def _glues_target_verify_metadata(self) -> bool: -+ """Whether this DSpark target verify runner's metadata prep runs through the -+ glue graph: switched on, and its backend declares the prep host-free.""" -+ if ( -+ not envs.SGLANG_OPT_DSV41_TARGET_VERIFY_METADATA_GLUE.get() -+ or self.model_runner.is_draft_worker -+ or self.capture_forward_mode != ForwardMode.TARGET_VERIFY -+ or not self.model_runner.spec_algorithm.is_dspark() -+ ): -+ return False -+ why = self.attn_backend.glue_target_verify_metadata() -+ if why: -+ logger.info("Target verify metadata glue graph off: %s.", why) -+ return False -+ logger.info("Target verify metadata prep through the glue graph, one per key.") -+ return True -+ -+ def _maybe_log_draft_glue(self) -> None: -+ glue = self._metadata_glue -+ steps = glue.replays + glue.eager -+ if steps >= self._draft_glue_logged + DRAFT_GLUE_LOG_EVERY: -+ self._draft_glue_logged = steps -+ logger.debug( -+ "%s glue: %d graph replays, %d eager (since warm-up)", -+ "target verify" if self._target_metadata_glue else "draft", -+ glue.replays, -+ glue.eager, -+ ) - -- variant_label = self._resolve_lora_variant(forward_batch) -- attention_variant = self._resolve_attention_variant(forward_batch, bs) -- stream_idx = get_current_stream_idx() if self.enable_pdmux else None -- self._replay_graph_key = self._make_graph_key( -- graph_size_key, stream_idx, variant_label, attention_variant -- ) -+ def _glue_draft_inputs(self, fb_view) -> None: -+ """The draft glue graph reads its inputs by address: out_cache_loc from the -+ registry slot fill_from just wrote, not the step's own (fresh) tensor.""" -+ if ( -+ self._draft_metadata_glue or self._target_metadata_glue -+ ) and fb_view.out_cache_loc is not None: -+ n = fb_view.out_cache_loc.shape[0] -+ fb_view.out_cache_loc = self.buffers.out_cache_loc[:n] - - def _ragged_graph_num_tokens(self, total_verify_tokens: int) -> int: - from sglang.srt.speculative.ragged_verify import round_up_grid -diff --git a/python/sglang/srt/model_executor/runner/early_verify_metadata.py b/python/sglang/srt/model_executor/runner/early_verify_metadata.py -new file mode 100644 -index 0000000000..81bc9c9db7 ---- /dev/null -+++ b/python/sglang/srt/model_executor/runner/early_verify_metadata.py -@@ -0,0 +1,149 @@ -+"""Target-verify attention metadata staged during the draft forward -+(SGLANG_OPT_DSV41_TARGET_METADATA_EARLY). -+ -+The verify inputs the metadata reads (positions, write locations, seq lens and -+req pool indices) are final once the decode head has run. ``stage``, which the host -+issues right after it launches the draft graph, copies them into the verify graph's -+buffers and replays the runner's captured metadata glue graph on a side stream that -+waits only for the head, so the GPU runs it beside the draft; the verify replay -+orders itself after that stream (``take``). Issued after the draft launch, the stage -+replaces the fill and glue replay the host would otherwise run before the verify, -+instead of adding host time before the draft. -+ -+Contract: -+ -+- The side stream first waits for the head's event, recorded on the current stream -+ after the previous verify replay, which has therefore finished reading the buffers -+ it rewrites. -+- The staged slots are private to the verify runner (never shared through the -+ process-wide input-buffer pool), so the draft graph neither reads nor writes -+ them; the glue graph writes only the verify backend's metadata. -+- ``take`` accepts the staged work only for the same glue key and the very same -+ source views; otherwise the current stream still waits for the side stream and -+ the runner refills and re-runs the glue graph itself. -+- Every staged record ends in a wait (``take`` or ``discard``) on the current -+ stream before anyone else refills the buffers. -+""" -+ -+from __future__ import annotations -+ -+import logging -+from typing import Any, Dict, Optional -+ -+import msgspec -+import torch -+ -+from sglang.srt.model_executor.cuda_graph_buffer_registry import ( -+ CudaGraphBufferRegistry, -+ same_tensor_view, -+) -+from sglang.srt.model_executor.runner.metadata_glue_graph import MetadataGlueGraph -+ -+logger = logging.getLogger(__name__) -+ -+ -+class VerifyInputSources(msgspec.Struct, frozen=True): -+ # input_ids is not staged: the draft graph may write it in place (mid fold). -+ positions: torch.Tensor -+ out_cache_loc: torch.Tensor -+ req_pool_indices: torch.Tensor -+ seq_lens: torch.Tensor -+ -+ -+STAGED_SLOTS = frozenset(VerifyInputSources.__struct_fields__) -+ -+ -+class _StagedVerifyInputs(msgspec.Struct, frozen=True): -+ key: Any -+ sources: VerifyInputSources -+ -+ -+class EarlyVerifyMetadata: -+ def __init__(self, *, device, log_every: int) -> None: -+ self._stream = torch.cuda.Stream(device=device) -+ self._done = torch.cuda.Event() -+ self._staged: Optional[_StagedVerifyInputs] = None -+ self._log_every = log_every -+ self.staged_ct = 0 -+ self.taken_ct = 0 -+ self.rejected_ct = 0 -+ # Per attention variant: [replays that took the staged metadata, replays]. -+ self.variant_cts: Dict[Any, list] = {} -+ -+ def stage( -+ self, -+ *, -+ glue: MetadataGlueGraph, -+ key, -+ registry: CudaGraphBufferRegistry, -+ sources: VerifyInputSources, -+ after: torch.cuda.Event, -+ ) -> None: -+ self.discard() -+ self._stream.wait_event(after) -+ slot_sources = msgspec.structs.asdict(sources) -+ with torch.cuda.stream(self._stream): -+ registry.copy_slots(slot_sources) -+ glue.replay(key) -+ self._done.record() -+ for src in slot_sources.values(): -+ src.record_stream(self._stream) -+ self._staged = _StagedVerifyInputs(key=key, sources=sources) -+ self.staged_ct += 1 -+ if self.staged_ct == 1 or self.staged_ct % self._log_every == 0: -+ logger.debug( -+ "Target verify metadata staged on the side stream: %d staged, " -+ "%d taken, %d rejected.", -+ self.staged_ct, -+ self.taken_ct, -+ self.rejected_ct, -+ ) -+ -+ def take(self, *, key, forward_batch) -> bool: -+ """True when this replay's inputs are the staged ones: the fill skips -+ ``STAGED_SLOTS`` and the glue graph already ran for ``key``.""" -+ staged = self._staged -+ if staged is None: -+ return False -+ self.discard() -+ src = staged.sources -+ matches = staged.key == key and all( -+ cur is not None and same_tensor_view(cur, staged_src) -+ for cur, staged_src in ( -+ (forward_batch.positions, src.positions), -+ (forward_batch.out_cache_loc, src.out_cache_loc), -+ (forward_batch.req_pool_indices, src.req_pool_indices), -+ (forward_batch.seq_lens, src.seq_lens), -+ ) -+ ) -+ if matches: -+ self.taken_ct += 1 -+ else: -+ self.rejected_ct += 1 -+ if self.rejected_ct == 1: -+ logger.info( -+ "Staged target verify metadata did not match the replay " -+ "(key %s vs %s); refilling on the main stream.", -+ staged.key, -+ key, -+ ) -+ return matches -+ -+ def count_variant(self, variant, *, taken: bool) -> None: -+ cts = self.variant_cts.setdefault(variant, [0, 0]) -+ cts[0] += taken -+ cts[1] += 1 -+ if cts[1] % self._log_every == 0: -+ logger.debug( -+ "Target verify replays of attention variant %s with staged metadata: " -+ "%d of %d.", -+ variant, -+ cts[0], -+ cts[1], -+ ) -+ -+ def discard(self) -> None: -+ """Order the current stream after any staged side-stream work.""" -+ if self._staged is not None: -+ torch.cuda.current_stream().wait_event(self._done) -+ self._staged = None -diff --git a/python/sglang/srt/model_executor/runner/metadata_glue_graph.py b/python/sglang/srt/model_executor/runner/metadata_glue_graph.py -index 1a6436b974..3f6cc1f135 100644 ---- a/python/sglang/srt/model_executor/runner/metadata_glue_graph.py -+++ b/python/sglang/srt/model_executor/runner/metadata_glue_graph.py -@@ -47,6 +47,10 @@ class MetadataGlueGraph: - def __init__(self, device): - self.device = device - self.disabled = False -+ # Since the first warm-up: prep steps served by a graph replay, and steps -+ # that ran eagerly after it (capture failure, disabled, or never routed here). -+ self.replays = 0 -+ self.eager = 0 - self._states: Dict[Any, dict] = {} - self._capture_stream = None - -@@ -55,6 +59,12 @@ class MetadataGlueGraph: - static buffers and backend state may have been rebuilt).""" - self._states.clear() - -+ def note_not_routed(self) -> None: -+ """A replay the caller prepared eagerly without calling ``run`` (padding, -+ TBO, pdmux, LoRA, disabled).""" -+ if self._states or self.disabled: -+ self.eager += 1 -+ - @staticmethod - def _leaves(attn_backend) -> List[Any]: - backends = [attn_backend] -@@ -62,6 +72,22 @@ class MetadataGlueGraph: - backends.extend(attn_backend.attn_backend_list) - return backends - -+ def is_captured(self, key) -> bool: -+ st = self._states.get(key) -+ return not self.disabled and st is not None and st["graph"] is not None -+ -+ def reinstall(self, key) -> None: -+ """Point each backend at the metadata ``key``'s graph writes.""" -+ for backend, metadata in self._states[key]["meta"]: -+ backend.forward_metadata = metadata -+ -+ def replay(self, key) -> None: -+ """Replay ``key``'s captured prep on the current stream (a staging side stream -+ included); the caller reinstalls its metadata before the forward.""" -+ self.reinstall(key) -+ self._states[key]["graph"].replay() -+ self.replays += 1 -+ - def run(self, attn_backend, fb_view, key) -> None: - """Run ``init_forward_metadata_out_graph`` for this replay, through the - captured glue graph once it is ready.""" -@@ -74,6 +100,7 @@ class MetadataGlueGraph: - for backend, metadata in st["meta"]: - backend.forward_metadata = metadata - st["graph"].replay() -+ self.replays += 1 - return - - if st["warmups"] < self.NUM_WARMUP: -@@ -85,7 +112,10 @@ class MetadataGlueGraph: - self._capture_stream = torch.cuda.Stream() - graph = torch.cuda.CUDAGraph() - try: -- with torch.cuda.graph(graph, stream=self._capture_stream): -+ # captured while serving: other threads may use CUDA meanwhile -+ with torch.cuda.graph( -+ graph, stream=self._capture_stream, capture_error_mode="thread_local" -+ ): - attn_backend.init_forward_metadata_out_graph(fb_view) - except Exception: - logger.warning( -@@ -95,6 +125,7 @@ class MetadataGlueGraph: - exc_info=True, - ) - self.disabled = True -+ self.eager += 1 - # Ops under a failed capture were recorded, not executed — run - # this step's prep for real. - attn_backend.init_forward_metadata_out_graph(fb_view) -diff --git a/python/sglang/srt/model_executor/runner_utils/forked_metadata_prep.py b/python/sglang/srt/model_executor/runner_utils/forked_metadata_prep.py -new file mode 100644 -index 0000000000..8b6494efeb ---- /dev/null -+++ b/python/sglang/srt/model_executor/runner_utils/forked_metadata_prep.py -@@ -0,0 +1,34 @@ -+"""The DSpark draft graph's in-graph metadata prep forked onto a side stream -+(SGLANG_OPT_DSV41_DSPARK_DRAFT_PREP_FORK): embedding and the first layer's -+pre-attention run meanwhile, and the first draft attention joins it before it -+stores KV or reads the attention metadata.""" -+ -+from __future__ import annotations -+ -+from typing import Callable, Optional -+ -+import torch -+ -+_pending_join: Optional[torch.cuda.Event] = None -+ -+ -+def fork_in_graph_metadata_prep( -+ *, stream: torch.cuda.Stream, done: torch.cuda.Event, prep: Callable[[], None] -+) -> None: -+ global _pending_join -+ assert _pending_join is None, "previous forked metadata prep was never joined" -+ stream.wait_stream(torch.cuda.current_stream()) -+ with torch.cuda.stream(stream): -+ prep() -+ done.record() -+ _pending_join = done -+ -+ -+def join_in_graph_metadata_prep() -> bool: -+ """Make the current stream wait for a pending forked prep; True if one was.""" -+ global _pending_join -+ if _pending_join is None: -+ return False -+ torch.cuda.current_stream().wait_event(_pending_join) -+ _pending_join = None -+ return True -diff --git a/python/sglang/srt/models/deepseek_v4_dspark.py b/python/sglang/srt/models/deepseek_v4_dspark.py -index bcebe99303..0b0a8c676b 100644 ---- a/python/sglang/srt/models/deepseek_v4_dspark.py -+++ b/python/sglang/srt/models/deepseek_v4_dspark.py -@@ -851,9 +851,16 @@ class DeepseekV4ForCausalLMDSpark(nn.Module): - positions: torch.Tensor, - pool: DeepSeekV4TokenToKVPool, - ) -> None: -+ kvs = self.project_commit_kv(main_hidden=main_hidden, pool=pool) -+ self.store_commit_kv(kvs=kvs, swa_loc=swa_loc, positions=positions, pool=pool) -+ -+ def project_commit_kv( -+ self, *, main_hidden: torch.Tensor, pool: DeepSeekV4TokenToKVPool -+ ) -> List[torch.Tensor]: -+ """The context rows' per-stage KV, before norm / rope / store; reads no KV -+ location, so it can run before the accept decides what is committed.""" - main_x = self.project_target_hidden(main_hidden) -- swa_loc = swa_loc.to(torch.int32) -- kvs = CommitKvProj.execute( -+ return CommitKvProj.execute( - main_x=main_x, - wkv_linears=[stage.self_attn.wkv for stage in self.stages], - # The FlashMLA writer reads an explicit KV row stride, so views are fine. -@@ -863,6 +870,16 @@ class DeepseekV4ForCausalLMDSpark(nn.Module): - and not pool.uniform_fp8 - ), - ) -+ -+ def store_commit_kv( -+ self, -+ *, -+ kvs: List[torch.Tensor], -+ swa_loc: torch.Tensor, -+ positions: torch.Tensor, -+ pool: DeepSeekV4TokenToKVPool, -+ ) -> None: -+ swa_loc = swa_loc.to(torch.int32) - # Under unified_kv the swa_kv_pool is None; the caller passes a unified - # ring loc (state_slot * ring + pos % ring, -1 for uncommitted) so the - # store just needs to target the bf16 ring instead of the fp8 flashmla -diff --git a/python/sglang/srt/speculative/dspark_components/dspark_deferred_commit.py b/python/sglang/srt/speculative/dspark_components/dspark_deferred_commit.py -new file mode 100644 -index 0000000000..f34686ed52 ---- /dev/null -+++ b/python/sglang/srt/speculative/dspark_components/dspark_deferred_commit.py -@@ -0,0 +1,300 @@ -+"""The draft context-KV commit of a static verify, split around the accept -+(SGLANG_DSPARK_DEFER_CONTEXT_KV). -+ -+The commit projects the committed rows' target hidden into each draft stage's KV -+(GEMMs, independent of the accept) and stores the committed rows (needs the accept's -+commit lengths). In a static verify graph the projection is forked onto a side stream -+at the target's logits processor (a forward pre-hook, which SGLang's forward and a -+megakernel's head both call), so it overlaps the LM head and the accept; the static -+epilogue joins it and stages the store's arguments (write locations, positions, gated -+commit lengths, ring slots). The next captured draft graph runs the stores on a side -+stream forked at its head (a capture head hook); the draft's first KV store joins -+them (``join``, from the draft attention backend's ``get_swa_out_cache_loc``, which -+SGLang's draft attention and a megakernel's both reach on the store's stream). Any -+other forward runs the stores eagerly first. -+ -+Contract: -+ -+- Every write disarms the staging (commit lengths 0), so a staging is written once. -+- A forward that may write or read draft KV (prefill, draft extend, an eager draft) -+ runs after the pending write; a draft graph whose rows miss staged ones is preceded -+ by an eager write of every staged row. -+- Nothing reads draft KV between the verify and the next draft forward. -+""" -+ -+from __future__ import annotations -+ -+import logging -+from typing import List, Optional -+ -+import torch -+ -+from sglang.srt.environ import envs -+from sglang.srt.layers.aux_hidden_states import pack_aux_hidden_states -+ -+logger = logging.getLogger(__name__) -+ -+# Draft forwards between two counter lines. -+_LOG_EVERY = 4096 -+ -+ -+class DeferredContextCommit: -+ def __init__( -+ self, -+ *, -+ max_bs: int, -+ stride: int, -+ device, -+ kv_injector, -+ ) -> None: -+ self.stride = stride -+ self._max_rows = max_bs * stride -+ self._device = device -+ self._kv_injector = kv_injector -+ # Per draft stage [max_rows, kv width], made at the first (warmup) projection. -+ self.kvs: Optional[List[torch.Tensor]] = None -+ rows = self._max_rows -+ self.cache_loc = torch.zeros((rows,), dtype=torch.int64, device=device) -+ self.positions = torch.zeros((rows,), dtype=torch.int64, device=device) -+ # 0 for every request past the staged ones: their rows are not written. -+ self.commit_lens = torch.zeros((max_bs,), dtype=torch.int32, device=device) -+ self.state_slot = torch.zeros((rows,), dtype=torch.int64, device=device) -+ # Host, set at the first staging: the injector writes a per-request SWA ring. -+ self._with_state_slot = False -+ # SGLANG_OPT_DSV41_DSPARK_ONE_LAUNCH_COMMIT_STAGE: stage() in one Triton launch. -+ self._one_launch_stage = ( -+ envs.SGLANG_OPT_DSV41_DSPARK_ONE_LAUNCH_COMMIT_STAGE.get() -+ and torch.device(device).type == "cuda" -+ ) -+ # Side streams and events, made at the first use. -+ self._proj_stream: Optional[torch.cuda.Stream] = None -+ self._proj_done: Optional[torch.cuda.Event] = None -+ self._store_stream: Optional[torch.cuda.Stream] = None -+ self._store_done: Optional[torch.cuda.Event] = None -+ # Host: requests a static verify staged since the last write (0: nothing pending). -+ self.staged_bs = 0 -+ # Host: a forked projection the static epilogue has not joined yet. -+ self._proj_unjoined = False -+ # Host, capture only: forked stores the draft's first KV store has not joined yet. -+ self._fork_unjoined = False -+ # Draft graph batch sizes whose capture recorded the forked stores. -+ self._forked_bs: set[int] = set() -+ self.num_written_in_graph = 0 -+ self.num_written_eagerly = 0 -+ self._eager_reasons: dict[str, int] = {} -+ self._draft_forwards = 0 -+ -+ @property -+ def pending(self) -> bool: -+ return self.staged_bs > 0 -+ -+ def _pool(self): -+ return self._kv_injector.draft_model_runner.token_to_kv_pool -+ -+ # Verify side: the projection (forked at the logits processor) and the staging. -+ -+ def logits_pre_hook(self, module, args, kwargs) -> None: -+ """Forward pre-hook on the target's logits processor: in a static verify -+ graph (capture or warmup), fork the projection of the DSpark hidden.""" -+ from sglang.srt.model_executor.runner import get_is_capture_mode -+ -+ metadata = args[3] if len(args) > 3 else kwargs.get("logits_metadata") -+ aux = args[4] if len(args) > 4 else kwargs.get("aux_hidden_states") -+ if ( -+ aux is None -+ or not metadata.forward_mode.is_target_verify() -+ or not get_is_capture_mode() -+ ): -+ return -+ if self._proj_stream is None: -+ self._proj_stream = torch.cuda.Stream(device=self._device) -+ self._proj_done = torch.cuda.Event() -+ self._proj_stream.wait_stream(torch.cuda.current_stream()) -+ with torch.cuda.stream(self._proj_stream), torch.inference_mode(): -+ kvs = self._kv_injector.draft_model.project_commit_kv( -+ main_hidden=pack_aux_hidden_states(aux), pool=self._pool() -+ ) -+ if self.kvs is None: -+ assert not _capturing(), "the commit KV buffers are made at a warmup" -+ self.kvs = [kv.new_zeros((self._max_rows, kv.shape[1])) for kv in kvs] -+ n = kvs[0].shape[0] -+ for buf, kv in zip(self.kvs, kvs): -+ buf[:n].copy_(kv) -+ self._proj_done.record() -+ self._proj_unjoined = True -+ -+ def join_projection(self) -> bool: -+ """In the static epilogue: wait for this graph's projection; False if none ran.""" -+ if not self._proj_unjoined: -+ return False -+ torch.cuda.current_stream().wait_event(self._proj_done) -+ self._proj_unjoined = False -+ return True -+ -+ def stage( -+ self, -+ *, -+ cache_loc: torch.Tensor, -+ positions: torch.Tensor, -+ commit_lens: torch.Tensor, -+ state_slot: Optional[torch.Tensor], -+ ) -> None: -+ """Recorded in a static verify graph of ``commit_lens.shape[0]`` requests.""" -+ bs = commit_lens.shape[0] -+ n = bs * self.stride -+ self._with_state_slot = state_slot is not None -+ if self._one_launch_stage: -+ from sglang.kernels.ops.speculative.dspark.stage_commit import stage_commit -+ -+ stage_commit( -+ cache_loc_dst=self.cache_loc, -+ positions_dst=self.positions, -+ commit_lens_dst=self.commit_lens, -+ state_slot_dst=self.state_slot if state_slot is not None else None, -+ cache_loc=cache_loc, -+ positions=positions, -+ commit_lens=commit_lens, -+ state_slot=state_slot, -+ rows=n, -+ ) -+ return -+ self.cache_loc[:n].copy_(cache_loc[:n]) -+ self.positions[:n].copy_(positions[:n]) -+ self.commit_lens[:bs].copy_(commit_lens) -+ self.commit_lens[bs:].zero_() -+ if state_slot is not None: -+ self.state_slot[:n].copy_(state_slot[:n]) -+ -+ def note_static_verify(self, live_bs: int) -> None: -+ """Host, after a static verify graph ran ``live_bs`` requests.""" -+ self.staged_bs = live_bs -+ -+ # Draft side: the gated stores. -+ -+ def write(self, bs: Optional[int] = None) -> None: -+ """The staged stores over the first ``bs`` requests (default all), then a -+ disarm, on the current stream.""" -+ if self.kvs is None: -+ return -+ bs = self.commit_lens.shape[0] if bs is None else bs -+ n = bs * self.stride -+ pool = self._pool() -+ cache_loc = self.cache_loc[:n] -+ positions = self.positions[:n] -+ swa_loc = self._kv_injector.committed_swa_loc( -+ pool=pool, -+ cache_loc=cache_loc, -+ positions=positions, -+ cache_loc_2d=cache_loc.view(bs, self.stride), -+ commit_lens=self.commit_lens[:bs], -+ state_slot=self.state_slot[:n] if self._with_state_slot else None, -+ ) -+ with torch.inference_mode(): -+ self._kv_injector.draft_model.store_commit_kv( -+ kvs=[kv[:n] for kv in self.kvs], -+ swa_loc=swa_loc, -+ positions=positions, -+ pool=pool, -+ ) -+ self.commit_lens.zero_() -+ -+ def flush(self, reason: str = "prefill") -> None: -+ """Host: write a pending staging now (an eager forward follows).""" -+ # A graph captured here would replay the write on every later replay. -+ if self.pending and not _capturing(): -+ self.write() -+ self.staged_bs = 0 -+ self.num_written_eagerly += 1 -+ self._eager_reasons[reason] = self._eager_reasons.get(reason, 0) + 1 -+ -+ def before_draft_forward(self, graph_bs: Optional[int]) -> None: -+ """Host, before a draft forward: a graph of ``graph_bs`` requests (None: eager) -+ writes only its own rows, so anything it would miss is written first.""" -+ self._draft_forwards += 1 -+ if self._draft_forwards % _LOG_EVERY == 0: -+ logger.debug( -+ "DSpark deferred context-KV commit: %d written in draft graphs, " -+ "%d eagerly %s", -+ self.num_written_in_graph, -+ self.num_written_eagerly, -+ self._eager_reasons, -+ ) -+ if graph_bs is None: -+ self.flush("eager draft") -+ elif graph_bs not in self._forked_bs: -+ self.flush("draft graph without the fork") -+ elif self.staged_bs > graph_bs: -+ self.flush("draft graph rows") -+ -+ def after_draft_forward(self, graph_ran: bool) -> None: -+ # A pending staging past before_draft_forward is one the graph writes. -+ if graph_ran and self.pending: -+ self.staged_bs = 0 -+ self.num_written_in_graph += 1 -+ -+ def capture_head_hook(self, graph_runner, forward_batch) -> None: -+ """First inside each draft decode graph capture (and its warmups).""" -+ if not forward_batch.forward_mode.is_target_verify(): -+ return -+ bs = forward_batch.batch_size -+ if not _capturing(): -+ # Warmups write the disarmed staging, so its kernels compile before capture. -+ if not self.pending: -+ self.write(bs) -+ return -+ if self._store_stream is None: -+ self._store_stream = torch.cuda.Stream(device=self._device) -+ self._store_done = torch.cuda.Event() -+ self._store_stream.wait_stream(torch.cuda.current_stream()) -+ with torch.cuda.stream(self._store_stream): -+ self.write(bs) -+ self._store_done.record() -+ self._fork_unjoined = True -+ self._forked_bs.add(bs) -+ logger.info( -+ "DSpark draft graph bs=%d: deferred context-KV commit forked at its head", -+ bs, -+ ) -+ -+ def join(self) -> None: -+ """At the draft's first KV store: the store waits for the forked stores.""" -+ if self._fork_unjoined and _capturing(): -+ torch.cuda.current_stream().wait_event(self._store_done) -+ self._fork_unjoined = False -+ logger.info( -+ "DSpark draft graph: deferred context-KV commit joined at the first KV store" -+ ) -+ -+ def disarm(self) -> None: -+ """Drop whatever warmups or captures staged on placeholder inputs.""" -+ self.commit_lens.zero_() -+ self.staged_bs = 0 -+ self._fork_unjoined = False -+ self._proj_unjoined = False -+ -+ -+def _capturing() -> bool: -+ return torch.cuda.is_available() and torch.cuda.is_current_stream_capturing() -+ -+ -+def defer_context_kv_refusal( -+ *, -+ static_verify: bool, -+ draft_is_moe: bool, -+ unified_kv: bool, -+ unified_memory: bool, -+ hicache: bool, -+ disaggregated: bool, -+ attn_dp: bool, -+) -> str: -+ """Why the deferred commit cannot run here, or "".""" -+ reasons = ( -+ (not static_verify, "the verify is not static (SGLANG_RAGGED_VERIFY_MODE)"), -+ (not draft_is_moe, "the draft has no MoE layers"), -+ (unified_kv, "unified KV writes the draft window through its ring"), -+ (unified_memory, "the unified memory pool compacts KV between steps"), -+ (hicache, "a HiCache storage backend moves KV between steps"), -+ (disaggregated, "PD disaggregation transfers KV between steps"), -+ (attn_dp, "attention DP runs idle draft forwards"), -+ ) -+ return "; ".join(why for refused, why in reasons if refused) -diff --git a/python/sglang/srt/speculative/dspark_components/dspark_draft.py b/python/sglang/srt/speculative/dspark_components/dspark_draft.py -index a02bb30e10..aef562ce60 100644 ---- a/python/sglang/srt/speculative/dspark_components/dspark_draft.py -+++ b/python/sglang/srt/speculative/dspark_components/dspark_draft.py -@@ -1,5 +1,6 @@ - from __future__ import annotations - -+import bisect - import functools - import logging - from typing import TYPE_CHECKING, NamedTuple, Optional -@@ -77,6 +78,9 @@ class DraftProposal(msgspec.Struct, frozen=True): - confidence: Optional[torch.Tensor] = None - confidence_raw: Optional[torch.Tensor] = None - folded: bool = False -+ # [bs, gamma + 1] ``[anchor | draft tokens]`` from the draft graph tail; None -+ # when the caller builds them. -+ verify_ids: Optional[torch.Tensor] = None - - - def select_draft_hidden_without_anchor( -@@ -164,6 +168,9 @@ def resolve_draft_params( - return DraftParams(temperatures, greedy_mask, step_temperatures) - - -+# Arbitrary; how often the proposer logs its restage-skip count, in graph steps. -+STAGED_PARAMS_LOG_EVERY = 500 -+ - # XORed into the server seed so the draft noise differs from other samplers'. - _DRAFT_NOISE_DOMAIN = 0x2D2A9C317E44B1F3 - -@@ -317,6 +324,11 @@ def sample_draft_block( - - - class DraftBlockProposer: -+ _staged_params_key = None -+ num_staged_params_skips = 0 -+ num_staged_params_calls = 0 -+ deferred_commit = None -+ - def __init__( - self, - *, -@@ -347,9 +359,16 @@ class DraftBlockProposer: - ) - self._draft_sampler = None - self._dp_moe_sync = dp_moe_sync -+ # SGLANG_DSPARK_DEFER_CONTEXT_KV's staged commit, set by the worker. -+ self.deferred_commit = None - # Persistent (bs, gamma) mask-token buffer: only column 0 (the bonus - # token) changes per step, so avoid a fresh torch.full every decode. - self._draft_block_ids_buf: Optional[torch.Tensor] = None -+ # (sampler, bs, temperatures, top_ks) last staged: SamplingBatchInfo rebinds -+ # these tensors when the batch changes, never edits them in place -+ self._staged_params_key: Optional[tuple] = None -+ self.num_staged_params_skips = 0 -+ self.num_staged_params_calls = 0 - self._num_token_non_padded = ( - torch.empty((1,), dtype=torch.int32, device=self.draft_model_runner.device) - if enable_num_token_non_padded() -@@ -363,6 +382,34 @@ class DraftBlockProposer: - def attach_draft_sampler(self, draft_sampler) -> None: - self._draft_sampler = draft_sampler - -+ def _stage_sampling_params(self, draft_sampler, *, bs: int, sampling_info) -> None: -+ """The draft graph's sampling params, restaged only when the sampler, bs or -+ the batch's temperature / top-k tensors changed since the last stage.""" -+ key = ( -+ draft_sampler, -+ bs, -+ None if sampling_info is None else sampling_info.temperatures, -+ None if sampling_info is None else sampling_info.top_ks, -+ ) -+ staged = self._staged_params_key -+ self.num_staged_params_calls += 1 -+ skip = ( -+ staged is not None -+ and staged[1] == bs -+ and all(staged[i] is key[i] for i in (0, 2, 3)) -+ ) -+ self.num_staged_params_skips += skip -+ if self.num_staged_params_calls % STAGED_PARAMS_LOG_EVERY == 0: -+ logger.debug( -+ "DSpark draft: sampling params restage skipped on %d of %d steps", -+ self.num_staged_params_skips, -+ self.num_staged_params_calls, -+ ) -+ if skip: -+ return -+ draft_sampler.stage_sampling_params(bs=bs, sampling_info=sampling_info) -+ self._staged_params_key = key -+ - def _base_logits_context(self): - return draft_tp_context(self._dp_moe_sync) - -@@ -376,6 +423,7 @@ class DraftBlockProposer: - device: str, - target_model, - sampling_info, -+ anchor_prepared: bool = False, - ) -> DraftProposal: - embed_module = unwrap_lora_layer( - self.draft_model.embed_tokens -@@ -392,10 +440,11 @@ class DraftBlockProposer: - embed_module=embed_module, - draft_sampler=draft_sampler, - sampling_info=sampling_info, -+ anchor_prepared=anchor_prepared, - ) - draft_block_ids = fwd.draft_block_ids - -- confidence = confidence_raw = None -+ confidence = confidence_raw = verify_ids = None - folded = False - if ( - envs.SGLANG_DSPARK_FOLDED_PROPOSAL.get() -@@ -415,6 +464,8 @@ class DraftBlockProposer: - if draft_sampler.confidence_out is not None: - confidence = draft_sampler.confidence_out[:bs] - confidence_raw = draft_sampler.confidence_raw_out[:bs] -+ if draft_sampler.verify_ids is not None: -+ verify_ids = draft_sampler.verify_ids[:bs] - else: - with self._base_logits_context(): - base_logits, confidence_features = self.draft_model.compute_base_logits( -@@ -449,6 +500,7 @@ class DraftBlockProposer: - confidence=confidence, - confidence_raw=confidence_raw, - folded=folded, -+ verify_ids=verify_ids, - ) - - def run_idle_participation(self, batch: ScheduleBatch) -> None: -@@ -477,6 +529,19 @@ class DraftBlockProposer: - with torch.inference_mode(): - self.draft_model_runner.forward(idle_batch) - -+ def draft_block_ids_view(self, *, bs: int, device) -> torch.Tensor: -+ """The ``[bs, query_token_num]`` draft input ids: mask tokens past column 0.""" -+ buf = self._draft_block_ids_buf -+ if buf is None or buf.shape[0] < bs or buf.device != torch.device(device): -+ buf = torch.full( -+ (bs, self.query_token_num), -+ int(self._mask_token_id), -+ dtype=torch.long, -+ device=device, -+ ) -+ self._draft_block_ids_buf = buf -+ return buf[:bs] -+ - def _run_forward( - self, - *, -@@ -488,6 +553,7 @@ class DraftBlockProposer: - embed_module, - draft_sampler=None, - sampling_info=None, -+ anchor_prepared: bool = False, - ) -> DraftForwardResult: - gamma = self.gamma - query_token_num = self.query_token_num -@@ -495,18 +561,9 @@ class DraftBlockProposer: - positions_2d = verify_window.positions_2d - verify_cache_loc_2d = verify_window.verify_cache_loc_2d - -- buf = self._draft_block_ids_buf -- if buf is None or buf.shape[0] < bs or buf.device != prefix_lens.device: -- buf = torch.full( -- (bs, query_token_num), -- int(self._mask_token_id), -- dtype=torch.long, -- device=device, -- ) -- self._draft_block_ids_buf = buf -- draft_block_ids = buf[:bs] -- -- draft_block_ids[:, 0].copy_(draft_input.bonus_tokens.view(-1)) -+ draft_block_ids = self.draft_block_ids_view(bs=bs, device=prefix_lens.device) -+ if not anchor_prepared: -+ draft_block_ids[:, 0].copy_(draft_input.bonus_tokens.view(-1)) - draft_positions = positions_2d[:, :query_token_num].reshape(-1) - draft_cache_loc = verify_cache_loc_2d[:, :query_token_num].reshape(-1) - -@@ -554,14 +611,29 @@ class DraftBlockProposer: - ) - self._fill_dp_moe_sync_metadata(draft_forward_batch, batch) - graph_runner = self.draft_model_runner.decode_cuda_graph_runner -- if ( -- draft_sampler is not None -- and graph_runner is not None -- and graph_runner.can_run_graph(draft_forward_batch) -- ): -- draft_sampler.stage_sampling_params(bs=bs, sampling_info=sampling_info) -+ runs_graph = graph_runner is not None and graph_runner.can_run_graph( -+ draft_forward_batch -+ ) -+ if draft_sampler is not None and runs_graph: -+ self._stage_sampling_params( -+ draft_sampler, bs=bs, sampling_info=sampling_info -+ ) -+ commit = self.deferred_commit -+ if commit is not None: -+ commit.before_draft_forward( -+ graph_bs=( -+ graph_runner.capture_bs[ -+ bisect.bisect_left(graph_runner.capture_bs, bs) -+ ] -+ if runs_graph -+ else None -+ ) -+ ) - with torch.inference_mode(): - draft_out = self.draft_model_runner.forward(draft_forward_batch) -+ if commit is not None: -+ assert draft_out.can_run_graph == runs_graph -+ commit.after_draft_forward(graph_ran=draft_out.can_run_graph) - logits_output = draft_out.logits_output - raw_hidden = logits_output.hidden_states - if raw_hidden is None: -diff --git a/python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py b/python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py -index f93ea04cc3..a85cc53ae9 100644 ---- a/python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py -+++ b/python/sglang/srt/speculative/dspark_components/dspark_draft_sampler.py -@@ -5,6 +5,7 @@ from typing import Callable, Optional - - import torch - -+from sglang.srt.environ import envs - from sglang.srt.layers.dp_attention import get_dp_tp_group - from sglang.srt.megakernels.runtime import megakernel_agree, megakernel_draft_sampler - from sglang.srt.speculative.dspark_components.dspark_draft import ( -@@ -26,6 +27,8 @@ _is_xpu = is_xpu() - class DsparkDraftSampler: - """The eager path's markov block, run as the draft cuda graph's tail.""" - -+ verify_ids = None -+ - def __init__( - self, - *, -@@ -53,6 +56,13 @@ class DsparkDraftSampler: - self.out = torch.empty( - (self.max_bs * self.gamma,), dtype=torch.int64, device=device - ) -+ # [max_bs, gamma + 1] verify ids ([anchor | draft tokens]) written by the -+ # graph tail, so the step skips its eager concat (SGLANG_OPT_DSV41_DSPARK_MID_FOLD). -+ self.verify_ids: Optional[torch.Tensor] = None -+ if envs.SGLANG_OPT_DSV41_DSPARK_MID_FOLD.get(): -+ self.verify_ids = torch.empty( -+ (self.max_bs, self.gamma + 1), dtype=torch.int64, device=device -+ ) - confidence_head = model.confidence_head - if confidence_head is None: - self.confidence_out = self.confidence_raw_out = None -@@ -157,6 +167,12 @@ class DsparkDraftSampler: - ) - self.confidence_out[:bs].copy_(confidence) - self.confidence_raw_out[:bs].copy_(confidence_raw) -+ if self.verify_ids is not None: -+ torch.cat( -+ [anchor.view(bs, 1), self.out[: bs * self.gamma].view(bs, self.gamma)], -+ dim=1, -+ out=self.verify_ids[:bs], -+ ) - - def _markov_block(self, model_hidden, sample_hidden, anchor, bs: int): - base_logits, confidence_features = self.model.compute_base_logits(model_hidden) -diff --git a/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py b/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py -index 24365707a4..a0a3f5ee15 100644 ---- a/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py -+++ b/python/sglang/srt/speculative/dspark_components/dspark_kv_inject.py -@@ -111,18 +111,18 @@ class TargetHiddenKvInjector: - target_hidden_is_projected=target_hidden_is_projected, - ) - -- def _inject_mla( -+ def committed_swa_loc( - self, - *, - pool, -- target_hidden: torch.Tensor, - cache_loc: torch.Tensor, - positions: torch.Tensor, - cache_loc_2d: Optional[torch.Tensor], - commit_lens: Optional[torch.Tensor], - state_slot: Optional[torch.Tensor] = None, - final_pos: Optional[torch.Tensor] = None, -- ) -> None: -+ ) -> torch.Tensor: -+ """The draft SWA rows the committed context tokens store into, -1 elsewhere.""" - if pool.swa_req_ring_size is not None: - swa_loc = self._ring_inject_loc( - pool=pool, -@@ -162,6 +162,29 @@ class TargetHiddenKvInjector: - committed_mask, swa_loc, torch.full_like(swa_loc, -1) - ) - -+ return swa_loc -+ -+ def _inject_mla( -+ self, -+ *, -+ pool, -+ target_hidden: torch.Tensor, -+ cache_loc: torch.Tensor, -+ positions: torch.Tensor, -+ cache_loc_2d: Optional[torch.Tensor], -+ commit_lens: Optional[torch.Tensor], -+ state_slot: Optional[torch.Tensor] = None, -+ final_pos: Optional[torch.Tensor] = None, -+ ) -> None: -+ swa_loc = self.committed_swa_loc( -+ pool=pool, -+ cache_loc=cache_loc, -+ positions=positions, -+ cache_loc_2d=cache_loc_2d, -+ commit_lens=commit_lens, -+ state_slot=state_slot, -+ final_pos=final_pos, -+ ) - with torch.inference_mode(): - self.draft_model.write_target_hidden_kv( - main_hidden=target_hidden, -diff --git a/python/sglang/srt/speculative/dspark_components/dspark_planner.py b/python/sglang/srt/speculative/dspark_components/dspark_planner.py -index 17a342c721..fea10838ef 100644 ---- a/python/sglang/srt/speculative/dspark_components/dspark_planner.py -+++ b/python/sglang/srt/speculative/dspark_components/dspark_planner.py -@@ -788,18 +788,30 @@ def alloc_verify_window( - block_pos_offsets: torch.Tensor, - model_runner, - seq_lens_cpu: Optional[torch.Tensor], -+ bonus: Optional[torch.Tensor] = None, -+ anchor_ids: Optional[torch.Tensor] = None, - ) -> VerifyWindow: - """``seq_lens_cpu``: a host bound on ``batch.seq_lens``, which sizes the -- plan's read table.""" -+ plan's read table. ``anchor_ids``, when given, gets ``bonus`` in column 0 -+ by the same launch (SGLANG_OPT_DSV41_DSPARK_PREPARE_INPUTS_ONCE).""" - prefix_lens = batch.seq_lens - verify_w = verify_num_draft_tokens -- positions_2d = prefix_lens.unsqueeze(1) + block_pos_offsets -+ positions_2d = None -+ if anchor_ids is not None: -+ positions_2d = torch.empty( -+ (bs, verify_w), dtype=torch.int64, device=prefix_lens.device -+ ) - plan = model_runner.kv_index_translator.plan_uniform_extend( - req_pool_indices=batch.req_pool_indices, - seq_lens=prefix_lens, - seq_lens_cpu=seq_lens_cpu, - width=verify_w, -+ positions_out=positions_2d, -+ anchor_src=bonus, -+ anchor_out=anchor_ids, - ) -+ if positions_2d is None: -+ positions_2d = prefix_lens.unsqueeze(1) + block_pos_offsets - verify_cache_loc = plan.write_virtual - return VerifyWindow( - positions_2d=positions_2d, -diff --git a/python/sglang/srt/speculative/dspark_components/dspark_sampling_accept_graph.py b/python/sglang/srt/speculative/dspark_components/dspark_sampling_accept_graph.py -new file mode 100644 -index 0000000000..521c050986 ---- /dev/null -+++ b/python/sglang/srt/speculative/dspark_components/dspark_sampling_accept_graph.py -@@ -0,0 +1,248 @@ -+"""CUDA graphs of the temperature-sampling verify accept of static DSpark decode steps -+(SGLANG_OPT_DSV41_SAMPLING_ACCEPT_GRAPH). -+ -+The static verify graph folds only the greedy accept (DsparkVerifyEpilogue). On an -+all-sampled step the rest ran eagerly after the replay: the draft and target softmax, -+the rejection kernel, the bonus gather, the accept-site TP broadcast, the engram -+history commit, the future relay and the target-hidden KV commit. This module captures -+that region once per verify-graph batch size and replays it right after the verify -+graph. -+ -+The region reads the verify graph's static inputs and outputs (``static_io``) and the -+draft sampler's static buffers, which hold this step's values after both replays, so a -+replay stages nothing. Its accept outputs land in the epilogue's static accept buffers, -+like the greedy fold. Per key the first step runs eagerly (it compiles kernels and warms -+allocations), the second captures, later steps replay. The uniform draws come from -+torch's default generator, whose graph-safe offsets make a replay draw what the eager -+accept draws at the same generator state; with block-wise rejection they come from the -+worker's one RejectionNoise, whose device step counter a replay advances like an eager -+call. The DSPARK_ACCEPT_SAMPLE broadcast stays in -+the region (pynccl inside the graph), so TP ranks agree as in the eager path. With the -+deferred context-KV commit, the verify graph already joined this step's projection, so -+the region stages the stores from it. -+ -+The caller routes only all-sampled steps without top-k / top-p, logit adjustments, -+grammar or a simulated sampled bonus; everything else keeps the eager accept. -+""" -+ -+from __future__ import annotations -+ -+import logging -+from collections.abc import Callable, Hashable -+from functools import partial -+from typing import Optional -+ -+import msgspec -+import torch -+ -+from sglang.kernels.ops.speculative.dspark.blockwise_rejection import RejectionNoise -+from sglang.srt.distributed.parallel_state import graph_capture -+from sglang.srt.speculative.dspark_components.dspark_draft import DraftBlockResult -+from sglang.srt.speculative.dspark_components.dspark_verify import ( -+ AcceptOuts, -+ DsparkVerifyEpilogue, -+ StaticVerifyIO, -+ accept_draft_tokens, -+ build_accept_outs, -+) -+from sglang.srt.speculative.spec_tp_sync import SpecTpSync, SpecTpSyncSite -+ -+logger = logging.getLogger(__name__) -+ -+ -+class GraphSamplingInfo(msgspec.Struct, frozen=True): -+ """The SamplingBatchInfo fields the sampling accept reads, for an all-sampled -+ batch without top-k / top-p.""" -+ -+ temperatures: torch.Tensor -+ is_all_greedy: bool = False -+ is_any_greedy: bool = False -+ need_top_k_sampling: bool = False -+ need_top_p_sampling: bool = False -+ -+ -+def sampling_accept_commit_lens( -+ io: StaticVerifyIO, -+ *, -+ verify_lens: torch.Tensor, -+ gate: torch.Tensor, -+ gated: bool, -+ draft_sampler, -+ epilogue: DsparkVerifyEpilogue, -+ tp_sync: SpecTpSync, -+ fused_argmax: bool, -+ block_verification: bool, -+ rejection_noise: Optional[RejectionNoise], -+) -> Optional[torch.Tensor]: -+ """The eager sampling accept and finalize into the epilogue's static buffers; -+ returns the gated commit lengths when ``gated``.""" -+ bs, stride = io.candidates.shape -+ params = draft_sampler.params -+ draft_tokens = io.candidates[:, 1:] -+ draft_block = DraftBlockResult( -+ draft_tokens=draft_tokens, -+ corrected_logits=( -+ None if draft_sampler.greedy_draft else draft_sampler.step_logits[:bs] -+ ), -+ greedy_mask=params.greedy_mask[:bs], -+ temperatures=params.temperatures[:bs], -+ greedy_draft=draft_sampler.greedy_draft, -+ ) -+ correct_len, bonus, cap_trim_lens = accept_draft_tokens( -+ candidates=io.candidates, -+ target_logits=io.logits, -+ draft_block=draft_block, -+ # params.temperatures is the batch's, clamped at 1e-5 (resolve_draft_params). -+ sampling_info=GraphSamplingInfo(temperatures=params.temperatures[:bs]), -+ draft_input=None, -+ gamma=stride - 1, -+ verify_num_draft_tokens=stride, -+ fused_argmax=fused_argmax, -+ block_verification=block_verification, -+ rejection_noise=rejection_noise, -+ ) -+ commit_lens = build_accept_outs( -+ correct_len=correct_len, -+ bonus=bonus, -+ cap_trim_lens=cap_trim_lens, -+ prefix_lens=io.seq_lens[:bs], -+ draft_tokens=draft_tokens.contiguous(), -+ gamma=stride - 1, -+ verify_num_draft_tokens=stride, -+ tp_sync=tp_sync, -+ sync_site=SpecTpSyncSite.DSPARK_ACCEPT_SAMPLE, -+ simulated_correct_len=epilogue.simulated_correct_len, -+ target_logits=io.logits, -+ out=epilogue.read_accept(bs), -+ block_accept_lens_out=epilogue.read_block_accept_lens(bs), -+ ).commit_lens -+ if not gated: -+ return None -+ return torch.minimum(commit_lens, verify_lens.to(torch.int32)) * gate -+ -+ -+class DsparkSamplingAcceptGraph: -+ """Per-batch-size CUDA graphs of the sampling accept region of static verify.""" -+ -+ # One key per verify-graph batch size is expected; more means addresses move, -+ # and the further keys run eagerly. Arbitrary bound. -+ MAX_GRAPHS = 32 -+ -+ def __init__( -+ self, -+ *, -+ epilogue: DsparkVerifyEpilogue, -+ resolve_draft_sampler: Callable[[], Optional[object]], -+ tp_sync: SpecTpSync, -+ fused_argmax: bool, -+ block_verification: bool, -+ device, -+ rejection_noise: Optional[RejectionNoise] = None, -+ ) -> None: -+ self._epilogue = epilogue -+ self._resolve_draft_sampler = resolve_draft_sampler -+ self._tp_sync = tp_sync -+ self._fused_argmax = fused_argmax -+ self._block_verification = block_verification -+ self._rejection_noise = rejection_noise -+ # The region always commits; padded rows are gated by verify_lens. -+ self._gate = torch.ones((1,), dtype=torch.int32, device=device) -+ self._graphs: dict[Hashable, torch.cuda.CUDAGraph] = {} -+ self._warmed_up: set[Hashable] = set() -+ self._pool = None -+ self.disabled = False -+ self.num_replays = 0 -+ # Set by run(): whether this step's region committed the engram history. -+ self.committed_engram = False -+ -+ def run(self, *, bs: int, target_logits: torch.Tensor) -> Optional[AcceptOuts]: -+ """This step's accept through the region, or None when the step must take the -+ eager path. Reads only host state every TP rank holds identically.""" -+ if self.disabled: -+ return None -+ draft_sampler = self._resolve_draft_sampler() -+ if draft_sampler is None or ( -+ not draft_sampler.greedy_draft and draft_sampler.step_logits is None -+ ): -+ return None -+ epilogue = self._epilogue -+ graph_bs = min((b for b in epilogue.static_io if b >= bs), default=None) -+ if graph_bs is None: -+ return None -+ io = epilogue.static_io[graph_bs] -+ # The replayed verify graph must be the one whose buffers were recorded. -+ if target_logits.data_ptr() != io.logits.data_ptr(): -+ return None -+ key = ( -+ graph_bs, -+ io.logits.data_ptr(), -+ draft_sampler.params.temperatures.data_ptr(), -+ 0 -+ if draft_sampler.step_logits is None -+ else draft_sampler.step_logits.data_ptr(), -+ ) -+ region = partial( -+ epilogue.run_static, -+ io, -+ accept=partial( -+ sampling_accept_commit_lens, -+ draft_sampler=draft_sampler, -+ epilogue=epilogue, -+ tp_sync=self._tp_sync, -+ fused_argmax=self._fused_argmax, -+ block_verification=self._block_verification, -+ rejection_noise=self._rejection_noise, -+ ), -+ gate=self._gate, -+ kv_projected=True, -+ ) -+ self.committed_engram = epilogue.engram_history() is not None -+ self._run(key, region) -+ return epilogue.read_accept(bs) -+ -+ def _run(self, key: Hashable, region: Callable[[], object]) -> None: -+ graph = self._graphs.get(key) -+ if graph is None: -+ if key not in self._warmed_up: -+ if len(self._warmed_up) < self.MAX_GRAPHS: -+ self._warmed_up.add(key) -+ region() -+ return -+ graph = self._capture(key, region) -+ if graph is None: -+ return -+ graph.replay() -+ self.num_replays += 1 -+ -+ def _capture( -+ self, key: Hashable, region: Callable[[], object] -+ ) -> Optional[torch.cuda.CUDAGraph]: -+ if self._pool is None: -+ self._pool = torch.cuda.graph_pool_handle() -+ graph = torch.cuda.CUDAGraph() -+ try: -+ # graph_capture() enables pynccl, which the in-graph accept broadcast needs. -+ with ( -+ graph_capture() as ctx, -+ torch.cuda.graph( -+ graph, -+ pool=self._pool, -+ stream=ctx.stream, -+ capture_error_mode="thread_local", -+ ), -+ ): -+ region() -+ except Exception: -+ logger.warning( -+ "DSpark sampling-accept graph capture failed for %s; sampling steps " -+ "take the eager accept from now on.", -+ key, -+ exc_info=True, -+ ) -+ self.disabled = True -+ # A failed capture recorded the ops without running them. -+ region() -+ return None -+ logger.info("Captured the DSpark sampling-accept region for %s.", key) -+ self._graphs[key] = graph -+ return graph -diff --git a/python/sglang/srt/speculative/dspark_components/dspark_verify.py b/python/sglang/srt/speculative/dspark_components/dspark_verify.py -index 86de26a3b5..9d9015839f 100644 ---- a/python/sglang/srt/speculative/dspark_components/dspark_verify.py -+++ b/python/sglang/srt/speculative/dspark_components/dspark_verify.py -@@ -1,17 +1,24 @@ - from __future__ import annotations - -+import logging - import random - from typing import Optional - - import msgspec - import torch - -+from sglang.kernels.ops.embeddings.engram_hash import engram_commit_history -+from sglang.kernels.ops.speculative.dspark.blockwise_rejection import ( -+ BlockwiseRejection, -+ RejectionNoise, -+) - from sglang.kernels.ops.speculative.dspark.dspark_accept import ( - AcceptGreedy, - AcceptSampling, - FinalizeAcceptLens, - SelectMixedAccept, - SoftmaxTemp, -+ _row_argmax, - ) - from sglang.kernels.ops.speculative.dspark.dspark_verify_window import ( - BuildCommitInjectLayout, -@@ -23,15 +30,25 @@ from sglang.kernels.ops.speculative.dspark.dspark_verify_window import ( - scatter_compact_to_strided_into, - ) - from sglang.kernels.ops.speculative.dspark.simulated_bonus import ( -+ simulated_bonus_partials_graph, - simulated_bonus_sample, - simulated_bonus_sample_graph, - ) -+from sglang.kernels.ops.speculative.dspark.static_accept_tail import static_accept_tail -+from sglang.srt.environ import envs - from sglang.srt.layers.logits_processor import LogitsProcessorOutput -+from sglang.srt.managers.overlap_utils import ( -+ FutureRelayBuffers, -+ offer_future_relay_buffers, -+) - from sglang.srt.managers.schedule_batch import ScheduleBatch - from sglang.srt.model_executor.forward_batch_info import CaptureHiddenMode, ForwardMode - from sglang.srt.speculative.dflash_info import DFlashVerifyInput - from sglang.srt.speculative.dflash_info_v2 import DFlashDraftInputV2 - from sglang.srt.speculative.dflash_utils import apply_dflash_verify_logits_adjustments -+from sglang.srt.speculative.dspark_components.dspark_deferred_commit import ( -+ DeferredContextCommit, -+) - from sglang.srt.speculative.dspark_components.dspark_draft import DraftBlockResult - from sglang.srt.speculative.dspark_components.dspark_kv_inject import ( - TargetHiddenKvInjector, -@@ -49,6 +66,8 @@ from sglang.srt.speculative.spec_utils import ( - from sglang.srt.utils import is_npu - from sglang.srt.utils.invariants import Bucket, Invariant, NotNaN, expect - -+logger = logging.getLogger(__name__) -+ - _is_npu = is_npu() - - # Draft proposal probs feeding rejection sampling; the data layer is the -@@ -103,6 +122,8 @@ def candidate_request_length_bound( - - - class TargetVerifyExecutor: -+ _rejection_noise = None -+ - def __init__( - self, - *, -@@ -116,6 +137,7 @@ class TargetVerifyExecutor: - simulate_acc_len: float = 0.0, - simulated_correct_len: Optional[torch.Tensor] = None, - block_verification: bool = False, -+ rejection_noise: Optional[RejectionNoise] = None, - ) -> None: - self.target_worker = target_worker - # candidate_max_seq_len_upper_bound only feeds the V4.1 candidate graphs. -@@ -136,6 +158,8 @@ class TargetVerifyExecutor: - self._verify_backend_self_adds_seq_lens_cache: Optional[bool] = None - self._simulate_acc_len = float(simulate_acc_len) - self._block_verification = block_verification -+ # Block-wise rejection draws (blockwise_rejection.py); None keeps the classic kernel. -+ self._rejection_noise = rejection_noise - self._simulated_correct_len = simulated_correct_len - - def accept_and_finalize( -@@ -161,6 +185,7 @@ class TargetVerifyExecutor: - override drawn by begin_simulated_step. - """ - if folded_accept: -+ self.verify_epilogue.note_static_verify(bs) - return self.verify_epilogue.read_accept(bs) - - simulate = self._simulated_correct_len is not None -@@ -178,6 +203,7 @@ class TargetVerifyExecutor: - cutoff_layout=layout, - fused_argmax=self._target_is_dsv41, - block_verification=self._block_verification, -+ rejection_noise=self._rejection_noise, - ) - sync_site = ( - SpecTpSyncSite.DSPARK_ACCEPT_GREEDY -@@ -513,6 +539,9 @@ class CommitInjectCtx(msgspec.Struct): - resolve_pool: object - resolve_req_to_token: object - kv_injector: Optional[TargetHiddenKvInjector] = None -+ # SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH: returns the target's engram hasher -+ # (or None), whose history commit the static epilogue then records in-graph. -+ resolve_engram_hasher: Optional[object] = None - - - class AcceptOuts(msgspec.Struct): -@@ -524,6 +553,18 @@ class AcceptOuts(msgspec.Struct): - out_tokens: torch.Tensor - - -+class StaticVerifyIO(msgspec.Struct, frozen=True): -+ """A static verify graph's input and output tensors for one captured batch size.""" -+ -+ candidates: torch.Tensor -+ logits: torch.Tensor -+ hidden: torch.Tensor -+ seq_lens: torch.Tensor -+ req_pool_indices: torch.Tensor -+ out_cache_loc: torch.Tensor -+ positions: torch.Tensor -+ -+ - class DsparkVerifyEpilogue: - def __init__( - self, -@@ -536,8 +577,20 @@ class DsparkVerifyEpilogue: - fused_argmax: bool = False, - simulated_correct_len: Optional[torch.Tensor] = None, - simulate_fold: bool = False, -+ fused_accept_tail: bool = False, -+ accept_tail_min_bs: int = 1, -+ accept_tail_max_bs: int = 0, -+ deferred_commit: Optional[DeferredContextCommit] = None, -+ post_fold: bool = False, - ) -> None: - self.max_bs = int(max_bs) -+ # SGLANG_OPT_DSV41_DSPARK_POST_FOLD: static graphs also scatter new seq lens -+ # and the bonus into the FutureMap's slots; built at the first warmup. -+ self._post_fold = bool(post_fold) -+ self.future_relay: Optional[FutureRelayBuffers] = None -+ # SGLANG_DSPARK_DEFER_CONTEXT_KV: static graphs join its forked projection and -+ # stage the commit's stores into it; the next draft forward runs them. -+ self.deferred_commit = deferred_commit - # SGLANG_SIMULATE_ACC_LEN with a sampled bonus inside the graph too: the bonus - # is drawn at the simulated correct_len from these buffers, which - # begin_sim_bonus writes before replay (<= 0 temperature: argmax). -@@ -575,11 +628,38 @@ class DsparkVerifyEpilogue: - self.out_tokens_buf = torch.zeros( - (self.max_bs, self.stride), dtype=torch.int64, device=device - ) -+ # Under the accept-site broadcast the fused tail serves only simulate_fold, -+ # whose broadcast inputs (length, draw) the kernel can take. -+ self._tail_broadcasts = bool(fused_accept_tail) and tp_sync.enabled( -+ SpecTpSyncSite.DSPARK_ACCEPT_GRAPH -+ ) -+ self._fused_accept_tail = bool(fused_accept_tail) and ( -+ self.simulate_fold or not self._tail_broadcasts -+ ) -+ if fused_accept_tail and not self._fused_accept_tail: -+ logger.info( -+ "DSpark fused accept tail off: the accept-site TP broadcast is " -+ "selected without SGLANG_DSPARK_SIMULATE_FOLD." -+ ) -+ self._accept_tail_bs = (int(accept_tail_min_bs), int(accept_tail_max_bs)) -+ self._accept_tail_logged: set[int] = set() -+ self.gated_commit_lens_buf = torch.zeros( -+ (self.max_bs,), dtype=torch.int32, device=device -+ ) -+ self.block_accept_lens_buf = ( -+ torch.zeros((self.max_bs,), dtype=torch.int32, device=device) -+ if envs.SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH.get() -+ else None -+ ) - # SGLANG_SIMULATE_ACC_LEN: the step's correct length, filled per step. - self.simulated_correct_len = simulated_correct_len - self.strided_logits: Optional[torch.Tensor] = None - self.strided_hidden: Optional[torch.Tensor] = None - self._static_step_state: Optional[tuple[int, bool]] = None -+ # Set when a captured static epilogue recorded the engram history commit. -+ self.folds_engram_commit = False -+ # Per captured static batch size; the sampling-accept region's replays read them. -+ self.static_io: dict[int, StaticVerifyIO] = {} - - def capture_hook(self, runner, out, forward_batch, num_tokens) -> None: - if ( -@@ -638,37 +718,224 @@ class DsparkVerifyEpilogue: - - def _static_epilogue(self, out, forward_batch) -> None: - bs = forward_batch.batch_size -- verify_lens = self.verify_lens_buf[:bs] -- candidates = forward_batch.input_ids.view(bs, self.stride) -- commit_lens = self._accept( -- candidates=candidates, -+ io = StaticVerifyIO( -+ candidates=forward_batch.input_ids.view(bs, self.stride), - logits=out.next_token_logits, -- draft_tokens=candidates[:, 1:].contiguous(), -+ hidden=out.hidden_states, - seq_lens=forward_batch.seq_lens, -+ req_pool_indices=forward_batch.req_pool_indices, -+ out_cache_loc=forward_batch.out_cache_loc, -+ positions=forward_batch.positions, - ) -- if not self.folds_commit: -- return -- # Same staged locations as target verify; padded and fallback rows skip KV. -- gated_commit_lens = ( -- torch.minimum(commit_lens, verify_lens.to(torch.int32)) -- * self.inject_gate_buf -+ capturing = ( -+ torch.cuda.is_available() and torch.cuda.is_current_stream_capturing() - ) -- cache_loc = forward_batch.out_cache_loc -+ if capturing: -+ self.static_io[bs] = io -+ committed_engram = self.run_static( -+ io, accept=self._accept_static_greedy, gate=self.inject_gate_buf -+ ) -+ if committed_engram and capturing: -+ self.folds_engram_commit = True -+ -+ def run_static( -+ self, io: StaticVerifyIO, *, accept, gate: torch.Tensor, kv_projected=False -+ ) -> bool: -+ """Run ``accept`` into the accept buffers, then the commits gated by ``gate``; -+ returns whether the engram history was committed.""" -+ bs = io.candidates.shape[0] -+ verify_lens = self.verify_lens_buf[:bs] -+ folds = self.folds_commit -+ gated_commit_lens = accept(io, verify_lens=verify_lens, gate=gate, gated=folds) -+ # Both accept branches leave the ungated commit lengths in commit_lens_buf. -+ committed_engram = self._commit_engram_history( -+ io.candidates, -+ io.req_pool_indices, -+ self.commit_lens_buf[:bs], -+ verify_lens, -+ gate, -+ ) -+ if self._post_fold: -+ self._scatter_future_relay(io.req_pool_indices, bs) -+ if not folds: -+ return committed_engram -+ cache_loc = io.out_cache_loc - state_slot = None - if self.commit_ctx.kv_injector.swa_ring_size is not None: - state_slot = ( -- forward_batch.req_pool_indices.view(-1, 1) -- .expand(bs, self.stride) -- .reshape(-1) -+ io.req_pool_indices.view(-1, 1).expand(bs, self.stride).reshape(-1) - ) -+ commit = self.deferred_commit -+ if commit is not None and (kv_projected or commit.join_projection()): -+ commit.stage( -+ cache_loc=cache_loc, -+ positions=io.positions, -+ commit_lens=gated_commit_lens, -+ state_slot=state_slot, -+ ) -+ return committed_engram - self.commit_ctx.kv_injector.inject_target_hidden( -- target_hidden=out.hidden_states, -+ target_hidden=io.hidden, - cache_loc=cache_loc, - cache_loc_2d=cache_loc.view(bs, self.stride), -- positions=forward_batch.positions, -+ positions=io.positions, - commit_lens=gated_commit_lens, - state_slot=state_slot, - ) -+ return committed_engram -+ -+ def _accept_static_greedy( -+ self, io: StaticVerifyIO, *, verify_lens, gate, gated: bool -+ ) -> Optional[torch.Tensor]: -+ bs = io.candidates.shape[0] -+ if self._serves_accept_tail(bs): -+ gated_commit_lens = self._static_accept_tail( -+ candidates=io.candidates, -+ logits=io.logits, -+ seq_lens=io.seq_lens, -+ verify_lens=verify_lens, -+ gated=gated, -+ ) -+ block = self.read_block_accept_lens(bs) -+ if block is not None: -+ # The static tail never cap-trims (it writes cap_trim_lens 0). -+ block.copy_(self.commit_lens_buf[:bs]) -+ return gated_commit_lens -+ commit_lens = self._accept( -+ candidates=io.candidates, -+ logits=io.logits, -+ draft_tokens=io.candidates[:, 1:].contiguous(), -+ seq_lens=io.seq_lens, -+ ) -+ # Same staged locations as target verify; padded and fallback rows skip KV. -+ return ( -+ torch.minimum(commit_lens, verify_lens.to(torch.int32)) * gate -+ if gated -+ else None -+ ) -+ -+ def engram_history(self) -> Optional[torch.Tensor]: -+ """The engram history the static epilogue commits into, or None.""" -+ if self.commit_ctx is None or self.commit_ctx.resolve_engram_hasher is None: -+ return None -+ hasher = self.commit_ctx.resolve_engram_hasher() -+ return None if hasher is None else hasher.history -+ -+ def _serves_accept_tail(self, bs: int) -> bool: -+ low, high = self._accept_tail_bs -+ return self._fused_accept_tail and low <= bs and (high == 0 or bs <= high) -+ -+ def _static_accept_tail( -+ self, *, candidates, logits, seq_lens, verify_lens, gated: bool -+ ) -> Optional[torch.Tensor]: -+ """The greedy ``_accept`` and gated commit lengths in one launch; under -+ simulate_fold the argmax is skipped and the bonus select runs in the tail.""" -+ bs = candidates.shape[0] -+ target_predict = bonus_in = bonus_parts = None -+ if not self.simulate_fold: -+ target_predict = _row_argmax(logits, fused=self._fused_argmax).view(-1) -+ elif self._tail_broadcasts: -+ bonus_in = self._sim_bonus(logits, bs) -+ # Rank 0's length and draw, as build_accept_outs broadcasts them. -+ self._tp_sync.sync( -+ SpecTpSyncSite.DSPARK_ACCEPT_GRAPH, self.simulated_correct_len -+ ) -+ self._tp_sync.sync(SpecTpSyncSite.DSPARK_ACCEPT_GRAPH, bonus_in) -+ else: -+ bonus_parts = ( -+ *simulated_bonus_partials_graph(**self._sim_bonus_args(logits, bs)), -+ logits.shape[1], -+ ) -+ self._log_accept_tail(bs, bonus_in=bonus_in) -+ static_accept_tail( -+ candidates=candidates, -+ target_predict=target_predict, -+ seq_lens=seq_lens, -+ verify_lens=verify_lens, -+ gate=self.inject_gate_buf, -+ correct_len_out=self.correct_len_buf, -+ bonus_out=self.bonus_buf, -+ cap_trim_lens_out=self.cap_trim_lens_buf, -+ commit_lens_out=self.commit_lens_buf, -+ new_seq_lens_out=self.new_seq_lens_buf, -+ out_tokens_out=self.out_tokens_buf, -+ simulated_correct_len=self.simulated_correct_len, -+ bonus_in=bonus_in, -+ bonus_parts=bonus_parts, -+ gated_commit_lens_out=self.gated_commit_lens_buf if gated else None, -+ ) -+ return self.gated_commit_lens_buf[:bs] if gated else None -+ -+ def _sim_bonus_args(self, logits, bs: int) -> dict: -+ return dict( -+ target_logits=logits, -+ # One length for every request: a stride-0 view, no copy node in the graph. -+ correct_len=self.simulated_correct_len.expand(bs), -+ temperatures=self.sim_temperatures_buf[:bs], -+ seed=self.sim_seed_buf, -+ bs=bs, -+ rows_per_request=self.stride, -+ ) -+ -+ def _sim_bonus(self, logits, bs: int) -> torch.Tensor: -+ return simulated_bonus_sample_graph(**self._sim_bonus_args(logits, bs)) -+ -+ def _log_accept_tail(self, bs: int, *, bonus_in) -> None: -+ """Once per captured batch size, from the branch that launches the kernel.""" -+ if ( -+ bs in self._accept_tail_logged -+ or not torch.cuda.is_available() -+ or not torch.cuda.is_current_stream_capturing() -+ ): -+ return -+ self._accept_tail_logged.add(bs) -+ logger.info( -+ "DSpark verify graph bs=%d: fused accept tail (bonus=%s, tp-broadcast=%s)", -+ bs, -+ "sim-fold" if self.simulate_fold else "argmax", -+ "inputs" if bonus_in is not None else "off", -+ ) -+ -+ def note_static_verify(self, bs: int) -> None: -+ """Host, after a static verify graph replayed ``bs`` requests.""" -+ if self.deferred_commit is not None: -+ self.deferred_commit.note_static_verify(bs) -+ -+ def _commit_engram_history( -+ self, candidates, req_pool_indices, commit_lens, verify_lens, gate -+ ) -> bool: -+ """The post-verify engram history commit, gated per row: padded rows -+ (verify_lens 0) and steps the graph does not commit (gate 0) are skipped.""" -+ history = self.engram_history() -+ if history is None: -+ return False -+ engram_commit_history( -+ history, -+ candidates, -+ req_pool_indices, -+ commit_lens, -+ live_rows=verify_lens, -+ gate=gate, -+ ) -+ return True -+ -+ def _scatter_future_relay(self, req_pool_indices: torch.Tensor, bs: int) -> None: -+ """Unconditional: a step that takes another accept publishes and stashes on -+ the host afterwards. Padded rows index slot 0, every pool's dummy row.""" -+ if self.commit_ctx is None: -+ return -+ if self.future_relay is None: -+ assert not ( -+ torch.cuda.is_available() and torch.cuda.is_current_stream_capturing() -+ ), "the future relay is built at a warmup, before capture" -+ self.future_relay = FutureRelayBuffers( -+ req_pool_size=self.commit_ctx.resolve_req_to_token().shape[0], -+ device=req_pool_indices.device, -+ ) -+ offer_future_relay_buffers(self.future_relay) -+ rows = req_pool_indices[:bs].to(torch.int64) -+ self.future_relay.new_seq_lens[rows] = self.new_seq_lens_buf[:bs] -+ self.future_relay.output_tokens[rows] = self.bonus_buf[:bs] - - def read_accept(self, bs: int) -> AcceptOuts: - return AcceptOuts( -@@ -680,6 +947,12 @@ class DsparkVerifyEpilogue: - out_tokens=self.out_tokens_buf[:bs], - ) - -+ def read_block_accept_lens(self, bs: int) -> Optional[torch.Tensor]: -+ """commit_lens + cap_trim_lens from the in-graph accept, or None.""" -+ if self.block_accept_lens_buf is None: -+ return None -+ return self.block_accept_lens_buf[:bs] -+ - @property - def folds_commit(self) -> bool: - if self.commit_ctx is None: -@@ -772,18 +1045,7 @@ class DsparkVerifyEpilogue: - ) - if self.simulate_fold: - # Before the TP broadcast in build_accept_outs: every rank commits rank 0's draw. -- bonus = ( -- simulated_bonus_sample_graph( -- target_logits=logits, -- correct_len=self.simulated_correct_len.repeat(bs), -- temperatures=self.sim_temperatures_buf[:bs], -- seed=self.sim_seed_buf, -- bs=bs, -- rows_per_request=self.stride, -- ) -- .to(bonus.dtype) -- .view_as(bonus) -- ) -+ bonus = self._sim_bonus(logits, bs).to(bonus.dtype).view_as(bonus) - accept = build_accept_outs( - correct_len=correct_len, - bonus=bonus, -@@ -796,6 +1058,7 @@ class DsparkVerifyEpilogue: - sync_site=SpecTpSyncSite.DSPARK_ACCEPT_GRAPH, - simulated_correct_len=self.simulated_correct_len, - out=self.read_accept(bs), -+ block_accept_lens_out=self.read_block_accept_lens(bs), - ) - return accept.commit_lens - -@@ -851,8 +1114,10 @@ def build_accept_outs( - target_logits: Optional[torch.Tensor] = None, - simulate_bonus_sampling_info=None, - out: Optional[AcceptOuts] = None, -+ block_accept_lens_out: Optional[torch.Tensor] = None, - ) -> AcceptOuts: -- """``out``: static buffers (the in-graph accept's) to copy the results into.""" -+ """``out``: static buffers (the in-graph accept's) to copy the results into; -+ ``block_accept_lens_out`` (with ``out``) gets commit_lens + cap_trim_lens.""" - bs = correct_len.shape[0] - if simulated_correct_len is not None: - # The accept runs as served; only its length is replaced. -@@ -898,6 +1163,10 @@ def build_accept_outs( - out.commit_lens.copy_(accept.commit_lens) - out.new_seq_lens.copy_(accept.new_seq_lens) - out.out_tokens.copy_(accept.out_tokens) -+ if block_accept_lens_out is not None: -+ torch.add( -+ accept.commit_lens, accept.cap_trim_lens, out=block_accept_lens_out -+ ) - return out - return accept - -@@ -923,6 +1192,49 @@ def sample_simulated_bonus( - return bonus.to(greedy_bonus.dtype).view_as(greedy_bonus) - - -+_blockwise_rejection_noted = False -+ -+ -+def _note_blockwise_rejection() -> None: -+ global _blockwise_rejection_noted -+ if not _blockwise_rejection_noted: -+ _blockwise_rejection_noted = True -+ logger.info("DSpark: sampled verify accepts use block-wise rejection") -+ -+ -+def _blockwise_rejection_applies( -+ *, -+ sampling_info, -+ rejection_noise: Optional[RejectionNoise], -+ block_verification: bool, -+) -> bool: -+ return ( -+ rejection_noise is not None -+ and not block_verification -+ and not sampling_info.need_top_k_sampling -+ and not sampling_info.need_top_p_sampling -+ ) -+ -+ -+def _draft_probs(draft_block: DraftBlockResult, vocab: int, device) -> torch.Tensor: -+ if draft_block.greedy_draft: -+ # An argmax draft is one-hot: rejection accepts at the target probability. -+ draft_tokens = draft_block.draft_tokens -+ draft_probs = torch.zeros( -+ (*draft_tokens.shape, vocab), dtype=torch.float32, device=device -+ ) -+ draft_probs.scatter_(-1, draft_tokens.unsqueeze(-1), 1.0) -+ return draft_probs -+ bs, gamma_rows, vocab = draft_block.corrected_logits.shape -+ draft_probs = SoftmaxTemp.execute( -+ logits=draft_block.corrected_logits.reshape(bs * gamma_rows, vocab), -+ temperatures=draft_block.temperatures, -+ rows_per_request=gamma_rows, -+ ).view(bs, gamma_rows, vocab) -+ expect(_VERIFY_DRAFT_PROBS, draft_probs) -+ return draft_probs -+ -+ - def accept_draft_tokens( - *, - candidates: torch.Tensor, -@@ -935,6 +1247,7 @@ def accept_draft_tokens( - cutoff_layout: Optional[RaggedVerifyLayout] = None, - fused_argmax: bool = False, - block_verification: bool = False, -+ rejection_noise: Optional[RejectionNoise] = None, - ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: - greedy_mask = draft_block.greedy_mask - cutoff_verify_lens = None if cutoff_layout is None else cutoff_layout.verify_lens -@@ -947,28 +1260,30 @@ def accept_draft_tokens( - cutoff_verify_lens=cutoff_verify_lens, - fused_argmax=fused_argmax, - ) -- if draft_block.greedy_draft: -- # An argmax draft is one-hot: rejection accepts at the target probability. -- draft_tokens = draft_block.draft_tokens -- draft_probs = torch.zeros( -- (*draft_tokens.shape, target_logits.shape[-1]), -- dtype=torch.float32, -- device=target_logits.device, -+ if _blockwise_rejection_applies( -+ sampling_info=sampling_info, -+ rejection_noise=rejection_noise, -+ block_verification=block_verification, -+ ): -+ _note_blockwise_rejection() -+ sampled = BlockwiseRejection.execute( -+ candidates=candidates, -+ target_logits=target_logits, -+ draft_logits=( -+ None if draft_block.greedy_draft else draft_block.corrected_logits -+ ), -+ target_temperatures=sampling_info.temperatures, -+ draft_temperatures=draft_block.temperatures, -+ noise=rejection_noise, -+ cutoff_verify_lens=cutoff_verify_lens, - ) -- draft_probs.scatter_(-1, draft_tokens.unsqueeze(-1), 1.0) - else: -- bs, gamma_rows, vocab = draft_block.corrected_logits.shape -- draft_probs = SoftmaxTemp.execute( -- logits=draft_block.corrected_logits.reshape(bs * gamma_rows, vocab), -- temperatures=draft_block.temperatures, -- rows_per_request=gamma_rows, -- ).view(bs, gamma_rows, vocab) -- expect(_VERIFY_DRAFT_PROBS, draft_probs) -- if not sampling_info.is_any_greedy: -- return AcceptSampling.execute( -+ sampled = AcceptSampling.execute( - candidates=candidates, - target_logits=target_logits, -- draft_probs=draft_probs, -+ draft_probs=_draft_probs( -+ draft_block, target_logits.shape[-1], target_logits.device -+ ), - sampling_info=sampling_info, - draft_input=draft_input, - gamma=gamma, -@@ -976,6 +1291,8 @@ def accept_draft_tokens( - cutoff_verify_lens=cutoff_verify_lens, - block_verification=block_verification, - ) -+ if not sampling_info.is_any_greedy: -+ return sampled - greedy_len, greedy_bonus, greedy_trim = AcceptGreedy.execute( - candidates=candidates, - target_logits=target_logits, -@@ -983,17 +1300,7 @@ def accept_draft_tokens( - cutoff_verify_lens=cutoff_verify_lens, - fused_argmax=fused_argmax, - ) -- sampling_len, sampling_bonus, sampling_trim = AcceptSampling.execute( -- candidates=candidates, -- target_logits=target_logits, -- draft_probs=draft_probs, -- sampling_info=sampling_info, -- draft_input=draft_input, -- gamma=gamma, -- verify_num_draft_tokens=verify_num_draft_tokens, -- cutoff_verify_lens=cutoff_verify_lens, -- block_verification=block_verification, -- ) -+ sampling_len, sampling_bonus, sampling_trim = sampled - selected = SelectMixedAccept.execute( - greedy_mask=greedy_mask, - greedy_len=greedy_len, -diff --git a/python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py b/python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py -index 4c9d524522..a789f2be68 100644 ---- a/python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py -+++ b/python/sglang/srt/speculative/dspark_components/dspark_worker_v2.py -@@ -3,6 +3,9 @@ from typing import TYPE_CHECKING, Callable, Optional, Protocol, runtime_checkabl - - import torch - -+from sglang.kernels.ops.speculative.dspark.blockwise_rejection import ( -+ make_rejection_noise, -+) - from sglang.srt.configs.hybrid_arch import mambaish_config - from sglang.srt.environ import envs - from sglang.srt.layers.dp_attention import get_dp_tp_group -@@ -22,6 +25,7 @@ from sglang.srt.model_loader.weight_utils import get_pp_stage_load_group - from sglang.srt.runtime_context import ( - get_disagg, - get_exec, -+ get_memory, - get_parallel, - get_schedule, - get_spec, -@@ -44,6 +48,10 @@ from sglang.srt.speculative.dspark_components.dspark_config import ( - draft_is_deepseek_v4, - resolve_runtime_config, - ) -+from sglang.srt.speculative.dspark_components.dspark_deferred_commit import ( -+ DeferredContextCommit, -+ defer_context_kv_refusal, -+) - from sglang.srt.speculative.dspark_components.dspark_draft import ( - DraftBlockProposer, - make_next_draft_input, -@@ -64,6 +72,9 @@ from sglang.srt.speculative.dspark_components.dspark_planner import ( - dp_global_verify_tier_num_tokens, - idle_ragged_layout, - ) -+from sglang.srt.speculative.dspark_components.dspark_sampling_accept_graph import ( -+ DsparkSamplingAcceptGraph, -+) - from sglang.srt.speculative.dspark_components.dspark_verify import ( - CommitInjectCtx, - DsparkVerifyEpilogue, -@@ -132,9 +143,27 @@ def _configure_target_hidden_projection( - ) - - -+def sim_draw_ahead_enabled(simulated_correct_len: Optional[torch.Tensor]) -> bool: -+ """SGLANG_OPT_DSV41_DSPARK_SIM_DRAW_AHEAD, only under simulated acceptance: with -+ real acceptance there is no draw, so the step order stays as it was.""" -+ return ( -+ envs.SGLANG_OPT_DSV41_DSPARK_SIM_DRAW_AHEAD.get() -+ and simulated_correct_len is not None -+ ) -+ -+ - class DSparkWorkerV2(BaseSpecWorker): - """Non-last PP stages run only the target; draft state belongs to the last stage.""" - -+ _sampling_accept_graph = None -+ _rejection_noise = None -+ _sim_draw_ahead = False -+ num_sim_draws_ahead = 0 -+ _prepare_inputs_once = False -+ num_folded_verify_ids_steps = 0 -+ num_relayed_in_graph_steps = 0 -+ _verify_inputs_ready = None -+ - def weight_update_runners(self) -> list[tuple[str, "ModelRunner"]]: - return [("draft", self.draft_model_runner)] if self._hosts_draft else [] - -@@ -258,6 +287,12 @@ class DSparkWorkerV2(BaseSpecWorker): - self._block_pos_offsets = build_block_pos_offsets( - length=self.verify_num_draft_tokens, device=self.device - ) -+ # Verify-window positions, cache locs and the draft anchor column in one launch. -+ self._prepare_inputs_once = ( -+ envs.SGLANG_OPT_DSV41_DSPARK_PREPARE_INPUTS_ONCE.get() -+ ) -+ self.num_folded_verify_ids_steps = 0 -+ self.num_relayed_in_graph_steps = 0 - self._draft_block_spec_info = make_draft_block_spec_info( - draft_token_num=int(self.query_token_num), device=self.device - ) -@@ -319,6 +354,10 @@ class DSparkWorkerV2(BaseSpecWorker): - if self._simulate_acc_len > 0 - else None - ) -+ # The simulated acceptance draw (and sim bonus seed) before the draft launch, -+ # where the host waits on the previous verify anyway; off with real acceptance. -+ self._sim_draw_ahead = sim_draw_ahead_enabled(self._simulated_correct_len) -+ self.num_sim_draws_ahead = 0 - self._greedy_draft = envs.SGLANG_DSPARK_USE_GREEDY_DRAFT.get() - self._proposer = DraftBlockProposer( - draft_model=self.draft_model, -@@ -332,6 +371,14 @@ class DSparkWorkerV2(BaseSpecWorker): - dp_moe_sync=self._draft_is_moe and get_parallel().attn_dp_enabled, - ) - self._verify_epilogue = None -+ self._sampling_accept_graph: Optional[DsparkSamplingAcceptGraph] = None -+ # Counter-based draws from the server seed: every TP rank draws the same coins, -+ # so no accept broadcast is needed. -+ self._rejection_noise = ( -+ make_rejection_noise(self.target_worker.random_seed, self.device) -+ if is_cuda() and envs.SGLANG_OPT_DSV41_BLOCKWISE_REJECTION.get() -+ else None -+ ) - target_is_dsv41 = ( - getattr( - self.target_worker.model_runner.model_config.hf_text_config, -@@ -340,6 +387,16 @@ class DSparkWorkerV2(BaseSpecWorker): - ) - == "deepseek_v41" - ) -+ # SGLANG_OPT_DSV41_TARGET_METADATA_EARLY: the static verify's inputs are final -+ # after the head; the target runner stages their metadata beside the draft. -+ self._verify_inputs_ready: Optional[torch.cuda.Event] = ( -+ torch.cuda.Event() -+ if envs.SGLANG_OPT_DSV41_TARGET_METADATA_EARLY.get() -+ and self._verify_planner.mode_value == "static" -+ and not get_parallel().attn_dp_enabled -+ and torch.device(self.device).type == "cuda" -+ else None -+ ) - static_epilogue_supported = ( - target_is_dsv41 - and self._verify_planner.mode_value == "static" -@@ -362,6 +419,16 @@ class DSparkWorkerV2(BaseSpecWorker): - fused_argmax=target_is_dsv41, - simulated_correct_len=self._simulated_correct_len, - simulate_fold=envs.SGLANG_DSPARK_SIMULATE_FOLD.get(), -+ fused_accept_tail=envs.SGLANG_DSPARK_FUSED_ACCEPT_TAIL.get(), -+ accept_tail_min_bs=envs.SGLANG_DSPARK_ACCEPT_TAIL_MIN_BS.get(), -+ accept_tail_max_bs=envs.SGLANG_DSPARK_ACCEPT_TAIL_MAX_BS.get(), -+ deferred_commit=self._maybe_build_deferred_commit( -+ static_epilogue_supported -+ ), -+ post_fold=( -+ static_epilogue_supported -+ and envs.SGLANG_OPT_DSV41_DSPARK_POST_FOLD.get() -+ ), - commit_ctx=CommitInjectCtx( - draft_model=self.draft_model, - block_pos_offsets=self._block_pos_offsets, -@@ -370,11 +437,34 @@ class DSparkWorkerV2(BaseSpecWorker): - self.model_runner.req_to_token_pool.req_to_token - ), - kv_injector=self._kv_injector, -+ resolve_engram_hasher=( -+ ( -+ lambda: ( -+ self.model_runner.ngram_embedding_manager.engram_hasher -+ ) -+ ) -+ if envs.SGLANG_OPT_DSV41_POST_FORWARD_CUDA_GRAPH.get() -+ else None -+ ), - ), - ) - self.model_runner.capture_tail_hooks.append( - self._verify_epilogue.capture_hook - ) -+ if ( -+ envs.SGLANG_OPT_DSV41_SAMPLING_ACCEPT_GRAPH.get() -+ and static_epilogue_supported -+ and is_cuda() -+ ): -+ self._sampling_accept_graph = DsparkSamplingAcceptGraph( -+ epilogue=self._verify_epilogue, -+ resolve_draft_sampler=lambda: self._draft_sampler, -+ tp_sync=self._tp_sync, -+ fused_argmax=target_is_dsv41, -+ block_verification=get_spec().speculative_use_block_verification, -+ device=self.device, -+ rejection_noise=self._rejection_noise, -+ ) - - self._simulate_acc_greedy = ( - self._simulate_acc_len > 0 and envs.SGLANG_SIMULATE_ACC_GREEDY.get() -@@ -408,6 +498,7 @@ class DSparkWorkerV2(BaseSpecWorker): - simulate_acc_len=self._simulate_acc_len, - simulated_correct_len=self._simulated_correct_len, - block_verification=get_spec().speculative_use_block_verification, -+ rejection_noise=self._rejection_noise, - ) - - self._forced_budget_frac: Optional[float] = None -@@ -520,9 +611,87 @@ class DSparkWorkerV2(BaseSpecWorker): - make_draft_sampler_capture_hook(self._draft_sampler) - ) - self._proposer.attach_draft_sampler(self._draft_sampler) -+ commit = self._deferred_commit() -+ if commit is not None: -+ self._wire_deferred_commit(commit) - self._draft_worker.init_cuda_graphs( - capture_decode_cuda_graph=capture_decode_cuda_graph - ) -+ if commit is not None: -+ commit.disarm() -+ -+ def _defer_context_kv_eligible(self, static_epilogue_supported: bool) -> bool: -+ """SGLANG_DSPARK_DEFER_CONTEXT_KV: only where nothing moves or reads draft KV -+ between a verify and the next draft forward but this worker's forwards.""" -+ if not envs.SGLANG_DSPARK_DEFER_CONTEXT_KV.get(): -+ return False -+ from sglang.srt.layers.attention.dsv4.unified_kv_gate import ( -+ is_unified_kv_triton, -+ ) -+ -+ memory = get_memory() -+ refusal = defer_context_kv_refusal( -+ static_verify=static_epilogue_supported, -+ draft_is_moe=self._draft_is_moe, -+ unified_kv=is_unified_kv_triton(), -+ unified_memory=memory.enable_unified_memory, -+ hicache=memory.enable_hierarchical_cache -+ or memory.hicache_storage_backend is not None, -+ disaggregated=get_disagg().disaggregation_mode != "null", -+ attn_dp=get_parallel().attn_dp_enabled, -+ ) -+ if refusal: -+ logger.warning( -+ "SGLANG_DSPARK_DEFER_CONTEXT_KV refused, the commit stays in the " -+ "verify graph: %s", -+ refusal, -+ ) -+ return False -+ return True -+ -+ def _maybe_build_deferred_commit( -+ self, static_epilogue_supported: bool -+ ) -> Optional[DeferredContextCommit]: -+ if not self._defer_context_kv_eligible(static_epilogue_supported): -+ return None -+ commit = DeferredContextCommit( -+ max_bs=max(get_exec().graph.cuda_graph_config.decode.bs), -+ stride=self.verify_num_draft_tokens, -+ device=self.device, -+ kv_injector=self._kv_injector, -+ ) -+ # The target's logits processor: SGLang's forward and a megakernel's head -+ # both call it, with the DSpark hidden, once the hidden is final. -+ self.model_runner.model.logits_processor.register_forward_pre_hook( -+ commit.logits_pre_hook, with_kwargs=True -+ ) -+ return commit -+ -+ def _deferred_commit(self): -+ epilogue = self._verify_epilogue -+ return None if epilogue is None else epilogue.deferred_commit -+ -+ def _wire_deferred_commit(self, commit) -> None: -+ """Draft side of SGLANG_DSPARK_DEFER_CONTEXT_KV: the draft graph forks the -+ staged write at its head and its first KV store joins it.""" -+ from sglang.srt.layers.attention.deepseek_v4_backend import ( -+ DeepseekV4AttnBackend, -+ DeepseekV4MultiStepBackend, -+ ) -+ -+ self._proposer.deferred_commit = commit -+ self.draft_model_runner.capture_head_hooks.append(commit.capture_head_hook) -+ backend = self.draft_model_runner.attn_backend -+ backends = [backend] -+ if isinstance(backend, DeepseekV4MultiStepBackend): -+ backends.extend(backend.attn_backends) -+ for b in backends: -+ if isinstance(b, DeepseekV4AttnBackend): -+ b.pre_kv_store_hook = commit.join -+ logger.info( -+ "SGLANG_DSPARK_DEFER_CONTEXT_KV: the draft context-KV commit runs at the " -+ "head of the next draft graph, joined at its first KV store." -+ ) - - def _maybe_build_draft_sampler(self): - return maybe_build_draft_sampler( -@@ -542,7 +711,12 @@ class DSparkWorkerV2(BaseSpecWorker): - ) - - def clear_cache_pool(self): -- pass -+ if not self._hosts_draft: -+ return -+ # The staged rows' slots were just freed. -+ commit = self._deferred_commit() -+ if commit is not None: -+ commit.disarm() - - def set_dspark_forced_budget_frac(self, frac: Optional[float]) -> None: - if not self._hosts_draft: -@@ -642,6 +816,10 @@ class DSparkWorkerV2(BaseSpecWorker): - ) - return self._decode_idle_result(on_publish=on_publish) - -+ # The prefill's draft KV may land in slots a pending commit targets. -+ commit = self._deferred_commit() -+ if commit is not None: -+ commit.flush() - batch_output = self.target_worker.forward_batch_generation( - batch, - pp_proxy_tensors=pp_proxy_tensors, -@@ -804,6 +982,27 @@ class DSparkWorkerV2(BaseSpecWorker): - new_seq_lens=next_draft_input.new_seq_lens, - ) - -+ def _stage_target_verify_metadata( -+ self, *, batch: ScheduleBatch, verify_window, seq_lens_cpu -+ ) -> None: -+ """Right after the draft graph's launch; the sources are the tensors the verify -+ batch uses, and the side stream waits only for the head (_verify_inputs_ready).""" -+ target_runner = self.target_worker.model_runner.decode_cuda_graph_runner -+ if target_runner is None: -+ return -+ target_runner.stage_verify_metadata_early( -+ seq_lens=batch.seq_lens, -+ req_pool_indices=batch.req_pool_indices, -+ out_cache_loc=verify_window.verify_cache_loc, -+ positions=verify_window.positions_2d.reshape(-1), -+ max_seq_len=( -+ int(seq_lens_cpu.max()) -+ if seq_lens_cpu is not None and seq_lens_cpu.numel() > 0 -+ else None -+ ), -+ after=self._verify_inputs_ready, -+ ) -+ - def _forward_decode( - self, - batch: ScheduleBatch, -@@ -860,6 +1059,16 @@ class DSparkWorkerV2(BaseSpecWorker): - self._observers.begin_step() - - target_model = self.target_worker.model_runner.model -+ anchor_ids = ( -+ self._proposer.draft_block_ids_view(bs=bs, device=prefix_lens.device) -+ if self._prepare_inputs_once -+ else None -+ ) -+ window_seq_lens_cpu = ( -+ batch.seq_lens_cpu -+ if batch.seq_lens_cpu is not None -+ else draft_input.nxt_kv_lens_cpu -+ ) - verify_window = alloc_verify_window( - batch=batch, - bs=bs, -@@ -867,12 +1076,13 @@ class DSparkWorkerV2(BaseSpecWorker): - verify_num_draft_tokens=self.verify_num_draft_tokens, - block_pos_offsets=self._block_pos_offsets, - model_runner=self.model_runner, -- seq_lens_cpu=( -- batch.seq_lens_cpu -- if batch.seq_lens_cpu is not None -- else draft_input.nxt_kv_lens_cpu -- ), -+ seq_lens_cpu=window_seq_lens_cpu, -+ bonus=draft_input.bonus_tokens.view(-1) if anchor_ids is not None else None, -+ anchor_ids=anchor_ids, - ) -+ if self._verify_inputs_ready is not None: -+ # The verify's inputs are final here; the early metadata waits for this. -+ self._verify_inputs_ready.record() - - sampling_info = batch.sampling_info - # Simulated acceptance overrides correct_len, so only the bonus token needs the -@@ -890,6 +1100,10 @@ class DSparkWorkerV2(BaseSpecWorker): - ): - simulate_bonus_sampling_info = sampling_info - sampling_info = None -+ if self._sim_draw_ahead: -+ self._begin_simulated_step_ahead( -+ bs=bs, simulate_bonus_sampling_info=simulate_bonus_sampling_info -+ ) - with self._draft_context(), self._observers.segment(InfoSegment.DRAFT): - proposal = self._proposer.propose( - batch=batch, -@@ -899,6 +1113,13 @@ class DSparkWorkerV2(BaseSpecWorker): - device=device, - target_model=target_model, - sampling_info=sampling_info, -+ anchor_prepared=anchor_ids is not None, -+ ) -+ if self._verify_inputs_ready is not None: -+ self._stage_target_verify_metadata( -+ batch=batch, -+ verify_window=verify_window, -+ seq_lens_cpu=window_seq_lens_cpu, - ) - draft_block_ids = proposal.draft_block_ids - draft_block = proposal.draft_block -@@ -926,9 +1147,15 @@ class DSparkWorkerV2(BaseSpecWorker): - ) - run_compact = self._verify_planner.should_run_compact(layout=layout) - -- verify_ids_2d = torch.cat( -- [draft_block_ids[:, :1], draft_tokens], dim=1 -- ).contiguous() -+ verify_ids_2d = proposal.verify_ids -+ if verify_ids_2d is None: -+ verify_ids_2d = torch.cat( -+ [draft_block_ids[:, :1], draft_tokens], dim=1 -+ ).contiguous() -+ else: -+ self.num_folded_verify_ids_steps += 1 -+ if self.num_folded_verify_ids_steps == 1: -+ logger.info("Verify ids read from the draft graph output (first step).") - - # Must stay ahead of the target verify launch below. - grammar_tree = ( -@@ -953,16 +1180,17 @@ class DSparkWorkerV2(BaseSpecWorker): - ) - and not batch.has_grammar - ) -- self._verify_executor.begin_simulated_step() -- if fold_eligible and self._verify_executor.verify_epilogue.simulate_fold: -- self._verify_executor.verify_epilogue.begin_sim_bonus( -- bs, -- ( -- None -- if simulate_bonus_sampling_info is None -- else simulate_bonus_sampling_info.temperatures[:bs] -- ), -- ) -+ if not self._sim_draw_ahead: -+ self._verify_executor.begin_simulated_step() -+ if fold_eligible and self._verify_executor.verify_epilogue.simulate_fold: -+ self._verify_executor.verify_epilogue.begin_sim_bonus( -+ bs, -+ ( -+ None -+ if simulate_bonus_sampling_info is None -+ else simulate_bonus_sampling_info.temperatures[:bs] -+ ), -+ ) - prepare_mamba_track_for_verify(batch) - with self._observers.segment(InfoSegment.TARGET_VERIFY): - if run_compact: -@@ -1012,24 +1240,53 @@ class DSparkWorkerV2(BaseSpecWorker): - and can_run_cuda_graph - and (run_compact or self._verify_planner.mode_value == "static") - ) -- accept = self._verify_executor.accept_and_finalize( -- folded_accept=folded_accept, -- bs=bs, -- verify_ids_2d=verify_ids_2d, -- target_logits=logits_output.next_token_logits, -- draft_block=draft_block, -- sampling_info=sampling_info, -- draft_input=draft_input, -- layout=layout, -- prefix_lens=prefix_lens, -- draft_tokens=draft_tokens, -- simulate_bonus_sampling_info=simulate_bonus_sampling_info, -- ) -- self.model_runner.ngram_embedding_manager.update_after_verify( -- verify_ids_2d=verify_ids_2d, -- req_pool_indices=batch.req_pool_indices, -- commit_lens=accept.commit_lens, -+ region_accept = None -+ if ( -+ not folded_accept -+ and can_run_cuda_graph -+ and not run_compact -+ and self._sampling_graph_eligible( -+ batch=batch, -+ proposal_folded=proposal.folded, -+ sampling_info=sampling_info, -+ simulate_bonus_sampling_info=simulate_bonus_sampling_info, -+ ) -+ ): -+ region_accept = self._sampling_accept_graph.run( -+ bs=bs, target_logits=logits_output.next_token_logits -+ ) -+ # The accept and its commits ran in a graph: the verify graph's fold or the -+ # sampling-accept region replayed right after it. -+ graph_accept = folded_accept or region_accept is not None -+ if region_accept is not None: -+ epilogue.note_static_verify(bs) -+ accept = region_accept -+ else: -+ accept = self._verify_executor.accept_and_finalize( -+ folded_accept=folded_accept, -+ bs=bs, -+ verify_ids_2d=verify_ids_2d, -+ target_logits=logits_output.next_token_logits, -+ draft_block=draft_block, -+ sampling_info=sampling_info, -+ draft_input=draft_input, -+ layout=layout, -+ prefix_lens=prefix_lens, -+ draft_tokens=draft_tokens, -+ simulate_bonus_sampling_info=simulate_bonus_sampling_info, -+ ) -+ engram_in_graph = ( -+ folded_accept and not run_compact and epilogue.folds_engram_commit -+ ) or ( -+ region_accept is not None and self._sampling_accept_graph.committed_engram - ) -+ # The static verify graph committed the engram history when it folded the accept. -+ if not engram_in_graph: -+ self.model_runner.ngram_embedding_manager.update_after_verify( -+ verify_ids_2d=verify_ids_2d, -+ req_pool_indices=batch.req_pool_indices, -+ commit_lens=accept.commit_lens, -+ ) - sampling_mask_capture = SpeculativeSamplingMaskCapture.from_logits( - sampling_info, - next_token_logits=logits_output.next_token_logits, -@@ -1051,6 +1308,11 @@ class DSparkWorkerV2(BaseSpecWorker): - chain_stride=self.verify_num_draft_tokens, - ) - -+ relay = self._future_relay_in_graph( -+ run_compact=run_compact, folded_accept=graph_accept -+ ) -+ if relay is not None: -+ relay.published_seq_lens = accept.new_seq_lens - if on_publish is not None: - if confidence is not None: - on_publish(accept.new_seq_lens, confidence=confidence) -@@ -1064,7 +1326,7 @@ class DSparkWorkerV2(BaseSpecWorker): - commit_lens=accept.commit_lens, - ) - -- folded_commit = folded_accept and epilogue.folds_commit -+ folded_commit = graph_accept and epilogue.folds_commit - # Consume in this step: every decode graph size shares one aux output, - # which the next target forward overwrites (resolve_aux_hidden_states_width). - if not folded_commit: -@@ -1108,11 +1370,15 @@ class DSparkWorkerV2(BaseSpecWorker): - bonus_tokens=accept.bonus, - new_seq_lens=accept.new_seq_lens, - ) -+ if relay is not None: -+ relay.published_bonus = next_draft_input.bonus_tokens - return GenerationBatchResult( - logits_output=logits_output, - next_token_ids=accept.out_tokens.reshape(-1), - accept_lens=accept.commit_lens, -- block_accept_lens=accept.commit_lens + accept.cap_trim_lens, -+ block_accept_lens=self._block_accept_lens( -+ accept=accept, folded_accept=graph_accept, bs=bs -+ ), - cap_lens=( - layout.verify_lens.to(torch.int32) if layout is not None else None - ), -@@ -1122,6 +1388,73 @@ class DSparkWorkerV2(BaseSpecWorker): - new_seq_lens=accept.new_seq_lens, - ) - -+ def _sampling_graph_eligible( -+ self, -+ *, -+ batch: ScheduleBatch, -+ proposal_folded: bool, -+ sampling_info, -+ simulate_bonus_sampling_info, -+ ) -> bool: -+ """An all-sampled static step the sampling-accept region reproduces exactly.""" -+ return ( -+ self._sampling_accept_graph is not None -+ and proposal_folded -+ and self._verify_planner.mode_value == "static" -+ and sampling_info is not None -+ and not sampling_info.is_any_greedy -+ and not sampling_info.need_top_k_sampling -+ and not sampling_info.need_top_p_sampling -+ and verify_logits_adjustments_are_noop(sampling_info) -+ and simulate_bonus_sampling_info is None -+ and not batch.has_grammar -+ ) -+ -+ def _future_relay_in_graph(self, *, run_compact: bool, folded_accept: bool): -+ """The FutureMap relay this step's static graph already scattered into -+ (SGLANG_OPT_DSV41_DSPARK_POST_FOLD), or None for the host scatter.""" -+ epilogue = self._verify_executor.verify_epilogue -+ if epilogue is None or run_compact or not folded_accept: -+ return None -+ relay = epilogue.future_relay -+ if relay is None or not relay.adopted: -+ return None -+ self.num_relayed_in_graph_steps += 1 -+ if self.num_relayed_in_graph_steps == 1: -+ logger.info("Seq lens and bonus relayed by the verify graph (first step).") -+ return relay -+ -+ def _begin_simulated_step_ahead(self, *, bs: int, simulate_bonus_sampling_info): -+ """Issued before the draft launch (neither write depends on it); a step that -+ turns out not fold-eligible ignores the sim bonus buffers.""" -+ executor = self._verify_executor -+ executor.begin_simulated_step() -+ epilogue = executor.verify_epilogue -+ if epilogue is not None and epilogue.simulate_fold: -+ epilogue.begin_sim_bonus( -+ bs, -+ ( -+ None -+ if simulate_bonus_sampling_info is None -+ else simulate_bonus_sampling_info.temperatures[:bs] -+ ), -+ ) -+ self.num_sim_draws_ahead += 1 -+ if self.num_sim_draws_ahead == 1: -+ logger.info( -+ "Simulated acceptance drawn ahead of the draft launch (first step)." -+ ) -+ -+ def _block_accept_lens(self, *, accept, folded_accept: bool, bs: int): -+ in_graph = ( -+ self._verify_epilogue.read_block_accept_lens(bs) -+ if folded_accept and self._verify_epilogue is not None -+ else None -+ ) -+ if in_graph is not None: -+ return in_graph -+ return accept.commit_lens + accept.cap_trim_lens -+ - def _commit_target_mamba_states_after_verify( - self, - *, diff --git a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml index 885433a1f7..523dee636b 100644 --- a/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml +++ b/inferencex-e2e/benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml @@ -5,8 +5,8 @@ base: identity: model: {} frameworks: - dynamo: "1.6.0.dev20261019" - sglang: "0.0.0.dev1+gc1c287a42" + dynamo: "1.6.0" + sglang: "0.0.0.dev1+g656331295" dynamo: install: false request_plane: tcp @@ -116,7 +116,6 @@ override_tp2_c16: override_tp4_c1: name: dsv41flash-fp4-gb300-dynamo-sglang-agentx-agg-tp4ep1-c1 - setup_script: dsv41flash-sglang-patches.sh roles: agg: gpus: 4 diff --git a/inferencex-e2e/configs/nvidia-master.yaml b/inferencex-e2e/configs/nvidia-master.yaml index 9134c25342..c5a248aa2e 100644 --- a/inferencex-e2e/configs/nvidia-master.yaml +++ b/inferencex-e2e/configs/nvidia-master.yaml @@ -9409,13 +9409,13 @@ dsv41flash-fp4-gb300-sglang-agentic-dspark: - { tp: 2, ep: 2, dp-attn: true, kv-offloading: none, spec-decoding: mtp, conc-list: [64, 128, 160], router: { name: sglang-router, version: "0.3.2" }, srt-recipe: agentic.yaml } - { tp: 4, ep: 1, kv-offloading: none, spec-decoding: mtp, conc-list: [1, 4, 16], srt-recipe: agentic.yaml } dsv41flash-fp4-gb300-dynamo-sglang-agentic-agg: - image: lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4@sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb + image: lmsysorg/sglang:nightly-dev-cu13-20261025-65633129@sha256:069efa1d6a2d58309529f53eeee34c39d69b1cdb455eaf7fb8de83e3fd0be727 model: deepseek-ai/DeepSeek-V4.1-Flash model-prefix: dsv41flash runner: cluster:gb300-nv precision: fp4 framework: dynamo-sglang - router: { name: dynamo-router, version: "1.6.0.dev20261019" } + router: { name: dynamo-router, version: "1.6.0" } multinode: true disagg: false srt-recipe-dir: dsv41flash/sglang/gb300-fp4/agentx diff --git a/inferencex-e2e/docs/waiver/4434.md b/inferencex-e2e/docs/waiver/4434.md deleted file mode 100644 index 8fb2842250..0000000000 --- a/inferencex-e2e/docs/waiver/4434.md +++ /dev/null @@ -1,42 +0,0 @@ -# Inference-engine patch waiver — PR #4434 - -Filed per [`docs/PR_REVIEW_CHECKLIST.md`](../PR_REVIEW_CHECKLIST.md) (image-provenance / patch item). One recipe variant in this PR patches the pinned serving-stack image before serving. The checklist prohibits this unless a filled-out waiver covers it. - -## Config covered - -- **Master config entry:** `dsv41flash-fp4-gb300-dynamo-sglang-agentic-agg` in [`configs/nvidia-master.yaml`](../../configs/nvidia-master.yaml). Only the TP4 c1 point is patched (`agg-variants.yaml:override_tp4_c1`). The c4, c16 and TP2 c16 points run the image as shipped. -- **Pinned image:** `lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4@sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb` -- **Patch entrypoint:** `setup_script: dsv41flash-sglang-patches.sh` in [`agg-variants.yaml`](../../benchmarks/multi_node/srt-slurm-recipes/dsv41flash/sglang/gb300-fp4/agentx/agg-variants.yaml) (`override_tp4_c1`) -- **Patch script:** [`benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh`](../../benchmarks/multi_node/srt-slurm-recipes/configs/dsv41flash-sglang-patches.sh) - -## What is patched - -The patch script makes two changes. Both are idempotent and serialized with `flock`. - -| Upstream PR/commit | What it changes | How | -|---|---|---| -| sglang [#45450](https://github.com/sgl-project/sglang/pull/45450), merged as `c82f7141` | Moves the host work between DSv4.1 DSpark decode graphs into the graphs on the megakernel path. Its new code paths are opt-in `SGLANG_OPT_*` / `SGLANG_DSPARK_*` env gates, and only the c1 point sets them. | `git apply` of `dsv41flash-sglang-patches/sglang-pr45450.patch` to `/sgl-workspace/sglang`. This is the merged squash backported to `c1c287a4`, with context conflicts in 4 files resolved to the `c1c287a4` side. | -| sgl-nvidia-mega `3333e4cf` (main at [#16](https://github.com/sgl-project/sgl-nvidia-mega/pull/16), including #7, #15 and #18) | Replaces the image's plugin pin `d47deb33`. That pin predates SGLang's kernel regrouping (sglang#45112) and the `TopKConfig` split (sglang#44912/#44913), which `c1c287a4` already contains. With `d47deb33`, `--enable-nvidia-megakernel` fails at startup. | `git fetch` + `checkout` of the pinned commit in the image's editable checkout `/sgl-workspace/sgl-nvidia-mega`. Its `pyproject.toml` is unchanged since `d47deb33`, so no reinstall is needed. | - -## Why the unmodified upstream image cannot run this benchmark - -The batch-1 megakernel recipe depends on the #45450 env gates, which do not exist in `c1c287a4`. It also depends on a plugin that builds on current SGLang. No public `lmsysorg/sglang` nightly contains #45450. - -- The dev-image builds of 2026-10-22 and 2026-10-23 failed at dependency resolution (the `python-dateutil`/`botocore` conflict addressed by sglang #45857 / #45860). -- SGLang's `docker/Dockerfile` still pins `SGL_NVIDIA_MEGA_COMMIT=d47deb33`. - -## Upstream PR / issue links - -- https://github.com/sgl-project/sglang/pull/45450 (merged) -- https://github.com/sgl-project/sgl-nvidia-mega/pull/16 (merged) -- https://github.com/sgl-project/sglang/pull/45857, https://github.com/sgl-project/sglang/pull/45860 (nightly build fix, open) -- https://github.com/sgl-project/sglang/pull/46030 (pins `SGL_NVIDIA_MEGA_COMMIT` to `3333e4cf`, open) - -## Removal plan - -Once sglang#46030 lands and a public `lmsysorg/sglang` nightly contains both #45450 and that sgl-nvidia-mega pin, make these changes in one PR: - -- move `dsv41flash-fp4-gb300-dynamo-sglang-agentic-agg` to that image; -- drop `setup_script` from `override_tp4_c1`; -- delete `dsv41flash-sglang-patches.sh` and `dsv41flash-sglang-patches/`; -- delete this waiver. diff --git a/inferencex-e2e/perf-changelog.yaml b/inferencex-e2e/perf-changelog.yaml index 9ec0676abb..3a74ab9b65 100644 --- a/inferencex-e2e/perf-changelog.yaml +++ b/inferencex-e2e/perf-changelog.yaml @@ -11155,9 +11155,9 @@ scenario-type: - agentic-coding description: - - "Move the aggregated points to lmsysorg/sglang:nightly-dev-cu13-20261021-c1c287a4 (digest sha256:b0473834763b2753e069cb96c1acaf235ba7fd632ccd9bbeb44da809c437fdeb) with the ai-dynamo 1.6.0.dev20261019 it ships, the image the disaggregated points already use. On this image dsv4-attn-backend auto picks FlashMLA MegaAttention (sglang#43922), which zero-pads the per-rank attention heads to 64, so TP4 c4/c16 and TP2/EP2 c16 pin dsv4-attn-backend flashmla and otherwise run the image as shipped, without the megakernel or the setup script." + - "Move the aggregated points to lmsysorg/sglang:nightly-dev-cu13-20261025-65633129 (digest sha256:069efa1d6a2d58309529f53eeee34c39d69b1cdb455eaf7fb8de83e3fd0be727) with the ai-dynamo 1.6.0 it ships. The image includes sglang#45450 and the sgl-nvidia-mega plugin at 6fd7ac30, so every point runs it as shipped." + - "On this image dsv4-attn-backend auto picks FlashMLA MegaAttention (sglang#43922), which zero-pads the per-rank attention heads to 64, so TP4 c4/c16 and TP2/EP2 c16 pin dsv4-attn-backend flashmla; their other engine settings are unchanged." - "TP4 c1 becomes a strict batch-1 NVIDIA megakernel point: max-running-requests 1, cuda-graph-max-bs-decode 1, --enable-nvidia-megakernel with 42 kernel slots, the sglang#45450 decode-graph gates, SWA prefix tails 128, prefill-decode interval 16, LPM scheduling and NCCL_CUMEM_ENABLE/NCCL_MNNVL_ENABLE off." - "TP4 c1 also sets kv-cache-dtype fp8_e4m3 and SGLANG_SPEC_TP_SYNC=rng,-dspark-accept-sample as in the reference BS1 recipe, and mem-fraction-static 0.91 (the reference launch's resolved default; the base recipe sets 0.8). It drops cuda-graph-backend-prefill: disabled, so prefill uses the image default, which disables the prefill CUDA graph for DeepSeek-V4." - - "Only TP4 c1 applies sglang#45450 (merged after the October 21 nightly) and checks out sgl-nvidia-mega 3333e4cf over the image's d47deb33 at startup (dsv41flash-sglang-patches.sh); waiver in docs/waiver/4434.md." - "Include the unchanged disaggregated points in the sweep so the curve is complete." pr-link: https://github.com/SemiAnalysisAI/InferenceX/pull/4434