Skip to content

[Perf] speculative: opt-in step CUDA graph and fused verify / relay paths for EAGLE v2 chains - #46211

Open
nvrohanv wants to merge 8 commits into
sgl-project:mainfrom
nvrohanv:eagle-step-cuda-graph
Open

nvrohanv wants to merge 8 commits into
sgl-project:mainfrom
nvrohanv:eagle-step-cuda-graph

Conversation

@nvrohanv

@nvrohanv nvrohanv commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

At one to four requests with topk-1 EAGLE v2 chains, a decode step on a fast model is a few milliseconds, and a large
share of it is host work and small launches between the per-stage CUDA graphs (draft, target verify, draft extend):
the verify result's three broadcasts, the sampling-info setup, the relay stash and gathers, the draft-extend tail, and
the step graph's input copies. This PR adds one opt-in flag, --enable-speculative-step-cuda-graph, which captures the
decode step as one CUDA graph and turns on six pieces that remove that work. With the flag off (the default), each
changed file runs its existing code. The pieces do not depend on any model or on the megakernel layer.

Modifications

Every piece below is on with --enable-speculative-step-cuda-graph and off without it (the default).

piece test / bisect override what it does outputs
child-graph splice none (used by the step graph) a full-backend graph replay inside an active capture is recorded as a child-graph node unchanged
step CUDA graph none (the flag itself) each eligible decode step (draft, target verify, draft extend and the eager work between them) is captured once per key and replayed as one CUDA graph; batch size up to 8; the first two steps of each key run the existing path bitwise (replays equal eager steps)
packed verify broadcast SGLANG_SPEC_PACKED_VERIFY_BROADCAST one collective per broadcast site instead of three bitwise
lean sampled verify SGLANG_SPEC_LEAN_SAMPLED_VERIFY temperature through a broadcast view; the target-only tree sampling path without the zero-filled draft_probs bitwise
fused relay SGLANG_SPEC_FUSED_RELAY one scatter launch for the relay stash; row views instead of gathered copies for a single request bitwise
fused draft-extend tail SGLANG_SPEC_FUSED_DRAFT_EXTEND_TAIL a split-row argmax whose last launch also writes the unit probabilities and the DSA seed rows; meant for use with the step graph, which captures it bitwise
fused input copy SGLANG_SPEC_STEP_GRAPH_FUSED_INPUT_COPY the step graph's input copies in one launch (13 copies at batch size 1) bitwise
chunked verify sampling SGLANG_SPEC_CHUNKED_VERIFY_SAMPLING (under the lean sampled verify) the target-only sampling kernel split into per-chunk statistics and a finish kernel, with the same floating-point operations in the same order bitwise
  • One flag: an override that is not set follows the flag as resolved at startup, so a setup that turns the flag off
    (pipeline parallelism, attention DP, topk above 1, ...) turns the six pieces off too. =0 turns one piece off
    under the flag, for bisecting; =1 turns it on without the flag, for tests. Each piece keeps its own eligibility
    checks and falls back to the existing code where they fail.

  • Credit: the fused relay carries the change proposed in [qwen 3.8 next] Fuse speculative relay payload stores and avoid single-request gathers #41170 behind a switch, rebased onto the current FutureMap;
    the fused draft-extend tail uses the two-stage argmax in row_argmax.py, the form proposed for the draft argmax in
    [qwen 3.8 next] Fuse exact greedy chain verification with argmax finalization #41172. The chunked kernels set their shared memory with runtime::set_max_dynamic_smem_per_device ([JIT] Clean up kernel headers: move runtime helpers, add once.h #41147).

  • Related PRs, both now on SGLang main (this branch merges it): [Feat] [NVIDIA] megakernels: Qwen3.5 binding and EAGLE entry wiring for NVIDIA megakernel plugins #45266 adds a Qwen3.5 binding for megakernel plugins,
    runs a plugin's EAGLE draft entries in the draft and draft-extend graphs and captures a megakernel's KV-length
    attention graph variants; without --enable-nvidia-megakernel it changes nothing. [Perf] [NVIDIA] speculative: Move the host work between Qwen3.5 MTP decode graphs into the graphs (1/2) #45474 moves the host work between
    the Qwen3.5 MTP decode graphs into graphs, into fewer launches or off the critical path, each piece behind a switch
    that defaults to off; among them are post-verify CUDA graphs for the EAGLE verify's sampling, acceptance and commits,
    and a sampled verify result sent in one broadcast instead of three (the idea of this PR's packed verify broadcast; the
    two now share one allocation, see Base below). This PR captures the whole decode step for any model with full decode
    graphs and needs no megakernel; a step that does not replay exactly the three per-stage graphs is never captured and
    runs the existing path.

  • Limitation: while --enable-speculative-step-cuda-graph is on, /update_weights_from_disk with
    recapture_cuda_graph is refused before any weight is loaded. The step graph replays the per-stage graphs it
    captured, and a recapture replaces their runners; recapture support is a follow-up.

  • Main's verify opt-ins: with SGLANG_ENABLE_EAGLE_POST_VERIFY_CUDA_GRAPH set ([Perf] [NVIDIA] speculative: Move the host work between Qwen3.5 MTP decode graphs into the graphs (1/2) #45474's post-verify graphs run their
    own graphs inside the verify) or SGLANG_Q35MF_EDGE_SPARSE_VERIFY_SAMPLING set (it picks its top-k branch per batch,
    outside the step graph's key), the launch turns --enable-speculative-step-cuda-graph off with a warning naming the
    variable and keeps the per-stage graphs.

  • Start-up warm-up: when the flag is on and a step graph runner is active, the HTTP server's start-up sends short
    requests with the sampling that a chat request setting no sampling field resolves to (the chat API's own
    to_sampling_params over the model's generation config; the tokenizer manager merges --preferred-sampling-params
    into it as into any request), in batches of 1, 2, ..., N requests per DP rank. N is the smallest of 8, the largest
    batch size of the per-stage decode graphs and --max-running-requests per DP rank. Each batch is one request with
    distinct 3-token prompts and 64 new tokens; the tokenizer manager sends it to the scheduler in one message, so with
    one DP rank its prompts are prefilled together and decode as one batch. The step graph therefore captures the key of
    every batch size from 1 to N, as client requests without sampling fields produce it, before the server takes
    requests; SGLang's own warm-up request captures the greedy batch-size-1 key. A batch size that still has no
    unconstrained key with the warm-up's sampling flags (greedy, top-k, top-p, min-p) afterwards gets one more batch; if
    it is still missing, a warning names it and its key is captured at first use.
    One log line gives the warm-up's time and each captured key with its memory. The warm-up is skipped with
    --skip-server-warmup and in the offline engine, and with SGLANG_RUST_SERVER=1 one log line says it is skipped;
    then every key is captured at its first use, as before.

  • Start-up cost: with SGLang's own warm-up request, the server handles 1 + N(N+1)/2 requests per DP rank at start-up
    (2 at --max-running-requests 1, 37 at 8; one more batch for a missing size); the N(N+1)/2 added ones each have a
    3-token prompt and 64 new tokens. They appear in the server's request metrics like SGLang's own warm-up request, so
    a client that checks for a server with no earlier requests has to allow for them. In the GLM-5.3 runs below
    (8 x B300, TP 8), the warm-up took 7.7 s at --max-running-requests 8, on a host where the same build had started
    before, and 49.0 s at --max-running-requests 1, on the first start of this build on its host. The step graphs then
    held 394 MB per GPU at --max-running-requests 8 (batch sizes 1 to 8 sampled, 372 MB, plus the greedy batch-size-1
    key, 22 MB) and 44 MB at 1.

  • Memory: a key is captured only when every rank has free device memory of at least the largest key captured so far
    (256 MiB before the first) plus 1 GiB. If that check fails while PyTorch's caching allocator holds enough unused
    memory on every rank to cover the need, that cache is released once for the key (torch.cuda.empty_cache(), at
    most once per key and 32 times per process) and the check is repeated. Otherwise that key's steps run the existing
    path, the capture is retried every 256 steps, and each rank logs the refusal once per key with its free, needed,
    reserved and allocated memory; each release is logged with the free memory before and after it.
    /get_server_info reports under spec_step_cuda_graph the memory_refusals count, the last_memory_refusal
    (batch size, greedy or sampled, constrained or not, and those four memory figures), the cache_releases count,
    the captured_keys (batch size, greedy or sampled, the top-k / top-p / min-p flags, constrained or not, and MB of
    each), the runner's max_batch_size and the caching allocator's num_alloc_retries and num_ooms. Device memory
    in use can grow
    while serving, so a key first met while serving (a greedy batch above 1, a constrained batch, or a batch size the
    start-up warm-up did not capture) may still be refused (see the agentic-trace runs below for the previous
    revision, which captured batch size 1 only at start-up).

  • Kernel inventory: kernels/ops/speculative/__init__.py registers the fused draft-extend tail
    (speculative.draft_extend_tail, Triton, CUDA only) next to div_argmax, as unit/kernels/test_kernels_namespace.py
    requires of a public kernel entry point.

  • Docs: the new flag in server_arguments.mdx; the flag, its six pieces and their overrides, the start-up warm-up,
    the memory check and the cache release in speculative_decoding.mdx.

  • Tests in this PR: cuda_graph/spec_step/test_child_graph_capture.py, cuda_graph/spec_step/test_eagle_step_cuda_graph_runner.py,
    unit/managers/test_single_request_relay.py, unit/spec/test_spec_step_graph_fused_input_copy.py (1 GPU),
    unit/spec/test_eagle_step_cuda_graph_eligibility.py (with the memory refusal, the cache release, the start-up
    warm-up and the fallback for main's verify opt-ins), unit/spec/test_simulated_accept_fixed_shape.py,
    unit/spec/test_spec_packed_verify_broadcast.py, unit/spec/test_spec_step_graph_switches.py (CPU), one line in
    unit/spec/test_spec_registry.py's fake server arguments, and
    e2e/models/test_dsa_glm52_nvfp4_tp_mtp_step_graph.py (4 GPUs, GLM-5.2 NVFP4).

  • Kernel tests of the new CUDA kernels (under test/registered/, 1 GPU each):

    file what it checks
    kernels/ops/speculative/test_spec_chain_verify_sampling.py for chains, tree_speculative_sampling_target_only three ways (stock, lean, two-launch chunked) returns the same predicts / accept_index / accept_token_num bit for bit over random, flat, peaked and tail-only distributions, edge coins, every vector width, one-chunk vocabularies, a zero-mass row and CUDA graph replay
    kernels/ops/speculative/test_spec_draft_extend_tail.py the fused topk-1 draft-extend tail equals the stock statements bit for bit (values, dtypes, shapes, strides) at batch sizes 1, 2 and 8 with vocabulary 154,880: ties at the first / last / random columns, +inf, -inf and NaN rows, select indices from real and forced acceptance, graph replay
    unit/layers/test_next_relay.py the relay scatter kernel (scatter_spec_extras) at batch sizes 0, 1 and 129 and widths 1, 17 and 2,560, in CUDA graph replay, with dense sources and indices and with sources whose row stride is wider than their width (a column slice of a wider buffer) and a stride-2 index tensor

Base and revisions: this branch is this PR's commit 3ba3fd1d2e on SGLang main dba22e9b68, a fix that matches
sampling modes in the start-up warm-up's missing-key check (bcf3db0ab6, above), a merge of SGLang main 286e018594,
three commits on top, and merges of SGLang main 00394f9f35 and 9e9296fdf3:

  • The merge of 286e018594 kept both sides of four conflicts: arg_groups/field_order.py (main's new fields, then
    enable_speculative_step_cuda_graph last), entrypoints/http_server.py (this PR's warm-up line for the Rust server,
    then main's rust_server_sidecar block), speculative/spec_utils.py (main's KV-cache imports and this PR's
    child_graph_capture import) and speculative/eagle_utils.py: [Perf] [NVIDIA] speculative: Move the host work between Qwen3.5 MTP decode graphs into the graphs (1/2) #45474 added the same packed verify broadcast behind
    SGLANG_Q35MF_EDGE_PACKED_VERIFY_BCAST (_verify_outputs); eagle_sample keeps this PR's _alloc_verify_outputs
    and _broadcast_verify_outputs, and _alloc_verify_outputs now allocates through _verify_outputs, packed when
    either variable is set, with the same layout.
  • Port to main: [Refactor] bcg: Record graph breaks at capture without running them #46719 records an eager_on_graph break at capture without running it, so a break
    returns None ([Refactor] bcg: Delete capture leftovers and rename capture_stub to on_capture #46792 renamed capture_stub to on_capture): the step graph's grammar mask break
    fills the runner-owned mask and returns None, and the child-graph test's break writes into a buffer the test owns.
    [Perf] [NVIDIA] speculative: Move the host work between Qwen3.5 MTP decode graphs into the graphs (1/2) #45474 samples the simulated acceptance length with the worker's generator; the step graph's override takes that
    generator and keeps it with the sample's other arguments, so a replay samples with it as the eager step does.
  • Three registered CPU tests that already failed with the filed revision now pass: test_full_cuda_graph_backend
    (FullCudaGraphBackend gets class defaults for _keep_raw_graph and graph_epoch), test_backend_resolution
    (resolve_decode_backend reads enable_speculative_step_cuda_graph only when the speculative config is published)
    and test_spec_registry (its fake server arguments set enable_speculative_step_cuda_graph=False).
  • The fallback for main's verify opt-ins (above), with a CPU test.
  • The merge of 00394f9f35 had no conflict, and no line of this PR changed in it.
  • The merge of 9e9296fdf3 had one conflict, in layers/attention/dsa_backend.py: main ([Feat] sail: support sail fa3 and flashmla [3/N] #45946)
    adds three methods to DeepseekSparseAttnBackend that wrap its FlashMLA calls, at the place where this PR adds
    out_graph_metadata_capturable. Both are kept, this PR's method first. [Feat] sail: support sail fa3 and flashmla [3/N] #45946 also routes the backend's FlashMLA
    calls through the new methods, which call the same functions as before; no line of this PR calls them, and no line
    of this PR changed in the merge.

Earlier revisions: against the revision before it (9258cb78da, also on SGLang main dba22e9b68), 3ba3fd1d2e
captures the keys of batch sizes 1 to N at start-up instead of batch size 1
only, releases PyTorch's cached memory once before a refused capture, reports captured_keys, cache_releases and
max_batch_size, and updates the docs and the eligibility tests (5 files). The revision before that (f35a9e5f82,
on SGLang main 74c08f3dc5) had no start-up warm-up, no memory-refusal diagnostics and no kernel-inventory
registration. Apart from those additions, the changes for SGLang main dba22e9b68 since the revisions measured on SGLang
main af856717c2 were these:

  • arg_groups/field_order.py appends enable_speculative_step_cuda_graph at the end of POSITIONAL_FIELD_ORDER
    (after main's newest field), as main's positional-slot test requires.
  • In managers/overlap_utils.py the fused relay branch of stash comes after main's check that skips the scatter when
    the graph has already published it. That check's relay is not used by the EAGLE chains measured below, so they run
    the same code as before.
  • The conflict in speculative/eagle_utils.py was resolved with this PR's changed lines as before; main's
    verify-sampling dispatch reaches, on CUDA, the same tree_speculative_sampling_target_only that this PR extends.
  • The typing import of speculative/eagle_worker_v2.py also takes main's Callable.

The accuracy results and the per-step table below were measured on SGLang main af856717c2 with the earlier
revisions each one names. The first agentic-trace table below was measured on SGLang main dba22e9b68 with 3ba3fd1d2e,
the megakernel hooks PR at 465a9dd5b7, #45795 at its head of that time 29e8125875 and the GLM-5.3
plugin PR at ad0bf9103d; the other agentic-trace runs below name their revisions. Before those runs,
3ba3fd1d2e was checked with the same PRs on one 8-GPU host with dummy weights: at --max-running-requests 4 and 8,
the start-up warm-up captured the sampled keys of batch sizes 1 to 4 and 1 to 8 and the greedy batch-size-1 key on
all 8 ranks before the server was ready, and short synthetic loads of 2 and 4 concurrent requests (at 4) and of 4
and 8 (at 8) then replayed every decode step, with no memory refusal and no new key.

On SGLang main 286e018594, before the merge of 00394f9f35, this branch was checked with the megakernel hooks PR
(ba86b681b5), #45795 (at 6ffe9cd46c) and the up-to-date GLM-5.3 plugin PR (b8a85c739b), on
8 x B300. The GPU checks ran this branch at 0d39d7fdbb, before the commit with the fallback for main's verify
opt-ins, except the fallback check (the last item), which ran the head of that time. On CPU, this PR's CPU tests
pass, and the registered CPU suites it
touches fail on no test id that does not also fail on SGLang main itself. On the GPU host, this PR's test files (all but the 4-GPU e2e) and unit/spec/test_spec_registry.py pass,
each file in its own process, with and without SGLANG_IS_IN_CI (0 failed).

  • GLM-5.3 NVFP4, 3 draft steps, with --enable-nvidia-megakernel --enable-speculative-step-cuda-graph --hicache-async-ready-sync at --max-running-requests 8: the start-up warm-up captured the sampled keys of batch sizes 1 to 8 and the greedy
    batch-size-1 key on 8 / 8 ranks (37 start-up requests, no memory refusal), and GSM8K-200 (5-shot, greedy) scored
    0.985 / 0.990 at 4 concurrent requests and 0.985 / 0.995 at 8 (all on / stock).
  • GLM-5.2 NVFP4 with the same flags and 5 draft steps: a regex request and a JSON-schema request (temperature 0) both
    returned HTTP 200, the first with output that fully matches the regex, the second with output that parses and
    validates against the schema.
  • With SGLANG_SIMULATE_ACC_LEN set (dummy weights): the start-up warm-up ran its 37 requests and captured its keys with
    no capture error, and decode steps replayed the step graph.
  • With SGLANG_ENABLE_EAGLE_POST_VERIFY_CUDA_GRAPH=1 (dummy weights), the server logs
    enable_speculative_step_cuda_graph disabled: SGLANG_ENABLE_EAGLE_POST_VERIFY_CUDA_GRAPH is not supported. Falling back to the per-stage CUDA graphs.
    and serves every request with the megakernel on and the per-stage graphs; on that head the eligibility test file,
    with its fallback test, also passes on the GPU host with and without SGLANG_IS_IN_CI.

After each merge of SGLang main (00394f9f35, then 9e9296fdf3), this branch was checked again on CPU: SGLang's
pre-commit checks pass on this PR's files; on that main, alone and together with the megakernel hooks PR (merged with
the same main), this PR's CPU tests pass, and the registered CPU suites it touches fail on no test id that does not
also fail on SGLang main itself. After the merge of 9e9296fdf3, this branch was checked again on 8 x B300 together
with the megakernel hooks PR (merged with the same main), #45795 (at 6ffe9cd46c) and the GLM-5.3
plugin PR, with GLM-5.3 NVFP4 and the same three flags at --max-running-requests 8, at 3 and at 5 draft steps: the
start-up warm-up captured the sampled keys of batch sizes 1 to 8 and the greedy batch-size-1 key on 8 / 8 ranks (37
start-up requests, no memory refusal), the step graph replayed on the DSA attention backend with no fallback, and
GSM8K-200 (5-shot, greedy) scored 0.995 with 3 draft steps and 0.990 with 5 at 4 concurrent requests, and 0.985 with
3 at 8 (one run each). The other GPU checks above ran before these merges.

Accuracy Tests

GLM-5.3 NVFP4, 8 x B300, TP 8, MTP (EAGLE, 3 steps, topk 1, 4 draft tokens), real acceptance, this PR alone on SGLang
main af856717c2 (stock attention and MoE). "On" is --enable-speculative-step-cuda-graph with the six overrides set
to 1, the same pieces as the flag alone; "off" is the flag off with no override set:

check result
on vs off, 40 prompts (20 greedy + 20 server-default sampling, incl. constrained tool-call rows; sent by a local script, not part of this PR) the same tokens on 40 / 40 (two off launches agree on 40 / 40)
step graph captured on 8 / 8 ranks
GSM8K-200, on 0.995, acceptance length 2.994
unit and kernel tests (this PR's unit files other than test_spec_step_graph_switches.py + its 3 kernel test files, run on an earlier revision of this PR with an earlier revision of the megakernel hooks PR (#46210) and an earlier version of the HiCache change of #45795 applied), also with SGLANG_IS_IN_CI=true all pass
unit/spec/test_spec_step_graph_switches.py (CPU: launch arguments parsed, resolved and published as a scheduler process publishes them), also with SGLANG_IS_IN_CI=true passes: the flag alone turns on all six pieces, each override =0 turns off only its piece, and without the flag (or when startup turns it off) all six are off
this revision's CPU tests of the start-up warm-up, the memory refusal and the cache release (unit/spec/test_eagle_step_cuda_graph_eligibility.py) and of the kernel inventory (test_reclassified_public_entry_points_are_inventoried in unit/kernels/test_kernels_namespace.py) pass: a memory refusal is counted and logged once per key; the cache is released only when it can cover the need, at most once per key and up to a cap, and with enough free memory the check is one collective as before; the warm-up's sampling gives the same capture key as a chat request without sampling fields, for six generation configs; the warm-up captures the keys of batch sizes 1 to N (for example 1 to 4 at --max-running-requests 4 and 1 to 8 at 16), one request per batch size k with k distinct prompts per DP rank, gives a missing size one more batch and then a warning (a key of another sampling mode or a constrained key does not count), and sends nothing without an active step graph runner; the draft-extend tail is in the kernel inventory

The "on" runs above set the six overrides to 1 because they were made on earlier revisions of this PR, in which the
overrides did not yet follow the flag; in this revision the flag alone turns on the same six pieces
(the test_spec_step_graph_switches.py row).

On the stack of the unit and kernel test row above, the draft-extend tail and relay scatter files also pass when run
as python3 <file> (15 and 18 passed).

On 4 x B300 with this PR alone on SGLang main af856717c2, the GLM-5.2 NVFP4 step-graph e2e
(e2e/models/test_dsa_glm52_nvfp4_tp_mtp_step_graph.py, 3 tests, real acceptance) passes with the step graph alone
(the six pieces off): GSM8K 0.952 (acceptance length 3.96) and the step graph replays with no capture failure.
That run used an earlier revision of this PR, in which the flag turned on the step graph alone. With the flag that
also turns on the six pieces, the e2e was rerun with 3ba3fd1d2e alone on SGLang main dba22e9b68 (4 x B300): 3
tests OK, GSM8K 0.942, acceptance length 3.97.

Speed Tests and Profiling

Per decode step at one request (--max-running-requests 1): GLM-5.3 NVFP4 on 8 x B300, TP 8, MTP (EAGLE, 3 steps,
topk 1, 4 draft tokens), fixed acceptance length 2.99. Stack: SGLang main af856717c2 with earlier
revisions of this PR and of the megakernel hooks PR (#46210) and an earlier version of the deferred HiCache
ready-count sync now proposed in #45795 (--hicache-async-ready-sync), plus an earlier revision of the
sgl-nvidia-mega GLM-5.3 target and draft specs (sgl-project/sgl-nvidia-mega#24; slots attention,moe,hops,draft, embedding replication
on). Workload (a local client script, not part of this PR): a synthetic multi-turn chat with a 253K-token prefix, then a 150-token and a 1,000-token reply;
HiCache write-back with a 270 GB host pool. ms per decode step = the median client-side chunk interval of the
1,000-token reply after its first 50 chunks.

  • On: --enable-speculative-step-cuda-graph with the six overrides set to 1 (the same pieces as the flag alone).
    Off, for a single piece: that piece's override set to 0, everything else on (for the step CUDA graph row: the flag
    off, the six overrides set to 1). Off, for "all of this PR": the flag off and no override set. The megakernel and
    --hicache-async-ready-sync stay on in every run of this table. Without the step graph the fused input copy has
    nothing to copy, and without the lean sampled verify the chunked verify sampling, which runs under it, is off too.
  • Order as run, one server launch per run, all on one host: on; all of this PR off, twice; on; the deferred HiCache
    sync flag off, twice (not reported here); on; step CUDA graph off, packed verify broadcast off; on; lean sampled
    verify off, fused relay off; on; fused draft-extend tail off, fused input copy off; on; chunked verify sampling off;
    on.
  • "On" is the mean of the two all-on runs just before and after the row's block; "off" is the row's off run (for
    "all of this PR", the mean of its two). The difference is off - on (positive: the piece makes the step shorter),
    computed before rounding.
piece ms per decode step, off on difference against the all-on run-to-run range (0.10 ms)
all of this PR 5.53 5.41 +0.12 larger
step CUDA graph 5.41 5.44 -0.03 within
packed verify broadcast 5.37 5.44 -0.07 within
lean sampled verify 5.40 5.43 -0.03 within
fused relay 5.45 5.43 +0.02 within
fused draft-extend tail 5.40 5.43 -0.03 within
fused input copy 5.40 5.43 -0.03 within
chunked verify sampling 5.44 5.45 -0.01 within

The seven all-on runs span 0.10 ms (5.37 to 5.47 ms per step). Only the difference for the whole PR is larger than
that range; each single piece's difference is within it.

On a multi-turn agentic coding trace, the public Hugging Face dataset semianalysisai/cc-traces-weka-062126 (split
train), replayed as recorded (about one hour per run; its requests set no sampling field, so they run with the
server's default sampling): GLM-5.3 NVFP4 on 8 x B300, TP 8, MTP as above, fixed acceptance length 2.99, HiCache
write-back with a 270 GB host pool, --cuda-graph-max-bs-decode equal to --max-running-requests, SGLang's compiled
Rust radix-tree core in every run. "Stock" is SGLang main dba22e9b68 with none of the flags below. "All on" is SGLang
main dba22e9b68 with 3ba3fd1d2e, the megakernel hooks PR (465a9dd5b7), #45795 at its head
29e8125875 and the GLM-5.3 plugin PR (ad0bf9103d), launched with --enable-nvidia-megakernel --enable-speculative-step-cuda-graph --hicache-async-ready-sync and no override set. The servers of each row ran on
one host in one session. Each cell is all on / stock.

client concurrency --max-running-requests p90 interactivity p90 end-to-end normalized interactivity p90 time to first token step graph keys in the all-on run
1 1 1.47x 1.20x 0.95x batch size 1, greedy and sampled, captured at start-up; the step graph replayed on every decode step (208,495 replays, 0 steps on the existing path)
4 8 1.31x 1.18x 1.01x batch sizes 1 to 8 sampled and batch size 1 greedy, captured at start-up (394 MB per GPU); the step graph replayed on every decode step (270,857 replays, 0 steps on the existing path), with no memory refusal

p90 interactivity is 1 / the p90 inter-token latency and p90 end-to-end normalized interactivity is 1 / the p90
end-to-end time per output token (higher is better for both); for p90 time to first token, lower is better. Usage
counts on this SGLang main include a known reasoning-token over-count at max_tokens; the numbers here count each
request's output tokens as its usage completion_tokens. The all-on server ran once per row. The stock server ran
twice per row, on the same host in the same session, and the table uses its second run; against its first run, all
on gives 1.47x p90 interactivity and 1.34x p90 end-to-end normalized interactivity at one user, and 1.25x and 1.12x
at four users.

The gain over stock includes the megakernel's (the GLM-5.3 plugin PR reports it without this PR). At four users, the
all-on server was also run with this PR's previous revision (9258cb78da, which captures only the batch-size-1 keys
at start-up), on the same host in the same session. There the sampled keys of batch sizes 2 to 5 (the sizes that run
reached) were first met while serving, when 7 of the 8 ranks (batch sizes 2 and 3) or 1 of them (batch sizes 4 and
5) had 372-750 MiB free against 1,046 MiB needed, with about 34 GiB on each of those ranks held in PyTorch's caching
allocator but not allocated. The capture check refused them 266 times, and 86 % of the decode steps replayed (36,654
ran the existing path). With this revision (the table's four-user run) there was no memory refusal and no step on the
existing path. This is one run each, so no speed-up is claimed from it. At one user, on the same host in the same
session, this revision and the previous one gave the same p90 interactivity (one run each).

In an earlier session on SGLang main 74c08f3dc5, with an earlier revision of this PR that captured the batch-size-1
keys at start-up, the all-on server was also run at one user without that warm-up (that revision's code without the
warm-up but with the diagnostics, and the plugin PR's revision ef1ead3681), on the same host in the same session.
There the sampled batch-size-1 key was refused for memory for the whole run, with 504-506 MiB free on 7 of 8 ranks
against 1,046 MiB needed (most likely trigger: #45565, the larger default MLA prefill CUDA graph;
not isolated), so every step ran the existing path with this PR's other pieces. With the warm-up, p90 interactivity
was 1.005x and p90 end-to-end normalized interactivity 1.010x that run's (one run each): at one user the warm-up makes
the step graph run, but it is not a measurable speed-up there, in line with the step CUDA graph row of the per-step
table above. In another session on that main, with the revision f35a9e5f82 (where, too, the step graph ran no
sampled step at one user), this PR's other pieces and the deferred HiCache sync together gave about 2 % higher p90
interactivity than the megakernel server without them, with p90 end-to-end normalized interactivity about the same
(one run each).

On SGLang main 286e018594, the same recipe with this branch, the megakernel hooks PR,
#45795 (at 6ffe9cd46c) and the up-to-date GLM-5.3 plugin PR (the revisions named above; this branch
at 0d39d7fdbb), launched with the same three flags, against SGLang main 286e018594 with none of them (one run per
server; the two servers of each row on one host in one session; each cell is all on / stock):

client concurrency --max-running-requests p90 interactivity p90 end-to-end normalized interactivity p90 time to first token step graph in the all-on run
1 1 1.47x 1.33x 0.80x replayed on every decode step (209,083 replays, 0 steps on the existing path)
4 8 1.26x 1.16x 0.96x replayed on every decode step (263,856 replays, 0 steps on the existing path), with no memory refusal

The gain over stock includes the megakernel's, as above.

Checklist

How to run

python -m sglang.launch_server ... --speculative-algorithm EAGLE --speculative-eagle-topk 1 --speculative-num-steps 3 \
  --speculative-num-draft-tokens 4 --enable-speculative-step-cuda-graph

To bisect, set one piece's override to 0 (for example SGLANG_SPEC_FUSED_RELAY=0) with the same command.


CI States

Latest PR Test (Base): ⊘ Skipped -- a maintainer comments /tag-and-rerun-ci to run CI tests.
Latest PR Test (Extra): ⊘ Skipped -- a maintainer comments /tag-and-rerun-ci to run CI tests.
Latest PR Test (AMD ROCm 10): ❌ Run #40886818721

Tip

Base CI only covers the core cases, and its workload may not exercise your change. Use /rerun-test to run the tests your change touches, or copy this prompt for an agent:

Find the registered tests this PR affects and run them with /rerun-test, following https://github.com/sgl-project/sglang/blob/main/.agents/skills/rerun-test/SKILL.md

@mintlify

mintlify Bot commented Oct 24, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit 93d499a.

Approve preview

…aths for EAGLE v2 chains

Opt-in with one flag, outputs bitwise identical:
--enable-speculative-step-cuda-graph captures each EAGLE v2 decode step as
one CUDA graph, built on splicing full-backend graphs into an enclosing
capture, and turns on six pieces: one TP broadcast for the verify result, a
lean sampled verify for chains, fused relay stores with single-request relay
views, a fused topk-1 draft-extend tail, one launch for the step graph's
input copies, and chain verify sampling in two launches. Each piece has a
SGLANG_SPEC_* environment variable as a test / bisect override (0 turns it
off under the flag). With the flag off and no override set each changed file
runs its existing code.
A weight update that asks for a CUDA graph recapture is refused while the
step graph is on.
The fused relay carries the change proposed in sgl-project#41170; the draft-extend tail
uses the two-stage argmax form proposed in sgl-project#41172.

At startup, when the flag is on and a step graph runner is active, the HTTP
server runs, for each batch size k from 1 to N, one batch of k requests per
DP rank with the sampling a chat request without sampling fields resolves
to (the chat API's own to_sampling_params over the model's generation
config). N is the smaller of the runner's largest batch size (at most 8,
and at most the largest of every per-stage graph) and the maximum number of
running requests. A batch of token ids reaches the scheduler as one
message, so its requests decode as one batch of k, and the step graph
captures each of those keys before serving; a batch size still without a
key gets one more batch, then a warning. The log lists each captured key
with its memory and the time the warmup took. The warmup is skipped with
--skip-server-warmup, and with SGLANG_RUST_SERVER one line says so. A
failed capture memory check is logged once per key on every rank with the
free, needed, reserved and allocated memory. When PyTorch caches enough
unused memory, the cache is released once for that key (at most 32 times
per process) and the check repeats. /get_server_info reports
memory_refusals, last_memory_refusal, cache_releases, captured_keys,
max_batch_size and the allocator's num_alloc_retries / num_ooms.

The draft-extend tail is registered in the kernel inventory (Triton, CUDA
only). Also kernel tests for chain verify sampling, the draft-extend tail
and the relay scatter.
@nvrohanv
nvrohanv force-pushed the eagle-step-cuda-graph branch 2 times, most recently from 9258cb7 to 3ba3fd1 Compare October 26, 2026 02:19
The sampled startup warmup added by sgl-project#46211 checks whether every requested
batch size has a captured graph. Its previous check accepted any key of
that size, so the greedy key left by the normal server warmup could hide
a missing default-sampling key. That suppressed the intended retry and
warning even though the graph needed by default chat requests was absent.

Resolve the warmup request's effective SamplingParams, including preferred
sampling parameters, and match greedy/top-k/top-p/min-p flags as well as
batch size. Exclude constrained keys. Expose the existing capture key's
filter flags in runner stats so the check can distinguish those modes.

A missing matching key receives the existing single retry, followed by a
warning if it is still absent. Successful captures behave as before; this
does not guarantee capture when memory is insufficient. Kernel arithmetic,
collectives, sampling, and graph replay are unchanged. The original static
table protocol disables step graphs, so this fix does not affect that path.

Add regression cases for greedy, constrained, top-k, top-p, and min-p key
mismatches, and make the fake server honor the request's sampling flags.
Remove the redundant assertion that exactly six switches are declared;
retain switch resolution, override, and fallback behavior coverage.

Validation: reproduce the missed retry with the previous implementation;
related CPU tests pass (30 tests, 57 subtests); changed-file pre-commit passes.
@YAMY1234

Copy link
Copy Markdown
Collaborator

Completed the companion GLM-5.3 NVFP4 static-table recheck on 8×B300 TP8 using step 3ba3fd1d2e, hooks 465a9dd5b7 and mega ad0bf9103d on base dba22e9b68: two fresh launches per configuration, two passes per launch, with relative gains consistent with the original table. Full table and protocol: sgl-project/sgl-nvidia-mega#24 (comment).

Step CUDA graphs are off in this static-table comparison, so these numbers do not measure this flag's speedup. The sampling-aware startup warmup fix and test cleanup are in bcf3db0ab6 (30 CPU tests + 57 subtests passed); the measured PR snapshots also passed 80 GPU tests + 89 subtests covering graph capture, sampling and relay paths.

Conflicts, each resolved to keep both sides:

- arg_groups/field_order.py: main's new fields, then
  enable_speculative_step_cuda_graph last.
- entrypoints/http_server.py: the Rust-server line about the step CUDA
  graph warm-up, then main's rust_server_sidecar block.
- speculative/spec_utils.py: main's KV-cache imports and this branch's
  child_graph_capture import.
- speculative/eagle_utils.py: sgl-project#45474 added the same
  packed verify broadcast behind SGLANG_Q35MF_EDGE_PACKED_VERIFY_BCAST
  (_verify_outputs). eagle_sample keeps this branch's
  _alloc_verify_outputs and _broadcast_verify_outputs, and
  _alloc_verify_outputs now allocates through _verify_outputs: packed
  when either variable is set, with the same layout.
- sgl-project#46719 records an eager_on_graph break at capture
  without running it, so a break returns None (sgl-project#46792
  renamed capture_stub to on_capture). The step graph's grammar mask
  break fills the runner-owned mask and returns None, and the
  child-graph test's break writes into a buffer the test owns.
- sgl-project#45474 draws the simulated acceptance length from
  the worker's generator (generate_simulated_accept_index(generator=)).
  The step graph's override takes the generator and keeps it with the
  draw arguments, so a replay draws from it as the eager step does.
Three registered CPU tests build objects that the step CUDA graph code
reads:

- test_full_cuda_graph_backend builds FullCudaGraphBackend without
  __init__: _keep_raw_graph and graph_epoch get class defaults.
- test_backend_resolution resolves a decode backend with no spec config
  published: resolve_decode_backend reads
  enable_speculative_step_cuda_graph only when the spec namespace is
  published.
- test_spec_registry's fake server args gain
  enable_speculative_step_cuda_graph=False, which
  handle_speculative_decoding now reads.
…pt-ins

- SGLANG_ENABLE_EAGLE_POST_VERIFY_CUDA_GRAPH runs its own graphs inside
  the verify, and SGLANG_Q35MF_EDGE_SPARSE_VERIFY_SAMPLING picks its
  top-k branch per batch outside the capture key: with either one on,
  the launch turns the step graph off and keeps the per-stage graphs.
- draw_args is annotated with the generator it carries.
One conflict, in DeepseekSparseAttnBackend of
python/sglang/srt/layers/attention/dsa_backend.py: main
(sgl-project#45946) adds the _call_flash_mla_* wrappers and this
branch adds out_graph_metadata_capturable at the same place, after the
class attributes. Both are kept: out_graph_metadata_capturable first,
next to the attribute comment it refers to, then main's wrappers.
@YAMY1234

Copy link
Copy Markdown
Collaborator

@nvrohanv We might need to break down every optimization in this large PR into multiple smaller, clearer PRs, let's discuss offline

@nvrohanv
nvrohanv marked this pull request as ready for review November 26, 2026 06:16

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

This branch has not been deployed

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

Labels

blackwell SM100/SM120 documentation Improvements or additions to documentation jit-kernel npu speculative-decoding

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants