Skip to content

[Perf] deepseek-v4.1: Replay the breakable prefill CUDA graph at any context length - #43733

Merged
hnyls2002 merged 35 commits into
sgl-project:mainfrom
jyizheng:dsv41-prefill-graph-any-context
Oct 19, 2026
Merged

hnyls2002 merged 35 commits into
sgl-project:mainfrom
jyizheng:dsv41-prefill-graph-any-context

Conversation

@jyizheng

@jyizheng jyizheng commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

DeepSeek-V4.1's breakable prefill CUDA graph is captured at a 16,384-token context width, and every batch with a longer context runs eager. The width is the candidate window (2,048 blocks of 8 tokens): inside it the captured full top-k equals the two-level candidate selection, and past it it does not. Eager DeepSeek-V4.1 prefill is bound by host kernel launches, so long-context requests lose the graph where it would help most.

Modifications

The graph replays at any context length when the two-level candidate indexer runs on DeepGEMM (SM100, no prefill context parallelism, no ratio-4/128 layers):

  • The full top-k layers (the ratio-2 index sources and the ratio-1 candidate source) score as eager breaks over the live batch, at the real context length, and write the sparse indices the attention break reads (_prefill_graph_full_topk_break). The candidate source also returns its block table (SparseTableBackend.publish_prefill_graph), which is copied into the addresses the consumers were captured with.
  • The ratio-1 consumers always take the two-level path inside the graph (SparseTableBackend.consume_prefill_captured) and score only the published candidate blocks, so nothing captured depends on the context length.
  • The replayed context limit moves from the DeepSeek-V4.1 server-args hook into the attention backend. prefill_cuda_graph_default_max_seq_len (None for every other backend) is 16,384 while the captured indexer bounds the context and None when any context replays. The runner uses it only when cuda_graph_config[prefill].max_seq_len is unset, so an explicit --cuda-graph-max-seq-len-prefill always applies.
  • Replay metadata is built at the live context, decided once for the full rows and the decoder-replay late-layer tail (_prefill_graph_context_width). In two-level mode the ratio-1/2 indexer metadata is reference-assigned on refresh instead of copied in place.
  • With decoder SWA bounded replay (the default), the candidate source is the late-layer tail's first layer, so its break takes the tail's request rows and positions.
  • An idle DP-attention rank that replays the graph scores its fabricated rows instead of asserting.
  • Each layer's candidate table is shared by all captured buckets.

Configurations without the candidate indexer (no candidate blocks, the torch prefill path, prefill context parallelism, or pre-SM100 GPUs) keep the 16K limit and today's behavior. The prefill graph stays opt-in for DeepSeek-V4.1 (--cuda-graph-backend-prefill breakable).

Accuracy Tests

GB300 with DeepSeek-V4.1-Flash, TP4 (DSPARK, chunked prefill 8192) and DEP2 with MegaMoE, against main:

  • First-token top-20 distributions, as total variation distance from main eager with decoder replay on:
    • two text needles (134K and 284K tokens): at most 0.019; main's own 16K graph is at 0.026, and a second main eager run at 0.013;
    • 155,648- and 327,680-token prefixes, cold and with 256 or 1,024 new tokens after them: at most 0.010; main's 16K graph is at 0.011, and the second eager run at 0.010.
    • Results are similar with decoder replay off and with encoder replay on, and both needles are retrieved in every run.
  • GSM8K (200 questions, 8-shot prefix): 97.0% on TP4 and 97.5% on DEP2, against main eager's 97.0% and 98.0%.
  • With an explicit --cuda-graph-max-seq-len-prefill 16384, and with SGLANG_DSV41_TORCH_PREFILL_INDEXER=1 (no two-level candidates, so the backend default of 16,384 applies), 14 of the same 123 prefill batches replay, as on main's 16K graph; by default 121 do.
  • One unit test checks the replay limit and the metadata width: a replay that is exact at any length has no default limit and its metadata spans the live context; otherwise both stay at the captured indexer width (16K).

Speed Tests and Profiling

TTFT, TP4, one request, decoder replay on, median of 3:

Cached prefix (tokens) New tokens main, 16K graph (ms) this PR (ms)
0 256 34.8 39.7
0 1,024 43.2 43.9
0 8,000 109.7 101.2
155,648 256 187.8 66.0
155,648 1,024 195.4 76.7
155,648 8,000 199.6 140.5
327,680 256 226.3 106.0
327,680 1,024 236.9 119.8
327,680 8,000 244.8 197.5
  • A cold prefill of 155,648 / 327,680 tokens takes 1,856 / 4,150 ms, against main's 3,031 / 6,586 ms.
  • Short prompts pay for the four breaks: one-step traces show the same GPU time as main and more host time at the breaks.
  • Prefill graph capture memory with decoder replay on: 5.33 GB per GPU, against main's 5.35 GB.

Checklist


CI States

Latest PR Test (Base): 🚫 Run #39209663048
Latest PR Test (Extra): ❌ Run #39209662889
Latest PR Test (AMD ROCm 10): ⏳ Run #39209663190

