Skip to content

[Kimi K3] Tensor/Sequence Parallelism support - #4499

Merged
tianyu-l merged 12 commits into
pytorch:mainfrom
QIU023:k3_tp_sp
Sep 16, 2026
Merged

tianyu-l merged 12 commits into
pytorch:mainfrom
QIU023:k3_tp_sp

Conversation

@QIU023

@QIU023 QIU023 commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Tensor parallelism, with and without sequence parallel, for Kimi K3 on spmd_types: KDA and MLA become head-parallel, the latent MoE takes core's expert sharding, and the MoonViT tower reuses Kimi K2.5's plan. At tp=1 nothing changes: loss and grad norm match main on all 100 steps.

  • Before: parallelize_kimi_k3 refuses tensor parallel, and MLA / KDA reshape to the global head count (view(num_tokens, n_heads, ...)). After: local_head_split splits the rank-local heads; wq_b, wkv_b, gate and KDA's q_proj, k_proj, v_proj, forget_b, beta, output_gate are colwise; wo and output_proj are rowwise, reduce-scattering under SP.
  • Two Kimi K2.5 commits sit under it. kimi_k2_7/vision_encoder.py: the packed position tables retype only the dp axis under type checking; retyping tp as well is refused at tp > 1, where the tables are already invariant on tp. kimi_k2_7/sharding.py: K2.5's MoonViT plan is public as set_moonvit_sharding_config, with the projector norm named by the caller (pre_norm in K2.5, post_norm in K3). The first can go as its own PR.
  • No core file changes.

Design

  • kimi_k3/sharding.py: set_kimi_k3_sharding_config(config, *, enable_sp, enable_ep) fills every sub-config unconditionally, as DeepSeek V3 does; Module.parallelize drops the disabled axes.
    • MLA: DeepSeek V3's plan without RoPE; wq_a, wkv_a and their norms replicated; inner attention through core's set_gqa_inner_attention_local_spmd; the headless rope key is broadcast to the local heads under spmd.local().
    • KDA: Qwen3.5 GatedDeltaNet's head-sharded plan; forget_a and output_norm replicated; the conv weights, A_log and dt_bias shard with the heads; the kernel is one local_spmd region on the local heads.
    • Latent MoE: core's set_moe_sharding_config, plus core's padding-mask sharding on the MoE layers. Under EP the routed path follows the router: routed_down takes the rank's token shard (without SP it drops the other TP ranks' tokens on entry), the experts' output stays token-sharded, and routed_norm and routed_up run on those tokens with Replicate weights, so their gradients reduce over TP; without SP, routed_up re-enters Partial and the MoE exit reduces once with the shared experts. Without EP the experts are TP-sharded: routed_down is replicated, and without SP the experts' Partial output is reduced at routed_norm.
    • Multimodal: tok_embeddings stays TP-replicated for the vision scatter; layer 0's input boundary puts the stream and the block-residual stack back in the decoder's layout (sequence shard under SP, invariant otherwise).
  • kimi_k3/model.py: update_from_config runs core's first, then checks that tp divides the tower's head count (as K2.5 does), then declares; the batch uses core's multimodal_input_sharding().
  • Not covered: TP x CP (support CP for KimiK3 #4500's); tp above 2 on the debug model, whose tower has 6 heads (the released tower has 12).

Results

torchrun --nproc_per_node=2 -m torchtitan.train --module kimi_k3 --config kimi_k3_debugmodel \
  --debug.seed 42 --debug.deterministic --training.steps 100 \
  --training.num-tokens-per-train-step 256 --training.num-tokens-per-microbatch-per-dp-rank 256 \
  --parallelism.tensor_parallel_degree 2   # --parallelism.no-enable-sequence-parallel for SP off

dp1, 256 tokens per step, against tp=1 on main; the last column counts the steps, of 100, whose logged loss and grad norm equal main's.

cell loss, step 1 step 10 step 20 grad norm, step 1 step 10 step 20 steps equal to main
tp=1, main 12.44473 4.12222 3.31114 27.2500 6.0625 6.1875 reference
tp=1, this PR 12.44473 4.12222 3.31114 27.2500 6.0625 6.1875 100 / 100
tp=1, this PR, fresh inductor cache 12.44473 4.12222 3.31114 27.2500 6.0625 6.1875 100 / 100
tp=2, SP on 12.45268 (+0.064%) 4.44351 (+7.79%) 3.20842 (-3.1%) 27.8750 (+2.29%) 6.9062 (+13.9%) 6.2188 (+0.51%) 0 / 100
tp=2, SP off 12.44544 (+0.0057%) 4.24770 (+3.04%) 3.38211 (+2.14%) 27.5000 (+0.92%) 8.8125 (+45.4%) 6.6875 (+8.08%) 0 / 100

dp2, 512 tokens per step (256 per rank; a multimodal row does not fit in 128), against dp2 on this PR.

cell loss, step 1 step 10 step 20 grad norm, step 1 step 10 step 20
dp2 12.45935 4.07423 3.38009 24.5000 6.0625 4.4375
dp2 x ep2 (no TP) 12.45935 (0%) 3.72571 (-8.55%) 3.40608 (+0.77%) 24.5000 (0%) 4.7188 (-22.2%) 4.2500 (-4.23%)
dp2 x tp2 12.50688 (+0.38%) 3.88132 (-4.73%) 3.41127 (+0.92%) 24.7500 (+1.02%) 5.0625 (-16.5%) 4.7500 (+7.04%)
dp2 x ep2 x tp2 12.52374 (+0.52%) 4.07369 (-0.013%) 3.45136 (+2.11%) 24.3750 (-0.51%) 4.5938 (-24.2%) 4.6250 (+4.23%)
dp2 x ep2 x tp2, SP off 12.48901 (+0.24%) 4.02450 (-1.22%) 3.42512 (+1.33%) 24.1250 (-1.53%) 8.4375 (+39.2%) 5.3438 (+20.4%)

Kimi K2.5, dp2, tp=1, 4096 tokens per step (its debug config), this PR against main; K2.5 refuses tp > 1 on main (DistMuon, #3353).

cell loss, step 1 step 10 step 20 grad norm, step 1 step 10 step 20 steps equal to main
main 8.01201 4.60605 3.24834 8.8055 4.5538 2.9925 reference
this PR 8.01201 4.60605 3.24834 8.8055 4.5538 2.9925 100 / 100

Type checking, 3 steps with --debug.spmd_typechecking and activation checkpointing off (as the b200 recipe sets it): the b200 cell kimi_k3_debugmodel_mm (fsdp 2 x tp 2 x ep 2) with SP on and off on 4 GPUs, and dp1 x tp2 on 2 GPUs, pass.

4 x H100 80GB HBM3 (SXM), main d34a13fdf, torch 2.15.0.dev20260906+cu130, attn-gym 0.0.8 (main's pin), spmd_types 0.2.5; KDA's capability guard widened locally to admit SM 9.0, not part of this PR. For scale, #4500's CP=2 rows on H100: +3.8% and +15.1% loss at step 10.

CI/CD Coverage

kimi_k3_mm in the b200 suite: kimi_k3_debugmodel_mm, fsdp 2 x tp 2 x ep 2 with SP and type checking, 4 GPUs; it replaces kimi_k3_mm_fsdp. test_integration_test_definitions.py and test_no_new_cli_options.py pass on this head.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Sep 6, 2026
@QIU023
QIU023 marked this pull request as draft September 6, 2026 09:25
@QIU023 QIU023 changed the title [DO NOT review, stacked on K3 spmd declaration PR ] [Kimi K3] Tensor parallelism with sequence parallel support, on the spmd_types declarations [DO NOT review, stacked on K3 spmd declaration] [Kimi K3] Tensor parallelism with sequence parallel support, on the spmd_types declarations Sep 9, 2026
@QIU023
QIU023 force-pushed the k3_tp_sp branch 2 times, most recently from 54ebe13 to ce10692 Compare September 9, 2026 23:39
@QIU023 QIU023 changed the title [DO NOT review, stacked on K3 spmd declaration] [Kimi K3] Tensor parallelism with sequence parallel support, on the spmd_types declarations [DO NOT review] [Kimi K3] Tensor parallelism with sequence parallel support, on the spmd_types declarations Sep 10, 2026
@QIU023 QIU023 changed the title [DO NOT review] [Kimi K3] Tensor parallelism with sequence parallel support, on the spmd_types declarations [DO NOT review] [Kimi K3] Tensor parallelism with sequence parallelism support, on the spmd_types declarations Sep 10, 2026
@QIU023
QIU023 marked this pull request as ready for review September 10, 2026 09:09
@QIU023 QIU023 changed the title [DO NOT review] [Kimi K3] Tensor parallelism with sequence parallelism support, on the spmd_types declarations [DO NOT review] [Kimi K3] Tensor parallelism with sequence parallelism support Sep 10, 2026
@QIU023 QIU023 changed the title [DO NOT review] [Kimi K3] Tensor parallelism with sequence parallelism support [DO NOT review] [Kimi K3] Tensor/Sequence Parallelism support Sep 10, 2026
@QIU023 QIU023 changed the title [DO NOT review] [Kimi K3] Tensor/Sequence Parallelism support [Kimi K3] Tensor/Sequence Parallelism support Sep 10, 2026
@QIU023

QIU023 commented Sep 10, 2026

Copy link
Copy Markdown
Contributor Author

Hi Shuhua @shuhuayu, as you mentioned in the tracking list, the TP/SP PR is formally raised for your review, thank you very much!

@tianyu-l
tianyu-l requested a review from shuhuayu September 10, 2026 17:12

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

Thx for the pr. overall impression is that we can check how kimi 2.7 (vit part) and qwen 3.5 (linear attention part) to tp sharding. currently vision tower is not tp parallel with all qkv and mlp replicated. also can you rebase so we can run tests.

Comment thread torchtitan/models/kimi_k3/kda.py Resolved
Comment thread torchtitan/models/kimi_k3/kda.py Resolved
Comment thread torchtitan/models/kimi_k3/model.py Resolved
Comment thread torchtitan/models/kimi_k3/model.py Resolved
Comment thread torchtitan/models/kimi_k3/model.py Resolved
Comment thread torchtitan/models/kimi_k3/sharding.py Outdated
layer.moe.routed_norm.sharding_config = routed_norm_cfg


def _set_vision_encoder_tp_invariant_sharding(ve_cfg, *, enable_sp: bool) -> None:

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.

Could we reuse or generalize the existing MoonViT sharding path here? set_vision_transformer_block_sharding_config() first configures the attention and MLP linears for TP, but this function immediately overwrites those declarations as invariant, including the attention and inner-attention boundaries. Effectively, only the norm setup survives, which makes the call-then-override flow difficult to reason about.

If replicating the entire vision tower is intentional, could we introduce a common invariant vision-block helper? Otherwise, can K3 reuse Kimi K2.5’s TP-sharded MoonViT setup and customize only its projector/post-norm differences?

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.

Ack, it's not intentional to replicate the entire ViT, reused K2.7 ViT TP sharding utils, please see below comments: #4499 (comment)

packed_pos = spmd.mutate_type(
packed_pos, src=spmd.R, dst={"dp": spmd.V, "tp": spmd.I}
)
# Per rank on dp, as the grids are; on tp the table's declaration holds.

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 reuse the kimi 2.7's tp sharding for vit in kimi 3? I do not see differences yet correct me if am wrong. so we do need changes in this 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.

Yes, in the new change, K3 reuses it: the tower runs K2.5's MoonViT plan via set_moonvit_sharding_config, with no ViT declarations of its own.

That reuse is why this file changes, by two lines: at tp > 1 the plan declares pos_embed / inv_freq invariant on tp, so the tables' mutate_type(src=R) on tp is refused by the type checker. The fix retypes only the dp axis. It is K2.5's own bug, not K3's, and nothing changes at tp = 1.

please LMK if you want me to separate this commit out to another PR: QIU023@94c6f79

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.

i see your point, this is an existing bug, thanks for fixing it.

Comment thread torchtitan/models/common/attention.py Resolved
Comment thread torchtitan/models/common/linear.py Resolved
@QIU023

QIU023 commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Thank you so much Shuhua @shuhuayu for your detailed reviews! I have spent the whole tonight addressing PP PR: #4312 so even if have drafted changes but haven't have time to do the verification and full responses tonight on this TP PR new fixes and reviewing the QB PR (please feel free to proceed QB PR if maintainers are all good about that, no need to wait for me), I will get back to it ASAP and try my best to publish next round of the changes and request your next round review within 1 day

@QIU023
QIU023 force-pushed the k3_tp_sp branch 2 times, most recently from bd55160 to 22eeec4 Compare September 12, 2026 08:54
@QIU023

QIU023 commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi Shuhua @shuhuayu , have addressed all comments, mainly about remove duplicate utils and reuse K2.7 ViT TP shardings, all experiments are now running on 4*H100 to align with CP PR criteria, please check, thanks again for detailed TP/SP review!

@QIU023
QIU023 requested a review from shuhuayu September 12, 2026 09:15

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

lgtm overall, please check the routed_down part tp sharding and some nit comments.

Comment thread torchtitan_recipes/tests/b200.py Outdated
return config


def kimi_k3_debugmodel_mm_tp2() -> Trainer.Config:

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.

let's merge this test with kimi_k3_debugmodel_mm_fsdp2 to have a unified test kimi_k3_debugmodel_mm with fsdp=2, tp=2, ep=2.

@QIU023 QIU023 Sep 15, 2026 •

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.

NP, changed, but when CP and PP merged in, seems we need a 16 GPU run for a 5D mesh CI if we put all of parallelism in one flavor ? or we still have to separate some flavor

Comment thread torchtitan/models/kimi_k3/sharding.py Resolved
Comment thread torchtitan/models/kimi_k3/sharding.py Resolved
Comment thread torchtitan/models/kimi_k3/sharding.py Resolved
Comment thread torchtitan/models/kimi_k3/sharding.py Resolved
Comment thread torchtitan/models/kimi_k3/sharding.py Resolved
Comment thread torchtitan/models/kimi_k3/sharding.py Resolved
Comment thread torchtitan/models/kimi_k3/sharding.py Resolved
Comment thread torchtitan/models/kimi_k3/sharding.py Outdated
)
# Replicated when the experts are TP-sharded; under EP they are whole on
# every tp rank, so routed_down follows the stream's rule.
moe_cfg.routed_down.sharding_config = (

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.

changes needed for the tp sharding for routed_down. we can make the sharding for routed_down the same with router, when sp is not enabled, we should discard unused local tokens, and make tokens still sharded on tp ranks.

@QIU023 QIU023 Sep 15, 2026 •

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.

Ack, fixed, in two commits, fix the routed_down as your indicated behavior, also fix the routed_norm and routed_up part,

EP enabled:

  1. routed_down now uses the router's layout: without SP it drops the other TP ranks' tokens on entry, and its weight is Replicate so the gradient is reduced over TP (1dec3ee).
  2. The tokens then stay sharded on TP through the rest of the routed path: the experts' output is no longer turned Partial, routed_norm and routed_up run on the local tokens, and only routed_up's output re-enters Partial for the MoE exit, so the latent all-reduce before routed_norm is gone (48632ad).

Please LMK if the new MoE sharding handling looks good to you or we want to further adjust behavior, thanks!

…tion under type checking

The learned position embedding and the 2-D RoPE cache are gathered from the
per-image tables and, under spmd_types type checking, retyped for the packed
stream. The retype named a tp destination as well as the dp one; with tensor
parallelism on, the checker then read the table's source type from the
declaration the tower's parameters carry on the tp axis and refused the
mismatch. The retype now names the dp axis only: per rank on dp, as the
grids are, while on tp the table's own declaration holds.
…norm named by the caller

Kimi K3's tower is a MoonViTEncoder with its own projector, whose norm
follows the second linear (post_norm) where Kimi K2.5's precedes the first
(pre_norm). set_moonvit_sharding_config is Kimi K2.5's plan unchanged, with
that norm's name as a keyword defaulting to K2.5's, so K3 reuses it.
set_kimi_k3_sharding_config declares the whole model unconditionally, as
DeepSeek V3's does; Module.parallelize drops the axes a run does not have.
It has DeepSeek V3's layout: the decoder root from set_decoder_sharding_config,
then one helper per layer.

- MLA takes DeepSeek V3's MLA plan, without RoPE and with a colwise gate.
- KDA is head-sharded as Qwen3.5's GatedDeltaNet, the kernel in one local
  SPMD region.
- The latent MoE is core's MoE plan plus its latent projections.
- The attention residual's norms and projections declare their weights only:
  _apply_attention_residual reads the weights, not the modules.
- The vision tower takes Kimi K2.5's MoonViT plan; with a tower the token
  embedding stays TP-replicated for the scatter and layer 0's boundary
  restores the decoder layout, as in Kimi K2.5.

MLA and KDA split heads with local_head_split, the vision head count is
checked against the TP degree as in Kimi K2.5, and tensor parallelism leaves
the unsupported list.
kimi_k3_mm_tp2 runs the multimodal debug flavor at tp=2 with sequence
parallel under spmd_types type checking.
kimi_k3_debugmodel_mm runs fsdp 2 x tp 2 x ep 2 on 4 GPUs with SPMD type
checking, replacing the separate FSDP and TP cells.
_tp_unsharded_weight_config and _set_multimodal_decoder_boundary_sharding
name what they declare; the output residual weights are set after the
layers, in forward order; two docstring notes go.
Like the router, the latent down-projection takes the rank's tokens when
experts are expert-parallel: without sequence parallel it drops the other
tp ranks' tokens on entry instead of projecting all of them, and its
weight is Replicate so the gradient is reduced over tp. The routed
experts' input is declared token-sharded to match.
@QIU023

QIU023 commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Thank you so much Shuhua! Will address all of them tonight!

SP is the default, but the cell exists to cover TP with SP; stating it keeps that coverage if the default changes, as the other TP recipes do.
…nder EP

Under EP the experts' output stays token-sharded instead of turning Partial,
and routed_norm and routed_up run on the rank's tokens with Replicate weights,
so their gradients reduce over tp. Without SP, routed_up re-enters Partial
and the MoE exit reduces once with the shared experts; the latent all-reduce
before routed_norm and the tp-fold repeated norm and up go away. Without EP
the path is unchanged.
…P-sharded

The routed path under EP is token-sharded without SP too, so the helper takes
token_sharded and its docstring states that rule; no sharding changes.
@QIU023

QIU023 commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks for your review Shuhua! all comments addressed, LMK if the new changes on MoE sharding config meets your expectation

@QIU023
QIU023 requested a review from shuhuayu September 15, 2026 09:31

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

LGTM, thx for addressing my comments.

@QIU023

QIU023 commented Sep 15, 2026

Copy link
Copy Markdown
Contributor Author

Thank you so much Shuhua @shuhuayu for approval! Could you help to check with Tianyu and merge this PR? Following up more query in #4272

@tianyu-l
tianyu-l merged commit 3ce746c into pytorch:main Sep 16, 2026
14 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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