Repository navigation
[rl] generator: SGLang MLA with per-head KV cache - #5818
Conversation
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The change copies the vLLM engine's batch-invariant MLA design (keep MLA's projection, cache per-head K/V with a separate V head dim). It stays inside the SGLang generator package and deletes a raise instead of adding a new path.
What this PR does. In the SGLang generator, an MLA layer's MLAAttention wrapper stays in place. Its inner varlen attention is replaced with SGLangInnerAttention, which now takes a value_head_dim. The HF-shaped config passes v_head_dim to SGLang so that its KV pool sizes V rows separately from K rows. The value_head_dim != head_dim raise is gone; only MLA reaches it, since get_attention_dimensions returns equal dims for every other model.
Example.
DeepSeek V3 debug, layer i: H heads, qk_nope=128, qk_rope=64, v=128
before: replace_sglang_layer_configs -> ValueError (inner is MLAAttention.Config, not varlen)
after: MLAAttention(wkv_b) -> materialize_mla_kv -> SGLangInnerAttention
k_THK: (T, H, 192), contiguous (torch.cat) -> cached as is
v_THV: (T, H, 128), stride (.., 256, 1) -> copied to flat rows, cached
out: (T, H * 128).view(T, -1, value_head_dim=128)
Must fix
- The PR description's "Summary (human-written)" section is empty. Please fill it in.
tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:403-- the trainer bug where the MoE at EP 2 isn't length-invariant needs an issue and aTODO(<link>). Until it's fixed, nothing tests MLA's TP-sharded path (inline).
Should consider
torchtitan/rl/generator/sglang/attention.py:261--_flat_rowson K never copies for any current model, so only V needs it. Consider matching vLLM'svalue_head_dim != head_dimcondition (inline).- The description says SGLang "raises for MLA (DeepSeek V3, Kimi K3)". Kimi K3 still raises after this PR because of its KDA layers (
kimi_k3/flavors.py:318). Kimi K2.7 is the other MLA model that this PR enables. Consider stating that, and listing K2.7 next to DeepSeek V3 in the README row if it was checked.
Details
- Gate. The problem is real: MLA models raise in
replace_sglang_layer_configs. The design matches the vLLM path (vllm/model_wrapper.py, theelsebranch whereis_mlarewrapsMLAAttention.Config). The compressed-latent cache is a TODO, as the vLLM batch-invariant path also skips it. No core code is touched. - TP.
SGLangInnerAttentionsplitsnum_headsandnum_kv_headsbytp_size. For MLA,num_kv_heads == n_heads, so the local head counts matchwkv_b's column-sharded head split. That is consistent by inspection, but only the TP 1 parity class runs (see must-fix 2). - CUDA graphs / perf. The V copy is a device op with a static shape, so it can be captured. It costs one extra (T, H, V) buffer per MLA layer per step, the same as on the vLLM side.
- Registry.
v_head_dimis read from the first full-attention layer only. That is fine for models whose layers all share the same dims, which covers every MLA model that reaches this path.
Not verified: that SGLang's MHA KV store needs flat (T, H * D) rows (SGLang isn't installed in this runner); the GB300 parity result is taken from the description.
| out = self.radix_attention( | ||
| q_THK[:num_tokens], k_THK[:num_tokens], v_THV[:num_tokens], forward_batch | ||
| q_THK[:num_tokens], | ||
| _flat_rows(k_THK[:num_tokens]), |
There was a problem hiding this comment.
_flat_rows on K never copies for any model we have. MLA's K comes from torch.cat in materialize_mla_kv, so it is contiguous, and the fused-QKV K is a head split with stride(-2) == K. The call is a "just in case" conversion (CLAUDE.md principle 8). Only V needs it. Suggest calling it on V only, or mirroring the sibling vLLM adapter (vllm/attention/attention.py:405-409: if self.value_head_dim != self.head_dim: v_THV = v_THV.contiguous()) so both engines handle MLA's strided V the same way.
| _flat_rows(k_THK[:num_tokens]), | |
| k_THK[:num_tokens], |
| """DeepSeek V3 debug model with random weights: MLA, whose per-head K/V SGLang | ||
| caches. One GPU: TP 2 needs EP 2 for its MoE, which is not length-invariant in the | ||
| trainer at EP 2.""" |
There was a problem hiding this comment.
This describes a real trainer bug: DeepSeek V3's MoE at EP 2 isn't length-invariant (prompt logprobs move by 3.8e-3 when 2 tokens are appended, first at layers.1.feed_forward). That is a silent numerics issue outside SGLang, and right now the only record of it is this docstring and the PR description. Please file an issue and make this a TODO(<issue link>): once it's fixed, move this class to TP 2 so it covers the sharded MLA path (num_heads // tp_size on wkv_b's per-head split), which nothing tests today.
8fce9ea to
fc312b3
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. Since the last review, _flat_rows was replaced by vLLM's value_head_dim != head_dim condition (V-only copy) and the README row now lists only DeepSeek V3. The open items are all edits to the description or a TODO.
What changed since the last review. SGLangInnerAttention.forward (attention.py:251-255) no longer runs a contiguity check on K and V. It copies V only when the V head dim differs from the K head dim, as vllm/attention/attention.py:405 does. For MLA, K comes from torch.cat in materialize_mla_kv (mla.py:48), so it is already contiguous and the change is safe. The fused-QKV path (equal dims) passes V through untouched, the same as on the base branch.
Example.
DeepSeek V3 debug, H heads, K = 192, V = 128
v_THV = split(kv_THP, [128, 128])[1] -> stride (.., 256, 1), not flat
value_head_dim (128) != head_dim (192) -> v_THV.contiguous() -> SGLang KV pool
Llama/Qwen fused QKV: value_head_dim == head_dim -> no copy (unchanged from base)
Resolved
attention.py: the K-side_flat_rowscall is gone, and the condition now matches the vLLM adapter.README.md:89: the row now says DeepSeek V3 only (no Kimi K3).
Must fix
- PR description. The "Summary (human-written)" section is still empty. Two other parts describe code that no longer exists: "What changed" says
SGLangInnerAttention"copies K/V only when their rows can't be viewed flat", and "Testing" says the sliding-window class "covers the conditional K/V copy for fused-QKV views". The code now copies V only when the head dims differ, and the sliding-window class never hits that copy. "Why" and the commit message still say SGLang raises for "DeepSeek V3, Kimi K3", but Kimi K3 still raises on its KDA layers (kimi_k3/flavors.py:318); Kimi K2.7 is the other MLA model this enables. Please update those lines and fill in the summary. tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:404-- still open. The trainer's MoE is not length-invariant at EP 2, which is a silent numerics bug. It still has no issue and noTODO(<link>), and until it's fixed nothing tests MLA's TP-sharded path. Please file the issue and add the TODO to this docstring.
Not verified: SGLang's KV pool needing flat V rows, and the GB300 parity result (both taken from the description; SGLang isn't installed in this runner).
fc312b3 to
c74a5c4
Compare
c74a5c4 to
fe4f5d6
Compare
fe4f5d6 to
c982a24
Compare
c982a24 to
c46c9af
Compare
|
@claude review again |
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The code-side items from the last review are fixed. Only the human-written summary is still missing.
What changed since the last review. The MLA parity class now runs at TP 1 through a new tensor_parallel_degree argument on _debug_model_config (default 2, so the existing classes are unchanged). Its docstring has a TODO(#5829) to move it to TP 2 / EP 2 once the trainer's shared-expert MoE is batch-invariant. The module docstring now explains that each class launches with as many processes as its TP degree. The description and commit message now say Kimi K3 also needs KDA (#5819), and they describe the V-only copy that the code actually does.
Example.
TestSGLangBitwiseParityMLA: torchrun --nproc_per_node=1 ... (trainer TP 1, EP 1; generator TP 1)
other classes: torchrun --nproc_per_node=2 ... (_debug_model_config default TP 2, unchanged)
TP 2 / EP 2 for MLA: blocked on #5829 (shared-expert MoE + TP reduce order), see TODO
Resolved
tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:408-- the EP 2 trainer bug now has aTODOlinking #5829, which fixes it.- Description and commit message: they now match the V-only copy and no longer claim that Kimi K3 is enabled.
Must fix
- PR description. "Summary (human-written)" still has only the template placeholder. Please write it yourself.
Not verified: the TP 1 GB300 parity result and SGLang's flat-V-row requirement. Both come from the description, since SGLang isn't installed in this runner.
c46c9af to
0f2d38a
Compare
0f2d38a to
b0e1e80
Compare
b0e1e80 to
930a57c
Compare
|
@claude review again |
c6082a3 to
6316c05
Compare
6316c05 to
e9b635c
Compare
4ae580c to
807b921
Compare
807b921 to
4567730
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The rebase left this PR's own diff unchanged. But #5829 has now landed on the branch, so the MLA parity class's TODO can be done: run it at TP 2 / EP 2.
What changed since the last review. The diff against sglang-5-gdn is the same as at the last approval: the MLA rewrap in _replace_sglang_layer_configs, value_head_dim on SGLangInnerAttention with the V-only copy, v_head_dim in the HF-shaped config, and the TP 1 parity class. The new base doesn't affect it. materialize_mla_kv (mla.py:38) still returns a contiguous K from torch.cat and a strided V from torch.split. get_attention_dimensions (rl/generator/model.py:39) still returns MLA's separate V head dim. #5963 touches only GDN. One thing is new on the rebased branch: #5829 merged on 2026-11-05, and its batch-invariant shared/routed MoE combine is on this branch (moe.py:857).
Example.
before rebase: TestSGLangBitwiseParityMLA at TP 1 (EP 2 trainer MoE not batch-invariant)
now: #5829 is in the base -> TP 2 / EP 2 is unblocked
(description: "4 passed, max delta 0" at TP 2 / EP 2 with #5829)
-> covers wkv_b's column-sharded heads vs num_heads // tp_size in SGLangInnerAttention
Must fix
- PR description. "Summary (human-written)" still has only the template placeholder (still open). Please write it yourself. Also update the "Numerics", "CI", and "Known issues" lines once the class runs at TP 2 / EP 2.
tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:441-- theTODO(#5829)is now actionable. Move the class to TP 2 / EP 2 through anexpert_parallel_degreekwarg on_debug_model_configinstead oftensor_parallel_degree, and revert the docstring edits about per-class process counts (inline)..github/workflows/integration_test_rl_b200.yaml:128-- after that change, add MLA to the existing two-process loop and delete the one-process loop (inline).
Not verified: the TP 2 / EP 2 GB300 result (from the description) and SGLang's flat-V-row requirement. SGLang isn't installed in this runner.
| class TestSGLangBitwiseParityMLA(SGLangBitwiseParityTestBase): | ||
| """DeepSeek V3 debug model with random weights: MLA, whose per-head K/V SGLang | ||
| caches. One GPU: TP 2 needs EP 2 for its MoE, where the trainer's MoE with shared | ||
| experts is not batch-invariant. | ||
|
|
||
| TODO(https://github.com/pytorch/torchtitan/pull/5829): run at TP 2 / EP 2, which | ||
| covers MLA's head-sharded path. | ||
| """ | ||
|
|
||
| __test__ = True | ||
| config_fn = staticmethod( | ||
| functools.partial( | ||
| _debug_model_config, | ||
| build_deepseek_v3_model_config, | ||
| tensor_parallel_degree=1, | ||
| ) | ||
| ) | ||
| sync_weights_from_trainer = True |
There was a problem hiding this comment.
This TODO can be done now. #5829 merged on 2026-11-05, and its fix is on this branch (moe.py:857, tp_routed_reduction). The description already says this class passes at TP 2 / EP 2 with #5829 and that it "moves to TP 2 once #5829 lands". At TP 1, nothing tests MLA's head-sharded path (num_heads // tp_size against wkv_b's column-sharded heads), which is the part of this PR most likely to break silently.
Smallest change: in _debug_model_config, replace the new tensor_parallel_degree kwarg with expert_parallel_degree: int = 1, and pass it to both the trainer's expert_parallel_degree and InferenceParallelismConfig(tensor_parallel_degree=2, expert_parallel_degree=...), as _qwen3_moe_debug_tp2_ep2_config does. Then this class becomes:
class TestSGLangBitwiseParityMLA(SGLangBitwiseParityTestBase):
"""DeepSeek V3 debug model with random weights: MLA, whose per-head K/V SGLang
caches, with EP 2 over TP 2."""
__test__ = True
config_fn = staticmethod(
functools.partial(
_debug_model_config,
build_deepseek_v3_model_config,
expert_parallel_degree=2,
)
)
sync_weights_from_trainer = TrueAlso revert the module-docstring and pytestmark comment edits about per-class process counts, since every class is back to two processes. The CI change is in the comment on the workflow file.
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Done in 5e94cfe: _debug_model_config takes expert_parallel_degree, the MLA class runs at TP 2 / EP 2, and the docstring edits are reverted. One addition: at EP 2 the debug recipe's all-to-all dispatcher syncs the host, so the class sets cuda_graph = "none", as MoEEP does. 4 passed, max delta 0, on 2x GB300.
4567730 to
80853c2
Compare
80853c2 to
5e94cfe
Compare
There was a problem hiding this comment.
Verdict: Approve -- please address the item below before merging. The MLA parity class now runs at TP 2 / EP 2, which tests MLA's head-sharded path. The only open item is the human-written summary.
What changed since the last review. _debug_model_config (test_sglang_bitwise_parity.py:382) no longer takes tensor_parallel_degree. It takes a keyword-only expert_parallel_degree: int = 1 and passes it to both the trainer parallelism and InferenceParallelismConfig(tensor_parallel_degree=2, ...). That matches _qwen3_moe_debug_tp2_ep2_config (:343). The default of 1 keeps the SlidingWindow class unchanged. TestSGLangBitwiseParityMLA (:434) uses expert_parallel_degree=2 and sets cuda_graph = "none" with the same reason given in MoEEP (:369-370). The module docstring and pytestmark edits about per-class process counts are reverted. The module docstring says --nproc_per_node=2 again (:36). In CI, MLA joins the existing two-process loop (integration_test_rl_b200.yaml:123), and the one-process loop is gone. The rebase left the engine-side diff (attention.py, model_wrapper.py, registry.py, README) the same.
Example.
before: TestSGLangBitwiseParityMLA torchrun --nproc-per-node=1 (trainer TP 1, generator TP 1)
after: for test_class in MoEEP GDN SlidingWindow MLA DistMoE -> --nproc-per-node=2
trainer: TP 2, EP 2 (DeepSeek V3 debug, wkv_b column-sharded by head)
generator: TP 2, EP 2 -> SGLangInnerAttention num_heads // 2, K 192 / V 128
cuda_graph="none" (all-to-all dispatcher syncs the host, as in MoEEP)
Resolved
tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:434-- the class runs at TP 2 / EP 2, and theTODO(#5829)is removed..github/workflows/integration_test_rl_b200.yaml:123-- MLA is in the two-process loop, and the one-process loop is deleted.- Description: "Numerics", "What changed", and "CI" now describe TP 2 / EP 2.
Must fix
- PR description. "Summary (human-written)" still holds only the template placeholder (still open). Please write it yourself.
Not verified: the TP 2 / EP 2 GB300 result ("4 passed, max delta 0", from the author's reply) and SGLang's flat-V-row requirement. SGLang isn't installed in this runner.
felipemello1
left a comment
There was a problem hiding this comment.
not super happy with it. Not to the point of blocking the pr. But i would have the agent double check the changes and best practices here.
| head_dim: int | ||
| """The query/key head dim.""" | ||
| value_head_dim: int |
There was a problem hiding this comment.
can we add a docstring for both, to distinguish their differnece
| out = out.view(num_tokens, -1, self.head_dim) | ||
| out = out.view(num_tokens, -1, self.value_head_dim) |
There was a problem hiding this comment.
hmmmm, is this change ok? I imagine that both values are usually the same, unless they are different, in which case we prefer to keep the value_head_dim?
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] The change is needed. RadixAttention returns (T, H * V) (SGLang's FA backend views its output by v_head_dim), so the heads are value_head_dim wide. For MLA that is 128 vs a K of 192. For every other model, get_attention_dimensions sets value_head_dim = head_dim, so nothing changes.
| q_THK[:num_tokens], k_THK[:num_tokens], v_THV[:num_tokens], forward_batch | ||
| q_THK[:num_tokens], k_THK[:num_tokens], v_THV, forward_batch |
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Nothing was removed: the [:num_tokens] slice of V moved up a few lines, so the copy touches only the rows SGLang scheduled. 7b3e34e also makes that copy unconditional (v[:num_tokens].contiguous(), a no-op for a contiguous V), instead of keying it on value_head_dim != head_dim.
| # compressed latent with SGLang's MLA backends, as the vLLM engine does | ||
| # outside batch-invariant mode; SGLang recognizes MLA models by their | ||
| # architecture name only. | ||
| mla_cfg, inner_cfg = inner_cfg, inner_cfg.inner_attention |
There was a problem hiding this comment.
[From Claude (AI agent), on behalf of @tianyu-l] Reworked in 7b3e34e. inner_cfg is no longer rebound in a tuple swap. mla_cfg is the MLA config, or None, and the MLA wrapping happens where the new layer is built, as in the vLLM wrapper. The TODO also states the cost of per-head K/V: about 9x the cache per token for DeepSeek V3 671B at TP 8.
There was a problem hiding this comment.
Automated review by claude. Do NOT put high weight on this comment.
The first full-attention layer's K/V geometry is used for every softmax layer, with no check.
K/V geometry = a layer's KV head count, head dim and V head dim.
- Inline comment: one K/V geometry from the first full-attention layer sizes every softmax layer, with no check (registry.py:66).
Follow-up 1: KV cost
For DeepSeek V3 671B (flavors.py:732, 737, 748-751 on main), per token per layer:
- Per-head K/V here: 128 x (192 + 128) = 40,960 elements.
- vLLM's latent, outside batch-invariant mode: 512 + 64 = 576 elements (vllm/registry.py:70-81).
- At TP 8, per rank: 5,120 vs 576.
- So about 8.9x more cache per token, at the same dtype.
The TODO at model_wrapper.py:106-110 could carry this number.
Follow-up 2: MLA under CUDA graphs
- In the tests, MLA runs only with
cuda_graph = "none"(test:448). - The reason: the all-to-all dispatcher syncs the host.
- A graph-compatible dispatcher could cover MLA under graphs (unverified for this model). Options: Dist-MoE, or DeepEP with
cuda_graph_compatiblefrom #5959.
| "num_attention_heads": n_heads, | ||
| "num_key_value_heads": n_kv_heads, | ||
| "head_dim": head_dim, | ||
| "v_head_dim": value_head_dim, |
There was a problem hiding this comment.
Automated review by claude. Do NOT put high weight on this comment.
Every softmax layer gets the first full-attention layer's K/V row shape, and nothing checks that the others match.
Problem
- SGLang allocates one K/V row shape for every softmax layer (memory_pool.py:2538-2549).
- This dict takes that shape from the first full-attention layer only.
- That has held for the KV head count and head dim since [rl] generator: SGLang generation engine #5812.
- This PR adds the V width, and drops the old equal-dims raise.
- [rl] generator: SGLang sliding-window attention #5816's sliding layers are not compared either.
Example (unverified on GPU)
- Two MLA layers: the first with V = 128, the second with V = 64.
- The pool is 128 wide.
- The second layer writes its V rows into it through
v.view(-1, v_row_dim)(memory_pool.py:181). - For one token, the view fails.
- For more tokens, the row counts do not match.
Fix
No shipped model mixes K/V row shapes, so this is a guard. Raise ValueError with the layer ids when any softmax layer's (n_kv_heads, head_dim, v_head_dim) differs from the first. _gdn_config_kwargs does the same for GDN.
|
[From Claude (AI agent), on behalf of @tianyu-l] On the review bodies:
|
MLA layers (DeepSeek V3; Kimi K3 also needs KDA) run in the SGLang engine with their projection of the latent to per-head K/V, which SGLang's KV pool caches, as the vLLM engine runs MLA in batch-invariant mode. SGLang's compressed latent MLA cache is not used: SGLang detects MLA models by architecture name (TODO). - attention.py: SGLangInnerAttention takes a V head dim that differs from K's; it then copies V (MLA's V is a strided view of its projection; SGLang's KV cache stores V rows flat), as the vLLM adapter does. - registry.py: the HF-shaped config carries v_head_dim, which sizes SGLang's KV pool. - test_sglang_bitwise_parity.py: DeepSeek V3 debug at TP 1 (TP 2 needs EP 2 for its MoE, where the trainer's MoE with shared experts is not batch-invariant; TODO for #5829).
- SGLangInnerAttention makes V contiguous unconditionally (a no-op unless V is a strided view, as MLA's is) instead of testing head_dim != value_head_dim, and documents both head dims. - The model wrapper names the MLA config without rebinding inner_cfg, and the latent-cache TODO states the per-head K/V cost. - The HF-shaped config raises unless all softmax attention layers share one (n_kv_heads, head_dim, value_head_dim), the one K/V row shape SGLang sizes.

Stacked on #5817 (SGLang GDN).
Summary (human-written)
Why
SGLangEngineraises for MLA (DeepSeek V3; Kimi K3 also needs KDA, #5819). The vLLM engine runs MLA inbatch-invariant mode by projecting the latent to per-head K/V and caching those
with the trainer's varlen kernel. SGLang's own MLA cache (the compressed latent)
needs SGLang's MLA kernels, and SGLang turns it on only for architectures it knows
by name. This PR does what vLLM's batch-invariant path does: MLA keeps its
projection, and SGLang caches per-head K/V whose V head dim differs from K's.
Example.
What changed
sglang/attention/attention.py:SGLangInnerAttentiontakes avalue_head_dim. When itdiffers from K's (MLA), it copies V, as the vLLM adapter does: MLA's V is a strided
view of its projection, and SGLang's KV cache stores V rows flat.
sglang/model_wrapper.py: MLA layers keep their projection and wrapSGLangInnerAttention. A TODO notes the compressed latent cache.sglang/registry.py: the HF-shaped config carriesv_head_dim.path;
_debug_model_configtakes anexpert_parallel_degree. The all-to-alldispatcher needs
cuda_graph="none".TestSGLangBitwiseParityMLA, with the othertwo-process classes.
it is a strided view, as MLA's is) instead of testing
value_head_dim != head_dim; both head dims are documented; the model wrapper no longer rebindsinner_cfg; the HF-shaped config raises unless all softmax attention layers shareone
(n_kv_heads, head_dim, value_head_dim), the one K/V row shape SGLang sizes(all 44 in-repo model flavors pass).
User-facing changes
Numerics
TestSGLangBitwiseParityMLA(DeepSeek V3 debug, TP 2 / EP 2)Testing
pytest tests/rl/unit_tests/cpu: 546 passed.Known issues / follow-ups
token than SGLang's MLA cache.