Skip to content

[moe] batch-invariant shared/routed combine under TP - #5829

Merged
tianyu-l merged 4 commits into
mainfrom
moe-bi-tp-shared-experts
Nov 5, 2026
Merged

tianyu-l merged 4 commits into
mainfrom
moe-bi-tp-shared-experts

Conversation

@tianyu-l

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

Copy link
Copy Markdown
Contributor

Summary (human-written)

today when TP(no SP)->EP is used, we do

  • shared expert output (partial) + routed expert output (shard -> partial), locally
  • all-reduce

This is not batch invariant, because when batch size change, a routed token can sit on different ranks, which affect the reduction order!

This PR

  • shared expert output (partial) -> all-reduce
  • routed expert output (shard -> partial) -> all-reduce, which is basically all-gather so deterministic and batch invariant
  • add together

Why

Batch-invariant mode breaks for MoE models with shared experts (DeepSeek V3, Kimi
K3) at TP >= 2 with EP. The same token gets different logprobs depending on how
many other tokens share its batch. With EP over TP and no sequence parallelism,
MoE runs:

  1. the routed experts on each TP rank's token shard;
  2. the shared experts on all tokens, as a TP partial sum.

The owner rank adds a token's routed output into its own partial before the single
TP all-reduce, so the summation order depends on which rank owns the token. That
moves with the token count.

Example. TP 2, a 150-token prompt vs the same prompt with 2 tokens appended:

150 tokens: token 75 is on rank 1 -> shared_0 + (routed + shared_1)
152 tokens: token 75 is on rank 0 -> (routed + shared_0) + shared_1
DeepSeek V3 debug, trainer prompt logprobs: max diff 3.8e-3 (first at layers.1.feed_forward, row 75)

What changed

  • models/common/moe/moe.py: the routed + shared + TP-reduce tail of MoE.forward
    is now MoE._add_shared_experts_and_reduce_across_tp.
    • In batch-invariant mode, with shared experts, EP over TP and no SP, it
      all-reduces the zero-filled routed output (exact: the other ranks add zeros)
      and the shared partials separately, then adds them. This costs one more TP
      all-reduce in batch-invariant mode only.
    • Otherwise it is unchanged (moved verbatim).
  • models/kimi_k3/moe.py: KimiLatentMoE.forward duplicated that tail; it now
    calls the method. MuseSparkMoE has no shared experts, so it is unaffected.
  • test_moe.py: the stub MoE gets the new method.

Alternatives considered

  • Reduce-scatter the shared partials, add the routed shard, then all-gather. Same
    communication as one all-reduce, but NCCL's reduce-scatter summation order is
    position-dependent beyond TP 2, and the gather requires even token shards.
  • Gather the routed shard instead of all-reducing it. Less traffic, but it requires
    even shards; the zero-fill path does not.

Numerics

Outside batch-invariant mode, nothing changes. The code path is moved verbatim, so
there are no golden changes. Batch-invariant CI runs Kimi K3 at TP 1 and Qwen3 MoE,
which has no shared experts, so no golden is affected.

Check Hardware Before After
Trainer prompt logprobs, +2 / +50 tokens (DeepSeek V3 debug, TP 2 / EP 2) 2x GB300 3.8e-3 0
Trainer, alone vs packed (Kimi K3 debug, TP 2 / EP 2) 2x GB300 4.6e-2 0
vLLM test_bitwise_parity Kimi K3 class at TP 2 / EP 2 (no CUDA graphs) 2x GB300 batch invariance fails (7.3e-3) 4 passed
SGLang parity, DeepSeek V3 and Kimi K3 at TP 2 / EP 2 (stack #5813) 2x GB300 fails 4 + 4 passed, max delta 0

Testing

  • As above, run with local scripts.
  • pytest tests/unit_tests/cpu -k "moe or kimi or deepseek": 244 passed.

Known issues / follow-ups

With EP over TP and no sequence parallelism, MoE adds each token's routed
output to its TP rank's shared-expert partial sum before the TP
all-reduce. Which rank owns a token depends on the token count, so the
same token's output is summed in a different order when the batch
changes: (routed + shared_0) + shared_1 on rank 0 versus
shared_0 + (routed + shared_1) on rank 1. This breaks batch invariance
for MoE models with shared experts (DeepSeek V3, Kimi K3) at TP >= 2:
appending 2 tokens to a 150-token prompt changes its logprobs by up to
3.8e-3 in the trainer.

In batch-invariant mode, reduce the routed output (zero-filled: exact)
and the shared partials separately, then add: one more TP all-reduce.
The routed/shared/TP-reduce tail moves into one MoE method that
KimiLatentMoE now shares; outside batch-invariant mode it is unchanged
(moved verbatim).
@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 2m 25s —— View job


Approve, with items to address before merging -- see the review.

tianyu-l added a commit that referenced this pull request Nov 4, 2026
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).

