Repository navigation
[rl] SGLang generator: extra_buffer prefix cache with overlap scheduling for GDN and KDA - #6172
Conversation
9004386 to
9f6cbc1
Compare
9f6cbc1 to
743bfb9
Compare
## Human Note ## Agent Notes A scheduler already knows the prefix it wants to reuse and the slot reserved for it. In [TorchTitan's SGLang integration](pytorch/torchtitan#6172), those are one position and one track slot per sequence per call. The periodic interface made the caller reserve a row for every eligible boundary and fill every unwanted row with a skip value. vLLM once consumed that kind of schedule in its Mamba "all" cache mode, but [removed it in favor of "align"](vllm-project/vllm#58997). Neither integration needs all intermediate states from a single forward. Replace the interval, packed row offsets, and block table with `StateCheckpoints(state_pool, checkpoint_positions, checkpoint_slots)`. Positions count new tokens in this call; non-positive slots opt out. A later call can select another prefix for the same request. This breaks the periodic constructor: one call no longer exports multiple checkpoints for one sequence. Without replay, only exact 64-token boundaries are written; an off-grid request never silently publishes a different prefix. For KDA replay, translate the position in the existing prefill planner and publish the last completed boundary at or before it. Saving the boundary state and making a mid-chunk slot resumable are different operations: copying the tail and setting its count remain the caller's responsibility in this base PR. The replay follow-up can use the original position directly. ## Validation Matched warm CUDA-graph replays on a GB300, with one selected prefix per sequence and the same cache resets in both graphs. Against main (5029e10), outputs and final cache contents matched bitwise, including KDA replay buffers. Median time in microseconds (old → new): | Path | Sequences × tokens, heads | Selected checkpoint | Checkpoints off | | --- | --- | ---: | ---: | | Chunk GDN | 8 × 512, 8 | 86.8 → 84.0 | 83.8 → 83.6 | | Chunk KDA | 8 × 512, 8 | 114.7 → 111.3 | 110.9 → 110.9 | | Replay KDA | 8 × 512, 8 | 275.5 → 272.4 | 271.4 → 271.6 | | Batch-invariant recurrent GDN | 4 × 256, 2 | 67.6 → 69.6 | 90.1 → 90.1 | stack-info: PR: #975, branch: drisspg/stack/315
d0dce99 to
9c44afc
Compare
|
@claude review |
|
Claude finished @acisseJZhong's task in 4m 9s —— View job Request changes: this can't merge before the Attention Gym pin bump (the shared GDN/KDA adapters, vLLM included, won't import on 0.0.20), and the 5-slots-per-request capacity cost needs an end-to-end measurement. Review |
There was a problem hiding this comment.
Verdict: Request changes -- this can't merge before the Attention Gym pin moves, because the shared rl/generator/attention/{gdn,kda}.py stop importing on 0.0.20. It also cuts the default number of running requests for GDN/KDA by about 40%, and there's no end-to-end measurement showing overlap scheduling makes up for that.
What this PR does. It switches SGLang's mamba radix cache for TorchTitan's GDN/KDA backends from no_buffer to extra_buffer. During prefill, the backends copy the conv window into SGLang's track slot and have Attention Gym write the recurrent state at the last 64-token boundary (StateCheckpoints, and copy_replay_tails for batch-invariant KDA). During decode, SGLang's _track_mamba_state_decode copies the states every 64 tokens. That lets the engine drop the normal event loop and hold shared-prompt requests for every model.
Example. A rollout group of 16 samples with a 150-token prompt:
main: all 16 prefill together; each computes 150 tokens (no reuse, overlap off)
this PR: s0 prefills, snapshotting the state at token 128 into its track slot
s1..s15 are held, then resume from 128 and compute 22 tokens each (overlap on)
cost: every running request now pins 5 state slots instead of 3
Must fix
torchtitan/models/common/attn_gym.py:131/torchtitan/rl/generator/attention/kda.py:17-- on the pinnedattn-gym==0.0.20,StateCheckpoints,ReplayStateandcopy_replay_tailsdon't exist.attn_gym.__getattr__turns that into anAttributeErrorwhen these modules are imported, so the vLLM GDN/KDA adapters break too, not only SGLang. Bump the pin in.ci/docker/requirements.txtin this PR, or rebase onto #6167 once it pins a commit with attention-gym#975/#977. Also update the version in the_raise_forinstall hint.- Main-path capacity regression with no e2e evidence. With 5 slots per request, the README table drops max running requests from ~730 to ~440 at the default ratio, and from 512 to 307 at
max_mamba_cache_size=1536. DAPO-Math now needs 2560 slots, roughly 49 GB more of state memory at ~48 MiB/slot. "Performance is not measured end to end." Please add before/after wall-clock for at least one KV-bound and one state-bound workload (e.g. the two in #6261) so maintainers can weigh it. torchtitan/rl/generator/sglang/README.md:259-263-- the "Rollout groups" section still says linear attention models don't hold requests and explains the oldno_bufferlimitation. The engine now holds them, so update the paragraph.linear_attention.py:130-- this relies on SGLang internals (conv_states_shapeoverride,forward_metadatatrack fields, private_track_mamba_state_decode) with no TODO or upstream issue (inline).
Should consider
rl/generator/attention/gdn.py:42-- replace thecheckpoint_slots/checkpoint_lenspair and the**checkpointsdict with a singleStateCheckpoints | Noneparam, and use Attention Gym'spositionsname (inline).
Questions
- #6261 (unified memory) rewrites the same README section and says the running cap is
state slots // 3. Which one lands first, and does unified memory combine withextra_buffer(the cap would become// 5)? - Does
extra_bufferwork with HiCache for GDN (which #6261 adds a test for)?
Not verified: the claims that SGLang's extend track positions count from the start of the extend, and that decode track positions are absolute multiples of 64, which the KDA replay-count zeroing relies on. The parity tests run only in batch-invariant mode, so the non-batch-invariant paged_chunk_gdn/paged_chunk_kda checkpoint path is not exercised by CI.
| def __init__(self, model_runner) -> None: | ||
| super().__init__(model_runner) | ||
| # SGLang's extend tracking reads the conv window length (W - 1) as the last | ||
| # dim of conv_states_shape; the pool keeps [W - 1, C] per slot, as SGLang's KDA | ||
| # backend does, which exposes the transposed shape too. | ||
| self.conv_states_shape = ( | ||
| self.state_pool.mamba_cache.conv[0].transpose(-1, -2).shape | ||
| ) |
There was a problem hiding this comment.
This depends on SGLang internals with no TODO. It overrides conv_states_shape so that SGLang's extend-tracking metadata (track_conv_indices) comes out right for our [W - 1, C] layout, and it reads forward_metadata.has_mamba_track_mask / mamba_track_mask_indices / track_conv_indices. The decode paths (gdn.py:149, kda.py:205) also call the private MambaAttnBackendBase._track_mamba_state_decode. If any of these change in an SGLang bump, the track slots silently get the wrong conv window or no snapshot, and the only symptom is a parity mismatch on cache reuse.
Per CLAUDE.md principle 3, add a TODO(<sglang issue link>) here, asking SGLang to expose the extra_buffer tracking (track positions/slots, and the decode copy) as public backend hooks. This PR removed the old #48463 TODO, so nothing in the code points upstream anymore.
| checkpoint_slots: torch.Tensor | None = None, | ||
| checkpoint_lens: torch.Tensor | None = None, |
There was a problem hiding this comment.
Two coupled optional params, plus a string-keyed dict that track_extend_states returns and callers splat with **checkpoints, all to rebuild an Attention Gym StateCheckpoints inside paged_gdn/paged_kda. A single state_checkpoints: StateCheckpoints | None = None param on both functions would be simpler. track_extend_states already has the layer cache, so it can build the object itself (pass it the recurrent pool) and return None when nothing is tracked. In paged_kda, copy_replay_tails can read .positions / .slots from it. That deletes the dict, the two None branches, and the duplicated docstrings in both files.
Naming: Attention Gym calls this value positions / checkpoint_positions, but here it is checkpoint_lens. Use one name for the concept.
d32956c to
8f8e830
Compare
8f8e830 to
9128073
Compare
|
@claude review again |
|
Claude finished @acisseJZhong's task in 2m 55s —— View job Approve: the earlier blocking items are fixed. What's left is one refactor suggestion and a capacity trade-off for the maintainers to weigh, and a maintainer still needs to review. Review |
There was a problem hiding this comment.
Verdict: Approve -- the new commits fix every blocking item from the last review: the Attention Gym pin, the stale README section, the upstream TODO, and the missing performance numbers. What's left is a small refactor and one capacity trade-off for the maintainers to weigh. This touches shared models/common code, so a maintainer still needs to review.
What changed since the last review (3d33ef1, 9128073).
- Attention Gym is now pinned to main
755691finrequirements.txt(the same file as.ci/docker/requirements.txt), with a TODO to move to a release. Because of the warpdrive rename, the sharedChunkGdnCudnnPacked/ChunkKdaCudnnimports andchunk_kernel_optionswere updated. Nocudnnnames are left in the repo. - Prefills that take a snapshot now pass
StateCheckpointsto Attention Gym's fused kernels. Warpdrive is skipped there, with a TODO pointing to attention-gym#980. - The KDA parity test now runs with
max_num_batched_tokens=100, so snapshots land mid-chunk andcopy_replay_tailsgets exercised.
Earlier must-fix items
- Attention Gym pin / vLLM adapters break on 0.0.20 -- resolved (pin bumped; the install hint now points to
requirements.txt). - Capacity regression with no end-to-end data -- mostly resolved. The description now shows 1.13-1.32x wall-clock gains on Qwen3.5-9B/0.8B. Every workload measured stays below the new cap of 428 running requests, though (see Questions).
- README "Rollout groups" paragraph -- resolved (
sglang/README.md:260-262). - No TODO for SGLang internals -- resolved (
linear_attention.py:133-136).
Should consider
- Still open from last review:
rl/generator/attention/{gdn,kda}.pytakecheckpoint_slots/checkpoint_lens, andtrack_extend_statesreturns a dict that callers splat with**checkpoints. Using onestate_checkpoints: StateCheckpoints | Noneparam would delete the dict and the duplicated docstrings. It would also use Attention Gym'spositionsname instead oflens. Inkda.py, it would also flatten the nestedkernel_optionsternary (None if ... else A if ... else B, around lines 443-450). linear_attention.py:133-- the new TODO reuses sgl-project/sglang#48463. That issue is aboutno_bufferreusing nothing, which this PR fixes. A dedicated SGLang issue would let the TODO be tracked and closed on its own: "expose extra_buffer track positions/slots and the decode copy as public backend hooks".
Questions
- For state-bound workloads, the cost is still only described, not measured. DAPO-Math at 512 running requests now needs
max_mamba_cache_size=2560instead of 1536, about 49 GB more state memory at ~48 MiB/slot, taken from KV. Are the maintainers fine with that trade-off for the overlap gain, or should one capacity-bound run be added to the description? - The description says the cap drops from 512 to 428 at the default ratio, but the README table says ~730 to ~440. Is the 512 baseline a separate cap, like
max_num_seqs? If so, a one-line note in the table would explain the gap.
Not verified: SGLang internals I can't read in this checkout:
- whether the extend track positions count from the extend start;
- whether
_track_mamba_state_decode, given per-layer pool views, copies every layer; - whether
forward_batch.mamba_track_maskis non-None during decode CUDA-graph capture, which the KDA replay-count zeroing (sglang/attention/kda.py:212) depends on.
test_trainer_vs_sglang_decode_after_cached_turn (cached tokens > prompt length, with parity) should catch the last two on GPU CI. Whether warpdrive still installs without the cudnn extra is also unverified.
tianyu-l
left a comment
There was a problem hiding this comment.
After you resolve most of the issues on engine and on hybrid attention, consider running the follow comparison again.
https://artifacts.internalmeta.com/?cards=1713038417195667&full=0
| # overlap, but needs the kernels to write state snapshots at | ||
| # intermediate positions (see register_to_sglang). | ||
| _normal_event_loop_iteration(scheduler) | ||
| _overlap_event_loop_iteration(scheduler) |
There was a problem hiding this comment.
when claude says
main: all 16 prefill together; each computes 150 tokens (no reuse, overlap off)
this PR: s0 prefills, snapshotting the state at token 128 into its track slot
s1..s15 are held, then resume from 128 and compute 22 tokens each (overlap on)
cost: every running request now pins 5 state slots instead of 3
I thought I did this for sglang engine. I even had a slide on this in my talk. Did I only do it for non-hybrid/linear attention? Please help confirm.
There was a problem hiding this comment.
yeah seems you are not holding the shared prompts for linear attn model https://github.com/pytorch/torchtitan/blob/b1c259cd3/torchtitan/rl/generator/sglang/engine.py#L388-L393
i will run a new set of comparisons after landing this diff, and with the sglang engine optimizations patches.
…ing for GDN and KDA The GDN and KDA backends register SGLang's extra_buffer mamba radix cache strategy (sgl-project/sglang#48463), which keeps overlap scheduling: they snapshot each tracked request's conv and recurrent state into its track slot. In prefill, Attention Gym's StateCheckpoints writes the recurrent state straight into the track slot, and copy_replay_tails gives batch-invariant KDA's slot its replay tail (meta-pytorch/attention-gym#975, #977); decode snapshots come from SGLang's decode tracking. The engine then always runs SGLang's overlap event loop, and requests with a shared prompt reuse its cached state.
9128073 to
7515dc9
Compare
…Gym's fused kernels On SM100/SM103 outside batch-invariant mode, chunk_kernel_options picks Attention Gym's warpdrive backend, but Attention Gym writes StateCheckpoints only from its fused kernels, so the first prefill that takes a snapshot raised. Use the fused backend for prefills that take a snapshot.
…pstream TODO - Pin Attention Gym to a main commit with StateCheckpoints and copy_replay_tails (meta-pytorch/attention-gym#975, #977); no release has them yet. That commit renames the cuDNN-derived GDN/KDA backend to warpdrive, so import and select it by its new name, and point the missing-package hint at requirements.txt. - README: linear attention models now hold requests that share a prompt. - TODO(sgl-project/sglang#48463) on the SGLang internals the extra_buffer support relies on.
7515dc9 to
0e8a05b
Compare
Conflicts, per-commit effect on ezpz, the three replays (pytorch#6164, pytorch#6325, pytorch#5881), the attn_gym venv upgrade for pytorch#6172, and the 21-arm smoke matrix on 15efc8b across Sunspot, Aurora and Sirius. Aurora 2B losses differ from earlier syncs; an attn_gym-hidden control on the same nodes reproduces the old values exactly.
Summary (human-written)
Why
SGLang runs our GDN/KDA backends (Qwen3.5, Kimi K3) with the
no_buffermamba radix cache. That disables overlap scheduling, and because it stores a state only at the end of a cached prefix, a repeated prompt reuses nothing (sgl-project/sglang#48463). Withextra_buffer, SGLang keeps overlap on. During the forward, the backend writes the state at a 64-token-aligned position into a separate track slot. Attention Gym's kernels now support that (meta-pytorch/attention-gym#975, #977).no_buffer)extra_buffer)What changed
registry.py: registersupport_mamba_cache_extra_buffer=True.sglang/attention/linear_attention.py,attention/{gdn,kda}.py): SGLang's tracked position and track slot go to Attention Gym asStateCheckpoints(state_pool, positions, slots), and the kernel writes the state into that slot. The conv history is copied from the inputs. Batch-invariant KDA also callscopy_replay_tailsfor the unfinished chunk. Prefills that take a snapshot use Attention Gym's fused kernels, the only ones that write checkpoints.sglang/attention/{gdn,kda}.py): SGLang's_track_mamba_state_decodecopies the states, and KDA zeroes the track slot's replay count.engine.py: overlap is always on (the normal event loop path is deleted), requests sharing a prompt are held for every model, andmamba_track_intervalis reserved at 64.755691f, the first commit with both APIs, until a release has them. That commit renames the cuDNN-derived GDN/KDA backend to warpdrive, so the imports andchunk_kernel_optionsuse the new name.Behavior changes for SGLang generator users
These apply to GDN/KDA models (Qwen3.5, Kimi K3); other models are unchanged.
SGLangEngine.step()runs SGLang's overlap event loop, as for other models.max_mamba_cache_sizeinextra_server_args, size it as 5x the running requests instead of 3x.mamba_track_intervalis fixed at 64: setting it inextra_server_argsnow raisesValueError.Performance
Qwen3.5-9B and 0.8B (GDN), TP 1, one GB300, default mode,
cuda_graph="breakable". 1000-token prompts, 512 tokens out per request. Time until all requests finish, median of 6 runs.Overlap scheduling gives the 1.13-1.21x; GRPO also reuses each group's prompt.