Repository navigation
[Kimi K3] Expert Parallelism support - #4314
Conversation
Wire the EP path for Kimi K3 on top of the PR-4025 FSDP2 base: declare routed-expert sharding via set_moe_sharding_config, build the edp mesh, gate model.parallelize and apply_fsdp_to_decoder's ep_degree/ edp_mesh on ep_enabled, and remove EP from the unsupported list. Pin the latent MoE to the standard all-to-all token dispatcher (no MoonEP). Add the debugmodel_text flavor and its trainer config for the EP text arm.
Covers expert parallel in CI: standard all-to-all dispatch with the routed experts on an expert-data-parallel mesh, at ep2 over two ranks.
_set_sharding_config runs on the config tree, so what it declares reads back without a mesh. Pins the routed-expert weights to Shard(0) on the expert axis and pins enable_sp to both axes rather than one: with EP on, TP is a token axis inside the MoE region, and declaring SP off enable_ep alone asks for a redistribution DTensor rejects at the first step, with a placement error that does not name this call site.
The CPU unit-test workflow collects tests/unit_tests/cpu, not the top level, so the declaration test would have sat there un-run; move it. The ep2 cell declares use_real_pg because what it covers is the token all-to-all; under Fake PG the dispatch is a no-op and the cell would pass without exercising it.
This branch is the expert-parallel PR and tensor parallel is not on it -- the parallelize entry still refuses TP -- so _set_sharding_config loses its enable_tp parameter, the SP derivation that only matters when both axes are on, and the test that pinned that derivation. All of it returns with the TP PR, where it can be reviewed against the axis it serves. Also: the dispatcher comment shrinks to the two facts a reader needs, the spmd_types import moves to the third-party block where every other file puts it, and moe.py's single deleted blank line is restored so the file leaves the diff entirely.
7709351 to
d7c884b
Compare
Same shape the integration branch settled on: the text flavor overrides the model spec, the vocabulary size that follows from it, and the dataloader, and inherits everything else instead of restating it. Verified configuration- identical -- 4810 and 4678 fields compared over the union of both key sets, zero differences.
Review ask on the EP PR, following qwen3_5/sharding.py. Declarations only: set_expert_parallel_sharding_config works on the config tree with no mesh or device in sight, which is also what lets the CPU unit test read back what it declared. model.py keeps the one call under its ep>1 gate and loses the sharding imports.
…avor goes Review ask: apply EP to kimi_k3_debugmodel instead of introducing a text-only flavor. EP touches neither the sequence nor the tower, so nothing in this PR needs the text variant: the CI cell, the recipe and the sharding unit test all move to the multimodal flavor upstream already ships, and the flavor plus its model-registry entry leave this branch. Verified before the switch: ep2 and ep4 train on the multimodal flavor (exit 0).
Review ask: the standalone file goes. The two checks keep their value -- the sharding config is set on the config tree and constructing configs directly has dropped declarations invisibly before, so plain-dp-leaves-the-tree-alone and EP-shards-the-expert-axis are worth pinning without a GPU -- but they live in tests/unit_tests/test_kimi_k3.py now, the file the original K3 PR created, rather than establishing a per-model sharding-test file this repo does not otherwise have.
Review ask: no separate feature cell. The model test kimi_k3_mm_fsdp becomes kimi_k3_mm_fsdp+ep -- same recipe with expert_parallel_degree 2 added, same 2 GPUs -- and the OverrideDefinitions block in features.py plus its recipe go. EP is exercised where the model is already exercised.
…ng import at top level config_registry.py leaves the diff entirely now that the text flavor is gone. The sharding import hoists to module level, matching how the CP branch imports from its sharding.py; sharding.py only references the model under TYPE_CHECKING so there is no cycle. One whitespace-only line in test_kimi_k3.py goes before pre-commit flags it.
|
Thanks a lot for reviewing @acisseJZhong @shuhuayu ! I have addressed the comments and rerun the evidence matrix using the full multi-modal debug flavor, will paste the result and push fixes very soon! Given that this PR is jointly splited together with the other 2 PRs for CP and PP and they also used the text only flavor (which we want to remove now), I will also rerun all of the parallelism numerical runs for 3 PRs evidence using the standard multi-modal one and remove text only debug model in all places, there might be a tricky part is that since the ViT parallelism will come later (Dynamic CP, PP DEP), so in these earlier PRs, the multi-modal debug flavor will have the ViT as non-Parallelized (PP case is special due to model layer splitting and we can discuss there instead, since this PR is for EP) |
Review follow-up: not wanted in test_kimi_k3.py either. Removed; the file is byte-identical to upstream again and EP coverage rests on the fsdp2 x ep2 model integration test. The silent-skip hazard the checks pinned (a dropped declaration trains all-to-all routing against unsharded weights) closes for good when Module.parallelize's None check becomes the assert its TODO promises.
Review feedback: no hardcoding. model_registry takes moe_comm_backend (default standard) and threads it through the flavor builders to make_token_dispatcher_config, so any core backend -- standard, deepep, hybridep, minimal_async_ep -- is selectable per spec exactly as deepseek_v3 selects it.
update_ep_token_dispatcher_config gave DeepEP, HybridEP and MinimalAsyncEP hidden_dim = model dim. The rows those dispatchers carry are the routed experts' input rows, which is the model dim on deepseek_v3 and qwen3 but the latent width on Kimi K3 (routed_down runs before the dispatch), so MinimalAsyncEP's receive buffer came back 1024 wide against 512-wide weights and the grouped GEMM failed on the contraction dim. Read the width from routed_experts.inner_experts.dim; unchanged where the two agree.
… EP update helper stops filling it
|
PS. the above 3 conflict files especially the kimi_k3/model.py is because upstream has moved fla KDA from torchtitan into Attention Gym in a fused SM100/103 impl, which should not block the EP change itself as it's irrelevant. I am adding the fla KDA / KCP back to Attention Gym in meta-pytorch/attention-gym#421, the PR evidence is based on fla KDA code in torchtitan, can do a full rebase and rerun all evidence matrix once Attention Gym has non-SM100/103 KDA backend added |
| comm_backend: str, | ||
| non_blocking_capacity_factor: float | None = None, | ||
| hidden_dim: int | None = None, | ||
| hidden_dim: int, |
There was a problem hiding this comment.
thanks! did you make sure all the other call cites pass in this value? also nit: move hidden_dim before non_blocking_capacity_factor as now it's required?
There was a problem hiding this comment.
Sure, moved the argument position as suggested.
Yes, all four already pass it.
The shared factory make_routed_experts_config passes the model dim (deepseek_v3, qwen3, qwen3_5, and the transformers backend go through it), gpt_oss passes its dim directly,
Kimi K3 passes latent_dim, the width its routed experts actually consume.
quantization/utils.py rebuilding a HybridEP config, forwards dispatcher.hidden_dim.
… call-site condition
Three resolutions. models/utils.py's get_moe_model_nparams_and_flops split upstream into delta_rule_flops_per_token, get_nparams_and_active_nparams and quadratic_attention_flops_per_token, so the import follows the new names. The Kimi K3 integration cell moved to the B200 lane in the CI reorg, so the ep2 cell and its recipe come out of the generic lane here and go to a follow-up that asks the lane owner where the EP cell belongs.
|
Thanks for your approval Jessica! Have rebased to latest main and since the KDA in Attention Gym is only supporting fused B200/B300, I will open a new PR to add the EP K3 debug model to CI over there, the current EP CI in this PR has no hardware available. cc @shuhuayu could you take a look and approve/merge if there is no other concerns? Thank you! |
|
shuhua is on PTO this week. I will ask @tianyu-l to stamp this PR for you to merge. For CI test, we have B200 CI added https://github.com/pytorch/torchtitan/pull/4379/changes#diff-39fae36ded83ad7af9c234c004db6bab0aa2bec236d3162c2814635cbb98780f |
|
Sure let me add a small follow up PR soon on the CI for EP once this is merged, thanks again! |
|
[Irrelevant with EP] Hi Jessica @acisseJZhong, Also saw you will review the PP PR #4312 , |
| from torchtitan.models.kimi_k3.model import KimiK3Model | ||
|
|
||
|
|
||
| def set_expert_parallel_sharding_config( |
There was a problem hiding this comment.
nit: current convention is to call it set_kimi_k3_sharding_config
There was a problem hiding this comment.
Rebased and fixed, thanks Tianyu!
# Conflicts: # torchtitan/models/kimi_k3/__init__.py
|
Thank you so much for all maintainers’ review! Are we ready to merge it? |
|
Thank you all so much! So excited and looking forward to other features PR collaborations for K3! |
Summary
Enables expert parallelism for Kimi K3 on the existing all-to-all token dispatcher. Expert parallel comes off the unsupported list; the dispatcher backend is a spec parameter,
moe_comm_backend, threaded frommodel_registrytomake_token_dispatcher_configthe way deepseek_v3 and gpt_oss do it:standard(PyTorch all-to-all) by default,deepep,hybridepandminimal_async_epselectable as on those models. The tables below are measured onstandard. MoonEP (the report's balanced EP with online redundant-expert planning) is not here; it needs its own dispatcher and backend.EP Design
Design points
set_moe_sharding_configdeclares the routed-expert layout,w1_EFD S(1), w2_EDF S(2), w3_EFD S(1), on the expert axis (sharding.py:26-46,set_expert_parallel_sharding_config).set_decoder_sharding_configsits above it so the activations reaching the MoE boundary are DTensors that can be redistributed onto the expert mesh.efsdp, that excludes the expert axis and hands it toapply_fsdp_to_decoderwithep_degree(parallelize.py:67-69,parallelize.py:104): the shapedeepseek_v3already resolves, so expert parameters shard on(dp_shard x cp x tp) / epand everything else on the full data axis.expert_parallel_degree > 1none of this executes.K3 EP runs:
To reproduce, from the torchtitan checkout root on this branch, 8 GPUs. Every cell loads the same seed checkpoint; run each cell twice and read the second run (a cold compile cache moves step 1). The runner we used, with the seed-load assertion and a disk gate, is https://github.com/QIU023/torchtitan_attention_residual/blob/611385d4e123d4d0527c6d08b06f8d701bb63e21/phase13_k3like_48b_posttrain/matrix_scripts/mx3.sh.
EP shards experts inside the data axis, so each cell is compared against the pure-data-parallel run at the same world size.
kimi_k3_debugmodel, seed 42,--debug.deterministic, one seed checkpoint loaded by every cell; at step 2 the EP cells are 3.3e-3, 9.0e-3 and 1.6e-5 from their own-degree baseline, against 1.7e-2, 2.5e-2 and 5.2e-2 for the dp2, dp4 and dp8 rows measured the same way against dp1 -- sharding the experts moves the loss less than changing the data-parallel degree does, at every degree:Changed files
CI/CD Coverage
The existing kimi_k3 model integration test becomes fsdp2 x ep2 on the same 2 GPUs.
Numerical Correction run with unmerged upstream grad-norm precision forced to FP32
The same matrix with the grad-norm reduction carried in float32 (#4135, a separate change not on this branch): dp1, dp4 and ep4 move (largest 2.0e-2 at step 3, on the dp1 baseline itself) and the other four cells are bitwise unchanged. The total norm is reduced over an expert group and a non-expert group separately, and which cells cross a bf16 rounding boundary shifts with what is in the groups -- the vision tower's parameters are part of the non-expert group here.
EP backend verify result
2 x H100 SXM (NVLink), torch 2.15.0.dev20260827+cu130, DeepEP v2 at the commit CI pins (
01dc3aa).kimi_k3_debugmodel, seed 42,--debug.deterministic, one seed checkpoint loaded by every cell. MinimalAsyncEP requires full activation checkpointing, so astandardfull-AC row isolates that.hybridepis not run: it lives on DeepEP'shybrid-epbranch and targets GB200 / NVL72.The backend is a
model_registryparameter rather than a flavor, so the cells select it in a configuration function rather than on the command line:Re-measured on the review-round head (
hidden_dimset at construction): dp2,standardandstandardfull-AC reproduce the rows above to every printed digit, so the dispatcher-config change is numerically inert.standardprints dp2's step-1 loss to every digit and its full-AC twin matches it through step 10;deepepdiffers by ordinary backend arithmetic.minimal_async_ep's step-3 gap is an upstream MinimalAsyncEP bug, not K3's: the expert GEMM saves a view of the recycled receive buffer that the combine backward overwrites, so the routedw1_EFD/w3_EFDgradients are lost; the one-line owned-dispatch fix goes in a separate PR, and with it the same cell is back in the noise band.