Skip to content

[rl] generator: SGLang MLA with per-head KV cache - #5818

Merged
tianyu-l merged 2 commits into
sglang-5-gdnfrom
sglang-6-mla
Nov 10, 2026
Merged

tianyu-l merged 2 commits into
sglang-5-gdnfrom
sglang-6-mla

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Stacked on #5817 (SGLang GDN).

Summary (human-written)

Why

SGLangEngine raises for MLA (DeepSeek V3; Kimi K3 also needs KDA, #5819). The vLLM engine runs MLA in
batch-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.

DeepSeek V3 debug: q/k head dim 192 (128 nope + 64 rope), v head dim 128
SGLang KV pool: K rows of H x 192, V rows of H x 128 (v_head_dim in the HF config)

What changed

  • sglang/attention/attention.py: SGLangInnerAttention takes a value_head_dim. When it
    differs 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 wrap
    SGLangInnerAttention. A TODO notes the compressed latent cache.
  • sglang/registry.py: the HF-shaped config carries v_head_dim.
  • Test: a DeepSeek V3 parity class at TP 2 / EP 2, which covers MLA's head-sharded
    path; _debug_model_config takes an expert_parallel_degree. The all-to-all
    dispatcher needs cuda_graph="none".
  • CI: the B200 SGLang step also runs TestSGLangBitwiseParityMLA, with the other
    two-process classes.
  • Review fixes (2ce5e23): V is made contiguous unconditionally (a no-op unless
    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 rebinds
    inner_cfg; 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
    (all 44 in-repo model flavors pass).

User-facing changes

Before After
MLA layers raise supported, with per-head K/V in the KV cache

Numerics

Check Hardware Result
TestSGLangBitwiseParityMLA (DeepSeek V3 debug, TP 2 / EP 2) 2x GB300 4 passed, max delta 0

Testing

  • The class above.
  • pytest tests/rl/unit_tests/cpu: 546 passed.

Known issues / follow-ups

  • The KV cache holds per-head K/V, not the compressed latent: more memory per
    token than SGLang's MLA cache.

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

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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


Approve -- please address the items in the review before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the items below before merging. The 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

  1. The PR description's "Summary (human-written)" section is empty. Please fill it in.
  2. 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 a TODO(<link>). Until it's fixed, nothing tests MLA's TP-sharded path (inline).

Should consider

  • torchtitan/rl/generator/sglang/attention.py:261 -- _flat_rows on K never copies for any current model, so only V needs it. Consider matching vLLM's value_head_dim != head_dim condition (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, the else branch where is_mla rewraps MLAAttention.Config). The compressed-latent cache is a TODO, as the vLLM batch-invariant path also skips it. No core code is touched.
  • TP. SGLangInnerAttention splits num_heads and num_kv_heads by tp_size. For MLA, num_kv_heads == n_heads, so the local head counts match wkv_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_dim is 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]),

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.

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

Suggested change
_flat_rows(k_THK[:num_tokens]),
k_THK[:num_tokens],

Comment on lines +403 to +405
"""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."""

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

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


Approve -- please address the remaining items (description updates, TODO with issue link for the EP 2 trainer bug) before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the items below before merging. 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_rows call 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

  1. 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.
  2. 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 no TODO(<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).

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


Approve -- the earlier code items are fixed; only the human-written summary in the description is still missing: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the item below before merging. The code-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 a TODO linking #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

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

@tianyu-l

tianyu-l commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@tianyu-l
tianyu-l force-pushed the sglang-6-mla branch 2 times, most recently from 4ae580c to 807b921 Compare November 8, 2026 22:58
@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 57s —— View job


Approve -- the rebase left the PR's diff unchanged, but #5829 is now on the branch, so please move the MLA parity class to TP 2 / EP 2 (and drop the one-process CI loop) and write the human-written summary before merging: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the items below before merging. The 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

  1. 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.
  2. tests/rl/unit_tests/gpu/test_sglang_bitwise_parity.py:441 -- the TODO(#5829) is now actionable. Move the class to TP 2 / EP 2 through an expert_parallel_degree kwarg on _debug_model_config instead of tensor_parallel_degree, and revert the docstring edits about per-class process counts (inline).
  3. .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.

Comment on lines +436 to +453
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

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 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 = True

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

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[From Claude (AI agent), on behalf of @tianyu-l] Done in 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.

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


Approve -- the MLA class now runs at TP 2 / EP 2 and CI runs it in the two-process loop; only the human-written summary in the description is still missing: review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the item below before merging. The 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 the TODO(#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

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

Copy link
Copy Markdown
Contributor

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

One MLA token on one TP rank: MLA keeps its projection from the 512-wide latent, and SGLang's paged KV pool stores per-head K (8 x 192) and V (8 x 128) instead of SGLang's own latent cache.

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

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.

Comment on lines 164 to +166
head_dim: int
"""The query/key head dim."""
value_head_dim: int

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 we add a docstring for both, to distinguish their differnece

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] Added in 7b3e34e: head_dim is the query/key head dim (K). value_head_dim is the width of the KV cache's V rows and of the output heads; MLA's differs because its K adds the rotary dims.

Comment on lines -252 to +261
out = out.view(num_tokens, -1, self.head_dim)
out = out.view(num_tokens, -1, self.value_head_dim)

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[From Claude (AI agent), on behalf of @tianyu-l] The 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.

Comment on lines -250 to +259
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

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.

why remove this?

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

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 looks a bit odd

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

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

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.

  1. 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_compatible from #5959.

"num_attention_heads": n_heads,
"num_key_value_heads": n_kv_heads,
"head_dim": head_dim,
"v_head_dim": value_head_dim,

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

Every softmax layer gets the first full-attention layer's K/V row shape, and nothing checks that the others match.

Problem

Example (unverified on GPU)

  1. Two MLA layers: the first with V = 128, the second with V = 64.
  2. The pool is 128 wide.
  3. The second layer writes its V rows into it through v.view(-1, v_row_dim) (memory_pool.py:181).
  4. For one token, the view fails.
  5. 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.

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] Added the guard in 7b3e34e: the HF-shaped config raises unless every softmax attention layer has the same (n_kv_heads, head_dim, value_head_dim). Checked all 44 flavors of the in-repo models; none mixes them.

@tianyu-l

Copy link
Copy Markdown
Contributor Author

[From Claude (AI agent), on behalf of @tianyu-l] On the review bodies:

  • Double-checking the changes. 7b3e34e reworks what the inline comments pointed at:
    • V is made contiguous unconditionally, not keyed on value_head_dim != head_dim;
    • both head dims are documented;
    • the MLA config no longer rebinds inner_cfg;
    • the HF-shaped config raises unless every softmax layer shares one K/V row shape, which all 44 in-repo model flavors do.
      The MLA class passes on 2x GB300.
  • KV cost. Per-head K/V take ~9x the cache per token for DeepSeek V3 671B at TP 8: 5,120 elements per layer and rank, vs the latent's 576. The latent-cache TODO now states this.
  • MLA under CUDA graphs. The class runs with cuda_graph="none" because of the all-to-all dispatcher. A graph-compatible dispatcher (Dist-MoE, or DeepEP with cuda_graph_compatible from [rl] generator: DeepEP and HybridEP token dispatchers on SGLang; shared dispatcher checks #5959) would cover it. That is a follow-up, since it needs DeepEP or dist_moe on the runner.

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