Repository navigation
[rl] generator: SGLang KDA linear attention - #5819
Conversation
|
@claude review |
|
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 |
There was a problem hiding this comment.
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
- 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_configis renamed;qwen3_5_debug_bitwise_configwas already public. torchtitan/rl/generator/sglang/registry.py:107-- the TODO for the monkeypatched privateKVCacheConfigurator._hybrid_full_attention_pool_classhas no upstream issue link (inline).
Should consider
torchtitan/rl/generator/sglang/kda.py:104-- theValueErrorcan't fire for bf16 or fp32 conv storage; it's an internal invariant, so anassertis enough (inline).tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:435-- themodel.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 bychunk(3)andreshape(B, 1, -1, K)gives the same tensors as the oldreshape(-1, 1, H, K).kernel_optionsis still taken from the pre-l2norm query on extend, and is stillNoneon decode.cu_seqlens=Noneon 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_statetocausal_conv1d_decodeorrecurrent_kda_decode, and passesNonetopaged_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:230guards 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_BACKENDSguard). 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.
| TODO: SGLang's HybridLinearKVPool builds its MHATokenToKVPool without | ||
| ``v_head_dim`` (V rows of K's head dim), though its pool sizing counts it. |
There was a problem hiding this comment.
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.
| 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" | ||
| ) |
There was a problem hiding this comment.
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:
| 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. |
There was a problem hiding this comment.
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).
| environment (see torchtitan/rl/generator/sglang/README.md; the Dist-MoE class also needs | ||
| the dist_moe package): |
There was a problem hiding this comment.
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).
d02b189 to
d1a134f
Compare
|
@claude review again |
|
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 |
There was a problem hiding this comment.
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: theValueErroris now anassert.test_sglang_bitwise_parity.pymodel.train()-- resolved: the comment now gives the reason (training mode only adds MoE load-balancing statistics).test_sglang_bitwise_parity.pyDist-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)
- 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_configis renamed;qwen3_5_debug_bitwise_configwas already public. torchtitan/rl/generator/sglang/registry.py:107-- the TODO on the monkeypatch of the privateKVCacheConfigurator._hybrid_full_attention_pool_classstill 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_kdaare unchanged in behavior; - the byte views of the replay entries are legal;
- the GDN + KDA ban at registration is kept;
- the
v_head_dimpatch does nothing for non-TorchTitan architectures and when V == K.
- the vLLM decode and extend paths through
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.
d1a134f to
96b0e3d
Compare
96b0e3d to
bcd9c1e
Compare
|
@claude review again |
|
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 |
There was a problem hiding this comment.
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.
TestSGLangBitwiseParityKDAnow carriesTODO(https://github.com/pytorch/torchtitan/pull/5829): run at TP 2 / EP 2and states it runs on one GPU, which matches the module docstring.paged_kda.pyhas a TODO about taking the replay layout constants from Attention Gym.- The earlier code fixes (
assertin_shape_in_dtype, themodel.train()reason) are still in place.
Must fix (still open)
- PR description: "Summary (human-written)" still holds only the template placeholder. The author needs to write it; agents don't fill it in.
torchtitan/rl/generator/sglang/registry.py:1131(the_patch_hybrid_full_attention_v_head_dimdocstring TODO) still has no upstream SGLang issue link. It covers a process-global monkeypatch of the privateKVCacheConfigurator._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 theReplayStatelayout 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 whenREPLAY_CHUNK_SIZE/REPLAY_STATE_DTYPEScan be removed.
Details
- The rest of the diff behaves as reviewed before:
paged_kdakeeps the vLLM decode and extend paths equivalent to the old code: the same reshape,kernel_optionsonly on extend, andhas_initial_statestill forwarded on vLLM decode;- the replay byte views are legal;
- the GDN + KDA ban at registration stays;
- the
v_head_dimpatch 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.
bcd9c1e to
0a93bcb
Compare
|
@claude review again |
|
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 |
There was a problem hiding this comment.
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.pynow 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_entryviews each entry back as[N, *shape]in the tensor's real dtype. This replaces the old last-dim byte resizing and theassertin_shape_in_dtype.- The README and the
TorchTitanKDAConfigdocstring 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)
- 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.
torchtitan/rl/generator/sglang/registry.py(_patch_hybrid_full_attention_v_head_dimdocstring TODO): still no upstream SGLang issue link for the monkeypatch of the privateKVCacheConfigurator._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 theReplayStatelayout 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.
| 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 |
There was a problem hiding this comment.
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.
0a93bcb to
6f466ac
Compare
|
@claude review again |
|
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. |
31a954f to
3e390cc
Compare
5353245 to
f8a890b
Compare
f8a890b to
50e61f3
Compare
50e61f3 to
029c4d6
Compare
|
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 |
There was a problem hiding this comment.
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.pyis nowgenerator/attention/kda.py, and the SGLang files are undersglang/attention/{gdn,kda,linear_attention}.py. Every importer is updated: the vLLM KDA adapter, the SGLang GDN and KDA backends, andregistry.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_gdnwith the same arguments (convolve_extendreturns the samecu_seqlens,state_indicesandhas_initial_statethe 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:
TestSGLangBitwiseParityKDAnow 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_dimpatch (sgl-project/sglang#48461), theReplayStateTODO (meta-pytorch/attention-gym#692), and the HiCachewrite_throughREADME caveat.
Must fix
- 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.pyandpaged_kda.py. They are nowsglang/attention/kda.py,sglang/attention/linear_attention.pyandgenerator/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.
029c4d6 to
30e4ceb
Compare
|
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. |
There was a problem hiding this comment.
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:
TestSGLangBitwiseParityMLAnow runs at TP 2 / EP 2, soTestSGLangBitwiseParityKDAis the only one-process class. The module docstring and CI were updated to match: KDA now runs in its own--nproc-per-node=1loop. - 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:
- the 16-byte-padded flat replay entries;
- the GDN + KDA ban;
- the
v_head_dimpatch (sgl-project/sglang#48461); - the
ReplayStateTODO (meta-pytorch/attention-gym#692); - the HiCache
write_throughREADME caveat; paged_kda's vLLM decode/extend equivalence.
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
- 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 forcescuda_graph="none") (inline).- Commit message: it still names
sglang/kda.py,sglang/linear_attention.pyandpaged_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. |
There was a problem hiding this comment.
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)withcuda_graph = "none", addKDAto 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."
There was a problem hiding this comment.
| # SGLang's HiCache copies each slot's state entries in 16-byte words. | ||
| _STATE_ENTRY_ALIGNMENT_BYTES = 16 |
There was a problem hiding this comment.
should we import this in case they change this number?
There was a problem hiding this comment.
[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).
| # 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) |
There was a problem hiding this comment.
is this the best way of doing it?
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
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).
- KDA + HiCache is a README TODO.
- But SGLang's default write policy is the one that mismatched.
- So
enable_hierarchical_cache=Truealone reaches it.
| 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. |
There was a problem hiding this comment.
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
write_throughis SGLang's defaulthicache_write_policy(srt/arg_groups/fields/memory.py:123-129).- 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. - 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_backis 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
- 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_throughalso copies inserts to host memory with zero evictions.
- 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%.
| 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 |
There was a problem hiding this comment.
can you also test if GDN has the same issue? and maybe create an issue in titan to track this investigation.
There was a problem hiding this comment.
[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.

Stacked on #5818 (SGLang MLA).
Summary (human-written)
Why
SGLangEngineraises 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.
What changed
sglang/attention/kda.py(new):TorchTitanKDAConfig(state slot shapes; inbatch-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 backas 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, theRadixLinearAttentionmodule, theweight hand-off and padding rows, and the extend-path convolution.
sglang/registry.py:its full-attention KV pool without
v_head_dim, though it counts it whensizing. 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 thevLLM adapter and shared by both engines. Mechanical.
sglang/engine.py: docstring only.test_bitwise_parity's Kimi K3 config, renamed to a publicname.
TestSGLangBitwiseParityKDA, in a one-processlaunch.
User-facing changes
Numerics
TestSGLangBitwiseParityKDA(Kimi K3 debug: KDA + MLA, TP 1), incl. the next-turn testTestBitwiseParityKimiK3DebugVarlen(covers the moved paged KDA)write_through, small GPU pools): cached turn whose prefix was evicted to host memory and loaded back (local script)TestSGLangBitwiseParityKDAwith HiCachewrite_through, 18 runs (local)Testing
shared code.
reset_kv_cache_on_model_state_dict_load=True(the Kimi K3 batch-invariantrecipe's setting), Qwen3.5 and Kimi K3. Checked with a local script:
flushes their states and recomputes them. Tokens and logprobs are identical to
a run without a reload (5 of 5 sequences each, delta 0).
pytest tests/rl/unit_tests/cpu: 546 passed.Known issues / follow-ups
write_through(SGLang's default policy), one run in 18 of the KDAparity class had a trainer-vs-SGLang mismatch (max delta 3.1e-2). Not
root-caused, so
SGLangEngineraises for KDA models withenable_hierarchical_cache(47dda9e).v_head_dim:HybridLinearKVPoolignoresv_head_dimfor the full-attention MHA pool (hybrid linear-attention models with V head dim != K head dim) sgl-project/sglang#48461;triton.next_power_of_2: Importing sglang replacestriton.next_power_of_2with a host-only function, breaking other Triton kernels in the process sgl-project/sglang#48460;ReplayStatelayout constants: Expose a constructor (or shape/dtype constants) forReplayStateused by replay-backed paged KDA meta-pytorch/attention-gym#692.Kimi K3 parity class does. With [moe] batch-invariant shared/routed combine under TP #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.