@jyizheng

Copy link
Copy Markdown
Contributor Author

@Oasis-Git This is the companion to #43736 (just merged) — could you add run-ci so the suite runs? Same DSV4.1 replay line, prefill side.

@weireweire

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@github-actions github-actions Bot added the run-ci CI: run the baseline test suite on this PR label Oct 14, 2026
@weireweire

Copy link
Copy Markdown
Collaborator

Thanks for the work, we also need this to make long context cuda graph work.

@nvpohanh

Copy link
Copy Markdown
Collaborator

cc @Oasis-Git @kpham-sgl this will be needed before we can use BCG

@nvpohanh nvpohanh mentioned this pull request Oct 14, 2026
17 of 56 tasks

@Oasis-Git Oasis-Git left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Codex]: Two issues in the retained captured full-top-k fallback path. These findings are based on source inspection; GPU reproduction has not been performed.

Comment on lines +1043 to +1047
maybe_copy_inplace(self.indexer_metadata, src=static_metadata.indexer_metadata)
maybe_copy_inplace(
self.c1_indexer_metadata, src=static_metadata.c1_indexer_metadata
)
maybe_copy_inplace(
self.c2_indexer_metadata, src=static_metadata.c2_indexer_metadata
)
# The ratio-1/2 indexer metadata is read by eager breaks (flat scoring)
# or only through scalars by captured kernels: take the live objects.
self.c1_indexer_metadata = static_metadata.c1_indexer_metadata
self.c2_indexer_metadata = static_metadata.c2_indexer_metadata

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Codex]: [P1] Preserve in-place metadata refresh for the captured full-top-k fallback. On SM100+ with CP=1, SGLANG_DSV41_TORCH_PREFILL_INDEXER=1 (or candidate_topk_blocks <= 0) makes the factory return DenseBlocksBackend, while low_ratio_prefill_graph can still be true. In that case forward_low_ratio_sources sets captured_index=True and captures FullTopKIndexer._deep_gemm_prefill_captured, which reads the tensor addresses of compressed_seq_lens, page_table, and the DeepGEMM schedule. Replacing the Python metadata objects here does not update those captured buffers, so subsequent requests can compute top-k using capture-time lengths and KV page mappings. Please retain copy_ for that path, or move its indexer out of capture as well. A replay test that changes request lengths and KV page mappings within the same bucket would cover this regression.

