Skip to content

[distmuon] 4/n Release scratch storage between optimizer updates - #5677

Merged
shuhuayu merged 3 commits into
mainfrom
shuhuayu/k3-dm-stack-04
Nov 5, 2026
Merged

shuhuayu merged 3 commits into
mainfrom
shuhuayu/k3-dm-stack-04

Conversation

@shuhuayu

@shuhuayu shuhuayu commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

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.

# 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.
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.

Draft stack — review and land in this order

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

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.

@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-03 branch from 0bab9cb to 649d215 Compare October 30, 2026 01:51
@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-03 branch from 649d215 to 7b2c4ec Compare October 30, 2026 04:34
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch from 5b24d90 to 6b492d5 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-03 branch from 7b2c4ec to 859d037 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 from 71613b5 to 7706c12 Compare November 4, 2026 01:03
@shuhuayu
shuhuayu changed the base branch from shuhuayu/k3-dm-stack-03 to main November 4, 2026 01:03
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch 2 times, most recently from c9b924a to c7c5a0a Compare November 4, 2026 03:34
@shuhuayu shuhuayu changed the title [optim] 4/n Bound optimizer memory ownership and allocation lifetimes [distmuon] 4/n Bound optimizer memory ownership and allocation lifetimes Nov 4, 2026
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch 2 times, most recently from 085df7c to 748aa3e Compare November 4, 2026 07:42
@shuhuayu
shuhuayu marked this pull request as ready for review November 4, 2026 07:52
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 4, 2026
@shuhuayu

shuhuayu commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review

@github-actions
github-actions Bot requested a review from weifengpy November 4, 2026 07:53
@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 2m 42s —— View job


Request changes: most of the scratch freed in transient mode sits in the transfer stream's allocator pool, where forward/backward can't reuse it. See the 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: Request changes -- most of the scratch that transient mode frees is allocated on the transfer stream, so forward/backward on the default stream can't reuse it without an allocator OOM retry (a device sync plus cudaFree) every step.

What this PR does. It adds DistMuon.Config.persistent_redistribution_buffers (default True). With False, construction and checkpoint load skip reserve_buffers(). Each step() then reserves the slot buffers before run() and clears them afterward, while keeping streams and events. Separately, _zeropower_via_newtonschulz drops the gram, gram_update and initial BF16 result references after their last use. Arithmetic is unchanged.

Example.

persistent=True  : [reserve at init] fwd | bwd | step(run) | fwd | bwd | step(run) ...
                   exchange + scratch stay allocated the whole time
persistent=False : init (no reserve)  fwd | bwd | reserve, run, release | fwd ...
  compute_scratch  (caller stream)   -> freed to caller pool   -> fwd/bwd can reuse
  storage_exchange/compute_exchange/storage_scratch
                   (transfer stream) -> freed to transfer pool -> fwd/bwd cannot reuse
                                        unless an allocation fails and the allocator
                                        syncs and cudaFrees all cached blocks

Must fix

  1. _optimizer_reshard_runtime.py:425 -- the transfer-stream-allocated buffers don't come back to forward/backward. The smallest fix is to allocate every slot buffer on the caller stream; the stream ordering in run() already makes the free safe (see inline).

Should consider

  • _optimizer_reshard_runtime.py:179, :236, :299-302 (unchanged lines, so not inline) -- three comments now describe the persistent case only. The record_compute_stream comment ("Pipeline exchange buffers stay alive and use explicit slot events") is the stated reason the exchange buffers skip record_stream. In transient mode that premise is false. Add one comment explaining why a free after run() is still ordered: the caller waited on every slot's done. Also update the _PipelineSlot docstring ("Persistent buffer keepalive") and the runtime docstring ("reserve_buffers must be called after planning ...").
  • dist_muon.py:294 -- the try/finally is unneeded given the fatal-exception contract (see inline).
  • test_dist_muon.py:269 -- the test asserts on private internals and mock call counts, and its CI cost doubles (see inline).

Questions

  • The PR says DistMuon optimizer updates can't be graph-captured in either mode, and the K3 recipes in #5793 choose False. What does persistent mode still buy, measured as per-step cost? If transient costs nothing measurable once allocations come from the caller stream, the knob could be dropped and transient made unconditional (.claude/rules/config.md: "If a value is always the same in practice, hardcode it").
  • Is there any measured peak-memory reduction for a K3 step with False vs. True, even on a reduced config? The description explicitly claims none, so right now the knob's value is unshown.
