Skip to content

[dist_moe] 11/n Support Kimi K3 SiTU-GLU experts - #5684

Merged
shuhuayu merged 1 commit into
mainfrom
shuhuayu/k3-dm-stack-11
Nov 25, 2026
Merged

shuhuayu merged 1 commit into
mainfrom
shuhuayu/k3-dm-stack-11

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary (human-written)

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:

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.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Oct 29, 2026
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch 2 times, most recently from 6c7a6fb to ccdf6ee Compare October 30, 2026 06:13
shuhuayu added a commit that referenced this pull request Oct 30, 2026
#5674)

Part **1/n** of the Kimi K3 / Dist-MoE training stack. Based on `main`:
the review diff contains only this feature.

human notes:
previously: `distributed/utils.py::init_distributed()` passes
`CommConfig.init_timeout_seconds` to
`torch.distributed.init_process_group()` so the world group has, say, 30
minutes timeout. now, that remains unchanged. Additionally,
`TrainingEngine._initialize_distributed_runtime()` calls
`set_pg_timeouts()` after `ParallelismContext.from_config()`, so the
tracked mesh subgroups get the configured timeout before
model/FSDP/optimizer initialization. this also covers the RL trainer.
without this pr, independently created NCCL subgroups can still use the
default 10-minute timeout even though we configured 30 minutes. the
existing switch to `train_timeout_seconds` after the first step is
unchanged.

## Why

The world process group receives `comm.init_timeout_seconds`, but mesh
subgroups created later do not inherit it. They can retain the
backend-default startup timeout through model initialization and the
first update.

Example: with `CommConfig(init_timeout_seconds=1800)`, the world group
uses 1,800 seconds but a later NCCL subgroup can use its 600-second
default. This change applies the configured startup budget to the groups
tracked by `ParallelismContext` before model/FSDP/optimizer
initialization.

## What changed

- Call the existing `set_pg_timeouts()` helper immediately after
`ParallelismContext.from_config()` in the shared training engine.
- Apply the same call in the TorchFT runtime override.
- Preserve the unconditional post-first-step switch to
`train_timeout_seconds`, including fake backends.
- Add no helper, configuration field, or test. The deleted
forwarding-only mock test is not coverage for the current code.

## User-facing changes

| Configuration | Before | After |
| --- | --- | --- |
| `init_timeout_seconds=1800` | World: 1,800 s; tracked NCCL mesh groups
may use 600 s during startup. | World and tracked mesh groups: 1,800 s
during startup. |
| Default `init_timeout_seconds=300` | World: 300 s; tracked NCCL mesh
groups may use 600 s. | World and tracked mesh groups: 300 s during
startup. |
| After the first update | Existing switch to `train_timeout_seconds`. |
Unchanged. |

Groups created separately outside the context's tracked mesh map,
including optimizer-specific communicators, are not covered by this
call.

## Numerics

No model math, parameter layout, gradient policy, or checkpoint mapping
changes. The existing helper adds one startup barrier/device
synchronization; there is no new per-update synchronization.

## Testing

Rebased onto upstream `ad7a9937b5e57ccadebbb98b3eb14ff139ceb2b3`. The
feature diff is unchanged: ten added lines in the shared engine and
TorchFT override.

```bash
CUDA_VISIBLE_DEVICES='' python -m pytest -q -p no:cacheprovider --tb=short \
  tests/unit_tests/cpu/test_trainer.py \
  tests/unit_tests/cpu/distributed/test_distributed_utils.py
```

Result: **76 passed**. These existing CPU tests do not directly verify
real NCCL subgroup timeout values.

## Known issues / landing gates

All non-type pre-commit checks passed in the preceding review. The three
Pyrefly failures were independently reproduced on unchanged upstream:
missing `torch_checkpointing.checkpoint_writer.CallbackArgs`, its
callback signature mismatch, and optional `video.stream.time_base`
multiplication. No unrelated source or dependency workaround is
included.


## Stack