topk_transform_paged_torch(
# Per row up to its own length: a wide graph then costs only the
# logits buffer, not a full-static-width top-k.
topk_transform_paged_from_metadata(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Codex]: [P2] Keep support for top-k sizes above 1024 in this fallback. _low_ratio_prefill_indexer_metadata sets use_topk_v2=False, so this helper dispatches to topk_transform_paged and the v1 CUDA kernel, whose kMaxTopK and runtime check cap k at 1024. For a captured full-top-k configuration with index_topk=2048 and sufficient capture width, warmup/capture now fails with topk must be in (0, 1024]; the previous torch.topk implementation supported that size. This affects the retained full-top-k fallback, not the new sparse-table consumer. Please use an implementation supporting the configured k (for example, a properly configured v2 path or the torch fallback) and add a capture case with k=2048.

…t length

The prefill graph is captured at a fixed context width and every batch
longer than it ran eager, which on GB300 is host-launch-bound. Run the flat
index layers (ratio-2 and the candidate source) as eager_on_graph breaks over
the live batch, keep the ratio-1 consumers on the two-level candidate path
inside the graph (identity inside the window, correct past it), select with
topk_transform_paged_from_metadata per row instead of a static-width
torch.topk, and let can_run_prefill_cuda_graph admit any context when the
candidate-window indexer is available. The capture width stays at 16k.
…ions for the flat layers

The flat index layers project q / head weights once inside their eager break (_index_q_and_weights);
the captured source projections now skip the indexer part for those layers and keep it only for the
captured candidate consumers (and for the all-captured path when the sparse candidate backend is absent).
… > 1024

Review follow-ups: the replay refresh hands the ratio-1/2 indexer metadata
over by reference only under two-level candidates; the captured full-top-k
fallback binds the lengths and page tables by address, so it copies in place.
The fallback's v1 top-k kernel caps k at 1024; wider selections keep the
torch top-k. CPU tests for both.
@jyizheng

Copy link
Copy Markdown
Contributor Author

@Oasis-Git thanks, both are right.

  • P1: refresh_for_breakable_cuda_graph_replay_ now takes low_ratio_index_captured; the backend passes not hasattr(prefill_candidates, "consume_prefill_captured"), so the captured full-top-k fallback keeps the in-place copy_ (its lengths and page tables are bound by address) and only the two-level path hands over the live objects. Covered by test_refresh_replay_low_ratio_index_metadata_follows_capture_mode (new lengths and page tables land in the captured tensors) and test_backend_replay_refreshes_low_ratio_index_in_place_unless_two_level.
  • P2: the captured fallback uses the torch top-k when min(index_topk, width) > 1024 under top-k v1 (TOPK_V1_MAX_K), the kernel otherwise. TestDSV4FullTopKCapturedFallback covers k=512, k=2048, width-clipped k and the v2 case.

Also rebased onto main (0f345f9).

@jyizheng jyizheng changed the title [DeepSeek-V4.1] Replay the breakable prefill CUDA graph at any context length [Perf] deepseek-v4.1: Replay the breakable prefill CUDA graph at any context length Oct 15, 2026
@YAMY1234 YAMY1234 mentioned this pull request Oct 15, 2026
# for the low-ratio prefill metadata), which caps k; wider selections
# keep the torch top-k over the captured width.
topk = min(indexer.index_topk, width)
torch_topk = not metadata.use_topk_v2 and topk > TOPK_V1_MAX_K

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[Codex]: [P2] Base the v1 limit check on the output width actually passed to the kernel. There is still a failing width-clipped case: with index_topk=2048, width=512, and use_topk_v2=False, topk is 512 here, so this selects the kernel branch. However, that branch passes the unsliced inputs.out_page_indices / inputs.out_raw_indices to topk_transform_paged_from_metadata. The helper slices rows only, and the v1 kernel derives k from the output column count, which is still 2048, triggering topk must be in (0, 1024]. Please select the torch fallback based on the actual output width (or safely adapt the kernel outputs). The new _topk_calls(2048, 512) test currently expects the kernel branch and mocks away this validation, so it should also be corrected to cover the actual kernel contract. This is based on source inspection, not a GPU reproduction.

…l sees

The v1 kernel derives k from the output columns it is handed, which the
metadata dispatcher slices by rows only, so a 2048-wide output needs the
torch path even when the captured width clips the selection. Test covers
that case and the short-width kernel case.
… branch; require the refresh mode; declare the graph buffer caches; define the break wrappers at module level
…cate to two-level, tail_rows to gather_rows; keep one name for unbounded replay
…oth metadata builders honor it; test the replay width
…nd; share the prefill sparse logits step; fix the padding-row comment
…e the DeepSeek-V4.1 16K default from the hook into the backends so an explicit max_seq_len always applies; test the limits
@hnyls2002

Copy link
Copy Markdown
Collaborator

/rerun-test test_dsv41_late_layer_tail_readers.py test_encoder_swa_replay.py test_prefill_cuda_graph_runner.py test_prefill_cuda_graph_runner_helpers.py test_platform_prefill_cp_deprecation.py test_eager_on_graph.py test_deepseek_v41_bcg_multimodal.py test_dsv4_compressed_pools.py test_dsv4_nonpaged_indexer.py test_deepseek_v4.py test_dsv41_prefill_sparse_indexer.py test_deepseek_v41_flash_gb300_tp4ep4.py test_deepseek_v41_flash_gb300_dp4ep4.py test_deepseek_v41_flash_gb300_trtllm_bounded_bcg.py

@hnyls2002

Copy link
Copy Markdown
Collaborator

/tag-and-rerun-ci

@github-actions

github-actions Bot commented Oct 19, 2026 •

Copy link
Copy Markdown
Contributor

🚀 ubuntu-latest (9 tests): ✅ View workflow run

cd test/ && python3 registered/unit/layers/test_dsv41_late_layer_tail_readers.py
cd test/ && python3 registered/unit/model_executor/test_encoder_swa_replay.py
cd test/ && python3 registered/unit/model_executor/test_prefill_cuda_graph_runner.py
cd test/ && python3 registered/unit/model_executor/test_prefill_cuda_graph_runner_helpers.py
cd test/ && python3 registered/unit/server_args/test_platform_prefill_cp_deprecation.py
cd test/ && python3 registered/unit/model_executor/test_eager_on_graph.py
cd test/ && python3 registered/unit/models/test_deepseek_v41_bcg_multimodal.py
cd test/ && python3 registered/unit/mem_cache/test_dsv4_compressed_pools.py
cd test/ && python3 registered/unit/layers/test_dsv4_nonpaged_indexer.py

🚀 4-gpu-b200 (2 tests): ✅ View workflow run

cd test/ && python3 registered/attention/unittests/dsv4/test_deepseek_v4.py
cd test/ && python3 registered/kernels/ops/attention/test_dsv41_prefill_sparse_indexer.py

🚀 1-gpu-h100 (1 test): ✅ View workflow run

cd test/ && python3 registered/attention/unittests/dsv4/test_deepseek_v4.py

🚀 4-gpu-gb300 (3 tests): ✅ View workflow run

cd test/ && python3 registered/e2e/models/test_deepseek_v41_flash_gb300_tp4ep4.py
cd test/ && python3 registered/e2e/models/test_deepseek_v41_flash_gb300_dp4ep4.py
cd test/ && python3 registered/e2e/models/test_deepseek_v41_flash_gb300_trtllm_bounded_bcg.py

@hnyls2002
hnyls2002 merged commit 8111841 into sgl-project:main Oct 19, 2026
159 of 207 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

deepseek jit-kernel run-ci CI: run the baseline test suite on this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants