Skip to content

[rl] SGLang generator: log the CUDA graph padding share and HiCache-loaded prompt tokens - #6419

Draft
felipemello1 wants to merge 3 commits into
mainfrom
felipemello1/sgl203/s4-sglang-metrics
Draft

felipemello1 wants to merge 3 commits into
mainfrom
felipemello1/sgl203/s4-sglang-metrics

Conversation

@felipemello1

@felipemello1 felipemello1 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Agent details

TLDR: The SGLang generator logs two new metrics. generator/cudagraph_padding_frac is 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_tokens is the part of a request's cached prompt that HiCache loaded from host memory or storage, next to generator/num_cached_tokens. The name follows vLLM's num_external_cached_tokens (PrefillStats, the source of PromptTokenStats.external_kv_transfer).

This PR adds generator/cudagraph_padding_frac: decodes of 3 and 5 requests replay the 4- and 8-row graphs (8 real tokens, 12 after padding), and with a second step of 4 tokens the share is 4 / 16. It also adds generator/num_external_cached_tokens: in the HiCache test, all 192 / 128 / 128 / 128 / 64 cached prompt tokens were loaded from host memory.

Problem

  1. The SGLang engine already reports per-request metrics: cached prompt tokens, queue time, time to first token, prefill and decode time, inter-token latency, preemptions.
  2. It reports no CUDA graph padding. SGLang pads each decode batch up to a captured batch size and each prefill up to a token bucket, and keeps no count of it.
  3. With HiCache, generator/num_cached_tokens mixes tokens found on the GPU with tokens loaded back from host memory, which cost a copy.

Solution

  1. _ForwardTokenCounts wraps fill_from of each SGLang runner's buffers. Every runner calls it once per forward with the token counts before and after padding.
  2. 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 into generator/cudagraph_padding_frac, weighted by forward tokens.
  3. The two RequestMetricsInputs count 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.
  4. _OutputCollector reads cached_tokens_details from SGLang's request stats when HiCache is on.
  5. Without HiCache, num_external_cached_tokens stays None and no metric is logged. The vLLM engine leaves it None: vLLM's RequestOutput has only num_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

TestSGLangBitwiseParityGDNHiCache at TP 1, one GB300 (Qwen3.5 debug model, breakable graphs):
  first turn: 5 prompts, prefill 524 tokens; next turns load their prefix back from host memory:
  per request   cached 192 / 128 / 128 / 128 / 64     external 192 / 128 / 128 / 128 / 64   (all from host)
  carrier       unpadded 419, padded 421: a 174-token prefill padded to the 176 bucket; decode batch 5 has its own graph

You may ask:

  • Why wrap a SGLang method? SGLang counts no padding (its metrics only say whether a batch ran in a graph). fill_from is 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).
  • Why not port the vLLM session-KV metrics (lost prefix, held blocks)? They measure 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.py and test_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__ and step() in sglang/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 to num_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_graphs now 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 at max_num_seqs 5 are 1, 2, 4, 5).
  • test_trainer_vs_sglang_decode_after_host_load_back now reads num_external_cached_tokens, not SGLang's request object. It checks that every cached token came from host memory.
  • Ran on one GB300 (this box has one GPU): 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_graphs and test_trainer_vs_sglang_decode_after_host_load_back included. 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).
  • pre-commit on the changed files (pyrefly excludes torchtitan/rl/): all hooks pass.

…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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 27, 2026
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude please review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

  1. torchtitan/rl/generator/sglang/engine.py:974 -- the TODO for the fill_from wrap and the private _eager_registry read 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 between generator/ and validation_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 on id(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_tokens mixes 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 leaves num_external_cached_tokens None, 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 the Mean(count=padded) weighting adds them up correctly across replicas.
  • Lost counts. Aborted requests still get a Completion with 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 to MAX_GEN_TOKENS, and 3 rows replay a larger graph. The HiCache test now goes through the public metrics path instead of patching admit.
  • 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.

Comment on lines +974 to +976
# 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment thread torchtitan/rl/generator/dispatcher.py Outdated
Comment on lines +429 to +431
# 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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_frac silently drops the windows that validation requests carried.
  • validation_generator/cudagraph_padding_frac mostly 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

Comment on lines +977 to +992
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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
@felipemello1

Copy link
Copy Markdown
Contributor Author

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 fill_from with raw_num_tokens 0 and padded_num_tokens > 0 (decode_cuda_graph_runner.py:1570-1594). Those forwards are no longer counted, which keeps the key's meaning close to the vLLM engine's:

# 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_tokens

A 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 fill_from TODO: the issue is drafted and under review.

@claude please review

@claude

claude Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

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 fill_from TODO once it's filed.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 by id(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 under validation_generator/ (matches controller.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 > 0 leaves them out, as #5945's vLLM runner does.
  • TODO without an upstream link (engine.py:974): still open, see below.

Must fix

  1. 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 == 0 forwards also keeps num_engine_padded_tokens at 0 on an idle rank, so a carrier that saw only idle forwards logs no metric (the > 0 gate at dispatcher.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.

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

ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant