Skip to content

[rl] SGLang generator: extra_buffer prefix cache with overlap scheduling for GDN and KDA - #6172

Merged
acisseJZhong merged 3 commits into
mainfrom
sglang-linear-attn-extra-buffer
Nov 21, 2026
Merged

acisseJZhong merged 3 commits into
mainfrom
sglang-linear-attn-extra-buffer

Conversation

@acisseJZhong

@acisseJZhong acisseJZhong commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

Why

SGLang runs our GDN/KDA backends (Qwen3.5, Kimi K3) with the no_buffer mamba 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). With extra_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).

150-token prompt, 50 decoded tokens main (no_buffer) this PR (extra_buffer)
Overlap scheduling off on
Same prompt again recomputes 150 tokens reuses the state at token 128
Next turn resumes at token 200 resumes at token 192

What changed

  • registry.py: register support_mamba_cache_extra_buffer=True.
  • Prefill (sglang/attention/linear_attention.py, attention/{gdn,kda}.py): SGLang's tracked position and track slot go to Attention Gym as StateCheckpoints(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 calls copy_replay_tails for the unfinished chunk. Prefills that take a snapshot use Attention Gym's fused kernels, the only ones that write checkpoints.
  • Decode (sglang/attention/{gdn,kda}.py): SGLang's _track_mamba_state_decode copies 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, and mamba_track_interval is reserved at 64.
  • Dependency (mechanical): pin Attention Gym to main 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 and chunk_kernel_options use the new name.

Behavior changes for SGLang generator users

These apply to GDN/KDA models (Qwen3.5, Kimi K3); other models are unchanged.

  • Overlap scheduling is on: SGLangEngine.step() runs SGLang's overlap event loop, as for other models.
  • Samples of a rollout group wait for the first sample's prefill, then start from its state at the prompt's last 64-token boundary.
  • Each running request reserves 5 state slots instead of 3, so fewer requests run at once with the same state pool (Qwen3.5-9B on GB300 at the default ratio: 512 -> 428). If you set max_mamba_cache_size in extra_server_args, size it as 5x the running requests instead of 3x.
  • mamba_track_interval is fixed at 64: setting it in extra_server_args now raises ValueError.

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.

Workload 9B: main → PR 0.8B: main → PR
128 unique prompts 9.27 → 8.22 s (1.13x) 5.62 → 4.75 s (1.19x)
GRPO: 32 prompts × 8 samples 15.22 → 11.50 s (1.32x) 9.91 → 7.89 s (1.25x)
Next turn of 128 sessions (+64 tokens) 8.29 → 7.24 s (1.14x) 5.44 → 4.49 s (1.21x)

Overlap scheduling gives the 1.13-1.21x; GRPO also reuses each group's prompt.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 18, 2026
@acisseJZhong
acisseJZhong force-pushed the sglang-linear-attn-extra-buffer branch 3 times, most recently from 9004386 to 9f6cbc1 Compare November 20, 2026 00:30
@acisseJZhong
acisseJZhong force-pushed the sglang-linear-attn-extra-buffer branch from 9f6cbc1 to 743bfb9 Compare November 20, 2026 06:57
drisspg added a commit to meta-pytorch/attention-gym that referenced this pull request Nov 20, 2026
## 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
@acisseJZhong
acisseJZhong force-pushed the sglang-linear-attn-extra-buffer branch 12 times, most recently from d0dce99 to 9c44afc Compare November 20, 2026 19:14
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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

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

  1. torchtitan/models/common/attn_gym.py:131 / torchtitan/rl/generator/attention/kda.py:17 -- on the pinned attn-gym==0.0.20, StateCheckpoints, ReplayState and copy_replay_tails don't exist. attn_gym.__getattr__ turns that into an AttributeError when these modules are imported, so the vLLM GDN/KDA adapters break too, not only SGLang. Bump the pin in .ci/docker/requirements.txt in this PR, or rebase onto #6167 once it pins a commit with attention-gym#975/#977. Also update the version in the _raise_for install hint.
  2. 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.
  3. torchtitan/rl/generator/sglang/README.md:259-263 -- the "Rollout groups" section still says linear attention models don't hold requests and explains the old no_buffer limitation. The engine now holds them, so update the paragraph.
  4. linear_attention.py:130 -- this relies on SGLang internals (conv_states_shape override, forward_metadata track fields, private _track_mamba_state_decode) with no TODO or upstream issue (inline).

Should consider

  • rl/generator/attention/gdn.py:42 -- replace the checkpoint_slots/checkpoint_lens pair and the **checkpoints dict with a single StateCheckpoints | None param, and use Attention Gym's positions name (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 with extra_buffer (the cap would become // 5)?
  • Does extra_buffer work 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.

Comment on lines +130 to +137
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
)

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.

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.

Comment on lines +42 to +43
checkpoint_slots: torch.Tensor | None = None,
checkpoint_lens: torch.Tensor | None = None,

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.

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.

@acisseJZhong
acisseJZhong marked this pull request as ready for review November 20, 2026 20:43
@pytorch-bot pytorch-bot Bot added ciflow/docker ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 20, 2026
@acisseJZhong

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

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

@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 -- 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 755691f in requirements.txt (the same file as .ci/docker/requirements.txt), with a TODO to move to a release. Because of the warpdrive rename, the shared ChunkGdnCudnnPacked / ChunkKdaCudnn imports and chunk_kernel_options were updated. No cudnn names are left in the repo.
  • Prefills that take a snapshot now pass StateCheckpoints to 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 and copy_replay_tails gets exercised.

Earlier must-fix items

  1. Attention Gym pin / vLLM adapters break on 0.0.20 -- resolved (pin bumped; the install hint now points to requirements.txt).
  2. 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).
  3. README "Rollout groups" paragraph -- resolved (sglang/README.md:260-262).
  4. No TODO for SGLang internals -- resolved (linear_attention.py:133-136).

Should consider

  • Still open from last review: rl/generator/attention/{gdn,kda}.py take checkpoint_slots / checkpoint_lens, and track_extend_states returns a dict that callers splat with **checkpoints. Using one state_checkpoints: StateCheckpoints | None param would delete the dict and the duplicated docstrings. It would also use Attention Gym's positions name instead of lens. In kda.py, it would also flatten the nested kernel_options ternary (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 about no_buffer reusing 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=2560 instead 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_mask is 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 tianyu-l 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.

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)

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.

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.

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.

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.
@acisseJZhong
acisseJZhong force-pushed the sglang-linear-attn-extra-buffer branch from 9128073 to 7515dc9 Compare November 21, 2026 07:20
…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.
@acisseJZhong
acisseJZhong force-pushed the sglang-linear-attn-extra-buffer branch from 7515dc9 to 0e8a05b Compare November 21, 2026 07:34
@acisseJZhong
acisseJZhong merged commit 31d93fe into main Nov 21, 2026
31 checks passed
saforem2 added a commit to saforem2/torchtitan that referenced this pull request Nov 30, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/docker ciflow/fake-pg Run 1-GPU Fake PG integration tests 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.

2 participants