Repository navigation
[rl] SGLang generator: log the CUDA graph padding share and HiCache-loaded prompt tokens - #6419
felipemello1 wants to merge 3 commits into
Conversation
…oaded prompt tokens generator/cudagraph_padding_frac counts the tokens SGLang's runners pad, through each runner's fill_from; one finished request per step carries the counts. The count fields and the dispatcher metric are the vLLM padding metric PR's shared code. generator/num_external_cached_tokens is the part of a request's cached prompt that HiCache loaded from host memory or storage.
|
Reply from claude: @claude please review |
|
Claude finished @felipemello1's task in 3m 49s —— View job Needs discussion -- review posted. A maintainer should decide, together with #5945, how the padding metric handles validation's key rename. One TODO still needs its upstream SGLang issue link. |
There was a problem hiding this comment.
Verdict: Needs discussion -- the code is small and the mechanism holds up, but a maintainer should decide, together with #5945, how the engine-wide padding metric handles validation's key rename. One TODO also needs its upstream link.
What this PR does. It wraps fill_from on each SGLang runner's buffer registry (eager, prefill graph, decode graph) to add up the tokens before and after CUDA graph padding. step() pops the running totals onto the first finished request. The dispatcher turns them into a token-weighted generator/cudagraph_padding_frac, using the same shared code as #5945. With HiCache on, it also reads SGLang's cached_tokens_details into a new num_external_cached_tokens metric.
Example.
step k: forwards fill_from(raw=174, padded=176), fill_from(raw=3, padded=4) x N
finished = [req_a (training), req_b]
req_a.metrics_inputs.num_engine_{unpadded,padded}_tokens = (174+3N, 176+4N)
-> generator/cudagraph_padding_frac Mean(2+N, count=176+4N)
step k+1: finished = [val_req (validation), ...]
-> controller renames to validation_generator/cudagraph_padding_frac,
though the forwards it covers mostly served training requests
HiCache: cached_tokens_details={"device": 0, "host": 192} -> num_external_cached_tokens=192
no HiCache -> None, no metric
Must fix
torchtitan/rl/generator/sglang/engine.py:974-- the TODO for thefill_fromwrap and the private_eager_registryread has no upstream issue link (CLAUDE.md principle 3). File the SGLang issue and link it.
Needs a maintainer decision
torchtitan/rl/generator/dispatcher.py:429-- the engine-wide value is filed under whichever carrier's key it lands on. That splits it betweengenerator/andvalidation_generator/, and both keys end up covering mixed forwards. The options are in the inline comment. Decide together with #5945, since that PR's test asserted the key stays unprefixed.
Should consider
torchtitan/rl/generator/sglang/engine.py:977-- the dedup is keyed on the runner, but the wrap goes on the registry. A shared registry would be counted twice without any error. Key onid(registry)instead.
Questions
- With DP attention, does an idle DP rank's empty batch go through
fill_from, for example as raw 0 padded to 1? If it does, SGLang counts that as padding. #5945's vLLM runner explicitly leaves an idle DP rank's dummy forwards out. The same key would then mean different things on the two engines.
Details
- Gate. This is an observability gap on main: SGLang counts no padding, and
num_cached_tokensmixes GPU hits with host load-backs. The PR uses the existing per-request metrics path and #5945's shared hunks, not a new mechanism. vLLM leavesnum_external_cached_tokensNone, with the reason given in the description, so the design isn't one-sided in a way that a shared version would fix. - TP/DP. Every TP rank has its own counter, and only TP rank 0 of each DP replica sends its results to rank 0 (
dispatcher.py:57-69). Each DP replica's forwards are therefore counted once, and theMean(count=padded)weighting adds them up correctly across replicas. - Lost counts. Aborted requests still get a
Completionwith metrics (dispatcher.py:267-286), so the counts are lost only in the reply-failure case the description already mentions. - Tests. In the prefill test, padding is certain:
stop_token_ids=[]makes all 3 requests decode together toMAX_GEN_TOKENS, and 3 rows replay a larger graph. The HiCache test now goes through the public metrics path instead of patchingadmit. - Overlap searches. Search terms:
cudagraph_padding_frac, "padding fraction", "sglang engine.py",num_external. They found:- #5945, the shared padding hunks (coordination already noted in the description).
- #6418, the NaN-abort PR, which conflicts in
_OutputCollector/step()(noted). - #6414, SGLang MTP: its draft runners won't be counted (noted).
- #6018, the SGLang output_sink PR, which would replace
_OutputCollector: the HiCache read moves with it.
Not verified: SGLang internals (the fill_from keyword signature, EagerRunner._eager_registry, the cached_tokens_details keys, Scheduler.enable_hierarchical_cache). The SGLang source wasn't available in this job. The author's GPU runs exercise these paths.
Before merge: fill in the human-written summary.
| # TODO: SGLang reports no CUDA graph padding counts, so this wraps a method of | ||
| # each runner's buffers, private attributes included. MTP draft runners are not | ||
| # counted. |
There was a problem hiding this comment.
Must fix: this TODO has no upstream issue link. It wraps a method on SGLang's buffer registries and reads the private EagerRunner._eager_registry. CLAUDE.md principle 3 asks for a TODO(<issue link>) on every workaround of an upstream gap or private-API use, like the other SGLang TODOs in this file (sglang/issues/48473, 48474, 48482). The description says the issue text is ready. Please file it and put the link here before merging.
There was a problem hiding this comment.
Reply from claude: Not yet: the SGLang issue (SGLang reports no CUDA graph padding counts) is drafted and under review on the author's fork. Its link goes into this TODO once it is filed.
There was a problem hiding this comment.
Reply from claude: The SGLang issue (SGLang reports no CUDA graph padding counts) is now drafted for the author's review: felipemello1/sglang#1. Once it is filed on SGLang's tracker, this TODO becomes # TODO(https://github.com/sgl-project/sglang/issues/<N>):. The code stays as it is until then.
| # Covers every request in the engine since the previous carrier, training and | ||
| # validation alike. Weighted by forward tokens. Eager steps pad only for sequence | ||
| # parallelism. |
There was a problem hiding this comment.
Maintainer decision: this value covers every forward in the engine, but which W&B key it lands under depends on the carrier. If the carrier is a validation request, controller.py:973 renames it to validation_generator/cudagraph_padding_frac.
Validation runs as async tasks alongside training rollouts (controller.py:1235), so the two keys end up like this:
generator/cudagraph_padding_fracsilently drops the windows that validation requests carried.validation_generator/cudagraph_padding_fracmostly measures training forwards, but its name says validation.
#5945's test asserted that the key stays unprefixed. The copied test here no longer checks that.
There are two ways out, and a maintainer should pick one, together with #5945:
- (a) Exempt this key in the controller's rename: one line at
controller.py:973, but the controller then knows about one generator metric. - (b) Keep the split and say in this comment that each key covers the forwards its carriers saw, not its own requests.
Either way, "training and validation alike" here should say which one was chosen.
There was a problem hiding this comment.
Reply from claude: Went with (b) in f629dd8. The controller stays generic, and the comment now says where a validation carrier's value lands.
# before
# Covers every request in the engine since the previous carrier, training and
# validation alike. Weighted by forward tokens. Eager steps pad only for sequence
# parallelism.
# after
# Covers every forward in the engine since the previous carrier, whichever
# requests ran in it. A validation carrier's value is logged under
# validation_generator/ (the controller prefixes validation's metrics). Weighted
# by forward tokens. Eager steps pad only for sequence parallelism.The body's NOTE says the same, and that each key covers the forwards its carriers saw. The padding metric PR shares this hunk, so whichever lands second takes this comment.
| runners = { | ||
| id(runner): runner | ||
| for runner in ( | ||
| model_runner.eager_runner, | ||
| model_runner.prefill_cuda_graph_runner, | ||
| model_runner.decode_cuda_graph_runner, | ||
| ) | ||
| if runner is not None | ||
| } | ||
| for runner in runners.values(): | ||
| registry = ( | ||
| runner._eager_registry | ||
| if isinstance(runner, EagerRunner) | ||
| else runner.buffer_registry | ||
| ) | ||
| registry.fill_from = self._counting(registry.fill_from) |
There was a problem hiding this comment.
Should consider: the dedup is keyed on the runner, but the wrap goes on the registry. If two runners ever share one buffer_registry (for example a prefill and a decode graph runner built on shared buffers), its fill_from gets wrapped twice. Every forward through it is then counted twice, the padding fraction still looks plausible, and nothing fails. Unverified: I couldn't read the SGLang source from this job. Keying on the object you actually patch removes the question:
registries = {}
for runner in (model_runner.eager_runner, model_runner.prefill_cuda_graph_runner, model_runner.decode_cuda_graph_runner):
if runner is None:
continue
registry = runner._eager_registry if isinstance(runner, EagerRunner) else runner.buffer_registry
registries[id(registry)] = registry
for registry in registries.values():
registry.fill_from = self._counting(registry.fill_from)Same size as now. If the shared-runner case can't happen in SGLang either, drop the dedup altogether.
There was a problem hiding this comment.
Reply from claude: Fixed in f629dd8: it now keeps one wrap per registry, keyed by id(registry).
At the pinned SGLang (851642ade), each runner builds its own registry: build_prefill_registry (model_executor/runner/prefill_cuda_graph_runner.py:499), build_decode_registry (decode_cuda_graph_runner.py:539) and build_eager_registry (eager_runner.py:127). The dedup still matters, because SGLang may hand its eager runner over as the prefill runner (model_runner_components/cuda_graph_setup.py:505).
…y where validation carriers' padding share lands
|
Reply from claude: Pushed f629dd8 with the dedup fix, the documented key split, and idle-DP forwards left out. The issue link waits for the issue to be filed. Idle attention-DP rank. Yes: before this push it counted as padding. Under attention DP, the decode runner pads every rank to the largest per-rank batch. So an idle rank calls # An idle attention-DP rank replays a graph with no real token: no real batch
# was padded.
if raw_num_tokens > 0:
self._num_unpadded_tokens += raw_num_tokens
self._num_padded_tokens += padded_num_tokensA rank with some real rows, padded up to the largest rank's batch, still counts as padding. The body's NOTE says so. DP > 1 is not tested here (one GPU). Deferred. The SGLang issue link for the @claude please review |
|
Claude finished @felipemello1's task in 1m 44s —— View job Approve -- please address the items below before merging. Review posted. One item is left: link the SGLang issue in the |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- f629dd8 resolves the earlier open points. The one item left is linking the SGLang issue in the TODO once it is filed.
What this PR does. It wraps fill_from once on each distinct SGLang buffer registry (eager, prefill graph, decode graph) to add up the forward tokens before and after CUDA graph padding. Forwards with no real token (an idle attention-DP rank) are skipped. step() pops the totals onto the first finished request, and the dispatcher logs them as a token-weighted generator/cudagraph_padding_frac. With HiCache on, cached_tokens_details host + storage becomes generator/num_external_cached_tokens.
Example.
DP rank A: decode 3 rows -> 4-row graph fill_from(raw=3, padded=4) counted
DP rank B: idle, padded to A's batch fill_from(raw=0, padded=4) skipped (was: 4 padding tokens)
eager runner reused as prefill runner one registry -> wrapped once (was: once per runner id, same here)
validation carrier -> validation_generator/cudagraph_padding_frac (documented, option b)
Earlier items
- Registry dedup (
engine.py:977): resolved. The wrap is now keyed byid(registry), the object that gets patched. - Validation key split (
dispatcher.py:429): resolved with option (b). The comment now says that a validation carrier's value lands undervalidation_generator/(matchescontroller.py:973), and each key covers the forwards its carriers saw. The key is new, so no existing metric key changes meaning. - Idle attention-DP forwards (question): answered and fixed.
raw_num_tokens > 0leaves them out, as #5945's vLLM runner does. - TODO without an upstream link (
engine.py:974): still open, see below.
Must fix
torchtitan/rl/generator/sglang/engine.py:974-- still open: once the SGLang issue is filed, change# TODO:to# TODO(https://github.com/sgl-project/sglang/issues/<N>):, like the other SGLang TODOs in this file (CLAUDE.md principle 3).
Details
- New commit reviewed in full: dedup loop, idle-DP filter, dispatcher comment. The new code adds no new knob or symbol.
- Idle-DP filter and the metric. A rank with some real rows that is padded up to the largest rank's batch still counts as padding. That is real wasted compute, and the description's NOTE says so. Skipping
raw == 0forwards also keepsnum_engine_padded_tokensat 0 on an idle rank, so a carrier that saw only idle forwards logs no metric (the> 0gate atdispatcher.py:428). - Overlap. #5945 (shared hunks) and #6418 (
_OutputCollector/step()conflict) are still open drafts by the same author, and the description covers the rebase order. Search terms:cudagraph_padding_frac,num_external_cached_tokens.
Not verified: the SGLang internals cited in the replies (decode_cuda_graph_runner.py:1570-1594 idle-rank padding, cuda_graph_setup.py:505 eager-as-prefill). The SGLang source wasn't available in this job. The fill_from signature and the registry wrap are exercised by the author's GPU run of test_prefill_replays_cuda_graphs. The idle-DP path is untested (DP > 1).
A maintainer still needs to review. Before merge: fill in the human-written summary.
Summary (human-written)
Agent details
TLDR: The SGLang generator logs two new metrics.
generator/cudagraph_padding_fracis the share of forward tokens that CUDA graph padding adds, as the vLLM engine's padding metric PR "[rl] Log the generator's CUDA graph padding fraction" adds for vLLM.generator/num_external_cached_tokensis the part of a request's cached prompt that HiCache loaded from host memory or storage, next togenerator/num_cached_tokens. The name follows vLLM'snum_external_cached_tokens(PrefillStats, the source ofPromptTokenStats.external_kv_transfer).Problem
generator/num_cached_tokensmixes tokens found on the GPU with tokens loaded back from host memory, which cost a copy.Solution
_ForwardTokenCountswrapsfill_fromof each SGLang runner's buffers. Every runner calls it once per forward with the token counts before and after padding.step()puts the counts on its first finished request, so each forward is counted at most once (a request whose reply fails before its metrics are logged takes its counts with it). The dispatcher turns them intogenerator/cudagraph_padding_frac, weighted by forward tokens.RequestMetricsInputscount fields and the dispatcher metric are the padding metric PR's shared code, rebased on main. That PR's vLLM half (TorchTitanGPUModelRunner.pop_forward_token_counts) is not here._OutputCollectorreadscached_tokens_detailsfrom SGLang's request stats when HiCache is on.num_external_cached_tokensstays None and no metric is logged. The vLLM engine leaves it None: vLLM'sRequestOutputhas onlynum_cached_tokens, and vLLM counts external tokens per step for its stat logger instead. A draft on the author's fork exports that counter: "[rl] vLLM stat logger: count prompt tokens a KV connector loaded (vllm.external_prompt_tokens)".Results
You may ask:
fill_fromis the one call every runner makes with both counts. A TODO at the wrap says so. Its SGLang issue link goes there once the issue is filed (text ready, not filed yet).VLLMSessionKVHolder, which the SGLang engine doesn't use: SGLang keeps sessions in its radix cache.NOTE: on main, the validation loop renames every key that doesn't start with "validation". So the padding share that a validation request carries is logged as
validation_generator/cudagraph_padding_frac, and the dispatcher's comment says so. Each key covers the forwards its carriers saw, not only its own requests. The padding metric PR meant one engine-wide key, but its base predates that rename.NOTE: whichever of this PR and the padding metric PR lands second drops the shared hunks in
types.py,dispatcher.pyandtest_generator.py. This PR's dispatcher comment adds the validation sentence above.NOTE: this PR and "[rl] SGLang generator: abort a request whose logprob turns NaN or -inf" both change
_OutputCollector.__init__andstep()insglang/engine.py. Whichever lands second rebases. It merges cleanly with "[rl] SGLang generator: fp8 KV cache through FA4's fp8 forward" and with "[rl] SGLang generator: top-k logprobs for score centering".NOTE: the vLLM stat logger PR above names the same count
num_external_prompt_tokens(a per-step field). Whichever of the two lands second renames that field tonum_external_cached_tokens. The metric keys can stay apart: one is a per-step counter, the other a per-request value.NOTE: not tested at TP > 1 or DP > 1 (one GPU here). With DP attention, SGLang pads each DP rank's decode batch to the largest one, and that counts as padding. An idle DP rank's forwards (no real token) are not counted.
NOTE: with MTP, the draft model's runners are not counted, only the target model's.
Test plan
test_generator.py::test_cudagraph_padding_frac_weights_each_engine_step_by_its_tokens(from the padding metric PR): steps of 8 -> 12 and 4 -> 4 tokens give 4 / 16.test_prefill_replays_cuda_graphsnow also checks that finished requests carry the counts: unpadded >= the prompts' tokens, and padded > unpadded. It sends 3 requests, so each decode batch of 3 rows replays the 4-row graph and padding is certain (the capture sizes atmax_num_seqs5 are 1, 2, 4, 5).test_trainer_vs_sglang_decode_after_host_load_backnow readsnum_external_cached_tokens, not SGLang's request object. It checks that every cached token came from host memory.TestSGLangBitwiseParityKDA(a 1-GPU class in CI too): 6 passed. The GDN HiCache class through a 1-GPU subclass at TP 1, on the last commit: 8 passed,test_prefill_replays_cuda_graphsandtest_trainer_vs_sglang_decode_after_host_load_backincluded. The multi-GPU classes that run the changed prefill test (Varlen, sliding-window, GDN, GDN HiCache, Dist-MoE, Dist-MoE DP-EP; the others capture no graphs and skip it) first run in CI.pytest tests/rl/unit_tests/cpu: 772 passed, 8 skipped, 2 failed (main: 771 passed, the same 2 failed:test_kv_offload_coordination.py::test_terminal_cleanup_preserves_block_identity, 2 cases).torchtitan/rl/): all hooks pass.