Repository navigation
[kimi_k3] Run Dist-MoE through Kimi K3's pipeline stages - #6049
Conversation
d31f74f to
0dfd3c2
Compare
0dfd3c2 to
19aab00
Compare
19aab00 to
aeb6e3b
Compare
aeb6e3b to
2e33d6e
Compare
|
@claude review |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging -- The PR fixes both stated failures inside the K3 folder: K3 now declares static (hidden, delta) metadata, and the AttnRes stage enters the Dist-MoE forward context itself. The remaining item is deleting the dynamic-inference path that this PR makes unreachable. A maintainer still needs to review, since torchtitan/distributed/pipeline_parallel.py makes two of its symbols public.
What this PR does. pipeline_kimi_k3 now builds complete per-stage metadata before it swaps core's stages for AttnResPipelineStage:
- The first stage takes token IDs as input, and the last stage outputs logits (or hidden states under chunked loss).
- Every boundary between stages carries
hidden_TDplusdelta_TND, where N is the number of blockslayout.delta_to_send(i)sends. - The token count comes from core's
build_decoder_stage_io, so it is CP-local, and also TP-local under sequence parallelism.
With complete metadata, PyTorch skips the serial inference pass. AttnResPipelineStage also stores the Dist-MoE forward-context factory and enters it around the model call in its own forward_one_chunk.
Example.
K3, CP2, 128 tokens per microbatch, PP2 x 2 stages per rank (Interleaved1F1B), Dist-MoE
before: rebuilt stages carry no metadata -> one serial fwd+bwd runs over all
stages on uninitialized inputs before step 1 (timed out at K3 scale);
forward_one_chunk never enters Dist-MoE's context -> no activation slot
after: stage 1 input_args = (hidden_TD[64, D], delta_TND[64, n_0, D]),
where n_0 = len(layout.delta_to_send(0)); no inference pass;
model call runs inside ctx(PipelineStageInfo(stage_index=1, microbatch_index=mb))
SP with no decoder layer on stage 0 -> ValueError (the boundary would carry
TP-replicated embeddings, which the static shape does not describe)
Must fix
tests/unit_tests/cpu/models/kimi_k3/test_kimi_k3_pp_block_grads.py:249-- Production can no longer reach dynamic inference. Make declared metadata the only mode: deleteAttnResPipelineStage._compute_outputs(stage.py:350) and the frozen-delta branch (stage.py:257-264), require the metadata in__init__, and switch the tests to declared metadata instead of adding it as a third and fourth run. Details are in the inline comment.
Should consider
torchtitan/models/kimi_k3/pipeline_parallel/stage.py:106-- Add aTODOwith an upstream issue link for the copiedregister_forward_context, and fix the "same contract" docstring if upstream allows several contexts. Details are in the inline comment.
Questions
- Any large model running PP on a real process group pays the same serial inference pass that timed out here; it is not specific to K3. Do the maintainers want core to declare static decoder metadata on real process groups too (as a follow-up, not in this PR)?
Details
- Necessity: Both problems exist on the base branch. Dist-MoE's
runtime.py:407registers its context throughstage.register_forward_context, but the base class only enters that context inside theforward_one_chunkthat K3 replaces. Real process groups previously always inferred metadata, because core buildsstage_ioonly for the fake backend (pipeline_parallel.py:111). - Metadata shapes: I checked them against
KimiK3Model.forwardandKimiK3TransformerBlock.forward. Non-last stages return(h_TD, block_residual_TND), both in the activation dtype. Mixed precision always applies here, becauseresolve_fsdp_meshkeeps FSDP even at size 1, soparam_dtypeis the right dtype. The ValueError for SP when stage 0 has no layer matches the model:h_TDis TP-replicated after embedding. The b200 entrykimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4(TP2 + SP) now runs on declared metadata. Its stage 0 still holds 2 layers (17 layers in total, 8 stages), so it does not hit the new error. - Mechanical changes: making
build_decoder_stage_io/DecoderStageIOpublic and updating the two callers intest_pipeline_parallel.py. - Integration test: extending the existing CP Dist-MoE entry with PP2 (4 -> 8 GPUs) follows
rules/tests.md.
Not verified:
- GPU runs.
- Whether PyTorch calls
_compute_outputsanywhere other than dynamic inference. - Whether upstream
register_forward_contextaccepts more than one context.
| cached, cached_sent = self._run_pipeline(split, dtype, cache=True) | ||
| naive, naive_sent = self._run_pipeline(split, dtype, cache=False) | ||
| # Declared metadata, as pipeline_kimi_k3 builds it, instead of | ||
| # inferring it by running the stages. | ||
| declared = [ | ||
| self._run_pipeline( | ||
| split, dtype, cache=cache, static_metadata=True | ||
| )[0] | ||
| for cache in (True, False) | ||
| ] | ||
| self.assertLess(cached_sent, naive_sent) | ||
| for step in range(STEPS): | ||
| ref_grads, ref_losses = reference[step] | ||
| for grads, losses in (cached[step], naive[step]): | ||
| runs = (cached, naive, *declared) |
There was a problem hiding this comment.
With this PR, production never runs dynamic inference. pipeline_kimi_k3 is the only builder of AttnResPipelineStage, and it always passes complete metadata through _swap_in_attn_res_stages. So the inferred-metadata runs here (cached, naive), and all of test_forward_only_eval_between_steps, now test a path that only tests use. They are also the only reason two pieces of production code still exist:
AttnResPipelineStage._compute_outputs(stage.py:350-375), which is dynamic inference's forward. It also never enters the Dist-MoE forward context, as the newregister_forward_contextdocstring admits.- The frozen-delta branch in
_retrieve_recv_grads(stage.py:257-264). It checksoutputs_meta[1].requires_grad, which is alwaysTruewith declared metadata.
This also doubles the work per subtest, from 2 pipeline runs to 4.
Smallest fix: make declared metadata the only mode.
- Build
stage_metadataunconditionally in_run_pipelineand dropstatic_metadata, keeping just thecachedandnaiveruns. - Delete
_compute_outputsand the frozen-delta branch. - Raise in
AttnResPipelineStage.__init__wheninput_args/output_argsare missing, so nobody can build a stage that would silently run inference without the Dist-MoE context.test_forward_enters_registered_pipeline_contextwould then pass**_linear_stage_metadata(1)[0].
That is roughly 40 lines removed. If upstream calls _compute_outputs from anything other than dynamic inference (I could not check the installed PyTorch), keep it and say so in a comment.
| def register_forward_context( | ||
| self, | ||
| context_factory: Callable[[PipelineStageInfo], AbstractContextManager[None]], | ||
| ) -> RemovableHandle: | ||
| """Wrap each forward of this stage in ``context_factory(info)``. | ||
|
|
||
| Same contract as ``PipelineStage.register_forward_context``. PyTorch enters | ||
| the context in the ``forward_one_chunk`` this class replaces, so the stage | ||
| keeps and enters it itself. Dynamic metadata inference does not enter it; | ||
| ``pipeline_kimi_k3`` always declares static metadata. | ||
| """ | ||
| if self._forward_context_factories: | ||
| raise RuntimeError( | ||
| f"stage {self.stage_index}: a forward context is already registered" | ||
| ) | ||
| handle = RemovableHandle(self._forward_context_factories) | ||
| self._forward_context_factories[handle.id] = context_factory | ||
| return handle |
There was a problem hiding this comment.
This copies PipelineStage.register_forward_context only because K3 replaces forward_one_chunk, and that is where PyTorch enters the registered contexts. CLAUDE.md principle 3 asks for a TODO with an upstream issue link here. Two possible upstream fixes: enter the forward context around a public hook that subclasses can keep (for example, the call to forward_maybe_with_nosync), or expose the registered factories. Either one lets this copy be deleted.
Also, the docstring says "Same contract as PipelineStage.register_forward_context", but this version raises on a second registration. If upstream allows several contexts on one stage, that claim is wrong. Either match upstream, or say in the docstring that only one is allowed.
2e33d6e to
22d0bdd
Compare
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline() starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE and on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline() starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE and on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline_flash_next (pipeline_parallel.py) starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE, and stages build on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support, so the text debug recipe takes an optimizer argument) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline_flash_next (pipeline_parallel.py) starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE, and stages build on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support, so the text debug recipe takes an optimizer argument) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline_flash_next (pipeline_parallel.py) starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE, and stages build on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support, so the text debug recipe takes an optimizer argument) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline_flash_next (pipeline_parallel.py) starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE, and stages build on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support, so the text debug recipe takes an optimizer argument) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline_flash_next (pipeline_parallel.py) starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE, and stages build on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support, so the text debug recipe takes an optimizer argument) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline_flash_next (pipeline_parallel.py) starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE, and stages build on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support, so the text debug recipe takes an optimizer argument) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
Non-final stages send all four residual streams; the final stage owns the stream mixer, final norm and LM head. Every stage receives original token IDs and document positions, and the first local model part prepares PLE routing through a weak reference when an interleaved schedule puts the table on a later local part. - Static stage metadata. pipeline_llm takes an optional stage_io, and build_decoder_stage_io / DecoderStageIO become public. Flash-Next's pipeline_flash_next (pipeline_parallel.py) starts from core's decoder boundaries and declares the hidden boundary as [T, num_streams * D], so PyTorch skips its metadata-inference forward. That forward ran every stage on uninitialized hidden states, whose routing could collapse onto a few experts and overflow Dist-MoE's scratch. With declared boundaries, PP works with Dist-MoE, and stages build on fake process groups. A split the static metadata cannot describe raises. - The rename duplicates #6049's; whichever lands second drops it. - Remaining bans, at build time: zero-bubble and CSV schedules (under full remat the split weight-gradient pass reads the shared MoE routing remat region as an unrecomputed placeholder; TODO), multimodal flavors (TODO), and a stage split that separates the mixer, norm and LM head. - The DistMuon policy now works under PP. OptimizersContainer built one optimizer per (model part, config) and raised when a pattern matched nothing in a part, but the policy's PLE Adam pattern matches only the part holding layers.1 and its DistMuon pattern misses a tok_embeddings-only part. The container now skips empty (part, config) pairs and raises only when a pattern matches nothing on every PP rank: one all-reduce over the PP group at build time, and the old local check without PP. A fake-PP process holds one stage and skips the check. DistMuon itself already ignores compute layouts for other stages and skips empty buckets. Tests: B200 FSDP2+TP2+SP+EP4+PP2 (all-to-all, AdamW; DistMuon has no TP support, so the text debug recipe takes an optimizer argument) and FSDP2+EP2+PP2 with the DistMuon policy, Dist-MoE and accelerator graphs, both Interleaved1F1B with full remat and PLE on a later local part. A CPU test covers the container's skip-and-raise rule over two model parts, with and without a PP group. Numerics (GB300, seed 42, deterministic, shared seed checkpoint): - FSDP2+TP2+EP4+PP2 against the same config without PP (4 accumulation microbatches instead of 4 PP microbatches, same data): step 1 identical (loss 7.73923, grad_norm 5.0487); later steps differ only by gradient summation order (step 10 loss 5.44578 vs 5.44624). - Debug Dist-MoE PP tracks all-to-all PP on the same mesh: step-1 loss 7.73953 vs 7.73918. - The TP2+SP PP config passes. The 125B recipe at FSDP8+EP8+PP2 gets past stage setup, then runs out of memory at step 2 on the PLE-holding stage, as the memory model predicts.
d871371 to
dfa481c
Compare
fb99f53 to
c6a7865
Compare
c6a7865 to
26d8ee6
Compare
7dc1c14 to
833279e
Compare
833279e to
f13cdda
Compare
|
all tests passed since pytorch/pytorch#205562 is now in pytorch nightly, now merge. |
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
Part **11/n** of the Kimi K3 training stack: bottom of a two-PR stack:
this PR -> #6049 (Kimi K3 PP stages).
## Why
Kimi K3's routed experts use bounded SiTU-GLU (`SiTUGLU.Config(beta,
linear_beta)`). `DistMoeTransform` only translates SwiGLU and clamped
SwiGLU, so Kimi K3 cannot use Dist-MoE at all:
```python
config = kimi_k3_debugmodel(...)
apply_transforms(config, [DistMoeTransform()])
# main: TypeError: Dist-MoE supports SwiGLU.Config or ClampedSwiGLU.Config; got SiTUGLU.Config
```
The native Dist-MoE kernels already implement SiTU-GLU
(`activation="situ_glu"`, `situ_glu_gate_beta`, `situ_glu_up_beta`);
only the TorchTitan translation is missing.
## What changed
- `config/transform/dist_moe.py`: translate `SiTUGLU.Config` to
`activation="situ_glu"` with `beta -> situ_glu_gate_beta` and
`linear_beta -> situ_glu_up_beta`. `linear_beta=None` (unbounded up
projection) raises, since the native kernel requires both bounds.
- `dist_moe/routed_experts.py`: add `"situ_glu"` and its two bounds to
`DistMoeRoutedExperts.Config`; validate that each activation sets
exactly its own parameters.
- `dist_moe/runtime.py`: pass the bounds to the native context config.
- `torchtitan_recipes/tests/models/kimi_k3.py`:
`kimi_k3_debugmodel_dist_moe_mxfp8` debug recipe (varlen attention),
used by the integration test below.
- `torchtitan_recipes/dist_moe.py` (mechanical move): `require_dist_moe`
and `dist_moe_runtime_config` move out of
`torchtitan_recipes/models/deepseek_v3.py`, where they were private, so
the Kimi recipes don't import another module's `_private` helpers.
Callers in the DeepSeek V3 recipes and `tests/rl/alphabet_sort.py` are
updated; the bodies are unchanged.
- `tests/integration_tests/b200.py`: Kimi K3 MXFP8 Dist-MoE with FSDP2 +
EP2 + CP2 (4 GPUs, real PG). CP maps KDA to `ContextParallelInnerKDA`
and MLA to `UlyssesMLAAttention`, which keeps the recipe on varlen
attention and needs no load balancer. The vision encoder is not
context-parallel: each CP rank encodes the full image input, as in every
VLM decoder. Type checking stays off, as for the DeepSeek Dist-MoE
entries: the MXFP8 Dist-MoE kernel's autograd function is not registered
with spmd_types (it fails with type checking on). BF16 SiTU-GLU is
covered by the GPU numerics test against the stock experts.
- `tests/integration_tests/b200.py` (reorder only): K3 configs and
entries are grouped together, which moves the two llama3 functions below
them with unchanged bodies.
- `dist_moe/README.md`: document SiTU-GLU support and the Kimi recipe
location.
## User-facing changes
| Before | After |
| --- | --- |
| `DistMoeTransform` rejects `SiTUGLU.Config` | Translated to native
`situ_glu`, BF16 and MXFP8 |
| No Kimi K3 Dist-MoE recipe | `kimi_k3_debugmodel_dist_moe_mxfp8` |
## Numerics
No change to existing activations. New SiTU-GLU path vs stock experts
(`test_bf16_matches_stock_situglu`, real EP2 on 2 GPUs): output and the
four gradient families (input, scores, W13, W2) match at the existing
BF16 tolerance. The test uses bounds (0.25, 0.1) that saturate tanh at
its input scale; with Kimi's (4.0, 25.0), tanh is nearly linear there
and SiTU-GLU would be indistinguishable from SwiGLU. Giving only the
native side (4.0, 25.0) makes 96% of output elements mismatch.
## Testing
Run with an env that has the `dist_moe` package (without it the Dist-MoE
tests are skipped).
| Check | Hardware | Result |
| --- | --- | --- |
| `tests/unit_tests/cpu/models/common/test_dist_moe.py` | CPU (1 GPU
visible, for the MXFP8 capability check) | pass |
| `tests/unit_tests/gpu/models/common/test_dist_moe.py` | 2x GB300 | 4
passed, including the new SiTU-GLU case |
| Integration `kimi_k3_dist_moe_fsdp_ep_cp` (MXFP8, FSDP2 + EP2 + CP2) |
4 GPUs | not run locally (only 3 free GPUs); relies on CI |
| MXFP8 recipe with CP2 + EP2 sharing the CP axis (2-GPU proxy of the CI
entry) | 2x GB300 | completes 4 steps |
| MXFP8 recipe with FSDP2 + EP2 (the previous CI entry) | 2x GB300 |
completes 4 steps |
New tests and what they catch:
- `test_transform_preserves_situglu_configuration`: both expert
precisions carry the model's bounds into the native config. It uses
bounds other than the annex defaults (4.0, 25.0), so a bound dropped
anywhere on the way fails.
- `test_transform_rejects_unbounded_situglu_up_projection`: an unbounded
SiTU-GLU fails at transform time instead of silently changing math.
- `test_bf16_matches_stock_situglu` (GPU): native SiTU-GLU, with bounds
that saturate tanh, matches the stock implementation; it fails if the
kernel ignores either bound.
Pre-commit passes on the changed files.
f13cdda to
1654ea9
Compare
## Summary (human-written) Part **14/n** of the Kimi K3 training stack. Independent PR on `main`: the pieces it composes are all on `main` now (SiTU-GLU Dist-MoE #5684, Kimi K3 Dist-MoE pipeline stages #6049, per-block remat #6104). ## Why TorchTitan has Kimi K3 debug recipes only. There is no recipe that runs the full 93-layer model with Dist-MoE, DistMuon and pipeline parallelism together, so the configuration used for full-scale throughput runs lives outside the repo. ## What changed `torchtitan_recipes/models/kimi_k3.py` adds one text-only 4K MXFP8 recipe: | Recipe | Hardware | PP / VPP / EP / FSDP | Microbatches / update | Tokens / update | | --- | --- | --- | ---: | ---: | | `kimi_k3_dist_moe_mxfp8_gb200_512` | 512 GB200 | 8 / 1 / 64 / 64 | 64 | 16,777,216 | - FP32 parameters, gradients and optimizer state with BF16 compute views; only routed-expert GEMMs use MXFP8 (Dist-MoE). Interleaved1F1B with one explicit chunk per rank (seven 12-layer chunks and a final 9-layer chunk), CUDA-graph forward/backward, DistMuon, FSDP parameters kept unsharded across forward/backward. - Expert routing uses core's `RoundRobinTokenChoiceTopKRouter`, so this is a **throughput recipe, not learned-router training**; gate scores and their gradients stay learned. KDA uses core's default kernel selection. - `torchtitan/models/kimi_k3/README.md`: a short "Full-Scale Recipe" section with measured throughput for forced and learned routing. - The K3 DistMuon optimizer builder moves from the K3 debug recipe to `torchtitan_recipes.models.kimi_k3.dist_muon_optimizer` and is simplified (one layout helper, one table per layer type, one pass over layers); the K3 and K3.1 debug recipes and the GPU test import it from there. The full-scale recipe keeps its own private copy of the expert compute layout helper instead of importing it from the K2.7 debug recipe. - CI: the B200 job, which installs Dist-MoE, also runs the recipe-build test (`test_full_recipe_selects_dist_moe_before_graph_validation`); it skips wherever Dist-MoE is not installed. ## Numerics No change to existing recipes. The simplified optimizer builder produces identical optimizer configs (Muon pattern, learning rates, ordered buckets and ordered per-FQN compute layouts) for the K3 debug, K3 debug MXFP8, K3.1 debug and full-scale recipes, and for the debug model at EP=1 and EP=2. ## Testing | Check | Result | | --- | --- | | `tests/unit_tests/cpu/recipes/test_kimi_dist_moe.py` (Dist-MoE selection before graph validation) | pass | | `tests/unit_tests/cpu/models/kimi_k3/` | pass | | `tests/unit_tests/gpu/models/kimi_k3/test_kimi_k3.py -k dist_muon` (1 GPU) | pass | | Kimi K2.5 / K3 / K3.1 debug recipes and the 512-GPU recipe build | pass | The README's forced-routing row (1,009.5 tokens/s/GPU, 651.44 model TFLOP/s/GPU, 158.41 GiB maximum reserved, twelve updates on 512 GB200) was measured with this recipe. The learned-routing row (971 tokens/s/GPU, 626.52 model TFLOP/s/GPU) used Kimi K3's default router with Dist-MoE scratch capacity 2.0.
…rops the local PP forward-context fix in favor of it) # Conflicts: # torchtitan/models/kimi_k3/pipeline_parallel/stage.py
Summary (human-written)
Part of the Kimi K3 training stack, stacked on #5684 (SiTU-GLU Dist-MoE).
Why
Kimi K3 rebuilds every PP stage as
AttnResPipelineStage(to carry AttnRes block stacks). With Dist-MoE under PP, that rebuild breaks two things onmain:AttnResPipelineStage.forward_one_chunkoverrides the base method and calls the model directly, so the contexts are never entered.(hidden, delta)carriers anyway. So PyTorch infers metadata by running one serial forward and backward through every stage before step 1, on uninitialized inputs:Example (K3 with CP16, 64K tokens per microbatch):
What changed
kimi_k3/pipeline_parallel/__init__.py:_build_attn_res_stage_metadatadeclares every stage's inputs, outputs and their gradients on the meta device. It reuses core's decoder boundaries: token IDs into the first stage, and logits (or hidden, under chunked loss) out of the last. Each boundary between stages is(hidden_TD, delta_TND), withNfrom the block layout.hidden_TD, so it is CP-local and sequence-sharded under SP. K3 declares this metadata on every backend.ValueError.kimi_k3/pipeline_parallel/stage.py:AttnResPipelineStageoverrides the publicregister_forward_context. It keeps the factory itself and enters it in its ownforward_one_chunkwith the stage and microbatch index; PyTorch enters registered contexts only in the baseforward_one_chunk, which this class replaces. No private PyTorch API is used.input_argsandoutput_args, so it can never fall back to dynamic inference, which would run outside its block routing and forward context._compute_outputsand_compute_input_grads(PyTorch calls them only from metadata inference), and the frozen-delta branch in_retrieve_recv_grads(declared metadata always gives the delta a gradient channel; PyTorch'sstage_backwardskips outputs that don't require grad).distributed/pipeline_parallel.py(mechanical):build_decoder_stage_ioandDecoderStageIObecome public, so K3 reuses core's boundary shapes instead of duplicating them.tests/integration_tests/b200.py: [dist_moe] 11/n Support Kimi K3 SiTU-GLU experts #5684's MXFP8 Dist-MoE entry adds PP2 (Interleaved1F1B, 4 microbatches) and becomes FSDP2 + EP2 + CP2 + PP2 on 8 GPUs. With CP2, the PP carriers are CP-local, which checks the static metadata's token count end to end.Alternatives considered
Numerics
No arithmetic change; the stage only gets metadata it used to infer.
test_kimi_k3_pp_block_gradsnow runs the pipeline with declared metadata, aspipeline_kimi_k3builds it, with and without the AttnRes cache. Every block gradient and loss matches the single-device reference bitwise, the same check the inferred-metadata runs passed before.Testing
tests/unit_tests/cpu/models/kimi_k3/,distributed/test_pipeline_parallel.py,models/common/test_dist_moe.pykimi_k3_dist_moe_fsdp_ep_cp_pp(MXFP8, FSDP2 + EP2 + CP2 + PP2)New and extended tests and what they catch:
test_kimi_k3_pp_block_gradsandtest_forward_only_eval_between_steps(switched to declared metadata): training and eval match the single-device reference; they fail if any boundary shape or gradient flag is wrong.test_forward_enters_registered_pipeline_context: the stage enters the forward context with the right stage and microbatch index, and stops once its handle is removed.TestStageSwap(extended): the rebuilt stage receives the declared metadata, so dynamic inference is off.Pre-commit passes on the changed files.