Skip to content

[rl] generator: SGLang GDN linear attention - #5817

Merged
tianyu-l merged 2 commits into
sglang-4-sliding-windowfrom
sglang-5-gdn
Nov 10, 2026
Merged

tianyu-l merged 2 commits into
sglang-4-sliding-windowfrom
sglang-5-gdn

Conversation

@tianyu-l

@tianyu-l tianyu-l commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5816 (SGLang sliding window).

Summary (human-written)

Why

SGLangEngine raises for GDN linear attention (Qwen3.5). GDN layers keep a
per-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.

turn 1: prompt (150) + completion (50) -> radix cache: KV of full-attention layers
                                          + GDN conv/recurrent state at token 200
turn 2: turn 1 + 8 new tokens          -> prefill 8 tokens from the cached state

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 on
      SGLang'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 without
    linear attention still require overlap scheduling.

  • sglang/registry.py: registers the backend through SGLang's linear attention
    model 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 the
    vLLM adapter and shared by both engines. This is mechanical. The vLLM GDN unit
    tests patch the moved names.

  • Tests:

  • 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_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
    check moved to SGLangEngine.__init__ (raise unless SGLang kept overlap or the
    model 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

Before After
GDN layers raise supported; SGLang runs these models without overlap scheduling

Numerics

Check Hardware Result
TestSGLangBitwiseParityGDN (Qwen3.5 debug, TP 2), incl. the next-turn test 2x GB300 4 passed, max delta 0; with the cached state ignored (has_initial_state False), it fails
Next-turn test on every class (Qwen3, MoE EP, Dist-MoE, sliding window) 2x GB300 passed, max delta 0
vLLM TestBitwiseParityQwen35DebugVarlen (covers the moved paged GDN) 2x GB300 5 passed
HiCache (write_through, small GPU pools): cached turn whose prefix was evicted to host memory and loaded back (local script; Qwen3.5 debug, TP 2) 2x GB300 max delta 0; 199 of 208 prompt tokens served from the cache (0 without HiCache)

Testing

Known issues / follow-ups

  • SGLang snapshots a request's state when it caches the request, not at
    intermediate positions: a prefix shared at another position recomputes.
  • No overlap scheduling for these models (SGLang's mamba radix cache).

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 4, 2026
@tianyu-l
tianyu-l added this pull request to stack #5813 November 4, 2026 19:49
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 4, 2026
@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 4m 41s —— View job


Approve -- please address the items before merging -- 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 -- 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

  1. The PR description's "Summary (human-written)" section is empty. Only the author can fill it in (see CONTRIBUTING.md, "AI-assisted contributions").
  2. torchtitan/rl/generator/sglang/gdn.py:319-320: assigning the A_log/dt_bias Parameters registers them on linear_attention, so state_dict() gains two extra keys per GDN layer after the first forward. Fix with object.__setattr__ (inline).

Should consider

  • torchtitan/rl/generator/sglang/engine.py:342-343: the overlap-scheduler ValueError is 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: rebuild Mamba2StateShape with dataclasses.replace instead 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_configs raised for GDN.Config on the base branch). The layer is right: SGLang already owns state slots and prefix snapshots for its hybrid models, and this plugs in through register_linear_attn_model rather than a parallel cache. The private SGLang loop internals that _normal_event_loop_iteration mirrors have a TODO, as the overlap version does.
  • Duplication between _gdn_config_kwargs (registry.py) and vLLM's unique_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_gdn body. Same ops, same order, same kwargs. local_key_dim is now computed from num_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 _private names.
  • 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_state is 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.

Comment thread torchtitan/rl/generator/sglang/gdn.py Outdated
Comment on lines +319 to +320
layer.A_log = A_log_H
layer.dt_bias = dt_bias_H

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.

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"):

Suggested change
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.)

Comment on lines 342 to +343
if not scheduler.enable_overlap:
raise ValueError("SGLangEngine needs SGLang's overlap scheduler")
return

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 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.

Comment thread torchtitan/rl/generator/sglang/gdn.py Outdated
Comment on lines +94 to +106
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,
)

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 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.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 5s —— View job