@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 fix targets the root cause: the summation order of the routed/shared combine depends on which rank owns a token. The extra all-reduce only happens in batch-invariant mode, and the default path is moved verbatim.

What this PR does. With EP over TP and no SP, each TP rank adds the routed output of the tokens it owns into its own shared-expert partial, and only then does the single TP all-reduce. Which rank owns a token changes with the token count, so the floating-point summation order changes too. In batch-invariant mode the PR all-reduces the zero-filled routed output and the shared partials separately, then adds the two. The zero-fill all-reduce is exact, and the tree all-reduce that batch_invariant.py:124 forces has a fixed order. Kimi K3's duplicated copy of this tail now calls the shared method.

Example. TP 2, token 75, shared partials s0 / s1, routed output r:

before, 150 tokens (rank 1 owns t75): s0 + (r + s1)
before, 152 tokens (rank 0 owns t75): (r + s0) + s1    -> differs in the last bits
after, any token count:              (r + 0) + (s0 + s1) = r + (s0 + s1)

Must fix

  1. The PR description's "Summary (human-written)" section is empty. Please fill it in.

Should consider

  • torchtitan/models/common/moe/moe.py:833-862 -- the batch-invariant gate repeats the helpers' own conditions, and the routed P->I region duplicates _maybe_all_reduce_moe_output_across_tp. Since both helpers do nothing outside EP-over-TP-without-SP, the gate can be just shared_experts is not None and is_in_batch_invariant_mode(). Details are in the inline comment.
  • torchtitan/distributed/REMAT.md:305 -- the new tp_routed_reduction region isn't listed under "Saving expensive MoE work". A policy that follows the documented example (it saves only moe.tp_output_reduction) will replay the routed TP all-reduce in backward when batch-invariant mode is on. Add it to the list and to the example policy.
  • Coverage: no CI test checks this fix. The cheapest guard is the follow-up the PR already lists. rl_grpo_kimi_k3_debug_batch_invariant (torchtitan_recipes/tests/rl/alphabet_sort.py:1044) runs at TP 1. It can switch to trainer TP 2 / EP 2 plus one TP 2 generator and still fit on its 4 GPUs. Doing that here would catch a regression that is otherwise silent.

Questions

  • Is the TP 2 Kimi K3 config left as a follow-up because of CUDA graphs? The vLLM parity row in the description says "no CUDA graphs". If CUDA graphs break batch invariance at TP 2 for a separate reason, please note that in the follow-up.
Details
  • Necessity: the problem is real on main. The example in the description is a concrete failing input, and the fix sits in the layer that owns the TP reduction (MoE), not in a caller.
  • Equivalence outside batch-invariant mode: the else path is the old tail line for line (kimi_k3/moe.py deleted lines vs moe.py:863-871), so no golden files change.
  • The suggested simplification is equivalent. With dense SP on, _maybe_zero_fill... and _maybe_all_reduce... both return their input, so the result is routed + shared, the same as the default path. With no TP group, both helpers also return their input. TP without EP already fails the assertion at moe.py:886.
  • MuseSparkMoE (muse_spark/moe.py:142-143) has no shared experts, so it needs no change. The test stub change in test_moe.py:105 is mechanical.
  • A maintainer still needs to review, since this touches models/common/.

Not verified: the GPU parity numbers in the description, and whether tree all-reduce with NCCL_MAX_NCHANNELS=1 gives a position-independent order at TP > 2.

Comment thread torchtitan/models/common/moe/moe.py Outdated
Comment on lines +833 to +862
tp_group = spmd_mesh_group(MeshAxisName.TP)
if (
self.shared_experts is not None
and is_in_batch_invariant_mode()
and spmd_sparse_mesh() is not None
and not spmd_dense_sp_enabled()
and tp_group is not None
):
# Adding a token's routed output to its TP rank's shared-expert partial
# sum (below) makes the reduced sum depend on which rank owns the token,
# which moves with the token count. Reduce the routed output (exact: the
# other ranks add zeros) and the shared partials separately, then add:
# one more all-reduce.
routed_out_TD = remat.region(
spmd.redistribute,
self.remat_region_name("tp_routed_reduction"),
recompute=self.remat_should_recompute("tp_routed_reduction"),
)(
self._maybe_zero_fill_routed_output_to_tp_partial(routed_out_TD),
tp_group,
src=spmd.P,
dst=spmd.I,
backward_options={"op_dtype": routed_out_TD.dtype},
)
shared_TD = self._maybe_all_reduce_moe_output_across_tp(
self.shared_experts(x_TD)
)
return remat.region(
torch.add, self.remat_region_name("shared_add"), recompute=False
)(routed_out_TD, shared_TD)

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 gate copies the checks already inside _maybe_zero_fill_routed_output_to_tp_partial (spmd_sparse_mesh() is not None and not spmd_dense_sp_enabled() and tp_group is not None), and the routed spmd.redistribute(P -> I) region repeats the body of _maybe_all_reduce_moe_output_across_tp. The two helpers already do nothing outside EP-over-TP-without-SP. So the batch-invariant branch can be gated on shared_experts is not None and is_in_batch_invariant_mode() alone, and it still gives routed + shared (the same result as the default path) under SP or without TP:

