Skip to content

[rl] generator: SGLang KDA linear attention - #5819

Merged
tianyu-l merged 3 commits into
sglang-6-mlafrom
sglang-7-kda
Nov 10, 2026
Merged

tianyu-l merged 3 commits into
sglang-6-mlafrom
sglang-7-kda

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Stacked on #5818 (SGLang MLA).

Summary (human-written)

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

@tianyu-l
tianyu-l added this pull request to stack #5813 November 4, 2026 19:49
@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 4, 2026
@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 3m 53s —— View job


Approve -- please address the items below before merging: fill in the "Summary (human-written)" section, and link the upstream SGLang issue in the v_head_dim patch TODO. Full review: PR reviews.

@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 follows the GDN path and the vLLM KDA adapter, and the shared code is factored out rather than duplicated. What's left is small: the description, a TODO link, and a few nits.

What this PR does. It runs Kimi K3's KDA layers inside SGLang on SGLang's mamba state pool, using the trainer's Attention Gym kernels. In batch-invariant mode, Attention Gym also needs a per-slot replay state for the unfinished 64-token chunk. SGLang's pool holds only one conv-state list in a single dtype, so the replay tensors become extra conv-list entries, sized in bf16 units and viewed back to their real dtypes in the backend. Two pieces are factored out so both engines and both layer types share them:

  • paged_kda.py, used by the vLLM and SGLang KDA paths;
  • sglang/linear_attention.py, used by SGLang GDN and KDA.

Example. Per-slot state for one KDA layer, head dim 128, H local heads, in batch-invariant mode:

conv  = [history  bf16 [W-1, 3*H*128],
         q, k, v  bf16 [64, H, 128],
         gate     fp32 as bf16 [64, H, 256],
         beta     fp32 as bf16 [64, 2H],
         count    int32 as bf16 [2]]
temporal = fp32 [H, 128, 128]     # 64 KiB*H; the replay entries total ~80 KiB*H (the 1.25x)
Before: replace_sglang_layer_configs raises "softmax attention and GDN only".
After:  decode -> paged_kda(T=1 per row, replay_state=views), bitwise equal to the trainer's chunk kernel.

Must fix

  1. PR description: "Summary (human-written)" is empty. The author needs to fill it in. Smaller point: "renamed to public names" (plural), but only kimi_k3_debug_bitwise_config is renamed; qwen3_5_debug_bitwise_config was already public.
  2. torchtitan/rl/generator/sglang/registry.py:107 -- the TODO for the monkeypatched private KVCacheConfigurator._hybrid_full_attention_pool_class has no upstream issue link (inline).

Should consider

  • torchtitan/rl/generator/sglang/kda.py:104 -- the ValueError can't fire for bf16 or fp32 conv storage; it's an internal invariant, so an assert is enough (inline).
  • tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:435 -- the model.train() comment doesn't say why (inline).
  • tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:31 -- the Dist-MoE note is unrelated to this PR (inline).
Details
  • Moved code (paged_kda, vLLM adapter). The vLLM decode and extend paths are equivalent to before:
    • convolved_BC.unsqueeze(1) followed by chunk(3) and reshape(B, 1, -1, K) gives the same tensors as the old reshape(-1, 1, H, K).
    • kernel_options is still taken from the pre-l2norm query on extend, and is still None on decode.
    • cu_seqlens=None on decode matches the old call, which omitted it.
  • Byte views. Each replay entry is its own pool tensor. The bf16 strides of the non-last dims are even, so view(float32/int32) is legal and 4-byte aligned. This also holds for the (2,)-shaped count entry.
  • SGLang decode vs. vLLM decode. The SGLang KDA decode doesn't pass has_initial_state to causal_conv1d_decode or recurrent_kda_decode, and passes None to paged_kda. That matches the SGLang GDN backend: every decode row follows an extend, and padding rows map to SGLang's null slot.
  • GDN + KDA ban. The ban at registry.py:230 guards a real silent failure: the parser would pick the GDN config, and the KDA layers would have no state slots. Keep it.
  • The v_head_dim patch. It runs once (inside the TORCHTITAN_VARLEN_ATTENTION_BACKEND not in ATTENTION_BACKENDS guard). It is a no-op for non-TorchTitan architectures and when V == K (Qwen3.5 GDN).