Bottom of stack; based on `main`. Next:
[#5675](#5675).

<details>
<summary>Full draft stack — review and land in this order</summary>

| Position | Draft PR |
| --- | --- |
| 1/n | [#5674 — [distributed] 1/n Apply initialization timeouts to mesh
process groups](#5674) |
| 2/n | [#5675 — [fsdp] 2/n Expose explicit backward-prefetch
policy](#5675) |
| 3/n | [#5676 — [fsdp] 3/n Support layer-scoped CPU
offload](#5676) |
| 4/n | [#5677 — [optim] 4/n Bound optimizer memory ownership and
allocation lifetimes](#5677) |
| 5/n | [#5678 — [dist_muon] 5/n Support CP and TP storage-to-compute
layouts](#5678) |
| 6/n | [#5679 — [profiler] 6/n Preserve failure context and merge
CUDA-graph streams](#5679) |
| 7/n | [#5680 — [kda] 7/n Preserve graph metadata and expose
chunk-kernel options](#5680) |
| 8/n | [#5681 — [cp] 8/n Add configurable graph-friendly Ulysses
transport](#5681) |
| 9/n | [#5682 — [compile] 9/n Compile MLA assembly and router
postprocessing](#5682) |
| 10/n | [#5683 — [pp] 10/n Make cache release and FSDP chunk lifetimes
explicit](#5683) |
| 11/n | [#5684 — [dist_moe] 11/n Enable Kimi K3 SiTU-GLU training and
pipeline lifecycle](#5684) |
| 12/n | [#5685 — [moe] 12/n Add opt-in shared-expert CUDA stream
overlap](#5685) |
| 13/n | [#5686 — [ac] 13/n Add block-scoped activation
retention](#5686) |

</details>

After the preceding PR lands, rebase the remaining suffix onto updated
main and retarget its next bottom PR to main. Keep the rest stacked; no
automatic landing is requested.
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch from ccdf6ee to 664401a Compare November 4, 2026 00:13
shuhuayu added a commit that referenced this pull request Nov 4, 2026
…tion (#5681)

Part **8/n** of the Kimi K3 / Dist-MoE training stack. Based directly on
`main`; this PR can land independently of the remaining stack.

human notes: fix the nccl ulysses safeguard that uses `Ulysses.Config`
instead of `UlyssesInnerAttention.Config`.

## Why

The existing NCCL Ulysses safeguard detects
`UlyssesInnerAttention.Config`.
Compact MLA, Ulysses KDA, and Ulysses GDN instead inherit directly from
`Ulysses.Config`, so these models miss the existing protection on
affected
NCCL versions.

Example: `UlyssesMLAAttention.Config` does not inherit from
`UlyssesInnerAttention.Config`. On NCCL 2.32.2 the old traversal leaves
graph
registration enabled; traversing the common base selects the existing
safeguard.
The NCCL fix and version boundary are unchanged:
[NVIDIA/nccl#2362](NVIDIA/nccl#2362).

## What changed

- Match the common `Ulysses.Config` base in the existing safeguard.
- Add one isolated GDN regression for a subclass outside the old
hierarchy.
Full attention uses K/V all-gather in this test, so it cannot
accidentally
  trigger the old safeguard.
- Keep the existing version-boundary and unsupported-runtime tests
rather than
  repeating them for each backend.

There are only two production-line replacements. Native attention and
communication paths are unchanged; no new option or dependency is
introduced.

## User-facing changes

| Before | After |
| --- | --- |
| The safeguard detects only full-attention Ulysses wrappers. | It also
detects compact MLA and linear-attention Ulysses wrappers. |
| NCCL >= 2.32.3, non-CUDA, and fake runtimes skip the safeguard. |
Unchanged. |

## Numerics

No tensor computation, collective implementation, parameter, or
checkpoint
layout changes. This extends an existing pre-initialization runtime
policy.
The CPU checks below do not claim fresh end-to-end training or
throughput
acceptance.

## Testing

Fresh validation against upstream
`73c4ebdac57de0d89bb20d5dfabed340449c8b0d`:

- **91 CPU tests and 84 subtests passed**, with no deselection.
- **Fresh negative control:** the retained GDN regression fails on
untouched main
because `NCCL_GRAPH_REGISTER` remains unset; it passes with this change.
- All non-type-checking pre-commit hooks passed over all files.

```bash
CUDA_VISIBLE_DEVICES='' python -m pytest -q -o addopts='' -p no:cacheprovider --tb=short \
  tests/unit_tests/cpu/distributed/test_ulysses_nccl.py \
  tests/unit_tests/cpu/models/common/test_cp_attention.py \
  tests/unit_tests/cpu/config/test_context_parallel_validation.py
```

The type error at unchanged
`torchtitan/components/data/multimodal/utils/video.py:114` independently
reproduces on untouched upstream `73c4ebdac`. This PR does not change
that file.

Not verified: a fresh real multi-rank CP/CUDA-graph training run.

## Stack

This PR is directly based on `main` and does not require 4/n-7/n. The
other
source branches are unchanged by this update.

1/n (#5674) is merged; 2/n (#5675) and 3/n (#5676) are closed.

| Position | PR |
| --- | --- |
| 4/n | [#5677](#5677) |
| 5/n | [#5678](#5678) |
| 6/n | [#5679](#5679) |
| 7/n | [#5680](#5680) |
| 8/n | [#5681](#5681),
independent on main |
| 9/n | [#5682](#5682) |
| 10/n | [#5683](#5683) |
| 11/n | [#5684](#5684) |
| 12/n | [#5685](#5685) |
| 13/n | [#5686](#5686) |
| 14/n | [#5793](#5793),
full-scale MXFP8 recipes |
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch from 664401a to 1fd66ed Compare November 5, 2026 01:50
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch from 1fd66ed to 14eb78d Compare November 5, 2026 07:13
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch from 14eb78d to 768b32b Compare November 5, 2026 08:50
shuhuayu added a commit that referenced this pull request Nov 5, 2026
Part **4/n** of the Kimi K3 / Dist-MoE training stack. Based directly on
`main`: the review diff contains only the optimizer-memory changes
below.

human notes: 
1. release distmuon's gpu redistribution and compute scratch after each
eager optimizer update by default. 1) in full eager training, later
fwd/bwd can reuse the released memory. 2) if one rank has two eager
optimizers (fwd/bwd can use cudagraph), like when vpp=2, their scratch
allocations can reuse memory instead of remaining simultaneously
resident. keep tensor metadata and cpu scratch, and release unused ns
intermediates earlier without changing the math.
2. the flow is: reserve shapes/dtypes/device, and use allocate for
setting real storage, and use resize_(0) to free the storage.
3. remove some ns step intermediate tensors without changing math. 

## Why

DistMuon retains exchange and compute scratch between updates, even when
eager forward/backward or a second eager optimizer could reuse that
memory. Dropping scratch allocated on the transfer stream does not let
the caller stream reuse its cached blocks.

Prepare the buffer capacities once, then regrow and release accelerator
backing storage on the caller stream. Keep CPU backing storage allocated
between updates to avoid repeated host allocations. Tensor objects,
shapes, bucket plans, communication streams/events, parameters, and
optimizer state remain alive. This is the default behavior; no new
config knob is added.

**Example.**

```python
# Forward/backward may be eager or CUDA-graphed; optimizer updates are eager.
chunk0_optimizer.step()  # Regrow cached scratch, update, resize storage to zero.
chunk1_optimizer.step()  # Can reuse released caller-stream allocator blocks.
# With one optimizer, later eager forward/backward can reuse those blocks too.
# A separate forward/backward CUDA-graph pool cannot reuse normal-pool scratch.
```

## What changed

- Keep the four scratch tensor types and their metadata; prepare
capacities at construction or checkpoint replanning, not before every
update.
- Regrow released backing storage with `untyped_storage().resize_(size)`
on the current caller stream. Preserve the existing transfer/caller
event ordering, then release accelerator storage with `resize_(0)` after
a successful eager update. CPU storage stays allocated; `allocate()`
already skips correctly sized storage.
- Make storage release the default rather than introduce a persistence
knob. Because every storage lifetime begins and ends on its caller
stream, the old persistent-buffer caller-tracking set is unnecessary.
- Release obsolete Newton-Schulz intermediate references after their
last use. Arithmetic, compute dtype, and update ordering do not change.

The net diff touches the runtime, DistMuon implementation, and one CPU
runtime regression. Existing optimizer/checkpoint tests exercise the new
default without new distributed CI variants. There are no
trainer/container changes, synthetic all-to-all warmups, new
dependencies, or communicator/CTA changes.

## User-facing behavior

| Before | After |
| --- | --- |
| Accelerator scratch tensor objects and backing storage remain resident
between updates | Tensor objects persist; accelerator backing storage is
released after each eager update |
| CPU scratch remains allocated between updates | Unchanged; the release
loop skips CPU tensors |
| Several eager optimizers each retain their scratch arena | Sequential
eager updates can reuse caller-stream scratch allocations |
| Forward/backward graph pools are separate from optimizer scratch |
Unchanged; this PR does not implement graph-pool sharing |

## Numerics

Compared with the `main` parent `22047b18a`:

- GPU 0: FP32 and BF16 parameters each produced bitwise-identical loss,
gradients, and updated weights for ten updates, with both eager and
CUDA-graphed forward/backward. Each run reloaded an optimizer checkpoint
after update five.
- Real two-rank CPU/Gloo redistribution: owned, uneven mixed-block, and
expert matrices produced bitwise-identical updated weights for ten
updates and a checkpoint reload. The owned matrix also matched
`torch.optim.Muon` exactly. Scratch tensor identities survived
updates/reloading; CPU backing storage now stays allocated between
updates, matching the host-buffer behavior on `main`.
- A standalone one-rank optimizer-capture smoke test completed ten
exact-parity replays. This is not multi-rank optimizer-graph validation;
the Titan optimizer container still does not enable DistMuon capture.

Fresh follow-up checks against the previous PR head `a4fada369` also
produced exact FP32/BF16 eager and graphed loss/gradient/weight parity,
and exact two-rank Gloo updates. An actual single-GPU FSDP2
`CPUOffloadPolicy` run with `ns_device=None` completed ten updates and a
checkpoint reload: a 16-to-16-to-8 linear model (384 weights, eight
input rows) kept its 1,024-byte host scratch allocated and reused its
pointer between replans, with bitwise-identical loss, gradients, and
weights. This is correctness/lifecycle evidence, not an offload
throughput or host-allocation-cost measurement.

Fresh multi-rank NCCL validation has not been rerun because only GPU 0
was available.

## Memory evidence

The following accelerator-only measurements predate the CPU-retention
correction; the correction does not change the accelerator release
branch. This is a synthetic single-GPU GB300 allocator benchmark, not a
Kimi K3 training run. BF16 forward/backward uses a bias-free
1024-to-8192 linear layer (8.39M weights) with 4096 input rows. Each
eager DistMuon instance updates a separate 29.36M-parameter workload
(14.68M local parameters on shape-only fake DP=2), with FP32
parameters/gradients/momentum, BF16 compute, and one Newton-Schulz
iteration.

The table covers ten updates after two eager warmups; graph cases
additionally capture/replay forward/backward before measurement. Values
are PyTorch allocator counters, not total device HBM. FakePG is used for
shapes here, not distributed numerical evidence.

| Forward/backward | Eager optimizers | Peak allocated: parent -> PR |
Steady reserved: parent -> PR |
| --- | ---: | ---: | ---: |
| Eager | 1 | 672 -> 528 MiB | 722 -> 594 MiB |
| Eager | 2 | 984 -> 696 MiB | 1058 -> 774 MiB |
| CUDA graph | 1 | 424 -> 420 MiB | 788 -> 800 MiB |
| CUDA graph | 2 | 736 -> 588 MiB | 1124 -> 980 MiB |

Each optimizer retains 144 MiB of scratch capacity metadata but zero
backing storage after an update, versus 144 MiB resident on the parent.
All cases had zero allocator retries. The single-optimizer graph case
does not show meaningful scratch-related peak savings; the two-optimizer
case demonstrates normal-pool scratch reuse, not graph-pool sharing.

A separate setup-call census over ten updates/two optimizers recorded
zero `reserve_buffers` and `_reserve_tensor` calls in the new steady
loop, versus 20 and 180 calls in the previous transient implementation.
Storage allocation/free operations still occur. No full-scale HBM or
throughput gain is claimed.

## Testing

- **123 CPU tests passed** for redistribution, optimizer
state/configuration, trainer, and accelerator graphs. The one added CPU
regression checks all four scratch buffer roles for ten release/allocate
cycles, verifying retained host capacity, pointers, and contents; it
fails cleanly against the previous PR head.
- The supplementary GPU-0, FSDP2 CPU-offload, and real Gloo probes above
passed; no new multi-GPU CI variants were added.
- All non-type-checking pre-commit hooks passed across the repository.
Both changed production files and the CPU regression pass focused
Pyrefly.
- Full-project Pyrefly reports the same single optional-value error at
`components/data/multimodal/utils/video.py:114` on both this patch and
the independently checked `main` parent. No unrelated fix or suppression
is included.

```bash
CUDA_VISIBLE_DEVICES='' python -m pytest -q \
  tests/unit_tests/cpu/distributed/flex_shard \
  tests/unit_tests/cpu/components/optim/test_optimizer_param_groups.py \
  tests/unit_tests/cpu/components/optim/test_optim.py \
  tests/unit_tests/cpu/test_trainer.py \
  tests/unit_tests/cpu/distributed/test_accelerator_graph.py

SKIP=pyrefly-check pre-commit run --all-files
pyrefly check torchtitan/distributed/flex_shard/_optimizer_reshard_runtime.py \
  torchtitan/distributed/flex_shard/dist_muon.py \
  tests/unit_tests/cpu/distributed/flex_shard/test_optimizer_reshard_runtime.py
```

## Stack

Based directly on `main`. Next:
[#5678](#5678).

<details>
<summary>Draft stack — review and land in this order</summary>

1/n (#5674) and 8/n (#5681) are merged. 2/n (#5675) and 3/n (#5676) are
closed because the chosen full-scale recipes use neither the
prefetch-disable policy nor selected-layer CPU offload. They are no
longer in the stack.

| Position | Draft PR |
| --- | --- |
| 4/n | [#5677 — [distmuon] 4/n Release scratch storage between
optimizer updates](#5677) |
| 5/n | [#5678 — [dist_muon] 5/n Support CP and TP storage-to-compute
layouts](#5678) |
| 6/n | [#5679 — [profiler] 6/n Preserve active failures during
shutdown](#5679) |
| 7/n | [#5680 — [attention] 7/n Keep linear-attention graph metadata
replayable](#5680) |
| 8/n, merged | [#5681 — [cp] 8/n Apply the Ulysses NCCL safeguard to
compact and linear
attention](#5681) |
| 9/n | [#5682 — [compile] 9/n Compile MLA assembly and router
postprocessing](#5682) |
| 10/n | [#5683 — [pp] 10/n Add once-only startup cache
release](#5683) |
| 11/n | [#5684 — [dist_moe] 11/n Enable Kimi K3 SiTU-GLU training and
pipeline lifecycle](#5684) |
| 12/n | [#5685 — [moe] 12/n Add opt-in shared-expert CUDA stream
overlap](#5685) |
| 13/n | [#5686 — [ac] 13/n Add block-scoped activation
retention](#5686) |
| 14/n | [#5793 — [recipes] 14/n Add full-scale Kimi K3 MXFP8
recipes](#5793) |

</details>

After this PR lands, rebase the remaining suffix onto updated main and
retarget its next bottom PR to main. Keep the rest stacked; no automatic
landing is requested.
@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 3m 37s —— View job


Approve -- please address the items before merging (main item: the new SiTU-GLU GPU numerics test uses inputs too small to engage the bounds): see review

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: Approve -- please address the items below before merging. The SiTU-GLU translation is correct and small. The main gap is that the new GPU numerics test uses inputs that are too small to tell SiTU-GLU apart from SwiGLU. A maintainer still needs to review, since this touches models/common/dist_moe.

What this PR does. DistMoeTransform now maps SiTUGLU.Config(beta, linear_beta) to the native activation="situ_glu", with situ_glu_gate_beta and situ_glu_up_beta. It rejects linear_beta=None. It adds BF16 and MXFP8 Kimi K3 debug recipes and a 4-GPU Kimi K3 MXFP8 FSDP2+EP2+CP2 integration entry. It also moves require_dist_moe and dist_moe_runtime_config into the public torchtitan_recipes/dist_moe.py.

Example.

config = kimi_k3_debugmodel()   # routed experts: SiTUGLU.Config(beta=4.0, linear_beta=25.0)
apply_transforms(config, [DistMoeTransform()])
# main: TypeError: Dist-MoE supports SwiGLU.Config or ClampedSwiGLU.Config; got SiTUGLU.Config
# PR:   experts -> DistMoeRoutedExperts.Config(activation="situ_glu",
#                    situ_glu_gate_beta=4.0, situ_glu_up_beta=25.0)
SiTUGLU.Config(beta=4.0, linear_beta=None)  # PR: ValueError "Dist-MoE SiTU-GLU requires linear_beta"

Must fix

  1. tests/unit_tests/gpu/models/common/test_dist_moe.py:231 -- With (4.0, 25.0) and the test's input scales, tanh is almost linear. A native kernel that ignored situ_glu_up_beta, or ran plain SwiGLU, would very likely pass. Use bounds that saturate tanh at these magnitudes, or a larger gate_std (details inline).
  2. tests/unit_tests/cpu/models/common/test_dist_moe.py:1069 -- test_kimi_k3_dist_moe_recipes_replace_every_expert re-checks what the transform already guarantees. Drop it, or add the Kimi factories as rows of the existing recipe test.
  3. tests/integration_tests/b200.py:135 -- The two llama3 recipe functions are moved with no change to their bodies. Leave them where they were.

Should consider

  • tests/integration_tests/b200.py:116 -- This is the first Kimi K3 CP entry in CI, and it runs without spmd type checking. The other Kimi B200 entries turn it on. Also, checkpointer = None is redundant.
  • torchtitan/models/common/dist_moe/routed_experts.py:33 -- Carrying the source activation config instead of flat per-activation fields would remove the _ACTIVATION_PARAMETERS table and the four-place edit per activation.

Questions

  • The DeepSeek Dist-MoE debug recipes set precision.reduce_dtype = "bfloat16" and dataloader.max_num_documents = 512, and the recipe test asserts both. The Kimi recipes keep the FP32 reduce dtype and the multimodal dataloader defaults. Is that deliberate? The README says FSDP casts the BF16 WGrad to reduce_dtype, so it works, but the precision differs from the DeepSeek recipes.
Details
  • Gate check: the problem is real on main. The transform rejected SiTUGLU.Config, and the Kimi K3 flavors use SiTUGLU.Config(beta=4.0, linear_beta=25.0) for routed experts (torchtitan/models/kimi_k3/flavors.py:432). The native kernel already exposes the bounds, so translating in TorchTitan is the right layer. The stock SiTUGLU._activation_fn computes beta*tanh(g/beta)*sigmoid(g) * linear_beta*tanh(u/linear_beta), which matches the gate/up mapping here.
  • Rejecting linear_beta=None with an error, rather than silently changing the math, follows the explicit-over-implicit rule.
  • Moving the recipe helpers is a mechanical change. I checked that the bodies are identical and that all three callers are updated (DeepSeek production/test recipes and tests/rl/alphabet_sort.py). No remaining references to _require_dist_moe or _dist_moe_runtime_config.
  • Setting CP after build_model_config(parallelism=...) in the integration entry follows the existing pattern in tests/integration_tests/models.py. The ContextParallelTransform map (InnerKDA, MLAAttention) covers both inner-attention types in Kimi K3.
  • The error messages the old tests matched no longer exist, and nothing else references them.

Not verified: the 4-GPU CP integration entry and the GPU numerics test (no GPU or dist_moe package here). The authors did not run the integration entry locally either.

Comment on lines +231 to 245
situ_glu_bounds = (
{"situ_glu_gate_beta": 4.0, "situ_glu_up_beta": 25.0}
if activation == "situ_glu"
else {}
)
stock = _stock_routed_experts(
num_experts=num_experts,
w13_E2FD=w13_E2FD,
w2_EDF=w2_EDF,
activation_fn=(
SiTUGLU.Config(beta=4.0, linear_beta=25.0)
if activation == "situ_glu"
else FusedSwiGLU.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.

With these inputs the bounds (4.0, 25.0) barely affect the result, so this test can't tell SiTU-GLU apart from plain SwiGLU.

_set_up_ep_inputs() uses x ~ N(0, 1) with D=256, a gate std of 0.02 and an up std of 0.01. That gives pre-activations of roughly std(g) ~ 0.32 and std(u) ~ 0.16.

  • Up: 25 * tanh(u / 25) differs from u by about u^2 / 1875, a relative change of about 1e-5. That is far below BF16 resolution and _TOL = 1e-4.
  • Gate: 4 * tanh(g / 4) differs from g by about g^2 / 48, about 0.2%. That is under one BF16 ulp for typical entries.

So a native kernel that ignores situ_glu_up_beta, or one that runs swiglu whenever activation="situ_glu", would very likely still pass. The CPU test only shows that the bounds reach dist_moe.Config. This GPU test is the only check that the kernel applies them.

Fix: choose bounds that saturate tanh at these magnitudes, e.g. beta=0.25, linear_beta=0.1, defined once and shared by the stock and native configs. Or pass a larger gate_std (as the MXFP8 test does) together with smaller bounds. A useful sanity check is that the stock SiTU-GLU output differs from the stock SwiGLU output by much more than _TOL.

),
],
)
def test_kimi_k3_dist_moe_recipes_replace_every_expert(factory, expected_type) -> 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.

This test adds little beyond the existing recipe test for DeepSeek. DistMoeTransform already raises TypeError on any routed expert it can't translate. test_transform_preserves_situglu_configuration already covers the Kimi activation, for both precisions. So "every Kimi expert is replaced" mostly re-reads what the transform guarantees (.claude/rules/tests.md: don't duplicate an existing test for one more model).

Fix: drop it. Or, if the recipe-level check is wanted, add the two Kimi factories as rows of test_dist_moe_bf16_recipes_use_varlen_and_replace_all_experts. That test would need to be parametrized on the expected expert type and the precision/document fields.

Comment on lines +135 to +149
def llama3_debugmodel_mxfp8_fsdp2() -> Trainer.Config:
from torchtitan_recipes.tests.models.llama3 import llama3_debugmodel_mxfp8

config = llama3_debugmodel_mxfp8()
config.parallelism.data_parallel_shard_degree = 2
return config


def llama3_debugmodel_nvfp4_fsdp2() -> Trainer.Config:
from torchtitan_recipes.tests.models.llama3 import llama3_debugmodel_nvfp4

config = llama3_debugmodel_nvfp4(seq_len=2048)
config.parallelism.data_parallel_shard_degree = 2
config.training.num_tokens_per_microbatch_per_dp_rank = 2048
return 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.

llama3_debugmodel_mxfp8_fsdp2 and llama3_debugmodel_nvfp4_fsdp2 are moved with no change to their bodies. That is reordering this PR doesn't need, and it makes the diff look like it touches the llama3 entries. Please leave them where they were.

Comment thread tests/integration_tests/b200.py Outdated
Comment on lines +116 to +121
config.parallelism.context_parallel_degree = 2
# Ulysses moves MLA's CP shard onto heads, so tokens stay contiguous.
config.parallelism.context_parallel_load_balancer = None
config.training.num_tokens_per_microbatch_per_dp_rank = 128
config.training.steps = 4
config.checkpointer = 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.

Two things here:

  • This would be the first Kimi K3 CP entry in CI, but it runs with debug.spmd_typechecking off (the default). The other Kimi B200 entries turn it on (_set_spmd_typechecking(config, typechecking=True) in kimi_k3_debugmodel_mm and kimi_k3_debugmodel_mm_muon). .claude/rules/tests.md asks CI to run with spmd_types type checking on. If Dist-MoE + CP supports it, turn it on here. If not, add a short comment explaining why, as kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4 does.
  • config.checkpointer = None is redundant, because kimi_k3_debugmodel already sets it.

Comment on lines +33 to +37
_ACTIVATION_PARAMETERS: dict[str, frozenset[str]] = {
"swiglu": frozenset(),
"swiglu_clamped": frozenset({"swiglu_alpha", "swiglu_limit"}),
"situ_glu": frozenset({"situ_glu_gate_beta", "situ_glu_up_beta"}),
}

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.

Optional, not blocking. Each activation now needs edits in four places:

  • the translation in config/transform/dist_moe.py;
  • flat swiglu_* / situ_glu_* fields on this Config, plus this table to validate them;
  • copies of those fields in __init__;
  • an if/elif in DistMoeRuntime._resolve_context_config.

Alternative: carry the source config itself, activation_fn: SwiGLU.Config | ClampedSwiGLU.Config | SiTUGLU.Config, and map it to dist_moe.Config kwargs in one place in the runtime. The transform would then pass source.activation_fn straight through. The linear_beta is None check would move to __post_init__. The _ACTIVATION_PARAMETERS table and the per-activation fields would go away. Adding a fourth activation would then touch only the type union and the runtime mapping. If you'd rather keep the flat fields to match the annex API, that's fine.

@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch from 0caa574 to 1f3899f Compare November 17, 2026 09:50
@shuhuayu
shuhuayu marked this pull request as ready for review November 17, 2026 20:36
@pytorch-bot pytorch-bot Bot added ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests labels Nov 17, 2026
activation = "swiglu"
swiglu_alpha = None
swiglu_limit = None
activation_values: dict[str, Any] = {"activation": "swiglu"}

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.

did you mean

Suggested change
activation_values: dict[str, Any] = {"activation": "swiglu"}
activation_kwargs: dict[str, Any] = {"activation": "swiglu"}

@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch 5 times, most recently from ecccff1 to a4fcbec Compare November 23, 2026 22:43
shuhuayu added a commit that referenced this pull request Nov 24, 2026
## Summary (human-written)

udpate b200 ci to cu132.

## Why

The B200 workflows install the latest PyTorch nightly without a pin,
from the
`cu130` index. PyTorch stopped publishing cu130 nightlies on 2026-11-03
(pytorch/pytorch#203260). The newest wheel on that index is
`torch==2.16.0.dev20261102+cu130`, so every B200 run since then has
tested a
three-week-old PyTorch:

| Index | Newest torch nightly (checked 2026-11-23) |
| --- | --- |
| `nightly/cu130` (B200 today) | `2.16.0.dev20261102` |
| `nightly/cu132` (other CUDA lanes) | `2.16.0.dev20261123` |

**Example.** pytorch/pytorch#205562, the fix for the cuDNN varlen
backward
wrong-dQ bug (pytorch/pytorch#205493), landed on 2026-11-19. It never
reaches
B200 CI, and `kimi_k3_dist_moe_fsdp_ep_cp` in #5684 keeps crashing with
`cuDNN SDPA ... illegal memory access`.

The other CUDA lanes moved to cu132 in #4661. The two B200 workflows
were not
updated.

## What changed

- `integration_test_b200.yaml` and
`integration_test_b200_graph_trainer.yaml`
  install torch, torchvision and torchao from `nightly/cu132` instead of
  `nightly/cu130`.
- The container image stays
`nvidia/cuda:13.0.3-cudnn-devel-ubuntu22.04`. The
  torch wheels ship their own CUDA runtime and cuDNN as `nvidia-*` pip
  packages.
- The torchao pin (`0.19.0.dev20261103`) is published on cu132, so
  `.github/requirements-torchao.txt` is unchanged.

## Testing

The B200 and B200 graph-trainer workflows run on this PR through the
`ciflow/b200` label. The run log should show
`torch==2.16.0.dev2026112x+cu132`.
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch 3 times, most recently from 42a3d8e to 2cab8c5 Compare November 24, 2026 20:57
Kimi K3's routed experts use bounded SiTU-GLU, which DistMoeTransform
rejected. Translate SiTUGLU.Config (beta, linear_beta) to the native
situ_glu activation and its gate/up bounds, validate the activation
parameters per activation, and add a Kimi K3 MXFP8 Dist-MoE debug recipe
with an FSDP2+EP2+CP2 integration test.
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-11 branch from 2cab8c5 to 11dfcd0 Compare November 25, 2026 01:09
@shuhuayu
shuhuayu merged commit f9a08cd into main Nov 25, 2026
31 of 33 checks passed
shuhuayu added a commit that referenced this pull request Nov 25, 2026
## Summary (human-written)

1) Let dist-moe get activation slots from the customized pp in k3. 
2) build pp metadata from config in build time, avoid timeout during
dynamic pp metadata inference in full scale kimi k3 runs.

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 on `main`:

1. **No activation slot is selected.** Dist-MoE picks its per-(stage,
microbatch) activation slot through the stage's registered forward
contexts. `AttnResPipelineStage.forward_one_chunk` overrides the base
method and calls the model directly, so the contexts are never entered.
2. **Every real-PG run does dynamic metadata inference.** Core declares
static stage metadata only on the fake backend, and its single-hidden
boundary does not fit K3's `(hidden, delta)` carriers anyway. So PyTorch
infers metadata by running one serial forward and backward through every
stage before step 1, on uninitialized inputs:
   - at full K3 scale (256 GB200, PP8) this hit the 600 s NCCL timeout;
- with learned routing, the uninitialized inputs collapsed onto a few
experts and tripped Dist-MoE's capacity guard before training (512 GB200
run).

**Example (K3 with CP16, 64K tokens per microbatch):**

```text
main:  stage rebuild -> no static metadata -> dynamic inference:
       serial fwd+bwd over all stages, uninitialized inputs routed through Dist-MoE
this:  stage i receives hidden_TD [4096, D] + delta_TND [4096, n_i, D]
       (65536 / CP16 = 4096 tokens; n_i = blocks sent into stage i)
       -> no inference pass; forward contexts select the Dist-MoE slot
```

## What changed

- `kimi_k3/pipeline_parallel/__init__.py`:
- `_build_attn_res_stage_metadata` declares 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)`, with `N` from the block layout.
- The block stack takes its token count from core's `hidden_TD`, so it
is CP-local and sequence-sharded under SP. K3 declares this metadata on
every backend.
- With sequence parallelism, the first stage must contain a decoder
layer; otherwise the first boundary would carry TP-replicated
embeddings, so this raises `ValueError`.
- The stage swap now happens after the layout is known, so the metadata
can be passed to the rebuilt stages.
- `kimi_k3/pipeline_parallel/stage.py`:
- `AttnResPipelineStage` overrides the public
`register_forward_context`. It keeps the factory itself and enters it in
its own `forward_one_chunk` with the stage and microbatch index; PyTorch
enters registered contexts only in the base `forward_one_chunk`, which
this class replaces. No private PyTorch API is used.
- The stage now requires `input_args` and `output_args`, so it can never
fall back to dynamic inference, which would run outside its block
routing and forward context.
- Deleted the code only dynamic inference reached: `_compute_outputs`
and `_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's
`stage_backward` skips outputs that don't require grad).
- `distributed/pipeline_parallel.py` (mechanical):
`build_decoder_stage_io` and `DecoderStageIO` become public, so K3
reuses core's boundary shapes instead of duplicating them.
- `tests/integration_tests/b200.py`: #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

- Make core declare static metadata on every backend: that changes PP
setup for every model. K3 needs its own carrier shapes regardless.
- Keep dynamic inference and only bypass Dist-MoE while it runs: it
still pays the serial setup pass that timed out at K3 scale.

## Numerics

No arithmetic change; the stage only gets metadata it used to infer.
`test_kimi_k3_pp_block_grads` now runs the pipeline with declared
metadata, as `pipeline_kimi_k3` builds 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

| Check | Hardware | Result |
| --- | --- | --- |
| `tests/unit_tests/cpu/models/kimi_k3/`,
`distributed/test_pipeline_parallel.py`,
`models/common/test_dist_moe.py` | CPU (1 GPU visible) | pass |
| Kimi K3 BF16 Dist-MoE, PP2 Interleaved1F1B, 4 microbatches (local
smoke, no FSDP/EP/CP) | 2x GB300 | completes 4 steps |
| Integration `kimi_k3_dist_moe_fsdp_ep_cp_pp` (MXFP8, FSDP2 + EP2 + CP2
+ PP2) | 8 GPUs | not run locally (only 3 free GPUs); relies on CI. Its
CP2 part passes in a 2-GPU proxy (see #5684) |

New and extended tests and what they catch:
- `test_kimi_k3_pp_block_grads` and
`test_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.
shuhuayu added a commit that referenced this pull request Nov 26, 2026
## 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.
shuhuayu added a commit that referenced this pull request Dec 1, 2026
Part **5/n** of the Kimi K3 / Dist-MoE training stack. Based on `main`.
Replaces #4353.

## Summary

human notes: add tp support for distmuon. 

## Why

DistMuon cannot be used with tensor parallelism on `main`. Muon must
orthogonalize complete matrices, but with TP+FSDP a matrix is split
across two mesh axes, and the FlexShard planner only supports transport
along one axis with every other axis replicated. The Kimi recipes
therefore reject `tensor_parallel_degree > 1` when DistMuon is
configured (`TODO(#3353)`).

**Example.**

```text
storage mesh: (dp_shard=2, tp=2); one matrix stored as (Shard(0), Shard(1))
rank (dp, tp) holds the [rows of dp] x [cols of tp] fragment
compute: {"dp_shard": Owned(), "tp": Owned()}   # one rank updates the whole matrix

main:    NotImplementedError: multi-axis transport is not implemented
this PR: the 4 ranks form one "dp_shard_tp" transport group; the owner receives
         the complete matrix, runs Newton-Schulz once, and every rank gets its
         original (Shard(0), Shard(1)) fragment back
```

The same applies to MLA head blocks stored as `(_StridedShard(0),
Shard(0))` (TP and FSDP sharding the same dim) and to experts stored as
`(Shard(0), Shard(1))`. CP already works with DistMuon on `main`
(`dp_shard_cp` is one flattened axis); with this PR it also composes
with TP (`dp_shard_cp` + `tp`).

## What changed

**FlexShard planner** (`flex_shard/dist_muon.py`,
`_optimizer_reshard_schedule.py`) -- the core of the PR:
- A transition may span several storage mesh axes;
`redistribution_storage_mesh_axis` becomes
`redistribution_storage_mesh_axes`.
- Storage is described as per-dimension index runs, so `_StridedShard`,
uneven, and empty shards map to logical regions exactly; each rank's
storage must be one contiguous region (true for TP + FSDP layouts),
otherwise planning raises. `_StridedShard` storage whose dimension is
not divisible by its split factor also raises: FSDP2 lays out that
uneven case differently from DTensor's split-then-shard rule (TODO in
the code). Non-transport axes keep their storage placement.
- `Owned` compute requires every non-owned axis to be replicated;
changing an axis outside the transport group raises `ValueError`.

**Explicit transport meshes.** FlexShard never creates process groups.
`BucketConfig.mesh` is removed: `DistMuon(..., transport_meshes=...)`
takes a pool of caller-owned 1D meshes, and each bucket uses the pool
mesh whose ranks equal the storage ranks of its transport axes (names
are not used). Without a match, a single-axis transport reuses its
storage group and a combined transport raises.
- `ParallelismContext.build_optimizer_meshes(axes_list, backend=...,
pg_options=...)` builds the pool. For each axes tuple it creates one
group per slice of those axes over the whole world and returns this
rank's 1D meshes, named by the joined axes (`dp_shard_tp`). Axes that
cover the same ranks share one group and one mesh: with dp_shard=2,
tp=2, ep=2, each rank's `edp_shard` slice equals its `dp_shard` slice,
and two pool meshes with the same ranks would make the bucket's mesh
ambiguous. Every rank creates every slice, so ranks on different PP
stages (including an expert-free stage) create the same groups in the
same order without an extra collective. The meshes are not registered on
the root mesh, so DTensor never uses them. This replaces
`build_alternative_fsdp_mesh`.
- The TorchTitan `DistMuon` wrapper (`components/optim/optimizer.py`)
requests `(dp_shard[, cp], tp)` when TP > 1. With
`max_nccl_ctas_for_comms` it also requests `dp_shard[, cp]` and, with
EP, `edp_shard`, all as NCCL communicators with that CTA cap (FSDP
groups unchanged). `Optim` passes `parallelism_context` through
`OptimizersContainer` to every optimizer build for this.

**Compute buffer reuse** (`_optimizer_reshard_runtime.py`,
`_optimizer_reshard_schedule.py`): the compute exchange buffer is reused
in place for returned fragments, which is only safe when both directions
pack each parameter identically. A replicated holder (e.g. a
TP-replicated `Owned` matrix) gets its update back on every holder, so
returned fragments could overwrite later parameters' unread input. The
bucket plan records `compute_to_storage_offset`: `0` when the layouts
match, otherwise returned fragments go after the received ones. This
duplicates #5695, where the same bug reproduces on `main` with plain
`Replicate` storage on a 1D mesh. #5695 lands first; this PR then
rebases and keeps only its TP test.

| | #5695 | this PR |
| --- | --- | --- |
| Plan field | `compute_to_storage_input_offset` |
`compute_to_storage_offset` |
| Offset rule | `0` if the compute -> storage input spans equal the
storage -> compute output spans, else the received buffer size | same |
| Runtime | buffer sized `offset + input_buffer_numel` (2 sites);
returned fragments and the outgoing all-to-all use `buffer[offset:]` |
same |
| Test | 1D `dp_shard`, `Replicate` storage between `Shard(1)` params;
shared bucket vs per-parameter buckets | DP x TP, TP-replicated `Owned`
before TP-sharded params; vs unsharded `torch.optim.Muon` |

**Kimi** (`models/kimi_k2_7/qk_clip.py`, recipes, README):
- QK-Clip derives its per-head scale placements from the MAX all-reduce
group (the `loss` mesh) instead of axis names: scales are `Replicate` on
mesh axes inside that group and keep the weight's `Shard(0)` on axes
that split heads (TP); anything else raises.
- Recipe compute layouts declare the `tp` axis only when
`tensor_parallel_degree > 1`; the TP guard is removed, so TP=1 layouts
are unchanged. TP with DistMuon is verified on K3.
- The recipes' `__post_init__` re-derives the dense layouts' `tp` axis
(and, as before, the routed-expert layouts) from the final parallelism
config, so a config that sets TP after building the recipe, like the
b200 cell, still gets TP layouts.

**Integration coverage:** the b200
`kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell (FSDP 2, TP 2, EP 2,
interleaved PP 2 x 4 stages, 8 GPUs, no golden file) now keeps the
recipe's DistMuon with its CTA cap instead of AdamW, so CI runs the TP
layouts, QK-Clip on TP-local heads, and transport group creation across
stages on real NCCL.

**Mechanical / skimmable:** FlexShard and Kimi README updates,
integration-test comments, DeepSeek V4 guard message (its layouts do not
declare `tp`), deletion of `build_alternative_fsdp_mesh` and its mocked
tests, `parallelism_context` plumbing through `Optim`,
`OptimizersContainer` and `TorchFTOptimizersContainer` and its test
updates.

## Alternatives considered

- Run Newton-Schulz on TP fragments independently: changes Muon's math.
- Let FlexShard create the groups itself: hides process-group policy
(CTA cap, NCCL options) inside the planner; the caller owns process
groups instead.
- Create groups lazily per bucket, with only their members
(`use_local_synchronization=True`), or with `split_group` from the
storage group (as `main` did for the CTA cap): every group creation
advances a per-rank counter that names later groups, so when PP stages
create different groups, later WORLD-wide group creation hangs.
- `DeviceMesh._flatten` from a storage mesh: private, needs the storage
mesh on every rank (fails for an expert-free stage), and registers the
combined mesh on the world root, which changes how DTensor gathers other
parameters on those axes.
- Create the combined groups in `ParallelismContext.build_mesh` (as
first proposed for option (a)): every TP run, AdamW included, would pay
for the extra communicators, and `build_mesh` would need the
DistMuon-only CTA cap. Instead the DistMuon wrapper calls
`build_optimizer_meshes` once at construction, and FlexShard picks each
bucket's mesh by ranks, so `BucketConfig.mesh` and the wrapper's bucket
matching are no longer needed.
- Create only the groups this rank's buckets need (query FlexShard for
each bucket's transport axes, all-gather the rank lists across PP
stages, create the union): needs a FlexShard query API and an extra
collective; creating every slice of a few fixed axis combinations is
simpler.
- DP-only transport for TP-local head blocks (a dedicated `dp_shard`
group, or pinning each head block to its TP shard inside the `(dp_shard,
tp)` group): not needed for correctness, and not faster in the
microbenchmark below. Head blocks use the same `(dp_shard, tp)`
all-to-all as the other dense weights.

`all_to_all_single` (bf16, uneven splits) on 4 GB300s, all NVLink, as
dp_shard=2 x tp=2. Time per call after warmup, slowest rank. Each rank
sends 2x "bytes/peer" in total in every column:
- pinned: 4-rank group, the same-TP peer and self get "bytes/peer" each,
cross-TP peers get 0
- spread: 4-rank group, the same total split evenly over all 4 ranks
(cross-TP allowed)
  - dp_shard: dedicated 2-rank group, same bytes as pinned

  | bytes/peer | pinned | spread | dp_shard |
  | --- | --- | --- | --- |
  | **default CTAs** | | | |
  | 64 KiB | 70 us | 90 us | 68 us |
  | 1 MiB | 74 us | 78 us | 70 us |
  | 8 MiB | 72 us | 76 us | 67 us |
  | 32 MiB | 212 us | 124 us | 123 us |
  | 128 MiB | 758 us | 415 us | 407 us |
  | **8-CTA cap (`max_nccl_ctas_for_comms`)** | | | |
  | 64 KiB | 74 us | 80 us | 69 us |
  | 1 MiB | 70 us | 74 us | 67 us |
  | 8 MiB | 197 us | 104 us | 113 us |
  | 32 MiB | 746 us | 394 us | 390 us |
  | 128 MiB | 1536 us | 1406 us | 1157 us |

Pinning is up to ~1.9x slower than spreading at 8 MiB/peer and above.
Spreading is within ~10% of a dedicated group except at 128 MiB with the
cap (1.2x). Single node only; cross-node behavior is unmeasured.

## User-facing changes

| Before | After |
| --- | --- |
| Kimi recipes with DistMuon reject `tensor_parallel_degree > 1` | DP x
TP supported (K3 also CP x TP) |
| `max_nccl_ctas_for_comms` caps `split_group` children of
`dp_shard`/`edp_shard` | caps the actual optimizer transport groups,
incl. combined DP/TP |
| `BucketConfig.mesh` overrides a bucket's groups with a storage-axis
child mesh | removed; FlexShard `DistMuon(transport_meshes=...)` takes a
pool of 1D meshes matched by ranks, including combined ones
(`dp_shard_tp`); the TorchTitan wrapper builds it with
`ParallelismContext.build_optimizer_meshes` |

Mesh setup requires every rank to construct the same sequence of
DistMuon optimizers (true for torchtitan PP schedules).

Memory: a bucket that contains a replicated holder region (e.g. a
TP-replicated `Owned` matrix) places returned fragments after the
received ones, so its compute exchange buffer grows by the bucket's
receive size, up to about 2x. Buckets whose receive and return layouts
match are unchanged.

## Numerics

Newton-Schulz arithmetic and the Muon update are unchanged; TP=1 layouts
take the same paths as before. With TP, every block/matrix is
orthogonalized whole, as without TP.

| Check | Workers / backend | Result |
| --- | --- | --- |
| Whole, TP-replicated `Owned`, strided head-block and expert matrices,
2 real Muon steps, DP-only `(4,1)`, TP-only `(1,4)` and DP x TP `(2,2)`
each vs. unsharded `torch.optim.Muon` | 4 / NCCL | whole matrices exact;
batched head blocks and experts within 2e-2 of the lr-normalized update
per step (batched vs per-matrix BF16 GEMMs) |
| Same parameters, shared bucket vs one bucket per parameter | 4 / NCCL
| exact |

**Kimi K3 debug model, 50 steps**, rebased on `main` at `72e556678`,
`scripts/loss_compare.py` from a shared seed checkpoint, dp_shard=2 +
ep=2, TP=1 (2 GPUs) vs TP=2 + SP (4 GPUs), GB300. TP changes reduction
order, so loss is not bitwise; the AdamW run shows the TP noise floor:

| Step | DistMuon TP=2 - TP=1 | AdamW TP=2 - TP=1 |
| --- | --- | --- |
| 2 | +0.001 | -0.002 |
| 5 | +0.008 | +0.000 |
| 10 | -0.001 | +0.006 |
| 25 | +0.009 | -0.009 |
| 50 | -0.007 | +0.002 |
| max \|diff\| over 50 steps | 0.017 | 0.021 |
| mean \|diff\| over 50 steps | 0.006 | 0.006 |

## Testing

```bash
CUDA_VISIBLE_DEVICES='' python -m pytest -q \
  tests/unit_tests/cpu/distributed/flex_shard \
  tests/unit_tests/cpu/distributed/test_distributed_utils.py \
  tests/unit_tests/cpu/distributed/test_parallelism_context.py \
  tests/unit_tests/cpu/components/optim \
  tests/unit_tests/cpu/recipes \
  torchtitan/experiments/torchft/tests
python -m pytest -q \
  tests/unit_tests/gpu/distributed/flex_shard/test_dist_muon.py \
  tests/unit_tests/gpu/models/kimi_k2_7/test_qk_clip.py   # 4 GPUs
```

CPU: 230 passed, 13 skipped (198 + 32 TorchFT; the skips are all in
`test_fused_mla_override.py`, which needs CUDA). GPU: 19 passed on 4x
GB300. Run with the attn-gym and torch_checkpointing commits pinned in
`requirements.txt`. `pre-commit` passes except Pyrefly, which reports 8
errors, all in files this PR does not change.

New tests and the regressions they catch:
- GPU `test_dist_muon.py::TestDistMuonMatchesUnshardedMuon`: DP-only,
TP-only and DP x TP storage each match unsharded `torch.optim.Muon`
(whole matrices exactly; batched head blocks and experts within the 2e-2
tolerance the other DistMuon tests use), for a bucket where a
TP-replicated `Owned` matrix sorts before TP-sharded, head-block and
expert parameters. The shared bucket must also match per-parameter
buckets exactly; the TP-only case fails that check without the
buffer-reuse fix. Also checks that FlexShard never creates groups and
that a combined transport without a matching transport mesh raises.
- GPU `test_dist_muon.py::TestDistMuonTensorParallelCudaGraph`: TP
routing stays exact under CUDA-graph replay.
- GPU `test_qk_clip.py::QKClipTensorParallelTest`: QK-Clip scales
TP-local heads when FSDP's shard splits a head, and raises when the
reduction group does not match the weight's placements.
- Group creation across PP stages: `TestBuildOptimizerMeshes` (next
bullet) checks that every rank creates every stage's groups in the same
order, and the b200 `kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell
runs DistMuon with the CTA cap under PP, TP and EP on 8 GPUs.
- CPU `test_parallelism_context.py::TestBuildOptimizerMeshes`: with PP 2
on a fake PG, a stage-1 rank also creates stage 0's slices, in the same
order as every other rank; `dp_shard` and `edp_shard` slices with equal
ranks share one group and return one mesh; the meshes are not registered
on the root mesh; an axis combination spanning the dense and sparse
meshes raises.

## Known issues / follow-ups

- Depends on #5695 landing first; this PR then drops its copy of the
buffer-reuse fix.
- The b200 `kimi_k3_debugmodel_fsdp2_tp2_ep2_pp2_vpp4` cell needs 8
GPUs, so only a 4-GPU variant (dp_shard=1, TP 2, EP 2, PP 2 x 4 stages)
was run here: DistMuon builds for all 4 model parts, then the first
forward fails in the attn-gym KDA kernel (`'tuple' object has no
attribute 'atom'`), the same failure as the cell config with AdamW on
`main` on this machine. The cell is therefore not verified end-to-end
locally.
- Kimi K3.1 shares the K3 DistMuon recipe, so it can now run DistMuon
with TP. DistMuon construction under FSDP 2, TP 2, EP 2 succeeds (243
Muon parameters, including the indexer layouts), but training was not
verified: the first forward fails in the attn-gym KDA kernel (`'tuple'
object has no attribute 'atom'`), with AdamW on `main` as well.
- Kimi `__post_init__` mutates a shared optimizer config under
`dataclasses.replace`; pre-existing on main, separate fix.

## Stack

| Position | PR |
| --- | --- |
| 5/n | [#5678 — Support TP storage-to-compute
layouts](#5678) |
| 7/n | [#5680 — Keep linear-attention graph metadata
replayable](#5680) |
| 11/n | [#5684 — Enable Kimi K3 SiTU-GLU training and pipeline
lifecycle](#5684) |
| 13/n | [#5686 — Add block-scoped activation
retention](#5686) |
| 14/n | [#5793 — Add full-scale Kimi K3 MXFP8
recipes](#5793) |

Merged: 1/n (#5674), 4/n (#5677), 6/n (#5679), 8/n (#5681), 9/n (#5682).
Closed: 2/n, 3/n, 10/n, 12/n.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/b200 Trigger B200 CI ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants