Repository navigation
[rl] generator: SGLang GDN linear attention - #5817
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The design reuses SGLang's own state pool, radix-cache snapshots and linear-attention registry, plus the trainer's Attention Gym kernels. It also deduplicates the paged GDN recurrence across vLLM and SGLang. The remaining items are small local edits.
What this PR does. It runs TorchTitan's GDN layers inside SGLang. SGLang allocates and snapshots each request's conv and recurrent state (TorchTitanGDNConfig sizes the slots, with a [W-1, C] conv layout and a float32 recurrent state). TorchTitanGDNAttnBackend advances those states with the trainer's kernels. Because SGLang's mamba radix cache disables overlap scheduling, step() now also drives SGLang's normal event loop. The vLLM GDN recurrence moves verbatim into paged_gdn.py, and both engines share it.
Example.
turn 1: session "0", prompt P (150) -> completion C (50)
radix cache: KV of the full-attention layers for P+C,
plus a GDN conv/recurrent snapshot at token 200
turn 2: session "0", prompt P + C + S (8)
before: SGLangEngine raises for GDN layers
after: forward_extend gets extend_prefix_lens = 200, so has_initial_state = True;
it prefills only S from the snapshot.
The new test checks num_cached_tokens > 150 and bitwise parity with the
trainer's prefill of P+C+S.
Must fix
- The PR description's "Summary (human-written)" section is empty. Only the author can fill it in (see
CONTRIBUTING.md, "AI-assisted contributions"). torchtitan/rl/generator/sglang/gdn.py:319-320: assigning theA_log/dt_biasParameters registers them onlinear_attention, sostate_dict()gains two extra keys per GDN layer after the first forward. Fix withobject.__setattr__(inline).
Should consider
torchtitan/rl/generator/sglang/engine.py:342-343: the overlap-schedulerValueErroris gone for every model, not just GDN models, so a non-GDN run with overlap off silently switches to the slower normal loop (inline).torchtitan/rl/generator/sglang/gdn.py:94-106: rebuildMamba2StateShapewithdataclasses.replaceinstead of copying every field by hand (inline).
Questions
- README advertises HiCache (CPU KV offload) through
extra_server_args. Does it compose with the mamba radix cache for GDN models? If not, the README's GDN section should say so, or the engine should reject the combination at build time.
Details
- Gate: the problem is real (
replace_sglang_layer_configsraised forGDN.Configon the base branch). The layer is right: SGLang already owns state slots and prefix snapshots for its hybrid models, and this plugs in throughregister_linear_attn_modelrather than a parallel cache. The private SGLang loop internals that_normal_event_loop_iterationmirrors have a TODO, as the overlap version does. - Duplication between
_gdn_config_kwargs(registry.py) and vLLM'sunique_state_shape+ GDN tuple extraction, and the GDN/KDA backend scaffolding, is factored out in the stacked #5819 (sglang/linear_attention.py). So it isn't flagged here. paged_gdn.py: checked against the removed_split_qkv+_forward_gdnbody. Same ops, same order, same kwargs.local_key_dimis now computed fromnum_k_heads * head_k_dim, which equals the deleted attribute. The test edits only follow the moved names.- The
_qwen3_5_debug_bitwise_config-> public rename is needed: the SGLang parity test imports it, and CLAUDE.md bans importing_privatenames. - The new next-turn test runs on every parity class. It guards session KV reuse for softmax attention (previously untested) and GDN state resume. The author reports that it fails when
has_initial_stateis forced to False, so it earns its cost. It sorts before..._after_model_state_dict_load, which must run last.
Not verified: SGLang internals (the event_loop_normal body, slot-0 padding semantics, Mamba2StateShape being a dataclass); SGLang isn't importable in this environment, and the GPU parity results are the author's.
| layer.A_log = A_log_H | ||
| layer.dt_bias = dt_bias_H |
There was a problem hiding this comment.
GDN.forward passes self.A_log and self.dt_bias, which are nn.Parameters (FSDP's unsharded parameters while the group is unsharded). nn.Module.__setattr__ registers a Parameter value, so after the first forward linear_attention owns A_log and dt_bias as its own parameters. That contradicts the _SGLangRadixLinearAttention docstring ("It holds no parameters"). From then on, model.state_dict() has two extra keys per GDN layer (...inner_attention.linear_attention.A_log/.dt_bias) pointing at the unsharded parameters. _fsdp_load_groups (inference_model.py:467-471) would fail its assert on them if it ran after a forward. Today it runs at loader init, before any forward, so nothing breaks yet. But any later state_dict(), e.g. a re-built loader or a debug dump, would differ from the trainer's keys. conv_weights isn't affected because it's a tuple.
Bypass registration, the same way model_wrapper.py aliases attn ("unregistered so the state dict is unchanged"):
| layer.A_log = A_log_H | |
| layer.dt_bias = dt_bias_H | |
| object.__setattr__(layer, "A_log", A_log_H) | |
| object.__setattr__(layer, "dt_bias", dt_bias_H) |
(Or pass both in one tuple, as with conv_weights.)
| if not scheduler.enable_overlap: | ||
| raise ValueError("SGLangEngine needs SGLang's overlap scheduler") | ||
| return |
There was a problem hiding this comment.
This used to raise ValueError("SGLangEngine needs SGLang's overlap scheduler"). Now it returns for every model. A Qwen3 or MoE run where overlap ends up off (extra_server_args={"disable_overlap_schedule": True}, or any SGLang condition that turns overlap off by itself) now quietly runs the normal loop. Nothing else changes, the throughput is lower, and that path is only exercised by the GDN test class. The class docstring and README say the normal loop is the GDN path.
Two options. (a) Keep the raise unless the model has linear-attention layers, e.g. pass has_gdn = _gdn_config_kwargs(model) is not None (or check isinstance(scheduler.model_config.hf_config, TorchTitanGDNConfig)). (b) If any model on the normal loop is meant to be supported, say so in the docstring and README instead of "for GDN models". (a) fits the "no silent fallback to a slower path" rule.
| shape = Mamba2StateShape( | ||
| conv=[conv_shape[::-1]], | ||
| temporal=shape.temporal, | ||
| disable_conv_window_dedup=True, | ||
| intermediate_size=shape.intermediate_size, | ||
| conv_dim=shape.conv_dim, | ||
| ssm_state_size=shape.ssm_state_size, | ||
| num_heads=shape.num_heads, | ||
| head_dim=shape.head_dim, | ||
| state_size=shape.state_size, | ||
| conv_kernel=shape.conv_kernel, | ||
| num_k_heads_per_tp=shape.num_k_heads_per_tp, | ||
| ) |
There was a problem hiding this comment.
This rebuilds Mamba2StateShape by copying every field by hand, only to change conv and disable_conv_window_dedup. If SGLang adds a field, it silently goes back to its default here. If Mamba2StateShape is a dataclass (unverified: I couldn't import SGLang here), dataclasses.replace(shape, conv=[conv_shape[::-1]], disable_conv_window_dedup=True) does the same in two lines and stays in sync with the pinned SGLang version.
b6442eb to
04cb3c8
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The code findings from the last review are fixed at 04cb3c8. Only the human-written summary is still missing.
What this PR does. SGLang now runs TorchTitan's GDN layers (Qwen3.5). SGLang's mamba state pool owns each request's conv and recurrent state, and its radix cache snapshots them. TorchTitanGDNAttnBackend advances those states with the trainer's Attention Gym kernels. SGLang turns overlap scheduling off for these models, so step() drives SGLang's normal event loop instead. The vLLM paged GDN recurrence moves into paged_gdn.py, and both engines share it.
Example.
turn 1: session "0", prompt P (150) -> completion C (50); snapshot at token 200
turn 2: session "0", prompt P + C + S (8)
before: SGLangEngine raises for GDN layers
after: extend_prefix_lens = 200 -> has_initial_state = True; only S is prefilled
Since the last review
- Fixed:
sglang/gdn.py:932-938.conv_weights,A_loganddt_biasare now set withobject.__setattr__, sostate_dict()no longer gains keys after the first forward. - Fixed:
sglang/engine.py:529-558. A model with noLinearAttention.Configlayer still raises if SGLang turns overlap off, so the silent fallback to the slower loop is gone.GDN.ConfigsubclassesLinearAttention.Config, andmodelhere is the replacedDecoder.Config, so the check sees the right layers. - Fixed:
sglang/gdn.py:717-719.Mamba2StateShapeis now rebuilt withdataclasses.replace.
Must fix
- Still open: the "Summary (human-written)" section of the description is still the template placeholder. Only the author can fill it in (
CONTRIBUTING.md, "AI-assisted contributions").
Questions
- Still open: the README advertises HiCache (CPU KV offload) through
extra_server_args(README.md:83). Does it compose with SGLang's mamba radix cache for GDN models? If not, the GDN section should say so, or the engine should reject the combination at build time.
Not verified: SGLang internals (the event_loop_normal body, whether Mamba2StateShape is a dataclass). SGLang can't be imported here, and the GPU parity results are the author's. The PR only touches RL generator code; a maintainer still needs to review.
04cb3c8 to
17f16fa
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. I found no new problems at 17f16fa. The only open must-fix is the empty human-written summary.
What this PR does. SGLang now runs TorchTitan's GDN layers (Qwen3.5). SGLang's mamba state pool owns each request's conv and recurrent state, and its radix cache snapshots them. TorchTitanGDNAttnBackend advances those states with the trainer's Attention Gym kernels. These models run without overlap scheduling, so step() drives SGLang's normal event loop. The paged GDN recurrence moves out of the vLLM adapter into paged_gdn.py, and both engines share it.
Example.
turn 1: session "0", prompt P (150) -> completion C (50); state snapshot at token 200
turn 2: session "0", prompt P + C + S (8)
before: SGLangEngine raises for GDN layers
after: extend_prefix_lens = 200 -> has_initial_state = True; only S is prefilled
Since the last review
The branch was force-pushed as a single commit, and I can't fetch the previously reviewed 04cb3c8, so I re-read the full diff against sglang-4-sliding-window.
- The three earlier fixes are still in place at HEAD:
object.__setattr__forconv_weights/A_log/dt_bias(sglang/gdn.py:310-317).- Models with no
LinearAttention.Configlayer still raise when overlap is off (sglang/engine.py:269-273,:353-356). dataclasses.replaceforMamba2StateShape(sglang/gdn.py:95-97).
- New: the README, the engine docstring and a TODO in
register_to_sglang(registry.py:214-216) now explain why overlap is off: the backend registers without SGLang'sextra_buffermamba cache strategy, which needs state snapshots at intermediate positions. This covers the PR description's two follow-ups, with no code change.
Must fix
- Still open: the "Summary (human-written)" section of the description is still the template placeholder. Only the author can fill it in (
CONTRIBUTING.md, "AI-assisted contributions").
Questions
- Still open:
README.md:83lists HiCache (CPU KV offload) as supported, and the new GDN section (README.md:116-126) doesn't say whether it works with SGLang's mamba radix cache. If it doesn't, the GDN section should say so, or the engine should reject the combination at build time.
Not verified: SGLang internals (the event_loop_normal body, schedule_stream on a non-overlap scheduler), because SGLang can't be imported here. The GPU parity results are the author's. The PR only touches RL generator code; a maintainer still needs to review.
17f16fa to
4a48219
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. I found no new problems at 4a48219. The HiCache question is now answered in the README. The only open must-fix is still the empty human-written summary.
What this PR does. SGLang now runs TorchTitan's GDN layers (Qwen3.5). SGLang's mamba state pool owns each request's conv and recurrent state, and its radix cache snapshots that state. TorchTitanGDNAttnBackend advances the states with the trainer's Attention Gym kernels. These models run without overlap scheduling, so step() drives SGLang's normal event loop for them. The paged GDN recurrence moves out of the vLLM adapter into paged_gdn.py, and both engines share it.
Example.
turn 1: session "0", prompt P (150) -> completion C (50); state snapshot at token 200
turn 2: session "0", prompt P + C + S (8)
before: SGLangEngine raises for GDN layers
after: extend_prefix_lens = 200 -> has_initial_state = True; only S is prefilled
Since the last review
The branch was force-pushed again as a single commit, so I re-read the full diff against sglang-4-sliding-window.
- The earlier fixes are still in place:
object.__setattr__sets the per-call weights (sglang/gdn.py:310-317).- Models with no
LinearAttention.Configlayer still raise when overlap is off (sglang/engine.py:269-277,:356-359). dataclasses.replacerebuildsMamba2StateShape(sglang/gdn.py:96-98), now with a comment explaining why the window axis must come last for dedup.
- Resolved: the HiCache question.
README.md:153-155now says HiCache also keeps the GDN conv/recurrent states of evicted prefixes in host memory, and that a cached turn loaded back from host memory matched the trainer's prefill bitwise.
Must fix
- Still open: the "Summary (human-written)" section of the description is still the template placeholder. Only the author can fill it in (
CONTRIBUTING.md, "AI-assisted contributions").
Should consider
- The PR description's Numerics table doesn't list the HiCache + GDN bitwise check that
README.md:153-155now reports. Please add that row (hardware, config, result), so reviewers can verify the claim against a run.
Not verified: SGLang internals (the event_loop_normal body, HiCache's handling of mamba states), because SGLang can't be imported here. The GPU parity and HiCache results are the author's. The PR only touches RL generator code; a maintainer still needs to review.
4a48219 to
0f54fff
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. I found no new problems at 0f54fff. The only must-fix still open is the empty human-written summary.
What this PR does. SGLang now runs TorchTitan's GDN layers (Qwen3.5). SGLang's mamba state pool holds each request's conv and recurrent state, and its radix cache snapshots that state. TorchTitanGDNAttnBackend advances the states with the trainer's Attention Gym kernels. SGLang turns overlap scheduling off for these models, so step() drives SGLang's normal event loop for them. The paged GDN recurrence moves out of the vLLM adapter into paged_gdn.py, and both engines share it.
Example.
turn 1: session "0", prompt P (150) -> completion C (50); state snapshot at token 200
turn 2: session "0", prompt P + C + S (8)
before: SGLangEngine raises for GDN layers
after: extend_prefix_lens = 200 -> has_initial_state = True; only S is prefilled
Since the last review
The branch was force-pushed again as a single commit, and 4a48219 can't be fetched, so I re-read the full diff against sglang-4-sliding-window.
- All earlier fixes are still in place:
object.__setattr__sets the per-call weights (sglang/gdn.py:310-317).- Models with no
LinearAttention.Configlayer still raise when overlap is off (sglang/engine.py:270-278,:352-354). dataclasses.replacerebuildsMamba2StateShape(sglang/gdn.py:96-98).
- Resolved: the PR description's Numerics table now has the HiCache + GDN row (2x GB300, max delta 0, 199 of 208 prompt tokens served from the cache). This backs the claim at
README.md:153-155. - The
extra_bufferTODO inregister_to_sglang(registry.py:211-214) links an upstream SGLang issue.
Must fix
- Still open: the "Summary (human-written)" section of the description is still the template placeholder. Only the author can fill it in (
CONTRIBUTING.md, "AI-assisted contributions").
Not verified: SGLang internals (the event_loop_normal body, HiCache's handling of mamba states), because SGLang can't be imported here. The GPU parity and HiCache results are the author's. The PR only touches RL generator code; a maintainer still needs to review.
0f54fff to
d0a18b2
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The rebase onto main (with #5963 at the bottom) changes no logic. It moves both new files into the existing attention/ packages. The PR description is still missing its human-written summary, and it now names the old file paths.
What this PR does. SGLang now runs TorchTitan's GDN layers (Qwen3.5). Each request's conv and recurrent state lives in SGLang's mamba state pool, and SGLang's radix cache snapshots it. TorchTitanGDNAttnBackend advances these states with the trainer's Attention Gym kernels. SGLang turns overlap scheduling off for these models, so step() runs SGLang's normal event loop for them. The paged GDN recurrence moves out of the vLLM adapter into a module that both engines use.
Example.
turn 1: session "0", prompt P (150) -> completion C (50); state snapshot at token 200
turn 2: session "0", prompt P + C + S (8)
before: SGLangEngine raises for GDN layers
after: extend_prefix_lens = 200 -> has_initial_state = True; only S is prefilled
Since the last approval (bd57c68)
- Moved files:
paged_gdn.py->torchtitan/rl/generator/attention/gdn.py. It now sits next toattention.py'spaged_varlen_attention_out, in the package for "engine-agnostic attention kernels over paged state". That placement is right.sglang/gdn.py->torchtitan/rl/generator/sglang/attention/gdn.py, next toSGLangInnerAttention.- The imports are updated in the vLLM adapter,
registry.py,model_wrapper.pyand both vLLM GDN unit tests. Nothing still refers to the old paths,_split_qkv,local_key_dimor_qwen3_5_debug_bitwise_config.
paged_gdnstill matches the removed vLLM_split_qkv+_forward_gdnbody op for op. This includeskernel_options={"batch_invariant": True}onrecurrent_gdn, which comes from #5963 on the base. So with the attn-gym pin inrequirements.txt, both engines now use the batch-invariant scan.- The earlier fixes are still in place:
object.__setattr__for the per-call weights (sglang/attention/gdn.py:308-315).- Models with no
LinearAttention.Configlayer still raise when overlap is off (sglang/engine.py:284-290,:371-375). dataclasses.replaceforMamba2StateShape.- Both TODOs keep their upstream links (sglang#48463, #48472).
Must fix
- PR description:
- "Summary (human-written)" is still the template placeholder. Only the author can fill it in (
CONTRIBUTING.md, "AI-assisted contributions"). - "What changed" still names
sglang/gdn.pyandpaged_gdn.py. Rename them tosglang/attention/gdn.pyandgenerator/attention/gdn.pyso reviewers can find the files. - "Known issues" still describes the attn-gym 0.0.18 flakiness as open. It is fixed lower in this stack by #5963, so it could move to Numerics or be dropped.
- "Summary (human-written)" is still the template placeholder. Only the author can fill it in (
Not verified: SGLang internals (the event_loop_normal body, HiCache's handling of mamba states), because SGLang can't be imported here. The GPU parity and HiCache results are the author's. The PR only touches RL generator code; a maintainer still needs to review.
8ebda58 to
9fadc3f
Compare
9fadc3f to
e17c67b
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. At e17c67b, the description's file paths and the attn-gym note are fixed. I found no new problems in the code. The human-written summary is still the only open must-fix.
What this PR does. SGLang now runs TorchTitan's GDN layers (Qwen3.5). Each request's conv and recurrent state lives in SGLang's mamba state pool, and SGLang's radix cache snapshots it. TorchTitanGDNAttnBackend advances these states with the trainer's Attention Gym kernels. SGLang turns overlap scheduling off for these models, so step() runs SGLang's normal event loop for them. The paged GDN recurrence moves out of the vLLM adapter into torchtitan/rl/generator/attention/gdn.py, and both engines use it from there.
Example.
turn 1: session "0", prompt P (150) -> completion C (50); state snapshot at token 200
turn 2: session "0", prompt P + C + S (8)
before: SGLangEngine raises for GDN layers
after: extend_prefix_lens = 200 -> has_initial_state = True; only S is prefilled
Since the last approval
- Resolved: "What changed" now names
sglang/attention/gdn.pyandgenerator/attention/gdn.py, which match the diff. - Resolved: the attn-gym 0.0.18 flakiness moved from "Known issues" to "Testing", and it now says the problem is fixed by #5963.
- Checked against the code: the design text matches. The config is built and validated at registration (
_gdn_config_kwargs,registry.py), and models without linear attention still raise when overlap is off (engine.py,_init_event_loop(needs_overlap=...)). - After the rebase, the code diff is the same as at the last approval. The earlier fixes are all still in place:
object.__setattr__for the per-call weights.dataclasses.replaceforMamba2StateShape.- Both TODOs still link upstream issues (sglang#48463, #48472).
paged_gdnstill matches the removed vLLM_split_qkv+_forward_gdnbody op for op,kernel_options={"batch_invariant": True}included.
Must fix
- Still open: "Summary (human-written)" in the description is still the template placeholder. Only the author can fill it in (
CONTRIBUTING.md, "AI-assisted contributions").
Not verified: SGLang internals (the event_loop_normal body, how HiCache handles mamba states), because SGLang can't be imported here. The GPU parity and HiCache results are the author's. The PR only touches RL generator code; a maintainer still needs to review.
e17c67b to
a8200c5
Compare
… and paged attention out of vllm/ (#5811) ## Summary (human-written) <!-- Write this yourself, not with an AI tool. 2-5 sentences: the problem, why this approach, and what you checked yourself. --> ## Why The generator's TorchTitan model build, its initial HF load, the FSDP per-group model state dict load, and the paged-KV call into the trainer's varlen FlashAttention live inside `generator/vllm/`, although none of them is vLLM-specific. The SGLang engine stacked on top of this PR needs the same code; without this move it would have to copy about 500 lines of FSDP storage handling. **Example.** ```python # before: VLLMModelWrapper owns the build and the load engine._get_model()._prefetched_model_state_dict engine._get_model().load_model_state_dict(fetch) # after: any engine's wrapper builds the same loader model, parallelism_context = build_inference_model(config, parallelism=..., precision=..., device=...) loader = ModelStateDictLoader(model, checkpointer_config=..., model_state_dict_load_mode=...) # initial load loader.load(fetch) # engine._get_model().model_state_dict_loader.load(fetch) ``` ## What changed Mostly mechanical: the moved bodies are unchanged. The vLLM wrapper's `__init__` now runs build -> Dist-MoE runtime -> NUMA binding -> `ModelStateDictLoader` (initial HF load, `_fsdp_load_groups` and the `gpu_fetch` quantized-parameter check, pinned receive buffers, unshard) -> attention sinks -> TP all-reduce patch, and its dtype check runs before the `ParallelismContext` is built. Against main: - The initial HF load now runs after `maybe_apply_numa_binding` (main loads first, then binds). Its host allocations are then first-touched on the GPU's NUMA node, as the pinned receive buffers already were. - The sink injection and the TP all-reduce patch now run after the unshard. No effect: sinks are read per call, and the patch still comes after the initial load. Files: - `torchtitan/rl/generator/model.py` (new): `build_inference_model`, `ModelStateDictLoader` (the initial load, the `_fsdp_load_groups`, reshard/restore/unshard helpers and the `load_model_state_dict` body from `vllm/model_wrapper.py`), and `get_attention_dimensions` (from `vllm/attention/attention.py`). - `torchtitan/rl/generator/attention/attention.py` (new): the FA3/FA4 activation and the `varlen_attn_out` call (cu_seqlens_k handling, `num_splits=1` for FA2 and batch-invariant mode) from the vLLM CUSTOM backend. The package also gets the SGLang stack's paged GDN (#5817) and KDA (#5819) helpers. - `vllm/model_wrapper.py`, `vllm/attention/attention.py`, `vllm/engine.py`, `vllm/registry.py`: call the shared code; the wrapper exposes `model_state_dict_loader`. - Tests: the load tests move from `test_vllm_wrapper.py` to `test_generator_model.py`. Their `_Wrapper` and manual `_unshard_and_free_sharded_params` loop are dropped, since `ModelStateDictLoader.__init__` now does that unshard; other tests follow the renames. Reviewers can skim the moved bodies; the call sites in `vllm/model_wrapper.py` are the part to check. ## Numerics No computation change. The vLLM generator still matches the trainer bitwise: | Test | GPUs | Result | | --- | --- | --- | | `test_bitwise_parity.py::TestBitwiseParityVarlen` | 2x GB300 | 3 passed | | `test_bitwise_parity.py::TestBitwiseParityQwen35DebugVarlen` (syncs trainer weights through `ModelStateDictLoader`) | 2x GB300 | 5 passed (one flaky assertion, see below) | | `test_generator_dist_moe_mxfp8.py` (cpu_prefetch load of MXFP8 Dist-MoE weights) | 1x GB300 | 1 passed | ## Testing - `pytest tests/rl/unit_tests/cpu`: 546 passed, 7 skipped. - The GPU tests above. ## Known issues / follow-ups - `TestBitwiseParityQwen35DebugVarlen` fails one bitwise assertion in about 1 of 4 runs (max delta ~2e-3) on `main` too. - Next in the stack: the SGLang generation engine.
a8200c5 to
03d1c4a
Compare
felipemello1
left a comment
There was a problem hiding this comment.
I remember that in mxfp8 implementation we didnt properly pass the attn scaling in vllm. Please ask an agent to take a look if mxfp8 is supported properly in this stack.
Also, in the pr description is seems that for <199 tokens the GDN state is not saved? that sounds wasteful. I wonder if there's a fix or if stock sglang is also like that.
nitty nit: personally, as a human reading the code, i would like if in the future we wrote some prompt to make this come more beautiful. Like, better and shorter comments, docstrings with examples, etc. It looks too messy :D
| # Only linear attention models run without overlap scheduling (see step()). | ||
| self._init_event_loop( | ||
| needs_overlap=not any( | ||
| isinstance(layer.attention, LinearAttention.Config) | ||
| for layer in model.layers | ||
| ) | ||
| ) |
There was a problem hiding this comment.
i didn't see "step()", but probably its worth double checking if thats how stock sglang does it
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] It matches stock SGLang: when a model does not support extra_buffer, SGLang itself chooses no_buffer and turns overlap scheduling off, and _dispatch_event_loop_once then runs event_loop_normal. _normal_event_loop_iteration mirrors one iteration of event_loop_normal line for line. It leaves out request ingestion, the paused-engine branch and the strict memory check, as the overlap mirror does.
| # overlap, but needs the kernels to write state snapshots at | ||
| # intermediate positions (see register_to_sglang). |
There was a problem hiding this comment.
kernels here is FA4? should we raise it to driss?
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] The kernels are not FA4: they are Attention Gym's GDN kernels (paged_chunk_gdn, recurrent_gdn, paged_causal_conv1d). The ask for Attention Gym is that the chunked kernel return the states at chunk boundaries, as SGLang's own GDN kernel does for its extra_buffer strategy. The TODO in register_to_sglang now says that (1ddcd6c). An Attention Gym issue is drafted and waiting for @tianyu-l to file it.
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Filed as meta-pytorch/attention-gym#735.
| ) | ||
|
|
||
|
|
||
| def _normal_event_loop_iteration(scheduler: Scheduler) -> None: |
There was a problem hiding this comment.
is there a better word for normal?
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] "normal" is SGLang's own name (Scheduler.event_loop_normal), and this function mirrors that loop, so the name keeps the two easy to keep in sync. The step() comment explains it is the loop without overlap scheduling.
There was a problem hiding this comment.
Automated review by claude. Do NOT put high weight on this comment.
Without SGLang's extra_buffer strategy, GDN models lose overlap scheduling and prompt sharing.
One inline comment (registry.py:221-234). Without extra_buffer, GDN models:
- lose overlap scheduling here.
- lose prompt sharing later, because #5918 turns it off for them.
| # TODO(https://github.com/sgl-project/sglang/issues/48463): support SGLang's | ||
| # extra_buffer mamba cache strategy (support_mamba_cache_extra_buffer), which | ||
| # keeps overlap scheduling; it needs the kernels to write state snapshots at | ||
| # intermediate positions. | ||
| register_linear_attn_model( | ||
| LinearAttnModelSpec( | ||
| config_class=TorchTitanGDNConfig, | ||
| backend_class_name=( | ||
| f"{TorchTitanGDNAttnBackend.__module__}." | ||
| f"{TorchTitanGDNAttnBackend.__qualname__}" | ||
| ), | ||
| uses_mamba_radix_cache=True, | ||
| support_mamba_cache=True, | ||
| ) |
There was a problem hiding this comment.
Automated review by claude. Do NOT put high weight on this comment.
Without extra_buffer, a GDN model on this engine loses overlap scheduling and prompt sharing.
The TODO undersells this. extra_buffer and no_buffer are SGLang strategies for caching the GDN state. Without extra_buffer, a GDN model loses two things:
- Overlap scheduling.
- SGLang falls back to
no_buffer. - The engine then steps the normal loop (engine.py:522-529).
- SGLang falls back to
- Prompt sharing in a rollout group.
- Holding = keep later requests with the same prompt out of SGLang's waiting queue until the first request's prefill is processed.
- Without
extra_buffer, the state exists only at the end of the cached prefix. So [rl] generator: SGLang reuses a rollout group's prompt KV #5918 turns holding off. - So a group of 16 samples prefills the prompt 16 times.
Who keeps both
- SGLang's own Qwen3.5 models keep both through
extra_buffer(overrides.py:396-405 at the pinned SGLang commit). - Miles uses those models.
- The Qwen3.5 recipes here pay both costs on SGLang (alphabet_sort.py:792, 865 and verifiers_terminal_bench.py:158, 279).
Why it is not a quick fix
It is more than a flag. The kernels must write a mid-prompt state snapshot, as the TODO says.
Listing both costs in the TODO would help weigh that work.
03d1c4a to
8ba0cf7
Compare
8ba0cf7 to
1ddcd6c
Compare
|
[From Claude (AI agent), on behalf of @tianyu-l] On @felipemello1's review body:
1ddcd6c also turns on |
| scheduler._war_barrier_enabled = is_war_barrier_enabled() | ||
| if not scheduler.enable_overlap: | ||
| raise ValueError("SGLangEngine needs SGLang's overlap scheduler") | ||
| if needs_overlap: |
There was a problem hiding this comment.
instead of introducing this flag here, can we do sth like
if server_args.disable_overlap_schedule and not any(
isinstance(layer.attention, LinearAttention.Config) for layer in model.layers
):
raise ValueError("SGLangEngine needs SGLang's overlap scheduler")
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Done in 29cce70: the check now sits in SGLangEngine.__init__ next to the model it reads, and _init_event_loop has no flag. It reads scheduler.enable_overlap rather than server_args.disable_overlap_schedule: SGLang decides overlap for linear attention models itself (it turns it off when extra_buffer is unsupported), so the scheduler's resolved value is the one that holds. #5853 then uses its has_linear_attention there. GDN (overlap off) and Varlen (overlap on) pass at this PR's head and at the top of the stack.
GDN layers (Qwen3.5) run on SGLang's mamba state pool with the trainer's Attention Gym kernels, registered through SGLang's linear attention model registry, so SGLang's radix cache snapshots each request's conv and recurrent state and a session's next turn resumes from its cached prefix. - sglang/gdn.py: the HF-shaped hybrid config (state slot shapes, with Attention Gym's [W - 1, C] conv layout and a float32 recurrent state), TorchTitanGDNAttnBackend, and SGLangInnerGDN. Breakable prefill CUDA graphs run the backend eagerly at replay with the layer attributes of the last capture, so the adapter passes parameter storage and the backend derives the tensors the kernels take. - engine.py: SGLang's mamba radix cache needs its normal (non-overlap) event loop; step() runs one iteration of whichever loop SGLang uses. Models without linear attention still require overlap scheduling. - registry.py: registers the GDN backend through SGLang's linear attention model registry; the GDN dimensions are validated at registration. - paged_gdn.py: the GDN recurrence over a paged state pool, moved from the vLLM adapter and shared by both engines (mechanical); the vLLM GDN unit tests patch the moved names. - test_sglang_bitwise_parity.py: Qwen3.5 debug at TP 2, and a new test for every model family: parity for a session's next turn, which resumes its cached prefix (KV, and GDN states). It also covers the session KV of softmax attention, which had no test. The GDN class reuses test_bitwise_parity's Qwen3.5 config, now public.
- The GDN parity class turns on reset_kv_cache_on_model_state_dict_load, so CI covers the reset path (retract, flush, continue) with SGLang's normal event loop, including a load while requests decode. - The extra_buffer TODO names both costs of its absence (no overlap scheduling, no reuse of a prefix shared mid-request) and the kernel change it needs. - The overlap-scheduling check moves to SGLangEngine.__init__, next to the model it reads: it raises unless SGLang kept overlap scheduling or the model has linear attention. _init_event_loop loses its needs_overlap flag. - The extra_buffer TODO links meta-pytorch/attention-gym#735.

Stacked on #5816 (SGLang sliding window).
Summary (human-written)
Why
SGLangEngineraises for GDN linear attention (Qwen3.5). GDN layers keep aper-request conv and recurrent state instead of KV. SGLang already manages such
states for its own hybrid models (a state pool whose slots its radix cache
snapshots), and its linear attention model registry accepts external models. This
PR runs TorchTitan's GDN on SGLang's state slots with the trainer's Attention Gym
kernels. A session's next turn resumes from its cached prefix, as with KV.
Example.
What changed
sglang/attention/gdn.py(new):TorchTitanGDNConfig: the HF-shaped config SGLang reads to size state slots.It uses Attention Gym's
[W - 1, C]conv layout and a float32 recurrent state.TorchTitanGDNAttnBackend: runs Attention Gym's conv and GDN kernels onSGLang's slots.
SGLangInnerGDN.Breakable prefill CUDA graphs call the backend eagerly at replay, using the layer
attributes from the last capture. So the adapter hands over parameter storage,
and the backend derives the tensors the kernels take.
sglang/engine.py: SGLang's mamba radix cache runs without overlap scheduling,so
step()runs one iteration of whichever event loop SGLang uses. Models withoutlinear attention still require overlap scheduling.
sglang/registry.py: registers the backend through SGLang's linear attentionmodel registry, and builds and validates the GDN config at registration.
generator/attention/gdn.py(new): the GDN recurrence over a paged state pool, moved from thevLLM adapter and shared by both engines. This is mechanical. The vLLM GDN unit
tests patch the moved names.
Tests:
session KV for softmax attention ([rl] generator: SGLang generation engine #5812), which had no test.
CI: the B200 SGLang step also runs
TestSGLangBitwiseParityGDN.Review fixes (29cce70): the GDN parity class turns on
reset_kv_cache_on_model_state_dict_load, so CI covers the reset path (retract,flush, continue) with SGLang's normal event loop, including a load mid-decode;
the
extra_bufferTODO names both costs of its absence (no overlap scheduling,no reuse of a prefix shared mid-request) and the kernel change it needs. The overlap
check moved to
SGLangEngine.__init__(raise unless SGLang kept overlap or themodel has linear attention); the TODO links Chunked GDN / KDA kernels: return the recurrent state at chunk boundaries (for SGLang's extra_buffer prefix cache) meta-pytorch/attention-gym#735.
User-facing changes
Numerics
TestSGLangBitwiseParityGDN(Qwen3.5 debug, TP 2), incl. the next-turn testhas_initial_stateFalse), it failsTestBitwiseParityQwen35DebugVarlen(covers the moved paged GDN)write_through, small GPU pools): cached turn whose prefix was evicted to host memory and loaded back (local script; Qwen3.5 debug, TP 2)Testing
pytest tests/rl/unit_tests/cpu: 546 passed.whose recurrent GDN scan rounds differently per launch config. [models] GDN batch-invariant mode: attn-gym's batch-invariant recurrent scan #5963 pins attn-gym with the
batch-invariant scan (Recurrent delta-rule scan: same output bits for every launch config meta-pytorch/attention-gym#704) and opts in; with it, the class passed
3 of 3 runs, where 0.0.18 failed 3 of 3.
Known issues / follow-ups
intermediate positions: a prefix shared at another position recomputes.