Repository navigation
[models] GDN batch-invariant mode: attn-gym's batch-invariant recurrent scan - #5963
Conversation
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The fix goes in the right layer: attn-gym owns the scan's arithmetic, and #704 is an upstream opt-in. Both sides of the parity test (trainer and vLLM) now pass it. A maintainer still needs to review, since this touches models/common/.
What this PR does. In batch-invariant mode, the trainer's GDN custom op and vLLM's GDN prefill and decode both run attn-gym's recurrent_gdn. In 0.0.18, that scan picks BV/num_warps/PREFETCH from the batch shape, and each config rounds differently. This PR pins attn-gym to the merge of meta-pytorch/attention-gym#704 and passes kernel_options={"batch_invariant": True} at both call sites. The scan then uses one arithmetic for every launch config. Non-batch-invariant paths (chunk_gdn, paged_chunk_gdn, recurrent_gdn_decode) are unchanged.
Example.
Sequence S, batch-invariant mode
trainer: S packed with 3 other docs -> scan launch config A
vLLM: S prefilled alone -> scan launch config B
before: config A and B round differently -> max_delta up to 5e-3, flaky parity test
after: batch_invariant=True -> same formula, fixed-order tl.sum, no FMA for A and B -> bitwise
Must fix
- PR description: the "Summary (human-written)" section is empty. The author needs to fill it in.
.ci/docker/requirements.txt:16: through the rootrequirements.txtsymlink andpyproject.toml:23, the git URL becomes a direct-URLRequires-Dist, which PyPI rejects. No release can be published while this pin is in place. Either get an attn-gym 0.0.19 first, or say so in the TODO (inline suggestion).tests/unit_tests/gpu/models/qwen3_5/test_qwen3_5_deltanet.py:842,863(outside the diff):test_batch_invariant_recurrent_matches_paged_attention_gymmirrors vLLM's paged call. It still callsrecurrent_gdnwithoutkernel_options={"batch_invariant": True}(and withoutautotune=False), and compares withatol=0against a trainer op that now passes the opt-in. So the bitwise check compares the batch-invariant arithmetic against the default arithmetic. It passes only if those agree at this shape. It would not catch a regression where vLLM's opt-in path and the trainer's diverge. Addautotune=False, kernel_options={"batch_invariant": True}to both reference calls so they matchrl/generator/vllm/attention/gdn.py:381-396.
Should consider
torchtitan/models/common/attention/gdn.py:84: the_recurrent_gdn_fwd->_batch_invariant_recurrent_gdn_fwdrename isn't needed for the fix (one concern per PR). See inline.
Not verified: that the batch-invariant scan is bitwise across trainer/vLLM shapes on hardware other than GB300 (I relied on the PR's 3x GB300 runs), and that test_qwen3_5_deltanet.py still passes with the reference change from item 3.
| # TODO: pin a release once attn-gym publishes one with | ||
| # https://github.com/meta-pytorch/attention-gym/pull/704 (batch-invariant | ||
| # recurrent scan), which GDN batch-invariant mode needs. | ||
| attn-gym[linear,cudnn] @ git+https://github.com/meta-pytorch/attention-gym.git@26beb363c6d1328851bfc5c9c8691fa2066bd1fa |
There was a problem hiding this comment.
This file is the root requirements.txt (symlink), and pyproject.toml:23 builds the package's dependencies from it. So the wheel's Requires-Dist now has a direct git+https URL. PyPI rejects uploads with direct URL dependencies ("Can't have direct dependency"), so release.yml and test_release.yml will fail at publish for as long as this pin is in place. Two ways to handle it: ask attn-gym to cut 0.0.19 with #704 before this merges, or keep the pin and say so in the TODO, so that whoever cuts the next release isn't surprised:
| # TODO: pin a release once attn-gym publishes one with | |
| # https://github.com/meta-pytorch/attention-gym/pull/704 (batch-invariant | |
| # recurrent scan), which GDN batch-invariant mode needs. | |
| attn-gym[linear,cudnn] @ git+https://github.com/meta-pytorch/attention-gym.git@26beb363c6d1328851bfc5c9c8691fa2066bd1fa | |
| # TODO: pin a release once attn-gym publishes one with | |
| # https://github.com/meta-pytorch/attention-gym/pull/704 (batch-invariant | |
| # recurrent scan), which GDN batch-invariant mode needs. PyPI rejects direct | |
| # URL dependencies, so torchtitan can't publish a release until then. | |
| attn-gym[linear,cudnn] @ git+https://github.com/meta-pytorch/attention-gym.git@26beb363c6d1328851bfc5c9c8691fa2066bd1fa |
| "torchtitan::batch_invariant_recurrent_gdn_fwd", | ||
| mutates_args=(), | ||
| device_types="cuda", | ||
| ) | ||
| def _recurrent_gdn_fwd( | ||
| def _batch_invariant_recurrent_gdn_fwd( |
There was a problem hiding this comment.
The fix doesn't need the rename _recurrent_gdn_fwd -> _batch_invariant_recurrent_gdn_fwd (and the op, fake, setup_context and backward renames). It makes up most of this file's diff and the test churn. The docstring already says "Run the batch-invariant GDN recurrent forward kernel", and the only caller sits under if is_in_batch_invariant_mode(). Under "one concern per PR", consider dropping the rename here or moving it to its own PR. If you keep it, it's mechanical and correct: no other references to torchtitan::recurrent_gdn_fwd remain in the repo.
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Keeping the rename: the maintainer asked for it, since _recurrent_gdn_fwd now always opts in to the batch-invariant scan and readers took it for the general recurrent path. The description marks it as mechanical.
| "Install it with: python -m pip install 'attn-gym[linear,cudnn]==0.0.18'.", | ||
| "Install it with: python -m pip install 'attn-gym[linear,cudnn] @ " | ||
| "git+https://github.com/meta-pytorch/attention-gym.git" | ||
| "@26beb363c6d1328851bfc5c9c8691fa2066bd1fa'.", |
There was a problem hiding this comment.
should we add a TODO to update this after @liangel-02 bumps the version?
There was a problem hiding this comment.
edit: i saw just that you added it to requiements. Probably worth adding it here as well, or a reference in requirements.txt, so we dont forget
There was a problem hiding this comment.
I don't think depending on nightly is a big problem. As long as stable release of torchtitan depends on stable attn-gym (which is a requirement of general releasing for obvious reasons), we should be OK.
| # Triton autotuning breaks batch invariance. | ||
| # Triton autotuning breaks batch invariance, and the scan otherwise | ||
| # picks its arithmetic from the batch shape. | ||
| autotune=False, |
There was a problem hiding this comment.
would we allow autotune for NON batch invariant?
There was a problem hiding this comment.
I think so? This is under batch inv condition
ed44ae5 to
89c2632
Compare
|
[From Claude (AI agent), on behalf of @tianyu-l] @claude review again. 89c2632: the attn-gym TODO now says torchtitan can't publish a release until attn-gym releases #704 (PyPI rejects direct URL dependencies), and |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. 89c2632 resolves both code findings from the last review. Only the empty human-written summary is left. A maintainer still needs to review, since this touches models/common/.
Earlier findings
- Resolved:
.ci/docker/requirements.txt:13-17. The TODO now says torchtitan can't publish a release while the direct-URL pin is in place. - Resolved:
tests/unit_tests/gpu/models/qwen3_5/test_qwen3_5_deltanet.py:853-854,876-877. Both referencerecurrent_gdncalls now passautotune=False, kernel_options={"batch_invariant": True}, which matchesrl/generator/vllm/attention/gdn.py:381-396. Theatol=0check now compares the opt-in arithmetic on both sides. - Rename (should-consider): the author kept it at the maintainer's request and marks it mechanical in the description. Closed.
- Still open: the "Summary (human-written)" section of the PR description is empty. The author needs to fill it in.
New commit
I found no new problems. tests/rl/unit_tests/gpu/test_gdn_cudagraph.py wraps recurrent_gdn (without_mask, and the call recorder in run_engine), and both wrappers forward **kwargs, so the new kernel_options keyword reaches the kernel.
On @felipemello1's comments
rl/generator/vllm/attention/gdn.py:394("autotune for non batch invariant?"): yes.autotune=Falseand the new opt-in only run in theis_in_batch_invariant_mode()branch. Outside that mode, vLLM callspaged_chunk_gdnwithchunk_kernel_options(query), which this PR doesn't change.models/common/attn_gym.py:151(a TODO for the version bump): the existing line 146 comment ("Keep the version in sync with the attn-gym pin in .ci/docker/requirements.txt") already points to the pin, and the TODO lives there. Adding a second TODO is optional. Neither comment has a reply on the PR yet.
Not verified: the GPU test results (9 passed in deltanet, 3x5 passes in the parity test on GB300); I relied on the author's runs.
|
Do we need a new releas of AG? |
|
@drisspg that'd be nice, but it seems also ok to use nightly before next titan stable release |
…nt scan attn-gym 0.0.18's recurrent GDN scan picks its arithmetic from the launch config, so the trainer and vLLM, which run it on different batch shapes, can differ in the last bits. TestBitwiseParityQwen35DebugVarlen fails on about half of main's RL Multi-GPU runs this way. Pin attention-gym at 26beb36 (meta-pytorch/attention-gym#704) and opt in with kernel_options={"batch_invariant": True} where torchtitan calls recurrent_gdn: the trainer's custom op (renamed to batch_invariant_recurrent_gdn_fwd, as it only runs in batch-invariant mode) and the vLLM GDN prefill.
89c2632 to
910f311
Compare
Stacked on #5816 (SGLang sliding window). ## 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 `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: - a Qwen3.5 parity class; - a new test in the base class: parity for a session's next turn. It also covers session KV for softmax attention (#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_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 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 - As above. vLLM GDN unit tests: 21 passed, 2 skipped (need a Qwen3.5-0.8B model). - `pytest tests/rl/unit_tests/cpu`: 546 passed. - The GDN parity class depends on #5963: it failed intermittently on attn-gym 0.0.18, whose recurrent GDN scan rounds differently per launch config. #5963 pins attn-gym with the batch-invariant scan (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 - 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).
Stacked on #5818 (SGLang MLA). ## 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 `SGLangEngine` raises for KDA linear attention (Kimi K3). KDA runs like GDN (#5817), with one difference. Batch-invariant GDN runs a sequential scan with no replay state (#5963), but the trainer's KDA runs a chunk kernel, so the generator keeps it: in batch-invariant mode, Attention Gym advances the recurrent state only at 64-token chunk boundaries. It keeps the unfinished chunk's q/k/v/gate/beta in a per-slot replay state, which is what makes decode match the trainer's chunk kernel bitwise. SGLang's state pool holds one conv list in one dtype plus one temporal state, with no place for replay tensors. **Example.** ``` after 150 tokens: recurrent state at token 128 + replay state of tokens 129-150 SGLang slot: conv list = [conv history (bf16, [W-1, C]), q, k, v, gate, beta, count: each flattened to bf16 bytes, padded to 16 bytes (count: 4 -> 16)] temporal = recurrent state (fp32) radix cache snapshot of a slot copies every conv entry -> replay state included ``` ## What changed - `sglang/attention/kda.py` (new): `TorchTitanKDAConfig` (state slot shapes; in batch-invariant mode, each replay tensor is one flat conv entry sized in bytes of the conv dtype and padded to 16 bytes, because SGLang's HiCache copies each slot entry in 16-byte words), `TorchTitanKDAAttnBackend` (views the replay entries back as their dtypes and shapes), and `SGLangInnerKDA`. - `sglang/attention/linear_attention.py` (new): the parts GDN and KDA share inside SGLang, moved out of `gdn.py`: the HF config base, the `RadixLinearAttention` module, the weight hand-off and padding rows, and the extend-path convolution. - `sglang/registry.py`: - registers the KDA backend; a model with both GDN and KDA layers raises. - patches SGLang's hybrid KV pool for TorchTitan models (TODO). The pool builds its full-attention KV pool without `v_head_dim`, though it counts it when sizing. Kimi K3's MLA layers have V head dim 128 against K 192. - `generator/attention/kda.py` (new): the KDA recurrence over a paged state pool, moved from the vLLM adapter and shared by both engines. Mechanical. - `sglang/engine.py`: docstring only. - Tests: - a Kimi K3 parity class (SM90+); - the class reuses `test_bitwise_parity`'s Kimi K3 config, renamed to a public name. - CI: the B200 SGLang step also runs `TestSGLangBitwiseParityKDA`, in a one-process launch. ## User-facing changes | Before | After | | --- | --- | | KDA layers raise | supported; in batch-invariant mode, the replay state takes 1.25x the recurrent state's memory (head dim 128) | ## Numerics | Check | Hardware | Result | | --- | --- | --- | | `TestSGLangBitwiseParityKDA` (Kimi K3 debug: KDA + MLA, TP 1), incl. the next-turn test | 1x GB300 | 4 passed, max delta 0 | | Same, replay state dropped (state-only decode) | 1x GB300 | fails, delta 3.7e-2 | | Same, cached state ignored | 1x GB300 | fails, delta 7.1e-2 | | Same tests outside batch-invariant mode (smoke) | 1x GB300 | mean abs logprob diff 2-5e-3, max < 0.08 | | vLLM `TestBitwiseParityKimiK3DebugVarlen` (covers the moved paged KDA) | 1x GB300 | 4 passed | | HiCache (`write_through`, small GPU pools): cached turn whose prefix was evicted to host memory and loaded back (local script) | 1x GB300 | max delta 0; 199 of 208 prompt tokens served from the cache (0 without HiCache). Unpadded entries crashed the first host backup | | `TestSGLangBitwiseParityKDA` with HiCache `write_through`, 18 runs (local) | 1x GB300 | 17 passed; 1 run had a trainer-vs-SGLang mismatch (see Known issues). 8 of 8 passed without HiCache | ## Testing - As above. - All SGLang parity classes rerun at the top of the stack. GDN covers the moved shared code. - `reset_kv_cache_on_model_state_dict_load=True` (the Kimi K3 batch-invariant recipe's setting), Qwen3.5 and Kimi K3. Checked with a local script: - A reload of the same weights mid-generation retracts the running requests, flushes their states and recomputes them. Tokens and logprobs are identical to a run without a reload (5 of 5 sequences each, delta 0). - The model-state-dict-load parity test passes in reset mode. - `pytest tests/rl/unit_tests/cpu`: 546 passed. ## Known issues / follow-ups - With HiCache `write_through` (SGLang's default policy), one run in 18 of the KDA parity class had a trainer-vs-SGLang mismatch (max delta 3.1e-2). Not root-caused, so `SGLangEngine` raises for KDA models with `enable_hierarchical_cache` (47dda9e). - Upstream issues for the workarounds in this stack, linked from their TODOs: - the hybrid pool's `v_head_dim`: sgl-project/sglang#48461; - MLA detection by architecture name: sgl-project/sglang#48462; - `triton.next_power_of_2`: sgl-project/sglang#48460; - the non-overlap requirement of the mamba radix cache: sgl-project/sglang#48463; - Attention Gym's `ReplayState` layout constants: meta-pytorch/attention-gym#692. - KDA at TP > 1 is not covered by this PR's test: the class runs at TP 1, as the vLLM Kimi K3 parity class does. With #5829 (now on main), it passed at TP 2 / EP 2 (4 passed, max delta 0); moving it there is a TODO in the test.
Bottom of the SGLang generator stack; based on main.
Summary (human-written)
The sections below were written by Claude (AI agent).
Problem
TestBitwiseParityQwen35DebugVarlen(RL Multi-GPU Unit Tests) fails on about half ofmain's runs: the trainer's Qwen3.5 GDN prefill and vLLM's differ in the last bits.
In batch-invariant mode, both sides run attn-gym's recurrent GDN scan. In attn-gym
0.0.18, the scan picks its launch config (
BV,num_warps,PREFETCH) from the batchshape, and each config rounds differently:
PREFETCHuses another output formula, andtl.sum's order and FMA fusion follow the thread layout. The trainer scores a sequencein a packed batch, vLLM in its own batch shape, so the bits depend on what else was
batched. meta-pytorch/attention-gym#704 adds an opt-in,
kernel_options={"batch_invariant": True},that uses one formula, fixed-order sums and no FMA fusion for every launch config.
What changed
.ci/docker/requirements.txt(and the rootrequirements.txt, a symlink to it): pinattn-gym at 26beb36, the merge of fix error in #701 #704, with a TODO to pin a release once one includes
it.
models/common/attn_gym.py's install hint andtest_optional_imports.pyfollowthe pin.
models/common/attention/gdn.py: the trainer's recurrent GDN custom op passes theopt-in. Mechanical: it is renamed
_recurrent_gdn_fwd->_batch_invariant_recurrent_gdn_fwd(op
torchtitan::batch_invariant_recurrent_gdn_fwd), since it only runs inbatch-invariant mode, and
test_qwen3_5_deltanet.pyfollows the rename.rl/generator/vllm/attention/gdn.py: vLLM's batch-invariant GDN path (prefill, anddecode, which runs the same scan) passes the opt-in.
Outside batch-invariant mode nothing changes: the chunked GDN kernels and
recurrent_gdn_decodedon't call the scan, and the scan's default arithmetic is 0.0.18's.attn-gym[linear,cudnn]==0.0.18attn-gym[linear,cudnn] @ git+...@26beb36Numerics
Batch-invariant GDN changes by last-bit rounding (the scan's arithmetic is now the
same for every launch config). Training outside batch-invariant mode is unchanged: no
loss or golden change.
Testing
On GB300,
torchrun --nproc-per-node=2 -m pytest tests/rl/unit_tests/gpu/test_bitwise_parity.py::TestBitwiseParityQwen35DebugVarlen, as CI runs it:max_delta=1.73e-03; after reload9.54e-07)tests/unit_tests/gpu/models/qwen3_5/test_qwen3_5_deltanet.py: 9 passed.tests/unit_tests/cpu/models/common/test_optional_imports.py: passes.TestBitwiseParityQwen35DebugVarlenalready covers it, and fails withoutthe fix.
ciflow/dockerlabel to build an image with the new pin.