Skip to content

[Kimi K3] Expert Parallelism support - #4314

Merged
tianyu-l merged 26 commits into
pytorch:mainfrom
QIU023:k3_ep
Sep 3, 2026
Merged

tianyu-l merged 26 commits into
pytorch:mainfrom
QIU023:k3_ep

Conversation

@QIU023

@QIU023 QIU023 commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

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 from model_registry to make_token_dispatcher_config the way deepseek_v3 and gpt_oss do it: standard (PyTorch all-to-all) by default, deepep, hybridep and minimal_async_ep selectable as on those models. The tables below are measured on standard. 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_config declares 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_config sits above it so the activations reaching the MoE boundary are DTensors that can be redistributed onto the expert mesh.
  • parallelize builds the expert-data-parallel mesh, efsdp, that excludes the expert axis and hands it to apply_fsdp_to_decoder with ep_degree (parallelize.py:67-69, parallelize.py:104): the shape deepseek_v3 already resolves, so expert parameters shard on (dp_shard x cp x tp) / ep and everything else on the full data axis.
  • Without expert_parallel_degree > 1 none 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.

COMMON="-m torchtitan.train --module kimi_k3 --config kimi_k3_debugmodel --debug.seed 42 --debug.deterministic --training.num-tokens-per-train-step 8192 --training.num-tokens-per-microbatch-per-dp-rank 256 --checkpoint.enable"
torchrun --nproc_per_node=1 $COMMON --training.steps 1 --parallelism.data_parallel_shard_degree 1 --checkpoint.create_seed_checkpoint --dump-folder seed
cell() { d=$1; n=$2; shift 2; rm -rf $d; mkdir -p $d; cp -r seed/checkpoint $d/; torchrun --nproc_per_node=$n $COMMON --training.steps 10 --metrics.log_freq 1 --checkpoint.interval 100000 "$@" --dump-folder $d; }
D="--parallelism.data_parallel_shard_degree"; E="--parallelism.expert_parallel_degree"
cell dp1 1 $D 1;  cell dp2 2 $D 2;  cell ep2_fsdp2 2 $D 2 $E 2
cell dp4 4 $D 4;  cell ep4_fsdp4 4 $D 4 $E 4;  cell dp8 8 $D 8;  cell ep8_fsdp8 8 $D 8 $E 8

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:

cell world step 1 step 3 step 10
dp1 1 12.59245 7.46936 3.18111
dp2 2 12.58904 7.61204 3.33502
ep2 x fsdp2 2 12.59108 7.59337 3.29070
dp4 4 12.58372 7.65474 3.24291
ep4 x fsdp4 4 12.58128 7.59719 3.17962
dp8 8 12.60943 8.26416 3.35955
ep8 x fsdp8 8 12.61045 8.38947 3.20613

Changed files

torchtitan/models/common/
  token_dispatcher.py    +4/-1  a hidden_dim set on the dispatcher
                               config wins; model dim is only the default
                               (K3 dispatches the latent stream)
  config_utils.py           +1  the minimal_async_ep factory branch
                               forwards hidden_dim
torchtitan/models/kimi_k3/
  sharding.py              +47  set_expert_parallel_sharding_config: the
                               routed-expert layout (new file, following
                               qwen3_5/sharding.py)
  model.py                  +3  the one call under the ep>1 gate
  __init__.py           +23/-6  moe_comm_backend threads from model_registry
                               to core's dispatcher factory: standard by
                               default, deepep / hybridep / minimal_async_ep
                               selectable as on deepseek_v3
  parallelize.py         +17/-2 the efsdp mesh, ep_degree through to
                               apply_fsdp_to_decoder, expert parallel off
                               the unsupported list, and a comment naming
                               the backends this model runs
tests/integration_tests/models.py       the model test gains ep2
torchtitan_recipes/tests/models.py    its configuration

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.

cell world step 1 step 3 step 10
dp1 1 12.59245 7.62176 3.19563
dp2 2 12.58904 7.61204 3.32351
ep2 x fsdp2 2 12.59108 7.59337 3.28553
dp4 4 12.58372 7.61710 3.23680
ep4 x fsdp4 4 12.58128 7.61100 3.14353
dp8 8 12.60943 8.26416 3.33049
ep8 x fsdp8 8 12.61045 8.38947 3.20156

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 a standard full-AC row isolates that. hybridep is not run: it lives on DeepEP's hybrid-ep branch and targets GB200 / NVL72.

The backend is a model_registry parameter rather than a flavor, so the cells select it in a configuration function rather than on the command line:

# torchtitan_recipes/k3_ep_backends.py
from torchtitan.models.kimi_k3 import model_registry
from torchtitan.models.kimi_k3.config_registry import kimi_k3_debugmodel

def _backend(name: str) -> Trainer.Config:
    config = kimi_k3_debugmodel()
    config.model_spec = model_registry("debugmodel", moe_comm_backend=name)
    return config