if self.shared_experts is not None and is_in_batch_invariant_mode():
    # <same comment>
    routed_out_TD = self._maybe_all_reduce_moe_output_across_tp(
        self._maybe_zero_fill_routed_output_to_tp_partial(routed_out_TD),
        region="tp_routed_reduction",
    )
    shared_TD = self._maybe_all_reduce_moe_output_across_tp(self.shared_experts(x_TD))
    return remat.region(
        torch.add, self.remat_region_name("shared_add"), recompute=False
    )(routed_out_TD, shared_TD)

To do this, _maybe_all_reduce_moe_output_across_tp takes the region name (muse_spark/moe.py:143 and the test at test_moe.py:567 pass "tp_output_reduction"). That removes the duplicated 5-way condition and the second copy of the redistribute region (about 12 lines), and it leaves one place that decides when the TP reduction happens.

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


Approve, with items to address before merging -- see the 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 new commit 9ef6ee7 resolves the REMAT.md item. The only remaining must-fix is the empty human-written summary.

What changed since the last review. 9ef6ee7 changes only torchtitan/distributed/REMAT.md. It documents tp_routed_reduction next to tp_output_reduction and adds "moe.tp_routed_reduction" to the example save policy. The code is the same as in the commit I reviewed before.

Example. With the policy from REMAT.md, batch-invariant mode, and TP 2 / EP 2 without SP:

before 9ef6ee7: save_regions has moe.tp_output_reduction only
                -> the routed P->I all-reduce is replayed in backward
after:          save_regions also has moe.tp_routed_reduction
                -> both TP all-reduces are saved, none is replayed

Resolved

  • torchtitan/distributed/REMAT.md:305 -- tp_routed_reduction is now documented and in the example policy.

Must fix (still open)

  1. The PR description's "Summary (human-written)" section is still the template placeholder. Please fill it in.

Should consider (still open, no reply yet)

  • torchtitan/models/common/moe/moe.py:833-862 -- the gate still repeats the helpers' own conditions, and the routed P->I region is a second copy of _maybe_all_reduce_moe_output_across_tp. The earlier inline comment shows the shorter version: gate on shared_experts is not None and is_in_batch_invariant_mode() and pass the region name to the helper.
  • Coverage: still no CI test for TP >= 2 with shared experts in batch-invariant mode. Moving rl_grpo_kimi_k3_debug_batch_invariant (torchtitan_recipes/tests/rl/alphabet_sort.py:1044) to trainer TP 2 / EP 2 in this PR would guard the fix. Otherwise a regression would go unnoticed.

Questions (still open)

  • Is the TP 2 Kimi K3 config left as a follow-up because of CUDA graphs? (The vLLM row in the description says "no CUDA graphs".)

A maintainer still needs to review, since this touches models/common/.

Not verified: the GPU parity numbers in the description.

Gate the batch-invariant combine on shared experts alone: the zero-fill and
TP reduction helpers are no-ops outside EP over TP without SP. The routed
sum keeps its own remat region (tp_routed_reduction) through a region name
argument.
@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, with items to address before merging -- see the 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. New commit 7649212 takes the suggested simplification. The new commit adds no new problems. The only must-fix left is the empty human-written summary.

What changed since the last review. In batch-invariant mode, 7649212 now gates only on shared_experts is not None and is_in_batch_invariant_mode(). It sends the routed sum through _maybe_all_reduce_moe_output_across_tp(..., region_name="tp_routed_reduction"). That removes the 5-way condition and the second copy of the P->I region. Net change in moe.py: -10 lines.

Example. Batch-invariant mode, shared experts present:

TP 2 / EP 2, no SP: (zero-filled routed -> all-reduce) + (shared -> all-reduce)   # 2 all-reduces
dense SP on:        both helpers return their input -> routed + shared       # same as default path
no TP:              both helpers return their input -> routed + shared       # same as default path