Approve -- please address the items before merging (all three code findings are fixed; the human-written summary is still empty) -- 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 -- 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_log and dt_bias are now set with object.__setattr__, so state_dict() no longer gains keys after the first forward.
  • Fixed: sglang/engine.py:529-558. A model with no LinearAttention.Config layer still raises if SGLang turns overlap off, so the silent fallback to the slower loop is gone. GDN.Config subclasses LinearAttention.Config, and model here is the replaced Decoder.Config, so the check sees the right layers.
  • Fixed: sglang/gdn.py:717-719. Mamba2StateShape is now rebuilt with dataclasses.replace.

Must fix

  1. 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.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 26s —— View job


Approve -- please address the item before merging (no new problems at 17f16fa; the human-written summary is still empty) -- 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 -- 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__ for conv_weights/A_log/dt_bias (sglang/gdn.py:310-317).
    • Models with no LinearAttention.Config layer still raise when overlap is off (sglang/engine.py:269-273, :353-356).
    • dataclasses.replace for Mamba2StateShape (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's extra_buffer mamba cache strategy, which needs state snapshots at intermediate positions. This covers the PR description's two follow-ups, with no code change.

Must fix

  1. 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:83 lists 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.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 51s —— View job


Approve -- please address the item before merging (no new problems at 4a48219; the HiCache question is answered; the human-written summary is still empty) -- 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 -- 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.Config layer still raise when overlap is off (sglang/engine.py:269-277, :356-359).
    • dataclasses.replace rebuilds Mamba2StateShape (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-155 now 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

  1. 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-155 now 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.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 10s —— View job


Approve -- please address the item before merging (no new problems at 0f54fff; the HiCache numerics row is now in the description; the human-written summary is still empty) -- 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 -- 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.Config layer still raise when overlap is off (sglang/engine.py:270-278, :352-354).
    • dataclasses.replace rebuilds Mamba2StateShape (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_buffer TODO in register_to_sglang (registry.py:211-214) links an upstream SGLang issue.

Must fix

  1. 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.

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 2s —— View job


Approve -- please address the item before merging (no new problems at d0a18b2; the human-written summary is still empty) -- review

@tianyu-l
tianyu-l removed this pull request from stack #5813 November 8, 2026 23:51
@tianyu-l
tianyu-l added this pull request to stack #5964 November 8, 2026 23:51
@tianyu-l

tianyu-l commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] @claude review again. The stack was rebased onto latest main, with the new #5963 (attn-gym batch-invariant GDN scan) at the bottom; please check the changes since your last approval.

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 1m 13s —— View job


Approve -- please address the item before merging. The rebase changes no logic, only moves the two new files into the attention/ packages. The PR description still lacks the human-written summary and names the old file paths. 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 -- 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 to attention.py's paged_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 to SGLangInnerAttention.
    • The imports are updated in the vLLM adapter, registry.py, model_wrapper.py and both vLLM GDN unit tests. Nothing still refers to the old paths, _split_qkv, local_key_dim or _qwen3_5_debug_bitwise_config.
  • paged_gdn still matches the removed vLLM _split_qkv + _forward_gdn body op for op. This includes kernel_options={"batch_invariant": True} on recurrent_gdn, which comes from #5963 on the base. So with the attn-gym pin in requirements.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.Config layer still raise when overlap is off (sglang/engine.py:284-290, :371-375).
    • dataclasses.replace for Mamba2StateShape.
    • Both TODOs keep their upstream links (sglang#48463, #48472).

Must fix

  1. 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.py and paged_gdn.py. Rename them to sglang/attention/gdn.py and generator/attention/gdn.py so 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.

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.

@tianyu-l

tianyu-l commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] @claude review again. The description is updated for your must-fix items (file paths and design now match the code); the stack is also rebased onto latest main.

@claude

claude Bot commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 49s —— View job


Approve -- please address the item before merging. The description's file paths and the attn-gym note are fixed, and the code is the same as at the last approval. The human-written summary is still empty. 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 -- 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.py and generator/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.replace for Mamba2StateShape.
    • Both TODOs still link upstream issues (sglang#48463, #48472).
  • paged_gdn still matches the removed vLLM _split_qkv + _forward_gdn body op for op, kernel_options={"batch_invariant": True} included.

Must fix

  1. 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.

tianyu-l added a commit that referenced this pull request Nov 9, 2026
… 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.
@felipemello1

Copy link
Copy Markdown
Contributor

from claude to felipe: a TLDR image of this PR, drawn from its diff at 03d1c4afa.

Before, SGLangEngine raised for GDN layers; now SGLang's radix cache keeps the KV plus the GDN state after token 199, so the next turn prefills only 9 tokens; a prefix shared at an earlier position still recomputes.

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

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

Comment on lines +284 to +290
# 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
)
)

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.

i didn't see "step()", but probably its worth double checking if thats how stock sglang does it

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.

[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.

Comment on lines +527 to +528
# overlap, but needs the kernels to write state snapshots at
# intermediate positions (see register_to_sglang).

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.

kernels here is FA4? should we raise it to driss?

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.

[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.

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.

[From Claude (AI agent), on behalf of @tianyu-l] Filed as meta-pytorch/attention-gym#735.

)


def _normal_event_loop_iteration(scheduler: Scheduler) -> 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.

is there a better word for normal?

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.

[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.

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

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:

  1. lose overlap scheduling here.
  2. lose prompt sharing later, because #5918 turns it off for them.

Comment on lines +221 to +234
# 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,
)

@felipemello1 felipemello1 Nov 10, 2026 •

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.

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:

  1. Overlap scheduling.
    • SGLang falls back to no_buffer.
    • The engine then steps the normal loop (engine.py:522-529).
  2. 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.

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.

[From Claude (AI agent), on behalf of @tianyu-l] Agreed. The TODO now names both costs, no overlap scheduling and no reuse of a prefix shared mid-request (e.g. a rollout group's prompt), plus the kernel change it needs (1ddcd6c).

@tianyu-l

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] On @felipemello1's review body:

  • MXFP8 and attention scaling. The vLLM bug I believe you mean is [rl] Fix model-specific attention scaling in vLLM #5347, a model-specific softmax_scale (GPT-OSS, DeepSeek YaRN mscale) that vLLM's attention replacement dropped. It was not MXFP8-specific.
    • The SGLang stack passes attention_cfg.softmax_scale into RadixAttention(scaling=...), and the inner attention raises if the model's scale differs. That covers MLA's scale (DeepSeek V3, Kimi K3).
    • MXFP8 itself goes through the shared model build, state dict loader and build_dist_moe_runtime, which the vLLM engine also uses.
    • No SGLang test runs MXFP8 yet; a GPU smoke run of an MXFP8 recipe on SGLang is a follow-up.
  • "<199 tokens". That row is a cached turn: the second turn's prompt is 208 tokens, the previous turn's 200 plus 8 new. 199 of them have KV and a GDN state, because the last sampled token never went through the model. So nothing is lost there, and vLLM and stock SGLang behave the same way.
    • The real limitation is the one under Known issues: with SGLang's no_buffer strategy, the state exists only at the end of the cached prefix, so a prefix shared at an earlier position (a rollout group's prompt) gets no reuse.
    • Stock SGLang with no_buffer is the same. extra_buffer fixes it but needs Attention Gym's chunked kernel to return the states at chunk boundaries. The TODO now says so (1ddcd6c), and an Attention Gym issue is drafted.
  • Readability. Noted; this round rewrote the comments the review pointed at.

1ddcd6c also turns on reset_kv_cache_on_model_state_dict_load in the GDN class, so CI covers the reset path with SGLang's normal event loop. The class passes 6 of 6 on 2x GB300.

scheduler._war_barrier_enabled = is_war_barrier_enabled()
if not scheduler.enable_overlap:
raise ValueError("SGLangEngine needs SGLang's overlap scheduler")
if needs_overlap:

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.

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")

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.

[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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI 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.

3 participants