Not verified: the pinned SGLang internals this relies on: KimiLinearStateShape.create giving a single [W-1, 3C] conv entry, ModelConfig.v_head_dim, and the private configurator method. The GPU parity results come from the description. This PR only touches the RL generator, but a maintainer still needs to review it.

Comment on lines +107 to +108
TODO: SGLang's HybridLinearKVPool builds its MHATokenToKVPool without
``v_head_dim`` (V rows of K's head dim), though its pool sizing counts it.

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 TODO has no upstream issue link, and it covers a process-global monkeypatch of a private SGLang method (KVCacheConfigurator._hybrid_full_attention_pool_class). CLAUDE.md principle 3 asks for the link. Without one, nothing tells us when the patch can go, and a SGLang bump that renames the method breaks KDA models with an AttributeError at registration. The PR description already lists this as a known follow-up. Please file the SGLang issue (the hybrid pool builds MHATokenToKVPool without v_head_dim even though the pool sizing counts it) and put its URL here before merging.

Comment thread torchtitan/rl/generator/sglang/kda.py Outdated
Comment on lines +104 to +108
if num_bytes % storage_dtype.itemsize != 0:
raise ValueError(
f"KDA replay state of shape {shape} and dtype {dtype} does not fit "
f"{storage_dtype} conv state slots"
)

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 check can't fail for any conv dtype the engine uses. The replay last dims are 128 * 2, 128 * 4, H * 4 and 1 * 4 bytes, and each divides evenly by the itemsize of both bf16 and fp32 storage (conv_state_dtype is precision.param_dtype). So it isn't a user-facing error. It is an internal invariant, so per principle 8 an assert is enough:

Suggested change
if num_bytes % storage_dtype.itemsize != 0:
raise ValueError(
f"KDA replay state of shape {shape} and dtype {dtype} does not fit "
f"{storage_dtype} conv state slots"
)
assert num_bytes % storage_dtype.itemsize == 0, (shape, dtype, storage_dtype)

@classmethod
def setUpClass(cls):
super().setUpClass()
# As test_bitwise_parity's KimiK3BitwiseParityTestBase.

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 comment says the code matches the other base class but not why the trainer reference has to be in training mode for Kimi K3. A reader can't tell whether it matters for parity. A one-line reason would help (or point at the reason in KimiK3BitwiseParityTestBase, whose docstring doesn't give one either).

Comment on lines +31 to +32
environment (see torchtitan/rl/generator/sglang/README.md; the Dist-MoE class also needs
the dist_moe package):

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.

The note that the Dist-MoE class needs the dist_moe package has nothing to do with KDA. If it's needed, it belongs in the Dist-MoE PR or its own docs fix (one concern per PR).

@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 57s —— View job


Approve -- please address the items below before merging: the code nits are fixed. Still open: the empty "Summary (human-written)" section, and the missing upstream SGLang issue link in the v_head_dim patch TODO. Full review: PR reviews.

@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 code nits from the last review are fixed. Two must-fix items are still open: the empty human-written summary, and the missing upstream issue link on the private-API monkeypatch. The new commit adds no new problems.

What changed since the last review (re-reviewed at d1a134f):

  • kda.py _shape_in_dtype -- resolved: the ValueError is now an assert.
  • test_sglang_bitwise_parity.py model.train() -- resolved: the comment now gives the reason (training mode only adds MoE load-balancing statistics).
  • test_sglang_bitwise_parity.py Dist-MoE note -- resolved: this was my mistake. The note is already on the base branch, and this PR only reflows the paragraph around it.

Must fix (still open)

  1. PR description: "Summary (human-written)" still holds only the template placeholder, so the author needs to write it. Smaller point: "renamed to public names" (plural) is inaccurate. Only kimi_k3_debug_bitwise_config is renamed; qwen3_5_debug_bitwise_config was already public.
  2. torchtitan/rl/generator/sglang/registry.py:107 -- the TODO on the monkeypatch of the private KVCacheConfigurator._hybrid_full_attention_pool_class still has no upstream SGLang issue link (CLAUDE.md principle 3). The description still says "not filed yet". Please file the issue and add its URL before merging.