I checked that the other callers still get tp_output_reduction through the default: muse_spark/moe.py:143, test_moe.py:567, and gpu/distributed/test_remat.py:249.

Resolved

  • torchtitan/models/common/moe/moe.py:833 -- the duplicated gate and the second redistribute region are gone.

Must fix (still open)

  1. The "Summary (human-written)" section of the PR description is still empty. Please fill it in.

Should consider

  • torchtitan/models/common/moe/moe.py:931 -- the docstring still says "Reduce the combined partial output". The function now also reduces the routed and shared partials separately. Changing it to "Reduce a TP-partial MoE output when dense SP is disabled" would make it accurate.
  • Coverage (still open): no CI test runs TP >= 2 with shared experts in batch-invariant mode. Moving rl_grpo_kimi_k3_debug_batch_invariant (torchtitan_recipes/tests/rl/alphabet_sort.py:1044) to trainer TP 2 / EP 2 would guard this fix. Otherwise a regression would go unnoticed.

Questions (still open)

  • Is the TP 2 Kimi K3 config left as a follow-up because of CUDA graphs? The vLLM row in the description says "no CUDA graphs".

A maintainer still needs to review, since this touches models/common/.

Not verified: the GPU parity numbers in the description.

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


Approve, with items to address before merging -- see the 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. New commit 21bd5e3 fixes the docstring item and adds no new problems. The only must-fix left is the empty human-written summary.

What changed since the last review. 21bd5e3 changes one line. The _maybe_all_reduce_moe_output_across_tp docstring now reads "Reduce a TP-partial MoE output when dense SP is disabled". That is accurate for both of its callers: the batch-invariant routed and shared reductions, and the default combined reduction.

Example. The same helper serves all three call sites:

batch-invariant, shared experts: helper(zero-filled routed, region_name="tp_routed_reduction")
                                 helper(shared partial)              # tp_output_reduction
default path / MuseSparkMoE:     helper(routed + shared)             # tp_output_reduction

Resolved

  • torchtitan/models/common/moe/moe.py:931 -- the docstring is now accurate.

Must fix (still open)

  1. The "Summary (human-written)" section of the PR description is still the template placeholder. Please fill it in.

Should consider (still open)

  • Coverage: no CI test runs TP >= 2 with shared experts in batch-invariant mode. Moving rl_grpo_kimi_k3_debug_batch_invariant (torchtitan_recipes/tests/rl/alphabet_sort.py:1044) to trainer TP 2 / EP 2 would guard this fix. Without it, a regression would go unnoticed.

Questions (still open)

  • Is the TP 2 Kimi K3 config left as a follow-up because of CUDA graphs? The vLLM row in the description says "no CUDA graphs".

A maintainer still needs to review, since this touches models/common/.

Not verified: the GPU parity numbers in the description.

tianyu-l added a commit that referenced this pull request Nov 4, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 4, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 4, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 4, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 4, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 4, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 4, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 5, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 5, 2026
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).
tianyu-l added a commit that referenced this pull request Nov 5, 2026
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).
@tianyu-l
tianyu-l marked this pull request as ready for review November 5, 2026 09:14
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 5, 2026
@tianyu-l
tianyu-l merged commit 61fd571 into main Nov 5, 2026
tianyu-l added a commit that referenced this pull request Nov 10, 2026
Stacked on #5818 (SGLang MLA).

## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
     this approach, and what you checked yourself. -->