def k3_deepep() -> Trainer.Config: return _backend("deepep")
def k3_minimal_async_ep() -> Trainer.Config: return _backend("minimal_async_ep")
BACKEND_COMMON="-m torchtitan.train --module torchtitan_recipes.k3_ep_backends --debug.seed 42 --debug.deterministic --training.steps 10 --metrics.log_freq 1 --training.num-tokens-per-train-step 8192 --training.num-tokens-per-microbatch-per-dp-rank 256 --parallelism.data_parallel_shard_degree 2 --parallelism.expert_parallel_degree 2"
torchrun --nproc_per_node=2 $BACKEND_COMMON --config k3_minimal_async_ep
# DeepEP v2 on a host with no RDMA NIC needs its own environment:
CUDA_HOME=/usr/local/cuda-13.0 NCCL_NVLS_ENABLE=0 EP_DISABLE_GIN=1 EP_REUSE_NCCL_COMM=0 \
  NVSHMEM_REMOTE_TRANSPORT=none NVSHMEM_DISABLE_MNNVL=1 \
  torchrun --nproc_per_node=2 $BACKEND_COMMON --config k3_deepep
cell backend AC step 1 step 3 step 10
dp2 - selective 12.59951 7.45599 3.26481
ep2 x fsdp2 standard selective 12.59951 7.43228 3.30036
ep2 x fsdp2 standard full 12.59951 7.43228 3.30036
ep2 x fsdp2 minimal_async_ep full 12.59768 7.56392 3.29721
ep2 x fsdp2 deepep selective 12.59438 7.46660 3.24408

Re-measured on the review-round head (hidden_dim set at construction): dp2, standard and standard full-AC reproduce the rows above to every printed digit, so the dispatcher-config change is numerically inert.

standard prints dp2's step-1 loss to every digit and its full-AC twin matches it through step 10; deepep differs 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 routed w1_EFD / w3_EFD gradients 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.

QIU023 added 4 commits August 25, 2026 01:34
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.
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 25, 2026
@QIU023
QIU023 marked this pull request as draft August 25, 2026 01:53
@QIU023 QIU023 changed the title [DO NOT review yet, pending final cleanup] Expert Parallelism support for Kimi K3 (text LLM side) [DO NOT review yet, pending final cleanup] Expert Parallelism support for Kimi K3 Aug 25, 2026
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.
@QIU023
QIU023 force-pushed the k3_ep branch 2 times, most recently from 7709351 to d7c884b Compare August 25, 2026 07:00
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.
@QIU023
QIU023 marked this pull request as ready for review August 26, 2026 05:45
@QIU023 QIU023 changed the title [DO NOT review yet, pending final cleanup] Expert Parallelism support for Kimi K3 Expert Parallelism support for Kimi K3 Aug 26, 2026
@QIU023

QIU023 commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

cc @shuhuayu @tianyu-l Kimi K3 text side EP (no MoonEP yet) PR ready for review, please let me know if the above PR summary might be too verbose or if you have any confusion / question and I will answer ASAP!

@QIU023 QIU023 mentioned this pull request Aug 26, 2026
14 of 18 tasks
Comment thread torchtitan/models/kimi_k3/__init__.py Resolved
Comment thread torchtitan/models/kimi_k3/model.py Resolved
Comment thread torchtitan_recipes/tests/features.py Resolved
Comment thread tests/integration_tests/features.py Resolved
QIU023 added 5 commits August 27, 2026 05:23
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.
@QIU023

QIU023 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor Author

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)

QIU023 added 3 commits August 27, 2026 14:48
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.
@QIU023 QIU023 changed the title Expert Parallelism support for Kimi K3 [Kimi K3] Expert Parallelism support Aug 31, 2026
@QIU023

QIU023 commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor Author

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

Comment thread torchtitan/models/kimi_k3/sharding.py Resolved
Comment thread torchtitan/models/kimi_k3/model.py Resolved
comm_backend: str,
non_blocking_capacity_factor: float | None = None,
hidden_dim: int | None = None,
hidden_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.

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?

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.

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.

@acisseJZhong acisseJZhong 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!

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

QIU023 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

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!

@acisseJZhong

Copy link
Copy Markdown
Contributor

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

@QIU023

QIU023 commented Sep 1, 2026

Copy link
Copy Markdown
Contributor Author

Sure let me add a small follow up PR soon on the CI for EP once this is merged, thanks again!

@QIU023

QIU023 commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor Author

[Irrelevant with EP]

Hi Jessica @acisseJZhong, Also saw you will review the PP PR #4312 ,
which has way larger amount and a custom design, no rush and please feel free to ask any questions and happy to provide a detailed explanation and discuss on it together!

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

please rebase

Comment thread torchtitan/models/kimi_k3/sharding.py Outdated
from torchtitan.models.kimi_k3.model import KimiK3Model


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

nit: current convention is to call it set_kimi_k3_sharding_config

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.

Rebased and fixed, thanks Tianyu!

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

@QIU023

QIU023 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Thank you so much for all maintainers’ review! Are we ready to merge it?

@tianyu-l
tianyu-l merged commit 9b5f60c into pytorch:main Sep 3, 2026
14 checks passed
@QIU023

QIU023 commented Sep 3, 2026

Copy link
Copy Markdown
Contributor Author

Thank you all so much! So excited and looking forward to other features PR collaborations for K3!

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.

4 participants