Details
  • Apart from the three fixes above, the diff matches what was reviewed before. The earlier checks still hold:
    • the vLLM decode and extend paths through paged_kda are unchanged in behavior;
    • the byte views of the replay entries are legal;
    • the GDN + KDA ban at registration is kept;
    • the v_head_dim patch does nothing for non-TorchTitan architectures and when V == K.

Not verified: the pinned SGLang internals (KimiLinearStateShape.create conv layout, ModelConfig.v_head_dim, the private configurator method) and the GPU parity results, which come from the description. This PR only touches the RL generator, but a maintainer still needs to review it.

@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 4s —— View job


Approve -- please address the items below before merging: the force-push adds no new problems. Still open: the empty "Summary (human-written)" section, and the missing upstream SGLang issue link in the v_head_dim patch TODO. Full review: PR reviews.

@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 force-pushed commit adds no new problems. The same two must-fix items are still open: the human-written summary and the upstream issue link on the private-API monkeypatch.

What changed since the last review (re-reviewed the full diff at bcd9c1e; the branch was force-pushed, so d1a134f couldn't be diffed directly):

  • Description: "renamed to a public name" is now accurate -- resolved.
  • TestSGLangBitwiseParityKDA now carries TODO(https://github.com/pytorch/torchtitan/pull/5829): run at TP 2 / EP 2 and states it runs on one GPU, which matches the module docstring.
  • paged_kda.py has a TODO about taking the replay layout constants from Attention Gym.
  • The earlier code fixes (assert in _shape_in_dtype, the model.train() reason) are still in place.

Must fix (still open)

  1. PR description: "Summary (human-written)" still holds only the template placeholder. The author needs to write it; agents don't fill it in.
  2. torchtitan/rl/generator/sglang/registry.py:1131 (the _patch_hybrid_full_attention_v_head_dim docstring TODO) still has no upstream SGLang issue link. It covers a process-global monkeypatch of the private KVCacheConfigurator._hybrid_full_attention_pool_class (CLAUDE.md principle 3). Please file the issue and add its URL here.

Should consider

  • torchtitan/rl/generator/paged_kda.py:115 -- the TODO about Attention Gym exposing the ReplayState layout is an upstream gap in a meta-pytorch repo. If you file the same issue batch for (2), add an attention-gym issue link here too, so it's clear when REPLAY_CHUNK_SIZE / REPLAY_STATE_DTYPES can be removed.
Details
  • The rest of the diff behaves as reviewed before:
    • paged_kda keeps the vLLM decode and extend paths equivalent to the old code: the same reshape, kernel_options only on extend, and has_initial_state still forwarded on vLLM decode;
    • the replay byte views are legal;
    • the GDN + KDA ban at registration stays;
    • the v_head_dim patch does nothing for non-TorchTitan architectures and when V == K.

Not verified: the pinned SGLang internals (KimiLinearStateShape.create conv layout, ModelConfig.v_head_dim, the private configurator method) and the GPU parity results, which come from the description. This PR only touches the RL generator, but a maintainer still needs to review it.

@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 2m 10s —— View job


Approve -- please address the items below before merging: the new flat, 16-byte-padded replay entries look correct. Still open: the empty "Summary (human-written)" section and the missing upstream SGLang issue link in the v_head_dim patch TODO. New: the README's claim that KDA is bitwise under HiCache isn't backed by a listed test. Full review: PR reviews.

@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 new commit's flat, 16-byte-padded replay entries look correct. The same two must-fix items are still open: the human-written summary, and the upstream issue link on the private-API monkeypatch.

What changed since the last review (0a93bcb; the branch was force-pushed again and bcd9c1e can't be fetched here, so I re-read the full diff):

  • kda.py now stores each replay tensor as a flat entry of the conv-dtype pool. Each entry is padded to 16 bytes because HiCache copies slot entries in 16-byte words. _unflatten_state_entry views each entry back as [N, *shape] in the tensor's real dtype. This replaces the old last-dim byte resizing and the assert in _shape_in_dtype.
  • The README and the TorchTitanKDAConfig docstring now say that HiCache keeps the replay state in host memory.

Example. Per-slot entries with bf16 conv storage and H local heads:

q, k, v  (64, H, 128) bf16  -> 16384*H bf16 elems   (no padding)
gate     (64, H, 128) fp32  -> 32768*H bf16 elems   (no padding)
beta     (64, H)      fp32  ->   128*H bf16 elems   (no padding)
count    (1,)         int32 -> 4 bytes, padded to 16 -> 8 bf16 elems
view: storage[:, :2].view(int32).unflatten(-1, (1,)) -> [N, 1], slot stride 4

The byte views are legal: each row stride is a multiple of 16 bytes and the last dim is contiguous. Only count ends up with a slot stride larger than its size.

Must fix (still open)

  1. PR description: "Summary (human-written)" still holds only the template placeholder. The author has to write it. Also, "What changed" and the example still describe the replay tensors as sized by the last dim. Please mention the flat entries and the 16-byte HiCache padding.
  2. torchtitan/rl/generator/sglang/registry.py (_patch_hybrid_full_attention_v_head_dim docstring TODO): still no upstream SGLang issue link for the monkeypatch of the private KVCacheConfigurator._hybrid_full_attention_pool_class (CLAUDE.md principle 3).

Should consider

  • torchtitan/rl/generator/sglang/README.md:163 -- the README says KDA prefixes loaded back from HiCache match bitwise, but no listed test backs that claim (inline).
  • torchtitan/rl/generator/paged_kda.py:21 -- still open from last time: add an attention-gym issue link to the ReplayState layout TODO.

Not verified: that Attention Gym's paged_chunk_kda reads the replay count through its slot stride rather than assuming a dense [N] layout (Attention Gym isn't installed here; the vLLM path's page-strided state suggests it does). Also not verified: the pinned SGLang internals and the GPU parity results, which come from the description. This PR only touches the RL generator, but a maintainer still needs to review it.

Comment on lines +163 to +165
host cache too. For GDN and KDA models, it keeps the conv and recurrent states
(and KDA's replay state) of evicted prefixes in host memory too: a cached turn
whose prefix was loaded back matched the trainer's prefill bitwise. It pays off when recomputing a prefix costs more than copying

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 sentence now says that for KDA, a prefix loaded back from HiCache (replay state included) matches the trainer's prefill bitwise. The Testing section of the PR description doesn't list a HiCache run with Kimi K3. The 16-byte padding in kda.py:99-112 was added for HiCache's copy, so this is the path that changed. If you ran it, please add the result to the description. If not, scope the bitwise claim to GDN here, or run it once: a multi-turn Kimi K3 workload with hicache_size set, where the evicted prefixes are loaded back.

@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 7s —— View job


Approve -- please address the items below before merging: both upstream TODO links are fixed. Still open: the empty "Summary (human-written)" section. New: the README says KDA under HiCache is bitwise but doesn't mention the 1-in-18 mismatch reported in the description. Full review: PR reviews.

@tianyu-l
tianyu-l force-pushed the sglang-7-kda branch 2 times, most recently from 5353245 to f8a890b Compare November 8, 2026 22:00
@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 23s —— View job


Approve -- please address the items below before merging: the rebase onto #5963 and the move to attention/ folders add no code problems. Still open: the empty "Summary (human-written)" section. New: the description still uses the old file paths and describes GDN as it was before #5963. Full review: PR reviews.

@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 rebase onto #5963 and the move to attention/ folders add no code problems. The description has to catch up with the new file paths, and the human-written summary is still empty.

What changed since the last review (029c4d6; the branch was force-pushed and rebased, so I re-read the full diff against sglang-6-mla):

  • Your two folder comments are resolved. paged_kda.py is now generator/attention/kda.py, and the SGLang files are under sglang/attention/{gdn,kda,linear_attention}.py. Every importer is updated: the vLLM KDA adapter, the SGLang GDN and KDA backends, and registry.py's lazy imports. Nothing in the repo still imports the old paths.
  • The rebase onto #5963 is consistent. After the refactor, the SGLang GDN extend path still calls the new paged_gdn with the same arguments (convolve_extend returns the same cu_seqlens, state_indices and has_initial_state the inline code computed). The batch-invariant GDN decode from #5963 is base-branch code that this PR only renames (linear_attention_weights, SGLangRadixLinearAttention).
  • KDA still needs the replay state after #5963. The trainer's KDA still runs the chunk kernel in batch-invariant mode, and only GDN switched to the sequential scan (models/common/attention/gdn.py:331). Attention Gym has no batch-invariant KDA scan here.
  • CI: TestSGLangBitwiseParityKDA now runs in the B200 SGLang step, in the one-process loop next to MLA, which matches its SM90+ skip and TP 1 config.
  • The rest matches the last review: the 16-byte-padded flat replay entries, the GDN + KDA ban, the v_head_dim patch (sgl-project/sglang#48461), the ReplayState TODO (meta-pytorch/attention-gym#692), and the HiCache write_through README caveat.

Must fix

  1. PR description:
    • "Summary (human-written)" still holds only the template placeholder. The author has to write it; agents don't fill it in.
    • "What changed" still lists sglang/kda.py, sglang/linear_attention.py and paged_kda.py. They are now sglang/attention/kda.py, sglang/attention/linear_attention.py and generator/attention/kda.py. The commit message uses the old names too.
    • "Why" says KDA "runs like GDN (#5817), with one addition". Since #5963, batch-invariant GDN runs a sequential scan with no replay state. Please say that KDA keeps the chunk kernel plus replay because the trainer's KDA does.

Not verified: the GPU results, which come from the description. The B200 CI run for 029c4d6, including the new KDA class, was still queued when I reviewed. This PR only touches the RL generator, but a maintainer still needs to review it.

@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. Code changed since your last review (see the replies on your inline comments); 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 1m 57s —— View job


Approve -- please address the items below before merging: the description now matches the code. Still open: the empty "Summary (human-written)" section. New: the KDA test's TP 1 TODO lost its reason now that #5829 has landed. Full review: PR reviews.

@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 description now matches the code. The human-written summary is still empty, and the rebase leaves the KDA class's TP 1 TODO without its reason.

What changed since the last review (4842a25; the branch was force-pushed and 029c4d6 can't be fetched here, so I re-read the full diff against sglang-6-mla):

  • Description -- resolved. "What changed" uses the attention/ paths. "Why" now says that since #5963, GDN runs a sequential scan, while KDA keeps the chunk kernel plus replay state because the trainer's KDA does.
  • The rebase changed the base: TestSGLangBitwiseParityMLA now runs at TP 2 / EP 2, so TestSGLangBitwiseParityKDA is the only one-process class. The module docstring and CI were updated to match: KDA now runs in its own --nproc-per-node=1 loop.
  • The KDA class TODO lost its #5829 link. #5829 is on main now, so the TODO no longer says what it waits for (inline).
  • The code is unchanged in substance from the last review:

Example. The coverage gap the TODO leaves:

TP 1 (this class):  replay entries sized with kda_num_heads // 1, read back via temporal.shape[1]
TP 2 (not in CI):   kda_num_heads // 2 per rank -- reported passing in the description, but not run in CI
MLA class:          already TP 2 / EP 2 via _debug_model_config, cuda_graph="none"

Must fix

  1. PR description: "Summary (human-written)" still holds only the template placeholder. The author has to write it; agents don't fill it in.

Should consider

  • tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:462 -- the TODO has no reason now that #5829 has landed. Either move the class to TP 2 / EP 2, or say why it stays at TP 1 (TP 2 needs EP, which forces cuda_graph="none") (inline).
  • Commit message: it still names sglang/kda.py, sglang/linear_attention.py and paged_kda.py, and describes GDN as it was before #5963. Please update it if the squash commit reuses it.

Not verified: the GPU results, which come from the description. This PR only touches the RL generator, but a maintainer still needs to review it.

replay state of each slot's unfinished 64-token chunk, and MLA. One GPU, as
test_bitwise_parity's vLLM Kimi K3 class.

TODO: run at TP 2 / EP 2, as the MLA class does.

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 TODO used to wait on #5829. That PR is on main now, the MLA class in this file already runs at TP 2 / EP 2 through _debug_model_config, and the description says this class passed at TP 2 / EP 2 (4 passed, delta 0). So the TODO no longer says what it is waiting for.

What TP 1 leaves untested: the TP-sharded replay state. TorchTitanKDAConfig.mamba2_cache_params sizes the replay entries with kda_num_heads // tp_size, and _state reads the local head count back from temporal.shape[1]. At TP 1 both are the global head count, so a mismatch between them can't show up. The one-process CI loop and the "one for TestSGLangBitwiseParityKDA" exception in the module docstring exist only because of this class.

The cost of moving: Kimi K3 at TP 2 needs EP, and the all-to-all dispatcher forces cuda_graph = "none" (as in the MLA class). That would drop the CUDA-graph coverage this class has now for KDA decode with replay views.

Pick one of these:

  • Move the class to functools.partial(_debug_model_config, <kimi_k3 build_model_config>, expert_parallel_degree=2) with cuda_graph = "none", add KDA to the two-process CI loop, and drop the one-process loop.
  • Keep TP 1 and write the reason in the TODO, e.g. "TP 2 needs EP, whose all-to-all disables CUDA graphs; this class covers the breakable-graph KDA decode."

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] Kept TP 1 and wrote the reason in the TODO (8745863): TP 2 needs EP, whose all-to-all rules out CUDA graphs, and this class covers KDA decode with replay state in CUDA graphs. The commit message now uses the current file paths.

@felipemello1

Copy link
Copy Markdown
Contributor

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

In batch-invariant mode, KDA's replay state for the unfinished chunk (q, k, v, gate, beta, count) is stored as extra bf16 conv entries in SGLang's state slot, 321 KiB next to the 256 KiB recurrent state (1.25x), so the radix cache keeps it too.

Comment on lines +99 to +100
# SGLang's HiCache copies each slot's state entries in 16-byte words.
_STATE_ENTRY_ALIGNMENT_BYTES = 16

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.

should we import this in case they change this number?

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 is not importable: the 16 lives only in SGLang's CUDA source (kBytesPerThreadPerStep in kernels/jit/csrc/kvcacheio/transfer_mamba.cuh), and no Python module exports it. If SGLang changes it, its own entry-size check there fails at the first host copy. The comment now names it (e9bef37).

Comment on lines +91 to +94
# object.__setattr__: nn.Module would register the parameters as the layer's.
object.__setattr__(layer, "conv_weights", conv_weights)
object.__setattr__(layer, "A_log", A_log)
object.__setattr__(layer, "dt_bias", dt_bias)

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 this the best way of doing 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] I think so. SGLang's linear attention backends read the weights from RadixLinearAttention attributes (layer.conv_weights, layer.A_log). SGLang's own models set them once at construction, but here the outer GDN/KDA module passes them to the inner attention on each call, so the inner attention sets them per call: 3 attribute writes per layer per step. object.__setattr__ is needed because RadixLinearAttention.__init__ already stores them as plain attributes (e.g. A_log=None). Setting them once in the wrapper would put GDN/KDA parameter names into it.

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

KDA + HiCache is only a README TODO, but SGLang's defaults reach the setup that mismatched the trainer.

One inline comment (README.md:171-172). HiCache = SGLang's hierarchical cache (enable_hierarchical_cache).

  1. KDA + HiCache is a README TODO.
  2. But SGLang's default write policy is the one that mismatched.
  3. So enable_hierarchical_cache=True alone reaches it.

Comment on lines +171 to +172
TODO: with HiCache's `write_through` policy, one run in 18 of the KDA parity
class mismatched the trainer (max logprob delta 3.1e-2); not root-caused.

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

Turning on HiCache alone gives the KDA setup that mismatched the trainer, and nothing stops it.

HiCache = SGLang's hierarchical cache (enable_hierarchical_cache).

Problem

  1. write_through is SGLang's default hicache_write_policy (srt/arg_groups/fields/memory.py:123-129).
  2. So extra_server_args={"enable_hierarchical_cache": True} alone gives the setup that mismatched the trainer: 1 of 18 runs, max delta 3.1e-2.
  3. Nothing stops it.

The cause is not isolated yet

  • The PR body's 8 clean runs without HiCache cannot rule out a 1-in-18 flake.
  • Why: (17/18)^8 = 0.63. That is the chance that all 8 runs pass even if each run fails 1 time in 18.
  • No KDA run with write_back is reported. So the README example's policy is untested too.

Smallest fix
Raise ValueError for models with KDA layers when enable_hierarchical_cache is set, until the mismatch is root-caused.

How to find the cause

  1. Start cheap: count host evictions and restores in the failing setup.
    • That shows whether a host restore happened.
    • It does not show whether HiCache is involved, because write_through also copies inserts to host memory with zero evictions.
  2. Rule out a 1-in-18 flake that also happens without HiCache. That takes about 53 clean runs without HiCache:
    • Assume each run independently fails with probability 1/18.
    • Then the chance that all 53 runs pass is 4.8%.
    • For 18 runs, it is 36%.

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. SGLangEngine now raises for KDA models with enable_hierarchical_cache until the mismatch is root-caused (e9bef37). The README says so.

if config.extra_server_args.get("enable_hierarchical_cache") and any(
isinstance(layer.attention, KDA.Config) for layer in model.layers
):
# TODO: with HiCache's default write_through policy, one run in 18 of

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

can you also test if GDN has the same issue? and maybe create an issue in titan to track this investigation.

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] Tested GDN with HiCache write_through: 23 of 23 runs of TestSGLangBitwiseParityGDN were bitwise identical to the trainer, so GDN stays allowed with HiCache. The KDA failure (1 in 18) is tracked in #6015; the TODO here now links it (47c8d29), and the KDA guard stays until it is root-caused.

KDA layers (Kimi K3) run on SGLang's mamba state pool with the trainer's
Attention Gym kernels, as GDN layers do.

- sglang/attention/kda.py: TorchTitanKDAConfig (Attention Gym's [W - 1, C] conv
  layout, float32 recurrent state), TorchTitanKDAAttnBackend and
  SGLangInnerKDA. In batch-invariant mode, each slot also holds Attention
  Gym's replay state of its unfinished 64-token chunk, as extra entries
  of SGLang's conv state list, sized in bytes and viewed as their dtypes;
  SGLang clears and copies every entry with the slot, so its radix cache
  snapshots the replay state with the recurrent state.
- sglang/attention/linear_attention.py: what GDN and KDA share inside SGLang (HF
  config base, RadixLinearAttention module, weight hand-off and padding
  rows, extend-path convolution), moved out of gdn.py.
- registry.py: registers the KDA backend; computes and validates the
  GDN/KDA config fields at registration through one shared helper, and
  rejects models with both. Patches SGLang's hybrid KV pool, which drops v_head_dim,
  for TorchTitan models (Kimi K3's MLA has V head dim 128, K 192) (TODO).
- engine.py, README.md: GDN and KDA models step the normal event loop.
- generator/attention/kda.py: the KDA recurrence over a paged state pool, moved from
  the vLLM adapter and shared by both engines (mechanical).
- test_sglang_bitwise_parity.py: Kimi K3 debug at TP 1 (KDA and MLA),
  reusing test_bitwise_parity's Kimi K3 config, now public.
- SGLangEngine raises for KDA models with SGLang's hierarchical cache: with
  its default write_through policy, one run in 18 of the KDA parity class
  mismatched the trainer, and the cause is not found.
- The HiCache state-entry alignment comment names the CUDA constant it
  mirrors; SGLang does not export it to Python.
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/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