## Why
`SGLangEngine` raises for KDA linear attention (Kimi K3). KDA runs like
GDN (#5817),
with one difference. Batch-invariant GDN runs a sequential scan with no
replay state
(#5963), but the trainer's KDA runs a chunk kernel, so the generator
keeps it: in
batch-invariant mode, Attention Gym advances the recurrent state only at
64-token
chunk boundaries. It keeps the unfinished chunk's
q/k/v/gate/beta in a per-slot replay state, which is what makes decode
match the
trainer's chunk kernel bitwise. SGLang's state pool holds one conv list
in one
dtype plus one temporal state, with no place for replay tensors.

**Example.**
```
after 150 tokens: recurrent state at token 128 + replay state of tokens 129-150
SGLang slot: conv list = [conv history (bf16, [W-1, C]),
                          q, k, v, gate, beta, count: each flattened to bf16 bytes,
                          padded to 16 bytes (count: 4 -> 16)]
             temporal  = recurrent state (fp32)
radix cache snapshot of a slot copies every conv entry -> replay state included
```

## What changed
- `sglang/attention/kda.py` (new): `TorchTitanKDAConfig` (state slot
shapes; in
batch-invariant mode, each replay tensor is one flat conv entry sized in
bytes of
the conv dtype and padded to 16 bytes, because SGLang's HiCache copies
each slot
entry in 16-byte words), `TorchTitanKDAAttnBackend` (views the replay
entries back
  as their dtypes and shapes), and `SGLangInnerKDA`.
- `sglang/attention/linear_attention.py` (new): the parts GDN and KDA
share inside SGLang,
moved out of `gdn.py`: the HF config base, the `RadixLinearAttention`
module, the
  weight hand-off and padding rows, and the extend-path convolution.
- `sglang/registry.py`:
- registers the KDA backend; a model with both GDN and KDA layers
raises.
- patches SGLang's hybrid KV pool for TorchTitan models (TODO). The pool
builds
its full-attention KV pool without `v_head_dim`, though it counts it
when
    sizing. Kimi K3's MLA layers have V head dim 128 against K 192.
- `generator/attention/kda.py` (new): the KDA recurrence over a paged
state pool, moved from the
  vLLM adapter and shared by both engines. Mechanical.
- `sglang/engine.py`: docstring only.
- Tests:
  - a Kimi K3 parity class (SM90+);
- the class reuses `test_bitwise_parity`'s Kimi K3 config, renamed to a
public
    name.
- CI: the B200 SGLang step also runs `TestSGLangBitwiseParityKDA`, in a
one-process
  launch.

## User-facing changes
| Before | After |
| --- | --- |
| KDA layers raise | supported; in batch-invariant mode, the replay
state takes 1.25x the recurrent state's memory (head dim 128) |

## Numerics
| Check | Hardware | Result |
| --- | --- | --- |
| `TestSGLangBitwiseParityKDA` (Kimi K3 debug: KDA + MLA, TP 1), incl.
the next-turn test | 1x GB300 | 4 passed, max delta 0 |
| Same, replay state dropped (state-only decode) | 1x GB300 | fails,
delta 3.7e-2 |
| Same, cached state ignored | 1x GB300 | fails, delta 7.1e-2 |
| Same tests outside batch-invariant mode (smoke) | 1x GB300 | mean abs
logprob diff 2-5e-3, max < 0.08 |
| vLLM `TestBitwiseParityKimiK3DebugVarlen` (covers the moved paged KDA)
| 1x GB300 | 4 passed |
| HiCache (`write_through`, small GPU pools): cached turn whose prefix
was evicted to host memory and loaded back (local script) | 1x GB300 |
max delta 0; 199 of 208 prompt tokens served from the cache (0 without
HiCache). Unpadded entries crashed the first host backup |
| `TestSGLangBitwiseParityKDA` with HiCache `write_through`, 18 runs
(local) | 1x GB300 | 17 passed; 1 run had a trainer-vs-SGLang mismatch
(see Known issues). 8 of 8 passed without HiCache |

## Testing
- As above.
- All SGLang parity classes rerun at the top of the stack. GDN covers
the moved
  shared code.
- `reset_kv_cache_on_model_state_dict_load=True` (the Kimi K3
batch-invariant
  recipe's setting), Qwen3.5 and Kimi K3. Checked with a local script:
- A reload of the same weights mid-generation retracts the running
requests,
flushes their states and recomputes them. Tokens and logprobs are
identical to
    a run without a reload (5 of 5 sequences each, delta 0).
  - The model-state-dict-load parity test passes in reset mode.
- `pytest tests/rl/unit_tests/cpu`: 546 passed.

## Known issues / follow-ups
- With HiCache `write_through` (SGLang's default policy), one run in 18
of the KDA
  parity class had a trainer-vs-SGLang mismatch (max delta 3.1e-2). Not
  root-caused, so `SGLangEngine` raises for KDA models with
  `enable_hierarchical_cache` (47dda9e).
- Upstream issues for the workarounds in this stack, linked from their
TODOs:
  - the hybrid pool's `v_head_dim`: sgl-project/sglang#48461;
  - MLA detection by architecture name: sgl-project/sglang#48462;
  - `triton.next_power_of_2`: sgl-project/sglang#48460;
- the non-overlap requirement of the mamba radix cache:
sgl-project/sglang#48463;
- Attention Gym's `ReplayState` layout constants:
meta-pytorch/attention-gym#692.
- KDA at TP > 1 is not covered by this PR's test: the class runs at TP
1, as the vLLM
Kimi K3 parity class does. With #5829 (now on main), it passed at TP 2 /
EP 2 (4
  passed, max delta 0); moving it there is a TODO in the test.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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.

2 participants