Details
  • Allocator reasoning. _BufferSlot.reserve (L136-162) allocates three of the four buffer kinds under device_handle.stream(transfer_stream). The caching allocator pools free blocks per stream, and the only cross-stream release is release_cached_blocks() on a failed allocation. That path synchronizes the device and frees whole segments to the driver. So in steady state, either memory doesn't drop, or every fwd/bwd triggers a retry and every step re-cudaMallocs.
  • Why caller-stream allocation is safe. Allocation on the caller happens before context.transfer_stream.wait_stream(caller) in run(). Every redistributed bucket ends with _release() -> caller.wait_event(slot.done). So all transfer-stream work is ordered before the caller-side free, and later caller-stream allocations that reuse the block are ordered after it.
  • Newton-Schulz dels. Checked; each one drops the last reference before the next large allocation, and the operation order is unchanged. del result in the batched path frees the initial copy after the first iteration rebinds matrices, because matrices is a view of it. No finding.
  • Consumer. No in-repo recipe sets False at HEAD; the consumer is torchtitan_recipes in #5793.

Not verified: no GPU run. The allocator-pool claim comes from reading the CUDA caching allocator and the code, not from a measurement. A maintainer still needs to review.

Comment on lines +425 to +432
def release_buffers(self) -> None:
"""Release optimizer-only tensors while preserving runtime resources."""
self._local_slot.buffers.clear()
self._local_slot._recorded_compute_streams.clear()
if self._context is not None:
for slot in self._context.slots:
slot.buffers.buffers.clear()
slot.buffers._recorded_compute_streams.clear()

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.

Most of what this releases can't be reused by forward/backward. _BufferSlot.reserve (L136-162) allocates storage_exchange, compute_exchange and storage_scratch under device_handle.stream(transfer_stream). The CUDA caching allocator only hands a freed block to later allocations on the stream it was allocated on. So after release_buffers(), those blocks sit cached in the transfer stream's pool, and forward/backward on the default stream can't use them. They only become available when an allocation fails and the allocator falls back to release_cached_blocks(). That path synchronizes the device, cudaFrees every free segment, and counts as an alloc retry. Then the next step's reserve_buffers has to cudaMalloc them again. Only compute_scratch (allocated on the caller stream) can be reused directly.

Consequence: either the knob saves much less than intended, or it saves memory by paying a device sync plus a malloc/free round trip every step, which is exactly what num_alloc_retries in the memory monitor flags.

Smallest fix: allocate every slot buffer on the caller/compute stream. That is stream-safe without record_stream. run() makes the transfer stream wait on the caller before its first redistributed use (context.transfer_stream.wait_stream(caller)), and the caller waits on every slot's done event before run() returns. So by the time the caller-stream free happens, all transfer-stream work on these blocks is already ordered before it. As a side effect this deletes the transfer_stream branch in _BufferSlot.reserve. Unverified on GPU; this is based on allocator semantics, so a torch.cuda.memory_stats() reading of reserved bytes and num_alloc_retries across steps in both modes would settle it.

Comment on lines +294 to +304
try:
self._redistribution_runtime.run(
self._bucket_plans,
local_tensor_spec=self._local_tensor_spec,
prepare=self._prepare_local,
compute=self._compute_update,
finalize=self._apply_update,
)
finally:
if not self._persistent_redistribution_buffers:
self._redistribution_runtime.release_buffers()

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.

The try/finally doesn't do anything useful. _BucketedRedistributionRuntime's contract says any exception from run() is fatal and the runtime/optimizer must not be reused. Releasing buffers on the error path only matters if someone keeps training after a failed step. Call release_buffers() unconditionally after run() and drop the try.

Comment on lines +269 to +290
runtime = current_optimizer._redistribution_runtime
context = runtime._context
events = (
tuple(
(slot.compute_input_ready, slot.compute_done, slot.done)
for slot in context.slots
)
if context is not None
else None
)
current_optimizer.step()
assert_buffer_lifetime(current_optimizer)
self.assertIsNotNone(runtime._context)
if context is not None:
self.assertIs(runtime._context, context)
self.assertEqual(
tuple(
(slot.compute_input_ready, slot.compute_done, slot.done)
for slot in context.slots
),
events,
)

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.

