Skip to content

[distmuon] 5/n Support TP storage-to-compute layouts - #5678

Merged
shuhuayu merged 1 commit into
mainfrom
shuhuayu/k3-dm-stack-05
Dec 1, 2026
Merged

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

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

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 [DistMuon] Fix compute buffer overwrite with replicated storage #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
7/n #5680 — Keep linear-attention graph metadata replayable
11/n #5684 — Enable Kimi K3 SiTU-GLU training and pipeline lifecycle
13/n #5686 — Add block-scoped activation retention
14/n #5793 — Add full-scale Kimi K3 MXFP8 recipes

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.

@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-04 branch from 98bbf7e to 5b24d90 Compare October 30, 2026 02:18
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch from 5b24d90 to 6b492d5 Compare October 30, 2026 04:34
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-05 branch from 600e7b1 to 6c4b02a Compare October 30, 2026 04:34
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-05 branch from 6c4b02a to da734bb Compare November 3, 2026 23:29
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch from 6b492d5 to 71613b5 Compare November 3, 2026 23:29
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch 5 times, most recently from 085df7c to 748aa3e Compare November 4, 2026 07:42
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-05 branch from da734bb to bfb36d2 Compare November 4, 2026 11:06
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch from 4d90fe7 to b229a71 Compare November 4, 2026 19:51
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-05 branch from bfb36d2 to 7a03e94 Compare November 4, 2026 20:35
Comment thread torchtitan/models/kimi_k2_7/qk_clip.py Outdated
tuple(
placement
if mesh_dim_names is not None
and mesh_dim_names[axis] == MeshAxisName.TP.value

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.

it's uncommon for clipping to depend on TP parallelsims. it's reasonable to let clipping depend on placements

from AI review

This puts parallelism-plan knowledge into QK-Clip in two places that have to agree. register_qk_clip_hook picks the MAX all-reduce group (get_mesh("loss")), and _distributed_row_scales separately decides by axis name that only tp keeps its placement. The axes the all-reduce covers must be exactly the axes where the scales are Replicate. Today that holds only because those two choices happen to line up.
With run_check=False, any drift gives silently wrong scales instead of an error:

  • a TP placement that isn't Shard(0) falls back to Replicate();
  • a future axis that shards heads won't be named tp.
    Could we derive the placements from the reduction group instead? Then QK-Clip depends only on the reduction_mesh it already receives, and no longer needs MeshAxisName:
def _distributed_row_scales(
    row_scales_R1: torch.Tensor, weight: DTensor, reduction_ranks: frozenset[int]
) -> DTensor:
    """Scales are identical across the MAX all-reduce group. On every other mesh
    axis a rank holds only its forward-local heads, i.e. a row shard of weight."""
    mesh = weight.device_mesh
    coordinate = mesh.get_coordinate()
    assert coordinate is not None
    placements = []
    for axis, placement in enumerate(weight.placements):
        index: list[int | slice] = list(coordinate)
        index[axis] = slice(None)
        if set(mesh.mesh[tuple(index)].tolist()) <= reduction_ranks:
            placements.append(Replicate())
        elif type(placement) is Shard and placement.dim == 0:
            placements.append(placement)
        else:
            raise ValueError(
                f"QK clip scales cannot follow {placement} on mesh axis {axis}"
            )
    return DTensor.from_local(row_scales_R1, mesh, tuple(placements), run_check=False)

reduction_ranks = frozenset(reduction_mesh.mesh.flatten().tolist()) is computed once in register_qk_clip_hook. A mismatch now raises, so changing the reduction group can't silently break the scales.
I checked this against the current version on CPU/gloo with 4 ranks. The weights used FSDP2's layouts, including (_StridedShard(0, sf=2), Shard(0)) for FSDP over TP. Cases: FSDP with uneven rows, dp_shard_cp, HSDP 2x2, and FSDP 2 x TP 2 with a head split by FSDP. In every case it gave the same placements as the current code, zero collectives under CommDebugMode, and matched full_weight * full_scales.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

this is more single source of truth, adopted.

for preserved_mesh_axis, preserved_placement in enumerate(param.placements):
if preserved_mesh_axis == transport_mesh_axis:
continue
if (

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.

ai reivew

Nit, readability: this condition packs one rule into seven flat clauses, and four of them don't depend on the loop variable. The rule is about matrix batches such as experts [E, F, D]. The transport axis (e.g. edp_shard) turns row shards Shard(ndim-2) into whole-matrix Shard(0), while a later mesh axis (e.g. ep) keeps Shard(0) storage. Without a declared shard order, Shard(0) nests in mesh order and contradicts the storage layout. Suggest naming the rule and hoisting the invariant part:

def _is_shard_on_dim(placement: object, dim: int, ndim: int) -> bool:
    """Exact Shard (not _StridedShard) on normalized tensor dimension ``dim``."""
    return type(placement) is Shard and placement.dim % ndim == dim
if len(transport_mesh_axes) == 1 and block_shard is None:
    (transport_mesh_axis,) = transport_mesh_axes
    # The transport turns each rank's matrix rows into whole matrices of the batch.
    rows_become_whole_matrices = _is_shard_on_dim(
        param.placements[transport_mesh_axis], param.ndim - 2, param.ndim
    ) and _is_shard_on_dim(
        normalized_target_sharding_by_storage_mesh_axis.get(transport_mesh_axis),
        0,
        param.ndim,
    )
    # A later mesh axis that keeps Shard(0) storage owns the outer batch chunks
    # (e.g. ep). Undeclared, Shard(0) nests in mesh order, putting the transport
    # axis outside it and contradicting the storage layout.
    preserved_batch_shard_axis = next(
        (
            axis
            for axis in range(transport_mesh_axis + 1, len(param.placements))
            if _is_shard_on_dim(param.placements[axis], 0, param.ndim)
        ),
        None,
    )
    if rows_become_whole_matrices and preserved_batch_shard_axis is not None:
        preserved_axis_name = mesh_axis_names[preserved_batch_shard_axis]
        transport_axis_name = mesh_axis_names[transport_mesh_axis]
        raise ValueError(
            f"Muon parameter {fqn!r} must declare "
            "shard_order_by_tensor_dim={0: "
            f"({preserved_axis_name!r}, {transport_axis_name!r})}} "
            f"when preserving Shard(0) on mesh axis {preserved_axis_name!r}"
        )
  • _is_shard_on_dim replaces the type(...) is Shard and dim % ndim == d pattern that appears three times.
  • The four loop-invariant clauses become rows_become_whole_matrices.
  • range(transport_mesh_axis + 1, ...) replaces the self-skip plus the transport_mesh_axis < preserved_mesh_axis clause.
    Behavior is unchanged. I brute-forced 49,540 combinations against the current code: tensor ndim 2–4, mesh ndim 1–3, Replicate/Shard/_StridedShard storage, and targets including None. Results match, including which axis the error names.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

added a helper function as suggested.

"BucketConfig",
"ComputeLayout",
"Owned",
"redistribution_mesh_axes",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

i am sensitive to why this gets exposed as a public contract - i guess there is something to do with max_ctas. chatted with claude on how to keep the public contract clean

ai review

Design question: can transport stay internal to FlexShard?

I'd expect the caller-facing contract to be: DTensor params with their storage placements, a ComputeLayout per param, and the mesh. Which groups the transport uses is FlexShard's business. This PR exposes it through several pieces:

  • the public redistribution_mesh_axes;
  • BucketConfig.mesh becoming mandatory for combined transports, with a "_".join(axes) naming convention;
  • the TorchTitan wrapper re-implementing bucket matching (fnmatch over bucket.patterns) to find each bucket's transport;
  • build_transport_meshes with the all-gather/sorted-union new_group scheme to stay PP-safe.

As far as I can tell, all of this follows from two choices: supporting max_nccl_ctas_for_comms (its docstring calls it a temporary workaround), and not using DeviceMesh._flatten. Building groups per optimizer and per PP stage is what creates the new_group ordering problem. That problem is what forces the caller to know the axes before construction.

Suggestion: make the combined groups part of the mesh, created where every other group is created. ParallelismContext.build_mesh already uses _unflatten and _flatten("loss_mesh"). Flatten the storage-axis combinations DistMuon can need there too, e.g. (dp_shard, tp) and, with CP, (dp_shard, cp, tp). DistMuon then only looks groups up on the storage mesh it already receives:

  • single axis: storage_mesh.get_group(axis), as on main;
  • multiple axes: the flattened mesh registered on the root whose layout matches those dims. DTensor already does this lookup in _redistribute.py (_get_flattened_mesh_by_layout), so no naming convention is needed. If no such mesh exists, raise and ask the mesh owner to flatten those dims.

Mesh construction is global and symmetric across PP stages, so the expert-free-stage and new_group ordering issues go away. FlexShard still never creates a group. This removes:

  • the public redistribution_mesh_axes;
  • build_transport_meshes;
  • the wrapper's bucket matching and mesh injection;
  • the joined-name rule;
  • the "combined transports require an explicit mesh" rule.

If the CTA cap must stay, _flatten(..., backend_override=(backend, options)) can carry the NCCL options when the dim is built, so the policy stays with the group owner. The cost is that DTensor collectives using that flattened dim are capped too.

On the objections in "Alternatives considered":

  • Registering the flattened mesh on the root changes how DTensor gathers other parameters. True: _optimize_transform_infos merges consecutive same-type collectives into one when a matching flattened mesh is registered. But this is DTensor's intended optimization. Without the flattened dim it warns "To optimize, flatten mesh dimensions [...] so DTensor can use a single operation instead". It never applies to _StridedShard placements, and it changes collective count and reduction order, not correctness. A loss comparison would confirm, and that seems better than maintaining a parallel group-building path.
  • _flatten is private. build_mesh already depends on _flatten/_unflatten.
  • The storage mesh must exist on every rank. At mesh-build time every rank constructs the full dense and sparse meshes, whichever stage it owns.

One thing to confirm: the parameter's storage mesh, which FSDP builds via DeviceMesh._concatenate, should share the root that build_mesh flattens on, so the layout lookup finds the flattened dim.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I also did not like this new public api but made this concession after iterating with claude, which is indeed related to the max_ctas configs when building a mesh. I like that the new proposal removes the public query and the wrapper plumbing. It does move away from the explicit, isolated mesh contract you asked for in #5183 that we were using the current pr, so I want to confirm which contract FlexShard should have before rewriting. There are two options below; the main open item for (b) is where the CTA cap lives. Which one do you prefer? @weifengpy

AI summary:

Context: what Wei asked for in #5183

  • "the convention of parallelism api is not to create pg implicitly inside, but let user pass device mesh as api contract… just like why fsdp2 need a device mesh"
  • "that's why i suggested passing a new device mesh to distmuon so the max_cta is only applied to distmuon"
  • "i want to make sure this device mesh contract is there, not only for max_ctas, but also for any future pg init opts"
  • His step 9: "for each bucket, take a matched parameter's storage mesh and dataclasses.replace(bucket, mesh=...)"

Both options below keep "FlexShard never creates groups". They differ in whether FlexShard gets groups explicitly (isolated) or finds them on the root (shared).


(a) Explicit, isolated meshes (#5183), created once at startup

  1. Creation. build_mesh creates the combined groups once, the same way on every rank: dp_shard × tp, and dp_shard_cp × tp under CP, only when TP > 1. It uses dist.new_group / DeviceMesh.from_group, not _flatten, so nothing is registered on the root and DTensor never uses them. If the cap is set, the groups get the NCCL options, so the cap applies only to DistMuon.
  2. Handoff. The groups reach DistMuon through BucketConfig.mesh, as on main.
  3. Validation. FlexShard checks the mesh covers the transport's ranks in storage order, as today.
  • Removes: build_transport_meshes's all-gather and union logic, since global creation makes PP ordering and expert-free stages safe.
  • Keeps:
    • BucketConfig.mesh and the wrapper's matching and injection (step 9);
    • a way to know which buckets need a combined mesh: the public redistribution_mesh_axes, or the wrapper offering the available meshes and FlexShard picking by axes.
  • Open questions:
    • how ParallelismContext's groups reach the optimizer, since the wrapper only gets parameters today;
    • where the cap value lives, since build_mesh would need it.

(b) Implicit lookup on the root (your proposal)

  1. Creation. build_mesh calls _flatten on the combined dense axes when TP > 1, which registers dp_shard_tp on the world root.
  2. Lookup. FlexShard finds combined groups with _get_flattened_mesh_by_layout(storage_mesh, dims) and raises if one is missing. Single-axis transports use the storage group. A fake-PG probe shows the lookup works with and without CP, including FSDP's _concatenate'd storage mesh.
  • Removes:
    • the public redistribution_mesh_axes;
    • build_transport_meshes;
    • the wrapper changes in this PR;
    • the joined-name rule;
    • the "combined transports need an explicit mesh" rule.
  • What we'd accept:
    • Shared with DTensor. A registered dp_shard_tp is used by DTensor's redistribute merging (optimize_transform_infos). In TorchTitan that's at least clip_grad_norm's norm.full_tensor() every step, plus some checkpoint-adapter redistributes for same-dim placements such as (Shard(0), Shard(0)).
    • Main-path numerics. The merged all-reduce changes reduction order, so grad_norm and loss may change bit-wise in every TP run, AdamW included. I'll run a loss comparison. The review bot also reproduced a wrong full_tensor() result for an uneven (Shard(0), Shard(0)) tensor on Gloo once the flattened mesh existed. We haven't checked it ourselves, but it should probably go upstream.
    • One more communicator in every TP run. DTensor's grad-norm merge would use dp_shard_tp even in non-DistMuon runs. I'll measure the memory.
    • No per-consumer group settings. Lookup by layout can't tell two meshes over the same ranks apart. That's the "future pg init opts" case from [distmuon] Isolate redistribution NCCL communicators #5183.
    • Private API. It adds _get_flattened_mesh_by_layout, which needs a TODO and an upstream issue.
  • The cap, pick one:
    • (i) not supported for combined transports (raise), so K3 runs with TP > 1 turn it off;
    • (ii) move the knob to the comm/parallelism config, and have build_mesh create all capped transport groups with it: combined ones via _flatten(..., backend_override=...), plus capped copies of dp_shard/edp_shard. DistMuon then has no group settings and one lookup mechanism, and the policy stays with the group owner. The only other capped traffic is the grad-norm scalar.

Question: should FlexShard's contract be explicit, isolated meshes (a), or lookup on the root (b)? If (b), which cap option do you prefer, and are you OK with the TP-wide grad-norm numerics check?

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.

option (a) looks good to me. i can review again once it's done

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

finished review

shuhuayu added a commit that referenced this pull request Nov 16, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP requires SP and a text-only flavor (both raise otherwise): TP without
  SP fails typechecking, and so does the shared Qwen3.5 vision encoder
  under TP.
- DistMuon does not support TP yet (#5678), so the TP debug recipe uses
  AdamW and the DistMuon policy raises under TP.
- B200 test: FSDP2 x TP2 + SP x EP2 on four GPUs with typechecking.
@shuhuayu
shuhuayu requested a review from weifengpy November 17, 2026 00:12
shuhuayu added a commit that referenced this pull request Nov 17, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP requires SP and a text-only flavor (both raise otherwise): TP without
  SP fails typechecking, and so does the shared Qwen3.5 vision encoder
  under TP.
- DistMuon does not support TP yet (#5678), so the TP debug recipe uses
  AdamW and the DistMuon policy raises under TP.
- B200 test: FSDP2 x TP2 + SP x EP2 on four GPUs with typechecking.
shuhuayu added a commit that referenced this pull request Nov 17, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP requires SP and a text-only flavor (both raise otherwise): TP without
  SP fails typechecking, and so does the shared Qwen3.5 vision encoder
  under TP.
- DistMuon does not support TP yet (#5678), so the TP debug recipe uses
  AdamW and the DistMuon policy raises under TP.
- B200 test: FSDP2 x TP2 + SP x EP2 on four GPUs with typechecking.
shuhuayu added a commit that referenced this pull request Nov 17, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP requires SP and a text-only flavor (both raise otherwise): TP without
  SP fails typechecking, and so does the shared Qwen3.5 vision encoder
  under TP.
- DistMuon does not support TP yet (#5678), so the TP debug recipe uses
  AdamW and the DistMuon policy raises under TP.
- B200 test: FSDP2 x TP2 + SP x EP2 on four GPUs with typechecking.

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

pending on option a

shuhuayu added a commit that referenced this pull request Nov 20, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP runs with or without SP. TP-unsharded weights (grouped norms, residual
  mixer linears) take the TP type of their input: I without SP, R otherwise.
- Multimodal flavors run under TP: like Qwen3.5, the fused embeddings
  declare their DP x CP token sharding before replicate_to_residual, which
  otherwise fails typechecking.
- DistMuon does not support TP yet (#5678), so the DistMuon policy raises
  under TP.
- 4/n's fused teacher override gets the same TP path: its kernel writes
  per-token head sums, which are all-reduced over TP before block pooling,
  and the indexer KL is scaled by 1/TP like the parent's. Its unit test
  checks a simulated TP2 head split against the pooled single-rank result.
shuhuayu added a commit that referenced this pull request Nov 20, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP runs with or without SP. TP-unsharded weights (grouped norms, residual
  mixer linears) take the TP type of their input: I without SP, R otherwise.
- Multimodal flavors run under TP: like Qwen3.5, the fused embeddings
  declare their DP x CP token sharding before replicate_to_residual, which
  otherwise fails typechecking.
- DistMuon does not support TP yet (#5678), so the DistMuon policy raises
  under TP.
- 4/n's fused teacher override gets the same TP path: its kernel writes
  per-token head sums, which are all-reduced over TP before block pooling,
  and the indexer KL is scaled by 1/TP like the parent's. Its unit test
  checks a simulated TP2 head split against the pooled single-rank result.
shuhuayu added a commit that referenced this pull request Nov 20, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP runs with or without SP. TP-unsharded weights (grouped norms, residual
  mixer linears) take the TP type of their input: I without SP, R otherwise.
- Multimodal flavors run under TP: like Qwen3.5, the fused embeddings
  declare their DP x CP token sharding before replicate_to_residual, which
  otherwise fails typechecking.
- DistMuon does not support TP yet (#5678), so the DistMuon policy raises
  under TP.
- 4/n's fused teacher override gets the same TP path: its kernel writes
  per-token head sums, which are all-reduced over TP before block pooling,
  and the indexer KL is scaled by 1/TP like the parent's. Its unit test
  checks a simulated TP2 head split against the pooled single-rank result.
shuhuayu added a commit that referenced this pull request Nov 20, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP runs with or without SP. TP-unsharded weights (grouped norms, residual
  mixer linears) take the TP type of their input: I without SP, R otherwise.
- Multimodal flavors run under TP: like Qwen3.5, the fused embeddings
  declare their DP x CP token sharding before replicate_to_residual, which
  otherwise fails typechecking.
- DistMuon does not support TP yet (#5678), so the DistMuon policy raises
  under TP.
- 4/n's fused teacher override gets the same TP path: its kernel writes
  per-token head sums, which are all-reduced over TP before block pooling,
  and the indexer KL is scaled by 1/TP like the parent's. Its unit test
  checks a simulated TP2 head split against the pooled single-rank result.
shuhuayu added a commit that referenced this pull request Nov 20, 2026
Shard QSA heads and PLE feature columns over TP with sequence-parallel
residuals. The indexer teacher sums head probabilities across TP before
max pooling each block, and the TP-replicated indexer contributes its KL
gradient once. The PLE table becomes DP-row x TP-column owned.

- Text-only embeddings run in the global SPMD context so their output
  records the DP shard; only the vision path needs the DP-local context.
- SplitLinear splits gates by their fixed per-group width: the SPMD checker
  reads a passed size as global, which the local group count is not.
- TP runs with or without SP. TP-unsharded weights (grouped norms, residual
  mixer linears) take the TP type of their input: I without SP, R otherwise.
- Multimodal flavors run under TP: like Qwen3.5, the fused embeddings
  declare their DP x CP token sharding before replicate_to_residual, which
  otherwise fails typechecking.
- DistMuon does not support TP yet (#5678), so the DistMuon policy raises
  under TP.
- 4/n's fused teacher override gets the same TP path: its kernel writes
  per-token head sums, which are all-reduced over TP before block pooling,
  and the indexer KL is scaled by 1/TP like the parent's. Its unit test
  checks a simulated TP2 head split against the pooled single-rank result.
shuhuayu added a commit that referenced this pull request Nov 21, 2026
## Summary (human-written)

add tp/sp. 

## Why

Stacked on #6053 (4/n).

Flash-Next rejects TP at config time. TP needs model-specific pieces
beyond the shared decoder sharding:

1. QSA's indexer teacher is a max-pool over blocks of the head-mean
attention probability. With heads sharded, pooling each shard first
computes a different target: max(mean over all heads) is not the mean of
per-shard maxes.
2. The indexer is TP-replicated, so its KL gradient would be counted TP
times.
3. PLE's table, owned by DP rows since 1/n, also needs TP column
ownership.
4. Several Flash-Next sharding declarations only typecheck for TP + SP
and text-only inputs.

**Example.** Two heads, one block of two tokens, head probabilities
`h0=[0.9,0.1]` and `h1=[0.1,0.9]`. The true teacher is `max([0.5,0.5]) =
0.5`. Pooling per TP shard and then averaging gives `(0.9+0.9)/2 = 0.9`.

## What changed

- **QSA teacher** (`QSAInnerAttention._teacher`): for each query chunk,
each rank divides its head-probability sum by the global head count,
all-reduces across TP, then max-pools blocks, so peak memory stays per
chunk as before. The KL contribution is scaled by `1/TP` in backward,
since the TP-replicated indexer's gradients are summed over TP ranks.
DeepSeek-V4's compressor uses the same two patterns; TODOs at both sites
point to sharing them (the scale belongs in `AuxLoss`).
- **4/n fused teacher override** (`flash_next_qsa_teacher.py`): same TP
path. `qsa_teacher` takes `num_global_heads` and returns the unpooled
per-token probabilities `[T, num_blocks * compress_ratio]`;
`_fused_teacher` all-reduces them over TP (when TP > 1) and then
max-pools. The indexer KL gets the same `1/TP` scale.
- **PLE table**: its `ngram_table_sharding` weight placement goes from
`{dp: S(0), tp: R}` to `{dp: S(0), tp: S(1)}`, i.e. DP-row x TP-column
owned. TP ranks hold the same token IDs (PLE runs TP-replicated), so
only DP ranks exchange IDs and vectors, at the local feature width;
`NGramEmbedding` then redistributes the looked-up vectors `S(2) -> R`
over TP. `NGramTable` already builds the weight as a DTensor on
`spmd_dense_mesh` with placements read from the sharding config (1/n),
so the column shard needs no mesh code. With TP and DP=1, `NGramTable`
uses the size-1 `dp_shard` mesh as its row mesh. The
`row_sharded_embedding` docstring now says D is the local feature width.
- **TP with or without SP**: TP-unsharded weights read by the residual
stream (the gated residuals' grouped `hc_norm` and mixer linears) take
the TP type of their input via `_unsharded_param_placement`: `I` without
SP, `R` with SP, as the shared `norm_sharding_config` does.
- **Multimodal flavors**: like Qwen3.5 (`qwen3_5/model.py`), the
multimodal forward declares the fused embeddings' DP x CP token sharding
(`spmd.assert_type`) before `replicate_to_residual`, which otherwise
fails typechecking under TP.
- **Text-only embeddings** run in the global SPMD context. Inside
`spmd_local_context("dp")`, the SP-scattered embedding recorded only
`(tp)` on the token dimension and lost its DP shard, so with DP > 1 the
first block failed typechecking. Only the multimodal vision path still
uses the DP-local context.
- **`SplitLinear`** unflattens gates by their fixed per-group width. The
SPMD checker reads a size passed to `unflatten` as global; the
projection's local group count is not, so FSDP2 x TP2 failed
typechecking in `cat`.
- **Config validation** (`build_model_config`): TP must divide the QSA
KV heads (2 in every flavor, so TP 1 or 2). PP still raises.
- **DistMuon**: the Flash-Next DistMuon policy raises `ValueError` under
TP, since DistMuon does not support TP storage layouts until #5678
(TODO).
- Mechanical / skimmable: README TP/SP row, docstring updates.

## User-facing changes

| Before | After |
| --- | --- |
| `tensor_parallel_degree > 1` raises | TP works, with or without SP,
for text and multimodal flavors, when TP divides the 2 QSA KV heads |
| DistMuon policy under TP: fails inside the optimizer | `ValueError` at
config time, TODO pointing to #5678 |

## Numerics

TP=1 is unchanged: the teacher runs the same ops (the all-reduce and the
`1/TP` scale are skipped; the fused override pools the same tensor it
pooled before), the TP placements only matter when TP > 1, and the
global-context embedding runs the same ops.

Fresh initialization under TP depends on the PLE table's mesh: DTensor
RNG offsets depend on the layout, so DP2, DP4, DP2 x TP2 and HSDP give
different tables (each distinct per owner). Loss at step 1 therefore
differs between layouts that don't load the same checkpoint.

The runs below used local configs that are not part of this PR (it adds
no recipe or integration entry), at earlier revisions, before TP without
SP and multimodal TP were enabled:

| Check (GB300, deterministic, seed 42) | Result |
| --- | --- |
| FSDP2 x TP2 + SP x EP2 debug model (typechecked, 4 GPUs, AdamW), 10
steps | Step 1 loss 7.76143 / grad norm 9.4439, step 5 6.63181, step 10
5.60357 / 3.465 |
| Resharding save/resume: FSDP4 x EP2 steps 1-5, then load at FSDP2 x
TP2 + SP x EP2, steps 6-10 | Load finished with no missing-key or
optimizer warnings; step 6 5.58456 / grad norm 4.4042, step 10 5.26044 |
| FSDP2 x EP2 (2 GPUs) vs FSDP2 x TP2 + SP x EP2 (4 GPUs), AdamW, same
seed checkpoint and global batch, 10 steps | Step 1 loss 7.732883 vs
7.733495 (+6.1e-4), grad norm 9.29617 vs 9.28646 (-1.0e-3 relative);
steps 2-10 within 6.0e-3 loss and 1.4e-2 relative grad norm, no
systematic offset |
| TP2 + SP x EP2 with Dist-MoE, accelerator graphs vs eager, 4 steps |
Loss and grad norm bitwise equal |

A wrong `1/TP` indexer scale or a doubled PLE gradient reduction would
show as a systematic grad-norm offset in the TP vs no-TP comparison.

TP without SP and multimodal TP were checked on fake process groups with
SPMD typechecking (FSDP2 x TP2 x EP2, fused teacher, 5 steps each): text
without SP, multimodal with and without SP, plus the existing text TP +
SP and multimodal FSDP2 x EP2 layouts as regression checks. They have
not run on GPUs.

## Testing

- CPU:
`test_qsa_teacher_sums_tp_head_shards_and_scales_indexer_gradient` runs
two simulated head shards (mocked TP all-reduce) against the unsharded
teacher. It guards the order (all-reduce before pooling) and the `1/TP`
indexer gradient scale, which a TP run's loss alone would not reveal.
- GPU (SM100): `test_teacher_matches_golden_with_and_without_tp_split`
checks the fused kernel's per-KV-head probabilities, summed then pooled,
against the golden teacher.
- This PR adds no integration entry. Real-GPU TP coverage in CI comes
from #6055's `qwen3_8_flash_next_fsdp_tp_sp_ep_pp` (FSDP2 + TP2 + SP +
EP4 + PP2, text, AdamW).

```bash
python -m pytest tests/unit_tests/cpu/models/qwen3_8_flash_next -q
python -m pytest tests/unit_tests/gpu/recipes/test_flash_next_qsa_teacher_override.py -q
```

## Known issues / follow-ups

- No CI covers TP without SP or multimodal TP, and no test checks a
resume that reshards the PLE table across TP.
- DistMuon under TP waits on #5678.
- TODOs: share the TP head-sum reduction and the `1/TP` scale with
DeepSeek-V4's compressor (the scale belongs in `AuxLoss`).

## Stack

1. #6046: model. 2. #6047: static QSA. 3. #6052: fixed-capacity PLE
routing. 4. #6053: 125B recipe + accelerator-graph test. 5. **#6054: TP
+ SP (this PR).** 6. #6055: pipeline parallelism.
@github-actions github-actions Bot mentioned this pull request Nov 21, 2026
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-05 branch 4 times, most recently from 69ebdae to 1180406 Compare November 25, 2026 10:48
@shuhuayu

Copy link
Copy Markdown
Contributor Author

i updated with option a, but used a separate build_optimizer_meshes function instead of adding that into build_mesh function and the consideration is that build_mesh is run by all training recipes including those not using distmuon.

another point is when head structure is there, we do not need to do cross tp communication, but to achieve that we either need to build separate mesh, or we need to use zero cross tp comms with in a (dp_shard, tp) mesh, my ablations show that the later two are actually not much faster than a regular all to all over the whole (dp_shard, tp) mesh.

axes_list.append((*dense_shard_axes, "tp"))
backend = pg_options = None
if max_ctas is not None:
if default_backend is None or dist.Backend.NCCL not in default_backend:

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.

Would be good if we could make this more general than cuda/nccl specific.
#5940 is an on-going attempt. Could you drive it to the finish line? If @rakkit is busy you can take over.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

sure, i will followup on that pr.

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.

sry, will fix today

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.

4 participants