These assertions check private runtime internals: _context identity, event tuples, _local_slot.buffers, and slot.buffers.buffers (via assert_buffer_lifetime at L190). The mock.patch.object(runtime, "reserve_buffers", ...) call count at L363-371 is the same kind of check. .claude/rules/tests.md says not to snapshot private layouts or repeat mock calls. They will break on any refactor of the runtime but can't catch a numerics regression. The useful invariant is that results still match plain Muon across a checkpoint when buffers are reallocated every step, and the existing reference comparison already covers that once the test is parametrized. Suggest dropping the internals and mock checks. Also, the parametrization doubles this 2-GPU test from 2 cases to 4. Running transient mode only on the mixed (4, 2) layout would keep coverage of the harder case at lower CI cost.

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 changed the title [distmuon] 4/n Bound optimizer memory ownership and allocation lifetimes [distmuon] 4/n Release optimizer scratch for fully eager reuse Nov 4, 2026
Make redistribution scratch retention explicit. In transient mode, skip scratch reservation during construction and checkpoint loading, reserve it before each eager update, and release it afterward. Preserve initialized communication contexts, streams and events.

Release Newton-Schulz intermediates after their final use without changing arithmetic, coefficients, compute dtype or the persistent default.

Extend existing optimizer checkpoint coverage for lazy reservation and resource retention. Optimizer-state initialization and accelerator-graph startup retain their existing paths; no synthetic collective warmup is added.
Allocate scratch on the caller stream and preserve cross-stream completion before release. Scope transient buffers to fully eager allocator reuse, retain normal fatal propagation, and simplify the existing checkpoint variants.
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch from 4d90fe7 to b229a71 Compare November 4, 2026 19:51
@shuhuayu

shuhuayu commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

@claude review again

@claude

claude Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @shuhuayu's task in 1m 42s —— View job


Approve: all items from the earlier review are fixed, and allocating the slot buffers on the caller stream is stream-safe. See the 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 -- every earlier must-fix and should-consider item is resolved at HEAD. The stream ordering of the new caller-stream allocation checks out. What's left is one docstring suggestion and one open question about the knob.

What changed since the last review.

before: storage_exchange / compute_exchange / storage_scratch allocated under transfer_stream
        -> after release_buffers() they sit in the transfer pool; fwd/bwd can't reuse them
after : all four buffer kinds allocated on the caller stream (_BufferSlot.reserve)
        -> released blocks go back to the caller pool; the next eager fwd/bwd reuses them
        with no OOM-retry/cudaFree round trip

Earlier items

  • Transfer-stream allocation (_optimizer_reshard_runtime.py, _BufferSlot.reserve): resolved. Every slot buffer is now caller-allocated, and the transfer_stream branch is gone.
  • Stale persistent-only comments (record_compute_stream, _PipelineSlot, runtime docstring): resolved.
  • try/finally around run() in DistMuon.step: resolved (removed).
  • Test asserting private internals and mock call counts: resolved. The test is now 3 cases, with transient mode only on the mixed (4, 2) layout.

Should consider

  • torchtitan/components/optim/optimizer.py:241-250 -- The docstring says False "targets fully eager training". It doesn't mention the case from your human notes: one rank with several eager DistMuon instances (VPP=2, possibly with graphed fwd/bwd), whose scratch can then share blocks instead of all being resident at once. That case is the one a user is most likely to have and the hardest to infer from the current text. One sentence would let users decide how to set the knob (.claude/rules/config.md, "how would a user decide how to set this?"). The same applies to the "Scope" section of the PR description.

Questions

  • Is persistent mode still better anywhere? Now that allocations come from the caller pool, the transient per-step cost is a few host-side torch.empty calls plus one wait_stream. The remaining argument for persistent is that fwd/bwd could fragment the freed segments and raise steady reserved memory. If you or a maintainer have seen that in a K3 run, that justifies keeping both modes. If not, making transient unconditional would remove the knob.
Details
  • Why freeing caller-allocated buffers that the transfer stream used is safe without record_stream(transfer). In run(), every redistributed bucket ends with _release() -> caller.wait_event(slot.done). That includes the final previous, and prefetched work becomes previous before the loop exits. So when release_buffers() (transient) runs, or _reserve_tensor regrows a buffer on reload (persistent), the caller stream is already ordered after all transfer work on those blocks. The fatal path's finally does caller.wait_stream(transfer_stream), which covers destruction after a failed step.
  • Reuse of newly reserved blocks. A fresh block may have been used earlier by caller-side work (e.g. freed activations). The transfer stream must not touch it before that work finishes. This is covered by the new transfer_stream.wait_stream(compute_stream) in reserve_buffers, and again by the existing wait at the first redistributed bucket in run(). When run() uses a different caller than the allocation stream, record_compute_stream now records that caller on all four buffer kinds, so the free on the allocation stream still waits for it.
  • Default path. With True, the three exchange/scratch buffers now live in the caller pool instead of the transfer pool. The buffers are long-lived, so total reserved memory is unchanged. No numerics change.
  • NS dels. Unchanged since the last review; no finding.

Not verified: no GPU run. The allocator reasoning comes from reading the code. The 656 -> 512 MiB numbers are the author's synthetic benchmark. A maintainer still needs to review, since this touches the core optimizer config.

self._local_slot.clear()
if self._context is not None:
for slot in self._context.slots:
slot.buffers.clear()

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 prefer resize_(0) like what fsdp2 does

  • if you go with python object free, i would be super sensitive to cpu overhead. the buffer metadata will be calculated at each iteration, and we would call torch.empty at each iteration
  • if you go with resize_(0), then all cpu overhead happens once during init

fsdp2 code examples

def alloc_storage(tensor):
    size = tensor.numel() * tensor.itemsize
    if (storage := tensor.untyped_storage()).size() != size:
        storage.resize_(size)

def free_storage(tensor):
    if (storage := tensor.untyped_storage()).size() != 0:
        storage.resize_(0)

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.

great suggestion thx!

momentum=0.8,
nesterov=True,
ns_steps=ns_steps,
persistent_redistribution_buffers=persistent_buffers,

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.

how about changing default behavior directly and not introduce persistent_redistribution_buffers at all?

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.

sounds good, applied. did not see any down side of this but let me if there are potential ones.

gram_update = torch.addmm(gram, gram, gram, beta=b, alpha=c)
del gram
result = torch.addmm(result, gram_update, result, beta=a)
del gram_update

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.

good catch!

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

see above

@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch from b229a71 to a4fada3 Compare November 5, 2026 00:59

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

It seems there's no user-facing change? If so I'm unblocking, and please wait for wei's approval.

@shuhuayu shuhuayu changed the title [distmuon] 4/n Release optimizer scratch for fully eager reuse [distmuon] 4/n Release scratch storage between optimizer updates Nov 5, 2026
@weifengpy

Copy link
Copy Markdown
Contributor

is this ready for review again? click "re-request review" so i know

Screenshot 2026-11-04 at 10 38 43 PM

@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch from a4fada3 to eadb42c Compare November 5, 2026 07:13
@shuhuayu

shuhuayu commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

is this ready for review again? click "re-request review" so i know

Screenshot 2026-11-04 at 10 38 43 PM

@weifengpy thx, now it is good for another review.

@shuhuayu
shuhuayu requested a review from weifengpy November 5, 2026 08:05
Keep fixed-capacity scratch tensor objects and plan their buffers once.
Regrow accelerator backing storage on the caller stream for each eager
optimizer update, then resize it to zero after the existing transfer
handoffs. Retain CPU scratch between updates to avoid host allocation churn.

Make accelerator storage release the default and remove the persistence
option, per-update buffer planning, and persistent cross-caller tracking.
Parameters, optimizer state, communication resources, and graph pools
retain their existing ownership. Add one CPU buffer-lifetime regression.
@shuhuayu
shuhuayu force-pushed the shuhuayu/k3-dm-stack-04 branch from eadb42c to 6c34130 Compare November 5, 2026 08:50
@shuhuayu
shuhuayu merged commit 5f5fc93 into main Nov 5, 2026
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/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.

3 participants